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
//! Decompile a parsed [`PeFile`] into a `.ud` AST.
//!
//! v0 scope: structural skeleton + raw bytes.
//!
//! The emitted AST captures enough PE metadata in `@module` for
//! [`lower_to_pe`](crate::translate::compile::lower_to_pe) to
//! reconstruct the file byte-identically. The actual content is laid
//! out as a sequence of `@raw(file_offset, [bytes])` items in
//! file-offset order, covering every byte of the input. No
//! instruction decoding happens here — that's a later iteration's
//! work, mirroring how the ELF decompile path grew.
//!
//! `@module.format = "pe"` distinguishes the lower path from the
//! ELF case so the same `.ud` file can hold either format and the
//! compiler routes correctly.
//!
//! [`PeFile`]: crate::format::pe::PeFile

use std::collections::HashMap;

use crate::arch::x86::{Bitness, lift_function};
use crate::ast::{Field, Item, Module, UdFile, Value};
use crate::format::pe::{
    COFF_SYM_CLASS_EXTERNAL, COFF_SYM_CLASS_STATIC, CoffSymbol, IMAGE_FILE_MACHINE_AMD64,
    IMAGE_FILE_MACHINE_I386, PeExport, PeFile, PeKind,
};

use crate::translate::decompile::build_function;

/// Build the AST for `pe`. Always succeeds — every byte of the input
/// is captured either via `@module` structured fields or via
/// per-region `@raw` blocks.
#[must_use]
pub fn decompile_pe(pe: &PeFile) -> UdFile {
    let module = build_pe_module(pe);
    let items = build_pe_items(pe);
    UdFile { module, items }
}

/// Convenience: build the AST and pretty-print it to canonical text.
#[must_use]
pub fn decompile_pe_to_text(pe: &PeFile) -> String {
    crate::ast::emit(&decompile_pe(pe))
}

#[allow(clippy::too_many_lines)]
fn build_pe_module(pe: &PeFile) -> Module {
    // Names match the convention `crate::arch::x86::codec::register`'s
    // factory uses (and what `build_module::build_module` emits for
    // ELF), so `resolve_arch_codec` finds the codec without extra
    // aliasing. "i386" not "x86" — the former is what the codec
    // factory and ELF EM_386 path use; emitting "x86" stranded
    // every 32-bit PE in the source round-trip path.
    let arch = match pe.coff.machine {
        IMAGE_FILE_MACHINE_I386 => "i386",
        IMAGE_FILE_MACHINE_AMD64 => "x86_64",
        _ => "unknown",
    };
    let bits = match pe.kind {
        PeKind::Pe32 => 32,
        PeKind::Pe32Plus => 64,
    };

    let coff_block = Value::Block(vec![
        field("machine", Value::Int(u64::from(pe.coff.machine))),
        field(
            "number_of_sections",
            Value::Int(u64::from(pe.coff.number_of_sections)),
        ),
        field(
            "time_date_stamp",
            Value::Int(u64::from(pe.coff.time_date_stamp)),
        ),
        field(
            "pointer_to_symbol_table",
            Value::Int(u64::from(pe.coff.pointer_to_symbol_table)),
        ),
        field(
            "number_of_symbols",
            Value::Int(u64::from(pe.coff.number_of_symbols)),
        ),
        field(
            "size_of_optional_header",
            Value::Int(u64::from(pe.coff.size_of_optional_header)),
        ),
        field(
            "characteristics",
            Value::Int(u64::from(pe.coff.characteristics)),
        ),
    ]);

    let sections_value = Value::List(
        pe.sections
            .iter()
            .enumerate()
            .map(|(i, s)| {
                let name = pe.section_name(i).unwrap_or_default().to_string();
                Value::Block(vec![
                    field("name", Value::String(name)),
                    field("name_raw", byte_list(&s.name)),
                    field("virtual_size", Value::Int(u64::from(s.virtual_size))),
                    field("virtual_address", Value::Int(u64::from(s.virtual_address))),
                    field(
                        "size_of_raw_data",
                        Value::Int(u64::from(s.size_of_raw_data)),
                    ),
                    field(
                        "pointer_to_raw_data",
                        Value::Int(u64::from(s.pointer_to_raw_data)),
                    ),
                    field(
                        "pointer_to_relocations",
                        Value::Int(u64::from(s.pointer_to_relocations)),
                    ),
                    field(
                        "pointer_to_linenumbers",
                        Value::Int(u64::from(s.pointer_to_linenumbers)),
                    ),
                    field(
                        "number_of_relocations",
                        Value::Int(u64::from(s.number_of_relocations)),
                    ),
                    field(
                        "number_of_linenumbers",
                        Value::Int(u64::from(s.number_of_linenumbers)),
                    ),
                    field("characteristics", Value::Int(u64::from(s.characteristics))),
                ])
            })
            .collect(),
    );

    let functions_value = Value::List(build_function_blocks(pe));

    let dos_block = build_dos_block(&pe.dos);
    let dos_stub_value = byte_list(&pe.dos_stub);
    let optional_value = pe
        .optional
        .as_ref()
        .map_or(Value::Block(Vec::new()), build_optional_block);
    let data_directories_value = Value::List(
        pe.data_directories
            .iter()
            .map(|dd| {
                Value::Block(vec![
                    field("virtual_address", Value::Int(u64::from(dd.virtual_address))),
                    field("size", Value::Int(u64::from(dd.size))),
                ])
            })
            .collect(),
    );

    let build = Value::Block(vec![
        field("e_lfanew", Value::Int(u64::from(pe.e_lfanew))),
        field("file_size", Value::Int(pe.file_size())),
        field("dos", dos_block),
        field("dos_stub", dos_stub_value),
        field("coff", coff_block),
        field("optional", optional_value),
        field("data_directories", data_directories_value),
        field("sections", sections_value),
        field("functions", functions_value),
        field("vtables", Value::List(scan_vtables(pe))),
    ]);

    Module {
        fields: vec![
            field("arch", Value::String(arch.into())),
            field("format", Value::String("pe".into())),
            field("bits", Value::Int(bits)),
            field("endian", Value::String("little".into())),
            field("build", build),
        ],
    }
}

