reknife 1.4.0

A reverse engineer's binary Swiss-army knife: parse, triage, and disassemble PE/ELF/Mach-O. Installs as `knife`.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
//! The bug finder: which sink call sites look wrong, not just which exist.
//!
//! `sinks` answers "where is `memcpy` called". That still leaves a researcher
//! reading every one. `audit` reads them first: for each catalogued call it
//! recovers where the interesting argument came from and keeps only the sites
//! whose provenance matches a bug pattern. A `memcpy` whose length was just
//! computed by a subtraction, an allocation sized by a multiply, a `printf`
//! whose format string is loaded from memory rather than pointed at a
//! constant: those are where the bugs are, and those are what it prints.
//!
//! The provenance is an intra-block backward walk over x86-64 registers. It is
//! deliberately shallow and deliberately honest: it looks back only within the
//! call's own basic block, stops at the previous call (argument registers do
//! not survive one), and when it cannot see where a value came from it says
//! nothing rather than guess. That keeps the false-positive rate low enough
//! that a finding is worth a researcher's attention, which is the only metric
//! that matters for a tool like this.

use crate::analysis::engine::Analysis;
use crate::analysis::thunks::bare_name;
use crate::model::{Arch, Binary, Format};
use iced_x86::{
    Decoder, DecoderOptions, Instruction, InstructionInfoFactory, Mnemonic, OpAccess, OpKind,
    Register,
};
use serde::Serialize;
use std::collections::{BTreeSet, VecDeque};

/// What to inspect about a given sink, and the 1-based C argument index.
#[derive(Clone, Copy)]
enum Check {
    /// A format-string argument that should be a fixed constant, not a value
    /// loaded at runtime.
    Format(u8),
    /// An allocation size, suspicious when computed by multiplication.
    AllocSize(u8),
    /// A copy length, suspicious when computed by subtraction or multiplication.
    CopySize(u8),
    /// A copy with no length argument at all; only the reachability matters.
    Unbounded,
}

/// The auditable subset of the sink surface, with what to check on each. An
/// API may carry more than one check (`sprintf` is both a format sink and an
/// unbounded copy).
fn checks(api: &str) -> &'static [Check] {
    use Check::*;
    match api {
        // format-string sinks: the format argument, by C position
        "printf" | "vprintf" => &[Format(1)],
        "fprintf" | "vfprintf" | "syslog" | "wsprintfA" | "wsprintfW" => &[Format(2)],
        "sprintf" | "vsprintf" => &[Format(2), Unbounded],
        "snprintf" | "_snprintf" => &[Format(3)],
        // allocation size
        "malloc" => &[AllocSize(1)],
        "realloc" | "VirtualAlloc" => &[AllocSize(2)],
        "HeapAlloc" => &[AllocSize(3)],
        // sized copies: the length argument
        "memcpy" | "memmove" | "memset" | "RtlCopyMemory" | "CopyMemory" | "bcopy" | "strncpy"
        | "strncat" | "wcsncpy" => &[CopySize(3)],
        // copies with no bound
        "strcpy" | "strcat" | "gets" | "wcscpy" | "wcscat" | "lstrcpyA" | "lstrcpyW"
        | "lstrcatA" | "lstrcatW" | "StrCpyA" | "StrCpyW" => &[Unbounded],
        _ => &[],
    }
}

#[derive(Debug, Clone, Serialize)]
pub struct Finding {
    /// Address of the calling instruction.
    pub addr: u64,
    pub func: Option<String>,
    pub api: String,
    /// Kebab-case pattern id, stable for scripting.
    pub pattern: &'static str,
    /// 3 = looks exploitable, 2 = worth a close look, 1 = context worth knowing.
    pub severity: u8,
    pub detail: String,
    /// The call sits in a function reachable from an entry point or export.
    pub reachable: bool,
}

