Skip to main content

rf_api/
lib.rs

1//! rf-api — the front-end-agnostic request layer of rop-finder.
2//!
3//! Everything both front ends need in order to turn *strings a user typed*
4//! into *a scan, an image report or a ROP chain*: [`ScanRequest`] and its
5//! option building ([`request_options`]), the loader dispatch
6//! ([`load_target`], [`prepare_view`]), the three pipelines
7//! ([`scan_bytes`], [`info_bytes`], [`chain_bytes`]) with their cancellable
8//! twin ([`scan_bytes_cancellable`]), and the v0.4 constraint query layer
9//! ([`query`]).
10//!
11//! # Why this crate exists
12//!
13//! It used to live in `rf-cli`, which is a **binary** crate, and `rf-mcp`
14//! depended on it there. That is not publishable (a binary crate has no
15//! usable library API for a third party), and it had already cost the
16//! project two real defects: the MCP server had to re-implement the option
17//! mapping and the cache key because the CLI's were private, and the
18//! `--align` post-filter (ANCH-02) and the cache char-boundary panic
19//! (ROB-04) each existed in two slightly different copies. `rf-cache` was
20//! split out for the second pair; this crate is the first pair, and it is
21//! the reason `cargo tree -p rop-finder-mcp` no longer mentions `rf-cli`.
22//!
23//! `rf-cli` re-exports everything here, so `rf_cli::ScanRequest` and
24//! `rf_api::ScanRequest` are the same type.
25//!
26//! # Layers
27//!
28//! ```text
29//!   rf-core   loaders, sections, mitigations
30//!   rf-scan   the gadget engine (ScanOptions -> Vec<Gadget>)
31//!   rf-classify  semantics over one gadget
32//!   rf-chain  chain builders over a gadget set
33//!        |
34//!   rf-api   <-- strings in, results out; no I/O policy, no output format
35//!      |  \
36//!   rf-cli   rf-mcp
37//! ```
38//!
39//! This crate deliberately holds **no output formatting** (human text, CSV,
40//! the MCP wire shapes) and **no I/O policy** (the cache directory, path
41//! confinement, the interactive console). Those differ per front end and
42//! are exactly the things that should not be shared.
43//!
44//! # Semver policy
45//!
46//! See [`docs/API-STABILITY.md`](https://github.com/rop-finder/rop-finder/blob/main/docs/API-STABILITY.md).
47//! In short: the item signatures below are covered by semver; the *text* of
48//! an error message, the exact JSON produced by [`info_json`] /
49//! [`plan_json`], and anything marked `#[doc(hidden)]` are not. Pin
50//! `rf-api = "1"` and treat error strings as diagnostics, not as an API.
51//!
52//! # Example
53//!
54//! Scan a raw x86-64 blob and print what came back. `pop rdi ; ret` is
55//! `5f c3`; a real caller passes `std::fs::read("/bin/ls")?` instead of a
56//! byte literal.
57//!
58//! ```
59//! use rf_api::{scan_bytes, ScanRequest};
60//! use rf_core::{Arch, Endianness};
61//!
62//! let bytes = [0x5fu8, 0xc3];
63//! let req = ScanRequest {
64//!     depth: 4,
65//!     ..ScanRequest::default()
66//! };
67//! let out = scan_bytes(&bytes, Some((Arch::X64, Endianness::Little, false)), &req)?;
68//! let texts: Vec<String> = out.result.gadgets.iter().map(|g| g.text()).collect();
69//! assert!(texts.iter().any(|t| t == "pop rdi ; ret"));
70//! # Ok::<(), rf_api::ScanError>(())
71//! ```
72
73// ENG-08: every public item carries documentation.
74#![warn(missing_docs)]
75
76use std::fmt;
77
78use globset::{Glob, GlobSetBuilder};
79use rf_core::{
80    Arch, Binary, Endianness, Image, LoadedBinary, MachOBinary, Mitigations, RawBinary, Section,
81    UniversalBinary,
82};
83use rf_scan::{CancelToken, Gadget, ScanOptions};
84
85mod info;
86// CHWIN-08 #3: the export directory rf-core does not parse.
87pub mod pe_exports;
88pub mod query;
89
90/// ROB-06 default input cap: 512 MiB.
91pub const DEFAULT_MAX_FILE_SIZE: u64 = 512 * 1024 * 1024;
92
93/// Parse a byte count with an optional binary `K`/`M`/`G` suffix
94/// (`--max-file-size`, `--max-memory`). Plain decimal, never hex: these
95/// are sizes a human types, and `--max-file-size 10M` must not silently
96/// become 0x10.
97pub fn parse_size(s: &str, what: &str) -> Result<u64, String> {
98    let t = s.trim();
99    if t.is_empty() {
100        return Err(format!("invalid {what} {s:?}: empty"));
101    }
102    let (digits, mult) = match t.as_bytes()[t.len() - 1] {
103        b'k' | b'K' => (&t[..t.len() - 1], 1024u64),
104        b'm' | b'M' => (&t[..t.len() - 1], 1024 * 1024),
105        b'g' | b'G' => (&t[..t.len() - 1], 1024 * 1024 * 1024),
106        _ => (t, 1),
107    };
108    let n: u64 = digits
109        .trim()
110        .parse()
111        .map_err(|e| format!("invalid {what} {s:?}: {e}"))?;
112    n.checked_mul(mult)
113        .ok_or_else(|| format!("invalid {what} {s:?}: overflows a u64"))
114}
115
116/// ROB-06: decide whether `path` may be read at all, from its metadata
117/// alone — BEFORE a byte is allocated.
118///
119/// Two refusals, both of which `std::fs::read` performs instead of
120/// diagnosing: a non-regular file (character device, FIFO, directory,
121/// socket) has no length, so `read_to_end` grows the buffer until the OS
122/// kills the process (`--binary /dev/zero`: 8.6 GB RSS at 1 s, measured in
123/// ROB-06); and a regular file larger than the cap is materialised in full
124/// before the format is even sniffed.
125///
126/// Split out from [`read_input_file`] so it is unit-testable without a
127/// character device, which Windows CI does not have.
128pub fn check_input_metadata(
129    path: &str,
130    meta: &std::fs::Metadata,
131    max_bytes: u64,
132) -> Result<(), String> {
133    if !meta.is_file() {
134        let kind = if meta.is_dir() {
135            "a directory"
136        } else {
137            "not a regular file (character device, FIFO, socket or symlink loop?)"
138        };
139        return Err(format!(
140            "cannot read {path}: {kind}; rop-finder reads whole files into memory and \
141             refuses inputs with no fixed length"
142        ));
143    }
144    let len = meta.len();
145    if len > max_bytes {
146        return Err(format!(
147            "cannot read {path}: {len} bytes exceeds the --max-file-size limit of \
148             {max_bytes} bytes; re-run with --max-file-size {len} to allow it"
149        ));
150    }
151    Ok(())
152}
153
154/// ROB-06: stat, then read. Never `std::fs::read` a path the caller has
155/// not bounded.
156pub fn read_input_file(path: &str, max_bytes: u64) -> Result<Vec<u8>, String> {
157    let meta = std::fs::metadata(path).map_err(|e| format!("cannot read {path}: {e}"))?;
158    check_input_metadata(path, &meta, max_bytes)?;
159    let bytes = std::fs::read(path).map_err(|e| format!("cannot read {path}: {e}"))?;
160    // TOCTOU: the file may have grown between the stat and the read.
161    if bytes.len() as u64 > max_bytes {
162        return Err(format!(
163            "cannot read {path}: file grew past the --max-file-size limit of {max_bytes} bytes \
164             while it was being read"
165        ));
166    }
167    Ok(bytes)
168}
169
170/// Parse a hexadecimal integer, with an optional `0x`/`0X` prefix.
171///
172/// ALWAYS base 16, prefix or not: `--offset 16` means 0x16, exactly as
173/// ROPgadget reads it. `what` names the flag in the error message.
174///
175/// ```
176/// assert_eq!(rf_api::parse_hex("0x401000", "--base")?, 0x401000);
177/// assert_eq!(rf_api::parse_hex("16", "--offset")?, 0x16);
178/// assert!(rf_api::parse_hex("zz", "--base").is_err());
179/// # Ok::<(), String>(())
180/// ```
181pub fn parse_hex(s: &str, what: &str) -> Result<u64, String> {
182    let t = s.trim().trim_start_matches("0x").trim_start_matches("0X");
183    u64::from_str_radix(t, 16).map_err(|e| format!("invalid {what} {s:?}: {e}"))
184}
185
186/// ROPgadget --range syntax: "0xSTART-0xEND". "0x0-0x0" means no range.
187pub fn parse_range(s: &str) -> Result<Option<(u64, u64)>, String> {
188    let (a, b) = s
189        .split_once('-')
190        .ok_or_else(|| format!("invalid --range {s:?} (expected 0x...-0x...)"))?;
191    let start = parse_hex(a, "--range start")?;
192    let end = parse_hex(b, "--range end")?;
193    if start == 0 && end == 0 {
194        return Ok(None);
195    }
196    if start > end {
197        return Err(format!("invalid --range {s:?} (start > end)"));
198    }
199    Ok(Some((start, end)))
200}
201
202/// ROPgadget --badbytes syntax: "bb|bb|lo-hi" (hex bytes, ranges inclusive).
203pub fn parse_badbytes(s: &str) -> Result<Vec<u8>, String> {
204    let mut out = Vec::new();
205    for part in s.split('|') {
206        if part.is_empty() {
207            continue; // ROPgadget ignores empty items
208        }
209        if let Some((lo, hi)) = part.split_once('-') {
210            let lo = parse_hex(lo, "--badbytes range low")?;
211            let hi = parse_hex(hi, "--badbytes range high")?;
212            if lo > 0xff || hi > 0xff || lo > hi {
213                return Err(format!("invalid --badbytes range {part:?}"));
214            }
215            out.extend((lo as u8)..=(hi as u8));
216        } else {
217            let b = parse_hex(part, "--badbytes byte")?;
218            if b > 0xff {
219                return Err(format!("invalid --badbytes byte {part:?}"));
220            }
221            out.push(b as u8);
222        }
223    }
224    Ok(out)
225}
226
227/// rop-finder's own architecture spelling, as it appears in `--info` and
228/// in JSON gadget records: `"x86"`, `"x64"`, `"arm-thumb"`, `"mips32"`.
229///
230/// Distinct from [`rf_core::Arch::slice_name`], which is the Mach-O
231/// spelling `--arch` accepts (`i386`, `x86_64`).
232///
233/// ```
234/// use rf_core::Arch;
235/// assert_eq!(rf_api::arch_name(Arch::X64), "x64");
236/// assert_eq!(Arch::X64.slice_name(), "x86_64");
237/// ```
238pub fn arch_name(arch: Arch) -> &'static str {
239    match arch {
240        Arch::X86 => "x86",
241        Arch::X64 => "x64",
242        Arch::Arm => "arm",
243        Arch::ArmThumb => "arm-thumb",
244        Arch::Arm64 => "arm64",
245        Arch::Mips32 => "mips32",
246        Arch::Mips64 => "mips64",
247        Arch::Ppc32 => "ppc32",
248        Arch::Ppc64 => "ppc64",
249        Arch::Sparc => "sparc",
250        Arch::Sparc64 => "sparc64",
251        Arch::SparcV9 => "sparcv9",
252        Arch::RiscV32 => "riscv32",
253        Arch::RiscV64 => "riscv64",
254    }
255}
256
257/// `"little"` or `"big"`, as `--info` spells it.
258pub fn endian_name(e: Endianness) -> &'static str {
259    match e {
260        Endianness::Little => "little",
261        Endianness::Big => "big",
262    }
263}
264
265/// A loaded binary before it is flattened into a scan view.
266pub enum Target {
267    /// An ELF image.
268    Elf(rf_core::ElfBinary),
269    /// A PE/COFF image.
270    Pe(rf_core::PeBinary),
271    /// A single-architecture Mach-O image.
272    MachO(MachOBinary),
273    /// A fat (Universal) Mach-O container; pick a slice with
274    /// [`resolve_arch`] before scanning.
275    Universal(UniversalBinary),
276    /// A flat blob loaded with an explicit architecture.
277    Raw(RawBinary),
278}
279
280/// Format-agnostic scan view over a loaded image.
281///
282/// For single-image binaries `regions` is exactly the image's
283/// `exec_scan_regions()` (ROPgadget parity path). For Universal binaries
284/// ROPgadget UNIVERSAL semantics apply (loaders/universal.py:77-108): the
285/// exec regions of every slice concatenated into one scan, using the FIRST
286/// slice's arch/mode/endianness — getArch/getArchMode/getEndian "just
287/// return whatever is in the first binary".
288///
289/// `named_exec` holds the named executable sections (`exec_sections()`)
290/// used by `--section` filtering and by the JSON `section` field. When
291/// `--section` is given, `regions` is replaced with the matching subset of
292/// `named_exec`.
293pub struct RegionView {
294    arch: Arch,
295    /// The byte order gadgets are decoded with.
296    pub endian: Endianness,
297    /// The view's image base, after any `--base` rebase.
298    pub base: u64,
299    /// The image's entry point, after any `--base` rebase.
300    pub entry: u64,
301    /// The regions the scanner walks. Replaced by the `--section` subset
302    /// when `--section` was given.
303    pub regions: Vec<Section>,
304    /// Every named executable section, for `--section` matching and for the
305    /// JSON `section` field.
306    pub named_exec: Vec<Section>,
307    /// True for Universal (multi-slice) binaries (JSON arch field).
308    pub universal: bool,
309}
310
311/// CORE-03/CORE-05 — resolve `--arch` against a loaded target.
312///
313/// Returns the architecture whose slice should be scanned, or a usage
314/// error. The three refusals are all deliberate:
315///
316///   * a multi-slice fat Mach-O with no `--arch` is REFUSED, not guessed.
317///     ROPgadget concatenates every slice's executable regions and
318///     disassembles the lot with the FIRST slice's decoder
319///     (`universal.py:92-108`). On an Apple-silicon x86_64+arm64e binary
320///     that means the arm64 slice is read as x86-64: measured on
321///     `/bin/ls`, 202 of 491 gadgets (41% of the output) are x86
322///     misreadings of ARM64 instructions, printed at addresses in the same
323///     range as the genuine ones so the user cannot separate them.
324///   * `--arch` naming a slice the container does not hold is an error
325///     that lists what it does hold (rf-core's message).
326///   * `--arch` on a non-fat image is accepted only when it agrees with
327///     the image's own architecture, so it can be left in a script without
328///     silently selecting nothing.
329pub fn resolve_arch(
330    target: &Target,
331    arch: Option<&str>,
332    compat: bool,
333) -> Result<Option<Arch>, ScanError> {
334    let named = match arch {
335        Some(a) => Some(Arch::from_slice_name(a).ok_or_else(|| {
336            ScanError::Usage(format!(
337                "unknown --arch {a:?}; expected an architecture slice name such as \
338                 x86_64, i386, arm64, arm, ppc, ppc64"
339            ))
340        })?),
341        None => None,
342    };
343    match target {
344        Target::Universal(u) => match named {
345            Some(a) => {
346                u.select(a).map_err(|e| ScanError::Usage(e.to_string()))?;
347                Ok(Some(a))
348            }
349            None => {
350                if u.needs_arch_selection() && !compat {
351                    let available = u
352                        .slice_infos()
353                        .iter()
354                        .map(|s| s.name())
355                        .collect::<Vec<_>>()
356                        .join(", ");
357                    Err(ScanError::Usage(format!(
358                        "universal (fat Mach-O) binary holds {} architecture slices \
359                         ({available}); pass --arch <slice> to choose one. Refusing to scan \
360                         the concatenation: the slices' virtual address ranges overlap and \
361                         every slice but the first would be disassembled with the wrong \
362                         decoder, so most of the output would be fabricated",
363                        u.slices().len()
364                    )))
365                } else {
366                    Ok(None)
367                }
368            }
369        },
370        other => match named {
371            None => Ok(None),
372            Some(a) => {
373                let actual = build_view(other).arch();
374                if a == actual {
375                    Ok(Some(a))
376                } else {
377                    Err(ScanError::Usage(format!(
378                        "--arch {} does not match this binary: it is {}. --arch selects a \
379                         slice of a fat (Universal) Mach-O; it does not reinterpret a \
380                         single-architecture image (use --rawArch for that)",
381                        a.slice_name(),
382                        actual.slice_name()
383                    )))
384                }
385            }
386        },
387    }
388}
389
390/// [`build_view`] with a fat-Mach-O slice already chosen. `arch` comes
391/// from [`resolve_arch`]; `None` keeps the legacy whole-container view,
392/// which is only reachable for a single-slice container.
393pub fn build_view_selected(target: &Target, arch: Option<Arch>) -> RegionView {
394    match (target, arch) {
395        (Target::Universal(u), Some(a)) => match u.select(a) {
396            Ok(slice) => RegionView {
397                arch: slice.arch(),
398                endian: slice.endianness(),
399                base: slice.image_base(),
400                entry: slice.entry(),
401                regions: slice.exec_scan_regions().to_vec(),
402                named_exec: slice.exec_sections().into_iter().cloned().collect(),
403                // Still flagged universal so the JSON output keeps naming
404                // the architecture the gadgets were decoded with.
405                universal: true,
406            },
407            // resolve_arch validated the slice exists; if it somehow did
408            // not, fall back rather than panic.
409            Err(_) => build_view(target),
410        },
411        _ => build_view(target),
412    }
413}
414
415/// Flatten a loaded [`Target`] into the [`RegionView`] the scanner walks.
416///
417/// For a fat Mach-O this takes ROPgadget's whole-container view; use
418/// [`build_view_selected`] with a slice from [`resolve_arch`] instead.
419pub fn build_view(target: &Target) -> RegionView {
420    match target {
421        Target::Elf(b) => RegionView::single(
422            Image::arch(b),
423            Image::endianness(b),
424            b.image_base(),
425            b.entry(),
426            b.exec_scan_regions(),
427            b.exec_sections(),
428        ),
429        Target::Pe(b) => RegionView::single(
430            Image::arch(b),
431            Image::endianness(b),
432            b.image_base(),
433            b.entry(),
434            b.exec_scan_regions(),
435            b.exec_sections(),
436        ),
437        Target::MachO(b) => RegionView::single(
438            Image::arch(b),
439            Image::endianness(b),
440            b.image_base(),
441            b.entry(),
442            b.exec_scan_regions(),
443            b.exec_sections(),
444        ),
445        Target::Raw(b) => RegionView::single(
446            Image::arch(b),
447            Image::endianness(b),
448            b.image_base(),
449            b.entry(),
450            b.exec_scan_regions(),
451            b.exec_sections(),
452        ),
453        Target::Universal(u) => {
454            let first = &u.slices()[0];
455            RegionView {
456                arch: first.arch(),
457                endian: first.endianness(),
458                base: first.image_base(),
459                entry: first.entry(),
460                regions: u.all_exec_scan_regions().into_iter().cloned().collect(),
461                named_exec: u
462                    .slices()
463                    .iter()
464                    .flat_map(|s| s.exec_sections().into_iter().cloned())
465                    .collect(),
466                universal: true,
467            }
468        }
469    }
470}
471
472impl RegionView {
473    fn single(
474        arch: Arch,
475        endian: Endianness,
476        base: u64,
477        entry: u64,
478        regions: &[Section],
479        named_exec: Vec<&Section>,
480    ) -> Self {
481        RegionView {
482            arch,
483            endian,
484            base,
485            entry,
486            regions: regions.to_vec(),
487            named_exec: named_exec.into_iter().cloned().collect(),
488            universal: false,
489        }
490    }
491}
492
493impl Image for RegionView {
494    fn arch(&self) -> Arch {
495        self.arch
496    }
497    fn endianness(&self) -> Endianness {
498        self.endian
499    }
500    fn image_base(&self) -> u64 {
501        self.base
502    }
503    fn entry(&self) -> u64 {
504        self.entry
505    }
506    fn exec_sections(&self) -> Vec<&Section> {
507        self.named_exec.iter().collect()
508    }
509    fn exec_scan_regions(&self) -> &[Section] {
510        &self.regions
511    }
512    /// Uniform slide of the whole view (for Universal: all slices slide by
513    /// the same delta — our --base extension; ROPgadget has no --base for
514    /// Universal).
515    fn rebase(&mut self, new_base: u64) {
516        let delta = new_base.wrapping_sub(self.base);
517        for s in &mut self.regions {
518            s.vaddr = s.vaddr.wrapping_add(delta);
519        }
520        for s in &mut self.named_exec {
521            s.vaddr = s.vaddr.wrapping_add(delta);
522        }
523        self.entry = self.entry.wrapping_add(delta);
524        self.base = new_base;
525    }
526}
527
528/// `--section` selection: keep the named exec sections whose name matches
529/// any glob pattern. Returns the matched sections plus a flag telling
530/// whether the binary only has synthetic fallback names (`PT_LOAD#n`,
531/// i.e. a stripped ELF without a section table).
532pub fn select_sections(
533    named_exec: &[Section],
534    patterns: &[String],
535) -> Result<(Vec<Section>, bool), String> {
536    let mut builder = GlobSetBuilder::new();
537    for p in patterns {
538        let glob = Glob::new(p).map_err(|e| format!("invalid --section pattern {p:?}: {e}"))?;
539        builder.add(glob);
540    }
541    let set = builder
542        .build()
543        .map_err(|e| format!("invalid --section patterns: {e}"))?;
544    let matched: Vec<Section> = named_exec
545        .iter()
546        .filter(|s| set.is_match(&s.name))
547        .cloned()
548        .collect();
549    let fallback_names =
550        !named_exec.is_empty() && named_exec.iter().all(|s| s.name.starts_with("PT_LOAD#"));
551    if matched.is_empty() {
552        let available = named_exec
553            .iter()
554            .map(|s| s.name.as_str())
555            .collect::<Vec<_>>()
556            .join(", ");
557        return Err(format!(
558            "no executable section matches {patterns:?}; available executable sections: {available}"
559        ));
560    }
561    Ok((matched, fallback_names))
562}
563
564/// Everything scannable: one image's gadgets plus its display parameters.
565pub struct ScanResult {
566    /// The gadgets, in the engine's deterministic order.
567    pub gadgets: Vec<Gadget>,
568    /// 4 or 8 - the width addresses are printed at.
569    pub addr_size: usize,
570    /// Some(arch) for Universal binaries (JSON arch field).
571    pub universal_arch: Option<Arch>,
572    /// Sections selected by --section as (name, vaddr, size), used for the
573    /// JSON `section` field. None when --section was not used.
574    pub selected_sections: Option<Vec<(String, u64, u64)>>,
575}
576
577/// `0x`-prefixed lowercase hex, unpadded - the spelling every JSON address
578/// field uses.
579pub fn hexs(v: u64) -> String {
580    format!("0x{v:x}")
581}
582
583fn section_json(s: &Section, delta: u64) -> serde_json::Value {
584    serde_json::json!({
585        "name": s.name,
586        "vaddr": hexs(s.vaddr.wrapping_add(delta)),
587        "size": s.size,
588        "executable": s.executable,
589        "writable": s.writable,
590    })
591}
592
593/// Rebase delta for `--info`: `new_base - image_base` (wrapping, so
594/// `wrapping_add(delta)` reproduces `Image::rebase`).
595fn rebase_delta(image_base: u64, new_base: Option<u64>) -> u64 {
596    new_base.map_or(0, |n| n.wrapping_sub(image_base))
597}
598
599/// Everything `--info` needs to describe one image.
600struct InfoView<'a> {
601    format: &'static str,
602    arch: Arch,
603    endian: Endianness,
604    image_base: u64,
605    entry: u64,
606    sections: &'a [Section],
607    imports: Vec<serde_json::Value>,
608    /// ECO-06: the exploit mitigations, as
609    /// `{name: {enabled: bool|"unknown", evidence, detail}}`.
610    mitigations: &'a Mitigations,
611    /// ECO-06: the symbol table, when the loader has one. `None` (rather
612    /// than `[]`) for a format whose symbols rf-core does not read yet, so
613    /// "no symbols in this file" and "not implemented for this format" are
614    /// distinguishable — the exact confusion the hardcoded empty `imports`
615    /// list created.
616    symbols: Option<Vec<serde_json::Value>>,
617    delta: u64,
618}
619
620fn image_info(v: InfoView) -> serde_json::Value {
621    let mut o = serde_json::json!({
622        "format": v.format,
623        "arch": arch_name(v.arch),
624        "endianness": endian_name(v.endian),
625        "addr_size": v.arch.addr_size(),
626        "image_base": hexs(v.image_base.wrapping_add(v.delta)),
627        "entry": hexs(v.entry.wrapping_add(v.delta)),
628        "sections": v.sections.iter().map(|s| section_json(s, v.delta)).collect::<Vec<_>>(),
629        "imports": v.imports,
630        "mitigations": info::mitigations_json(v.mitigations),
631        "mitigations_order": info::mitigation_order_json(v.mitigations),
632    });
633    let map = o.as_object_mut().expect("json! built an object");
634    // An empty mitigation set is a fact with a reason (a raw blob has no
635    // headers); rendering `{}` alone would read as "nothing is enabled".
636    if let Some(note) = v.mitigations.note() {
637        map.insert("mitigations_note".into(), note.into());
638    }
639    if let Some(syms) = v.symbols {
640        map.insert("symbol_count".into(), syms.len().into());
641        map.insert("symbols".into(), syms.into());
642    }
643    o
644}
645
646fn macho_info(b: &MachOBinary, delta: u64) -> serde_json::Value {
647    image_info(InfoView {
648        format: "macho",
649        arch: b.arch(),
650        endian: b.endianness(),
651        image_base: b.image_base(),
652        entry: b.entry(),
653        sections: b.sections(),
654        imports: Vec::new(),
655        mitigations: b.mitigations(),
656        symbols: None,
657        delta,
658    })
659}
660
661/// PLAN.md §6.4: `--info` payload. Addresses are hex strings (consistent
662/// with gadget vaddrs), sizes are numbers. `--base` is honoured so the
663/// printed addresses match what a scan would emit.
664pub fn info_json(target: &Target, new_base: Option<u64>) -> serde_json::Value {
665    match target {
666        Target::Elf(b) => {
667            let delta = rebase_delta(b.image_base(), new_base);
668            image_info(InfoView {
669                format: "elf",
670                arch: Image::arch(b),
671                endian: Image::endianness(b),
672                image_base: b.image_base(),
673                entry: b.entry(),
674                sections: b.sections(),
675                // ECO-06: this was `Vec::new()` — README documented it as
676                // "PE only; [] otherwise" — so ret2plt/ret2libc needed a
677                // second tool on every ELF. It is now the SHN_UNDEF subset
678                // of .dynsym/.symtab, with the DT_JMPREL GOT slot and a
679                // PLT address where one is provable.
680                imports: b
681                    .imports()
682                    .iter()
683                    .map(|s| info::elf_import_json(s, delta))
684                    .collect(),
685                mitigations: b.mitigations(),
686                symbols: Some(
687                    b.symbols()
688                        .iter()
689                        .map(|s| info::symbol_json(s, delta))
690                        .collect(),
691                ),
692                delta,
693            })
694        }
695        Target::Pe(b) => {
696            let delta = rebase_delta(b.image_base(), new_base);
697            let imports = b
698                .imports()
699                .iter()
700                .map(|i| {
701                    // CHWIN-03: `iat_vaddr` is the IAT slot the loader
702                    // patches (deref this); `hint_name_vaddr` is the
703                    // IMAGE_IMPORT_BY_NAME record holding the name string.
704                    // Before the fix `iat_vaddr` carried the latter.
705                    serde_json::json!({
706                        "dll": i.dll,
707                        "symbol": i.name,
708                        "iat_vaddr": hexs(i.iat_slot_vaddr.wrapping_add(delta)),
709                        "hint_name_vaddr": hexs(i.hint_name_vaddr.wrapping_add(delta)),
710                    })
711                })
712                .collect();
713            image_info(InfoView {
714                format: "pe",
715                arch: Image::arch(b),
716                endian: Image::endianness(b),
717                image_base: b.image_base(),
718                entry: b.entry(),
719                sections: b.sections(),
720                imports,
721                mitigations: b.mitigations(),
722                symbols: None,
723                delta,
724            })
725        }
726        Target::MachO(b) => macho_info(b, rebase_delta(b.image_base(), new_base)),
727        Target::Raw(b) => {
728            // `RawBinary::mitigations()` returns by value (an empty set
729            // carrying its note), so it has to outlive the borrow.
730            let m = b.mitigations();
731            image_info(InfoView {
732                format: "raw",
733                arch: Image::arch(b),
734                endian: Image::endianness(b),
735                image_base: b.image_base(),
736                entry: b.entry(),
737                sections: std::slice::from_ref(b.section()),
738                imports: Vec::new(),
739                mitigations: &m,
740                symbols: None,
741                delta: rebase_delta(b.image_base(), new_base),
742            })
743        }
744        Target::Universal(u) => {
745            // Same convention as RegionView: the view base is the FIRST
746            // slice's image base, so --base slides every slice by
747            // new_base - first_base.
748            let first_base = u.slices()[0].image_base();
749            let delta = rebase_delta(first_base, new_base);
750            // CORE-03: each slice also carries the name `--arch` accepts.
751            // `arch` is rop-finder's internal spelling ("x64"), `slice` is
752            // the Mach-O one ("x86_64"); without both, `--info` tells you a
753            // fat binary has two slices and not what to type to pick one.
754            let slices: Vec<serde_json::Value> = u
755                .slices()
756                .iter()
757                .zip(u.slice_infos())
758                .map(|(s, info)| {
759                    let mut v = macho_info(s, delta);
760                    if let Some(o) = v.as_object_mut() {
761                        o.insert("slice".into(), info.name().into());
762                        o.insert("slice_offset".into(), hexs(info.offset).into());
763                        o.insert("slice_size".into(), info.size.into());
764                    }
765                    v
766                })
767                .collect();
768            serde_json::json!({
769                "format": "universal",
770                "fat64": u.is_fat64(),
771                "arch_selection_required": u.needs_arch_selection(),
772                "slices": slices,
773            })
774        }
775    }
776}
777
778// ---------------------------------------------------------------------------
779// Library API (Phase 3): string-level scan requests shared by the CLI and
780// the rf-mcp MCP server. Error precedence mirrors the CLI exactly:
781// depth/file/raw-spec checks, then option parsing, then binary load, then
782// --base parsing, then --section selection, then the scan itself.
783// ---------------------------------------------------------------------------
784
785/// Structured failure for library callers. The CLI maps `Usage` to exit 1
786/// and `Binary` to exit 2.
787#[derive(Debug, Clone, PartialEq, Eq)]
788pub enum ScanError {
789    /// Bad arguments (unparsable hex/range/badbytes, unknown section, ...).
790    Usage(String),
791    /// Malformed/unsupported binary or scan-time failure.
792    Binary(String),
793    /// Chain generation failure (unsupported target, missing gadgets,
794    /// violated IR invariant). Maps to CLI exit 1.
795    Chain(String),
796}
797
798impl fmt::Display for ScanError {
799    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
800        match self {
801            ScanError::Usage(m) | ScanError::Binary(m) | ScanError::Chain(m) => f.write_str(m),
802        }
803    }
804}
805
806impl std::error::Error for ScanError {}
807
808/// Raw-loader spec: (arch, endianness, thumb) as resolved by the CLI's
809/// `--rawArch/--rawMode/--rawEndian/--thumb` validation.
810pub type RawSpec = (Arch, Endianness, bool);
811
812/// Scan inputs at the same string level as the CLI flags, so both front
813/// ends share parsing and validation.
814#[derive(Debug, Clone)]
815pub struct ScanRequest {
816    /// `--depth`: how many bytes back from an anchor a gadget may start.
817    pub depth: usize,
818    /// Search the ROP anchor table (`--norop` clears it).
819    pub rop: bool,
820    /// Search the JOP anchor table (`--nojop` clears it).
821    pub jop: bool,
822    /// Search the SYS anchor table (`--nosys` clears it).
823    pub sys: bool,
824    /// `--multibr`: allow branches in the middle of a gadget.
825    pub multibr: bool,
826    /// `--only`: a `|`-separated mnemonic set; every instruction must match.
827    pub only: Option<String>,
828    /// `--filter`: a `|`-separated regex alternation, full-matched against
829    /// each mnemonic; a gadget with a match is dropped.
830    pub filter: Option<String>,
831    /// `--range`: `"0xSTART-0xEND"`. `"0x0-0x0"` means no range.
832    pub range: Option<String>,
833    /// `--badbytes`: `"bb|bb|lo-hi"`, rejected in the FINAL address.
834    pub badbytes: Option<String>,
835    /// `--offset` (hex): added to gadget addresses at emission.
836    pub offset: Option<String>,
837    /// `--base` (hex): the image base to rebase to before scanning.
838    pub base: Option<String>,
839    /// `--section`: glob patterns naming the executable sections to scan.
840    pub section: Vec<String>,
841    /// `--thumb`: decode 32-bit ARM in T32 mode.
842    pub thumb: bool,
843    /// CFG/CET-aware scan (Phase 4b): keep only endbr64/endbr32-entering
844    /// gadgets.
845    pub cfg_aware: bool,
846    /// ROPgadget --align: anchor-stepping alignment override (engine
847    /// semantics, gadgets.py:66-67 — NOT a post-filter).
848    pub align: Option<usize>,
849    /// ROPgadget --callPreceded: capture prev bytes for the CLI filter.
850    pub call_preceded: bool,
851    /// ROPgadget --all: skip dedup.
852    pub all: bool,
853    /// ROPgadget --noinstr: skip dedup and sort; print bare addresses.
854    pub noinstr: bool,
855    /// Fat Mach-O slice selection (CORE-03/CORE-05), as the `--arch`
856    /// spelling (`x86_64`, `arm64`, ...). `None` on a multi-slice container
857    /// is a REFUSAL, not a guess.
858    pub arch: Option<String>,
859    /// PERF-05 `--max-gadgets`: abort with a budget error once this many
860    /// gadgets have been accepted. `None` = unbounded.
861    pub max_gadgets: Option<usize>,
862    /// PERF-05 `--max-memory`: abort with a budget error once the retained
863    /// gadgets are estimated to exceed this many heap bytes.
864    pub max_memory: Option<usize>,
865    /// `--compat`: reproduce ROPgadget bug-for-bug where rop-finder
866    /// deliberately differs (today: scan a multi-slice fat Mach-O as the
867    /// concatenation instead of refusing it).
868    pub compat: bool,
869}
870
871impl Default for ScanRequest {
872    fn default() -> Self {
873        ScanRequest {
874            depth: 10,
875            rop: true,
876            jop: true,
877            sys: true,
878            multibr: false,
879            only: None,
880            filter: None,
881            range: None,
882            badbytes: None,
883            offset: None,
884            base: None,
885            section: Vec::new(),
886            thumb: false,
887            cfg_aware: false,
888            align: None,
889            call_preceded: false,
890            all: false,
891            noinstr: false,
892            arch: None,
893            max_gadgets: None,
894            max_memory: None,
895            compat: false,
896        }
897    }
898}
899
900/// Everything a scan produces, plus the resolved options (needed for the
901/// offset-aware JSON `section` lookup) and the stripped-ELF warning flag.
902pub struct ScanOutcome {
903    /// The gadgets and their display parameters.
904    pub result: ScanResult,
905    /// The engine options the request resolved to - carry these into a
906    /// cache key or a JSON `section` lookup rather than re-deriving them.
907    pub opts: ScanOptions,
908    /// True when --section matched only synthetic `PT_LOAD#n` names.
909    pub fallback_names: bool,
910}
911
912impl From<LoadedBinary> for Target {
913    fn from(l: LoadedBinary) -> Self {
914        match l {
915            LoadedBinary::Elf(b) => Target::Elf(b),
916            LoadedBinary::Pe(b) => Target::Pe(b),
917            LoadedBinary::MachO(b) => Target::MachO(b),
918            LoadedBinary::Raw(b) => Target::Raw(b),
919            LoadedBinary::Universal(u) => Target::Universal(u),
920        }
921    }
922}
923
924/// Load `bytes` into a [`Target`]; `raw` forces the raw loader
925/// (binary.py:32-49 — --rawArch wins over magic-byte detection).
926pub fn load_target(bytes: &[u8], raw: Option<RawSpec>) -> Result<Target, ScanError> {
927    if let Some((arch, endian, _)) = raw {
928        return Ok(Target::Raw(RawBinary::new(bytes, arch, endian)));
929    }
930    Binary::load(bytes)
931        .map(Target::from)
932        .map_err(|e| ScanError::Binary(e.to_string()))
933}
934
935/// Cancellation and resource limits layered on top of a [`ScanRequest`].
936///
937/// A [`ScanRequest`] describes *what to scan*; this describes *how far the
938/// caller is willing to let it run*. The CLI never sets one (it has a
939/// process to kill); the MCP server always does, because a request that
940/// cannot be stopped is a denial of service against the host (MCP-03).
941///
942/// `max_gadgets`/`max_memory` here OVERRIDE the request's own budgets when
943/// they are `Some`, so a server can cap a client that asked for more.
944///
945/// ```
946/// use rf_api::ScanBudget;
947/// use rf_scan::CancelToken;
948///
949/// let cancel = CancelToken::new();
950/// let budget = ScanBudget {
951///     cancel: cancel.clone(),
952///     max_gadgets: Some(10_000),
953///     ..ScanBudget::default()
954/// };
955/// assert_eq!(budget.max_gadgets, Some(10_000));
956/// cancel.cancel(); // from another thread, mid-scan
957/// ```
958#[derive(Debug, Clone, Default)]
959pub struct ScanBudget {
960    /// Observed by [`rf_scan::scan_bounded`]'s hot loops. Default: a token
961    /// that is never set.
962    pub cancel: CancelToken,
963    /// Hard cap on accepted gadgets; overrides [`ScanRequest::max_gadgets`].
964    pub max_gadgets: Option<usize>,
965    /// Hard cap on estimated retained bytes; overrides
966    /// [`ScanRequest::max_memory`].
967    pub max_memory: Option<usize>,
968}
969
970/// Turn a [`ScanRequest`] into engine [`ScanOptions`], with no budget and
971/// no cancellation.
972///
973/// This is where every string field of the request is parsed
974/// (`--range`, `--badbytes`, `--offset`, the `|`-separated `--only` and
975/// `--filter` alternations), so a malformed value is a
976/// [`ScanError::Usage`] before any file is read.
977///
978/// ```
979/// use rf_api::{request_options, ScanRequest};
980///
981/// let req = ScanRequest {
982///     depth: 6,
983///     badbytes: Some("0a|0d".to_string()),
984///     offset: Some("0x1000".to_string()),
985///     ..ScanRequest::default()
986/// };
987/// let opts = request_options(&req, None)?;
988/// assert_eq!(opts.depth, 6);
989/// assert_eq!(opts.badbytes, vec![0x0a, 0x0d]);
990/// assert_eq!(opts.offset, 0x1000);
991/// # Ok::<(), rf_api::ScanError>(())
992/// ```
993pub fn request_options(req: &ScanRequest, raw: Option<RawSpec>) -> Result<ScanOptions, ScanError> {
994    request_options_with(req, raw, &ScanBudget::default())
995}
996
997/// [`request_options`] with a [`ScanBudget`] wired in.
998///
999/// The MCP server used to carry its own copy of this mapping because the
1000/// CLI's was private and hard-coded `CancelToken::never()`; the copy was
1001/// guarded by a test that scanned four request shapes both ways and
1002/// compared the gadget lists. The mapping is now written once and that
1003/// test still runs against it.
1004pub fn request_options_with(
1005    req: &ScanRequest,
1006    raw: Option<RawSpec>,
1007    budget: &ScanBudget,
1008) -> Result<ScanOptions, ScanError> {
1009    if req.depth < 2 {
1010        return Err(ScanError::Usage("--depth must be >= 2".to_string()));
1011    }
1012    let usage = |e: String| ScanError::Usage(e);
1013    let mut opts = ScanOptions {
1014        depth: req.depth,
1015        rop: req.rop,
1016        jop: req.jop,
1017        sys: req.sys,
1018        multibr: req.multibr,
1019        only: req
1020            .only
1021            .as_deref()
1022            .map(|s| s.split('|').map(|x| x.to_string()).collect()),
1023        range: match &req.range {
1024            Some(r) => parse_range(r).map_err(usage)?,
1025            None => None,
1026        },
1027        badbytes: match &req.badbytes {
1028            Some(b) => parse_badbytes(b).map_err(usage)?,
1029            None => Vec::new(),
1030        },
1031        filter: req
1032            .filter
1033            .as_deref()
1034            .map(|s| s.split('|').map(|x| x.to_string()).collect())
1035            .unwrap_or_default(),
1036        offset: match &req.offset {
1037            Some(o) => parse_hex(o, "--offset").map_err(usage)?,
1038            None => 0,
1039        },
1040        thumb: req.thumb,
1041        cfg_aware: req.cfg_aware,
1042        align: req.align,
1043        call_preceded: req.call_preceded,
1044        all: req.all,
1045        noinstr: req.noinstr,
1046        parallel: true,
1047        // The CLI splits --filter on '|' above; rf-scan rejoins the parts
1048        // and compiles ROPgadget's anchored `({...})$` itself, so there is
1049        // nothing to pre-compile here.
1050        filter_re: None,
1051        cancel: budget.cancel.clone(),
1052        max_gadgets: budget.max_gadgets.or(req.max_gadgets),
1053        max_memory: budget.max_memory.or(req.max_memory),
1054    };
1055    if let Some((_, _, raw_thumb)) = raw {
1056        opts.thumb = opts.thumb || raw_thumb;
1057    }
1058    Ok(opts)
1059}
1060
1061/// Build the scan view for `target`, applying `--base` rebase and
1062/// Selected-section table entry: (name, vaddr, size) — used for the JSON
1063/// `section` field lookup.
1064pub type SectionEntry = (String, u64, u64);
1065
1066/// Result of [`prepare_view`]: the scan view, the selected-section table
1067/// (when `--section` was used), and the stripped-ELF fallback-name flag.
1068pub struct PreparedView {
1069    /// The view to scan.
1070    pub view: RegionView,
1071    /// The `--section` table, when `--section` was used.
1072    pub selected_sections: Option<Vec<SectionEntry>>,
1073    /// True when `--section` matched only synthetic `PT_LOAD#n` names.
1074    pub fallback_names: bool,
1075}
1076
1077/// Build the scan view for `target`, applying `--arch` slice selection,
1078/// `--base` rebase and `--section` selection.
1079pub fn prepare_view(
1080    target: &Target,
1081    base: Option<u64>,
1082    sections: &[String],
1083    arch: Option<&str>,
1084    compat: bool,
1085) -> Result<PreparedView, ScanError> {
1086    let slice = resolve_arch(target, arch, compat)?;
1087    let mut view = build_view_selected(target, slice);
1088    if let Some(base) = base {
1089        view.rebase(base);
1090    }
1091    let mut selected_sections = None;
1092    let mut fallback_names = false;
1093    if !sections.is_empty() {
1094        let (matched, fb) =
1095            select_sections(&view.named_exec, sections).map_err(ScanError::Usage)?;
1096        fallback_names = fb;
1097        selected_sections = Some(
1098            matched
1099                .iter()
1100                .map(|s| (s.name.clone(), s.vaddr, s.size))
1101                .collect(),
1102        );
1103        view.regions = matched;
1104    }
1105    Ok(PreparedView {
1106        view,
1107        selected_sections,
1108        fallback_names,
1109    })
1110}
1111
1112/// Full scan pipeline over in-memory bytes: options → load → view → scan.
1113pub fn scan_bytes(
1114    bytes: &[u8],
1115    raw: Option<RawSpec>,
1116    req: &ScanRequest,
1117) -> Result<ScanOutcome, ScanError> {
1118    let opts = request_options(req, raw)?;
1119    let target = load_target(bytes, raw)?;
1120    let base = req
1121        .base
1122        .as_deref()
1123        .map(|b| parse_hex(b, "--base"))
1124        .transpose()
1125        .map_err(ScanError::Usage)?;
1126    let prepared = prepare_view(&target, base, &req.section, req.arch.as_deref(), req.compat)?;
1127    let view = prepared.view;
1128    let selected_sections = prepared.selected_sections;
1129    let fallback_names = prepared.fallback_names;
1130    let universal_arch = view.universal.then_some(view.arch());
1131    let gadgets = run_scan_engine(&view, &opts).map_err(ScanError::Binary)?;
1132    Ok(ScanOutcome {
1133        result: ScanResult {
1134            gadgets,
1135            addr_size: view.addr_size(),
1136            universal_arch,
1137            selected_sections,
1138        },
1139        opts,
1140        fallback_names,
1141    })
1142}
1143
1144/// Everything a cancellable scan produced.
1145///
1146/// The same facts [`ScanOutcome`] carries, minus the resolved
1147/// [`ScanOptions`] and plus the `--offset` on its own, because a caller
1148/// that is streaming gadgets back to a client needs the offset (to map an
1149/// address to its section) and nothing else from the option set.
1150pub struct ScanProduct {
1151    /// The gadgets, in the engine's deterministic order.
1152    pub gadgets: Vec<Gadget>,
1153    /// 4 or 8 — the width addresses are printed at.
1154    pub addr_size: usize,
1155    /// `Some(arch)` when the image was a fat Mach-O.
1156    pub universal_arch: Option<Arch>,
1157    /// The `--section` table, when `--section` was used.
1158    pub selected_sections: Option<Vec<SectionEntry>>,
1159    /// True when `--section` matched only synthetic `PT_LOAD#n` names.
1160    pub fallback_names: bool,
1161    /// The resolved `--offset`; gadget ids are keyed on the UNSLID vaddr.
1162    pub offset: u64,
1163}
1164
1165/// How [`scan_bytes_cancellable`] failed.
1166///
1167/// Two halves, because a front end reports them differently: a
1168/// [`ScanError`] is the caller's fault (a bad `--range`, an unsupported
1169/// container) and an [`rf_scan::Error`] happened to a scan that had already
1170/// started — cancelled, or over budget.
1171#[derive(Debug)]
1172pub enum ScanFailure {
1173    /// The request could not be turned into a scan.
1174    Request(ScanError),
1175    /// The engine stopped: cancelled, over budget, or a decode failure.
1176    Engine(rf_scan::Error),
1177}
1178
1179impl From<ScanError> for ScanFailure {
1180    fn from(e: ScanError) -> Self {
1181        ScanFailure::Request(e)
1182    }
1183}
1184
1185impl fmt::Display for ScanFailure {
1186    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1187        match self {
1188            ScanFailure::Request(e) => write!(f, "{e}"),
1189            ScanFailure::Engine(e) => write!(f, "{e}"),
1190        }
1191    }
1192}
1193
1194impl std::error::Error for ScanFailure {}
1195
1196/// [`scan_bytes`] with a [`ScanBudget`] threaded into the engine, so the
1197/// scan can be stopped from another thread and capped in gadgets and
1198/// memory.
1199///
1200/// This routes through [`rf_scan::scan_bounded`], one of the two entry
1201/// points that observe the cancel token; [`scan_bytes`] uses the unbounded
1202/// `scan_binary` when no budget is set. The two agree gadget for gadget on
1203/// the same request — `rf-mcp`'s `scan_matches_the_cli_pipeline` test scans
1204/// four request shapes both ways and requires identical lists.
1205///
1206/// The raw-loader spec is not a parameter: a cancellable scan is what a
1207/// server runs, and `--rawArch` reinterpretation is a local-shell decision.
1208///
1209/// ```
1210/// use rf_api::{scan_bytes_cancellable, ScanBudget, ScanRequest};
1211/// use rf_scan::CancelToken;
1212///
1213/// let cancel = CancelToken::new();
1214/// cancel.cancel(); // already cancelled: the scan stops immediately
1215/// let budget = ScanBudget { cancel, ..ScanBudget::default() };
1216/// let elf = std::fs::read(concat!(
1217///     env!("CARGO_MANIFEST_DIR"),
1218///     "/../../tests/fixtures/elf-Linux-x64"
1219/// ));
1220/// if let Ok(bytes) = elf {
1221///     let err = scan_bytes_cancellable(&bytes, &ScanRequest::default(), &budget)
1222///         .err()
1223///         .expect("a cancelled scan cannot succeed");
1224///     assert!(matches!(err, rf_api::ScanFailure::Engine(rf_scan::Error::Cancelled)));
1225/// }
1226/// ```
1227pub fn scan_bytes_cancellable(
1228    bytes: &[u8],
1229    req: &ScanRequest,
1230    budget: &ScanBudget,
1231) -> Result<ScanProduct, ScanFailure> {
1232    let opts = request_options_with(req, None, budget)?;
1233    let target = load_target(bytes, None)?;
1234    let base = req
1235        .base
1236        .as_deref()
1237        .map(|b| parse_hex(b, "--base"))
1238        .transpose()
1239        .map_err(ScanError::Usage)?;
1240    let prepared = prepare_view(&target, base, &req.section, req.arch.as_deref(), req.compat)?;
1241    let view = prepared.view;
1242    let universal_arch = view.universal.then(|| Image::arch(&view));
1243    let gadgets = rf_scan::scan_bounded(&view, &opts).map_err(ScanFailure::Engine)?;
1244    Ok(ScanProduct {
1245        gadgets,
1246        addr_size: view.addr_size(),
1247        universal_arch,
1248        selected_sections: prepared.selected_sections,
1249        fallback_names: prepared.fallback_names,
1250        offset: opts.offset,
1251    })
1252}
1253
1254/// Everything the user has to be told BEFORE reading a gadget listing.
1255///
1256/// Each of these existed as a silent behaviour before v0.2.0, and each one
1257/// makes the listing mean something different from what it looks like:
1258///
1259///   * CRIT-01 — `--cfg-aware` on a binary with no `endbr32`/`endbr64`
1260///     landing pads at all. The flag then constrains nothing, and a user
1261///     who believes it does will conclude the JOP surface is empty when it
1262///     is merely unmarked. `rf_scan::ibt_applicable` answers this; it is
1263///     false for all 24 repository fixtures.
1264///   * CORE-07 — an ELF whose `e_machine` and `EI_CLASS` disagree about
1265///     the register width (x32, ELFCLASS64 + EM_386, AArch64 ILP32).
1266///     rop-finder decodes by `e_machine` and ROPgadget decodes by
1267///     `EI_CLASS`, so the two tools' output legitimately differs here and
1268///     the user is told which one they are looking at.
1269///   * CLI-11/`--compat` — the fat Mach-O concatenation the refusal
1270///     normally prevents.
1271pub fn scan_warnings(
1272    target: &Target,
1273    view: &RegionView,
1274    cfg_aware: bool,
1275    compat: bool,
1276) -> Vec<String> {
1277    let mut out = Vec::new();
1278    if cfg_aware && !rf_scan::ibt_applicable(view) {
1279        out.push(
1280            "[Warning] --cfg-aware: this binary contains no endbr32/endbr64 landing pads, \
1281             so Intel CET/IBT is not enforced on it and the flag constrains nothing. \
1282             (PE GUARD_CF is a different mitigation and is not what --cfg-aware models.)"
1283                .to_string(),
1284        );
1285    }
1286    if let Target::Elf(b) = target {
1287        if let Some(d) = b.mode_divergence() {
1288            out.push(format!(
1289                "[Warning] ELF e_machine {:#x} declares {}-bit code but EI_CLASS says \
1290                 {}-bit. rop-finder decodes it as {}-bit (the width the instruction \
1291                 encodings actually use); ROPgadget decodes it as {}-bit. Gadget text and \
1292                 counts will differ from the oracle on this file.",
1293                d.machine, d.rf_bits, d.oracle_bits, d.rf_bits, d.oracle_bits
1294            ));
1295        }
1296    }
1297    if compat {
1298        if let Target::Universal(u) = target {
1299            if u.needs_arch_selection() {
1300                out.push(format!(
1301                    "[Warning] --compat: scanning all {} slices of this fat Mach-O \
1302                     concatenated and decoding every one of them as {}, exactly as \
1303                     ROPgadget does. Every slice but the first is decoded with the WRONG \
1304                     architecture: its listing mixes FABRICATED gadgets — misreadings of \
1305                     another architecture's instructions, at addresses indistinguishable \
1306                     from the genuine ones — with real gadgets it silently drops. Use \
1307                     --arch <slice> for a trustworthy listing.",
1308                    u.slices().len(),
1309                    view.arch().slice_name()
1310                ));
1311            }
1312        }
1313    }
1314    out
1315}
1316
1317/// PERF-05: run the engine, choosing the bounded (streaming-sink) entry
1318/// point when `--max-gadgets` / `--max-memory` asked for one.
1319///
1320/// `scan_binary` collects into an unbounded `Vec`; `scan_bounded` drives a
1321/// [`rf_scan::BoundedSink`] that aborts the scan the moment either budget is
1322/// crossed, so the residual cost after the limit is one atomic load per
1323/// remaining work item rather than the gadgets it would have produced.
1324/// The two agree gadget-for-gadget while no budget is set, so the default
1325/// path is left exactly as it was.
1326pub fn run_scan_engine(view: &RegionView, opts: &ScanOptions) -> Result<Vec<Gadget>, String> {
1327    if opts.max_gadgets.is_none() && opts.max_memory.is_none() {
1328        return rf_scan::scan_binary(view, opts).map_err(|e| e.to_string());
1329    }
1330    rf_scan::scan_bounded(view, opts).map_err(scan_error_message)
1331}
1332
1333/// The user-facing wording for a scan-time failure.
1334///
1335/// Shared by the buffered and the streaming (`--format jsonl`) paths so that
1336/// the same `--max-gadgets` produces the same sentence whichever format it
1337/// was asked for; the raw `Error::Budget` Display says what happened but not
1338/// what to do about it.
1339pub fn scan_error_message(e: rf_scan::Error) -> String {
1340    match e {
1341        rf_scan::Error::Budget { produced, limit } => format!(
1342            "scan budget exhausted after {produced} gadgets (limit {limit}); raise \
1343             --max-gadgets/--max-memory, lower --depth, or narrow the scan with --section"
1344        ),
1345        other => other.to_string(),
1346    }
1347}
1348
1349/// `--info` pipeline over in-memory bytes. `new_base` is the already-parsed
1350/// `--base` value (parse errors are usage errors on the caller side).
1351pub fn info_bytes(
1352    bytes: &[u8],
1353    raw: Option<RawSpec>,
1354    new_base: Option<u64>,
1355) -> Result<serde_json::Value, ScanError> {
1356    let target = load_target(bytes, raw)?;
1357    Ok(info_json(&target, new_base))
1358}
1359
1360// ---------------------------------------------------------------------------
1361// --ropchain (Phases 4a/4b, PLAN.md sec. 6.2): chain generation.
1362// ---------------------------------------------------------------------------
1363
1364/// Format name for chain dispatch / errors.
1365pub fn target_format(target: &Target) -> &'static str {
1366    match target {
1367        Target::Elf(_) => "elf",
1368        Target::Pe(_) => "pe",
1369        Target::MachO(_) => "macho",
1370        Target::Universal(_) => "universal",
1371        Target::Raw(_) => "raw",
1372    }
1373}
1374
1375/// Chain target + Windows parameters (the CLI's `--chain`, `--api-addr`,
1376/// `--api-name`, `--shellcode-addr`, `--shellcode-size`, `--chain-base`,
1377/// `--prot`; MCP passes the same).
1378#[derive(Debug, Clone, Default)]
1379pub struct ChainSpec {
1380    /// "linux-execve" (default) or "windows-virtualprotect".
1381    pub target: String,
1382    /// `--api-addr` (hex): the runtime address of the API to call. A
1383    /// comma-separated list supplies one address per `--api-name`.
1384    pub api_addr: Option<String>,
1385    /// CHWIN-06: which API to resolve and whose argument recipe to use.
1386    /// `None` = the builder's default, VirtualProtect.
1387    pub api_name: Option<String>,
1388    /// `--shellcode-addr` (hex): where the shellcode will live.
1389    pub shellcode_addr: Option<String>,
1390    /// `--shellcode-size` (hex): the `dwSize` / length argument.
1391    pub shellcode_size: Option<String>,
1392    /// CHWIN-04: "aligned" or "return-address"/"return_address".
1393    /// `None` = the builder's default, return_address.
1394    pub chain_base: Option<String>,
1395    /// flNewProtect / flProtect (hex). `None` = 0x40 on Windows, 7
1396    /// (PROT_READ|WRITE|EXEC) for `linux-mprotect`.
1397    pub prot: Option<String>,
1398    /// `--syscall <n>`: decimal, or hex with an explicit `0x`.
1399    pub syscall: Option<String>,
1400    /// `--syscall-args rdi=..,rsi=..`.
1401    pub syscall_args: Option<String>,
1402    /// `--chain-pivot <addr>` (CHWIN-08).
1403    pub pivot: Option<String>,
1404    /// `--stage <hex>` (CHWIN-08).
1405    pub stage: Option<String>,
1406}
1407
1408impl ChainSpec {
1409    /// Default when `--ropchain` is given without `--chain`.
1410    pub fn linux() -> Self {
1411        ChainSpec {
1412            target: "linux-execve".to_string(),
1413            ..ChainSpec::default()
1414        }
1415    }
1416}
1417
1418/// A generated chain plus the scan it was built from.
1419pub struct ChainOutcome {
1420    /// The chain itself, as the Chain IR.
1421    pub chain: rf_chain::RopChain,
1422    /// The scan the chain was built from.
1423    pub outcome: ScanOutcome,
1424    /// CHWIN-04: what the Windows builder assumed about the world the
1425    /// chain will run in — the chain-base parity, the API recipe, and the
1426    /// two addresses CHWIN-02 keeps apart. `None` for a Linux chain, which
1427    /// makes none of these assumptions.
1428    pub assumptions: Option<rf_chain::windows::WinAssumptions>,
1429}
1430
1431/// The Chain IR as JSON, plus the `assumptions` object a Windows chain
1432/// carries (CHWIN-04). The IR itself is `rf_chain`'s serialisation,
1433/// untouched; the assumptions sit beside it as their own key so a reader
1434/// gets the layout AND what the layout took for granted from one document.
1435/// ECO-04: parse `--syscall-args rdi=0x1000,rsi=8` into `(reg, value)`
1436/// pairs. Register names are validated by the builder against the ABI, so
1437/// the error here is only about the SHAPE.
1438pub fn parse_syscall_args(spec: &str) -> Result<Vec<(String, u64)>, String> {
1439    let mut out = Vec::new();
1440    for item in spec.split(',').map(str::trim).filter(|s| !s.is_empty()) {
1441        let (reg, value) = item.split_once('=').ok_or_else(|| {
1442            format!("invalid --syscall-args item {item:?}: expected <reg>=<value>")
1443        })?;
1444        let reg = reg.trim().to_ascii_lowercase();
1445        if reg.is_empty() {
1446            return Err(format!(
1447                "invalid --syscall-args item {item:?}: empty register name"
1448            ));
1449        }
1450        let value = parse_hex(value.trim(), "--syscall-args")?;
1451        out.push((reg, value));
1452    }
1453    Ok(out)
1454}
1455
1456/// `--syscall <n>`: DECIMAL by default (a syscall number is written in
1457/// decimal everywhere from the kernel table to strace), hexadecimal only
1458/// with an explicit `0x` — the same rule `parse_align` applies for the same
1459/// reason (ANCH-02).
1460pub fn parse_syscall_nr(v: &str) -> Result<u64, String> {
1461    let t = v.trim();
1462    if let Some(hex) = t.strip_prefix("0x").or_else(|| t.strip_prefix("0X")) {
1463        return u64::from_str_radix(hex, 16).map_err(|e| format!("invalid --syscall {v:?}: {e}"));
1464    }
1465    t.parse::<u64>()
1466        .map_err(|e| format!("invalid --syscall {v:?}: {e}"))
1467}
1468
1469/// `--stage 9090cc` -> the bytes to write.
1470pub fn parse_hex_bytes(v: &str, flag: &str) -> Result<Vec<u8>, String> {
1471    let t: String = v
1472        .trim()
1473        .trim_start_matches("0x")
1474        .chars()
1475        .filter(|c| !c.is_whitespace())
1476        .collect();
1477    if t.is_empty() {
1478        return Err(format!("{flag}: no bytes given"));
1479    }
1480    if t.len() % 2 != 0 {
1481        return Err(format!(
1482            "{flag} {v:?}: hex byte string has an odd number of digits"
1483        ));
1484    }
1485    (0..t.len())
1486        .step_by(2)
1487        .map(|i| u8::from_str_radix(&t[i..i + 2], 16).map_err(|e| format!("{flag} {v:?}: {e}")))
1488        .collect()
1489}
1490
1491/// Parse the Linux chain parameters (`ECO-04` / `CHLX-07`).
1492pub fn linux_opts(spec: &ChainSpec) -> Result<rf_chain::LinuxChainOpts, ScanError> {
1493    use rf_chain::LinuxTarget;
1494    let usage = ScanError::Usage;
1495    let target = LinuxTarget::parse(&spec.target).ok_or_else(|| {
1496        ScanError::Usage(format!(
1497            "unknown Linux chain target {:?}; supported: {}",
1498            spec.target,
1499            LinuxTarget::NAMES.join(", ")
1500        ))
1501    })?;
1502    Ok(rf_chain::LinuxChainOpts {
1503        target,
1504        syscall_nr: spec
1505            .syscall
1506            .as_deref()
1507            .map(parse_syscall_nr)
1508            .transpose()
1509            .map_err(usage)?,
1510        syscall_args: spec
1511            .syscall_args
1512            .as_deref()
1513            .map(parse_syscall_args)
1514            .transpose()
1515            .map_err(usage)?
1516            .unwrap_or_default(),
1517        func_addr: spec
1518            .api_addr
1519            .as_deref()
1520            .map(|a| parse_hex(a, "--api-addr"))
1521            .transpose()
1522            .map_err(usage)?,
1523        shellcode_addr: spec
1524            .shellcode_addr
1525            .as_deref()
1526            .map(|a| parse_hex(a, "--shellcode-addr"))
1527            .transpose()
1528            .map_err(usage)?,
1529        shellcode_size: match &spec.shellcode_size {
1530            Some(s) => parse_hex(s, "--shellcode-size").map_err(usage)?,
1531            None => rf_chain::linux::DEFAULT_LINUX_LEN,
1532        },
1533        prot: match &spec.prot {
1534            Some(s) => parse_hex(s, "--prot").map_err(usage)?,
1535            None => rf_chain::linux::DEFAULT_LINUX_PROT,
1536        },
1537    })
1538}
1539
1540/// The Chain IR as pretty JSON, with the Windows `assumptions` object
1541/// beside it (`null` for a target that makes none).
1542pub fn chain_json(outcome: &ChainOutcome) -> String {
1543    let mut value = outcome.chain.to_json();
1544    if let Some(obj) = value.as_object_mut() {
1545        // Always present, `null` when the target makes no such assumptions
1546        // — the same rule rf-mcp's schema.rs states, so a parser written
1547        // against one surface does not break on the other.
1548        obj.insert(
1549            "assumptions".to_string(),
1550            match outcome.assumptions.as_ref() {
1551                Some(a) => serde_json::to_value(a).unwrap_or(serde_json::Value::Null),
1552                None => serde_json::Value::Null,
1553            },
1554        );
1555    }
1556    serde_json::to_string_pretty(&value).unwrap()
1557}
1558
1559fn chain_err(e: rf_chain::ChainError) -> ScanError {
1560    match e {
1561        rf_chain::ChainError::Unsupported { .. } => ScanError::Usage(e.to_string()),
1562        other => ScanError::Chain(other.to_string()),
1563    }
1564}
1565
1566/// Parse the Windows chain parameters (hex strings → WinChainOpts).
1567///
1568/// `--api-name` and `--chain-base` are validated HERE rather than deep in
1569/// the builder so a typo is a usage error naming the accepted values, and
1570/// so the MCP (which calls the same function through `chain_bytes`) rejects
1571/// the same set the CLI does — the ECO-02 property `capability_matrix.py`
1572/// gates.
1573pub fn win_opts(spec: &ChainSpec) -> Result<rf_chain::WinChainOpts, ScanError> {
1574    use rf_chain::windows::{ApiRecipe, ChainBaseParity};
1575    let usage = ScanError::Usage;
1576    // CHWIN-08 #2: `--api-name A,B` composes two calls into one chain, and
1577    // `--api-addr` then takes one address per name. One name and one
1578    // address is the ordinary single-call case, unchanged.
1579    let raw_names: Vec<&str> = match spec.api_name.as_deref().map(str::trim) {
1580        None | Some("") => vec![],
1581        Some(v) => v
1582            .split(',')
1583            .map(str::trim)
1584            .filter(|s| !s.is_empty())
1585            .collect(),
1586    };
1587    let canonical = |name: &str| -> Result<String, ScanError> {
1588        ApiRecipe::NAMES
1589            .iter()
1590            .find(|n| n.eq_ignore_ascii_case(name))
1591            .map(|n| (*n).to_string())
1592            .ok_or_else(|| {
1593                ScanError::Usage(format!(
1594                    "--api-name {name:?}: supported values are {} (their argument recipes                      differ, so an unmodelled API cannot be called correctly)",
1595                    ApiRecipe::NAMES.join(", ")
1596                ))
1597            })
1598    };
1599    let names: Vec<String> = if raw_names.is_empty() {
1600        vec![rf_chain::WinChainOpts::default().api_name]
1601    } else {
1602        raw_names
1603            .iter()
1604            .map(|n| canonical(n))
1605            .collect::<Result<Vec<_>, _>>()?
1606    };
1607
1608    let addrs: Vec<u64> = match spec.api_addr.as_deref().map(str::trim) {
1609        None | Some("") => Vec::new(),
1610        Some(v) => v
1611            .split(',')
1612            .map(str::trim)
1613            .filter(|s| !s.is_empty())
1614            .map(|a| parse_hex(a, "--api-addr"))
1615            .collect::<Result<Vec<_>, _>>()
1616            .map_err(usage)?,
1617    };
1618    if !addrs.is_empty() && addrs.len() != names.len() {
1619        return Err(ScanError::Usage(format!(
1620            "--api-addr has {} address(es) but --api-name names {} API(s): a composed chain              needs one runtime address per call, or none at all (IAT resolution)",
1621            addrs.len(),
1622            names.len()
1623        )));
1624    }
1625    let addr_of = |i: usize| addrs.get(i).copied();
1626
1627    let chain_base = match spec.chain_base.as_deref().map(str::trim) {
1628        None | Some("") => ChainBaseParity::default(),
1629        Some(v) => ChainBaseParity::parse(v).ok_or_else(|| {
1630            ScanError::Usage(format!(
1631                "--chain-base {v:?}: supported values are {}",
1632                ChainBaseParity::VALUES.join(", ")
1633            ))
1634        })?,
1635    };
1636    Ok(rf_chain::WinChainOpts {
1637        api_name: names[0].clone(),
1638        api_addr: addr_of(0),
1639        extra_calls: names
1640            .iter()
1641            .enumerate()
1642            .skip(1)
1643            .map(|(i, n)| (n.clone(), addr_of(i)))
1644            .collect(),
1645        shellcode_addr: spec
1646            .shellcode_addr
1647            .as_deref()
1648            .map(|a| parse_hex(a, "--shellcode-addr"))
1649            .transpose()
1650            .map_err(usage)?,
1651        shellcode_size: match &spec.shellcode_size {
1652            Some(s) => parse_hex(s, "--shellcode-size").map_err(usage)?,
1653            None => rf_chain::windows::DEFAULT_SHELLCODE_SIZE,
1654        },
1655        new_protect: match &spec.prot {
1656            Some(s) => parse_hex(s, "--prot").map_err(usage)?,
1657            None => rf_chain::windows::DEFAULT_PROTECT,
1658        },
1659        chain_base,
1660        pivot: spec
1661            .pivot
1662            .as_deref()
1663            .map(|a| parse_hex(a, "--chain-pivot"))
1664            .transpose()
1665            .map_err(usage)?,
1666        stage: spec
1667            .stage
1668            .as_deref()
1669            .map(|h| parse_hex_bytes(h, "--stage"))
1670            .transpose()
1671            .map_err(usage)?
1672            .unwrap_or_default(),
1673        // Image data, not a flag: `chain_bytes` / `plan_once` fill it in
1674        // from the file they already hold (CHWIN-08 #3).
1675        exports: Vec::new(),
1676    })
1677}
1678
1679/// Every `--chain` value, in help order. `linux-*` need an ELF x86/x64,
1680/// `windows-virtualprotect` a PE x86/x64.
1681pub fn chain_targets() -> Vec<&'static str> {
1682    let mut v: Vec<&'static str> = rf_chain::LinuxTarget::NAMES.to_vec();
1683    v.push("windows-virtualprotect");
1684    v
1685}
1686
1687/// Format/arch gate for a chain target. Shared by `chain_bytes` and
1688/// `plan_chain_bytes` so the two cannot disagree about what is dispatchable.
1689fn check_chain_target(
1690    name: &str,
1691    target: &Target,
1692    arch: Arch,
1693    format: &str,
1694) -> Result<(), ScanError> {
1695    let unsupported = || {
1696        Err(chain_err(rf_chain::ChainError::Unsupported {
1697            arch: rf_chain::arch_name(arch),
1698            format: format.to_string(),
1699        }))
1700    };
1701    match name {
1702        t if rf_chain::LinuxTarget::parse(t).is_some() => {
1703            if !matches!(target, Target::Elf(_)) || !matches!(arch, Arch::X86 | Arch::X64) {
1704                return unsupported();
1705            }
1706        }
1707        "windows-virtualprotect" => {
1708            if !matches!(target, Target::Pe(_)) || !matches!(arch, Arch::X86 | Arch::X64) {
1709                return unsupported();
1710            }
1711        }
1712        other => {
1713            return Err(ScanError::Usage(format!(
1714                "unknown chain target {other:?}; supported: {}",
1715                chain_targets().join(", ")
1716            )));
1717        }
1718    }
1719    Ok(())
1720}
1721
1722/// `ECO-04`: one probe run — load, scan, and ask the target's planner.
1723///
1724/// Separate from [`plan_chain_bytes`] because the relaxation search runs it
1725/// several times with different scan parameters and compares the answers.
1726fn plan_once(
1727    bytes: &[u8],
1728    raw: Option<RawSpec>,
1729    req: &ScanRequest,
1730    spec: &ChainSpec,
1731) -> Result<(rf_chain::ChainPlan, Vec<rf_scan::Gadget>, u64), ScanError> {
1732    let opts = request_options(req, raw)?;
1733    let mut target = load_target(bytes, raw)?;
1734    let format = target_format(&target);
1735    let arch = match &target {
1736        Target::Elf(b) => Image::arch(b),
1737        Target::Pe(b) => Image::arch(b),
1738        t => Image::arch(&build_view(t)),
1739    };
1740    // ECO-04: `plan_chain` ALWAYS succeeds, so the format/arch gate that
1741    // `chain_bytes` applies is NOT applied here — "this builder does not
1742    // cover PE x64 / linux-execve" is a REQUIREMENT the probe reports
1743    // (`target_supported`), not an error the caller has to parse. Only an
1744    // unknown target NAME is a usage error, because there is then nothing
1745    // to plan for.
1746    if !chain_targets().contains(&spec.target.as_str()) {
1747        return Err(ScanError::Usage(format!(
1748            "unknown chain target {:?}; supported: {}",
1749            spec.target,
1750            chain_targets().join(", ")
1751        )));
1752    }
1753
1754    let base = req
1755        .base
1756        .as_deref()
1757        .map(|b| parse_hex(b, "--base"))
1758        .transpose()
1759        .map_err(ScanError::Usage)?;
1760    match &mut target {
1761        Target::Elf(b) => {
1762            if let Some(base) = base {
1763                b.rebase(base);
1764            }
1765        }
1766        Target::Pe(b) => {
1767            if let Some(base) = base {
1768                b.rebase(base);
1769            }
1770        }
1771        _ => {}
1772    }
1773    let prepared = prepare_view(&target, None, &req.section, req.arch.as_deref(), req.compat)?;
1774    let gadgets = rf_scan::scan_binary(&prepared.view, &opts)
1775        .map_err(|e| ScanError::Binary(e.to_string()))?;
1776    let sections: &[rf_core::Section] = match &target {
1777        Target::Elf(b) => b.sections(),
1778        Target::Pe(b) => b.sections(),
1779        // A Mach-O or raw target hosts neither chain family; the probe
1780        // says so through `target_supported` and needs no sections.
1781        _ => &[],
1782    };
1783    let data_sections: Vec<rf_chain::DataSection> = sections
1784        .iter()
1785        .filter(|s| !s.executable)
1786        .map(|s| rf_chain::DataSection {
1787            name: s.name.clone(),
1788            vaddr: s.vaddr.wrapping_add(opts.offset),
1789            writable: s.writable,
1790        })
1791        .collect();
1792
1793    let plan = match (&target, spec.target.as_str()) {
1794        (_, "windows-virtualprotect") => {
1795            let mut wopts = win_opts(spec)?;
1796            if let Target::Pe(pe) = &target {
1797                wopts.exports = pe_exports::parse_pe_exports(bytes, pe.image_base());
1798            }
1799            rf_chain::plan_windows(
1800                &gadgets,
1801                &data_sections,
1802                match &target {
1803                    Target::Pe(pe) => pe.imports(),
1804                    _ => &[],
1805                },
1806                arch,
1807                format,
1808                &wopts,
1809                &opts.badbytes,
1810            )
1811        }
1812        _ => {
1813            let lopts = linux_opts(spec)?;
1814            rf_chain::plan_linux(
1815                &gadgets,
1816                &data_sections,
1817                arch,
1818                format,
1819                &opts.badbytes,
1820                &lopts,
1821            )
1822        }
1823    };
1824    Ok((plan, gadgets, opts.offset))
1825}
1826
1827/// `ECO-04`: the feasibility report, with COMPUTED relaxations.
1828///
1829/// The relaxation loop is the point. For every requirement the base scan
1830/// could not satisfy, the same probe is re-run against a scan taken with one
1831/// parameter changed — `depth` doubled, then `--multibr` on — and
1832/// `would_help` records what that re-run actually measured. Nothing here
1833/// predicts; a `would_help: true` means a scan was taken and the gadget was
1834/// there.
1835///
1836/// The re-scans are skipped entirely when the base plan is already feasible,
1837/// which is the common case and the one where they would cost the most.
1838pub fn plan_chain_bytes(
1839    bytes: &[u8],
1840    raw: Option<RawSpec>,
1841    req: &ScanRequest,
1842    spec: &ChainSpec,
1843) -> Result<ChainPlanOutcome, ScanError> {
1844    let (mut plan, gadgets, offset) = plan_once(bytes, raw, req, spec)?;
1845    if plan.requirements.iter().any(|r| !r.satisfied) {
1846        let deeper = ScanRequest {
1847            depth: req.depth.saturating_mul(2),
1848            ..req.clone()
1849        };
1850        if let Ok((v, _, _)) = plan_once(bytes, raw, &deeper, spec) {
1851            plan.merge_relaxation(
1852                &v,
1853                "depth",
1854                &req.depth.to_string(),
1855                &deeper.depth.to_string(),
1856            );
1857        }
1858        let multibr = ScanRequest {
1859            multibr: true,
1860            ..req.clone()
1861        };
1862        if !req.multibr {
1863            if let Ok((v, _, _)) = plan_once(bytes, raw, &multibr, spec) {
1864                plan.merge_relaxation(&v, "multibr", "false", "true");
1865            }
1866        }
1867    }
1868    Ok(ChainPlanOutcome {
1869        plan,
1870        gadgets,
1871        offset,
1872    })
1873}
1874
1875/// `--plan-chain`'s document.
1876///
1877/// `gadget_id` stays `null` on the CLI: the stable id is the MCP's handle
1878/// for referring to a gadget across tool calls, and a shell's handle is the
1879/// address (the same asymmetry `tests/capability_matrix.py` records for the
1880/// `ids` parameter). `vaddr` and `text` are here, which is what a shell
1881/// pipeline needs.
1882pub fn plan_json(outcome: &ChainPlanOutcome) -> String {
1883    serde_json::to_string_pretty(&outcome.plan.to_json()).unwrap()
1884}
1885
1886/// A plan plus the scan it was measured on, so a front end can turn the
1887/// satisfying gadgets into the stable ids `get_gadgets` resolves.
1888pub struct ChainPlanOutcome {
1889    /// The feasibility report.
1890    pub plan: rf_chain::ChainPlan,
1891    /// The scan the plan was measured on.
1892    pub gadgets: Vec<rf_scan::Gadget>,
1893    /// `--offset` applied to the scan; ids are keyed on the UNSLID vaddr.
1894    pub offset: u64,
1895}
1896
1897impl ChainPlanOutcome {
1898    /// The bytes of the gadget at `vaddr`, for a caller computing ids.
1899    pub fn gadget_bytes(&self, vaddr: u64) -> Option<&[u8]> {
1900        self.gadgets
1901            .iter()
1902            .find(|g| g.vaddr == vaddr)
1903            .map(|g| g.bytes.as_slice())
1904    }
1905}
1906
1907/// `--ropchain` pipeline: options → load → dispatch on `--chain` target →
1908/// rebase → scan → chain build.
1909///
1910///   * `linux-execve` (default): ELF x86/x64, mirroring ropmaker.py:23-40.
1911///   * `windows-virtualprotect`: PE x86/x64 (Phase 4b, PLAN sec. 6.2).
1912pub fn chain_bytes(
1913    bytes: &[u8],
1914    raw: Option<RawSpec>,
1915    req: &ScanRequest,
1916    spec: &ChainSpec,
1917) -> Result<ChainOutcome, ScanError> {
1918    let opts = request_options(req, raw)?;
1919    let mut target = load_target(bytes, raw)?;
1920
1921    let format = target_format(&target);
1922    let arch = match &target {
1923        Target::Elf(b) => Image::arch(b),
1924        Target::Pe(b) => Image::arch(b),
1925        t => Image::arch(&build_view(t)), // others: only used for the error
1926    };
1927
1928    // Target dispatch: format gates the chain family.
1929    check_chain_target(&spec.target, &target, arch, format)?;
1930
1931    // Rebase the TARGET (not just the view) so the writable sections used
1932    // for the string write / lpflOldProtect carry the rebased vaddrs too.
1933    let base = req
1934        .base
1935        .as_deref()
1936        .map(|b| parse_hex(b, "--base"))
1937        .transpose()
1938        .map_err(ScanError::Usage)?;
1939    match &mut target {
1940        Target::Elf(b) => {
1941            if let Some(base) = base {
1942                b.rebase(base);
1943            }
1944        }
1945        Target::Pe(b) => {
1946            if let Some(base) = base {
1947                b.rebase(base);
1948            }
1949        }
1950        _ => {}
1951    }
1952
1953    // CFG/CET guidance (PLAN sec. 6.2 #6): a GUARD_CF-marked PE scanned
1954    // without --cfg-aware produces chains that are DOA under enforced IBT.
1955    if let Target::Pe(b) = &target {
1956        if b.guard_cf() && !req.cfg_aware {
1957            eprintln!(
1958                "[Warning] PE is GUARD_CF-marked (CFG/CET); generated chains may be blocked \
1959                 under enforced IBT — consider --cfg-aware"
1960            );
1961        }
1962    }
1963
1964    let prepared = prepare_view(&target, None, &req.section, req.arch.as_deref(), req.compat)?;
1965    let universal_arch = prepared.view.universal.then_some(prepared.view.arch());
1966    let gadgets = rf_scan::scan_binary(&prepared.view, &opts)
1967        .map_err(|e| ScanError::Binary(e.to_string()))?;
1968
1969    let sections: &[rf_core::Section] = match &target {
1970        Target::Elf(b) => b.sections(),
1971        Target::Pe(b) => b.sections(),
1972        _ => unreachable!("dispatched above"),
1973    };
1974    // ROPgadget's getDataSections (elf.py:323-334): non-executable
1975    // sections; .data is picked by name inside the builders.
1976    let data_sections: Vec<rf_chain::DataSection> = sections
1977        .iter()
1978        .filter(|s| !s.executable)
1979        .map(|s| rf_chain::DataSection {
1980            name: s.name.clone(),
1981            // + opts.offset mirrors ropmaker's liboffset (the --offset
1982            // emission-time slide applies to .data too).
1983            vaddr: s.vaddr.wrapping_add(opts.offset),
1984            writable: s.writable,
1985        })
1986        .collect();
1987
1988    // CHLX-08: the symmetric warning to the PE GUARD_CF one. Every address
1989    // in a chain built against an ET_DYN image is a LINK-TIME offset, and
1990    // the tool already knows both facts it needs to say so.
1991    if let Target::Elf(b) = &target {
1992        // ET_DYN is exactly what rf-core's `pie` mitigation decides, and it
1993        // decides it from `e_type` — so the warning and `--info` /
1994        // get_mitigations cannot disagree about whether a target is PIE.
1995        let is_dyn = b.mitigations().enabled(rf_core::mitigations::PIE)
1996            == rf_core::mitigations::Enabled::Yes;
1997        if let Some(w) = rf_chain::linux::pie_chain_warning(is_dyn, b.image_base(), opts.offset) {
1998            eprintln!("[Warning] {w}");
1999        }
2000    }
2001
2002    let mut assumptions = None;
2003    let chain = match spec.target.as_str() {
2004        t if rf_chain::LinuxTarget::parse(t).is_some() => {
2005            let lopts = linux_opts(spec)?;
2006            rf_chain::build_linux(
2007                &gadgets,
2008                &data_sections,
2009                arch,
2010                format,
2011                &opts.badbytes,
2012                &lopts,
2013            )
2014            .map_err(chain_err)?
2015        }
2016        "windows-virtualprotect" => {
2017            let Target::Pe(pe) = &target else {
2018                unreachable!("dispatched above")
2019            };
2020            let mut wopts = win_opts(spec)?;
2021            // CHWIN-08 #3: strategy (c). Parsed from the bytes we already
2022            // hold, and rebased with the image, so an export resolves to
2023            // the same address the rest of the chain uses.
2024            wopts.exports = pe_exports::parse_pe_exports(bytes, pe.image_base());
2025            let chain = rf_chain::build_windows_virtualprotect(
2026                &gadgets,
2027                &data_sections,
2028                pe.imports(),
2029                arch,
2030                format,
2031                &wopts,
2032                &opts.badbytes,
2033            )
2034            .map_err(chain_err)?;
2035            // CHWIN-04: the same computation the builder ran, reported back
2036            // so the assumption is in the artefact rather than only in the
2037            // source. Never a second, drifting derivation.
2038            assumptions = Some(
2039                rf_chain::windows::windows_assumptions(&data_sections, arch, &wopts)
2040                    .map_err(chain_err)?,
2041            );
2042            chain
2043        }
2044        _ => unreachable!("validated above"),
2045    };
2046
2047    Ok(ChainOutcome {
2048        chain,
2049        assumptions,
2050        outcome: ScanOutcome {
2051            result: ScanResult {
2052                gadgets,
2053                addr_size: prepared.view.addr_size(),
2054                universal_arch,
2055                selected_sections: prepared.selected_sections,
2056            },
2057            opts,
2058            fallback_names: prepared.fallback_names,
2059        },
2060    })
2061}
2062
2063/// Image base of a target (first slice for Universal) — the pre-rebase
2064/// view base, used to compute the `--base` slide for the search sections.
2065///
2066/// ```
2067/// use rf_api::{load_target, target_base};
2068/// use rf_core::{Arch, Endianness};
2069///
2070/// // A raw blob is based at 0 until it is rebased.
2071/// let t = load_target(&[0x5f, 0xc3], Some((Arch::X64, Endianness::Little, false)))?;
2072/// assert_eq!(target_base(&t), 0);
2073/// # Ok::<(), rf_api::ScanError>(())
2074/// ```
2075pub fn target_base(target: &Target) -> u64 {
2076    match target {
2077        Target::Elf(b) => b.image_base(),
2078        Target::Pe(b) => b.image_base(),
2079        Target::MachO(b) => b.image_base(),
2080        Target::Raw(b) => b.image_base(),
2081        Target::Universal(u) => u.slices()[0].image_base(),
2082    }
2083}
2084
2085/// A gadget address, zero-padded to the image's address width.
2086///
2087/// ```
2088/// assert_eq!(rf_api::fmt_addr(0x401000, 8), "0x0000000000401000");
2089/// assert_eq!(rf_api::fmt_addr(0x8048000, 4), "0x08048000");
2090/// ```
2091pub fn fmt_addr(vaddr: u64, addr_size: usize) -> String {
2092    match addr_size {
2093        4 => format!("0x{vaddr:08x}"),
2094        _ => format!("0x{vaddr:016x}"),
2095    }
2096}
2097
2098/// Name of the selected section containing `vaddr` (a scan-view address,
2099/// i.e. after --base but before --offset), if any.
2100pub fn section_of(selected: &[(String, u64, u64)], vaddr: u64) -> Option<String> {
2101    selected
2102        .iter()
2103        .find(|(_, s_vaddr, s_size)| vaddr >= *s_vaddr && vaddr < s_vaddr.wrapping_add(*s_size))
2104        .map(|(name, _, _)| name.clone())
2105}