synth-backend 0.11.2

ARM encoder, ELF builder, vector table, linker scripts, and MPU configuration
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
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
//! ELF (Executable and Linkable Format) Builder for ARM
//!
//! Generates ELF32 files for ARM Cortex-M targets

use synth_core::Result;

/// ELF file class
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ElfClass {
    /// 32-bit
    Elf32 = 1,
    /// 64-bit
    Elf64 = 2,
}

/// ELF data encoding
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ElfData {
    /// Little-endian
    LittleEndian = 1,
    /// Big-endian
    BigEndian = 2,
}

/// ELF file type
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ElfType {
    /// Relocatable file
    Rel = 1,
    /// Executable file
    Exec = 2,
    /// Shared object file
    Dyn = 3,
}

/// ELF machine architecture
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ElfMachine {
    /// ARM
    Arm = 40,
    /// ARM64/AArch64
    AArch64 = 183,
}

/// Section type
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SectionType {
    /// Null section
    Null = 0,
    /// Program data
    ProgBits = 1,
    /// Symbol table
    SymTab = 2,
    /// String table
    StrTab = 3,
    /// Relocation entries with addends
    Rela = 4,
    /// Symbol hash table
    Hash = 5,
    /// Dynamic linking information
    Dynamic = 6,
    /// Note
    Note = 7,
    /// No space (BSS)
    NoBits = 8,
    /// Relocation entries
    Rel = 9,
}

/// Section flags
#[derive(Debug, Clone, Copy)]
pub struct SectionFlags(pub u32);

impl SectionFlags {
    /// Writable
    pub const WRITE: u32 = 0x1;
    /// Occupies memory during execution
    pub const ALLOC: u32 = 0x2;
    /// Executable
    pub const EXEC: u32 = 0x4;
    /// Mergeable
    pub const MERGE: u32 = 0x10;
    /// Contains null-terminated strings
    pub const STRINGS: u32 = 0x20;
}

/// ELF section
#[derive(Debug, Clone)]
pub struct Section {
    /// Section name (index into string table)
    pub name: String,
    /// Section type
    pub section_type: SectionType,
    /// Section flags
    pub flags: u32,
    /// Virtual address
    pub addr: u32,
    /// Section data
    pub data: Vec<u8>,
    /// Alignment
    pub align: u32,
    /// Explicit size (for NoBits sections like .bss where data is empty)
    pub explicit_size: Option<u32>,
}

impl Section {
    /// Create a new section
    pub fn new(name: &str, section_type: SectionType) -> Self {
        Self {
            name: name.to_string(),
            section_type,
            flags: 0,
            addr: 0,
            data: Vec::new(),
            align: 1,
            explicit_size: None,
        }
    }

    /// Set flags
    pub fn with_flags(mut self, flags: u32) -> Self {
        self.flags = flags;
        self
    }

    /// Set address
    pub fn with_addr(mut self, addr: u32) -> Self {
        self.addr = addr;
        self
    }

    /// Set alignment
    pub fn with_align(mut self, align: u32) -> Self {
        self.align = align;
        self
    }

    /// Add data
    pub fn with_data(mut self, data: Vec<u8>) -> Self {
        self.data = data;
        self
    }

    /// Set explicit size (for NoBits sections like .bss where data is empty)
    pub fn with_size(mut self, size: u32) -> Self {
        self.explicit_size = Some(size);
        self
    }

    /// Get the effective size of the section
    pub fn size(&self) -> u32 {
        self.explicit_size.unwrap_or(self.data.len() as u32)
    }
}

/// Symbol binding
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SymbolBinding {
    /// Local symbol
    Local = 0,
    /// Global symbol
    Global = 1,
    /// Weak symbol
    Weak = 2,
}

/// Symbol type
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SymbolType {
    /// No type
    NoType = 0,
    /// Object (data)
    Object = 1,
    /// Function
    Func = 2,
    /// Section
    Section = 3,
    /// File name
    File = 4,
}

/// ELF symbol
#[derive(Debug, Clone)]
pub struct Symbol {
    /// Symbol name
    pub name: String,
    /// Value/address
    pub value: u32,
    /// Size
    pub size: u32,
    /// Binding
    pub binding: SymbolBinding,
    /// Type
    pub symbol_type: SymbolType,
    /// Section index
    pub section: u16,
}

impl Symbol {
    /// Create a new symbol
    pub fn new(name: &str) -> Self {
        Self {
            name: name.to_string(),
            value: 0,
            size: 0,
            binding: SymbolBinding::Local,
            symbol_type: SymbolType::NoType,
            section: 0,
        }
    }

    /// Set value
    pub fn with_value(mut self, value: u32) -> Self {
        self.value = value;
        self
    }

    /// Set size
    pub fn with_size(mut self, size: u32) -> Self {
        self.size = size;
        self
    }

    /// Set binding
    pub fn with_binding(mut self, binding: SymbolBinding) -> Self {
        self.binding = binding;
        self
    }

    /// Set type
    pub fn with_type(mut self, symbol_type: SymbolType) -> Self {
        self.symbol_type = symbol_type;
        self
    }

