llvm-native-core 0.1.10

LLVM-native core semantic engine — IR, CodeGen, X86 MC, Clang frontend pipeline
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
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
//! ELF file writer/emitter — produces valid ELF32 and ELF64 object files,
//! executables, and shared libraries.
//!
//! Clean-room reimplementation from the ELF specification
//! (System V gABI, AMD64 supplement, ELF-64 Object File Format).

use crate::elf::elf_symbols::ElfSymbolTable;
use crate::elf::elf_types::{
    elf_r_info, elf_r_info32, ElfClass, ElfEndian, ElfMachine, ElfOsAbi, EI_CLASS, EI_DATA,
    EI_MAG0, EI_MAG1, EI_MAG2, EI_MAG3, EI_NIDENT, EI_OSABI, EI_VERSION, ELF_MAGIC, EM_386,
    EM_AARCH64, EM_ARM, EM_PPC64, EM_RISCV, EM_X86_64, ET_DYN, ET_EXEC, ET_REL, EV_CURRENT, PF_R,
    PF_W, PF_X, PT_LOAD, PT_NOTE, PT_NULL, PT_PHDR, SECTION_NAME_SHSTRTAB, SHF_ALLOC,
    SHF_EXECINSTR, SHF_WRITE, SHT_NOBITS, SHT_NOTE, SHT_NULL, SHT_PROGBITS, SHT_REL, SHT_RELA,
    SHT_STRTAB, SHT_SYMTAB,
};

use std::collections::HashMap;

// ============================================================================
// ElfRelocation
// ============================================================================

/// A relocation entry to be applied to a section.
#[derive(Debug, Clone, PartialEq)]
pub struct ElfRelocation {
    /// Where to apply the relocation (section offset or virtual address).
    pub offset: u64,
    /// Symbol table index.
    pub symbol_index: u32,
    /// Relocation type (e.g., `R_X86_64_*`).
    pub rel_type: u32,
    /// Addend for RELA-type relocations.
    pub addend: i64,
    /// `true` = RELA (with explicit addend), `false` = REL (implicit addend at site).
    pub is_rela: bool,
}

impl ElfRelocation {
    /// Create a RELA relocation entry.
    pub fn rela(offset: u64, symbol_index: u32, rel_type: u32, addend: i64) -> Self {
        ElfRelocation {
            offset,
            symbol_index,
            rel_type,
            addend,
            is_rela: true,
        }
    }

    /// Create a REL relocation entry (no explicit addend).
    pub fn rel(offset: u64, symbol_index: u32, rel_type: u32) -> Self {
        ElfRelocation {
            offset,
            symbol_index,
            rel_type,
            addend: 0,
            is_rela: false,
        }
    }
}

// ============================================================================
// ElfPhdrInfo
// ============================================================================

/// Information for a program header (segment descriptor).
#[derive(Debug, Clone, PartialEq)]
pub struct ElfPhdrInfo {
    /// Segment type (`PT_LOAD`, `PT_DYNAMIC`, `PT_NOTE`, etc.).
    pub segment_type: u32,
    /// Segment flags (`PF_X`, `PF_W`, `PF_R`).
    pub flags: u32,
    /// File offset of the segment data.
    pub offset: u64,
    /// Virtual address of the segment in memory.
    pub vaddr: u64,
    /// Physical address of the segment.
    pub paddr: u64,
    /// Size of the segment in the file image.
    pub filesz: u64,
    /// Size of the segment in memory.
    pub memsz: u64,
    /// Required alignment of the segment.
    pub align: u64,
}

impl ElfPhdrInfo {
    /// Create a new program header entry.
    pub fn new(
        segment_type: u32,
        flags: u32,
        offset: u64,
        vaddr: u64,
        filesz: u64,
        memsz: u64,
        align: u64,
    ) -> Self {
        ElfPhdrInfo {
            segment_type,
            flags,
            offset,
            vaddr,
            paddr: vaddr,
            filesz,
            memsz,
            align,
        }
    }

    /// Create a `PT_LOAD` segment.
    pub fn load(flags: u32, offset: u64, vaddr: u64, filesz: u64, memsz: u64, align: u64) -> Self {
        Self::new(PT_LOAD, flags, offset, vaddr, filesz, memsz, align)
    }
}

// ============================================================================
// ElfNote
// ============================================================================

/// An ELF note entry.
#[derive(Debug, Clone, PartialEq)]
pub struct ElfNote {
    /// Note owner name (e.g., "GNU").
    pub name: String,
    /// Note type.
    pub note_type: u32,
    /// Note descriptor data.
    pub desc: Vec<u8>,
}

impl ElfNote {
    /// Create a new note.
    pub fn new(name: impl Into<String>, note_type: u32, desc: Vec<u8>) -> Self {
        ElfNote {
            name: name.into(),
            note_type,
            desc,
        }
    }
}

// ============================================================================
// ElfSection
// ============================================================================

/// A section in the ELF file.
#[derive(Debug, Clone)]
pub struct ElfSection {
    /// Section name.
    pub name: String,
    /// Section type (`SHT_PROGBITS`, `SHT_SYMTAB`, etc.).
    pub section_type: u32,
    /// Section flags (`SHF_WRITE`, `SHF_ALLOC`, `SHF_EXECINSTR`, etc.).
    pub flags: u64,
    /// Virtual address of the section in memory.
    pub addr: u64,
    /// Section content data.
    pub data: Vec<u8>,
    /// Link to another section (interpretation depends on section type).
    pub link: u32,
    /// Additional section information.
    pub info: u32,
    /// Required alignment of the section (0 or 1 = no alignment).
    pub addralign: u64,
    /// Size of each entry if the section holds a table of fixed-size entries.
    pub entsize: u64,
}

impl ElfSection {
    /// Create a new section.
    pub fn new(
        name: impl Into<String>,
        data: Vec<u8>,
        section_type: u32,
        flags: u64,
        addralign: u64,
    ) -> Self {
        ElfSection {
            name: name.into(),
            section_type,
            flags,
            addr: 0,
            data,
            link: 0,
            info: 0,
            addralign,
            entsize: 0,
        }
    }
}

// ============================================================================
// ElfWriter
// ============================================================================

/// ELF file writer/emitter.
///
/// Produces valid ELF32 and ELF64 object files (`.o`), executables, and
/// shared libraries.
///
/// # Example
///
/// ```ignore
/// let mut writer = ElfWriter::new_elf64_rel(ElfMachine::X86_64);
/// let text_idx = writer.add_section(".text", code_bytes, SHT_PROGBITS,
///                                    SHF_ALLOC | SHF_EXECINSTR, 16);
/// let data = writer.write();
/// ```
pub struct ElfWriter {
    /// ELF class: 32-bit or 64-bit.
    pub class: ElfClass,
    /// Endianness.
    pub endian: ElfEndian,
    /// OS/ABI identification.
    pub os_abi: ElfOsAbi,
    /// Target machine architecture.
    pub machine: ElfMachine,
    /// File type (`ET_REL`, `ET_EXEC`, `ET_DYN`).
    pub file_type: u16,
    /// Entry point address.
    pub entry: u64,
    /// Processor-specific flags.
    pub flags: u32,

    // Internal state
    sections: Vec<ElfSection>,
    shstrtab: Vec<u8>,
    shstrtab_name_offsets: HashMap<String, u32>,
    symtab: Option<ElfSymbolTable>,
    program_headers: Vec<ElfPhdrInfo>,
    notes: Vec<ElfNote>,
    /// Relocations: each entry is (section_index, vec of relocations).
    relocations: Vec<(u32, Vec<ElfRelocation>)>,

    // Track reserved section indices
    symtab_section_index: Option<u32>,
    strtab_section_index: Option<u32>,
    shstrtab_section_index: Option<u32>,
    null_section_added: bool,
}

impl ElfWriter {
    // ------------------------------------------------------------------
    // Constructor
    // ------------------------------------------------------------------

    /// Create a new `ElfWriter` with the given ELF parameters.
    pub fn new(
        class: ElfClass,
        endian: ElfEndian,
        os_abi: ElfOsAbi,
        machine: ElfMachine,
        file_type: u16,
    ) -> Self {
        ElfWriter {
            class,
            endian,
            os_abi,
            machine,
            file_type,
            entry: 0,
            flags: 0,
            sections: Vec::new(),
            shstrtab: Vec::new(),
            shstrtab_name_offsets: HashMap::new(),
            symtab: None,
            program_headers: Vec::new(),
            notes: Vec::new(),
            relocations: Vec::new(),
            symtab_section_index: None,
            strtab_section_index: None,
            shstrtab_section_index: None,
            null_section_added: false,
        }
    }

    // ------------------------------------------------------------------
    // Convenience constructors
    // ------------------------------------------------------------------

    /// Create for 64-bit ELF relocatable object.
    pub fn new_elf64_rel(machine: ElfMachine) -> Self {
        Self::new(
            ElfClass::Elf64,
            ElfEndian::Little,
            ElfOsAbi::SystemV,
            machine,
            ET_REL,
        )
    }

    /// Create for 32-bit ELF relocatable object.
    pub fn new_elf32_rel(machine: ElfMachine) -> Self {
        Self::new(
            ElfClass::Elf32,
            ElfEndian::Little,
            ElfOsAbi::SystemV,
            machine,
            ET_REL,
        )
    }

    /// Create for 64-bit ELF executable.
    pub fn new_elf64_exec(machine: ElfMachine, entry: u64) -> Self {
        let mut w = Self::new(
            ElfClass::Elf64,
            ElfEndian::Little,
            ElfOsAbi::SystemV,
            machine,
            ET_EXEC,
        );
        w.entry = entry;
        w
    }

