ud-cli 0.1.4

The `ud` command-line driver for the univdreams suite.
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
// `LRESULT` / `HRESULT` / Win32 IC* return codes inhabit the u32
// ↔ i32 boundary by design (the negative half encodes errors).
// Allow the cast at module level rather than peppering 14 inline
// attrs across the VfW handlers.
#![allow(clippy::cast_possible_wrap)]

use std::path::{Path, PathBuf};
use std::process::ExitCode;

use anyhow::Context;
use clap::{Parser, Subcommand};

#[derive(Parser, Debug)]
#[command(
    name = "ud",
    version,
    about = "univdreams: a universal compiler/decompiler suite",
    long_about = "Decompile binaries to a directive-rich C-like source language and \
                  recompile to byte-identical binaries."
)]
struct Cli {
    #[command(subcommand)]
    command: Command,
}

#[derive(Subcommand, Debug)]
enum Command {
    /// Run the full pipeline (decompile then compile) and verify byte-equality
    /// with the input.
    ///
    /// Without `--through-source`, routes through `ud-format-elf`'s
    /// parse + write-to-vec — defends the format-level round-trip.
    ///
    /// With `--through-source`, routes through the full source pipeline:
    /// decompile → emit → parse → lower_to_elf. Surfaces verify-asm
    /// warnings and a byte-diff offset when the result diverges; never
    /// fails on warnings, only on hard pipeline errors.
    Roundtrip {
        /// Input binary.
        input: PathBuf,

        /// Where to write the rebuilt binary. Defaults to `<input>.rebuilt`.
        #[arg(long)]
        out: Option<PathBuf>,

        /// Route through the source language (decompile → text → parse →
        /// lower_to_elf) instead of the format-level path.
        #[arg(long)]
        through_source: bool,
    },

    /// Decompile a binary to `.ud` source.
    ///
    /// v0 emits one `fn` block per discovered function with `@asm("…")`
    /// lines for every instruction. Padding between functions and
    /// non-text sections aren't represented yet.
    Decompile {
        /// Input binary.
        input: PathBuf,

        /// Where to write the `.ud` source. Defaults to stdout.
        #[arg(short, long)]
        out: Option<PathBuf>,
    },

    /// Verify a `.ud` source file: parse, then check every `@asm`
    /// line's text against the canonical form for its pinned bytes.
    /// Warnings go to stderr; the exit code is non-zero only on
    /// parse errors, not on warnings.
    Verify {
        /// `.ud` source file.
        input: PathBuf,
    },

    /// Compile a `.ud` source file back to a binary. Dispatches on
    /// the `@module.format` field — `"elf"` → ELF, `"pe"` → PE,
    /// `"macho"` → Mach-O, `"raw"` → raw image.
    ///
    /// Editing the source between decompile and compile is the
    /// supported workflow: PC-relative encoders (jmp, jcc, call,
    /// switch) re-resolve at lower time so moving a function or
    /// growing its body produces a working binary.
    Compile {
        /// `.ud` source file.
        input: PathBuf,

        /// Where to write the rebuilt binary. Defaults to
        /// `<input>.bin`.
        #[arg(short, long)]
        out: Option<PathBuf>,
    },

    /// Run a binary inside the bounded i386 emulator and report
    /// what it does — Win32 calls, code coverage, traps. Treats
    /// the input as untrusted (it's the whole point of a
    /// sandboxed run) but inspects the structured execution
    /// trace, not the raw output. Today supports PE32 DLLs;
    /// the run drives `DllMain(PROCESS_ATTACH)` and reports
    /// every Win32 API the codec touched plus a coverage
    /// summary.
    Analyze {
        /// PE32 DLL (or DLL-shaped binary) to analyse.
        input: PathBuf,

        /// Cap the run at this many guest instructions.
        /// `DllMain` of a CRT-driven codec usually fits in a
        /// few million; the cap is just a safety net for
        /// adversarial samples that loop.
        #[arg(long, default_value_t = 5_000_000)]
        max_instructions: u64,

        /// Emit a JSON report on stdout instead of the
        /// human-readable summary. Suitable for piping into
        /// downstream analysis tooling.
        #[arg(long)]
        json: bool,
    },

    /// Video for Windows codec tools — drive a codec DLL
    /// through the VfW `IC*` pipeline inside the sandbox.
    /// See `ud vfw --help` for the per-command list.
    Vfw {
        #[command(subcommand)]
        command: VfwCommand,
    },
}

#[derive(Subcommand, Debug)]
enum VfwCommand {
    /// Load a codec DLL + DllMain + DRV_OPEN + ICGetInfo +
    /// ICDecompressQuery (RGB24 default). Quick sanity check
    /// that the codec accepts a reasonable BIH pair.
    Probe {
        /// Codec DLL.
        dll: PathBuf,

        /// FourCC handler override (defaults to the
        /// filename-based heuristic).
        #[arg(long = "fcc-handler", value_name = "FCC")]
        fcc_handler: Option<String>,

        /// Probe-test output pixel format. RGB24 is the
        /// VfW lingua franca and the format every decoder
        /// is expected to support.
        #[arg(long = "pix-format", value_enum, default_value_t = PixFormat::Rgb24)]
        pix_format: PixFormat,

        /// Test frame width (used for the probe BIH only;
        /// the codec usually doesn't care at this stage).
        #[arg(long, default_value_t = 320)]
        width: u32,

        /// Test frame height.
        #[arg(long, default_value_t = 240)]
        height: u32,

        /// Cap the run at this many guest instructions.
        #[arg(long, default_value_t = 100_000_000)]
        max_instructions: u64,
    },