    /// Set section
    pub fn with_section(mut self, section: u16) -> Self {
        self.section = section;
        self
    }
}

/// Program header type
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ProgramType {
    /// Null entry
    Null = 0,
    /// Loadable segment
    Load = 1,
    /// Dynamic linking info
    Dynamic = 2,
    /// Interpreter path
    Interp = 3,
    /// Note section
    Note = 4,
}

/// Program header flags
pub struct ProgramFlags;

impl ProgramFlags {
    /// Executable
    pub const EXEC: u32 = 0x1;
    /// Writable
    pub const WRITE: u32 = 0x2;
    /// Readable
    pub const READ: u32 = 0x4;
}

/// ELF program header (segment)
#[derive(Debug, Clone)]
pub struct ProgramHeader {
    /// Segment type
    pub p_type: ProgramType,
    /// Offset in file
    pub offset: u32,
    /// Virtual address
    pub vaddr: u32,
    /// Physical address
    pub paddr: u32,
    /// Size in file
    pub filesz: u32,
    /// Size in memory
    pub memsz: u32,
    /// Flags (R/W/X)
    pub flags: u32,
    /// Alignment
    pub align: u32,
}

impl ProgramHeader {
    /// Create a new LOAD segment
    pub fn load(vaddr: u32, offset: u32, size: u32, flags: u32) -> Self {
        Self {
            p_type: ProgramType::Load,
            offset,
            vaddr,
            paddr: vaddr, // Physical = virtual for simple cases
            filesz: size,
            memsz: size,
            flags,
            align: 4,
        }
    }

    /// Create a new LOAD segment for BSS-like regions (no file data, only memory)
    /// Used for .bss, linear memory, and other zero-initialized regions
    pub fn load_nobits(vaddr: u32, memsz: u32, flags: u32) -> Self {
        Self {
            p_type: ProgramType::Load,
            offset: 0, // No file offset for NoBits
            vaddr,
            paddr: vaddr, // Physical = virtual
            filesz: 0,    // No file data
            memsz,        // Memory size to allocate
            flags,
            align: 4,
        }
    }
}

/// ARM relocation type
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ArmRelocationType {
    /// R_ARM_THM_CALL (10) — Thumb BL/BLX instruction (Cortex-M). This is the
    /// correct relocation for a Thumb-2 `bl` call site; `Call`/R_ARM_CALL below
    /// is the ARM-mode form and is mis-resolved by `ld` for Thumb calls.
    ThmCall = 10,
    /// R_ARM_CALL (28) — BL/BLX instruction
    Call = 28,
    /// R_ARM_JUMP24 (29) — B/BL<cond> instruction
    Jump24 = 29,
    /// R_ARM_ABS32 (2) — Direct 32-bit reference
    Abs32 = 2,
    /// R_ARM_MOVW_ABS_NC (43) — MOVW instruction (low 16 bits)
    MovwAbsNc = 43,
    /// R_ARM_MOVT_ABS (44) — MOVT instruction (high 16 bits)
    MovtAbs = 44,
}

/// ELF relocation entry (REL format, no addend)
#[derive(Debug, Clone)]
pub struct Relocation {
    /// Offset within the section where the relocation applies
    pub offset: u32,
    /// Symbol index in the symbol table
    pub symbol_index: u32,
    /// Relocation type
    pub reloc_type: ArmRelocationType,
}

/// ARM EABI version 5 (soft-float)
pub const EF_ARM_EABI_VER5: u32 = 0x05000000;
/// ARM hard-float ABI flag
pub const EF_ARM_ABI_FLOAT_HARD: u32 = 0x00000400;
/// ARM soft-float ABI flag
pub const EF_ARM_ABI_FLOAT_SOFT: u32 = 0x00000200;

/// ELF file builder
pub struct ElfBuilder {
    /// File class (32 or 64 bit)
    class: ElfClass,
    /// Data encoding
    data: ElfData,
    /// File type
    elf_type: ElfType,
    /// Machine architecture
    machine: ElfMachine,
    /// Entry point address
    entry: u32,
    /// ELF e_flags (EABI version + float ABI)
    e_flags: u32,
    /// Sections
    sections: Vec<Section>,
    /// Symbols
    symbols: Vec<Symbol>,
    /// Program headers (segments)
    program_headers: Vec<ProgramHeader>,
    /// Relocations for .text section
    relocations: Vec<Relocation>,
}

impl ElfBuilder {
    /// Create a new ELF builder for ARM32
    pub fn new_arm32() -> Self {
        Self {
            class: ElfClass::Elf32,
            data: ElfData::LittleEndian,
            elf_type: ElfType::Exec,
            machine: ElfMachine::Arm,
            entry: 0,
            e_flags: EF_ARM_EABI_VER5,
            sections: Vec::new(),
            symbols: Vec::new(),
            program_headers: Vec::new(),
            relocations: Vec::new(),
        }
    }

