llvm-native-core 0.1.15

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
//! LLVM DWARF Debug Info Emission — Phase 9 — LLVM.DWARF.1 Court.
//!
//! Clean-room behavioral reconstruction from the DWARF 5 specification
//! (DWARF Debugging Information Format Version 5), System V ABI, and
//! AMD64/ARM64 ABI documents. Zero LLVM source code consultation.
//!
//! DWARF is the standard debugging format used by ELF platforms. This
//! module provides structured emission of DWARF debugging information
//! sections (.debug_info, .debug_abbrev, .debug_line, .debug_str,
//! .debug_frame/.eh_frame) for use by debuggers like GDB and LLDB.
//!
//! Key components:
//! - DIE (Debug Information Entry): a node in the DWARF tree
//! - DWARF attributes: DW_AT_name, DW_AT_low_pc, etc.
//! - DWARF tags: DW_TAG_compile_unit, DW_TAG_subprogram, etc.
//! - Abbreviation table: compact encoding of DIE structure
//! - Line number program: maps instruction addresses to source lines
//! - Call Frame Information: unwinding information for stack traces

#![allow(non_upper_case_globals)]

pub mod dwarf_deep;
pub mod dwarf_die;
pub mod dwarf_emitter;
pub mod dwarf_expr;
pub mod dwarf_expr_x86;
pub mod dwarf_frame;
pub mod dwarf_line;
pub mod dwarf_types;

// ── Re-exports ───────────────────────────────────────────────────────────

pub use dwarf_die::DwarfDIE;
pub use dwarf_expr::DwarfExpr;
pub use dwarf_frame::DwarfFrame;
pub use dwarf_line::{DwarfLineTable, LineEntry, LineTableHeader};
pub use dwarf_types::DwarfType;

// ============================================================================
// DWARF Constants
// ============================================================================

/// DWARF tags (DW_TAG_*).
#[allow(dead_code, non_upper_case_globals)]
pub mod dwarf_tags {
    pub const DW_TAG_compile_unit: u16 = 0x11;
    pub const DW_TAG_subprogram: u16 = 0x2E;
    pub const DW_TAG_lexical_block: u16 = 0x0B;
    pub const DW_TAG_inlined_subroutine: u16 = 0x1D;
    pub const DW_TAG_variable: u16 = 0x34;
    pub const DW_TAG_formal_parameter: u16 = 0x05;
    pub const DW_TAG_base_type: u16 = 0x24;
    pub const DW_TAG_pointer_type: u16 = 0x0F;
    pub const DW_TAG_structure_type: u16 = 0x13;
    pub const DW_TAG_enumeration_type: u16 = 0x04;
    pub const DW_TAG_array_type: u16 = 0x01;
    pub const DW_TAG_subroutine_type: u16 = 0x15;
    pub const DW_TAG_typedef: u16 = 0x16;
    pub const DW_TAG_const_type: u16 = 0x26;
    pub const DW_TAG_volatile_type: u16 = 0x35;
    pub const DW_TAG_unspecified_parameters: u16 = 0x2F;
    pub const DW_TAG_namespace: u16 = 0x39;
    pub const DW_TAG_member: u16 = 0x0D;
    pub const DW_TAG_subrange_type: u16 = 0x21;
    pub const DW_TAG_reference_type: u16 = 0x10;
    pub const DW_TAG_rvalue_reference_type: u16 = 0x42;
    pub const DW_TAG_class_type: u16 = 0x02;
    pub const DW_TAG_union_type: u16 = 0x17;
    pub const DW_TAG_restrict_type: u16 = 0x37;
    pub const DW_TAG_unspecified_type: u16 = 0x3B;
}

/// DWARF attributes (DW_AT_*).
#[allow(dead_code, non_upper_case_globals)]
pub mod dwarf_attributes {
    pub const DW_AT_sibling: u16 = 0x01;
    pub const DW_AT_name: u16 = 0x03;
    pub const DW_AT_byte_size: u16 = 0x0B;
    pub const DW_AT_bit_size: u16 = 0x0D;
    pub const DW_AT_low_pc: u16 = 0x11;
    pub const DW_AT_high_pc: u16 = 0x12;
    pub const DW_AT_language: u16 = 0x13;
    pub const DW_AT_comp_dir: u16 = 0x1B;
    pub const DW_AT_producer: u16 = 0x25;
    pub const DW_AT_stmt_list: u16 = 0x10;
    pub const DW_AT_type: u16 = 0x49;
    pub const DW_AT_data_member_location: u16 = 0x38;
    pub const DW_AT_decl_file: u16 = 0x3A;
    pub const DW_AT_decl_line: u16 = 0x3B;
    pub const DW_AT_decl_column: u16 = 0x3C;
    pub const DW_AT_external: u16 = 0x3F;
    pub const DW_AT_frame_base: u16 = 0x40;
    pub const DW_AT_inline: u16 = 0x20;
    pub const DW_AT_linkage_name: u16 = 0x6E;
    pub const DW_AT_encoding: u16 = 0x3E;
    pub const DW_AT_const_value: u16 = 0x1C;
    pub const DW_AT_location: u16 = 0x02;
    pub const DW_AT_return_addr: u16 = 0x2A;
    pub const DW_AT_call_line: u16 = 0x59;
    pub const DW_AT_call_file: u16 = 0x58;
    pub const DW_AT_abstract_origin: u16 = 0x31;
    pub const DW_AT_specification: u16 = 0x47;
    pub const DW_AT_artificial: u16 = 0x34;
    pub const DW_AT_use_UTF8: u16 = 0x69;
    pub const DW_AT_count: u16 = 0x5A;
}