/// What the backward walk concluded about where a register's value came from.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Origin {
    /// A fixed address: `lea reg, [rip+k]` or `mov reg, imm`. Not attacker
    /// controlled, so a format pointer that is one of these is safe.
    Fixed,
    /// Loaded from memory or copied from another register: a runtime value.
    Dynamic,
    /// Produced by a multiply or a left shift.
    Multiply,
    /// Produced by a subtraction.
    Subtract,
    /// A small constant immediate (a length known at compile time).
    Constant,
    /// A pointer into the stack frame: `lea reg, [rsp+k]` / `[rbp-k]`. As a copy
    /// destination this is a fixed-size stack buffer, so an unbounded write into
    /// it is the classic stack overflow.
    Stack,
    /// No defining instruction was found in the block before the call.
    Unknown,
}

pub fn run(an: &Analysis, bin: &Binary, bytes: &[u8]) -> Vec<Finding> {
    // The provenance walk is x86-only; other architectures get no findings
    // rather than wrong ones. The caller tells the user why.
    if !matches!(an.arch, Arch::X86 | Arch::X86_64) {
        return Vec::new();
    }
    let win64 = bin.format == Format::Pe && an.bits == 64;
    let reachable = reachable_functions(an, bin);

    let mut out = Vec::new();
    for f in &an.functions {
        let from_entry = reachable.contains(&f.addr);
        for block in &f.blocks {
            for (i, ins) in block.insns.iter().enumerate() {
                let Some(target) = ins.target else { continue };
                // Resolve the call target to a bare API name.
                let Some(full) = an.imports.get(&target).or_else(|| an.names.get(&target)) else {
                    continue;
                };
                let api = bare_name(full);
                let cs = checks(api);
                if cs.is_empty() {
                    continue;
                }
                for check in cs {
                    if let Some(mut fnd) =
                        classify(*check, api, an, bin, bytes, block, i, win64, from_entry)
                    {
                        fnd.func = Some(f.name.clone());
                        out.push(fnd);
                    }
                }
            }
        }
    }

    out.sort_by(|a, b| {
        b.severity
            .cmp(&a.severity)
            .then(b.reachable.cmp(&a.reachable))
            .then(a.addr.cmp(&b.addr))
    });
    out
}

#[allow(clippy::too_many_arguments)]
fn classify(
    check: Check,
    api: &str,
    an: &Analysis,
    bin: &Binary,
    bytes: &[u8],
    block: &crate::analysis::engine::BasicBlock,
    call_idx: usize,
    win64: bool,
    reachable: bool,
) -> Option<Finding> {
    let addr = block.insns[call_idx].addr + an.display_base;
    let mk = |pattern, severity, detail: String| Finding {
        addr,
        func: None,
        api: api.to_string(),
        pattern,
        severity,
        detail,
        reachable,
    };

    // The copy destination is the first argument of every copy sink. A write
    // into a fixed-size stack buffer is the classic overflow, so it is worth
    // knowing whichever length pattern applies.
    let dest_is_stack =
        provenance(an, bin, bytes, block, call_idx, 1, win64).origin == Origin::Stack;

    match check {
        Check::Unbounded => {
            // An unbounded copy into a stack buffer is the textbook stack
            // overflow; that is a stronger, more specific finding than a bare
            // unbounded copy, and it is high severity on its own merit.
            if dest_is_stack {
                return Some(mk(
                    "stack-overflow",
                    3,
                    "unbounded copy into a stack buffer (classic stack overflow)".to_string(),
                ));
            }
            // No length argument to inspect; the finding is the call plus reach.
            let sev = if reachable { 3 } else { 2 };
            let detail = if reachable {
                "unbounded copy reachable from an entry point or export".to_string()
            } else {
                "unbounded copy; no length argument bounds the write".to_string()
            };
            Some(mk("unbounded-copy", sev, detail))
        }
        Check::Format(arg) => {
            // A format pointer that is a fixed constant is the normal, safe
            // case; a runtime pointer is the format-string bug. Anything we
            // could not resolve is left alone rather than guessed at.
            match provenance(an, bin, bytes, block, call_idx, arg, win64).origin {
                Origin::Dynamic => Some(mk(
                    "format-string",
                    3,
                    "format argument is loaded at runtime, not a constant string".to_string(),
                )),
                _ => None,
            }
        }
        // A size that is clamped or masked before the call cannot actually reach
        // an extreme, so the finding is kept but ranked well below the raw ones:
        // still worth a glance, no longer worth an afternoon.
        Check::AllocSize(arg) => {
            let p = provenance(an, bin, bytes, block, call_idx, arg, win64);
            match p.origin {
                Origin::Multiply => Some(sized(
                    &mk,
                    "alloc-overflow",
                    3,
                    "allocation size computed by multiplication (integer overflow?)",
                    p.bounded,
                )),
                Origin::Subtract => Some(sized(
                    &mk,
                    "alloc-underflow",
                    2,
                    "allocation size computed by subtraction",
                    p.bounded,
                )),
                _ => None,
            }
        }
        Check::CopySize(arg) => {
            let p = provenance(an, bin, bytes, block, call_idx, arg, win64);
            // A stack destination turns an attacker-influenced length into a
            // stack-smash rather than a heap one, worth saying in the finding.
            let dst = if dest_is_stack {
                " into a stack buffer"
            } else {
                ""
            };
            match p.origin {
                Origin::Subtract => Some(sized(
                    &mk,
                    "copy-underflow",
                    3,
                    &format!(
                        "copy length computed by subtraction (integer underflow to a huge size?){dst}"
                    ),
                    p.bounded,
                )),
                Origin::Multiply => Some(sized(
                    &mk,
                    "copy-overflow",
                    2,
                    &format!("copy length computed by multiplication (integer overflow?){dst}"),
                    p.bounded,
                )),
                _ => None,
            }
        }
    }
}