    /// Set entry point
    ///
    /// For ARM (Thumb) targets, bit 0 is automatically set to indicate Thumb mode.
    /// Cortex-M is Thumb-only, so function addresses in ELF must have bit 0 set.
    pub fn with_entry(mut self, entry: u32) -> Self {
        self.entry = if self.machine == ElfMachine::Arm {
            entry | 1 // Set Thumb bit for ARM targets
        } else {
            entry
        };
        self
    }

    /// Set ELF e_flags (e.g. to add hard-float ABI)
    pub fn set_flags(&mut self, flags: u32) {
        self.e_flags = flags;
    }

    /// Set file type
    pub fn with_type(mut self, elf_type: ElfType) -> Self {
        self.elf_type = elf_type;
        self
    }

    /// Add a section
    pub fn add_section(&mut self, section: Section) {
        self.sections.push(section);
    }

    /// Add a symbol
    pub fn add_symbol(&mut self, symbol: Symbol) {
        self.symbols.push(symbol);
    }

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

    /// Add a relocation entry for the .text section
    pub fn add_relocation(&mut self, reloc: Relocation) {
        self.relocations.push(reloc);
    }

    /// Add an undefined external symbol (e.g., __meld_dispatch_import)
    /// Returns the symbol index (1-based, accounting for null symbol)
    pub fn add_undefined_symbol(&mut self, name: &str) -> u32 {
        let index = self.symbols.len() as u32 + 1; // +1 for null symbol
        self.symbols.push(Symbol {
            name: name.to_string(),
            value: 0,
            size: 0,
            binding: SymbolBinding::Global,
            symbol_type: SymbolType::Func,
            section: 0, // SHN_UNDEF
        });
        index
    }

    /// Build the ELF file to bytes
    pub fn build(&self) -> Result<Vec<u8>> {
        let mut output = Vec::new();

        // ELF header size (52 bytes for ELF32)
        let header_size = 52;
        // Program header size (32 bytes for ELF32)
        let ph_entry_size = 32;
        let ph_count = self.program_headers.len();
        let ph_table_size = ph_entry_size * ph_count;

        // Reserve space for ELF header + program headers
        output.resize(header_size + ph_table_size, 0);

        // Build string table for section names
        let (shstrtab_data, section_name_offsets) = self.build_section_string_table();

        // Build symbol string table
        let (strtab_data, symbol_name_offsets) = self.build_symbol_string_table();

        // Calculate section offsets (after ELF header + program headers)
        let mut current_offset = header_size + ph_table_size;

        // Section 1: .shstrtab (section name string table)
        let shstrtab_offset = current_offset;
        current_offset += shstrtab_data.len();

        // Section 2: .strtab (symbol name string table)
        let strtab_offset = current_offset;
        current_offset += strtab_data.len();

        // User sections
        let mut section_offsets = Vec::new();
        for section in &self.sections {
            section_offsets.push(current_offset);
            current_offset += section.data.len();
        }

        // Section 3: .symtab (symbol table)
        let symtab_offset = current_offset;
        let symtab_data = self.build_symbol_table(&symbol_name_offsets);
        current_offset += symtab_data.len();

        // Section 4+ (optional): .rel.text (relocations)
        let rel_data = self.build_relocation_table();
        let rel_offset = current_offset;
        current_offset += rel_data.len();

        // Section header table comes at the end
        let sh_offset = current_offset;

        // Now write all the data
        output.extend_from_slice(&shstrtab_data);
        output.extend_from_slice(&strtab_data);

        for section in &self.sections {
            output.extend_from_slice(&section.data);
        }

        output.extend_from_slice(&symtab_data);
        output.extend_from_slice(&rel_data);

        // Write section headers
        let section_headers = self.build_section_headers_with_rel(
            &section_name_offsets,
            shstrtab_offset,
            &shstrtab_data,
            strtab_offset,
            &strtab_data,
            symtab_offset,
            &symtab_data,
            &section_offsets,
            rel_offset,
            &rel_data,
        );
        output.extend_from_slice(&section_headers);

        // Write program headers (right after ELF header)
        // Auto-correct p_offset for LOAD segments by matching vaddr to section addrs
        for (i, ph) in self.program_headers.iter().enumerate() {
            let ph_offset = header_size + i * ph_entry_size;
            let mut corrected_ph = ph.clone();
            if corrected_ph.filesz > 0 {
                // Find the section whose addr matches this segment's vaddr
                for (si, section) in self.sections.iter().enumerate() {
                    if section.addr == corrected_ph.vaddr && si < section_offsets.len() {
                        corrected_ph.offset = section_offsets[si] as u32;
                        break;
                    }
                }
            }
            self.write_program_header(
                &mut output[ph_offset..ph_offset + ph_entry_size],
                &corrected_ph,
            );
        }

        // Now write the actual ELF header at the beginning
        let has_rel = !self.relocations.is_empty();
        let num_sections = 4 + self.sections.len() + if has_rel { 1 } else { 0 };
        let ph_offset = if ph_count > 0 { header_size as u32 } else { 0 };
        self.write_elf_header_with_phdrs(
            &mut output[0..header_size],
            ph_offset,
            ph_count as u16,
            sh_offset as u32,
            num_sections as u16,
        )?;

        Ok(output)
    }