    /// Drive `ICDecompress` on a codec bitstream-only frame:
    /// load the codec DLL, run `DllMain(DLL_PROCESS_ATTACH)`,
    /// open the codec via `ICOpen`, run the full
    /// `ICDecompressQuery → Begin → Decompress → End → Close`
    /// sequence, and write the decoded frame to the output file.
    Decode {
        /// Codec DLL.
        dll: PathBuf,

        /// Raw codec frame (no container — extract from any
        /// AVI / MOV wrapper beforehand).
        #[arg(long, value_name = "FILE")]
        input: PathBuf,

        /// Output frame width (pixels).
        #[arg(long)]
        width: u32,

        /// Output frame height (pixels).
        #[arg(long)]
        height: u32,

        /// FourCC handler override (`MP43`, `IV31`, `cvid`, …).
        /// Defaults: derived from the DLL filename.
        #[arg(long = "fcc-handler", value_name = "FCC")]
        fcc_handler: Option<String>,

        /// Output pixel format.
        #[arg(long = "pix-format", value_enum, default_value_t = PixFormat::Rgb24)]
        pix_format: PixFormat,

        /// Write decoded frame here. Defaults to stdout.
        #[arg(long, value_name = "FILE")]
        output: Option<PathBuf>,

        /// Cap the run at this many guest instructions.
        #[arg(long, default_value_t = 100_000_000)]
        max_instructions: u64,
    },

    /// Drive `ICCompress` on uncompressed pixel input: load
    /// the codec DLL, run `DllMain`, open the codec in
    /// compress mode, query / begin / compress / end / close.
    /// Outputs the encoded codec bitstream.
    Encode {
        /// Codec DLL.
        dll: PathBuf,

        /// Raw uncompressed pixel input (no header — bytes
        /// only). Required.
        #[arg(long, value_name = "FILE")]
        input: PathBuf,

        /// Input frame width (pixels).
        #[arg(long)]
        width: u32,

        /// Input frame height (pixels).
        #[arg(long)]
        height: u32,

        /// FourCC handler override.
        #[arg(long = "fcc-handler", value_name = "FCC")]
        fcc_handler: Option<String>,

        /// Uncompressed-input pixel format.
        #[arg(long = "input-format", value_enum, default_value_t = InputFormat::Bgr24)]
        input_format: InputFormat,

        /// Encoder quality (VfW convention, `0..=10000`).
        #[arg(long, default_value_t = 5000)]
        quality: u32,

        /// Request a keyframe (sets `ICCOMPRESS_KEYFRAME`).
        #[arg(long, default_value_t = true, action = clap::ArgAction::Set)]
        keyframe: bool,

        /// Write encoded frame here. Defaults to stdout.
        #[arg(long, value_name = "FILE")]
        output: Option<PathBuf>,

        /// Cap the run at this many guest instructions.
        #[arg(long, default_value_t = 100_000_000)]
        max_instructions: u64,
    },
}

#[derive(Copy, Clone, Debug, PartialEq, Eq, clap::ValueEnum)]
enum PixFormat {
    Rgb24,
    Rgb32,
    Yuv,
}

impl PixFormat {
    fn bi_bit_count(self) -> u16 {
        match self {
            PixFormat::Rgb24 => 24,
            PixFormat::Rgb32 => 32,
            PixFormat::Yuv => 16,
        }
    }
    fn bi_compression(self) -> [u8; 4] {
        match self {
            PixFormat::Rgb24 | PixFormat::Rgb32 => [0; 4],
            PixFormat::Yuv => *b"YUY2",
        }
    }
    fn bytes_per_pixel(self) -> u32 {
        match self {
            PixFormat::Rgb24 => 3,
            PixFormat::Rgb32 => 4,
            PixFormat::Yuv => 2,
        }
    }
}

#[derive(Copy, Clone, Debug, PartialEq, Eq, clap::ValueEnum)]
enum InputFormat {
    Bgr24,
    Bgr32,
    Yv12,
    I420,
    Yuy2,
}

impl InputFormat {
    fn bi_bit_count(self) -> u16 {
        match self {
            InputFormat::Bgr24 => 24,
            InputFormat::Bgr32 => 32,
            InputFormat::Yv12 | InputFormat::I420 => 12,
            InputFormat::Yuy2 => 16,
        }
    }
    fn bi_compression(self) -> [u8; 4] {
        match self {
            InputFormat::Bgr24 | InputFormat::Bgr32 => [0; 4],
            InputFormat::Yv12 => *b"YV12",
            InputFormat::I420 => *b"I420",
            InputFormat::Yuy2 => *b"YUY2",
        }
    }
    fn frame_bytes(self, width: u32, height: u32) -> u32 {
        let pixels = width.saturating_mul(height);
        match self {
            InputFormat::Bgr24 => pixels * 3,
            InputFormat::Bgr32 => pixels * 4,
            InputFormat::Yv12 | InputFormat::I420 => pixels * 3 / 2,
            InputFormat::Yuy2 => pixels * 2,
        }
    }
}

fn main() -> ExitCode {
    let cli = Cli::parse();
    match run(cli) {
        Ok(()) => ExitCode::SUCCESS,
        Err(err) => {
            eprintln!("ud: {err:#}");
            ExitCode::FAILURE
        }
    }
}

