ud-emulator 0.2.0

Pure-Rust 32-bit x86 emulator + PE runtime loader + Win32 host shims. Mirrors oxideav-vfw; intended to grow into the dynamic-analysis backend that informs decompilation (indirect-target recovery, constant-data discovery).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
//! Top-level [`Sandbox`] — owns the MMU, the CPU, the Win32 stub
//! registry, and the per-emulator host state, and exposes the
//! "load this DLL and call its DllMain" workflow that the
//! integration tests + future codec wrapper layers drive.
//!
//! This is the highest-level public entry point in the crate.
//! Round-1 exposed [`Sandbox::load`] + [`Sandbox::call_dll_main`];
//! round-2 adds the generic [`Sandbox::call_export`] helper that
//! the `vfw32` host stubs use to invoke the codec's `DriverProc`
//! synchronously.

use crate::emulator::{mmu::Perm, Cpu, Mmu};
use crate::pe::{Image, Loader};
use crate::win32::{
    call_guest, run_until_sentinel as run_until_sentinel_free, vfw32, HostState, Registry,
    DATA_IMPORT_BASE,
};

/// `DllMain` reason code: process is loading the DLL.
pub const DLL_PROCESS_ATTACH: u32 = 1;
/// `DllMain` reason code: process is unloading the DLL.
pub const DLL_PROCESS_DETACH: u32 = 0;

/// Default region the loader can use as the kernel32 heap arena.
const HEAP_ARENA_START: u32 = 0x6000_0000;
const HEAP_ARENA_END: u32 = 0x7000_0000;

/// Const-arena region — read-only canned strings handed back from
/// `GetCommandLineA` / `GetEnvironmentStrings` etc.
const CONST_ARENA_START: u32 = 0x7000_0000;
const CONST_ARENA_END: u32 = 0x7010_0000;

/// Data-import slot region — see [`crate::win32::DATA_IMPORT_BASE`].
/// Holds 4-byte values backing CRT data imports like
/// `msvcrt!_adjust_fdiv`. 4 KiB is plenty.
const DATA_IMPORT_REGION_SIZE: u32 = 0x0000_1000;

/// Default guest stack region — plenty of room above the heap.
const STACK_BOTTOM: u32 = 0x9000_0000;
const STACK_SIZE: u32 = 0x0010_0000; // 1 MiB
const STACK_TOP: u32 = STACK_BOTTOM + STACK_SIZE;

/// Thread-stack arena. `CreateThread` carves a 64 KiB region
/// out of this pool per spawned thread, walking down from the
/// top. 0x8000_0000 .. 0x9000_0000 = 256 MiB → ~4096 aux
/// threads, plenty for codec / installer corpora.
const THREAD_STACK_POOL_BOTTOM: u32 = 0x8000_0000;
const THREAD_STACK_POOL_SIZE: u32 = 0x1000_0000; // 256 MiB
const THREAD_STACK_POOL_TOP: u32 = THREAD_STACK_POOL_BOTTOM + THREAD_STACK_POOL_SIZE;

/// Thread Environment Block — Windows places its TEB at
/// `0x7FFD_E000` historically. We map a 4 KiB page here and
/// stage the SEH chain head (`FS:[0]`) to `0xFFFF_FFFF` ("end of
/// chain"). Real Windows fills many more fields; for the codec
/// CRT init we only need a writable page so the codec's SEH
/// `__try` setup can save the prior chain head, write its own,
/// and restore on exit.
const TEB_BASE: u32 = 0x7FFD_E000;
const TEB_SIZE: u32 = 0x0000_1000; // 4 KiB
/// `EXCEPTION_REGISTRATION_RECORD*` initialiser at FS:[0].
const SEH_END_OF_CHAIN: u32 = 0xFFFF_FFFF;

/// Per-thread TIB pool. `CreateThread` carves a 4 KiB TIB out
/// of this pool per spawned thread, walking down from the
/// top. 256 KiB → 64 aux thread TIBs, well above any plausible
/// codec / installer thread count.
const TIB_POOL_BOTTOM: u32 = 0x7FFC_0000;
const TIB_POOL_SIZE: u32 = 0x0001_E000; // ~120 KiB → 30 TIBs
const TIB_POOL_TOP: u32 = TIB_POOL_BOTTOM + TIB_POOL_SIZE;

/// Child-process pools. `CreateProcessA` loads each spawned PE
/// at [`CHILD_IMAGE_BASE_START`] + N * `CHILD_IMAGE_STRIDE` and
/// gives each child a private 16 MiB heap arena out of
/// `[CHILD_HEAP_POOL_START, CHILD_HEAP_POOL_END)`. Picked above
/// the parent's mapped regions but below TEB / stack-pool
/// addresses to keep guest pointers easy to read in traces.
const CHILD_IMAGE_BASE_START: u32 = 0x1000_0000;
const CHILD_HEAP_POOL_START: u32 = 0xA000_0000;
const CHILD_HEAP_POOL_SIZE: u32 = 0x1000_0000; // 256 MiB → 16 children
const CHILD_HEAP_POOL_END: u32 = CHILD_HEAP_POOL_START + CHILD_HEAP_POOL_SIZE;

/// One sandbox instance per loaded codec DLL.
pub struct Sandbox {
    pub mmu: Mmu,
    pub cpu: Cpu,
    pub registry: Registry,
    pub host: HostState,
}

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

impl Sandbox {
    /// Borrow the always-on coverage map populated by the
    /// interpreter. Records every dispatched instruction's
    /// entry EIP plus every guest memory write. See
    /// [`crate::coverage::CoverageMap`] for the consumer
    /// surface.
    #[must_use]
    pub fn coverage(&self) -> &crate::coverage::CoverageMap {
        &self.mmu.coverage
    }

    /// Mutable accessor for the coverage map — useful for
    /// per-export resets (`coverage_mut().clear()`) between
    /// runs of the same sandbox.
    pub fn coverage_mut(&mut self) -> &mut crate::coverage::CoverageMap {
        &mut self.mmu.coverage
    }

    /// Borrow the emulation-context layer (virtual filesystem,
    /// virtual registry, future surfaces). Always present;
    /// the per-surface options decide whether the guest
    /// observes synthetic state or the fail-soft Win32
    /// default. See [`crate::context::Context`].
    #[must_use]
    pub fn context(&self) -> &crate::context::Context {
        &self.host.context
    }

    /// Mutable accessor for the context.
    pub fn context_mut(&mut self) -> &mut crate::context::Context {
        &mut self.host.context
    }

    /// Builder: attach a virtual filesystem so guest file-API
    /// calls land in-memory instead of fail-soft no-ops. See
    /// [`crate::VirtualFs`] for the stage-some-files / capture-
    /// what's-written workflow.
    #[must_use]
    pub fn with_vfs(mut self, vfs: crate::context::VirtualFs) -> Self {
        self.host.context.vfs = Some(vfs);
        self
    }

    /// Builder: attach a virtual registry so guest `Reg*` calls
    /// observe analyst-staged keys and writes land in-memory.
    /// See [`crate::VirtualRegistry`].
    #[must_use]
    pub fn with_registry(mut self, reg: crate::context::VirtualRegistry) -> Self {
        self.host.context.registry = Some(reg);
        self
    }

