elf_loader 0.16.0

A no_std-friendly ELF loader and runtime linker for Rust.
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
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
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
//! Error types returned by Relink APIs.

use crate::{
    elf::{ElfClass, ElfDataEncoding, ElfDynamicTag, ElfFileType, ElfMachine},
    linker::{ContextId, KeyId, ModuleId},
};
use alloc::{borrow::Cow, boxed::Box};
use core::fmt::{self, Display};

/// Structured I/O error details.
pub enum IoError {
    /// The provided path contains an interior NUL byte.
    NullByteInPath,
    /// `open failed for {path} with error: {code}`
    OpenFailed {
        /// Path that failed to open.
        path: Box<str>,
        /// Platform error code returned by the open operation.
        code: u32,
    },
    /// `seek failed with error: {code}`
    SeekFailed {
        /// Platform error code returned by the seek operation.
        code: u32,
    },
    /// `read failed with error: {code}`
    ReadFailed {
        /// Platform error code returned by the read operation.
        code: u32,
    },
    /// `failed to fill buffer`
    FailedToFillBuffer,
    /// `read buffer is too large`
    ReadBufferTooLarge,
    /// `out of memory while allocating read buffer`
    OutOfMemory,
    /// `read offset out of bounds: offset {offset}, len {len}, available {available}`
    ReadOutOfBounds(Box<ReadBoundsError>),
    /// The temporary read buffer is not aligned for the requested view.
    ReadBufferNotAligned {
        /// Required byte alignment.
        align: usize,
    },
    /// `close failed`
    CloseFailed,
}

/// Structured details for an out-of-bounds read.
#[derive(Debug)]
pub struct ReadBoundsError {
    offset: usize,
    len: usize,
    available: usize,
}

impl ReadBoundsError {
    #[inline]
    pub(crate) fn new(offset: usize, len: usize, available: usize) -> Self {
        Self {
            offset,
            len,
            available,
        }
    }
}

impl Display for IoError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::NullByteInPath => f.write_str("path contains an interior NUL byte"),
            Self::OpenFailed { path, code } => {
                write!(f, "open failed for {path} with error: {code}")
            }
            Self::SeekFailed { code } => write!(f, "seek failed with error: {code}"),
            Self::ReadFailed { code } => write!(f, "read failed with error: {code}"),
            Self::FailedToFillBuffer => f.write_str("failed to fill buffer"),
            Self::ReadBufferTooLarge => f.write_str("read buffer is too large"),
            Self::OutOfMemory => f.write_str("out of memory while allocating read buffer"),
            Self::ReadOutOfBounds(err) => write!(
                f,
                "read offset out of bounds: offset {}, len {}, available {}",
                err.offset, err.len, err.available
            ),
            Self::ReadBufferNotAligned { align } => {
                write!(f, "read buffer is not aligned to {align} bytes")
            }
            Self::CloseFailed => f.write_str("close failed"),
        }
    }
}

/// Structured memory-mapping error details.
pub enum MmapError {
    /// The configured loader page size is incompatible with the mapping backend.
    InvalidPageSize {
        /// Page size requested by the loader.
        configured: usize,
        /// Minimum page size required by the mapping backend.
        required: usize,
    },
    #[cfg(not(windows))]
    /// `mmap failed with error: {code}`
    MmapFailed {
        /// Platform error code returned by `mmap`.
        code: u32,
    },
    #[cfg(not(windows))]
    /// `mmap anonymous failed with error: {code}`
    MmapAnonymousFailed {
        /// Platform error code returned by anonymous `mmap`.
        code: u32,
    },
    #[cfg(not(windows))]
    /// `munmap failed with error: {code}`
    MunmapFailed {
        /// Platform error code returned by `munmap`.
        code: u32,
    },
    #[cfg(windows)]
    /// `MapViewOfFile3 failed with error: {code}`
    MapViewOfFile3 {
        /// Windows error code returned by `MapViewOfFile3`.
        code: u32,
    },
    #[cfg(windows)]
    /// `VirtualAlloc failed with error: {code}`
    VirtualAlloc {
        /// Windows error code returned by `VirtualAlloc`.
        code: u32,
    },
    /// `mprotect failed with error: {code}`
    Mprotect {
        /// Platform error code returned by memory protection changes.
        code: u32,
    },
    /// `madvise failed with error: {code}`
    Madvise {
        /// Platform error code returned by `madvise`.
        code: u32,
    },
    /// A mapped-region byte range is outside the region bounds.
    InvalidMappedRegionRange,
    /// The mapped region cannot expose a host-accessible pointer.
    HostPointerUnavailable,
    #[cfg(windows)]
    /// `CreateFileMappingW failed with error: {code}`
    CreateFileMappingW {
        /// Windows error code returned by `CreateFileMappingW`.
        code: u32,
    },
    #[cfg(windows)]
    /// `VirtualFree failed with error: {code}`
    VirtualFree {
        /// Windows error code returned by `VirtualFree`.
        code: u32,
    },
}