/// Scan the read-only data sections for sequences of 4-byte
/// values that look like function pointers (each value lives
/// inside an executable section). A run of two or more such
/// values is reported as a candidate vtable.
///
/// Returns one `Value::Block({addr, count})` per vtable. The
/// addr is the section-relative VA of the first entry; count is
/// how many function-pointer entries the run contains. Used as
/// informational metadata in `@module.build.vtables` so the
/// reader can locate C++ virtual-function dispatch tables.
fn scan_vtables(pe: &PeFile) -> Vec<Value> {
    let mut out: Vec<Value> = Vec::new();
    let bits = match pe.kind {
        PeKind::Pe32 => 32,
        PeKind::Pe32Plus => 64,
    };
    let ptr_size = if bits == 64 { 8 } else { 4 };
    // Identify the executable sections' VA ranges. Code sections
    // are those whose IMAGE_SCN_MEM_EXECUTE (0x2000_0000) is set.
    let mut text_ranges: Vec<(u64, u64)> = Vec::new();
    for sh in &pe.sections {
        if sh.characteristics & 0x2000_0000 != 0 {
            let start = pe.image_base + u64::from(sh.virtual_address);
            let size = u64::from(sh.virtual_size.max(sh.size_of_raw_data));
            text_ranges.push((start, start + size));
        }
    }
    let in_text = |va: u64| text_ranges.iter().any(|(s, e)| va >= *s && va < *e);
    // Scan data sections (writable OR initialized-data) for
    // function-pointer runs.
    for (idx, sh) in pe.sections.iter().enumerate() {
        let is_data =
            sh.characteristics & 0x4000_0000 != 0 && sh.characteristics & 0x2000_0000 == 0;
        if !is_data {
            continue;
        }
        let Some(data) = pe.section_data(idx) else {
            continue;
        };
        let sec_base = pe.image_base + u64::from(sh.virtual_address);
        let mut i = 0usize;
        while i + ptr_size <= data.len() {
            let raw = &data[i..i + ptr_size];
            let val = if bits == 64 {
                u64::from_le_bytes(raw.try_into().unwrap_or([0; 8]))
            } else {
                u64::from(u32::from_le_bytes(raw[..4].try_into().unwrap_or([0; 4])))
            };
            if val != 0 && in_text(val) {
                let run_start = i;
                let mut count = 0usize;
                while i + ptr_size <= data.len() {
                    let raw = &data[i..i + ptr_size];
                    let val = if bits == 64 {
                        u64::from_le_bytes(raw.try_into().unwrap_or([0; 8]))
                    } else {
                        u64::from(u32::from_le_bytes(raw[..4].try_into().unwrap_or([0; 4])))
                    };
                    if val == 0 || !in_text(val) {
                        break;
                    }
                    count += 1;
                    i += ptr_size;
                }
                if count >= 2 {
                    out.push(Value::Block(vec![
                        field("addr", Value::Int(sec_base + run_start as u64)),
                        field("count", Value::Int(count as u64)),
                    ]));
                }
            } else {
                i += ptr_size;
            }
        }
    }
    out
}

