ud-emulator 0.1.3

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
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
//! `kernel32.dll` stubs — the minimum surface a Cinepak-class
//! codec DLL imports.
//!
//! Round-1 set per design doc §"`kernel32.dll` essentials" and
//! §"Milestone 1":
//!
//! * `GetProcessHeap`
//! * `HeapAlloc`, `HeapFree`, `HeapReAlloc`
//! * `LocalAlloc`, `LocalFree`
//! * `OutputDebugStringA`
//! * `GetTickCount`
//! * `InterlockedIncrement`, `InterlockedDecrement`
//! * `LoadLibraryA`, `GetProcAddress`
//!
//! Round-4 adds the additional 24 `kernel32` stubs an Indeo 3
//! class DLL imports through its CRT init: `ExitProcess`,
//! `GetACP` / `GetOEMCP` / `GetCPInfo`, `GetCommandLineA`,
//! `GetEnvironmentStrings`, `GetFileType`, `GetLastError` /
//! `SetLastError`, `GetModuleFileNameA` / `GetModuleHandleA`,
//! `GetStartupInfoA` / `GetStdHandle` / `GetSystemInfo` /
//! `GetVersion`, `GlobalAlloc` / `GlobalFree` / `GlobalLock` /
//! `GlobalUnlock`, `MultiByteToWideChar` / `WideCharToMultiByte`,
//! `RtlUnwind`, `VirtualAlloc` / `VirtualFree`, `WriteFile`.
//!
//! Each stub references its MSDN page in a comment for review;
//! the implementations honour the public contract (return
//! values, error semantics, side effects on `lastError`).

use super::{arg_dword, HostState, Registry, StubFn, Win32Error};
use crate::emulator::mmu::{Perm, PAGE_SIZE};
use crate::emulator::{Cpu, Mmu};