impl Display for MmapError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidPageSize {
                configured,
                required,
            } => write!(
                f,
                "invalid loader page size: configured {configured}, required a multiple of {required}"
            ),
            #[cfg(not(windows))]
            Self::MmapFailed { code } => write!(f, "mmap failed with error: {code}"),
            #[cfg(not(windows))]
            Self::MmapAnonymousFailed { code } => {
                write!(f, "mmap anonymous failed with error: {code}")
            }
            #[cfg(not(windows))]
            Self::MunmapFailed { code } => write!(f, "munmap failed with error: {code}"),
            #[cfg(windows)]
            Self::MapViewOfFile3 { code } => {
                write!(f, "MapViewOfFile3 failed with error: {code}")
            }
            #[cfg(windows)]
            Self::VirtualAlloc { code } => {
                write!(f, "VirtualAlloc failed with error: {code}")
            }
            Self::Mprotect { code } => write!(f, "mprotect failed with error: {code}"),
            Self::Madvise { code } => write!(f, "madvise failed with error: {code}"),
            Self::InvalidMappedRegionRange => f.write_str("mapped region range is out of bounds"),
            Self::HostPointerUnavailable => f.write_str("mapped region is not host-accessible"),
            #[cfg(windows)]
            Self::CreateFileMappingW { code } => {
                write!(f, "CreateFileMappingW failed with error: {code}")
            }
            #[cfg(windows)]
            Self::VirtualFree { code } => {
                write!(f, "VirtualFree failed with error: {code}")
            }
        }
    }
}

/// Structured relocation-table parsing error details.
pub enum RelocTableError {
    /// `DT_JMPREL` table size is malformed.
    JmpRelSize,
    /// `DT_REL`/`DT_RELA` table size is malformed.
    DynRelSize,
    /// `DT_RELR` table size is malformed.
    RelrSize,
    /// `DT_RELAENT` does not match the selected `ElfRela` layout.
    RelaEntrySize {
        /// Expected `ElfRela` entry size.
        expected: usize,
        /// Actual `DT_RELAENT` value.
        actual: usize,
    },
    /// `DT_RELENT` does not match the selected `ElfRel` layout.
    RelEntrySize {
        /// Expected `ElfRel` entry size.
        expected: usize,
        /// Actual `DT_RELENT` value.
        actual: usize,
    },
    /// `DT_RELRENT` does not match the selected `ElfRelr` layout.
    RelrEntrySize {
        /// Expected `ElfRelr` entry size.
        expected: usize,
        /// Actual `DT_RELRENT` value.
        actual: usize,
    },
}

impl Display for RelocTableError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::JmpRelSize => f.write_str("DT_JMPREL relocation table size is malformed"),
            Self::DynRelSize => f.write_str("DT_REL/DT_RELA relocation table size is malformed"),
            Self::RelrSize => f.write_str("DT_RELR relocation table size is malformed"),
            Self::RelaEntrySize { expected, actual } => write!(
                f,
                "DT_RELAENT relocation entry size {actual} does not match ElfRela size {expected}"
            ),
            Self::RelEntrySize { expected, actual } => write!(
                f,
                "DT_RELENT relocation entry size {actual} does not match ElfRel size {expected}"
            ),
            Self::RelrEntrySize { expected, actual } => write!(
                f,
                "DT_RELRENT relocation entry size {actual} does not match ElfRelr size {expected}"
            ),
        }
    }
}

/// Structured dynamic-section parsing error details.
pub enum ParseDynamicError {
    /// `{tag}` is required by the ABI but missing from the dynamic section.
    MissingRequiredTag {
        /// Required dynamic tag.
        tag: ElfDynamicTag,
    },
    /// A dynamic-section address calculation overflowed.
    AddressOverflow,
    /// The dynamic table byte size is not a multiple of an `ElfDyn` entry.
    InvalidDynamicTableSize {
        /// Byte size declared by `PT_DYNAMIC.p_filesz`.
        size: usize,
        /// Size of one dynamic-table entry for the selected ELF layout.
        entry_size: usize,
    },
    /// `DT_RELCOUNT`/`DT_RELACOUNT` exceeds the dynamic relocation table length.
    RelativeRelocationCountOutOfRange {
        /// Relative relocation count declared by the dynamic section.
        count: usize,
        /// Number of entries in the dynamic relocation table.
        table_len: usize,
    },
    /// `DT_JMPREL` cannot fit as the tail of `DT_REL`/`DT_RELA`.
    PltRelocationTailOutOfRange {
        /// Number of PLT relocation entries.
        plt_len: usize,
        /// Number of dynamic relocation entries available after relative relocations.
        dynrel_tail_len: usize,
    },
    /// A relocation table described by the dynamic section is invalid.
    InvalidRelocTable {
        /// Structured reason why the relocation table is malformed.
        reason: RelocTableError,
    },
    /// A required dynamic hash subtable is empty.
    EmptyHashTable {
        /// Name of the empty hash subtable.
        table: &'static str,
    },
    /// A GNU hash bucket names a symbol index before the GNU hash symbol bias.
    GnuHashBucketBeforeSymbolBias {
        /// Symbol index read from the GNU hash bucket table.
        bucket_symbol: usize,
        /// GNU hash symbol bias declared by the hash header.
        symbol_bias: usize,
    },
    /// A symbol hash table described by the dynamic section is malformed.
    MalformedHashTable {
        /// Static detail describing why the table is malformed.
        detail: &'static str,
    },
    /// A symbol table described by the dynamic section is malformed.
    MalformedSymbolTable {
        /// Static detail describing why the table is malformed.
        detail: &'static str,
    },
    /// A string table described by the dynamic section is malformed.
    MalformedStringTable {
        /// Static detail describing why the table is malformed.
        detail: &'static str,
    },
    /// A lifecycle function table described by the dynamic section is malformed.
    MalformedLifecycleTable {
        /// Static detail describing why the table is malformed.
        detail: &'static str,
    },
}

