rustrip 0.1.1

Make stripped Rust binaries readable again: recover slice-string boundaries, demangle symbols, and reconstruct panic source locations from release/stripped ELF/PE binaries.
Documentation
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
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
//! Parsed-binary model: ELF / PE / Mach-O, with `vaddr <-> file offset`
//! translation and size-aware readers.
//!
//! The model is intentionally narrow: it exposes only what analyzers need
//! (`Section`s, `Symbol`s, byte reads by virtual address, target architecture
//! bitness). Anything richer (full disassembly, relocation processing) is
//! deliberately out of scope — `rustrip` reasons about *data*, not control
//! flow, in v0.1.

use anyhow::{anyhow, Context, Result};
use goblin::{elf, mach, pe, Object};

/// The executable format of a parsed binary.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BinaryFormat {
    /// ELF (Unix/Linux).
    Elf,
    /// PE (Windows).
    Pe,
    /// Mach-O (macOS/iOS).
    MachO,
}

/// A named section from the binary's section table.
#[derive(Debug, Clone)]
pub struct Section {
    /// Section name (e.g. `.rodata`, `.text`).
    pub name: String,
    /// Virtual address where the section is loaded.
    pub vaddr: u64,
    /// Declared size from the section header.
    pub size: u64,
    /// Raw section bytes (may be shorter than `size` if the on-disk segment
    /// is truncated; never longer).
    pub data: Vec<u8>,
}

/// A symbol from the binary's symbol table.
#[derive(Debug, Clone)]
pub struct Symbol {
    /// Virtual address of the symbol.
    pub vaddr: u64,
    /// Demangled symbol name.
    pub name: String,
    /// Symbol size (0 if unknown).
    pub size: u64,
}

/// In-memory parsed object representing a single executable format.
///
/// File bytes are kept so that vaddrs can be resolved even if sections were
/// truncated on disk (NOBITS, sparse Mach-O, etc.) — readers return `None`
/// rather than panic when ranges fall outside the loaded segment.
pub struct Binary {
    pub path: Option<String>,
    pub format: BinaryFormat,
    pub arch: String,
    /// `true` for 64-bit objects, `false` for 32-bit. Analyzers size their
    /// pointer reads off this flag.
    pub is_64: bool,
    pub little_endian: bool,
    pub bytes: Vec<u8>,
    pub sections: Vec<Section>,
    pub symbols: Vec<Symbol>,

    /// Sorted by vaddr for binary-search lookup: `(vaddr_begin, vaddr_end_exclusive, section_index)`
    /// where the address range covered is `[begin, end)`.
    #[doc(hidden)]
    pub sec_by_vaddr: Vec<(u64, u64, usize)>,
    /// Indices into `sections` of sections we believe may host string bytes.
    #[doc(hidden)]
    pub string_sections: Vec<usize>,
}

impl Binary {
    /// Parse a raw object file (ELF, PE, or single-arch Mach-O).
    ///
    /// The input is cloned once internally so that the parsed object's
    /// `&[u8]` references (via `Elf<'_>`, `PE<'_>`, `Mach<'_>`) stay valid
    /// until we finish copying them out into owned types.
    ///
    /// # Errors
    ///
    /// Returns `Err` when goblin cannot recognize the format, when the
    /// object is truncated, when an ar archive is passed (we do not
    /// dereference archive members in v0.1), or when a Mach-O fat archive
    /// is passed (we only support single-arch slices).
    pub fn parse(path: Option<&str>, bytes: Vec<u8>) -> Result<Self> {
        let parse_buffer = bytes.clone();
        let obj = Object::parse(&parse_buffer).context("goblin: failed to parse object")?;
        match obj {
            Object::Elf(elf) => load_elf(path, &elf, bytes),
            Object::PE(pe) => load_pe(path, &pe, bytes),
            Object::Mach(mach) => load_mach(path, &mach, bytes),
            _ => Err(anyhow!("unsupported object kind (likely archive)")),
        }
    }