    /// Create a fresh sandbox with the heap arena and stack
    /// pre-mapped, the kernel32 stub set registered, and the
    /// CPU's `esp` pointing at a freshly-allocated stack.
    pub fn new() -> Self {
        let mut mmu = Mmu::new();
        // Heap arena (R+W+X). Old codecs (e.g. Cinepak) ship
        // architecture-specific inner-loop assembly that they
        // copy into `malloc`'d memory at init time and then call.
        // On real Windows, `HeapAlloc(GetProcessHeap, ...)` returns
        // executable memory by default; modelling the same is
        // simpler than chasing per-codec `VirtualProtect(PAGE_EXEC)`
        // calls. Bytes still respect `mmu.write_initializer`'s
        // perm rules; only the X bit is broader.
        mmu.map(
            HEAP_ARENA_START,
            HEAP_ARENA_END - HEAP_ARENA_START,
            Perm::R | Perm::W | Perm::X,
        );
        // Const-arena for canned strings (R+W mapped; the caller
        // ABI treats it as R-only — we use write_initializer for
        // population, then any reads honour the perm bits).
        mmu.map(
            CONST_ARENA_START,
            CONST_ARENA_END - CONST_ARENA_START,
            Perm::R | Perm::W,
        );
        // Data-import slot region (R+W) — holds the 4-byte
        // values backing CRT data imports like
        // `msvcrt!_adjust_fdiv`. Seeded with each registered
        // import's `initial` value.
        mmu.map(DATA_IMPORT_BASE, DATA_IMPORT_REGION_SIZE, Perm::R | Perm::W);
        // Stack (R+W)
        mmu.map(STACK_BOTTOM, STACK_SIZE, Perm::R | Perm::W);
        // Thread-stack pool (R+W). `CreateThread` carves
        // 64 KiB stacks out of the top of this pool, walking
        // down with each thread.
        mmu.map(
            THREAD_STACK_POOL_BOTTOM,
            THREAD_STACK_POOL_SIZE,
            Perm::R | Perm::W,
        );
        // Stub-thunk region (R-only, zeroed). The run loop
        // detects `eip == thunk_addr` via `Registry::is_thunk`
        // *before* hitting the MMU, so execution still routes
        // to the stub regardless of the X bit — but codecs that
        // *read* a function pointer's bytes (a hot-patch /
        // forwarder probe; CamStudio does this in DllMain) need
        // a mapped region behind the address. Zeros pass every
        // standard "is this byte E9/EB/CC/C3?" introspection.
        mmu.map(crate::win32::THUNK_BASE, 0x1_0000, Perm::R);
        // TEB / FS-segment data (R+W). Initialise FS:[0] = -1
        // (no SEH handler installed) and FS:[0x18] = TEB self
        // pointer per the Windows TEB ABI used by Win32 CRTs.
        mmu.map(TEB_BASE, TEB_SIZE, Perm::R | Perm::W);
        mmu.write_initializer(TEB_BASE, &SEH_END_OF_CHAIN.to_le_bytes())
            .expect("seed TEB FS:[0]");
        mmu.write_initializer(TEB_BASE + 0x18, &TEB_BASE.to_le_bytes())
            .expect("seed TEB FS:[0x18] (self pointer)");
        // Per-thread TIB pool (R+W). `CreateThread` carves a
        // fresh TIB out of this pool for each spawned thread,
        // setting the new thread's FS base to its own TIB.
        mmu.map(TIB_POOL_BOTTOM, TIB_POOL_SIZE, Perm::R | Perm::W);
        // Child-process heap pool (R+W+X). Each `CreateProcessA`
        // carves a 16 MiB heap arena from this region for the
        // spawned child.
        mmu.map(
            CHILD_HEAP_POOL_START,
            CHILD_HEAP_POOL_SIZE,
            Perm::R | Perm::W | Perm::X,
        );
        // FS:[0x30] would be the PEB pointer — we leave it 0
        // until a codec actually dereferences it.

        let mut cpu = Cpu::new();
        cpu.regs.set_esp(STACK_TOP - 0x100); // leave a guard at the top
        cpu.set_fs_base(TEB_BASE);

        let mut registry = Registry::new();
        registry.register_all();
        // Seed data-import slot values into the mapped region.
        for (_dll, _name, d) in registry.data_imports() {
            mmu.write_initializer(d.addr, &d.initial.to_le_bytes())
                .expect("seed data import");
        }

        let mut host = HostState::new(HEAP_ARENA_START, HEAP_ARENA_END)
            .with_const_arena(CONST_ARENA_START, CONST_ARENA_END)
            .with_thread_stack_pool(THREAD_STACK_POOL_BOTTOM, THREAD_STACK_POOL_TOP)
            .with_tib_pool(TIB_POOL_BOTTOM, TIB_POOL_TOP)
            .with_child_arena(
                CHILD_IMAGE_BASE_START,
                CHILD_HEAP_POOL_START,
                CHILD_HEAP_POOL_END,
            );
        // Bootstrap thread's TIB lives at the runtime-owned
        // TEB_BASE (already mapped + seeded above) — mirror
        // its address into ThreadState so SetLastError /
        // GetLastError can also write through `fs:[0x34]`.
        if let Some(t) = host.threads.get_mut(&1) {
            t.tib_addr = TEB_BASE;
        }

        // Pre-register the system DLLs whose stub registries we
        // ship as "loaded modules". Real Windows always has these
        // available, and codec CRTs commonly probe them via
        // `GetModuleHandleW(L"KERNEL32.DLL")` before walking their
        // exports (e.g. lagarith's `_CRT_INIT` rolls back its heap
        // and bails if `KERNEL32.DLL`'s handle comes back NULL).
        // The handles are synthetic, distinct, non-zero values in
        // the otherwise-unmapped `0x7800_0000..0x7900_0000` band.
        // Codecs use these handles for identity comparisons and
        // as opaque arguments to `GetProcAddress`; the band is
        // clear of every other mapped region (heap, const arena,
        // TEB, stack, VirtualAlloc range, thunk space) so a
        // codec that tries to *walk* the handle as if it were a
        // PE image gets a clean `MemoryFault` rather than
        // accidentally hitting some other arena.
        for (i, dll) in [
            "kernel32.dll",
            "user32.dll",
            "gdi32.dll",
            "advapi32.dll",
            "ole32.dll",
            "shell32.dll",
            "shlwapi.dll",
            "comctl32.dll",
            "winmm.dll",
            "msvcrt.dll",
            "msvcr71.dll",
            "msvcr80.dll",
            "msvcr90.dll",
            "pncrt.dll",
            "mfplat.dll",
            "version.dll",
            "vfw32.dll",
        ]
        .iter()
        .enumerate()
        {
            let handle = 0x7800_0000u32.wrapping_add((i as u32) * 0x10_0000);
            host.modules.insert((*dll).to_string(), handle);
        }

        // Round 35 — pre-register the canonical DirectShow memory
        // allocator class factory in the in-process class-factory
        // cache.  Codecs that internally call
        // `CoCreateInstance(CLSID_MemoryAllocator, NULL, _,
        // IID_IMemAllocator, &alloc)` (e.g. mpg4ds32 from inside
        // `IMemInputPin::GetAllocator`) will now hit our host
        // factory rather than the round-34 baseline
        // `CLASS_E_CLASSNOTAVAILABLE` (`0x80040111`) miss.  CLSID
        // value sourced from Windows SDK header `axextend.h`.
        if let Ok(factory) =
            crate::com::mint_host_mem_allocator_class_factory(&mut host, &mut mmu, &registry)
        {
            host.com
                .register_class_factory(crate::com::CLSID_MEMORY_ALLOCATOR, factory);
        }

        Sandbox {
            mmu,
            cpu,
            registry,
            host,
        }
    }

    /// Builder-style seed setter for the `msvcrt!rand` LCG.
    ///
    /// PRNG state for `msvcrt!rand` calls from sandboxed codec
    /// code.  Default `1` matches MSVC's documented "no `srand`
    /// called yet" initial value.  Set via `with_rand_seed` /
    /// `set_rand_seed` for reproducible encode output: two
    /// sandboxes seeded identically produce identical `rand`
    /// sequences, which makes encode regression tests
    /// deterministic across runs.
    ///
    /// The guest's own `msvcrt!srand(seed)` call writes to the
    /// same field, so the codec may re-seed at any time; in that
    /// case [`Self::rand_seed`] will report whatever value the
    /// codec last installed.
    ///
    /// Round 55.
    pub fn with_rand_seed(mut self, seed: u32) -> Self {
        self.host.rand_state = seed;
        self
    }

    /// Set the `msvcrt!rand` LCG state at runtime.
    ///
    /// Same contract as [`Self::with_rand_seed`], but mutates an
    /// already-constructed sandbox — useful for tests that drive
    /// multiple encode runs with different seeds, or for fuzzing
    /// harnesses that want to force the codec into a known state
    /// before each iteration.
    ///
    /// Round 55.
    pub fn set_rand_seed(&mut self, seed: u32) {
        self.host.rand_state = seed;
    }

    /// Override the value `kernel32!GetCommandLineA` returns to
    /// the guest. The string is stashed (NUL-terminated) in the
    /// host's const arena and a pointer to it is parked at
    /// `command_line_ptr`. Installer-class binaries consult
    /// this to pick up `/quiet`, `/qn`, `/S` and similar
    /// silent-install flags.
    pub fn set_command_line(&mut self, cmdline: &str) -> Result<(), crate::Error> {
        let mut bytes = cmdline.as_bytes().to_vec();
        bytes.push(0);
        let addr = self
            .host
            .arena_const_alloc(bytes.len() as u32)
            .map_err(crate::Error::Win32)?;
        self.mmu.write_initializer(addr, &bytes)?;
        self.host.command_line_ptr = addr;
        Ok(())
    }

    /// Read the current `msvcrt!rand` LCG state.
    ///
    /// Reflects whatever the host or the guest last wrote: a
    /// fresh sandbox returns `1` (MSVC's documented "no `srand`
    /// called yet" initial value); after host
    /// [`Self::set_rand_seed`] / [`Self::with_rand_seed`] returns
    /// that value; after a guest `msvcrt!srand(s)` call returns
    /// `s`; after any number of `msvcrt!rand` calls returns the
    /// post-step LCG state.
    ///
    /// Round 55.
    pub fn rand_seed(&self) -> u32 {
        self.host.rand_state
    }

    /// Load a PE32 image from `bytes`, mapping it into the
    /// sandbox's MMU. The returned [`Image`] holds the entry
    /// point + export table.
    ///
    /// Strict-resolution: any IAT entry the
    /// [`crate::win32::Registry`] doesn't satisfy is a hard
    /// load-time error. Use [`Sandbox::load_fail_soft`] for
    /// EXEs whose import list exceeds the codec-class stub
    /// surface (installers, GUI apps, etc.).
    pub fn load(&mut self, name: &str, bytes: &[u8]) -> Result<Image, crate::Error> {
        let mut loader = Loader::new(&mut self.mmu, &mut self.registry, &mut self.host);
        let img = loader.load(name, bytes)?;
        // Record primary module base so `GetModuleHandleA(NULL)`
        // returns the right value.
        self.host.primary_module_base = img.image_base;
        // Also record the loaded module under its filename so
        // `GetModuleHandleA("name.dll")` finds it. Lower-cased,
        // matching the lookup in `stub_get_module_handle_a` /
        // `_w`.
        self.host
            .modules
            .insert(name.to_ascii_lowercase(), img.image_base);
        Ok(img)
    }

    /// Load a PE32 image in fail-soft import-resolution mode.
    /// Imports the codec-class stub registry doesn't satisfy
    /// get a trap-on-call fallback thunk so the load succeeds.
    /// Returns the loaded [`Image`] plus the list of
    /// `(dll, name)` pairs that received a fallback — i.e.
    /// the set of APIs the operator now knows the binary uses
    /// but we don't yet stub.
    ///
    /// Intended for the install-monitor workflow: load
    /// QuickTimeInstaller.exe with fail-soft, drive the entry
    /// point, watch the trap stream for the next missing API.
    pub fn load_fail_soft(
        &mut self,
        name: &str,
        bytes: &[u8],
    ) -> Result<(Image, Vec<(String, String)>), crate::Error> {
        let mut options = crate::pe::LoadOptions {
            imports: crate::pe::imports::ResolveMode::FailSoft,
            fail_soft_log: Some(Vec::new()),
            target_image_base: None,
        };
        let mut loader = Loader::new(&mut self.mmu, &mut self.registry, &mut self.host);
        let img = loader.load_with_options(name, bytes, &mut options)?;
        self.host.primary_module_base = img.image_base;
        self.host
            .modules
            .insert(name.to_ascii_lowercase(), img.image_base);
        Ok((img, options.fail_soft_log.unwrap_or_default()))
    }

