elf_loader 0.15.0

A no_std-friendly ELF loader, runtime linker, and JIT linker for Rust.
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
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
//! Pre-mapping ELF descriptions and lazily readable section data.

use crate::{
    AlignedBytes, ParseDynamicError, ParsePhdrError, Result,
    arch::NativeArch,
    elf::{
        ElfDyn, ElfHeader, ElfLayout, ElfPhdr, ElfProgramType, ElfSectionFlags, ElfSectionIndex,
        ElfSectionType, ElfShdr, ElfStringTable, NativeElfLayout, parse_dynamic_entries,
    },
    entity::entity_ref,
    input::{ElfReader, ElfReaderExt, Path, PathBuf},
    loader::ScanBuilder,
    relocation::RelocationArch,
};
use alloc::{boxed::Box, vec::Vec};
use core::{fmt, mem::size_of, num::NonZeroUsize, ptr};
use elf::abi::{DF_1_NOW, DF_BIND_NOW, DF_STATIC_TLS};

struct DynamicScanParts {
    dynamic: ScannedDynamicInfo,
    strtab: Box<[u8]>,
    needed_libs: Box<[usize]>,
    soname: Option<usize>,
    rpath: Option<usize>,
    runpath: Option<usize>,
}

impl DynamicScanParts {
    fn new<L: ElfLayout>(object: &mut dyn ElfReader, phdrs: &[ElfPhdr<L>]) -> Result<Self> {
        let dynamic_phdr = phdrs
            .iter()
            .find(|phdr| phdr.program_type() == ElfProgramType::DYNAMIC)
            .ok_or(ParsePhdrError::MissingDynamicSection)?;
        if dynamic_phdr.p_filesz() % size_of::<ElfDyn<L>>() != 0 {
            return Err(
                ParsePhdrError::malformed("PT_DYNAMIC size is not a multiple of ElfDyn").into(),
            );
        }

        let dyns = object.read_to_vec::<ElfDyn<L>>(
            dynamic_phdr.p_offset(),
            dynamic_phdr.p_filesz() / core::mem::size_of::<ElfDyn<L>>(),
        )?;
        let parsed = parse_dynamic_entries(
            dyns.into_iter()
                .map(|dynamic| (dynamic.tag(), dynamic.value())),
        );

        let strtab_vaddr =
            NonZeroUsize::new(parsed.strtab_off).ok_or(ParseDynamicError::AddressOverflow)?;
        let strtab_file_off = vaddr_to_file_offset(strtab_vaddr.get(), phdrs)?;
        let strtab_size = parsed
            .strtab_size
            .ok_or(ParseDynamicError::MissingRequiredTag { tag: "DT_STRSZ" })?
            .get();
        let strtab = object.read_to_vec(strtab_file_off, strtab_size)?;

        let needed_libs = parsed
            .needed_libs
            .into_iter()
            .map(|offset| offset.get())
            .collect::<Vec<_>>()
            .into_boxed_slice();
        let soname = parsed.soname_off.map(|offset| offset.get());
        let rpath = parsed.rpath_off.map(|offset| offset.get());
        let runpath = parsed.runpath_off.map(|offset| offset.get());

        Ok(Self {
            dynamic: ScannedDynamicInfo::new(
                parsed.bind_now
                    || parsed.flags & DF_BIND_NOW as usize != 0
                    || parsed.flags_1 & DF_1_NOW as usize != 0,
                parsed.flags & DF_STATIC_TLS as usize != 0,
            ),
            strtab: strtab.into_boxed_slice(),
            needed_libs,
            soname,
            rpath,
            runpath,
        })
    }
}

struct SectionTable<L: ElfLayout = NativeElfLayout> {
    sections: Box<[ElfShdr<L>]>,
    shstrtab: Box<[u8]>,
}

