rf_chain/lib.rs
1//! rf-chain — ROP chain builders (Phase 4a, PLAN.md §6.2).
2//!
3//! **Chain IR first** (the review-driven design): builders produce a
4//! structured [`RopChain`] — a `Vec<ChainWord>` where every word knows its
5//! kind, its comment, and which gadget it came from — and renderers turn
6//! the IR into ROPgadget-compatible Python exploit text, JSON, or raw
7//! little-endian bytes. ROPgadget's stdout-text design is why nothing can
8//! consume its chains programmatically; the IR is the fix.
9//!
10//! Invariants are checked at build/validation time and reported as
11//! structured [`ChainError`]s, never panics:
12//! * every `GadgetAddr` word's value is the vaddr of an actually-reported
13//! gadget (checked against the scan's vaddr universe);
14//! * every non-gadget word (`Immediate` / `DataAddr` / `Padding`) must be
15//! badbyte-free when bad bytes are configured — bad bytes are a
16//! property of the final packed word (PLAN.md §6.4);
17//! * per-target invariant hooks ([`ChainInvariant`]) are the Phase 4b
18//! extension point — the Win64 16-byte stack-alignment invariant lands
19//! there; Linux execve needs no extra invariants.
20//!
21//! # Getting started
22//!
23//! ```
24//! use rf_chain::{build_linux, DataSection, LinuxChainOpts, WordKind};
25//! use rf_core::{Arch, Binary, Image};
26//! use rf_scan::{scan_binary, ScanOptions};
27//!
28//! # fn demo(bytes: &[u8]) -> Result<(), Box<dyn std::error::Error>> {
29//! let elf = Binary::parse(bytes)?;
30//! let gadgets = scan_binary(&elf, &ScanOptions::default())?;
31//! let data: Vec<DataSection> = elf
32//! .sections()
33//! .iter()
34//! .filter(|s| !s.executable)
35//! .map(|s| DataSection { name: s.name.clone(), vaddr: s.vaddr, writable: s.writable })
36//! .collect();
37//!
38//! let chain = build_linux(
39//! &gadgets,
40//! &data,
41//! Image::arch(&elf),
42//! "elf",
43//! &[],
44//! &LinuxChainOpts::default(),
45//! )?;
46//!
47//! // The IR is the point: every word knows what it is.
48//! assert!(chain.words.iter().any(|w| w.kind == WordKind::GadgetAddr));
49//! let _python = chain.to_python();
50//! let _json = chain.to_json();
51//! let _bytes = chain.to_bytes();
52//! # Ok(())
53//! # }
54//! ```
55//!
56//! # Semver policy
57//!
58//! Covered by semver from 1.0: the signatures of [`build_linux`],
59//! [`build_windows_virtualprotect`], [`plan_linux`] and [`plan_windows`];
60//! the fields of [`RopChain`], [`ChainWord`], [`GadgetRef`] and
61//! [`plan::ChainPlan`]; the [`WordKind`] and [`ChainError`] variant sets;
62//! and the `--chain` target names in [`LinuxTarget::NAMES`].
63//!
64//! **Not** covered, and free to change in a patch release: **which gadgets
65//! a chain picks and therefore its exact byte payload** — a better strategy
66//! is a bug fix, and the emulator harness (`tests/emulate.py`) is what
67//! holds the behaviour, not the byte sequence; the exact Python script text
68//! beyond the ROPgadget-compatible header; and every error and comment
69//! string. Adding a [`WordKind`] variant or a chain target is a minor
70//! release. Pin `rf-chain = "1"`.
71//!
72//! See `docs/API-STABILITY.md` in the repository for the workspace-wide
73//! statement.
74
75#![warn(missing_docs)]
76
77use rf_core::Arch;
78use serde::Serialize;
79use std::collections::HashSet;
80
81pub mod linux;
82pub mod plan;
83pub mod windows;
84
85pub use linux::plan_linux;
86pub use linux::{build_linux, build_linux_execve, DataSection, LinuxChainOpts, LinuxTarget};
87pub use plan::{
88 ChainPlan, PlanAssumptions, Relaxation, Requirement, SatisfiedRequirement, Strategy,
89};
90pub use windows::plan_windows;
91pub use windows::{build_windows_virtualprotect, PeExport, WinChainOpts};
92
93/// What a chain word is for.
94#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
95#[serde(rename_all = "snake_case")]
96pub enum WordKind {
97 /// Address of a gadget in the scanned binary.
98 GadgetAddr,
99 /// Immediate constant rendered as a Python bytes literal (e.g. the
100 /// packed "/bin//sh" string).
101 Immediate,
102 /// Address-like constant rendered as a `pack()` word: data-section
103 /// locations (`@ .data`), and on Windows also numeric stack arguments.
104 DataAddr,
105 /// Control-flow target that is not a gadget from this binary: an API
106 /// entry address (`--api-addr`), a shellcode/return address. Rendered
107 /// as a `pack()` word; badbyte-checked like DataAddr.
108 CodeAddr,
109 /// Filler consumed by a `pop` in a gadget's tail, shadow space, or a
110 /// stack-alignment word.
111 Padding,
112}
113
114fn hex_u64<S: serde::Serializer>(v: &u64, s: S) -> Result<S::Ok, S::Error> {
115 s.serialize_str(&format!("0x{v:x}"))
116}
117
118/// One machine word of the chain (8 bytes on x64, 4 on x86).
119#[derive(Debug, Clone, Serialize)]
120pub struct ChainWord {
121 /// The word's value, serialized as a hex string.
122 #[serde(serialize_with = "hex_u64")]
123 pub value: u64,
124 /// What this word IS - the distinction the emulator harness checks.
125 pub kind: WordKind,
126 /// Human-readable note, emitted beside the word in the Python script.
127 pub comment: String,
128 /// Index into [`RopChain::gadgets`] for `GadgetAddr` words.
129 #[serde(skip_serializing_if = "Option::is_none")]
130 pub source_gadget: Option<usize>,
131}
132
133/// A gadget referenced by the chain.
134#[derive(Debug, Clone, Serialize)]
135pub struct GadgetRef {
136 /// The gadget's address, serialized as a hex string.
137 #[serde(serialize_with = "hex_u64")]
138 pub vaddr: u64,
139 /// The gadget's disassembly text.
140 pub text: String,
141}
142
143/// A generated ROP chain in target-independent form.
144#[derive(Debug, Clone, Serialize)]
145pub struct RopChain {
146 /// e.g. "x86" / "x64".
147 pub arch: String,
148 /// Human-readable summary of what the chain does.
149 pub description: String,
150 /// Second line of the python script header. Linux builders keep
151 /// "# execve generated by ROPgadget" verbatim for byte parity; Windows
152 /// builders use their own comment.
153 pub script_comment: String,
154 /// Bytes per word (4 or 8).
155 pub word_size: usize,
156 /// The chain payload, one machine word per entry, in stack order.
157 pub words: Vec<ChainWord>,
158 /// Distinct gadgets referenced by `GadgetAddr` words, in order of
159 /// first reference; `ChainWord::source_gadget` indexes this list.
160 pub gadgets: Vec<GadgetRef>,
161}
162
163/// Structured chain-building failure. Builders never panic and never emit
164/// partial garbage: any missing gadget or violated invariant is an `Err`.
165#[derive(Debug, thiserror::Error)]
166pub enum ChainError {
167 /// Mirrors ropmaker.py:23-40 dispatch: only ELF x86/x64 are supported.
168 #[error("arch {arch} / format {format} not supported yet for the rop chain generation")]
169 Unsupported {
170 /// The architecture that was asked for.
171 arch: String,
172 /// The container format that was asked for.
173 format: String,
174 },
175 /// A required gadget is absent from the scan output.
176 #[error("can't find a suitable gadget: {0}")]
177 MissingGadget(String),
178 /// No `.data` (and no fallback writable section) for the string write.
179 #[error("can't find a writable section")]
180 NoWritableSection,
181 /// An IR invariant was violated (see [`RopChain::validate`]).
182 #[error("chain word {index} (0x{value:016x}, {kind:?}): {reason}")]
183 InvalidWord {
184 /// Index into [`RopChain::words`].
185 index: usize,
186 /// The offending word's value.
187 value: u64,
188 /// The offending word's kind.
189 kind: WordKind,
190 /// Which invariant it violated.
191 reason: String,
192 },
193}
194
195/// Per-target invariant hook (Phase 4b extension point). Receives the full
196/// chain; returns `Err` to reject it. Example for Phase 4b (Win64):
197/// "rsp must be 16-byte aligned at the VirtualProtect call site".
198pub type ChainInvariant<'a> = &'a dyn Fn(&RopChain) -> Result<(), ChainError>;
199
200/// What consumed a stack word, as reconstructed by
201/// [`RopChain::verify_stack_accounting`].
202///
203/// In a ret-chain every word has exactly one consumer. There is no such
204/// thing as a word the machine skips over.
205#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
206#[serde(rename_all = "snake_case")]
207pub enum WordRole {
208 /// A `ret` (or the initial pivot) loaded this word into the instruction
209 /// pointer.
210 ControlTransfer,
211 /// A `pop` in the preceding gadget took this word (or a `ret <imm>`
212 /// stack adjustment discarded it).
213 PopOperand,
214 /// Past the point where control leaves the chain — an API entry, a
215 /// `jmp reg`, a `syscall`. Return addresses, Win64 shadow space and
216 /// stdcall arguments live here. Static accounting cannot model an
217 /// opaque callee, so it stops and says so instead of guessing.
218 CalleeFrame,
219}
220
221/// The outcome of the static stack-word accounting walk (CHLX-04).
222#[derive(Debug, Clone, Serialize)]
223pub struct StackAccounting {
224 /// One entry per word of the chain, in order.
225 pub roles: Vec<WordRole>,
226 /// Index of the first word the walk could no longer account for, i.e.
227 /// the start of the callee's frame. `None` when the chain accounts for
228 /// every word it emits.
229 pub callee_frame_from: Option<usize>,
230 /// Why the walk stopped ("chain fully accounted", "control left the
231 /// chain at word 8 via `jmp rax`", ...).
232 pub stop_reason: String,
233 /// `CHWIN-08`: the index of the word a `pop rsp` / `pop esp` consumed
234 /// as the new stack pointer, when the chain pivots. The walk continues
235 /// past a pivot rather than abstaining, because the builder's pivot
236 /// layout contract (`WinAssumptions::pivot_addr` / `pivot_words`) says
237 /// the body sits at that address, i.e. exactly where the IR continues.
238 pub pivot_at: Option<usize>,
239}
240
241impl StackAccounting {
242 /// Words the walk verified (everything before the callee frame).
243 pub fn words_verified(&self) -> usize {
244 self.callee_frame_from.unwrap_or(self.roles.len())
245 }
246}
247
248/// Split a gadget's rendered text into instructions. `Gadget::text()` joins
249/// with `" ; "` (rf-scan engine.rs), and the Chain IR carries that same
250/// string, so the verifier reads the same text a user reads.
251fn gadget_insns(text: &str) -> Vec<&str> {
252 text.split(" ; ").map(str::trim).collect()
253}
254
255/// `ret 0x10` / `ret 16` -> the immediate; `ret` -> `None`.
256fn ret_immediate(insn: &str) -> Option<u64> {
257 let arg = insn.strip_prefix("ret ")?.trim();
258 match arg.strip_prefix("0x") {
259 Some(hex) => u64::from_str_radix(hex, 16).ok(),
260 None => arg.parse::<u64>().ok(),
261 }
262}
263
264/// Instructions that move rsp by an amount the verifier does not model.
265/// None of the current builders emit one; a stack pivot (CHWIN-08) will, and
266/// when it does the walk must stop rather than report a confident wrong
267/// answer.
268fn unmodelled_stack_effect(insn: &str) -> bool {
269 let mut parts = insn.splitn(2, ' ');
270 let head = parts.next().unwrap_or("");
271 if matches!(
272 head,
273 "leave" | "enter" | "push" | "pusha" | "pushad" | "pushal" | "popa" | "popad" | "popal"
274 ) {
275 return true;
276 }
277 // `pop rsp` / `pop esp` IS modelled -- see the pivot arm of
278 // `verify_stack_accounting` (CHWIN-08) -- so it is not unmodelled here.
279 if insn == "pop rsp" || insn == "pop esp" {
280 return false;
281 }
282 // Anything else whose destination operand IS the stack pointer:
283 // `add rsp, 0x18`, `xchg rsp, rax`, `mov esp, ebp`.
284 let dst = parts
285 .next()
286 .unwrap_or("")
287 .split(',')
288 .next()
289 .unwrap_or("")
290 .trim();
291 matches!(dst, "rsp" | "esp" | "sp")
292}
293
294impl RopChain {
295 /// Check the build-time invariants:
296 /// * every `GadgetAddr` word points at a real reported gadget
297 /// (`universe` = the scan's vaddr set) and its `source_gadget`
298 /// index agrees;
299 /// * every non-gadget word is badbyte-free (packed at `word_size`).
300 pub fn validate(&self, universe: &HashSet<u64>, badbytes: &[u8]) -> Result<(), ChainError> {
301 self.validate_with(universe, badbytes, &[])
302 }
303
304 /// [`validate`](Self::validate) plus per-target invariant hooks.
305 pub fn validate_with(
306 &self,
307 universe: &HashSet<u64>,
308 badbytes: &[u8],
309 hooks: &[ChainInvariant],
310 ) -> Result<(), ChainError> {
311 for (i, w) in self.words.iter().enumerate() {
312 let invalid = |reason: String| ChainError::InvalidWord {
313 index: i,
314 value: w.value,
315 kind: w.kind,
316 reason,
317 };
318 match w.kind {
319 WordKind::GadgetAddr => {
320 let idx = w
321 .source_gadget
322 .ok_or_else(|| invalid("gadget word without source_gadget".to_string()))?;
323 let g = self
324 .gadgets
325 .get(idx)
326 .ok_or_else(|| invalid(format!("source_gadget {idx} out of range")))?;
327 if g.vaddr != w.value {
328 return Err(invalid(format!(
329 "value {:#x} != gadgets[{idx}].vaddr {:#x}",
330 w.value, g.vaddr
331 )));
332 }
333 if !universe.contains(&w.value) {
334 return Err(invalid(format!(
335 "vaddr {:#x} is not in the scan output",
336 w.value
337 )));
338 }
339 }
340 WordKind::Immediate
341 | WordKind::DataAddr
342 | WordKind::CodeAddr
343 | WordKind::Padding => {
344 if !badbytes.is_empty() {
345 let packed = &w.value.to_le_bytes()[..self.word_size];
346 if let Some(b) = packed.iter().find(|b| badbytes.contains(b)) {
347 return Err(invalid(format!(
348 "packed word contains bad byte 0x{b:02x}"
349 )));
350 }
351 }
352 }
353 }
354 }
355 // CHLX-04: the words are well-formed; are they a chain that RUNS?
356 // A refusal, not a warning — "chains that are emitted must be
357 // runnable or not emitted".
358 self.verify_stack_accounting()?;
359 for hook in hooks {
360 hook(self)?;
361 }
362 Ok(())
363 }
364
365 /// Static semantic verification: walk the chain the way the machine
366 /// will, and account for every stack word (CHLX-04).
367 ///
368 /// `RopChain::validate` only ever answered "do these words point at real
369 /// gadgets, and are they badbyte-free?" — a chain whose words are all of
370 /// the right *kind* but whose layout is dead passes it. This walk asks
371 /// the next question. In a ret-chain every stack word is consumed by
372 /// exactly one thing: a `pop` inside a gadget, or the `ret` that ends
373 /// one. There is no filler the machine skips over, so the model is
374 /// exact rather than approximate:
375 ///
376 /// 1. the pivot's `ret` loads word 0 into rip;
377 /// 2. a `GadgetAddr` word's gadget consumes one word per `pop` it
378 /// contains, then its terminator decides what happens next —
379 /// a bare `ret` transfers to the following word, `ret <imm>`
380 /// additionally discards `imm/word_size` words, and anything else
381 /// (`syscall`, `int 0x80`, `jmp reg`, `call reg`) hands control to
382 /// something this chain does not describe;
383 /// 3. a `CodeAddr` word is an entry point outside the chain (an API
384 /// address, a shellcode address) — same thing.
385 ///
386 /// From (2)/(3) onwards the remaining words are the callee's frame — a
387 /// return address, Win64 shadow space, stdcall arguments — and are
388 /// reported as [`WordRole::CalleeFrame`] rather than guessed at. The
389 /// emulator covers that half; this walk covers the half a static check
390 /// can actually decide.
391 ///
392 /// Two shapes are rejected, and both are real inherited defects:
393 ///
394 /// * **a data word in control position** — the preceding gadget's `ret`
395 /// consumes an `Immediate`/`DataAddr`/`Padding` word as its next
396 /// instruction pointer. That is CHWIN-01 exactly: an inert
397 /// `0x4141414141414141` alignment pad inserted before the API
398 /// transfer word is not skipped, it is *jumped to*. A stack-alignment
399 /// pad has to be the address of a bare `ret` gadget, which consumes
400 /// itself and advances rsp by one word.
401 /// * **a gadget address in pop position** — a `pop` swallows a word the
402 /// IR itself labelled `GadgetAddr`, which means the padding count and
403 /// the emitted word count have drifted apart (a missing padding word
404 /// shifts every later word left by one). A code pointer that is
405 /// *meant* to be popped as data should be emitted as `CodeAddr`.
406 pub fn verify_stack_accounting(&self) -> Result<StackAccounting, ChainError> {
407 let n = self.words.len();
408 let mut roles: Vec<WordRole> = Vec::with_capacity(n);
409 let mut callee_frame_from = None;
410 let mut stop_reason = String::from("chain fully accounted: every word is consumed");
411 let mut sp = 0usize;
412 let mut pending_drop = 0usize;
413 let mut pivot_at: Option<usize> = None;
414
415 let invalid = |i: usize, reason: String| {
416 let w = &self.words[i];
417 ChainError::InvalidWord {
418 index: i,
419 value: w.value,
420 kind: w.kind,
421 reason,
422 }
423 };
424
425 while sp < n {
426 let here = sp;
427 let w = &self.words[here];
428 roles.push(WordRole::ControlTransfer);
429 sp += 1;
430 // A `ret <imm>` that transferred here also discarded imm bytes.
431 for _ in 0..pending_drop {
432 if sp >= n {
433 break;
434 }
435 roles.push(WordRole::PopOperand);
436 sp += 1;
437 }
438 pending_drop = 0;
439
440 let text = match w.kind {
441 WordKind::GadgetAddr => {
442 let idx = w.source_gadget.ok_or_else(|| {
443 invalid(here, "gadget word without source_gadget".to_string())
444 })?;
445 self.gadgets
446 .get(idx)
447 .ok_or_else(|| invalid(here, format!("source_gadget {idx} out of range")))?
448 .text
449 .clone()
450 }
451 WordKind::CodeAddr => {
452 callee_frame_from = Some(sp);
453 stop_reason = format!(
454 "control leaves the chain at word {here} ({:#x} is an entry point \
455 outside this binary's gadget set); words {sp}.. are the callee's frame",
456 w.value
457 );
458 break;
459 }
460 WordKind::Immediate | WordKind::DataAddr | WordKind::Padding => {
461 return Err(invalid(
462 here,
463 format!(
464 "static stack accounting (CHLX-04): control transfers here — the \
465 preceding `ret` loads this word into rip — but it is a {:?} word, \
466 not a gadget or code address. In a ret-chain there is no filler the \
467 machine skips over: a stack alignment pad must be the ADDRESS OF A \
468 BARE `ret` GADGET, which consumes itself and advances rsp by one \
469 word (CHWIN-01)",
470 w.kind
471 ),
472 ));
473 }
474 };
475
476 let insns = gadget_insns(&text);
477 let mut terminal: Option<String> = None;
478 for insn in &insns {
479 if unmodelled_stack_effect(insn) {
480 terminal = Some(format!("`{insn}` moves rsp by an unmodelled amount"));
481 break;
482 }
483 if *insn == "pop rsp" || *insn == "pop esp" {
484 // CHWIN-08: a stack pivot. The word this takes is the
485 // NEW stack pointer; the gadget's own `ret` then reads
486 // its target from there, which the chain IR places
487 // immediately after by the pivot layout contract
488 // (`WinAssumptions::pivot_addr` / `pivot_words`). So
489 // the walk continues instead of abstaining -- and it
490 // records where, because a reader of the accounting
491 // needs to know the words after this point live at a
492 // different address.
493 if sp >= n {
494 return Err(invalid(
495 here,
496 format!(
497 "static stack accounting (CHLX-04): the pivot gadget `{text}` pops the stack pointer past the end of the chain"
498 ),
499 ));
500 }
501 if pivot_at.is_some() {
502 terminal = Some(format!(
503 "`{insn}` is a SECOND stack pivot; one relocation of the chain body is a declared layout, two is not modelled"
504 ));
505 break;
506 }
507 roles.push(WordRole::PopOperand);
508 pivot_at = Some(sp);
509 sp += 1;
510 continue;
511 }
512 if insn.starts_with("pop ") {
513 if sp >= n {
514 return Err(invalid(
515 here,
516 format!(
517 "static stack accounting (CHLX-04): gadget `{text}` pops past the \
518 end of the chain — only {} word(s) follow it, and it needs one \
519 per `pop`",
520 n - here - 1
521 ),
522 ));
523 }
524 if self.words[sp].kind == WordKind::GadgetAddr {
525 return Err(invalid(
526 sp,
527 format!(
528 "static stack accounting (CHLX-04): `{insn}` in the gadget at \
529 word {here} consumes this word as data, but the IR labels it a \
530 gadget address — the emitted word \
531 count and the gadget's pop count have drifted apart (a missing \
532 padding word shifts every later word left). Emit a code pointer \
533 that is meant to be popped as `CodeAddr` (CHLX-04)"
534 ),
535 ));
536 }
537 roles.push(WordRole::PopOperand);
538 sp += 1;
539 continue;
540 }
541 }
542 if let Some(why) = terminal {
543 callee_frame_from = Some(sp);
544 stop_reason = format!(
545 "stopped at word {here}: {why}; words {sp}.. are not statically accounted"
546 );
547 break;
548 }
549
550 match insns.last().copied().unwrap_or("") {
551 // `repz ret` / `rep ret` is the AMD-K8 branch-prediction
552 // spelling of a plain near return; `rf_classify` reports it
553 // as `Terminator::Ret`, `linux.rs::is_bare_ret` accepts it,
554 // and elf-x64-bash-v4.1.5.1's only route to rdx is
555 // `pop rdx ; repz ret` -- so a walk that did not know the
556 // spelling abstained on real emitted chains.
557 "ret" | "repz ret" | "rep ret" | "ret 0" | "ret 0x0" => {}
558 other if ret_immediate(other).is_some() => {
559 let imm = ret_immediate(other).unwrap_or(0) as usize;
560 pending_drop = imm / self.word_size.max(1);
561 }
562 other => {
563 callee_frame_from = Some(sp);
564 stop_reason = format!(
565 "control leaves the chain at word {here} via `{other}`; \
566 words {sp}.. are the callee's frame"
567 );
568 break;
569 }
570 }
571 }
572
573 while roles.len() < n {
574 roles.push(WordRole::CalleeFrame);
575 }
576 Ok(StackAccounting {
577 roles,
578 pivot_at,
579 callee_frame_from,
580 stop_reason,
581 })
582 }
583
584 /// The scan's vaddr universe, for [`validate`](Self::validate).
585 pub fn universe_from(gadgets: &[rf_scan::Gadget]) -> HashSet<u64> {
586 gadgets.iter().map(|g| g.vaddr).collect()
587 }
588
589 fn pack_char(&self) -> (char, usize) {
590 match self.word_size {
591 4 => ('I', 8),
592 _ => ('Q', 16),
593 }
594 }
595
596 /// ROPgadget-compatible Python exploit script (ropmakerx64.py output
597 /// structure: the `from struct import pack` header, `p = b''`, and
598 /// `p += pack('<Q', 0x...) # ...` lines; string immediates render as
599 /// `p += b'...'`). The header comment line comes from
600 /// [`RopChain::script_comment`].
601 ///
602 /// Every line is emitted at column 0 (ROB-05: ropmaker indents padding
603 /// lines with a literal tab, which makes the script an
604 /// `IndentationError` at module level — we deliberately diverge), and
605 /// every comment goes through [`py_comment`] first (ROB-01: comment
606 /// text is derived from the analysed binary, so a newline in it would
607 /// otherwise close the comment and inject top-level Python).
608 pub fn to_python(&self) -> String {
609 let (c, w) = self.pack_char();
610 let mask = if self.word_size >= 8 {
611 u64::MAX
612 } else {
613 (1u64 << (self.word_size * 8)) - 1
614 };
615 let mut header = py_comment(&self.script_comment);
616 if !header.starts_with('#') {
617 header.insert_str(0, "# ");
618 }
619 let mut out = format!(
620 "#!/usr/bin/env python3\n{header}\n\nfrom struct import pack\n\n# Padding goes here\np = b''\n\n"
621 );
622 for word in &self.words {
623 let value = word.value & mask;
624 match word.kind {
625 WordKind::Immediate => {
626 let bytes = &value.to_le_bytes()[..self.word_size];
627 out.push_str(&format!("p += b'{}'\n", py_bytes_escape(bytes)));
628 }
629 WordKind::GadgetAddr
630 | WordKind::DataAddr
631 | WordKind::CodeAddr
632 | WordKind::Padding => {
633 out.push_str(&format!(
634 "p += pack('<{c}', 0x{:0w$x}) # {}\n",
635 value,
636 py_comment(&word.comment)
637 ));
638 }
639 }
640 }
641 out
642 }
643
644 /// JSON form of the IR.
645 pub fn to_json(&self) -> serde_json::Value {
646 serde_json::to_value(self).unwrap()
647 }
648
649 /// Raw little-endian bytes of the chain (what `p` contains at runtime).
650 pub fn to_bytes(&self) -> Vec<u8> {
651 let mut out = Vec::with_capacity(self.words.len() * self.word_size);
652 for w in &self.words {
653 out.extend_from_slice(&w.value.to_le_bytes()[..self.word_size]);
654 }
655 out
656 }
657}
658
659/// Maximum length of a comment rendered into the generated Python script.
660pub const PY_COMMENT_MAX: usize = 64;
661
662/// Sanitise a string for use inside a `#` comment of the generated Python
663/// script (ROB-01).
664///
665/// Comment text is derived from the analysed binary — the PE import DLL
666/// name ([`rf_core::PeImport::dll`], copied verbatim out of the import
667/// descriptor) and the disassembled gadget text both end up here. A
668/// newline in such a string terminates the `#` comment and turns whatever
669/// follows into top-level Python that the user then executes, so every
670/// character outside printable ASCII (`0x20..=0x7e`) — newlines and
671/// carriage returns included — is dropped rather than escaped, and the
672/// result is truncated to [`PY_COMMENT_MAX`] characters.
673pub fn py_comment(s: &str) -> String {
674 s.chars()
675 .filter(|c| (' '..='~').contains(c))
676 .take(PY_COMMENT_MAX)
677 .collect()
678}
679
680/// Render bytes as a Python `b'...'` literal body (ROPgadget only ever
681/// emits printable ASCII here, but escape defensively).
682fn py_bytes_escape(bytes: &[u8]) -> String {
683 let mut out = String::new();
684 for &b in bytes {
685 match b {
686 b'\'' => out.push_str("\\'"),
687 b'\\' => out.push_str("\\\\"),
688 0x20..=0x7e => out.push(b as char),
689 _ => out.push_str(&format!("\\x{b:02x}")),
690 }
691 }
692 out
693}
694
695/// Arch display name used in the IR (`"x86"` / `"x64"` / ...).
696pub fn arch_name(arch: Arch) -> String {
697 match arch {
698 Arch::X86 => "x86",
699 Arch::X64 => "x64",
700 Arch::Arm => "arm",
701 Arch::ArmThumb => "arm-thumb",
702 Arch::Arm64 => "arm64",
703 Arch::Mips32 => "mips32",
704 Arch::Mips64 => "mips64",
705 Arch::Ppc32 => "ppc32",
706 Arch::Ppc64 => "ppc64",
707 Arch::Sparc => "sparc",
708 Arch::Sparc64 => "sparc64",
709 Arch::SparcV9 => "sparcv9",
710 Arch::RiscV32 => "riscv32",
711 Arch::RiscV64 => "riscv64",
712 }
713 .to_string()
714}
715
716#[cfg(test)]
717pub(crate) mod tests {
718 use super::*;
719
720 /// Pure-Rust "is this a flat, un-injected script?" check, shared with
721 /// the windows builder tests. Every generated script is a flat
722 /// sequence of top-level statements, so every line must be blank, a
723 /// comment, one of the two fixed header statements, or a `p += …`
724 /// append — and no line may be indented (ROB-05) or introduce a
725 /// statement of its own (ROB-01). A script that passes this also
726 /// parses as Python.
727 pub(crate) fn assert_flat_python_script(py: &str) {
728 let mut lines = py.lines();
729 assert_eq!(lines.next(), Some("#!/usr/bin/env python3"));
730 let header = lines.next().unwrap_or("");
731 assert!(
732 header.starts_with('#'),
733 "header is not a comment: {header:?}"
734 );
735 for (i, line) in py.lines().enumerate() {
736 assert!(
737 !(line.starts_with(' ') || line.starts_with('\t')),
738 "line {i} is indented at module level: {line:?}"
739 );
740 let ok = line.is_empty()
741 || line.starts_with('#')
742 || line == "from struct import pack"
743 || line == "p = b''"
744 || line.starts_with("p += ");
745 assert!(ok, "line {i} is not a header or append statement: {line:?}");
746 }
747 }
748
749 /// Assert `needle` never occurs in statement position: on every line
750 /// that contains it, the line's first `#` comes first.
751 pub(crate) fn assert_only_in_comment(py: &str, needle: &str) {
752 for line in py.lines() {
753 let Some(at) = line.find(needle) else {
754 continue;
755 };
756 let hash = line
757 .find('#')
758 .unwrap_or_else(|| panic!("{needle:?} outside any comment: {line:?}"));
759 assert!(hash < at, "{needle:?} in statement position: {line:?}");
760 }
761 }
762
763 /// The interpreter to cross-check generated scripts with:
764 /// `$RF_CHAIN_PYTHON` when set, else `python`, else `python3`.
765 /// Candidates are probed with `-c "import ast"` so a non-working stub
766 /// (the Windows Store alias) counts as absent.
767 fn python_interpreter() -> Option<String> {
768 let candidates = match std::env::var("RF_CHAIN_PYTHON") {
769 Ok(p) => vec![p],
770 Err(_) => vec!["python".to_string(), "python3".to_string()],
771 };
772 candidates.into_iter().find(|exe| {
773 std::process::Command::new(exe)
774 .args(["-c", "import ast"])
775 .output()
776 .map(|o| o.status.success())
777 .unwrap_or(false)
778 })
779 }
780
781 /// Optional cross-check: `ast.parse` the generated script with a real
782 /// interpreter. A no-op when no interpreter can be spawned, so the
783 /// suite never depends on a Python installation — the pure-Rust
784 /// [`assert_flat_python_script`] is the load-bearing assertion.
785 pub(crate) fn assert_python_parses(py: &str) {
786 let Some(exe) = python_interpreter() else {
787 return;
788 };
789 // pid + a per-process counter: tests run in parallel threads.
790 static SEQ: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
791 let n = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
792 let mut path = std::env::temp_dir();
793 path.push(format!("rf-chain-script-{}-{n}.py", std::process::id()));
794 std::fs::write(&path, py).unwrap();
795 let out = std::process::Command::new(&exe)
796 .args(["-c", "import ast,sys;ast.parse(open(sys.argv[1]).read())"])
797 .arg(&path)
798 .output()
799 .unwrap();
800 let _ = std::fs::remove_file(&path);
801 assert!(
802 out.status.success(),
803 "{exe} rejected the generated script: {}\n--- script ---\n{py}",
804 String::from_utf8_lossy(&out.stderr)
805 );
806 }
807
808 /// A KNOWN-GOOD chain, in the sense CHLX-04 means it: every word is
809 /// consumed by exactly one `pop` or `ret`, and control ends at a
810 /// terminator rather than running off the end.
811 ///
812 /// word 0 pop rdi ; pop rbx ; ret <- the pivot's `ret` lands here
813 /// word 1 @ .data <- popped into rdi
814 /// word 2 padding <- popped into rbx
815 /// word 3 syscall <- the `ret` lands here; terminal
816 ///
817 /// The corruption tests below start from this and break it one way each.
818 fn chain_fixture() -> RopChain {
819 RopChain {
820 arch: "x64".to_string(),
821 description: "test".to_string(),
822 script_comment: "# execve generated by ROPgadget".to_string(),
823 word_size: 8,
824 gadgets: vec![
825 GadgetRef {
826 vaddr: 0x401000,
827 text: "pop rdi ; pop rbx ; ret".to_string(),
828 },
829 GadgetRef {
830 vaddr: 0x401100,
831 text: "syscall".to_string(),
832 },
833 ],
834 words: vec![
835 ChainWord {
836 value: 0x401000,
837 kind: WordKind::GadgetAddr,
838 comment: "pop rdi ; pop rbx ; ret".to_string(),
839 source_gadget: Some(0),
840 },
841 ChainWord {
842 value: 0x6bc080,
843 kind: WordKind::DataAddr,
844 comment: "@ .data".to_string(),
845 source_gadget: None,
846 },
847 ChainWord {
848 value: 0x4141414141414141,
849 kind: WordKind::Padding,
850 comment: "padding".to_string(),
851 source_gadget: None,
852 },
853 ChainWord {
854 value: 0x401100,
855 kind: WordKind::GadgetAddr,
856 comment: "syscall".to_string(),
857 source_gadget: Some(1),
858 },
859 ],
860 }
861 }
862
863 fn fixture_universe() -> HashSet<u64> {
864 [0x401000, 0x401100].into_iter().collect()
865 }
866
867 #[test]
868 fn validate_accepts_wellformed() {
869 let c = chain_fixture();
870 c.validate(&fixture_universe(), &[]).unwrap();
871 }
872
873 /// CHLX-04, the headline: a chain that passes the word-kind checks but
874 /// cannot run must be REFUSED, not warned about.
875 ///
876 /// The corruption is the one CHWIN-01 ships: an inert padding word
877 /// spliced in front of a control word. Every word in the result is still
878 /// of a legal kind, every gadget address is still real, no bad byte
879 /// appears — `validate`'s pre-CHLX-04 checks all pass — and the chain
880 /// still dies at 0x4141414141414141, because the `ret` before the gap
881 /// loads the gap into rip.
882 #[test]
883 fn padding_gap_is_refused_not_warned() {
884 let good = chain_fixture();
885 good.validate(&fixture_universe(), &[]).unwrap();
886 let acct = good.verify_stack_accounting().unwrap();
887 assert_eq!(
888 acct.roles,
889 vec![
890 WordRole::ControlTransfer, // the pivot's ret lands on the gadget
891 WordRole::PopOperand, // pop rdi
892 WordRole::PopOperand, // pop rbx
893 WordRole::ControlTransfer, // the gadget's ret lands on `syscall`
894 ]
895 );
896 // `syscall` is the terminator AND the last word, so the callee frame
897 // is empty: every word the chain emits is accounted for.
898 assert_eq!(acct.callee_frame_from, Some(4), "{}", acct.stop_reason);
899 assert_eq!(acct.words_verified(), acct.roles.len());
900
901 let mut corrupt = good.clone();
902 corrupt.words.insert(
903 3,
904 ChainWord {
905 value: 0x4141414141414141,
906 kind: WordKind::Padding,
907 comment: "stack alignment word".to_string(),
908 source_gadget: None,
909 },
910 );
911 let err = corrupt
912 .validate(&fixture_universe(), &[])
913 .expect_err("a chain with a padding gap must be refused");
914 match err {
915 ChainError::InvalidWord { index, kind, .. } => {
916 assert_eq!(index, 3);
917 assert_eq!(kind, WordKind::Padding);
918 }
919 other => panic!("wrong error: {other}"),
920 }
921 assert!(
922 err_text(&corrupt).contains("BARE `ret` GADGET"),
923 "the refusal must say how to fix it: {}",
924 err_text(&corrupt)
925 );
926 }
927
928 /// The other half of "no inherited padding gaps": a MISSING padding
929 /// word. `pop rdi ; pop rbx ; ret` needs two operand words; delete one
930 /// and the second `pop` swallows the next gadget address, so the chain
931 /// runs one word out of phase from there on.
932 #[test]
933 fn missing_padding_word_is_refused() {
934 let mut corrupt = chain_fixture();
935 corrupt.words.remove(2); // the `pop rbx` operand
936 let err = corrupt
937 .validate(&fixture_universe(), &[])
938 .expect_err("a chain that is one padding word short must be refused");
939 let text = err.to_string();
940 assert!(text.contains("consumes this word as data"), "{text}");
941 assert!(text.contains("CHLX-04"), "{text}");
942 }
943
944 /// A gadget whose pops run off the end of the chain.
945 #[test]
946 fn pops_past_the_end_are_refused() {
947 let mut corrupt = chain_fixture();
948 corrupt.words.truncate(2); // gadget + one of its two operands
949 let err = corrupt
950 .validate(&fixture_universe(), &[])
951 .expect_err("a chain that pops past its own end must be refused");
952 assert!(err.to_string().contains("pops past the"), "{err}");
953 }
954
955 /// Accounting stops — honestly, and with a reason — where control leaves
956 /// the chain. The words after an API entry are the callee's frame (a
957 /// return address, Win64 shadow space): no static walk can model them,
958 /// so the verifier reports them rather than pretending to check them.
959 #[test]
960 fn callee_frame_is_reported_not_guessed() {
961 let mut c = chain_fixture();
962 c.words[3] = ChainWord {
963 value: 0x7fff_1234_0000,
964 kind: WordKind::CodeAddr,
965 comment: "VirtualProtect (--api-addr)".to_string(),
966 source_gadget: None,
967 };
968 c.words.push(ChainWord {
969 value: 0x140003000,
970 kind: WordKind::CodeAddr,
971 comment: "return address: shellcode".to_string(),
972 source_gadget: None,
973 });
974 for _ in 0..4 {
975 c.words.push(ChainWord {
976 value: 0x4141414141414141,
977 kind: WordKind::Padding,
978 comment: "shadow space (Win64 ABI)".to_string(),
979 source_gadget: None,
980 });
981 }
982 c.gadgets.truncate(1);
983 c.validate(&fixture_universe(), &[]).unwrap();
984 let acct = c.verify_stack_accounting().unwrap();
985 assert_eq!(acct.callee_frame_from, Some(4));
986 assert_eq!(acct.words_verified(), 4);
987 assert!(acct.roles[4..].iter().all(|r| *r == WordRole::CalleeFrame));
988 assert!(
989 acct.stop_reason.contains("callee's frame"),
990 "{}",
991 acct.stop_reason
992 );
993 }
994
995 /// `ret <imm>` discards `imm` bytes of stack after taking its return
996 /// address — the stdcall shape. The walk accounts for those words too.
997 #[test]
998 fn ret_imm_discards_its_operands() {
999 let c = RopChain {
1000 arch: "x86".to_string(),
1001 description: "test".to_string(),
1002 script_comment: "#".to_string(),
1003 word_size: 4,
1004 gadgets: vec![
1005 GadgetRef {
1006 vaddr: 0x8048000,
1007 text: "pop eax ; ret 0x8".to_string(),
1008 },
1009 GadgetRef {
1010 vaddr: 0x8048100,
1011 text: "int 0x80".to_string(),
1012 },
1013 ],
1014 words: vec![
1015 ChainWord {
1016 value: 0x8048000,
1017 kind: WordKind::GadgetAddr,
1018 comment: "pop eax ; ret 0x8".to_string(),
1019 source_gadget: Some(0),
1020 },
1021 ChainWord {
1022 value: 0xb,
1023 kind: WordKind::DataAddr,
1024 comment: "eax".to_string(),
1025 source_gadget: None,
1026 },
1027 ChainWord {
1028 value: 0x8048100,
1029 kind: WordKind::GadgetAddr,
1030 comment: "int 0x80".to_string(),
1031 source_gadget: Some(1),
1032 },
1033 ChainWord {
1034 value: 0x41414141,
1035 kind: WordKind::Padding,
1036 comment: "discarded by ret 0x8".to_string(),
1037 source_gadget: None,
1038 },
1039 ChainWord {
1040 value: 0x41414141,
1041 kind: WordKind::Padding,
1042 comment: "discarded by ret 0x8".to_string(),
1043 source_gadget: None,
1044 },
1045 ],
1046 };
1047 let acct = c.verify_stack_accounting().unwrap();
1048 assert_eq!(
1049 acct.roles,
1050 vec![
1051 WordRole::ControlTransfer,
1052 WordRole::PopOperand,
1053 WordRole::ControlTransfer,
1054 WordRole::PopOperand,
1055 WordRole::PopOperand,
1056 ]
1057 );
1058 }
1059
1060 /// A stack pivot moves rsp by an amount the walk does not model. It must
1061 /// STOP and say so, not silently report a wrong verdict — CHWIN-08 adds
1062 /// pivots, and a verifier that guesses there is worse than one that
1063 /// abstains.
1064 #[test]
1065 fn unmodelled_stack_effect_stops_the_walk() {
1066 let mut c = chain_fixture();
1067 c.gadgets[0].text = "add rsp, 0x18 ; ret".to_string();
1068 c.words[0].comment = "add rsp, 0x18 ; ret".to_string();
1069 c.validate(&fixture_universe(), &[]).unwrap();
1070 let acct = c.verify_stack_accounting().unwrap();
1071 assert_eq!(acct.callee_frame_from, Some(1));
1072 assert!(
1073 acct.stop_reason.contains("unmodelled"),
1074 "{}",
1075 acct.stop_reason
1076 );
1077 }
1078
1079 fn err_text(c: &RopChain) -> String {
1080 c.validate(&fixture_universe(), &[])
1081 .unwrap_err()
1082 .to_string()
1083 }
1084
1085 #[test]
1086 fn validate_rejects_unknown_gadget_addr() {
1087 let mut c = chain_fixture();
1088 c.words[0].value = 0xdead0000;
1089 let universe: HashSet<u64> = [0x401000].into_iter().collect();
1090 let err = c.validate(&universe, &[]).unwrap_err();
1091 assert!(matches!(err, ChainError::InvalidWord { index: 0, .. }));
1092 }
1093
1094 #[test]
1095 fn validate_rejects_source_mismatch_and_missing_index() {
1096 let universe: HashSet<u64> = [0x401000, 0x401002].into_iter().collect();
1097 let mut c = chain_fixture();
1098 c.words[0].value = 0x401002; // in universe but != gadgets[0].vaddr
1099 assert!(c.validate(&universe, &[]).is_err());
1100 let mut c = chain_fixture();
1101 c.words[0].source_gadget = None;
1102 assert!(c.validate(&universe, &[]).is_err());
1103 let mut c = chain_fixture();
1104 c.words[0].source_gadget = Some(7);
1105 assert!(c.validate(&universe, &[]).is_err());
1106 }
1107
1108 #[test]
1109 fn validate_rejects_badbyte_immediates_and_data_addrs() {
1110 let c = chain_fixture();
1111 let universe = fixture_universe();
1112 // 0x6bc080 packs to 80 c0 6b 00 ... — byte 00 is bad
1113 let err = c.validate(&universe, &[0x00]).unwrap_err();
1114 assert!(matches!(err, ChainError::InvalidWord { index: 1, .. }));
1115 // 0x41 in the padding constant
1116 let err = c.validate(&universe, &[0x41]).unwrap_err();
1117 assert!(matches!(err, ChainError::InvalidWord { index: 2, .. }));
1118 // gadget words are not re-checked (they passed scan-time badbytes)
1119 c.validate(&universe, &[0x10]).unwrap();
1120 }
1121
1122 #[test]
1123 fn invariant_hooks_run() {
1124 let c = chain_fixture();
1125 let universe = fixture_universe();
1126 let reject: ChainInvariant = &|_| {
1127 Err(ChainError::InvalidWord {
1128 index: 0,
1129 value: 0,
1130 kind: WordKind::GadgetAddr,
1131 reason: "hook says no".to_string(),
1132 })
1133 };
1134 let err = c.validate_with(&universe, &[], &[reject]).unwrap_err();
1135 assert!(err.to_string().contains("hook says no"));
1136 }
1137
1138 #[test]
1139 fn python_renderer_matches_ropmaker_format() {
1140 let c = chain_fixture();
1141 let py = c.to_python();
1142 assert!(py.starts_with(
1143 "#!/usr/bin/env python3\n# execve generated by ROPgadget\n\nfrom struct import pack\n\n# Padding goes here\np = b''\n\n"
1144 ));
1145 assert!(py.contains("p += pack('<Q', 0x0000000000401000) # pop rdi ; pop rbx ; ret\n"));
1146 assert!(py.contains("p += pack('<Q', 0x00000000006bc080) # @ .data\n"));
1147 }
1148
1149 /// ROB-05: ropmaker indents padding lines with a literal tab, which
1150 /// makes every script with a padding word an `IndentationError`. We
1151 /// deliberately diverge — every line is at column 0.
1152 #[test]
1153 fn padding_lines_are_not_indented() {
1154 let c = chain_fixture();
1155 let py = c.to_python();
1156 assert!(py.contains("p += pack('<Q', 0x4141414141414141) # padding\n"));
1157 assert!(!py.contains('\t'), "{py}");
1158 assert_flat_python_script(&py);
1159 assert_python_parses(&py);
1160 }
1161
1162 #[test]
1163 fn x86_pack_format() {
1164 let mut c = chain_fixture();
1165 c.word_size = 4;
1166 let py = c.to_python();
1167 assert!(py.contains("pack('<I', 0x00401000)"));
1168 assert!(py.contains("p += pack('<I', 0x41414141) # padding\n"));
1169 assert!(!py.contains('\t'), "{py}");
1170 // raw bytes are 4-byte LE words
1171 let raw = c.to_bytes();
1172 assert_eq!(raw.len(), 16);
1173 assert_eq!(&raw[0..4], &0x401000u32.to_le_bytes());
1174 }
1175
1176 #[test]
1177 fn immediate_renders_as_python_bytes() {
1178 let mut c = chain_fixture();
1179 c.words.push(ChainWord {
1180 value: u64::from_le_bytes(*b"/bin//sh"),
1181 kind: WordKind::Immediate,
1182 comment: String::new(),
1183 source_gadget: None,
1184 });
1185 let py = c.to_python();
1186 assert!(py.contains("p += b'/bin//sh'\n"));
1187 let raw = c.to_bytes();
1188 assert_eq!(&raw[32..40], b"/bin//sh");
1189 }
1190
1191 /// ROB-01: the sanitiser itself.
1192 #[test]
1193 fn py_comment_strips_control_chars_and_truncates() {
1194 assert_eq!(
1195 py_comment("@ IAT VirtualProtect (KERNEL32.dll)"),
1196 "@ IAT VirtualProtect (KERNEL32.dll)"
1197 );
1198 // newlines, carriage returns and tabs are removed, not escaped
1199 assert_eq!(
1200 py_comment("KERNEL32\nimport os\r\nx\t.dll"),
1201 "KERNEL32import osx.dll"
1202 );
1203 // everything else outside 0x20..=0x7e goes too (NUL, DEL, non-ASCII)
1204 assert_eq!(py_comment("a\u{0}b\u{7f}c\u{e9}d\u{1f600}"), "abcd");
1205 assert_eq!(py_comment(&"A".repeat(4096)).len(), PY_COMMENT_MAX);
1206 }
1207
1208 /// ROB-01: a comment carried in the IR cannot break out of the `#`,
1209 /// whichever word kind or the script header carries it.
1210 #[test]
1211 fn tainted_comments_cannot_escape_the_python_comment() {
1212 let mut c = chain_fixture();
1213 c.script_comment = "# hdr\nimport os\nos.system('id')".to_string();
1214 c.words[0].comment = "pop rdi ; ret\nimport os\nos.system('id')".to_string();
1215 c.words[1].comment = "@ .data\nimport os\nos.system('id')".to_string();
1216 c.words[2].comment = "padding\nimport os\nos.system('id')".to_string();
1217 let py = c.to_python();
1218 assert!(py.contains("os.system('id')"), "{py}");
1219 for line in py.lines() {
1220 assert!(
1221 !line.starts_with("import os"),
1222 "injected statement: {line:?}"
1223 );
1224 }
1225 assert_only_in_comment(&py, "import os");
1226 assert_only_in_comment(&py, "os.system('id')");
1227 assert_flat_python_script(&py);
1228 assert_python_parses(&py);
1229 }
1230
1231 /// A `script_comment` that is not already a comment still renders as
1232 /// one, so the second line of the script is never a statement.
1233 #[test]
1234 fn script_comment_is_forced_into_a_comment() {
1235 let mut c = chain_fixture();
1236 c.script_comment = "os.system('id')".to_string();
1237 let py = c.to_python();
1238 assert!(
1239 py.starts_with("#!/usr/bin/env python3\n# os.system('id')\n"),
1240 "{py}"
1241 );
1242 assert_flat_python_script(&py);
1243 }
1244
1245 #[test]
1246 fn json_renderer_roundtrips() {
1247 let c = chain_fixture();
1248 let v = c.to_json();
1249 assert_eq!(v["arch"], "x64");
1250 assert_eq!(v["word_size"], 8);
1251 assert_eq!(v["words"][0]["value"], "0x401000");
1252 assert_eq!(v["words"][0]["kind"], "gadget_addr");
1253 assert_eq!(v["gadgets"][0]["text"], "pop rdi ; pop rbx ; ret");
1254 }
1255}