    /// Write a single program header
    fn write_program_header(&self, output: &mut [u8], ph: &ProgramHeader) {
        let mut cursor = 0;

        // p_type (4 bytes)
        output[cursor..cursor + 4].copy_from_slice(&(ph.p_type as u32).to_le_bytes());
        cursor += 4;

        // p_offset (4 bytes)
        output[cursor..cursor + 4].copy_from_slice(&ph.offset.to_le_bytes());
        cursor += 4;

        // p_vaddr (4 bytes)
        output[cursor..cursor + 4].copy_from_slice(&ph.vaddr.to_le_bytes());
        cursor += 4;

        // p_paddr (4 bytes)
        output[cursor..cursor + 4].copy_from_slice(&ph.paddr.to_le_bytes());
        cursor += 4;

        // p_filesz (4 bytes)
        output[cursor..cursor + 4].copy_from_slice(&ph.filesz.to_le_bytes());
        cursor += 4;

        // p_memsz (4 bytes)
        output[cursor..cursor + 4].copy_from_slice(&ph.memsz.to_le_bytes());
        cursor += 4;

        // p_flags (4 bytes)
        output[cursor..cursor + 4].copy_from_slice(&ph.flags.to_le_bytes());
        cursor += 4;

        // p_align (4 bytes)
        output[cursor..cursor + 4].copy_from_slice(&ph.align.to_le_bytes());
    }

    /// Write ELF header with program header info
    fn write_elf_header_with_phdrs(
        &self,
        output: &mut [u8],
        ph_offset: u32,
        ph_count: u16,
        sh_offset: u32,
        sh_count: u16,
    ) -> Result<()> {
        let mut cursor = 0;

        // ELF magic number
        output[cursor..cursor + 4].copy_from_slice(&[0x7f, b'E', b'L', b'F']);
        cursor += 4;

        // Class (32-bit)
        output[cursor] = self.class as u8;
        cursor += 1;

        // Data (little-endian)
        output[cursor] = self.data as u8;
        cursor += 1;

        // Version
        output[cursor] = 1;
        cursor += 1;

        // OS/ABI
        output[cursor] = 0; // System V
        cursor += 1;

        // ABI version
        output[cursor] = 0;
        cursor += 1;

        // Padding (7 bytes)
        output[cursor..cursor + 7].copy_from_slice(&[0; 7]);
        cursor += 7;

        // Type (little-endian u16)
        let etype = self.elf_type as u16;
        output[cursor..cursor + 2].copy_from_slice(&etype.to_le_bytes());
        cursor += 2;

        // Machine (little-endian u16)
        let machine = self.machine as u16;
        output[cursor..cursor + 2].copy_from_slice(&machine.to_le_bytes());
        cursor += 2;

        // Version (little-endian u32)
        output[cursor..cursor + 4].copy_from_slice(&1u32.to_le_bytes());
        cursor += 4;

        // Entry point (little-endian u32)
        output[cursor..cursor + 4].copy_from_slice(&self.entry.to_le_bytes());
        cursor += 4;

        // Program header offset (little-endian u32)
        output[cursor..cursor + 4].copy_from_slice(&ph_offset.to_le_bytes());
        cursor += 4;

        // Section header offset (little-endian u32)
        output[cursor..cursor + 4].copy_from_slice(&sh_offset.to_le_bytes());
        cursor += 4;

        // Flags (little-endian u32) - ARM EABI version 5 + float ABI
        output[cursor..cursor + 4].copy_from_slice(&self.e_flags.to_le_bytes());
        cursor += 4;

        // ELF header size (little-endian u16)
        output[cursor..cursor + 2].copy_from_slice(&52u16.to_le_bytes());
        cursor += 2;

        // Program header entry size (little-endian u16)
        let ph_entry_size: u16 = if ph_count > 0 { 32 } else { 0 };
        output[cursor..cursor + 2].copy_from_slice(&ph_entry_size.to_le_bytes());
        cursor += 2;

        // Program header count (little-endian u16)
        output[cursor..cursor + 2].copy_from_slice(&ph_count.to_le_bytes());
        cursor += 2;

        // Section header entry size (little-endian u16)
        output[cursor..cursor + 2].copy_from_slice(&40u16.to_le_bytes());
        cursor += 2;

        // Section header count (little-endian u16)
        output[cursor..cursor + 2].copy_from_slice(&sh_count.to_le_bytes());
        cursor += 2;

        // Section header string table index (little-endian u16) - .shstrtab is section 1
        output[cursor..cursor + 2].copy_from_slice(&1u16.to_le_bytes());

        Ok(())
    }