impl<L: ElfLayout> SectionTable<L> {
    fn new(object: &mut dyn ElfReader, ehdr: &ElfHeader<L>) -> Result<Option<Self>> {
        if ehdr.e_shnum() == 0 {
            return Ok(None);
        }

        let Some((start, _)) = ehdr.checked_shdr_layout()? else {
            return Ok(None);
        };

        let shdrs = object.read_to_vec::<ElfShdr<L>>(start, ehdr.e_shnum())?;
        let shstrndx = ehdr.e_shstrndx();
        let shstrtab = match shdrs.get(shstrndx) {
            Some(shdr) if shdr.section_type() != ElfSectionType::NOBITS => {
                object.read_to_vec(shdr.sh_offset(), shdr.sh_size())?
            }
            _ => return Ok(None),
        };

        Ok(Some(SectionTable {
            sections: shdrs.into_boxed_slice(),
            shstrtab: shstrtab.into_boxed_slice(),
        }))
    }
}

/// The planning capability exposed by one scanned module.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum ModuleCapability {
    /// The module has no usable section-table view for planning.
    Opaque,
    /// The module exposes section metadata/data, but not enough retained
    /// relocation inputs to support section reordering repair.
    SectionData,
    /// The module exposes enough retained relocation inputs for section-level
    /// reordering and repair.
    SectionReorderable,
}

impl ModuleCapability {
    /// Returns whether this module exposes section metadata/data.
    #[inline]
    pub const fn has_section_data(self) -> bool {
        !matches!(self, Self::Opaque)
    }

    /// Returns whether this module supports section reordering repair.
    #[inline]
    pub const fn supports_reorder_repair(self) -> bool {
        matches!(self, Self::SectionReorderable)
    }
}

/// Dynamic-library metadata collected before the object is mapped.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct ScannedDynamicInfo {
    bind_now: bool,
    static_tls: bool,
}

impl ScannedDynamicInfo {
    #[inline]
    pub(crate) const fn new(bind_now: bool, static_tls: bool) -> Self {
        Self {
            bind_now,
            static_tls,
        }
    }

    /// Returns whether the object requests eager binding.
    #[inline]
    pub fn bind_now(&self) -> bool {
        self.bind_now
    }

    /// Returns whether the object requests static TLS.
    #[inline]
    pub fn static_tls(&self) -> bool {
        self.static_tls
    }
}

/// A dynamic ELF image that has been parsed but not yet mapped into memory.
pub struct ScannedDynamic<Arch: RelocationArch = NativeArch> {
    path: PathBuf,
    ehdr: ElfHeader<Arch::Layout>,
    phdrs: Box<[ElfPhdr<Arch::Layout>]>,
    interp: Option<Box<[u8]>>,
    _strtab_bytes: Box<[u8]>,
    strtab: ElfStringTable,
    section_table: Option<SectionTable<Arch::Layout>>,
    soname: Option<usize>,
    rpath: Option<usize>,
    runpath: Option<usize>,
    needed_libs: Box<[usize]>,
    capability: ModuleCapability,
    reader: Box<dyn ElfReader + 'static>,
    dynamic: ScannedDynamicInfo,
}

/// A static executable that has been parsed but not yet mapped into memory.
pub struct ScannedExec<Arch: RelocationArch = NativeArch> {
    path: PathBuf,
    ehdr: ElfHeader<Arch::Layout>,
    phdrs: Box<[ElfPhdr<Arch::Layout>]>,
    interp: Option<Box<[u8]>>,
    section_table: Option<SectionTable<Arch::Layout>>,
    #[allow(dead_code)]
    reader: Box<dyn ElfReader + 'static>,
}

/// A scanned ELF image classified by the metadata available before mapping.
#[derive(Debug)]
pub enum ScannedElf<Arch: RelocationArch = NativeArch> {
    /// An image with `PT_DYNAMIC` metadata.
    Dynamic(ScannedDynamic<Arch>),
    /// An executable without `PT_DYNAMIC` metadata.
    StaticExec(ScannedExec<Arch>),
}