    /// Translate `vaddr` to `(section_index, offset_within_section)`. Returns
    /// `None` if `vaddr` falls outside the span of any loaded section.
    ///
    /// # Panics
    ///
    /// Panics if `(vaddr - section_start)` does not fit in `usize` — only
    /// possible on platforms with 32-bit pointers where the section rises
    /// above `usize::MAX` bytes. We do not support building on such a host.
    #[must_use]
    pub fn vaddr_to_offset(&self, vaddr: u64) -> Option<(usize, usize)> {
        let idx = self.sec_by_vaddr.binary_search_by(|(start, end, _)| {
            if vaddr < *start {
                std::cmp::Ordering::Greater
            } else if vaddr >= *end {
                std::cmp::Ordering::Less
            } else {
                std::cmp::Ordering::Equal
            }
        });
        idx.ok().map(|i| {
            let (start, _end, sec_i) = self.sec_by_vaddr[i];
            let off_in_sec = usize::try_from(vaddr - start)
                .expect("vaddr-to-offset: offset within section fits usize on supported targets");
            (sec_i, off_in_sec)
        })
    }

    /// Read `len` bytes at `vaddr`. Returns `None` if any byte falls
    /// outside the section bounds or the backing `data` is too short.
    #[must_use]
    pub fn read_at_vaddr(&self, vaddr: u64, len: usize) -> Option<&[u8]> {
        let (sec_i, off) = self.vaddr_to_offset(vaddr)?;
        let sec = &self.sections[sec_i];
        if off.checked_add(len)? > sec.data.len() {
            return None;
        }
        Some(&sec.data[off..off + len])
    }

    /// Read a pointer-sized value (4 bytes on 32-bit, 8 on 64-bit) at
    /// `vaddr`, respecting the binary's endianness.
    #[must_use]
    pub fn read_ptr(&self, vaddr: u64) -> Option<u64> {
        let sz = if self.is_64 { 8 } else { 4 };
        let bytes = self.read_at_vaddr(vaddr, sz)?;
        Some(if self.little_endian {
            read_le_ptr(bytes, self.is_64)
        } else {
            read_be_ptr(bytes, self.is_64)
        })
    }

    /// Read a u32 (little- or big-endian per `self.little_endian`).
    #[must_use]
    pub fn read_u32(&self, vaddr: u64) -> Option<u32> {
        let bytes = self.read_at_vaddr(vaddr, 4)?;
        Some(if self.little_endian {
            u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])
        } else {
            u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])
        })
    }

    /// `true` if `vaddr..vaddr+len` lies entirely inside a section
    /// classified as hosting string bytes (read-only data across formats).
    #[must_use]
    pub fn vaddr_in_string_section(&self, vaddr: u64, len: u64) -> bool {
        for &i in &self.string_sections {
            let sec = &self.sections[i];
            if vaddr >= sec.vaddr
                && vaddr
                    .checked_add(len)
                    .is_some_and(|e| e <= sec.vaddr + sec.size)
            {
                return true;
            }
        }
        false
    }

    /// Indices into `self.sections` of sections classified as hosting
    /// string bytes (`.rodata*`, `.rdata*`, `__cstring`, ...).
    #[must_use]
    pub fn string_section_indices(&self) -> &[usize] {
        &self.string_sections
    }

    /// All sections parsed from the object file (not all are guaranteed
    /// to contain parseable bytes — some are NOBITS or sparse).
    #[must_use]
    pub fn sections(&self) -> &[Section] {
        &self.sections
    }

    /// Test-utility constructor: build a `Binary` from a set of
    /// precomputed sections and (optionally) symbols.
    ///
    /// Used by integration tests to construct minimal-but-representative
    /// blobs without going through goblin's parser. The internal indices
    /// are rebuilt from the provided sections before the function returns.
    /// `force_string_sections` lets a test bypass the name-based
    /// predicate and pin specific sections as string-hosting.
    ///
    /// ⚠️ Public-but-test-oriented. Production callers should use
    /// `Binary::parse`. The signature may change without notice.
    #[doc(hidden)]
    #[must_use]
    pub fn from_test_parts(
        format: BinaryFormat,
        is_64: bool,
        little_endian: bool,
        sections: Vec<Section>,
        symbols: Vec<Symbol>,
        force_string_sections: Vec<usize>,
    ) -> Self {
        let mut bin = Self {
            path: None,
            format,
            arch: "test".into(),
            is_64,
            little_endian,
            bytes: vec![],
            sections,
            symbols,
            sec_by_vaddr: Vec::new(),
            string_sections: Vec::new(),
        };
        bin.build_indices();
        bin.string_sections = force_string_sections;
        bin
    }
}