#[allow(clippy::too_many_lines)]
fn run(cli: Cli) -> anyhow::Result<()> {
    match cli.command {
        Command::Roundtrip {
            input,
            out,
            through_source,
        } => {
            let output = out.unwrap_or_else(|| {
                let mut p = input.clone().into_os_string();
                p.push(".rebuilt");
                PathBuf::from(p)
            });
            if through_source {
                let report =
                    ud_cli::roundtrip_through_source(&input, &output).with_context(|| {
                        format!(
                            "source round-trip from {} to {}",
                            input.display(),
                            output.display()
                        )
                    })?;
                for w in &report.warnings {
                    eprintln!("warning: {}", format_warning(w));
                }
                if !report.warnings.is_empty() {
                    eprintln!("({} verify warning(s))", report.warnings.len());
                }
                if report.byte_identical {
                    println!(
                        "source round-trip ok: {} == {} ({} bytes)",
                        input.display(),
                        output.display(),
                        report.input_len,
                    );
                } else {
                    let offset = report
                        .first_diff_offset
                        .map_or("?".into(), |o| format!("0x{o:x}"));
                    println!(
                        "source round-trip differs: {} != {} (input {} bytes, output {} bytes; first diff at {})",
                        input.display(),
                        output.display(),
                        report.input_len,
                        report.output_len,
                        offset,
                    );
                    if let Some(ctx) = &report.diff_context {
                        eprintln!(
                            "input  @ 0x{:x}: {}",
                            ctx.window_start,
                            hex_window(&ctx.input_window)
                        );
                        eprintln!(
                            "output @ 0x{:x}: {}",
                            ctx.window_start,
                            hex_window(&ctx.output_window)
                        );
                    }
                }
                Ok(())
            } else {
                ud_cli::roundtrip(&input, &output).with_context(|| {
                    format!(
                        "round-trip from {} to {}",
                        input.display(),
                        output.display()
                    )
                })?;
                println!("round-trip ok: {} == {}", input.display(), output.display());
                Ok(())
            }
        }
        Command::Decompile { input, out } => {
            let bytes =
                std::fs::read(&input).with_context(|| format!("read {}", input.display()))?;
            let source = if ud_format::elf::is_elf64_le(&bytes) {
                let elf = ud_format::elf::Elf64File::parse(&bytes)
                    .with_context(|| format!("parse {} as ELF", input.display()))?;
                ud_translate::decompile::decompile_to_text(&elf)
                    .with_context(|| format!("decompile {}", input.display()))?
            } else if ud_format::pe::is_pe(&bytes) {
                let pe = ud_format::pe::PeFile::parse(&bytes)
                    .with_context(|| format!("parse {} as PE", input.display()))?;
                ud_translate::decompile::decompile_pe_to_text(&pe)
            } else if ud_format::macho::is_macho64(&bytes) {
                let macho = ud_format::macho::MachoFile::parse(&bytes)
                    .with_context(|| format!("parse {} as Mach-O", input.display()))?;
                ud_translate::decompile::decompile_macho_to_text(&macho)
            } else if let Some(load_addr) = ud_cli::raw_6502_load_addr(&bytes) {
                let image = ud_format::raw::RawImage::new(bytes, load_addr);
                ud_translate::decompile::decompile_raw_6502_to_text(&image)
                    .with_context(|| format!("decompile {} as 6502 raw", input.display()))?
            } else {
                anyhow::bail!(
                    "unrecognised binary format: {} (expected ELF, PE, Mach-O, or 6502 raw image)",
                    input.display()
                );
            };
            if let Some(path) = out {
                std::fs::write(&path, source)
                    .with_context(|| format!("write {}", path.display()))?;
            } else {
                use std::io::Write as _;
                std::io::stdout().write_all(source.as_bytes())?;
            }
            Ok(())
        }
        Command::Verify { input } => {
            let text = std::fs::read_to_string(&input)
                .with_context(|| format!("read {}", input.display()))?;
            let ast = ud_translate::compile::parse(&text)
                .with_context(|| format!("parse {}", input.display()))?;
            let warnings = ud_translate::compile::verify_asm(&ast);
            if warnings.is_empty() {
                println!(
                    "ok: {} ({} item{})",
                    input.display(),
                    ast.items.len(),
                    if ast.items.len() == 1 { "" } else { "s" }
                );
                return Ok(());
            }
            for w in &warnings {
                eprintln!("{}", format_warning(w));
            }
            eprintln!("{} warning(s) in {}", warnings.len(), input.display());
            Ok(())
        }
        Command::Compile { input, out } => {
            let output = out.unwrap_or_else(|| {
                let mut p = input.clone().into_os_string();
                p.push(".bin");
                PathBuf::from(p)
            });
            let text = std::fs::read_to_string(&input)
                .with_context(|| format!("read {}", input.display()))?;
            let ast = ud_translate::compile::parse(&text)
                .with_context(|| format!("parse {}", input.display()))?;
            let format = ast
                .module
                .fields
                .iter()
                .find(|f| f.name == "format")
                .and_then(|f| match &f.value {
                    ud_ast::Value::String(s) => Some(s.clone()),
                    _ => None,
                })
                .ok_or_else(|| {
                    anyhow::anyhow!("`@module.format` is missing — expected \"elf\", \"pe\", \"macho\", or \"raw\"")
                })?;
            let bytes = match format.as_str() {
                "elf" => ud_translate::compile::lower_to_elf(&ast)
                    .with_context(|| format!("lower {} to ELF", input.display()))?,
                "pe" => ud_translate::compile::lower_to_pe(&ast)
                    .with_context(|| format!("lower {} to PE", input.display()))?,
                "macho" => ud_translate::compile::lower_to_macho(&ast)
                    .with_context(|| format!("lower {} to Mach-O", input.display()))?,
                "raw" => ud_translate::compile::lower_to_raw(&ast)
                    .with_context(|| format!("lower {} to raw", input.display()))?,
                other => anyhow::bail!(
                    "unsupported `@module.format` value {other:?} (expected \"elf\", \"pe\", \"macho\", or \"raw\")"
                ),
            };
            std::fs::write(&output, &bytes)
                .with_context(|| format!("write {}", output.display()))?;
            println!(
                "compiled: {}{} ({} bytes, format: {})",
                input.display(),
                output.display(),
                bytes.len(),
                format,
            );
            Ok(())
        }
        Command::Analyze {
            input,
            max_instructions,
            json,
        } => analyze(&input, max_instructions, json),
        Command::Vfw { command } => match command {
            VfwCommand::Probe {
                dll,
                fcc_handler,
                pix_format,
                width,
                height,
                max_instructions,
            } => vfw_probe(
                &dll,
                fcc_handler.as_deref(),
                pix_format,
                width,
                height,
                max_instructions,
            ),
            VfwCommand::Decode {
                dll,
                input,
                width,
                height,
                fcc_handler,
                pix_format,
                output,
                max_instructions,
            } => decode_cmd(
                &dll,
                &input,
                width,
                height,
                fcc_handler.as_deref(),
                pix_format,
                output.as_deref(),
                max_instructions,
            ),
            VfwCommand::Encode {
                dll,
                input,
                width,
                height,
                fcc_handler,
                input_format,
                quality,
                keyframe,
                output,
                max_instructions,
            } => encode_cmd(
                &dll,
                &input,
                width,
                height,
                fcc_handler.as_deref(),
                input_format,
                quality,
                keyframe,
                output.as_deref(),
                max_instructions,
            ),
        },
    }
}