    /// Create for 64-bit ELF shared object.
    pub fn new_elf64_shared(machine: ElfMachine) -> Self {
        Self::new(
            ElfClass::Elf64,
            ElfEndian::Little,
            ElfOsAbi::SystemV,
            machine,
            ET_DYN,
        )
    }

    // ------------------------------------------------------------------
    // Configuration
    // ------------------------------------------------------------------

    /// Set the entry point address.
    pub fn set_entry(&mut self, addr: u64) {
        self.entry = addr;
    }

    // ------------------------------------------------------------------
    // Section management
    // ------------------------------------------------------------------

    /// Ensure section 0 is a `SHT_NULL` section.
    ///
    /// If section 0 has already been added (or any section exists at index 0),
    /// this is a no-op. Otherwise, a null section is inserted at index 0.
    pub fn add_null_section(&mut self) {
        if self.null_section_added {
            return;
        }
        if !self.sections.is_empty() {
            // If sections already exist but first is not null, don't override.
            // We just mark null as added.
            self.null_section_added = true;
            return;
        }
        let null_sec = ElfSection::new("", Vec::new(), SHT_NULL, 0, 0);
        self.sections.push(null_sec);
        self.null_section_added = true;
    }

    /// Add a section and return its index (0-based).
    ///
    /// Section 0 is automatically added as `SHT_NULL` if not already present.
    pub fn add_section(
        &mut self,
        name: impl Into<String>,
        data: Vec<u8>,
        section_type: u32,
        flags: u64,
        addralign: u64,
    ) -> u32 {
        self.add_null_section();

        let name = name.into();
        let sec = ElfSection::new(&name, data, section_type, flags, addralign);
        let idx = self.sections.len() as u32;
        self.sections.push(sec);
        idx
    }

    /// Add the symbol table. This also adds the `.symtab` and `.strtab` sections.
    ///
    /// Returns the symbol table section index.
    pub fn add_symbol_table(&mut self, symtab: ElfSymbolTable) -> u32 {
        // Build the string table from symbol names
        let strtab_data = symtab.build_strtab();

        // Add .strtab section first
        let strtab_idx = self.add_section(".strtab", strtab_data, SHT_STRTAB, 0, 1);

        // Build symbol table entries
        let is_64bit = self.class.is_64bit();
        let symtab_data = symtab.build_symtab_entries(is_64bit);
        let entsize = if is_64bit { 24u64 } else { 16u64 };

        // Add .symtab section
        let mut symtab_idx = self.add_section(".symtab", symtab_data, SHT_SYMTAB, 0, 1);

        // Set sh_link (.symtab -> .strtab) and sh_entsize
        {
            let sec = &mut self.sections[symtab_idx as usize];
            sec.link = strtab_idx;
            sec.entsize = entsize;
            // sh_info = index of first non-local symbol
            sec.info = symtab.first_global() as u32;
        }

        self.symtab = Some(symtab);
        self.symtab_section_index = Some(symtab_idx);
        self.strtab_section_index = Some(strtab_idx);

        symtab_idx
    }

    /// Add a program header (segment).
    pub fn add_program_header(&mut self, phdr: ElfPhdrInfo) {
        self.program_headers.push(phdr);
    }

    /// Add a note.
    pub fn add_note(&mut self, note: ElfNote) {
        self.notes.push(note);
    }

    /// Add a relocation to a specific section.
    ///
    /// Relocations are collected and emitted into a corresponding
    /// `.relaNAME` or `.relNAME` section during `write()`.
    pub fn add_relocation(&mut self, section_index: u32, reloc: ElfRelocation) {
        // Find or create the relocation list for this section
        for (idx, relocs) in self.relocations.iter_mut() {
            if *idx == section_index {
                relocs.push(reloc);
                return;
            }
        }
        self.relocations.push((section_index, vec![reloc]));
    }

    // ------------------------------------------------------------------
    // String table helpers
    // ------------------------------------------------------------------

    /// Get or add a string to the internal string table buffer.
    fn add_strtab_string(&mut self, s: &str) -> u32 {
        if s.is_empty() {
            return 0;
        }
        if let Some(&off) = self.shstrtab_name_offsets.get(s) {
            return off;
        }
        let off = self.shstrtab.len() as u32;
        self.shstrtab_name_offsets.insert(s.to_string(), off);
        self.shstrtab.extend_from_slice(s.as_bytes());
        self.shstrtab.push(0u8);
        off
    }

    /// Build the section header string table (`.shstrtab`).
    ///
    /// This collects all section names, builds the string table, and
    /// ensures the shstrtab section includes its own name.
    pub fn build_shstrtab(&mut self) {
        // Ensure section 0 exists
        self.add_null_section();

        // Reset shstrtab
        self.shstrtab.clear();
        self.shstrtab_name_offsets.clear();
        self.shstrtab.push(0u8); // index 0 = NUL

        // Collect all section names (including .shstrtab itself)
        let mut names: Vec<String> = Vec::new();
        for sec in &self.sections {
            if !sec.name.is_empty() {
                names.push(sec.name.clone());
            }
        }

        // Also add names for relocation sections that will be created
        for (sec_idx, relocs) in &self.relocations {
            if relocs.is_empty() {
                continue;
            }
            let first_reloc = &relocs[0];
            let target_name = self
                .sections
                .get(*sec_idx as usize)
                .map(|s| s.name.as_str())
                .unwrap_or("");
            let prefix = if first_reloc.is_rela { ".rela" } else { ".rel" };
            let reloc_name = format!("{}{}", prefix, target_name);
            names.push(reloc_name);
        }

        // Also add names for note sections if any
        if !self.notes.is_empty() {
            names.push(".note".to_string());
        }

        // Ensure .shstrtab is in the list
        let shstrtab_name = SECTION_NAME_SHSTRTAB.to_string();
        if !names.contains(&shstrtab_name) {
            names.push(shstrtab_name);
        }

        // Build string table
        for name in &names {
            self.add_strtab_string(name);
        }
    }

    // ------------------------------------------------------------------
    // Compute offsets
    // ------------------------------------------------------------------

    /// Align an offset up to the given alignment.
    fn align_up(offset: u64, align: u64) -> u64 {
        if align <= 1 {
            return offset;
        }
        (offset + align - 1) & !(align - 1)
    }

    /// Compute the file offset where section data begins.
    fn data_start_offset(&self) -> u64 {
        let ehdr_size = self.ehdr_size();
        let phdr_size = self.phdr_total_size();
        ehdr_size + phdr_size
    }

    /// Size of the ELF header in bytes.
    fn ehdr_size(&self) -> u64 {
        if self.class.is_64bit() {
            64
        } else {
            52
        }
    }

    /// Total size of all program headers.
    fn phdr_total_size(&self) -> u64 {
        if self.program_headers.is_empty() {
            return 0;
        }
        let entry_size = if self.class.is_64bit() { 56u64 } else { 32u64 };
        self.program_headers.len() as u64 * entry_size
    }

    /// Size of one section header.
    fn shdr_entry_size(&self) -> u64 {
        if self.class.is_64bit() {
            64
        } else {
            40
        }
    }

    /// Get all sections including auto-generated relocation and note sections.
    fn all_sections(&self) -> Vec<(usize, &ElfSection)> {
        // We return indices into the internal sections vec, plus
        // synthetic sections for relocations and notes.
        // For offset computation, we need a flat list.
        // Strategy: return pairs of (original_index_or_special, section_ref)
        // But we need to know the data. Let's do this differently.
        // Just iterate and build temporary sections.

        // Actually, let's handle this in write() directly.
        Vec::new() // placeholder
    }

    // ------------------------------------------------------------------
    // Write methods
    // ------------------------------------------------------------------

    /// Write the ELF identification bytes (`e_ident`).
    fn write_e_ident(&self) -> Vec<u8> {
        let mut ident = vec![0u8; EI_NIDENT];
        ident[EI_MAG0] = ELF_MAGIC[0];
        ident[EI_MAG1] = ELF_MAGIC[1];
        ident[EI_MAG2] = ELF_MAGIC[2];
        ident[EI_MAG3] = ELF_MAGIC[3];
        ident[EI_CLASS] = self.class.to_u8();
        ident[EI_DATA] = self.endian.to_u8();
        ident[EI_VERSION] = EV_CURRENT as u8;
        ident[EI_OSABI] = self.os_abi.to_u8();
        // EI_ABIVERSION = 0 (already zero)
        // EI_PAD = 0 (already zero)
        ident
    }

    /// Helper: write u16 in the configured endianness.
    fn write_u16(&self, v: u16) -> [u8; 2] {
        match self.endian {
            ElfEndian::Little => v.to_le_bytes(),
            ElfEndian::Big => v.to_be_bytes(),
        }
    }

    /// Helper: write u32 in the configured endianness.
    fn write_u32(&self, v: u32) -> [u8; 4] {
        match self.endian {
            ElfEndian::Little => v.to_le_bytes(),
            ElfEndian::Big => v.to_be_bytes(),
        }
    }

    /// Helper: write u64 in the configured endianness.
    fn write_u64(&self, v: u64) -> [u8; 8] {
        match self.endian {
            ElfEndian::Little => v.to_le_bytes(),
            ElfEndian::Big => v.to_be_bytes(),
        }
    }

    /// Helper: write i32 in the configured endianness.
    fn write_i32(&self, v: i32) -> [u8; 4] {
        match self.endian {
            ElfEndian::Little => v.to_le_bytes(),
            ElfEndian::Big => v.to_be_bytes(),
        }
    }

    /// Helper: write i64 in the configured endianness.
    fn write_i64(&self, v: i64) -> [u8; 8] {
        match self.endian {
            ElfEndian::Little => v.to_le_bytes(),
            ElfEndian::Big => v.to_be_bytes(),
        }
    }