    /// Build section name string table
    fn build_section_string_table(&self) -> (Vec<u8>, Vec<usize>) {
        let mut strtab = vec![0]; // null string at offset 0
        let mut offsets = Vec::new();

        // Standard sections
        strtab.extend_from_slice(b".shstrtab\0");
        strtab.extend_from_slice(b".strtab\0");
        strtab.extend_from_slice(b".symtab\0");

        // User sections
        for section in &self.sections {
            let offset = strtab.len();
            offsets.push(offset);
            strtab.extend_from_slice(section.name.as_bytes());
            strtab.push(0);
        }

        // .rel.text (if relocations exist)
        if !self.relocations.is_empty() {
            strtab.extend_from_slice(b".rel.text\0");
        }

        (strtab, offsets)
    }

    /// Build symbol name string table
    fn build_symbol_string_table(&self) -> (Vec<u8>, Vec<usize>) {
        let mut strtab = vec![0]; // null string at offset 0
        let mut offsets = Vec::new();

        for symbol in &self.symbols {
            let offset = strtab.len();
            offsets.push(offset);
            strtab.extend_from_slice(symbol.name.as_bytes());
            strtab.push(0);
        }

        (strtab, offsets)
    }

    /// Build relocation table (ELF32 REL entries: 8 bytes each)
    fn build_relocation_table(&self) -> Vec<u8> {
        if self.relocations.is_empty() {
            return Vec::new();
        }

        let mut rel_data = Vec::new();
        for reloc in &self.relocations {
            // r_offset (4 bytes)
            rel_data.extend_from_slice(&reloc.offset.to_le_bytes());
            // r_info (4 bytes) = (sym_index << 8) | type
            let r_info = (reloc.symbol_index << 8) | (reloc.reloc_type as u32);
            rel_data.extend_from_slice(&r_info.to_le_bytes());
        }
        rel_data
    }

    /// Build symbol table
    fn build_symbol_table(&self, name_offsets: &[usize]) -> Vec<u8> {
        let mut symtab = Vec::new();

        // First entry is always null symbol
        symtab.extend_from_slice(&[0u8; 16]); // 16 bytes per symbol in ELF32

        // User symbols
        for (i, symbol) in self.symbols.iter().enumerate() {
            let name_offset = if i < name_offsets.len() {
                name_offsets[i] as u32
            } else {
                0
            };

            // st_name (4 bytes)
            symtab.extend_from_slice(&name_offset.to_le_bytes());

            // st_value (4 bytes)
            // For ARM targets, STT_FUNC symbols must have bit 0 set (Thumb interworking)
            let value = if self.machine == ElfMachine::Arm && symbol.symbol_type == SymbolType::Func
            {
                symbol.value | 1
            } else {
                symbol.value
            };
            symtab.extend_from_slice(&value.to_le_bytes());

            // st_size (4 bytes)
            symtab.extend_from_slice(&symbol.size.to_le_bytes());

            // st_info (1 byte) = (binding << 4) | (type & 0xf)
            let info = ((symbol.binding as u8) << 4) | (symbol.symbol_type as u8 & 0xf);
            symtab.push(info);

            // st_other (1 byte)
            symtab.push(0);

            // st_shndx (2 bytes)
            symtab.extend_from_slice(&symbol.section.to_le_bytes());
        }

        symtab
    }

    /// Build section headers (with optional .rel.text)
    #[allow(clippy::too_many_arguments)]
    fn build_section_headers_with_rel(
        &self,
        section_name_offsets: &[usize],
        shstrtab_offset: usize,
        shstrtab_data: &[u8],
        strtab_offset: usize,
        strtab_data: &[u8],
        symtab_offset: usize,
        symtab_data: &[u8],
        section_offsets: &[usize],
        rel_offset: usize,
        rel_data: &[u8],
    ) -> Vec<u8> {
        let mut headers = Vec::new();

        // Section header size is 40 bytes for ELF32

        // Section 0: null section
        headers.extend_from_slice(&[0u8; 40]);

        // Section 1: .shstrtab
        self.write_section_header(
            &mut headers,
            1,
            SectionType::StrTab as u32,
            0,
            0,
            shstrtab_offset as u32,
            shstrtab_data.len() as u32,
            0,
            0,
            1,
            0,
        );

        // Section 2: .strtab
        let strtab_name_offset = ".shstrtab\0".len();
        self.write_section_header(
            &mut headers,
            strtab_name_offset as u32,
            SectionType::StrTab as u32,
            0,
            0,
            strtab_offset as u32,
            strtab_data.len() as u32,
            0,
            0,
            1,
            0,
        );

        // Section 3: .symtab (links to .strtab which is section 2)
        let symtab_name_offset = ".shstrtab\0.strtab\0".len();
        self.write_section_header(
            &mut headers,
            symtab_name_offset as u32,
            SectionType::SymTab as u32,
            0,
            0,
            symtab_offset as u32,
            symtab_data.len() as u32,
            2,
            1,
            4,
            16,
        );

        // User sections
        for (i, section) in self.sections.iter().enumerate() {
            let name_offset = if i < section_name_offsets.len() {
                section_name_offsets[i] as u32
            } else {
                0
            };
            let offset = if i < section_offsets.len() {
                section_offsets[i] as u32
            } else {
                0
            };

            self.write_section_header(
                &mut headers,
                name_offset,
                section.section_type as u32,
                section.flags,
                section.addr,
                offset,
                section.size(),
                0,
                0,
                section.align,
                0,
            );
        }

        // .rel.text section (if relocations exist)
        if !rel_data.is_empty() {
            let rel_name_offset = self.rel_text_shstrtab_offset();
            // sh_link = symtab section index (3), sh_info = .text section index (4, first user section)
            let text_section_idx = 4u32; // null(0) + shstrtab(1) + strtab(2) + symtab(3) + .text(4)
            self.write_section_header(
                &mut headers,
                rel_name_offset as u32,
                SectionType::Rel as u32,
                0,
                0,
                rel_offset as u32,
                rel_data.len() as u32,
                3,                // sh_link = .symtab section index
                text_section_idx, // sh_info = section to which relocations apply
                4,
                8, // Each REL entry is 8 bytes
            );
        }

        headers
    }