fn fourcc_to_u32(s: &str) -> u32 {
    let mut b = [b' '; 4];
    for (i, c) in s.bytes().take(4).enumerate() {
        b[i] = c;
    }
    u32::from_le_bytes(b)
}

fn derive_default_fcc(p: &Path) -> String {
    let stem = p
        .file_stem()
        .map(|s| s.to_string_lossy().to_ascii_uppercase())
        .unwrap_or_default();
    if stem.contains("IR32") {
        "IV31".into()
    } else if stem.contains("IR41") {
        "IV41".into()
    } else if stem.contains("IR50") {
        "IV50".into()
    } else if stem.contains("CVID") || stem.contains("ICCVID") {
        "cvid".into()
    } else if stem.contains("MPG4C32") || stem.contains("MPG4") {
        "MP43".into()
    } else {
        "IV31".into()
    }
}

const ICMODE_DECOMPRESS: u32 = 1;
const ICMODE_COMPRESS: u32 = 2;
const ICCOMPRESS_KEYFRAME: u32 = 0x0000_0001;

#[allow(clippy::too_many_lines)]
fn vfw_probe(
    dll_path: &Path,
    fcc_handler: Option<&str>,
    pix_format: PixFormat,
    width: u32,
    height: u32,
    max_instructions: u64,
) -> anyhow::Result<()> {
    let dll_bytes =
        std::fs::read(dll_path).with_context(|| format!("reading {}", dll_path.display()))?;
    let dll_name = dll_path
        .file_name()
        .map_or_else(|| "codec.dll".into(), |n| n.to_string_lossy().into_owned());

    let mut sandbox = ud_emulator::Sandbox::new();
    sandbox.host.instruction_budget = Some(max_instructions);
    sandbox.host.trace_stubs = true;

    let img = sandbox
        .load(&dll_name, &dll_bytes)
        .with_context(|| format!("load {}", dll_path.display()))?;
    let _ = sandbox
        .call_dll_main(&img, ud_emulator::DLL_PROCESS_ATTACH)
        .with_context(|| "DllMain")?;
    sandbox
        .install_codec(&img)
        .with_context(|| "install_codec")?;

    let fcc = fcc_handler.map_or_else(|| derive_default_fcc(dll_path), str::to_owned);
    let fcc_type = u32::from_le_bytes(*b"VIDC");
    let fcc_handler_u32 = fourcc_to_u32(&fcc);

    let hic = sandbox
        .ic_open(fcc_type, fcc_handler_u32, ICMODE_DECOMPRESS)
        .context("ICOpen(ICMODE_DECOMPRESS)")?;
    if hic == 0 {
        anyhow::bail!("codec refused DRV_OPEN");
    }
    println!(
        "[probe] loaded {} (image_base 0x{:x})",
        dll_path.display(),
        img.image_base
    );
    println!("[probe] HIC = {hic}; fcc_handler = {fcc:?}");

    // ICGetInfo: codec metadata.
    match sandbox.ic_get_info(hic, 568) {
        Ok(info) => {
            // ICINFO layout: u32 dwSize, u32 fccType, u32 fccHandler,
            //   u32 dwFlags, u32 dwVersion, u32 dwVersionICM, then
            //   szName (utf-16) @ offset 24, szDescription @ offset 88.
            let read_u32 = |off: usize| -> u32 {
                if off + 4 <= info.len() {
                    u32::from_le_bytes(info[off..off + 4].try_into().unwrap_or([0; 4]))
                } else {
                    0
                }
            };
            let read_utf16 = |off: usize, max_chars: usize| -> String {
                let mut out = String::new();
                for i in 0..max_chars {
                    let o = off + i * 2;
                    if o + 2 > info.len() {
                        break;
                    }
                    let c = u16::from_le_bytes([info[o], info[o + 1]]);
                    if c == 0 {
                        break;
                    }
                    if let Some(ch) = char::from_u32(u32::from(c)) {
                        out.push(ch);
                    }
                }
                out
            };
            let fcc_type_bytes = read_u32(4).to_le_bytes();
            let fcc_handler_bytes = read_u32(8).to_le_bytes();
            let flags = read_u32(12);
            let version = read_u32(16);
            let version_icm = read_u32(20);
            let name = read_utf16(24, 16);
            let desc = read_utf16(24 + 32, 128);
            println!("[probe] ICINFO:");
            println!(
                "  fccType      = {:?}",
                std::str::from_utf8(&fcc_type_bytes).unwrap_or("?")
            );
            println!(
                "  fccHandler   = {:?}",
                std::str::from_utf8(&fcc_handler_bytes).unwrap_or("?")
            );
            println!("  dwFlags      = 0x{flags:08x}");
            println!("  dwVersion    = 0x{version:08x}");
            println!("  dwVersionICM = 0x{version_icm:08x}");
            println!("  szName       = {name:?}");
            println!("  szDescription= {desc:?}");
        }
        Err(e) => {
            println!("[probe] ICGetInfo failed: {e}");
        }
    }

    // ICDecompressQuery with an RGB24 default.
    let in_bih = ud_emulator::Bih {
        bi_size: 40,
        width: width as i32,
        height: height as i32,
        planes: 1,
        bit_count: 24,
        compression: fcc_handler_u32.to_le_bytes(),
        size_image: 0,
        ..ud_emulator::Bih::default()
    };
    let out_bih = ud_emulator::Bih {
        bi_size: 40,
        width: width as i32,
        height: height as i32,
        planes: 1,
        bit_count: pix_format.bi_bit_count(),
        compression: pix_format.bi_compression(),
        size_image: width * height * pix_format.bytes_per_pixel(),
        ..ud_emulator::Bih::default()
    };
    match sandbox.ic_decompress_query(hic, &in_bih, Some(&out_bih)) {
        Ok(q) => println!(
            "[probe] ICDecompressQuery({}x{} {:?}{:?}) = {} (0 = ICERR_OK)",
            width, height, &fcc, pix_format, q as i32
        ),
        Err(e) => println!("[probe] ICDecompressQuery failed: {e}"),
    }

    let _ = sandbox.ic_close(hic);
    println!();
    println!(
        "[probe] Win32 calls: {}; instructions executed: {}",
        sandbox.host.stub_calls.len(),
        sandbox.host.instructions_executed
    );
    Ok(())
}