    /// Emit the complete ELF file as a byte vector.
    pub fn write(&mut self) -> Vec<u8> {
        // Build the section header string table
        self.build_shstrtab();

        // Ensure we have a .shstrtab section
        let shstrtab_idx = self.ensure_shstrtab_section();

        // Build relocation sections
        let mut reloc_sections: Vec<(u32, Vec<u8>, ElfSection)> = Vec::new();

        for (sec_idx, relocs) in &self.relocations {
            if relocs.is_empty() {
                continue;
            }
            let first_reloc = &relocs[0];
            let target_name = self
                .sections
                .get(*sec_idx as usize)
                .map(|s| s.name.as_str())
                .unwrap_or("");
            let prefix = if first_reloc.is_rela { ".rela" } else { ".rel" };
            let reloc_name = format!("{}{}", prefix, target_name);
            let section_type = if first_reloc.is_rela {
                SHT_RELA
            } else {
                SHT_REL
            };

            let is_64 = self.class.is_64bit();
            let entsize = if is_64 {
                if first_reloc.is_rela {
                    24u64
                } else {
                    16u64
                }
            } else {
                if first_reloc.is_rela {
                    12u64
                } else {
                    8u64
                }
            };

            // Generate relocation section data
            let reloc_data = self.write_relocations_raw(relocs);

            let mut reloc_sec = ElfSection::new(reloc_name, reloc_data, section_type, 0, 8);
            reloc_sec.entsize = entsize;
            reloc_sec.link = self.symtab_section_index.unwrap_or(0);
            reloc_sec.info = *sec_idx;

            reloc_sections.push((*sec_idx, Vec::new(), reloc_sec));
        }

        // Build note section if any notes exist
        let note_section: Option<ElfSection> = if !self.notes.is_empty() {
            let note_data = self.write_notes_raw();
            Some(ElfSection::new(".note", note_data, SHT_NOTE, 0, 4))
        } else {
            None
        };

        // Compute offsets
        // Layout:
        //   [ELF Header]
        //   [Program Headers]
        //   [Section Data 0]  (null, no data)
        //   [Section Data 1]
        //   ...
        //   [Relocation Sections]
        //   [Note Section]
        //   [.shstrtab]       (placed last for easy extension)
        //   [Section Headers]

        let ehdr_size = self.ehdr_size();
        let phdr_size = self.phdr_total_size();

        let mut current_offset = ehdr_size + phdr_size;
        let mut section_offsets: Vec<u64> = Vec::new();

        // Compute offsets for regular sections
        for (i, sec) in self.sections.iter().enumerate() {
            if sec.addralign > 1 {
                current_offset = Self::align_up(current_offset, sec.addralign);
            }
            section_offsets.push(current_offset);
            if sec.section_type != SHT_NOBITS && sec.section_type != SHT_NULL {
                current_offset += sec.data.len() as u64;
            }
            // SHT_NOBITS occupies no space in the file
        }

        // Compute offsets for relocation sections
        let mut reloc_section_offsets: Vec<u64> = Vec::new();
        for (_, _, reloc_sec) in &reloc_sections {
            if reloc_sec.addralign > 1 {
                current_offset = Self::align_up(current_offset, reloc_sec.addralign);
            }
            reloc_section_offsets.push(current_offset);
            current_offset += reloc_sec.data.len() as u64;
        }

        // Note section offset
        let note_offset = if note_section.is_some() {
            let off = current_offset;
            current_offset += note_section.as_ref().unwrap().data.len() as u64;
            off
        } else {
            0
        };

        // .shstrtab section offset
        if self.shstrtab_section_index.is_none() {
            // We need to add the shstrtab section
            // It will be a synthetic section at the end
        }
        // Update shstrtab data in the section
        if let Some(idx) = self.shstrtab_section_index {
            let sec = &mut self.sections[idx as usize];
            sec.data = self.shstrtab.clone();
        }

        // Recompute with shstrtab data included
        current_offset = ehdr_size + phdr_size;
        section_offsets.clear();

        for (i, sec) in self.sections.iter().enumerate() {
            if sec.addralign > 1 {
                current_offset = Self::align_up(current_offset, sec.addralign);
            }
            section_offsets.push(current_offset);
            if sec.section_type != SHT_NOBITS && sec.section_type != SHT_NULL && i != 0 {
                current_offset += sec.data.len() as u64;
            }
            // For index 0, SHT_NULL has no data
        }

        // Relocation section offsets (recompute)
        reloc_section_offsets.clear();
        for (_, _, reloc_sec) in &reloc_sections {
            if reloc_sec.addralign > 1 {
                current_offset = Self::align_up(current_offset, reloc_sec.addralign);
            }
            reloc_section_offsets.push(current_offset);
            current_offset += reloc_sec.data.len() as u64;
        }

        // Note section offset (recompute)
        let note_offset_final = if note_section.is_some() {
            let off = current_offset;
            current_offset += note_section.as_ref().unwrap().data.len() as u64;
            off
        } else {
            0
        };

        // Section header table offset (aligned to 8 for 64-bit, 4 for 32-bit)
        let shdr_align = if self.class.is_64bit() { 8u64 } else { 4u64 };
        current_offset = Self::align_up(current_offset, shdr_align);
        let shoff = current_offset;

        // Total sections: existing + relocation + note + shstrtab (if not already present)
        let total_sections =
            self.sections.len() + reloc_sections.len() + note_section.iter().count();

        // Start building the output
        let mut buf: Vec<u8> = Vec::new();

        // 1. ELF header
        buf.extend_from_slice(&self.write_elf_header_raw(
            phdr_size,
            shoff,
            shstrtab_idx,
            total_sections as u16,
        ));

        // 2. Program headers
        if !self.program_headers.is_empty() {
            buf.resize(ehdr_size as usize + phdr_size as usize, 0);
            let phdr_data = self.write_program_headers_raw();
            // Write into the reserved space
            let start = ehdr_size as usize;
            buf[start..start + phdr_data.len()].copy_from_slice(&phdr_data);
        }

        // 3. Section data
        for (i, sec) in self.sections.iter().enumerate() {
            let off = section_offsets[i] as usize;
            if buf.len() < off {
                buf.resize(off, 0);
            }
            if sec.section_type != SHT_NOBITS && sec.section_type != SHT_NULL {
                if buf.len() < off + sec.data.len() {
                    buf.resize(off + sec.data.len(), 0);
                }
                buf[off..off + sec.data.len()].copy_from_slice(&sec.data);
            }
        }

        // 4. Relocation section data
        for (j, (_, _, reloc_sec)) in reloc_sections.iter().enumerate() {
            let off = reloc_section_offsets[j] as usize;
            if buf.len() < off {
                buf.resize(off, 0);
            }
            if buf.len() < off + reloc_sec.data.len() {
                buf.resize(off + reloc_sec.data.len(), 0);
            }
            buf[off..off + reloc_sec.data.len()].copy_from_slice(&reloc_sec.data);
        }

        // 5. Note section data
        if let Some(ref note_sec) = note_section {
            let off = note_offset_final as usize;
            if buf.len() < off {
                buf.resize(off, 0);
            }
            if buf.len() < off + note_sec.data.len() {
                buf.resize(off + note_sec.data.len(), 0);
            }
            buf[off..off + note_sec.data.len()].copy_from_slice(&note_sec.data);
        }

        // 6. Section headers
        // Make sure shoff is correct
        let shoff_actual = buf.len() as u64;
        if shoff_actual < shoff {
            buf.resize(shoff as usize, 0);
        }

        let shdr_start = buf.len();
        let shdr_data = self.write_section_headers_raw(
            &section_offsets,
            &reloc_sections,
            &reloc_section_offsets,
            &note_section,
            note_offset_final,
            shstrtab_idx,
        );
        buf.extend_from_slice(&shdr_data);

        // Patch the ELF header with correct shoff and shnum if needed
        let shoff_field_offset = if self.class.is_64bit() { 0x28 } else { 0x20 };
        let shnum_field_offset = if self.class.is_64bit() { 0x3C } else { 0x30 };

        let shoff_bytes = if self.class.is_64bit() {
            self.write_u64(shdr_start as u64).to_vec()
        } else {
            self.write_u32(shdr_start as u32).to_vec()
        };
        let shnum_bytes = self.write_u16(total_sections as u16).to_vec();

        // Patch shoff
        let soff = shoff_field_offset as usize;
        buf[soff..soff + shoff_bytes.len()].copy_from_slice(&shoff_bytes);

        // Patch shnum
        let snum = shnum_field_offset as usize;
        buf[snum..snum + 2].copy_from_slice(&shnum_bytes);

        buf
    }

    /// Ensure the .shstrtab section exists and return its index.
    fn ensure_shstrtab_section(&mut self) -> u32 {
        if let Some(idx) = self.shstrtab_section_index {
            return idx;
        }

        // Check if a section named ".shstrtab" already exists
        for (i, sec) in self.sections.iter().enumerate() {
            if sec.name == SECTION_NAME_SHSTRTAB {
                let idx = i as u32;
                self.shstrtab_section_index = Some(idx);
                // Update its data
                self.sections[i].data = self.shstrtab.clone();
                return idx;
            }
        }

        // Add the shstrtab section
        let data = self.shstrtab.clone();
        let idx = self.add_section(SECTION_NAME_SHSTRTAB, data, SHT_STRTAB, 0, 1);
        self.shstrtab_section_index = Some(idx);
        idx
    }