    /// Compute the shstrtab offset where .rel.text name begins
    fn rel_text_shstrtab_offset(&self) -> usize {
        // Layout: \0 .shstrtab\0 .strtab\0 .symtab\0 [user sections...] .rel.text\0
        let mut offset = 1 + ".shstrtab\0".len() + ".strtab\0".len() + ".symtab\0".len();
        for section in &self.sections {
            offset += section.name.len() + 1;
        }
        offset
    }

    /// Write a single section header
    #[allow(clippy::too_many_arguments)]
    fn write_section_header(
        &self,
        output: &mut Vec<u8>,
        name: u32,
        sh_type: u32,
        flags: u32,
        addr: u32,
        offset: u32,
        size: u32,
        link: u32,
        info: u32,
        align: u32,
        entsize: u32,
    ) {
        output.extend_from_slice(&name.to_le_bytes());
        output.extend_from_slice(&sh_type.to_le_bytes());
        output.extend_from_slice(&flags.to_le_bytes());
        output.extend_from_slice(&addr.to_le_bytes());
        output.extend_from_slice(&offset.to_le_bytes());
        output.extend_from_slice(&size.to_le_bytes());
        output.extend_from_slice(&link.to_le_bytes());
        output.extend_from_slice(&info.to_le_bytes());
        output.extend_from_slice(&align.to_le_bytes());
        output.extend_from_slice(&entsize.to_le_bytes());
    }