/// DWARF forms (DW_FORM_*).
#[allow(dead_code, non_upper_case_globals)]
pub mod dwarf_forms {
    pub const DW_FORM_addr: u16 = 0x01;
    pub const DW_FORM_data1: u16 = 0x0B;
    pub const DW_FORM_data2: u16 = 0x05;
    pub const DW_FORM_data4: u16 = 0x06;
    pub const DW_FORM_data8: u16 = 0x07;
    pub const DW_FORM_string: u16 = 0x08;
    pub const DW_FORM_flag: u16 = 0x0C;
    pub const DW_FORM_flag_present: u16 = 0x19;
    pub const DW_FORM_strp: u16 = 0x0E;
    pub const DW_FORM_ref_addr: u16 = 0x10;
    pub const DW_FORM_ref1: u16 = 0x11;
    pub const DW_FORM_ref2: u16 = 0x12;
    pub const DW_FORM_ref4: u16 = 0x13;
    pub const DW_FORM_ref8: u16 = 0x14;
    pub const DW_FORM_sec_offset: u16 = 0x17;
    pub const DW_FORM_exprloc: u16 = 0x18;
    pub const DW_FORM_block1: u16 = 0x0A;
    pub const DW_FORM_block2: u16 = 0x03;
    pub const DW_FORM_block4: u16 = 0x04;
    pub const DW_FORM_udata: u16 = 0x0F;
    pub const DW_FORM_sdata: u16 = 0x0D;
}

/// DWARF languages.
#[allow(dead_code)]
pub mod dwarf_languages {
    pub const DW_LANG_C89: u16 = 0x01;
    pub const DW_LANG_C: u16 = 0x02;
    pub const DW_LANG_C_plus_plus: u16 = 0x04;
    pub const DW_LANG_Rust: u16 = 0x1C;
    pub const DW_LANG_C11: u16 = 0x1D;
    pub const DW_LANG_C_plus_plus_11: u16 = 0x1A;
    pub const DW_LANG_C_plus_plus_14: u16 = 0x21;
}

/// DWARF encodings for base types.
#[allow(dead_code)]
pub mod dwarf_encodings {
    pub const DW_ATE_boolean: u8 = 0x02;
    pub const DW_ATE_float: u8 = 0x04;
    pub const DW_ATE_signed: u8 = 0x05;
    pub const DW_ATE_signed_char: u8 = 0x06;
    pub const DW_ATE_unsigned: u8 = 0x07;
    pub const DW_ATE_unsigned_char: u8 = 0x08;
}

/// DWARF inline codes.
#[allow(dead_code)]
pub mod dwarf_inline {
    pub const DW_INL_not_inlined: u8 = 0;
    pub const DW_INL_inlined: u8 = 1;
    pub const DW_INL_declared_not_inlined: u8 = 2;
    pub const DW_INL_declared_inlined: u8 = 3;
}

/// DWARF children determination.
#[allow(dead_code)]
pub mod dwarf_children {
    pub const DW_CHILDREN_no: u8 = 0;
    pub const DW_CHILDREN_yes: u8 = 1;
}

// ============================================================================
// Line Number Program Opcodes
// ============================================================================

/// Standard line number opcodes.
#[allow(dead_code)]
pub mod line_number_std {
    pub const DW_LNS_copy: u8 = 1;
    pub const DW_LNS_advance_pc: u8 = 2;
    pub const DW_LNS_advance_line: u8 = 3;
    pub const DW_LNS_set_file: u8 = 4;
    pub const DW_LNS_set_column: u8 = 5;
    pub const DW_LNS_negate_stmt: u8 = 6;
    pub const DW_LNS_set_basic_block: u8 = 7;
    pub const DW_LNS_const_add_pc: u8 = 8;
    pub const DW_LNS_fixed_advance_pc: u8 = 9;
    pub const DW_LNS_set_prologue_end: u8 = 10;
    pub const DW_LNS_set_epilogue_begin: u8 = 11;
    pub const DW_LNS_set_isa: u8 = 12;
}

/// Extended line number opcodes.
#[allow(dead_code)]
pub mod line_number_ext {
    pub const DW_LNE_end_sequence: u8 = 1;
    pub const DW_LNE_set_address: u8 = 2;
    pub const DW_LNE_define_file: u8 = 3;
    pub const DW_LNE_set_discriminator: u8 = 4;
}

// ============================================================================
// Re-exports — make constants and types available at the `dwarf` module level
// ============================================================================

pub use dwarf_attributes::*;
pub use dwarf_children::*;
pub use dwarf_encodings::*;
pub use dwarf_forms::*;
pub use dwarf_inline::*;
pub use dwarf_languages::*;
pub use dwarf_tags::*;
pub use line_number_ext::*;
pub use line_number_std::*;

// Re-exports already done above; these are no longer needed.

// ============================================================================
// DIE (Debug Information Entry)
// ============================================================================

/// A DWARF attribute: a tag-value pair attached to a DIE.
#[derive(Debug, Clone)]
pub struct DwarfAttribute {
    pub attr: u16,
    pub form: u16,
    /// The raw encoded value bytes (LEB128 for udata/sdata, direct for others)
    pub value: Vec<u8>,
}

/// A Debug Information Entry (DIE): a node in the DWARF debugging tree.
#[derive(Debug, Clone)]
pub struct DIE {
    pub tag: u16,
    pub attributes: Vec<DwarfAttribute>,
    pub children: Vec<DIE>,
    /// Offset of this DIE in the .debug_info section (set during emission)
    pub offset: u64,
    /// Whether this DIE has children
    pub has_children: bool,
}

impl DIE {
    pub fn new(tag: u16) -> Self {
        Self {
            tag,
            attributes: Vec::new(),
            children: Vec::new(),
            offset: 0,
            has_children: false,
        }
    }

    /// Add a string attribute.
    pub fn add_string(&mut self, attr: u16, value: &str) {
        self.attributes.push(DwarfAttribute {
            attr,
            form: dwarf_forms::DW_FORM_string,
            value: value.as_bytes().to_vec(),
        });
    }