/// Build the items list. Strategy: walk file-offset order, emit
/// `@raw` blocks for every contiguous byte range. Sections are
/// emitted as standalone `@raw` blocks (rather than nested under
/// `@section`) — the format lower path identifies them via the
/// section table in `@module.build.sections` rather than via
/// structural nesting.
///
/// Within a code section, the section's flat `@raw` is split by
/// COFF function boundaries: each detected function gets its own
/// `@raw` preceded by a `// fn <name> at 0x<rva>` comment.
/// Inter-function gaps (alignment, unknown content) get their own
/// `@raw` blocks. Round-trip is unchanged because the lower path
/// concatenates `@raw` blocks in offset order.
fn build_pe_items(pe: &PeFile) -> Vec<Item> {
    let bytes = pe.raw_bytes();
    let mut items: Vec<Item> = Vec::new();

    // Group functions by section index for fast lookup when we
    // emit each section's bytes.
    let funcs_by_section = group_functions_by_section(pe);

    // Collect structured byte regions in file-offset order. Each
    // region is `(start, end_exclusive, section_idx)`.
    let mut regions: Vec<(usize, usize, usize)> = Vec::new();
    for (idx, s) in pe.sections.iter().enumerate() {
        let start = s.pointer_to_raw_data as usize;
        let size = s.size_of_raw_data as usize;
        if size == 0 {
            continue; // uninitialised data has no on-disk presence
        }
        let end = start.saturating_add(size);
        if end > bytes.len() {
            continue; // skip out-of-range section data
        }
        regions.push((start, end, idx));
    }
    regions.sort_unstable_by_key(|(start, _, _)| *start);

    // The DOS header, DOS stub, COFF header, optional header,
    // data directories, and section table are all captured
    // structurally in `@module.build` and regenerated by the
    // PE lower path. Compute their end offset so the leading
    // @raw block starts past them — only the alignment padding
    // between the section table end and the first section's
    // raw data needs to ride along as bytes.
    let header_end = pe_header_region_end(pe);

    let mut cursor = header_end.min(bytes.len());
    for (start, end, sec_idx) in &regions {
        if *start > cursor {
            // Trailing alignment between section table and
            // first section's raw data. Small, often a few
            // hundred bytes for file-alignment.
            items.push(Item::Raw {
                addr: cursor as u64,
                bytes: bytes[cursor..*start].to_vec(),
            });
        }
        if let Some(funcs) = funcs_by_section.get(sec_idx) {
            emit_section_with_function_split(pe, *sec_idx, *start, *end, funcs, bytes, &mut items);
        } else {
            items.push(Item::Raw {
                addr: *start as u64,
                bytes: bytes[*start..*end].to_vec(),
            });
        }
        cursor = *end;
    }

    if cursor < bytes.len() {
        items.push(Item::Raw {
            addr: cursor as u64,
            bytes: bytes[cursor..].to_vec(),
        });
    }

    items
}

/// Function record local to this module: the COFF symbol's name plus
/// the function's offset within its section (the COFF symbol's
/// `value` field) and the RVA derived from the section's
/// `virtual_address`. We carry the RVA explicitly so the rendered
/// comment names the user-visible address rather than the file
/// offset.
struct PeFunctionRecord {
    name: String,
    section_offset: u32,
    rva: u32,
}

fn group_functions_by_section(
    pe: &PeFile,
) -> std::collections::HashMap<usize, Vec<PeFunctionRecord>> {
    let mut out: std::collections::HashMap<usize, Vec<PeFunctionRecord>> =
        std::collections::HashMap::new();
    for sym in pe.coff_symbols() {
        if !is_code_function(pe, &sym) {
            continue;
        }
        // is_code_function rejects section_number <= 0 already.
        #[allow(clippy::cast_sign_loss)]
        let idx = (sym.section_number - 1) as usize;
        let Some(sh) = pe.sections.get(idx) else {
            continue;
        };
        let rva = sh.virtual_address.wrapping_add(sym.value);
        out.entry(idx).or_default().push(PeFunctionRecord {
            name: sym.name,
            section_offset: sym.value,
            rva,
        });
    }
    // Supplement with optional-header entry point and Export
    // Address Table entries. This is the only function source for
    // stripped DLLs / EXEs.
    add_pe_entry_point(pe, &mut out);
    add_pe_exports(pe, &mut out);
    // Walk direct `call` instructions reachable from those entries
    // and treat every target as another function. Stripped PE has
    // no symbol table to lean on; the call graph is the only
    // remaining signal.
    add_pe_call_graph_targets(pe, &mut out);
    for v in out.values_mut() {
        v.sort_by_key(|f| f.section_offset);
        v.dedup_by(|a, b| a.section_offset == b.section_offset && a.name == b.name);
    }
    out
}