    /// Synchronously call `DllMain(hModule, fdwReason, lpvReserved)`
    /// inside the emulator and return the dword `eax` value at
    /// the point the function returned to the synthetic
    /// `RET_SENTINEL`.
    ///
    /// The DllMain ABI is stdcall (callee-cleanup), so we push
    /// `lpvReserved` first, then `fdwReason`, then `hModule`,
    /// then the return-address sentinel. The callee's `RET 12`
    /// (or equivalent) cleans the args.
    ///
    /// Resolution: prefer the `DllMain` named export (Indeo
    /// codecs); fall back to the PE `AddressOfEntryPoint`
    /// (mpg4c32.dll and other CRT-startup-driven DLLs that
    /// don't export `DllMain` by name). Both expose the same
    /// stdcall (HINSTANCE, DWORD, LPVOID) ABI.
    pub fn call_dll_main(&mut self, image: &Image, reason: u32) -> Result<u32, crate::Error> {
        let h_module = image.image_base;
        let lpv_reserved = 0u32;
        let target = image.export("DllMain").unwrap_or(image.entry_point);
        if target == 0 {
            return Err(crate::Error::Win32(
                crate::win32::Win32Error::InvalidArgument {
                    stub: "call_dll_main",
                    reason: format!(
                        "no DllMain export and no PE entry point in {:?}",
                        image.name
                    ),
                },
            ));
        }
        call_guest(
            &mut self.cpu,
            &mut self.mmu,
            &self.registry,
            &mut self.host,
            target,
            &[h_module, reason, lpv_reserved],
        )
    }

    /// Generic stdcall guest-call helper. Resolves `name` against
    /// `image`'s export table, pushes `args` right-to-left + the
    /// `RET_SENTINEL`, and runs until the callee returns.
    /// Returns `eax`.
    ///
    /// Used both internally (by [`Self::call_dll_main`]) and by
    /// future codec adapter layers that need to drive arbitrary
    /// codec exports — `DriverProc`, `MyCodecGetVersion`,
    /// `MyCodecExtraInit`, etc. The round-2 `vfw32::ic_*` host
    /// surface uses [`crate::win32::call_guest`] directly with
    /// the codec's `DriverProc` VA.
    pub fn call_export(
        &mut self,
        image: &Image,
        name: &str,
        args: &[u32],
    ) -> Result<u32, crate::Error> {
        let target = image.export(name).ok_or_else(|| {
            crate::Error::Win32(crate::win32::Win32Error::InvalidArgument {
                stub: "call_export",
                reason: format!("export {name:?} not found in {:?}", image.name),
            })
        })?;
        call_guest(
            &mut self.cpu,
            &mut self.mmu,
            &self.registry,
            &mut self.host,
            target,
            args,
        )
    }

    /// Call the image's PE entry point (`AddressOfEntryPoint`).
    /// For an EXE this is the CRT startup, which expects no
    /// arguments and never returns under normal Windows
    /// semantics (it calls `ExitProcess`). Here it runs until
    /// the runtime returns to the synthetic `RET_SENTINEL` or
    /// hits a trap (e.g. unresolved import, instruction limit).
    pub fn call_entry_point(&mut self, image: &Image) -> Result<u32, crate::Error> {
        if image.entry_point == 0 {
            return Err(crate::Error::Win32(
                crate::win32::Win32Error::InvalidArgument {
                    stub: "call_entry_point",
                    reason: format!("no PE entry point in {:?}", image.name),
                },
            ));
        }
        call_guest(
            &mut self.cpu,
            &mut self.mmu,
            &self.registry,
            &mut self.host,
            image.entry_point,
            &[],
        )
    }

    /// Drive the CPU until `eip == RET_SENTINEL`, dispatching to
    /// Win32 stubs whenever `eip` lands on a registered thunk
    /// address. Thin wrapper over [`crate::win32::run_until_sentinel`]
    /// kept for API stability.
    pub fn run_until_sentinel(&mut self) -> Result<(), crate::Error> {
        run_until_sentinel_free(&mut self.cpu, &mut self.mmu, &self.registry, &mut self.host)
    }

    // ---- vfw32 IC* convenience wrappers ------------------------------

    /// Mark `image` as the codec the next [`Self::ic_open`] call
    /// should target.
    ///
    /// Round 2 supports a single codec image per sandbox — round 3
    /// will lift that into a multi-codec registry. The image must
    /// export `DriverProc`.
    pub fn install_codec(&mut self, image: &Image) -> Result<(), crate::Error> {
        let dp = image.export("DriverProc").ok_or_else(|| {
            crate::Error::Win32(crate::win32::Win32Error::InvalidArgument {
                stub: "install_codec",
                reason: format!("DriverProc not exported by {:?}", image.name),
            })
        })?;
        self.host.default_driver_proc = dp;
        Ok(())
    }

    /// Open the installed codec (`DRV_OPEN`).
    pub fn ic_open(
        &mut self,
        fcc_type: u32,
        fcc_handler: u32,
        mode: u32,
    ) -> Result<u32, crate::Error> {
        vfw32::ic_open(
            &mut self.cpu,
            &mut self.mmu,
            &self.registry,
            &mut self.host,
            fcc_type,
            fcc_handler,
            mode,
        )
    }

    /// Close a codec instance (`DRV_CLOSE`).
    pub fn ic_close(&mut self, hic: u32) -> Result<u32, crate::Error> {
        vfw32::ic_close(
            &mut self.cpu,
            &mut self.mmu,
            &self.registry,
            &mut self.host,
            hic,
        )
    }

    /// Read the codec's `ICINFO` block.
    pub fn ic_get_info(&mut self, hic: u32, cb: u32) -> Result<Vec<u8>, crate::Error> {
        vfw32::ic_get_info(
            &mut self.cpu,
            &mut self.mmu,
            &self.registry,
            &mut self.host,
            hic,
            cb,
        )
    }

    /// `ICDecompressQuery` — does the codec accept this format?
    pub fn ic_decompress_query(
        &mut self,
        hic: u32,
        input: &vfw32::Bih,
        output: Option<&vfw32::Bih>,
    ) -> Result<u32, crate::Error> {
        vfw32::ic_decompress_query(
            &mut self.cpu,
            &mut self.mmu,
            &self.registry,
            &mut self.host,
            hic,
            input,
            output,
        )
    }

    /// `ICDecompressGetFormat` — ask the codec for the output BIH
    /// matching `input`. Round 30 uses this to probe stream
    /// dimensions when `CodecParameters` lacks them.
    pub fn ic_decompress_get_format(
        &mut self,
        hic: u32,
        input: &vfw32::Bih,
    ) -> Result<(u32, vfw32::Bih), crate::Error> {
        vfw32::ic_decompress_get_format(
            &mut self.cpu,
            &mut self.mmu,
            &self.registry,
            &mut self.host,
            hic,
            input,
        )
    }

    /// `ICDecompressBegin` — set up the decoder pipeline.
    pub fn ic_decompress_begin(
        &mut self,
        hic: u32,
        input: &vfw32::Bih,
        output: &vfw32::Bih,
    ) -> Result<u32, crate::Error> {
        vfw32::ic_decompress_begin(
            &mut self.cpu,
            &mut self.mmu,
            &self.registry,
            &mut self.host,
            hic,
            input,
            output,
        )
    }

    /// `ICDecompressEnd` — tear down the decoder pipeline.
    pub fn ic_decompress_end(&mut self, hic: u32) -> Result<u32, crate::Error> {
        vfw32::ic_decompress_end(
            &mut self.cpu,
            &mut self.mmu,
            &self.registry,
            &mut self.host,
            hic,
        )
    }

    // ---- Trace-mode programmatic API (gated on the `trace`
    // ---- Cargo feature). Documented in
    // ---- `docs/winmf/winmf-emulator.md` §"Trace mode".

    /// Install a memory watchpoint covering `[addr, addr+size)`.
    /// Any guest access whose address range intersects the
    /// watchpoint emits a `kind=mem_write` (or `mem_read`) JSONL
    /// event to the configured sink. Multiple watchpoints may
    /// overlap; each fires independently.
    #[cfg(feature = "trace")]
    pub fn watch(&mut self, addr: u32, size: u32, mode: crate::trace::WatchMode) {
        self.mmu.trace.watch(addr, size, mode);
    }

    /// Remove watchpoints whose `(addr, size)` exactly matches.
    /// Mode is ignored for the match.
    #[cfg(feature = "trace")]
    pub fn unwatch(&mut self, addr: u32, size: u32) {
        self.mmu.trace.unwatch(addr, size);
    }

    /// Toggle per-instruction execution trace at runtime. Has no
    /// effect unless the crate was built with the `trace-exec`
    /// sub-feature.
    #[cfg(feature = "trace")]
    pub fn set_exec_trace(&mut self, on: bool) {
        self.mmu.trace.exec_on = on;
    }

    /// Override the trace JSONL sink at runtime. Defaults to
    /// honouring `OXIDEAV_VFW_TRACE_FILE`.
    #[cfg(feature = "trace")]
    pub fn set_trace_sink(&mut self, sink: Box<dyn std::io::Write + Send>) {
        self.mmu.trace.set_sink(sink);
    }

    // ---- COM / DirectShow surface (round 25) ------------------------