    /// Write raw relocation data for a list of relocations.
    fn write_relocations_raw(&self, relocs: &[ElfRelocation]) -> Vec<u8> {
        let mut buf = Vec::new();
        let is_64 = self.class.is_64bit();

        for reloc in relocs {
            if is_64 {
                if reloc.is_rela {
                    // Elf64Rela: 24 bytes
                    buf.extend_from_slice(&self.write_u64(reloc.offset));
                    buf.extend_from_slice(
                        &self.write_u64(elf_r_info(
                            reloc.symbol_index as u64,
                            reloc.rel_type as u64,
                        )),
                    );
                    buf.extend_from_slice(&self.write_i64(reloc.addend));
                } else {
                    // Elf64Rel: 16 bytes
                    buf.extend_from_slice(&self.write_u64(reloc.offset));
                    buf.extend_from_slice(
                        &self.write_u64(elf_r_info(
                            reloc.symbol_index as u64,
                            reloc.rel_type as u64,
                        )),
                    );
                }
            } else {
                if reloc.is_rela {
                    // Elf32Rela: 12 bytes
                    buf.extend_from_slice(&self.write_u32(reloc.offset as u32));
                    buf.extend_from_slice(
                        &self.write_u32(elf_r_info32(reloc.symbol_index, reloc.rel_type)),
                    );
                    buf.extend_from_slice(&self.write_i32(reloc.addend as i32));
                } else {
                    // Elf32Rel: 8 bytes
                    buf.extend_from_slice(&self.write_u32(reloc.offset as u32));
                    buf.extend_from_slice(
                        &self.write_u32(elf_r_info32(reloc.symbol_index, reloc.rel_type)),
                    );
                }
            }
        }

        buf
    }

    /// Write raw note data.
    fn write_notes_raw(&self) -> Vec<u8> {
        let mut buf = Vec::new();

        for note in &self.notes {
            let name_bytes = note.name.as_bytes();
            let name_len = name_bytes.len() as u32;
            let desc_len = note.desc.len() as u32;

            // ElfNhdr
            buf.extend_from_slice(&self.write_u32(name_len));
            buf.extend_from_slice(&self.write_u32(desc_len));
            buf.extend_from_slice(&self.write_u32(note.note_type));

            // Name (padded to 4-byte alignment)
            buf.extend_from_slice(name_bytes);
            let name_padding = (4 - (name_len as usize % 4)) % 4;
            for _ in 0..name_padding {
                buf.push(0u8);
            }

            // Descriptor (padded to 4-byte alignment)
            buf.extend_from_slice(&note.desc);
            let desc_padding = (4 - (desc_len as usize % 4)) % 4;
            for _ in 0..desc_padding {
                buf.push(0u8);
            }
        }

        buf
    }

    /// Write raw ELF header.
    fn write_elf_header_raw(
        &self,
        phdr_size: u64,
        shoff: u64,
        shstrndx: u32,
        shnum: u16,
    ) -> Vec<u8> {
        let mut buf = Vec::new();
        let e_ident = self.write_e_ident();

        if self.class.is_64bit() {
            // Elf64Ehdr: 64 bytes
            buf.extend_from_slice(&e_ident);
            buf.extend_from_slice(&self.write_u16(self.file_type));
            buf.extend_from_slice(&self.write_u16(self.machine.to_u16()));
            buf.extend_from_slice(&self.write_u32(EV_CURRENT));
            buf.extend_from_slice(&self.write_u64(self.entry));
            buf.extend_from_slice(&self.write_u64(if phdr_size > 0 {
                self.ehdr_size()
            } else {
                0
            }));
            buf.extend_from_slice(&self.write_u64(shoff));
            buf.extend_from_slice(&self.write_u32(self.flags));
            buf.extend_from_slice(&self.write_u16(64)); // e_ehsize
            buf.extend_from_slice(&self.write_u16(if phdr_size > 0 { 56 } else { 0 })); // e_phentsize
            buf.extend_from_slice(&self.write_u16(self.program_headers.len() as u16)); // e_phnum
            buf.extend_from_slice(&self.write_u16(64)); // e_shentsize
            buf.extend_from_slice(&self.write_u16(shnum)); // e_shnum
            buf.extend_from_slice(&self.write_u16(shstrndx as u16)); // e_shstrndx
        } else {
            // Elf32Ehdr: 52 bytes
            buf.extend_from_slice(&e_ident);
            buf.extend_from_slice(&self.write_u16(self.file_type));
            buf.extend_from_slice(&self.write_u16(self.machine.to_u16()));
            buf.extend_from_slice(&self.write_u32(EV_CURRENT));
            buf.extend_from_slice(&self.write_u32(self.entry as u32));
            buf.extend_from_slice(&self.write_u32(if phdr_size > 0 { 52 } else { 0 })); // e_phoff
            buf.extend_from_slice(&self.write_u32(shoff as u32)); // e_shoff
            buf.extend_from_slice(&self.write_u32(self.flags));
            buf.extend_from_slice(&self.write_u16(52)); // e_ehsize
            buf.extend_from_slice(&self.write_u16(if phdr_size > 0 { 32 } else { 0 })); // e_phentsize
            buf.extend_from_slice(&self.write_u16(self.program_headers.len() as u16)); // e_phnum
            buf.extend_from_slice(&self.write_u16(40)); // e_shentsize
            buf.extend_from_slice(&self.write_u16(shnum)); // e_shnum
            buf.extend_from_slice(&self.write_u16(shstrndx as u16)); // e_shstrndx
        }

        buf
    }

    /// Write raw program headers.
    fn write_program_headers_raw(&self) -> Vec<u8> {
        let mut buf = Vec::new();

        for phdr in &self.program_headers {
            if self.class.is_64bit() {
                buf.extend_from_slice(&self.write_u32(phdr.segment_type));
                buf.extend_from_slice(&self.write_u32(phdr.flags));
                buf.extend_from_slice(&self.write_u64(phdr.offset));
                buf.extend_from_slice(&self.write_u64(phdr.vaddr));
                buf.extend_from_slice(&self.write_u64(phdr.paddr));
                buf.extend_from_slice(&self.write_u64(phdr.filesz));
                buf.extend_from_slice(&self.write_u64(phdr.memsz));
                buf.extend_from_slice(&self.write_u64(phdr.align));
            } else {
                buf.extend_from_slice(&self.write_u32(phdr.segment_type));
                buf.extend_from_slice(&self.write_u32(phdr.offset as u32));
                buf.extend_from_slice(&self.write_u32(phdr.vaddr as u32));
                buf.extend_from_slice(&self.write_u32(phdr.paddr as u32));
                buf.extend_from_slice(&self.write_u32(phdr.filesz as u32));
                buf.extend_from_slice(&self.write_u32(phdr.memsz as u32));
                buf.extend_from_slice(&self.write_u32(phdr.flags));
                buf.extend_from_slice(&self.write_u32(phdr.align as u32));
            }
        }

        buf
    }

    /// Write raw section headers.
    fn write_section_headers_raw(
        &self,
        section_offsets: &[u64],
        reloc_sections: &[(u32, Vec<u8>, ElfSection)],
        reloc_offsets: &[u64],
        note_section: &Option<ElfSection>,
        note_offset: u64,
        shstrtab_idx: u32,
    ) -> Vec<u8> {
        let mut buf = Vec::new();

        // Compute string table offsets for section names
        let name_offsets: HashMap<String, u32> = self.shstrtab_name_offsets.clone();

        let get_name_offset = |name: &str| -> u32 {
            if name.is_empty() {
                return 0;
            }
            name_offsets.get(name).copied().unwrap_or(0)
        };

        let is_64 = self.class.is_64bit();

        // Write regular sections
        for (i, sec) in self.sections.iter().enumerate() {
            let name_off = get_name_offset(&sec.name);
            let offset = section_offsets.get(i).copied().unwrap_or(0);
            let size = if sec.section_type == SHT_NOBITS {
                sec.data.len() as u64
            } else if sec.section_type == SHT_NULL {
                0
            } else {
                sec.data.len() as u64
            };

            if is_64 {
                buf.extend_from_slice(&self.write_u32(name_off));
                buf.extend_from_slice(&self.write_u32(sec.section_type));
                buf.extend_from_slice(&self.write_u64(sec.flags));
                buf.extend_from_slice(&self.write_u64(sec.addr));
                buf.extend_from_slice(&self.write_u64(offset));
                buf.extend_from_slice(&self.write_u64(size));
                buf.extend_from_slice(&self.write_u32(sec.link));
                buf.extend_from_slice(&self.write_u32(sec.info));
                buf.extend_from_slice(&self.write_u64(sec.addralign));
                buf.extend_from_slice(&self.write_u64(sec.entsize));
            } else {
                buf.extend_from_slice(&self.write_u32(name_off));
                buf.extend_from_slice(&self.write_u32(sec.section_type));
                buf.extend_from_slice(&self.write_u32(sec.flags as u32));
                buf.extend_from_slice(&self.write_u32(sec.addr as u32));
                buf.extend_from_slice(&self.write_u32(offset as u32));
                buf.extend_from_slice(&self.write_u32(size as u32));
                buf.extend_from_slice(&self.write_u32(sec.link));
                buf.extend_from_slice(&self.write_u32(sec.info));
                buf.extend_from_slice(&self.write_u32(sec.addralign as u32));
                buf.extend_from_slice(&self.write_u32(sec.entsize as u32));
            }
        }

        // Write relocation section headers
        let reg_count = self.sections.len();
        for (j, (target_idx, _, reloc_sec)) in reloc_sections.iter().enumerate() {
            let name_off = get_name_offset(&reloc_sec.name);
            let offset = reloc_offsets.get(j).copied().unwrap_or(0);

            if is_64 {
                buf.extend_from_slice(&self.write_u32(name_off));
                buf.extend_from_slice(&self.write_u32(reloc_sec.section_type));
                buf.extend_from_slice(&self.write_u64(reloc_sec.flags));
                buf.extend_from_slice(&self.write_u64(reloc_sec.addr));
                buf.extend_from_slice(&self.write_u64(offset));
                buf.extend_from_slice(&self.write_u64(reloc_sec.data.len() as u64));
                buf.extend_from_slice(&self.write_u32(reloc_sec.link));
                buf.extend_from_slice(&self.write_u32(reloc_sec.info));
                buf.extend_from_slice(&self.write_u64(reloc_sec.addralign));
                buf.extend_from_slice(&self.write_u64(reloc_sec.entsize));
            } else {
                buf.extend_from_slice(&self.write_u32(name_off));
                buf.extend_from_slice(&self.write_u32(reloc_sec.section_type));
                buf.extend_from_slice(&self.write_u32(reloc_sec.flags as u32));
                buf.extend_from_slice(&self.write_u32(reloc_sec.addr as u32));
                buf.extend_from_slice(&self.write_u32(offset as u32));
                buf.extend_from_slice(&self.write_u32(reloc_sec.data.len() as u32));
                buf.extend_from_slice(&self.write_u32(reloc_sec.link));
                buf.extend_from_slice(&self.write_u32(reloc_sec.info));
                buf.extend_from_slice(&self.write_u32(reloc_sec.addralign as u32));
                buf.extend_from_slice(&self.write_u32(reloc_sec.entsize as u32));
            }
        }

        // Write note section header
        if let Some(ns) = note_section {
            let name_off = get_name_offset(&ns.name);
            let size = ns.data.len() as u64;

            if is_64 {
                buf.extend_from_slice(&self.write_u32(name_off));
                buf.extend_from_slice(&self.write_u32(ns.section_type));
                buf.extend_from_slice(&self.write_u64(ns.flags));
                buf.extend_from_slice(&self.write_u64(ns.addr));
                buf.extend_from_slice(&self.write_u64(note_offset));
                buf.extend_from_slice(&self.write_u64(size));
                buf.extend_from_slice(&self.write_u32(ns.link));
                buf.extend_from_slice(&self.write_u32(ns.info));
                buf.extend_from_slice(&self.write_u64(ns.addralign));
                buf.extend_from_slice(&self.write_u64(ns.entsize));
            } else {
                buf.extend_from_slice(&self.write_u32(name_off));
                buf.extend_from_slice(&self.write_u32(ns.section_type));
                buf.extend_from_slice(&self.write_u32(ns.flags as u32));
                buf.extend_from_slice(&self.write_u32(ns.addr as u32));
                buf.extend_from_slice(&self.write_u32(note_offset as u32));
                buf.extend_from_slice(&self.write_u32(size as u32));
                buf.extend_from_slice(&self.write_u32(ns.link));
                buf.extend_from_slice(&self.write_u32(ns.info));
                buf.extend_from_slice(&self.write_u32(ns.addralign as u32));
                buf.extend_from_slice(&self.write_u32(ns.entsize as u32));
            }
        }

        buf
    }