pub(crate) struct ScannedDynamicLoadParts<Arch: RelocationArch = NativeArch> {
    pub(crate) ehdr: ElfHeader<Arch::Layout>,
    pub(crate) phdrs: Box<[ElfPhdr<Arch::Layout>]>,
    pub(crate) reader: Box<dyn ElfReader + 'static>,
}

/// A stable identifier for one scanned section.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(transparent)]
pub struct ScannedSectionId(usize);
entity_ref!(ScannedSectionId);

impl ScannedSectionId {
    /// Converts a symbol `st_shndx` value into a scanned section id when it
    /// names a real section table entry.
    #[inline]
    pub const fn from_symbol_shndx(index: ElfSectionIndex) -> Option<Self> {
        if index.is_undef() || index.is_abs() {
            None
        } else {
            Some(Self::new(index.index()))
        }
    }
}

/// A readable view over one scanned section and its metadata.
pub struct ScannedSection<'a, L: ElfLayout = NativeElfLayout> {
    id: ScannedSectionId,
    name: &'a str,
    header: &'a ElfShdr<L>,
}

impl<L: ElfLayout> Copy for ScannedSection<'_, L> {}

impl<L: ElfLayout> Clone for ScannedSection<'_, L> {
    #[inline]
    fn clone(&self) -> Self {
        *self
    }
}

/// Iterator over the usable section-table entries of a scanned module.
pub struct ScannedSections<'a, L: ElfLayout = NativeElfLayout> {
    sections: &'a [ElfShdr<L>],
    shstrtab: *const u8,
    index: usize,
}

impl<'a, L: ElfLayout> ScannedSections<'a, L> {
    #[inline]
    fn new(sections: &'a [ElfShdr<L>], shstrtab: *const u8) -> Self {
        Self {
            sections,
            shstrtab,
            index: 0,
        }
    }

    #[inline]
    fn section_name(&self, section: &ElfShdr<L>) -> &'a str {
        let table = ElfStringTable::new(self.shstrtab);
        table.get_str(section.sh_name() as usize)
    }
}

impl<'a, L: ElfLayout> Iterator for ScannedSections<'a, L> {
    type Item = ScannedSection<'a, L>;

    fn next(&mut self) -> Option<Self::Item> {
        let header = self.sections.get(self.index)?;
        let id = ScannedSectionId::new(self.index);
        self.index += 1;
        Some(ScannedSection::new(id, self.section_name(header), header))
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = self.sections.len().saturating_sub(self.index);
        (remaining, Some(remaining))
    }
}

impl<L: ElfLayout> ExactSizeIterator for ScannedSections<'_, L> {}

impl<'a, L: ElfLayout> ScannedSection<'a, L> {
    #[inline]
    fn new(id: ScannedSectionId, name: &'a str, header: &'a ElfShdr<L>) -> Self {
        Self { id, name, header }
    }

    /// Returns the stable section id.
    #[inline]
    pub const fn id(&self) -> ScannedSectionId {
        self.id
    }