/// PE `IMAGE_FILE_DLL` characteristic bit (0x2000). When set, the
/// entry point names `DllMain`; otherwise it's a plain `_start` /
/// `EntryPoint`.
const IMAGE_FILE_DLL: u16 = 0x2000;

/// Locate the section containing `rva` and return `(section_idx,
/// rva - section.virtual_address)`. None if `rva` is in no section
/// (e.g. inside a NOBITS region or past the end of the image).
fn rva_to_section(pe: &PeFile, rva: u32) -> Option<(usize, u32)> {
    for (idx, sh) in pe.sections.iter().enumerate() {
        let start = sh.virtual_address;
        let size = sh.virtual_size.max(sh.size_of_raw_data);
        if let Some(end) = start.checked_add(size)
            && rva >= start
            && rva < end
        {
            return Some((idx, rva - start));
        }
    }
    None
}

fn add_pe_entry_point(
    pe: &PeFile,
    out: &mut std::collections::HashMap<usize, Vec<PeFunctionRecord>>,
) {
    let ep = pe.address_of_entry_point;
    if ep == 0 {
        return;
    }
    let Some((idx, off)) = rva_to_section(pe, ep) else {
        return;
    };
    let already = out.get(&idx).is_some_and(|v| v.iter().any(|f| f.rva == ep));
    if already {
        return;
    }
    let name = if pe.coff.characteristics & IMAGE_FILE_DLL != 0 {
        "DllMain".to_string()
    } else {
        "_start".to_string()
    };
    out.entry(idx).or_default().push(PeFunctionRecord {
        name,
        section_offset: off,
        rva: ep,
    });
}

fn add_pe_exports(pe: &PeFile, out: &mut std::collections::HashMap<usize, Vec<PeFunctionRecord>>) {
    for export in pe.exports() {
        let Some((idx, off)) = rva_to_section(pe, export.rva) else {
            continue;
        };
        let already = out
            .get(&idx)
            .is_some_and(|v| v.iter().any(|f| f.rva == export.rva));
        if already {
            continue;
        }
        let name = export_function_name(&export);
        out.entry(idx).or_default().push(PeFunctionRecord {
            name,
            section_offset: off,
            rva: export.rva,
        });
    }
}

/// Transitive call-graph walk for stripped PE: from every seed
/// already in `out`, decode linearly up to the next function-end
/// instruction (RET / unconditional jump) and record every direct
/// `call` target. Each discovered target becomes a new seed
/// (named `sub_<rva>`). Repeat until the worklist drains.
///
/// The walk only follows targets that land inside the same section
/// as the seed (typically `.text`), since cross-section targets
/// are usually imports or jump-table references rather than local
/// functions.
/// Cap per-function decode length so a function with no clear exit
/// (e.g. unreachable padding after a tail call) doesn't sweep the
/// whole section.
const MAX_FUNCTION_BYTES: usize = 65536;

fn add_pe_call_graph_targets(
    pe: &PeFile,
    out: &mut std::collections::HashMap<usize, Vec<PeFunctionRecord>>,
) {
    let bitness = match pe.coff.machine {
        IMAGE_FILE_MACHINE_I386 => Bitness::Bits32,
        IMAGE_FILE_MACHINE_AMD64 => Bitness::Bits64,
        _ => return,
    };

    // Track every RVA we've ever decided is a function so we don't
    // re-walk the same one (cycles via recursion would loop
    // otherwise). Seeded from whatever's already in `out`.
    let mut known: std::collections::HashSet<u32> = std::collections::HashSet::new();
    let mut worklist: Vec<u32> = Vec::new();
    for fns in out.values() {
        for f in fns {
            if known.insert(f.rva) {
                worklist.push(f.rva);
            }
        }
    }

    let raw = pe.raw_bytes();
    while let Some(rva) = worklist.pop() {
        let Some((sec_idx, _)) = rva_to_section(pe, rva) else {
            continue;
        };
        let Some(sec) = pe.sections.get(sec_idx) else {
            continue;
        };
        let Some(start_off) = pe.rva_to_file_offset(rva) else {
            continue;
        };
        let sec_raw_end_rva = sec.virtual_address.saturating_add(sec.size_of_raw_data);
        let in_section = (sec_raw_end_rva.saturating_sub(rva)) as usize;
        let read_len = in_section.min(MAX_FUNCTION_BYTES);
        let slice = &raw[start_off..start_off.saturating_add(read_len).min(raw.len())];
        let insns = crate::arch::x86::decode_tolerant(bitness, slice, u64::from(rva));
        if insns.is_empty() {
            continue;
        }
        // Build the CFG. This is what tells us "every instruction
        // reachable from `rva`" — including paths past early
        // returns, follow-the-conditional-branch paths, etc.
        let Ok(lifted) = lift_function(format!("seed_{rva:x}"), &insns) else {
            continue;
        };
        for block in &lifted.blocks {
            for ins in &block.insns {
                let Some(target_u64) = crate::arch::x86::direct_call_target(&ins.iced) else {
                    continue;
                };
                // The decoder's IP was set to `rva` (an RVA),
                // not `image_base + rva`, so iced's computed call
                // target is already an RVA. Just narrow to u32.
                let Ok(target_rva) = u32::try_from(target_u64) else {
                    continue;
                };
                let Some((tgt_sec, tgt_off)) = rva_to_section(pe, target_rva) else {
                    continue;
                };
                if tgt_sec != sec_idx {
                    continue;
                }
                if known.insert(target_rva) {
                    out.entry(tgt_sec).or_default().push(PeFunctionRecord {
                        name: format!("sub_{target_rva:x}"),
                        section_offset: tgt_off,
                        rva: target_rva,
                    });
                    worklist.push(target_rva);
                }
            }
        }
    }
}