impl Display for ParseDynamicError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::MissingRequiredTag { tag } => {
                write!(f, "dynamic section is missing required tag {tag}")
            }
            Self::AddressOverflow => f.write_str("dynamic section address calculation overflowed"),
            Self::InvalidDynamicTableSize { size, entry_size } => write!(
                f,
                "dynamic table size {size} is not a multiple of entry size {entry_size}"
            ),
            Self::RelativeRelocationCountOutOfRange { count, table_len } => write!(
                f,
                "relative relocation count {count} exceeds dynamic relocation table length {table_len}"
            ),
            Self::PltRelocationTailOutOfRange {
                plt_len,
                dynrel_tail_len,
            } => write!(
                f,
                "PLT relocation tail length {plt_len} exceeds remaining dynamic relocation length {dynrel_tail_len}"
            ),
            Self::InvalidRelocTable { reason } => Display::fmt(reason, f),
            Self::EmptyHashTable { table } => write!(f, "{table} is empty"),
            Self::GnuHashBucketBeforeSymbolBias {
                bucket_symbol,
                symbol_bias,
            } => write!(
                f,
                "DT_GNU_HASH bucket symbol index {bucket_symbol} precedes symbol bias {symbol_bias}"
            ),
            Self::MalformedHashTable { detail } => f.write_str(detail),
            Self::MalformedSymbolTable { detail } => f.write_str(detail),
            Self::MalformedStringTable { detail } => f.write_str(detail),
            Self::MalformedLifecycleTable { detail } => f.write_str(detail),
        }
    }
}

/// Structured ELF note parsing error details.
pub enum ParseNoteError {
    /// The note alignment is not supported.
    InvalidAlign {
        /// Alignment value supplied by the note section or segment.
        align: usize,
    },
    /// The note header is truncated.
    Header {
        /// Byte offset of the note header.
        offset: usize,
        /// Remaining bytes from `offset`.
        remaining: usize,
    },
    /// The note name field is truncated.
    Name {
        /// Byte offset of the note header.
        offset: usize,
        /// Size declared by `n_namesz`.
        size: usize,
        /// Bytes remaining at the name field.
        remaining: usize,
    },
    /// The note descriptor field is truncated.
    Desc {
        /// Byte offset of the note header.
        offset: usize,
        /// Size declared by `n_descsz`.
        size: usize,
        /// Bytes remaining at the descriptor field.
        remaining: usize,
    },
    /// A note field offset calculation overflowed.
    Overflow {
        /// Byte offset of the note header.
        offset: usize,
    },
}

impl Display for ParseNoteError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidAlign { align } => write!(f, "invalid ELF note alignment {align}"),
            Self::Header { offset, remaining } => write!(
                f,
                "ELF note header at offset {offset} is truncated: {remaining} bytes remaining"
            ),
            Self::Name {
                offset,
                size,
                remaining,
            } => write!(
                f,
                "ELF note at offset {offset} has invalid name size {size}: {remaining} bytes remaining"
            ),
            Self::Desc {
                offset,
                size,
                remaining,
            } => write!(
                f,
                "ELF note at offset {offset} has invalid descriptor size {size}: {remaining} bytes remaining"
            ),
            Self::Overflow { offset } => {
                write!(
                    f,
                    "ELF note at offset {offset} overflows address calculation"
                )
            }
        }
    }
}