    /// Drive `DllGetClassObject(rclsid, riid, ppv)` on `image`,
    /// staging the GUID arguments + the `ppv` out-slot in a
    /// freshly-allocated heap region inside the sandbox.  On
    /// success returns the guest pointer the codec wrote into
    /// `*ppv` — typically a guest-side `IClassFactory`.
    ///
    /// When `riid == IID_IClassFactory`, the returned pointer is
    /// also registered with [`crate::com::ComObjectTable::register_class_factory`]
    /// keyed under `clsid`, so subsequent
    /// [`Self::co_create_instance`] calls can resolve `clsid`
    /// without re-driving `DllGetClassObject`.
    ///
    /// MSDN: `HRESULT DllGetClassObject(REFCLSID rclsid, REFIID
    /// riid, LPVOID *ppv)` — every COM in-process server
    /// exports it; DirectShow filter binaries (`.ax`) export it
    /// instead of `DriverProc`.
    pub fn dll_get_class_object(
        &mut self,
        image: &crate::pe::Image,
        clsid: crate::com::Guid,
        riid: crate::com::Guid,
    ) -> Result<u32, crate::Error> {
        let target = image.export("DllGetClassObject").ok_or_else(|| {
            crate::Error::Win32(crate::win32::Win32Error::InvalidArgument {
                stub: "dll_get_class_object",
                reason: format!("DllGetClassObject not exported by {:?}", image.name),
            })
        })?;
        // Stage the two GUIDs + the out-pointer slot in
        // contiguous arena memory: 16 + 16 + 4 = 36 bytes.
        let scratch = self.host.arena_alloc(36).map_err(crate::Error::Win32)?;
        clsid
            .stage(&mut self.mmu, scratch)
            .map_err(crate::Error::Trap)?;
        riid.stage(&mut self.mmu, scratch + 16)
            .map_err(crate::Error::Trap)?;
        // Zero the ppv slot.
        self.mmu
            .write_initializer(scratch + 32, &0u32.to_le_bytes())
            .map_err(crate::Error::Trap)?;
        let hr = call_guest(
            &mut self.cpu,
            &mut self.mmu,
            &self.registry,
            &mut self.host,
            target,
            &[scratch, scratch + 16, scratch + 32],
        )?;
        if hr != crate::com::S_OK {
            return Err(crate::Error::Win32(
                crate::win32::Win32Error::InvalidArgument {
                    stub: "dll_get_class_object",
                    reason: format!("DllGetClassObject returned HRESULT {hr:#010x}"),
                },
            ));
        }
        let out_ptr = self.mmu.load32(scratch + 32).map_err(crate::Error::Trap)?;
        if out_ptr == 0 {
            return Err(crate::Error::Win32(
                crate::win32::Win32Error::InvalidArgument {
                    stub: "dll_get_class_object",
                    reason: "DllGetClassObject succeeded but *ppv is NULL".into(),
                },
            ));
        }
        // Bookkeep the new object.  If it is a class factory,
        // also register it under `clsid` so `CoCreateInstance`
        // can pick it up.
        self.host.com.intern(out_ptr, Some(riid));
        if riid == crate::com::IID_ICLASSFACTORY {
            self.host.com.register_class_factory(clsid, out_ptr);
        }
        Ok(out_ptr)
    }

    /// Drive `CoCreateInstance(clsid, NULL, CLSCTX_INPROC_SERVER,
    /// riid, ppv)` against the in-process class-factory cache.
    /// The CLSID must already be registered (typically by a
    /// prior [`Self::dll_get_class_object`] call); otherwise
    /// surfaces `CLASS_E_CLASSNOTAVAILABLE` as an error.
    pub fn co_create_instance(
        &mut self,
        clsid: crate::com::Guid,
        riid: crate::com::Guid,
    ) -> Result<u32, crate::Error> {
        let factory = self.host.com.lookup_class_factory(&clsid).ok_or_else(|| {
            crate::Error::Win32(crate::win32::Win32Error::InvalidArgument {
                stub: "co_create_instance",
                reason: format!(
                    "CLSID {clsid} not registered; \
                     call dll_get_class_object first"
                ),
            })
        })?;
        // Stage IID + out slot.
        let scratch = self.host.arena_alloc(20).map_err(crate::Error::Win32)?;
        riid.stage(&mut self.mmu, scratch)
            .map_err(crate::Error::Trap)?;
        self.mmu
            .write_initializer(scratch + 16, &0u32.to_le_bytes())
            .map_err(crate::Error::Trap)?;
        let r = crate::com::call::call_method(
            &mut self.cpu,
            &mut self.mmu,
            &self.registry,
            &mut self.host,
            factory,
            crate::com::SLOT_CLASS_FACTORY_CREATE_INSTANCE,
            &[0, scratch, scratch + 16],
        )?;
        if r != crate::com::S_OK {
            return Err(crate::Error::Win32(
                crate::win32::Win32Error::InvalidArgument {
                    stub: "co_create_instance",
                    reason: format!("CreateInstance returned HRESULT {r:#010x}"),
                },
            ));
        }
        let out = self.mmu.load32(scratch + 16).map_err(crate::Error::Trap)?;
        if out != 0 {
            self.host.com.intern(out, Some(riid));
        }
        Ok(out)
    }

    /// Drive `obj->QueryInterface(riid, ppv)` on a guest COM
    /// object, staging the IID + out-slot in arena memory.
    /// Returns the new interface pointer on success, or surfaces
    /// the HRESULT in an error message.
    pub fn query_interface(
        &mut self,
        obj: u32,
        riid: crate::com::Guid,
    ) -> Result<u32, crate::Error> {
        let scratch = self.host.arena_alloc(20).map_err(crate::Error::Win32)?;
        riid.stage(&mut self.mmu, scratch)
            .map_err(crate::Error::Trap)?;
        self.mmu
            .write_initializer(scratch + 16, &0u32.to_le_bytes())
            .map_err(crate::Error::Trap)?;
        let r = crate::com::call::query_interface(
            &mut self.cpu,
            &mut self.mmu,
            &self.registry,
            &mut self.host,
            obj,
            scratch,
            scratch + 16,
        )?;
        if r != crate::com::S_OK {
            return Err(crate::Error::Win32(
                crate::win32::Win32Error::InvalidArgument {
                    stub: "query_interface",
                    reason: format!("QueryInterface returned HRESULT {r:#010x}"),
                },
            ));
        }
        let out = self.mmu.load32(scratch + 16).map_err(crate::Error::Trap)?;
        if out != 0 {
            self.host.com.intern(out, Some(riid));
        }
        Ok(out)
    }

    /// Round 27 — mint a host-side `IFilterGraph` stub so the
    /// codec's `IBaseFilter::JoinFilterGraph(pGraph, pName)` call
    /// has a non-NULL parent graph to record.  The returned guest
    /// pointer's vtable function-pointer slots are synthetic
    /// thunk addresses that route into the host stubs registered
    /// by [`crate::com::host_iface::register`].
    ///
    /// `QueryInterface(IID_IUnknown | IID_IFilterGraph)` →
    /// `S_OK + *ppv = obj`; every other IID returns
    /// `E_NOINTERFACE`.  All eight `IFilterGraph` methods return
    /// `E_NOTIMPL` — none are exercised on the
    /// `JoinFilterGraph → ReceiveConnection` path the round-27
    /// probe takes.
    pub fn mint_host_filter_graph(&mut self) -> Result<u32, crate::Error> {
        crate::com::mint_host_filter_graph(&mut self.host, &mut self.mmu, &self.registry)
    }

    /// Round 27 — mint a host-side `IPin` stub that pretends to
    /// be an OUTPUT pin advertising `amt_addr` (a pointer to a
    /// staged `AM_MEDIA_TYPE`).  Suitable as the `pConnector`
    /// argument of `IPin::ReceiveConnection`.
    ///
    /// `QueryDirection` reports `PIN_OUTPUT`; `QueryAccept`
    /// returns `S_OK`; `ConnectionMediaType` copies the staged
    /// AMT; `EnumMediaTypes` vends an enumerator yielding the
    /// staged AMT once.
    pub fn mint_host_output_pin(&mut self, amt_addr: u32) -> Result<u32, crate::Error> {
        crate::com::host_iface::mint_host_output_pin(
            &mut self.host,
            &mut self.mmu,
            &self.registry,
            amt_addr,
        )
    }

    /// Round 37 — same as [`Self::mint_host_output_pin`] but also
    /// stamps the codec's input-pin pointer (`connected_pin`) into
    /// the new pin object so `IPin::ConnectedTo` can return it,
    /// and synthesizes a parent `HostIBaseFilter` so
    /// `IPin::QueryPinInfo` can fill in `PIN_INFO::pFilter`.
    ///
    /// `connected_pin == 0` falls back to the round-30 behaviour
    /// where the pin reports `VFW_E_NOT_CONNECTED` from
    /// `ConnectedTo`.
    pub fn mint_host_output_pin_with_connection(
        &mut self,
        amt_addr: u32,
        connected_pin: u32,
    ) -> Result<u32, crate::Error> {
        crate::com::host_iface::mint_host_output_pin_with_connection(
            &mut self.host,
            &mut self.mmu,
            &self.registry,
            amt_addr,
            connected_pin,
        )
    }

    /// Round 37 — number of `IPin::QueryPinInfo` calls the codec
    /// has driven against any host pin during this sandbox's
    /// lifetime.
    pub fn query_pin_info_call_count(&self) -> usize {
        crate::com::host_iface::query_pin_info_call_count(&self.host)
    }

    /// Round 37 — number of `IBaseFilter::QueryFilterInfo` calls
    /// the codec has driven against any host filter during this
    /// sandbox's lifetime.
    pub fn query_filter_info_call_count(&self) -> usize {
        crate::com::host_iface::query_filter_info_call_count(&self.host)
    }

    /// Round 37 — `this` pointers of every `IPin::QueryPinInfo`
    /// call observed.
    pub fn query_pin_info_calls(&self) -> Vec<u32> {
        crate::com::host_iface::query_pin_info_calls(&self.host)
    }

    /// Round 37 — `this` pointers of every
    /// `IBaseFilter::QueryFilterInfo` call observed.
    pub fn query_filter_info_calls(&self) -> Vec<u32> {
        crate::com::host_iface::query_filter_info_calls(&self.host)
    }