#[allow(clippy::too_many_arguments)]
#[allow(clippy::too_many_lines)]
fn decode_cmd(
    dll_path: &Path,
    input: &Path,
    width: u32,
    height: u32,
    fcc_handler: Option<&str>,
    pix_format: PixFormat,
    output: Option<&Path>,
    max_instructions: u64,
) -> anyhow::Result<()> {
    let dll_bytes =
        std::fs::read(dll_path).with_context(|| format!("reading {}", dll_path.display()))?;
    let dll_name = dll_path
        .file_name()
        .map_or_else(|| "codec.dll".into(), |n| n.to_string_lossy().into_owned());
    let frame =
        std::fs::read(input).with_context(|| format!("reading frame {}", input.display()))?;

    let mut sandbox = ud_emulator::Sandbox::new();
    sandbox.host.instruction_budget = Some(max_instructions);

    let img = sandbox
        .load(&dll_name, &dll_bytes)
        .with_context(|| format!("load {}", dll_path.display()))?;
    let _ = sandbox
        .call_dll_main(&img, ud_emulator::DLL_PROCESS_ATTACH)
        .with_context(|| "DllMain")?;
    sandbox
        .install_codec(&img)
        .with_context(|| "install_codec")?;

    let fcc = fcc_handler.map_or_else(|| derive_default_fcc(dll_path), str::to_owned);
    let fcc_type = u32::from_le_bytes(*b"VIDC");
    let fcc_handler_u32 = fourcc_to_u32(&fcc);

    let in_bih = ud_emulator::Bih {
        bi_size: 40,
        width: width as i32,
        height: height as i32,
        planes: 1,
        bit_count: 24,
        compression: fcc_handler_u32.to_le_bytes(),
        size_image: u32::try_from(frame.len()).unwrap_or(u32::MAX),
        ..ud_emulator::Bih::default()
    };
    let out_bih = ud_emulator::Bih {
        bi_size: 40,
        width: width as i32,
        height: height as i32,
        planes: 1,
        bit_count: pix_format.bi_bit_count(),
        compression: pix_format.bi_compression(),
        size_image: width * height * pix_format.bytes_per_pixel(),
        ..ud_emulator::Bih::default()
    };

    let hic = sandbox
        .ic_open(fcc_type, fcc_handler_u32, ICMODE_DECOMPRESS)
        .context("ICOpen(ICMODE_DECOMPRESS)")?;
    if hic == 0 {
        anyhow::bail!("codec refused DRV_OPEN");
    }
    eprintln!("[decode] HIC = {hic}; fcc_handler = {fcc:?}");

    let q = sandbox
        .ic_decompress_query(hic, &in_bih, Some(&out_bih))
        .context("ICDecompressQuery")?;
    eprintln!("[decode] ICDecompressQuery = {} (0 = ICERR_OK)", q as i32);

    if (q as i32) != 0 {
        anyhow::bail!("codec rejected the in/out BIH pair");
    }

    let _ = sandbox.ic_decompress_begin(hic, &in_bih, &out_bih);
    let out_capacity = width * height * pix_format.bytes_per_pixel();
    let (rc, decoded) = sandbox
        .ic_decompress(hic, 0, &in_bih, &frame, &out_bih, out_capacity)
        .context("ICDecompress")?;
    eprintln!(
        "[decode] ICDecompress = {} (output {} bytes)",
        rc as i32,
        decoded.len()
    );

    if let Some(path) = output {
        std::fs::write(path, &decoded)
            .with_context(|| format!("writing output {}", path.display()))?;
        eprintln!(
            "[decode] wrote {} bytes to {}",
            decoded.len(),
            path.display()
        );
    } else {
        use std::io::Write as _;
        std::io::stdout().write_all(&decoded)?;
    }

    let _ = sandbox.ic_decompress_end(hic);
    let _ = sandbox.ic_close(hic);
    Ok(())
}

