univdreams 0.4.0

Byte-identical binary <-> source round-tripping: binary formats, multi-arch decode/encode, a .ud decompiler/compiler, and an x86 emulator with Win16/Win32/Linux hosts.
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
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
//! Decompile a parsed ELF into a `.ud` AST.
//!
//! The output of [`decompile`] is a [`crate::ast::UdFile`] in canonical
//! shape:
//!
//! * A `@module { … }` header pinned from the ELF header.
//! * A top-level `@section("name", 0x…) { … }` block per ELF section
//!   that has on-disk content (everything except NULL, NOBITS, and
//!   debug-info sections without a virtual address). Section bodies
//!   contain `fn` declarations for discovered functions and `@raw`
//!   blocks for everything between/around them — alignment padding,
//!   data section content, etc.
//! * `// note: …` comments at the top level for functions we know
//!   exist but couldn't locate bytes for (no recorded size, missing
//!   from any executable section).
//!
//! The byte-identity invariant the decompiler defends:
//!
//! > For every section emitted, concatenating the bytes of its items
//! > in source order reproduces the section's on-disk content exactly.
//!
//! This is the precondition for full source-level binary round-trip
//! once `phdr` / `shdr` metadata makes it into `@module` (next
//! iteration).
//!
//! [`decompile_to_text`] is the thin wrapper that calls
//! [`crate::ast::emit`] on the AST.

#![allow(clippy::cast_possible_truncation)]

mod aarch64;
mod args;
mod bpf;
mod bpf_args_ssa;
mod bpf_ssa;
mod build_function;
mod build_module;
mod data_lookup;
mod expr;
mod idioms;
pub mod macho;
pub mod ne;
mod patterns;
pub mod pe;
pub mod raw6502;
mod ssa;
mod stack_slots;
pub mod wasm;
mod wasm_disasm;

pub use data_lookup::DataLookup;
pub use macho::{decompile_macho, decompile_macho_to_text};
pub use ne::{decompile_ne, decompile_ne_to_text};
pub use pe::{decompile_pe, decompile_pe_to_text};
pub use raw6502::{decompile_raw_6502, decompile_raw_6502_to_text};
pub use wasm::{decompile_wasm, decompile_wasm_to_text};

use std::collections::HashMap;

use crate::analysis::{FunctionMap, discover_functions};
use crate::arch::x86::{Bitness, decode, lift_function};
use crate::ast::{Item, UdFile};
use crate::debug::DebugFunction;
use crate::format::elf::{
    EM_386, EM_AARCH64, EM_BPF, EM_SBF, EM_X86_64, Elf64File, ElfClass, SHF_EXECINSTR, Shdr64,
};

/// Which arch backend to drive for a given ELF.
#[derive(Debug, Clone, Copy)]
enum Arch {
    X86 {
        bitness: Bitness,
    },
    Aarch64,
    Bpf {
        variant: crate::arch::bpf::BpfVariant,
    },
}

/// Errors surfaced by the top-level entry point.
#[derive(Debug, thiserror::Error)]
pub enum Error {
    #[error("only x86 ELF inputs are supported; got e_machine = {0}")]
    UnsupportedMachine(u16),