    /// Returns the section name.
    #[inline]
    pub fn name(&self) -> &'a str {
        self.name
    }

    /// Returns the underlying ELF section header.
    #[inline]
    pub fn header(&self) -> &'a ElfShdr<L> {
        self.header
    }

    /// Returns the parsed section type.
    #[inline]
    pub fn section_type(&self) -> ElfSectionType {
        self.header.section_type()
    }

    /// Returns the parsed section flags.
    #[inline]
    pub fn flags(&self) -> ElfSectionFlags {
        self.header.flags()
    }

    /// Returns the section address.
    #[inline]
    pub fn address(&self) -> usize {
        self.header.sh_addr()
    }

    /// Returns the section file offset.
    #[inline]
    pub fn file_offset(&self) -> usize {
        self.header.sh_offset()
    }

    /// Returns the section size in bytes.
    #[inline]
    pub fn size(&self) -> usize {
        self.header.sh_size()
    }

    /// Returns the section alignment in bytes.
    #[inline]
    pub fn alignment(&self) -> usize {
        self.header.sh_addralign()
    }

    /// Returns whether the section contributes to the loaded memory image.
    #[inline]
    pub fn is_allocated(&self) -> bool {
        self.flags().contains(ElfSectionFlags::ALLOC)
    }

    /// Returns whether the section is writable after mapping.
    #[inline]
    pub fn is_writable(&self) -> bool {
        self.flags().contains(ElfSectionFlags::WRITE)
    }

    /// Returns whether the section is executable.
    #[inline]
    pub fn is_executable(&self) -> bool {
        self.flags().contains(ElfSectionFlags::EXECINSTR)
    }

    /// Returns whether the section belongs to TLS storage.
    #[inline]
    pub fn is_tls(&self) -> bool {
        self.flags().contains(ElfSectionFlags::TLS)
    }

    /// Returns whether the section is zero-fill only (`SHT_NOBITS`).
    #[inline]
    pub fn is_nobits(&self) -> bool {
        self.section_type() == ElfSectionType::NOBITS
    }

    /// Returns whether the section stores retained relocations.
    #[inline]
    pub fn is_relocation_section(&self) -> bool {
        matches!(
            self.section_type(),
            ElfSectionType::REL | ElfSectionType::RELA
        )
    }

    /// Returns the linked section id referenced by `sh_link`, when non-zero.
    #[inline]
    pub fn linked_section_id(&self) -> Option<ScannedSectionId> {
        (self.header.sh_link() != 0)
            .then_some(ScannedSectionId::new(self.header.sh_link() as usize))
    }

    /// Returns the info section id referenced by `sh_info`, when non-zero.
    #[inline]
    pub fn info_section_id(&self) -> Option<ScannedSectionId> {
        (self.header.sh_info() != 0)
            .then_some(ScannedSectionId::new(self.header.sh_info() as usize))
    }
}

impl<'a, L: ElfLayout> fmt::Debug for ScannedSection<'a, L> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ScannedSection")
            .field("id", &self.id)
            .field("name", &self.name)
            .field("type", &self.section_type())
            .field("size", &self.size())
            .field("align", &self.alignment())
            .finish()
    }
}

impl<Arch: RelocationArch> fmt::Debug for ScannedDynamic<Arch> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ScannedDynamic")
            .field("path", &self.path)
            .field("soname", &self.soname())
            .field("needed_libs", &self.needed_libs().collect::<Vec<_>>())
            .field(
                "sections",
                &self
                    .section_table
                    .as_ref()
                    .map_or(0, |table| table.sections.len()),
            )
            .field("capability", &self.capability)
            .field("bind_now", &self.dynamic.bind_now)
            .field("static_tls", &self.dynamic.static_tls)
            .finish()
    }
}

impl<Arch: RelocationArch> fmt::Debug for ScannedExec<Arch> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ScannedExec")
            .field("path", &self.path)
            .field(
                "sections",
                &self
                    .section_table
                    .as_ref()
                    .map_or(0, |table| table.sections.len()),
            )
            .finish()
    }
}

impl<Arch: RelocationArch> ScannedElf<Arch> {
    /// Returns the loader source path or caller-provided source identifier.
    #[inline]
    pub fn path(&self) -> &Path {
        match self {
            Self::Dynamic(image) => image.path(),
            Self::StaticExec(image) => image.path(),
        }
    }

    /// Returns the ELF image identity used for diagnostics.
    #[inline]
    pub fn name(&self) -> &str {
        match self {
            Self::Dynamic(image) => image.name(),
            Self::StaticExec(image) => image.name(),
        }
    }

    /// Returns the parsed ELF header.
    #[inline]
    pub fn ehdr(&self) -> &ElfHeader<Arch::Layout> {
        match self {
            Self::Dynamic(image) => image.ehdr(),
            Self::StaticExec(image) => image.ehdr(),
        }
    }

    /// Returns the parsed program headers.
    #[inline]
    pub fn phdrs(&self) -> &[ElfPhdr<Arch::Layout>] {
        match self {
            Self::Dynamic(image) => image.phdrs(),
            Self::StaticExec(image) => image.phdrs(),
        }
    }