    /// Write ELF header (legacy method for tests)
    #[allow(dead_code)]
    fn write_elf_header(&self, output: &mut Vec<u8>) -> Result<()> {
        // ELF magic number
        output.extend_from_slice(&[0x7f, b'E', b'L', b'F']);

        // Class (32-bit)
        output.push(self.class as u8);

        // Data (little-endian)
        output.push(self.data as u8);

        // Version
        output.push(1);

        // OS/ABI
        output.push(0); // System V

        // ABI version
        output.push(0);

        // Padding
        output.extend_from_slice(&[0; 7]);

        // Type (little-endian u16)
        let etype = self.elf_type as u16;
        output.extend_from_slice(&etype.to_le_bytes());

        // Machine (little-endian u16)
        let machine = self.machine as u16;
        output.extend_from_slice(&machine.to_le_bytes());

        // Version (little-endian u32)
        output.extend_from_slice(&1u32.to_le_bytes());

        // Entry point (little-endian u32)
        output.extend_from_slice(&self.entry.to_le_bytes());

        // Program header offset (little-endian u32)
        output.extend_from_slice(&0u32.to_le_bytes());

        // Section header offset (little-endian u32)
        output.extend_from_slice(&0u32.to_le_bytes());

        // Flags (little-endian u32)
        output.extend_from_slice(&0u32.to_le_bytes());

        // ELF header size (little-endian u16)
        output.extend_from_slice(&52u16.to_le_bytes());

        // Program header entry size (little-endian u16)
        output.extend_from_slice(&0u16.to_le_bytes());

        // Program header count (little-endian u16)
        output.extend_from_slice(&0u16.to_le_bytes());

        // Section header entry size (little-endian u16)
        output.extend_from_slice(&40u16.to_le_bytes());

        // Section header count (little-endian u16)
        output.extend_from_slice(&0u16.to_le_bytes());

        // Section header string table index (little-endian u16)
        output.extend_from_slice(&0u16.to_le_bytes());

        Ok(())
    }
}

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

    #[test]
    fn test_elf_builder_creation() {
        let builder = ElfBuilder::new_arm32();
        assert_eq!(builder.class, ElfClass::Elf32);
        assert_eq!(builder.data, ElfData::LittleEndian);
        assert_eq!(builder.machine, ElfMachine::Arm);
    }

    #[test]
    fn test_section_creation() {
        let section = Section::new(".text", SectionType::ProgBits)
            .with_flags(SectionFlags::ALLOC | SectionFlags::EXEC)
            .with_addr(0x8000)
            .with_align(4);

        assert_eq!(section.name, ".text");
        assert_eq!(section.section_type, SectionType::ProgBits);
        assert_eq!(section.addr, 0x8000);
        assert_eq!(section.align, 4);
    }

    #[test]
    fn test_symbol_creation() {
        let symbol = Symbol::new("main")
            .with_value(0x8000)
            .with_size(128)
            .with_binding(SymbolBinding::Global)
            .with_type(SymbolType::Func)
            .with_section(1);

        assert_eq!(symbol.name, "main");
        assert_eq!(symbol.value, 0x8000);
        assert_eq!(symbol.size, 128);
        assert_eq!(symbol.binding, SymbolBinding::Global);
        assert_eq!(symbol.symbol_type, SymbolType::Func);
    }

    #[test]
    fn test_elf_header_generation() {
        let builder = ElfBuilder::new_arm32().with_entry(0x8000);
        let elf = builder.build().unwrap();

        // Check magic number
        assert_eq!(&elf[0..4], &[0x7f, b'E', b'L', b'F']);

        // Check class (32-bit)
        assert_eq!(elf[4], 1);

        // Check data (little-endian)
        assert_eq!(elf[5], 1);

        // Check version
        assert_eq!(elf[6], 1);
    }

    #[test]
    fn test_add_sections() {
        let mut builder = ElfBuilder::new_arm32();

        let text = Section::new(".text", SectionType::ProgBits)
            .with_flags(SectionFlags::ALLOC | SectionFlags::EXEC);

        let data = Section::new(".data", SectionType::ProgBits)
            .with_flags(SectionFlags::ALLOC | SectionFlags::WRITE);

        builder.add_section(text);
        builder.add_section(data);

        assert_eq!(builder.sections.len(), 2);
    }

    #[test]
    fn test_add_symbols() {
        let mut builder = ElfBuilder::new_arm32();

        let main_sym = Symbol::new("main")
            .with_binding(SymbolBinding::Global)
            .with_type(SymbolType::Func);

        let data_sym = Symbol::new("data")
            .with_binding(SymbolBinding::Local)
            .with_type(SymbolType::Object);

        builder.add_symbol(main_sym);
        builder.add_symbol(data_sym);

        assert_eq!(builder.symbols.len(), 2);
    }

    #[test]
    fn test_complete_elf_generation() {
        // Create a complete ELF file with sections and symbols
        let mut builder = ElfBuilder::new_arm32()
            .with_entry(0x8000)
            .with_type(ElfType::Exec);

        // Add .text section with some ARM code
        let text_code = vec![
            0x00, 0x48, 0x2d, 0xe9, // push {fp, lr}
            0x04, 0xb0, 0x8d, 0xe2, // add fp, sp, #4
            0x00, 0x00, 0xa0, 0xe3, // mov r0, #0
            0x00, 0x88, 0xbd, 0xe8, // pop {fp, pc}
        ];
        let text = Section::new(".text", SectionType::ProgBits)
            .with_flags(SectionFlags::ALLOC | SectionFlags::EXEC)
            .with_addr(0x8000)
            .with_align(4)
            .with_data(text_code);

        builder.add_section(text);

        // Add .data section
        let data_content = vec![0x01, 0x02, 0x03, 0x04];
        let data = Section::new(".data", SectionType::ProgBits)
            .with_flags(SectionFlags::ALLOC | SectionFlags::WRITE)
            .with_addr(0x8100)
            .with_align(4)
            .with_data(data_content);

        builder.add_section(data);

        // Add .bss section (no data)
        let bss = Section::new(".bss", SectionType::NoBits)
            .with_flags(SectionFlags::ALLOC | SectionFlags::WRITE)
            .with_addr(0x8200)
            .with_align(4);

        builder.add_section(bss);

        // Add symbols
        let main_sym = Symbol::new("main")
            .with_value(0x8000)
            .with_size(16)
            .with_binding(SymbolBinding::Global)
            .with_type(SymbolType::Func)
            .with_section(4); // .text is section 4 (0=null, 1=shstrtab, 2=strtab, 3=symtab, 4=.text)

        builder.add_symbol(main_sym);

        let data_var = Symbol::new("global_var")
            .with_value(0x8100)
            .with_size(4)
            .with_binding(SymbolBinding::Global)
            .with_type(SymbolType::Object)
            .with_section(5); // .data is section 5

        builder.add_symbol(data_var);

        // Build the ELF file
        let elf = builder.build().unwrap();

        // Validate ELF header
        assert_eq!(&elf[0..4], &[0x7f, b'E', b'L', b'F']);
        assert_eq!(elf[4], 1); // 32-bit
        assert_eq!(elf[5], 1); // little-endian
        assert_eq!(elf[6], 1); // version

        // Check that we have a reasonable file size
        assert!(elf.len() > 52); // At least header size
        assert!(elf.len() < 10000); // Reasonable upper bound

        // Validate entry point is set correctly (Thumb bit set for ARM)
        let entry_bytes = &elf[24..28];
        let entry = u32::from_le_bytes([
            entry_bytes[0],
            entry_bytes[1],
            entry_bytes[2],
            entry_bytes[3],
        ]);
        assert_eq!(entry, 0x8001); // 0x8000 | 1 (Thumb bit)

        // Validate section header offset is non-zero
        let sh_off_bytes = &elf[32..36];
        let sh_off = u32::from_le_bytes([
            sh_off_bytes[0],
            sh_off_bytes[1],
            sh_off_bytes[2],
            sh_off_bytes[3],
        ]);
        assert!(sh_off > 0);

        // Validate section count (null + shstrtab + strtab + symtab + .text + .data + .bss = 7)
        let sh_num_bytes = &elf[48..50];
        let sh_num = u16::from_le_bytes([sh_num_bytes[0], sh_num_bytes[1]]);
        assert_eq!(sh_num, 7);

        // Validate string table index points to .shstrtab (section 1)
        let shstrndx_bytes = &elf[50..52];
        let shstrndx = u16::from_le_bytes([shstrndx_bytes[0], shstrndx_bytes[1]]);
        assert_eq!(shstrndx, 1);
    }

    #[test]
    fn test_string_table_generation() {
        let mut builder = ElfBuilder::new_arm32();

        builder.add_section(Section::new(".text", SectionType::ProgBits));
        builder.add_section(Section::new(".data", SectionType::ProgBits));

        let (strtab, offsets) = builder.build_section_string_table();

        // Should have null byte at start
        assert_eq!(strtab[0], 0);

        // Should contain .shstrtab, .strtab, .symtab, .text, .data
        let strtab_str = String::from_utf8_lossy(&strtab);
        assert!(strtab_str.contains(".shstrtab"));
        assert!(strtab_str.contains(".strtab"));
        assert!(strtab_str.contains(".symtab"));
        assert!(strtab_str.contains(".text"));
        assert!(strtab_str.contains(".data"));

        // Should have offsets for user sections
        assert_eq!(offsets.len(), 2);
    }

    #[test]
    fn test_relocation_support() {
        let mut builder = ElfBuilder::new_arm32()
            .with_entry(0x8000)
            .with_type(ElfType::Rel);

        // Add .text section with a BL placeholder
        let text_code = vec![0x00u8; 16]; // 4 instructions of placeholder
        let text = Section::new(".text", SectionType::ProgBits)
            .with_flags(SectionFlags::ALLOC | SectionFlags::EXEC)
            .with_addr(0x8000)
            .with_align(4)
            .with_data(text_code);
        builder.add_section(text);

        // Add undefined external symbol
        let sym_idx = builder.add_undefined_symbol("__meld_dispatch_import");
        assert!(sym_idx > 0);

        // Add relocation for the BL at offset 4
        builder.add_relocation(Relocation {
            offset: 4,
            symbol_index: sym_idx,
            reloc_type: ArmRelocationType::Call,
        });

        let elf = builder.build().unwrap();

        // Verify ELF is valid
        assert_eq!(&elf[0..4], &[0x7f, b'E', b'L', b'F']);

        // Section count should include .rel.text
        // null(1) + shstrtab(1) + strtab(1) + symtab(1) + .text(1) + .rel.text(1) = 6
        let sh_num = u16::from_le_bytes([elf[48], elf[49]]);
        assert_eq!(sh_num, 6);

        // Verify the symbol table contains the undefined symbol
        // (section = 0 for SHN_UNDEF)
        let has_undef = elf
            .windows(b"__meld_dispatch_import".len())
            .any(|w| w == b"__meld_dispatch_import");
        assert!(
            has_undef,
            "ELF should contain __meld_dispatch_import symbol name"
        );
    }

    #[test]
    fn test_symbol_table_encoding() {
        let mut builder = ElfBuilder::new_arm32();

        let sym = Symbol::new("test_func")
            .with_value(0x1000)
            .with_size(64)
            .with_binding(SymbolBinding::Global)
            .with_type(SymbolType::Func)
            .with_section(1);

        builder.add_symbol(sym);

        let (_strtab, offsets) = builder.build_symbol_string_table();
        let symtab = builder.build_symbol_table(&offsets);

        // Should have null symbol (16 bytes) + 1 symbol (16 bytes) = 32 bytes
        assert_eq!(symtab.len(), 32);

        // First symbol should be all zeros
        assert!(symtab[0..16].iter().all(|&b| b == 0));

        // Second symbol should have correct encoding
        // Check st_value (bytes 4-7 of second entry)
        // For ARM STT_FUNC symbols, bit 0 is set for Thumb interworking
        let value_bytes = &symtab[20..24];
        let value = u32::from_le_bytes([
            value_bytes[0],
            value_bytes[1],
            value_bytes[2],
            value_bytes[3],
        ]);
        assert_eq!(value, 0x1001); // 0x1000 | 1 (Thumb bit)

        // Check st_size (bytes 8-11 of second entry)
        let size_bytes = &symtab[24..28];
        let size = u32::from_le_bytes([size_bytes[0], size_bytes[1], size_bytes[2], size_bytes[3]]);
        assert_eq!(size, 64);

        // Check st_info (byte 12 of second entry)
        let info = symtab[28];
        let binding = info >> 4;
        let sym_type = info & 0xf;
        assert_eq!(binding, SymbolBinding::Global as u8);
        assert_eq!(sym_type, SymbolType::Func as u8);
    }
}