    // ------------------------------------------------------------------
    // Public write methods (for individual components)
    // ------------------------------------------------------------------

    /// Emit the ELF header (`Elf64Ehdr` or `Elf32Ehdr`).
    pub fn write_elf_header(&self) -> Vec<u8> {
        // For standalone use, use dummy values
        let phdr_size = if self.program_headers.is_empty() {
            0u64
        } else {
            self.phdr_total_size()
        };
        self.write_elf_header_raw(phdr_size, 0, 0, 0)
    }

    /// Emit all section headers.
    pub fn write_section_headers(&self) -> Vec<u8> {
        // Build minimal data for the call
        let mut offsets = Vec::new();
        for _ in &self.sections {
            offsets.push(0u64);
        }
        let empty_relocs: Vec<(u32, Vec<u8>, ElfSection)> = Vec::new();
        let empty_offsets: Vec<u64> = Vec::new();
        self.write_section_headers_raw(&offsets, &empty_relocs, &empty_offsets, &None, 0, 0)
    }

    /// Emit section contents in order.
    pub fn write_section_data(&self) -> Vec<u8> {
        let mut buf = Vec::new();
        for sec in &self.sections {
            if sec.section_type != SHT_NOBITS && sec.section_type != SHT_NULL {
                buf.extend_from_slice(&sec.data);
            }
        }
        buf
    }

    /// Emit symbol table entries.
    pub fn write_symtab(&self) -> Vec<u8> {
        if let Some(ref symtab) = self.symtab {
            symtab.build_symtab_entries(self.class.is_64bit())
        } else {
            Vec::new()
        }
    }

    /// Emit the string table section data.
    pub fn write_strtab(&self) -> Vec<u8> {
        if let Some(ref symtab) = self.symtab {
            symtab.build_strtab()
        } else {
            vec![0u8]
        }
    }

    /// Emit RELA/REL entries for a given section.
    pub fn write_relocations(&self, section: &ElfSection) -> Vec<u8> {
        // Find the section index
        let sec_idx = self
            .sections
            .iter()
            .position(|s| std::ptr::eq(s as *const _, section as *const _))
            .map(|i| i as u32);

        if let Some(idx) = sec_idx {
            for (sid, relocs) in &self.relocations {
                if *sid == idx {
                    return self.write_relocations_raw(relocs);
                }
            }
        }
        Vec::new()
    }

    /// Emit program headers.
    pub fn write_program_headers(&self) -> Vec<u8> {
        self.write_program_headers_raw()
    }

    /// Emit notes.
    pub fn write_notes(&self) -> Vec<u8> {
        self.write_notes_raw()
    }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::elf::elf_types::{
        SECTION_NAME_BSS, SECTION_NAME_DATA, SECTION_NAME_RODATA, SECTION_NAME_TEXT, SHF_ALLOC,
        SHF_EXECINSTR, SHF_WRITE, SHT_NOBITS, SHT_PROGBITS, SHT_RELA, SHT_STRTAB, SHT_SYMTAB,
        STB_GLOBAL, STB_LOCAL, STT_FUNC, STT_NOTYPE, STT_OBJECT,
    };

    // ------------------------------------------------------------------
    // Helper: parse a little-endian u16 from bytes
    // ------------------------------------------------------------------
    fn read_u16_le(bytes: &[u8], offset: usize) -> u16 {
        u16::from_le_bytes([bytes[offset], bytes[offset + 1]])
    }

    fn read_u32_le(bytes: &[u8], offset: usize) -> u32 {
        u32::from_le_bytes([
            bytes[offset],
            bytes[offset + 1],
            bytes[offset + 2],
            bytes[offset + 3],
        ])
    }

    fn read_u64_le(bytes: &[u8], offset: usize) -> u64 {
        u64::from_le_bytes([
            bytes[offset],
            bytes[offset + 1],
            bytes[offset + 2],
            bytes[offset + 3],
            bytes[offset + 4],
            bytes[offset + 5],
            bytes[offset + 6],
            bytes[offset + 7],
        ])
    }

    // ------------------------------------------------------------------
    // Test: Empty ELF object creation
    // ------------------------------------------------------------------

    #[test]
    fn test_empty_elf64_object() {
        let mut writer = ElfWriter::new_elf64_rel(ElfMachine::X86_64);
        writer.add_null_section();
        let data = writer.write();

        // Should be non-empty and start with ELF magic
        assert!(data.len() > 64);
        assert_eq!(&data[0..4], &ELF_MAGIC);

        // Check e_ident
        assert_eq!(data[4], 2); // ELFCLASS64
        assert_eq!(data[5], 1); // ELFDATA2LSB
        assert_eq!(data[6], 1); // EV_CURRENT

        // Check e_type = ET_REL
        assert_eq!(read_u16_le(&data, 16), ET_REL);

        // Check e_machine = EM_X86_64
        assert_eq!(read_u16_le(&data, 18), EM_X86_64);
    }

    #[test]
    fn test_empty_elf32_object() {
        let mut writer = ElfWriter::new_elf32_rel(ElfMachine::X86);
        let data = writer.write();

        assert!(data.len() >= 52);
        assert_eq!(&data[0..4], &ELF_MAGIC);
        assert_eq!(data[4], 1); // ELFCLASS32
        assert_eq!(data[5], 1); // ELFDATA2LSB
        assert_eq!(read_u16_le(&data, 16), ET_REL);
        assert_eq!(read_u16_le(&data, 18), EM_386);
    }

    // ------------------------------------------------------------------
    // Test: Object with .text section
    // ------------------------------------------------------------------

    #[test]
    fn test_elf64_with_text_section() {
        let mut writer = ElfWriter::new_elf64_rel(ElfMachine::X86_64);
        let code = vec![0x90u8; 16]; // 16 NOPs
        let text_idx = writer.add_section(
            ".text",
            code.clone(),
            SHT_PROGBITS,
            SHF_ALLOC | SHF_EXECINSTR,
            16,
        );

        let data = writer.write();
        assert!(data.len() > 100);

        // Section index should be 1 (after null section)
        assert_eq!(text_idx, 1);

        // Verify .text data appears in the output
        // Find the code bytes somewhere after the ELF header
        let found = data.windows(16).any(|w| w == code.as_slice());
        assert!(found, "Expected to find .text data in ELF output");
    }

    // ------------------------------------------------------------------
    // Test: Object with .data, .rodata, .bss sections
    // ------------------------------------------------------------------