    #[error(transparent)]
    Analysis(#[from] crate::analysis::Error),

    #[error(transparent)]
    Decode(#[from] crate::arch::x86::Error),

    #[error(transparent)]
    Lift(#[from] crate::arch::x86::LiftError),

    #[error(transparent)]
    Debug(#[from] crate::debug::DebugError),

    #[error(transparent)]
    Aarch64Decode(crate::arch::aarch64::Error),

    #[error(transparent)]
    BpfDecode(crate::arch::bpf::Error),

    #[error(transparent)]
    BpfReloc(crate::analysis::bpf_relocs::BpfRelocError),
}

pub type Result<T, E = Error> = std::result::Result<T, E>;

/// Build the AST for `elf`. The structural form is the primary output
/// of decompilation; [`decompile_to_text`] is a thin convenience.
pub fn decompile(elf: &Elf64File) -> Result<UdFile> {
    let arch = match (elf.class, elf.ehdr.e_machine) {
        (ElfClass::Elf64, EM_X86_64) => Arch::X86 {
            bitness: Bitness::Bits64,
        },
        (ElfClass::Elf32, EM_386) => Arch::X86 {
            bitness: Bitness::Bits32,
        },
        (ElfClass::Elf64, EM_AARCH64) => Arch::Aarch64,
        // Linux eBPF — `e_machine = 247`. Always ELF64-LE
        // regardless of host endianness; SBF support below
        // covers the Solana-specific machine number.
        (ElfClass::Elf64, EM_BPF) => Arch::Bpf {
            variant: crate::arch::bpf::BpfVariant::Linux,
        },
        // Solana SBF — `e_machine = 263`. sBPFv1 vs sBPFv2 is
        // a runtime decision made by the loader from
        // `e_flags`; for the decompile path we default to
        // sBPFv1 since the encoding is shared and the variant
        // only changes a handful of mnemonics. A future pass
        // can sharpen this once a real sBPFv2 fixture lands.
        (ElfClass::Elf64, EM_SBF) => Arch::Bpf {
            variant: crate::arch::bpf::BpfVariant::Sbfv1,
        },
        _ => return Err(Error::UnsupportedMachine(elf.ehdr.e_machine)),
    };

    let module = build_module::build_module(elf);
    let map = discover_functions(elf)?;
    let debug_by_addr: HashMap<u64, DebugFunction> = crate::debug::read_debug_info(elf)?;

    // Build an address → name map once; passed to every build_function so
    // call sites can be annotated with target names.
    let name_at: HashMap<u64, String> = map.iter().map(|f| (f.addr.0, f.name.clone())).collect();

    // BPF / SBF only: build a `call <imm> → symbol name` map
    // from `.rel.dyn`. This is layer 1 of the BPF
    // decompile-quality push — `call 0xeca` becomes
    // `call sol_log_` for every relocation-resolved import.
    // Non-BPF arches don't carry these relocations; the map
    // stays empty and the rewrite path is a no-op.
    let call_site_names: HashMap<u64, String> = match arch {
        Arch::Bpf { .. } => {
            crate::analysis::bpf_relocs::build_call_site_names(elf).map_err(Error::BpfReloc)?
        }
        _ => HashMap::new(),
    };

    let mut items = Vec::new();

    // Top-level notes for functions we know about but can't body.
    for f in map.iter() {
        if f.size == 0 {
            items.push(Item::Comment(format!(
                "note: `{}` at 0x{:x} has no known size; not bodied",
                f.name, f.addr.0
            )));
        } else if !function_lives_in_a_section(elf, f.addr.0, f.size) {
            items.push(Item::Comment(format!(
                "note: `{}` at 0x{:x} not in any on-disk section; not bodied",
                f.name, f.addr.0
            )));
        }
    }

    // One @section block per ELF section worth emitting.
    for (idx, sh, data) in elf.sections() {
        if !section_is_emittable(sh) {
            continue;
        }
        let name = elf
            .section_name(idx)
            .map_or_else(|| format!("section{idx}"), str::to_string);
        let mut section_items = build_section_items(
            elf,
            sh,
            data,
            &map,
            &debug_by_addr,
            &name_at,
            &call_site_names,
            arch,
        )?;
        drop_redundant_function_addrs(sh.sh_addr, &mut section_items);
        items.push(Item::Section {
            name,
            addr: sh.sh_addr,
            items: section_items,
        });
    }

    // After every section is built, harvest the jump-table
    // metadata from `Stmt::Switch` instances and replace the
    // corresponding `@raw` byte run in `.rodata` (or any other
    // section that holds the table) with an `@jump_table`
    // directive. This is the symbolic form — editing a case
    // target re-encodes the table at lower time.
    let tables = collect_switch_tables(&items);
    replace_raw_with_jump_tables(&mut items, &tables);

    // Drop the byte list from every `@asm("text", [bytes])`
    // statement whose text re-assembles to those exact bytes —
    // we can regenerate them at lower time from the text alone.
    // This shrinks the .ud source toward "minimal bytes": only
    // forms the assembler doesn't yet cover keep their pinned
    // bytes.
    let bitness = if let Arch::X86 { bitness } = arch {
        Some(bitness)
    } else {
        None
    };
    if let Some(bitness) = bitness {
        drop_regenerable_asm_bytes(&mut items, bitness);
    }
    // Framework byte-drop: try the codec's `encode_*` methods
    // against every lifted Stmt's pinned bytes. BPF picks up
    // Move / Return / Call / RegArith; x86 picks up Move for
    // the simple `var_X = LITERAL / reg = reg` shapes the
    // codec models. Anything `Unsupported` keeps its bytes.
    match arch {
        Arch::Bpf { variant } => {
            let codec = crate::arch::bpf::BpfCodec(variant);
            drop_regenerable_bytes(&mut items, &codec);
        }
        Arch::X86 { bitness } => {
            let codec = crate::arch::x86::X86Codec(bitness);
            drop_regenerable_bytes(&mut items, &codec);
        }
        Arch::Aarch64 => {}
    }

    Ok(UdFile { module, items })
}

/// Generic byte-drop pass driven by an [`crate::arch::codec::ArchCodec`].
///
/// Walks every `Stmt::Asm` / `Stmt::IfBlock` / `Stmt::WhileBlock`
/// recursively, asks the codec to re-encode each one's
/// canonical text form, and clears the pinned bytes when the
/// codec reproduces them exactly. The byte-identity guard means
/// "drop only when the lower-time default reproduces these
/// bytes" — the same regen happens on both sides, so a passing
/// drop on this side guarantees round-trip.
///
/// Originally BPF-specific; the trait abstraction lets the same
/// loop service any fixed-width arch whose codec implements
/// `assemble_one`, `desymbolize`, `encode_cond_jump`, and
/// `encode_jump`. Arches without those methods return
/// `Unsupported` and the loop is a no-op for them.
#[allow(clippy::too_many_lines, clippy::items_after_statements)]
fn drop_regenerable_bytes(items: &mut [Item], arch: &dyn crate::arch::codec::ArchCodec) {
    // Probe the arch's fixed instruction width via a
    // self-relative jump-size query. BPF returns 8;
    // fixed-width arches return their natural width.
    let slot_size = arch.encoded_jump_size(0, 0, crate::arch::codec::EncodeHints::default()) as u64;

    /// Walk a slice of statements, threading the cursor IP
    /// so each @asm's address is known.
    fn visit_stmts(
        stmts: &mut [crate::ast::Stmt],
        ip: &mut u64,
        arch: &dyn crate::arch::codec::ArchCodec,
        slot_size: u64,
    ) {
        for stmt in stmts.iter_mut() {
            match stmt {
                crate::ast::Stmt::Asm { text, bytes } => {
                    let here = *ip;
                    if bytes.is_empty() {
                        *ip = ip.saturating_add(slot_size);
                        continue;
                    }
                    // Try the pure form first; symbolic forms
                    // (BPF's `call sub_<hex>`, `jeq …,
                    // label_<hex>`) need desymbolize first.
                    let mut dropped = false;
                    if let Ok(encoded) = arch.assemble_one(text, here)
                        && encoded == *bytes
                    {
                        bytes.clear();
                        dropped = true;
                    }
                    if !dropped {
                        let desym = arch.desymbolize(text, here);
                        if desym != *text
                            && let Ok(encoded) = arch.assemble_one(&desym, here)
                            && encoded == *bytes
                        {
                            bytes.clear();
                        }
                    }
                    *ip = ip.saturating_add(slot_size);
                }
                crate::ast::Stmt::Move { dst, src, bytes } => {
                    if !bytes.is_empty()
                        && let Ok(encoded) = arch.encode_move(dst, src)
                        && encoded == *bytes
                    {
                        bytes.clear();
                    }
                    // 1 slot for plain Move, 2 for LDDW Move
                    // (16 pinned bytes); after byte-drop bytes
                    // may be empty — assume 1 slot.
                    let slots = if bytes.is_empty() {
                        1
                    } else {
                        (bytes.len() as u64).max(slot_size) / slot_size
                    };
                    *ip = ip.saturating_add(slots * slot_size);
                }
                crate::ast::Stmt::RegArith {
                    dst,
                    op,
                    src,
                    bytes,
                } => {
                    if !bytes.is_empty()
                        && let Ok(encoded) = arch.encode_arith(dst, op, src)
                        && encoded == *bytes
                    {
                        bytes.clear();
                    }
                    *ip = ip.saturating_add(slot_size);
                }
                crate::ast::Stmt::Return { value, bytes } => {
                    if !bytes.is_empty()
                        && let Ok(encoded) = arch.encode_return(Some(*value))
                        && encoded == *bytes
                    {
                        bytes.clear();
                    }
                    *ip = ip.saturating_add(slot_size);
                }
                crate::ast::Stmt::Call {
                    bytes,
                    direct_target,
                    ..
                } => {
                    // Byte-drop is supported only for intra-
                    // program calls (direct_target is set
                    // AND the codec considers the bytes the
                    // complete instruction). Syscalls keep
                    // their pinned bytes — the imm carries a
                    // relocation hash the codec can't
                    // reproduce without external context.
                    if !bytes.is_empty()
                        && arch.direct_call_bytes_contain_call()
                        && let Some(target) = *direct_target
                    {
                        // BPF has two intra-program call
                        // shapes (0x8d Linux call_local
                        // vs 0x85 src=1 Solana sBPF
                        // call_internal). The codec's
                        // default regen at lower time is
                        // call_internal, so only drop
                        // bytes when the original ALSO
                        // used call_internal — call_local
                        // sites keep their pinned bytes
                        // so the lower-time regen doesn't
                        // silently switch encodings.
                        // Storing the original encoding
                        // in the AST is a follow-up if
                        // call_local sites become more
                        // common in real fixtures.
                        if bytes.first() == Some(&0x85)
                            && let Ok(encoded) = arch.encode_call(
                                *ip,
                                target,
                                crate::arch::codec::EncodeHints::default(),
                            )
                            && encoded == *bytes
                        {
                            bytes.clear();
                        }
                    }
                    *ip = ip.saturating_add(slot_size);
                }
                crate::ast::Stmt::IfBlock {
                    cond_text,
                    cond_bytes,
                    then_body,
                    then_tail_jmp,
                    else_body,
                } => {
                    // Cond_bytes: jcc skipping the then-body
                    // (and the tail ja) when cond_text is
                    // false. Target = past then_body + tail.
                    if !cond_bytes.is_empty() {
                        let cond_ip = *ip;
                        let then_body_size = build_function::lowered_body_size_at(
                            then_body,
                            cond_ip.saturating_add(cond_bytes.len() as u64),
                        );
                        let target = cond_ip
                            .saturating_add(slot_size)
                            .saturating_add(then_body_size)
                            .saturating_add(then_tail_jmp.len() as u64);
                        if let Ok(encoded) = arch.encode_cond_jump(
                            cond_text,
                            cond_ip,
                            target,
                            crate::arch::codec::EncodeHints::default(),
                        ) && encoded == *cond_bytes
                        {
                            cond_bytes.clear();
                        }
                    }
                    *ip = ip.saturating_add(slot_size);
                    visit_stmts(then_body, ip, arch, slot_size);
                    // then_tail_jmp: unconditional `ja` over
                    // the else body.
                    if !then_tail_jmp.is_empty() {
                        let ttj_ip = *ip;
                        let else_size = build_function::lowered_body_size_at(
                            else_body,
                            ttj_ip.saturating_add(slot_size),
                        );
                        let target = ttj_ip.saturating_add(slot_size).saturating_add(else_size);
                        if let Ok(encoded) = arch.encode_jump(
                            ttj_ip,
                            target,
                            crate::arch::codec::EncodeHints::default(),
                        ) && encoded == *then_tail_jmp
                        {
                            then_tail_jmp.clear();
                        }
                        *ip = ip.saturating_add(slot_size);
                    }
                    visit_stmts(else_body, ip, arch, slot_size);
                }
                crate::ast::Stmt::WhileBlock {
                    cond_text,
                    entry_bytes,
                    body: wb,
                    tail_bytes,
                } => {
                    let entry_ip = *ip;
                    if !entry_bytes.is_empty() {
                        let body_size = build_function::lowered_body_size_at(
                            wb,
                            entry_ip.saturating_add(entry_bytes.len() as u64),
                        );
                        let target = entry_ip
                            .saturating_add(slot_size)
                            .saturating_add(body_size)
                            .saturating_add(tail_bytes.len() as u64);
                        if let Ok(encoded) = arch.encode_cond_jump(
                            cond_text,
                            entry_ip,
                            target,
                            crate::arch::codec::EncodeHints::default(),
                        ) && encoded == *entry_bytes
                        {
                            entry_bytes.clear();
                        }
                    }
                    *ip = ip.saturating_add(slot_size);
                    visit_stmts(wb, ip, arch, slot_size);
                    if !tail_bytes.is_empty() {
                        let ja_ip = *ip;
                        // Back-edge: jump to entry_ip.
                        if let Ok(encoded) = arch.encode_jump(
                            ja_ip,
                            entry_ip,
                            crate::arch::codec::EncodeHints::default(),
                        ) && encoded == *tail_bytes
                        {
                            tail_bytes.clear();
                        }
                        *ip = ip.saturating_add(slot_size);
                    }
                }
                crate::ast::Stmt::IfBranch {
                    pre_body,
                    cond_bytes,
                    then_body,
                    else_body,
                    ..
                } => {
                    visit_stmts(pre_body, ip, arch, slot_size);
                    *ip = ip.saturating_add(cond_bytes.len() as u64);
                    visit_stmts(then_body, ip, arch, slot_size);
                    if let Some(eb) = else_body {
                        visit_stmts(eb, ip, arch, slot_size);
                    }
                }
                _ => {}
            }
        }
    }

    /// Recover the function's IP-space starting address.
    /// Order of preference:
    /// 1. `fd.addr` if set (`@addr(0x…)` survived the
    ///    `drop_redundant_function_addrs` pass).
    /// 2. Hex suffix of the name: `sub_<hex>` maps to the
    ///    address directly (this is the convention the
    ///    decompiler uses when no real symbol exists).
    /// 3. Zero — give up; the byte-drop won't fire for
    ///    address-dependent symbolic forms in this function.
    fn fn_base_addr(fd: &crate::ast::FnDecl) -> u64 {
        if let Some(a) = fd.addr {
            return a;
        }
        if let Some(rest) = fd.name.strip_prefix("sub_")
            && let Ok(a) = u64::from_str_radix(rest, 16)
        {
            return a;
        }
        0
    }

    /// Walk a section's items in order, threading a
    /// cursor through them so functions whose `@addr` was
    /// dropped (because their address equals the running
    /// cursor) still get their base IP recovered. Mirrors
    /// `drop_redundant_function_addrs` plus
    /// `build_function::lowered_body_size_at` — and
    /// matches exactly what the lower path does at
    /// recompile time.
    fn visit_section_items(
        section_addr: u64,
        items: &mut [Item],
        arch: &dyn crate::arch::codec::ArchCodec,
        slot_size: u64,
    ) {
        let mut cursor = section_addr;
        for item in items.iter_mut() {
            match item {
                Item::Function(fd) => {
                    let start = if let Some(a) = fd.addr {
                        a
                    } else if let Some(rest) = fd.name.strip_prefix("sub_") {
                        u64::from_str_radix(rest, 16).unwrap_or(cursor)
                    } else {
                        cursor
                    };
                    // CRITICAL: compute body_size BEFORE
                    // visit_stmts runs — visit_stmts drops
                    // bytes from @asm lines, which causes
                    // `lowered_body_size_at` to report 0
                    // for those (it sums `bytes.len()`).
                    let body_size = build_function::lowered_body_size_at(&fd.body, start);
                    let mut ip = start;
                    visit_stmts(&mut fd.body, &mut ip, arch, slot_size);
                    cursor = start.saturating_add(body_size);
                }
                Item::Raw { addr, bytes } => {
                    cursor = (*addr).saturating_add(bytes.len() as u64);
                }
                Item::Section { addr, items, .. } => {
                    visit_section_items(*addr, items, arch, slot_size);
                }
                _ => {}
            }
        }
    }

    for item in items.iter_mut() {
        match item {
            Item::Section { addr, items, .. } => {
                visit_section_items(*addr, items, arch, slot_size);
            }
            Item::Function(fd) => {
                let mut ip = fn_base_addr(fd);
                visit_stmts(&mut fd.body, &mut ip, arch, slot_size);
            }
            _ => {}
        }
    }
}

/// Walk every `Stmt::Asm` in the AST. For each, try to encode
/// `text` via the in-crate x86 assembler at the statement's
/// actual IP; if it succeeds and the encoded bytes equal the
/// pinned `bytes`, clear the byte list — lower will re-assemble
/// at the same IP and reproduce the same bytes.
///
/// The IP threading matters for RIP-relative encodings
/// (`jmp/call/push qword ptr [abs]` in 64-bit mode): the
/// emitted bytes carry `disp32 = target − (rip + insn_size)`,
/// so assembling at IP 0 would produce a different disp than
/// the original bytes at the real IP. Threading the cursor
/// through gives us both the regen path and the drop test
/// against the same fixed reference point.
#[allow(clippy::too_many_lines)]
fn drop_regenerable_asm_bytes(items: &mut [Item], bitness: crate::arch::x86::Bitness) {
    /// Return the encoded byte size of `stmt` so the cursor can
    /// step past it. For `Stmt::Asm`, the pinned bytes' length
    /// is the source of truth; for re-encoded forms the size is
    /// what our assembler would emit.
    fn asm_size(stmt: &crate::ast::Stmt, bitness: crate::arch::x86::Bitness, ip: u64) -> u64 {
        if let crate::ast::Stmt::Asm { text, bytes } = stmt {
            if !bytes.is_empty() {
                return bytes.len() as u64;
            }
            if let Ok(encoded) = crate::arch::x86::assemble_intel(bitness, text, ip) {
                return encoded.len() as u64;
            }
        }
        0
    }

    fn visit_stmts(
        stmts: &mut [crate::ast::Stmt],
        bitness: crate::arch::x86::Bitness,
        ip: &mut u64,
    ) {
        for stmt in stmts.iter_mut() {
            let here = *ip;
            match stmt {
                crate::ast::Stmt::Asm { text, bytes } => {
                    if bytes.is_empty() {
                        *ip = ip.saturating_add(asm_size(stmt, bitness, here));
                        continue;
                    }
                    if let Ok(encoded) = crate::arch::x86::assemble_intel(bitness, text, here)
                        && encoded == *bytes
                    {
                        bytes.clear();
                    }
                    *ip = ip.saturating_add(asm_size(stmt, bitness, here));
                }
                crate::ast::Stmt::IfBranch {
                    pre_body,
                    cond_bytes,
                    then_body,
                    else_body,
                    ..
                } => {
                    visit_stmts(pre_body, bitness, ip);
                    *ip = ip.saturating_add(cond_bytes.len() as u64);
                    visit_stmts(then_body, bitness, ip);
                    if let Some(eb) = else_body {
                        visit_stmts(eb, bitness, ip);
                    }
                }
                crate::ast::Stmt::Loop {
                    entry_jmp_bytes,
                    body,
                    tail_bytes,
                    ..
                } => {
                    if let Some(jmp) = entry_jmp_bytes {
                        *ip = ip.saturating_add(jmp.len() as u64);
                    }
                    visit_stmts(body, bitness, ip);
                    *ip = ip.saturating_add(tail_bytes.len() as u64);
                }
                other => {
                    // Conservative fallback: bump the cursor by
                    // any byte-bearing sub-field we know about.
                    // Inaccurate for some statement kinds but
                    // sufficient since RIP-relative forms only
                    // appear in `Stmt::Asm` today.
                    *ip = ip.saturating_add(stmt_min_size(other));
                }
            }
        }
    }

    fn auto_prologue_size(f: &crate::ast::FnDecl) -> u64 {
        let has_flag = f.attrs.iter().any(|a| {
            (a.key == "autogen_pro" || a.key == "autogen_pro_legacy")
                && matches!(a.value, crate::ast::AttrValue::Flag)
        });
        if !has_flag {
            return 0;
        }
        let profile = build_function::profile_inputs_from_fn(f);
        let cb = if profile.bits == 64 {
            crate::arch::x86::CodecBits::Bits64
        } else {
            crate::arch::x86::CodecBits::Bits32
        };
        let pro = crate::arch::x86::default_prologue(&profile);
        crate::arch::x86::encode_prologue(&pro, cb).len() as u64
    }

    fn auto_epilogue_size(f: &crate::ast::FnDecl) -> u64 {
        let has_flag = f.attrs.iter().any(|a| {
            (a.key == "autogen_pro" || a.key == "autogen_pro_legacy")
                && matches!(a.value, crate::ast::AttrValue::Flag)
        });
        if !has_flag {
            return 0;
        }
        let profile = build_function::profile_inputs_from_fn(f);
        let cb = if profile.bits == 64 {
            crate::arch::x86::CodecBits::Bits64
        } else {
            crate::arch::x86::CodecBits::Bits32
        };
        let epi = crate::arch::x86::default_epilogue(&profile);
        crate::arch::x86::encode_epilogue(&epi, cb).len() as u64
    }

    #[allow(clippy::enum_glob_use)]
    fn stmt_min_size(stmt: &crate::ast::Stmt) -> u64 {
        use crate::ast::Stmt::*;
        match stmt {
            Asm { bytes, .. }
            | Return { bytes, .. }
            | Prologue { bytes, .. }
            | Epilogue { bytes, .. }
            | Save { bytes, .. }
            | Restore { bytes, .. }
            | ReturnExpr { bytes, .. }
            | ArgSpill { bytes, .. }
            | LocalSet { bytes, .. }
            | LocalArith { bytes, .. }
            | LocalCompound { bytes, .. }
            | Move { bytes, .. }
            | Inc16 { bytes, .. }
            | SehInstall { bytes }
            | SehRestore { bytes } => bytes.len() as u64,
            Call {
                bytes,
                direct_target,
                ..
            } => bytes.len() as u64 + if direct_target.is_some() { 5 } else { 0 },
            Goto { wide, .. } => {
                if *wide {
                    5
                } else {
                    2
                }
            }
            IfGoto {
                cmp_bytes, wide, ..
            }
            | IfReturn {
                cmp_bytes, wide, ..
            } => cmp_bytes.len() as u64 + if *wide { 6 } else { 2 },
            _ => 0,
        }
    }

    fn visit_items(items: &mut [Item], bitness: crate::arch::x86::Bitness, section_cursor: u64) {
        let mut cursor = section_cursor;
        for item in items.iter_mut() {
            match item {
                Item::Function(f) => {
                    let fn_ip = f.addr.unwrap_or(cursor);
                    let mut ip = fn_ip;
                    // Account for the auto-generated prologue
                    // bytes the lower path will emit when
                    // `@autogen_pro` (or its legacy alias) is
                    // set — the first body statement's IP sits
                    // past those bytes.
                    ip = ip.saturating_add(auto_prologue_size(f));
                    visit_stmts(&mut f.body, bitness, &mut ip);
                    // The trailing autogen epilogue, when set,
                    // also lives in the function's bytes but
                    // emits after the body — for cursor
                    // tracking past the function, add it.
                    ip = ip.saturating_add(auto_epilogue_size(f));
                    cursor = ip;
                }
                Item::Section {
                    addr,
                    items: nested,
                    ..
                } => visit_items(nested, bitness, *addr),
                Item::Raw { addr, bytes } => {
                    cursor = (*addr).saturating_add(bytes.len() as u64);
                }
                Item::Strings { addr, strings } => {
                    cursor =
                        (*addr).saturating_add(strings.iter().map(|s| (s.len() + 1) as u64).sum());
                }
                Item::Notes { addr, .. } => {
                    cursor = *addr;
                }
                Item::JumpTable { addr, entries, .. } => {
                    cursor = (*addr).saturating_add((entries.len() as u64) * 4);
                }
                Item::Comment(_) => {}
            }
        }
    }
    visit_items(items, bitness, 0);
}

/// One switch-dispatch table harvested from a `Stmt::Switch`.
#[derive(Debug, Clone)]
struct SwitchTable {
    table_va: u64,
    dispatch: String,
    /// Case targets in source order — entry `[i]` is the address
    /// that case `i` dispatches to.
    cases: Vec<u64>,
}

fn collect_switch_tables(items: &[Item]) -> Vec<SwitchTable> {
    fn walk(items: &[Item], out: &mut Vec<SwitchTable>) {
        for item in items {
            match item {
                Item::Function(f) => collect_in_stmts(&f.body, out),
                Item::Section { items: nested, .. } => walk(nested, out),
                _ => {}
            }
        }
    }
    fn collect_in_stmts(stmts: &[crate::ast::Stmt], out: &mut Vec<SwitchTable>) {
        for s in stmts {
            match s {
                crate::ast::Stmt::Switch {
                    cases,
                    dispatch,
                    table_va,
                    ..
                } if *table_va != 0 && !cases.is_empty() => {
                    out.push(SwitchTable {
                        table_va: *table_va,
                        dispatch: dispatch.clone(),
                        cases: cases.clone(),
                    });
                }
                crate::ast::Stmt::IfBranch {
                    pre_body,
                    then_body,
                    else_body,
                    ..
                } => {
                    collect_in_stmts(pre_body, out);
                    collect_in_stmts(then_body, out);
                    if let Some(eb) = else_body {
                        collect_in_stmts(eb, out);
                    }
                }
                crate::ast::Stmt::Loop { body, .. } => collect_in_stmts(body, out),
                _ => {}
            }
        }
    }
    let mut out = Vec::new();
    walk(items, &mut out);
    out
}

/// Walk the section tree and, for every `@raw` block that fully
/// contains a known switch table's bytes, split it into:
///
/// ```text
/// @raw(<addr>, [prefix])
/// @jump_table(<table_va>, dispatch="…") { case_<i>: label_<target>; … }
/// @raw(<table_end>, [suffix])
/// ```
///
/// Zero-length prefix / suffix slices are omitted. Today the
/// known dispatch encodings (`gcc_pie_rel32`, `msvc_va32`) both
/// use 4-byte entries, so each table covers `4 * cases.len()`
/// bytes starting at `table_va`. Unknown dispatch kinds are
/// skipped (no replacement, no error).
fn replace_raw_with_jump_tables(items: &mut [Item], tables: &[SwitchTable]) {
    fn entry_size(dispatch: &str) -> Option<u64> {
        match dispatch {
            "gcc_pie_rel32" | "msvc_va32" => Some(4),
            _ => None,
        }
    }
    fn rewrite_section(section_items: &mut Vec<Item>, tables: &[SwitchTable]) {
        let mut i = 0;
        while i < section_items.len() {
            // Try each table; the first that fits splits this raw
            // block.
            let mut replacement: Option<(usize, Vec<Item>)> = None;
            if let Item::Raw { addr, bytes } = &section_items[i] {
                for t in tables {
                    let Some(esz) = entry_size(&t.dispatch) else {
                        continue;
                    };
                    let table_size = esz * (t.cases.len() as u64);
                    let raw_start = *addr;
                    let raw_end = raw_start.saturating_add(bytes.len() as u64);
                    let table_end = t.table_va.saturating_add(table_size);
                    if t.table_va < raw_start || table_end > raw_end {
                        continue;
                    }
                    // Slice the raw into prefix / table / suffix.
                    let prefix_len = (t.table_va - raw_start) as usize;
                    let table_len = table_size as usize;
                    let suffix_start = prefix_len + table_len;
                    let mut new_items: Vec<Item> = Vec::new();
                    if prefix_len > 0 {
                        new_items.push(Item::Raw {
                            addr: raw_start,
                            bytes: bytes[..prefix_len].to_vec(),
                        });
                    }
                    let entries = t
                        .cases
                        .iter()
                        .enumerate()
                        .map(|(idx, target)| crate::ast::JumpTableEntry {
                            case: idx as u64,
                            target: *target,
                        })
                        .collect();
                    new_items.push(Item::JumpTable {
                        addr: t.table_va,
                        dispatch: t.dispatch.clone(),
                        entries,
                    });
                    if suffix_start < bytes.len() {
                        new_items.push(Item::Raw {
                            addr: table_end,
                            bytes: bytes[suffix_start..].to_vec(),
                        });
                    }
                    replacement = Some((1, new_items));
                    break;
                }
            }
            if let Some((remove, mut new_items)) = replacement {
                section_items.remove(i);
                let added = new_items.len();
                for (off, it) in new_items.drain(..).enumerate() {
                    section_items.insert(i + off, it);
                }
                let _ = remove; // we always remove exactly one item
                i += added;
            } else {
                i += 1;
            }
        }
    }
    for item in items.iter_mut() {
        if let Item::Section { items: nested, .. } = item {
            rewrite_section(nested, tables);
        }
    }
}

/// Walk a section's items in declaration order and drop
/// `@addr(…)` from every `Function` whose address is exactly the
/// cumulative cursor — i.e., the function would fall in at the
/// expected position anyway. This removes noise from the
/// decompiled source: the addr-pinned shape is reserved for
/// items that diverge from the running cursor (functions
/// preceded by a deliberate alignment gap, or hand-edited
/// placements). On lower, items without an explicit addr take
/// the cumulative cursor automatically.
///
/// `Raw`, `Strings`, and `Notes` items keep their `addr` — those
/// are required by the AST today, and they're typically pinned
/// at section-relative offsets that matter for the binary's
/// data layout. We advance the cursor past them by recomputing
/// the on-disk byte size locally so subsequent function-addr
/// comparisons land at the right position.
fn drop_redundant_function_addrs(section_addr: u64, items: &mut [Item]) {
    let mut cursor = section_addr;
    for item in items.iter_mut() {
        match item {
            Item::Function(f) => {
                let body_size = build_function::lowered_body_size_at(&f.body, cursor);
                if f.addr == Some(cursor) {
                    f.addr = None;
                }
                cursor = cursor.saturating_add(body_size);
            }
            Item::Raw { addr, bytes } => {
                cursor = (*addr).saturating_add(bytes.len() as u64);
            }
            Item::Strings { addr, strings } => {
                cursor = (*addr).saturating_add(strings_byte_size(strings));
            }
            Item::Notes { addr, entries } => {
                cursor = (*addr).saturating_add(notes_byte_size(entries));
            }
            Item::JumpTable { addr, entries, .. } => {
                // Every supported dispatch encoding uses 4-byte
                // entries; case_count * 4 is the on-disk size.
                cursor = (*addr).saturating_add((entries.len() as u64) * 4);
            }
            Item::Comment(_) | Item::Section { .. } => {}
        }
    }
}

fn strings_byte_size(strings: &[String]) -> u64 {
    strings.iter().map(|s| (s.len() + 1) as u64).sum()
}

fn notes_byte_size(entries: &[crate::ast::NoteEntry]) -> u64 {
    let mut size: u64 = 0;
    for e in entries {
        size += 12; // Nhdr: name_size + desc_size + type
        let name_padded = ((e.name.len() + 1) + 3) & !3; // null-terminated, 4-aligned
        size += name_padded as u64;
        let desc_padded = (e.desc.len() + 3) & !3;
        size += desc_padded as u64;
    }
    size
}

/// Convenience: build the AST and pretty-print it to canonical text.
pub fn decompile_to_text(elf: &Elf64File) -> Result<String> {
    let ast = decompile(elf)?;
    Ok(crate::ast::emit(&ast))
}

/// Whether a section will be emitted as `@section`. Skips sections
/// without on-disk content (NULL, NOBITS, zero-size). Sections with
/// `sh_addr == 0` (debug info, `.comment`, `.symtab`, …) ARE emitted —
/// their items are addressed in [0, sh_size) since virtual addresses
/// don't apply, and the lower path matches them to shdrs by name.
fn section_is_emittable(sh: &Shdr64) -> bool {
    const SHT_NULL: u32 = 0;
    const SHT_NOBITS: u32 = 8;
    sh.sh_type != SHT_NULL && sh.sh_type != SHT_NOBITS && sh.sh_size > 0
}

fn function_lives_in_a_section(elf: &Elf64File, addr: u64, size: u64) -> bool {
    if size == 0 {
        return false;
    }
    let end = addr.saturating_add(size);
    for (_, sh, _) in elf.sections() {
        let sh_end = sh.sh_addr.saturating_add(sh.sh_size);
        if sh.sh_addr <= addr && end <= sh_end {
            return true;
        }
    }
    false
}

/// Decode an ELF `SHT_STRTAB` section as a list of null-terminated
/// strings. Returns `None` when any string contains non-UTF-8 bytes
/// or the section doesn't end on a terminator — in that case the
/// caller falls back to the opaque `@raw` form.
fn decode_strtab(data: &[u8]) -> Option<Vec<String>> {
    if data.is_empty() {
        return Some(Vec::new());
    }
    if *data.last().unwrap() != 0 {
        return None;
    }
    let mut out = Vec::new();
    for chunk in data.split(|&b| b == 0) {
        if chunk.is_empty() {
            out.push(String::new());
        } else {
            out.push(std::str::from_utf8(chunk).ok()?.to_string());
        }
    }
    // `split` on a trailing 0 produces a final empty chunk that
    // isn't a real entry — drop it so the encode round-trips.
    if out.last().is_some_and(String::is_empty) {
        out.pop();
    }
    Some(out)
}

/// Decode an ELF `SHT_NOTE` section into a flat list of notes.
/// Returns `None` on any structural mismatch (truncated header,
/// non-UTF-8 name, padding that doesn't round-trip cleanly).
fn decode_notes(data: &[u8]) -> Option<Vec<crate::ast::NoteEntry>> {
    let mut out = Vec::new();
    let mut i = 0;
    while i < data.len() {
        if i + 12 > data.len() {
            return None;
        }
        let name_size = u32::from_le_bytes(data[i..i + 4].try_into().ok()?) as usize;
        let desc_size = u32::from_le_bytes(data[i + 4..i + 8].try_into().ok()?) as usize;
        let note_type = u32::from_le_bytes(data[i + 8..i + 12].try_into().ok()?);
        i += 12;
        if name_size == 0 || i + name_size > data.len() {
            return None;
        }
        // name_size includes the trailing NUL.
        let name_bytes = &data[i..i + name_size - 1];
        if data[i + name_size - 1] != 0 {
            return None;
        }
        let name = std::str::from_utf8(name_bytes).ok()?.to_string();
        i += name_size;
        // Pad to 4-byte boundary.
        while i % 4 != 0 {
            if i >= data.len() || data[i] != 0 {
                return None;
            }
            i += 1;
        }
        if i + desc_size > data.len() {
            return None;
        }
        let desc = data[i..i + desc_size].to_vec();
        i += desc_size;
        while i % 4 != 0 {
            if i >= data.len() || data[i] != 0 {
                return None;
            }
            i += 1;
        }
        out.push(crate::ast::NoteEntry {
            note_type,
            name,
            desc,
        });
    }
    Some(out)
}

/// Build the items inside one `@section` block: any functions whose
/// address range falls inside the section, plus `@raw` blocks for
/// every byte not covered by a function.
#[allow(clippy::too_many_arguments)]
fn build_section_items(
    elf: &Elf64File,
    sh: &Shdr64,
    data: &[u8],
    map: &FunctionMap,
    debug_by_addr: &HashMap<u64, DebugFunction>,
    name_at: &HashMap<u64, String>,
    call_site_names: &HashMap<u64, String>,
    arch: Arch,
) -> Result<Vec<Item>> {
    // Structured-form sections short-circuit before the
    // function-coverage walk: ELF string tables and note sections
    // have a well-defined byte layout we can faithfully decode and
    // re-emit. When the structured decode covers the whole section
    // cleanly, prefer it over `@raw`. Round-trip safety comes from
    // the lower-side encoder producing the same bytes.
    const SHT_STRTAB: u32 = 3;
    const SHT_NOTE: u32 = 7;
    let section_name = elf
        .shdrs
        .iter()
        .position(|sh2| std::ptr::eq(sh2, sh))
        .and_then(|idx| elf.section_name(idx))
        .unwrap_or("");
    // `.interp` is `SHT_PROGBITS` by sh_type but always contains a
    // single null-terminated path to the dynamic linker. Decoding it
    // as a one-entry `@strings` matches the lower-side encoder.
    let is_interp = section_name == ".interp";
    if (sh.sh_type == SHT_STRTAB || is_interp)
        && let Some(strings) = decode_strtab(data)
    {
        return Ok(vec![Item::Strings {
            addr: sh.sh_addr,
            strings,
        }]);
    }
    if sh.sh_type == SHT_NOTE
        && let Some(entries) = decode_notes(data)
    {
        return Ok(vec![Item::Notes {
            addr: sh.sh_addr,
            entries,
        }]);
    }

    let section_start = sh.sh_addr;
    let section_end = sh.sh_addr.saturating_add(sh.sh_size);

    // Functions whose entire range falls inside this section.
    // For relocatable object files (`.o`) multiple sections
    // share `sh_addr = 0`, so an address-range match alone
    // would pull `.text` functions into `.symtab` / `.strtab`
    // too. Filter on `SHF_EXECINSTR` first: data sections
    // never contain functions regardless of how their address
    // range overlaps.
    let is_exec = sh.sh_flags & SHF_EXECINSTR != 0;
    let mut funcs: Vec<_> = if is_exec {
        map.iter()
            .filter(|f| {
                f.size > 0
                    && f.addr.0 >= section_start
                    && f.addr.0.saturating_add(f.size) <= section_end
            })
            .collect()
    } else {
        Vec::new()
    };
    funcs.sort_by_key(|f| f.addr.0);

    let mut out = Vec::new();
    let mut cursor = section_start;

    for f in &funcs {
        // Gap before this function — usually padding bytes, but
        // for stripped BPF binaries (Solana programs without a
        // `.symtab`) the gap is the whole program. Lift it as
        // anonymous BPF code instead of `@raw` so the output is
        // actually readable.
        if cursor < f.addr.0 {
            let lo = (cursor - section_start) as usize;
            let hi = (f.addr.0 - section_start) as usize;
            emit_gap(
                &mut out,
                arch,
                is_exec,
                cursor,
                &data[lo..hi],
                name_at,
                call_site_names,
                elf,
            )?;
        }
        // The function itself.
        let lo = (f.addr.0 - section_start) as usize;
        let hi = lo + f.size as usize;
        let slice = &data[lo..hi];
        let fn_decl = match arch {
            Arch::X86 { bitness } => {
                let insns = decode(bitness, slice, f.addr.0)?;
                let lifted = lift_function(f.name.clone(), &insns)?;
                let debug = debug_by_addr.get(&f.addr.0);
                build_function::build_function(&lifted, debug, name_at, elf)
            }
            Arch::Aarch64 => {
                let insns =
                    crate::arch::aarch64::decode(slice, f.addr.0).map_err(Error::Aarch64Decode)?;
                let lifted = crate::arch::aarch64::lift_function(f.name.clone(), &insns);
                aarch64::build_function(&lifted, name_at)
            }
            Arch::Bpf { variant } => {
                let insns =
                    crate::arch::bpf::decode(slice, f.addr.0, variant).map_err(Error::BpfDecode)?;
                let lifted = crate::arch::bpf::lift_function(f.name.clone(), &insns);
                bpf::build_function(&lifted, name_at, call_site_names, variant, Some(elf))
            }
        };
        out.push(Item::Function(fn_decl));
        cursor = f.addr.0.saturating_add(f.size);
    }

    // Trailing gap to the section's end.
    if cursor < section_end {
        let lo = (cursor - section_start) as usize;
        emit_gap(
            &mut out,
            arch,
            is_exec,
            cursor,
            &data[lo..],
            name_at,
            call_site_names,
            elf,
        )?;
    }

    Ok(out)
}

/// Emit a section gap. For non-executable sections or non-BPF
/// arches, the gap is preserved as `@raw` bytes (the historical
/// behaviour). For executable BPF sections, the gap is lifted
/// as anonymous BPF code under a synthetic `fragment_<addr>`
/// function so stripped Solana programs surface as readable
/// instructions instead of one giant byte blob.
///
/// BPF is the only arch we lift gaps for because BPF `.text`
/// is guaranteed to contain instruction-aligned 8-byte slots
/// only. x86 `.text` may mix jump-table data with code, so
/// blanket-decoding a gap there can produce nonsense; aarch64
/// is the same concern at a smaller scale. The fix slot in
/// `discover_functions` for x86 / aarch64 is call-site /
/// landing-pad-style function discovery, which is its own
/// project.
#[allow(clippy::too_many_arguments)]
fn emit_gap(
    out: &mut Vec<Item>,
    arch: Arch,
    is_exec: bool,
    addr: u64,
    bytes: &[u8],
    name_at: &HashMap<u64, String>,
    call_site_names: &HashMap<u64, String>,
    elf: &Elf64File,
) -> Result<()> {
    if bytes.is_empty() {
        return Ok(());
    }
    if is_exec && let Arch::Bpf { variant } = arch {
        // BPF slots are 8 bytes. If the gap doesn't align
        // to that, the leading misaligned bytes ride out as
        // `@raw` and the rest gets lifted. This usually
        // means the section has padding ahead of the first
        // instruction; rare on Solana programs but cheap
        // to defend against.
        let prefix_len = bytes.len() % crate::arch::bpf::INSN_SIZE;
        let (prefix, code) = bytes.split_at(prefix_len);
        if !prefix.is_empty() {
            out.push(Item::Raw {
                addr,
                bytes: prefix.to_vec(),
            });
        }
        let code_addr = addr + prefix_len as u64;
        if !code.is_empty() {
            let insns =
                crate::arch::bpf::decode(code, code_addr, variant).map_err(Error::BpfDecode)?;
            let lifted = crate::arch::bpf::lift_function(format!("fragment_{code_addr:x}"), &insns);
            out.push(Item::Function(bpf::build_function(
                &lifted,
                name_at,
                call_site_names,
                variant,
                Some(elf),
            )));
        }
        return Ok(());
    }
    out.push(Item::Raw {
        addr,
        bytes: bytes.to_vec(),
    });
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ast::{FnDecl, Stmt};

    #[test]
    fn replace_raw_with_jump_table_splits_around_table_va() {
        // Synthetic section: a function with a Stmt::Switch
        // pointing at a `@raw` data block. The replacement
        // should split the raw into prefix + jump_table + suffix.
        let switch_stmt = Stmt::Switch {
            selector: "ecx".into(),
            cases: vec![0x117a, 0x1183, 0x118c],
            default_addr: 0x1200,
            dispatch: "gcc_pie_rel32".into(),
            table_va: 0x2008,
        };
        // .rodata starts at 0x2000 with 8 bytes of prefix,
        // 12 bytes of jump table (3 entries × 4 bytes), 4 bytes
        // of suffix.
        let raw_bytes = vec![
            // prefix (0x2000..0x2008)
            0x01, 0x00, 0x02, 0x00, 0x53, 0x75, 0x6e,
            0x00, // table (0x2008..0x2014) — bytes don't matter, will be replaced
            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
            // suffix (0x2014..0x2018)
            0xde, 0xad, 0xbe, 0xef,
        ];
        let mut items = vec![Item::Section {
            name: ".text".into(),
            addr: 0x1000,
            items: vec![Item::Function(FnDecl {
                addr: Some(0x1000),
                name: "f".into(),
                attrs: Vec::new(),
                signature: None,
                locals: Vec::new(),
                body: vec![switch_stmt],
            })],
        }];
        items.push(Item::Section {
            name: ".rodata".into(),
            addr: 0x2000,
            items: vec![Item::Raw {
                addr: 0x2000,
                bytes: raw_bytes,
            }],
        });
        let tables = collect_switch_tables(&items);
        assert_eq!(tables.len(), 1);
        replace_raw_with_jump_tables(&mut items, &tables);

        let Item::Section {
            items: ro_items, ..
        } = &items[1]
        else {
            panic!("expected .rodata section");
        };
        // Expect: [Raw(prefix 0x2000..0x2008), JumpTable(0x2008), Raw(suffix 0x2014..)]
        assert_eq!(ro_items.len(), 3);
        match &ro_items[0] {
            Item::Raw { addr, bytes } => {
                assert_eq!(*addr, 0x2000);
                assert_eq!(bytes.len(), 8);
            }
            other => panic!("expected Raw prefix, got {other:?}"),
        }
        match &ro_items[1] {
            Item::JumpTable {
                addr,
                dispatch,
                entries,
            } => {
                assert_eq!(*addr, 0x2008);
                assert_eq!(dispatch, "gcc_pie_rel32");
                assert_eq!(entries.len(), 3);
                assert_eq!(entries[0].target, 0x117a);
                assert_eq!(entries[2].target, 0x118c);
            }
            other => panic!("expected JumpTable, got {other:?}"),
        }
        match &ro_items[2] {
            Item::Raw { addr, bytes } => {
                assert_eq!(*addr, 0x2014);
                assert_eq!(bytes, &[0xde, 0xad, 0xbe, 0xef]);
            }
            other => panic!("expected Raw suffix, got {other:?}"),
        }
    }

    #[test]
    fn replace_raw_with_jump_table_skips_unknown_dispatch() {
        let switch_stmt = Stmt::Switch {
            selector: "ecx".into(),
            cases: vec![0x100, 0x200],
            default_addr: 0x300,
            dispatch: "bogus-dispatch".into(),
            table_va: 0x2000,
        };
        let mut items = vec![
            Item::Section {
                name: ".text".into(),
                addr: 0x1000,
                items: vec![Item::Function(FnDecl {
                    addr: Some(0x1000),
                    name: "f".into(),
                    attrs: Vec::new(),
                    signature: None,
                    locals: Vec::new(),
                    body: vec![switch_stmt],
                })],
            },
            Item::Section {
                name: ".rodata".into(),
                addr: 0x2000,
                items: vec![Item::Raw {
                    addr: 0x2000,
                    bytes: vec![0u8; 8],
                }],
            },
        ];
        let tables = collect_switch_tables(&items);
        replace_raw_with_jump_tables(&mut items, &tables);
        // Unknown dispatch → no replacement → raw stays intact.
        let Item::Section {
            items: ro_items, ..
        } = &items[1]
        else {
            panic!()
        };
        assert!(matches!(&ro_items[0], Item::Raw { .. }));
    }
}