fn export_function_name(export: &PeExport) -> String {
    export
        .name
        .clone()
        .unwrap_or_else(|| format!("Ord_{}", export.ordinal))
}

/// Emit one section whose contents are split by COFF function
/// boundaries. Each function gets a leading `// fn <name> at <rva>`
/// comment followed by an `@raw` covering its bytes; pre/inter/post-
/// function gaps (alignment, unknown content) get their own `@raw`
/// blocks so the byte coverage stays exhaustive.
fn emit_section_with_function_split(
    pe: &PeFile,
    sec_idx: usize,
    start: usize,
    end: usize,
    funcs: &[PeFunctionRecord],
    bytes: &[u8],
    items: &mut Vec<Item>,
) {
    let _ = &pe.sections[sec_idx]; // bounds check; structural fields used via section_name below
    let section_size = (end - start) as u32;

    // Emit leading gap before the first function.
    let first_off = funcs
        .first()
        .map_or(section_size, |f| f.section_offset.min(section_size));
    if first_off > 0 {
        let lo = start;
        let hi = start + first_off as usize;
        items.push(Item::Raw {
            addr: lo as u64,
            bytes: bytes[lo..hi].to_vec(),
        });
    }

    let bitness = match pe.coff.machine {
        IMAGE_FILE_MACHINE_I386 => Some(Bitness::Bits32),
        IMAGE_FILE_MACHINE_AMD64 => Some(Bitness::Bits64),
        _ => None,
    };
    let name_at = pe_name_at(pe);
    for (i, f) in funcs.iter().enumerate() {
        let off = f.section_offset.min(section_size);
        let next_off = funcs
            .get(i + 1)
            .map_or(section_size, |n| n.section_offset.min(section_size));
        if next_off <= off {
            continue; // zero-size or stacked symbols
        }
        let lo = start + off as usize;
        let hi = start + next_off as usize;
        let func_bytes = &bytes[lo..hi];

        // Try to lift the function body. Returns the fn item plus
        // an optional trailing `@raw` covering bytes the decoder
        // couldn't reach (jump tables, padding, data-in-code).
        // Falls back to a per-function `@raw` block on hard
        // failures (zero decoded bytes, unsupported machine type,
        // CFG construction failure).
        if let Some(bn) = bitness
            && let Some(emitted) =
                lift_pe_function(pe, &f.name, lo as u64, f.rva, bn, func_bytes, &name_at)
        {
            items.extend(emitted);
            continue;
        }
        let section_name = pe.section_name(sec_idx).unwrap_or_default();
        items.push(Item::Comment(format!(
            "fn {} at {section_name}+0x{off:x} (rva 0x{:x}, {} bytes)",
            f.name,
            f.rva,
            hi - lo,
        )));
        items.push(Item::Raw {
            addr: lo as u64,
            bytes: func_bytes.to_vec(),
        });
    }

    // Emit trailing gap after the last function.
    let last_end = funcs.last().map_or(0u32, |f| {
        // The last function's end is the next-symbol boundary,
        // which the loop above used as `section_size`. So the
        // trailing gap is empty unless the last symbol's offset
        // was past section_size (defensive).
        let off = f.section_offset.min(section_size);
        off.max(section_size)
    });
    if (last_end as usize) < (end - start) {
        let lo = start + last_end as usize;
        items.push(Item::Raw {
            addr: lo as u64,
            bytes: bytes[lo..end].to_vec(),
        });
    }
}