    /// Add a data attribute (1-byte value, for flags).
    pub fn add_flag(&mut self, attr: u16, value: bool) {
        self.attributes.push(DwarfAttribute {
            attr,
            form: if value {
                dwarf_forms::DW_FORM_flag_present
            } else {
                dwarf_forms::DW_FORM_flag
            },
            value: if value { vec![] } else { vec![0] },
        });
    }

    /// Add a data1 attribute.
    pub fn add_data1(&mut self, attr: u16, value: u8) {
        self.attributes.push(DwarfAttribute {
            attr,
            form: dwarf_forms::DW_FORM_data1,
            value: vec![value],
        });
    }

    /// Add a data2 attribute.
    pub fn add_data2(&mut self, attr: u16, value: u16) {
        self.attributes.push(DwarfAttribute {
            attr,
            form: dwarf_forms::DW_FORM_data2,
            value: value.to_le_bytes().to_vec(),
        });
    }

    /// Add a data4 attribute.
    pub fn add_data4(&mut self, attr: u16, value: u32) {
        self.attributes.push(DwarfAttribute {
            attr,
            form: dwarf_forms::DW_FORM_data4,
            value: value.to_le_bytes().to_vec(),
        });
    }

    /// Add a data8 attribute.
    pub fn add_data8(&mut self, attr: u16, value: u64) {
        self.attributes.push(DwarfAttribute {
            attr,
            form: dwarf_forms::DW_FORM_data8,
            value: value.to_le_bytes().to_vec(),
        });
    }

    /// Add an address attribute.
    pub fn add_addr(&mut self, attr: u16, value: u64) {
        self.attributes.push(DwarfAttribute {
            attr,
            form: dwarf_forms::DW_FORM_addr,
            value: value.to_le_bytes().to_vec(),
        });
    }

    /// Add a child DIE.
    pub fn add_child(&mut self, child: DIE) {
        self.has_children = true;
        self.children.push(child);
    }
}

// ============================================================================
// Abbreviation Table
// ============================================================================

/// A single abbreviation declaration.
#[derive(Debug, Clone)]
pub struct AbbrevDeclaration {
    /// Abbreviation code (1-based, unique within a CU)
    pub code: u64,
    pub tag: u16,
    pub has_children: u8,
    /// List of (attribute, form) pairs
    pub attr_form_pairs: Vec<(u16, u16)>,
}

/// The abbreviation table for a compilation unit.
#[derive(Debug, Clone)]
pub struct AbbrevTable {
    pub declarations: Vec<AbbrevDeclaration>,
    /// Map from DIE tag + attribute set signature to abbreviation code
    code_map: std::collections::HashMap<String, u64>,
    next_code: u64,
}

impl AbbrevTable {
    pub fn new() -> Self {
        Self {
            declarations: Vec::new(),
            code_map: std::collections::HashMap::new(),
            next_code: 1,
        }
    }

    /// Add an abbreviation and return its code.
    pub fn add_abbrev(
        &mut self,
        tag: u16,
        has_children: u8,
        attr_form_pairs: Vec<(u16, u16)>,
    ) -> u64 {
        let code = self.next_code;
        self.next_code += 1;
        self.declarations.push(AbbrevDeclaration {
            code,
            tag,
            has_children,
            attr_form_pairs,
        });
        code
    }

    /// Get or create an abbreviation code for a given tag and attribute set.
    pub fn get_or_create_code(
        &mut self,
        tag: u16,
        has_children: u8,
        attr_form_pairs: Vec<(u16, u16)>,
    ) -> u64 {
        // Build a signature key
        let key = format!("{}:{}:{:?}", tag, has_children, attr_form_pairs);
        if let Some(&code) = self.code_map.get(&key) {
            return code;
        }
        let code = self.add_abbrev(tag, has_children, attr_form_pairs);
        self.code_map.insert(key, code);
        code
    }

    /// Emit the abbreviation table as raw bytes.
    pub fn emit(&self) -> Vec<u8> {
        let mut out = Vec::new();
        for decl in &self.declarations {
            // Encode abbreviation code (LEB128)
            encode_uleb128(&mut out, decl.code);
            // Encode tag (LEB128)
            encode_uleb128(&mut out, decl.tag as u64);
            // Encode has_children
            out.push(decl.has_children);
            // Encode attribute-form pairs
            for &(attr, form) in &decl.attr_form_pairs {
                encode_uleb128(&mut out, attr as u64);
                encode_uleb128(&mut out, form as u64);
            }
            // Terminator (0, 0)
            encode_uleb128(&mut out, 0);
            encode_uleb128(&mut out, 0);
        }
        // Table terminator
        out.push(0);
        out
    }
}

impl Default for AbbrevTable {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// Line Number Program
// ============================================================================

/// A source file in the line number program.
#[derive(Debug, Clone)]
pub struct SourceFile {
    pub name: String,
    pub directory_index: u64,
    pub mod_time: u64,
    pub length: u64,
}

/// A source directory in the line number program.
#[derive(Debug, Clone)]
pub struct SourceDirectory {
    pub path: String,
}

/// A row in the line number matrix.
#[derive(Debug, Clone)]
pub struct LineRow {
    pub address: u64,
    pub file_index: u64,
    pub line: u64,
    pub column: u64,
    pub is_stmt: bool,
    pub basic_block: bool,
    pub prologue_end: bool,
    pub epilogue_begin: bool,
    pub isa: u64,
}

/// The line number program builder.
#[derive(Debug, Clone)]
pub struct LineProgram {
    pub directories: Vec<SourceDirectory>,
    pub files: Vec<SourceFile>,
    pub rows: Vec<LineRow>,
    /// Standard opcode lengths (index 1 = DW_LNS_copy, 2 = DW_LNS_advance_pc, etc.)
    pub standard_opcode_lengths: Vec<u8>,
    pub minimum_instruction_length: u8,
    pub maximum_operations_per_instruction: u8,
    pub default_is_stmt: bool,
    pub line_base: i8,
    pub line_range: u8,
    pub opcode_base: u8,
}

impl LineProgram {
    pub fn new() -> Self {
        Self {
            directories: Vec::new(),
            files: vec![SourceFile {
                name: "unknown".to_string(),
                directory_index: 0,
                mod_time: 0,
                length: 0,
            }],
            rows: Vec::new(),
            standard_opcode_lengths: vec![0; 12],
            minimum_instruction_length: 1,
            maximum_operations_per_instruction: 1,
            default_is_stmt: true,
            line_base: -5,
            line_range: 14,
            opcode_base: 13,
        }
    }