    #[test]
    fn test_elf64_with_data_sections() {
        let mut writer = ElfWriter::new_elf64_rel(ElfMachine::X86_64);

        let text_data = vec![0xCCu8; 32];
        let rodata_data = vec![0xAAu8; 16];
        let data_data = vec![0xBBu8; 8];
        let bss_size = 64usize;

        writer.add_section(
            ".text",
            text_data.clone(),
            SHT_PROGBITS,
            SHF_ALLOC | SHF_EXECINSTR,
            16,
        );
        writer.add_section(".rodata", rodata_data.clone(), SHT_PROGBITS, SHF_ALLOC, 8);
        writer.add_section(
            ".data",
            data_data.clone(),
            SHT_PROGBITS,
            SHF_ALLOC | SHF_WRITE,
            8,
        );
        writer.add_section(
            ".bss",
            vec![0u8; bss_size],
            SHT_NOBITS,
            SHF_ALLOC | SHF_WRITE,
            16,
        );

        let data = writer.write();

        // BSS should take NO space in file (SHT_NOBITS)
        // All other sections should be present
        assert!(data.len() > 150);
    }

    // ------------------------------------------------------------------
    // Test: Object with symbol table
    // ------------------------------------------------------------------

    #[test]
    fn test_elf64_with_symbol_table() {
        let mut writer = ElfWriter::new_elf64_rel(ElfMachine::X86_64);

        // Add a .text section first
        let text_idx = writer.add_section(
            ".text",
            vec![0x90u8; 16],
            SHT_PROGBITS,
            SHF_ALLOC | SHF_EXECINSTR,
            16,
        );

        // Build a symbol table
        let mut symtab = ElfSymbolTable::new();
        symtab.add_file_symbol("test.c");
        symtab.add_global_symbol("main", 0, 16, STT_FUNC, text_idx as u16);
        symtab.add_local_symbol("helper", 8, 8, STT_FUNC, text_idx as u16);

        let symtab_idx = writer.add_symbol_table(symtab);

        let data = writer.write();
        assert!(data.len() > 200);

        // We should have .symtab and .strtab sections
        // The symtab section should be SHT_SYMTAB
        assert!(symtab_idx > 0);
    }

    // ------------------------------------------------------------------
    // Test: Object with relocations
    // ------------------------------------------------------------------

    #[test]
    fn test_elf64_with_relocations() {
        let mut writer = ElfWriter::new_elf64_rel(ElfMachine::X86_64);

        // Add a .text section
        let text_idx = writer.add_section(
            ".text",
            vec![0u8; 32],
            SHT_PROGBITS,
            SHF_ALLOC | SHF_EXECINSTR,
            16,
        );

        // Add symbol table
        let mut symtab = ElfSymbolTable::new();
        symtab.add_global_symbol("ext_func", 0, 0, STT_FUNC, 0); // undefined
        symtab.add_global_symbol("main", 0, 16, STT_FUNC, text_idx as u16);
        writer.add_symbol_table(symtab);

        // Add relocations
        writer.add_relocation(text_idx, ElfRelocation::rela(0, 1, 1, -4)); // R_X86_64_64
        writer.add_relocation(text_idx, ElfRelocation::rela(8, 1, 2, -4)); // R_X86_64_PC32

        let data = writer.write();
        assert!(data.len() > 200);

        // Should have .rela.text section
        let rela_text_found = data.windows(12).any(|w| {
            // Look for ".rela.text" in string table
            w == b".rela.text\0"
        });
        // Actually, check for the section header entry
        // Just verify output is valid
        assert!(data.len() > 64);
    }

    // ------------------------------------------------------------------
    // Test: Multiple sections and symbols
    // ------------------------------------------------------------------

    #[test]
    fn test_elf64_multiple_sections_and_symbols() {
        let mut writer = ElfWriter::new_elf64_rel(ElfMachine::X86_64);

        let text_idx = writer.add_section(
            ".text",
            vec![0x90u8; 64],
            SHT_PROGBITS,
            SHF_ALLOC | SHF_EXECINSTR,
            16,
        );
        let data_idx = writer.add_section(
            ".data",
            vec![0x42u8; 32],
            SHT_PROGBITS,
            SHF_ALLOC | SHF_WRITE,
            8,
        );
        writer.add_section(".rodata", vec![0x13u8; 16], SHT_PROGBITS, SHF_ALLOC, 4);

        let mut symtab = ElfSymbolTable::new();
        symtab.add_file_symbol("multi.c");
        symtab.add_global_symbol("start", 0, 64, STT_FUNC, text_idx as u16);
        symtab.add_global_symbol("global_data", 0, 32, STT_OBJECT, data_idx as u16);
        symtab.add_local_symbol("local_const", 0, 16, STT_OBJECT, 2);
        writer.add_symbol_table(symtab);

        let data = writer.write();
        assert!(data.len() > 300);

        // Check ELF magic
        assert_eq!(&data[0..4], &ELF_MAGIC);
    }

    // ------------------------------------------------------------------
    // Test: Object with program headers (executable)
    // ------------------------------------------------------------------

    #[test]
    fn test_elf64_exec_with_program_headers() {
        let mut writer = ElfWriter::new_elf64_exec(ElfMachine::X86_64, 0x401000);

        let text_data = vec![0x90u8; 64];
        writer.add_section(
            ".text",
            text_data.clone(),
            SHT_PROGBITS,
            SHF_ALLOC | SHF_EXECINSTR,
            4096,
        );

        // Add a program header for the text segment
        writer.add_program_header(ElfPhdrInfo::load(
            PF_R | PF_X,
            0x1000,
            0x401000,
            64,
            64,
            4096,
        ));

        let data = writer.write();
        assert!(data.len() > 100);

        // Check e_type = ET_EXEC
        assert_eq!(read_u16_le(&data, 16), ET_EXEC);

        // Check entry point
        assert_eq!(read_u64_le(&data, 24), 0x401000);

        // Check that program headers exist
        // e_phnum should be > 0
        let phnum = read_u16_le(&data, 56);
        assert_eq!(phnum, 1);

        // e_phoff should point to right after ELF header
        let phoff = read_u64_le(&data, 32);
        assert_eq!(phoff, 64); // right after 64-byte ELF header
    }

    // ------------------------------------------------------------------
    // Test: ELF32 vs ELF64 output
    // ------------------------------------------------------------------

    #[test]
    fn test_elf32_vs_elf64_header_sizes() {
        let mut w32 = ElfWriter::new_elf32_rel(ElfMachine::X86);
        let data32 = w32.write();

        let mut w64 = ElfWriter::new_elf64_rel(ElfMachine::X86_64);
        let data64 = w64.write();

        // ELF32 header is 52 bytes, ELF64 is 64 bytes
        // Check e_ehsize
        assert_eq!(read_u16_le(&data32, 40), 52); // e_ehsize for 32-bit
        assert_eq!(read_u16_le(&data64, 52), 64); // e_ehsize for 64-bit

        // Both should start with ELF magic
        assert_eq!(&data32[0..4], &ELF_MAGIC);
        assert_eq!(&data64[0..4], &ELF_MAGIC);

        // Different classes
        assert_eq!(data32[4], 1); // ELFCLASS32
        assert_eq!(data64[4], 2); // ELFCLASS64
    }

    // ------------------------------------------------------------------
    // Test: 32-bit object with sections and symbols
    // ------------------------------------------------------------------

    #[test]
    fn test_elf32_with_sections() {
        let mut writer = ElfWriter::new_elf32_rel(ElfMachine::ARM);

        let text_idx = writer.add_section(
            ".text",
            vec![0x00u8; 32],
            SHT_PROGBITS,
            SHF_ALLOC | SHF_EXECINSTR,
            4,
        );

        let mut symtab = ElfSymbolTable::new();
        symtab.add_global_symbol("arm_func", 0, 32, STT_FUNC, text_idx as u16);
        writer.add_symbol_table(symtab);

        let data = writer.write();

        assert_eq!(&data[0..4], &ELF_MAGIC);
        assert_eq!(data[4], 1); // ELFCLASS32
        assert_eq!(read_u16_le(&data, 18), EM_ARM);

        // Should have section headers
        assert!(data.len() > 100);
    }

    // ------------------------------------------------------------------
    // Test: Big-endian output
    // ------------------------------------------------------------------

    #[test]
    fn test_elf64_big_endian_output() {
        let mut writer = ElfWriter::new(
            ElfClass::Elf64,
            ElfEndian::Big,
            ElfOsAbi::SystemV,
            ElfMachine::X86_64,
            ET_REL,
        );

        writer.add_section(
            ".text",
            vec![0x90u8; 16],
            SHT_PROGBITS,
            SHF_ALLOC | SHF_EXECINSTR,
            16,
        );

        let data = writer.write();

        // Check ELF magic
        assert_eq!(&data[0..4], &ELF_MAGIC);

        // Check endianness byte
        assert_eq!(data[5], 2); // ELFDATA2MSB

        // Check e_type in big-endian
        let e_type = u16::from_be_bytes([data[16], data[17]]);
        assert_eq!(e_type, ET_REL);
    }

    #[test]
    fn test_elf32_big_endian_output() {
        let mut writer = ElfWriter::new(
            ElfClass::Elf32,
            ElfEndian::Big,
            ElfOsAbi::SystemV,
            ElfMachine::X86,
            ET_REL,
        );

        let data = writer.write();

        assert_eq!(&data[0..4], &ELF_MAGIC);
        assert_eq!(data[4], 1); // ELFCLASS32
        assert_eq!(data[5], 2); // ELFDATA2MSB
    }

    // ------------------------------------------------------------------
    // Test: OS/ABI settings
    // ------------------------------------------------------------------

    #[test]
    fn test_elf_with_linux_abi() {
        let mut writer = ElfWriter::new(
            ElfClass::Elf64,
            ElfEndian::Little,
            ElfOsAbi::Linux,
            ElfMachine::X86_64,
            ET_REL,
        );
        writer.add_null_section();
        let data = writer.write();

        assert_eq!(data[7], 3); // ELFOSABI_LINUX
    }