fn field(name: &str, value: Value) -> Field {
    Field {
        name: name.to_string(),
        value,
    }
}

fn byte_list(bs: &[u8]) -> Value {
    Value::List(bs.iter().map(|b| Value::Int(u64::from(*b))).collect())
}

/// File offset at which the PE skeleton (DOS header + DOS stub +
/// PE signature + COFF header + optional header + data
/// directories + section table) ends. Bytes from offset 0 up to
/// this point are fully covered by `@module.build` structured
/// fields, so the decompile path no longer emits an `@raw` for
/// them — the lower path reconstructs the bytes from the
/// structured fields via `PeFile::from_parts`.
fn pe_header_region_end(pe: &PeFile) -> usize {
    const PE_SIG_SIZE: usize = 4;
    const COFF_HEADER_SIZE: usize = 20;
    let opt_size = pe.coff.size_of_optional_header as usize;
    let pe_off = pe.e_lfanew as usize;
    let opt_off = pe_off + PE_SIG_SIZE + COFF_HEADER_SIZE;
    let sec_off = opt_off + opt_size;
    sec_off + pe.sections.len() * crate::format::pe::SECTION_HEADER_SIZE
}

fn build_dos_block(dos: &crate::format::pe::DosHeader) -> Value {
    Value::Block(vec![
        field("e_magic", byte_list(&dos.e_magic)),
        field("e_cblp", Value::Int(u64::from(dos.e_cblp))),
        field("e_cp", Value::Int(u64::from(dos.e_cp))),
        field("e_crlc", Value::Int(u64::from(dos.e_crlc))),
        field("e_cparhdr", Value::Int(u64::from(dos.e_cparhdr))),
        field("e_minalloc", Value::Int(u64::from(dos.e_minalloc))),
        field("e_maxalloc", Value::Int(u64::from(dos.e_maxalloc))),
        field("e_ss", Value::Int(u64::from(dos.e_ss))),
        field("e_sp", Value::Int(u64::from(dos.e_sp))),
        field("e_csum", Value::Int(u64::from(dos.e_csum))),
        field("e_ip", Value::Int(u64::from(dos.e_ip))),
        field("e_cs", Value::Int(u64::from(dos.e_cs))),
        field("e_lfarlc", Value::Int(u64::from(dos.e_lfarlc))),
        field("e_ovno", Value::Int(u64::from(dos.e_ovno))),
        field(
            "e_res",
            Value::List(
                dos.e_res
                    .iter()
                    .map(|n| Value::Int(u64::from(*n)))
                    .collect(),
            ),
        ),
        field("e_oemid", Value::Int(u64::from(dos.e_oemid))),
        field("e_oeminfo", Value::Int(u64::from(dos.e_oeminfo))),
        field(
            "e_res2",
            Value::List(
                dos.e_res2
                    .iter()
                    .map(|n| Value::Int(u64::from(*n)))
                    .collect(),
            ),
        ),
        field("e_lfanew", Value::Int(u64::from(dos.e_lfanew))),
    ])
}