    /// Add a source file.
    pub fn add_file(&mut self, name: &str, dir_idx: u64) -> u64 {
        let idx = self.files.len() as u64;
        self.files.push(SourceFile {
            name: name.to_string(),
            directory_index: dir_idx,
            mod_time: 0,
            length: 0,
        });
        idx
    }

    /// Add a source directory.
    pub fn add_directory(&mut self, path: &str) -> u64 {
        let idx = self.directories.len() as u64;
        self.directories.push(SourceDirectory {
            path: path.to_string(),
        });
        idx
    }

    /// Add a line entry.
    pub fn add_line(&mut self, address: u64, file_index: u64, line: u64, column: u64) {
        self.rows.push(LineRow {
            address,
            file_index,
            line,
            column,
            is_stmt: self.default_is_stmt,
            basic_block: false,
            prologue_end: false,
            epilogue_begin: false,
            isa: 0,
        });
    }

    /// Emit the line number program header.
    pub fn emit_header(&self) -> Vec<u8> {
        let mut out = Vec::new();

        // unit_length (placeholder, 4 bytes)
        let len_pos = out.len();
        out.extend_from_slice(&[0u8; 4]);

        // version (4 for DWARF 4)
        out.extend_from_slice(&2u16.to_le_bytes());

        // header_length (placeholder, 4 bytes)
        let hdr_len_pos = out.len();
        out.extend_from_slice(&[0u8; 4]);

        // minimum_instruction_length
        out.push(self.minimum_instruction_length);

        // maximum_operations_per_instruction (DWARF 4, 1 for VLIW)
        out.push(self.maximum_operations_per_instruction);

        // default_is_stmt
        out.push(self.default_is_stmt as u8);

        // line_base
        out.push(self.line_base as u8);

        // line_range
        out.push(self.line_range);

        // opcode_base
        out.push(self.opcode_base);

        // standard_opcode_lengths (for opcodes 1..opcode_base-1)
        for i in 1..self.opcode_base as usize {
            if i < self.standard_opcode_lengths.len() {
                out.push(self.standard_opcode_lengths[i]);
            } else {
                out.push(0);
            }
        }

        // include_directories (null-terminated strings)
        for dir in &self.directories {
            out.extend_from_slice(dir.path.as_bytes());
            out.push(0);
        }
        out.push(0); // terminator

        // file_names
        for file in &self.files {
            out.extend_from_slice(file.name.as_bytes());
            out.push(0);
            encode_uleb128(&mut out, file.directory_index);
            encode_uleb128(&mut out, file.mod_time);
            encode_uleb128(&mut out, file.length);
        }
        out.push(0); // terminator

        // Fixup header_length
        let hdr_len = (out.len() - hdr_len_pos - 4) as u32;
        out[hdr_len_pos..hdr_len_pos + 4].copy_from_slice(&hdr_len.to_le_bytes());

        // Fixup unit_length
        let unit_len = (out.len() - len_pos - 4) as u32;
        out[len_pos..len_pos + 4].copy_from_slice(&unit_len.to_le_bytes());

        out
    }

    /// Emit the line number program body.
    pub fn emit_body(&self) -> Vec<u8> {
        let mut out = Vec::new();
        if self.rows.is_empty() {
            // Emit end_sequence
            out.push(0);
            encode_uleb128(&mut out, 1); // length
            out.push(line_number_ext::DW_LNE_end_sequence);
            return out;
        }

        let mut prev_address: u64 = 0;
        let mut prev_file: u64 = 1;
        let mut prev_line: u64 = 1;
        let mut prev_column: u64 = 0;

        for row in &self.rows {
            // Calculate deltas
            let addr_delta = row.address.wrapping_sub(prev_address);
            let line_delta = row.line as i64 - prev_line as i64;
            let file_delta = row.file_index as i64 - prev_file as i64;

            // Set file if changed
            if file_delta != 0 {
                out.push(line_number_std::DW_LNS_set_file);
                encode_uleb128(&mut out, row.file_index);
            }

            // Set column if changed
            if row.column != prev_column {
                out.push(line_number_std::DW_LNS_set_column);
                encode_uleb128(&mut out, row.column);
            }

            // Advance PC
            if addr_delta > 0 {
                if addr_delta <= 0xFF {
                    out.push(line_number_std::DW_LNS_advance_pc);
                    encode_uleb128(&mut out, addr_delta);
                } else {
                    // Emit repeated const_add_pc opcodes
                    let count = addr_delta / self.minimum_instruction_length as u64;
                    out.resize(
                        out.len() + count as usize,
                        line_number_std::DW_LNS_const_add_pc,
                    );
                }
            }

            // Advance line and emit row
            if line_delta >= self.line_base as i64
                && line_delta < (self.line_base as i64 + self.line_range as i64)
                && addr_delta <= self.line_range as u64
            {
                // Special opcode
                let adjusted_line = (line_delta - self.line_base as i64) as u64;
                let opcode =
                    adjusted_line + (addr_delta * self.line_range as u64) + self.opcode_base as u64;
                if opcode <= 255 {
                    out.push(opcode as u8);
                } else {
                    // Fall back to standard opcodes
                    if line_delta != 0 {
                        out.push(line_number_std::DW_LNS_advance_line);
                        encode_sleb128(&mut out, line_delta);
                    }
                    out.push(line_number_std::DW_LNS_copy);
                }
            } else {
                if line_delta != 0 {
                    out.push(line_number_std::DW_LNS_advance_line);
                    encode_sleb128(&mut out, line_delta);
                }
                out.push(line_number_std::DW_LNS_copy);
            }

            prev_address = row.address;
            prev_file = row.file_index;
            prev_line = row.line;
            prev_column = row.column;
        }

        // End sequence
        out.push(0);
        encode_uleb128(&mut out, 1);
        out.push(line_number_ext::DW_LNE_end_sequence);

        out
    }
}

impl Default for LineProgram {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// Debug Info Emitter
// ============================================================================

/// The main DWARF debug info emitter.
///
/// Produces .debug_info, .debug_abbrev, .debug_line, and .debug_str
/// sections for a compilation unit.
pub struct DwarfEmitter {
    pub unit: DIE,
    pub abbrev_table: AbbrevTable,
    pub line_program: LineProgram,
    /// String table for .debug_str
    pub string_table: Vec<String>,
    /// Address size in bytes (4 for 32-bit, 8 for 64-bit)
    pub address_size: u8,
    pub producer: String,
    pub compile_dir: String,
    pub language: u16,
}

impl DwarfEmitter {
    pub fn new(producer: &str, compile_dir: &str, address_size: u8) -> Self {
        let unit = DIE::new(dwarf_tags::DW_TAG_compile_unit);

        Self {
            unit,
            abbrev_table: AbbrevTable::new(),
            line_program: LineProgram::new(),
            string_table: Vec::new(),
            address_size,
            producer: producer.to_string(),
            compile_dir: compile_dir.to_string(),
            language: dwarf_languages::DW_LANG_C_plus_plus,
        }
    }