/// Structured ELF header parsing error details.
pub enum ParseEhdrError {
    /// The ELF magic bytes do not match `0x7fELF`.
    InvalidMagic,
    /// `file class mismatch: expected {expected}, found {found}`
    FileClassMismatch {
        /// ELF class expected by the selected loader configuration.
        expected: ElfClass,
        /// ELF class found in the file header.
        found: ElfClass,
    },
    /// `file endian mismatch: expected {expected}, found {found}`
    FileEndianMismatch {
        /// ELF data encoding expected by this build.
        expected: ElfDataEncoding,
        /// ELF data encoding found in the file header.
        found: ElfDataEncoding,
    },
    /// The ELF version is not `EV_CURRENT`.
    InvalidVersion,
    /// `file arch mismatch: expected {expected}, found {found}`
    FileArchMismatch {
        /// Machine type expected by the selected target architecture.
        expected: ElfMachine,
        /// Machine type found in the file header.
        found: ElfMachine,
    },
    /// The target-specific ELF header flags are unsupported.
    InvalidFlags {
        /// Machine type whose `e_flags` were rejected.
        machine: ElfMachine,
        /// Raw `e_flags` value from the ELF header.
        flags: u32,
        /// Static detail describing why the flags are unsupported.
        detail: &'static str,
    },
    /// A shared object was required but the file type was different.
    ExpectedDylib {
        /// File type found in the ELF header.
        found: ElfFileType,
    },
    /// An executable or PIE-compatible file was required but the file type was different.
    ExpectedExecutable {
        /// File type found in the ELF header.
        found: ElfFileType,
    },
    /// A relocatable object was required but the file type was different.
    ExpectedRelocatable {
        /// File type found in the ELF header.
        found: ElfFileType,
    },
    /// Relocatable object support is disabled for this build.
    RelocatableObjectsDisabled,
}

impl Display for ParseEhdrError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidMagic => f.write_str("invalid ELF magic"),
            Self::FileClassMismatch { expected, found } => {
                write!(f, "file class mismatch: expected {expected}, found {found}")
            }
            Self::FileEndianMismatch { expected, found } => write!(
                f,
                "file endian mismatch: expected {expected}, found {found}"
            ),
            Self::InvalidVersion => f.write_str("invalid ELF version"),
            Self::FileArchMismatch { expected, found } => write!(
                f,
                "file arch mismatch: expected {}, found {}",
                expected, found,
            ),
            Self::InvalidFlags {
                machine,
                flags,
                detail,
            } => write!(
                f,
                "invalid ELF header flags for {machine}: 0x{flags:x} ({detail})"
            ),
            Self::ExpectedDylib { found } => {
                write!(f, "file type mismatch: expected ET_DYN, found {found}")
            }
            Self::ExpectedExecutable { found } => write!(
                f,
                "file type mismatch: expected ET_EXEC or ET_DYN, found {}",
                found,
            ),
            Self::ExpectedRelocatable { found } => {
                write!(f, "file type mismatch: expected ET_REL, found {found}")
            }
            Self::RelocatableObjectsDisabled => {
                f.write_str("file type ET_REL requires enabling the `object` feature")
            }
        }
    }
}

/// Structured section-header parsing error details.
pub enum ParseShdrError {
    /// A section-header table was required but not present.
    MissingSectionHeaders,
    /// The section header entry size does not match the selected ELF layout.
    InvalidEntrySize {
        /// Entry size required by the selected ELF layout.
        expected: usize,
        /// Entry size found in the ELF header.
        found: usize,
    },
    /// The section header table is malformed.
    Malformed {
        /// Static detail describing why the section headers are malformed.
        detail: &'static str,
    },
}

impl ParseShdrError {
    #[inline]
    #[cfg_attr(not(feature = "object"), allow(dead_code))]
    pub(crate) const fn malformed(detail: &'static str) -> Self {
        Self::Malformed { detail }
    }
}

impl Display for ParseShdrError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::MissingSectionHeaders => f.write_str("section header table is missing"),
            Self::InvalidEntrySize { expected, found } => write!(
                f,
                "section header entry size mismatch: expected {expected}, found {found}"
            ),
            Self::Malformed { detail } => f.write_str(detail),
        }
    }
}

/// Structured program-header parsing error details.
pub enum ParsePhdrError {
    /// The program header entry size does not match the selected ELF layout.
    InvalidEntrySize {
        /// Entry size required by the selected ELF layout.
        expected: usize,
        /// Entry size found in the ELF header.
        found: usize,
    },
    /// The program header table is malformed.
    Malformed {
        /// Static detail describing why the program headers are malformed.
        detail: &'static str,
    },
    /// A `PT_LOAD` segment cannot be mapped with the selected page size.
    PageAlignmentMismatch {
        /// Loader page size used for validation.
        page_size: usize,
    },
    /// A dynamic image was expected to carry `PT_DYNAMIC`.
    MissingDynamicSection,
    /// `{field} contains invalid UTF-8`
    InvalidUtf8 {
        /// Program-header field or payload that failed UTF-8 validation.
        field: &'static str,
    },
}

impl ParsePhdrError {
    #[inline]
    pub(crate) const fn malformed(detail: &'static str) -> Self {
        Self::Malformed { detail }
    }
}