fn build_optional_block(opt: &crate::format::pe::OptionalHeader) -> Value {
    Value::Block(vec![
        field("magic", Value::Int(u64::from(opt.magic))),
        field(
            "major_linker_version",
            Value::Int(u64::from(opt.major_linker_version)),
        ),
        field(
            "minor_linker_version",
            Value::Int(u64::from(opt.minor_linker_version)),
        ),
        field("size_of_code", Value::Int(u64::from(opt.size_of_code))),
        field(
            "size_of_initialized_data",
            Value::Int(u64::from(opt.size_of_initialized_data)),
        ),
        field(
            "size_of_uninitialized_data",
            Value::Int(u64::from(opt.size_of_uninitialized_data)),
        ),
        field(
            "address_of_entry_point",
            Value::Int(u64::from(opt.address_of_entry_point)),
        ),
        field("base_of_code", Value::Int(u64::from(opt.base_of_code))),
        field("base_of_data", Value::Int(u64::from(opt.base_of_data))),
        field("image_base", Value::Int(opt.image_base)),
        field(
            "section_alignment",
            Value::Int(u64::from(opt.section_alignment)),
        ),
        field("file_alignment", Value::Int(u64::from(opt.file_alignment))),
        field(
            "major_operating_system_version",
            Value::Int(u64::from(opt.major_operating_system_version)),
        ),
        field(
            "minor_operating_system_version",
            Value::Int(u64::from(opt.minor_operating_system_version)),
        ),
        field(
            "major_image_version",
            Value::Int(u64::from(opt.major_image_version)),
        ),
        field(
            "minor_image_version",
            Value::Int(u64::from(opt.minor_image_version)),
        ),
        field(
            "major_subsystem_version",
            Value::Int(u64::from(opt.major_subsystem_version)),
        ),
        field(
            "minor_subsystem_version",
            Value::Int(u64::from(opt.minor_subsystem_version)),
        ),
        field(
            "win32_version_value",
            Value::Int(u64::from(opt.win32_version_value)),
        ),
        field("size_of_image", Value::Int(u64::from(opt.size_of_image))),
        field(
            "size_of_headers",
            Value::Int(u64::from(opt.size_of_headers)),
        ),
        field("check_sum", Value::Int(u64::from(opt.check_sum))),
        field("subsystem", Value::Int(u64::from(opt.subsystem))),
        field(
            "dll_characteristics",
            Value::Int(u64::from(opt.dll_characteristics)),
        ),
        field(
            "size_of_stack_reserve",
            Value::Int(opt.size_of_stack_reserve),
        ),
        field("size_of_stack_commit", Value::Int(opt.size_of_stack_commit)),
        field("size_of_heap_reserve", Value::Int(opt.size_of_heap_reserve)),
        field("size_of_heap_commit", Value::Int(opt.size_of_heap_commit)),
        field("loader_flags", Value::Int(u64::from(opt.loader_flags))),
        field(
            "number_of_rva_and_sizes",
            Value::Int(u64::from(opt.number_of_rva_and_sizes)),
        ),
    ])
}

/// Build the `name_at: addr -> name` map that arch-x86's call-site
/// analyzer uses to render call targets.
///
/// Keys are mixed: COFF symbols are keyed by RVA (matching iced's
/// direct-call target after IP=RVA decoding), while IAT slots are
/// keyed by their absolute virtual address (matching what an
/// indirect `call dword ptr [VA]` operand carries in the encoded
/// instruction). The two key spaces don't overlap in practice — an
/// IAT slot's VA includes `image_base` (e.g. `0x1C201030` for our
/// reference DLL), while RVAs are small section-relative offsets.
fn pe_name_at(pe: &PeFile) -> HashMap<u64, String> {
    let mut out = HashMap::new();
    for sym in pe.coff_symbols() {
        if !is_code_function(pe, &sym) {
            continue;
        }
        // is_code_function rejects section_number <= 0
        #[allow(clippy::cast_sign_loss)]
        let idx = (sym.section_number - 1) as usize;
        let Some(sh) = pe.sections.get(idx) else {
            continue;
        };
        let rva = u64::from(sh.virtual_address.wrapping_add(sym.value));
        out.insert(rva, sym.name);
    }
    // Inject import-table entries keyed by IAT-slot VA. The
    // rendered name for an import is just its function name; the
    // DLL name is informational only and elided unless the same
    // function name is imported from multiple DLLs (rare).
    let mut name_count: HashMap<String, u32> = HashMap::new();
    for imp in pe.imports() {
        if let Some(name) = &imp.name {
            *name_count.entry(name.clone()).or_default() += 1;
        }
    }
    for imp in pe.imports() {
        let label = match (&imp.name, imp.ordinal) {
            (Some(name), _) => {
                if name_count.get(name).copied().unwrap_or(0) > 1 && !imp.dll_name.is_empty() {
                    // Strip the `.dll` suffix for the qualifier so
                    // `KERNEL32.dll!HeapAlloc` reads as
                    // `KERNEL32!HeapAlloc`.
                    let stem = imp
                        .dll_name
                        .strip_suffix(".dll")
                        .or_else(|| imp.dll_name.strip_suffix(".DLL"))
                        .unwrap_or(&imp.dll_name);
                    format!("{stem}!{name}")
                } else {
                    name.clone()
                }
            }
            (None, Some(ord)) => {
                let stem = imp
                    .dll_name
                    .strip_suffix(".dll")
                    .or_else(|| imp.dll_name.strip_suffix(".DLL"))
                    .unwrap_or(&imp.dll_name);
                format!("{stem}@{ord}")
            }
            (None, None) => continue,
        };
        out.insert(imp.iat_va, label);
    }
    out
}