/// Build a size-argument finding, downgrading it a band and annotating it when
/// the value was clamped or masked before the call.
fn sized(
    mk: &dyn Fn(&'static str, u8, String) -> Finding,
    pattern: &'static str,
    severity: u8,
    detail: &str,
    bounded: bool,
) -> Finding {
    if bounded {
        // A clamped or masked size is likely safe, so it sinks to the bottom
        // band rather than merely one step down.
        mk(
            pattern,
            1,
            format!("{detail}; but clamped or masked before the call, likely safe"),
        )
    } else {
        mk(pattern, severity, detail.to_string())
    }
}

/// Which 64-bit register carries C argument `n` (1-based) under the ABI.
fn arg_register(n: u8, win64: bool) -> Option<Register> {
    let table: &[Register] = if win64 {
        &[Register::RCX, Register::RDX, Register::R8, Register::R9]
    } else {
        &[
            Register::RDI,
            Register::RSI,
            Register::RDX,
            Register::RCX,
            Register::R8,
            Register::R9,
        ]
    };
    table.get((n as usize).checked_sub(1)?).copied()
}

/// What the backward walk found about an argument: where its value came from,
/// and whether it was bounded before the call.
struct Prov {
    origin: Origin,
    /// A clamp (`cmp` + `cmov`) or a mask (`and reg, imm`) was applied to the
    /// value between its computation and the call, so a raw subtraction or
    /// multiply cannot actually reach an extreme.
    bounded: bool,
}

/// Walk backward through the block from the call to find where the argument
/// register was last written, classify it, and note any clamp on the way.
fn provenance(
    an: &Analysis,
    bin: &Binary,
    bytes: &[u8],
    block: &crate::analysis::engine::BasicBlock,
    call_idx: usize,
    arg: u8,
    win64: bool,
) -> Prov {
    let Some(target) = arg_register(arg, win64) else {
        return Prov {
            origin: Origin::Unknown,
            bounded: false,
        };
    };
    // The register we are currently tracing. A plain register-to-register move
    // retargets it to the source, so a value that was computed in one register
    // and moved into the argument register is followed to its real origin.
    let mut want = target.full_register();
    let mut bounded = false;

    let mut info = InstructionInfoFactory::new();
    for j in (0..call_idx).rev() {
        let ins = &block.insns[j];
        let Some(d) = decode_one(&ins.bytes, ins.addr, an.bits) else {
            continue;
        };
        // Argument registers do not survive an intervening call, so a value set
        // before one is not the value passed here.
        if matches!(d.mnemonic(), Mnemonic::Call) {
            return Prov {
                origin: Origin::Unknown,
                bounded,
            };
        }

        // A conditional move into the tracked register is the min/max clamp
        // idiom (`cmp size, limit; cmova size, limit`). It writes the register
        // only conditionally, so the backward walk would otherwise step past it
        // to the raw arithmetic and call a bounded value dangerous. Record the
        // clamp and keep following the kept value.
        if is_cmov(&d) && writes_reg(&mut info, &d, want) {
            bounded = true;
            continue;
        }

        let writes = writes_reg(&mut info, &d, want);
        if !writes {
            continue;
        }
        // A mask bounds the value to the immediate, which is the other way a
        // subtraction or product is made safe.
        if d.mnemonic() == Mnemonic::And && d.op1_kind() != OpKind::Register {
            bounded = true;
        }
        // Follow a copy: `mov edi, eax` means the value's real origin is
        // whatever last wrote eax, so keep walking with that register.
        if d.mnemonic() == Mnemonic::Mov
            && d.op0_kind() == OpKind::Register
            && d.op1_kind() == OpKind::Register
        {
            want = d.op1_register().full_register();
            continue;
        }
        return Prov {
            origin: origin_of(&d, bin, an, bytes),
            bounded,
        };
    }
    Prov {
        origin: Origin::Unknown,
        bounded,
    }
}

/// Does this instruction write (or conditionally write) the given 64-bit reg?
fn writes_reg(info: &mut InstructionInfoFactory, d: &Instruction, want: Register) -> bool {
    info.info(d)
        .used_registers()
        .iter()
        .filter(|u| {
            matches!(
                u.access(),
                OpAccess::Write | OpAccess::ReadWrite | OpAccess::CondWrite
            )
        })
        .any(|u| u.register().is_gpr() && u.register().full_register() == want)
}

/// Every conditional-move variant, without listing all sixteen: their debug
/// names all begin with `Cmov`.
fn is_cmov(d: &Instruction) -> bool {
    format!("{:?}", d.mnemonic()).starts_with("Cmov")
}

/// Classify the instruction that defined an argument register.
fn origin_of(d: &Instruction, bin: &Binary, an: &Analysis, bytes: &[u8]) -> Origin {
    match d.mnemonic() {
        Mnemonic::Imul | Mnemonic::Mul => Origin::Multiply,
        // A left shift is a multiply by a power of two; on a size it overflows
        // the same way.
        Mnemonic::Shl | Mnemonic::Sal => Origin::Multiply,
        Mnemonic::Sub | Mnemonic::Sbb => Origin::Subtract,
        // `lea reg, [base + index*scale]` with a real index is a multiply; a
        // frame-relative lea is a stack buffer; a plain `lea reg, [rip+k]` is a
        // fixed address.
        Mnemonic::Lea => {
            let base = d.memory_base();
            if matches!(
                base,
                Register::RSP | Register::ESP | Register::RBP | Register::EBP
            ) && d.memory_index() == Register::None
            {
                Origin::Stack
            } else if d.memory_index() != Register::None {
                Origin::Multiply
            } else {
                Origin::Fixed
            }
        }
        Mnemonic::Mov => classify_mov(d, bin, an, bytes),
        Mnemonic::Movzx | Mnemonic::Movsx | Mnemonic::Movsxd => Origin::Dynamic,
        Mnemonic::Xor => {
            // xor reg, reg is the idiom for zero.
            if d.op0_register() == d.op1_register() {
                Origin::Constant
            } else {
                Origin::Dynamic
            }
        }
        _ => Origin::Dynamic,
    }
}

fn classify_mov(d: &Instruction, bin: &Binary, an: &Analysis, bytes: &[u8]) -> Origin {
    match d.op1_kind() {
        // mov reg, imm: a compile-time constant. A pointer-sized immediate that
        // lands on a mapped string is a fixed format pointer; otherwise it is a
        // constant length.
        OpKind::Immediate8
        | OpKind::Immediate16
        | OpKind::Immediate32
        | OpKind::Immediate32to64
        | OpKind::Immediate64 => {
            let imm = d.immediate(1);
            if points_at_string(bin, an, bytes, imm) {
                Origin::Fixed
            } else {
                Origin::Constant
            }
        }
        // mov reg, [mem]: a runtime load.
        OpKind::Memory => Origin::Dynamic,
        // mov reg, reg: value came from another register (often a call return).
        OpKind::Register => Origin::Dynamic,
        _ => Origin::Dynamic,
    }
}

/// Does this address land within a string literal in a mapped section? Used to
/// tell a fixed format-string pointer from a dangerous runtime one.
fn points_at_string(bin: &Binary, an: &Analysis, bytes: &[u8], va: u64) -> bool {
    let base = an.display_base;
    let Some(off) = crate::analysis::engine::va_to_off(bin, base, va) else {
        return false;
    };
    // A printable run of a few bytes at the target is a string constant.
    bytes
        .get(off..off + 4)
        .is_some_and(|w| w.iter().all(|&b| (0x20..0x7f).contains(&b)))
}

/// Decode a single instruction from an engine block's stored bytes, so the
/// audit can read operands the block model does not keep.
fn decode_one(raw: &[u8], ip: u64, bits: u32) -> Option<Instruction> {
    if raw.is_empty() {
        return None;
    }
    let mut dec = Decoder::with_ip(bits, raw, ip, DecoderOptions::NONE);
    if !dec.can_decode() {
        return None;
    }
    let insn = dec.decode();
    (!insn.is_invalid()).then_some(insn)
}

/// Functions reachable from the entry point or an export, by forward walk over
/// the recovered call graph. A sink inside one of these is attacker-reachable.
fn reachable_functions(an: &Analysis, bin: &Binary) -> BTreeSet<u64> {
    let base = crate::analysis::engine::display_base(bin);
    let is_func: BTreeSet<u64> = an.functions.iter().map(|f| f.addr).collect();

    let mut roots: Vec<u64> = bin
        .symbols
        .iter()
        .filter(|s| s.kind == crate::model::SymKind::Export)
        .map(|s| s.addr + base)
        .filter(|a| is_func.contains(a))
        .collect();
    let entry = bin.entry + base;
    if is_func.contains(&entry) {
        roots.push(entry);
    }

    let mut seen: BTreeSet<u64> = roots.iter().copied().collect();
    let mut queue: VecDeque<u64> = roots.into_iter().collect();
    while let Some(a) = queue.pop_front() {
        let Some(f) = an.find_function(a) else {
            continue;
        };
        for &callee in &f.calls {
            if is_func.contains(&callee) && seen.insert(callee) {
                queue.push_back(callee);
            }
        }
    }
    seen
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::analysis::engine;
    use crate::db::Db;
    use crate::model::{Section, SymKind, Symbol};

    /// Assemble a single function: a run of x86-64 bytes at `va` ending in the
    /// caller's `ret`, plus an imported sink at `slot` that the code calls via
    /// `call [rip]`. Returns the analysis so a test can audit it.
    struct Harness {
        bin: Binary,
        bytes: Vec<u8>,
    }

    impl Harness {
        /// `code` is placed at 0x1000; `sink` is imported at slot 0x4000 and is
        /// the target of the final `call qword [rip+disp]` the caller appends.
        fn new(sink: &str, mut code: Vec<u8>) -> Harness {
            let va = 0x1000u64;
            let slot = 0x4000u64;
            // call qword ptr [rip+disp] -> slot. Instruction is 6 bytes.
            let call_at = va + code.len() as u64;
            let disp = (slot as i64 - (call_at as i64 + 6)) as i32;
            code.push(0xff);
            code.push(0x15);
            code.extend_from_slice(&disp.to_le_bytes());
            code.push(0xc3); // ret

            let mut bin = Binary::stub(Format::Elf, Arch::X86_64);
            bin.entry = va;
            bin.sections = vec![Section {
                name: ".text".into(),
                vaddr: va,
                vsize: code.len() as u64,
                file_off: va,
                file_size: code.len() as u64,
                entropy: 0.0,
                read: true,
                write: false,
                exec: true,
            }];
            bin.symbols = vec![Symbol {
                addr: slot,
                name: sink.into(),
                kind: SymKind::Import,
            }];
            let mut bytes = vec![0u8; va as usize];
            bytes.extend_from_slice(&code);
            Harness { bin, bytes }
        }

        fn findings(&self) -> Vec<Finding> {
            let an = engine::analyze(&self.bin, &self.bytes, 10_000, &Db::default());
            run(&an, &self.bin, &self.bytes)
        }
    }

    #[test]
    fn memcpy_length_from_subtraction_is_flagged() {
        // mov rdi, rsi ; mov edx, ecx ; sub edx, eax ; call memcpy
        // The length (rdx, SysV arg3) is a subtraction: underflow candidate.
        let code = vec![
            0x48, 0x89, 0xf7, // mov rdi, rsi
            0x89, 0xca, // mov edx, ecx
            0x29, 0xc2, // sub edx, eax
        ];
        let f = Harness::new("memcpy", code).findings();
        let hit = f
            .iter()
            .find(|x| x.pattern == "copy-underflow")
            .expect("expected copy-underflow");
        assert_eq!(hit.severity, 3, "an unclamped subtraction is high severity");
    }

    #[test]
    fn a_clamped_subtraction_is_downgraded_not_dropped() {
        // sub edx, eax ; cmp edx, ecx ; cmova edx, ecx ; call memcpy
        // The length (rdx, SysV arg3) is a subtraction, but the cmov clamps it,
        // so it is the safe min()/max() idiom, not an underflow. The finding
        // should survive but drop below the raw ones.
        let code = vec![
            0x29, 0xc2, // sub edx, eax
            0x39, 0xca, // cmp edx, ecx
            0x0f, 0x47, 0xd1, // cmova edx, ecx
        ];
        let f = Harness::new("memcpy", code).findings();
        let hit = f
            .iter()
            .find(|x| x.pattern == "copy-underflow")
            .expect("still reported");
        assert_eq!(hit.severity, 1, "a clamped subtraction is downgraded");
        assert!(hit.detail.contains("clamped or masked"));
    }

    #[test]
    fn a_clamp_through_a_move_hop_is_detected() {
        // The exact shape seen in 7z.dll: the length is computed in one 64-bit
        // register, clamped there with a cmov, then moved into the argument
        // register. The walk must follow the move and still see the clamp.
        //   sub r12, rax ; cmp r12, rcx ; cmova r12, rcx ; mov rdx, r12 ; call
        let code = vec![
            0x49, 0x29, 0xc4, // sub r12, rax
            0x49, 0x39, 0xcc, // cmp r12, rcx
            0x4c, 0x0f, 0x47, 0xe1, // cmova r12, rcx
            0x4c, 0x89, 0xe2, // mov rdx, r12   (rdx = SysV arg3)
        ];
        let f = Harness::new("memcpy", code).findings();
        let hit = f
            .iter()
            .find(|x| x.pattern == "copy-underflow")
            .expect("still reported");
        assert_eq!(hit.severity, 1, "the clamp is seen through the move hop");
    }

    #[test]
    fn strcpy_into_a_stack_buffer_is_a_stack_overflow() {
        // lea rdi, [rsp+0x20] ; call strcpy
        // The destination (rdi, SysV arg1) is a stack buffer, so an unbounded
        // strcpy into it is the textbook stack overflow, not a generic one.
        let code = vec![0x48, 0x8d, 0x7c, 0x24, 0x20]; // lea rdi, [rsp+0x20]
        let f = Harness::new("strcpy", code).findings();
        let hit = f
            .iter()
            .find(|x| x.pattern == "stack-overflow")
            .expect("expected stack-overflow");
        assert_eq!(hit.severity, 3);
        assert!(hit.detail.contains("stack buffer"));
    }

    #[test]
    fn strcpy_into_a_heap_pointer_is_a_plain_unbounded_copy() {
        // mov rdi, [rbx] ; call strcpy — the destination is a loaded pointer,
        // not a stack buffer, so it stays the generic unbounded-copy finding.
        let code = vec![0x48, 0x8b, 0x3b]; // mov rdi, [rbx]
        let f = Harness::new("strcpy", code).findings();
        assert!(f.iter().any(|x| x.pattern == "unbounded-copy"));
        assert!(!f.iter().any(|x| x.pattern == "stack-overflow"));
    }

    #[test]
    fn malloc_size_from_multiply_is_flagged() {
        // mov eax, edi ; imul eax, esi ; mov edi, eax ; call malloc
        // The size (rdi, SysV arg1) traces to an imul: overflow candidate.
        let code = vec![
            0x89, 0xf8, // mov eax, edi
            0x0f, 0xaf, 0xc6, // imul eax, esi
            0x89, 0xc7, // mov edi, eax
        ];
        let f = Harness::new("malloc", code).findings();
        assert!(
            f.iter().any(|x| x.pattern == "alloc-overflow"),
            "expected alloc-overflow, got {:?}",
            f.iter().map(|x| x.pattern).collect::<Vec<_>>()
        );
    }

    #[test]
    fn memcpy_with_a_constant_length_is_not_flagged() {
        // mov edx, 0x10 ; call memcpy — a fixed length is not a bug.
        let code = vec![0xba, 0x10, 0x00, 0x00, 0x00]; // mov edx, 16
        let f = Harness::new("memcpy", code).findings();
        assert!(
            !f.iter().any(|x| x.pattern.starts_with("copy-")),
            "a constant length must not be flagged: {:?}",
            f.iter().map(|x| x.pattern).collect::<Vec<_>>()
        );
    }

    #[test]
    fn printf_with_a_runtime_format_is_flagged() {
        // mov rdi, [rsi] ; call printf — format loaded from memory.
        let code = vec![0x48, 0x8b, 0x3e]; // mov rdi, [rsi]
        let f = Harness::new("printf", code).findings();
        assert!(
            f.iter().any(|x| x.pattern == "format-string"),
            "expected format-string, got {:?}",
            f.iter().map(|x| x.pattern).collect::<Vec<_>>()
        );
    }

    #[test]
    fn printf_with_a_fixed_format_pointer_is_not_flagged() {
        // lea rdi, [rip+k] ; call printf — a constant format string is fine.
        let code = vec![0x48, 0x8d, 0x3d, 0x10, 0x00, 0x00, 0x00]; // lea rdi,[rip+0x10]
        let f = Harness::new("printf", code).findings();
        assert!(
            !f.iter().any(|x| x.pattern == "format-string"),
            "a fixed format pointer must not be flagged: {:?}",
            f.iter().map(|x| x.pattern).collect::<Vec<_>>()
        );
    }

    #[test]
    fn strcpy_reachable_from_entry_is_high_severity() {
        // The harness places the code at the entry point, so the call is
        // reachable; an unbounded copy there is the worst case.
        let f = Harness::new("strcpy", Vec::new()).findings();
        let u = f
            .iter()
            .find(|x| x.pattern == "unbounded-copy")
            .expect("unbounded-copy expected");
        assert!(u.reachable);
        assert_eq!(u.severity, 3);
    }

    #[test]
    fn a_value_set_before_an_intervening_call_is_not_attributed() {
        // mov edx, eax (a subtraction would flag, but here it is a plain move
        // BEFORE a call) ; call something ; call memcpy — rdx does not survive
        // the first call, so the sub is not the memcpy length.
        // Represented minimally: sub edx,eax ; call [rip] (other) ; then the
        // harness appends call memcpy. The sub precedes an intervening call.
        // other import at a different slot:
        let va = 0x1000u64;
        let other = 0x5000u64;
        let mut code = vec![0x29, 0xc2]; // sub edx, eax
        let call_at = va + code.len() as u64;
        let disp = (other as i64 - (call_at as i64 + 6)) as i32;
        code.push(0xff);
        code.push(0x15);
        code.extend_from_slice(&disp.to_le_bytes()); // call [rip] -> other
        let mut h = Harness::new("memcpy", code);
        h.bin.symbols.push(Symbol {
            addr: other,
            name: "getpid".into(),
            kind: SymKind::Import,
        });
        let f = h.findings();
        assert!(
            !f.iter().any(|x| x.pattern == "copy-underflow"),
            "a value set before an intervening call must not be attributed"
        );
    }
}