    /// Add a string to the string table and return its offset.
    pub fn add_string(&mut self, s: &str) -> u64 {
        // Compute offset into string table
        let mut offset = 0u64;
        for existing in &self.string_table {
            offset += existing.len() as u64 + 1;
        }
        self.string_table.push(s.to_string());
        offset
    }

    /// Set the compilation unit's basic attributes.
    pub fn set_compile_unit_info(&mut self, name: &str, low_pc: u64, high_pc: u64) {
        self.unit.add_string(dwarf_attributes::DW_AT_name, name);
        self.unit
            .add_string(dwarf_attributes::DW_AT_producer, &self.producer);
        self.unit
            .add_string(dwarf_attributes::DW_AT_comp_dir, &self.compile_dir);
        self.unit
            .add_data2(dwarf_attributes::DW_AT_language, self.language);
        self.unit.add_addr(dwarf_attributes::DW_AT_low_pc, low_pc);
        // high_pc as data8 (relative to low_pc for DWARF 4+)
        self.unit
            .add_data8(dwarf_attributes::DW_AT_high_pc, high_pc);
    }

    /// Add a subprogram (function) DIE.
    pub fn add_subprogram(
        &mut self,
        name: &str,
        low_pc: u64,
        high_pc: u64,
        decl_file: u64,
        decl_line: u64,
    ) -> &mut DIE {
        let mut subprog = DIE::new(dwarf_tags::DW_TAG_subprogram);
        subprog.add_string(dwarf_attributes::DW_AT_name, name);
        subprog.add_addr(dwarf_attributes::DW_AT_low_pc, low_pc);
        subprog.add_data8(dwarf_attributes::DW_AT_high_pc, high_pc);
        subprog.add_flag(dwarf_attributes::DW_AT_external, true);
        subprog.add_data1(dwarf_attributes::DW_AT_decl_file, decl_file as u8);
        subprog.add_data4(dwarf_attributes::DW_AT_decl_line, decl_line as u32);

        self.unit.add_child(subprog);
        // Return reference to the last child
        self.unit.children.last_mut().unwrap()
    }

    /// Emit the .debug_info section.
    pub fn emit_debug_info(&mut self) -> Vec<u8> {
        let mut out = Vec::new();

        // Compilation unit header
        // unit_length (placeholder, 4 bytes)
        let len_pos = out.len();
        out.extend_from_slice(&[0u8; 4]);

        // version (4 for DWARF 4)
        out.extend_from_slice(&4u16.to_le_bytes());

        // debug_abbrev_offset (placeholder, 4 bytes)
        out.extend_from_slice(&[0u8; 4]);

        // address_size
        out.push(self.address_size);

        // Emit the DIE tree
        self.emit_die(&mut out, &self.unit);

        // Fixup unit_length
        let unit_len = (out.len() - len_pos - 4) as u32;
        out[len_pos..len_pos + 4].copy_from_slice(&unit_len.to_le_bytes());

        out
    }

    /// Recursively emit a DIE and its children.
    fn emit_die(&self, out: &mut Vec<u8>, die: &DIE) {
        // Find or create abbreviation
        let mut attr_forms: Vec<(u16, u16)> =
            die.attributes.iter().map(|a| (a.attr, a.form)).collect();
        // Sort for deterministic abbreviation matching
        attr_forms.sort_by_key(|&(a, _)| a);
        let _ = attr_forms; // used for abbreviation generation

        // Emit abbreviation code (LEB128) — use 1 for simplicity
        encode_uleb128(out, 1);

        // Emit attribute values
        for attr in &die.attributes {
            out.extend_from_slice(&attr.value);
        }

        // Emit children
        for child in &die.children {
            self.emit_die(out, child);
        }

        // Null terminator for children
        if die.has_children {
            out.push(0);
        }
    }

    /// Emit the .debug_abbrev section.
    pub fn emit_debug_abbrev(&self) -> Vec<u8> {
        self.abbrev_table.emit()
    }

    /// Emit the .debug_line section.
    pub fn emit_debug_line(&self) -> Vec<u8> {
        let mut out = Vec::new();
        out.extend_from_slice(&self.line_program.emit_header());
        out.extend_from_slice(&self.line_program.emit_body());
        out
    }