    /// Returns the PT_INTERP string when present.
    #[inline]
    pub fn interp(&self) -> Option<&str> {
        match self {
            Self::Dynamic(image) => image.interp(),
            Self::StaticExec(image) => image.interp(),
        }
    }

    /// Returns the dynamic scan data when this is a dynamic image.
    #[inline]
    pub fn as_dynamic(&self) -> Option<&ScannedDynamic<Arch>> {
        match self {
            Self::Dynamic(image) => Some(image),
            Self::StaticExec(_) => None,
        }
    }

    /// Returns the static executable scan data when this is a static executable.
    #[inline]
    pub fn as_static_exec(&self) -> Option<&ScannedExec<Arch>> {
        match self {
            Self::Dynamic(_) => None,
            Self::StaticExec(image) => Some(image),
        }
    }

    /// Consumes this value and returns dynamic scan data when present.
    #[inline]
    pub fn into_dynamic(self) -> Option<ScannedDynamic<Arch>> {
        match self {
            Self::Dynamic(image) => Some(image),
            Self::StaticExec(_) => None,
        }
    }

    /// Consumes this value and returns static executable scan data when present.
    #[inline]
    pub fn into_static_exec(self) -> Option<ScannedExec<Arch>> {
        match self {
            Self::Dynamic(_) => None,
            Self::StaticExec(image) => Some(image),
        }
    }

    /// Returns whether the image exposes a usable section-table view.
    #[inline]
    pub fn has_sections(&self) -> bool {
        match self {
            Self::Dynamic(image) => image.has_sections(),
            Self::StaticExec(image) => image.has_sections(),
        }
    }

    /// Returns the raw ELF section headers, when the section table is usable.
    #[inline]
    pub fn section_headers(&self) -> Option<&[ElfShdr<Arch::Layout>]> {
        match self {
            Self::Dynamic(image) => image.section_headers(),
            Self::StaticExec(image) => image.section_headers(),
        }
    }

    /// Returns one scanned section by id.
    #[inline]
    pub fn section(
        &self,
        id: impl Into<ScannedSectionId>,
    ) -> Option<ScannedSection<'_, Arch::Layout>> {
        match self {
            Self::Dynamic(image) => image.section(id),
            Self::StaticExec(image) => image.section(id),
        }
    }

    /// Iterates over all scanned sections together with stable ids.
    #[inline]
    pub fn sections(&self) -> ScannedSections<'_, Arch::Layout> {
        match self {
            Self::Dynamic(image) => image.sections(),
            Self::StaticExec(image) => image.sections(),
        }
    }

    /// Iterates over sections that contribute to the loaded memory image.
    #[inline]
    pub fn alloc_sections(&self) -> impl Iterator<Item = ScannedSection<'_, Arch::Layout>> {
        self.sections().filter(|section| section.is_allocated())
    }
}

impl<Arch: RelocationArch> ScannedDynamic<Arch> {
    pub(crate) fn from_builder(builder: ScanBuilder<Arch::Layout>) -> Result<Self> {
        let ScanBuilder {
            path,
            ehdr,
            phdrs,
            mut reader,
        } = builder;
        let interp = read_interp(reader.as_mut(), &phdrs)?;
        let DynamicScanParts {
            dynamic,
            strtab,
            needed_libs,
            soname,
            rpath,
            runpath,
        } = DynamicScanParts::new(reader.as_mut(), &phdrs)?;
        let section_table = SectionTable::new(reader.as_mut(), &ehdr)?;
        let strtab_view = ElfStringTable::new(strtab.as_ptr());
        let capability = section_table
            .as_ref()
            .map_or(ModuleCapability::Opaque, |table| {
                classify_module_capability(&table.sections)
            });

        Ok(Self {
            path,
            ehdr,
            phdrs,
            interp,
            _strtab_bytes: strtab,
            strtab: strtab_view,
            section_table,
            soname,
            rpath,
            runpath,
            needed_libs,
            capability,
            reader,
            dynamic,
        })
    }

