Skip to main content

rf_cli/
lib.rs

1//! rop-finder — ROPgadget-compatible CLI library.
2//!
3//! Phase 1: ELF, PE, Mach-O, Universal/fat Mach-O, and raw blobs; all
4//! supported architectures. Format dispatch mirrors ROPgadget's
5//! `binary.py`: `--rawArch` forces the raw loader regardless of magic
6//! bytes; otherwise magic-byte dispatch via `rf_core::Binary::load`.
7//! Universal (fat Mach-O) binaries follow ROPgadget's `universal.py`:
8//! every slice's executable regions are concatenated and scanned with the
9//! FIRST slice's arch/mode/endianness (universal.py:92-108 returns
10//! "whatever is in the first binary").
11//!
12//! Phase 2 (PLAN.md §6.3/§6.4):
13//!   * `--section <glob>` — restrict the scan to named executable sections
14//!     (repeatable, comma-separated, `*` globbing).
15//!   * `--base <hex>` — rebase the image at load time (rf-core `rebase`).
16//!   * `--info` — dump image metadata as JSON without scanning.
17//!
18//! Phase 3 (PLAN.md §6.1): the scan orchestration (`ScanRequest` →
19//! [`scan_bytes`] / [`info_bytes`]) is library API so the `rf-mcp` MCP
20//! server reuses it without shelling out to the CLI. Since v1.0 that
21//! orchestration lives in the `rf-api` LIBRARY crate and is re-exported
22//! here unchanged (ENG-08/ECO-10): `rf-mcp` depends on `rf-api`, never on
23//! this binary crate. What is left in this file is the CLI itself — the
24//! clap surface, the output formats, the scan cache's key and directory,
25//! and `main_entry`.
26//!
27//! Exit codes: 0 success, 1 usage error, 2 malformed/unsupported binary.
28
29use std::process::ExitCode;
30
31mod console;
32mod format;
33mod out;
34mod search;
35
36use clap::Parser;
37use rf_core::{Arch, Endianness, Image};
38use rf_scan::{Gadget, ScanOptions};
39
40/// The shared request layer, re-exported so that `rf_cli::ScanRequest` and
41/// `rf_api::ScanRequest` stay one type and every existing `use rf_cli::…`
42/// keeps compiling. The definitions live in `rf-api`.
43pub use rf_api::*;
44
45/// `--version` body (CLAIM-10). clap prints `"rop-finder "` in front of
46/// it, so the first line completes the usual `name version` line and the
47/// rest is the provenance a bug report needs.
48///
49/// The capstone version is the one the process is actually linked against,
50/// asked of the library at runtime — PLAN.md:262 names capstone drift the
51/// project's #1 residual parity risk, and a version reprinted from a
52/// Cargo.toml pin would not detect the drift it is supposed to record.
53///
54/// No Cargo.lock hash is printed. Computing one honestly needs a build
55/// script hashing a file that does not exist in a packaged crate or in a
56/// `cargo install` build, and a hash that is silently absent or wrong is
57/// worse than no hash; the lockfile is committed instead (ENG-02).
58///
59/// Returned as `&'static str` (built once in a `OnceLock`) because clap's
60/// `long_version` only accepts a borrowed string unless the `string`
61/// feature is enabled workspace-wide.
62fn long_version() -> &'static str {
63    static LONG_VERSION: std::sync::OnceLock<String> = std::sync::OnceLock::new();
64    LONG_VERSION.get_or_init(|| {
65        format!(
66            "{ver}\n\
67             Written by {authors}.\n\
68             \n\
69             capstone {cs} (bundled; decodes ARM, ARM64, MIPS, PPC, SPARC, RISC-V)\n\
70             iced-x86 (decodes x86/x64)\n\
71             \n\
72             A port of ROPgadget by Jonathan Salwan, Alexey Vishnyakov and \
73             contributors (BSD-3-Clause):\n\
74             https://github.com/JonathanSalwan/ROPgadget",
75            ver = env!("CARGO_PKG_VERSION"),
76            // From `authors` in the workspace manifest, so the binary and the
77            // crates.io metadata cannot disagree. Cargo joins multiple authors
78            // with ':'. This credits the author of the Rust work; it does NOT
79            // replace the ROPgadget line below, which credits the upstream
80            // project this is a port of and is required by its licence (ENG-03).
81            authors = env!("CARGO_PKG_AUTHORS").replace(':', ", "),
82            cs = rf_scan::capstone_version(),
83        )
84    })
85}
86
87#[derive(Parser, Debug)]
88#[command(
89    name = "rop-finder",
90    version,
91    long_version = long_version(),
92    disable_version_flag = true,
93    about = "Fast Rust ROP/JOP/SYS gadget finder (ROPgadget rewrite)"
94)]
95pub struct Cli {
96    /// Display the version, the linked capstone build and the ROPgadget
97    /// attribution, and exit 0
98    ///
99    /// CLI-12: ROPgadget spells this `-v`/`--version` (args.py:75) and
100    /// rop-finder bound only clap's automatic `-V`, so every ROPgadget
101    /// script that starts with a `-v` capability probe died on
102    /// "unexpected argument '-v' found". Both shorts are bound here; the
103    /// text deliberately still differs from the oracle's four-line block,
104    /// because CLAIM-10 requires the linked capstone version to be in it.
105    #[arg(
106        short = 'v',
107        short_alias = 'V',
108        long = "version",
109        action = clap::ArgAction::Version
110    )]
111    pub version: Option<bool>,
112
113    /// Specify a binary filename to analyze (optional with --console)
114    #[arg(long)]
115    pub binary: Option<String>,
116
117    /// Depth for search engine (default 10)
118    #[arg(long, default_value_t = 10)]
119    pub depth: usize,
120
121    /// Disable ROP search engine
122    #[arg(long)]
123    pub norop: bool,
124
125    /// Disable JOP search engine
126    #[arg(long)]
127    pub nojop: bool,
128
129    /// Disable SYS search engine
130    #[arg(long)]
131    pub nosys: bool,
132
133    /// Enable multiple branch gadgets
134    #[arg(long)]
135    pub multibr: bool,
136
137    /// Only show specific instructions (e.g. "pop|ret|mov")
138    #[arg(long)]
139    pub only: Option<String>,
140
141    /// Suppress gadgets containing a matching mnemonic. A `|`-separated
142    /// regex alternation, FULL-matched against each mnemonic as ROPgadget
143    /// does (e.g. "leave|enter", "j.*"). Not a suffix match: "op" matches
144    /// no mnemonic and so filters nothing, it does not remove `pop`
145    #[arg(long)]
146    pub filter: Option<String>,
147
148    /// Search between two addresses (0x...-0x...)
149    #[arg(long)]
150    pub range: Option<String>,
151
152    /// Rejects specific bytes in the gadget's FINAL address, after --base
153    /// rebase and --offset (e.g. "0a|0d" or "00-1f")
154    #[arg(long)]
155    pub badbytes: Option<String>,
156
157    /// Specify an offset ADDED to gadget addresses after any --base rebase
158    /// (hex)
159    #[arg(long)]
160    pub offset: Option<String>,
161
162    /// Rebase the binary to this image base at load time, before scanning
163    /// and before --offset is applied (hex). Use 0 for RVA-style addresses
164    #[arg(long)]
165    pub base: Option<String>,
166
167    /// Dump image metadata (format/arch/sections/imports) as JSON and exit
168    /// without scanning
169    #[arg(long)]
170    pub info: bool,
171
172    /// Generate a ROP chain; default output is the Python exploit script,
173    /// with --json the JSON Chain IR. Target selection via --chain
174    #[arg(long)]
175    pub ropchain: bool,
176
177    /// Machine-readable feasibility report for the --chain target instead
178    /// of a chain: which requirements this binary meets, which it does not,
179    /// what was tried, and which parameter changes would help (measured, by
180    /// re-scanning). Always succeeds; always JSON (ECO-04)
181    #[arg(long)]
182    pub plan_chain: bool,
183
184    /// Chain target for --ropchain / --plan-chain: linux-execve (default),
185    /// linux-mprotect, linux-syscall, linux-ret2libc, linux-srop (ELF
186    /// x86/x64) or windows-virtualprotect (PE x86/x64)
187    #[arg(long, default_value = "linux-execve")]
188    pub chain: String,
189
190    /// Syscall number for --chain linux-syscall, and the syscall the
191    /// linux-srop frame invokes (decimal, or hex with 0x)
192    #[arg(long, value_name = "<n>")]
193    pub syscall: Option<String>,
194
195    /// Argument registers for --chain linux-syscall / linux-srop, e.g.
196    /// "rdi=0x404000,rsi=0x1000,rdx=7" (hex values)
197    #[arg(long, value_name = "<reg=val,...>")]
198    pub syscall_args: Option<String>,
199
200    /// Pivot the stack pointer to this address before the chain body runs
201    /// (hex). The emitted chain is then in two pieces: the leading
202    /// `pivot_words` go at the overflow point, the rest go here (CHWIN-08).
203    /// Spelled `--chain-pivot` because `--pivot` is the v0.4 gadget-query
204    /// preset (ECO-12) and taking that name would silently change what an
205    /// existing command means
206    #[arg(long = "chain-pivot", value_name = "<addr>")]
207    pub chain_pivot: Option<String>,
208
209    /// Shellcode bytes (hex, e.g. "9090cc") for windows-virtualprotect to
210    /// WRITE into the region at --shellcode-addr with write-what-where
211    /// gadgets, instead of assuming it is already there (CHWIN-08)
212    #[arg(long, value_name = "<hex>")]
213    pub stage: Option<String>,
214
215    /// Runtime address of the target API for windows-virtualprotect (hex),
216    /// or the function linux-ret2libc calls. Primary resolution path;
217    /// without it a PE must import the API (IAT dereference). A
218    /// comma-separated list supplies one address per --api-name
219    #[arg(long)]
220    pub api_addr: Option<String>,
221
222    /// API windows-virtualprotect targets: VirtualProtect (default) or
223    /// VirtualAlloc. Selects the IAT import to resolve AND the argument
224    /// recipe — the two do not take the same four arguments (CHWIN-06).
225    /// A comma-separated list composes several calls into one chain, each
226    /// returning into the next through a stack-adjust gadget (CHWIN-08)
227    #[arg(long)]
228    pub api_name: Option<String>,
229
230    /// What the windows-virtualprotect x64 alignment invariant may assume
231    /// about the chain's first word: return-address (default, the chain
232    /// overwrites a saved return address, so its base is 8 mod 16) or
233    /// aligned (the base is 16-byte aligned)
234    #[arg(long)]
235    pub chain_base: Option<String>,
236
237    /// Protection constant (hex). For windows-virtualprotect it is
238    /// flNewProtect / flProtect and defaults to 0x40 =
239    /// PAGE_EXECUTE_READWRITE; for linux-mprotect it is mprotect's `prot`
240    /// and defaults to 7 = PROT_READ|PROT_WRITE|PROT_EXEC. The default
241    /// follows the target because the two constant spaces are unrelated
242    #[arg(long)]
243    pub prot: Option<String>,
244
245    /// Runtime address the shellcode will occupy for windows-virtualprotect
246    /// (hex; default: the binary's writable .data section)
247    #[arg(long)]
248    pub shellcode_addr: Option<String>,
249
250    /// dwSize argument for windows-virtualprotect (hex; default 0x1000)
251    #[arg(long)]
252    pub shellcode_size: Option<String>,
253
254    /// CFG/CET-aware scan: keep only gadgets whose entry is an
255    /// endbr64/endbr32 instruction (x86/x64)
256    #[arg(long)]
257    pub cfg_aware: bool,
258
259    /// Scan only the named executable section(s); repeatable and
260    /// comma-separated, `*` globbing allowed (e.g. --section .text or
261    /// --section ".init*,.plt")
262    #[arg(long = "section", value_delimiter = ',')]
263    pub section: Vec<String>,
264
265    /// Use the thumb mode for the search engine (ARM only)
266    #[arg(long)]
267    pub thumb: bool,
268
269    /// Specify an arch for a raw file: x86|arm|arm64|sparc|mips|ppc|riscv
270    #[arg(long = "rawArch", value_name = "<arch>")]
271    pub raw_arch: Option<String>,
272
273    /// Specify a mode for a raw file: 32|64|arm|thumb|riscv
274    #[arg(long = "rawMode", value_name = "<mode>")]
275    pub raw_mode: Option<String>,
276
277    /// Specify an endianness for a raw file: little|big
278    #[arg(long = "rawEndian", value_name = "<endian>")]
279    pub raw_endian: Option<String>,
280
281    /// Emit a JSON array of {vaddr, bytes, text} instead of human output
282    #[arg(long)]
283    pub json: bool,
284
285    /// Semantic classification (Phase 5): --json gadget records gain
286    /// class/labels/regs_written/regs_read/side_effects/quality fields.
287    /// Rules live in TAXONOMY.md; no effect without --json
288    #[arg(long)]
289    pub classify: bool,
290
291    /// Rank gadgets by quality score (best first, ties by address);
292    /// applies to both human and JSON output
293    #[arg(long)]
294    pub rank: bool,
295
296    /// Keep only gadgets whose primary class is one of these
297    /// (comma-separated): reg-write, stack-pivot, mem-read, mem-write,
298    /// arithmetic, syscall, dispatcher, other. Implies --classify's
299    /// analysis; add --classify to see the fields in --json output
300    /// (CLS-08 — the MCP server has the same filter)
301    #[arg(long = "class", value_name = "<class[,class...]>")]
302    pub class: Option<String>,
303
304    /// Keep only gadgets carrying at least one of these labels (same
305    /// vocabulary as --class; a gadget can earn several)
306    #[arg(long = "label", value_name = "<label[,label...]>")]
307    pub label: Option<String>,
308
309    /// Keep only gadgets that write ALL of these registers
310    /// (comma-separated, e.g. rdi or rdi,rsi). Names are matched
311    /// lowercase and without a $/% sigil
312    #[arg(long = "writes-reg", value_name = "<reg[,reg...]>")]
313    pub writes_reg: Option<String>,
314
315    // -- ECO-01 / ECO-12: the constraint query layer (v0.4) ---------------
316    // Every flag below is one `find_gadgets_by_effect` parameter of the
317    // same name in snake_case. See crates/rf-cli/src/query.rs.
318    /// Keep only gadgets that WRITE these registers with a value the chain
319    /// payload decides (rf_classify `sets`, full-width architectural names:
320    /// rdi not edi on x64, x0 not w0 on ARM64)
321    #[arg(long = "set-reg", value_name = "<reg[,reg...]>")]
322    pub set_reg: Option<String>,
323
324    /// Require the write to ORIGINATE in a pop or a stack-pointer-relative
325    /// load rather than an arbitrary computation ("xor rdi, rdi" sets rdi
326    /// but does not take it from the stack). Narrows --set-reg, or
327    /// --writes-reg, or — with neither — means "some register comes off
328    /// the payload"
329    #[arg(long = "from-stack")]
330    pub from_stack: bool,
331
332    /// Reject gadgets that CLOBBER any of these registers (comma-separated).
333    /// Clobber is the rf_classify partition, not regs_written: a register
334    /// written with a payload-controlled value is a `set`, not a clobber
335    #[arg(long = "no-clobber", value_name = "<reg[,reg...]>")]
336    pub no_clobber: Option<String>,
337
338    /// Keep only gadgets that READ ALL of these registers (comma-separated) — as an operand, an
339    /// address component, a transfer dependency or the terminator's target
340    #[arg(long = "reads-reg", value_name = "<reg[,reg...]>")]
341    pub reads_reg: Option<String>,
342
343    /// Keep only gadgets whose stack pointer moves at most N bytes
344    /// (terminator included). A gadget whose rsp effect is not provably
345    /// constant reports "unknown" and is REJECTED, never treated as 0
346    #[arg(
347        long = "max-stack-delta",
348        value_name = "<n>",
349        allow_negative_numbers = true
350    )]
351    pub max_stack_delta: Option<i64>,
352
353    /// Keep only gadgets with at most N side effects (TAXONOMY.md R11)
354    #[arg(long = "max-side-effects", value_name = "<n>")]
355    pub max_side_effects: Option<usize>,
356
357    /// Keep only gadgets with at most N instructions (the terminator counts)
358    #[arg(long = "max-insns", value_name = "<n>")]
359    pub max_insns: Option<usize>,
360
361    /// Keep only gadgets with this terminator; comma-separated, any-of.
362    /// Coarse: ret|jmp|call|syscall|none|any. Fine (CLS-09): bare-ret|
363    /// ret-imm|jmp-reg|jmp-mem|call-reg|call-mem|far|other. Coarse "ret"
364    /// includes ret imm16/retf/iret; "bare-ret" is the plain near return
365    /// only; "any" is no constraint. Same 13 values as the MCP
366    /// `terminator` parameter
367    #[arg(long = "terminator", value_name = "<kind[,kind...]>")]
368    pub terminator: Option<String>,
369
370    /// Ropper-style gadget-sequence search, e.g. "pop rdi; ret". Matches a
371    /// CONTIGUOUS run of instructions; `?` is any one character and `%` any
372    /// run of characters within one instruction. Not --re, which is
373    /// ROPgadget's per-instruction regex conjunction
374    #[arg(long = "search", value_name = "<pattern>")]
375    pub search: Option<String>,
376
377    /// Stack-pivot preset (ECO-12): exactly --label stack-pivot
378    #[arg(long)]
379    pub pivot: bool,
380
381    // -- ECO-09: output formats ------------------------------------------
382    /// Output format: human (default), json, jsonl, csv, raw. `jsonl`
383    /// STREAMS — records are written during the scan, in scan order rather
384    /// than the alphabetical order of the other formats. `raw` is the
385    /// undecorated listing; with --noinstr it is the address-only mode
386    #[arg(long = "format", value_name = "<fmt>")]
387    pub format: Option<String>,
388
389    /// --ropchain output: python (default), json, or raw (the packed
390    /// little-endian chain payload, written to stdout as BYTES)
391    #[arg(long = "chain-format", value_name = "<fmt>")]
392    pub chain_format: Option<String>,
393
394    /// Cache scan results on disk, keyed by the binary's content hash plus
395    /// all scan parameters. Cache directory: ROP_FINDER_CACHE_DIR, else
396    /// %LOCALAPPDATA%/rop-finder/cache (Windows) or ~/.cache/rop-finder
397    #[arg(long)]
398    pub cache: bool,
399
400    /// Delete every entry in the scan cache directory and exit. Needs no
401    /// --binary. Size cap and lifetime are ROP_FINDER_CACHE_MAX_BYTES
402    /// (default 512 MiB) and ROP_FINDER_CACHE_TTL_SECS (default 14 days)
403    #[arg(long)]
404    pub cache_purge: bool,
405
406    /// Search a string (byte regex, e.g. "m..n") in readable (data)
407    /// sections instead of gadget scanning
408    #[arg(long)]
409    pub string: Option<String>,
410
411    /// Search an opcode byte sequence (hex, e.g. c9c3) in executable
412    /// sections instead of gadget scanning
413    #[arg(long)]
414    pub opcode: Option<String>,
415
416    /// Search the first occurrence of each byte of the string across all
417    /// readable sections instead of gadget scanning
418    #[arg(long)]
419    pub memstr: Option<String>,
420
421    /// Regular expression over gadget instructions; every |-separated
422    /// pattern must match at least one instruction (options.py:64-98)
423    #[arg(long)]
424    pub re: Option<String>,
425
426    /// Only show gadgets immediately preceded by a call instruction
427    /// (x86/x64; options.py:100-120 heuristic)
428    #[arg(long = "callPreceded")]
429    pub call_preceded: bool,
430
431    /// Disable the gadget instruction printing: bare addresses, no dedup,
432    /// no sort
433    #[arg(long)]
434    pub noinstr: bool,
435
436    /// Append the gadget bytes to human output (" // hexbytes")
437    #[arg(long)]
438    pub dump: bool,
439
440    /// Suppress gadget printing during analysis (the callPreceded filter
441    /// line still prints, as in ROPgadget)
442    #[arg(long)]
443    pub silent: bool,
444
445    /// Align gadget addresses (overrides anchor stepping alignment, in
446    /// bytes; 0 = no alignment constraint)
447    #[arg(long)]
448    pub align: Option<usize>,
449
450    /// MIPS useful-gadget finder: stackfinder|system|tails|lia0|registers
451    #[arg(long)]
452    pub mipsrop: Option<String>,
453
454    /// Disable duplicate-gadget removal
455    #[arg(long)]
456    pub all: bool,
457
458    /// Interactive console (REPL) for the search engine; with --binary the
459    /// binary is preloaded
460    #[arg(long)]
461    pub console: bool,
462
463    /// Architecture slice to scan in a fat (Universal) Mach-O, e.g.
464    /// x86_64, arm64, i386. REQUIRED for a multi-slice file: without it
465    /// rop-finder refuses rather than concatenating slices whose virtual
466    /// address ranges overlap (CORE-03)
467    #[arg(long, value_name = "<slice>")]
468    pub arch: Option<String>,
469
470    /// Refuse input files larger than this many bytes; accepts a K/M/G
471    /// suffix. Non-regular files (devices, FIFOs, directories) are always
472    /// refused (ROB-06)
473    #[arg(long = "max-file-size", value_name = "<bytes>", default_value = "512M")]
474    pub max_file_size: String,
475
476    /// Stop the scan once this many gadgets have been accepted, and report
477    /// the budget instead of a truncated listing (PERF-05)
478    #[arg(long = "max-gadgets", value_name = "<n>")]
479    pub max_gadgets: Option<usize>,
480
481    /// Stop the scan once the retained gadgets are estimated to exceed this
482    /// many heap bytes; accepts a K/M/G suffix (PERF-05)
483    #[arg(long = "max-memory", value_name = "<bytes>")]
484    pub max_memory: Option<String>,
485
486    /// Bug-for-bug ROPgadget compatibility where rop-finder deliberately
487    /// differs (CLI-11). Exactly two things. (1) A fat (Universal) Mach-O
488    /// with no --arch is scanned as ROPgadget scans it — every slice's
489    /// executable regions concatenated and disassembled with the FIRST
490    /// slice's decoder — instead of being refused; the output is then
491    /// knowingly part-fabricated and a warning says so. (2) --string and
492    /// --memstr read a section's DECLARED file extent (elf.py:332) rather
493    /// than the bytes it really owns, which resurrects the oracle's
494    /// SHT_NOBITS phantom hits. It does NOT change gadget text or layout
495    #[arg(long)]
496    pub compat: bool,
497}
498
499/// ROPgadget's raw-loader argument validation (args.py:114-128) and the
500/// raw.py arch/mode/endian mapping, resolved to the rf-core contract.
501/// Returns (arch, endianness, thumb) when a raw load was requested.
502fn parse_raw_spec(cli: &Cli) -> Result<Option<(Arch, Endianness, bool)>, String> {
503    if cli.thumb && cli.raw_mode.is_some() && cli.raw_mode.as_deref() != Some("thumb") {
504        return Err("--rawMode is conflicting with --thumb".to_string());
505    }
506    if cli.raw_arch.is_none() && cli.raw_mode.is_some() {
507        return Err("Specify --rawArch".to_string());
508    }
509    if cli.raw_arch.is_none() && cli.raw_endian.is_some() {
510        return Err("Specify --rawArch".to_string());
511    }
512    let Some(arch_s) = cli.raw_arch.as_deref() else {
513        return Ok(None);
514    };
515    // args.py:123 — --thumb implies rawMode=thumb.
516    let mode_s = if cli.thumb {
517        Some("thumb")
518    } else {
519        cli.raw_mode.as_deref()
520    };
521    let Some(mode_s) = mode_s else {
522        return Err("Specify --rawMode".to_string());
523    };
524    if !["32", "64", "arm", "thumb", "riscv"].contains(&mode_s) {
525        return Err(format!(
526            "invalid --rawMode {mode_s:?} (32|64|arm|thumb|riscv)"
527        ));
528    }
529    // args.py:128 — the flag that is missing here is --rawEndian, not
530    // --rawArch (which the `let Some(arch_s)` above has already proved
531    // present). CLI-13: this message was a copy-paste of the two guards
532    // above and named the wrong flag.
533    if cli.raw_endian.is_none() && arch_s != "x86" {
534        return Err("Specify --rawEndian".to_string());
535    }
536    let endian = match cli.raw_endian.as_deref() {
537        None | Some("little") => Endianness::Little,
538        Some("big") => Endianness::Big,
539        Some(e) => return Err(format!("invalid --rawEndian {e:?} (little|big)")),
540    };
541    // raw.py:71-72 — x86 is always little-endian.
542    let endian = if arch_s == "x86" {
543        Endianness::Little
544    } else {
545        endian
546    };
547    // raw.py mode/endian interplay with gadgets.py's per-arch mode
548    // overrides: arm64 always lands in CS_MODE_ARM, sparc in mode 0, riscv
549    // in RV64|RISCVC regardless of the requested 32/64 (gadgets.py:178,
550    // 191, 202), so those accept any listed mode.
551    let (arch, thumb) = match (arch_s, mode_s) {
552        ("x86", "32") => (Arch::X86, false),
553        ("x86", "64") => (Arch::X64, false),
554        ("arm", "thumb") => (Arch::ArmThumb, true),
555        ("arm", _) => (Arch::Arm, false),
556        ("arm64", _) => (Arch::Arm64, false),
557        ("sparc", _) => (Arch::Sparc, false),
558        ("mips", "32") => (Arch::Mips32, false),
559        ("mips", "64") => (Arch::Mips64, false),
560        ("ppc", "32") => (Arch::Ppc32, false),
561        ("ppc", "64") => (Arch::Ppc64, false),
562        ("riscv", _) => (Arch::RiscV64, false),
563        (a, m) => {
564            return Err(format!(
565                "unsupported --rawArch {a:?} / --rawMode {m:?} combination"
566            ))
567        }
568    };
569    Ok(Some((arch, endian, thumb)))
570}
571
572/// options.py:22-33 — the post-scan gadget filters in oracle order: --re
573/// first, then --callPreceded. The "Filtered out" line prints even under
574/// --silent because Options runs inside __getGadgets, before the looking
575/// function's silent check.
576///
577/// `json` redirects that line to STDERR. ROPgadget has no --json, so there is
578/// no oracle behaviour to copy here, and a progress line on stdout ahead of
579/// the array makes `--json` unparseable — `--callPreceded --json` emitted
580/// `Options().removeNonCallPreceded(): ...` followed by the JSON and every
581/// consumer (the parity harness included) failed to decode it. Human output
582/// is byte-for-byte unchanged, so the --compat diff against the oracle is
583/// unaffected.
584fn apply_post_filters(
585    gadgets: &mut Vec<Gadget>,
586    re: &Option<String>,
587    call_preceded: bool,
588    arch: Arch,
589    json: bool,
590    out: &mut dyn std::io::Write,
591) -> Result<(), String> {
592    if let Some(re) = re {
593        search::apply_re_filter(gadgets, re)?;
594    }
595    if call_preceded {
596        let line = if matches!(arch, Arch::X86 | Arch::X64) {
597            let before = gadgets.len();
598            gadgets.retain(|g| g.prev.as_deref().is_some_and(search::is_call_preceded));
599            format!(
600                "Options().removeNonCallPreceded(): Filtered out {} gadgets.",
601                before - gadgets.len()
602            )
603        } else {
604            "Options().removeNonCallPreceded(): Unsupported architecture.".to_string()
605        };
606        if json {
607            eprintln!("{line}");
608        } else {
609            let _ = writeln!(out, "{line}");
610        }
611    }
612    Ok(())
613}
614
615/// Every byte of stdout goes through `out` — one buffered, locked writer
616/// owned by [`main_entry`] (PERF-07), which also decides what a write
617/// failure means for the exit code (ROB-03). There is deliberately no
618/// `println!` left on any path reachable from here: it would take the
619/// stdout lock again and interleave ahead of what is still buffered.
620fn run(cli: Cli, out: &mut dyn std::io::Write) -> Result<i32, String> {
621    // Error precedence mirrors the pre-refactor CLI exactly: depth → file
622    // read → raw spec → option parsing → binary load → (--info | --base →
623    // --section → scan).
624    if cli.depth < 2 {
625        return Err("--depth must be >= 2".to_string());
626    }
627    // args.py:108-112 cross-flag validation.
628    if cli.noinstr && cli.only.is_some() {
629        return Err("--noinstr and --only=<key> can't be used together".to_string());
630    }
631    if cli.noinstr && cli.re.is_some() {
632        return Err("--noinstr and --re=<re> can't be used together".to_string());
633    }
634    // --cache-purge is maintenance, not analysis: it runs before the
635    // "a binary is required" gate so `rop-finder --cache-purge` works on
636    // its own (CLI-08/PERF-12).
637    if cli.cache_purge {
638        return Ok(run_cache_purge(out));
639    }
640    // args.py:142-143: a binary is required unless the console is requested.
641    if cli.binary.is_none() && !cli.console {
642        return Err("Need a binary filename (--binary/--console or --help)".to_string());
643    }
644
645    // ECO-09. Parsed here, before any work, so `--format yaml` costs a
646    // message rather than a scan.
647    let (out_format, chain_format) = resolve_formats(&cli)?;
648    // ECO-01: one predicate, built once, applied by both the streaming and
649    // the buffered path.
650    let q = query::Query::parse(&query::QuerySpec {
651        class: cli.class.as_deref(),
652        label: cli.label.as_deref(),
653        writes_reg: cli.writes_reg.as_deref(),
654        set_reg: cli.set_reg.as_deref(),
655        from_stack: cli.from_stack,
656        no_clobber: cli.no_clobber.as_deref(),
657        reads_reg: cli.reads_reg.as_deref(),
658        max_stack_delta: cli.max_stack_delta,
659        max_side_effects: cli.max_side_effects,
660        max_insns: cli.max_insns,
661        terminator: cli.terminator.as_deref(),
662        search: cli.search.as_deref(),
663        pivot: cli.pivot,
664    })?;
665
666    // --console: interactive REPL (binary optional, preloaded when given).
667    if cli.console {
668        return console::run_console(&cli, out);
669    }
670
671    let binary = cli.binary.as_deref().unwrap();
672    // ROB-06: stat before allocating. `--binary /dev/zero` now errors in
673    // milliseconds instead of consuming the machine.
674    let max_file_size = parse_size(&cli.max_file_size, "--max-file-size")?;
675    let bytes = read_input_file(binary, max_file_size)?;
676    let raw = parse_raw_spec(&cli)?;
677
678    let max_memory = cli
679        .max_memory
680        .as_deref()
681        .map(|m| parse_size(m, "--max-memory"))
682        .transpose()?
683        .map(|m| m as usize);
684
685    let req = ScanRequest {
686        depth: cli.depth,
687        rop: !cli.norop,
688        jop: !cli.nojop,
689        sys: !cli.nosys,
690        multibr: cli.multibr,
691        only: cli.only.clone(),
692        filter: cli.filter.clone(),
693        range: cli.range.clone(),
694        badbytes: cli.badbytes.clone(),
695        offset: cli.offset.clone(),
696        base: cli.base.clone(),
697        section: cli.section.clone(),
698        thumb: cli.thumb,
699        cfg_aware: cli.cfg_aware,
700        align: cli.align,
701        call_preceded: cli.call_preceded,
702        all: cli.all,
703        noinstr: cli.noinstr,
704        arch: cli.arch.clone(),
705        max_gadgets: cli.max_gadgets,
706        max_memory,
707        compat: cli.compat,
708    };
709    let opts = match request_options(&req, raw) {
710        Ok(o) => o,
711        Err(ScanError::Usage(e)) => return Err(e),
712        Err(ScanError::Binary(e) | ScanError::Chain(e)) => return Err(e), // unreachable
713    };
714    let target = match load_target(&bytes, raw) {
715        Ok(t) => t,
716        Err(ScanError::Binary(e)) => {
717            eprintln!("[Error] {e}");
718            return Ok(2);
719        }
720        Err(ScanError::Usage(e) | ScanError::Chain(e)) => return Err(e), // unreachable
721    };
722
723    // --info: metadata only, no scanning. --base is honoured.
724    if cli.info {
725        let new_base = cli
726            .base
727            .as_deref()
728            .map(|b| parse_hex(b, "--base"))
729            .transpose()?;
730        let _ = writeln!(
731            out,
732            "{}",
733            serde_json::to_string_pretty(&info_json(&target, new_base)).unwrap()
734        );
735        return Ok(0);
736    }
737
738    // --ropchain: chain generation (--chain selects the target). Unlike
739    // ROPgadget, which dumps the gadget list and step logs first, we print
740    // only the exploit script (or the JSON Chain IR with --json).
741    if cli.ropchain || cli.plan_chain {
742        // CHWIN-09: warn before doing the work, not after printing a
743        // chain that looks authoritative.
744        if let Some(warning) = chain_experimental_warning(&cli.chain) {
745            eprint!("{warning}");
746        }
747        let spec = ChainSpec {
748            target: cli.chain.clone(),
749            api_addr: cli.api_addr.clone(),
750            api_name: cli.api_name.clone(),
751            shellcode_addr: cli.shellcode_addr.clone(),
752            shellcode_size: cli.shellcode_size.clone(),
753            chain_base: cli.chain_base.clone(),
754            prot: cli.prot.clone(),
755            syscall: cli.syscall.clone(),
756            syscall_args: cli.syscall_args.clone(),
757            pivot: cli.chain_pivot.clone(),
758            stage: cli.stage.clone(),
759        };
760        // ECO-04: `--plan-chain` ALWAYS succeeds. Infeasibility is a
761        // result, and it is the same document `--ropchain --json` prints
762        // when it has to refuse, so an agent parses one shape either way.
763        if cli.plan_chain {
764            let outcome = match plan_chain_bytes(&bytes, raw, &req, &spec) {
765                Ok(o) => o,
766                Err(ScanError::Usage(e)) | Err(ScanError::Chain(e)) => return Err(e),
767                Err(ScanError::Binary(e)) => {
768                    eprintln!("[Error] {e}");
769                    return Ok(2);
770                }
771            };
772            let _ = writeln!(out, "{}", plan_json(&outcome));
773            return Ok(0);
774        }
775        let outcome = match chain_bytes(&bytes, raw, &req, &spec) {
776            Ok(o) => o,
777            Err(ScanError::Usage(e)) | Err(ScanError::Chain(e)) => {
778                // ECO-04: on the JSON surface a refusal is a DOCUMENT, not
779                // a sentence. `--ropchain --json` that cannot build prints
780                // the same ChainPlan `--plan-chain` prints (feasible:false,
781                // with the requirement that failed), and still exits
782                // non-zero. The human/python surface is untouched.
783                if chain_format == format::ChainFormat::Json {
784                    if let Ok(o) = plan_chain_bytes(&bytes, raw, &req, &spec) {
785                        let _ = writeln!(out, "{}", plan_json(&o));
786                    }
787                }
788                return Err(e);
789            }
790            Err(ScanError::Binary(e)) => {
791                eprintln!("[Error] {e}");
792                return Ok(2);
793            }
794        };
795        if outcome.outcome.fallback_names {
796            eprintln!(
797                "[Warning] binary has no section names (stripped ELF?);                  executable segments are named PT_LOAD#n"
798            );
799        }
800        match chain_format {
801            format::ChainFormat::Json => {
802                let _ = writeln!(out, "{}", chain_json(&outcome));
803            }
804            // ECO-09 part 2: MANUAL.md has advertised "raw bytes" chain
805            // output since v0.1 and `RopChain::to_bytes` was called only
806            // from unit tests. These are real bytes, not a hex dump —
807            // redirect them into a file or a harness's stdin.
808            format::ChainFormat::Raw => {
809                let _ = out.write_all(&outcome.chain.to_bytes());
810            }
811            format::ChainFormat::Python => {
812                let _ = write!(out, "{}", outcome.chain.to_python());
813            }
814        }
815        return Ok(0);
816    }
817
818    let orig_base = target_base(&target);
819    let base = cli
820        .base
821        .as_deref()
822        .map(|b| parse_hex(b, "--base"))
823        .transpose()?;
824    let prepared = match prepare_view(&target, base, &cli.section, cli.arch.as_deref(), cli.compat)
825    {
826        Ok(v) => v,
827        Err(ScanError::Usage(e)) => return Err(e),
828        Err(ScanError::Binary(e) | ScanError::Chain(e)) => return Err(e), // unreachable
829    };
830    let view = prepared.view;
831    if prepared.fallback_names {
832        eprintln!(
833            "[Warning] binary has no section names (stripped ELF?); \
834             executable segments are named PT_LOAD#n"
835        );
836    }
837    for w in scan_warnings(&target, &view, cli.cfg_aware, cli.compat) {
838        eprintln!("{w}");
839    }
840    let universal_arch = view.universal.then_some(view.arch());
841
842    // core.py:248-261 dispatch order: console → string → opcode → memstr
843    // → mipsrop → gadget scan. Search modes ignore --section (the oracle
844    // has no --section); --base/--offset/--range apply.
845    if cli.string.is_some() || cli.opcode.is_some() || cli.memstr.is_some() {
846        if cli.silent {
847            return Ok(0); // core.py:163-164 etc.: search modes print nothing
848        }
849        let delta = view.base.wrapping_sub(orig_base);
850        let width8 = search::search_width8(&target, view.arch());
851        // --compat: search the raw file extent a section DECLARES rather
852        // than the content it really owns, reproducing the oracle's
853        // SHT_NOBITS read (see search::compat_bytes).
854        let compat_file = cli.compat.then_some(bytes.as_slice());
855        if let Some(s) = &cli.string {
856            let hits =
857                search::find_string(&target, delta, opts.offset, opts.range, s, compat_file)?;
858            if out_format.is_structured() {
859                let v = search::search_json_string(&hits, width8);
860                print_hit_records(&v, search::STRING_COLUMNS, out_format, out);
861            } else {
862                search::print_string_hits(&hits, width8, out);
863            }
864        } else if let Some(op) = &cli.opcode {
865            let hits = search::find_opcode(&target, delta, opts.offset, opts.range, op)?;
866            if out_format.is_structured() {
867                let v = search::search_json_opcode(&hits, op, width8);
868                print_hit_records(&v, search::OPCODE_COLUMNS, out_format, out);
869            } else {
870                search::print_opcode_hits(&hits, op, width8, out);
871            }
872        } else if let Some(m) = &cli.memstr {
873            let hits = search::find_memstr(&target, delta, opts.offset, opts.range, m, compat_file);
874            if out_format.is_structured() {
875                let v = search::search_json_memstr(&hits, width8);
876                print_hit_records(&v, search::MEMSTR_COLUMNS, out_format, out);
877            } else {
878                search::print_memstr_hits(&hits, width8, out);
879            }
880        }
881        return Ok(0);
882    }
883
884    let do_scan = |view: &RegionView, opts: &ScanOptions| -> Result<Vec<Gadget>, i32> {
885        match run_scan_engine(view, opts) {
886            Ok(g) => Ok(g),
887            Err(e) => {
888                // Scan-time Unsupported errors (e.g. capstone mode) and
889                // exhausted --max-gadgets/--max-memory budgets are
890                // binary-level failures, like ROPgadget's loader errors.
891                eprintln!("[Error] {e}");
892                Err(2)
893            }
894        }
895    };
896    // Opened once, before the closure, so a cache that cannot be trusted
897    // reports itself exactly once per run.
898    let cache = if cli.cache {
899        let opened = open_cache();
900        if opened.is_none() && cache_dir().is_none() {
901            eprintln!("[Cache] no cache directory (set ROP_FINDER_CACHE_DIR); scanning");
902        }
903        opened
904    } else {
905        None
906    };
907    // Gadget acquisition, shared by the --mipsrop and normal paths.
908    let acquire = || -> Result<Vec<Gadget>, i32> {
909        let Some(cache) = &cache else {
910            return do_scan(&view, &opts);
911        };
912        let key = cache_key(&bytes, &opts, &CacheIdentity::of(&cli, base));
913        // `load` authenticates and validates; a tampered or corrupt entry
914        // is a warning plus a miss, never a served result (CLI-07, ROB-04).
915        if let Some(g) = cache
916            .load(&key)
917            .as_ref()
918            .and_then(rf_cache::CachedScan::to_scan_gadgets)
919        {
920            eprintln!(
921                "[Cache] hit {} ({} gadgets)",
922                rf_cache::key_prefix(&key),
923                g.len()
924            );
925            return Ok(g);
926        }
927        let g = do_scan(&view, &opts)?;
928        match cache.store(&key, &rf_cache::CachedScan::from_scan_gadgets(&g)) {
929            Ok(()) => eprintln!(
930                "[Cache] miss {} — stored {} gadgets",
931                rf_cache::key_prefix(&key),
932                g.len()
933            ),
934            Err(e) => eprintln!(
935                "[Cache] miss {} — store failed: {e}",
936                rf_cache::key_prefix(&key)
937            ),
938        }
939        Ok(g)
940    };
941
942    // --mipsrop (core.py:118-157): silent check first, then the mode
943    // check, then the header — all BEFORE the gadget scan.
944    if let Some(mode) = &cli.mipsrop {
945        if cli.silent {
946            return Ok(0);
947        }
948        let Some(regexes) = search::compile_mips_regexes(mode) else {
949            let _ = writeln!(out, "Unrecognized option {mode}");
950            let _ = writeln!(
951                out,
952                "Accepted options stackfinder|system|tails|lia0|registers"
953            );
954            return Ok(1); // analyze() -> False -> exit 1
955        };
956        let _ = writeln!(out, "MIPS ROP ({mode})");
957        let _ = writeln!(out, "{}", search::RULE60);
958        let mut gadgets = match acquire() {
959            Ok(g) => g,
960            Err(c) => return Ok(c),
961        };
962        apply_post_filters(
963            &mut gadgets,
964            &cli.re,
965            cli.call_preceded,
966            view.arch(),
967            out_format != format::OutFormat::Human,
968            out,
969        )?;
970        search::print_mips_gadgets(
971            &gadgets,
972            &regexes,
973            cli.dump,
974            search::search_width8(&target, view.arch()),
975            out,
976        );
977        return Ok(0);
978    }
979
980    // ECO-09: the streaming path. Chosen BEFORE `acquire()`, because the
981    // whole point is that no `Vec<Gadget>` is ever built.
982    if format::can_stream(out_format, cli.rank, cli.cache, false) && !cli.silent {
983        let re = cli
984            .re
985            .as_deref()
986            .map(search::ReFilter::compile)
987            .transpose()?;
988        // apply_post_filters() only applies --callPreceded on x86/x64 and
989        // prints "Unsupported architecture." otherwise; the same rule here.
990        let cp_supported = matches!(view.arch(), Arch::X86 | Arch::X64);
991        let classifier =
992            (cli.classify || !q.is_empty()).then(|| rf_classify::Classifier::new(view.arch()));
993        let mut sink = format::JsonlSink::new(
994            out,
995            &opts,
996            view.addr_size(),
997            format::RecordCtx {
998                addr_size: view.addr_size(),
999                offset: opts.offset,
1000                universal_arch,
1001                selected_sections: prepared.selected_sections.as_deref(),
1002                classify: cli.classify,
1003            },
1004            format::GadgetFilters {
1005                re: re.as_ref(),
1006                call_preceded: cli.call_preceded && cp_supported,
1007                query: &q,
1008                classify: classifier.as_ref(),
1009            },
1010        );
1011        if let Err(e) = rf_scan::scan_binary_into(&view, &opts, &mut sink) {
1012            // Records already written cannot be unwritten, so a budget hit
1013            // leaves a partial stream on stdout plus this line on stderr and
1014            // exit 2 - the same exit code the buffered path uses, which is
1015            // what a script actually checks.
1016            eprintln!("[Error] {}", scan_error_message(e));
1017            return Ok(2);
1018        }
1019        // The oracle prints this line before the listing; a streamed
1020        // listing has no "before", and it is a count over the whole run.
1021        // It goes to stderr so the JSONL stream stays parseable, which is
1022        // where the --json path already sent it.
1023        if cli.call_preceded {
1024            if cp_supported {
1025                eprintln!(
1026                    "Options().removeNonCallPreceded(): Filtered out {} gadgets.",
1027                    sink.call_preceded_dropped()
1028                );
1029            } else {
1030                eprintln!("Options().removeNonCallPreceded(): Unsupported architecture.");
1031            }
1032        }
1033        return Ok(0);
1034    }
1035
1036    let mut gadgets = match acquire() {
1037        Ok(g) => g,
1038        Err(c) => return Ok(c),
1039    };
1040    // options.py:22-33 — --re then --callPreceded, after the scan.
1041    apply_post_filters(
1042        &mut gadgets,
1043        &cli.re,
1044        cli.call_preceded,
1045        view.arch(),
1046        out_format != format::OutFormat::Human,
1047        out,
1048    )?;
1049    let mut classes: Option<Vec<rf_classify::Classification>> = None;
1050    // CLS-08 + ECO-01/ECO-12: the classification is computed for every
1051    // gadget and was only ever *printed* before v0.3. The `--class` /
1052    // `--label` / `--writes-reg` filters made it queryable; the v0.4
1053    // constraint flags ask the question a practitioner actually has. Same
1054    // predicate, same names, as the MCP `find_gadgets_by_effect` tool.
1055    if cli.classify || cli.rank || !q.is_empty() {
1056        let (g, c) = classify_gadgets(gadgets, view.arch(), cli.rank);
1057        gadgets = g;
1058        classes = Some(c);
1059    }
1060    if let Some(cs) = classes.as_mut() {
1061        if !q.is_empty() {
1062            let keep: Vec<bool> = gadgets
1063                .iter()
1064                .zip(cs.iter())
1065                .map(|(g, c)| {
1066                    let text = g.text();
1067                    q.matches(c, &text.split(" ; ").collect::<Vec<_>>())
1068                })
1069                .collect();
1070            let mut it = keep.iter();
1071            gadgets.retain(|_| *it.next().unwrap_or(&true));
1072            let mut it = keep.iter();
1073            cs.retain(|_| *it.next().unwrap_or(&true));
1074        }
1075    }
1076    let result = ScanResult {
1077        gadgets,
1078        addr_size: view.addr_size(),
1079        universal_arch,
1080        selected_sections: prepared.selected_sections,
1081    };
1082
1083    // core.py:103-104 — --silent suppresses all gadget output (the
1084    // callPreceded filter line above still printed, as in the oracle).
1085    if cli.silent {
1086        return Ok(0);
1087    }
1088    // --rank alone reorders but does not add classification fields.
1089    let classes = classes.as_deref().filter(|_| cli.classify);
1090    print_result(&result, opts.offset, classes, out_format, &cli, out);
1091    Ok(0)
1092}
1093
1094/// ECO-09: resolve `--format` / `--chain-format`, reconciling them with the
1095/// older `--json` boolean.
1096///
1097/// `--json` predates both and cannot be removed — it is in the manual, in
1098/// the MCP allowlist and in every existing script — so it stays as the
1099/// spelling of `--format json` (and, under `--ropchain`, of
1100/// `--chain-format json`). Asking for two different things at once is a
1101/// usage error rather than a silent precedence rule, because a script that
1102/// says `--json --format csv` has a bug either way and a quiet winner would
1103/// hide it.
1104fn resolve_formats(cli: &Cli) -> Result<(format::OutFormat, format::ChainFormat), String> {
1105    let out = match cli.format.as_deref() {
1106        Some(f) => {
1107            let f = format::OutFormat::parse(f).ok_or_else(|| {
1108                format!(
1109                    "invalid --format {f:?}; valid values are {}",
1110                    format::OutFormat::ALL.join(", ")
1111                )
1112            })?;
1113            if cli.json && f != format::OutFormat::Json {
1114                return Err(format!(
1115                    "--json and --format {} conflict; --json means --format json",
1116                    f.name()
1117                ));
1118            }
1119            f
1120        }
1121        None if cli.json => format::OutFormat::Json,
1122        None => format::OutFormat::Human,
1123    };
1124    let chain = match cli.chain_format.as_deref() {
1125        Some(f) => {
1126            let f = format::ChainFormat::parse(f).ok_or_else(|| {
1127                format!(
1128                    "invalid --chain-format {f:?}; valid values are {}",
1129                    format::ChainFormat::ALL.join(", ")
1130                )
1131            })?;
1132            if cli.json && f != format::ChainFormat::Json {
1133                return Err(
1134                    "--json and --chain-format conflict; --json means --chain-format json"
1135                        .to_string(),
1136                );
1137            }
1138            f
1139        }
1140        None if cli.json => format::ChainFormat::Json,
1141        None => format::ChainFormat::Python,
1142    };
1143    Ok((out, chain))
1144}
1145
1146/// Render a search-mode hit list (`--string` / `--opcode` / `--memstr`) in
1147/// one of the structured formats. `cols` fixes the CSV column order.
1148fn print_hit_records(
1149    hits: &serde_json::Value,
1150    cols: &[&str],
1151    fmt: format::OutFormat,
1152    out: &mut dyn std::io::Write,
1153) {
1154    let empty = Vec::new();
1155    let rows = hits.as_array().unwrap_or(&empty);
1156    match fmt {
1157        format::OutFormat::Jsonl => {
1158            for r in rows {
1159                let _ = writeln!(out, "{r}");
1160            }
1161        }
1162        format::OutFormat::Csv => {
1163            let _ = writeln!(out, "{}", cols.join(","));
1164            for r in rows {
1165                let cells: Vec<String> = cols
1166                    .iter()
1167                    .map(|c| match &r[*c] {
1168                        serde_json::Value::Null => String::new(),
1169                        serde_json::Value::String(s) => s.clone(),
1170                        v => v.to_string(),
1171                    })
1172                    .collect();
1173                let _ = writeln!(out, "{}", format::csv_join(&cells));
1174            }
1175        }
1176        // Serialization of this simple structure cannot fail.
1177        _ => {
1178            let _ = writeln!(out, "{}", serde_json::to_string_pretty(hits).unwrap());
1179        }
1180    }
1181}
1182
1183/// The buffered gadget listing, in whichever `--format` was asked for.
1184fn print_result(
1185    res: &ScanResult,
1186    offset: u64,
1187    classes: Option<&[rf_classify::Classification]>,
1188    fmt: format::OutFormat,
1189    cli: &Cli,
1190    out: &mut dyn std::io::Write,
1191) {
1192    let ctx = format::RecordCtx {
1193        addr_size: res.addr_size,
1194        offset,
1195        universal_arch: res.universal_arch,
1196        selected_sections: res.selected_sections.as_deref(),
1197        classify: cli.classify,
1198    };
1199    let rec = |i: usize| format::record(&res.gadgets[i], classes.map(|cs| &cs[i]), &ctx);
1200    match fmt {
1201        format::OutFormat::Human => print_human(res, cli.noinstr, cli.dump, out),
1202        format::OutFormat::Json => {
1203            let all: Vec<_> = (0..res.gadgets.len()).map(rec).collect();
1204            let _ = writeln!(out, "{}", serde_json::to_string_pretty(&all).unwrap());
1205        }
1206        // The same records the streaming path emits; reached only when
1207        // `--rank`/`--cache` forced the buffered path.
1208        format::OutFormat::Jsonl => {
1209            for i in 0..res.gadgets.len() {
1210                if let Ok(line) = serde_json::to_string(&rec(i)) {
1211                    let _ = writeln!(out, "{line}");
1212                }
1213            }
1214        }
1215        format::OutFormat::Csv => {
1216            let _ = writeln!(out, "{}", format::CSV_HEADER);
1217            for i in 0..res.gadgets.len() {
1218                let _ = writeln!(out, "{}", format::csv_row(&rec(i)));
1219            }
1220        }
1221        format::OutFormat::Raw => {
1222            for g in &res.gadgets {
1223                let _ = writeln!(
1224                    out,
1225                    "{}",
1226                    format::raw_line(g, res.addr_size, cli.noinstr, cli.dump)
1227                );
1228            }
1229        }
1230    }
1231}
1232
1233/// Phase 5: classify every gadget and, when `rank` is set, sort by
1234/// quality descending with vaddr-ascending tie-break (TAXONOMY.md R12).
1235fn classify_gadgets(
1236    gadgets: Vec<Gadget>,
1237    arch: Arch,
1238    rank: bool,
1239) -> (Vec<Gadget>, Vec<rf_classify::Classification>) {
1240    let mut pairs: Vec<(Gadget, rf_classify::Classification)> = gadgets
1241        .into_iter()
1242        .map(|g| {
1243            let c = rf_classify::classify(&g, arch);
1244            (g, c)
1245        })
1246        .collect();
1247    if rank {
1248        pairs.sort_by(|(ga, ca), (gb, cb)| {
1249            cb.quality.cmp(&ca.quality).then(ga.vaddr.cmp(&gb.vaddr))
1250        });
1251    }
1252    pairs.into_iter().unzip()
1253}
1254
1255/// core.py:99-116 `__lookingForGadgets`. With --noinstr the gadget dicts
1256/// carry no text, so the line is the bare address (core.py:110-111);
1257/// --dump appends " // hexbytes" (core.py:112).
1258///
1259/// CLI-11: `noinstr` used to be ignored here on the theory that a
1260/// --noinstr scan produced gadgets with empty `insns`. It does not — the
1261/// v0.2.0 engine keeps the disassembly and lets --noinstr mean only "skip
1262/// dedup and skip the alphabetical sort" (`core.py:87,94`), because
1263/// `--filter`/`--badbytes` still have to look at the instructions. The
1264/// oracle drops the text at PRINT time (`gadgets.py:117` never stores
1265/// `g["gadget"]`, and `core.py:110-111` then formats an empty `insts`), so
1266/// the suppression belongs here. Without this, every --noinstr line
1267/// carried a ` : <text>` the oracle does not print: 68,386 of 68,390 lines
1268/// differed on elf-Linux-x86.
1269fn print_human(res: &ScanResult, noinstr: bool, dump: bool, out: &mut dyn std::io::Write) {
1270    let _ = writeln!(out, "Gadgets information");
1271    let _ = writeln!(out, "{}", search::RULE60);
1272    for g in &res.gadgets {
1273        let text = if noinstr { String::new() } else { g.text() };
1274        let insts = if text.is_empty() {
1275            String::new()
1276        } else {
1277            format!(" : {text}")
1278        };
1279        let bytes_str = if dump {
1280            format!(" // {}", g.bytes_hex())
1281        } else {
1282            String::new()
1283        };
1284        let _ = writeln!(
1285            out,
1286            "{}{}{}",
1287            fmt_addr(g.vaddr, res.addr_size),
1288            insts,
1289            bytes_str
1290        );
1291    }
1292    let _ = writeln!(out, "\nUnique gadgets found: {}", res.gadgets.len());
1293}
1294
1295/// The `--format json` record list. Kept as a named function because the
1296/// crate's tests assert on the *typed* record rather than on parsed JSON.
1297#[cfg(test)]
1298fn to_json(res: &ScanResult, offset: u64) -> Vec<format::GadgetRecord<'_>> {
1299    to_json_classified(res, offset, None)
1300}
1301
1302#[cfg(test)]
1303fn to_json_classified<'a>(
1304    res: &'a ScanResult,
1305    offset: u64,
1306    classes: Option<&'a [rf_classify::Classification]>,
1307) -> Vec<format::GadgetRecord<'a>> {
1308    let ctx = format::RecordCtx {
1309        addr_size: res.addr_size,
1310        offset,
1311        universal_arch: res.universal_arch,
1312        selected_sections: res.selected_sections.as_deref(),
1313        classify: classes.is_some(),
1314    };
1315    (0..res.gadgets.len())
1316        .map(|i| format::record(&res.gadgets[i], classes.map(|cs| &cs[i]), &ctx))
1317        .collect()
1318}
1319
1320// ---------------------------------------------------------------------------
1321// Scan cache (--cache, --cache-purge).
1322//
1323// The cache itself — the key schema, the HMAC that authenticates an entry,
1324// the permissions, the atomic write and the LRU — lives in `rf_cache` and
1325// is shared byte for byte with the MCP server. That sharing IS the fix:
1326// the ROB-04 char-boundary panic and the ANCH-02 align post-filter each
1327// existed twice because there were two copies of this code. What stays
1328// here is only what the CLI knows and the library cannot: where the cache
1329// directory is, and which flags of *this* front end change the output.
1330// ---------------------------------------------------------------------------
1331
1332/// Cache directory: ROP_FINDER_CACHE_DIR wins, else the platform default
1333/// (%LOCALAPPDATA%/rop-finder/cache on Windows, ~/.cache/rop-finder
1334/// elsewhere). None when no base directory can be determined.
1335fn cache_dir() -> Option<std::path::PathBuf> {
1336    if let Ok(d) = std::env::var("ROP_FINDER_CACHE_DIR") {
1337        if !d.is_empty() {
1338            return Some(std::path::PathBuf::from(d));
1339        }
1340    }
1341    #[cfg(windows)]
1342    {
1343        std::env::var_os("LOCALAPPDATA")
1344            .map(|p| std::path::PathBuf::from(p).join("rop-finder").join("cache"))
1345    }
1346    #[cfg(not(windows))]
1347    {
1348        std::env::var_os("HOME").map(|p| {
1349            std::path::PathBuf::from(p)
1350                .join(".cache")
1351                .join("rop-finder")
1352        })
1353    }
1354}
1355
1356/// Everything that changes what a scan produces and is *not* already in
1357/// [`ScanOptions`].
1358///
1359/// CLI-01/ENG-05 was exactly a missing member of this list: the key
1360/// omitted `--rawArch`/`--rawMode`/`--rawEndian`, so a cached scan was
1361/// served for the wrong architecture. Reproduced on
1362/// `tests/fixtures/raw-x86.raw`: `--rawArch x86 --rawMode 32 --cache`
1363/// stored 2 gadgets, and `--rawArch arm --rawMode arm --rawEndian little
1364/// --cache` was then served those same 2 x86 gadgets, when the true
1365/// answer for the ARM query is 0.
1366struct CacheIdentity<'a> {
1367    /// `--section` globs, as written.
1368    sections: &'a [String],
1369    /// `--base`, already parsed.
1370    base: Option<u64>,
1371    /// `--rawArch`/`--rawMode`/`--rawEndian`: which loader runs, and how
1372    /// the bytes are decoded. The CLI-01/ENG-05 omission.
1373    raw_arch: Option<&'a str>,
1374    raw_mode: Option<&'a str>,
1375    raw_endian: Option<&'a str>,
1376    /// `--arch`: which slice of a fat Mach-O is scanned (CORE-03).
1377    arch: Option<&'a str>,
1378    /// `--compat`: decides whether a multi-slice container is scanned as a
1379    /// concatenation or refused.
1380    compat: bool,
1381}
1382
1383impl<'a> CacheIdentity<'a> {
1384    fn of(cli: &'a Cli, base: Option<u64>) -> Self {
1385        CacheIdentity {
1386            sections: &cli.section,
1387            base,
1388            raw_arch: cli.raw_arch.as_deref(),
1389            raw_mode: cli.raw_mode.as_deref(),
1390            raw_endian: cli.raw_endian.as_deref(),
1391            arch: cli.arch.as_deref(),
1392            compat: cli.compat,
1393        }
1394    }
1395}
1396
1397/// Cache key: the binary's content hash plus **every** parameter that can
1398/// change the output.
1399///
1400/// `parallel` is the one deliberate omission — rayon scheduling cannot
1401/// change the result — and `cancel` is not a parameter. Everything else
1402/// goes in: the engine options wave 2A added (`align`, `all`, `noinstr`,
1403/// `call_preceded`, `filter_re`), the loader identity above, and the
1404/// `--max-gadgets`/`--max-memory` budgets, which *truncate* a result and
1405/// so must never let a bounded scan be served for an unbounded query.
1406/// [`rf_cache::make_key`] folds in the key-schema version, so the next
1407/// time this list grows the old entries miss instead of mismatching.
1408fn cache_key(bytes: &[u8], opts: &ScanOptions, id: &CacheIdentity<'_>) -> String {
1409    let params = format!(
1410        "depth={}|rop={}|jop={}|sys={}|multibr={}|only={:?}|filter={:?}|\
1411         filter_re={:?}|range={:?}|badbytes={:?}|offset={}|thumb={}|cfg_aware={}|\
1412         align={:?}|call_preceded={}|all={}|noinstr={}|max_gadgets={:?}|\
1413         max_memory={:?}|sections={:?}|base={:?}|raw_arch={:?}|raw_mode={:?}|\
1414         raw_endian={:?}|arch={:?}|compat={}",
1415        opts.depth,
1416        opts.rop,
1417        opts.jop,
1418        opts.sys,
1419        opts.multibr,
1420        opts.only,
1421        opts.filter,
1422        opts.filter_re.as_ref().map(regex::Regex::as_str),
1423        opts.range,
1424        opts.badbytes,
1425        opts.offset,
1426        opts.thumb,
1427        opts.cfg_aware,
1428        opts.align,
1429        opts.call_preceded,
1430        opts.all,
1431        opts.noinstr,
1432        opts.max_gadgets,
1433        opts.max_memory,
1434        id.sections,
1435        id.base,
1436        id.raw_arch,
1437        id.raw_mode,
1438        id.raw_endian,
1439        id.arch,
1440        id.compat,
1441    );
1442    rf_cache::make_key(&rf_cache::sha256_hex(bytes), &params)
1443}
1444
1445/// ROB-04. This was `&s[i..i + 2]` — a byte-range slice of a `&str` —
1446/// and it is reachable from `--opcode`, not only from the cache:
1447/// `rop-finder --binary <elf> --opcode "€€"` aborted the process with
1448/// `byte index 2 is not a char boundary; it is inside '€'`. The shared
1449/// decoder works over `as_bytes()` and checks the alphabet itself.
1450///
1451/// `usize::MAX` because `--opcode` has never had a length limit and this
1452/// change is about the panic, not about adding one; the *record* fields
1453/// that an attacker controls are capped in `rf_cache` instead.
1454fn hex_decode(s: &str) -> Option<Vec<u8>> {
1455    rf_cache::decode_hex(s, usize::MAX)
1456}
1457
1458/// Open the on-disk cache, or say on stderr why there is none.
1459///
1460/// CLI-07/MCP-04: when the directory or its key file cannot be trusted,
1461/// the cache is *disabled*. It never degrades to unauthenticated reads —
1462/// that fallback is the finding.
1463fn open_cache() -> Option<rf_cache::DiskCache> {
1464    let dir = cache_dir()?;
1465    match rf_cache::DiskCache::open(&dir, rf_cache::CacheLimits::from_env()) {
1466        Ok(c) => Some(c),
1467        Err(e) => {
1468            eprintln!("[Cache] disabled: {e}");
1469            None
1470        }
1471    }
1472}
1473
1474/// `--cache-purge` (CLI-08/PERF-12): empty the cache directory and exit.
1475/// Before this the only way to reclaim the 5.3 MB per scan configuration
1476/// the cache accumulated in `~/.cache/rop-finder` was `rm -rf`, and the
1477/// user had to know the path.
1478fn run_cache_purge(out: &mut dyn std::io::Write) -> i32 {
1479    let Some(dir) = cache_dir() else {
1480        eprintln!("[Cache] no cache directory (set ROP_FINDER_CACHE_DIR); nothing to purge");
1481        return 0;
1482    };
1483    let cache = match rf_cache::DiskCache::open(&dir, rf_cache::CacheLimits::from_env()) {
1484        Ok(c) => c,
1485        Err(e) => {
1486            eprintln!(
1487                "[Error] cannot open the cache directory {}: {e}",
1488                dir.display()
1489            );
1490            return 2;
1491        }
1492    };
1493    match cache.purge() {
1494        Ok((files, bytes)) => {
1495            let _ = writeln!(
1496                out,
1497                "Purged {files} cache {} ({bytes} bytes) from {}",
1498                if files == 1 { "entry" } else { "entries" },
1499                dir.display()
1500            );
1501            0
1502        }
1503        Err(e) => {
1504            eprintln!("[Error] cache purge failed: {e}");
1505            2
1506        }
1507    }
1508}
1509
1510/// CHWIN-09. The Windows VirtualProtect builder emits a chain that does
1511/// not execute (CHWIN-01/02/03); until v0.5 fixes it, saying so out loud —
1512/// on stderr, so a piped `--ropchain > exploit.py` still gets a clean
1513/// script and the human still gets the warning — is the honest gate.
1514/// Returns the warning for a target that has one, `None` otherwise.
1515fn chain_experimental_warning(target: &str) -> Option<&'static str> {
1516    (target == "windows-virtualprotect").then_some(
1517        "[Warning] --chain windows-virtualprotect is EXPERIMENTAL: the chain it emits \
1518         executes under this project's emulator (tests/emulate.py), not on Windows.\n\
1519         [Warning] The four layout defects this warning used to name — CHWIN-01, \
1520         CHWIN-02, CHWIN-03, CHWIN-07 — are fixed in v0.5, each with a failing-before \
1521         and a passing-after run recorded in docs/chain-regressions.md.\n\
1522         [Warning] What the emulator cannot check is still yours: that --api-addr is \
1523         the runtime address, that rsp really is --chain-base mod 16 at entry, and that \
1524         CFG/CET is not enforced on the target.\n",
1525    )
1526}
1527
1528/// clap signals `--help` and `--version` as an `Err` whose `exit_code()`
1529/// is 0: they are successful terminations, not usage errors. CLI-06 /
1530/// ENG-06 — the old blanket `ExitCode::from(1)` broke the project's own
1531/// build script (`set -e` + a final `rop-finder --version`), Homebrew and
1532/// dpkg post-install smoke tests, and every CI step that checks a tool is
1533/// runnable. ROPgadget exits 0 for both.
1534fn clap_exit_code(kind: clap::error::ErrorKind) -> u8 {
1535    use clap::error::ErrorKind as K;
1536    match kind {
1537        K::DisplayHelp | K::DisplayVersion | K::DisplayHelpOnMissingArgumentOrSubcommand => 0,
1538        // MANUAL's documented contract: 1 is the usage error (clap's own 2
1539        // is deliberately not adopted).
1540        _ => 1,
1541    }
1542}
1543
1544pub fn main_entry() -> ExitCode {
1545    let cli = match Cli::try_parse() {
1546        Ok(c) => c,
1547        Err(e) => {
1548            let code = clap_exit_code(e.kind());
1549            // clap writes help/version to stdout and errors to stderr.
1550            let _ = e.print();
1551            return ExitCode::from(code);
1552        }
1553    };
1554    // One buffered, locked stdout for the whole run (PERF-07), whose first
1555    // I/O error decides the exit code instead of panicking (ROB-03).
1556    let mut out = out::StdOut::stdout();
1557    let code = match run(cli, &mut out) {
1558        Ok(code) => code,
1559        Err(msg) => {
1560            eprintln!("[Error] {msg}");
1561            1
1562        }
1563    };
1564    match out.finish() {
1565        Ok(()) => ExitCode::from(code as u8),
1566        // A run that already failed keeps its own exit code; a run that
1567        // succeeded into a closed pipe ends at 0, like every other text
1568        // tool, rather than at 101 with a panic message.
1569        Err(e) => match out::exit_code_for(&e) {
1570            Ok(pipe_code) => ExitCode::from(if code == 0 { pipe_code } else { code } as u8),
1571            Err(msg) => {
1572                eprintln!("[Error] {msg}");
1573                ExitCode::from(1)
1574            }
1575        },
1576    }
1577}
1578
1579#[cfg(test)]
1580mod tests {
1581    use super::*;
1582    // Loader types the moved-out library layer no longer needs at the crate
1583    // root, but the CLI's own tests still construct directly.
1584    use rf_core::{Binary, LoadedBinary, RawBinary, Section};
1585
1586    fn cli_with(
1587        thumb: bool,
1588        raw_arch: Option<&str>,
1589        raw_mode: Option<&str>,
1590        raw_endian: Option<&str>,
1591    ) -> Cli {
1592        Cli {
1593            binary: Some("x".into()),
1594            depth: 10,
1595            norop: false,
1596            nojop: false,
1597            nosys: false,
1598            multibr: false,
1599            // v0.4 (ECO-01/ECO-09): the constraint query and output
1600            // formats. All absent = the v0.3 behaviour, unchanged.
1601            version: None,
1602            set_reg: None,
1603            from_stack: false,
1604            no_clobber: None,
1605            reads_reg: None,
1606            max_stack_delta: None,
1607            max_side_effects: None,
1608            max_insns: None,
1609            terminator: None,
1610            search: None,
1611            pivot: false,
1612            format: None,
1613            chain_format: None,
1614            // CLS-08's three semantic filters; None = unfiltered.
1615            class: None,
1616            label: None,
1617            writes_reg: None,
1618            only: None,
1619            filter: None,
1620            range: None,
1621            badbytes: None,
1622            offset: None,
1623            base: None,
1624            info: false,
1625            ropchain: false,
1626            plan_chain: false,
1627            syscall: None,
1628            syscall_args: None,
1629            chain_pivot: None,
1630            stage: None,
1631            chain: "linux-execve".into(),
1632            api_addr: None,
1633            api_name: None,
1634            shellcode_addr: None,
1635            shellcode_size: None,
1636            chain_base: None,
1637            prot: None,
1638            cfg_aware: false,
1639            section: Vec::new(),
1640            thumb,
1641            raw_arch: raw_arch.map(Into::into),
1642            raw_mode: raw_mode.map(Into::into),
1643            raw_endian: raw_endian.map(Into::into),
1644            json: false,
1645            classify: false,
1646            rank: false,
1647            cache: false,
1648            cache_purge: false,
1649            string: None,
1650            opcode: None,
1651            memstr: None,
1652            re: None,
1653            call_preceded: false,
1654            noinstr: false,
1655            dump: false,
1656            silent: false,
1657            align: None,
1658            mipsrop: None,
1659            all: false,
1660            console: false,
1661            arch: None,
1662            max_file_size: "512M".to_string(),
1663            max_gadgets: None,
1664            max_memory: None,
1665            compat: false,
1666        }
1667    }
1668
1669    fn fixture_bytes(name: &str) -> Vec<u8> {
1670        std::fs::read(format!(
1671            "{}/../../tests/fixtures/{name}",
1672            env!("CARGO_MANIFEST_DIR")
1673        ))
1674        .unwrap()
1675    }
1676
1677    fn load_target(bytes: &[u8]) -> Target {
1678        match Binary::load(bytes).unwrap() {
1679            LoadedBinary::Elf(b) => Target::Elf(b),
1680            LoadedBinary::Pe(b) => Target::Pe(b),
1681            LoadedBinary::MachO(b) => Target::MachO(b),
1682            LoadedBinary::Raw(b) => Target::Raw(b),
1683            LoadedBinary::Universal(u) => Target::Universal(u),
1684        }
1685    }
1686
1687    fn default_opts() -> ScanOptions {
1688        ScanOptions {
1689            depth: 10,
1690            rop: true,
1691            jop: true,
1692            sys: true,
1693            multibr: false,
1694            only: None,
1695            range: None,
1696            badbytes: Vec::new(),
1697            filter: Vec::new(),
1698            offset: 0,
1699            thumb: false,
1700            cfg_aware: false,
1701            align: None,
1702            call_preceded: false,
1703            all: false,
1704            noinstr: false,
1705            parallel: true,
1706            ..ScanOptions::default()
1707        }
1708    }
1709
1710    /// Scan `fixture` with the given view mutations; returns (view, gadgets).
1711    fn scan_fixture(
1712        fixture: &str,
1713        base: Option<u64>,
1714        sections: &[&str],
1715        configure: impl Fn(&mut ScanOptions),
1716    ) -> (RegionView, Vec<Gadget>) {
1717        let bytes = fixture_bytes(fixture);
1718        let target = load_target(&bytes);
1719        let mut view = build_view(&target);
1720        if let Some(b) = base {
1721            view.rebase(b);
1722        }
1723        if !sections.is_empty() {
1724            let pats: Vec<String> = sections.iter().map(|s| s.to_string()).collect();
1725            let (secs, _) = select_sections(&view.named_exec, &pats).unwrap();
1726            view.regions = secs;
1727        }
1728        let mut opts = default_opts();
1729        configure(&mut opts);
1730        let gadgets = rf_scan::scan_binary(&view, &opts).unwrap();
1731        (view, gadgets)
1732    }
1733
1734    fn make_section(name: &str, vaddr: u64, size: u64) -> Section {
1735        Section {
1736            name: name.to_string(),
1737            vaddr,
1738            offset: 0,
1739            size,
1740            bytes: vec![0u8; size as usize],
1741            executable: true,
1742            writable: false,
1743            allocated: true,
1744        }
1745    }
1746
1747    /// vaddr of the dedup-stable bare "ret" gadget (traversal order is
1748    /// base-invariant, so the survivor is the same gadget across rebases).
1749    fn bare_ret_vaddr(gadgets: &[Gadget]) -> Option<u64> {
1750        gadgets.iter().find(|g| g.text() == "ret").map(|g| g.vaddr)
1751    }
1752
1753    fn scan_result_for(fixture: &str, depth: usize) -> (RegionView, ScanResult) {
1754        let (view, gadgets) = scan_fixture(fixture, None, &[], |o| o.depth = depth);
1755        let res = ScanResult {
1756            gadgets,
1757            addr_size: view.addr_size(),
1758            universal_arch: None,
1759            selected_sections: None,
1760        };
1761        (view, res)
1762    }
1763
1764    /// Unique temp directory per test (parallel cargo test safe); removed
1765    /// on drop.
1766    struct TempDir(std::path::PathBuf);
1767    impl TempDir {
1768        fn new(tag: &str) -> Self {
1769            let p = std::env::temp_dir().join(format!(
1770                "rf-cli-{tag}-{}-{}",
1771                std::process::id(),
1772                std::time::SystemTime::now()
1773                    .duration_since(std::time::UNIX_EPOCH)
1774                    .unwrap()
1775                    .as_nanos()
1776            ));
1777            std::fs::create_dir_all(&p).unwrap();
1778            TempDir(p)
1779        }
1780    }
1781    impl Drop for TempDir {
1782        fn drop(&mut self) {
1783            let _ = std::fs::remove_dir_all(&self.0);
1784        }
1785    }
1786
1787    #[test]
1788    fn cache_roundtrip_and_key_sensitivity() {
1789        let (view, res) = scan_result_for("elf-Linux-x64", 4);
1790        let bytes = fixture_bytes("elf-Linux-x64");
1791        let mut opts = default_opts();
1792        opts.depth = 4;
1793        let dir = TempDir::new("cache");
1794        let cache = rf_cache::DiskCache::open(&dir.0, rf_cache::CacheLimits::default()).unwrap();
1795
1796        let plain_cli = cli_with(false, None, None, None);
1797        let id = CacheIdentity::of(&plain_cli, None);
1798        let key = cache_key(&bytes, &opts, &id);
1799        assert!(cache.load(&key).is_none(), "cold cache misses");
1800        cache
1801            .store(&key, &rf_cache::CachedScan::from_scan_gadgets(&res.gadgets))
1802            .unwrap();
1803        let loaded = cache
1804            .load(&key)
1805            .and_then(|s| s.to_scan_gadgets())
1806            .expect("warm cache hits");
1807        assert_eq!(loaded.len(), res.gadgets.len());
1808        for (a, b) in loaded.iter().zip(res.gadgets.iter()) {
1809            assert_eq!(a.vaddr, b.vaddr);
1810            assert_eq!(a.bytes, b.bytes);
1811            assert_eq!(a.insns, b.insns);
1812            assert_eq!(a.delay_slot, b.delay_slot);
1813            assert_eq!(a.prev, b.prev);
1814        }
1815
1816        // Same inputs → same key (determinism).
1817        assert_eq!(key, cache_key(&bytes, &opts, &id));
1818        // ':' would be an invalid Windows file name; keys must avoid it.
1819        assert!(!key.contains(':'));
1820        drop(view);
1821    }
1822
1823    /// CLI-01/ENG-05 and the wave-2A engine options: every parameter that
1824    /// can change the output has to move the key. Each `assert_ne!` below
1825    /// that names a raw-loader flag, an align/all/noinstr/callPreceded
1826    /// flag or a budget fails against the pre-v0.2 key, which hashed
1827    /// eighteen fields and none of these.
1828    #[test]
1829    fn cache_key_covers_every_output_affecting_parameter() {
1830        let bytes = fixture_bytes("elf-Linux-x64");
1831        let base_cli = cli_with(false, None, None, None);
1832        let opts = default_opts();
1833        let key = cache_key(&bytes, &opts, &CacheIdentity::of(&base_cli, None));
1834
1835        // ScanOptions half.
1836        let with = |mutate: &dyn Fn(&mut ScanOptions), what: &str| {
1837            let mut o = default_opts();
1838            mutate(&mut o);
1839            assert_ne!(
1840                key,
1841                cache_key(&bytes, &o, &CacheIdentity::of(&base_cli, None)),
1842                "{what} must be part of the cache key"
1843            );
1844        };
1845        with(&|o| o.depth = 11, "--depth");
1846        with(&|o| o.rop = !o.rop, "--norop");
1847        with(&|o| o.jop = !o.jop, "--nojop");
1848        with(&|o| o.sys = !o.sys, "--nosys");
1849        with(&|o| o.multibr = true, "--multibr");
1850        with(&|o| o.only = Some(vec!["pop".into()]), "--only");
1851        with(&|o| o.filter = vec!["pop".into()], "--filter");
1852        with(&|o| o.range = Some((0x1000, 0x2000)), "--range");
1853        with(&|o| o.badbytes = vec![0x0a], "--badbytes");
1854        with(&|o| o.offset = 0x10, "--offset");
1855        with(&|o| o.thumb = true, "--thumb");
1856        with(&|o| o.cfg_aware = true, "--cfg-aware");
1857        with(&|o| o.align = Some(4), "--align");
1858        with(&|o| o.call_preceded = true, "--callPreceded");
1859        with(&|o| o.all = true, "--all");
1860        with(&|o| o.noinstr = true, "--noinstr");
1861        with(&|o| o.max_gadgets = Some(10), "--max-gadgets");
1862        with(&|o| o.max_memory = Some(1 << 20), "--max-memory");
1863        with(
1864            &|o| o.filter_re = Some(regex::Regex::new("pop").unwrap()),
1865            "a compiled --filter regex",
1866        );
1867        // `parallel` is the deliberate exception: it cannot change output.
1868        let mut par = default_opts();
1869        par.parallel = !par.parallel;
1870        assert_eq!(
1871            key,
1872            cache_key(&bytes, &par, &CacheIdentity::of(&base_cli, None)),
1873            "--parallel is output-identical and must NOT split the cache"
1874        );
1875
1876        // CacheIdentity half.
1877        let sections = vec![".text".to_string()];
1878        let raw_x86 = cli_with(false, Some("x86"), Some("32"), None);
1879        let raw_arm = cli_with(false, Some("arm"), Some("arm"), Some("little"));
1880        let ids: Vec<(CacheIdentity<'_>, &str)> = vec![
1881            (
1882                CacheIdentity {
1883                    sections: &sections,
1884                    ..CacheIdentity::of(&base_cli, None)
1885                },
1886                "--section",
1887            ),
1888            (CacheIdentity::of(&base_cli, Some(0x40_0000)), "--base"),
1889            (CacheIdentity::of(&raw_x86, None), "--rawArch/--rawMode"),
1890            (CacheIdentity::of(&raw_arm, None), "--rawEndian"),
1891            (
1892                CacheIdentity {
1893                    arch: Some("arm64"),
1894                    ..CacheIdentity::of(&base_cli, None)
1895                },
1896                "--arch",
1897            ),
1898            (
1899                CacheIdentity {
1900                    compat: true,
1901                    ..CacheIdentity::of(&base_cli, None)
1902                },
1903                "--compat",
1904            ),
1905        ];
1906        for (id, what) in &ids {
1907            assert_ne!(
1908                key,
1909                cache_key(&bytes, &opts, id),
1910                "{what} must be part of the cache key"
1911            );
1912        }
1913        // ...and the raw specs differ from EACH OTHER, not just from "none".
1914        let x86 = cache_key(&bytes, &opts, &CacheIdentity::of(&raw_x86, None));
1915        let arm = cache_key(&bytes, &opts, &CacheIdentity::of(&raw_arm, None));
1916        assert_ne!(x86, arm, "--rawArch x86 and arm are different scans");
1917
1918        // File content, obviously.
1919        assert_ne!(
1920            key,
1921            cache_key(
1922                b"not the same binary",
1923                &opts,
1924                &CacheIdentity::of(&base_cli, None)
1925            )
1926        );
1927    }
1928
1929    /// Serializes the tests that set `ROP_FINDER_CACHE_DIR`, which is
1930    /// process-global.
1931    static CACHE_ENV: std::sync::Mutex<()> = std::sync::Mutex::new(());
1932
1933    fn run_to_string(cli: Cli) -> String {
1934        let mut out: Vec<u8> = Vec::new();
1935        let code = run(cli, &mut out).expect("no usage error");
1936        assert_eq!(code, 0, "scan exited {code}");
1937        String::from_utf8(out).unwrap()
1938    }
1939
1940    /// CLI-01/ENG-05, end to end through `run`.
1941    ///
1942    /// Against the pre-v0.2 key this fails on the first assertion: the ARM
1943    /// query is served the x86 entry and prints
1944    /// `0x00000010 : xor eax, eax ; ret`, two gadgets, where the truth for
1945    /// ARM is zero.
1946    #[test]
1947    fn a_cached_scan_is_never_served_across_rawarch() {
1948        let _guard = CACHE_ENV
1949            .lock()
1950            .unwrap_or_else(std::sync::PoisonError::into_inner);
1951        let dir = TempDir::new("rawarch");
1952        std::env::set_var("ROP_FINDER_CACHE_DIR", &dir.0);
1953
1954        let raw = format!(
1955            "{}/../../tests/fixtures/raw-x86.raw",
1956            env!("CARGO_MANIFEST_DIR")
1957        );
1958        let mk = |arch: &str, mode: &str, endian: Option<&str>, cache: bool| Cli {
1959            binary: Some(raw.clone()),
1960            depth: 4,
1961            cache,
1962            ..cli_with(false, Some(arch), Some(mode), endian)
1963        };
1964
1965        let x86_first = run_to_string(mk("x86", "32", None, true));
1966        let arm_cached = run_to_string(mk("arm", "arm", Some("little"), true));
1967        let arm_uncached = run_to_string(mk("arm", "arm", Some("little"), false));
1968        let x86_uncached = run_to_string(mk("x86", "32", None, false));
1969        let x86_hit = run_to_string(mk("x86", "32", None, true));
1970
1971        assert_ne!(
1972            x86_first, arm_cached,
1973            "the ARM query was served the x86 cache entry"
1974        );
1975        assert_eq!(
1976            arm_cached, arm_uncached,
1977            "the ARM query must reproduce the uncached ARM run byte for byte"
1978        );
1979        assert_eq!(
1980            x86_hit, x86_uncached,
1981            "the x86 cache hit must reproduce the uncached x86 run byte for byte"
1982        );
1983        assert_eq!(x86_first, x86_hit);
1984        // One entry per architecture, not one shared between them.
1985        let entries = std::fs::read_dir(&dir.0)
1986            .unwrap()
1987            .flatten()
1988            .filter(|e| e.path().extension().and_then(|s| s.to_str()) == Some("rfc"))
1989            .count();
1990        assert_eq!(entries, 2, "each --rawArch needs its own entry");
1991
1992        std::env::remove_var("ROP_FINDER_CACHE_DIR");
1993    }
1994
1995    /// CLI-07 through the CLI: a fabricated entry at the deterministic
1996    /// file name is not printed. Before v0.2 this run printed
1997    /// `0xdeadbeefcafe0000 : pop rdi ; ret`.
1998    #[test]
1999    fn a_poisoned_cache_entry_is_not_printed() {
2000        let _guard = CACHE_ENV
2001            .lock()
2002            .unwrap_or_else(std::sync::PoisonError::into_inner);
2003        let dir = TempDir::new("poison");
2004        std::env::set_var("ROP_FINDER_CACHE_DIR", &dir.0);
2005
2006        let cli = || Cli {
2007            binary: Some(format!(
2008                "{}/../../tests/fixtures/elf-Linux-x86",
2009                env!("CARGO_MANIFEST_DIR")
2010            )),
2011            depth: 3,
2012            cache: true,
2013            ..cli_with(false, None, None, None)
2014        };
2015        let genuine = run_to_string(cli());
2016        assert!(!genuine.contains("0xdeadbeefcafe0000"));
2017
2018        // Overwrite every entry with the attacker's version, in the shape
2019        // the old cache accepted and in the shape the new one writes.
2020        let entry = std::fs::read_dir(&dir.0)
2021            .unwrap()
2022            .flatten()
2023            .map(|e| e.path())
2024            .find(|p| p.extension().and_then(|s| s.to_str()) == Some("rfc"))
2025            .expect("the miss stored an entry");
2026        let fabricated = br#"{"version":2,"gadgets":[{"vaddr":"0xdeadbeefcafe0000","bytes":"5fc3","text":"pop rdi ; ret","insns":["pop rdi","ret"]}]}"#;
2027        std::fs::write(&entry, fabricated).unwrap();
2028        let after_plain = run_to_string(cli());
2029        // ...and with the frame header, so only the tag is wrong.
2030        let mut framed = Vec::from(b"RFCACHE\x02".as_slice());
2031        framed.extend_from_slice(&[0u8; 32]);
2032        framed.extend_from_slice(fabricated);
2033        std::fs::write(&entry, &framed).unwrap();
2034        let after_framed = run_to_string(cli());
2035
2036        for (what, out) in [("bare JSON", &after_plain), ("bad tag", &after_framed)] {
2037            assert!(
2038                !out.contains("0xdeadbeefcafe0000"),
2039                "{what}: a poisoned entry reached the output"
2040            );
2041            assert_eq!(out, &genuine, "{what}: the rescan reproduces the truth");
2042        }
2043
2044        std::env::remove_var("ROP_FINDER_CACHE_DIR");
2045    }
2046
2047    /// CLS-08 on the CLI: the classification the tool already computes is
2048    /// now queryable, with the same three filters the MCP server exposes.
2049    ///
2050    /// Without the flags this is the finding itself — `--classify` prints
2051    /// class, labels and regs_written for 16,707 gadgets and there is no
2052    /// way to ask for the 2,027 that are stack pivots.
2053    #[test]
2054    fn class_label_and_writes_reg_filter_the_gadget_list() {
2055        let base = || Cli {
2056            binary: Some(format!(
2057                "{}/../../tests/fixtures/elf-Linux-x64",
2058                env!("CARGO_MANIFEST_DIR")
2059            )),
2060            depth: 4,
2061            json: true,
2062            classify: true,
2063            ..cli_with(false, None, None, None)
2064        };
2065        let parse = |s: &str| -> Vec<serde_json::Value> { serde_json::from_str(s).unwrap() };
2066
2067        let all = parse(&run_to_string(base()));
2068        assert!(
2069            all.len() > 1000,
2070            "{} gadgets is too few to prove anything",
2071            all.len()
2072        );
2073
2074        // --class keeps only that primary class, and narrows.
2075        let pivots = parse(&run_to_string(Cli {
2076            class: Some("stack-pivot".into()),
2077            ..base()
2078        }));
2079        assert!(!pivots.is_empty() && pivots.len() < all.len());
2080        for g in &pivots {
2081            assert_eq!(g["class"], "stack-pivot", "{g}");
2082        }
2083
2084        // --label is any-of over the full label set, so it is a superset
2085        // of the same name used as --class.
2086        let labelled = parse(&run_to_string(Cli {
2087            label: Some("stack-pivot".into()),
2088            ..base()
2089        }));
2090        assert!(labelled.len() >= pivots.len());
2091        for g in &labelled {
2092            assert!(
2093                g["labels"]
2094                    .as_array()
2095                    .unwrap()
2096                    .iter()
2097                    .any(|l| l == "stack-pivot"),
2098                "{g}"
2099            );
2100        }
2101
2102        // --writes-reg is all-of, and sigil/case insensitive.
2103        for spelling in ["rdi", "$RDI"] {
2104            let writes = parse(&run_to_string(Cli {
2105                writes_reg: Some(spelling.into()),
2106                ..base()
2107            }));
2108            assert!(!writes.is_empty(), "{spelling}");
2109            for g in &writes {
2110                assert!(
2111                    g["regs_written"]
2112                        .as_array()
2113                        .unwrap()
2114                        .iter()
2115                        .any(|r| r == "rdi"),
2116                    "{spelling}: {g}"
2117                );
2118            }
2119        }
2120        let both = parse(&run_to_string(Cli {
2121            writes_reg: Some("rdi,rsi".into()),
2122            ..base()
2123        }));
2124        for g in &both {
2125            let w = g["regs_written"].as_array().unwrap();
2126            assert!(
2127                w.iter().any(|r| r == "rdi") && w.iter().any(|r| r == "rsi"),
2128                "{g}"
2129            );
2130        }
2131
2132        // The filters compose, and an unknown value names the valid set
2133        // instead of leaving the user to guess.
2134        let combined = parse(&run_to_string(Cli {
2135            class: Some("reg-write".into()),
2136            writes_reg: Some("rdi".into()),
2137            ..base()
2138        }));
2139        for g in &combined {
2140            assert_eq!(g["class"], "reg-write", "{g}");
2141            assert!(g["regs_written"]
2142                .as_array()
2143                .unwrap()
2144                .iter()
2145                .any(|r| r == "rdi"));
2146        }
2147        let err = run(
2148            Cli {
2149                class: Some("stack_pivot".into()),
2150                ..base()
2151            },
2152            &mut Vec::new(),
2153        )
2154        .unwrap_err();
2155        assert!(err.contains("--class"), "{err}");
2156        assert!(err.contains("stack-pivot"), "{err}");
2157    }
2158
2159    /// The predicate itself, against classifications the classifier really
2160    /// produced rather than ones this test invented.
2161    #[test]
2162    fn the_semantic_predicate_matches_what_it_claims() {
2163        let g = |bytes: Vec<u8>, insns: &[&str]| Gadget {
2164            vaddr: 0x1000,
2165            bytes,
2166            insns: insns.iter().map(|s| (*s).to_string()).collect(),
2167            delay_slot: false,
2168            prev: None,
2169            table: rf_scan::TableKind::Rop,
2170        };
2171        let pop_rdi = rf_classify::classify(&g(vec![0x5f, 0xc3], &["pop rdi", "ret"]), Arch::X64);
2172        let bare_ret = rf_classify::classify(&g(vec![0xc3], &["ret"]), Arch::X64);
2173
2174        let q = |spec: query::QuerySpec<'_>| query::Query::parse(&spec).unwrap();
2175        let pop_rdi_insns = ["pop rdi", "ret"];
2176        let ret_insns = ["ret"];
2177
2178        let empty = q(query::QuerySpec::default());
2179        assert!(empty.is_empty());
2180        assert!(empty.matches(&pop_rdi, &pop_rdi_insns));
2181        assert!(empty.matches(&bare_ret, &ret_insns));
2182
2183        let f = q(query::QuerySpec {
2184            writes_reg: Some("%RDI"),
2185            ..Default::default()
2186        });
2187        assert!(f.matches(&pop_rdi, &pop_rdi_insns));
2188        assert!(!f.matches(&bare_ret, &ret_insns));
2189
2190        let f = q(query::QuerySpec {
2191            writes_reg: Some("rdi,rsi"),
2192            ..Default::default()
2193        });
2194        assert!(!f.matches(&pop_rdi, &pop_rdi_insns), "all-of, not any-of");
2195
2196        assert!(query::Query::parse(&query::QuerySpec {
2197            class: Some("nope"),
2198            ..Default::default()
2199        })
2200        .is_err());
2201        assert!(query::Query::parse(&query::QuerySpec {
2202            label: Some("stack_pivot"),
2203            ..Default::default()
2204        })
2205        .is_err());
2206    }
2207
2208    /// ROB-04 on the `--opcode` path, which is the same decoder and was
2209    /// the same panic: `--opcode "€€"` aborted with
2210    /// `byte index 2 is not a char boundary; it is inside '€'`.
2211    #[test]
2212    fn hex_decode_never_panics_on_non_ascii() {
2213        assert_eq!(hex_decode("€€"), None);
2214        assert_eq!(hex_decode("c3€"), None);
2215        assert_eq!(hex_decode("zz"), None);
2216        assert_eq!(hex_decode("c3"), Some(vec![0xc3]));
2217        let err = run(
2218            Cli {
2219                binary: Some(format!(
2220                    "{}/../../tests/fixtures/elf-Linux-x86",
2221                    env!("CARGO_MANIFEST_DIR")
2222                )),
2223                opcode: Some("€€".to_string()),
2224                ..cli_with(false, None, None, None)
2225            },
2226            &mut Vec::new(),
2227        );
2228        assert!(
2229            err.unwrap_err().contains("invalid --opcode"),
2230            "a bad --opcode is a usage error, not a panic"
2231        );
2232    }
2233
2234    /// CLI-08/PERF-12.
2235    #[test]
2236    fn cache_purge_empties_the_directory() {
2237        let _guard = CACHE_ENV
2238            .lock()
2239            .unwrap_or_else(std::sync::PoisonError::into_inner);
2240        let dir = TempDir::new("purge");
2241        std::env::set_var("ROP_FINDER_CACHE_DIR", &dir.0);
2242
2243        let scan = Cli {
2244            binary: Some(format!(
2245                "{}/../../tests/fixtures/elf-Linux-x86",
2246                env!("CARGO_MANIFEST_DIR")
2247            )),
2248            depth: 3,
2249            cache: true,
2250            ..cli_with(false, None, None, None)
2251        };
2252        run_to_string(scan);
2253        let count = |dir: &std::path::Path| {
2254            std::fs::read_dir(dir)
2255                .unwrap()
2256                .flatten()
2257                .filter(|e| e.path().extension().and_then(|s| s.to_str()) == Some("rfc"))
2258                .count()
2259        };
2260        assert_eq!(count(&dir.0), 1);
2261
2262        let report = run_to_string(Cli {
2263            cache_purge: true,
2264            binary: None,
2265            ..cli_with(false, None, None, None)
2266        });
2267        assert!(report.starts_with("Purged 1 cache entry ("), "{report}");
2268        assert_eq!(count(&dir.0), 0);
2269
2270        std::env::remove_var("ROP_FINDER_CACHE_DIR");
2271    }
2272
2273    #[test]
2274    fn classify_adds_json_fields() {
2275        let (view, res) = scan_result_for("elf-Linux-x64", 5);
2276        let (gadgets, classes) = classify_gadgets(res.gadgets, view.arch(), false);
2277        let res = ScanResult { gadgets, ..res };
2278        let json = to_json_classified(&res, 0, Some(&classes));
2279        let pop_rax = json
2280            .iter()
2281            .find(|j| j.text == "pop rax ; ret")
2282            .expect("fixture has pop rax ; ret");
2283        assert_eq!(pop_rax.class, Some("reg-write"));
2284        assert_eq!(pop_rax.labels.as_deref(), Some(&["reg-write"][..]));
2285        assert_eq!(pop_rax.regs_written.unwrap(), &["rax".to_string()]);
2286        assert_eq!(pop_rax.side_effects, Some(1));
2287        assert_eq!(pop_rax.quality, Some(100));
2288        assert_eq!(pop_rax.dispatcher, Some(false));
2289        assert_eq!(pop_rax.low_confidence, Some(false));
2290        // Without --classify the fields are absent from the JSON text.
2291        let plain = serde_json::to_string(&to_json(&res, 0)[0]).unwrap();
2292        assert!(!plain.contains("\"class\""));
2293        assert!(!plain.contains("\"quality\""));
2294    }
2295
2296    #[test]
2297    fn rank_sorts_by_quality_desc_then_vaddr() {
2298        let (view, res) = scan_result_for("elf-Linux-x64", 5);
2299        let (gadgets, classes) = classify_gadgets(res.gadgets, view.arch(), true);
2300        assert_eq!(gadgets.len(), classes.len());
2301        for (gw, cw) in gadgets.windows(2).zip(classes.windows(2)) {
2302            let (ga, gb, ca, cb) = (&gw[0], &gw[1], &cw[0], &cw[1]);
2303            assert!(
2304                ca.quality > cb.quality || (ca.quality == cb.quality && ga.vaddr < gb.vaddr),
2305                "ordering violated: q{} @ {:#x} before q{} @ {:#x}",
2306                ca.quality,
2307                ga.vaddr,
2308                cb.quality,
2309                gb.vaddr
2310            );
2311        }
2312        // The cleanest gadgets score 100 and lead the output.
2313        assert_eq!(classes[0].quality, 100);
2314        assert!(gadgets[0].text().ends_with(" ; ret") || gadgets[0].text() == "ret");
2315    }
2316
2317    /// CLI-06 / ENG-06: clap's help and version terminations are
2318    /// successes. Driven through the real parser so a clap upgrade that
2319    /// renamed a kind would fail here.
2320    #[test]
2321    fn help_and_version_exit_zero() {
2322        for args in [
2323            vec!["rop-finder", "--help"],
2324            vec!["rop-finder", "-h"],
2325            vec!["rop-finder", "--version"],
2326            vec!["rop-finder", "-V"],
2327        ] {
2328            let e = Cli::try_parse_from(&args).expect_err("clap reports these as Err");
2329            assert_eq!(e.exit_code(), 0, "{args:?} is a successful termination");
2330            assert_eq!(clap_exit_code(e.kind()), 0, "{args:?} must exit 0");
2331        }
2332        // ...and a real usage error still exits 1 (MANUAL's contract).
2333        let e = Cli::try_parse_from(["rop-finder", "--no-such-flag"]).unwrap_err();
2334        assert_eq!(clap_exit_code(e.kind()), 1);
2335        assert_eq!(
2336            clap_exit_code(clap::error::ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand),
2337            0
2338        );
2339    }
2340
2341    /// CLAIM-10: `--version` records the disassembler build and the
2342    /// attribution the port owes ROPgadget.
2343    #[test]
2344    fn long_version_names_capstone_and_ropgadget() {
2345        let v = long_version();
2346        assert!(v.starts_with(env!("CARGO_PKG_VERSION")), "{v}");
2347        assert!(
2348            v.contains(&format!("capstone {}", rf_scan::capstone_version())),
2349            "{v}"
2350        );
2351        assert!(v.contains("ROPgadget"), "{v}");
2352        assert!(v.contains("Jonathan Salwan"), "{v}");
2353        // The version is the linked library's, not a placeholder.
2354        assert!(v.contains("capstone 5.0"), "{v}");
2355        // The author of the Rust work is named, and is taken from the
2356        // manifest rather than typed here — a literal would drift, which is
2357        // exactly how the MCP server came to report version 0.1.0 for a
2358        // 1.0.0 build.
2359        assert!(v.contains("Written by "), "{v}");
2360        for author in env!("CARGO_PKG_AUTHORS").split(':') {
2361            assert!(v.contains(author), "author {author:?} missing from:\n{v}");
2362        }
2363        // Crediting the port's author must never displace the upstream
2364        // attribution the licence requires (ENG-03). Both, always.
2365        assert!(
2366            v.find("Written by ") < v.find("A port of ROPgadget"),
2367            "the author line must precede, not replace, the upstream credit:\n{v}"
2368        );
2369    }
2370
2371    /// CHWIN-09: the experimental gate fires for the Windows chain and
2372    /// only for it.
2373    #[test]
2374    fn windows_chain_target_is_gated_by_a_warning() {
2375        let w = chain_experimental_warning("windows-virtualprotect")
2376            .expect("windows-virtualprotect must warn");
2377        assert!(w.contains("EXPERIMENTAL"), "{w}");
2378        assert!(w.contains("CHWIN-01"), "{w}");
2379        assert!(w.contains("CHWIN-02"), "{w}");
2380        assert!(w.contains("CHWIN-03"), "{w}");
2381        assert!(w.contains("CHWIN-07"), "{w}");
2382        assert!(w.contains("v0.5"), "{w}");
2383        // v0.5: the warning still fires, but it may no longer say the chain
2384        // cannot run. CHWIN-01/-02/-03/-07 are fixed and every one of them
2385        // has a recorded run under tests/emulate.py, so this sentence would
2386        // now be a false statement about the tool's own output. It is
2387        // asserted absent so it cannot be reinstated by a copy-paste.
2388        assert!(
2389            !w.contains("known NOT to execute"),
2390            "the pre-v0.5 retraction text is back: {w}"
2391        );
2392        assert!(w.contains("docs/chain-regressions.md"), "{w}");
2393        assert!(w.ends_with('\n'), "{w:?}");
2394        assert!(chain_experimental_warning("linux-execve").is_none());
2395    }
2396
2397    #[test]
2398    fn badbytes_parsing() {
2399        assert_eq!(parse_badbytes("0a|0d").unwrap(), vec![0x0a, 0x0d]);
2400        // Ranges are inclusive (ropgadget/options.py:134, range(low, high+1)).
2401        assert_eq!(parse_badbytes("00-03|ff").unwrap(), vec![0, 1, 2, 3, 0xff]);
2402        assert_eq!(parse_badbytes("0a|").unwrap(), vec![0x0a]); // trailing | ok
2403        assert!(parse_badbytes("0x100").is_err());
2404        assert!(parse_badbytes("zz").is_err());
2405    }
2406
2407    #[test]
2408    fn range_parsing() {
2409        assert_eq!(parse_range("0x0-0x0").unwrap(), None);
2410        assert_eq!(
2411            parse_range("0x1000-0x2000").unwrap(),
2412            Some((0x1000, 0x2000))
2413        );
2414        assert!(parse_range("0x2000-0x1000").is_err());
2415        assert!(parse_range("nonsense").is_err());
2416    }
2417
2418    #[test]
2419    fn hex_parsing() {
2420        assert_eq!(parse_hex("0x41414141", "x").unwrap(), 0x41414141);
2421        assert_eq!(parse_hex("ff", "x").unwrap(), 0xff);
2422        assert!(parse_hex("0xz", "x").is_err());
2423    }
2424
2425    #[test]
2426    fn raw_spec_validation_mirrors_args_py() {
2427        // no raw flags at all → no raw load
2428        assert!(parse_raw_spec(&cli_with(false, None, None, None))
2429            .unwrap()
2430            .is_none());
2431        // rawMode/rawEndian without rawArch
2432        assert!(parse_raw_spec(&cli_with(false, None, Some("32"), None)).is_err());
2433        assert!(parse_raw_spec(&cli_with(false, None, None, Some("big"))).is_err());
2434        // rawArch without mode
2435        assert!(parse_raw_spec(&cli_with(false, Some("x86"), None, None)).is_err());
2436        // rawArch non-x86 without endian. CLI-13: the message must name
2437        // the flag that is missing (--rawEndian), not the one already
2438        // given; args.py:128 says "Specify --rawEndian".
2439        assert_eq!(
2440            parse_raw_spec(&cli_with(false, Some("arm"), Some("arm"), None)).unwrap_err(),
2441            "Specify --rawEndian"
2442        );
2443        // ...while a genuinely missing --rawArch still says --rawArch
2444        // (args.py:117-121).
2445        assert_eq!(
2446            parse_raw_spec(&cli_with(false, None, None, Some("big"))).unwrap_err(),
2447            "Specify --rawArch"
2448        );
2449        // thumb conflicting with rawMode
2450        assert!(parse_raw_spec(&cli_with(true, Some("arm"), Some("arm"), Some("little"))).is_err());
2451        // unknown mode / arch+mode combo
2452        assert!(parse_raw_spec(&cli_with(false, Some("x86"), Some("v99"), None)).is_err());
2453        assert!(
2454            parse_raw_spec(&cli_with(false, Some("mips"), Some("thumb"), Some("big"))).is_err()
2455        );
2456        assert!(parse_raw_spec(&cli_with(false, Some("s390"), Some("64"), Some("big"))).is_err());
2457    }
2458
2459    #[test]
2460    fn raw_spec_mapping() {
2461        let (a, e, t) = parse_raw_spec(&cli_with(false, Some("x86"), Some("32"), None))
2462            .unwrap()
2463            .unwrap();
2464        assert_eq!((a, e, t), (Arch::X86, Endianness::Little, false));
2465        // x86 forces little-endian even if big requested (raw.py:71-72)
2466        let (_, e, _) = parse_raw_spec(&cli_with(false, Some("x86"), Some("64"), Some("big")))
2467            .unwrap()
2468            .unwrap();
2469        assert_eq!(e, Endianness::Little);
2470        let (a, _, t) =
2471            parse_raw_spec(&cli_with(false, Some("arm"), Some("thumb"), Some("little")))
2472                .unwrap()
2473                .unwrap();
2474        assert_eq!((a, t), (Arch::ArmThumb, true));
2475        // --thumb implies rawMode=thumb (args.py:123)
2476        let (a, _, t) = parse_raw_spec(&cli_with(true, Some("arm"), None, Some("big")))
2477            .unwrap()
2478            .unwrap();
2479        assert_eq!((a, t), (Arch::ArmThumb, true));
2480        let (a, e, _) = parse_raw_spec(&cli_with(false, Some("mips"), Some("64"), Some("big")))
2481            .unwrap()
2482            .unwrap();
2483        assert_eq!((a, e), (Arch::Mips64, Endianness::Big));
2484        let (a, _, _) = parse_raw_spec(&cli_with(
2485            false,
2486            Some("riscv"),
2487            Some("riscv"),
2488            Some("little"),
2489        ))
2490        .unwrap()
2491        .unwrap();
2492        assert_eq!(a, Arch::RiscV64);
2493    }
2494
2495    // ---- Phase 2: --section selection (PLAN.md §6.3) ----
2496
2497    #[test]
2498    fn select_sections_glob_and_fallback_flag() {
2499        let secs = vec![
2500            make_section(".init", 0x1000, 0x10),
2501            make_section(".plt", 0x1010, 0x20),
2502            make_section(".text", 0x2000, 0x100),
2503        ];
2504        // exact match
2505        let (m, fb) = select_sections(&secs, &[".text".to_string()]).unwrap();
2506        assert_eq!(m.len(), 1);
2507        assert_eq!(m[0].name, ".text");
2508        assert!(!fb);
2509        // glob match
2510        let (m, _) = select_sections(&secs, &[".p*".to_string()]).unwrap();
2511        assert_eq!(m.len(), 1);
2512        assert_eq!(m[0].name, ".plt");
2513        // multiple patterns
2514        let (m, _) = select_sections(&secs, &[".init".to_string(), ".plt".to_string()]).unwrap();
2515        assert_eq!(m.len(), 2);
2516        // zero matches → error listing available names
2517        let err = select_sections(&secs, &[".nope".to_string()]).unwrap_err();
2518        assert!(err.contains(".text"), "error lists available: {err}");
2519        assert!(err.contains(".plt"), "error lists available: {err}");
2520        // stripped-ELF fallback names detected
2521        let stripped = vec![
2522            make_section("PT_LOAD#0", 0x1000, 0x10),
2523            make_section("PT_LOAD#1", 0x2000, 0x20),
2524        ];
2525        let (m, fb) = select_sections(&stripped, &["PT_LOAD#*".to_string()]).unwrap();
2526        assert_eq!(m.len(), 2);
2527        assert!(fb);
2528        // invalid glob
2529        assert!(select_sections(&secs, &["[".to_string()]).is_err());
2530    }
2531
2532    #[test]
2533    fn section_filter_pe_matches_default_scan() {
2534        // PE exec scan regions == exec sections, so --section .text must
2535        // reproduce the default scan exactly, with every vaddr inside .text.
2536        let (_, all) = scan_fixture("pe-x64-cmd-v6.1.7601", None, &[], |_| {});
2537        let (view, filtered) = scan_fixture("pe-x64-cmd-v6.1.7601", None, &[".text"], |_| {});
2538        assert!(!filtered.is_empty());
2539        assert_eq!(all.len(), filtered.len());
2540        let text = &view.named_exec.iter().find(|s| s.name == ".text").unwrap();
2541        for g in &filtered {
2542            assert!(
2543                g.vaddr >= text.vaddr && g.vaddr < text.vaddr + text.size,
2544                "gadget {:#x} outside .text",
2545                g.vaddr
2546            );
2547        }
2548    }
2549
2550    #[test]
2551    fn section_filter_elf_multi_and_glob() {
2552        // ELF: exec sections (.init/.plt/.text/.fini) are a subset of the
2553        // PT_LOAD scan regions, so filtering narrows coverage (intended,
2554        // PLAN §6.3).
2555        let (view, plt) = scan_fixture("elf-x64-bash-v4.1.5.1", None, &[".p*"], |_| {});
2556        assert!(!plt.is_empty());
2557        let plt_sec = view.named_exec.iter().find(|s| s.name == ".plt").unwrap();
2558        for g in &plt {
2559            assert!(
2560                g.vaddr >= plt_sec.vaddr && g.vaddr < plt_sec.vaddr + plt_sec.size,
2561                "gadget {:#x} outside .plt",
2562                g.vaddr
2563            );
2564        }
2565        // comma-style multi selection (clap splits commas; here two pats)
2566        let (_, multi) = scan_fixture("elf-x64-bash-v4.1.5.1", None, &[".init", ".plt"], |_| {});
2567        let init_sec = view.named_exec.iter().find(|s| s.name == ".init").unwrap();
2568        assert!(multi.len() > plt.len(), ".init adds gadgets");
2569        for g in &multi {
2570            let in_plt = g.vaddr >= plt_sec.vaddr && g.vaddr < plt_sec.vaddr + plt_sec.size;
2571            let in_init = g.vaddr >= init_sec.vaddr && g.vaddr < init_sec.vaddr + init_sec.size;
2572            assert!(
2573                in_plt || in_init,
2574                "gadget {:#x} outside .init/.plt",
2575                g.vaddr
2576            );
2577        }
2578        // filtered scan finds strictly fewer gadgets than the default
2579        let (_, all) = scan_fixture("elf-x64-bash-v4.1.5.1", None, &[], |_| {});
2580        assert!(multi.len() < all.len());
2581    }
2582
2583    #[test]
2584    fn section_unknown_name_is_usage_error() {
2585        let bytes = fixture_bytes("elf-x64-bash-v4.1.5.1");
2586        let target = load_target(&bytes);
2587        let view = build_view(&target);
2588        let err = select_sections(&view.named_exec, &[".nonexistent".to_string()]).unwrap_err();
2589        assert!(err.contains(".text"), "lists available sections: {err}");
2590    }
2591
2592    #[test]
2593    fn stripped_elf_falls_back_to_segment_names() {
2594        // Zero e_shoff (0x28, 8 bytes) and e_shnum (0x3c, 2 bytes) of an
2595        // ELF64 fixture copy — the loader must fall back to PT_LOAD#n names.
2596        let mut bytes = fixture_bytes("elf-x64-bash-v4.1.5.1");
2597        assert_eq!(&bytes[0..4], b"\x7fELF");
2598        assert_eq!(bytes[4], 2, "fixture must be ELF64");
2599        bytes[0x28..0x30].fill(0);
2600        bytes[0x3c..0x3e].fill(0);
2601        let target = load_target(&bytes);
2602        let view = build_view(&target);
2603        assert!(!view.named_exec.is_empty());
2604        assert!(view
2605            .named_exec
2606            .iter()
2607            .all(|s| s.name.starts_with("PT_LOAD#")));
2608        let (matched, fallback) =
2609            select_sections(&view.named_exec, &["PT_LOAD#*".to_string()]).unwrap();
2610        assert!(fallback, "warning flag set for fallback names");
2611        assert_eq!(matched.len(), view.named_exec.len());
2612    }
2613
2614    #[test]
2615    fn range_composes_with_section() {
2616        // --range applies to whatever regions the view exposes (here: the
2617        // selected .text section only).
2618        let (view, _) = scan_fixture("elf-x64-bash-v4.1.5.1", None, &[".text"], |_| {});
2619        let text = view.named_exec.iter().find(|s| s.name == ".text").unwrap();
2620        let mid = text.vaddr + text.size / 2;
2621        let (_, gadgets) = scan_fixture("elf-x64-bash-v4.1.5.1", None, &[".text"], |o| {
2622            o.range = Some((text.vaddr, mid));
2623        });
2624        assert!(!gadgets.is_empty());
2625        for g in &gadgets {
2626            assert!(g.vaddr >= text.vaddr && g.vaddr < mid);
2627        }
2628    }
2629
2630    #[test]
2631    fn json_gadgets_carry_section_name() {
2632        let (view, gadgets) = scan_fixture("elf-x64-bash-v4.1.5.1", None, &[".plt"], |_| {});
2633        let res = ScanResult {
2634            gadgets,
2635            addr_size: view.addr_size(),
2636            universal_arch: None,
2637            selected_sections: Some(
2638                view.regions
2639                    .iter()
2640                    .map(|s| (s.name.clone(), s.vaddr, s.size))
2641                    .collect(),
2642            ),
2643        };
2644        let json = to_json(&res, 0);
2645        assert!(!json.is_empty());
2646        for g in &json {
2647            assert_eq!(g.section.as_deref(), Some(".plt"));
2648        }
2649        // offset is subtracted before the section lookup: with an offset
2650        // of 0x10 the lookup keys shift 16 bytes down, so gadgets at the
2651        // very start of .plt (if any) fall out; with a huge offset every
2652        // key lands below the section and the section is None.
2653        let huge = to_json(&res, 0x8000_0000);
2654        assert!(huge.iter().all(|g| g.section.is_none()));
2655    }
2656
2657    // ---- Phase 2: --base hardening (PLAN.md §6.4) ----
2658
2659    #[test]
2660    fn base_zero_pe_gives_rvas() {
2661        let bytes = fixture_bytes("pe-x64-cmd-v6.1.7601");
2662        let target = load_target(&bytes);
2663        let orig_base = build_view(&target).base;
2664        let (_, default) = scan_fixture("pe-x64-cmd-v6.1.7601", None, &[], |_| {});
2665        let (_, rebased) = scan_fixture("pe-x64-cmd-v6.1.7601", Some(0), &[], |_| {});
2666        let ret_default = bare_ret_vaddr(&default).expect("bare ret in default scan");
2667        let ret_base0 = bare_ret_vaddr(&rebased).expect("bare ret in base-0 scan");
2668        assert_eq!(ret_base0, ret_default - orig_base);
2669        // PLAN §6.4 review point: rebasing changes address-dependent
2670        // operand text, so the text SETS differ even though the traversal
2671        // is identical.
2672        let texts_default: std::collections::BTreeSet<_> =
2673            default.iter().map(|g| g.text()).collect();
2674        let texts_base0: std::collections::BTreeSet<_> = rebased.iter().map(|g| g.text()).collect();
2675        assert_ne!(texts_default, texts_base0);
2676    }
2677
2678    #[test]
2679    fn base_shift_pie_elf() {
2680        let bytes = fixture_bytes("elf-x64-bash-v4.1.5.1");
2681        let target = load_target(&bytes);
2682        let orig_base = build_view(&target).base;
2683        let (_, default) = scan_fixture("elf-x64-bash-v4.1.5.1", None, &[], |_| {});
2684        let (_, rebased) = scan_fixture("elf-x64-bash-v4.1.5.1", Some(0x55550000), &[], |_| {});
2685        let ret_default = bare_ret_vaddr(&default).expect("bare ret in default scan");
2686        let ret_shifted = bare_ret_vaddr(&rebased).expect("bare ret in rebased scan");
2687        assert_eq!(ret_shifted, ret_default - orig_base + 0x55550000);
2688    }
2689
2690    #[test]
2691    fn badbytes_check_final_rebased_address() {
2692        // After --base 0x55550000 every gadget address contains byte 0x55,
2693        // so --badbytes 55 eliminates everything.
2694        let (_, filtered) = scan_fixture("elf-x64-bash-v4.1.5.1", Some(0x55550000), &[], |o| {
2695            o.badbytes = vec![0x55];
2696        });
2697        assert!(filtered.is_empty(), "badbytes apply after rebase");
2698        // Same rebase without badbytes finds gadgets.
2699        let (_, plain) = scan_fixture("elf-x64-bash-v4.1.5.1", Some(0x55550000), &[], |_| {});
2700        assert!(!plain.is_empty());
2701        // At the default base (0x400000-ish) 0x55 bytes are rare → gadgets
2702        // survive.
2703        let (_, default) = scan_fixture("elf-x64-bash-v4.1.5.1", None, &[], |o| {
2704            o.badbytes = vec![0x55];
2705        });
2706        assert!(!default.is_empty());
2707    }
2708
2709    #[test]
2710    fn base_and_offset_compose() {
2711        let bytes = fixture_bytes("elf-x64-bash-v4.1.5.1");
2712        let target = load_target(&bytes);
2713        let orig_base = build_view(&target).base;
2714        let (_, default) = scan_fixture("elf-x64-bash-v4.1.5.1", None, &[], |_| {});
2715        let ret_default = bare_ret_vaddr(&default).unwrap();
2716        // offset applies AFTER rebase: vaddr == default - orig + B + O
2717        let (_, composed) = scan_fixture("elf-x64-bash-v4.1.5.1", Some(0x70000000), &[], |o| {
2718            o.offset = 0x1000;
2719        });
2720        let ret_composed = bare_ret_vaddr(&composed).unwrap();
2721        assert_eq!(ret_composed, ret_default - orig_base + 0x70000000 + 0x1000);
2722        // Same for PE.
2723        let bytes = fixture_bytes("pe-x64-cmd-v6.1.7601");
2724        let target = load_target(&bytes);
2725        let orig_base = build_view(&target).base;
2726        let (_, default) = scan_fixture("pe-x64-cmd-v6.1.7601", None, &[], |_| {});
2727        let ret_default = bare_ret_vaddr(&default).unwrap();
2728        let (_, composed) = scan_fixture("pe-x64-cmd-v6.1.7601", Some(0x80000000), &[], |o| {
2729            o.offset = 0x2000;
2730        });
2731        let ret_composed = bare_ret_vaddr(&composed).unwrap();
2732        assert_eq!(ret_composed, ret_default - orig_base + 0x80000000 + 0x2000);
2733    }
2734
2735    // ---- Phase 2: --info (PLAN.md §6.4) ----
2736
2737    #[test]
2738    fn info_pe_shape() {
2739        let bytes = fixture_bytes("pe-x64-cmd-v6.1.7601");
2740        let target = load_target(&bytes);
2741        let Target::Pe(ref pe) = target else {
2742            panic!("expected PE")
2743        };
2744        let expect_base = hexs(pe.image_base());
2745        let info = info_json(&target, None);
2746        assert_eq!(info["format"], "pe");
2747        assert_eq!(info["arch"], "x64");
2748        assert_eq!(info["endianness"], "little");
2749        assert_eq!(info["addr_size"], 8);
2750        assert_eq!(info["image_base"], serde_json::json!(expect_base));
2751        let sections = info["sections"].as_array().unwrap();
2752        let text = sections
2753            .iter()
2754            .find(|s| s["name"] == ".text")
2755            .expect(".text section");
2756        assert_eq!(text["executable"], true);
2757        assert_eq!(text["writable"], false);
2758        let imports = info["imports"].as_array().unwrap();
2759        assert!(!imports.is_empty());
2760        assert!(imports.iter().any(|i| i["dll"]
2761            .as_str()
2762            .unwrap()
2763            .to_uppercase()
2764            .contains("KERNEL32")));
2765        assert!(imports[0]["symbol"].is_string());
2766        assert!(imports[0]["iat_vaddr"].as_str().unwrap().starts_with("0x"));
2767
2768        // CHWIN-03: `iat_vaddr` is the IAT slot the loader patches, NOT the
2769        // IMAGE_IMPORT_BY_NAME record. Measured out of this fixture by hand:
2770        // image_base 0x4ad00000, IAT directory RVA 0x29000, so
2771        // msvcrt.dll!memset sits at slot 0x4ad29000 with its hint/name
2772        // record at 0x4ad2af40 (which is what --info used to print).
2773        let memset = imports
2774            .iter()
2775            .find(|i| {
2776                i["dll"]
2777                    .as_str()
2778                    .unwrap()
2779                    .eq_ignore_ascii_case("msvcrt.dll")
2780                    && i["symbol"] == "memset"
2781            })
2782            .expect("msvcrt.dll!memset");
2783        assert_eq!(memset["iat_vaddr"], "0x4ad29000");
2784        assert_eq!(memset["hint_name_vaddr"], "0x4ad2af40");
2785        for i in imports {
2786            assert_ne!(
2787                i["iat_vaddr"], i["hint_name_vaddr"],
2788                "{i} — the IAT slot must not be the hint/name record"
2789            );
2790        }
2791    }
2792
2793    /// CHWIN-03: `--base` slides both import addresses by the same delta.
2794    #[test]
2795    fn info_pe_imports_honour_base() {
2796        let bytes = fixture_bytes("pe-x64-cmd-v6.1.7601");
2797        let target = load_target(&bytes);
2798        let info = info_json(&target, Some(0));
2799        let memset = info["imports"]
2800            .as_array()
2801            .unwrap()
2802            .iter()
2803            .find(|i| {
2804                i["dll"]
2805                    .as_str()
2806                    .unwrap()
2807                    .eq_ignore_ascii_case("msvcrt.dll")
2808                    && i["symbol"] == "memset"
2809            })
2810            .expect("msvcrt.dll!memset")
2811            .clone();
2812        // rebased to 0 ⇒ the printed addresses are the RVAs.
2813        assert_eq!(memset["iat_vaddr"], "0x29000");
2814        assert_eq!(memset["hint_name_vaddr"], "0x2af40");
2815    }
2816
2817    #[test]
2818    fn info_elf_shape() {
2819        let bytes = fixture_bytes("elf-x64-bash-v4.1.5.1");
2820        let target = load_target(&bytes);
2821        let info = info_json(&target, None);
2822        assert_eq!(info["format"], "elf");
2823        assert_eq!(info["arch"], "x64");
2824        let sections = info["sections"].as_array().unwrap();
2825        assert!(sections.iter().any(|s| s["name"] == ".text"));
2826        assert!(info["entry"].as_str().unwrap().starts_with("0x"));
2827
2828        // ECO-06: `imports` was hardcoded `[]` for every ELF, so there was
2829        // no ret2plt/ret2libc symbol resolution anywhere in the tool. It is
2830        // now the SHN_UNDEF subset of the symbol tables.
2831        let imports = info["imports"].as_array().unwrap();
2832        assert!(!imports.is_empty(), "a dynamic ELF has undefined symbols");
2833        let strcpy = imports
2834            .iter()
2835            .find(|i| i["symbol"] == "strcpy")
2836            .expect("bash imports strcpy");
2837        assert_eq!(strcpy["binding"], "GLOBAL");
2838        // A DT_JMPREL relocation, not a guess.
2839        assert!(
2840            strcpy["got"].as_str().is_some_and(|g| g.starts_with("0x")),
2841            "{strcpy}"
2842        );
2843        let symbols = info["symbols"].as_array().unwrap();
2844        assert_eq!(
2845            info["symbol_count"].as_u64().unwrap() as usize,
2846            symbols.len()
2847        );
2848        assert!(symbols.len() >= imports.len());
2849
2850        // ECO-06: the mitigation report, with `unknown` as a first-class
2851        // answer that states its reason.
2852        let m = &info["mitigations"];
2853        for key in ["nx", "pie", "relro", "canary", "fortify"] {
2854            let v = &m[key];
2855            assert!(!v.is_null(), "missing mitigation {key}");
2856            assert!(
2857                v["enabled"].is_boolean() || v["enabled"] == "unknown",
2858                "{key}: enabled must be a bool or the string \"unknown\", got {}",
2859                v["enabled"]
2860            );
2861            assert!(
2862                v["evidence"].as_str().is_some_and(|e| !e.is_empty()),
2863                "{key} has no evidence"
2864            );
2865        }
2866        // The declaration order is carried beside the (alphabetical) map.
2867        assert_eq!(
2868            info["mitigations_order"],
2869            serde_json::json!(["nx", "pie", "relro", "canary", "fortify", "rpath", "runpath"])
2870        );
2871    }
2872
2873    #[test]
2874    fn info_honours_base() {
2875        let bytes = fixture_bytes("elf-x64-bash-v4.1.5.1");
2876        let target = load_target(&bytes);
2877        let Target::Elf(ref elf) = target else {
2878            panic!("expected ELF")
2879        };
2880        let orig_base = elf.image_base();
2881        let orig_entry = elf.entry();
2882        let info = info_json(&target, Some(0x55550000));
2883        assert_eq!(info["image_base"], "0x55550000");
2884        assert_eq!(
2885            info["entry"],
2886            serde_json::json!(hexs(orig_entry - orig_base + 0x55550000))
2887        );
2888    }
2889
2890    #[test]
2891    fn info_universal_and_raw() {
2892        let bytes = fixture_bytes("UNIVERSAL-x86-x64-libSystem.B.dylib");
2893        let target = load_target(&bytes);
2894        let Target::Universal(ref u) = target else {
2895            panic!("expected Universal")
2896        };
2897        let n_slices = u.slices().len();
2898        let info = info_json(&target, None);
2899        assert_eq!(info["format"], "universal");
2900        let slices = info["slices"].as_array().unwrap();
2901        assert_eq!(slices.len(), n_slices);
2902        assert!(slices.iter().all(|s| s["format"] == "macho"));
2903
2904        let raw = RawBinary::new(&fixture_bytes("raw-x86.raw"), Arch::X86, Endianness::Little);
2905        let info = info_json(&Target::Raw(raw), None);
2906        assert_eq!(info["format"], "raw");
2907        assert_eq!(info["arch"], "x86");
2908        assert_eq!(info["image_base"], "0x0");
2909    }
2910
2911    // -- --ropchain (Phase 4a) ------------------------------------------------
2912
2913    fn chain_fixture(fixture: &str) -> ChainOutcome {
2914        match chain_bytes(
2915            &fixture_bytes(fixture),
2916            None,
2917            &ScanRequest::default(),
2918            &ChainSpec::linux(),
2919        ) {
2920            Ok(o) => o,
2921            Err(e) => panic!("chain build failed for {fixture}: {e}"),
2922        }
2923    }
2924
2925    /// vaddr universe for `RopChain::validate`: the scan's gadget vaddrs.
2926    fn scan_universe(out: &ChainOutcome) -> std::collections::HashSet<u64> {
2927        out.outcome
2928            .result
2929            .gadgets
2930            .iter()
2931            .map(|g| g.vaddr.wrapping_add(out.outcome.opts.offset))
2932            .collect()
2933    }
2934
2935    // -- ECO-04 / CHLX-07 / CHLX-08 -------------------------------------------
2936
2937    #[test]
2938    fn syscall_number_is_decimal_unless_it_says_0x() {
2939        assert_eq!(parse_syscall_nr("59").unwrap(), 59);
2940        assert_eq!(parse_syscall_nr(" 10 ").unwrap(), 10);
2941        // ANCH-02's rule, for the same reason: a syscall number is written
2942        // in decimal everywhere from the kernel table to strace.
2943        assert_eq!(parse_syscall_nr("0x3b").unwrap(), 59);
2944        assert!(parse_syscall_nr("zz").is_err());
2945    }
2946
2947    #[test]
2948    fn syscall_args_parse_into_register_value_pairs() {
2949        let got = parse_syscall_args("rdi=0x1000,rsi=8, RDX =7").unwrap();
2950        assert_eq!(
2951            got,
2952            vec![
2953                ("rdi".to_string(), 0x1000),
2954                ("rsi".to_string(), 8),
2955                ("rdx".to_string(), 7),
2956            ]
2957        );
2958        assert!(parse_syscall_args("rdi")
2959            .unwrap_err()
2960            .contains("<reg>=<value>"));
2961        assert!(parse_syscall_args("=1")
2962            .unwrap_err()
2963            .contains("empty register"));
2964        assert!(parse_syscall_args("").unwrap().is_empty());
2965    }
2966
2967    #[test]
2968    fn stage_bytes_parse_as_hex() {
2969        assert_eq!(
2970            parse_hex_bytes("9090cc", "--stage").unwrap(),
2971            vec![0x90, 0x90, 0xcc]
2972        );
2973        assert_eq!(
2974            parse_hex_bytes("0x90 90", "--stage").unwrap(),
2975            vec![0x90, 0x90]
2976        );
2977        assert!(parse_hex_bytes("909", "--stage")
2978            .unwrap_err()
2979            .contains("odd number"));
2980        assert!(parse_hex_bytes("", "--stage")
2981            .unwrap_err()
2982            .contains("no bytes"));
2983    }
2984
2985    /// CHWIN-08 #2: `--api-name A,B` composes two calls; `--api-addr` then
2986    /// needs one address per call or none.
2987    #[test]
2988    fn api_name_list_composes_calls_and_pairs_with_api_addr() {
2989        let spec = ChainSpec {
2990            target: "windows-virtualprotect".into(),
2991            api_name: Some("VirtualAlloc,virtualprotect".into()),
2992            api_addr: Some("0x1000,0x2000".into()),
2993            ..ChainSpec::default()
2994        };
2995        let o = win_opts(&spec).unwrap();
2996        assert_eq!(o.api_name, "VirtualAlloc");
2997        assert_eq!(o.api_addr, Some(0x1000));
2998        // canonical casing, so the IAT lookup and the description agree
2999        assert_eq!(
3000            o.extra_calls,
3001            vec![("VirtualProtect".to_string(), Some(0x2000))]
3002        );
3003
3004        let mismatched = ChainSpec {
3005            api_addr: Some("0x1000".into()),
3006            ..spec.clone()
3007        };
3008        let err = win_opts(&mismatched).unwrap_err().to_string();
3009        assert!(err.contains("one runtime address per call"), "{err}");
3010
3011        let unknown = ChainSpec {
3012            api_name: Some("VirtualAlloc,LoadLibraryA".into()),
3013            api_addr: None,
3014            ..spec
3015        };
3016        let err = win_opts(&unknown).unwrap_err().to_string();
3017        assert!(err.contains("LoadLibraryA"), "{err}");
3018    }
3019
3020    /// ECO-04: `--plan-chain` always succeeds and names the requirement
3021    /// that failed. This is the exit criterion's fixture.
3022    #[test]
3023    fn plan_chain_on_pe_x64_cmd_reports_set_rdx_with_computed_relaxations() {
3024        let bytes = fixture_bytes("pe-x64-cmd-v6.1.7601");
3025        let spec = ChainSpec {
3026            target: "windows-virtualprotect".into(),
3027            ..ChainSpec::default()
3028        };
3029        let out = plan_chain_bytes(&bytes, None, &ScanRequest::default(), &spec).unwrap();
3030        let plan = &out.plan;
3031        assert!(!plan.feasible);
3032        let rdx = plan.requirement("set_rdx").expect("set_rdx");
3033        assert!(!rdx.satisfied);
3034        assert!(
3035            !rdx.strategies_tried.is_empty(),
3036            "strategies_tried must not be empty"
3037        );
3038        // Computed, not guessed: each relaxation is a real re-scan.
3039        assert!(
3040            !rdx.relaxations.is_empty(),
3041            "at least one computed relaxation"
3042        );
3043        assert!(rdx.relaxations.iter().any(|r| r.param == "depth"));
3044        assert!(rdx.relaxations.iter().any(|r| r.param == "multibr"));
3045        // ...and the requirements this binary DOES meet are listed, with a
3046        // vaddr that is a real gadget of the scan.
3047        assert!(!plan.satisfied_requirements.is_empty());
3048        let rcx = plan
3049            .satisfied_requirements
3050            .iter()
3051            .find(|s| s.id == "set_rcx")
3052            .expect("set_rcx is satisfied on cmd.exe");
3053        assert!(
3054            out.gadget_bytes(rcx.vaddr).is_some(),
3055            "the vaddr resolves in the scan"
3056        );
3057    }
3058
3059    /// ECO-04: `--plan-chain` on a target it cannot even dispatch is still
3060    /// a document, not an error.
3061    #[test]
3062    fn plan_chain_never_fails_for_a_feasible_target() {
3063        let bytes = fixture_bytes("elf-Linux-x64");
3064        for target in ["linux-execve", "linux-mprotect", "linux-srop"] {
3065            let spec = ChainSpec {
3066                target: target.to_string(),
3067                ..ChainSpec::default()
3068            };
3069            let out = plan_chain_bytes(&bytes, None, &ScanRequest::default(), &spec).unwrap();
3070            assert!(out.plan.feasible, "{target}: {:?}", out.plan.error);
3071            assert!(
3072                out.plan.requirements.iter().all(|r| r.satisfied),
3073                "{target}"
3074            );
3075            // A feasible plan does no relaxation re-scans at all.
3076            assert!(out
3077                .plan
3078                .requirements
3079                .iter()
3080                .all(|r| r.relaxations.is_empty()));
3081        }
3082    }
3083
3084    /// ECO-04: `--plan-chain` is a DOCUMENT even when the target is not
3085    /// dispatchable at all. `--ropchain --json` prints the same document
3086    /// when it has to refuse, which is the one-contract rule.
3087    #[test]
3088    fn plan_chain_reports_an_undispatchable_target_as_a_requirement() {
3089        let bytes = fixture_bytes("pe-x64-cmd-v6.1.7601");
3090        let spec = ChainSpec::linux();
3091        let out = plan_chain_bytes(&bytes, None, &ScanRequest::default(), &spec).unwrap();
3092        assert!(!out.plan.feasible);
3093        assert_eq!(
3094            out.plan
3095                .requirements
3096                .iter()
3097                .map(|r| r.id.as_str())
3098                .collect::<Vec<_>>(),
3099            vec!["target_supported"]
3100        );
3101        assert!(out.plan.error.unwrap().contains("not supported yet"));
3102        // ...and a target name that does not exist at all IS a usage error,
3103        // because there is then nothing to plan for.
3104        let spec = ChainSpec {
3105            target: "linux-nonsense".into(),
3106            ..ChainSpec::default()
3107        };
3108        let err = match plan_chain_bytes(&bytes, None, &ScanRequest::default(), &spec) {
3109            Ok(_) => panic!("an unknown target name must be a usage error"),
3110            Err(e) => e.to_string(),
3111        };
3112        assert!(err.contains("unknown chain target"), "{err}");
3113    }
3114
3115    /// CHLX-07: every advertised chain target is dispatchable on both
3116    /// surfaces, and an unknown one names the accepted set.
3117    #[test]
3118    fn chain_targets_are_the_advertised_set() {
3119        assert_eq!(
3120            chain_targets(),
3121            vec![
3122                "linux-execve",
3123                "linux-mprotect",
3124                "linux-syscall",
3125                "linux-ret2libc",
3126                "linux-srop",
3127                "windows-virtualprotect",
3128            ]
3129        );
3130        let bytes = fixture_bytes("elf-Linux-x64");
3131        let spec = ChainSpec {
3132            target: "linux-nonsense".into(),
3133            ..ChainSpec::default()
3134        };
3135        let m = match chain_bytes(&bytes, None, &ScanRequest::default(), &spec) {
3136            Ok(_) => panic!("an unknown target must not build"),
3137            Err(e) => e.to_string(),
3138        };
3139        assert!(m.contains("linux-srop"), "{m}");
3140        assert!(m.contains("windows-virtualprotect"), "{m}");
3141    }
3142
3143    /// CHLX-08: the symmetric warning to the PE GUARD_CF one. It fires for
3144    /// an ET_DYN target with no `--offset`, and not otherwise.
3145    #[test]
3146    fn chlx08_pie_targets_are_warned_about() {
3147        assert!(rf_chain::linux::pie_chain_warning(true, 0, 0)
3148            .unwrap()
3149            .contains("--offset"));
3150        assert!(rf_chain::linux::pie_chain_warning(true, 0, 0x7ffff7a00000).is_none());
3151        assert!(rf_chain::linux::pie_chain_warning(false, 0x400000, 0).is_none());
3152        // ...and rf-core agrees the shipped shared object IS ET_DYN, which
3153        // is what the CLI branches on.
3154        let bytes = fixture_bytes("Linux_lib64.so");
3155        let Target::Elf(b) = load_target(&bytes) else {
3156            panic!("not an ELF");
3157        };
3158        assert_eq!(
3159            b.mitigations().enabled(rf_core::mitigations::PIE),
3160            rf_core::mitigations::Enabled::Yes
3161        );
3162        let bytes = fixture_bytes("elf-Linux-x64");
3163        let Target::Elf(b) = load_target(&bytes) else {
3164            panic!("not an ELF");
3165        };
3166        assert_ne!(
3167            b.mitigations().enabled(rf_core::mitigations::PIE),
3168            rf_core::mitigations::Enabled::Yes
3169        );
3170    }
3171
3172    #[test]
3173    fn chain_builds_on_linux_x64() {
3174        let out = chain_fixture("elf-Linux-x64");
3175        let chain = &out.chain;
3176        assert_eq!(chain.arch, "x64");
3177        assert_eq!(chain.word_size, 8);
3178        chain.validate(&scan_universe(&out), &[]).unwrap();
3179        // Renderers: python script has the ropmaker header; every word
3180        // except string immediates renders as a pack line (padding, like
3181        // every other word, renders at column 0 — ROB-05); JSON exposes the
3182        // full IR.
3183        let py = chain.to_python();
3184        assert!(py.starts_with("#!/usr/bin/env python3\n# execve generated by ROPgadget\n"));
3185        assert!(py.contains("p += b'/bin//sh'"));
3186        assert_eq!(
3187            py.matches("p += pack('<Q',").count(),
3188            chain
3189                .words
3190                .iter()
3191                .filter(|w| w.kind != rf_chain::WordKind::Immediate)
3192                .count()
3193        );
3194        let json = chain.to_json();
3195        assert_eq!(json["arch"], "x64");
3196        assert_eq!(json["words"].as_array().unwrap().len(), chain.words.len());
3197    }
3198
3199    #[test]
3200    fn chain_builds_on_linux_x86() {
3201        let out = chain_fixture("elf-Linux-x86");
3202        let chain = &out.chain;
3203        assert_eq!(chain.arch, "x86");
3204        assert_eq!(chain.word_size, 4);
3205        chain.validate(&scan_universe(&out), &[]).unwrap();
3206        assert!(chain.to_python().contains("pack('<I',"));
3207    }
3208
3209    #[test]
3210    fn chain_gadget_addrs_come_from_scan() {
3211        // Property test: every GadgetAddr word references a vaddr the scan
3212        // actually produced, and the chain's gadget table agrees.
3213        let out = chain_fixture("elf-Linux-x64");
3214        let universe = scan_universe(&out);
3215        for w in &out.chain.words {
3216            if w.kind == rf_chain::WordKind::GadgetAddr {
3217                let g = &out.chain.gadgets[w.source_gadget.unwrap()];
3218                assert_eq!(g.vaddr, w.value);
3219                assert!(
3220                    universe.contains(&w.value),
3221                    "chain gadget {:#x} not in scan output",
3222                    w.value
3223                );
3224            }
3225        }
3226        // The execve chain must end in a syscall gadget.
3227        let last = out.chain.gadgets.last().unwrap();
3228        assert!(last.text.contains("syscall"));
3229    }
3230
3231    #[test]
3232    fn chain_rejects_unsupported_targets() {
3233        // PE x64 → Usage error ("not supported"), mirroring ropmaker.py's
3234        // dispatch which only knows ELF x86/x64.
3235        let err = match chain_bytes(
3236            &fixture_bytes("pe-x64-cmd-v6.1.7601"),
3237            None,
3238            &ScanRequest::default(),
3239            &ChainSpec::linux(),
3240        ) {
3241            Err(e) => e,
3242            Ok(_) => panic!("PE chain build unexpectedly succeeded"),
3243        };
3244        match err {
3245            ScanError::Usage(m) => assert!(m.contains("not supported"), "{m}"),
3246            other => panic!("expected Usage, got {other:?}"),
3247        }
3248        // ELF but wrong arch (ARM64) → same structured refusal.
3249        let err = match chain_bytes(
3250            &fixture_bytes("elf-ARM64-bash"),
3251            None,
3252            &ScanRequest::default(),
3253            &ChainSpec::linux(),
3254        ) {
3255            Err(e) => e,
3256            Ok(_) => panic!("ARM64 chain build unexpectedly succeeded"),
3257        };
3258        assert!(matches!(err, ScanError::Usage(_)));
3259    }
3260
3261    #[test]
3262    fn chain_missing_gadgets_is_structured_error() {
3263        // A gadget the recipe needs and the scan does not hold is a
3264        // ScanError::Chain naming it — ROPgadget prints "Can't find ..."
3265        // and gives up.
3266        //
3267        // The scan is pinned to `depth: 2` deliberately. This used to run
3268        // at the default depth against elf-x64-bash, but CHLX-01's
3269        // fallback strategies now build a chain there, and pinning a
3270        // *shortage* test to a fixture that has since grown a route makes
3271        // the assertion about the fixture rather than about the error
3272        // shape. A two-instruction gadget budget is a shortage no
3273        // fallback can search its way out of; the assertion below is on
3274        // the shape and on the message naming a gadget, not on which one.
3275        let req = ScanRequest {
3276            depth: 2,
3277            ..ScanRequest::default()
3278        };
3279        let err = match chain_bytes(
3280            &fixture_bytes("elf-x64-bash-v4.1.5.1"),
3281            None,
3282            &req,
3283            &ChainSpec::linux(),
3284        ) {
3285            Err(e) => e,
3286            Ok(_) => panic!("bash chain build at depth 2 unexpectedly succeeded"),
3287        };
3288        match err {
3289            ScanError::Chain(m) => {
3290                assert!(m.contains("can't find a suitable gadget"), "{m}");
3291                assert!(m.len() > "can't find a suitable gadget: ".len(), "{m}");
3292            }
3293            other => panic!("expected Chain, got {other:?}"),
3294        }
3295    }
3296
3297    #[test]
3298    fn chain_honours_badbytes() {
3299        // elf-Linux-x64's image base is 0x400000; banning 0x40 must make
3300        // the build fail (every gadget address contains it), proving the
3301        // badbytes constraint reaches the chain builder.
3302        let req = ScanRequest {
3303            badbytes: Some("40".into()),
3304            ..ScanRequest::default()
3305        };
3306        let res = chain_bytes(
3307            &fixture_bytes("elf-Linux-x64"),
3308            None,
3309            &req,
3310            &ChainSpec::linux(),
3311        );
3312        assert!(matches!(res, Err(ScanError::Chain(_))));
3313    }
3314
3315    // -- --chain windows-virtualprotect (Phase 4b) ---------------------------
3316
3317    fn win_spec() -> ChainSpec {
3318        ChainSpec {
3319            target: "windows-virtualprotect".into(),
3320            api_addr: Some("0x7fff12340000".into()),
3321            ..ChainSpec::default()
3322        }
3323    }
3324
3325    #[test]
3326    fn chain_windows_x86_stdcall_full_chain() {
3327        // pe-x86-cmd: stdcall needs no gadgets — the chain is
3328        // [api][ret→shellcode][4 args] and VirtualProtect's ret 0x10
3329        // continues into the shellcode (second-stack frame).
3330        let out = chain_bytes(
3331            &fixture_bytes("pe-x86-cmd-v6.1.7600"),
3332            None,
3333            &ScanRequest::default(),
3334            &win_spec(),
3335        )
3336        .unwrap();
3337        let chain = &out.chain;
3338        assert_eq!(chain.arch, "x86");
3339        assert_eq!(chain.word_size, 4);
3340        let values: Vec<u64> = chain.words.iter().map(|w| w.value).collect();
3341        assert_eq!(values.len(), 6);
3342        assert_eq!(values[0], 0x7fff12340000, "api addr (--api-addr)");
3343        assert_eq!(
3344            values[1], values[2],
3345            "return-to and lpAddress both = shellcode"
3346        );
3347        assert_eq!(values[3], 0x1000, "default dwSize");
3348        assert_eq!(values[4], 0x40, "PAGE_EXECUTE_READWRITE");
3349        // shellcode defaults to the PE's writable .data
3350        assert!(chain.description.contains("VirtualProtect"));
3351        chain
3352            .validate(&std::collections::HashSet::new(), &[])
3353            .unwrap();
3354        // python renderer: 6 pack('<I') words
3355        assert_eq!(chain.to_python().matches("pack('<I',").count(), 6);
3356    }
3357
3358    /// CHWIN-02, on a binary the project ships. `build_win32` used to pass
3359    /// the writable section's vaddr for BOTH the shellcode home and
3360    /// `&lpflOldProtect`, so VirtualProtect wrote the previous-protection
3361    /// DWORD over the first four bytes of the buffer it had just made RWX,
3362    /// and the `ret 0x10` then landed on it. The emulator saw
3363    /// `90909090 -> 04000000` (docs/chain-regressions.md, CHWIN-02-x86).
3364    #[test]
3365    fn chain_windows_x86_out_parameter_does_not_alias_the_shellcode() {
3366        let out = chain_bytes(
3367            &fixture_bytes("pe-x86-cmd-v6.1.7600"),
3368            None,
3369            &ScanRequest::default(),
3370            &win_spec(),
3371        )
3372        .unwrap();
3373        let values: Vec<u64> = out.chain.words.iter().map(|w| w.value).collect();
3374        let shellcode = values[2];
3375        let old = values[5];
3376        assert_eq!(shellcode, 0x4ad24000, "the .data vaddr --info reports");
3377        assert_ne!(old, shellcode, "CHWIN-02: the out-parameter aliases arg1");
3378        assert!(
3379            old < shellcode || old >= shellcode + 4,
3380            "{old:#x} lands in the shellcode's first DWORD"
3381        );
3382        let a = out.assumptions.as_ref().unwrap();
3383        assert_eq!(a.shellcode_addr, shellcode);
3384        assert_eq!(a.old_protect_addr, Some(old));
3385        assert!(out.chain.words[5].comment.contains("NOT the shellcode"));
3386    }
3387
3388    /// CHWIN-06 on the shipped fixture: cmd.exe imports VirtualAlloc, not
3389    /// VirtualProtect (measured with `--info`: VirtualAlloc, VirtualFree,
3390    /// VirtualQuery). `--api-name` selects both the symbol and the argument
3391    /// recipe, so arg3 becomes MEM_COMMIT and arg4 the protection.
3392    #[test]
3393    fn chain_windows_api_name_selects_the_recipe() {
3394        let out = chain_bytes(
3395            &fixture_bytes("pe-x86-cmd-v6.1.7600"),
3396            None,
3397            &ScanRequest::default(),
3398            &ChainSpec {
3399                api_name: Some("virtualalloc".into()), // case-insensitive
3400                ..win_spec()
3401            },
3402        )
3403        .unwrap();
3404        let values: Vec<u64> = out.chain.words.iter().map(|w| w.value).collect();
3405        assert_eq!(values[4], rf_chain::windows::MEM_COMMIT, "flAllocationType");
3406        assert_eq!(values[5], 0x40, "flProtect");
3407        assert!(out.chain.description.contains("VirtualAlloc"));
3408        assert!(out.chain.description.contains("MEM_COMMIT"));
3409        // No out-parameter, so nothing for CHWIN-02 to alias.
3410        assert_eq!(out.assumptions.as_ref().unwrap().old_protect_addr, None);
3411        assert_eq!(out.assumptions.as_ref().unwrap().api_name, "VirtualAlloc");
3412    }
3413
3414    /// CHWIN-04: `--chain-base` changes the layout the invariant enforces,
3415    /// and `--prot` reaches flNewProtect. Both are usage-validated.
3416    #[test]
3417    fn chain_base_and_prot_flags_are_parsed_and_validated() {
3418        let spec = ChainSpec {
3419            chain_base: Some("aligned".into()),
3420            prot: Some("0x20".into()),
3421            ..win_spec()
3422        };
3423        let o = win_opts(&spec).unwrap();
3424        assert_eq!(o.chain_base, rf_chain::windows::ChainBaseParity::Aligned);
3425        assert_eq!(o.new_protect, 0x20);
3426        // Defaults, when the flags are absent.
3427        let d = win_opts(&win_spec()).unwrap();
3428        assert_eq!(
3429            d.chain_base,
3430            rf_chain::windows::ChainBaseParity::ReturnAddress
3431        );
3432        assert_eq!(d.new_protect, 0x40);
3433        assert_eq!(d.api_name, "VirtualProtect");
3434        // The MCP passes snake_case; both surfaces accept both spellings.
3435        for v in ["return-address", "return_address"] {
3436            let o = win_opts(&ChainSpec {
3437                chain_base: Some(v.into()),
3438                ..win_spec()
3439            })
3440            .unwrap();
3441            assert_eq!(
3442                o.chain_base,
3443                rf_chain::windows::ChainBaseParity::ReturnAddress
3444            );
3445        }
3446        // Bad values are usage errors that name the accepted set.
3447        let err = win_opts(&ChainSpec {
3448            chain_base: Some("stack".into()),
3449            ..win_spec()
3450        })
3451        .unwrap_err();
3452        assert!(
3453            matches!(&err, ScanError::Usage(m) if m.contains("aligned")),
3454            "{err:?}"
3455        );
3456        let err = win_opts(&ChainSpec {
3457            api_name: Some("VirtualProtectEx".into()),
3458            ..win_spec()
3459        })
3460        .unwrap_err();
3461        assert!(
3462            matches!(&err, ScanError::Usage(m) if m.contains("VirtualProtect, VirtualAlloc")),
3463            "{err:?}"
3464        );
3465        assert!(win_opts(&ChainSpec {
3466            prot: Some("zz".into()),
3467            ..win_spec()
3468        })
3469        .is_err());
3470    }
3471
3472    /// CHWIN-04's disclosure half on the CLI: `--ropchain --json` carries
3473    /// the assumption the layout was built on, next to the layout.
3474    #[test]
3475    fn chain_json_carries_the_windows_assumptions() {
3476        let out = chain_bytes(
3477            &fixture_bytes("pe-x86-cmd-v6.1.7600"),
3478            None,
3479            &ScanRequest::default(),
3480            &win_spec(),
3481        )
3482        .unwrap();
3483        let v: serde_json::Value = serde_json::from_str(&chain_json(&out)).unwrap();
3484        let a = &v["assumptions"];
3485        assert_eq!(a["chain_base_parity"], "return_address");
3486        assert_eq!(a["chain_base_mod16"], 8);
3487        assert_eq!(a["api_name"], "VirtualProtect");
3488        assert_eq!(a["shellcode_addr"], "0x4ad24000");
3489        assert_ne!(a["old_protect_addr"], a["shellcode_addr"]);
3490        // The IR itself is untouched: same words, same order.
3491        assert_eq!(v["words"].as_array().unwrap().len(), out.chain.words.len());
3492        // A Linux chain makes none of these assumptions and says nothing.
3493        let lin = chain_bytes(
3494            &fixture_bytes("elf-Linux-x64"),
3495            None,
3496            &ScanRequest::default(),
3497            &ChainSpec::linux(),
3498        )
3499        .unwrap();
3500        assert!(lin.assumptions.is_none());
3501        let lv: serde_json::Value = serde_json::from_str(&chain_json(&lin)).unwrap();
3502        assert_eq!(lv["assumptions"], serde_json::Value::Null);
3503    }
3504
3505    #[test]
3506    fn chain_windows_x64_cmd_reports_spike_scarcity() {
3507        // The spike finding: pe-x64-cmd has NO ret-terminated gadget that
3508        // writes rdx/r8/r9. The builder must fail with a structured error
3509        // naming the unpopulatable register and the strategies tried.
3510        let err = chain_bytes(
3511            &fixture_bytes("pe-x64-cmd-v6.1.7601"),
3512            None,
3513            &ScanRequest::default(),
3514            &win_spec(),
3515        )
3516        .err()
3517        .expect("x64 cmd cannot sustain a VirtualProtect chain (spike report)");
3518        match err {
3519            ScanError::Chain(m) => {
3520                assert!(m.contains("cannot populate rdx"), "{m}");
3521                assert!(m.contains("pop rdx"), "{m}");
3522                assert!(m.contains("mov rdx, rax"), "{m}");
3523            }
3524            other => panic!("expected Chain, got {other:?}"),
3525        }
3526    }
3527
3528    #[test]
3529    fn chain_windows_x64_ntoskrnl_full_chain() {
3530        // ring0 target from PLAN sec. 6.2 #5; the spike binary is
3531        // gitignored, so skip gracefully when absent.
3532        let path = format!(
3533            "{}/../../tests/spike-binaries/ntoskrnl.exe",
3534            env!("CARGO_MANIFEST_DIR")
3535        );
3536        let Ok(bytes) = std::fs::read(&path) else {
3537            eprintln!("skipping: tests/spike-binaries/ntoskrnl.exe not present");
3538            return;
3539        };
3540        let out = chain_bytes(&bytes, None, &ScanRequest::default(), &win_spec()).unwrap();
3541        let chain = &out.chain;
3542        assert_eq!(chain.arch, "x64");
3543        assert_eq!(chain.word_size, 8);
3544
3545        // Structure: 4×(pop gadget + arg word), transfer at an ODD index
3546        // under the DEFAULT chain base (`return_address`, CHWIN-04), then
3547        // return-to-shellcode + 4 shadow words.
3548        let call_idx = chain
3549            .words
3550            .iter()
3551            .position(|w| w.comment.contains("--api-addr"))
3552            .unwrap();
3553        assert_eq!(call_idx % 2, 1, "alignment invariant (return_address base)");
3554        assert_eq!(chain.words.len(), call_idx + 1 + 1 + 4);
3555        assert_eq!(chain.words[call_idx].value, 0x7fff12340000);
3556        assert_eq!(
3557            chain.words[call_idx + 1].value,
3558            chain.words[1].value,
3559            "return address = shellcode (arg1)"
3560        );
3561        assert!(chain.words[call_idx + 2..]
3562            .iter()
3563            .all(|w| w.kind == rf_chain::WordKind::Padding));
3564
3565        // CHWIN-01, on a real 20 MB PE: whatever word the API transfer is
3566        // reached through, it is never an inert data word — the preceding
3567        // gadget's `ret` loads it into rip.
3568        let before = &chain.words[call_idx - 1];
3569        assert!(
3570            matches!(
3571                before.kind,
3572                rf_chain::WordKind::GadgetAddr | rf_chain::WordKind::Padding
3573            ),
3574            "{before:?}"
3575        );
3576        if before.kind == rf_chain::WordKind::GadgetAddr {
3577            let g = &chain.gadgets[before.source_gadget.unwrap()];
3578            assert_eq!(g.text, "ret", "the alignment slide must consume itself");
3579        }
3580        chain.verify_stack_accounting().unwrap();
3581
3582        // CHWIN-02: &lpflOldProtect is arg4 (word 7) and must not alias the
3583        // shellcode, which is arg1 (word 1).
3584        let assumptions = out.assumptions.as_ref().expect("windows assumptions");
3585        assert_eq!(assumptions.chain_base_parity, "return_address");
3586        assert_eq!(assumptions.shellcode_addr, chain.words[1].value);
3587        let old = assumptions
3588            .old_protect_addr
3589            .expect("VirtualProtect out-param");
3590        assert_eq!(chain.words[7].value, old);
3591        assert!(
3592            old < chain.words[1].value || old >= chain.words[1].value + 4,
3593            "{old:#x} aliases the shellcode at {:#x}",
3594            chain.words[1].value
3595        );
3596
3597        // Property: every gadget word references a real scan gadget.
3598        let universe: std::collections::HashSet<u64> = out
3599            .outcome
3600            .result
3601            .gadgets
3602            .iter()
3603            .map(|g| g.vaddr.wrapping_add(out.outcome.opts.offset))
3604            .collect();
3605        for w in &chain.words {
3606            if w.kind == rf_chain::WordKind::GadgetAddr {
3607                assert!(universe.contains(&w.value), "{:#x} not in scan", w.value);
3608            }
3609        }
3610        chain.validate(&universe, &[]).unwrap();
3611    }
3612
3613    #[test]
3614    fn chain_windows_rejects_wrong_format_and_unknown_target() {
3615        // windows-virtualprotect on an ELF → structured "not supported".
3616        let err = chain_bytes(
3617            &fixture_bytes("elf-Linux-x64"),
3618            None,
3619            &ScanRequest::default(),
3620            &win_spec(),
3621        )
3622        .err()
3623        .unwrap();
3624        match err {
3625            ScanError::Usage(m) => assert!(m.contains("not supported"), "{m}"),
3626            other => panic!("expected Usage, got {other:?}"),
3627        }
3628        // unknown --chain value → usage error naming valid targets.
3629        let err = chain_bytes(
3630            &fixture_bytes("elf-Linux-x64"),
3631            None,
3632            &ScanRequest::default(),
3633            &ChainSpec {
3634                target: "plan9-forkbomb".into(),
3635                ..ChainSpec::default()
3636            },
3637        )
3638        .err()
3639        .unwrap();
3640        match err {
3641            ScanError::Usage(m) => assert!(m.contains("linux-execve"), "{m}"),
3642            other => panic!("expected Usage, got {other:?}"),
3643        }
3644    }
3645
3646    // -----------------------------------------------------------------
3647    // ROB-06 - input bounds
3648    // -----------------------------------------------------------------
3649
3650    #[test]
3651    fn parse_size_is_decimal_with_binary_suffixes() {
3652        assert_eq!(parse_size("512", "x").unwrap(), 512);
3653        // The whole point: 16 means SIXTEEN. parse_hex would say 22.
3654        assert_eq!(parse_size("16", "x").unwrap(), 16);
3655        assert_eq!(parse_size("1K", "x").unwrap(), 1024);
3656        assert_eq!(parse_size("1k", "x").unwrap(), 1024);
3657        assert_eq!(parse_size("512M", "x").unwrap(), DEFAULT_MAX_FILE_SIZE);
3658        assert_eq!(parse_size("2G", "x").unwrap(), 2 * 1024 * 1024 * 1024);
3659        assert_eq!(parse_size(" 4M ", "x").unwrap(), 4 * 1024 * 1024);
3660        for bad in ["", "0x10", "abc", "-1", "1T", "99999999999999999999G"] {
3661            assert!(parse_size(bad, "--max-file-size").is_err(), "{bad:?}");
3662        }
3663    }
3664
3665    #[test]
3666    fn check_input_metadata_refuses_non_regular_and_oversized() {
3667        let dir = format!("{}/../../tests/fixtures", env!("CARGO_MANIFEST_DIR"));
3668        let meta = std::fs::metadata(&dir).unwrap();
3669        let err = check_input_metadata(&dir, &meta, DEFAULT_MAX_FILE_SIZE).unwrap_err();
3670        assert!(err.contains("directory"), "{err}");
3671
3672        let f = format!("{dir}/elf-Linux-x86");
3673        let meta = std::fs::metadata(&f).unwrap();
3674        let len = meta.len();
3675        // At the limit: allowed. One byte under: refused, naming both
3676        // numbers so the user can raise the cap without guessing.
3677        assert!(check_input_metadata(&f, &meta, len).is_ok());
3678        let err = check_input_metadata(&f, &meta, len - 1).unwrap_err();
3679        assert!(err.contains(&len.to_string()), "{err}");
3680        assert!(err.contains(&(len - 1).to_string()), "{err}");
3681    }
3682
3683    #[test]
3684    fn read_input_file_honours_the_cap() {
3685        let f = format!(
3686            "{}/../../tests/fixtures/elf-Linux-x86",
3687            env!("CARGO_MANIFEST_DIR")
3688        );
3689        assert!(read_input_file(&f, 1024).is_err());
3690        let got = read_input_file(&f, DEFAULT_MAX_FILE_SIZE).unwrap();
3691        assert_eq!(got.len() as u64, std::fs::metadata(&f).unwrap().len());
3692    }
3693
3694    // -----------------------------------------------------------------
3695    // CORE-01 / CORE-03 / CORE-05 - refuse rather than fabricate
3696    // -----------------------------------------------------------------
3697
3698    /// CORE-01: the loader refuses, so no caller can hold an image whose
3699    /// architecture was guessed. The same bytes used to produce a full
3700    /// x86 listing.
3701    #[test]
3702    fn unrecognized_e_machine_is_a_load_error_not_an_x86_guess() {
3703        let mut bytes = fixture_bytes("elf-Linux-x86");
3704        bytes[18] = 0x99;
3705        bytes[19] = 0x99;
3706        let err = scan_bytes(&bytes, None, &ScanRequest::default())
3707            .err()
3708            .expect("must refuse");
3709        match err {
3710            ScanError::Binary(m) => {
3711                assert!(m.contains("0x9999"), "must name the machine type: {m}");
3712            }
3713            other => panic!("expected Binary, got {other:?}"),
3714        }
3715        // ...and --info refuses too, rather than reporting arch "x86".
3716        assert!(info_bytes(&bytes, None, None).is_err());
3717    }
3718
3719    /// CORE-03: `resolve_arch` is the refusal gate, and it is the only
3720    /// place the decision is made (scan, chain and console all route
3721    /// through `prepare_view`).
3722    #[test]
3723    fn fat_macho_needs_an_explicit_arch() {
3724        let bytes = fixture_bytes("UNIVERSAL-x86-x64-libSystem.B.dylib");
3725        let target = load_target(&bytes);
3726        assert!(matches!(target, Target::Universal(_)));
3727
3728        let err = resolve_arch(&target, None, false).unwrap_err();
3729        match err {
3730            ScanError::Usage(m) => {
3731                assert!(m.contains("--arch"), "{m}");
3732                assert!(m.contains("x86_64") && m.contains("i386"), "{m}");
3733            }
3734            other => panic!("expected Usage, got {other:?}"),
3735        }
3736        // --compat opts back into ROPgadget's concatenation.
3737        assert_eq!(resolve_arch(&target, None, true).unwrap(), None);
3738        // Explicit selection, including aliases and case folding.
3739        assert_eq!(
3740            resolve_arch(&target, Some("x86_64"), false).unwrap(),
3741            Some(Arch::X64)
3742        );
3743        assert_eq!(
3744            resolve_arch(&target, Some("AMD64"), false).unwrap(),
3745            Some(Arch::X64)
3746        );
3747        assert_eq!(
3748            resolve_arch(&target, Some("i386"), false).unwrap(),
3749            Some(Arch::X86)
3750        );
3751        assert!(resolve_arch(&target, Some("arm64"), false).is_err());
3752        assert!(resolve_arch(&target, Some("nonesuch"), false).is_err());
3753    }
3754
3755    /// The selected slice really is scanned alone: each slice's gadget set
3756    /// is a strict subset of the concatenation, and the two differ.
3757    #[test]
3758    fn fat_macho_slice_selection_scans_one_slice() {
3759        let bytes = fixture_bytes("UNIVERSAL-x86-x64-libSystem.B.dylib");
3760        let req = |arch: Option<&str>, compat: bool| ScanRequest {
3761            arch: arch.map(str::to_string),
3762            compat,
3763            ..ScanRequest::default()
3764        };
3765        let keys = |r: &ScanOutcome| -> std::collections::HashSet<(u64, Vec<u8>)> {
3766            r.result
3767                .gadgets
3768                .iter()
3769                .map(|g| (g.vaddr, g.bytes.clone()))
3770                .collect()
3771        };
3772        let x64 = scan_bytes(&bytes, None, &req(Some("x86_64"), false)).unwrap();
3773        let x86 = scan_bytes(&bytes, None, &req(Some("i386"), false)).unwrap();
3774        let cat = scan_bytes(&bytes, None, &req(None, true)).unwrap();
3775        let (k64, k86, kc) = (keys(&x64), keys(&x86), keys(&cat));
3776        assert!(!k64.is_empty() && !k86.is_empty());
3777        assert_ne!(k64, k86);
3778        assert!(kc.len() > k64.len());
3779
3780        // This is CORE-03. The concatenation decodes EVERY slice with the
3781        // FIRST slice's decoder (universal.py:92-108, "just return
3782        // whatever is in the first binary"), so the x86_64 slice - first
3783        // in this container - survives intact while the i386 slice is read
3784        // as x86-64. On THIS fixture the two ISAs share most short
3785        // encodings, so the damage is mild and measurable rather than
3786        // catastrophic: 20 of 185 real i386 gadgets are dropped and one
3787        // concatenation entry belongs to neither real slice. (The audit's
3788        // 41%-fabricated figure is for an arm64+x86_64 Apple-silicon
3789        // binary, where the two decoders share nothing; no such fixture is
3790        // in the corpus.) Both directions of the damage are asserted, so
3791        // this fails if the concatenation ever silently becomes the union
3792        // of two honest scans.
3793        assert!(
3794            k64.is_subset(&kc),
3795            "the first slice decodes correctly in the concatenation"
3796        );
3797        let lost: Vec<_> = k86.difference(&kc).collect();
3798        assert!(
3799            !lost.is_empty(),
3800            "the concatenation must LOSE real second-slice gadgets"
3801        );
3802        let real = &k64 | &k86;
3803        let fabricated: Vec<_> = kc.difference(&real).collect();
3804        assert!(
3805            !fabricated.is_empty(),
3806            "the concatenation must contain gadgets belonging to NEITHER real slice"
3807        );
3808    }
3809
3810    /// `--arch` on a single-architecture image is accepted only when it
3811    /// agrees with the image.
3812    #[test]
3813    fn arch_on_a_single_architecture_image_must_agree() {
3814        let target = load_target(&fixture_bytes("elf-Linux-x86"));
3815        assert_eq!(
3816            resolve_arch(&target, Some("i386"), false).unwrap(),
3817            Some(Arch::X86)
3818        );
3819        assert_eq!(resolve_arch(&target, None, false).unwrap(), None);
3820        let err = resolve_arch(&target, Some("arm64"), false).unwrap_err();
3821        match err {
3822            ScanError::Usage(m) => assert!(m.contains("does not match"), "{m}"),
3823            other => panic!("expected Usage, got {other:?}"),
3824        }
3825    }
3826
3827    // -----------------------------------------------------------------
3828    // CRIT-01 / CORE-07 - say it out loud
3829    // -----------------------------------------------------------------
3830
3831    /// `--cfg-aware` on a binary with no landing pads warns instead of
3832    /// letting the user read an unconstrained result as a constrained one.
3833    #[test]
3834    fn cfg_aware_warns_when_ibt_is_not_in_play() {
3835        let bytes = fixture_bytes("pe-x64-cmd-v6.1.7601");
3836        let target = load_target(&bytes);
3837        let view = build_view(&target);
3838        let quiet = scan_warnings(&target, &view, false, false);
3839        assert!(quiet.is_empty(), "{quiet:?}");
3840        let loud = scan_warnings(&target, &view, true, false);
3841        assert_eq!(loud.len(), 1, "{loud:?}");
3842        assert!(loud[0].contains("endbr"), "{}", loud[0]);
3843        assert!(loud[0].contains("GUARD_CF"), "{}", loud[0]);
3844    }
3845
3846    /// CLI-11/`--compat`: the fat-Mach-O escape hatch is never silent.
3847    #[test]
3848    fn compat_fat_macho_scan_is_announced() {
3849        let bytes = fixture_bytes("UNIVERSAL-x86-x64-libSystem.B.dylib");
3850        let target = load_target(&bytes);
3851        let view = build_view(&target);
3852        assert!(scan_warnings(&target, &view, false, false).is_empty());
3853        let w = scan_warnings(&target, &view, false, true);
3854        assert_eq!(w.len(), 1, "{w:?}");
3855        assert!(w[0].contains("FABRICATED"), "{}", w[0]);
3856    }
3857
3858    // -----------------------------------------------------------------
3859    // PERF-05
3860    // -----------------------------------------------------------------
3861
3862    /// A budget that is not hit changes nothing; a budget that is hit
3863    /// reports itself rather than truncating silently.
3864    #[test]
3865    fn max_gadgets_bounds_the_scan_without_changing_an_unbounded_one() {
3866        let bytes = fixture_bytes("macho-x64-ls");
3867        let keys = |o: &ScanOutcome| -> Vec<(u64, Vec<u8>)> {
3868            o.result
3869                .gadgets
3870                .iter()
3871                .map(|g| (g.vaddr, g.bytes.clone()))
3872                .collect()
3873        };
3874        let plain = scan_bytes(&bytes, None, &ScanRequest::default()).unwrap();
3875        let n = plain.result.gadgets.len();
3876        assert!(n > 10);
3877
3878        let generous = scan_bytes(
3879            &bytes,
3880            None,
3881            &ScanRequest {
3882                max_gadgets: Some(n * 100),
3883                ..ScanRequest::default()
3884            },
3885        )
3886        .unwrap();
3887        assert_eq!(keys(&generous), keys(&plain));
3888
3889        let err = scan_bytes(
3890            &bytes,
3891            None,
3892            &ScanRequest {
3893                max_gadgets: Some(5),
3894                ..ScanRequest::default()
3895            },
3896        )
3897        .err()
3898        .expect("budget must trip");
3899        match err {
3900            ScanError::Binary(m) => assert!(m.contains("budget"), "{m}"),
3901            other => panic!("expected Binary, got {other:?}"),
3902        }
3903    }
3904
3905    // -----------------------------------------------------------------
3906    // CLI-11 - the print path
3907    // -----------------------------------------------------------------
3908
3909    /// core.py:110-111: a --noinstr line is the bare address (plus
3910    /// " // bytes" under --dump). The engine still carries the text -
3911    /// --filter and --badbytes need it - so the suppression is the CLI's.
3912    #[test]
3913    fn print_human_suppresses_text_under_noinstr() {
3914        let res = ScanResult {
3915            gadgets: vec![Gadget {
3916                vaddr: 0x0804_8000,
3917                bytes: vec![0x5f, 0xc3],
3918                insns: vec!["pop edi".into(), "ret".into()],
3919                delay_slot: false,
3920                prev: None,
3921                table: rf_scan::TableKind::Rop,
3922            }],
3923            addr_size: 4,
3924            universal_arch: None,
3925            selected_sections: None,
3926        };
3927        let render = |noinstr, dump| {
3928            let mut buf: Vec<u8> = Vec::new();
3929            print_human(&res, noinstr, dump, &mut buf);
3930            String::from_utf8(buf).unwrap()
3931        };
3932        assert!(render(false, false).contains("0x08048000 : pop edi ; ret\n"));
3933        assert!(render(true, false).contains("0x08048000\n"));
3934        assert!(!render(true, false).contains("pop edi"));
3935        assert!(render(true, true).contains("0x08048000 // 5fc3\n"));
3936        assert!(!render(true, true).contains("pop edi"));
3937        assert!(render(false, true).contains("0x08048000 : pop edi ; ret // 5fc3\n"));
3938    }
3939}