// ---------------------------------------------------------------------------
// parsers — each returns an owned `Binary` so the parsed view's borrows on
// the input buffer can be dropped before we hand the buffer back to the
// caller. This is the only end-of-fn ELF<'_>-in-scope-after-bytes-moved risk
// can be eliminated cleanly.
// ---------------------------------------------------------------------------

// We return `Result<Binary>` uniformly from all three loaders so that
// `Binary::parse`'s caller code stays symmetric. The inner loaders can't
// fail for ELF in v0.1, but we keep the signature stable for the day
// when they can (e.g., a malformed Mach-O archive detection).
/// Extract section data from file bytes with boundary protection.
fn extract_section_data(off: usize, sz: usize, cap: usize, bytes: &[u8]) -> Vec<u8> {
    if sz == 0 {
        Vec::new()
    } else if let Some(end) = off.checked_add(sz) {
        if off <= cap && end <= cap {
            bytes[off..end].to_vec()
        } else if off < cap {
            bytes[off..cap].to_vec()
        } else {
            Vec::new()
        }
    } else {
        Vec::new()
    }
}

#[allow(clippy::unnecessary_wraps)]
fn load_elf(path: Option<&str>, elf: &elf::Elf<'_>, bytes: Vec<u8>) -> Result<Binary> {
    let is_64 = elf.is_64;
    let little_endian = elf.little_endian;
    let arch = arch_name_elf(elf.header.e_machine);
    let cap = bytes.len();

    let mut sections: Vec<Section> = Vec::new();
    for sc in &elf.section_headers {
        let name = elf.shdr_strtab.get_at(sc.sh_name).unwrap_or("").to_string();
        let off = usize::try_from(sc.sh_offset)
            .expect("ELF: section file offset exceeds usize on this host");
        let sz = usize::try_from(sc.sh_size).expect("ELF: section size exceeds usize on this host");
        let data = extract_section_data(off, sz, cap, &bytes);
        sections.push(Section {
            name,
            vaddr: sc.sh_addr,
            size: sc.sh_size,
            data,
        });
    }

    let mut symbols: Vec<Symbol> = Vec::new();
    for sym in elf.syms.iter().chain(elf.dynsyms.iter()) {
        if sym.st_value == 0 {
            continue;
        }
        let Some(raw) = elf.strtab.get_at(sym.st_name) else {
            continue;
        };
        if raw.is_empty() {
            continue;
        }
        symbols.push(Symbol {
            vaddr: sym.st_value,
            name: raw.to_string(),
            size: sym.st_size,
        });
    }

    let mut bin = Binary {
        path: path.map(String::from),
        format: BinaryFormat::Elf,
        arch,
        is_64,
        little_endian,
        bytes,
        sections,
        symbols,
        sec_by_vaddr: Vec::new(),
        string_sections: Vec::new(),
    };
    bin.build_indices();
    Ok(bin)
}

#[allow(clippy::unnecessary_wraps)]
fn load_pe(path: Option<&str>, pe: &pe::PE<'_>, bytes: Vec<u8>) -> Result<Binary> {
    let is_64 = pe.is_64;
    let arch = arch_name_pe(pe.header.coff_header.machine);
    let cap = bytes.len();
    let base = pe.image_base as u64; // goblin types this as `usize`; `as` is lossless on supported targets

    let mut sections: Vec<Section> = Vec::new();
    for sc in &pe.sections {
        let name = sc.name().unwrap_or("").to_string();
        let off = usize::try_from(sc.pointer_to_raw_data)
            .expect("PE: section raw pointer exceeds usize on this host");
        let sz = usize::try_from(sc.size_of_raw_data)
            .expect("PE: section raw size exceeds usize on this host");
        let data = extract_section_data(off, sz, cap, &bytes);
        let vaddr = base.wrapping_add(u64::from(sc.virtual_address));
        sections.push(Section {
            name,
            vaddr,
            size: u64::from(sc.virtual_size),
            data,
        });
    }

    let mut symbols: Vec<Symbol> = Vec::new();
    for exp in &pe.exports {
        let Some(raw) = exp.name else { continue };
        if raw.is_empty() {
            continue;
        }
        symbols.push(Symbol {
            vaddr: base.wrapping_add(exp.rva as u64),
            name: raw.to_string(),
            size: 0,
        });
    }

    let mut bin = Binary {
        path: path.map(String::from),
        format: BinaryFormat::Pe,
        arch,
        is_64,
        little_endian: true,
        bytes,
        sections,
        symbols,
        sec_by_vaddr: Vec::new(),
        string_sections: Vec::new(),
    };
    bin.build_indices();
    Ok(bin)
}