/// Register every kernel32 stub into `registry`.
pub fn register(registry: &mut Registry) {
    // The list mirrors the design doc §Milestone 1; comments
    // cite the MSDN page.

    // https://learn.microsoft.com/en-us/windows/win32/api/heapapi/nf-heapapi-getprocessheap
    registry.register(
        "kernel32.dll",
        "GetProcessHeap",
        stub_get_process_heap as StubFn,
        0,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/heapapi/nf-heapapi-heapalloc
    registry.register("kernel32.dll", "HeapAlloc", stub_heap_alloc as StubFn, 3);
    // https://learn.microsoft.com/en-us/windows/win32/api/heapapi/nf-heapapi-heapfree
    registry.register("kernel32.dll", "HeapFree", stub_heap_free as StubFn, 3);
    // https://learn.microsoft.com/en-us/windows/win32/api/heapapi/nf-heapapi-heaprealloc
    registry.register(
        "kernel32.dll",
        "HeapReAlloc",
        stub_heap_realloc as StubFn,
        4,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/heapapi/nf-heapapi-heapsize
    // Round 15 — IR41_32.AX uses HeapSize to query the live size
    // of an allocation it returned from HeapAlloc / HeapReAlloc.
    registry.register("kernel32.dll", "HeapSize", stub_heap_size as StubFn, 3);
    // https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-localalloc
    registry.register("kernel32.dll", "LocalAlloc", stub_local_alloc as StubFn, 2);
    // https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-localfree
    registry.register("kernel32.dll", "LocalFree", stub_local_free as StubFn, 1);
    // https://learn.microsoft.com/en-us/windows/win32/api/debugapi/nf-debugapi-outputdebugstringa
    registry.register(
        "kernel32.dll",
        "OutputDebugStringA",
        stub_output_debug_string_a as StubFn,
        1,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-gettickcount
    registry.register(
        "kernel32.dll",
        "GetTickCount",
        stub_get_tick_count as StubFn,
        0,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/winnt/nf-winnt-interlockedincrement
    registry.register(
        "kernel32.dll",
        "InterlockedIncrement",
        stub_interlocked_increment as StubFn,
        1,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/winnt/nf-winnt-interlockeddecrement
    registry.register(
        "kernel32.dll",
        "InterlockedDecrement",
        stub_interlocked_decrement as StubFn,
        1,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-loadlibrarya
    registry.register(
        "kernel32.dll",
        "LoadLibraryA",
        stub_load_library_a as StubFn,
        1,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-getprocaddress
    registry.register(
        "kernel32.dll",
        "GetProcAddress",
        stub_get_proc_address as StubFn,
        2,
    );

    // ---- Round-4 additions (24 stubs) -----------------------------

    // https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-exitprocess
    registry.register(
        "kernel32.dll",
        "ExitProcess",
        stub_exit_process as StubFn,
        1,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/winnls/nf-winnls-getacp
    registry.register("kernel32.dll", "GetACP", stub_get_acp as StubFn, 0);
    // https://learn.microsoft.com/en-us/windows/win32/api/winnls/nf-winnls-getoemcp
    registry.register("kernel32.dll", "GetOEMCP", stub_get_oem_cp as StubFn, 0);
    // https://learn.microsoft.com/en-us/windows/win32/api/winnls/nf-winnls-getcpinfo
    registry.register("kernel32.dll", "GetCPInfo", stub_get_cp_info as StubFn, 2);
    // https://learn.microsoft.com/en-us/windows/win32/api/processenv/nf-processenv-getcommandlinea
    registry.register(
        "kernel32.dll",
        "GetCommandLineA",
        stub_get_command_line_a as StubFn,
        0,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/processenv/nf-processenv-getenvironmentstrings
    registry.register(
        "kernel32.dll",
        "GetEnvironmentStrings",
        stub_get_environment_strings as StubFn,
        0,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getfiletype
    registry.register(
        "kernel32.dll",
        "GetFileType",
        stub_get_file_type as StubFn,
        1,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/errhandlingapi/nf-errhandlingapi-getlasterror
    registry.register(
        "kernel32.dll",
        "GetLastError",
        stub_get_last_error as StubFn,
        0,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/errhandlingapi/nf-errhandlingapi-setlasterror
    registry.register(
        "kernel32.dll",
        "SetLastError",
        stub_set_last_error as StubFn,
        1,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-getmodulefilenamea
    registry.register(
        "kernel32.dll",
        "GetModuleFileNameA",
        stub_get_module_file_name_a as StubFn,
        3,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-getmodulehandlea
    registry.register(
        "kernel32.dll",
        "GetModuleHandleA",
        stub_get_module_handle_a as StubFn,
        1,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-getstartupinfoa
    registry.register(
        "kernel32.dll",
        "GetStartupInfoA",
        stub_get_startup_info_a as StubFn,
        1,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/processenv/nf-processenv-getstdhandle
    registry.register(
        "kernel32.dll",
        "GetStdHandle",
        stub_get_std_handle as StubFn,
        1,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getsysteminfo
    registry.register(
        "kernel32.dll",
        "GetSystemInfo",
        stub_get_system_info as StubFn,
        1,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getversion
    registry.register("kernel32.dll", "GetVersion", stub_get_version as StubFn, 0);
    // https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-globalalloc
    registry.register(
        "kernel32.dll",
        "GlobalAlloc",
        stub_global_alloc as StubFn,
        2,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-globalfree
    registry.register("kernel32.dll", "GlobalFree", stub_global_free as StubFn, 1);
    // https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-globallock
    registry.register("kernel32.dll", "GlobalLock", stub_global_lock as StubFn, 1);
    // https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-globalunlock
    registry.register(
        "kernel32.dll",
        "GlobalUnlock",
        stub_global_unlock as StubFn,
        1,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/stringapiset/nf-stringapiset-multibytetowidechar
    registry.register(
        "kernel32.dll",
        "MultiByteToWideChar",
        stub_multi_byte_to_wide_char as StubFn,
        6,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/stringapiset/nf-stringapiset-widechartomultibyte
    registry.register(
        "kernel32.dll",
        "WideCharToMultiByte",
        stub_wide_char_to_multi_byte as StubFn,
        8,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/winnt/nf-winnt-rtlunwind
    registry.register("kernel32.dll", "RtlUnwind", stub_rtl_unwind as StubFn, 4);
    // https://learn.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-virtualalloc
    registry.register(
        "kernel32.dll",
        "VirtualAlloc",
        stub_virtual_alloc as StubFn,
        4,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-virtualfree
    registry.register(
        "kernel32.dll",
        "VirtualFree",
        stub_virtual_free as StubFn,
        3,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-writefile
    registry.register("kernel32.dll", "WriteFile", stub_write_file as StubFn, 5);

    // ---- Round-8 additions (IR50_32.DLL needs) --------------------
    //
    // Most of these are fail-soft "the DLL imports it but the
    // decode path doesn't actually exercise it". Each returns the
    // canonical "no-op success" / "no error" value per MSDN.

    // https://learn.microsoft.com/en-us/windows/win32/api/handleapi/nf-handleapi-closehandle
    registry.register(
        "kernel32.dll",
        "CloseHandle",
        stub_close_handle as StubFn,
        1,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-createfilemappinga
    registry.register(
        "kernel32.dll",
        "CreateFileMappingA",
        stub_create_file_mapping_a as StubFn,
        6,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-createsemaphorea
    registry.register(
        "kernel32.dll",
        "CreateSemaphoreA",
        stub_create_semaphore_a as StubFn,
        4,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-deletecriticalsection
    registry.register(
        "kernel32.dll",
        "DeleteCriticalSection",
        stub_delete_critical_section as StubFn,
        1,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-disablethreadlibrarycalls
    registry.register(
        "kernel32.dll",
        "DisableThreadLibraryCalls",
        stub_disable_thread_library_calls as StubFn,
        1,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-entercriticalsection
    registry.register(
        "kernel32.dll",
        "EnterCriticalSection",
        stub_enter_critical_section as StubFn,
        1,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-leavecriticalsection
    registry.register(
        "kernel32.dll",
        "LeaveCriticalSection",
        stub_leave_critical_section as StubFn,
        1,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-initializecriticalsection
    registry.register(
        "kernel32.dll",
        "InitializeCriticalSection",
        stub_initialize_critical_section as StubFn,
        1,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-findresourcea
    registry.register(
        "kernel32.dll",
        "FindResourceA",
        stub_find_resource_a as StubFn,
        3,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-flushfilebuffers
    registry.register(
        "kernel32.dll",
        "FlushFileBuffers",
        stub_flush_file_buffers as StubFn,
        1,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/processenv/nf-processenv-freeenvironmentstringsa
    registry.register(
        "kernel32.dll",
        "FreeEnvironmentStringsA",
        stub_free_environment_strings as StubFn,
        1,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/processenv/nf-processenv-freeenvironmentstringsw
    registry.register(
        "kernel32.dll",
        "FreeEnvironmentStringsW",
        stub_free_environment_strings as StubFn,
        1,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-freelibrary
    registry.register(
        "kernel32.dll",
        "FreeLibrary",
        stub_free_library as StubFn,
        1,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-freeresource
    registry.register(
        "kernel32.dll",
        "FreeResource",
        stub_free_resource as StubFn,
        1,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-getcurrentprocess
    registry.register(
        "kernel32.dll",
        "GetCurrentProcess",
        stub_get_current_process as StubFn,
        0,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-getcurrentthreadid
    registry.register(
        "kernel32.dll",
        "GetCurrentThreadId",
        stub_get_current_thread_id as StubFn,
        0,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/processenv/nf-processenv-getenvironmentstringsw
    registry.register(
        "kernel32.dll",
        "GetEnvironmentStringsW",
        stub_get_environment_strings_w as StubFn,
        0,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/winnls/nf-winnls-getlocaleinfoa
    registry.register(
        "kernel32.dll",
        "GetLocaleInfoA",
        stub_get_locale_info_a as StubFn,
        4,
    );
    registry.register(
        "kernel32.dll",
        "GetLocaleInfoW",
        stub_get_locale_info_a as StubFn,
        4,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getshortpathnamea
    registry.register(
        "kernel32.dll",
        "GetShortPathNameA",
        stub_get_short_path_name_a as StubFn,
        3,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/winnls/nf-winnls-getstringtypea
    registry.register(
        "kernel32.dll",
        "GetStringTypeA",
        stub_get_string_type as StubFn,
        5,
    );
    registry.register(
        "kernel32.dll",
        "GetStringTypeW",
        stub_get_string_type as StubFn,
        4,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getsystemdirectorya
    registry.register(
        "kernel32.dll",
        "GetSystemDirectoryA",
        stub_get_system_directory_a as StubFn,
        2,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getversionexa
    registry.register(
        "kernel32.dll",
        "GetVersionExA",
        stub_get_version_ex_a as StubFn,
        1,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-globalhandle
    registry.register(
        "kernel32.dll",
        "GlobalHandle",
        stub_global_handle as StubFn,
        1,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-globalrealloc
    registry.register(
        "kernel32.dll",
        "GlobalReAlloc",
        stub_global_realloc as StubFn,
        3,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/heapapi/nf-heapapi-heapcreate
    registry.register("kernel32.dll", "HeapCreate", stub_heap_create as StubFn, 3);
    // https://learn.microsoft.com/en-us/windows/win32/api/heapapi/nf-heapapi-heapdestroy
    registry.register(
        "kernel32.dll",
        "HeapDestroy",
        stub_heap_destroy as StubFn,
        1,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-isbadcodeptr
    registry.register("kernel32.dll", "IsBadCodePtr", stub_is_bad_ptr as StubFn, 1);
    // https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-isbadreadptr
    registry.register("kernel32.dll", "IsBadReadPtr", stub_is_bad_ptr as StubFn, 2);
    // https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-isbadwriteptr
    registry.register(
        "kernel32.dll",
        "IsBadWritePtr",
        stub_is_bad_ptr as StubFn,
        2,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/winnls/nf-winnls-lcmapstringa
    registry.register(
        "kernel32.dll",
        "LCMapStringA",
        stub_lc_map_string as StubFn,
        6,
    );
    registry.register(
        "kernel32.dll",
        "LCMapStringW",
        stub_lc_map_string as StubFn,
        6,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-loadresource
    registry.register(
        "kernel32.dll",
        "LoadResource",
        stub_load_resource as StubFn,
        2,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-localhandle
    registry.register(
        "kernel32.dll",
        "LocalHandle",
        stub_local_handle as StubFn,
        1,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-locallock
    registry.register("kernel32.dll", "LocalLock", stub_local_lock as StubFn, 1);
    // https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-localunlock
    registry.register(
        "kernel32.dll",
        "LocalUnlock",
        stub_local_unlock as StubFn,
        1,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-lockresource
    registry.register(
        "kernel32.dll",
        "LockResource",
        stub_lock_resource as StubFn,
        1,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-sizeofresource
    // Round 13 — round 12 added the impl with `#[allow(dead_code)]`
    // because IR50_32.DLL doesn't import it. Now wired into the
    // dispatch registry so future codecs that DO import it pick
    // up a real implementation rather than tripping the
    // unresolved-import trap.
    registry.register(
        "kernel32.dll",
        "SizeofResource",
        stub_sizeof_resource as StubFn,
        2,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-mapviewoffile
    registry.register(
        "kernel32.dll",
        "MapViewOfFile",
        stub_map_view_of_file as StubFn,
        5,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-openfilemappinga
    registry.register(
        "kernel32.dll",
        "OpenFileMappingA",
        stub_open_file_mapping_a as StubFn,
        3,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/profileapi/nf-profileapi-queryperformancecounter
    registry.register(
        "kernel32.dll",
        "QueryPerformanceCounter",
        stub_query_performance_counter as StubFn,
        1,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/profileapi/nf-profileapi-queryperformancefrequency
    registry.register(
        "kernel32.dll",
        "QueryPerformanceFrequency",
        stub_query_performance_frequency as StubFn,
        1,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/errhandlingapi/nf-errhandlingapi-raiseexception
    registry.register(
        "kernel32.dll",
        "RaiseException",
        stub_raise_exception as StubFn,
        4,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-releasesemaphore
    registry.register(
        "kernel32.dll",
        "ReleaseSemaphore",
        stub_release_semaphore as StubFn,
        3,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-setfilepointer
    registry.register(
        "kernel32.dll",
        "SetFilePointer",
        stub_set_file_pointer as StubFn,
        4,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-sethandlecount
    registry.register(
        "kernel32.dll",
        "SetHandleCount",
        stub_set_handle_count as StubFn,
        1,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/processenv/nf-processenv-setstdhandle
    registry.register(
        "kernel32.dll",
        "SetStdHandle",
        stub_set_std_handle as StubFn,
        2,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/errhandlingapi/nf-errhandlingapi-setunhandledexceptionfilter
    registry.register(
        "kernel32.dll",
        "SetUnhandledExceptionFilter",
        stub_set_unhandled_exception_filter as StubFn,
        1,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-sleep
    registry.register("kernel32.dll", "Sleep", stub_sleep as StubFn, 1);
    // https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-terminateprocess
    registry.register(
        "kernel32.dll",
        "TerminateProcess",
        stub_terminate_process as StubFn,
        2,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-tlsalloc
    registry.register("kernel32.dll", "TlsAlloc", stub_tls_alloc as StubFn, 0);
    registry.register("kernel32.dll", "TlsFree", stub_tls_free as StubFn, 1);
    registry.register(
        "kernel32.dll",
        "TlsGetValue",
        stub_tls_get_value as StubFn,
        1,
    );
    registry.register(
        "kernel32.dll",
        "TlsSetValue",
        stub_tls_set_value as StubFn,
        2,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-unmapviewoffile
    registry.register(
        "kernel32.dll",
        "UnmapViewOfFile",
        stub_unmap_view_of_file as StubFn,
        1,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-waitforsingleobject
    registry.register(
        "kernel32.dll",
        "WaitForSingleObject",
        stub_wait_for_single_object as StubFn,
        2,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-writeprivateprofilestringa
    registry.register(
        "kernel32.dll",
        "WritePrivateProfileStringA",
        stub_write_private_profile_string_a as StubFn,
        4,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-lstrlena
    registry.register("kernel32.dll", "lstrlenA", stub_lstrlen_a as StubFn, 1);

    // ---- Round-20 additions (mpg4c32.dll DllMain reach) -----------
    //
    // Per `docs/winmf/winmf-emulator.md` §"Milestone 3.1". The
    // MSMPEG4 v3 codec adds a thread-creation surface its
    // C++ runtime touches at static-init time; because our
    // sandbox is single-threaded, `CreateThread` is implemented
    // synchronously (call the start address, return a fake
    // HANDLE).
    //
    // https://learn.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-createeventa
    registry.register(
        "kernel32.dll",
        "CreateEventA",
        stub_create_event_a as StubFn,
        4,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createthread
    registry.register(
        "kernel32.dll",
        "CreateThread",
        stub_create_thread as StubFn,
        6,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-setevent
    registry.register("kernel32.dll", "SetEvent", stub_set_event as StubFn, 1);
    // https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-setthreadpriority
    // Single-threaded sandbox — no-op TRUE. Pre-emptively
    // registered (mpg4ds32.ax / msadds32.ax both import it).
    registry.register(
        "kernel32.dll",
        "SetThreadPriority",
        stub_set_thread_priority as StubFn,
        2,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-resumethread
    registry.register(
        "kernel32.dll",
        "ResumeThread",
        stub_resume_thread as StubFn,
        1,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-muldiv
    registry.register("kernel32.dll", "MulDiv", stub_muldiv as StubFn, 3);
    // https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-getprofileinta
    registry.register(
        "kernel32.dll",
        "GetProfileIntA",
        stub_get_profile_int_a as StubFn,
        3,
    );

    // ----- Corpus-driven additions ----------------------------------
    // Stubs added in response to the codec-corpus test
    // (`tests/codec_corpus.rs`) showing high-frequency
    // unresolved-import counts. Each entry below was missing
    // from ≥6 codecs in the manifest; closing them unblocks
    // those codecs' `Sandbox::load`.

    // https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-getcurrentprocessid
    registry.register(
        "kernel32.dll",
        "GetCurrentProcessId",
        stub_get_current_process_id as StubFn,
        0,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getsystemtimeasfiletime
    registry.register(
        "kernel32.dll",
        "GetSystemTimeAsFileTime",
        stub_get_system_time_as_file_time as StubFn,
        1,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-getcurrentthread
    registry.register(
        "kernel32.dll",
        "GetCurrentThread",
        stub_get_current_thread as StubFn,
        0,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/winnt/nf-winnt-interlockedexchange
    registry.register(
        "kernel32.dll",
        "InterlockedExchange",
        stub_interlocked_exchange as StubFn,
        2,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/winnt/nf-winnt-interlockedcompareexchange
    registry.register(
        "kernel32.dll",
        "InterlockedCompareExchange",
        stub_interlocked_compare_exchange as StubFn,
        3,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/errhandlingapi/nf-errhandlingapi-unhandledexceptionfilter
    registry.register(
        "kernel32.dll",
        "UnhandledExceptionFilter",
        stub_unhandled_exception_filter as StubFn,
        1,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/errhandlingapi/nf-errhandlingapi-seterrormode
    registry.register(
        "kernel32.dll",
        "SetErrorMode",
        stub_set_error_mode as StubFn,
        1,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-resetevent
    registry.register("kernel32.dll", "ResetEvent", stub_reset_event as StubFn, 1);
    // https://learn.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-waitformultipleobjects
    registry.register(
        "kernel32.dll",
        "WaitForMultipleObjects",
        stub_wait_for_multiple_objects as StubFn,
        4,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-createeventw
    registry.register(
        "kernel32.dll",
        "CreateEventW",
        stub_create_event_w as StubFn,
        4,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-createsemaphorew
    registry.register(
        "kernel32.dll",
        "CreateSemaphoreW",
        stub_create_semaphore_w as StubFn,
        4,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getlocaltime
    registry.register(
        "kernel32.dll",
        "GetLocalTime",
        stub_get_local_time as StubFn,
        1,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-getmodulehandlew
    registry.register(
        "kernel32.dll",
        "GetModuleHandleW",
        stub_get_module_handle_w as StubFn,
        1,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-getprivateprofileinta
    registry.register(
        "kernel32.dll",
        "GetPrivateProfileIntA",
        stub_get_private_profile_int_a as StubFn,
        4,
    );
    // `DelayLoadFailureHook` — DELAYLOAD glue called by the
    // VC++ delay-load helper when an import resolves at run
    // time. Synthetic stub returns 0 (loader treats this as
    // "handled"). https://learn.microsoft.com/en-us/cpp/build/reference/error-handling-and-notification
    registry.register(
        "kernel32.dll",
        "DelayLoadFailureHook",
        stub_delay_load_failure_hook as StubFn,
        2,
    );

    // ---- Corpus round 2 --------------------------------------------
    registry.register(
        "kernel32.dll",
        "GetVersionExW",
        stub_get_version_ex_w as StubFn,
        1,
    );
    registry.register(
        "kernel32.dll",
        "SignalObjectAndWait",
        stub_signal_object_and_wait as StubFn,
        4,
    );
    registry.register(
        "kernel32.dll",
        "InitializeCriticalSectionAndSpinCount",
        stub_init_cs_spin as StubFn,
        2,
    );
    registry.register(
        "kernel32.dll",
        "IsDebuggerPresent",
        stub_is_debugger_present as StubFn,
        0,
    );
    registry.register(
        "kernel32.dll",
        "VirtualProtect",
        stub_virtual_protect as StubFn,
        4,
    );
    registry.register(
        "kernel32.dll",
        "InterlockedExchangeAdd",
        stub_interlocked_exchange_add as StubFn,
        2,
    );
    registry.register(
        "kernel32.dll",
        "GetComputerNameA",
        stub_get_computer_name_a as StubFn,
        2,
    );
    registry.register(
        "kernel32.dll",
        "GetEnvironmentVariableW",
        stub_get_environment_variable_w as StubFn,
        3,
    );
    registry.register(
        "kernel32.dll",
        "GetProcessAffinityMask",
        stub_get_process_affinity_mask as StubFn,
        3,
    );
    registry.register(
        "kernel32.dll",
        "GetThreadPriority",
        stub_get_thread_priority as StubFn,
        1,
    );
    registry.register(
        "kernel32.dll",
        "SetThreadAffinityMask",
        stub_set_thread_affinity_mask as StubFn,
        2,
    );
    registry.register(
        "kernel32.dll",
        "LoadLibraryW",
        stub_load_library_w as StubFn,
        1,
    );
    registry.register("kernel32.dll", "ReadFile", stub_read_file as StubFn, 5);

    // ---- Codec-corpus probe additions --------------------------
    //
    // The 30 stubs below close the kernel32 import gap for the
    // VfW codecs whose `ICOpen` probe was previously blocked by
    // unresolved imports: Cinepak (`iccvid`), Indeo Audio
    // (`IAC25`), HuffYUV, Lagarith, MagicYUV. Most are pulled in
    // by CRT startup or the codec's config-dialog path — not the
    // decode core — so they are fail-soft by design.

    // lstrcat / lstrcpy / lstrcmpi — kernel32's string helpers.
    registry.register("kernel32.dll", "lstrcatA", stub_lstrcat_a as StubFn, 2);
    registry.register("kernel32.dll", "lstrcpyA", stub_lstrcpy_a as StubFn, 2);
    registry.register("kernel32.dll", "lstrcmpiA", stub_lstrcmpi_a as StubFn, 2);
    // CompareString — locale-aware string compare (CRT collate).
    registry.register(
        "kernel32.dll",
        "CompareStringA",
        stub_compare_string_a as StubFn,
        6,
    );
    registry.register(
        "kernel32.dll",
        "CompareStringW",
        stub_compare_string_w as StubFn,
        6,
    );
    // FatalAppExitA — CRT abort path; no-op (never hit on the
    // happy path, just needs to resolve).
    registry.register(
        "kernel32.dll",
        "FatalAppExitA",
        stub_fatal_app_exit_a as StubFn,
        2,
    );
    // GetSystemTime / GetTimeZoneInformation — wall-clock surface.
    registry.register(
        "kernel32.dll",
        "GetSystemTime",
        stub_get_system_time as StubFn,
        1,
    );
    registry.register(
        "kernel32.dll",
        "GetTimeZoneInformation",
        stub_get_time_zone_information as StubFn,
        1,
    );
    // LoadLibraryExA — like LoadLibraryA, ignores the flags.
    registry.register(
        "kernel32.dll",
        "LoadLibraryExA",
        stub_load_library_ex_a as StubFn,
        3,
    );
    // SetEnvironmentVariableA — no-op success.
    registry.register(
        "kernel32.dll",
        "SetEnvironmentVariableA",
        stub_returns_true as StubFn,
        2,
    );
    // Console surface — codecs that link a console-subsystem
    // config tool. All no-op success.
    registry.register(
        "kernel32.dll",
        "AllocConsole",
        stub_returns_true as StubFn,
        0,
    );
    registry.register(
        "kernel32.dll",
        "SetConsoleScreenBufferSize",
        stub_returns_true as StubFn,
        2,
    );
    registry.register(
        "kernel32.dll",
        "SetConsoleCtrlHandler",
        stub_returns_true as StubFn,
        2,
    );
    registry.register(
        "kernel32.dll",
        "WriteConsoleA",
        stub_write_console_a as StubFn,
        5,
    );
    // EncodePointer / DecodePointer — pointer obfuscation. We
    // model them as the identity transform, which is a valid
    // (no-op) implementation: encode then decode round-trips.
    registry.register(
        "kernel32.dll",
        "EncodePointer",
        stub_identity_pointer as StubFn,
        1,
    );
    registry.register(
        "kernel32.dll",
        "DecodePointer",
        stub_identity_pointer as StubFn,
        1,
    );
    // EnumSystemLocalesA — report success without invoking the
    // callback (the CRT only needs the call to not fail).
    registry.register(
        "kernel32.dll",
        "EnumSystemLocalesA",
        stub_returns_true as StubFn,
        2,
    );
    // GetModuleFileNameW / GetStartupInfoW — wide twins of the
    // existing ANSI stubs.
    registry.register(
        "kernel32.dll",
        "GetModuleFileNameW",
        stub_get_module_file_name_w as StubFn,
        3,
    );
    registry.register(
        "kernel32.dll",
        "GetStartupInfoW",
        stub_get_startup_info_w as StubFn,
        1,
    );
    // GetUserDefaultLCID — en-US.
    registry.register(
        "kernel32.dll",
        "GetUserDefaultLCID",
        stub_get_user_default_lcid as StubFn,
        0,
    );
    // HeapQueryInformation — report "not supported" (return 0);
    // the caller treats the heap as a plain heap.
    registry.register(
        "kernel32.dll",
        "HeapQueryInformation",
        stub_returns_zero as StubFn,
        5,
    );
    // IsProcessorFeaturePresent — report every feature ABSENT
    // (return 0). That steers SIMD-dispatching codecs onto their
    // scalar fallback, which the emulator decodes reliably.
    registry.register(
        "kernel32.dll",
        "IsProcessorFeaturePresent",
        stub_returns_zero as StubFn,
        1,
    );
    // IsValidCodePage / IsValidLocale — accept anything.
    registry.register(
        "kernel32.dll",
        "IsValidCodePage",
        stub_returns_true as StubFn,
        1,
    );
    registry.register(
        "kernel32.dll",
        "IsValidLocale",
        stub_returns_true as StubFn,
        2,
    );
    // WaitForMultipleObjectsEx — like WaitForMultipleObjects,
    // ignoring the extra `bAlertable` arg.
    registry.register(
        "kernel32.dll",
        "WaitForMultipleObjectsEx",
        stub_wait_for_multiple_objects as StubFn,
        5,
    );
    // FreeLibraryAndExitThread — thread-teardown path; no-op.
    registry.register(
        "kernel32.dll",
        "FreeLibraryAndExitThread",
        stub_returns_zero as StubFn,
        2,
    );
    // GetLongPathNameA — no long/short distinction in the
    // sandbox: echo the input path back.
    registry.register(
        "kernel32.dll",
        "GetLongPathNameA",
        stub_get_long_path_name_a as StubFn,
        3,
    );
    // GetModuleHandleExA — resolve like GetModuleHandleA and
    // write the handle through the out-pointer.
    registry.register(
        "kernel32.dll",
        "GetModuleHandleExA",
        stub_get_module_handle_ex_a as StubFn,
        3,
    );
    // IsDBCSLeadByteEx — single-byte code page: no lead bytes.
    registry.register(
        "kernel32.dll",
        "IsDBCSLeadByteEx",
        stub_returns_zero as StubFn,
        2,
    );
    // VirtualQuery — report "query failed" (return 0); codecs
    // use it for an optional guard-page probe.
    registry.register(
        "kernel32.dll",
        "VirtualQuery",
        stub_returns_zero as StubFn,
        3,
    );
}

// ----- Heap ----------------------------------------------------------

/// `HANDLE GetProcessHeap(void)` — return the canned handle.
fn stub_get_process_heap(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    Ok(state.process_heap_handle)
}

const HEAP_ZERO_MEMORY: u32 = 0x0000_0008;

/// `LPVOID HeapAlloc(HANDLE, DWORD dwFlags, SIZE_T dwBytes)`.
fn stub_heap_alloc(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let _h_heap = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("HeapAlloc", t))?;
    let flags = arg_dword(cpu, mmu, 1).map_err(|t| trap_to_win32("HeapAlloc", t))?;
    let n = arg_dword(cpu, mmu, 2).map_err(|t| trap_to_win32("HeapAlloc", t))?;
    let addr = bump_alloc(state, n)?;
    let buf = state.heap.entry(addr).or_default();
    buf.resize(n as usize, 0);
    if (flags & HEAP_ZERO_MEMORY) != 0 {
        for b in buf.iter_mut() {
            *b = 0;
        }
    }
    // Mirror the bytes into emulator memory so the codec can use
    // them directly.
    let bytes = buf.clone();
    mmu.write_initializer(addr, &bytes)
        .map_err(|t| trap_to_win32("HeapAlloc", t))?;
    Ok(addr)
}

/// `BOOL HeapFree(HANDLE, DWORD dwFlags, LPVOID lpMem)`.
fn stub_heap_free(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let _h = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("HeapFree", t))?;
    let _flags = arg_dword(cpu, mmu, 1).map_err(|t| trap_to_win32("HeapFree", t))?;
    let addr = arg_dword(cpu, mmu, 2).map_err(|t| trap_to_win32("HeapFree", t))?;
    if addr == 0 {
        return Ok(1); // BOOL TRUE; freeing NULL is a no-op
    }
    state
        .heap
        .remove(&addr)
        .ok_or(Win32Error::InvalidHeapBlock {
            stub: "HeapFree",
            addr,
        })?;
    Ok(1)
}

/// `LPVOID HeapReAlloc(HANDLE, DWORD dwFlags, LPVOID lpMem, SIZE_T dwBytes)`.
fn stub_heap_realloc(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let _h = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("HeapReAlloc", t))?;
    let flags = arg_dword(cpu, mmu, 1).map_err(|t| trap_to_win32("HeapReAlloc", t))?;
    let addr = arg_dword(cpu, mmu, 2).map_err(|t| trap_to_win32("HeapReAlloc", t))?;
    let n = arg_dword(cpu, mmu, 3).map_err(|t| trap_to_win32("HeapReAlloc", t))?;
    if addr == 0 {
        // MSDN: passing NULL for lpMem is undefined; we choose to
        // treat as fresh alloc for resilience.
        return stub_heap_alloc(cpu, mmu, state, _registry);
    }
    let old = state
        .heap
        .remove(&addr)
        .ok_or(Win32Error::InvalidHeapBlock {
            stub: "HeapReAlloc",
            addr,
        })?;
    let new_addr = bump_alloc(state, n)?;
    let mut buf = vec![0u8; n as usize];
    let copy_n = old.len().min(n as usize);
    buf[..copy_n].copy_from_slice(&old[..copy_n]);
    if (flags & HEAP_ZERO_MEMORY) != 0 {
        for b in buf.iter_mut().skip(copy_n) {
            *b = 0;
        }
    }
    mmu.write_initializer(new_addr, &buf)
        .map_err(|t| trap_to_win32("HeapReAlloc", t))?;
    state.heap.insert(new_addr, buf);
    Ok(new_addr)
}

/// `SIZE_T HeapSize(HANDLE, DWORD dwFlags, LPCVOID lpMem)` —
/// MSDN "Heap functions / HeapSize": returns the size, in bytes,
/// of the memory block pointed to by `lpMem`, or `(SIZE_T)-1`
/// (`0xFFFF_FFFF` on a 32-bit guest) on failure. Round 15 —
/// `IR41_32.AX` queries the live block size after a `HeapAlloc`
/// to size a follow-up copy.
fn stub_heap_size(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let _h = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("HeapSize", t))?;
    let _flags = arg_dword(cpu, mmu, 1).map_err(|t| trap_to_win32("HeapSize", t))?;
    let addr = arg_dword(cpu, mmu, 2).map_err(|t| trap_to_win32("HeapSize", t))?;
    if addr == 0 {
        return Ok(0xFFFF_FFFF);
    }
    Ok(state
        .heap
        .get(&addr)
        .map(|v| v.len() as u32)
        .unwrap_or(0xFFFF_FFFF))
}

fn bump_alloc(state: &mut HostState, n: u32) -> Result<u32, Win32Error> {
    // Round up to 16 to keep allocations roughly cache-line aligned.
    let aligned = n
        .checked_add(15)
        .map(|v| v & !15u32)
        .ok_or(Win32Error::InvalidArgument {
            stub: "HeapAlloc",
            reason: "size overflow".into(),
        })?;
    let addr = state.heap_cursor;
    let next = addr
        .checked_add(aligned)
        .ok_or(Win32Error::InvalidArgument {
            stub: "HeapAlloc",
            reason: "heap address-space overflow".into(),
        })?;
    if next > state.heap_arena_end {
        return Err(Win32Error::InvalidArgument {
            stub: "HeapAlloc",
            reason: format!(
                "arena exhausted (need {n}, have {})",
                state.heap_arena_end - addr
            ),
        });
    }
    state.heap_cursor = next;
    Ok(addr)
}

const LMEM_ZEROINIT: u32 = 0x0040;

/// `HLOCAL LocalAlloc(UINT uFlags, SIZE_T uBytes)`.
fn stub_local_alloc(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let flags = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("LocalAlloc", t))?;
    let n = arg_dword(cpu, mmu, 1).map_err(|t| trap_to_win32("LocalAlloc", t))?;
    let addr = bump_alloc(state, n)?;
    let mut buf = vec![0u8; n as usize];
    if (flags & LMEM_ZEROINIT) != 0 {
        for b in buf.iter_mut() {
            *b = 0;
        }
    }
    mmu.write_initializer(addr, &buf)
        .map_err(|t| trap_to_win32("LocalAlloc", t))?;
    state.heap.insert(addr, buf);
    if state.trace_stubs {
        state
            .stub_trace
            .push(format!("  LocalAlloc(flags={flags:#x}, n={n}) → {addr:#x}"));
    }
    Ok(addr)
}

/// `HLOCAL LocalFree(HLOCAL hMem)`.
fn stub_local_free(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let addr = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("LocalFree", t))?;
    if addr == 0 {
        return Ok(0);
    }
    state
        .heap
        .remove(&addr)
        .ok_or(Win32Error::InvalidHeapBlock {
            stub: "LocalFree",
            addr,
        })?;
    Ok(0) // Returns NULL on success per MSDN.
}

// ----- Debug + time --------------------------------------------------

/// `void OutputDebugStringA(LPCSTR lpOutputString)`. We log into
/// `state.debug_log` so the fixture-gated end-to-end test can
/// assert the codec emitted a known boot string.
fn stub_output_debug_string_a(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let p = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("OutputDebugStringA", t))?;
    let s = read_cstr(mmu, p, 4096)?;
    state.debug_log.push(s);
    Ok(0)
}

/// `DWORD GetTickCount(void)`. Returns a monotonically-increasing
/// pseudo-tick. Real wall-clock time is not modelled; many codecs
/// only use the tick as a seed.
fn stub_get_tick_count(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    state.tick = state.tick.wrapping_add(1);
    Ok(state.tick)
}

// ----- Atomics -------------------------------------------------------

/// `LONG InterlockedIncrement(LONG volatile *Addend)`.
fn stub_interlocked_increment(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let p = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("InterlockedIncrement", t))?;
    let v = mmu
        .load32(p)
        .map_err(|t| trap_to_win32("InterlockedIncrement", t))?;
    let new = v.wrapping_add(1);
    mmu.store32(p, new)
        .map_err(|t| trap_to_win32("InterlockedIncrement", t))?;
    Ok(new)
}

/// `LONG InterlockedDecrement(LONG volatile *Addend)`.
fn stub_interlocked_decrement(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let p = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("InterlockedDecrement", t))?;
    let v = mmu
        .load32(p)
        .map_err(|t| trap_to_win32("InterlockedDecrement", t))?;
    let new = v.wrapping_sub(1);
    mmu.store32(p, new)
        .map_err(|t| trap_to_win32("InterlockedDecrement", t))?;
    Ok(new)
}

// ----- Library / function lookup -------------------------------------

/// `HMODULE LoadLibraryA(LPCSTR lpLibFileName)`.
///
/// Round-1 only acknowledges loaded modules in the registry; it
/// does not attempt to load a fresh DLL on demand. The PE loader
/// records every successfully-loaded DLL in `state.modules`.
fn stub_load_library_a(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let p = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("LoadLibraryA", t))?;
    let name = read_cstr(mmu, p, 260)?.to_ascii_lowercase();
    if let Some(base) = state.modules.get(&name) {
        return Ok(*base);
    }
    // We pretend the module did not load. Many codecs handle
    // NULL gracefully; the ones that don't will raise a clear
    // trap downstream.
    Ok(0)
}

/// `FARPROC GetProcAddress(HMODULE hModule, LPCSTR lpProcName)`.
///
/// Round-1 returns a registered thunk for the (module, name)
/// pair if one exists; otherwise NULL. Lookup-by-ordinal is not
/// supported in round 1 (low-bit-set address) — a target codec
/// that needs it will surface as a clean trap.
fn stub_get_proc_address(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let _h = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("GetProcAddress", t))?;
    let name_p = arg_dword(cpu, mmu, 1).map_err(|t| trap_to_win32("GetProcAddress", t))?;
    if name_p < 0x10000 {
        // Pointer is an ordinal (HIWORD == 0) — unsupported.
        return Ok(0);
    }
    // We don't know which DLL was identified, so always return
    // NULL for round-1; callers fall back to import-table
    // resolution.
    Ok(0)
}

// ----- Round-4 stubs -------------------------------------------------

/// `void ExitProcess(UINT uExitCode)`. Sets `state.exit_requested`,
/// which the run-loop converts into a clean RET_SENTINEL exit so
/// the host caller can introspect the codec's exit code without
/// having to handle a panic. Codecs *should* never call this from
/// their loaded path; if one does, the entire emulator session is
/// over.
fn stub_exit_process(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let code = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("ExitProcess", t))?;
    state.exit_requested = Some(code);
    Ok(0)
}

/// `UINT GetACP(void)`. Returns Windows-1252 (the canonical code
/// page for the Indeo 3 era).
fn stub_get_acp(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    Ok(1252)
}

/// `UINT GetOEMCP(void)`. Returns 437 (US English code page).
fn stub_get_oem_cp(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    Ok(437)
}

/// `BOOL GetCPInfo(UINT codepage, LPCPINFO lpCPInfo)`. Fills the
/// `CPINFO` struct with `MaxCharSize=1`, `DefaultChar={'?',0}`,
/// `LeadByte=[0;12]`. Returns TRUE.
fn stub_get_cp_info(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let _cp = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("GetCPInfo", t))?;
    let p = arg_dword(cpu, mmu, 1).map_err(|t| trap_to_win32("GetCPInfo", t))?;
    if p == 0 {
        return Ok(0);
    }
    // CPINFO layout (per winnls.h):
    //   UINT  MaxCharSize;        // 4
    //   BYTE  DefaultChar[2];     // 2
    //   BYTE  LeadByte[12];       // 12
    // total: 18 bytes, then padded — we explicitly write each
    // field so layout-padding is irrelevant.
    mmu.store32(p, 1)
        .map_err(|t| trap_to_win32("GetCPInfo", t))?;
    mmu.store8(p + 4, b'?')
        .map_err(|t| trap_to_win32("GetCPInfo", t))?;
    mmu.store8(p + 5, 0)
        .map_err(|t| trap_to_win32("GetCPInfo", t))?;
    for i in 0..12 {
        mmu.store8(p + 6 + i, 0)
            .map_err(|t| trap_to_win32("GetCPInfo", t))?;
    }
    Ok(1)
}

/// `LPSTR GetCommandLineA(void)`. Returns a guest-side pointer
/// to the canned `"oxideav-vfw\0"` string.
fn stub_get_command_line_a(
    _cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    if state.command_line_ptr == 0 {
        let s = b"oxideav-vfw\0";
        let addr = state.arena_const_alloc(s.len() as u32)?;
        mmu.write_initializer(addr, s)
            .map_err(|t| trap_to_win32("GetCommandLineA", t))?;
        state.command_line_ptr = addr;
    }
    Ok(state.command_line_ptr)
}

/// `LPCH GetEnvironmentStrings(void)`. Returns a guest-side
/// pointer to a static block `"\0\0"` (empty environment,
/// double-null-terminated).
fn stub_get_environment_strings(
    _cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    if state.environment_strings_ptr == 0 {
        let s = b"\0\0";
        let addr = state.arena_const_alloc(s.len() as u32)?;
        mmu.write_initializer(addr, s)
            .map_err(|t| trap_to_win32("GetEnvironmentStrings", t))?;
        state.environment_strings_ptr = addr;
    }
    Ok(state.environment_strings_ptr)
}

/// `DWORD GetFileType(HANDLE hFile)`. Returns
/// `FILE_TYPE_UNKNOWN = 0` for any handle. Codecs typically only
/// call this for stdin/stdout, which they don't actually use.
fn stub_get_file_type(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    Ok(0)
}

/// `DWORD GetLastError(void)` — returns `state.last_error`.
fn stub_get_last_error(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    Ok(state.last_error)
}

/// `void SetLastError(DWORD dwErrCode)` — writes `state.last_error`.
fn stub_set_last_error(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let code = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("SetLastError", t))?;
    state.last_error = code;
    Ok(0)
}

/// `DWORD GetModuleFileNameA(HMODULE hModule, LPSTR lpFilename,
/// DWORD nSize)`. Writes `"oxideav-vfw\0"` into the buffer up to
/// `nSize`, returns the number of bytes written (excluding NUL).
fn stub_get_module_file_name_a(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let _h = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("GetModuleFileNameA", t))?;
    let dst = arg_dword(cpu, mmu, 1).map_err(|t| trap_to_win32("GetModuleFileNameA", t))?;
    let n_size = arg_dword(cpu, mmu, 2).map_err(|t| trap_to_win32("GetModuleFileNameA", t))?;
    if dst == 0 || n_size == 0 {
        return Ok(0);
    }
    let s = b"oxideav-vfw";
    let mut written = 0u32;
    for (i, b) in s.iter().enumerate() {
        if (i as u32) >= n_size.saturating_sub(1) {
            break;
        }
        mmu.store8(dst + i as u32, *b)
            .map_err(|t| trap_to_win32("GetModuleFileNameA", t))?;
        written = written.saturating_add(1);
    }
    // Always NUL-terminate (within nSize).
    if n_size > 0 {
        let nul_off = written.min(n_size - 1);
        mmu.store8(dst + nul_off, 0)
            .map_err(|t| trap_to_win32("GetModuleFileNameA", t))?;
    }
    Ok(written)
}

/// `HMODULE GetModuleHandleA(LPCSTR lpModuleName)`. NULL =>
/// the primary loaded DLL's image base; otherwise look up via
/// `state.modules`.
fn stub_get_module_handle_a(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let p = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("GetModuleHandleA", t))?;
    if p == 0 {
        return Ok(state.primary_module_base);
    }
    let name = read_cstr(mmu, p, 260)?.to_ascii_lowercase();
    Ok(state.modules.get(&name).copied().unwrap_or(0))
}

/// `void GetStartupInfoA(LPSTARTUPINFO lpStartupInfo)`. Fills
/// the `STARTUPINFO` struct with `cb=68`, all other fields zero.
fn stub_get_startup_info_a(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let p = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("GetStartupInfoA", t))?;
    if p == 0 {
        return Ok(0);
    }
    // STARTUPINFOA is 68 bytes — zero all of it, then stamp cb.
    for i in 0..68u32 {
        mmu.store8(p + i, 0)
            .map_err(|t| trap_to_win32("GetStartupInfoA", t))?;
    }
    mmu.store32(p, 68)
        .map_err(|t| trap_to_win32("GetStartupInfoA", t))?;
    Ok(0)
}

/// `HANDLE GetStdHandle(DWORD nStdHandle)`. Returns
/// `INVALID_HANDLE_VALUE = 0xFFFFFFFF`. Codecs that branch on
/// this fall through to a no-stdio path.
fn stub_get_std_handle(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    Ok(0xFFFF_FFFF)
}

/// `void GetSystemInfo(LPSYSTEM_INFO lpSystemInfo)`. Fills the
/// `SYSTEM_INFO` struct with sensible defaults — single Pentium
/// processor, 4 KiB pages.
fn stub_get_system_info(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let p = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("GetSystemInfo", t))?;
    if p == 0 {
        return Ok(0);
    }
    let trap = |t: crate::emulator::Trap| trap_to_win32("GetSystemInfo", t);
    // SYSTEM_INFO layout (winbase.h):
    //   union { DWORD dwOemId;
    //           struct { WORD wProcessorArchitecture;
    //                    WORD wReserved; } };           // 4
    //   DWORD dwPageSize;                               // 4
    //   LPVOID lpMinimumApplicationAddress;             // 4
    //   LPVOID lpMaximumApplicationAddress;             // 4
    //   DWORD_PTR dwActiveProcessorMask;                // 4 (32-bit)
    //   DWORD dwNumberOfProcessors;                     // 4
    //   DWORD dwProcessorType;                          // 4
    //   DWORD dwAllocationGranularity;                  // 4
    //   WORD wProcessorLevel;                           // 2
    //   WORD wProcessorRevision;                        // 2
    // total: 36 bytes.
    mmu.store32(p, 0).map_err(trap)?; // dwOemId = PROCESSOR_ARCHITECTURE_INTEL = 0
    mmu.store32(p + 4, PAGE_SIZE as u32).map_err(trap)?;
    mmu.store32(p + 8, 0x10000).map_err(trap)?;
    mmu.store32(p + 12, 0x7FFF_FFFF).map_err(trap)?;
    mmu.store32(p + 16, 1).map_err(trap)?; // ActiveProcessorMask
    mmu.store32(p + 20, 1).map_err(trap)?; // NumberOfProcessors
    mmu.store32(p + 24, 586).map_err(trap)?; // dwProcessorType (PROCESSOR_INTEL_PENTIUM)
    mmu.store32(p + 28, 0x10000).map_err(trap)?; // dwAllocationGranularity
    mmu.store16(p + 32, 0).map_err(trap)?; // wProcessorLevel
    mmu.store16(p + 34, 0).map_err(trap)?; // wProcessorRevision
    Ok(0)
}

/// `DWORD GetVersion(void)`. Returns Win98-shaped value: low
/// word = (minor << 8) | major, high word = build (= 0).
/// `0x00000A04` = major=4, minor=10 → Windows 98.
fn stub_get_version(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    Ok(0x0000_0A04)
}

/// `HGLOBAL GlobalAlloc(UINT uFlags, SIZE_T dwBytes)`. The
/// `Global*` family is a legacy alias for `Local*` — same heap.
const GMEM_ZEROINIT: u32 = 0x0040;

fn stub_global_alloc(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let flags = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("GlobalAlloc", t))?;
    let n = arg_dword(cpu, mmu, 1).map_err(|t| trap_to_win32("GlobalAlloc", t))?;
    let addr = bump_alloc(state, n)?;
    let mut buf = vec![0u8; n as usize];
    if (flags & GMEM_ZEROINIT) != 0 {
        for b in buf.iter_mut() {
            *b = 0;
        }
    }
    mmu.write_initializer(addr, &buf)
        .map_err(|t| trap_to_win32("GlobalAlloc", t))?;
    state.heap.insert(addr, buf);
    Ok(addr)
}

/// `HGLOBAL GlobalFree(HGLOBAL hMem)`. Removes the slab; returns
/// NULL on success per MSDN.
fn stub_global_free(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let addr = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("GlobalFree", t))?;
    if addr == 0 {
        return Ok(0);
    }
    state
        .heap
        .remove(&addr)
        .ok_or(Win32Error::InvalidHeapBlock {
            stub: "GlobalFree",
            addr,
        })?;
    Ok(0)
}

/// `LPVOID GlobalLock(HGLOBAL hMem)`. We don't move handles, so
/// we return the address itself.
fn stub_global_lock(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let addr = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("GlobalLock", t))?;
    Ok(addr)
}

/// `BOOL GlobalUnlock(HGLOBAL hMem)`. Returns FALSE per MSDN
/// when "the memory object is no longer locked" — but with our
/// no-op-lock model we always return FALSE+last_error=NO_ERROR
/// so the caller's reference count goes to zero cleanly.
fn stub_global_unlock(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let _addr = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("GlobalUnlock", t))?;
    state.last_error = 0; // NO_ERROR
    Ok(0)
}

/// `int MultiByteToWideChar(UINT codepage, DWORD dwFlags,
/// LPCSTR lpMultiByteStr, int cbMultiByte, LPWSTR
/// lpWideCharStr, int cchWideChar)`.
///
/// Implements code pages CP_ACP (1252), CP_OEMCP (437), and
/// CP_UTF8 (65001) by zero-extending each input byte to a
/// UTF-16 code unit. Honours the cchWideChar=0 case (return
/// required length without writing).
fn stub_multi_byte_to_wide_char(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let _cp = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("MultiByteToWideChar", t))?;
    let _flags = arg_dword(cpu, mmu, 1).map_err(|t| trap_to_win32("MultiByteToWideChar", t))?;
    let src = arg_dword(cpu, mmu, 2).map_err(|t| trap_to_win32("MultiByteToWideChar", t))?;
    let cb = arg_dword(cpu, mmu, 3).map_err(|t| trap_to_win32("MultiByteToWideChar", t))?;
    let dst = arg_dword(cpu, mmu, 4).map_err(|t| trap_to_win32("MultiByteToWideChar", t))?;
    let cch = arg_dword(cpu, mmu, 5).map_err(|t| trap_to_win32("MultiByteToWideChar", t))?;
    if src == 0 {
        return Ok(0);
    }
    // cbMultiByte = -1 means "include the NUL terminator and stop
    // at it"; i.e. compute strlen+1.
    let n = if cb == 0xFFFF_FFFF {
        let mut p = src;
        let mut k: u32 = 0;
        loop {
            let b = mmu
                .load8(p)
                .map_err(|t| trap_to_win32("MultiByteToWideChar", t))?;
            k = k.saturating_add(1);
            if b == 0 {
                break;
            }
            p = p.wrapping_add(1);
            if k > 0x0010_0000 {
                break; // safety bound (1 MiB)
            }
        }
        k
    } else {
        cb
    };

    if cch == 0 {
        // Caller wants the required length, no write.
        return Ok(n);
    }
    if dst == 0 {
        return Ok(0);
    }
    let to_write = core::cmp::min(n, cch);
    for i in 0..to_write {
        let b = mmu
            .load8(src + i)
            .map_err(|t| trap_to_win32("MultiByteToWideChar", t))?;
        mmu.store16(dst + i * 2, u16::from(b))
            .map_err(|t| trap_to_win32("MultiByteToWideChar", t))?;
    }
    Ok(to_write)
}

/// `int WideCharToMultiByte(UINT codepage, DWORD dwFlags,
/// LPCWSTR lpWideCharStr, int cchWideChar, LPSTR
/// lpMultiByteStr, int cbMultiByte, LPCSTR lpDefaultChar,
/// LPBOOL lpUsedDefaultChar)`.
///
/// Inverse of `MultiByteToWideChar`: writes the low byte if
/// the UTF-16 unit fits in 8 bits, else uses lpDefaultChar
/// (or `'?'` if lpDefaultChar is NULL) and sets
/// `*lpUsedDefaultChar = TRUE`.
#[allow(clippy::too_many_arguments)]
fn stub_wide_char_to_multi_byte(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let _cp = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("WideCharToMultiByte", t))?;
    let _flags = arg_dword(cpu, mmu, 1).map_err(|t| trap_to_win32("WideCharToMultiByte", t))?;
    let src = arg_dword(cpu, mmu, 2).map_err(|t| trap_to_win32("WideCharToMultiByte", t))?;
    let cch = arg_dword(cpu, mmu, 3).map_err(|t| trap_to_win32("WideCharToMultiByte", t))?;
    let dst = arg_dword(cpu, mmu, 4).map_err(|t| trap_to_win32("WideCharToMultiByte", t))?;
    let cb = arg_dword(cpu, mmu, 5).map_err(|t| trap_to_win32("WideCharToMultiByte", t))?;
    let p_default = arg_dword(cpu, mmu, 6).map_err(|t| trap_to_win32("WideCharToMultiByte", t))?;
    let p_used = arg_dword(cpu, mmu, 7).map_err(|t| trap_to_win32("WideCharToMultiByte", t))?;
    if src == 0 {
        return Ok(0);
    }

    // cchWideChar = -1 ⇒ stop at NUL (and include it in count).
    let n = if cch == 0xFFFF_FFFF {
        let mut p = src;
        let mut k: u32 = 0;
        loop {
            let u = mmu
                .load16(p)
                .map_err(|t| trap_to_win32("WideCharToMultiByte", t))?;
            k = k.saturating_add(1);
            if u == 0 {
                break;
            }
            p = p.wrapping_add(2);
            if k > 0x0010_0000 {
                break;
            }
        }
        k
    } else {
        cch
    };

    let default_char: u8 = if p_default != 0 {
        mmu.load8(p_default)
            .map_err(|t| trap_to_win32("WideCharToMultiByte", t))?
    } else {
        b'?'
    };

    if cb == 0 {
        return Ok(n);
    }
    if dst == 0 {
        return Ok(0);
    }

    let to_write = core::cmp::min(n, cb);
    let mut used_default = false;
    for i in 0..to_write {
        let u = mmu
            .load16(src + i * 2)
            .map_err(|t| trap_to_win32("WideCharToMultiByte", t))?;
        let b = if u <= 0xFF {
            u as u8
        } else {
            used_default = true;
            default_char
        };
        mmu.store8(dst + i, b)
            .map_err(|t| trap_to_win32("WideCharToMultiByte", t))?;
    }
    if p_used != 0 {
        mmu.store32(p_used, if used_default { 1 } else { 0 })
            .map_err(|t| trap_to_win32("WideCharToMultiByte", t))?;
    }
    Ok(to_write)
}

/// `void RtlUnwind(PVOID TargetFrame, PVOID TargetIp,
/// PEXCEPTION_RECORD ExceptionRecord, PVOID ReturnValue)`.
///
/// SEH-stub per the design doc's "out of scope until specifically
/// needed" entry. The codec's `__try` blocks effectively become
/// no-ops; if a codec actually relies on SEH for control flow
/// (rather than only for cleanup), the trap will surface on the
/// first instruction past the try-body it expected to skip.
fn stub_rtl_unwind(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    Ok(0)
}

const MEM_COMMIT: u32 = 0x0000_1000;
const MEM_RESERVE: u32 = 0x0000_2000;
#[allow(dead_code)]
const MEM_RELEASE: u32 = 0x0000_8000;
#[allow(dead_code)]
const MEM_DECOMMIT: u32 = 0x0000_4000;
const PAGE_NOACCESS: u32 = 0x01;
const PAGE_READONLY: u32 = 0x02;
const PAGE_READWRITE: u32 = 0x04;
#[allow(dead_code)]
const PAGE_EXECUTE: u32 = 0x10;
const PAGE_EXECUTE_READ: u32 = 0x20;
const PAGE_EXECUTE_READWRITE: u32 = 0x40;

fn page_protect_to_perm(flprot: u32) -> Perm {
    // Mask out PAGE_GUARD / PAGE_NOCACHE / PAGE_WRITECOMBINE.
    let base = flprot & 0xFF;
    match base {
        PAGE_NOACCESS => Perm::from_bits(0),
        PAGE_READONLY => Perm::R,
        PAGE_READWRITE => Perm::R | Perm::W,
        PAGE_EXECUTE_READ => Perm::R | Perm::X,
        PAGE_EXECUTE_READWRITE => Perm::R | Perm::W | Perm::X,
        _ => Perm::R | Perm::W,
    }
}

/// Region [0xA000_0000, 0xC000_0000) reserved for VirtualAlloc
/// when the caller passes lpAddress=NULL. Kept well above the
/// heap/stack regions configured by `Sandbox::new`.
const VIRTUAL_ALLOC_LO: u32 = 0xA000_0000;
const VIRTUAL_ALLOC_HI: u32 = 0xC000_0000;

/// `LPVOID VirtualAlloc(LPVOID lpAddress, SIZE_T dwSize,
/// DWORD flAllocationType, DWORD flProtect)`.
///
/// MEM_RESERVE alone reserves address space without committing
/// pages; MEM_COMMIT (alone or together) maps the pages with
/// the `flProtect` permissions. We honour MEM_COMMIT by mapping
/// real pages; MEM_RESERVE-only is treated the same way (we
/// don't model the reserve/commit split distinctly).
fn stub_virtual_alloc(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let lp_addr = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("VirtualAlloc", t))?;
    let size = arg_dword(cpu, mmu, 1).map_err(|t| trap_to_win32("VirtualAlloc", t))?;
    let alloc_type = arg_dword(cpu, mmu, 2).map_err(|t| trap_to_win32("VirtualAlloc", t))?;
    let prot = arg_dword(cpu, mmu, 3).map_err(|t| trap_to_win32("VirtualAlloc", t))?;

    if size == 0 {
        return Ok(0);
    }
    let perm = page_protect_to_perm(prot);
    let aligned_size = ((size + (PAGE_SIZE as u32 - 1)) & !(PAGE_SIZE as u32 - 1)).max(size);

    let base = if lp_addr == 0 {
        match mmu.find_free_range(VIRTUAL_ALLOC_LO, VIRTUAL_ALLOC_HI, aligned_size) {
            Some(b) => b,
            None => return Ok(0),
        }
    } else {
        // Round down to a page boundary.
        lp_addr & !(PAGE_SIZE as u32 - 1)
    };

    if (alloc_type & (MEM_COMMIT | MEM_RESERVE)) != 0 || alloc_type == 0 {
        mmu.map(base, aligned_size, perm);
    }
    Ok(base)
}

/// `BOOL VirtualFree(LPVOID lpAddress, SIZE_T dwSize, DWORD dwFreeType)`.
fn stub_virtual_free(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let lp_addr = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("VirtualFree", t))?;
    let size = arg_dword(cpu, mmu, 1).map_err(|t| trap_to_win32("VirtualFree", t))?;
    let _free_type = arg_dword(cpu, mmu, 2).map_err(|t| trap_to_win32("VirtualFree", t))?;
    if lp_addr == 0 {
        return Ok(0);
    }
    // For MEM_RELEASE, MSDN requires dwSize == 0 — we ignore that
    // detail and unmap whatever range the caller supplied. If
    // size == 0 (release of the whole allocation), do nothing —
    // we don't track per-allocation extents.
    if size > 0 {
        let aligned_size = (size + (PAGE_SIZE as u32 - 1)) & !(PAGE_SIZE as u32 - 1);
        mmu.unmap(lp_addr & !(PAGE_SIZE as u32 - 1), aligned_size);
    }
    Ok(1)
}

/// `BOOL WriteFile(HANDLE hFile, LPCVOID lpBuffer,
/// DWORD nNumberOfBytesToWrite, LPDWORD lpNumberOfBytesWritten,
/// LPOVERLAPPED lpOverlapped)`. Stub failure: returns FALSE,
/// sets last error to ERROR_INVALID_HANDLE.
const ERROR_INVALID_HANDLE: u32 = 6;
fn stub_write_file(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let _h = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("WriteFile", t))?;
    let _lp_buf = arg_dword(cpu, mmu, 1).map_err(|t| trap_to_win32("WriteFile", t))?;
    let _n = arg_dword(cpu, mmu, 2).map_err(|t| trap_to_win32("WriteFile", t))?;
    let lp_written = arg_dword(cpu, mmu, 3).map_err(|t| trap_to_win32("WriteFile", t))?;
    let _lp_ovl = arg_dword(cpu, mmu, 4).map_err(|t| trap_to_win32("WriteFile", t))?;
    if lp_written != 0 {
        // Best-effort write zero into bytes-written so the
        // caller's error path doesn't UB-read garbage.
        mmu.store32(lp_written, 0)
            .map_err(|t| trap_to_win32("WriteFile", t))?;
    }
    state.last_error = ERROR_INVALID_HANDLE;
    Ok(0)
}

// ----- helpers -------------------------------------------------------

fn read_cstr(mmu: &Mmu, mut addr: u32, max: u32) -> Result<String, Win32Error> {
    let mut bytes = Vec::new();
    for _ in 0..max {
        let b = mmu.load8(addr).map_err(|t| trap_to_win32("read_cstr", t))?;
        if b == 0 {
            break;
        }
        bytes.push(b);
        addr = addr.wrapping_add(1);
    }
    Ok(String::from_utf8_lossy(&bytes).into_owned())
}

fn trap_to_win32(stub: &'static str, t: crate::emulator::Trap) -> Win32Error {
    Win32Error::InvalidArgument {
        stub,
        reason: format!("{t}"),
    }
}

// ====================================================================
// Round-8 fail-soft stubs.
// ====================================================================
//
// Each function below is the "minimum viable" implementation: it
// honours the public ABI (return value semantics + arg-count for
// stdcall cleanup) but performs no real Windows operation. Codecs
// that genuinely depend on a side effect (e.g. a real critical
// section excluding a phantom thread) would surface a fault later;
// in practice IR50_32.DLL imports many of these for rarely-taken
// branches (registry, dialog config, error-popup paths) that the
// `IC*` decode pipeline never executes.

/// `BOOL CloseHandle(HANDLE)`. Always succeeds.
fn stub_close_handle(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    Ok(1)
}

/// `HANDLE CreateFileMappingA(HANDLE hFile, LPSECURITY_ATTRIBUTES,
/// DWORD flProtect, DWORD dwMaxSizeHigh, DWORD dwMaxSizeLow,
/// LPCSTR lpName)`. Round 12 — for `hFile == INVALID_HANDLE_VALUE`
/// (-1) the call requests a pagefile-backed anonymous mapping;
/// `IR50_32.DLL` uses this to share its huffman / DCT tables
/// between concurrent decoder instances. Our sandbox is
/// single-instance so we just allocate a fresh buffer of size
/// `dwMaxSizeLow` and return its address as the handle. The
/// matching `MapViewOfFile` returns the same address.
fn stub_create_file_mapping_a(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let _h_file = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("CreateFileMappingA", t))?;
    let _attrs = arg_dword(cpu, mmu, 1).map_err(|t| trap_to_win32("CreateFileMappingA", t))?;
    let _protect = arg_dword(cpu, mmu, 2).map_err(|t| trap_to_win32("CreateFileMappingA", t))?;
    let _size_hi = arg_dword(cpu, mmu, 3).map_err(|t| trap_to_win32("CreateFileMappingA", t))?;
    let size_lo = arg_dword(cpu, mmu, 4).map_err(|t| trap_to_win32("CreateFileMappingA", t))?;
    let _name = arg_dword(cpu, mmu, 5).map_err(|t| trap_to_win32("CreateFileMappingA", t))?;
    if size_lo == 0 {
        return Ok(0);
    }
    let addr = bump_alloc(state, size_lo)?;
    let buf = vec![0u8; size_lo as usize];
    mmu.write_initializer(addr, &buf)
        .map_err(|t| trap_to_win32("CreateFileMappingA", t))?;
    state.heap.insert(addr, buf);
    Ok(addr)
}

/// `HANDLE CreateSemaphoreA(...)`. Returns a non-zero pseudo
/// handle so the codec's RAII wrappers don't bail on NULL. We
/// don't actually model semaphores.
fn stub_create_semaphore_a(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    Ok(0xC0DE_5E3A) // pseudo-handle
}

/// `void DeleteCriticalSection(LPCRITICAL_SECTION)`. No-op.
fn stub_delete_critical_section(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    Ok(0)
}

/// `BOOL DisableThreadLibraryCalls(HMODULE)`. We don't model
/// per-thread DllMain calls; success is the right answer.
fn stub_disable_thread_library_calls(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    Ok(1)
}

/// `void EnterCriticalSection(LPCRITICAL_SECTION)`. We are
/// single-threaded; the section is always free.
fn stub_enter_critical_section(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    Ok(0)
}

/// `void LeaveCriticalSection(LPCRITICAL_SECTION)`. No-op.
fn stub_leave_critical_section(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    Ok(0)
}

/// `void InitializeCriticalSection(LPCRITICAL_SECTION lpcs)`.
/// Real initialisation zeroes the structure (20 bytes for x86
/// CRITICAL_SECTION). We mimic the zero-fill so callers that
/// inspect the structure see a clean state.
fn stub_initialize_critical_section(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let p = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("InitializeCriticalSection", t))?;
    if p != 0 {
        // 24-byte CRITICAL_SECTION on x86. Touching pages outside
        // the structure would WriteProtectFault — the codec
        // always allocates this from its heap, so writes succeed.
        for i in 0..24u32 {
            // Best-effort: ignore individual byte faults so a
            // truncated mapping doesn't blow up the test. The
            // structure is opaque from the codec's POV.
            let _ = mmu.store8(p + i, 0);
        }
    }
    Ok(0)
}

/// Walk a `IMAGE_RESOURCE_DIRECTORY` looking for an entry matching
/// `key`. The directory's entries (named first, then ID-keyed) are
/// laid out immediately after the 16-byte header. `dir_va` is the
/// VA of the directory itself; `rsrc_base` is the VA of the
/// top-level resource directory (used to resolve sub-directory
/// offsets, which are relative to it).
///
/// Returns `Some((offset_to_data_or_dir, is_directory))` on match,
/// where `offset_to_data_or_dir` is relative to `rsrc_base`.
///
/// `key` may be either an ID (`name & 0x8000_0000 == 0`, low 16
/// bits = id) or a string-name (`name & 0x8000_0000 != 0`,
/// low 31 bits = offset relative to `rsrc_base` of a UTF-16
/// length-prefixed name). Round 12 only walks ID-keyed entries
/// because `IR50_32.DLL`'s codec resources are all ID-keyed
/// (RT_BITMAP / 112).
fn rsrc_dir_lookup_id(
    mmu: &Mmu,
    _rsrc_base: u32,
    dir_va: u32,
    target_id: u32,
) -> Option<(u32, bool)> {
    // Header: NumberOfNamedEntries at offset 12, NumberOfIdEntries at 14.
    let n_named = mmu.load16(dir_va + 12).ok()? as u32;
    let n_id = mmu.load16(dir_va + 14).ok()? as u32;
    let entries_va = dir_va + 16;
    // ID entries follow the named ones.
    for i in 0..n_id {
        let e_va = entries_va + (n_named + i) * 8;
        let name = mmu.load32(e_va).ok()?;
        // Defensive: skip name-keyed entries in the ID table
        // (PE format guarantees they don't appear there, but
        // a malformed image shouldn't fault us).
        if (name & 0x8000_0000) != 0 {
            continue;
        }
        if name == target_id {
            let off = mmu.load32(e_va + 4).ok()?;
            let is_dir = (off & 0x8000_0000) != 0;
            return Some((off & 0x7FFF_FFFF, is_dir));
        }
    }
    None
}

/// Resolve a `(hModule, lpName, lpType)` triple to the VA of the
/// `IMAGE_RESOURCE_DATA_ENTRY` for that resource. Returns `None`
/// if the module has no resource directory or no matching entry.
///
/// Both `lpName` and `lpType` are interpreted as
/// `MAKEINTRESOURCE`-style integers when their high 16 bits are
/// zero (this is how `IR50_32.DLL` invokes us — type 2 = RT_BITMAP,
/// name 112). Round 12 doesn't yet support string-keyed
/// resources; if either argument is a pointer, return `None`.
pub(crate) fn find_resource_data_entry(
    state: &HostState,
    mmu: &Mmu,
    h_module: u32,
    lp_name: u32,
    lp_type: u32,
) -> Option<u32> {
    // hModule = 0 means "the calling module" — use the primary.
    let h = if h_module == 0 {
        state.primary_module_base
    } else {
        h_module
    };
    let rsrc_base = *state.module_resource_dirs.get(&h)?;
    // MAKEINTRESOURCE check: high word zero → integer ID. PE
    // resource tables store integer IDs as the low 31 bits with
    // the high bit clear. lpName=112 fits in u16; same for lpType.
    if lp_name & 0xFFFF_0000 != 0 || lp_type & 0xFFFF_0000 != 0 {
        return None;
    }
    // Top-level: keyed by type. PE format guarantees the high
    // bit of the offset is set (each top-level entry points to a
    // sub-directory).
    let (off_type, is_dir) = rsrc_dir_lookup_id(mmu, rsrc_base, rsrc_base, lp_type)?;
    if !is_dir {
        return None;
    }
    // Second-level: keyed by name (or ID).
    let (off_name, is_dir) = rsrc_dir_lookup_id(mmu, rsrc_base, rsrc_base + off_type, lp_name)?;
    if !is_dir {
        return None;
    }
    // Third-level: keyed by language. We pick the first entry
    // (LANG_NEUTRAL would be ideal but real codecs ship one
    // language; IR50 ships 1033 = en-US).
    let lang_dir_va = rsrc_base + off_name;
    let n_named = mmu.load16(lang_dir_va + 12).ok()? as u32;
    let n_id = mmu.load16(lang_dir_va + 14).ok()? as u32;
    if n_named + n_id == 0 {
        return None;
    }
    let first_entry = lang_dir_va + 16;
    let off = mmu.load32(first_entry + 4).ok()?;
    if (off & 0x8000_0000) != 0 {
        // Should be a leaf, not another directory.
        return None;
    }
    Some(rsrc_base + (off & 0x7FFF_FFFF))
}

/// `HRSRC FindResourceA(HMODULE, LPCSTR lpName, LPCSTR lpType)`.
/// Round-12 walks the PE resource directory of `hModule` (or the
/// primary module if NULL) looking for an `(lpType, lpName)`
/// match. Returns the VA of the `IMAGE_RESOURCE_DATA_ENTRY`
/// (the on-disk struct that points to the actual resource bytes)
/// — `LoadResource` then dereferences this to a pointer.
fn stub_find_resource_a(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let h_module = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("FindResourceA", t))?;
    let lp_name = arg_dword(cpu, mmu, 1).map_err(|t| trap_to_win32("FindResourceA", t))?;
    let lp_type = arg_dword(cpu, mmu, 2).map_err(|t| trap_to_win32("FindResourceA", t))?;
    Ok(find_resource_data_entry(state, mmu, h_module, lp_name, lp_type).unwrap_or(0))
}

/// `BOOL FlushFileBuffers(HANDLE)`. Always succeeds.
fn stub_flush_file_buffers(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    Ok(1)
}

/// `BOOL FreeEnvironmentStringsA/W(LPCSTR/LPCWSTR)`. No-op
/// success.
fn stub_free_environment_strings(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    Ok(1)
}

/// `BOOL FreeLibrary(HMODULE)`. We don't actually unload modules
/// inside the sandbox; success keeps the codec's RAII shims happy.
fn stub_free_library(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    Ok(1)
}

/// `BOOL FreeResource(HGLOBAL hResData)`. No-op success.
fn stub_free_resource(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    Ok(1)
}

/// `HANDLE GetCurrentProcess(void)`. Pseudo-handle 0xFFFFFFFF
/// per MSDN (a magic constant the codec only compares to itself).
fn stub_get_current_process(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    Ok(0xFFFF_FFFF)
}

/// `DWORD GetCurrentThreadId(void)`. Synthetic 1 (single thread).
fn stub_get_current_thread_id(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    Ok(1)
}

/// `LPWCH GetEnvironmentStringsW(void)`. We hand back the same
/// pointer as `GetEnvironmentStrings` (an empty UTF-16 block).
fn stub_get_environment_strings_w(
    _cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    if state.environment_strings_ptr != 0 {
        return Ok(state.environment_strings_ptr);
    }
    // 4 bytes: two UTF-16 NULs (one to end the last entry, one to
    // terminate the block).
    let p = state.arena_const_alloc(4)?;
    mmu.write_initializer(p, &[0, 0, 0, 0])
        .map_err(|t| trap_to_win32("GetEnvironmentStringsW", t))?;
    state.environment_strings_ptr = p;
    Ok(p)
}

/// `int GetLocaleInfoA/W(LCID, LCTYPE, LPSTR/LPWSTR, int)`.
/// Return 0 (= "no data") and let the CRT use the default locale.
fn stub_get_locale_info_a(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    Ok(0)
}

/// `DWORD GetShortPathNameA(LPCSTR, LPSTR, DWORD)`. No filesystem
/// is modelled — return 0 = "fail". The codec falls back to the
/// long-path string.
fn stub_get_short_path_name_a(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    Ok(0)
}

/// `BOOL GetStringTypeA/W(...)`. Return 1 = "success", with no
/// type bits actually written. Some CRTs use this for is_alpha;
/// the codec's decode body doesn't, so leaving the buffer
/// untouched is benign.
fn stub_get_string_type(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    Ok(1)
}

/// `UINT GetSystemDirectoryA(LPSTR lpBuffer, UINT uSize)`.
/// Writes "C:\\WINDOWS\\System32" into `lpBuffer` and returns the
/// length. Codecs use this to locate sibling DLLs; we don't
/// actually load them, but the returned string keeps the codec's
/// path-construction code happy.
fn stub_get_system_directory_a(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let buf = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("GetSystemDirectoryA", t))?;
    let size = arg_dword(cpu, mmu, 1).map_err(|t| trap_to_win32("GetSystemDirectoryA", t))?;
    let s = b"C:\\WINDOWS\\System32";
    if buf == 0 || size == 0 {
        return Ok(s.len() as u32 + 1);
    }
    let n = (size as usize).saturating_sub(1).min(s.len());
    for (i, &b) in s.iter().take(n).enumerate() {
        mmu.store8(buf + i as u32, b)
            .map_err(|t| trap_to_win32("GetSystemDirectoryA", t))?;
    }
    mmu.store8(buf + n as u32, 0)
        .map_err(|t| trap_to_win32("GetSystemDirectoryA", t))?;
    Ok(n as u32)
}

/// `BOOL GetVersionExA(LPOSVERSIONINFOA)`. Fills in a Windows 95
/// shape: 4.00.0950, VER_PLATFORM_WIN32_WINDOWS = 1.
///
/// OSVERSIONINFOA layout (148 bytes):
///   DWORD dwOSVersionInfoSize     (in)
///   DWORD dwMajorVersion
///   DWORD dwMinorVersion
///   DWORD dwBuildNumber
///   DWORD dwPlatformId
///   CHAR  szCSDVersion[128]
fn stub_get_version_ex_a(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let p = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("GetVersionExA", t))?;
    if p == 0 {
        return Ok(0);
    }
    // Skip dwOSVersionInfoSize at offset 0 (caller-supplied).
    mmu.store32(p + 4, 4)
        .map_err(|t| trap_to_win32("GetVersionExA", t))?; // dwMajorVersion
    mmu.store32(p + 8, 0)
        .map_err(|t| trap_to_win32("GetVersionExA", t))?; // dwMinorVersion
    mmu.store32(p + 12, 950)
        .map_err(|t| trap_to_win32("GetVersionExA", t))?; // dwBuildNumber
    mmu.store32(p + 16, 1)
        .map_err(|t| trap_to_win32("GetVersionExA", t))?; // dwPlatformId
                                                          // szCSDVersion: ""
    mmu.store8(p + 20, 0)
        .map_err(|t| trap_to_win32("GetVersionExA", t))?;
    Ok(1)
}

/// `HGLOBAL GlobalHandle(LPCVOID pMem)`. Return the same pointer
/// — our heap is single-flat-arena, so `pMem` and the "handle"
/// are the same value.
fn stub_global_handle(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let p = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("GlobalHandle", t))?;
    Ok(p)
}

/// `HGLOBAL GlobalReAlloc(HGLOBAL hMem, SIZE_T dwBytes, UINT
/// uFlags)`. Same shape as `HeapReAlloc` minus the `dwFlags`
/// argument; reuse the heap re-alloc path.
fn stub_global_realloc(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let addr = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("GlobalReAlloc", t))?;
    let n = arg_dword(cpu, mmu, 1).map_err(|t| trap_to_win32("GlobalReAlloc", t))?;
    let _flags = arg_dword(cpu, mmu, 2).map_err(|t| trap_to_win32("GlobalReAlloc", t))?;
    if addr == 0 {
        let new_addr = bump_alloc(state, n)?;
        let buf = vec![0u8; n as usize];
        mmu.write_initializer(new_addr, &buf)
            .map_err(|t| trap_to_win32("GlobalReAlloc", t))?;
        state.heap.insert(new_addr, buf);
        return Ok(new_addr);
    }
    let old = state
        .heap
        .remove(&addr)
        .ok_or(Win32Error::InvalidHeapBlock {
            stub: "GlobalReAlloc",
            addr,
        })?;
    let new_addr = bump_alloc(state, n)?;
    let mut buf = vec![0u8; n as usize];
    let copy_n = old.len().min(n as usize);
    buf[..copy_n].copy_from_slice(&old[..copy_n]);
    mmu.write_initializer(new_addr, &buf)
        .map_err(|t| trap_to_win32("GlobalReAlloc", t))?;
    state.heap.insert(new_addr, buf);
    Ok(new_addr)
}

/// `HANDLE HeapCreate(DWORD flOptions, SIZE_T dwInitialSize,
/// SIZE_T dwMaximumSize)`. Hand back the global heap handle —
/// codecs don't typically pin to a private heap.
fn stub_heap_create(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    Ok(state.process_heap_handle)
}

/// `BOOL HeapDestroy(HANDLE)`. No-op success.
fn stub_heap_destroy(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    Ok(1)
}

/// `BOOL IsBadCodePtr/IsBadReadPtr/IsBadWritePtr(...)`. Return 0
/// (= "the pointer is fine"); we trust the codec to read/write
/// only validly-mapped pages.
fn stub_is_bad_ptr(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    Ok(0)
}

/// `int LCMapStringA/W(...)`. Return 0 = failure; CRTs fall back
/// to byte-by-byte processing.
fn stub_lc_map_string(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    Ok(0)
}

/// `HGLOBAL LoadResource(HMODULE hModule, HRSRC hResInfo)`.
/// Round 12 — `hResInfo` is the `IMAGE_RESOURCE_DATA_ENTRY` VA
/// returned by `FindResourceA`. The Win32 contract is that
/// `LoadResource` returns an `HGLOBAL` whose only contract is
/// being a valid argument to `LockResource` / `SizeofResource`;
/// we simply return `hResInfo` itself (Wine and several MSDN
/// samples do the same — both `LoadResource` and `LockResource`
/// are no-ops on modern Windows since the resource bytes are
/// already memory-mapped).
fn stub_load_resource(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let _h_module = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("LoadResource", t))?;
    let h_res_info = arg_dword(cpu, mmu, 1).map_err(|t| trap_to_win32("LoadResource", t))?;
    Ok(h_res_info)
}

/// `HLOCAL LocalHandle(LPCVOID pMem)`. Round-tripping a
/// `LocalAlloc` pointer.
fn stub_local_handle(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let p = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("LocalHandle", t))?;
    Ok(p)
}

/// `LPVOID LocalLock(HLOCAL)`. The handle IS the pointer for our
/// heap arena. Real LocalLock is a no-op for fixed (= LMEM_FIXED)
/// allocations, which the CRT defaults to.
fn stub_local_lock(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let p = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("LocalLock", t))?;
    Ok(p)
}

/// `BOOL LocalUnlock(HLOCAL)`. No-op success.
fn stub_local_unlock(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    Ok(1)
}

/// `LPVOID LockResource(HGLOBAL)`. Round 12 — the `HGLOBAL` is
/// the `IMAGE_RESOURCE_DATA_ENTRY` VA we returned from
/// `FindResourceA` / `LoadResource`. The first dword of that
/// struct is `OffsetToData` (an RVA, NOT relative to .rsrc),
/// the second is `Size`. We resolve the RVA against the module
/// base — since all sections including `.rsrc` are mapped into
/// emulator memory at their preferred VA, the resource bytes
/// are directly addressable.
fn stub_lock_resource(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let h = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("LockResource", t))?;
    if h == 0 {
        return Ok(0);
    }
    // First dword of IMAGE_RESOURCE_DATA_ENTRY = RVA.
    let rva = match mmu.load32(h) {
        Ok(v) => v,
        Err(_) => return Ok(0),
    };
    // The RVA is relative to the module image base. We don't
    // know exactly which module the resource belongs to; the
    // primary module's base is the right answer for a
    // single-codec sandbox (round 12). For multi-codec we'd
    // need to thread hModule through.
    if state.primary_module_base == 0 {
        return Ok(0);
    }
    Ok(state.primary_module_base.wrapping_add(rva))
}

/// `DWORD SizeofResource(HMODULE, HRSRC)`. Round 12 — the
/// `HRSRC` is the `IMAGE_RESOURCE_DATA_ENTRY` VA from
/// `FindResourceA`; second dword is `Size`. We're asked to
/// return the byte count. Round 13 wires it into the dispatch
/// registry; IR50_32 doesn't import it, but other codecs (and
/// future round-14+ targets) will.
fn stub_sizeof_resource(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let _h_module = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("SizeofResource", t))?;
    let h_res_info = arg_dword(cpu, mmu, 1).map_err(|t| trap_to_win32("SizeofResource", t))?;
    if h_res_info == 0 {
        return Ok(0);
    }
    match mmu.load32(h_res_info + 4) {
        Ok(v) => Ok(v),
        Err(_) => Ok(0),
    }
}

/// `LPVOID MapViewOfFile(HANDLE hFileMappingObject, DWORD desiredAccess,
/// DWORD offsetHigh, DWORD offsetLow, SIZE_T numBytesToMap)`. Round
/// 12 — `CreateFileMappingA` returned the buffer's start VA as
/// the handle; the view is the entire buffer, so we return
/// `hFileMappingObject` directly (offset 0, full size). Round-13
/// might add real offset support if a codec ever calls with
/// non-zero offset.
fn stub_map_view_of_file(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let h = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("MapViewOfFile", t))?;
    let _access = arg_dword(cpu, mmu, 1).map_err(|t| trap_to_win32("MapViewOfFile", t))?;
    let _off_hi = arg_dword(cpu, mmu, 2).map_err(|t| trap_to_win32("MapViewOfFile", t))?;
    let off_lo = arg_dword(cpu, mmu, 3).map_err(|t| trap_to_win32("MapViewOfFile", t))?;
    let _num = arg_dword(cpu, mmu, 4).map_err(|t| trap_to_win32("MapViewOfFile", t))?;
    if h == 0 {
        return Ok(0);
    }
    Ok(h.wrapping_add(off_lo))
}

/// `HANDLE OpenFileMappingA(...)`. Return NULL.
fn stub_open_file_mapping_a(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    Ok(0)
}

/// `BOOL QueryPerformanceCounter(LARGE_INTEGER* lpPerformanceCount)`.
/// Synthesise a monotonically-increasing 64-bit tick by chaining
/// `state.tick`.
fn stub_query_performance_counter(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let p = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("QueryPerformanceCounter", t))?;
    state.tick = state.tick.wrapping_add(1);
    if p != 0 {
        mmu.store32(p, state.tick)
            .map_err(|t| trap_to_win32("QueryPerformanceCounter", t))?;
        mmu.store32(p + 4, 0)
            .map_err(|t| trap_to_win32("QueryPerformanceCounter", t))?;
    }
    Ok(1)
}

/// `BOOL QueryPerformanceFrequency(LARGE_INTEGER* lpFreq)`. We
/// model 1 MHz (one tick per microsecond). The codec uses this as
/// a divisor for elapsed-time calculations.
fn stub_query_performance_frequency(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let p = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("QueryPerformanceFrequency", t))?;
    if p != 0 {
        mmu.store32(p, 1_000_000)
            .map_err(|t| trap_to_win32("QueryPerformanceFrequency", t))?;
        mmu.store32(p + 4, 0)
            .map_err(|t| trap_to_win32("QueryPerformanceFrequency", t))?;
    }
    Ok(1)
}

/// `void RaiseException(DWORD, DWORD, DWORD, const ULONG_PTR*)`.
/// Real Windows raises a structured exception that the codec's
/// SEH handler may catch. We have no SEH unwinder; logging the
/// event keeps the test diagnosable while the call returns.
fn stub_raise_exception(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let code = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("RaiseException", t))?;
    state
        .debug_log
        .push(format!("RaiseException code={code:#010x}"));
    Ok(0)
}

/// `BOOL ReleaseSemaphore(HANDLE, LONG, LPLONG)`. No-op success.
fn stub_release_semaphore(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    Ok(1)
}

/// `DWORD SetFilePointer(...)`. We have no real file system;
/// return INVALID_SET_FILE_POINTER (= 0xFFFFFFFF).
fn stub_set_file_pointer(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    Ok(0xFFFF_FFFF)
}

/// `UINT SetHandleCount(UINT)`. Return the input (= "we honoured
/// the request"). The CRT uses this to bump its FILE table size.
fn stub_set_handle_count(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let n = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("SetHandleCount", t))?;
    Ok(n)
}

/// `BOOL SetStdHandle(DWORD nStdHandle, HANDLE hHandle)`. No-op
/// success.
fn stub_set_std_handle(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    Ok(1)
}

/// `LPTOP_LEVEL_EXCEPTION_FILTER SetUnhandledExceptionFilter(...)`.
/// Return NULL (= "no previous filter installed"). We don't run
/// the filter on a fault.
fn stub_set_unhandled_exception_filter(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    Ok(0)
}

/// `void Sleep(DWORD)`. We're synchronous — drop the call.
fn stub_sleep(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    Ok(0)
}

/// `BOOL TerminateProcess(HANDLE hProcess, UINT uExitCode)`.
/// Mirror `ExitProcess` — set the exit-requested flag so the run
/// loop returns cleanly.
fn stub_terminate_process(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let _h = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("TerminateProcess", t))?;
    let code = arg_dword(cpu, mmu, 1).map_err(|t| trap_to_win32("TerminateProcess", t))?;
    state.exit_requested = Some(code);
    Ok(1)
}

/// `DWORD TlsAlloc(void)`. Return a synthetic TLS index. TLS in
/// our single-threaded sandbox is just a key/value map keyed by
/// index; we use small integers and store via the host state's
/// debug-log channel for visibility.
fn stub_tls_alloc(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    // tick doubles as a monotonic counter for TLS index minting.
    state.tick = state.tick.wrapping_add(1);
    Ok(state.tick)
}

/// `BOOL TlsFree(DWORD)`. No-op success.
fn stub_tls_free(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    Ok(1)
}

/// `LPVOID TlsGetValue(DWORD)`. Always returns NULL — codecs use
/// this for per-thread caches we don't model.
fn stub_tls_get_value(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    Ok(0)
}

/// `BOOL TlsSetValue(DWORD, LPVOID)`. No-op success.
fn stub_tls_set_value(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    Ok(1)
}

/// `BOOL UnmapViewOfFile(LPCVOID)`. No-op success.
fn stub_unmap_view_of_file(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    Ok(1)
}

/// `DWORD WaitForSingleObject(HANDLE, DWORD)`. Return
/// `WAIT_OBJECT_0` (= 0) — the object is "signaled" immediately.
/// Single-threaded sandbox: any wait succeeds without blocking.
fn stub_wait_for_single_object(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    Ok(0)
}

/// `BOOL WritePrivateProfileStringA(...)`. No-op success — we
/// have no INI files.
fn stub_write_private_profile_string_a(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    Ok(1)
}

/// `int lstrlenA(LPCSTR)`. Real strlen on the guest pointer.
fn stub_lstrlen_a(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let p = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("lstrlenA", t))?;
    if p == 0 {
        return Ok(0);
    }
    let mut n: u32 = 0;
    while n < 0x10000 {
        match mmu.load8(p + n) {
            Ok(0) => break,
            Ok(_) => n = n.wrapping_add(1),
            Err(_) => break,
        }
    }
    Ok(n)
}

// ====================================================================
// Round-20 stubs — `mpg4c32.dll` PE-load surface (Milestone 3.1).
// ====================================================================

/// `HANDLE CreateEventA(LPSECURITY_ATTRIBUTES lpEventAttributes,
/// BOOL bManualReset, BOOL bInitialState, LPCSTR lpName)`. The
/// codec only uses the returned HANDLE as an opaque key for
/// `SetEvent` / `WaitForSingleObject`. We return a non-zero
/// pseudo-handle (`0xCAFE_E001` + a tick-driven offset) so
/// every distinct call site sees a fresh value.
fn stub_create_event_a(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let _attrs = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("CreateEventA", t))?;
    let _manual = arg_dword(cpu, mmu, 1).map_err(|t| trap_to_win32("CreateEventA", t))?;
    let _init = arg_dword(cpu, mmu, 2).map_err(|t| trap_to_win32("CreateEventA", t))?;
    let _name = arg_dword(cpu, mmu, 3).map_err(|t| trap_to_win32("CreateEventA", t))?;
    state.tick = state.tick.wrapping_add(1);
    Ok(0xCAFE_E000u32.wrapping_add(state.tick))
}

/// `HANDLE CreateThread(LPSECURITY_ATTRIBUTES lpThreadAttributes,
/// SIZE_T dwStackSize, LPTHREAD_START_ROUTINE lpStartAddress,
/// LPVOID lpParameter, DWORD dwCreationFlags,
/// LPDWORD lpThreadId)`.
///
/// Single-threaded sandbox semantics: invoke the start routine
/// synchronously (stdcall, one parameter) using
/// [`crate::win32::call_guest`], then return a non-zero
/// pseudo-HANDLE. If the caller passed `lpThreadId`, write a
/// pseudo-thread-id (the same numeric value as the handle).
///
/// `dwCreationFlags & CREATE_SUSPENDED (0x4)` is honoured by
/// returning *without* running the start address; a paired
/// `ResumeThread` does nothing in our model. This mirrors the
/// MSDN contract closely enough for codec init, which only
/// uses the suspend bit to set thread priority before letting
/// the thread run.
fn stub_create_thread(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    registry: &Registry,
) -> Result<u32, Win32Error> {
    const CREATE_SUSPENDED: u32 = 0x0000_0004;
    let _attrs = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("CreateThread", t))?;
    let _stack = arg_dword(cpu, mmu, 1).map_err(|t| trap_to_win32("CreateThread", t))?;
    let start = arg_dword(cpu, mmu, 2).map_err(|t| trap_to_win32("CreateThread", t))?;
    let param = arg_dword(cpu, mmu, 3).map_err(|t| trap_to_win32("CreateThread", t))?;
    let flags = arg_dword(cpu, mmu, 4).map_err(|t| trap_to_win32("CreateThread", t))?;
    let p_tid = arg_dword(cpu, mmu, 5).map_err(|t| trap_to_win32("CreateThread", t))?;

    state.tick = state.tick.wrapping_add(1);
    let handle = 0xCAFE_C000u32.wrapping_add(state.tick);
    if p_tid != 0 {
        mmu.store32(p_tid, handle)
            .map_err(|t| trap_to_win32("CreateThread", t))?;
    }
    if start != 0 && (flags & CREATE_SUSPENDED) == 0 {
        // stdcall: one DWORD argument. The thread proc returns
        // its exit code in eax; we discard it.
        let _ = crate::win32::call_guest(cpu, mmu, registry, state, start, &[param]);
    }
    Ok(handle)
}

/// `BOOL SetEvent(HANDLE)`. Single-threaded sandbox: the event
/// is "signaled" but no one is waiting on it. Return TRUE.
fn stub_set_event(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    Ok(1)
}

/// `BOOL SetThreadPriority(HANDLE, int)`. Single-threaded
/// sandbox: priority changes have no effect, return TRUE.
fn stub_set_thread_priority(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    Ok(1)
}

/// `DWORD ResumeThread(HANDLE)`. Single-threaded sandbox: thread
/// is already "running" (we ran it synchronously inside
/// `CreateThread`), so resume returns the previous suspend count
/// 0. Real `ResumeThread` returns `(DWORD)-1` on failure but
/// codecs don't check.
fn stub_resume_thread(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    Ok(0)
}

/// `int MulDiv(int nNumber, int nNumerator, int nDenominator)`.
/// Returns `(i64)nNumber * nNumerator / nDenominator` rounded
/// to nearest, half away from zero. Returns -1 on
/// `nDenominator == 0` or i32 overflow.
fn stub_muldiv(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let a = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("MulDiv", t))? as i32;
    let b = arg_dword(cpu, mmu, 1).map_err(|t| trap_to_win32("MulDiv", t))? as i32;
    let c = arg_dword(cpu, mmu, 2).map_err(|t| trap_to_win32("MulDiv", t))? as i32;
    if c == 0 {
        return Ok((-1i32) as u32);
    }
    let prod = (a as i64).wrapping_mul(b as i64);
    let cb = c as i64;
    // Half-away-from-zero rounding: add cb/2 (with sign of
    // prod * sign of c) before the divide.
    let sign_match = (prod < 0) == (cb < 0);
    let half = cb.wrapping_abs() / 2;
    let adj = if sign_match { half } else { -half };
    let result = prod.wrapping_add(adj) / cb;
    if result > i32::MAX as i64 || result < i32::MIN as i64 {
        return Ok((-1i32) as u32);
    }
    Ok((result as i32) as u32)
}

/// `UINT GetProfileIntA(LPCSTR lpAppName, LPCSTR lpKeyName,
/// INT nDefault)`. We have no `win.ini` to consult, so always
/// return the caller's default. (Pre-XP API; modern codecs
/// only use it for legacy compatibility settings.)
fn stub_get_profile_int_a(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let _app = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("GetProfileIntA", t))?;
    let _key = arg_dword(cpu, mmu, 1).map_err(|t| trap_to_win32("GetProfileIntA", t))?;
    let default = arg_dword(cpu, mmu, 2).map_err(|t| trap_to_win32("GetProfileIntA", t))?;
    Ok(default)
}

// ----- Corpus-driven additions --------------------------------------

/// `DWORD GetCurrentProcessId(void)`. Synthetic 1 — codecs use
/// the PID as a poor man's hash seed or as a TLS-store key.
fn stub_get_current_process_id(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    Ok(1)
}

/// `void GetSystemTimeAsFileTime(LPFILETIME lpSystemTimeAsFileTime)`.
/// Writes a `FILETIME` (two `DWORD`s, little-endian: low then
/// high) representing 100-ns intervals since 1601-01-01 UTC.
/// We derive the value from `state.tick` so successive calls
/// return monotonically increasing timestamps without modelling
/// real wall-clock time. Most codecs use this for seeding RNGs
/// or for performance counters that just need monotonicity.
fn stub_get_system_time_as_file_time(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let p = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("GetSystemTimeAsFileTime", t))?;
    if p == 0 {
        return Ok(0);
    }
    // Synthesise a monotonically-increasing FILETIME by
    // multiplying the tick by 10000 (one tick ≈ 1 ms ≈ 10000
    // 100-ns units) and adding a base offset roughly equal to
    // 2024-01-01 in FILETIME units. Codecs that compare two
    // calls see strictly-increasing values.
    state.tick = state.tick.wrapping_add(1);
    let base: u64 = 133_482_240_000_000_000; // 2024-01-01 UTC in 100-ns ticks since 1601
    let ft = base.wrapping_add(u64::from(state.tick).wrapping_mul(10_000));
    let low = ft as u32;
    let high = (ft >> 32) as u32;
    mmu.store32(p, low)
        .map_err(|t| trap_to_win32("GetSystemTimeAsFileTime", t))?;
    mmu.store32(p.wrapping_add(4), high)
        .map_err(|t| trap_to_win32("GetSystemTimeAsFileTime", t))?;
    Ok(0)
}

/// `HANDLE GetCurrentThread(void)`. Pseudo-handle `-2` per the
/// Win32 ABI (current thread).
fn stub_get_current_thread(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    Ok(0xFFFF_FFFE)
}

/// `LONG InterlockedExchange(LONG volatile *Target, LONG Value)`.
/// Atomically writes `Value` to `*Target` and returns the
/// previous value. Single-threaded emulator → no atomicity
/// dance needed.
fn stub_interlocked_exchange(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let target = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("InterlockedExchange", t))?;
    let value = arg_dword(cpu, mmu, 1).map_err(|t| trap_to_win32("InterlockedExchange", t))?;
    let prev = mmu
        .load32(target)
        .map_err(|t| trap_to_win32("InterlockedExchange", t))?;
    mmu.store32(target, value)
        .map_err(|t| trap_to_win32("InterlockedExchange", t))?;
    Ok(prev)
}

/// `LONG InterlockedCompareExchange(LONG volatile *Destination,
/// LONG Exchange, LONG Comparand)`. Returns the original value
/// at `*Destination`; if it equalled `Comparand`, writes
/// `Exchange` over it.
fn stub_interlocked_compare_exchange(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let dest =
        arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("InterlockedCompareExchange", t))?;
    let exchange =
        arg_dword(cpu, mmu, 1).map_err(|t| trap_to_win32("InterlockedCompareExchange", t))?;
    let comparand =
        arg_dword(cpu, mmu, 2).map_err(|t| trap_to_win32("InterlockedCompareExchange", t))?;
    let prev = mmu
        .load32(dest)
        .map_err(|t| trap_to_win32("InterlockedCompareExchange", t))?;
    if prev == comparand {
        mmu.store32(dest, exchange)
            .map_err(|t| trap_to_win32("InterlockedCompareExchange", t))?;
    }
    Ok(prev)
}

/// `LONG UnhandledExceptionFilter(EXCEPTION_POINTERS *)`. Real
/// behaviour: pops the system "this program has stopped working"
/// dialog. We return `EXCEPTION_CONTINUE_SEARCH = 0` so the SEH
/// chain keeps unwinding; codecs that wrap their entire init in
/// `__try` / `__except(UnhandledExceptionFilter(GetExceptionInformation()))`
/// won't intercept anything.
fn stub_unhandled_exception_filter(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    Ok(0)
}

/// `UINT SetErrorMode(UINT uMode)`. We don't model the system
/// error dialog so any mode is fine. Returns the previous mode
/// (synthetic 0).
fn stub_set_error_mode(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let _new_mode = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("SetErrorMode", t))?;
    Ok(0)
}

/// `BOOL ResetEvent(HANDLE hEvent)`. Single-threaded emulator
/// has no real event objects; return 1 (success).
fn stub_reset_event(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let _h = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("ResetEvent", t))?;
    Ok(1)
}

/// `DWORD WaitForMultipleObjects(DWORD nCount, const HANDLE *lpHandles,
/// BOOL bWaitAll, DWORD dwMilliseconds)`. Always returns
/// `WAIT_OBJECT_0 = 0` — everything is "ready" in our
/// single-threaded sandbox.
fn stub_wait_for_multiple_objects(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let _ncount = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("WaitForMultipleObjects", t))?;
    let _phandles =
        arg_dword(cpu, mmu, 1).map_err(|t| trap_to_win32("WaitForMultipleObjects", t))?;
    let _waitall =
        arg_dword(cpu, mmu, 2).map_err(|t| trap_to_win32("WaitForMultipleObjects", t))?;
    let _ms = arg_dword(cpu, mmu, 3).map_err(|t| trap_to_win32("WaitForMultipleObjects", t))?;
    Ok(0)
}

/// `HANDLE CreateEventW(LPSECURITY_ATTRIBUTES, BOOL, BOOL, LPCWSTR)`.
/// Returns a synthetic non-NULL handle. Codecs use this to
/// coordinate between threads — we don't model threads, but the
/// codec just needs a non-zero handle to signal/wait on.
fn stub_create_event_w(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    state.tick = state.tick.wrapping_add(1);
    Ok(0xE000_0000u32.wrapping_add(state.tick))
}

/// `HANDLE CreateSemaphoreW(LPSECURITY_ATTRIBUTES, LONG, LONG, LPCWSTR)`.
/// Synthetic handle like [`stub_create_event_w`]; the codec
/// gets a non-NULL value, releases/waits are no-ops.
fn stub_create_semaphore_w(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    state.tick = state.tick.wrapping_add(1);
    Ok(0xE100_0000u32.wrapping_add(state.tick))
}

/// `void GetLocalTime(LPSYSTEMTIME)`. Writes a 16-byte
/// `SYSTEMTIME` (wYear, wMonth, wDayOfWeek, wDay, wHour,
/// wMinute, wSecond, wMilliseconds — each `WORD`). We hand
/// back a fixed canned value (2024-01-01 00:00:00.000) so
/// codec-output bitstreams that embed timestamps are
/// deterministic across runs.
fn stub_get_local_time(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let p = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("GetLocalTime", t))?;
    if p == 0 {
        return Ok(0);
    }
    // wYear=2024, wMonth=1, wDayOfWeek=1 (Mon), wDay=1,
    // wHour=0, wMinute=0, wSecond=0, wMilliseconds=0
    let fields: [u16; 8] = [2024, 1, 1, 1, 0, 0, 0, 0];
    for (i, w) in fields.iter().enumerate() {
        mmu.store16(p.wrapping_add(i as u32 * 2), *w)
            .map_err(|t| trap_to_win32("GetLocalTime", t))?;
    }
    Ok(0)
}

/// `HMODULE GetModuleHandleW(LPCWSTR lpModuleName)`. Wide-char
/// sibling of `GetModuleHandleA`. We don't yet resolve the
/// name; passing `NULL` returns the primary module base,
/// anything else returns 0 (codec falls back to a load attempt).
fn stub_get_module_handle_w(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let p = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("GetModuleHandleW", t))?;
    if p == 0 {
        return Ok(state.primary_module_base);
    }
    Ok(0)
}

/// `UINT GetPrivateProfileIntA(LPCSTR lpAppName, LPCSTR lpKeyName,
/// INT nDefault, LPCSTR lpFileName)`. We have no INI file to
/// consult; return the caller's default.
fn stub_get_private_profile_int_a(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let _app = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("GetPrivateProfileIntA", t))?;
    let _key = arg_dword(cpu, mmu, 1).map_err(|t| trap_to_win32("GetPrivateProfileIntA", t))?;
    let default = arg_dword(cpu, mmu, 2).map_err(|t| trap_to_win32("GetPrivateProfileIntA", t))?;
    let _file = arg_dword(cpu, mmu, 3).map_err(|t| trap_to_win32("GetPrivateProfileIntA", t))?;
    Ok(default)
}

/// `FARPROC WINAPI DelayLoadFailureHook(LPCSTR pszDllName,
/// LPCSTR pszProcName)`. VC++ delay-load glue. Real handler
/// returns 0 to signal "let the runtime raise an exception";
/// the codec sees a NULL pointer and either bails or falls
/// through to its own backup path. We do the same.
fn stub_delay_load_failure_hook(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let _dll = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("DelayLoadFailureHook", t))?;
    let _proc = arg_dword(cpu, mmu, 1).map_err(|t| trap_to_win32("DelayLoadFailureHook", t))?;
    Ok(0)
}

// ----- Corpus round 2 -----------------------------------------------

/// `BOOL GetVersionExW(LPOSVERSIONINFOW lpVersionInformation)`.
/// Fills the OSVERSIONINFO[EX]W struct with values that
/// announce "Windows 7" (major 6.1, build 7600). Codecs that
/// gate on minimum-Windows-version checks pass.
fn stub_get_version_ex_w(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let p = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("GetVersionExW", t))?;
    if p == 0 {
        return Ok(0);
    }
    // First DWORD = dwOSVersionInfoSize. Codecs set this to
    // either sizeof(OSVERSIONINFOW)=276 or
    // sizeof(OSVERSIONINFOEXW)=284 before the call; we don't
    // overwrite it. Then: dwMajorVersion, dwMinorVersion,
    // dwBuildNumber, dwPlatformId (VER_PLATFORM_WIN32_NT = 2),
    // then szCSDVersion (128 wide chars). If the caller passed
    // a too-small struct we still write the first 5 dwords —
    // it's the caller's responsibility to set dwOSVersionInfoSize
    // correctly.
    mmu.store32(p.wrapping_add(4), 6)
        .map_err(|t| trap_to_win32("GetVersionExW", t))?;
    mmu.store32(p.wrapping_add(8), 1)
        .map_err(|t| trap_to_win32("GetVersionExW", t))?;
    mmu.store32(p.wrapping_add(12), 7600)
        .map_err(|t| trap_to_win32("GetVersionExW", t))?;
    mmu.store32(p.wrapping_add(16), 2)
        .map_err(|t| trap_to_win32("GetVersionExW", t))?;
    // Zero szCSDVersion[128] = 256 bytes
    let zeros = [0u8; 256];
    mmu.write(p.wrapping_add(20), &zeros)
        .map_err(|t| trap_to_win32("GetVersionExW", t))?;
    Ok(1)
}

/// `DWORD SignalObjectAndWait(HANDLE, HANDLE, DWORD, BOOL)`.
/// Single-threaded sandbox → return `WAIT_OBJECT_0`.
fn stub_signal_object_and_wait(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    Ok(0)
}

/// `BOOL InitializeCriticalSectionAndSpinCount(LPCRITICAL_SECTION,
/// DWORD)`. Returns 1; we model critical sections as no-ops.
fn stub_init_cs_spin(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    Ok(1)
}

/// `BOOL IsDebuggerPresent(void)`. We say "no" — codecs that
/// gate anti-analysis behaviour on this take the non-debugger
/// branch. https://learn.microsoft.com/en-us/windows/win32/api/debugapi/nf-debugapi-isdebuggerpresent
fn stub_is_debugger_present(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    Ok(0)
}

/// `BOOL VirtualProtect(LPVOID lpAddress, SIZE_T dwSize,
/// DWORD flNewProtect, PDWORD lpflOldProtect)`. We don't
/// model per-page protection swaps — every page in our MMU
/// is R+W+X-as-needed once mapped. Just write a plausible old
/// protection into the out-param and return success.
fn stub_virtual_protect(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let _addr = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("VirtualProtect", t))?;
    let _size = arg_dword(cpu, mmu, 1).map_err(|t| trap_to_win32("VirtualProtect", t))?;
    let _new = arg_dword(cpu, mmu, 2).map_err(|t| trap_to_win32("VirtualProtect", t))?;
    let out = arg_dword(cpu, mmu, 3).map_err(|t| trap_to_win32("VirtualProtect", t))?;
    if out != 0 {
        // 0x40 = PAGE_EXECUTE_READWRITE — the most permissive
        // value, indicates the page was fully accessible.
        mmu.store32(out, 0x40)
            .map_err(|t| trap_to_win32("VirtualProtect", t))?;
    }
    Ok(1)
}

/// `LONG InterlockedExchangeAdd(LONG volatile *Addend, LONG Value)`.
/// Atomically adds `Value` to `*Addend` and returns the
/// previous value.
fn stub_interlocked_exchange_add(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let addend = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("InterlockedExchangeAdd", t))?;
    let value = arg_dword(cpu, mmu, 1).map_err(|t| trap_to_win32("InterlockedExchangeAdd", t))?;
    let prev = mmu
        .load32(addend)
        .map_err(|t| trap_to_win32("InterlockedExchangeAdd", t))?;
    let new = prev.wrapping_add(value);
    mmu.store32(addend, new)
        .map_err(|t| trap_to_win32("InterlockedExchangeAdd", t))?;
    Ok(prev)
}

/// `BOOL GetComputerNameA(LPSTR lpBuffer, LPDWORD nSize)`.
/// Writes a canned ASCII name and updates `*nSize`.
fn stub_get_computer_name_a(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let buf = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("GetComputerNameA", t))?;
    let n_ptr = arg_dword(cpu, mmu, 1).map_err(|t| trap_to_win32("GetComputerNameA", t))?;
    let name = b"UDEMULATOR\0";
    let mut cap = 0u32;
    if n_ptr != 0 {
        cap = mmu
            .load32(n_ptr)
            .map_err(|t| trap_to_win32("GetComputerNameA", t))?;
        mmu.store32(n_ptr, name.len() as u32 - 1)
            .map_err(|t| trap_to_win32("GetComputerNameA", t))?;
    }
    if buf != 0 && cap as usize >= name.len() {
        mmu.write(buf, name)
            .map_err(|t| trap_to_win32("GetComputerNameA", t))?;
    }
    Ok(1)
}

/// `DWORD GetEnvironmentVariableW(LPCWSTR lpName, LPWSTR
/// lpBuffer, DWORD nSize)`. We have no environment — return 0
/// and let the caller take its default branch.
fn stub_get_environment_variable_w(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    Ok(0)
}

/// `BOOL GetProcessAffinityMask(HANDLE hProcess,
/// PDWORD_PTR lpProcessAffinityMask,
/// PDWORD_PTR lpSystemAffinityMask)`. Reports a single-CPU
/// system (mask 1). Codecs use this to decide how many worker
/// threads to spawn.
fn stub_get_process_affinity_mask(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let _h = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("GetProcessAffinityMask", t))?;
    let proc_mask =
        arg_dword(cpu, mmu, 1).map_err(|t| trap_to_win32("GetProcessAffinityMask", t))?;
    let sys_mask =
        arg_dword(cpu, mmu, 2).map_err(|t| trap_to_win32("GetProcessAffinityMask", t))?;
    if proc_mask != 0 {
        mmu.store32(proc_mask, 1)
            .map_err(|t| trap_to_win32("GetProcessAffinityMask", t))?;
    }
    if sys_mask != 0 {
        mmu.store32(sys_mask, 1)
            .map_err(|t| trap_to_win32("GetProcessAffinityMask", t))?;
    }
    Ok(1)
}

/// `int GetThreadPriority(HANDLE hThread)`. Returns `THREAD_PRIORITY_NORMAL = 0`.
fn stub_get_thread_priority(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    Ok(0)
}

/// `DWORD_PTR SetThreadAffinityMask(HANDLE, DWORD_PTR)`.
/// Returns the previous affinity mask (synthetic 1).
fn stub_set_thread_affinity_mask(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    Ok(1)
}

/// `HMODULE LoadLibraryW(LPCWSTR lpLibFileName)`. We don't
/// load arbitrary host DLLs into the guest; return 0 (failure)
/// so the codec falls through to a backup path. Codecs that
/// require a successful LoadLibrary tend to be the optional-
/// codec-pack splitter shapes we don't try to fully drive.
fn stub_load_library_w(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    Ok(0)
}

/// `BOOL ReadFile(HANDLE, LPVOID, DWORD, LPDWORD, LPOVERLAPPED)`.
/// No filesystem mapped — report "read 0 bytes" success.
fn stub_read_file(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let _h = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("ReadFile", t))?;
    let _buf = arg_dword(cpu, mmu, 1).map_err(|t| trap_to_win32("ReadFile", t))?;
    let _n = arg_dword(cpu, mmu, 2).map_err(|t| trap_to_win32("ReadFile", t))?;
    let out = arg_dword(cpu, mmu, 3).map_err(|t| trap_to_win32("ReadFile", t))?;
    if out != 0 {
        mmu.store32(out, 0)
            .map_err(|t| trap_to_win32("ReadFile", t))?;
    }
    Ok(1)
}

// ============================================================
// Codec-corpus probe stubs
// ============================================================

/// Generic fail-soft stub: returns 0 (FALSE / NULL / "no").
fn stub_returns_zero(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    Ok(0)
}

/// Generic success stub: returns 1 (TRUE).
fn stub_returns_true(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    Ok(1)
}

/// Bound for the in-stub C-string scan loops below.
const CSTR_SCAN_CAP: u32 = 0x1_0000;

/// `LPSTR lstrcatA(LPSTR lpString1, LPCSTR lpString2)`. Appends
/// `lpString2` onto the NUL-terminated `lpString1`. Returns
/// `lpString1`.
fn stub_lstrcat_a(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let dst = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("lstrcatA", t))?;
    let src = arg_dword(cpu, mmu, 1).map_err(|t| trap_to_win32("lstrcatA", t))?;
    if dst == 0 {
        return Ok(0);
    }
    let mut end = dst;
    let mut scanned = 0u32;
    while scanned < CSTR_SCAN_CAP && mmu.load8(end).map_err(|t| trap_to_win32("lstrcatA", t))? != 0
    {
        end = end.wrapping_add(1);
        scanned += 1;
    }
    if src != 0 {
        let mut i = 0u32;
        loop {
            let b = mmu
                .load8(src.wrapping_add(i))
                .map_err(|t| trap_to_win32("lstrcatA", t))?;
            mmu.store8(end.wrapping_add(i), b)
                .map_err(|t| trap_to_win32("lstrcatA", t))?;
            if b == 0 || i >= CSTR_SCAN_CAP {
                break;
            }
            i += 1;
        }
    } else {
        mmu.store8(end, 0)
            .map_err(|t| trap_to_win32("lstrcatA", t))?;
    }
    Ok(dst)
}

/// `LPSTR lstrcpyA(LPSTR lpString1, LPCSTR lpString2)`. Copies
/// `lpString2` (incl. NUL) into `lpString1`. Returns
/// `lpString1`.
fn stub_lstrcpy_a(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let dst = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("lstrcpyA", t))?;
    let src = arg_dword(cpu, mmu, 1).map_err(|t| trap_to_win32("lstrcpyA", t))?;
    if dst == 0 {
        return Ok(0);
    }
    if src == 0 {
        mmu.store8(dst, 0)
            .map_err(|t| trap_to_win32("lstrcpyA", t))?;
        return Ok(dst);
    }
    let mut i = 0u32;
    loop {
        let b = mmu
            .load8(src.wrapping_add(i))
            .map_err(|t| trap_to_win32("lstrcpyA", t))?;
        mmu.store8(dst.wrapping_add(i), b)
            .map_err(|t| trap_to_win32("lstrcpyA", t))?;
        if b == 0 || i >= CSTR_SCAN_CAP {
            break;
        }
        i += 1;
    }
    Ok(dst)
}

/// Read a NUL-terminated ASCII string, lower-cased, for the
/// case-insensitive comparisons below.
fn read_cstr_lower(mmu: &Mmu, base: u32) -> Vec<u8> {
    let mut out = Vec::new();
    if base == 0 {
        return out;
    }
    for i in 0..CSTR_SCAN_CAP {
        match mmu.load8(base.wrapping_add(i)) {
            Ok(0) | Err(_) => break,
            Ok(b) => out.push(b.to_ascii_lowercase()),
        }
    }
    out
}

/// `int lstrcmpiA(LPCSTR lpString1, LPCSTR lpString2)`. Case-
/// insensitive ordinal compare; returns a negative / zero /
/// positive value like the C `strcmp` family.
fn stub_lstrcmpi_a(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let s1 = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("lstrcmpiA", t))?;
    let s2 = arg_dword(cpu, mmu, 1).map_err(|t| trap_to_win32("lstrcmpiA", t))?;
    let a = read_cstr_lower(mmu, s1);
    let b = read_cstr_lower(mmu, s2);
    Ok(match a.cmp(&b) {
        std::cmp::Ordering::Less => (-1i32) as u32,
        std::cmp::Ordering::Equal => 0,
        std::cmp::Ordering::Greater => 1,
    })
}

// CompareString return values — `winnls.h`.
const CSTR_LESS_THAN: u32 = 1;
const CSTR_EQUAL: u32 = 2;
const CSTR_GREATER_THAN: u32 = 3;

fn cmp_to_cstr(ord: std::cmp::Ordering) -> u32 {
    match ord {
        std::cmp::Ordering::Less => CSTR_LESS_THAN,
        std::cmp::Ordering::Equal => CSTR_EQUAL,
        std::cmp::Ordering::Greater => CSTR_GREATER_THAN,
    }
}

/// `int CompareStringA(LCID, DWORD dwCmpFlags, LPCSTR lpString1,
/// int cchCount1, LPCSTR lpString2, int cchCount2)`. Ordinal
/// compare of the two NUL-terminated strings (explicit lengths
/// ignored — the CRT collate path passes `-1`). Returns
/// `CSTR_LESS_THAN` / `CSTR_EQUAL` / `CSTR_GREATER_THAN`.
fn stub_compare_string_a(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let s1 = arg_dword(cpu, mmu, 2).map_err(|t| trap_to_win32("CompareStringA", t))?;
    let s2 = arg_dword(cpu, mmu, 4).map_err(|t| trap_to_win32("CompareStringA", t))?;
    let a = read_cstr_lower(mmu, s1);
    let b = read_cstr_lower(mmu, s2);
    Ok(cmp_to_cstr(a.cmp(&b)))
}

/// `int CompareStringW(...)`. Wide twin of [`stub_compare_string_a`].
fn stub_compare_string_w(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let s1 = arg_dword(cpu, mmu, 2).map_err(|t| trap_to_win32("CompareStringW", t))?;
    let s2 = arg_dword(cpu, mmu, 4).map_err(|t| trap_to_win32("CompareStringW", t))?;
    let read_w = |base: u32| -> Vec<u16> {
        let mut out = Vec::new();
        if base == 0 {
            return out;
        }
        for i in 0..CSTR_SCAN_CAP {
            match mmu.load16(base.wrapping_add(i * 2)) {
                Ok(0) | Err(_) => break,
                Ok(c) => out.push(c),
            }
        }
        out
    };
    let a = read_w(s1);
    let b = read_w(s2);
    Ok(cmp_to_cstr(a.cmp(&b)))
}

/// `void FatalAppExitA(UINT uAction, LPCSTR lpMessageText)`.
/// The CRT links this for its abort path; the sandbox never
/// reaches it on a healthy decode. No-op.
fn stub_fatal_app_exit_a(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    Ok(0)
}

/// `void GetSystemTime(LPSYSTEMTIME lpSystemTime)`. Fills the
/// 16-byte `SYSTEMTIME` with a fixed 2024-01-01T00:00:00 stamp.
fn stub_get_system_time(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let p = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("GetSystemTime", t))?;
    if p == 0 {
        return Ok(0);
    }
    // wYear, wMonth, wDayOfWeek, wDay, wHour, wMinute, wSecond,
    // wMilliseconds — 2024-01-01 was a Monday (wDayOfWeek = 1).
    let fields: [u16; 8] = [2024, 1, 1, 1, 0, 0, 0, 0];
    for (i, v) in fields.iter().enumerate() {
        mmu.store16(p.wrapping_add(i as u32 * 2), *v)
            .map_err(|t| trap_to_win32("GetSystemTime", t))?;
    }
    Ok(0)
}

/// `DWORD GetTimeZoneInformation(LPTIME_ZONE_INFORMATION lpTzi)`.
/// Zeroes the 172-byte struct and reports `TIME_ZONE_ID_UNKNOWN`
/// (0) — the sandbox runs in a fixed, DST-free UTC.
fn stub_get_time_zone_information(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let p = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("GetTimeZoneInformation", t))?;
    if p != 0 {
        mmu.write(p, &[0u8; 172])
            .map_err(|t| trap_to_win32("GetTimeZoneInformation", t))?;
    }
    Ok(0)
}

/// `HMODULE LoadLibraryExA(LPCSTR lpLibFileName, HANDLE hFile,
/// DWORD dwFlags)`. Resolves like `LoadLibraryA`, ignoring the
/// flags — a loaded module returns its image base, otherwise 0.
fn stub_load_library_ex_a(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let p = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("LoadLibraryExA", t))?;
    let name = read_cstr(mmu, p, 260)?.to_ascii_lowercase();
    Ok(state.modules.get(&name).copied().unwrap_or(0))
}

/// `BOOL WriteConsoleA(HANDLE, const VOID*, DWORD nNumberOfChars,
/// LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)`. Discards
/// the output, reports all characters written.
fn stub_write_console_a(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let n = arg_dword(cpu, mmu, 2).map_err(|t| trap_to_win32("WriteConsoleA", t))?;
    let written = arg_dword(cpu, mmu, 3).map_err(|t| trap_to_win32("WriteConsoleA", t))?;
    if written != 0 {
        mmu.store32(written, n)
            .map_err(|t| trap_to_win32("WriteConsoleA", t))?;
    }
    Ok(1)
}

/// `PVOID EncodePointer/DecodePointer(PVOID Ptr)`. Modelled as
/// the identity transform — a valid no-op implementation, since
/// `Decode(Encode(p)) == p` holds trivially.
fn stub_identity_pointer(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("EncodePointer/DecodePointer", t))
}

/// `DWORD GetModuleFileNameW(HMODULE, LPWSTR lpFilename,
/// DWORD nSize)`. Wide twin of `GetModuleFileNameA` — writes
/// `"oxideav-vfw"` as UTF-16, returns the character count.
fn stub_get_module_file_name_w(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let _h = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("GetModuleFileNameW", t))?;
    let dst = arg_dword(cpu, mmu, 1).map_err(|t| trap_to_win32("GetModuleFileNameW", t))?;
    let n_size = arg_dword(cpu, mmu, 2).map_err(|t| trap_to_win32("GetModuleFileNameW", t))?;
    if dst == 0 || n_size == 0 {
        return Ok(0);
    }
    let s = "oxideav-vfw";
    let mut written = 0u32;
    for (i, c) in s.chars().enumerate() {
        if (i as u32) >= n_size.saturating_sub(1) {
            break;
        }
        mmu.store16(dst + i as u32 * 2, c as u16)
            .map_err(|t| trap_to_win32("GetModuleFileNameW", t))?;
        written += 1;
    }
    let nul_off = written.min(n_size - 1);
    mmu.store16(dst + nul_off * 2, 0)
        .map_err(|t| trap_to_win32("GetModuleFileNameW", t))?;
    Ok(written)
}

/// `void GetStartupInfoW(LPSTARTUPINFOW lpStartupInfo)`. Wide
/// twin of `GetStartupInfoA` — `STARTUPINFOW` is also 68 bytes
/// on 32-bit; zero it and stamp `cb`.
fn stub_get_startup_info_w(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let p = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("GetStartupInfoW", t))?;
    if p == 0 {
        return Ok(0);
    }
    mmu.write(p, &[0u8; 68])
        .map_err(|t| trap_to_win32("GetStartupInfoW", t))?;
    mmu.store32(p, 68)
        .map_err(|t| trap_to_win32("GetStartupInfoW", t))?;
    Ok(0)
}

/// `LCID GetUserDefaultLCID(void)`. Reports `en-US` (0x0409).
fn stub_get_user_default_lcid(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    Ok(0x0409)
}

/// `DWORD GetLongPathNameA(LPCSTR lpszShortPath,
/// LPSTR lpszLongPath, DWORD cchBuffer)`. The sandbox draws no
/// short/long distinction — echo the input path back and report
/// its length.
fn stub_get_long_path_name_a(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let short = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("GetLongPathNameA", t))?;
    let long = arg_dword(cpu, mmu, 1).map_err(|t| trap_to_win32("GetLongPathNameA", t))?;
    let cch = arg_dword(cpu, mmu, 2).map_err(|t| trap_to_win32("GetLongPathNameA", t))?;
    let path = read_cstr(mmu, short, CSTR_SCAN_CAP)?;
    let len = path.len() as u32;
    // MSDN: when the buffer is too small (or NULL) the return
    // value is the required size, including the terminating NUL.
    if long == 0 || cch < len + 1 {
        return Ok(len + 1);
    }
    let mut bytes = path.into_bytes();
    bytes.push(0);
    mmu.write(long, &bytes)
        .map_err(|t| trap_to_win32("GetLongPathNameA", t))?;
    Ok(len)
}

/// `BOOL GetModuleHandleExA(DWORD dwFlags, LPCSTR lpModuleName,
/// HMODULE *phModule)`. Resolves like `GetModuleHandleA` and
/// writes the handle through `phModule`. Returns TRUE.
fn stub_get_module_handle_ex_a(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let name_p = arg_dword(cpu, mmu, 1).map_err(|t| trap_to_win32("GetModuleHandleExA", t))?;
    let out = arg_dword(cpu, mmu, 2).map_err(|t| trap_to_win32("GetModuleHandleExA", t))?;
    let handle = if name_p == 0 {
        state.primary_module_base
    } else {
        let name = read_cstr(mmu, name_p, 260)?.to_ascii_lowercase();
        state.modules.get(&name).copied().unwrap_or(0)
    };
    if out != 0 {
        mmu.store32(out, handle)
            .map_err(|t| trap_to_win32("GetModuleHandleExA", t))?;
    }
    Ok(1)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::emulator::mmu::Perm;
    use crate::emulator::regs::Reg32;
    use crate::win32::Registry;

    fn make_env() -> (Cpu, Mmu, Registry, HostState) {
        let mut mmu = Mmu::new();
        // Heap arena
        mmu.map(0x4000, 0x4000, Perm::R | Perm::W);
        // Stack
        mmu.map(0x9000, 0x1000, Perm::R | Perm::W);
        let mut cpu = Cpu::new();
        cpu.regs.set_esp(0x9F00);
        let mut registry = Registry::new();
        registry.register_kernel32();
        let state = HostState::new(0x4000, 0x8000);
        (cpu, mmu, registry, state)
    }

    fn push_args_and_call(
        cpu: &mut Cpu,
        mmu: &mut Mmu,
        registry: &Registry,
        state: &mut HostState,
        dll: &str,
        name: &str,
        args: &[u32],
    ) -> Result<(), crate::Error> {
        // Push args right-to-left.
        for a in args.iter().rev() {
            cpu.push32(mmu, *a)?;
        }
        // Push synthetic ret addr.
        cpu.push32(mmu, 0xDEAD_DEAD)?;
        cpu.regs.eip = registry.resolve(dll, name).expect("registered");
        crate::win32::dispatch_stub(cpu, mmu, registry, state)
    }

    #[test]
    fn registers_at_least_twelve_kernel32_stubs() {
        let mut r = Registry::new();
        let n = r.register_kernel32();
        assert!(n >= 12, "expected ≥ 12 round-1 stubs, got {n}");
    }

    #[test]
    fn get_process_heap_returns_canned_handle() {
        let (mut cpu, mut mmu, registry, mut state) = make_env();
        push_args_and_call(
            &mut cpu,
            &mut mmu,
            &registry,
            &mut state,
            "kernel32.dll",
            "GetProcessHeap",
            &[],
        )
        .unwrap();
        assert_eq!(cpu.regs.get32(Reg32::Eax), 0xDEAD_BEEF);
    }

    #[test]
    fn heap_alloc_then_heap_free_roundtrip() {
        let (mut cpu, mut mmu, registry, mut state) = make_env();
        push_args_and_call(
            &mut cpu,
            &mut mmu,
            &registry,
            &mut state,
            "kernel32.dll",
            "HeapAlloc",
            &[0xDEAD_BEEF, 0, 64],
        )
        .unwrap();
        let addr = cpu.regs.get32(Reg32::Eax);
        assert_ne!(addr, 0);
        assert!(state.heap.contains_key(&addr));

        push_args_and_call(
            &mut cpu,
            &mut mmu,
            &registry,
            &mut state,
            "kernel32.dll",
            "HeapFree",
            &[0xDEAD_BEEF, 0, addr],
        )
        .unwrap();
        assert_eq!(cpu.regs.get32(Reg32::Eax), 1);
        assert!(!state.heap.contains_key(&addr));
    }

    #[test]
    fn heap_alloc_zero_fills_when_flag_set() {
        let (mut cpu, mut mmu, registry, mut state) = make_env();
        push_args_and_call(
            &mut cpu,
            &mut mmu,
            &registry,
            &mut state,
            "kernel32.dll",
            "HeapAlloc",
            &[0xDEAD_BEEF, HEAP_ZERO_MEMORY, 16],
        )
        .unwrap();
        let addr = cpu.regs.get32(Reg32::Eax);
        for i in 0..16 {
            assert_eq!(mmu.load8(addr + i).unwrap(), 0);
        }
    }

    #[test]
    fn heap_free_invalid_pointer_errors() {
        let (mut cpu, mut mmu, registry, mut state) = make_env();
        let bad = 0xBAD_ADD00u32;
        let r = push_args_and_call(
            &mut cpu,
            &mut mmu,
            &registry,
            &mut state,
            "kernel32.dll",
            "HeapFree",
            &[0xDEAD_BEEF, 0, bad],
        );
        match r {
            Err(crate::Error::Win32(Win32Error::InvalidHeapBlock { addr, .. })) if addr == bad => {}
            other => panic!("expected InvalidHeapBlock, got {other:?}"),
        }
    }

    #[test]
    fn local_alloc_local_free() {
        let (mut cpu, mut mmu, registry, mut state) = make_env();
        push_args_and_call(
            &mut cpu,
            &mut mmu,
            &registry,
            &mut state,
            "kernel32.dll",
            "LocalAlloc",
            &[LMEM_ZEROINIT, 32],
        )
        .unwrap();
        let addr = cpu.regs.get32(Reg32::Eax);
        assert_ne!(addr, 0);
        push_args_and_call(
            &mut cpu,
            &mut mmu,
            &registry,
            &mut state,
            "kernel32.dll",
            "LocalFree",
            &[addr],
        )
        .unwrap();
        assert_eq!(cpu.regs.get32(Reg32::Eax), 0);
    }

    #[test]
    fn output_debug_string_a_logs() {
        let (mut cpu, mut mmu, registry, mut state) = make_env();
        // Lay out "hi\0" at 0x4000 (heap arena start, R+W).
        mmu.write(0x4000, b"hi\0").unwrap();
        // Bump the heap_cursor to skip those bytes for cleanliness.
        state.heap_cursor = 0x4010;
        push_args_and_call(
            &mut cpu,
            &mut mmu,
            &registry,
            &mut state,
            "kernel32.dll",
            "OutputDebugStringA",
            &[0x4000],
        )
        .unwrap();
        assert_eq!(state.debug_log.last().unwrap(), "hi");
    }

    #[test]
    fn get_tick_count_monotonic() {
        let (mut cpu, mut mmu, registry, mut state) = make_env();
        push_args_and_call(
            &mut cpu,
            &mut mmu,
            &registry,
            &mut state,
            "kernel32.dll",
            "GetTickCount",
            &[],
        )
        .unwrap();
        let t1 = cpu.regs.get32(Reg32::Eax);
        push_args_and_call(
            &mut cpu,
            &mut mmu,
            &registry,
            &mut state,
            "kernel32.dll",
            "GetTickCount",
            &[],
        )
        .unwrap();
        let t2 = cpu.regs.get32(Reg32::Eax);
        assert!(t2 > t1);
    }

    #[test]
    fn interlocked_increment_decrement_roundtrip() {
        let (mut cpu, mut mmu, registry, mut state) = make_env();
        // Place a u32 = 5 at 0x4000.
        mmu.store32(0x4000, 5).unwrap();
        state.heap_cursor = 0x4010;

        push_args_and_call(
            &mut cpu,
            &mut mmu,
            &registry,
            &mut state,
            "kernel32.dll",
            "InterlockedIncrement",
            &[0x4000],
        )
        .unwrap();
        assert_eq!(cpu.regs.get32(Reg32::Eax), 6);
        assert_eq!(mmu.load32(0x4000).unwrap(), 6);

        push_args_and_call(
            &mut cpu,
            &mut mmu,
            &registry,
            &mut state,
            "kernel32.dll",
            "InterlockedDecrement",
            &[0x4000],
        )
        .unwrap();
        assert_eq!(cpu.regs.get32(Reg32::Eax), 5);
    }

    #[test]
    fn load_library_a_returns_known_module_or_null() {
        let (mut cpu, mut mmu, registry, mut state) = make_env();
        state.modules.insert("kernel32.dll".into(), 0x10000);
        // Lay out "kernel32.dll\0"
        let s = b"kernel32.dll\0";
        mmu.write(0x4000, s).unwrap();
        state.heap_cursor = 0x4020;

        push_args_and_call(
            &mut cpu,
            &mut mmu,
            &registry,
            &mut state,
            "kernel32.dll",
            "LoadLibraryA",
            &[0x4000],
        )
        .unwrap();
        assert_eq!(cpu.regs.get32(Reg32::Eax), 0x10000);

        // Unknown module → 0
        let s = b"unknown.dll\0";
        mmu.write(0x4040, s).unwrap();
        push_args_and_call(
            &mut cpu,
            &mut mmu,
            &registry,
            &mut state,
            "kernel32.dll",
            "LoadLibraryA",
            &[0x4040],
        )
        .unwrap();
        assert_eq!(cpu.regs.get32(Reg32::Eax), 0);
    }

    #[test]
    fn heap_realloc_preserves_old_bytes() {
        let (mut cpu, mut mmu, registry, mut state) = make_env();
        push_args_and_call(
            &mut cpu,
            &mut mmu,
            &registry,
            &mut state,
            "kernel32.dll",
            "HeapAlloc",
            &[0xDEAD_BEEF, 0, 8],
        )
        .unwrap();
        let addr = cpu.regs.get32(Reg32::Eax);
        for i in 0..8u32 {
            mmu.store8(addr + i, (i + 1) as u8).unwrap();
            // Mirror in heap-state buffer too.
            state.heap.get_mut(&addr).unwrap()[i as usize] = (i + 1) as u8;
        }
        push_args_and_call(
            &mut cpu,
            &mut mmu,
            &registry,
            &mut state,
            "kernel32.dll",
            "HeapReAlloc",
            &[0xDEAD_BEEF, 0, addr, 16],
        )
        .unwrap();
        let new_addr = cpu.regs.get32(Reg32::Eax);
        for i in 0..8u32 {
            assert_eq!(mmu.load8(new_addr + i).unwrap(), (i + 1) as u8);
        }
    }

    /// Round 12 — `FindResourceA` should walk a synthetic
    /// 3-level resource directory and return the data-entry VA.
    #[test]
    fn find_resource_a_walks_synthetic_resource_directory() {
        let (mut cpu, mut mmu, registry, mut state) = make_env();
        // Build a tiny resource directory at 0x10000:
        //   level 1 (type=2 → level 2)
        //   level 2 (id=112 → level 3)
        //   level 3 (lang=1033 → data entry @ 0x10080)
        // …all relative to 0x10000.
        // Map a region for it.
        mmu.map(0x10000, 0x1000, Perm::R | Perm::W);
        let rsrc_base = 0x10000u32;

        // Level-1 dir at 0x10000 (16-byte hdr + 1 entry @ 0x10010).
        mmu.store32(rsrc_base, 0).unwrap(); // characteristics
        mmu.store32(rsrc_base + 4, 0).unwrap(); // timestamp
        mmu.store32(rsrc_base + 8, 0).unwrap(); // versions (2x u16)
        mmu.store16(rsrc_base + 12, 0).unwrap(); // num named
        mmu.store16(rsrc_base + 14, 1).unwrap(); // num id
        mmu.store32(rsrc_base + 16, 2).unwrap(); // entry: id = 2
        mmu.store32(rsrc_base + 20, 0x8000_0020).unwrap(); // offset = 0x20, is_dir=1

        // Level-2 dir at 0x10020 (= rsrc_base + 0x20). Same shape.
        mmu.store16(rsrc_base + 0x20 + 12, 0).unwrap();
        mmu.store16(rsrc_base + 0x20 + 14, 1).unwrap();
        mmu.store32(rsrc_base + 0x20 + 16, 112).unwrap(); // id = 112
        mmu.store32(rsrc_base + 0x20 + 20, 0x8000_0040).unwrap(); // → 0x40, is_dir=1

        // Level-3 dir at 0x10040.
        mmu.store16(rsrc_base + 0x40 + 12, 0).unwrap();
        mmu.store16(rsrc_base + 0x40 + 14, 1).unwrap();
        mmu.store32(rsrc_base + 0x40 + 16, 1033).unwrap(); // lang
        mmu.store32(rsrc_base + 0x40 + 20, 0x60).unwrap(); // → 0x60, is_data

        // Data entry at 0x10060: rva, size, codepage, reserved.
        mmu.store32(rsrc_base + 0x60, 0xC000).unwrap();
        mmu.store32(rsrc_base + 0x60 + 4, 0x1234).unwrap();

        // Register a fake module @ 0x10000000 with rsrc at our test base.
        let h_module = 0x10000000u32;
        state.modules.insert("synth.dll".into(), h_module);
        state.module_resource_dirs.insert(h_module, rsrc_base);

        push_args_and_call(
            &mut cpu,
            &mut mmu,
            &registry,
            &mut state,
            "kernel32.dll",
            "FindResourceA",
            &[h_module, 112, 2],
        )
        .unwrap();
        // Should land on the data-entry VA.
        assert_eq!(cpu.regs.get32(Reg32::Eax), rsrc_base + 0x60);
    }
}