Skip to main content

rf_scan/
lib.rs

1//! rf-scan — the gadget scanning engine (multi-arch, parallel).
2//!
3//! Pipeline: memchr-accelerated anchor scan (tables ported from ROPgadget's
4//! `gadgets.py`) → clean-decode validity (`total decoded size == end -
5//! start`) → passClean port → output dedup by gadget text
6//! (first-occurrence-wins in deterministic traversal order: section → table
7//! (ROP/JOP/SYS) → anchor pattern → anchor-hit offset → depth, decided by
8//! the [`trie`] index) → post-dedup filters (`--only`, `--badbytes`) →
9//! alphabetical sort. `--range` truncates sections pre-scan; `--offset`
10//! slides vaddrs at emission without affecting disassembly.
11//!
12//! Dispatch (`scan_binary` over `impl rf_core::Image`): x86/x64 → iced-x86
13//! ([`x86`]); all other architectures → capstone ([`cs`]). Scanning runs
14//! over slices of each anchor's hit list — overlapping byte ranges of the
15//! region — optionally under rayon with deterministic output
16//! (`ScanOptions::parallel`).
17//!
18//! The "per-start decode cache" this crate was once described by is gone
19//! (PERF-03): it had a 0.8% hit rate and cost more than the decodes it
20//! avoided. On the fixed-width architectures a single resumable region
21//! decode ([`cs::RegionIndex`]) replaces it and answers each candidate with
22//! an array lookup; on x86/x64 each candidate is simply decoded, over
23//! exactly its own bytes.
24//!
25//! # Getting started
26//!
27//! [`scan_binary`] takes anything that implements [`rf_core::Image`] and a
28//! [`ScanOptions`], and hands back the finished listing: deduplicated,
29//! filtered and sorted the way ROPgadget sorts it.
30//!
31//! ```
32//! use rf_core::{Arch, Endianness, RawBinary};
33//! use rf_scan::{scan_binary, ScanOptions};
34//!
35//! // A real caller loads a file with `rf_core::Binary::load`. These bytes
36//! // are `xor eax, eax ; ret` followed by `pop rdi ; ret`.
37//! let image = RawBinary::new(&[0x31, 0xc0, 0xc3, 0x5f, 0xc3], Arch::X64, Endianness::Little);
38//!
39//! let opts = ScanOptions {
40//!     depth: 4,
41//!     ..ScanOptions::default()
42//! };
43//! let gadgets = scan_binary(&image, &opts)?;
44//!
45//! let texts: Vec<String> = gadgets.iter().map(|g| g.text()).collect();
46//! assert!(texts.iter().any(|t| t == "pop rdi ; ret"));
47//! assert!(texts.iter().any(|t| t == "xor eax, eax ; ret"));
48//! // The listing is sorted and deduplicated.
49//! let mut sorted = texts.clone();
50//! sorted.sort();
51//! assert_eq!(texts, sorted);
52//! # Ok::<(), rf_core::Error>(())
53//! ```
54//!
55//! ## Filtering
56//!
57//! Filters are engine options, not a post-pass over the listing, because
58//! several of them (`align`, `cfg_aware`) change which candidate starts are
59//! generated at all:
60//!
61//! ```
62//! use rf_core::{Arch, Endianness, RawBinary};
63//! use rf_scan::{scan_binary, ScanOptions};
64//!
65//! let image = RawBinary::new(&[0x31, 0xc0, 0xc3, 0x5f, 0xc3], Arch::X64, Endianness::Little);
66//! let opts = ScanOptions {
67//!     depth: 4,
68//!     // ROPgadget `--only`: every mnemonic must be in this set.
69//!     only: Some(["pop".to_string(), "ret".to_string()].into_iter().collect()),
70//!     ..ScanOptions::default()
71//! };
72//! let texts: Vec<String> = scan_binary(&image, &opts)?.iter().map(|g| g.text()).collect();
73//! // `xor eax, eax ; ret` is gone: `xor` is not in the set.
74//! assert_eq!(texts, vec!["pop rdi ; ret".to_string(), "ret".to_string()]);
75//! # Ok::<(), rf_core::Error>(())
76//! ```
77//!
78//! ## Bounding and cancelling a scan
79//!
80//! [`scan_binary`] is unbounded and uncancellable by construction — it
81//! resets the budget fields before it runs, so no caller can be surprised
82//! by one. To bound a scan, use [`scan_bounded`]; to stop one from another
83//! thread, put a [`CancelToken`] in the options and use either
84//! [`scan_bounded`] or [`scan_binary_into`], which are the two entry points
85//! that observe it.
86//!
87//! ```
88//! use rf_core::{Arch, Endianness, RawBinary};
89//! use rf_scan::{scan_bounded, CancelToken, Error, ScanOptions};
90//!
91//! let image = RawBinary::new(&[0x31, 0xc0, 0xc3, 0x5f, 0xc3], Arch::X64, Endianness::Little);
92//! let cancel = CancelToken::new();
93//! cancel.cancel(); // in practice: from another thread, or on a timeout
94//! let opts = ScanOptions {
95//!     depth: 4,
96//!     cancel,
97//!     max_gadgets: Some(1_000_000),
98//!     ..ScanOptions::default()
99//! };
100//! assert!(matches!(scan_bounded(&image, &opts), Err(Error::Cancelled)));
101//! ```
102//!
103//! ## Streaming
104//!
105//! For a listing too large to hold, implement [`GadgetSink`] and call
106//! [`scan_binary_into`], which never builds a `Vec`. The stream is in raw
107//! traversal order: run [`post_process`] over what you collected if you
108//! want the deduplicated, sorted listing.
109//!
110//! # Semver policy
111//!
112//! Covered by semver from 1.0: the signatures of [`scan_binary`],
113//! [`scan_binary_into`], [`scan_bounded`], [`post_process`] and
114//! [`scan_section`]; the [`GadgetSink`] trait; and the fields of
115//! [`ScanOptions`] and [`Gadget`].
116//!
117//! **Not** covered, and free to change in a patch release: **the exact
118//! disassembly text** in [`Gadget::insns`] and [`Gadget::text`] — it is
119//! whatever iced-x86 and the linked capstone print, both of which drift
120//! between releases, which is why `tests/parity.py` re-measures it rather
121//! than asserting it; which gadgets a given binary yields (a decode fix
122//! changes the set, and that is the point of a fix); and the text of any
123//! [`Error`]. Adding a field to [`ScanOptions`] is a minor release, so
124//! construct it with `..ScanOptions::default()` rather than exhaustively.
125//! Pin `rf-scan = "1"`.
126//!
127//! See `docs/API-STABILITY.md` in the repository for the workspace-wide
128//! statement.
129
130#![forbid(unsafe_code)]
131// ENG-08: every public item carries documentation.
132#![warn(missing_docs)]
133
134pub mod anchors;
135pub mod cancel;
136pub mod cs;
137pub mod detail;
138mod engine;
139pub mod sink;
140pub mod trie;
141pub mod x86;
142
143pub use anchors::TableKind;
144pub use cancel::{CancelToken, Error};
145pub use detail::{Access, Detailer, InsnDetail, InsnGroups, MemRef, Operand, OperandInfo};
146pub use engine::{
147    ibt_applicable, is_call_preceded, post_process, scan_binary, scan_binary_into, scan_bounded,
148    scan_section, Gadget, ScanOptions, PREV_BYTES,
149};
150pub use sink::{BoundedSink, GadgetSink, VecSink};
151pub use trie::GadgetTrie;
152
153/// The capstone C library this build is linked against, as `"major.minor"`.
154///
155/// Reported by the library itself at runtime (`cs_version()`, wrapped by
156/// capstone-rs as `Capstone::lib_version`), not by the crate version — so
157/// it stays true if the pin in Cargo.toml ever moves or a distributor
158/// links a system capstone. capstone's C API returns only major and
159/// minor: `CS_VERSION_EXTRA` is a compile-time macro that `cs_version()`
160/// does not hand back, so there is no patch level to print and none is
161/// invented here (CLAIM-10; PLAN.md:262 wants this recorded because
162/// disassembly text drifts between capstone releases and that drift is
163/// the project's #1 parity risk).
164///
165/// Only the non-x86 architectures decode through capstone; x86/x64 go
166/// through iced-x86, which exposes no runtime version at all.
167pub fn capstone_version() -> String {
168    let (major, minor) = capstone::Capstone::lib_version();
169    format!("{major}.{minor}")
170}
171
172#[cfg(test)]
173mod tests {
174    /// The pinned `capstone = "=0.13.0"` bundles the capstone 5.0 C core;
175    /// if a future bump changes what the linked library reports, this
176    /// fails and `--version` has to be re-checked rather than silently
177    /// printing something new.
178    #[test]
179    fn capstone_version_is_the_linked_library_version() {
180        assert_eq!(super::capstone_version(), "5.0");
181    }
182}