    #[test]
    fn test_elf_with_freebsd_abi() {
        let mut writer = ElfWriter::new(
            ElfClass::Elf64,
            ElfEndian::Little,
            ElfOsAbi::FreeBSD,
            ElfMachine::X86_64,
            ET_REL,
        );
        writer.add_null_section();
        let data = writer.write();

        assert_eq!(data[7], 9); // ELFOSABI_FREEBSD
    }

    // ------------------------------------------------------------------
    // Test: Different machine types
    // ------------------------------------------------------------------

    #[test]
    fn test_machine_aarch64() {
        let mut writer = ElfWriter::new_elf64_rel(ElfMachine::AArch64);
        let data = writer.write();

        assert_eq!(read_u16_le(&data, 18), EM_AARCH64);
    }

    #[test]
    fn test_machine_riscv() {
        let mut writer = ElfWriter::new_elf64_rel(ElfMachine::RiscV);
        let data = writer.write();

        assert_eq!(read_u16_le(&data, 18), EM_RISCV);
    }

    #[test]
    fn test_machine_arm32() {
        let mut writer = ElfWriter::new_elf32_rel(ElfMachine::ARM);
        let data = writer.write();

        assert_eq!(read_u16_le(&data, 18), EM_ARM);
    }

    // ------------------------------------------------------------------
    // Test: Section flags
    // ------------------------------------------------------------------

    #[test]
    fn test_section_flags_propagation() {
        let mut writer = ElfWriter::new_elf64_rel(ElfMachine::X86_64);

        writer.add_section(
            ".text",
            vec![0x90u8; 16],
            SHT_PROGBITS,
            SHF_ALLOC | SHF_EXECINSTR,
            16,
        );

        let data = writer.write();

        // The section header table should reflect the flags
        // We'd need to parse the section header to verify, but
        // at minimum the output should be valid
        assert!(data.len() > 64);
    }

    // ------------------------------------------------------------------
    // Test: BSS section (SHT_NOBITS)
    // ------------------------------------------------------------------

    #[test]
    fn test_bss_section_no_file_space() {
        let mut writer = ElfWriter::new_elf64_rel(ElfMachine::X86_64);

        // Add .text first
        writer.add_section(
            ".text",
            vec![0x90u8; 16],
            SHT_PROGBITS,
            SHF_ALLOC | SHF_EXECINSTR,
            16,
        );

        // Add .bss with large size
        writer.add_section(
            ".bss",
            vec![0u8; 1024],
            SHT_NOBITS,
            SHF_ALLOC | SHF_WRITE,
            16,
        );

        let data = writer.write();

        // The file should be small (BSS takes no file space)
        // Total should be roughly: header + .text (16 bytes) + shstrtab + section headers
        assert!(data.len() < 500, "BSS should not occupy file space");
    }

    // ------------------------------------------------------------------
    // Test: Symbol table with null entry
    // ------------------------------------------------------------------

    #[test]
    fn test_symbol_table_null_entry() {
        let mut writer = ElfWriter::new_elf64_rel(ElfMachine::X86_64);

        let text_idx = writer.add_section(
            ".text",
            vec![0x90u8; 16],
            SHT_PROGBITS,
            SHF_ALLOC | SHF_EXECINSTR,
            16,
        );

        let mut symtab = ElfSymbolTable::new();
        symtab.add_global_symbol("my_func", 0, 16, STT_FUNC, text_idx as u16);

        let symtab_idx = writer.add_symbol_table(symtab);
        let data = writer.write();

        // The symbol table should start with a null entry (all zeros)
        // We can check the section data for .symtab
        assert!(symtab_idx > 0);
        assert!(data.len() > 100);
    }

    // ------------------------------------------------------------------
    // Test: Relocation with addend
    // ------------------------------------------------------------------

    #[test]
    fn test_relocations_with_addend() {
        let mut writer = ElfWriter::new_elf64_rel(ElfMachine::X86_64);

        let text_idx = writer.add_section(
            ".text",
            vec![0u8; 32],
            SHT_PROGBITS,
            SHF_ALLOC | SHF_EXECINSTR,
            16,
        );

        let mut symtab = ElfSymbolTable::new();
        symtab.add_global_symbol("ext_sym", 0, 0, STT_FUNC, 0);
        let sym_idx = writer.add_symbol_table(symtab);

        writer.add_relocation(
            text_idx,
            ElfRelocation::rela(4, 1, 1, 42), // offset=4, sym=1, type=1, addend=42
        );
        writer.add_relocation(
            text_idx,
            ElfRelocation::rela(16, 1, 2, -8), // offset=16, sym=1, type=2, addend=-8
        );

        let data = writer.write();
        assert!(data.len() > 150);
    }

    // ------------------------------------------------------------------
    // Test: REL vs RELA relocations
    // ------------------------------------------------------------------

    #[test]
    fn test_rel_vs_rela() {
        // RELA
        {
            let mut writer = ElfWriter::new_elf64_rel(ElfMachine::X86_64);
            let text_idx = writer.add_section(
                ".text",
                vec![0u8; 16],
                SHT_PROGBITS,
                SHF_ALLOC | SHF_EXECINSTR,
                16,
            );
            let mut symtab = ElfSymbolTable::new();
            symtab.add_global_symbol("sym", 0, 0, STT_FUNC, 0);
            writer.add_symbol_table(symtab);
            writer.add_relocation(text_idx, ElfRelocation::rela(0, 1, 1, 0));
            let data = writer.write();
            assert!(data.len() > 100);
        }

        // REL
        {
            let mut writer = ElfWriter::new_elf64_rel(ElfMachine::X86_64);
            let text_idx = writer.add_section(
                ".text",
                vec![0u8; 16],
                SHT_PROGBITS,
                SHF_ALLOC | SHF_EXECINSTR,
                16,
            );
            let mut symtab = ElfSymbolTable::new();
            symtab.add_global_symbol("sym", 0, 0, STT_FUNC, 0);
            writer.add_symbol_table(symtab);
            writer.add_relocation(text_idx, ElfRelocation::rel(0, 1, 1));
            let data = writer.write();
            assert!(data.len() > 100);
        }
    }

    // ------------------------------------------------------------------
    // Test: Notes
    // ------------------------------------------------------------------

    #[test]
    fn test_elf_with_notes() {
        let mut writer = ElfWriter::new_elf64_rel(ElfMachine::X86_64);

        writer.add_note(ElfNote::new("GNU", 3, vec![1, 2, 3, 4])); // NT_GNU_BUILD_ID = 3
        writer.add_note(ElfNote::new("test", 1, vec![0xAA, 0xBB]));

        let data = writer.write();
        assert!(data.len() > 100);

        // Check that note data is present
        let found_gnu = data.windows(4).any(|w| w == b"GNU\0");
        assert!(found_gnu, "Expected to find 'GNU' note name in output");
    }

    // ------------------------------------------------------------------
    // Test: Shared library (ET_DYN)
    // ------------------------------------------------------------------

    #[test]
    fn test_elf64_shared_object() {
        let mut writer = ElfWriter::new_elf64_shared(ElfMachine::X86_64);

        writer.add_section(
            ".text",
            vec![0x90u8; 16],
            SHT_PROGBITS,
            SHF_ALLOC | SHF_EXECINSTR,
            16,
        );

        let data = writer.write();

        assert_eq!(read_u16_le(&data, 16), ET_DYN);
        assert_eq!(&data[0..4], &ELF_MAGIC);
    }

    // ------------------------------------------------------------------
    // Test: Entry point
    // ------------------------------------------------------------------

    #[test]
    fn test_set_entry_point() {
        let mut writer = ElfWriter::new_elf64_exec(ElfMachine::X86_64, 0x400000);
        let data = writer.write();

        assert_eq!(read_u64_le(&data, 24), 0x400000);
    }

    #[test]
    fn test_set_entry_after_construction() {
        let mut writer = ElfWriter::new_elf64_rel(ElfMachine::X86_64);
        writer.file_type = ET_EXEC;
        writer.set_entry(0x800000);

        let data = writer.write();
        assert_eq!(read_u64_le(&data, 24), 0x800000);
        assert_eq!(read_u16_le(&data, 16), ET_EXEC);
    }

    // ------------------------------------------------------------------
    // Test: Section alignment
    // ------------------------------------------------------------------

    #[test]
    fn test_section_alignment() {
        let mut writer = ElfWriter::new_elf64_rel(ElfMachine::X86_64);

        // Add sections with different alignments
        writer.add_section(
            ".text",
            vec![0x90u8; 1],
            SHT_PROGBITS,
            SHF_ALLOC | SHF_EXECINSTR,
            64,
        );
        writer.add_section(
            ".data",
            vec![0x42u8; 1],
            SHT_PROGBITS,
            SHF_ALLOC | SHF_WRITE,
            1,
        );

        let data = writer.write();
        // Output should be valid (aligned properly)
        assert!(data.len() > 64);
    }

    // ------------------------------------------------------------------
    // Test: Flags field
    // ------------------------------------------------------------------

    #[test]
    fn test_flags_field() {
        let mut writer = ElfWriter::new_elf64_rel(ElfMachine::X86_64);
        writer.flags = 0x12345678;
        let data = writer.write();

        let flags = read_u32_le(&data, 48); // e_flags at offset 48 in Elf64Ehdr
        assert_eq!(flags, 0x12345678);
    }

    // ------------------------------------------------------------------
    // Test: shstrtab includes all section names
    // ------------------------------------------------------------------