fn load_mach(path: Option<&str>, mach: &mach::Mach<'_>, bytes: Vec<u8>) -> Result<Binary> {
    let mach_bin = match mach {
        mach::Mach::Binary(b) => b,
        mach::Mach::Fat(_) => return Err(anyhow!("Mach-O fat archives are not supported")),
    };
    let is_64 = mach_bin.is_64;
    let mut sections: Vec<Section> = Vec::new();
    for seg_iter in mach_bin.segments.sections() {
        for entry in seg_iter {
            let (sc, data) = entry.context("mach-o section parse")?;
            let sectname = sc.name().unwrap_or("").to_string();
            let segname = sc.segname().unwrap_or("").to_string();
            let name = if segname.is_empty() {
                sectname
            } else {
                format!("{segname}.{sectname}")
            };
            sections.push(Section {
                name,
                vaddr: sc.addr,
                size: sc.size,
                data: data.to_vec(),
            });
        }
    }

    let mut bin = Binary {
        path: path.map(String::from),
        format: BinaryFormat::MachO,
        arch: String::from("macho"),
        is_64,
        little_endian: true,
        bytes,
        sections,
        symbols: Vec::new(),
        sec_by_vaddr: Vec::new(),
        string_sections: Vec::new(),
    };
    bin.build_indices();
    Ok(bin)
}

impl Binary {
    fn build_indices(&mut self) {
        for (i, sec) in self.sections.iter().enumerate() {
            let end = sec.vaddr.wrapping_add(sec.size);
            self.sec_by_vaddr.push((sec.vaddr, end, i));
        }
        self.sec_by_vaddr.sort_by_key(|(start, _end, _i)| *start);

        for (i, sec) in self.sections.iter().enumerate() {
            if is_string_section_name(&sec.name) {
                self.string_sections.push(i);
            }
        }
    }
}

fn read_le_ptr(bytes: &[u8], is_64: bool) -> u64 {
    if is_64 {
        let mut a = [0u8; 8];
        a.copy_from_slice(&bytes[..8]);
        u64::from_le_bytes(a)
    } else {
        let mut a = [0u8; 4];
        a.copy_from_slice(&bytes[..4]);
        u64::from(u32::from_le_bytes(a))
    }
}

fn read_be_ptr(bytes: &[u8], is_64: bool) -> u64 {
    if is_64 {
        let mut a = [0u8; 8];
        a.copy_from_slice(&bytes[..8]);
        u64::from_be_bytes(a)
    } else {
        let mut a = [0u8; 4];
        a.copy_from_slice(&bytes[..4]);
        u64::from(u32::from_be_bytes(a))
    }
}

fn is_string_section_name(name: &str) -> bool {
    if name == ".rodata" || name.starts_with(".rodata.") {
        return true;
    }
    if name == ".data.rel.ro" || name.starts_with(".data.rel.ro.") {
        return true;
    }
    if name == ".rdata" || name.starts_with(".rdata.") {
        return true;
    }
    if name == "__cstring" || name.starts_with("__cstring,") {
        return true;
    }
    if name == "__const" || name.starts_with("__const,") {
        return true;
    }
    false
}

fn arch_name_elf(machine: u16) -> String {
    use goblin::elf::header::{EM_386, EM_AARCH64, EM_ARM, EM_MIPS, EM_PPC64, EM_RISCV, EM_X86_64};
    match machine {
        EM_X86_64 => "x86_64".into(),
        EM_386 => "x86".into(),
        EM_AARCH64 => "aarch64".into(),
        EM_ARM => "arm".into(),
        EM_RISCV => "riscv".into(),
        EM_PPC64 => "ppc64".into(),
        EM_MIPS => "mips".into(),
        _ => format!("elf:{machine}"),
    }
}