impl Display for ParsePhdrError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidEntrySize { expected, found } => write!(
                f,
                "program header entry size mismatch: expected {expected}, found {found}"
            ),
            Self::Malformed { detail } => f.write_str(detail),
            Self::PageAlignmentMismatch { page_size } => write!(
                f,
                "program headers are not compatible with page size {page_size}"
            ),
            Self::MissingDynamicSection => f.write_str("program headers do not contain PT_DYNAMIC"),
            Self::InvalidUtf8 { field } => write!(f, "{field} contains invalid UTF-8"),
        }
    }
}

#[derive(Clone, Copy)]
pub(crate) enum RelocReason {
    UnknownSymbol,
    Unsupported,
    MissingTlsModuleId,
    MissingTlsTpOffset,
    IntConversionOutOfRange,
}

impl Display for RelocReason {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::UnknownSymbol => f.write_str("unknown symbol"),
            Self::Unsupported => f.write_str("unsupported relocation"),
            Self::MissingTlsModuleId => f.write_str("TLS module id is unavailable"),
            Self::MissingTlsTpOffset => f.write_str("TLS thread-pointer offset is unavailable"),
            Self::IntConversionOutOfRange => {
                f.write_str("out of range integral type conversion attempted")
            }
        }
    }
}

/// Detailed relocation failure carried separately so the top-level [`Error`] stays compact.
pub struct RelocationFailure {
    file: Box<str>,
    r_type: &'static str,
    symbol: Option<Box<str>>,
    reason: RelocReason,
}

impl RelocationFailure {
    #[inline]
    pub(crate) fn new(
        file: &str,
        r_type: &'static str,
        symbol: Option<&str>,
        reason: RelocReason,
    ) -> Self {
        Self {
            file: file.into(),
            r_type,
            symbol: symbol.map(Into::into),
            reason,
        }
    }
}

impl Display for RelocationFailure {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "file: {}, relocation type: {}, ", self.file, self.r_type)?;
        if let Some(symbol) = &self.symbol {
            write!(f, "symbol name: {symbol}, ")?;
        } else {
            f.write_str("no symbol, ")?;
        }
        write!(f, "error: {}", self.reason)
    }
}

/// Structured relocation error details.
pub enum RelocationError {
    /// Detailed relocation context, formatted lazily in `Display`.
    Context(Box<RelocationFailure>),
    /// Lazy binding setup or runtime binding failed.
    LazyBinding(LazyBindingError),
    /// `object file missing symbol table`
    MissingSymbolTable,
}

impl Display for RelocationError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Context(ctx) => Display::fmt(ctx, f),
            Self::LazyBinding(err) => {
                write!(f, "lazy binding failed: {err}")
            }
            Self::MissingSymbolTable => f.write_str("object file missing symbol table"),
        }
    }
}

/// Structured lazy binding failure details.
pub enum LazyBindingError {
    /// Lazy binding was requested without installing a binder.
    MissingBinder,
    /// Native same-process lazy binding is unavailable for the target architecture.
    NativeUnsupported,
    /// The image has no GOT/PLTGOT entry to install lazy binding state.
    MissingGotPlt,
    /// The lazy relocation index does not exist.
    RelocIndexOutOfRange,
    /// The relocation is not a valid lazy PLT relocation.
    InvalidPltReloc,
    /// The relocation references a symbol table entry that does not exist.
    SymbolIndexOutOfRange,
}

impl Display for LazyBindingError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::MissingBinder => f.write_str("missing lazy binder"),
            Self::NativeUnsupported => {
                f.write_str("native binding is not supported for this target architecture")
            }
            Self::MissingGotPlt => f.write_str("missing GOT/PLTGOT entry"),
            Self::RelocIndexOutOfRange => f.write_str("relocation index is out of range"),
            Self::InvalidPltReloc => f.write_str("invalid PLT relocation"),
            Self::SymbolIndexOutOfRange => f.write_str("symbol index is out of range"),
        }
    }
}

/// Structured runtime code execution error details.
pub enum CodeError {
    /// Native code execution is not supported for this target architecture.
    NativeUnsupported,
}

impl Display for CodeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::NativeUnsupported => {
                f.write_str("native code execution is not supported for this target architecture")
            }
        }
    }
}

/// Structured user-defined error details.
pub enum CustomError {
    /// A plain message supplied by the caller.
    Message(Cow<'static, str>),
    /// A user error object preserved for display, source chaining, and downcasting.
    Boxed(Box<dyn core::error::Error + Send + Sync + 'static>),
}

impl CustomError {
    /// Creates a custom error from a user-facing message.
    #[inline]
    pub fn message(msg: impl Into<Cow<'static, str>>) -> Self {
        Self::Message(msg.into())
    }

    /// Wraps a user error object without losing its concrete type.
    #[inline]
    pub fn boxed(error: impl core::error::Error + Send + Sync + 'static) -> Self {
        Self::Boxed(Box::new(error))
    }

    /// Attempts to borrow the boxed user error as a concrete type.
    #[inline]
    pub fn downcast_ref<T: core::error::Error + 'static>(&self) -> Option<&T> {
        match self {
            Self::Message(_) => None,
            Self::Boxed(error) => error.downcast_ref::<T>(),
        }
    }
}

impl Display for CustomError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Message(msg) => f.write_str(msg),
            Self::Boxed(error) => Display::fmt(error, f),
        }
    }
}