    #[test]
    fn test_shstrtab_contains_all_names() {
        let mut writer = ElfWriter::new_elf64_rel(ElfMachine::X86_64);

        writer.add_section(
            ".text",
            vec![0x90u8; 8],
            SHT_PROGBITS,
            SHF_ALLOC | SHF_EXECINSTR,
            16,
        );
        writer.add_section(".my_custom_section", vec![0u8; 4], SHT_PROGBITS, 0, 1);

        let data = writer.write();

        // Check that section names appear in the string table
        let found_text = data.windows(6).any(|w| w == b".text\0");
        let found_custom = data
            .windows(20)
            .any(|w| w.len() >= 19 && w[..19] == b".my_custom_section\0"[..19]);

        assert!(found_text, ".text should be in shstrtab");
        assert!(found_custom, ".my_custom_section should be in shstrtab");
        // .shstrtab should contain its own name
        let found_shstrtab = data.windows(10).any(|w| w == b".shstrtab\0");
        assert!(found_shstrtab, ".shstrtab should be in shstrtab");
    }

    // ------------------------------------------------------------------
    // Test: Section link fields
    // ------------------------------------------------------------------

    #[test]
    fn test_section_link_fields() {
        let mut writer = ElfWriter::new_elf64_rel(ElfMachine::X86_64);

        let text_idx = writer.add_section(
            ".text",
            vec![0x90u8; 16],
            SHT_PROGBITS,
            SHF_ALLOC | SHF_EXECINSTR,
            16,
        );

        let mut symtab = ElfSymbolTable::new();
        symtab.add_global_symbol("func", 0, 16, STT_FUNC, text_idx as u16);
        let symtab_idx = writer.add_symbol_table(symtab);

        writer.add_relocation(text_idx, ElfRelocation::rela(0, 1, 1, 0));

        let data = writer.write();

        // The symtab's sh_link should point to strtab
        // The rela section's sh_link should point to symtab
        assert!(symtab_idx > 0);
        assert!(data.len() > 100);
    }

    // ------------------------------------------------------------------
    // Test: Multiple program headers
    // ------------------------------------------------------------------

    #[test]
    fn test_multiple_program_headers() {
        let mut writer = ElfWriter::new_elf64_exec(ElfMachine::X86_64, 0x401000);

        writer.add_program_header(ElfPhdrInfo::load(
            PF_R | PF_X,
            0x1000,
            0x401000,
            0x1000,
            0x1000,
            0x1000,
        ));
        writer.add_program_header(ElfPhdrInfo::load(
            PF_R | PF_W,
            0x2000,
            0x602000,
            0x500,
            0x500,
            0x1000,
        ));

        let data = writer.write();

        let phnum = read_u16_le(&data, 56);
        assert_eq!(phnum, 2);
    }

    // ------------------------------------------------------------------
    // Test: Convenience constructors
    // ------------------------------------------------------------------

    #[test]
    fn test_convenience_constructors() {
        // new_elf64_rel
        {
            let w = ElfWriter::new_elf64_rel(ElfMachine::AArch64);
            assert_eq!(w.class, ElfClass::Elf64);
            assert_eq!(w.file_type, ET_REL);
            assert_eq!(w.machine, ElfMachine::AArch64);
            assert_eq!(w.endian, ElfEndian::Little);
        }

        // new_elf32_rel
        {
            let w = ElfWriter::new_elf32_rel(ElfMachine::ARM);
            assert_eq!(w.class, ElfClass::Elf32);
            assert_eq!(w.file_type, ET_REL);
            assert_eq!(w.machine, ElfMachine::ARM);
        }

        // new_elf64_exec
        {
            let w = ElfWriter::new_elf64_exec(ElfMachine::X86_64, 0x1000);
            assert_eq!(w.class, ElfClass::Elf64);
            assert_eq!(w.file_type, ET_EXEC);
            assert_eq!(w.entry, 0x1000);
        }

        // new_elf64_shared
        {
            let w = ElfWriter::new_elf64_shared(ElfMachine::X86_64);
            assert_eq!(w.class, ElfClass::Elf64);
            assert_eq!(w.file_type, ET_DYN);
        }
    }

    // ------------------------------------------------------------------
    // Test: idempotent add_null_section
    // ------------------------------------------------------------------

    #[test]
    fn test_add_null_section_idempotent() {
        let mut writer = ElfWriter::new_elf64_rel(ElfMachine::X86_64);
        writer.add_null_section();
        writer.add_null_section();
        writer.add_null_section();

        // Should only have one section (index 0)
        assert_eq!(writer.sections.len(), 1);
        assert_eq!(writer.sections[0].section_type, SHT_NULL);
    }

    // ------------------------------------------------------------------
    // Test: Write individual components
    // ------------------------------------------------------------------

    #[test]
    fn test_write_individual_components() {
        let mut writer = ElfWriter::new_elf64_rel(ElfMachine::X86_64);

        writer.add_section(
            ".text",
            vec![0xCCu8; 8],
            SHT_PROGBITS,
            SHF_ALLOC | SHF_EXECINSTR,
            16,
        );

        let mut symtab = ElfSymbolTable::new();
        symtab.add_global_symbol("fn", 0, 8, STT_FUNC, 1);
        writer.add_symbol_table(symtab);

        writer.add_note(ElfNote::new("GNU", 3, vec![0x12, 0x34]));

        // Test individual writers
        let ehdr = writer.write_elf_header();
        assert_eq!(ehdr.len(), 64);
        assert_eq!(&ehdr[0..4], &ELF_MAGIC);

        let shdrs = writer.write_section_headers();
        assert!(!shdrs.is_empty());

        let sec_data = writer.write_section_data();
        assert!(sec_data.contains(&0xCCu8));

        let symtab_data = writer.write_symtab();
        assert!(!symtab_data.is_empty());
        // null entry + 2 symbols (file + fn) = 3 entries * 24 bytes = 72
        // Actually: null + file_symbol(not added in this test) + fn
        // symtab.new() has null entry, then we add "fn" = 2 entries * 24
        assert_eq!(symtab_data.len(), 2 * 24);

        let strtab = writer.write_strtab();
        assert_eq!(strtab[0], 0u8); // Starts with NUL

        let phdrs = writer.write_program_headers();
        assert!(phdrs.is_empty()); // No program headers added

        let notes = writer.write_notes();
        assert!(!notes.is_empty());
    }

    // ------------------------------------------------------------------
    // Test: Roundtrip — write then validate with elf_types parsing
    // ------------------------------------------------------------------

    #[test]
    fn test_roundtrip_write_and_validate_header() {
        let mut writer = ElfWriter::new_elf64_rel(ElfMachine::X86_64);

        let text_data = vec![0x90u8; 32];
        writer.add_section(
            ".text",
            text_data.clone(),
            SHT_PROGBITS,
            SHF_ALLOC | SHF_EXECINSTR,
            16,
        );

        let mut symtab = ElfSymbolTable::new();
        symtab.add_global_symbol("main", 0, 32, STT_FUNC, 1);
        writer.add_symbol_table(symtab);

        let data = writer.write();

        // Validate ELF header fields
        assert_eq!(&data[0..4], &[0x7f, b'E', b'L', b'F']);
        assert_eq!(data[4], 2); // ELFCLASS64
        assert_eq!(data[5], 1); // ELFDATA2LSB
        assert_eq!(data[6], 1); // EV_CURRENT

        let e_type = u16::from_le_bytes([data[16], data[17]]);
        assert_eq!(e_type, ET_REL);

        let e_machine = u16::from_le_bytes([data[18], data[19]]);
        assert_eq!(e_machine, EM_X86_64);

        // Header size
        let e_ehsize = u16::from_le_bytes([data[52], data[53]]);
        assert_eq!(e_ehsize, 64);

        // Section header size
        let e_shentsize = u16::from_le_bytes([data[58], data[59]]);
        assert_eq!(e_shentsize, 64);

        // Should have at least: null, .text, .symtab, .strtab, .shstrtab
        let e_shnum = u16::from_le_bytes([data[60], data[61]]);
        assert!(e_shnum >= 5);

        // e_shstrndx should be valid
        let e_shstrndx = u16::from_le_bytes([data[62], data[63]]);
        assert!(e_shstrndx < e_shnum);
    }

    // ------------------------------------------------------------------
    // Test: Large number of sections
    // ------------------------------------------------------------------

    #[test]
    fn test_many_sections() {
        let mut writer = ElfWriter::new_elf64_rel(ElfMachine::X86_64);

        for i in 0..10 {
            let name = format!(".section_{}", i);
            writer.add_section(
                name,
                vec![i as u8; 8],
                SHT_PROGBITS,
                SHF_ALLOC,
                if i % 2 == 0 { 16 } else { 8 },
            );
        }

        let data = writer.write();
        assert!(data.len() > 400);

        // Should have proper section headers (null + 10 sections + .shstrtab = 12)
        let e_shnum = u16::from_le_bytes([data[60], data[61]]);
        assert_eq!(e_shnum, 12);
    }

    // ------------------------------------------------------------------
    // Test: Write with no sections except null
    // ------------------------------------------------------------------

    #[test]
    fn test_write_with_only_null_section() {
        let mut writer = ElfWriter::new_elf64_rel(ElfMachine::X86_64);
        writer.add_null_section();
        let data = writer.write();

        assert!(data.len() >= 64);
        assert_eq!(&data[0..4], &ELF_MAGIC);
    }

    // ------------------------------------------------------------------
    // Test: Processor-specific flags
    // ------------------------------------------------------------------

    #[test]
    fn test_processor_specific_flags() {
        let mut writer = ElfWriter::new_elf64_rel(ElfMachine::X86_64);
        writer.flags = 0xDEADBEEF;
        let data = writer.write();

        // e_flags is at offset 48 in Elf64Ehdr
        let e_flags = u32::from_le_bytes([data[48], data[49], data[50], data[51]]);
        assert_eq!(e_flags, 0xDEADBEEF);
    }
}