    /// Returns the loader source path or caller-provided source identifier.
    #[inline]
    pub fn path(&self) -> &Path {
        self.path.as_path()
    }

    /// Returns the ELF image identity used for diagnostics.
    #[inline]
    pub fn name(&self) -> &str {
        self.soname().unwrap_or_else(|| self.path().file_name())
    }

    /// Returns the parsed ELF header.
    #[inline]
    pub fn ehdr(&self) -> &ElfHeader<Arch::Layout> {
        &self.ehdr
    }

    /// Returns the parsed program headers.
    #[inline]
    pub fn phdrs(&self) -> &[ElfPhdr<Arch::Layout>] {
        &self.phdrs
    }

    /// Returns the PT_INTERP string when present.
    #[inline]
    pub fn interp(&self) -> Option<&str> {
        self.interp.as_deref().and_then(|bytes| {
            let end = bytes
                .iter()
                .position(|byte| *byte == 0)
                .unwrap_or(bytes.len());
            core::str::from_utf8(&bytes[..end]).ok()
        })
    }

    /// Returns the DT_RPATH string when present.
    #[inline]
    pub fn rpath(&self) -> Option<&str> {
        self.rpath.map(|offset| self.strtab.get_str(offset))
    }

    /// Returns the DT_RUNPATH string when present.
    #[inline]
    pub fn runpath(&self) -> Option<&str> {
        self.runpath.map(|offset| self.strtab.get_str(offset))
    }

    /// Returns the DT_SONAME string when present.
    #[inline]
    pub fn soname(&self) -> Option<&str> {
        self.soname.map(|offset| self.strtab.get_str(offset))
    }

    /// Returns one `DT_NEEDED` entry by index.
    #[inline]
    pub fn needed_lib(&self, index: usize) -> Option<&str> {
        self.needed_libs
            .get(index)
            .map(|offset| self.strtab.get_str(*offset))
    }

    /// Iterates over the `DT_NEEDED` entries.
    #[inline]
    pub fn needed_libs(&self) -> impl ExactSizeIterator<Item = &str> + '_ {
        self.needed_libs
            .iter()
            .map(|offset| self.strtab.get_str(*offset))
    }

    /// Returns the planning capability of this module.
    #[inline]
    pub const fn capability(&self) -> ModuleCapability {
        self.capability
    }

    #[inline]
    fn shstrtab(&self) -> Option<ElfStringTable> {
        self.section_table
            .as_ref()
            .map(|table| ElfStringTable::new(table.shstrtab.as_ptr()))
    }

    /// Returns whether the module exposes a usable section-table view.
    #[inline]
    pub fn has_sections(&self) -> bool {
        self.section_table.is_some()
    }

    /// Returns the raw ELF section headers, when the section table is usable.
    #[inline]
    pub fn section_headers(&self) -> Option<&[ElfShdr<Arch::Layout>]> {
        self.section_table
            .as_ref()
            .map(|table| table.sections.as_ref())
    }

    /// Returns one scanned section by id.
    #[inline]
    pub fn section(
        &self,
        id: impl Into<ScannedSectionId>,
    ) -> Option<ScannedSection<'_, Arch::Layout>> {
        let id = id.into();
        let section_table = self.section_table.as_ref()?;
        let shstrtab = self.shstrtab()?;
        let header = section_table.sections.get(id.index())?;
        Some(ScannedSection::new(
            id,
            shstrtab.get_str(header.sh_name() as usize),
            header,
        ))
    }

    /// Iterates over all scanned sections together with stable ids.
    #[inline]
    pub fn sections(&self) -> ScannedSections<'_, Arch::Layout> {
        ScannedSections::new(
            self.section_table
                .as_ref()
                .map_or(&[], |table| table.sections.as_ref()),
            self.section_table
                .as_ref()
                .map_or(ptr::null(), |table| table.shstrtab.as_ptr()),
        )
    }

    /// Iterates over sections that contribute to the loaded memory image.
    #[inline]
    pub fn alloc_sections(&self) -> impl Iterator<Item = ScannedSection<'_, Arch::Layout>> {
        self.sections().filter(|section| section.is_allocated())
    }

    /// Iterates over retained relocation sections emitted into the section table.
    #[inline]
    pub fn relocation_sections(&self) -> impl Iterator<Item = ScannedSection<'_, Arch::Layout>> {
        self.sections()
            .filter(|section| section.is_relocation_section())
    }

    /// Captures one section's backing bytes.
    pub(crate) fn section_data(
        &mut self,
        id: impl Into<ScannedSectionId>,
    ) -> Result<Option<AlignedBytes>> {
        let Some(section) = self.section(id) else {
            return Ok(None);
        };

        if section.is_nobits() {
            return Ok(Some(
                AlignedBytes::with_len(section.size()).expect("failed to allocate section bytes"),
            ));
        }

        Ok(Some(
            self.read_bytes(section.file_offset(), section.size())?,
        ))
    }

    #[inline]
    fn read_bytes(&mut self, offset: usize, len: usize) -> Result<AlignedBytes> {
        let mut bytes = AlignedBytes::with_len(len).ok_or(ParseDynamicError::AddressOverflow)?;
        self.reader.read_slice(bytes.as_mut(), offset)?;
        Ok(bytes)
    }

    /// Returns the dynamic binding and TLS policy flags discovered during scan.
    #[inline]
    pub fn dynamic(&self) -> &ScannedDynamicInfo {
        &self.dynamic
    }

    pub(crate) fn into_load_parts(self) -> ScannedDynamicLoadParts<Arch> {
        let Self {
            ehdr,
            phdrs,
            reader,
            ..
        } = self;

        ScannedDynamicLoadParts {
            ehdr,
            phdrs,
            reader,
        }
    }
}