    /// Round 37 — drop every captured introspection call from this
    /// sandbox's per-state log.
    pub fn clear_query_info_log(&self) {
        crate::com::host_iface::clear_query_info_log(&self.host)
    }

    /// Round 30 — mint a host-side `IMemAllocator` backed by a
    /// pool of `pool_size` IMediaSample slots, each carrying a
    /// fresh `sample_capacity`-byte data region. The returned
    /// guest pointer is suitable as the `pAllocator` argument of
    /// `IMemInputPin::NotifyAllocator`.
    ///
    /// `media_type_ptr` is returned by every minted sample's
    /// `IMediaSample::GetMediaType` — pass `0` if no AMT should
    /// surface there (codecs then fall back to the upstream pin's
    /// connection media type).
    pub fn mint_host_mem_allocator(
        &mut self,
        pool_size: u32,
        sample_capacity: u32,
        media_type_ptr: u32,
    ) -> Result<u32, crate::Error> {
        crate::com::mint_host_mem_allocator(
            &mut self.host,
            &mut self.mmu,
            &self.registry,
            pool_size,
            sample_capacity,
            media_type_ptr,
        )
    }

    /// Round 35 — mint a host-side `IClassFactory` whose
    /// `CreateInstance` mints fresh `HostIMemAllocator` instances.
    ///
    /// Pre-registered in [`Sandbox::new`] under
    /// [`crate::com::CLSID_MEMORY_ALLOCATOR`]; this method exists
    /// for tests that want a raw factory pointer to drive
    /// `IClassFactory::CreateInstance` directly without going
    /// through the `ole32!CoCreateInstance` cascade.
    pub fn mint_host_mem_allocator_class_factory(&mut self) -> Result<u32, crate::Error> {
        crate::com::mint_host_mem_allocator_class_factory(
            &mut self.host,
            &mut self.mmu,
            &self.registry,
        )
    }

    /// Round 30 — mint a single host-side `IMediaSample` wrapping
    /// a fresh `data_capacity`-byte data region. Useful for
    /// stand-alone tests; production paths typically mint samples
    /// implicitly via [`Self::mint_host_mem_allocator`].
    pub fn mint_host_media_sample(
        &mut self,
        data_capacity: u32,
        media_type_ptr: u32,
    ) -> Result<u32, crate::Error> {
        crate::com::mint_host_media_sample(
            &mut self.host,
            &mut self.mmu,
            &self.registry,
            data_capacity,
            media_type_ptr,
        )
    }

    /// Round 30 — copy a payload into a previously-minted sample
    /// + flag whether it is a sync (key) frame.
    ///
    /// Wraps [`crate::com::media_sample_set_payload`].
    pub fn media_sample_set_payload(
        &mut self,
        sample: u32,
        payload: &[u8],
        sync_point: bool,
    ) -> Result<(), crate::Error> {
        crate::com::media_sample_set_payload(&mut self.mmu, sample, payload, sync_point)
    }

    /// Round 31 — mint a paired downstream `(HostIPin, HostIMemInputPin)`
    /// for receiving samples the codec pushes from its output pin.
    pub fn host_iface_r31_mint_input_pin_pair(&mut self) -> Result<(u32, u32), crate::Error> {
        crate::com::host_iface_r31::mint_host_input_pin_pair(
            &mut self.host,
            &mut self.mmu,
            &self.registry,
        )
    }

    /// Round 31 — mint a minimal HostIBaseFilter exposing
    /// `input_pin`.
    pub fn host_iface_r31_mint_base_filter(&mut self, input_pin: u32) -> Result<u32, crate::Error> {
        crate::com::host_iface_r31::mint_host_base_filter(
            &mut self.host,
            &mut self.mmu,
            &self.registry,
            input_pin,
        )
    }

    /// Round 31 — pop the oldest sample captured by the
    /// downstream `HostIMemInputPin::Receive` callback.
    pub fn pop_received_sample(&self) -> Option<crate::com::host_iface_r31::ReceivedSample> {
        crate::com::host_iface_r31::pop_sample(&self.host)
    }

    /// Round 31 — number of samples currently waiting in the
    /// host-side queue.
    pub fn received_samples_len(&self) -> usize {
        crate::com::host_iface_r31::queue_len(&self.host)
    }

    /// Round 33 — return the most recent
    /// `IMemAllocator::SetProperties` capture observed on this
    /// sandbox, or `None` if no codec has called `SetProperties`
    /// yet.  See [`crate::com::AllocatorPropertiesCapture`] for
    /// the captured field shape.
    pub fn last_set_properties(&self) -> Option<crate::com::AllocatorPropertiesCapture> {
        crate::com::last_set_properties(&self.host)
    }

    /// Round 33 — return every `SetProperties` capture observed on
    /// this sandbox, in arrival order.
    pub fn all_set_properties(&self) -> Vec<crate::com::AllocatorPropertiesCapture> {
        crate::com::all_set_properties(&self.host)
    }

    /// Round 33 — drop every captured `SetProperties` for this
    /// sandbox.  Useful for resetting per-test state.
    pub fn clear_set_properties_log(&self) {
        crate::com::clear_set_properties_log(&self.host)
    }

    /// Drive `obj->AddRef()`.  Returns the codec-reported new
    /// refcount; the host's bookkeeping is updated automatically.
    pub fn com_add_ref(&mut self, obj: u32) -> Result<u32, crate::Error> {
        crate::com::call::add_ref(
            &mut self.cpu,
            &mut self.mmu,
            &self.registry,
            &mut self.host,
            obj,
        )
    }

    /// Drive `obj->Release()`.  Returns the codec-reported new
    /// refcount.  The host's bookkeeping is updated automatically.
    pub fn com_release(&mut self, obj: u32) -> Result<u32, crate::Error> {
        crate::com::call::release(
            &mut self.cpu,
            &mut self.mmu,
            &self.registry,
            &mut self.host,
            obj,
        )
    }

    /// `ICDecompress` — decode one frame.
    #[allow(clippy::too_many_arguments)]
    pub fn ic_decompress(
        &mut self,
        hic: u32,
        flags: u32,
        input_bih: &vfw32::Bih,
        input_bytes: &[u8],
        output_bih: &vfw32::Bih,
        output_capacity: u32,
    ) -> Result<(u32, Vec<u8>), crate::Error> {
        vfw32::ic_decompress(
            &mut self.cpu,
            &mut self.mmu,
            &self.registry,
            &mut self.host,
            hic,
            flags,
            input_bih,
            input_bytes,
            output_bih,
            output_capacity,
        )
    }

    // ---- Round 51: encode (compress) wrappers --------------------------

    /// `ICCompressQuery` — does the codec accept this input/output
    /// format pair? `output` may be `None` to defer the choice.
    pub fn ic_compress_query(
        &mut self,
        hic: u32,
        input: &vfw32::Bih,
        output: Option<&vfw32::Bih>,
    ) -> Result<u32, crate::Error> {
        vfw32::ic_compress_query(
            &mut self.cpu,
            &mut self.mmu,
            &self.registry,
            &mut self.host,
            hic,
            input,
            output,
        )
    }

    /// `ICCompressGetFormat` — ask the codec for the output BIH
    /// describing what its compressed format looks like for the
    /// supplied input.
    pub fn ic_compress_get_format(
        &mut self,
        hic: u32,
        input: &vfw32::Bih,
    ) -> Result<(u32, vfw32::Bih), crate::Error> {
        vfw32::ic_compress_get_format(
            &mut self.cpu,
            &mut self.mmu,
            &self.registry,
            &mut self.host,
            hic,
            input,
        )
    }

    /// `ICCompressGetSize` — max encoded-frame byte count for the
    /// supplied input/output BIH pair.
    pub fn ic_compress_get_size(
        &mut self,
        hic: u32,
        input: &vfw32::Bih,
        output: &vfw32::Bih,
    ) -> Result<u32, crate::Error> {
        vfw32::ic_compress_get_size(
            &mut self.cpu,
            &mut self.mmu,
            &self.registry,
            &mut self.host,
            hic,
            input,
            output,
        )
    }

    /// `ICCompressBegin` — set up the encoder pipeline.
    pub fn ic_compress_begin(
        &mut self,
        hic: u32,
        input: &vfw32::Bih,
        output: &vfw32::Bih,
    ) -> Result<u32, crate::Error> {
        vfw32::ic_compress_begin(
            &mut self.cpu,
            &mut self.mmu,
            &self.registry,
            &mut self.host,
            hic,
            input,
            output,
        )
    }

    /// `ICCompressEnd` — tear down the encoder pipeline.
    pub fn ic_compress_end(&mut self, hic: u32) -> Result<u32, crate::Error> {
        vfw32::ic_compress_end(
            &mut self.cpu,
            &mut self.mmu,
            &self.registry,
            &mut self.host,
            hic,
        )
    }

    /// `ICCompress` — encode one frame. Returns the full encode
    /// outcome: codec LRESULT, encoded bytes, the post-call output
    /// BIH (whose `biSizeImage` holds the actual encoded byte
    /// count), the codec-written `*lpdwFlags` (e.g. whether the
    /// codec marked the emitted frame as a keyframe), and the
    /// codec-written `*lpckid`.
    ///
    /// `prev_bih_opt` / `prev_bytes_opt` are the previous
    /// reconstructed frame (P-frame encoding). Pass `None` for
    /// keyframes.
    #[allow(clippy::too_many_arguments)]
    pub fn ic_compress(
        &mut self,
        hic: u32,
        flags: u32,
        input_bih: &vfw32::Bih,
        input_bytes: &[u8],
        output_bih: &vfw32::Bih,
        output_capacity: u32,
        ckid: u32,
        frame_num: i32,
        frame_size_limit: u32,
        quality: u32,
        prev_bih_opt: Option<&vfw32::Bih>,
        prev_bytes_opt: Option<&[u8]>,
    ) -> Result<vfw32::CompressOutcome, crate::Error> {
        vfw32::ic_compress(
            &mut self.cpu,
            &mut self.mmu,
            &self.registry,
            &mut self.host,
            hic,
            flags,
            input_bih,
            input_bytes,
            output_bih,
            output_capacity,
            ckid,
            frame_num,
            frame_size_limit,
            quality,
            prev_bih_opt,
            prev_bytes_opt,
        )
    }