fn arch_name_pe(machine: u16) -> String {
    use goblin::pe::header::{
        COFF_MACHINE_ARM, COFF_MACHINE_ARM64, COFF_MACHINE_X86, COFF_MACHINE_X86_64,
    };
    match machine {
        COFF_MACHINE_X86_64 => "x86_64".into(),
        COFF_MACHINE_X86 => "x86".into(),
        COFF_MACHINE_ARM64 => "aarch64".into(),
        COFF_MACHINE_ARM => "arm".into(),
        _ => format!("pe:{machine}"),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn fake_binary_empty() -> Binary {
        Binary {
            path: None,
            format: BinaryFormat::Elf,
            arch: "x86_64".into(),
            is_64: true,
            little_endian: true,
            bytes: vec![],
            sections: vec![Section {
                name: ".rodata".into(),
                vaddr: 0x2000,
                size: 0x1000,
                data: vec![0; 0x1000],
            }],
            symbols: vec![],
            sec_by_vaddr: vec![(0x2000, 0x3000, 0)],
            string_sections: vec![0],
        }
    }

    /// Direct unit tests for `arch_name_elf` covering every documented ELF
    /// architecture. cargo-mutants otherwise flags each individual match
    /// arm as uncaught because the only path we exercised was `x86_64`;
    /// these tests catch any future removal.
    #[test]
    fn arch_name_elf_x86_64() {
        assert_eq!(arch_name_elf(goblin::elf::header::EM_X86_64), "x86_64");
    }

    #[test]
    fn arch_name_elf_x86() {
        assert_eq!(arch_name_elf(goblin::elf::header::EM_386), "x86");
    }

    #[test]
    fn arch_name_elf_aarch64() {
        assert_eq!(arch_name_elf(goblin::elf::header::EM_AARCH64), "aarch64");
    }

    #[test]
    fn arch_name_elf_arm() {
        assert_eq!(arch_name_elf(goblin::elf::header::EM_ARM), "arm");
    }

    #[test]
    fn arch_name_elf_riscv() {
        assert_eq!(arch_name_elf(goblin::elf::header::EM_RISCV), "riscv");
    }

    #[test]
    fn arch_name_elf_ppc64() {
        assert_eq!(arch_name_elf(goblin::elf::header::EM_PPC64), "ppc64");
    }

    #[test]
    fn arch_name_elf_mips() {
        assert_eq!(arch_name_elf(goblin::elf::header::EM_MIPS), "mips");
    }

    #[test]
    fn arch_name_elf_unknown_emits_default() {
        assert_eq!(arch_name_elf(0xFFFF), "elf:65535");
    }

    #[test]
    fn arch_name_pe_x86_64() {
        assert_eq!(
            arch_name_pe(goblin::pe::header::COFF_MACHINE_X86_64),
            "x86_64"
        );
    }

    #[test]
    fn arch_name_pe_x86() {
        assert_eq!(arch_name_pe(goblin::pe::header::COFF_MACHINE_X86), "x86");
    }

    #[test]
    fn arch_name_pe_aarch64() {
        assert_eq!(
            arch_name_pe(goblin::pe::header::COFF_MACHINE_ARM64),
            "aarch64"
        );
    }

    #[test]
    fn arch_name_pe_arm() {
        assert_eq!(arch_name_pe(goblin::pe::header::COFF_MACHINE_ARM), "arm");
    }

    #[test]
    fn arch_name_pe_unknown_emits_default() {
        assert_eq!(arch_name_pe(0xBEEF), "pe:48879");
    }

    #[test]
    fn is_string_section_name_full_matrix_positive() {
        let positives = [
            ".rodata",
            ".rodata.1",
            ".rodata.foo.bar",
            ".data.rel.ro",
            ".data.rel.ro.local",
            ".rdata",
            ".rdata.0",
            "__cstring",
            "__cstring,FOO",
            "__const",
            "__const,FUNC",
        ];
        for n in positives {
            assert!(
                super::is_string_section_name(n),
                "{n} should be classified as string-hosting",
            );
        }
    }

    #[test]
    fn vaddr_lookup_in_range() {
        let b = fake_binary_empty();
        // nosemgrep: rustrip-no-unwrapping-trust-bytes (test code)
        let r = b.vaddr_to_offset(0x2000 + 5).unwrap();
        assert_eq!(r, (0, 5));
        assert!(b.vaddr_to_offset(0x3000).is_none());
        assert!(b.vaddr_to_offset(0x1FFF).is_none());
    }

    #[test]
    fn read_ptr_endianness_le() {
        let mut b = fake_binary_empty();
        // 0x1122_3344_5566_7788 little-endian
        b.sections[0].data[..8].copy_from_slice(&[0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11]);
        // nosemgrep: rustrip-no-unwrapping-trust-bytes (test code)
        assert_eq!(b.read_ptr(0x2000).unwrap(), 0x1122_3344_5566_7788);
    }

    #[test]
    fn string_section_recognized() {
        let b = fake_binary_empty();
        assert!(b.vaddr_in_string_section(0x2000, 1));
        assert!(b.vaddr_in_string_section(0x2800, 0x800));
        assert!(!b.vaddr_in_string_section(0x3000, 1));
    }

    #[test]
    fn read_be_ptr_64bit() {
        let bytes = [0x11u8, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88];
        assert_eq!(read_be_ptr(&bytes, true), 0x1122_3344_5566_7788);
    }

    #[test]
    fn read_be_ptr_32bit() {
        let bytes = [0x11u8, 0x22, 0x33, 0x44];
        assert_eq!(read_be_ptr(&bytes, false), 0x1122_3344);
    }

    #[test]
    fn read_ptr_endianness_be() {
        let mut b = fake_binary_empty();
        b.little_endian = false;
        b.sections[0].data[..8].copy_from_slice(&[0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88]);
        // nosemgrep: rustrip-no-unwrapping-trust-bytes (test code)
        assert_eq!(b.read_ptr(0x2000).unwrap(), 0x1122_3344_5566_7788);
    }

    #[test]
    fn is_string_section_name_rejects_non_string_sections() {
        assert!(!is_string_section_name(".text"));
        assert!(!is_string_section_name(".data"));
        assert!(!is_string_section_name(".bss"));
        assert!(!is_string_section_name(".got"));
        assert!(!is_string_section_name(".dynsym"));
    }

    #[test]
    fn string_section_indices_correct_with_multiple_sections() {
        // Can't use from_test_parts because it overwrites string_sections
        // with force_string_sections. Build manually to let build_indices
        // classify by name.
        let mut bin = Binary {
            path: None,
            format: BinaryFormat::Elf,
            arch: "x86_64".into(),
            is_64: true,
            little_endian: true,
            bytes: vec![],
            sections: vec![
                Section {
                    name: ".text".into(),
                    vaddr: 0x1000,
                    size: 0x100,
                    data: vec![0; 0x100],
                },
                Section {
                    name: ".rodata".into(),
                    vaddr: 0x2000,
                    size: 0x100,
                    data: vec![0; 0x100],
                },
                Section {
                    name: ".data".into(),
                    vaddr: 0x3000,
                    size: 0x100,
                    data: vec![0; 0x100],
                },
                Section {
                    name: ".rdata".into(),
                    vaddr: 0x4000,
                    size: 0x100,
                    data: vec![0; 0x100],
                },
            ],
            symbols: vec![],
            sec_by_vaddr: Vec::new(),
            string_sections: Vec::new(),
        };
        bin.build_indices();
        let indices = bin.string_section_indices();
        assert!(indices.contains(&1), ".rodata must be in string_sections");
        assert!(indices.contains(&3), ".rdata must be in string_sections");
        assert!(
            !indices.contains(&0),
            ".text must NOT be in string_sections"
        );
    }

    #[test]
    fn string_section_indices_empty_when_no_string_sections() {
        let bin = Binary::from_test_parts(
            BinaryFormat::Elf,
            true,
            true,
            vec![
                Section {
                    name: ".text".into(),
                    vaddr: 0x1000,
                    size: 0x100,
                    data: vec![0; 0x100],
                },
                Section {
                    name: ".data".into(),
                    vaddr: 0x2000,
                    size: 0x100,
                    data: vec![0; 0x100],
                },
            ],
            vec![],
            vec![],
        );
        assert!(bin.string_section_indices().is_empty());
    }

    fn minimal_elf64() -> Vec<u8> {
        let mut e = vec![0u8; 64];
        e[0..4].copy_from_slice(b"\x7fELF");
        e[4] = 2;
        e[5] = 1;
        e[6] = 1;
        e[16..18].copy_from_slice(&2u16.to_le_bytes());
        e[18..20].copy_from_slice(&62u16.to_le_bytes());
        e[20..24].copy_from_slice(&1u32.to_le_bytes());
        e[52..54].copy_from_slice(&64u16.to_le_bytes());
        e[58..60].copy_from_slice(&64u16.to_le_bytes());
        e
    }

    #[test]
    fn parse_minimal_elf_succeeds() {
        let elf = minimal_elf64();
        let bin = Binary::parse(Some("test.elf"), elf).expect("minimal ELF must parse");
        assert_eq!(bin.format, BinaryFormat::Elf);
        assert!(bin.is_64);
        assert!(bin.little_endian);
        assert_eq!(bin.arch, "x86_64");
    }

    /// Build a minimal ELF64 with one .rodata section containing "hello".
    fn elf64_with_rodata() -> Vec<u8> {
        let mut buf = vec![0u8; 64]; // ELF header
        buf[0..4].copy_from_slice(b"\x7fELF");
        buf[4] = 2;
        buf[5] = 1;
        buf[6] = 1;
        buf[16..18].copy_from_slice(&2u16.to_le_bytes());
        buf[18..20].copy_from_slice(&62u16.to_le_bytes());
        buf[20..24].copy_from_slice(&1u32.to_le_bytes());
        buf[40..48].copy_from_slice(&64u64.to_le_bytes()); // e_shoff
        buf[52..54].copy_from_slice(&64u16.to_le_bytes()); // e_ehsize
        buf[58..60].copy_from_slice(&64u16.to_le_bytes()); // e_shentsize
        buf[60..62].copy_from_slice(&2u16.to_le_bytes()); // e_shnum = 2
                                                          // Section header 0: null
        buf.extend_from_slice(&[0u8; 64]);
        // Section header 1: .rodata with 5 bytes at offset 192
        let data_off = 192u64;
        let sh1 = 64 + 64; // offset of section header 1
        buf.extend_from_slice(&[0u8; 64]);
        buf[sh1 + 4..sh1 + 8].copy_from_slice(&1u32.to_le_bytes()); // SHT_PROGBITS
        buf[sh1 + 16..sh1 + 24].copy_from_slice(&0x1000u64.to_le_bytes()); // addr
        buf[sh1 + 24..sh1 + 32].copy_from_slice(&data_off.to_le_bytes()); // offset
        buf[sh1 + 32..sh1 + 40].copy_from_slice(&5u64.to_le_bytes()); // size = 5
                                                                      // Section data
        buf.extend_from_slice(b"hello");
        buf
    }

    #[test]
    fn parse_elf_section_data_not_empty() {
        let elf = elf64_with_rodata();
        let bin = Binary::parse(Some("test.elf"), elf).expect("parse");
        let has_data = bin.sections.iter().any(|s| !s.data.is_empty());
        assert!(
            has_data,
            "at least one section must have non-empty data (kills sz==0 → != mutation)"
        );
    }

    #[test]
    fn parse_elf_truncated_section_clamps_data() {
        // Build an ELF where .rodata claims 100 bytes but only 5 exist.
        let mut elf = elf64_with_rodata();
        // Modify sh_size of section 1 to 100 (was 5)
        let sh1_size_off = 64 + 64 + 32; // header + null section + offset to sh_size
        elf[sh1_size_off..sh1_size_off + 8].copy_from_slice(&100u64.to_le_bytes());
        // File is only 197 bytes, section data starts at 192, so only 5 bytes available
        let bin = Binary::parse(Some("truncated.elf"), elf).expect("parse");
        let rodata = bin.sections.iter().find(|s| s.size == 100);
        assert!(rodata.is_some(), "section with size=100 must exist");
        // nosemgrep: rustrip-no-unwrapping-trust-bytes (test code)
        let rodata = rodata.unwrap();
        // Data must be clamped to available bytes (5), not 100
        assert_eq!(
            rodata.data.len(),
            5,
            "truncated section data must be clamped to available bytes"
        );
    }

    fn minimal_macho64() -> Vec<u8> {
        let mut m = vec![0u8; 32];
        m[0..4].copy_from_slice(&0xfeed_facf_u32.to_le_bytes());
        m[4..8].copy_from_slice(&0x0100_0007_u32.to_le_bytes());
        m[8..12].copy_from_slice(&3u32.to_le_bytes());
        m[12..16].copy_from_slice(&1u32.to_le_bytes());
        m
    }

    #[test]
    fn parse_minimal_macho_succeeds() {
        let macho = minimal_macho64();
        let bin = Binary::parse(Some("test.macho"), macho).expect("minimal Mach-O must parse");
        assert_eq!(bin.format, BinaryFormat::MachO);
        assert!(bin.is_64);
    }

    #[test]
    fn vaddr_to_offset_finds_correct_section() {
        let bin = Binary::from_test_parts(
            BinaryFormat::Elf,
            true,
            true,
            vec![
                Section {
                    name: ".text".into(),
                    vaddr: 0x1000,
                    size: 0x100,
                    data: vec![0xAA; 0x100],
                },
                Section {
                    name: ".rodata".into(),
                    vaddr: 0x2000,
                    size: 0x100,
                    data: vec![0xBB; 0x100],
                },
            ],
            vec![],
            vec![],
        );
        // nosemgrep: rustrip-no-unwrapping-trust-bytes (test code)
        let (sec_i, off) = bin.vaddr_to_offset(0x2005).unwrap();
        assert_eq!(sec_i, 1);
        assert_eq!(off, 5);
        assert_eq!(bin.read_at_vaddr(0x2005, 1).unwrap()[0], 0xBB);
    }

    #[test]
    fn parse_rejects_empty_input() {
        assert!(Binary::parse(Some("empty"), vec![]).is_err());
    }

    #[test]
    fn parse_rejects_garbage() {
        assert!(Binary::parse(Some("garbage"), vec![0x42; 128]).is_err());
    }

    // ── extract_section_data boundary tests (kill 9 load_elf/load_pe misses) ──

    #[test]
    fn extract_data_full_section_within_file() {
        // off=10, sz=5, cap=20: fully within file → bytes[10..15]
        let bytes = b"0123456789HELLO-----".to_vec();
        let data = extract_section_data(10, 5, bytes.len(), &bytes);
        assert_eq!(data, b"HELLO");
    }

    #[test]
    fn extract_data_section_extends_past_file() {
        // off=15, sz=10, cap=20: end=25 > cap=20 → truncated bytes[15..20]
        let bytes = b"0123456789ABCDEPARTI".to_vec();
        let data = extract_section_data(15, 10, bytes.len(), &bytes);
        assert_eq!(data, b"PARTI");
    }

    #[test]
    fn extract_data_offset_at_exact_file_end() {
        // off=20, sz=5, cap=20: off == cap → empty
        let bytes = b"0123456789ABCDEFGHIJ".to_vec(); // 20 bytes
        let data = extract_section_data(20, 5, bytes.len(), &bytes);
        assert!(data.is_empty(), "offset at file end must yield empty data");
    }

    #[test]
    fn extract_data_offset_past_file_end() {
        // off=25, sz=5, cap=20: off > cap → empty
        let bytes = b"0123456789ABCDEFGHIJ".to_vec();
        let data = extract_section_data(25, 5, bytes.len(), &bytes);
        assert!(
            data.is_empty(),
            "offset past file end must yield empty data"
        );
    }

    #[test]
    fn extract_data_zero_size_returns_empty() {
        let bytes = b"0123456789".to_vec();
        let data = extract_section_data(0, 0, bytes.len(), &bytes);
        assert!(data.is_empty(), "zero-size section must yield empty data");
    }

    #[test]
    fn extract_data_offset_zero_full_file() {
        // off=0, sz=10, cap=10: entire file
        let bytes = b"0123456789".to_vec();
        let data = extract_section_data(0, 10, bytes.len(), &bytes);
        assert_eq!(data, b"0123456789");
    }

    #[test]
    fn extract_data_section_at_exact_end_boundary() {
        // off=15, sz=5, cap=20: end=20 == cap → full data
        let bytes = b"0123456789ABCDEEND!!".to_vec(); // 20 bytes
        let data = extract_section_data(15, 5, bytes.len(), &bytes);
        assert_eq!(data, b"END!!");
    }

    #[test]
    fn extract_data_overflow_protection() {
        // off=usize::MAX-2, sz=10: checked_add overflows → empty
        let bytes = b"0123456789".to_vec();
        let data = extract_section_data(usize::MAX - 2, 10, bytes.len(), &bytes);
        assert!(data.is_empty(), "overflow in off+sz must yield empty data");
    }
}