impl<Arch: RelocationArch> ScannedExec<Arch> {
    pub(crate) fn from_builder(builder: ScanBuilder<Arch::Layout>) -> Result<Self> {
        let ScanBuilder {
            path,
            ehdr,
            phdrs,
            mut reader,
        } = builder;
        let interp = read_interp(reader.as_mut(), &phdrs)?;
        let section_table = SectionTable::new(reader.as_mut(), &ehdr)?;

        Ok(Self {
            path,
            ehdr,
            phdrs,
            interp,
            section_table,
            reader,
        })
    }

    /// Returns the loader source path or caller-provided source identifier.
    #[inline]
    pub fn path(&self) -> &Path {
        self.path.as_path()
    }

    /// Returns the executable identity used for diagnostics.
    #[inline]
    pub fn name(&self) -> &str {
        self.path().file_name()
    }

    /// Returns the parsed ELF header.
    #[inline]
    pub fn ehdr(&self) -> &ElfHeader<Arch::Layout> {
        &self.ehdr
    }

    /// Returns the parsed program headers.
    #[inline]
    pub fn phdrs(&self) -> &[ElfPhdr<Arch::Layout>] {
        &self.phdrs
    }

    /// Returns the PT_INTERP string when present.
    #[inline]
    pub fn interp(&self) -> Option<&str> {
        self.interp.as_deref().and_then(|bytes| {
            let end = bytes
                .iter()
                .position(|byte| *byte == 0)
                .unwrap_or(bytes.len());
            core::str::from_utf8(&bytes[..end]).ok()
        })
    }

    #[inline]
    fn shstrtab(&self) -> Option<ElfStringTable> {
        self.section_table
            .as_ref()
            .map(|table| ElfStringTable::new(table.shstrtab.as_ptr()))
    }

    /// Returns whether the executable exposes a usable section-table view.
    #[inline]
    pub fn has_sections(&self) -> bool {
        self.section_table.is_some()
    }

    /// Returns the raw ELF section headers, when the section table is usable.
    #[inline]
    pub fn section_headers(&self) -> Option<&[ElfShdr<Arch::Layout>]> {
        self.section_table
            .as_ref()
            .map(|table| table.sections.as_ref())
    }