    /// `ICGetState` — ask the codec to serialise its private
    /// per-instance state into `dst_buf`.  Returns the byte count
    /// the codec actually wrote.
    ///
    /// Round 70 — wraps `ICM_GETSTATE` (`0x5009`) per MSDN; required
    /// by oxideav-tracevfw to drive the encoder's per-quality knob
    /// round-trip alongside [`Self::ic_set_state`].  See MSDN
    /// `ICGetState` topic page for the public contract.
    pub fn ic_get_state(&mut self, hic: u32, dst_buf: &mut [u8]) -> Result<u32, crate::Error> {
        vfw32::ic_get_state(
            &mut self.cpu,
            &mut self.mmu,
            &self.registry,
            &mut self.host,
            hic,
            dst_buf,
        )
    }

    /// `ICSetState` — ask the codec to deserialise `src_buf` into
    /// its private per-instance state.  Returns `Ok(())` on
    /// `ICERR_OK`, or [`crate::Error`] wrapping the codec's raw
    /// `LRESULT` otherwise.
    ///
    /// Round 70 — wraps `ICM_SETSTATE` (`0x500A`) per MSDN.  See
    /// MSDN `ICSetState` topic page for the public contract.
    pub fn ic_set_state(&mut self, hic: u32, src_buf: &[u8]) -> Result<(), crate::Error> {
        vfw32::ic_set_state(
            &mut self.cpu,
            &mut self.mmu,
            &self.registry,
            &mut self.host,
            hic,
            src_buf,
        )
    }