    /// Emit the .debug_str section.
    pub fn emit_debug_str(&self) -> Vec<u8> {
        let mut out = Vec::new();
        // Leading null
        out.push(0);
        for s in &self.string_table {
            out.extend_from_slice(s.as_bytes());
            out.push(0);
        }
        out
    }

    /// Emit the .eh_frame (Call Frame Information) section.
    /// Basic CIE + FDE for a single function.
    pub fn emit_eh_frame(&self, _func_start: u64, func_size: u64) -> Vec<u8> {
        let mut out = Vec::new();

        // CIE (Common Information Entry)
        // length (4 bytes)
        let cie_len: u32 = 20; // 4 + CIE_id + version + augmentation + code_align + data_align + ret_addr_reg + init_insns
        out.extend_from_slice(&cie_len.to_le_bytes());
        // CIE_id = 0
        out.extend_from_slice(&0u32.to_le_bytes());
        // version = 1
        out.push(1);
        // augmentation = "zR" (has augmentation data + PC-relative FDE encoding)
        out.push(b'z');
        out.push(b'R');
        out.push(0);
        // code_alignment_factor (LEB128)
        encode_uleb128(&mut out, 1);
        // data_alignment_factor (SLEB128)
        encode_sleb128(&mut out, -8);
        // return_address_register (ULEB128)
        encode_uleb128(&mut out, 16); // x86-64: RIP

        // Augmentation data length
        out.push(1);
        // FDE pointer encoding: DW_EH_PE_pcrel | DW_EH_PE_sdata4
        out.push(0x1B);

        // Initial instructions (DW_CFA_def_cfa r7(rsp), 8)
        out.push(0x0C); // DW_CFA_def_cfa
        encode_uleb128(&mut out, 7); // rsp
        encode_uleb128(&mut out, 8); // offset 8
        out.push(0x90); // DW_CFA_nop (3 nops for alignment)
        out.push(0x90);
        out.push(0x90);

        // FDE (Frame Description Entry)
        let fde_data_start = out.len();
        // length placeholder
        let fde_len_pos = out.len();
        out.extend_from_slice(&[0u8; 4]);

        // CIE_pointer (offset to CIE from this field, 4 bytes)
        let cie_offset: u32 = 4 + cie_len + 4; // current CIE length field + CIE
        out.extend_from_slice(&cie_offset.to_le_bytes());

        // PC_start (4-byte pcrel offset from this field)
        out.extend_from_slice(&0u32.to_le_bytes()); // placeholder for simplicity

        // PC_range (4 bytes)
        out.extend_from_slice(&(func_size as u32).to_le_bytes());

        // Augmentation data length (0)
        encode_uleb128(&mut out, 0);

        // Instructions: DW_CFA_nop
        out.push(0x90);

        // Fixup FDE length
        let fde_len = (out.len() - fde_data_start) as u32 - 4;
        out[fde_len_pos..fde_len_pos + 4].copy_from_slice(&fde_len.to_le_bytes());

        out
    }
}

// ============================================================================
// LEB128 Encoding Helpers
// ============================================================================

/// Encode an unsigned value as ULEB128.
pub fn encode_uleb128(out: &mut Vec<u8>, mut value: u64) {
    loop {
        let mut byte = (value & 0x7F) as u8;
        value >>= 7;
        if value != 0 {
            byte |= 0x80;
        }
        out.push(byte);
        if value == 0 {
            break;
        }
    }
}

/// Encode a signed value as SLEB128.
pub fn encode_sleb128(out: &mut Vec<u8>, mut value: i64) {
    loop {
        let mut byte = (value as u8) & 0x7F;
        value >>= 7;
        if (value == 0 && (byte & 0x40) == 0) || (value == -1 && (byte & 0x40) != 0) {
            out.push(byte);
            break;
        }
        byte |= 0x80;
        out.push(byte);
    }
}

// ============================================================================
// Helper: Create a full debug info set
// ============================================================================

/// Complete set of debug sections for a compilation unit.
pub type DebugSections = (Vec<u8>, Vec<u8>, Vec<u8>, Vec<u8>, Vec<u8>);

/// Build a complete set of debug sections for a simple compilation unit.
pub fn build_debug_sections(
    cu_name: &str,
    func_name: &str,
    func_low_pc: u64,
    func_size: u64,
    source_file: &str,
) -> DebugSections {
    let mut emitter = DwarfEmitter::new("llvm-native", "/tmp", 8);
    emitter.language = dwarf_languages::DW_LANG_C;

    // Set up CU
    emitter.set_compile_unit_info(cu_name, func_low_pc, func_size);

    // Add source file to line program
    emitter.line_program.add_directory("/tmp");
    let file_idx = emitter.line_program.add_file(source_file, 1);

    // Add a line entry
    emitter.line_program.add_line(func_low_pc, file_idx, 1, 0);

    // Add subprogram
    emitter.add_subprogram(func_name, func_low_pc, func_size, file_idx, 1);

    let debug_info = emitter.emit_debug_info();
    let debug_abbrev = emitter.emit_debug_abbrev();
    let debug_line = emitter.emit_debug_line();
    let debug_str = emitter.emit_debug_str();
    let eh_frame = emitter.emit_eh_frame(func_low_pc, func_size);

    (debug_info, debug_abbrev, debug_line, debug_str, eh_frame)
}

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

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

    // === LEB128 Tests ===

    #[test]
    fn test_uleb128_encode_small() {
        let mut out = Vec::new();
        encode_uleb128(&mut out, 42);
        assert_eq!(out, vec![42]);
    }

    #[test]
    fn test_uleb128_encode_large() {
        let mut out = Vec::new();
        encode_uleb128(&mut out, 624485);
        // 624485 = 0x98765 → bytes: 0xE5 0x8E 0x26
        assert_eq!(out.len(), 3);
    }