#[allow(clippy::too_many_arguments)]
#[allow(clippy::too_many_lines)]
fn encode_cmd(
    dll_path: &Path,
    input: &Path,
    width: u32,
    height: u32,
    fcc_handler: Option<&str>,
    input_format: InputFormat,
    quality: u32,
    keyframe: bool,
    output: Option<&Path>,
    max_instructions: u64,
) -> anyhow::Result<()> {
    let dll_bytes =
        std::fs::read(dll_path).with_context(|| format!("reading {}", dll_path.display()))?;
    let dll_name = dll_path
        .file_name()
        .map_or_else(|| "codec.dll".into(), |n| n.to_string_lossy().into_owned());

    let frame =
        std::fs::read(input).with_context(|| format!("reading input frame {}", input.display()))?;
    let expected_frame_bytes = input_format.frame_bytes(width, height) as usize;
    if frame.len() < expected_frame_bytes {
        anyhow::bail!(
            "input frame is {} bytes but {}x{} {:?} expects {} bytes",
            frame.len(),
            width,
            height,
            input_format,
            expected_frame_bytes
        );
    }

    let mut sandbox = ud_emulator::Sandbox::new();
    sandbox.host.instruction_budget = Some(max_instructions);

    let img = sandbox
        .load(&dll_name, &dll_bytes)
        .with_context(|| format!("load {}", dll_path.display()))?;
    let _ = sandbox
        .call_dll_main(&img, ud_emulator::DLL_PROCESS_ATTACH)
        .with_context(|| "DllMain")?;
    sandbox
        .install_codec(&img)
        .with_context(|| "install_codec")?;

    let fcc = fcc_handler.map_or_else(|| derive_default_fcc(dll_path), str::to_owned);
    let fcc_type = u32::from_le_bytes(*b"VIDC");
    let fcc_handler_u32 = fourcc_to_u32(&fcc);

    let in_bih = ud_emulator::Bih {
        bi_size: 40,
        width: width as i32,
        height: height as i32,
        planes: 1,
        bit_count: input_format.bi_bit_count(),
        compression: input_format.bi_compression(),
        size_image: input_format.frame_bytes(width, height),
        ..ud_emulator::Bih::default()
    };

    let hic = sandbox
        .ic_open(fcc_type, fcc_handler_u32, ICMODE_COMPRESS)
        .context("ICOpen(ICMODE_COMPRESS)")?;
    if hic == 0 {
        anyhow::bail!("codec refused DRV_OPEN(COMPRESS)");
    }
    eprintln!("[encode] HIC = {hic}; fcc_handler = {fcc:?}");

    let (_, out_bih) = sandbox
        .ic_compress_get_format(hic, &in_bih)
        .context("ICCompressGetFormat")?;
    eprintln!(
        "[encode] codec picked output: bit_count={} compression={:?} size_image={}",
        out_bih.bit_count, out_bih.compression, out_bih.size_image
    );

    let q = sandbox
        .ic_compress_query(hic, &in_bih, Some(&out_bih))
        .context("ICCompressQuery")?;
    eprintln!("[encode] ICCompressQuery = {} (0 = ICERR_OK)", q as i32);
    if (q as i32) != 0 {
        anyhow::bail!("codec rejected the input/output BIH pair");
    }

    let cap = sandbox
        .ic_compress_get_size(hic, &in_bih, &out_bih)
        .context("ICCompressGetSize")?;
    eprintln!("[encode] ICCompressGetSize = {cap} bytes");

    let _ = sandbox.ic_compress_begin(hic, &in_bih, &out_bih);
    let flags = if keyframe { ICCOMPRESS_KEYFRAME } else { 0 };
    let frame_slice = &frame[..expected_frame_bytes];
    let result = sandbox
        .ic_compress(
            hic,
            flags,
            &in_bih,
            frame_slice,
            &out_bih,
            cap,
            0, // ckid
            0, // frame_num
            0, // frame_size_limit
            quality,
            None, // prev_bih
            None, // prev_bytes
        )
        .context("ICCompress")?;
    eprintln!(
        "[encode] ICCompress = {} (output {} bytes, output_bih.size_image={})",
        result.lresult as i32,
        result.bytes.len(),
        result.output_bih.size_image,
    );

    if let Some(path) = output {
        std::fs::write(path, &result.bytes)
            .with_context(|| format!("writing output {}", path.display()))?;
        eprintln!(
            "[encode] wrote {} bytes to {}",
            result.bytes.len(),
            path.display()
        );
    } else {
        use std::io::Write as _;
        std::io::stdout().write_all(&result.bytes)?;
    }

    let _ = sandbox.ic_compress_end(hic);
    let _ = sandbox.ic_close(hic);
    Ok(())
}