/// Decode + lift + build one PE function's body as a structured
/// `FnDecl`. Returns `None` on any decoder rejection so the caller
/// can fall back to a per-function `@raw` block.
/// Lift one PE function, tolerating a decoder failure mid-stream.
///
/// Returns a list of items: a `Function` for the bytes the decoder
/// could reach, followed by an `@raw` for the trailing bytes it
/// couldn't (jump tables embedded after a `ret`, alignment padding,
/// or true data-in-code). Returns `None` when there's nothing to
/// lift — empty decode result or a CFG construction failure.
fn lift_pe_function(
    pe: &PeFile,
    name: &str,
    file_offset: u64,
    rva: u32,
    bitness: Bitness,
    func_bytes: &[u8],
    name_at: &HashMap<u64, String>,
) -> Option<Vec<Item>> {
    let insns = crate::arch::x86::decode_tolerant(bitness, func_bytes, u64::from(rva));
    if insns.is_empty() {
        return None;
    }
    let consumed: usize = insns.iter().map(|i| i.original_bytes.len()).sum();
    let lifted = lift_function(name.to_string(), &insns).ok()?;
    let fn_decl = build_function::build_function(&lifted, None, name_at, pe);
    let mut out = Vec::with_capacity(2);
    out.push(Item::Function(crate::ast::FnDecl {
        addr: Some(file_offset),
        name: name.to_string(),
        attrs: fn_decl.attrs,
        signature: fn_decl.signature,
        locals: fn_decl.locals,
        body: fn_decl.body,
    }));
    if consumed < func_bytes.len() {
        out.push(Item::Raw {
            addr: file_offset + consumed as u64,
            bytes: func_bytes[consumed..].to_vec(),
        });
    }
    Some(out)
}

/// `.ud` identifiers must start with an alpha character or `_` and
/// can contain `.` after that; COFF section-marker symbols (`.text`,
/// `.data`, etc.) start with `.` and would not parse back as
/// identifiers if we surfaced them as `fn` blocks. Filter them out
/// here before they reach the decompile output.
fn is_emittable_function_name(name: &str) -> bool {
    let mut chars = name.chars();
    let Some(first) = chars.next() else {
        return false;
    };
    if !(first == '_' || first.is_ascii_alphabetic()) {
        return false;
    }
    chars.all(|c| c == '_' || c == '.' || c.is_ascii_alphanumeric())
}

fn build_function_blocks(pe: &PeFile) -> Vec<Value> {
    pe.coff_symbols()
        .iter()
        .filter(|s| is_code_function(pe, s))
        .map(|s| {
            // section_number is 1-indexed and >0 here (filter rejects
            // ABS/DEBUG/UNDEF), so the i16 → usize cast is non-lossy.
            #[allow(clippy::cast_sign_loss)]
            let section_idx = (s.section_number - 1) as usize;
            let section_va = pe
                .sections
                .get(section_idx)
                .map_or(0u32, |sh| sh.virtual_address);
            let rva = section_va.wrapping_add(s.value);
            // Likewise the section_number fits in u16 once positive.
            #[allow(clippy::cast_sign_loss)]
            let section = s.section_number as u16;
            Value::Block(vec![
                field("name", Value::String(s.name.clone())),
                field("rva", Value::Int(u64::from(rva))),
                field("section", Value::Int(u64::from(section))),
                field("section_offset", Value::Int(u64::from(s.value))),
                field("storage_class", Value::Int(u64::from(s.storage_class))),
            ])
        })
        .collect()
}

/// True for COFF symbols that look like functions in code sections —
/// the candidates for later body lifting. Filters out absolute (`-1`),
/// debug (`-2`), and undefined (`0`) section numbers, plus
/// section-marker symbols whose name doesn't make a valid `.ud`
/// identifier (`.text`, `.data`, etc.).
fn is_code_function(pe: &PeFile, sym: &CoffSymbol) -> bool {
    if sym.section_number <= 0 {
        return false;
    }
    if !is_emittable_function_name(&sym.name) {
        return false;
    }
    // section_number > 0 here, so subtracting 1 stays non-negative
    // and the cast to usize is non-lossy.
    #[allow(clippy::cast_sign_loss)]
    let section_idx = (sym.section_number - 1) as usize;
    let Some(sh) = pe.sections.get(section_idx) else {
        return false;
    };
    // IMAGE_SCN_MEM_EXECUTE
    let is_executable = sh.characteristics & 0x2000_0000 != 0;
    if !is_executable {
        return false;
    }
    // Either the symbol's Type field marks it a function (DT_FCN
    // high nibble), or its storage class is EXTERNAL/STATIC and it
    // sits in a code section. mingw frequently leaves Type = 0 even
    // for entries it generated, so we accept both forms.
    if sym.is_function() {
        return true;
    }
    matches!(
        sym.storage_class,
        COFF_SYM_CLASS_EXTERNAL | COFF_SYM_CLASS_STATIC
    )
}