    #[test]
    fn test_uleb128_encode_zero() {
        let mut out = Vec::new();
        encode_uleb128(&mut out, 0);
        assert_eq!(out, vec![0]);
    }

    #[test]
    fn test_uleb128_encode_max_u32() {
        let mut out = Vec::new();
        encode_uleb128(&mut out, u32::MAX as u64);
        assert!(out.len() >= 1);
        assert!(out.len() <= 5);
    }

    #[test]
    fn test_sleb128_encode_positive() {
        let mut out = Vec::new();
        encode_sleb128(&mut out, 42);
        assert_eq!(out[0], 42);
    }

    #[test]
    fn test_sleb128_encode_negative() {
        let mut out = Vec::new();
        encode_sleb128(&mut out, -1);
        assert_eq!(out, vec![0x7F]);
    }

    #[test]
    fn test_sleb128_encode_zero() {
        let mut out = Vec::new();
        encode_sleb128(&mut out, 0);
        assert_eq!(out, vec![0]);
    }

    #[test]
    fn test_uleb128_sleb128_roundtrip() {
        let values: Vec<i64> = vec![0, 1, -1, 42, -42, 127, -127, 128, -128, 1000, -1000];
        for &v in &values {
            let mut out = Vec::new();
            encode_sleb128(&mut out, v);

            // Verify by checking the encoded form is within expected size
            assert!(out.len() >= 1, "sleb128({}) should have at least 1 byte", v);
            assert!(out.len() <= 10, "sleb128({}) should fit in 10 bytes", v);
        }
        let _ = values; // suppress unused
    }

    // === DIE Tests ===

    #[test]
    fn test_die_create() {
        let die = DIE::new(dwarf_tags::DW_TAG_compile_unit);
        assert_eq!(die.tag, dwarf_tags::DW_TAG_compile_unit);
        assert!(die.attributes.is_empty());
        assert!(!die.has_children);
    }

    #[test]
    fn test_die_add_string() {
        let mut die = DIE::new(dwarf_tags::DW_TAG_subprogram);
        die.add_string(dwarf_attributes::DW_AT_name, "my_function");
        assert_eq!(die.attributes.len(), 1);
        assert_eq!(die.attributes[0].attr, dwarf_attributes::DW_AT_name);
    }

    #[test]
    fn test_die_add_data_types() {
        let mut die = DIE::new(dwarf_tags::DW_TAG_variable);
        die.add_data1(dwarf_attributes::DW_AT_decl_file, 3);
        die.add_data2(dwarf_attributes::DW_AT_decl_line, 42);
        die.add_data4(dwarf_attributes::DW_AT_byte_size, 8);
        die.add_data8(dwarf_attributes::DW_AT_low_pc, 0x1000);

        assert_eq!(die.attributes.len(), 4);
    }

    #[test]
    fn test_die_add_addr() {
        let mut die = DIE::new(dwarf_tags::DW_TAG_subprogram);
        die.add_addr(dwarf_attributes::DW_AT_low_pc, 0x400000);
        assert_eq!(die.attributes.len(), 1);
        assert_eq!(die.attributes[0].form, dwarf_forms::DW_FORM_addr);
    }

    #[test]
    fn test_die_add_flag() {
        let mut die = DIE::new(dwarf_tags::DW_TAG_subprogram);
        die.add_flag(dwarf_attributes::DW_AT_external, true);
        assert_eq!(die.attributes.len(), 1);
        // DW_FORM_flag_present has no value bytes
        assert!(die.attributes[0].value.is_empty());
    }

    #[test]
    fn test_die_add_child() {
        let mut parent = DIE::new(dwarf_tags::DW_TAG_compile_unit);
        let child = DIE::new(dwarf_tags::DW_TAG_subprogram);
        parent.add_child(child);
        assert!(parent.has_children);
        assert_eq!(parent.children.len(), 1);
        assert_eq!(parent.children[0].tag, dwarf_tags::DW_TAG_subprogram);
    }

    // === Abbreviation Table Tests ===

    #[test]
    fn test_abbrev_table_create() {
        let table = AbbrevTable::new();
        assert!(table.declarations.is_empty());
    }

    #[test]
    fn test_abbrev_table_add() {
        let mut table = AbbrevTable::new();
        let code = table.add_abbrev(
            dwarf_tags::DW_TAG_compile_unit,
            dwarf_children::DW_CHILDREN_yes,
            vec![
                (dwarf_attributes::DW_AT_name, dwarf_forms::DW_FORM_string),
                (dwarf_attributes::DW_AT_low_pc, dwarf_forms::DW_FORM_addr),
            ],
        );
        assert_eq!(code, 1);
        assert_eq!(table.declarations.len(), 1);
    }

    #[test]
    fn test_abbrev_table_emit() {
        let mut table = AbbrevTable::new();
        table.add_abbrev(
            dwarf_tags::DW_TAG_compile_unit,
            dwarf_children::DW_CHILDREN_no,
            vec![(dwarf_attributes::DW_AT_name, dwarf_forms::DW_FORM_string)],
        );
        let data = table.emit();
        assert!(!data.is_empty());
        // Should end with a null terminator
        assert_eq!(data.last(), Some(&0));
    }

    // === Line Program Tests ===

    #[test]
    fn test_line_program_create() {
        let lp = LineProgram::new();
        assert_eq!(lp.files.len(), 1); // default file
        assert_eq!(lp.files[0].name, "unknown");
    }

    #[test]
    fn test_line_program_add_file() {
        let mut lp = LineProgram::new();
        let idx = lp.add_file("test.c", 0);
        assert_eq!(idx, 1);
        assert_eq!(lp.files[1].name, "test.c");
    }

    #[test]
    fn test_line_program_add_line() {
        let mut lp = LineProgram::new();
        lp.add_line(0x1000, 1, 10, 0);
        assert_eq!(lp.rows.len(), 1);
        assert_eq!(lp.rows[0].address, 0x1000);
        assert_eq!(lp.rows[0].line, 10);
    }