impl core::error::Error for CustomError {
    #[inline]
    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
        match self {
            Self::Message(_) => None,
            Self::Boxed(error) => Some(&**error),
        }
    }
}

/// Unresolved dependency details carried separately so the top-level [`Error`] stays compact.
pub struct UnresolvedDependency {
    owner: Box<str>,
    dependency: Box<str>,
}

impl UnresolvedDependency {
    #[inline]
    pub(crate) fn new(owner: &str, dependency: &str) -> Self {
        Self {
            owner: owner.into(),
            dependency: dependency.into(),
        }
    }
}

impl Display for UnresolvedDependency {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "unresolved dependency [{}] needed by [{}]",
            self.dependency, self.owner
        )
    }
}

/// Structured committed linker-context failure details.
pub enum LinkContextError {
    /// A key id from one [`crate::LinkContext`] was used with another context.
    KeyContextMismatch {
        /// The key id that failed the context check.
        id: KeyId,
        /// The context that received the key id.
        expected: ContextId,
    },
    /// A module id from one [`crate::LinkContext`] was used with another context.
    ModuleContextMismatch {
        /// The module id that failed the context check.
        id: ModuleId,
        /// The context that received the module id.
        expected: ContextId,
    },
    /// A module id no longer resolves to committed state.
    ModuleNotCommitted {
        /// The module id that could not be resolved.
        id: ModuleId,
    },
    /// A key id does not resolve to a committed module.
    KeyNotCommitted {
        /// The key id that did not resolve to a committed module.
        id: KeyId,
    },
}

impl Display for LinkContextError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::KeyContextMismatch { id, expected } => {
                write!(f, "key id {} was used with link context {}", id, expected)
            }
            Self::ModuleContextMismatch { id, expected } => write!(
                f,
                "module id {} was used with link context {}",
                id, expected
            ),
            Self::ModuleNotCommitted { id } => write!(f, "module id {} is not committed", id),
            Self::KeyNotCommitted { id } => write!(f, "key id {} is not committed", id),
        }
    }
}

/// Structured resolver failure details.
pub enum LinkResolverError {
    /// The resolver returned `Existing`, but the key is not visible.
    ExistingKeyNotVisible,
    /// The resolver returned a new module source, but the key is already known.
    NewKeyAlreadyKnown,
    /// The root module could not be found by a resolver.
    RootNotFound,
}

impl Display for LinkResolverError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::ExistingKeyNotVisible => {
                f.write_str("resolver referenced an unknown visible key")
            }
            Self::NewKeyAlreadyKnown => {
                f.write_str("resolver produced an already-known key; use Existing to reuse it")
            }
            Self::RootNotFound => f.write_str("root module was not found by resolver"),
        }
    }
}

/// Structured scan/planned-load failure details.
pub enum LinkScanError {
    /// A requested materialization mode is invalid for the module/layout.
    Materialization {
        /// Static detail describing the materialization failure.
        detail: &'static str,
    },
    /// Section data could not be materialized or borrowed as requested.
    SectionData {
        /// Static detail describing the section-data failure.
        detail: &'static str,
    },
    /// Mapped section-arena memory is inconsistent with the layout plan.
    MappedArena {
        /// Static detail describing the mapped-arena failure.
        detail: &'static str,
    },
    /// Runtime memory built for section-region materialization is invalid.
    RuntimeMemory {
        /// Static detail describing the runtime-memory failure.
        detail: &'static str,
    },
    /// Runtime metadata repair failed after section-region mapping.
    MetadataRewrite {
        /// Static detail describing the metadata rewrite failure.
        detail: &'static str,
    },
}

impl Display for LinkScanError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Materialization { detail }
            | Self::SectionData { detail }
            | Self::MappedArena { detail }
            | Self::RuntimeMemory { detail }
            | Self::MetadataRewrite { detail } => f.write_str(detail),
        }
    }
}

/// Structured linker error details.
pub enum LinkerError {
    /// A dependency could not be resolved by the resolver callback.
    UnresolvedDependency(Box<UnresolvedDependency>),
    /// Committed linker context state rejected an operation.
    Context {
        /// Structured context failure reason.
        reason: Box<LinkContextError>,
    },
    /// Resolver state was inconsistent with the current link context.
    Resolver {
        /// Structured resolver failure reason.
        reason: LinkResolverError,
    },
    /// Object exports were installed after the core had already been retained.
    ObjectCoreRetainedBeforeExports,
    /// Scan-first/planned-load state was inconsistent.
    Scan {
        /// Structured scan failure reason.
        reason: Box<LinkScanError>,
    },
}