    /// Round 63 — patch `msadds32.ax`'s `helper_addref` thunk (at
    /// RVA `0x5cea`) to unconditionally return `value` (32-bit
    /// integer).
    ///
    /// **Why.** Round-62 forensics
    /// (`docs/codec/msadds32-receive-null-0x20.md`) traced the
    /// `IMemInputPin::Receive` NULL-deref trap at RVA `0x256a` to
    /// a buffer-pool init that's handed a size of zero.  The size
    /// is `(h * 10) / size_calc(...)` where `h` is what
    /// `helper_addref` returns.  On a fresh codec instance the
    /// helper-object field at `helper_90 + 0x3c` (the "initialised"
    /// flag the addref checks) is zero, so `helper_addref` returns
    /// `0`, the quotient is `0`, `operator new(0)` returns NULL,
    /// `buffer_pool_init` fails, and the Receive cleanup branch
    /// trips a NULL+0x20 deref.
    ///
    /// In a real DirectShow host the flag is set during
    /// `IFilterGraph::JoinFilterGraph` / `Pause` (the codec stamps
    /// the field as part of its run-state machine).  Until we
    /// drive that path, the surgical workaround is to short-circuit
    /// `helper_addref` to return a fixed non-zero value — which
    /// empirically lifts the trap and lets Receive run to
    /// completion (with HRESULT `0x8000ffff` from the decode body,
    /// which is the next round's investigation surface).
    ///
    /// **Encoding.** The original function (RVA `0x5cea`, 10 bytes)
    /// is:
    ///
    /// ```text
    /// 0x5cea: 83 79 20 00  cmp [ecx+0x20], 0
    /// 0x5cee: 74 04        jz  +4
    /// 0x5cf0: 8b 41 28     mov eax, [ecx+0x28]
    /// 0x5cf3: c3           ret
    /// 0x5cf4: 33 c0        xor eax, eax
    /// 0x5cf6: c3           ret
    /// ```
    ///
    /// We overwrite the first 6 bytes with:
    ///
    /// ```text
    /// b8 XX XX XX XX  mov eax, imm32
    /// c3              ret
    /// ```
    ///
    /// The remaining bytes at `0x5cf0..0x5cf6` are unreachable
    /// after the patch (no caller enters there directly), so the
    /// dead-code is harmless.
    ///
    /// `image_base` is the address the codec was loaded at; pass
    /// the value returned by [`Self::load`] on `msadds32.ax`.
    ///
    /// # Reference material (clean-room only)
    ///
    /// * Intel SDM Vol. 2A — `MOV imm32` (`B8+rd`), `RET` (`C3`).
    /// * Raw bytes of `msadds32.ax` from
    ///   `docs/video/msmpeg4/reference/binaries/wmpcdcs8-2001/`.
    ///
    /// No Wine / ReactOS / MinGW / Microsoft DShow source consulted.
    pub fn msadds32_patch_helper_addref(
        &mut self,
        image_base: u32,
        value: u32,
    ) -> Result<(), crate::Error> {
        const RVA_HELPER_ADDREF: u32 = 0x5cea;
        let va = image_base.wrapping_add(RVA_HELPER_ADDREF);
        let mut patch = [0u8; 6];
        patch[0] = 0xb8; // mov eax, imm32
        patch[1..5].copy_from_slice(&value.to_le_bytes());
        patch[5] = 0xc3; // ret
        self.mmu
            .write_initializer(va, &patch)
            .map_err(crate::Error::Trap)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::emulator::isa_int::RET_SENTINEL;
    use crate::emulator::regs::Reg32;
    use crate::pe::test_image::build_minimal_dll;

    #[test]
    fn load_synth_dll_and_run_dll_main_returns_to_sentinel() {
        let bytes = build_minimal_dll();
        let mut sb = Sandbox::new();
        let img = sb.load("synth.dll", &bytes).unwrap();
        // Pre-set eax = 1 so we can confirm the synth DllMain
        // returned without modifying it (it's just `ret 12`).
        sb.cpu.regs.set32(Reg32::Eax, 1);
        let ret = sb.call_dll_main(&img, DLL_PROCESS_ATTACH).unwrap();
        assert_eq!(ret, 1);
        assert_eq!(sb.cpu.regs.eip, RET_SENTINEL);
    }

    #[test]
    fn calling_through_iat_thunk_invokes_kernel32_stub() {
        // Emulator-only test: fabricate a code block that calls
        // a kernel32!GetProcessHeap thunk and rets. Verifies the
        // run loop's "is_thunk → dispatch" path.
        let mut sb = Sandbox::new();
        let thunk = sb
            .registry
            .resolve("kernel32.dll", "GetProcessHeap")
            .unwrap();
        // Map a code page at 0x1000.
        sb.mmu.map(0x1000, 0x1000, Perm::R | Perm::X);
        // call dword [thunk_slot]; ret 0
        // Easier: set eip directly to the thunk after pushing
        // the synthetic ret-sentinel.
        sb.cpu.push32(&mut sb.mmu, RET_SENTINEL).unwrap();
        sb.cpu.regs.eip = thunk;
        sb.run_until_sentinel().unwrap();
        assert_eq!(sb.cpu.regs.get32(Reg32::Eax), 0xDEAD_BEEF);
    }

    /// Phase 3c of the scheduler refactor: `WaitForSingleObject`
    /// on an unsignalled auto-reset Event parks the calling
    /// thread; `SetEvent` from a peer wakes exactly one waiter.
    /// We exercise this directly through state mutation rather
    /// than spawning guest threads (the kernel32 thunk path is
    /// covered by the spawn test below).
    #[test]
    fn wait_for_single_object_blocks_until_set_event() {
        let mut sb = Sandbox::new();
        // Mint an auto-reset Event, initially unsignalled.
        let h = sb
            .host
            .scheduler
            .insert_object(crate::sched::WaitObject::Event {
                signaled: false,
                manual_reset: false,
            });
        // Inject a second thread parked on a wait for the event.
        let mut t2 = crate::win32::ThreadState::new(2, 1);
        t2.parked_cpu = Some(crate::emulator::Cpu::new());
        t2.status = crate::sched::ThreadStatus::Waiting;
        t2.wait = Some(crate::sched::WaitCondition::Object {
            handle: h,
            timeout_after: None,
        });
        sb.host.threads.insert(2, t2);

        // Bootstrap drives SetEvent via the kernel32 thunk.
        let set_event = sb.registry.resolve("kernel32.dll", "SetEvent").unwrap();
        sb.cpu.push32(&mut sb.mmu, h).unwrap();
        sb.cpu.push32(&mut sb.mmu, RET_SENTINEL).unwrap();
        sb.cpu.regs.eip = set_event;
        sb.run_until_sentinel().unwrap();

        // Thread 2 should be back to Ready with no wait.
        let t = sb.host.threads.get(&2).unwrap();
        assert!(
            matches!(t.status, crate::sched::ThreadStatus::Ready),
            "expected thread 2 Ready, got {:?}",
            t.status
        );
        assert!(t.wait.is_none(), "wait condition must be cleared");
        // Auto-reset: the signal is consumed by the wake.
        match sb.host.scheduler.objects.get(&h).unwrap() {
            crate::sched::WaitObject::Event { signaled, .. } => assert!(!*signaled),
            _ => panic!(),
        }
    }

    /// Mutex round-trip: contention parks the second caller,
    /// `ReleaseMutex` from the holder wakes them and transfers
    /// ownership.
    #[test]
    fn mutex_transfers_ownership_on_release() {
        let mut sb = Sandbox::new();
        // Mint a Mutex owned by tid 1 (the bootstrap).
        let h = sb
            .host
            .scheduler
            .insert_object(crate::sched::WaitObject::Mutex {
                owner: Some(1),
                recursion: 1,
            });
        // Inject thread 2 waiting on the mutex.
        let mut t2 = crate::win32::ThreadState::new(2, 1);
        t2.parked_cpu = Some(crate::emulator::Cpu::new());
        t2.status = crate::sched::ThreadStatus::Waiting;
        t2.wait = Some(crate::sched::WaitCondition::Object {
            handle: h,
            timeout_after: None,
        });
        sb.host.threads.insert(2, t2);

        // Bootstrap calls ReleaseMutex.
        let release = sb.registry.resolve("kernel32.dll", "ReleaseMutex").unwrap();
        sb.cpu.push32(&mut sb.mmu, h).unwrap();
        sb.cpu.push32(&mut sb.mmu, RET_SENTINEL).unwrap();
        sb.cpu.regs.eip = release;
        sb.run_until_sentinel().unwrap();
        assert_eq!(sb.cpu.regs.get32(Reg32::Eax), 1, "release succeeds");

        // Ownership transferred to thread 2; thread 2 Ready.
        match sb.host.scheduler.objects.get(&h).unwrap() {
            crate::sched::WaitObject::Mutex { owner, recursion } => {
                assert_eq!(*owner, Some(2));
                assert_eq!(*recursion, 1);
            }
            _ => panic!(),
        }
        let t = sb.host.threads.get(&2).unwrap();
        assert!(matches!(t.status, crate::sched::ThreadStatus::Ready));
    }

    /// Semaphore round-trip: `ReleaseSemaphore(N)` wakes up to
    /// N waiters and bumps the count.
    #[test]
    fn semaphore_release_wakes_waiters_and_bumps_count() {
        let mut sb = Sandbox::new();
        let h = sb
            .host
            .scheduler
            .insert_object(crate::sched::WaitObject::Semaphore { count: 0, max: 10 });
        // Two waiters.
        for tid in [2u32, 3u32] {
            let mut t = crate::win32::ThreadState::new(tid, 1);
            t.parked_cpu = Some(crate::emulator::Cpu::new());
            t.status = crate::sched::ThreadStatus::Waiting;
            t.wait = Some(crate::sched::WaitCondition::Object {
                handle: h,
                timeout_after: None,
            });
            sb.host.threads.insert(tid, t);
        }
        // Bootstrap releases 2.
        let release = sb
            .registry
            .resolve("kernel32.dll", "ReleaseSemaphore")
            .unwrap();
        sb.mmu.map(0x500_0000, 0x1000, Perm::R | Perm::W);
        let p_prev = 0x500_0000u32;
        sb.cpu.push32(&mut sb.mmu, p_prev).unwrap();
        sb.cpu.push32(&mut sb.mmu, 2u32).unwrap();
        sb.cpu.push32(&mut sb.mmu, h).unwrap();
        sb.cpu.push32(&mut sb.mmu, RET_SENTINEL).unwrap();
        sb.cpu.regs.eip = release;
        sb.run_until_sentinel().unwrap();
        assert_eq!(sb.cpu.regs.get32(Reg32::Eax), 1);
        // Previous count was 0.
        assert_eq!(sb.mmu.load32(p_prev).unwrap(), 0);
        // Both waiters woke; each consumed one count → net count = 0.
        match sb.host.scheduler.objects.get(&h).unwrap() {
            crate::sched::WaitObject::Semaphore { count, .. } => {
                assert_eq!(*count, 0, "both waiters consumed their signals");
            }
            _ => panic!(),
        }
        for tid in [2u32, 3u32] {
            let t = sb.host.threads.get(&tid).unwrap();
            assert!(matches!(t.status, crate::sched::ThreadStatus::Ready));
        }
    }

    /// Phase 5c: when the target EXE is staged in the
    /// VirtualFs, `CreateProcessA` actually loads it at a
    /// fresh image base and mints a Ready primary thread the
    /// scheduler can run alongside the parent. The PE used
    /// here is the synthetic-DLL fixture — it has a real PE
    /// header and the only import (`kernel32!ExitProcess`) is
    /// satisfied by our stub registry.
    #[test]
    fn create_process_a_loads_real_child_pe_from_vfs() {
        use crate::pe::test_image::build_minimal_dll;
        let mut sb = Sandbox::default();
        // Stage a child binary in the VFS.
        let dll_bytes = build_minimal_dll();
        let child_path = "c:\\setup\\helper.exe";
        let mut vfs = crate::context::VirtualFs::new();
        vfs.insert(child_path, dll_bytes);
        sb.host.context.vfs = Some(vfs);

        // Stage a PROCESS_INFORMATION scratch region.
        sb.mmu.map(0x500_0000, 0x1000, Perm::R | Perm::W);
        let pi = 0x500_0000u32;
        // Stage the lpApplicationName string.
        sb.mmu.map(0x500_1000, 0x1000, Perm::R | Perm::W);
        let app_ptr = 0x500_1000u32;
        sb.mmu
            .write_initializer(app_ptr, child_path.as_bytes())
            .unwrap();
        sb.mmu.store8(app_ptr + child_path.len() as u32, 0).unwrap();

        let create_proc = sb
            .registry
            .resolve("kernel32.dll", "CreateProcessA")
            .unwrap();
        for &a in [app_ptr, 0u32, 0, 0, 0, 0, 0, 0, 0, pi].iter().rev() {
            sb.cpu.push32(&mut sb.mmu, a).unwrap();
        }
        sb.cpu.push32(&mut sb.mmu, RET_SENTINEL).unwrap();
        sb.cpu.regs.eip = create_proc;
        sb.run_until_sentinel().unwrap();
        assert_eq!(sb.cpu.regs.get32(Reg32::Eax), 1, "CreateProcessA TRUE");

        // The new process should be in the table, distinct PID,
        // and its primary thread Ready (not Terminated like the
        // fake-child fallback).
        let child_pid = sb.mmu.load32(pi + 8).unwrap();
        let child_tid = sb.mmu.load32(pi + 12).unwrap();
        let p = sb
            .host
            .processes
            .get(&child_pid)
            .expect("child process present");
        assert_ne!(
            p.image_base, 0,
            "child PE was rebased into a fresh image slot"
        );
        assert_eq!(p.parent_pid, 1);
        let t = sb
            .host
            .threads
            .get(&child_tid)
            .expect("child primary thread present");
        assert!(matches!(
            t.status,
            crate::sched::ThreadStatus::Ready | crate::sched::ThreadStatus::Running
        ));
        // The minimal-DLL entry just rets, so a subsequent
        // run_until_sentinel will Halt it cleanly.
    }

    /// Phase 3d: `EnterCriticalSection` takes ownership of an
    /// implicit Mutex keyed by `LPCRITICAL_SECTION`'s guest
    /// address; recursion increments on re-entry by the same
    /// thread; `LeaveCriticalSection` decrements and clears
    /// ownership when the count reaches zero. Exercised through
    /// IPC: `CreatePipe` mints a read/write handle pair;
    /// `WriteFile` on the write end stages bytes that
    /// `ReadFile` on the read end picks up. The two handles
    /// share an in-memory buffer through the scheduler's
    /// pipe table; closing the write end drains EOF on the
    /// reader.
    #[test]
    fn create_pipe_write_read_round_trip() {
        let mut sb = Sandbox::new();
        // Scratch region for handle outputs + data buffers.
        sb.mmu.map(0x500_0000, 0x1000, Perm::R | Perm::W);
        let p_read_h = 0x500_0000u32;
        let p_write_h = 0x500_0004u32;
        let p_written = 0x500_0010u32;
        let p_data_in = 0x500_0020u32; // bytes to write
        let p_data_out = 0x500_0040u32; // bytes to read into
        let p_n_read = 0x500_0080u32;

        // CreatePipe(read, write, NULL, 0).
        let create_pipe = sb.registry.resolve("kernel32.dll", "CreatePipe").unwrap();
        for &a in [p_read_h, p_write_h, 0u32, 0u32].iter().rev() {
            sb.cpu.push32(&mut sb.mmu, a).unwrap();
        }
        sb.cpu.push32(&mut sb.mmu, RET_SENTINEL).unwrap();
        sb.cpu.regs.eip = create_pipe;
        sb.run_until_sentinel().unwrap();
        assert_eq!(sb.cpu.regs.get32(Reg32::Eax), 1, "CreatePipe TRUE");
        let h_read = sb.mmu.load32(p_read_h).unwrap();
        let h_write = sb.mmu.load32(p_write_h).unwrap();
        assert!(h_read >= crate::sched::WAIT_OBJECT_HANDLE_BASE);
        assert_ne!(h_read, h_write, "distinct ends");

        // Stage data in MMU + WriteFile(write_handle, data, 5, &written, NULL).
        sb.mmu.write_initializer(p_data_in, b"HELLO").unwrap();
        let write_file = sb.registry.resolve("kernel32.dll", "WriteFile").unwrap();
        for &a in [h_write, p_data_in, 5u32, p_written, 0u32].iter().rev() {
            sb.cpu.push32(&mut sb.mmu, a).unwrap();
        }
        sb.cpu.push32(&mut sb.mmu, RET_SENTINEL).unwrap();
        sb.cpu.regs.eip = write_file;
        sb.run_until_sentinel().unwrap();
        assert_eq!(sb.cpu.regs.get32(Reg32::Eax), 1);
        assert_eq!(sb.mmu.load32(p_written).unwrap(), 5);

        // ReadFile(read_handle, out_buf, 5, &n_read, NULL).
        let read_file = sb.registry.resolve("kernel32.dll", "ReadFile").unwrap();
        for &a in [h_read, p_data_out, 5u32, p_n_read, 0u32].iter().rev() {
            sb.cpu.push32(&mut sb.mmu, a).unwrap();
        }
        sb.cpu.push32(&mut sb.mmu, RET_SENTINEL).unwrap();
        sb.cpu.regs.eip = read_file;
        sb.run_until_sentinel().unwrap();
        assert_eq!(sb.cpu.regs.get32(Reg32::Eax), 1);
        assert_eq!(sb.mmu.load32(p_n_read).unwrap(), 5);
        // Verify the bytes round-tripped.
        let mut got = [0u8; 5];
        for i in 0..5 {
            got[i] = sb.mmu.load8(p_data_out + i as u32).unwrap();
        }
        assert_eq!(&got, b"HELLO");
    }

    /// Named-pipe handshake: a `CreateNamedPipeA(\\.\pipe\X)`
    /// server end + a `CreateFileA(\\.\pipe\X)` client end
    /// reach each other through the named-object registry
    /// and share a buffer for `WriteFile` / `ReadFile`.
    #[test]
    fn named_pipe_server_and_client_share_buffer() {
        let mut sb = Sandbox::new();
        sb.mmu.map(0x501_0000, 0x1000, Perm::R | Perm::W);
        let p_name = 0x501_0000u32;
        let pipe_path = b"\\\\.\\pipe\\test\0";
        sb.mmu.write_initializer(p_name, pipe_path).unwrap();
        let p_data_in = 0x501_0100u32;
        let p_data_out = 0x501_0200u32;
        let p_written = 0x501_0300u32;
        let p_n_read = 0x501_0310u32;

        // CreateNamedPipeA(name, PIPE_ACCESS_OUTBOUND, ...). With
        // OUTBOUND, the server holds the write end.
        let cnp = sb
            .registry
            .resolve("kernel32.dll", "CreateNamedPipeA")
            .unwrap();
        for &a in [p_name, 2u32, 0u32, 1u32, 4096u32, 4096u32, 0u32, 0u32]
            .iter()
            .rev()
        {
            sb.cpu.push32(&mut sb.mmu, a).unwrap();
        }
        sb.cpu.push32(&mut sb.mmu, RET_SENTINEL).unwrap();
        sb.cpu.regs.eip = cnp;
        sb.run_until_sentinel().unwrap();
        let h_server = sb.cpu.regs.get32(Reg32::Eax);
        assert!(h_server >= crate::sched::WAIT_OBJECT_HANDLE_BASE);

        // Client: CreateFileA(\\.\pipe\test, GENERIC_READ, ...).
        let cfa = sb.registry.resolve("kernel32.dll", "CreateFileA").unwrap();
        for &a in [p_name, 0x8000_0000u32, 0u32, 0u32, 3u32, 0u32, 0u32]
            .iter()
            .rev()
        {
            sb.cpu.push32(&mut sb.mmu, a).unwrap();
        }
        sb.cpu.push32(&mut sb.mmu, RET_SENTINEL).unwrap();
        sb.cpu.regs.eip = cfa;
        sb.run_until_sentinel().unwrap();
        let h_client = sb.cpu.regs.get32(Reg32::Eax);
        assert_ne!(h_client, 0xFFFF_FFFF, "client open should succeed");
        assert_ne!(h_client, h_server, "distinct handles");

        // Server WriteFile.
        sb.mmu.write_initializer(p_data_in, b"PING!").unwrap();
        let wfile = sb.registry.resolve("kernel32.dll", "WriteFile").unwrap();
        for &a in [h_server, p_data_in, 5u32, p_written, 0u32].iter().rev() {
            sb.cpu.push32(&mut sb.mmu, a).unwrap();
        }
        sb.cpu.push32(&mut sb.mmu, RET_SENTINEL).unwrap();
        sb.cpu.regs.eip = wfile;
        sb.run_until_sentinel().unwrap();
        assert_eq!(sb.cpu.regs.get32(Reg32::Eax), 1);
        assert_eq!(sb.mmu.load32(p_written).unwrap(), 5);

        // Client ReadFile.
        let rfile = sb.registry.resolve("kernel32.dll", "ReadFile").unwrap();
        for &a in [h_client, p_data_out, 5u32, p_n_read, 0u32].iter().rev() {
            sb.cpu.push32(&mut sb.mmu, a).unwrap();
        }
        sb.cpu.push32(&mut sb.mmu, RET_SENTINEL).unwrap();
        sb.cpu.regs.eip = rfile;
        sb.run_until_sentinel().unwrap();
        assert_eq!(sb.cpu.regs.get32(Reg32::Eax), 1);
        assert_eq!(sb.mmu.load32(p_n_read).unwrap(), 5);
        let mut got = [0u8; 5];
        for i in 0..5 {
            got[i] = sb.mmu.load8(p_data_out + i as u32).unwrap();
        }
        assert_eq!(&got, b"PING!");
    }

    /// the kernel32 thunk dispatch.
    #[test]
    fn enter_leave_critical_section_round_trip() {
        let mut sb = Sandbox::new();
        // Map a CRITICAL_SECTION scratch region.
        sb.mmu.map(0x400_0000, 0x1000, Perm::R | Perm::W);
        let cs = 0x400_0000u32;
        let enter = sb
            .registry
            .resolve("kernel32.dll", "EnterCriticalSection")
            .unwrap();
        let leave = sb
            .registry
            .resolve("kernel32.dll", "LeaveCriticalSection")
            .unwrap();
        // First enter: take ownership, recursion=1.
        sb.cpu.push32(&mut sb.mmu, cs).unwrap();
        sb.cpu.push32(&mut sb.mmu, RET_SENTINEL).unwrap();
        sb.cpu.regs.eip = enter;
        sb.run_until_sentinel().unwrap();
        let h = sb.host.scheduler.critical_sections[&cs];
        match sb.host.scheduler.objects.get(&h).unwrap() {
            crate::sched::WaitObject::CriticalSection {
                owner, recursion, ..
            } => {
                assert_eq!(*owner, Some(1));
                assert_eq!(*recursion, 1);
            }
            _ => panic!(),
        }
        // Re-entry by same thread: recursion=2.
        sb.cpu.push32(&mut sb.mmu, cs).unwrap();
        sb.cpu.push32(&mut sb.mmu, RET_SENTINEL).unwrap();
        sb.cpu.regs.eip = enter;
        sb.run_until_sentinel().unwrap();
        match sb.host.scheduler.objects.get(&h).unwrap() {
            crate::sched::WaitObject::CriticalSection { recursion, .. } => {
                assert_eq!(*recursion, 2);
            }
            _ => panic!(),
        }
        // First leave: recursion→1.
        sb.cpu.push32(&mut sb.mmu, cs).unwrap();
        sb.cpu.push32(&mut sb.mmu, RET_SENTINEL).unwrap();
        sb.cpu.regs.eip = leave;
        sb.run_until_sentinel().unwrap();
        // Second leave: recursion→0, owner cleared.
        sb.cpu.push32(&mut sb.mmu, cs).unwrap();
        sb.cpu.push32(&mut sb.mmu, RET_SENTINEL).unwrap();
        sb.cpu.regs.eip = leave;
        sb.run_until_sentinel().unwrap();
        match sb.host.scheduler.objects.get(&h).unwrap() {
            crate::sched::WaitObject::CriticalSection {
                owner, recursion, ..
            } => {
                assert_eq!(*owner, None);
                assert_eq!(*recursion, 0);
            }
            _ => panic!(),
        }
    }

    /// Phase 3b of the scheduler refactor: `CreateThread` mints
    /// a Ready thread, the scheduler context-switches into it
    /// the first time the bootstrap thread yields, and the new
    /// thread runs to its own RET_SENTINEL where it
    /// terminates. Verifies both halves of the round trip.
    #[test]
    fn create_thread_spawns_a_real_runnable_thread() {
        let mut sb = Sandbox::new();
        // Map a code page for the synthetic thread proc.
        sb.mmu.map(0x1000, 0x1000, Perm::R | Perm::X);
        // Thread proc: `mov eax, 0x42; ret 4` (stdcall, one arg
        // consumed; eax = exit code).
        let proc_va = 0x1010u32;
        let proc_code: [u8; 8] = [
            0xb8, 0x42, 0x00, 0x00, 0x00, // mov eax, 0x42
            0xc2, 0x04, 0x00, // ret 4
        ];
        sb.mmu.write_initializer(proc_va, &proc_code).unwrap();
        // Drive CreateThread via the kernel32 thunk so we exercise
        // the same code path a real codec would.
        let create_thread = sb.registry.resolve("kernel32.dll", "CreateThread").unwrap();
        // Push args right-to-left: (attrs, stack, start, param,
        // flags, p_tid) = (0, 0, proc_va, 0xCAFE, 0, 0).
        for &a in [0u32, 0, proc_va, 0xCAFE, 0, 0].iter().rev() {
            sb.cpu.push32(&mut sb.mmu, a).unwrap();
        }
        sb.cpu.push32(&mut sb.mmu, RET_SENTINEL).unwrap();
        sb.cpu.regs.eip = create_thread;
        sb.run_until_sentinel().unwrap();
        let thread_handle = sb.cpu.regs.get32(Reg32::Eax);
        assert!(thread_handle >= crate::sched::WAIT_OBJECT_HANDLE_BASE);
        // The new thread is in the table, Ready, with its CPU
        // parked. TID 2 (bootstrap is 1).
        let t = sb.host.threads.get(&2).expect("new thread present");
        assert!(matches!(t.status, crate::sched::ThreadStatus::Ready));
        assert!(t.parked_cpu.is_some());
        assert_ne!(
            t.parked_cpu.as_ref().unwrap().regs.esp(),
            0,
            "stack was carved from the pool"
        );

        // Bootstrap now Sleeps — the scheduler must context
        // switch into the new thread, run it to its
        // RET_SENTINEL, mark it Terminated, and then come
        // back to the bootstrap (which wakes after the sleep
        // clock advances).
        let sleep_thunk = sb.registry.resolve("kernel32.dll", "Sleep").unwrap();
        // Sleep(1ms)
        sb.cpu.push32(&mut sb.mmu, 1u32).unwrap();
        sb.cpu.push32(&mut sb.mmu, RET_SENTINEL).unwrap();
        sb.cpu.regs.eip = sleep_thunk;
        sb.run_until_sentinel().unwrap();
        // After the run, the new thread should have ran to
        // completion (status Terminated, eax = 0x42 on its
        // parked CPU if any).
        let t = sb.host.threads.get(&2).expect("new thread still present");
        assert!(
            matches!(t.status, crate::sched::ThreadStatus::Terminated),
            "expected thread 2 Terminated, got {:?}",
            t.status
        );
    }
}