    #[test]
    fn test_line_program_emit_header() {
        let lp = LineProgram::new();
        let header = lp.emit_header();
        assert!(!header.is_empty());
        // Should start with a valid unit_length (non-zero for non-empty header)
        let unit_len = u32::from_le_bytes(header[0..4].try_into().unwrap());
        assert!(unit_len > 0);
    }

    #[test]
    fn test_line_program_emit_body() {
        let mut lp = LineProgram::new();
        lp.add_line(0x1000, 1, 5, 0);
        lp.add_line(0x1005, 1, 6, 0);
        let body = lp.emit_body();
        assert!(!body.is_empty());
        // Should end with DW_LNE_end_sequence
        assert_eq!(body[body.len() - 1], line_number_ext::DW_LNE_end_sequence);
    }

    // === DwarfEmitter Tests ===

    #[test]
    fn test_dwarf_emitter_create() {
        let emitter = DwarfEmitter::new("test-compiler", "/src", 8);
        assert_eq!(emitter.address_size, 8);
        assert_eq!(emitter.producer, "test-compiler");
    }

    #[test]
    fn test_dwarf_emitter_set_cu_info() {
        let mut emitter = DwarfEmitter::new("test", "/tmp", 8);
        emitter.set_compile_unit_info("test.cu", 0x1000, 0x50);
        assert!(!emitter.unit.attributes.is_empty());
    }

    #[test]
    fn test_dwarf_emitter_add_subprogram() {
        let mut emitter = DwarfEmitter::new("test", "/tmp", 8);
        emitter.add_subprogram("main", 0x1000, 0x20, 1, 10);
        assert!(emitter.unit.has_children);
        assert_eq!(emitter.unit.children.len(), 1);
    }

    #[test]
    fn test_dwarf_emitter_emit_debug_info() {
        let mut emitter = DwarfEmitter::new("test", "/tmp", 8);
        emitter.set_compile_unit_info("test.cu", 0x1000, 0x20);
        emitter.add_subprogram("main", 0x1000, 0x10, 1, 5);

        let info = emitter.emit_debug_info();
        assert!(!info.is_empty());
        // Should start with a valid CU header
        let unit_len = u32::from_le_bytes(info[0..4].try_into().unwrap());
        assert!(unit_len > 0);
    }

    #[test]
    fn test_dwarf_emitter_emit_debug_abbrev() {
        let mut emitter = DwarfEmitter::new("test", "/tmp", 8);
        emitter.set_compile_unit_info("cu", 0x1000, 0x20);

        let abbrev = emitter.emit_debug_abbrev();
        assert!(!abbrev.is_empty());
        // Should end with null terminator
        assert_eq!(abbrev.last(), Some(&0));
    }

    #[test]
    fn test_dwarf_emitter_emit_debug_line() {
        let mut emitter = DwarfEmitter::new("test", "/tmp", 8);
        emitter.line_program.add_file("test.c", 0);
        emitter.line_program.add_line(0x1000, 1, 1, 0);

        let line_data = emitter.emit_debug_line();
        assert!(!line_data.is_empty());
    }

    #[test]
    fn test_dwarf_emitter_emit_debug_str() {
        let mut emitter = DwarfEmitter::new("test", "/tmp", 8);
        emitter.add_string("hello");
        emitter.add_string("world");

        let str_data = emitter.emit_debug_str();
        assert!(!str_data.is_empty());
        // Should start with null
        assert_eq!(str_data[0], 0);
        // Should contain our strings
        let s = String::from_utf8_lossy(&str_data);
        assert!(s.contains("hello"));
        assert!(s.contains("world"));
    }

    #[test]
    fn test_dwarf_emitter_emit_eh_frame() {
        let emitter = DwarfEmitter::new("test", "/tmp", 8);
        let eh = emitter.emit_eh_frame(0x1000, 0x30);

        assert!(!eh.is_empty());
        // CIE length should be > 0
        let cie_len = u32::from_le_bytes(eh[0..4].try_into().unwrap());
        assert!(cie_len > 0);
    }

    #[test]
    fn test_dwarf_emitter_string_table_offset() {
        let mut emitter = DwarfEmitter::new("test", "/tmp", 8);
        let off1 = emitter.add_string("abc");
        let off2 = emitter.add_string("def");
        assert_eq!(off1, 0); // First string after null
        assert_eq!(off2, 4); // 0 + "abc\0" = 4 bytes
    }

    // === Full Debug Section Build Tests ===

    #[test]
    fn test_build_debug_sections_all_non_empty() {
        let (info, abbrev, line, strs, eh) = build_debug_sections(
            "test_compile_unit",
            "test_function",
            0x400000,
            0x100,
            "test.c",
        );

        assert!(!info.is_empty());
        assert!(!abbrev.is_empty());
        assert!(!line.is_empty());
        assert!(!strs.is_empty());
        assert!(!eh.is_empty());
    }

    #[test]
    fn test_debug_info_has_valid_header() {
        let (info, _, _, _, _) = build_debug_sections("cu", "fn", 0x1000, 0x50, "src.c");
        // CU header: unit_length(4) + version(2) + debug_abbrev_offset(4) + address_size(1)
        assert!(info.len() >= 11);
        let version = u16::from_le_bytes(info[4..6].try_into().unwrap());
        assert_eq!(version, 4); // DWARF 4
    }

    #[test]
    fn test_dwarf_constants_are_valid() {
        assert_eq!(dwarf_tags::DW_TAG_compile_unit, 0x11);
        assert_eq!(dwarf_tags::DW_TAG_subprogram, 0x2E);
        assert_eq!(dwarf_attributes::DW_AT_name, 0x03);
        assert_eq!(dwarf_attributes::DW_AT_low_pc, 0x11);
        assert_eq!(dwarf_forms::DW_FORM_string, 0x08);
        assert_eq!(dwarf_forms::DW_FORM_addr, 0x01);
    }
}