impl LinkerError {
    #[inline]
    pub(crate) fn context(reason: LinkContextError) -> Self {
        Self::Context {
            reason: Box::new(reason),
        }
    }

    #[inline]
    pub(crate) fn resolver(reason: LinkResolverError) -> Self {
        Self::Resolver { reason }
    }

    #[inline]
    pub(crate) fn materialization(detail: &'static str) -> Self {
        Self::Scan {
            reason: Box::new(LinkScanError::Materialization { detail }),
        }
    }

    #[inline]
    pub(crate) fn section_data(detail: &'static str) -> Self {
        Self::Scan {
            reason: Box::new(LinkScanError::SectionData { detail }),
        }
    }

    #[inline]
    pub(crate) fn duplicate_section_data_access() -> Self {
        Self::section_data(
            "disjoint section data access referenced the same section more than once",
        )
    }

    #[inline]
    pub(crate) fn missing_section_data_access() -> Self {
        Self::section_data("disjoint section data access was not materialized")
    }

    #[inline]
    pub(crate) fn mapped_arena(detail: &'static str) -> Self {
        Self::Scan {
            reason: Box::new(LinkScanError::MappedArena { detail }),
        }
    }

    #[inline]
    pub(crate) fn runtime_memory(detail: &'static str) -> Self {
        Self::Scan {
            reason: Box::new(LinkScanError::RuntimeMemory { detail }),
        }
    }

    #[inline]
    pub(crate) fn metadata_rewrite(detail: &'static str) -> Self {
        Self::Scan {
            reason: Box::new(LinkScanError::MetadataRewrite { detail }),
        }
    }
}

impl Display for LinkerError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::UnresolvedDependency(err) => Display::fmt(err, f),
            Self::Context { reason } => Display::fmt(reason, f),
            Self::Resolver { reason } => Display::fmt(reason, f),
            Self::ObjectCoreRetainedBeforeExports => {
                f.write_str("raw object core was retained before runtime exports were installed")
            }
            Self::Scan { reason } => Display::fmt(reason, f),
        }
    }
}

/// Structured TLS error details.
pub enum TlsError {
    /// The current resolver does not support dynamic TLS.
    ResolverUnsupported,
    /// The current resolver does not support static TLS registration.
    StaticResolverUnsupported,
    /// The TLS image source can no longer provide template bytes.
    TemplateUnavailable,
    /// The TLS module ID is not registered.
    InvalidModuleId,
}

impl Display for TlsError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::ResolverUnsupported => {
                f.write_str("TLS operation is not supported by the configured resolver")
            }
            Self::StaticResolverUnsupported => {
                f.write_str("static TLS is not supported by the configured resolver")
            }
            Self::TemplateUnavailable => f.write_str("TLS template image is no longer available"),
            Self::InvalidModuleId => f.write_str("TLS module ID is not registered"),
        }
    }
}

/// Error types used throughout the `elf_loader` library.
/// These errors represent various failure conditions that can occur during
/// ELF file loading, parsing, and relocation operations.
pub enum Error {
    /// An error occurred while opening, reading, or writing ELF files.
    Io(IoError),

    /// An error occurred during memory mapping operations.
    Mmap(MmapError),

    /// An error occurred during dynamic library relocation.
    Relocation(RelocationError),

    /// An error occurred while parsing the dynamic section.
    ParseDynamic(ParseDynamicError),

    /// An error occurred while parsing the ELF header.
    ParseEhdr(ParseEhdrError),

    /// An error occurred while parsing section headers.
    ParseShdr(ParseShdrError),

    /// An error occurred while parsing program headers.
    ParsePhdr(ParsePhdrError),

    /// An error occurred while parsing ELF notes.
    ParseNote(ParseNoteError),

    /// An error occurred during linker resolution, planning, or materialization.
    Linker(LinkerError),

    /// An error occurred while executing mapped code.
    Code(CodeError),

    /// An error occurred in a user-defined callback or handler.
    Custom(CustomError),

    /// An error occurred during TLS (Thread Local Storage) processing.
    Tls(TlsError),
}

impl From<IoError> for Error {
    fn from(err: IoError) -> Self {
        Self::Io(err)
    }
}

impl From<MmapError> for Error {
    fn from(err: MmapError) -> Self {
        Self::Mmap(err)
    }
}

impl From<RelocationFailure> for RelocationError {
    fn from(err: RelocationFailure) -> Self {
        Self::Context(Box::new(err))
    }
}

impl From<RelocationError> for Error {
    fn from(err: RelocationError) -> Self {
        Self::Relocation(err)
    }
}

impl From<RelocationFailure> for Error {
    fn from(err: RelocationFailure) -> Self {
        RelocationError::from(err).into()
    }
}