#[allow(clippy::too_many_lines)]
fn analyze(input: &Path, max_instructions: u64, as_json: bool) -> anyhow::Result<()> {
    let bytes = std::fs::read(input).with_context(|| format!("read {}", input.display()))?;
    if !ud_format::pe::is_pe(&bytes) {
        anyhow::bail!(
            "ud analyze currently only supports PE32 DLLs; {} is not a PE",
            input.display()
        );
    }
    let stem = input
        .file_stem()
        .and_then(|s| s.to_str())
        .unwrap_or("input");

    let mut sandbox = ud_emulator::Sandbox::new();
    sandbox.host.trace_stubs = true;
    sandbox.host.instruction_budget = Some(max_instructions);

    let load_result = sandbox.load(stem, &bytes);
    let image = match load_result {
        Ok(img) => img,
        Err(e) => {
            // Surface load failures cleanly in both text and
            // JSON shapes — the front-end consumer cares
            // whether the load even got off the ground.
            if as_json {
                let pe = ud_format::pe::PeFile::parse(&bytes).ok();
                let indicators = pe.as_ref().map(extract_indicators).unwrap_or_default();
                let report = AnalyzeReport {
                    input: input.display().to_string(),
                    image_base: 0,
                    entry_point: 0,
                    dll_main: DllMainOutcome::LoadFailed {
                        message: e.to_string(),
                    },
                    win32_calls: Vec::new(),
                    win32_calls_by_function: Vec::new(),
                    coverage: CoverageSummary::default(),
                    indicators,
                    instructions_executed: 0,
                    instruction_budget: max_instructions,
                };
                let s = serde_json::to_string_pretty(&report)?;
                println!("{s}");
                return Ok(());
            }
            anyhow::bail!("load {}: {}", input.display(), e);
        }
    };

    let dll_main_result = sandbox.call_dll_main(&image, ud_emulator::DLL_PROCESS_ATTACH);
    let stub_calls = std::mem::take(&mut sandbox.host.stub_calls);
    let _: Vec<String> = std::mem::take(&mut sandbox.host.stub_trace);
    let instructions_executed = sandbox.host.instructions_executed;

    let win32_calls: Vec<Win32Call> = stub_calls
        .into_iter()
        .map(|c| Win32Call {
            dll: c.dll,
            name: c.name,
            args: c.args,
            return_value: c.ret,
            call_site_eip: c.call_site_eip,
        })
        .collect();

    let mut by_func: std::collections::BTreeMap<String, usize> = std::collections::BTreeMap::new();
    for c in &win32_calls {
        *by_func.entry(format!("{}!{}", c.dll, c.name)).or_default() += 1;
    }
    let win32_calls_by_function: Vec<Win32CallCount> = by_func
        .into_iter()
        .map(|(function, count)| Win32CallCount { function, count })
        .collect();

    let cov = sandbox.coverage();
    let ranges = cov.executed_ranges();
    let writes = cov.written_addresses().count();
    let smc: Vec<u32> = cov.self_modifying_addresses().collect();
    let coverage = CoverageSummary {
        executed_addresses: cov.executed_count(),
        executed_ranges: ranges.len(),
        bytes_written: writes,
        self_modifying_bytes: smc.len(),
        self_modifying_sample: smc.iter().take(8).copied().collect(),
    };

    let dll_main = match &dll_main_result {
        Ok(ret) => DllMainOutcome::Returned { value: *ret },
        Err(e) => DllMainOutcome::Trapped {
            message: e.to_string(),
        },
    };

    // Static-side indicator extraction: scan the data
    // sections of the parsed PE for printable ASCII / UTF-16
    // strings, classify a few well-known shapes (URLs, file
    // paths, registry keys), and report. Doesn't depend on
    // the run completing, so even codecs that trap mid-DllMain
    // surface their string indicators.
    let pe = ud_format::pe::PeFile::parse(&bytes).ok();
    let indicators = pe.as_ref().map(extract_indicators).unwrap_or_default();

    let report = AnalyzeReport {
        input: input.display().to_string(),
        image_base: image.image_base,
        entry_point: image.entry_point,
        dll_main,
        win32_calls,
        win32_calls_by_function,
        coverage,
        indicators,
        instructions_executed,
        instruction_budget: max_instructions,
    };

    if as_json {
        let s = serde_json::to_string_pretty(&report)?;
        println!("{s}");
    } else {
        report.write_text(input);
    }
    Ok(())
}

#[derive(serde::Serialize)]
struct AnalyzeReport {
    input: String,
    image_base: u32,
    entry_point: u32,
    dll_main: DllMainOutcome,
    win32_calls: Vec<Win32Call>,
    win32_calls_by_function: Vec<Win32CallCount>,
    coverage: CoverageSummary,
    indicators: Indicators,
    instructions_executed: u64,
    instruction_budget: u64,
}

#[derive(serde::Serialize, Default)]
struct Indicators {
    /// Strings flagged as URLs (`http://…`, `https://…`,
    /// `ftp://…`).
    urls: Vec<String>,
    /// Strings flagged as file paths — anything containing a
    /// drive-letter prefix `X:\\` or matching the Windows
    /// `\\\\?\\` long-path scheme.
    file_paths: Vec<String>,
    /// Strings flagged as registry keys (`HKEY_…`,
    /// `HKCR\\…`).
    registry_keys: Vec<String>,
    /// All printable ASCII strings of length ≥ `STRING_MIN_LEN`
    /// extracted from the PE's data sections. The classified
    /// shapes above are a subset of this list.
    ascii_strings: Vec<String>,
}

const STRING_MIN_LEN: usize = 5;

fn extract_indicators(pe: &ud_format::pe::PeFile) -> Indicators {
    let mut all: Vec<String> = Vec::new();
    for (idx, sh) in pe.sections.iter().enumerate() {
        // Skip executable code sections — strings landing in
        // `.text` are usually false positives off instruction
        // operands. Data and read-only data sections are the
        // primary indicator source.
        let is_exec = sh.characteristics & 0x2000_0000 != 0;
        if is_exec {
            continue;
        }
        let Some(data) = pe.section_data(idx) else {
            continue;
        };
        scan_ascii_strings(data, &mut all);
    }
    all.sort();
    all.dedup();

    let urls = all
        .iter()
        .filter(|s| {
            s.starts_with("http://")
                || s.starts_with("https://")
                || s.starts_with("ftp://")
                || s.starts_with("ws://")
                || s.starts_with("wss://")
        })
        .cloned()
        .collect();
    let file_paths = all
        .iter()
        .filter(|s| {
            // Drive-letter path like `C:\foo` or UNC-style
            // `\\server\share` (with the backslashes preserved
            // in the captured string).
            let bytes = s.as_bytes();
            (bytes.len() >= 3
                && bytes[0].is_ascii_alphabetic()
                && bytes[1] == b':'
                && (bytes[2] == b'\\' || bytes[2] == b'/'))
                || s.starts_with("\\\\?\\")
                || s.starts_with("\\\\.\\")
        })
        .cloned()
        .collect();
    let registry_keys = all
        .iter()
        .filter(|s| {
            s.starts_with("HKEY_")
                || s.starts_with("HKLM\\")
                || s.starts_with("HKCU\\")
                || s.starts_with("HKCR\\")
                || s.starts_with("HKU\\")
        })
        .cloned()
        .collect();
    Indicators {
        urls,
        file_paths,
        registry_keys,
        ascii_strings: all,
    }
}