    /// Returns one scanned section by id.
    #[inline]
    pub fn section(
        &self,
        id: impl Into<ScannedSectionId>,
    ) -> Option<ScannedSection<'_, Arch::Layout>> {
        let id = id.into();
        let section_table = self.section_table.as_ref()?;
        let shstrtab = self.shstrtab()?;
        let header = section_table.sections.get(id.index())?;
        Some(ScannedSection::new(
            id,
            shstrtab.get_str(header.sh_name() as usize),
            header,
        ))
    }

    /// Iterates over all scanned sections together with stable ids.
    #[inline]
    pub fn sections(&self) -> ScannedSections<'_, Arch::Layout> {
        ScannedSections::new(
            self.section_table
                .as_ref()
                .map_or(&[], |table| table.sections.as_ref()),
            self.section_table
                .as_ref()
                .map_or(ptr::null(), |table| table.shstrtab.as_ptr()),
        )
    }

    /// Iterates over sections that contribute to the loaded memory image.
    #[inline]
    pub fn alloc_sections(&self) -> impl Iterator<Item = ScannedSection<'_, Arch::Layout>> {
        self.sections().filter(|section| section.is_allocated())
    }

    /// Captures one section's backing bytes.
    #[allow(dead_code)]
    pub(crate) fn section_data(
        &mut self,
        id: impl Into<ScannedSectionId>,
    ) -> Result<Option<AlignedBytes>> {
        let Some(section) = self.section(id) else {
            return Ok(None);
        };

        if section.is_nobits() {
            return Ok(Some(
                AlignedBytes::with_len(section.size()).expect("failed to allocate section bytes"),
            ));
        }

        Ok(Some(
            self.read_bytes(section.file_offset(), section.size())?,
        ))
    }

    #[inline]
    #[allow(dead_code)]
    fn read_bytes(&mut self, offset: usize, len: usize) -> Result<AlignedBytes> {
        let mut bytes = AlignedBytes::with_len(len).ok_or(ParseDynamicError::AddressOverflow)?;
        self.reader.read_slice(bytes.as_mut(), offset)?;
        Ok(bytes)
    }
}

fn classify_module_capability<L: ElfLayout>(sections: &[ElfShdr<L>]) -> ModuleCapability {
    for section in sections {
        if !matches!(
            section.section_type(),
            ElfSectionType::REL | ElfSectionType::RELA
        ) {
            continue;
        }

        if !section.flags().contains(ElfSectionFlags::ALLOC)
            && section.sh_info() != 0
            && section.sh_link() != 0
        {
            return ModuleCapability::SectionReorderable;
        }
    }

    ModuleCapability::SectionData
}

fn read_interp<L: ElfLayout>(
    object: &mut dyn ElfReader,
    phdrs: &[ElfPhdr<L>],
) -> Result<Option<Box<[u8]>>> {
    let Some(interp) = phdrs
        .iter()
        .find(|phdr| phdr.program_type() == ElfProgramType::INTERP)
    else {
        return Ok(None);
    };

    let bytes = object.read_to_vec(interp.p_offset(), interp.p_filesz())?;
    Ok(Some(bytes.into_boxed_slice()))
}

fn vaddr_to_file_offset<L: ElfLayout>(vaddr: usize, phdrs: &[ElfPhdr<L>]) -> Result<usize> {
    for phdr in phdrs
        .iter()
        .filter(|phdr| phdr.program_type() == ElfProgramType::LOAD)
    {
        let seg_start = phdr.p_vaddr();
        let seg_end = seg_start
            .checked_add(phdr.p_filesz())
            .ok_or(ParseDynamicError::AddressOverflow)?;
        if seg_start <= vaddr && vaddr < seg_end {
            return phdr
                .p_offset()
                .checked_add(vaddr - seg_start)
                .ok_or(ParseDynamicError::AddressOverflow.into());
        }
    }

    Err(ParsePhdrError::malformed("virtual address is not covered by a PT_LOAD segment").into())
}