impl From<ParseDynamicError> for Error {
    fn from(err: ParseDynamicError) -> Self {
        Self::ParseDynamic(err)
    }
}

impl From<ParseEhdrError> for Error {
    fn from(err: ParseEhdrError) -> Self {
        Self::ParseEhdr(err)
    }
}

impl From<ParseShdrError> for Error {
    fn from(err: ParseShdrError) -> Self {
        Self::ParseShdr(err)
    }
}

impl From<ParsePhdrError> for Error {
    fn from(err: ParsePhdrError) -> Self {
        Self::ParsePhdr(err)
    }
}

impl From<ParseNoteError> for Error {
    fn from(err: ParseNoteError) -> Self {
        Self::ParseNote(err)
    }
}

impl From<LinkerError> for Error {
    fn from(err: LinkerError) -> Self {
        Self::Linker(err)
    }
}

impl From<CodeError> for Error {
    fn from(err: CodeError) -> Self {
        Self::Code(err)
    }
}

impl From<CustomError> for Error {
    fn from(err: CustomError) -> Self {
        Self::Custom(err)
    }
}

impl From<TlsError> for Error {
    fn from(err: TlsError) -> Self {
        Self::Tls(err)
    }
}

impl Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Io(err) => write!(f, "I/O error: {err}"),
            Self::Mmap(err) => write!(f, "Memory mapping error: {err}"),
            Self::Relocation(err) => write!(f, "Relocation error: {err}"),
            Self::ParseDynamic(err) => write!(f, "Dynamic section parsing error: {err}"),
            Self::ParseEhdr(err) => write!(f, "ELF header parsing error: {err}"),
            Self::ParseShdr(err) => write!(f, "Section header parsing error: {err}"),
            Self::ParsePhdr(err) => write!(f, "Program header parsing error: {err}"),
            Self::ParseNote(err) => write!(f, "ELF note parsing error: {err}"),
            Self::Linker(err) => write!(f, "Linker error: {err}"),
            Self::Code(err) => write!(f, "Code execution error: {err}"),
            Self::Custom(err) => write!(f, "Custom error: {err}"),
            Self::Tls(err) => write!(f, "TLS error: {err}"),
        }
    }
}

impl core::error::Error for Error {
    #[inline]
    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
        match self {
            Self::Custom(error) => core::error::Error::source(error),
            _ => None,
        }
    }
}

macro_rules! debug_as_display {
    ($($ty:ty),* $(,)?) => {
        $(
            impl fmt::Debug for $ty {
                #[inline]
                fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                    Display::fmt(self, f)
                }
            }
        )*
    };
}

debug_as_display!(
    IoError,
    MmapError,
    RelocTableError,
    ParseDynamicError,
    ParseEhdrError,
    ParseShdrError,
    ParsePhdrError,
    ParseNoteError,
    RelocReason,
    RelocationFailure,
    RelocationError,
    LazyBindingError,
    CodeError,
    CustomError,
    UnresolvedDependency,
    LinkerError,
    TlsError,
    Error,
);

#[cold]
#[inline(never)]
pub(crate) fn relocate_context_error(
    file: &str,
    r_type: &'static str,
    symbol: Option<&str>,
    reason: RelocReason,
) -> Error {
    Error::Relocation(RelocationError::Context(Box::new(RelocationFailure::new(
        file, r_type, symbol, reason,
    ))))
}

#[cold]
#[inline(never)]
pub(crate) fn custom_error(msg: impl Into<Cow<'static, str>>) -> Error {
    Error::Custom(CustomError::message(msg))
}

#[cfg(test)]
mod tests {
    use super::*;
    use alloc::{format, string::ToString};
    use core::mem::size_of;

    #[test]
    fn error_stays_compact() {
        assert!(
            size_of::<Error>() <= 32,
            "Error grew to {} bytes",
            size_of::<Error>()
        );
    }

    #[test]
    fn debug_matches_display() {
        let parse_err = ParseEhdrError::InvalidMagic;
        assert_eq!(format!("{parse_err:?}"), parse_err.to_string());

        let err = Error::from(parse_err);
        assert_eq!(format!("{err:?}"), err.to_string());
    }

    #[test]
    fn custom_boxed_error_preserves_source() {
        #[derive(Debug)]
        struct UserError(u32);

        impl Display for UserError {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                write!(f, "user error {}", self.0)
            }
        }

        impl core::error::Error for UserError {}

        let err = Error::Custom(CustomError::boxed(UserError(7)));
        assert_eq!(err.to_string(), "Custom error: user error 7");

        let source = core::error::Error::source(&err).expect("custom source should be preserved");
        assert_eq!(source.to_string(), "user error 7");
        assert_eq!(source.downcast_ref::<UserError>().unwrap().0, 7);

        let Error::Custom(custom) = &err else {
            panic!("expected custom error");
        };
        assert_eq!(custom.downcast_ref::<UserError>().unwrap().0, 7);
    }
}