fn scan_ascii_strings(buf: &[u8], out: &mut Vec<String>) {
    let mut start: Option<usize> = None;
    for (i, &b) in buf.iter().enumerate() {
        let printable = matches!(b, 0x20..=0x7e);
        if printable {
            start.get_or_insert(i);
        } else if let Some(s) = start.take() {
            if i - s >= STRING_MIN_LEN {
                if let Ok(text) = std::str::from_utf8(&buf[s..i]) {
                    out.push(text.to_string());
                }
            }
        }
    }
    if let Some(s) = start {
        let end = buf.len();
        if end - s >= STRING_MIN_LEN {
            if let Ok(text) = std::str::from_utf8(&buf[s..end]) {
                out.push(text.to_string());
            }
        }
    }
}

impl AnalyzeReport {
    fn write_text(&self, input: &Path) {
        println!(
            "loaded: {} (image_base 0x{:x}, entry 0x{:x})",
            input.display(),
            self.image_base,
            self.entry_point
        );
        println!();
        println!("Win32 calls observed: {}", self.win32_calls.len());
        for c in &self.win32_calls_by_function {
            println!("  {:5}× {}", c.count, c.function);
        }
        println!();
        println!("Coverage:");
        println!(
            "  {} distinct EIP addresses executed",
            self.coverage.executed_addresses
        );
        println!(
            "  {} executed address ranges (contiguous spans)",
            self.coverage.executed_ranges
        );
        println!("  {} guest bytes written", self.coverage.bytes_written);
        println!(
            "  {} bytes were both written and executed (self-modifying / unpacker)",
            self.coverage.self_modifying_bytes
        );
        if !self.coverage.self_modifying_sample.is_empty() {
            let preview: Vec<String> = self
                .coverage
                .self_modifying_sample
                .iter()
                .map(|a| format!("0x{a:x}"))
                .collect();
            println!("    first few: {}", preview.join(", "));
        }
        println!();
        println!(
            "Instructions executed: {} of {}",
            self.instructions_executed, self.instruction_budget
        );
        println!();
        println!("Indicators:");
        println!(
            "  {} ASCII strings extracted from data sections",
            self.indicators.ascii_strings.len()
        );
        if !self.indicators.urls.is_empty() {
            println!("  URLs ({}):", self.indicators.urls.len());
            for u in &self.indicators.urls {
                println!("    {u}");
            }
        }
        if !self.indicators.file_paths.is_empty() {
            println!("  File paths ({}):", self.indicators.file_paths.len());
            for p in self.indicators.file_paths.iter().take(8) {
                println!("    {p}");
            }
            if self.indicators.file_paths.len() > 8 {
                println!("{} more", self.indicators.file_paths.len() - 8);
            }
        }
        if !self.indicators.registry_keys.is_empty() {
            println!("  Registry keys ({}):", self.indicators.registry_keys.len());
            for k in &self.indicators.registry_keys {
                println!("    {k}");
            }
        }
        println!();
        match &self.dll_main {
            DllMainOutcome::Returned { value } => {
                println!("DllMain(DLL_PROCESS_ATTACH) returned 0x{value:x}");
            }
            DllMainOutcome::Trapped { message } => {
                println!("DllMain trapped: {message}");
            }
            DllMainOutcome::LoadFailed { message } => {
                println!("load failed: {message}");
            }
        }
    }
}

#[derive(serde::Serialize)]
#[serde(tag = "status", rename_all = "snake_case")]
enum DllMainOutcome {
    Returned { value: u32 },
    Trapped { message: String },
    LoadFailed { message: String },
}

#[derive(serde::Serialize)]
struct Win32Call {
    dll: String,
    name: String,
    args: Vec<u32>,
    return_value: u32,
    call_site_eip: u32,
}

#[derive(serde::Serialize)]
struct Win32CallCount {
    function: String,
    count: usize,
}

#[derive(serde::Serialize, Default)]
struct CoverageSummary {
    executed_addresses: usize,
    executed_ranges: usize,
    bytes_written: usize,
    self_modifying_bytes: usize,
    self_modifying_sample: Vec<u32>,
}

fn format_warning(w: &ud_translate::compile::AsmWarning) -> String {
    match w {
        ud_translate::compile::AsmWarning::Divergence {
            location,
            text,
            canonical,
        } => format!(
            "{}: text {:?} disagrees with canonical form {:?}",
            format_location(location),
            text,
            canonical,
        ),
        ud_translate::compile::AsmWarning::Undecodable { location, text } => format!(
            "{}: pinned bytes don't decode as a valid x86 instruction (text was {:?})",
            format_location(location),
            text,
        ),
        ud_translate::compile::AsmWarning::MultipleInsns {
            location,
            text,
            count,
        } => format!(
            "{}: pinned bytes decode to {} instructions, not 1 (text was {:?})",
            format_location(location),
            count,
            text,
        ),
    }
}

fn format_location(l: &ud_translate::compile::AsmLocation) -> String {
    let section = l.section.as_deref().unwrap_or("<top-level>");
    let function = l.function.as_deref().unwrap_or("<no fn>");
    format!("{section}::{function}#{}", l.stmt_index)
}

fn hex_window(bytes: &[u8]) -> String {
    bytes
        .iter()
        .map(|b| format!("{b:02x}"))
        .collect::<Vec<_>>()
        .join(" ")
}