ud-emulator 0.2.0

Pure-Rust 32-bit x86 emulator + PE runtime loader + Win32 host shims. Mirrors oxideav-vfw; intended to grow into the dynamic-analysis backend that informs decompilation (indirect-target recovery, constant-data discovery).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
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
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
//! `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/synchapi/nf-synchapi-tryentercriticalsection
    registry.register(
        "kernel32.dll",
        "TryEnterCriticalSection",
        stub_try_enter_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/processthreadsapi/nf-processthreadsapi-exitthread
    registry.register("kernel32.dll", "ExitThread", stub_exit_thread as StubFn, 1);
    // https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-switchtothread
    registry.register(
        "kernel32.dll",
        "SwitchToThread",
        stub_switch_to_thread as StubFn,
        0,
    );
    // 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);
    // https://learn.microsoft.com/en-us/windows/win32/api/namedpipeapi/nf-namedpipeapi-createpipe
    registry.register("kernel32.dll", "CreatePipe", stub_create_pipe as StubFn, 4);
    // https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-createnamedpipea
    registry.register(
        "kernel32.dll",
        "CreateNamedPipeA",
        stub_create_named_pipe_a as StubFn,
        8,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/namedpipeapi/nf-namedpipeapi-connectnamedpipe
    registry.register(
        "kernel32.dll",
        "ConnectNamedPipe",
        stub_connect_named_pipe as StubFn,
        2,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/namedpipeapi/nf-namedpipeapi-disconnectnamedpipe
    registry.register(
        "kernel32.dll",
        "DisconnectNamedPipe",
        stub_disconnect_named_pipe as StubFn,
        1,
    );

    // ---- 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,
    );

    // ---- Install-monitor additions (QuickTime 7.7.9 trail) --------
    //
    // The file-IO / directory / temp-path stubs below route through
    // [`crate::context::VirtualFs`] when one is attached, so an
    // installer's writes land in the monitor report. Without a VFS
    // attached they fall back to conservative success values.
    //
    // https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-gettemppatha
    registry.register(
        "kernel32.dll",
        "GetTempPathA",
        stub_get_temp_path_a as StubFn,
        2,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-gettempfilenamea
    registry.register(
        "kernel32.dll",
        "GetTempFileNameA",
        stub_get_temp_file_name_a as StubFn,
        4,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilea
    registry.register(
        "kernel32.dll",
        "CreateFileA",
        stub_create_file_a as StubFn,
        7,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createdirectorya
    registry.register(
        "kernel32.dll",
        "CreateDirectoryA",
        stub_create_directory_a as StubFn,
        2,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-deletefilea
    registry.register(
        "kernel32.dll",
        "DeleteFileA",
        stub_delete_file_a as StubFn,
        1,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getfileattributesa
    registry.register(
        "kernel32.dll",
        "GetFileAttributesA",
        stub_get_file_attributes_a as StubFn,
        1,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getfilesize
    registry.register(
        "kernel32.dll",
        "GetFileSize",
        stub_get_file_size as StubFn,
        2,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-dosdatetimetofiletime
    registry.register(
        "kernel32.dll",
        "DosDateTimeToFileTime",
        stub_dos_date_time_to_file_time as StubFn,
        3,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-createmutexa
    registry.register(
        "kernel32.dll",
        "CreateMutexA",
        stub_create_mutex_a as StubFn,
        3,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-releasemutex
    registry.register(
        "kernel32.dll",
        "ReleaseMutex",
        stub_release_mutex as StubFn,
        1,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createprocessa
    registry.register(
        "kernel32.dll",
        "CreateProcessA",
        stub_create_process_a as StubFn,
        10,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-getexitcodeprocess
    registry.register(
        "kernel32.dll",
        "GetExitCodeProcess",
        stub_get_exit_code_process as StubFn,
        2,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/wincon/nf-wincon-getconsolecp
    registry.register(
        "kernel32.dll",
        "GetConsoleCP",
        stub_get_console_cp as StubFn,
        0,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/wincon/nf-wincon-getconsoleoutputcp
    registry.register(
        "kernel32.dll",
        "GetConsoleOutputCP",
        stub_get_console_cp as StubFn,
        0,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/consoleapi/nf-consoleapi-getconsolemode
    registry.register(
        "kernel32.dll",
        "GetConsoleMode",
        stub_get_console_mode as StubFn,
        2,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/timezoneapi/nf-timezoneapi-localfiletimetofiletime
    registry.register(
        "kernel32.dll",
        "LocalFileTimeToFileTime",
        stub_local_file_time_to_file_time as StubFn,
        2,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-removedirectorya
    registry.register(
        "kernel32.dll",
        "RemoveDirectoryA",
        stub_remove_directory_a as StubFn,
        1,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-setendoffile
    registry.register(
        "kernel32.dll",
        "SetEndOfFile",
        stub_returns_true as StubFn,
        1,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-setfileattributesa
    registry.register(
        "kernel32.dll",
        "SetFileAttributesA",
        stub_returns_true as StubFn,
        2,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-setfiletime
    registry.register(
        "kernel32.dll",
        "SetFileTime",
        stub_returns_true as StubFn,
        4,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-setprocessworkingsetsize
    registry.register(
        "kernel32.dll",
        "SetProcessWorkingSetSize",
        stub_returns_true as StubFn,
        3,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/consoleapi/nf-consoleapi-writeconsolew
    registry.register(
        "kernel32.dll",
        "WriteConsoleW",
        stub_write_console_w as StubFn,
        5,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/handleapi/nf-handleapi-duplicatehandle
    registry.register(
        "kernel32.dll",
        "DuplicateHandle",
        stub_duplicate_handle as StubFn,
        7,
    );
    // https://learn.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-openeventa
    registry.register("kernel32.dll", "OpenEventA", stub_open_event_a as StubFn, 3);
    registry.register("kernel32.dll", "OpenEventW", stub_open_event_w as StubFn, 3);
    // https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-openprocess
    registry.register(
        "kernel32.dll",
        "OpenProcess",
        stub_open_process 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)`.
///
/// Reverse-resolves `hModule` through `state.modules` (the
/// system-DLL pre-registration in `Sandbox::new` plus the
/// codec's own load entry from `Sandbox::load`) and looks the
/// name up in the stub registry under that DLL. Returns the
/// thunk address on hit, NULL otherwise. Lookup-by-ordinal
/// (low-bit-set name pointer) is not supported.
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);
    }
    let name = read_cstr(mmu, name_p, 260)?;
    // Reverse-map handle -> dll name.
    let dll = state
        .modules
        .iter()
        .find(|(_, &base)| base == h)
        .map(|(n, _)| n.clone());
    let Some(dll) = dll else {
        return Ok(0);
    };
    Ok(registry.resolve(&dll, &name).unwrap_or(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);
    state.cur_process_mut().exit_code = 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)`. Maps known handle kinds
/// to their canonical types: VFS-owned handles report
/// `FILE_TYPE_DISK = 1` so the CRT's `_initstdio` accepts
/// them as valid stdio targets; standard handles report
/// `FILE_TYPE_CHAR = 2` (console-style); everything else
/// reports `FILE_TYPE_UNKNOWN = 0`.
fn stub_get_file_type(
    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("GetFileType", t))?;
    // STD_INPUT_HANDLE / STD_OUTPUT_HANDLE / STD_ERROR_HANDLE
    // (negative DWORDs).
    if matches!(h, 0xFFFF_FFF6 | 0xFFFF_FFF5 | 0xFFFF_FFF4) {
        return Ok(2); // FILE_TYPE_CHAR
    }
    if let Some(vfs) = state.context.vfs.as_ref() {
        if vfs.owns(h) {
            return Ok(1); // FILE_TYPE_DISK
        }
    }
    Ok(0)
}

/// `DWORD GetLastError(void)` — reads the per-thread
/// LastError. Mirrored through `fs:[0x34]` on the active
/// thread's TIB so guest code that reads the TIB directly
/// observes the same value (Phase 6).
fn stub_get_last_error(
    _cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let tib = state.cur_thread().tib_addr;
    if tib != 0 {
        if let Ok(v) = mmu.load32(tib + 0x34) {
            return Ok(v);
        }
    }
    Ok(state.last_error)
}

/// `void SetLastError(DWORD dwErrCode)` — writes the per-thread
/// LastError. Mirrored through `fs:[0x34]` on the active
/// thread's TIB.
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;
    let tib = state.cur_thread().tib_addr;
    if tib != 0 {
        let _ = mmu.store32(tib + 0x34, 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,
        PAGE_EXECUTE => Perm::R | Perm::X,
        _ => Perm::R | Perm::W,
    }
}

/// Inverse of [`page_protect_to_perm`] for the `lpflOldProtect`
/// out-parameter of `VirtualProtect`.
fn perm_to_page_protect(perm: Perm) -> u32 {
    let r = perm.contains(Perm::R);
    let w = perm.contains(Perm::W);
    let x = perm.contains(Perm::X);
    match (r, w, x) {
        (false, false, false) => PAGE_NOACCESS,
        (true, false, false) => PAGE_READONLY,
        (true, true, false) => PAGE_READWRITE,
        (true, false, true) => PAGE_EXECUTE_READ,
        (true, true, true) => PAGE_EXECUTE_READWRITE,
        // No-read combos are rare under Win32 protection
        // taxonomy; report the closest match.
        (false, _, true) => PAGE_EXECUTE,
        (false, true, false) => PAGE_READWRITE,
    }
}

/// 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)`. When the handle was minted by the
/// virtual filesystem, the bytes flow through it so the monitor
/// can report what was written. Unknown handles fall through to
/// fail-soft "wrote nothing".
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))?;
    // Pipe write end: append to the shared buffer + wake any
    // thread blocked on the paired read end.
    if let Some(crate::sched::WaitObject::Pipe {
        pipe_id,
        is_read_end: false,
    }) = state.scheduler.objects.get(&h).cloned()
    {
        let mut buf = vec![0u8; n as usize];
        if lp_buf != 0 {
            for (i, b) in buf.iter_mut().enumerate() {
                *b = mmu
                    .load8(lp_buf + i as u32)
                    .map_err(|t| trap_to_win32("WriteFile", t))?;
            }
        }
        if let Some(p) = state.scheduler.pipes.get_mut(&pipe_id) {
            p.bytes.extend(buf.iter());
        }
        // Wake any thread blocked on the read end of this pipe.
        let read_handles: Vec<u32> = state
            .scheduler
            .objects
            .iter()
            .filter_map(|(handle, obj)| match obj {
                crate::sched::WaitObject::Pipe {
                    pipe_id: pid,
                    is_read_end: true,
                } if *pid == pipe_id => Some(*handle),
                _ => None,
            })
            .collect();
        for rh in read_handles {
            for tid in crate::sched::waiters_on(&state.threads, rh) {
                if let Some(t) = state.threads.get_mut(&tid) {
                    t.status = crate::sched::ThreadStatus::Ready;
                    t.wait = None;
                }
            }
        }
        if lp_written != 0 {
            mmu.store32(lp_written, n)
                .map_err(|t| trap_to_win32("WriteFile", t))?;
        }
        return Ok(1);
    }
    if let Some(vfs) = state.context.vfs.as_mut() {
        if vfs.owns(h) && lp_buf != 0 {
            let mut buf = vec![0u8; n as usize];
            for (i, b) in buf.iter_mut().enumerate() {
                *b = mmu
                    .load8(lp_buf + i as u32)
                    .map_err(|t| trap_to_win32("WriteFile", t))?;
            }
            let written = vfs.write_handle(h, &buf).unwrap_or(0) as u32;
            if lp_written != 0 {
                mmu.store32(lp_written, written)
                    .map_err(|t| trap_to_win32("WriteFile", t))?;
            }
            return Ok(1);
        }
    }
    if lp_written != 0 {
        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)`. Closes the corresponding VFS or
/// registry handle when one is owned by [`crate::context`]; falls
/// through to a no-op success otherwise (the historical
/// behaviour, used by the wide set of synthetic handles minted
/// elsewhere in the kernel32 stub family).
fn stub_close_handle(
    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("CloseHandle", t))?;
    if let Some(vfs) = state.context.vfs.as_mut() {
        if vfs.owns(h) {
            vfs.close(h);
            return Ok(1);
        }
    }
    if let Some(reg) = state.context.registry.as_mut() {
        if reg.owns(h) {
            reg.close_key(h);
            return Ok(1);
        }
    }
    // Pipe end: bump the buffer's closed-ends counter and
    // wake any reader blocked on the matching end (so they
    // can observe EOF). Drop the WaitObject entry once the
    // pipe is fully closed.
    if let Some(crate::sched::WaitObject::Pipe {
        pipe_id,
        is_read_end,
    }) = state.scheduler.objects.get(&h).cloned()
    {
        if let Some(p) = state.scheduler.pipes.get_mut(&pipe_id) {
            p.closed_ends = p.closed_ends.saturating_add(1);
        }
        // Wake parked readers if the writer just closed.
        if !is_read_end {
            let read_handles: Vec<u32> = state
                .scheduler
                .objects
                .iter()
                .filter_map(|(handle, obj)| match obj {
                    crate::sched::WaitObject::Pipe {
                        pipe_id: pid,
                        is_read_end: true,
                    } if *pid == pipe_id => Some(*handle),
                    _ => None,
                })
                .collect();
            for rh in read_handles {
                for tid in crate::sched::waiters_on(&state.threads, rh) {
                    if let Some(t) = state.threads.get_mut(&tid) {
                        t.status = crate::sched::ThreadStatus::Ready;
                        t.wait = None;
                    }
                }
            }
        }
        state.scheduler.objects.remove(&h);
        return Ok(1);
    }
    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(LPSECURITY_ATTRIBUTES,
/// LONG lInitialCount, LONG lMaximumCount, LPCSTR lpName)`.
/// Mints a Semaphore WaitObject seeded with the supplied
/// initial count and maximum.
fn stub_create_semaphore_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("CreateSemaphoreA", t))?;
    let init = arg_dword(cpu, mmu, 1).map_err(|t| trap_to_win32("CreateSemaphoreA", t))?;
    let max = arg_dword(cpu, mmu, 2).map_err(|t| trap_to_win32("CreateSemaphoreA", t))?;
    let _name = arg_dword(cpu, mmu, 3).map_err(|t| trap_to_win32("CreateSemaphoreA", t))?;
    Ok(state
        .scheduler
        .insert_object(crate::sched::WaitObject::Semaphore { count: init, max }))
}

/// `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 lpcs)`. Takes
/// ownership of the implicit Mutex-shaped object keyed by
/// `lpcs`'s guest address; lazily allocates the object on first
/// touch via [`crate::sched::Scheduler::critical_section_handle`].
/// If the section is already owned by another thread the caller
/// yields a `Wait` on the section's handle and the scheduler
/// blocks it until the owner releases.
fn stub_enter_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("EnterCriticalSection", t))?;
    if p == 0 {
        return Ok(0);
    }
    let cur_tid = state.active_tid;
    let h = state.scheduler.critical_section_handle(p);
    let take_immediately = matches!(
        state.scheduler.objects.get(&h),
        Some(crate::sched::WaitObject::CriticalSection { owner: None, .. })
    ) || matches!(
        state.scheduler.objects.get(&h),
        Some(crate::sched::WaitObject::CriticalSection { owner: Some(o), .. }) if *o == cur_tid
    );
    if take_immediately {
        if let Some(crate::sched::WaitObject::CriticalSection {
            owner, recursion, ..
        }) = state.scheduler.objects.get_mut(&h)
        {
            if owner.is_some() {
                *recursion += 1;
            } else {
                *owner = Some(cur_tid);
                *recursion = 1;
            }
        }
        return Ok(0);
    }
    // Contended: yield until the section is released.
    state.yield_requested = Some(crate::sched::YieldRequest::Wait(
        crate::sched::WaitCondition::Object {
            handle: h,
            timeout_after: None,
        },
    ));
    Ok(0)
}

/// `void LeaveCriticalSection(LPCRITICAL_SECTION lpcs)`.
/// Decrements the section's recursion count; when it reaches
/// zero, clears the owner and wakes the first waiter (which
/// becomes the new owner per
/// [`crate::sched::consume_signal_if_auto_reset`]).
fn stub_leave_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("LeaveCriticalSection", t))?;
    if p == 0 {
        return Ok(0);
    }
    // Only act if the section has been touched at least once.
    let Some(&h) = state.scheduler.critical_sections.get(&p) else {
        return Ok(0);
    };
    let cur_tid = state.active_tid;
    let release_now =
        if let Some(crate::sched::WaitObject::CriticalSection {
            owner, recursion, ..
        }) = state.scheduler.objects.get_mut(&h)
        {
            if *owner != Some(cur_tid) {
                return Ok(0);
            }
            *recursion = recursion.saturating_sub(1);
            if *recursion == 0 {
                *owner = None;
                true
            } else {
                false
            }
        } else {
            false
        };
    if release_now {
        let waiters = crate::sched::waiters_on(&state.threads, h);
        if let Some(&tid) = waiters.first() {
            wake_thread(state, tid, h);
        }
    }
    Ok(0)
}

/// `BOOL TryEnterCriticalSection(LPCRITICAL_SECTION lpcs)`.
/// Same as `EnterCriticalSection` but returns FALSE
/// immediately instead of blocking when the section is owned
/// by another thread.
fn stub_try_enter_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("TryEnterCriticalSection", t))?;
    if p == 0 {
        return Ok(0);
    }
    let cur_tid = state.active_tid;
    let h = state.scheduler.critical_section_handle(p);
    if let Some(crate::sched::WaitObject::CriticalSection {
        owner, recursion, ..
    }) = state.scheduler.objects.get_mut(&h)
    {
        match *owner {
            None => {
                *owner = Some(cur_tid);
                *recursion = 1;
                return Ok(1);
            }
            Some(o) if o == cur_tid => {
                *recursion += 1;
                return Ok(1);
            }
            _ => return Ok(0),
        }
    }
    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
}

/// Look up an entry by string name in a PE resource directory.
/// The PE format stores named entries first (sorted by name);
/// each entry's `Name` field has the high bit set and the low
/// 31 bits are an offset (relative to `rsrc_base`) of an
/// `IMAGE_RESOURCE_DIR_STRING_U`: WORD length + UTF-16 chars
/// (no NUL terminator).
fn rsrc_dir_lookup_name(
    mmu: &Mmu,
    rsrc_base: u32,
    dir_va: u32,
    target: &str,
) -> Option<(u32, bool)> {
    let n_named = mmu.load16(dir_va + 12).ok()? as u32;
    let entries_va = dir_va + 16;
    let target_upper: Vec<u16> = target.to_ascii_uppercase().encode_utf16().collect();
    for i in 0..n_named {
        let e_va = entries_va + i * 8;
        let name = mmu.load32(e_va).ok()?;
        if (name & 0x8000_0000) == 0 {
            continue;
        }
        let str_va = rsrc_base + (name & 0x7FFF_FFFF);
        let len = mmu.load16(str_va).ok()? as u32;
        if len as usize != target_upper.len() {
            continue;
        }
        let mut matches = true;
        for j in 0..len {
            let w = mmu.load16(str_va + 2 + j * 2).ok()?;
            let upper = (w as u8).to_ascii_uppercase() as u16; // narrow upper-case for ASCII-only names
            if upper != target_upper[j as usize] {
                matches = false;
                break;
            }
        }
        if matches {
            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, otherwise as pointers to a NUL-terminated ASCII
/// string (`FindResourceA` contract; the function up-converts
/// to UTF-16 to match the on-disk format).
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)?;
    // 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) = if lp_type & 0xFFFF_0000 != 0 {
        let name = read_cstr(mmu, lp_type, 260).ok()?;
        rsrc_dir_lookup_name(mmu, rsrc_base, rsrc_base, &name)?
    } else {
        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) = if lp_name & 0xFFFF_0000 != 0 {
        let name = read_cstr(mmu, lp_name, 260).ok()?;
        rsrc_dir_lookup_name(mmu, rsrc_base, rsrc_base + off_type, &name)?
    } else {
        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)`. Returns the scheduler's
/// active TID. The bootstrap thread is `1`; subsequent
/// `CreateThread` calls mint monotonically increasing values.
fn stub_get_current_thread_id(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    Ok(state.active_tid)
}

/// `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 hSemaphore, LONG lReleaseCount,
/// LPLONG lpPreviousCount)`. Adds `lReleaseCount` to the
/// semaphore's count (clamped against `max`), writes the prior
/// count through `lpPreviousCount`, and wakes up to
/// `lReleaseCount` waiters in TID order.
fn stub_release_semaphore(
    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("ReleaseSemaphore", t))?;
    let release = arg_dword(cpu, mmu, 1).map_err(|t| trap_to_win32("ReleaseSemaphore", t))?;
    let lp_prev = arg_dword(cpu, mmu, 2).map_err(|t| trap_to_win32("ReleaseSemaphore", t))?;
    let Some(crate::sched::WaitObject::Semaphore { count, max }) =
        state.scheduler.objects.get_mut(&h)
    else {
        return Ok(0);
    };
    let prev = *count;
    *count = count.saturating_add(release).min(*max);
    if lp_prev != 0 {
        mmu.store32(lp_prev, prev)
            .map_err(|t| trap_to_win32("ReleaseSemaphore", t))?;
    }
    // Wake up to `release` waiters.
    let waiters = crate::sched::waiters_on(&state.threads, h);
    for tid in waiters.into_iter().take(release as usize) {
        wake_thread(state, tid, h);
    }
    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 ms)`. Asks the scheduler to suspend the
/// current thread until `INSTRUCTIONS_PER_MS * ms` more guest
/// instructions have elapsed. With a single thread, the run
/// loop fast-forwards the global clock to the wake target so
/// `Sleep` returns roughly immediately in wall-clock time but
/// the `tick` / `GetTickCount` chain advances correctly.
fn stub_sleep(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let ms = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("Sleep", t))?;
    let now = state.scheduler.instructions_global;
    let resume_after_instructions =
        now.saturating_add(u64::from(ms).saturating_mul(crate::sched::INSTRUCTIONS_PER_MS));
    state.yield_requested = Some(crate::sched::YieldRequest::Wait(
        crate::sched::WaitCondition::Sleep {
            resume_after_instructions,
        },
    ));
    // Mirror to the legacy tick counter so `GetTickCount` from
    // inside the same Sleep run sees a plausible advance.
    state.tick = state.tick.wrapping_add(ms);
    Ok(0)
}

/// `BOOL TerminateProcess(HANDLE hProcess, UINT uExitCode)`.
/// Mirror `ExitProcess` — set the exit-requested flag so the run
/// loop returns cleanly.
///
/// `STATUS_STACK_BUFFER_OVERRUN` (0xC0000409) is the exit code
/// MSVC's `__report_gsfailure` passes when the GS cookie
/// check fires. Emulators routinely false-positive this
/// check (small differences in FPU state, segment register
/// shadow values, etc. perturb a stack-spill that ends up
/// adjacent to the saved cookie), so when an installer-class
/// binary tries to abort with this specific code we log it
/// to `debug_log` and let the process keep running instead
/// of unwinding the entire monitor session.
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))?;
    if code == 0xC000_0409 {
        state.debug_log.push(format!(
            "TerminateProcess(STATUS_STACK_BUFFER_OVERRUN) — \
             treating as spurious GS check, continuing"
        ));
        return Ok(1);
    }
    // `TerminateProcess(GetCurrentProcess())` / negative -1 →
    // act on the active process. Otherwise look up the target
    // Process WaitObject.
    let target_pid = if h == 0xFFFF_FFFF {
        state.active_pid
    } else if let Some(crate::sched::WaitObject::Process { pid }) = state.scheduler.objects.get(&h)
    {
        *pid
    } else {
        state.active_pid
    };
    if let Some(p) = state.processes.get_mut(&target_pid) {
        p.exit_code = Some(code);
    }
    // Wake every waiter whose wait references the Process
    // WaitObject for this PID.
    let process_handles: Vec<u32> = state
        .scheduler
        .objects
        .iter()
        .filter_map(|(handle, obj)| match obj {
            crate::sched::WaitObject::Process { pid } if *pid == target_pid => Some(*handle),
            _ => None,
        })
        .collect();
    for h in process_handles {
        for tid in crate::sched::waiters_on(&state.threads, h) {
            if let Some(t) = state.threads.get_mut(&tid) {
                t.status = crate::sched::ThreadStatus::Ready;
                t.wait = None;
            }
        }
    }
    if target_pid == state.active_pid {
        state.exit_requested = Some(code);
    }
    Ok(1)
}

/// `DWORD TlsAlloc(void)`. Mints a fresh process-scoped TLS slot
/// index. The slot's value is stored per-thread (see
/// [`ThreadState::tls_slots`]); calling threads start with the
/// slot reading back zero.
fn stub_tls_alloc(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let proc_ = state.cur_process_mut();
    let slot = proc_.next_tls_slot;
    proc_.next_tls_slot = proc_.next_tls_slot.wrapping_add(1);
    Ok(slot)
}

/// `BOOL TlsFree(DWORD)`. Removes the slot from every thread's
/// TLS map (releasing whatever value was stored). Returns TRUE
/// even when the slot was never assigned in any thread.
fn stub_tls_free(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let idx = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("TlsFree", t))?;
    for t in state.threads.values_mut() {
        t.tls_slots.remove(&idx);
    }
    Ok(1)
}

/// `LPVOID TlsGetValue(DWORD)`. Reads the current thread's TLS
/// slot. Slots that were never assigned read back zero — matching
/// the MSDN "indeterminate, but typically NULL" contract.
fn stub_tls_get_value(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let idx = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("TlsGetValue", t))?;
    Ok(state.cur_thread().tls_slots.get(&idx).copied().unwrap_or(0))
}

/// `BOOL TlsSetValue(DWORD, LPVOID)`. Writes the current thread's
/// TLS slot.
fn stub_tls_set_value(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let idx = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("TlsSetValue", t))?;
    let value = arg_dword(cpu, mmu, 1).map_err(|t| trap_to_win32("TlsSetValue", t))?;
    state.cur_thread_mut().tls_slots.insert(idx, value);
    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 hHandle, DWORD dwMilliseconds)`.
/// Returns `WAIT_OBJECT_0` (= 0) immediately if the object is
/// signaled; otherwise asks the scheduler to suspend the
/// current thread until it signals (or the timeout expires).
///
/// `dwMilliseconds = INFINITE (0xFFFF_FFFF)` waits forever.
/// Any handle that isn't registered with the scheduler is
/// treated as "signaled" so codec corpora that pass synthetic
/// non-WaitObject handles still get the historical
/// pass-through behaviour.
fn stub_wait_for_single_object(
    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("WaitForSingleObject", t))?;
    let ms = arg_dword(cpu, mmu, 1).map_err(|t| trap_to_win32("WaitForSingleObject", t))?;
    if !state.scheduler.objects.contains_key(&h) {
        // Unknown handle — fail-soft: report signaled, matching
        // the pre-Phase-3c contract.
        return Ok(0);
    }
    let cur_tid = state.active_tid;
    // Resolve "is it signaled?" — Thread / Process objects
    // also signal on Terminated.
    let signaled = match state.scheduler.objects.get(&h) {
        Some(crate::sched::WaitObject::Thread { tid }) => state
            .threads
            .get(tid)
            .map(|t| matches!(t.status, crate::sched::ThreadStatus::Terminated))
            .unwrap_or(true),
        Some(crate::sched::WaitObject::Process { pid }) => state
            .processes
            .get(pid)
            .map(|p| p.exit_code.is_some())
            .unwrap_or(true),
        Some(obj) => crate::sched::object_is_signaled(obj),
        None => false,
    };
    if signaled {
        if let Some(obj) = state.scheduler.objects.get_mut(&h) {
            crate::sched::consume_signal_if_auto_reset(obj, cur_tid);
        }
        return Ok(0);
    }
    // Block — record the wait with optional timeout.
    let timeout_after = if ms == 0xFFFF_FFFF {
        None
    } else {
        Some(
            state
                .scheduler
                .instructions_global
                .saturating_add(u64::from(ms).saturating_mul(crate::sched::INSTRUCTIONS_PER_MS)),
        )
    };
    state.yield_requested = Some(crate::sched::YieldRequest::Wait(
        crate::sched::WaitCondition::Object {
            handle: h,
            timeout_after,
        },
    ));
    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)`.
/// Mints an `Event` WaitObject with the supplied
/// manual-reset / initial-state pair. When `lpName` is
/// non-NULL and an event with that name already exists in
/// the scheduler's named-object registry, returns the
/// existing handle (matching the Win32 contract: subsequent
/// `CreateEvent` calls on a named event "open" rather than
/// "create"). Otherwise the new event is registered under
/// the name so a sibling `OpenEventA` can find it.
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 p_name = arg_dword(cpu, mmu, 3).map_err(|t| trap_to_win32("CreateEventA", t))?;
    let name = if p_name != 0 {
        read_cstr(mmu, p_name, 260).ok()
    } else {
        None
    };
    if let Some(n) = &name {
        if let Some(h) = state.scheduler.lookup_named(n) {
            // ERROR_ALREADY_EXISTS surfaces via GetLastError;
            // the function still returns the existing handle.
            state.last_error = 183;
            return Ok(h);
        }
    }
    let h = state
        .scheduler
        .insert_object(crate::sched::WaitObject::Event {
            signaled: init != 0,
            manual_reset: manual != 0,
        });
    if let Some(n) = name {
        state.scheduler.register_named(&n, h);
    }
    Ok(h)
}

/// `HANDLE CreateThread(LPSECURITY_ATTRIBUTES lpThreadAttributes,
/// SIZE_T dwStackSize, LPTHREAD_START_ROUTINE lpStartAddress,
/// LPVOID lpParameter, DWORD dwCreationFlags,
/// LPDWORD lpThreadId)`.
///
/// Mints a fresh [`crate::win32::ThreadState`] with its own CPU
/// register file + stack region, parks the CPU on the start
/// routine (one stdcall argument: `lpParameter`, RET_SENTINEL
/// as the return-to address), marks the thread `Ready`, and
/// hands back a Thread `WaitObject` handle. The scheduler
/// switches into the new thread the next time the current one
/// yields or hits a `Wait*` / quantum boundary.
///
/// `CREATE_SUSPENDED` (0x0000_0004) parks the thread in
/// `Suspended` state instead — `ResumeThread` moves it to
/// `Ready`.
fn stub_create_thread(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    use crate::emulator::isa_int::RET_SENTINEL;
    use crate::sched::{ThreadStatus, WaitObject};
    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))?;
    if start == 0 {
        return Ok(0);
    }
    // Reserve the next slot in the thread-stack arena.
    let arena_top = state.cur_process().next_thread_stack_top;
    let arena_bottom = state.cur_process().thread_stack_pool_bottom;
    if arena_top == 0 || arena_top.saturating_sub(arena_bottom) < crate::win32::THREAD_STACK_SIZE {
        return Err(Win32Error::InvalidArgument {
            stub: "CreateThread",
            reason:
                "thread-stack pool exhausted (configure with HostState::with_thread_stack_pool)"
                    .into(),
        });
    }
    let stack_top = arena_top;
    state.cur_process_mut().next_thread_stack_top = stack_top - crate::win32::THREAD_STACK_SIZE;
    // Reserve a fresh TIB for the new thread. Phase 6 of the
    // scheduler refactor: each thread gets its own FS-segment
    // base so the CRT's `fs:[0x34]` LastError / `fs:[0]` SEH
    // chain head don't collide across threads.
    let tib_addr = if state.cur_process().tib_pool_bottom != 0 {
        let addr = state.cur_process().next_tib_addr;
        state.cur_process_mut().next_tib_addr = addr.wrapping_add(crate::win32::THREAD_TIB_SIZE);
        // Seed the new TIB: FS:[0] = -1 (no SEH handler) and
        // FS:[0x18] = self pointer (TIB ABI).
        let _ = mmu.store32(addr, 0xFFFF_FFFF);
        let _ = mmu.store32(addr + 0x18, addr);
        addr
    } else {
        0
    };
    // Build the new thread's CPU state.
    let mut new_cpu = Cpu::new();
    new_cpu.regs.set_esp(stack_top - 0x10); // small guard
    new_cpu.regs.eip = start;
    if tib_addr != 0 {
        new_cpu.set_fs_base(tib_addr);
    }
    // stdcall: one DWORD argument (lpParameter). Push param +
    // RET_SENTINEL so a plain RET inside the start routine
    // returns to the sentinel, which the run loop catches as
    // "thread done".
    new_cpu
        .push32(mmu, param)
        .map_err(|t| trap_to_win32("CreateThread", t))?;
    new_cpu
        .push32(mmu, RET_SENTINEL)
        .map_err(|t| trap_to_win32("CreateThread", t))?;
    // Allocate a TID + register the thread.
    let tid = state.next_tid;
    state.next_tid = state.next_tid.wrapping_add(1);
    let pid = state.cur_thread().pid;
    let mut t = crate::win32::ThreadState::new(tid, pid);
    t.parked_cpu = Some(new_cpu);
    t.tib_addr = tib_addr;
    t.status = if (flags & CREATE_SUSPENDED) != 0 {
        ThreadStatus::Suspended
    } else {
        ThreadStatus::Ready
    };
    state.threads.insert(tid, t);
    // Mint a Thread wait object for parent-side
    // WaitForSingleObject. Phase 3c wires this into Wait*; for
    // now we just hand back the handle.
    let handle = state.scheduler.insert_object(WaitObject::Thread { tid });
    if p_tid != 0 {
        mmu.store32(p_tid, tid)
            .map_err(|t| trap_to_win32("CreateThread", t))?;
    }
    Ok(handle)
}

/// `void ExitThread(DWORD dwExitCode)`. Marks the current
/// thread `Terminated` and asks the scheduler to switch. Never
/// returns (the run loop catches the yield request and the
/// next thread runs in place of this one).
fn stub_exit_thread(
    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("ExitThread", t))?;
    state.yield_requested = Some(crate::sched::YieldRequest::Exit { code });
    Ok(0)
}

/// `BOOL SetEvent(HANDLE)`. Marks the Event WaitObject signaled
/// and moves every Waiting thread back to Ready (manual-reset)
/// or just the first waiter in TID order (auto-reset, which
/// also clears the signal again per
/// [`crate::sched::consume_signal_if_auto_reset`]).
fn stub_set_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("SetEvent", t))?;
    let Some(crate::sched::WaitObject::Event {
        signaled,
        manual_reset,
    }) = state.scheduler.objects.get_mut(&h)
    else {
        return Ok(0);
    };
    *signaled = true;
    let manual = *manual_reset;
    let waiters = crate::sched::waiters_on(&state.threads, h);
    if manual {
        for tid in waiters {
            wake_thread(state, tid, h);
        }
    } else if let Some(&tid) = waiters.first() {
        wake_thread(state, tid, h);
    }
    Ok(1)
}

/// Helper used by signal-side stubs: move `tid` from Waiting to
/// Ready, clear its wait condition, and take the side effect
/// implied by signal consumption (auto-reset Event, Mutex
/// ownership transfer, Semaphore decrement) against `handle`.
fn wake_thread(state: &mut HostState, tid: u32, handle: u32) {
    if let Some(obj) = state.scheduler.objects.get_mut(&handle) {
        crate::sched::consume_signal_if_auto_reset(obj, tid);
    }
    if let Some(t) = state.threads.get_mut(&tid) {
        t.status = crate::sched::ThreadStatus::Ready;
        t.wait = None;
    }
}

/// `BOOL SetThreadPriority(HANDLE hThread, int nPriority)`.
/// Looks up the Thread WaitObject behind the handle and
/// updates the target thread's priority. The scheduler picks
/// higher-priority Ready threads first (Phase 4).
fn stub_set_thread_priority(
    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("SetThreadPriority", t))?;
    let prio = arg_dword(cpu, mmu, 1).map_err(|t| trap_to_win32("SetThreadPriority", t))? as i32;
    if let Some(crate::sched::WaitObject::Thread { tid }) = state.scheduler.objects.get(&h) {
        let tid = *tid;
        if let Some(t) = state.threads.get_mut(&tid) {
            t.priority = prio;
        }
    }
    Ok(1)
}

/// `BOOL SwitchToThread(void)`. Voluntarily yields the
/// current quantum to any Ready peer; returns FALSE when no
/// other thread was Ready (so we kept running).
fn stub_switch_to_thread(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let cur_tid = state.active_tid;
    let has_peer = state
        .threads
        .iter()
        .any(|(tid, t)| *tid != cur_tid && matches!(t.status, crate::sched::ThreadStatus::Ready));
    if has_peer {
        state.yield_requested = Some(crate::sched::YieldRequest::Yield);
        Ok(1)
    } else {
        Ok(0)
    }
}

/// `DWORD ResumeThread(HANDLE)`. Looks up the Thread wait
/// object behind the handle; if the corresponding thread is
/// `Suspended`, moves it to `Ready`. Returns the previous
/// suspend count (always 0 or 1 in our model).
fn stub_resume_thread(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    use crate::sched::{ThreadStatus, WaitObject};
    let h = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("ResumeThread", t))?;
    let tid = match state.scheduler.objects.get(&h) {
        Some(WaitObject::Thread { tid }) => *tid,
        _ => return Ok(0xFFFF_FFFF),
    };
    let Some(t) = state.threads.get_mut(&tid) else {
        return Ok(0xFFFF_FFFF);
    };
    if matches!(t.status, ThreadStatus::Suspended) {
        t.status = ThreadStatus::Ready;
        return Ok(1);
    }
    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)`. Returns the PID owning
/// the active thread (`1` for the bootstrap process; Phase 5
/// will mint child PIDs).
fn stub_get_current_process_id(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    Ok(state.cur_thread().pid)
}

/// `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)`. Clears the Event
/// WaitObject's signaled flag. Pending waiters stay parked
/// (only signal transitions wake them).
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))?;
    if let Some(crate::sched::WaitObject::Event { signaled, .. }) =
        state.scheduler.objects.get_mut(&h)
    {
        *signaled = false;
    }
    Ok(1)
}

/// `DWORD WaitForMultipleObjects(DWORD nCount, const HANDLE *lpHandles,
/// BOOL bWaitAll, DWORD dwMilliseconds)`. Returns
/// `WAIT_OBJECT_0 + n` for the first signaled handle when
/// `bWaitAll = FALSE`; with `bWaitAll = TRUE` it parks the
/// caller until every handle has signaled. Unknown handles
/// (not in the scheduler) are treated as "already signaled" —
/// preserves the pre-Phase-3c fail-soft pass-through.
fn stub_wait_for_multiple_objects(
    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("WaitForMultipleObjects", t))?;
    let p_handles =
        arg_dword(cpu, mmu, 1).map_err(|t| trap_to_win32("WaitForMultipleObjects", t))?;
    let wait_all =
        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))?;
    if n == 0 || p_handles == 0 {
        return Ok(0);
    }
    let mut handles = Vec::with_capacity(n as usize);
    for i in 0..n {
        handles.push(
            mmu.load32(p_handles + i * 4)
                .map_err(|t| trap_to_win32("WaitForMultipleObjects", t))?,
        );
    }
    let signaled_now: Vec<bool> = handles
        .iter()
        .map(|h| match state.scheduler.objects.get(h) {
            Some(obj) => crate::sched::object_is_signaled(obj),
            None => true,
        })
        .collect();
    let cur_tid = state.active_tid;
    if wait_all != 0 {
        if signaled_now.iter().all(|x| *x) {
            for h in &handles {
                if let Some(obj) = state.scheduler.objects.get_mut(h) {
                    crate::sched::consume_signal_if_auto_reset(obj, cur_tid);
                }
            }
            return Ok(0);
        }
    } else if let Some(idx) = signaled_now.iter().position(|x| *x) {
        if let Some(obj) = state.scheduler.objects.get_mut(&handles[idx]) {
            crate::sched::consume_signal_if_auto_reset(obj, cur_tid);
        }
        return Ok(idx as u32);
    }
    let timeout_after = if ms == 0xFFFF_FFFF {
        None
    } else {
        Some(
            state
                .scheduler
                .instructions_global
                .saturating_add(u64::from(ms).saturating_mul(crate::sched::INSTRUCTIONS_PER_MS)),
        )
    };
    state.yield_requested = Some(crate::sched::YieldRequest::Wait(
        crate::sched::WaitCondition::Multiple {
            handles,
            wait_all: wait_all != 0,
            timeout_after,
        },
    ));
    Ok(0)
}

/// `HANDLE CreateEventW(LPSECURITY_ATTRIBUTES, BOOL, BOOL, LPCWSTR)`.
/// UTF-16 twin of [`stub_create_event_a`] — same named-object
/// dedup semantics on the UTF-8-converted name.
fn stub_create_event_w(
    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("CreateEventW", t))?;
    let manual = arg_dword(cpu, mmu, 1).map_err(|t| trap_to_win32("CreateEventW", t))?;
    let init = arg_dword(cpu, mmu, 2).map_err(|t| trap_to_win32("CreateEventW", t))?;
    let p_name = arg_dword(cpu, mmu, 3).map_err(|t| trap_to_win32("CreateEventW", t))?;
    let name = if p_name != 0 {
        Some(super::read_wide_cstr_local(mmu, p_name, 260))
    } else {
        None
    };
    if let Some(n) = &name {
        if let Some(h) = state.scheduler.lookup_named(n) {
            state.last_error = 183;
            return Ok(h);
        }
    }
    let h = state
        .scheduler
        .insert_object(crate::sched::WaitObject::Event {
            signaled: init != 0,
            manual_reset: manual != 0,
        });
    if let Some(n) = &name {
        state.scheduler.register_named(n, h);
    }
    Ok(h)
}

/// `HANDLE CreateSemaphoreW(LPSECURITY_ATTRIBUTES, LONG, LONG, LPCWSTR)`.
/// UTF-16 twin of [`stub_create_semaphore_a`].
fn stub_create_semaphore_w(
    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("CreateSemaphoreW", t))?;
    let init = arg_dword(cpu, mmu, 1).map_err(|t| trap_to_win32("CreateSemaphoreW", t))?;
    let max = arg_dword(cpu, mmu, 2).map_err(|t| trap_to_win32("CreateSemaphoreW", t))?;
    let _name = arg_dword(cpu, mmu, 3).map_err(|t| trap_to_win32("CreateSemaphoreW", t))?;
    Ok(state
        .scheduler
        .insert_object(crate::sched::WaitObject::Semaphore { count: init, max }))
}

/// `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`. `NULL` returns the primary
/// module base; otherwise resolve via `state.modules` (lower-cased
/// — `Sandbox::new` pre-registers the canonical system DLLs there
/// so codec CRTs that probe `GetModuleHandleW(L"KERNEL32.DLL")`
/// during init get a non-NULL handle back).
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);
    }
    let name = read_wcstr(mmu, p, 260)?.to_ascii_lowercase();
    Ok(state.modules.get(&name).copied().unwrap_or(0))
}

/// Read a NUL-terminated wide (UTF-16LE) string from guest
/// memory and return it as a host `String` (lossily, ASCII-bias
/// — codec module names and CRT probes are all ASCII-clean).
fn read_wcstr(mmu: &Mmu, mut addr: u32, max: u32) -> Result<String, Win32Error> {
    let mut bytes = Vec::with_capacity(64);
    for _ in 0..max {
        let c = mmu
            .load16(addr)
            .map_err(|t| trap_to_win32("read_wcstr", t))?;
        if c == 0 {
            break;
        }
        bytes.push(c);
        addr = addr.wrapping_add(2);
    }
    Ok(String::from_utf16_lossy(&bytes))
}

/// `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)`. Actually
/// updates the MMU permissions for every page in
/// `[lpAddress, lpAddress + dwSize)`. The bytes are preserved
/// — `Mmu::map` rewrites the perm slot without touching page
/// contents. Required by codecs (e.g. `wmvdecod.dll`) that
/// self-patch a thunk inside their own `.text` section during
/// `DllMain` by flipping it RW, writing, then flipping it
/// back. `lpflOldProtect` receives the prior protection of the
/// first page in the range — sufficient for the
/// flip-write-flip pattern.
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))?;
    // MSDN: all pages in the range must already be committed;
    // return FALSE if any unmapped page is hit.
    if size == 0 || !mmu.is_mapped(addr) {
        return Ok(0);
    }
    let old_perm = mmu.perm_at(addr).unwrap_or(Perm::from_bits(0));
    if out != 0 {
        mmu.store32(out, perm_to_page_protect(old_perm))
            .map_err(|t| trap_to_win32("VirtualProtect", t))?;
    }
    let new_perm = page_protect_to_perm(new);
    mmu.map(addr, size, new_perm);
    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> {
    let p = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("LoadLibraryW", t))?;
    if p == 0 {
        return Ok(0);
    }
    let name = read_wcstr(mmu, p, 260)?.to_ascii_lowercase();
    Ok(state.modules.get(&name).copied().unwrap_or(0))
}

/// `BOOL ReadFile(HANDLE, LPVOID, DWORD, LPDWORD, LPOVERLAPPED)`.
/// Routes pipe handles through the scheduler's pipe buffer
/// (parks the caller when empty so the writing peer can run),
/// VFS handles through the virtual filesystem; otherwise
/// reports "read 0 bytes" success (the historical no-FS
/// fallback).
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))?;
    // Pipe read end: drain up to `n` bytes from the shared
    // buffer. Empty + writer alive → block on the handle until
    // the writer adds data. Empty + writer closed → EOF
    // (return TRUE, bytes_read = 0).
    if let Some(crate::sched::WaitObject::Pipe {
        pipe_id,
        is_read_end: true,
    }) = state.scheduler.objects.get(&h).cloned()
    {
        let (have_bytes, writer_open) = state
            .scheduler
            .pipes
            .get(&pipe_id)
            .map(|p| (!p.bytes.is_empty(), p.closed_ends < 2))
            .unwrap_or((false, false));
        if !have_bytes && writer_open {
            // Park on the read handle; the writer's WriteFile
            // wakes us.
            state.yield_requested = Some(crate::sched::YieldRequest::Wait(
                crate::sched::WaitCondition::Object {
                    handle: h,
                    timeout_after: None,
                },
            ));
            if out != 0 {
                mmu.store32(out, 0)
                    .map_err(|t| trap_to_win32("ReadFile", t))?;
            }
            return Ok(1);
        }
        let want = n as usize;
        let mut tmp = Vec::with_capacity(want);
        if let Some(p) = state.scheduler.pipes.get_mut(&pipe_id) {
            for _ in 0..want {
                if let Some(b) = p.bytes.pop_front() {
                    tmp.push(b);
                } else {
                    break;
                }
            }
        }
        if !tmp.is_empty() && buf != 0 {
            mmu.write(buf, &tmp)
                .map_err(|t| trap_to_win32("ReadFile", t))?;
        }
        if out != 0 {
            mmu.store32(out, tmp.len() as u32)
                .map_err(|t| trap_to_win32("ReadFile", t))?;
        }
        return Ok(1);
    }
    if let Some(vfs) = state.context.vfs.as_mut() {
        if vfs.owns(h) && buf != 0 {
            let mut tmp = vec![0u8; n as usize];
            let got = vfs.read_handle(h, &mut tmp).unwrap_or(0);
            if got > 0 {
                mmu.write(buf, &tmp[..got])
                    .map_err(|t| trap_to_win32("ReadFile", t))?;
            }
            if out != 0 {
                mmu.store32(out, got as u32)
                    .map_err(|t| trap_to_win32("ReadFile", t))?;
            }
            return Ok(1);
        }
    }
    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)
}

// ============================================================
// Install-monitor stub implementations
// ============================================================

/// Canonical temp directory string handed back to the guest. Kept
/// in one place so the monitor's "what did the installer write?"
/// report can match `c:/temp/*` paths reliably.
const TEMP_PATH_A: &[u8] = b"C:\\Temp\\\0";

/// Write `s` into the guest buffer at `dst`, capped at `cch`
/// bytes (including the NUL). Returns the number of bytes
/// actually written (excluding the NUL).
fn write_cstr(
    mmu: &mut Mmu,
    dst: u32,
    cch: u32,
    s: &[u8],
    stub: &'static str,
) -> Result<u32, Win32Error> {
    if dst == 0 || cch == 0 {
        return Ok(0);
    }
    let cap = cch.saturating_sub(1) as usize;
    let n = s.len().min(cap);
    if n > 0 {
        mmu.write(dst, &s[..n])
            .map_err(|t| trap_to_win32(stub, t))?;
    }
    mmu.store8(dst + n as u32, 0)
        .map_err(|t| trap_to_win32(stub, t))?;
    Ok(n as u32)
}

/// `DWORD GetTempPathA(DWORD nBufferLength, LPSTR lpBuffer)`.
/// Writes `"C:\\Temp\\"` (length 8) plus a NUL into the buffer.
/// Returns the path length (excluding NUL). If the buffer is too
/// small, returns the required length including NUL — matching
/// the MSDN contract.
fn stub_get_temp_path_a(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let n_buf = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("GetTempPathA", t))?;
    let lp_buf = arg_dword(cpu, mmu, 1).map_err(|t| trap_to_win32("GetTempPathA", t))?;
    let path = &TEMP_PATH_A[..TEMP_PATH_A.len() - 1]; // strip trailing NUL
    let need = path.len() as u32 + 1; // including NUL
    if lp_buf == 0 || n_buf < need {
        return Ok(need);
    }
    write_cstr(mmu, lp_buf, n_buf, path, "GetTempPathA")?;
    Ok(path.len() as u32)
}

/// `UINT GetTempFileNameA(LPCSTR lpPathName, LPCSTR lpPrefixString,
/// UINT uUnique, LPSTR lpTempFileName)`. Builds a deterministic
/// `pathname\prefix<unique>.tmp` string and writes it back. When
/// `uUnique == 0`, picks a fresh counter from the tick. Creates a
/// zero-byte entry in the VFS so a follow-up `CreateFileA` sees
/// the file.
fn stub_get_temp_file_name_a(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let p_path = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("GetTempFileNameA", t))?;
    let p_prefix = arg_dword(cpu, mmu, 1).map_err(|t| trap_to_win32("GetTempFileNameA", t))?;
    let mut unique = arg_dword(cpu, mmu, 2).map_err(|t| trap_to_win32("GetTempFileNameA", t))?;
    let dst = arg_dword(cpu, mmu, 3).map_err(|t| trap_to_win32("GetTempFileNameA", t))?;
    let path = if p_path != 0 {
        read_cstr(mmu, p_path, 260)?
    } else {
        String::new()
    };
    let prefix = if p_prefix != 0 {
        read_cstr(mmu, p_prefix, 3)?
    } else {
        String::new()
    };
    if unique == 0 {
        state.tick = state.tick.wrapping_add(1);
        unique = state.tick;
    }
    let trimmed = path.trim_end_matches(['\\', '/']);
    let full = if trimmed.is_empty() {
        format!("{prefix}{unique:04X}.tmp")
    } else {
        format!("{trimmed}\\{prefix}{unique:04X}.tmp")
    };
    if let Some(vfs) = state.context.vfs.as_mut() {
        vfs.insert(&full, Vec::new());
    }
    write_cstr(mmu, dst, 260, full.as_bytes(), "GetTempFileNameA")?;
    Ok(unique)
}

/// `HANDLE CreateFileA(LPCSTR lpFileName, DWORD dwDesiredAccess,
/// DWORD dwShareMode, LPSECURITY_ATTRIBUTES, DWORD dwCreationDisposition,
/// DWORD dwFlagsAndAttributes, HANDLE hTemplateFile)`. Routes the
/// open through the VFS when one is attached; returns
/// `INVALID_HANDLE_VALUE` (= `0xFFFFFFFF`) otherwise. The MSDN
/// `dwCreationDisposition` axis is honoured at a coarse level —
/// `CREATE_ALWAYS` / `CREATE_NEW` / `TRUNCATE_EXISTING` truncate
/// the backing file; `OPEN_EXISTING` fails when the file is
/// absent.
const CREATE_NEW: u32 = 1;
const CREATE_ALWAYS: u32 = 2;
const OPEN_EXISTING: u32 = 3;
const TRUNCATE_EXISTING: u32 = 5;
const INVALID_HANDLE_VALUE: u32 = 0xFFFF_FFFF;
const ERROR_FILE_NOT_FOUND: u32 = 2;
const ERROR_FILE_EXISTS: u32 = 80;

fn stub_create_file_a(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let p_name = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("CreateFileA", t))?;
    let access = arg_dword(cpu, mmu, 1).map_err(|t| trap_to_win32("CreateFileA", t))?;
    let _share = arg_dword(cpu, mmu, 2).map_err(|t| trap_to_win32("CreateFileA", t))?;
    let _sa = arg_dword(cpu, mmu, 3).map_err(|t| trap_to_win32("CreateFileA", t))?;
    let disp = arg_dword(cpu, mmu, 4).map_err(|t| trap_to_win32("CreateFileA", t))?;
    let _attrs = arg_dword(cpu, mmu, 5).map_err(|t| trap_to_win32("CreateFileA", t))?;
    let _tmpl = arg_dword(cpu, mmu, 6).map_err(|t| trap_to_win32("CreateFileA", t))?;
    if p_name == 0 {
        state.last_error = ERROR_FILE_NOT_FOUND;
        return Ok(INVALID_HANDLE_VALUE);
    }
    let name = read_cstr(mmu, p_name, 260)?;
    // `\\.\pipe\<name>` is the Win32 pipe-client syntax —
    // attach to a named pipe registered by a sibling
    // CreateNamedPipeA call rather than opening a file in
    // the VFS. Mint a fresh read-end handle pointing at the
    // pipe's buffer.
    if let Some(pipe_name) = parse_pipe_client_path(&name) {
        if let Some(server_handle) = state.scheduler.lookup_named(&pipe_name) {
            let pipe_id = match state.scheduler.objects.get(&server_handle) {
                Some(crate::sched::WaitObject::Pipe { pipe_id, .. }) => *pipe_id,
                _ => {
                    state.last_error = ERROR_FILE_NOT_FOUND;
                    return Ok(INVALID_HANDLE_VALUE);
                }
            };
            // Client end: read from server's write side, so
            // client opens the *other* end of the pair.
            let is_read_end = !matches!(
                state.scheduler.objects.get(&server_handle),
                Some(crate::sched::WaitObject::Pipe {
                    is_read_end: true,
                    ..
                })
            );
            return Ok(state
                .scheduler
                .insert_object(crate::sched::WaitObject::Pipe {
                    pipe_id,
                    is_read_end,
                }));
        }
        state.last_error = ERROR_FILE_NOT_FOUND;
        return Ok(INVALID_HANDLE_VALUE);
    }
    let Some(vfs) = state.context.vfs.as_mut() else {
        state.last_error = ERROR_FILE_NOT_FOUND;
        return Ok(INVALID_HANDLE_VALUE);
    };
    let exists = vfs.contains(&name);
    match disp {
        OPEN_EXISTING => {
            if !exists {
                state.last_error = ERROR_FILE_NOT_FOUND;
                return Ok(INVALID_HANDLE_VALUE);
            }
        }
        CREATE_NEW => {
            if exists {
                state.last_error = ERROR_FILE_EXISTS;
                return Ok(INVALID_HANDLE_VALUE);
            }
            vfs.insert(&name, Vec::new());
        }
        CREATE_ALWAYS | TRUNCATE_EXISTING => {
            vfs.write_path(&name, Vec::new());
        }
        _ => {
            // OPEN_ALWAYS (4) and unknown values: open if exists,
            // create empty otherwise.
            if !exists {
                vfs.insert(&name, Vec::new());
            }
        }
    }
    let fa = crate::context::FileAccess::from_win32_desired_access(access);
    match vfs.open(&name, fa) {
        Some(h) => Ok(h),
        None => {
            state.last_error = ERROR_FILE_NOT_FOUND;
            Ok(INVALID_HANDLE_VALUE)
        }
    }
}

/// `BOOL CreateDirectoryA(LPCSTR lpPathName, LPSECURITY_ATTRIBUTES
/// lpSecurityAttributes)`. Creates a `<path>/.dir` marker in the
/// VFS so directory existence is observable; otherwise reports
/// success. Returns FALSE only when the path is NULL or already
/// recorded.
fn stub_create_directory_a(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let p_name = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("CreateDirectoryA", t))?;
    let _sa = arg_dword(cpu, mmu, 1).map_err(|t| trap_to_win32("CreateDirectoryA", t))?;
    if p_name == 0 {
        state.last_error = ERROR_FILE_NOT_FOUND;
        return Ok(0);
    }
    let name = read_cstr(mmu, p_name, 260)?;
    let marker = format!("{}\\.dir", name.trim_end_matches(['\\', '/']));
    if let Some(vfs) = state.context.vfs.as_mut() {
        if vfs.contains(&marker) {
            state.last_error = ERROR_FILE_EXISTS;
            return Ok(0);
        }
        vfs.insert(&marker, Vec::new());
    }
    Ok(1)
}

/// `BOOL DeleteFileA(LPCSTR lpFileName)`. Removes from the VFS
/// when present; reports success even without a VFS attached.
fn stub_delete_file_a(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let p_name = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("DeleteFileA", t))?;
    if p_name == 0 {
        state.last_error = ERROR_FILE_NOT_FOUND;
        return Ok(0);
    }
    let name = read_cstr(mmu, p_name, 260)?;
    if let Some(vfs) = state.context.vfs.as_mut() {
        vfs.remove(&name);
    }
    Ok(1)
}

/// `DWORD GetFileAttributesA(LPCSTR lpFileName)`. Reports
/// `FILE_ATTRIBUTE_NORMAL = 0x80` when the path exists in the
/// VFS (file or `.dir` marker); otherwise returns
/// `INVALID_FILE_ATTRIBUTES = 0xFFFFFFFF`.
fn stub_get_file_attributes_a(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let p_name = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("GetFileAttributesA", t))?;
    if p_name == 0 {
        state.last_error = ERROR_FILE_NOT_FOUND;
        return Ok(0xFFFF_FFFF);
    }
    let name = read_cstr(mmu, p_name, 260)?;
    let Some(vfs) = state.context.vfs.as_ref() else {
        state.last_error = ERROR_FILE_NOT_FOUND;
        return Ok(0xFFFF_FFFF);
    };
    if vfs.contains(&name) {
        return Ok(0x80); // FILE_ATTRIBUTE_NORMAL
    }
    let dir_marker = format!("{}\\.dir", name.trim_end_matches(['\\', '/']));
    if vfs.contains(&dir_marker) {
        return Ok(0x10); // FILE_ATTRIBUTE_DIRECTORY
    }
    state.last_error = ERROR_FILE_NOT_FOUND;
    Ok(0xFFFF_FFFF)
}

/// `DWORD GetFileSize(HANDLE hFile, LPDWORD lpFileSizeHigh)`.
/// Returns the low dword of the file size (high dword written
/// through `lpFileSizeHigh` when non-NULL). `INVALID_FILE_SIZE
/// = 0xFFFFFFFF` for unknown handles.
fn stub_get_file_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("GetFileSize", t))?;
    let p_hi = arg_dword(cpu, mmu, 1).map_err(|t| trap_to_win32("GetFileSize", t))?;
    if let Some(vfs) = state.context.vfs.as_ref() {
        if let Some(sz) = vfs.size(h) {
            if p_hi != 0 {
                mmu.store32(p_hi, (sz >> 32) as u32)
                    .map_err(|t| trap_to_win32("GetFileSize", t))?;
            }
            return Ok(sz as u32);
        }
    }
    state.last_error = ERROR_INVALID_HANDLE;
    Ok(0xFFFF_FFFF)
}

/// `BOOL DosDateTimeToFileTime(WORD wFatDate, WORD wFatTime,
/// LPFILETIME lpFileTime)`. Pure conversion — no environment
/// state. We emit a deterministic FILETIME for the given pair so
/// the installer's archive-extract path proceeds.
fn stub_dos_date_time_to_file_time(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let fat_date =
        arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("DosDateTimeToFileTime", t))? & 0xFFFF;
    let fat_time =
        arg_dword(cpu, mmu, 1).map_err(|t| trap_to_win32("DosDateTimeToFileTime", t))? & 0xFFFF;
    let p_out = arg_dword(cpu, mmu, 2).map_err(|t| trap_to_win32("DosDateTimeToFileTime", t))?;
    if p_out == 0 {
        return Ok(0);
    }
    let year = 1980 + ((fat_date >> 9) & 0x7F) as i32;
    let month = ((fat_date >> 5) & 0x0F).max(1) as i32;
    let day = (fat_date & 0x1F).max(1) as i32;
    let hour = ((fat_time >> 11) & 0x1F) as i32;
    let minute = ((fat_time >> 5) & 0x3F) as i32;
    let second = ((fat_time & 0x1F) * 2) as i32;
    // Days from 1601-01-01 to year-01-01 (approx — ignore leap-day
    // distribution beyond Gregorian arithmetic). This is the
    // "FILETIME = 100-ns ticks since 1601-01-01" surface; the
    // installer only needs a strictly-increasing reproducible
    // value, not a precise calendar conversion.
    let days_from_1601 = (year - 1601) as i64 * 365 + ((year - 1601) / 4) as i64
        - ((year - 1601) / 100) as i64
        + ((year - 1601) / 400) as i64;
    let month_days = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
    let mut day_of_year = month_days[(month - 1).clamp(0, 11) as usize] as i64;
    if month > 2 && (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) {
        day_of_year += 1;
    }
    day_of_year += day as i64 - 1;
    let total_days = days_from_1601 + day_of_year;
    let total_seconds =
        total_days * 86_400 + hour as i64 * 3600 + minute as i64 * 60 + second as i64;
    let ticks = (total_seconds * 10_000_000) as u64;
    mmu.store32(p_out, ticks as u32)
        .map_err(|t| trap_to_win32("DosDateTimeToFileTime", t))?;
    mmu.store32(p_out + 4, (ticks >> 32) as u32)
        .map_err(|t| trap_to_win32("DosDateTimeToFileTime", t))?;
    Ok(1)
}

/// `HANDLE CreateMutexA(LPSECURITY_ATTRIBUTES, BOOL bInitialOwner,
/// LPCSTR lpName)`. Mints a Mutex WaitObject. If
/// `bInitialOwner` is TRUE the calling thread becomes the
/// owner immediately.
fn stub_create_mutex_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("CreateMutexA", t))?;
    let init_owner = arg_dword(cpu, mmu, 1).map_err(|t| trap_to_win32("CreateMutexA", t))?;
    let _name = arg_dword(cpu, mmu, 2).map_err(|t| trap_to_win32("CreateMutexA", t))?;
    let owner = if init_owner != 0 {
        Some(state.active_tid)
    } else {
        None
    };
    let recursion = if init_owner != 0 { 1 } else { 0 };
    Ok(state
        .scheduler
        .insert_object(crate::sched::WaitObject::Mutex { owner, recursion }))
}

/// `BOOL ReleaseMutex(HANDLE)`. Decrements the recursion count;
/// when it reaches zero, clears the owner and wakes the first
/// pending waiter (which then becomes the new owner). Returns
/// FALSE if the caller isn't the current owner.
fn stub_release_mutex(
    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("ReleaseMutex", t))?;
    let cur_tid = state.active_tid;
    let Some(crate::sched::WaitObject::Mutex { owner, recursion }) =
        state.scheduler.objects.get_mut(&h)
    else {
        return Ok(0);
    };
    if *owner != Some(cur_tid) {
        return Ok(0);
    }
    *recursion = recursion.saturating_sub(1);
    if *recursion == 0 {
        *owner = None;
        // Wake the first waiter (consume_signal_if_auto_reset
        // will transfer ownership to them).
        let waiters = crate::sched::waiters_on(&state.threads, h);
        if let Some(&tid) = waiters.first() {
            wake_thread(state, tid, h);
        }
    }
    Ok(1)
}

/// `BOOL CreateProcessA(LPCSTR lpApplicationName,
/// LPSTR lpCommandLine, LPSECURITY_ATTRIBUTES lpProcessAttributes,
/// LPSECURITY_ATTRIBUTES lpThreadAttributes,
/// BOOL bInheritHandles, DWORD dwCreationFlags,
/// LPVOID lpEnvironment, LPCSTR lpCurrentDirectory,
/// LPSTARTUPINFO lpStartupInfo,
/// LPPROCESS_INFORMATION lpProcessInformation)`.
///
/// Tries to load + run the child PE for `CreateProcessA` when
/// the target EXE is staged in the virtual filesystem. The
/// PE is rebased to the next slot in the child-image arena
/// and its imports resolved strictly against the parent's
/// registry (no fallback thunks — the child needs every
/// import it lists to be host-stubbed). Returns
/// `Some(child_pid, child_tid)` on success and `None` when
/// the file isn't in the VFS, lacks relocations, has
/// unresolved imports, or fails any parse step. The caller
/// then falls back to the synthetic immediate-exit child.
fn try_spawn_child_pe(
    state: &mut HostState,
    mmu: &mut Mmu,
    registry: &Registry,
    target_path: &str,
    cmd: &str,
) -> Option<(u32, u32)> {
    use crate::emulator::isa_int::RET_SENTINEL;
    use crate::emulator::mmu::Perm;
    use crate::pe;
    use crate::sched::ThreadStatus;
    // Read PE bytes from the VFS.
    let vfs = state.context.vfs.as_ref()?;
    let bytes = vfs.read(target_path)?.to_vec();
    let parsed = pe::header::parse(&bytes).ok()?;
    // Require base relocations: `IMAGE_FILE_RELOCS_STRIPPED` (0x0001)
    // means the PE can only be loaded at its preferred base,
    // which would collide with the parent.
    if (parsed.file.characteristics & 0x0001) != 0
        && parsed.optional.image_base == state.processes[&1].image_base
    {
        return None;
    }
    // Reserve the next child image base + heap arena.
    let child_image_base = state.next_child_image_base;
    if child_image_base == 0 {
        return None;
    }
    state.next_child_image_base = child_image_base.wrapping_add(crate::win32::CHILD_IMAGE_STRIDE);
    let heap_start = state.next_child_heap_base;
    let heap_end = heap_start.wrapping_add(crate::win32::CHILD_HEAP_SIZE);
    if heap_start == 0 || heap_end > state.child_heap_arena_end {
        return None;
    }
    state.next_child_heap_base = heap_end;
    // Map the child's sections at the target base.
    let secs = pe::sections::map_sections_at(mmu, &parsed, &bytes, child_image_base).ok()?;
    let delta = child_image_base.wrapping_sub(parsed.optional.image_base);
    if delta != 0 {
        pe::reloc::apply(mmu, &parsed, child_image_base, delta).ok()?;
    }
    // Strict import resolution — every import must be host-stubbed.
    pe::imports::resolve_strict(mmu, &parsed, child_image_base, registry).ok()?;
    // Stamp final permissions.
    for s in &secs {
        pe::sections::apply_section_permissions(mmu, s);
    }
    // Reserve a stack for the primary thread.
    let stack_top = state.cur_process().next_thread_stack_top;
    let stack_bottom = state.cur_process().thread_stack_pool_bottom;
    if stack_top == 0 || stack_top.saturating_sub(stack_bottom) < crate::win32::THREAD_STACK_SIZE {
        return None;
    }
    state.cur_process_mut().next_thread_stack_top = stack_top - crate::win32::THREAD_STACK_SIZE;
    // Reserve a TIB for the primary thread.
    let tib_addr = if state.cur_process().tib_pool_bottom != 0 {
        let addr = state.cur_process().next_tib_addr;
        state.cur_process_mut().next_tib_addr = addr.wrapping_add(crate::win32::THREAD_TIB_SIZE);
        let _ = mmu.store32(addr, 0xFFFF_FFFF);
        let _ = mmu.store32(addr + 0x18, addr);
        addr
    } else {
        0
    };
    // Mint child PID + TID + ProcessState.
    let parent_pid = state.cur_thread().pid;
    let child_pid = state.next_pid;
    state.next_pid = state.next_pid.wrapping_add(1);
    let child_tid = state.next_tid;
    state.next_tid = state.next_tid.wrapping_add(1);
    let entry_point = child_image_base.wrapping_add(parsed.optional.address_of_entry_point);
    let _ = Perm::R; // silence unused warning if not referenced
    let mut child_proc = crate::win32::ProcessState {
        pid: child_pid,
        parent_pid,
        image_base: child_image_base,
        primary_module_base: child_image_base,
        process_heap_handle: 0xDEAD_BEEF,
        next_hic: 1,
        rand_state: 1,
        heap_cursor: heap_start,
        heap_arena_end: heap_end,
        exit_code: None,
        ..crate::win32::ProcessState::default()
    };
    // Children inherit the parent's pools for thread stacks +
    // TIBs by default (the bootstrap pools have plenty of
    // room).
    child_proc.thread_stack_pool_bottom = stack_bottom;
    child_proc.next_thread_stack_top = state.cur_process().next_thread_stack_top;
    child_proc.tib_pool_bottom = state.cur_process().tib_pool_bottom;
    child_proc.next_tib_addr = state.cur_process().next_tib_addr;
    child_proc
        .modules
        .insert(target_path.to_ascii_lowercase(), child_image_base);
    if let Some(rsrc_dir) = parsed.optional.data_directories.get(2) {
        if rsrc_dir.virtual_address != 0 && rsrc_dir.size != 0 {
            child_proc.module_resource_dirs.insert(
                child_image_base,
                child_image_base.wrapping_add(rsrc_dir.virtual_address),
            );
        }
    }
    state.processes.insert(child_pid, child_proc);
    // Build the primary thread's CPU.
    let mut new_cpu = Cpu::new();
    new_cpu.regs.set_esp(stack_top - 0x10);
    new_cpu.regs.eip = entry_point;
    if tib_addr != 0 {
        new_cpu.set_fs_base(tib_addr);
    }
    // Children's entry points are stdcall void(void) for EXEs
    // (the CRT entry handles its own argv). Push a RET_SENTINEL
    // so a plain RET inside the entry routine surfaces "thread
    // done" to our run loop.
    new_cpu.push32(mmu, RET_SENTINEL).ok()?;
    let mut child_thread = crate::win32::ThreadState::new(child_tid, child_pid);
    child_thread.parked_cpu = Some(new_cpu);
    child_thread.tib_addr = tib_addr;
    child_thread.status = ThreadStatus::Ready;
    state.threads.insert(child_tid, child_thread);
    state
        .debug_log
        .push(format!("spawned child PE {target_path:?} (cmd={cmd:?}) pid={child_pid} base={child_image_base:#010x}"));
    Some((child_pid, child_tid))
}

/// Phase 5b/c semantics: every `CreateProcessA` call succeeds.
/// Phase 5c: when the target EXE is staged in the VFS and its
/// imports are all satisfied by the host stub registry,
/// [`try_spawn_child_pe`] loads it at a fresh image base and
/// mints a real `Ready` primary thread the scheduler will run
/// alongside the parent. Otherwise the child is a synthetic
/// ProcessState pre-marked `Terminated` with exit code 0 (the
/// fall-through path that keeps installer-class binaries
/// moving past their msiexec invocation when no real msiexec
/// is staged).
///
/// `WaitForSingleObject` on the returned process handle blocks
/// until the child's exit_code is set (or returns immediately
/// for the synthetic path); `GetExitCodeProcess` reports the
/// recorded exit code.
fn stub_create_process_a(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    registry: &Registry,
) -> Result<u32, Win32Error> {
    use crate::sched::{ThreadStatus, WaitObject};
    let p_app = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("CreateProcessA", t))?;
    let p_cmd = arg_dword(cpu, mmu, 1).map_err(|t| trap_to_win32("CreateProcessA", t))?;
    let _attrs_p = arg_dword(cpu, mmu, 2).map_err(|t| trap_to_win32("CreateProcessA", t))?;
    let _attrs_t = arg_dword(cpu, mmu, 3).map_err(|t| trap_to_win32("CreateProcessA", t))?;
    let _inh = arg_dword(cpu, mmu, 4).map_err(|t| trap_to_win32("CreateProcessA", t))?;
    let _flags = arg_dword(cpu, mmu, 5).map_err(|t| trap_to_win32("CreateProcessA", t))?;
    let _env = arg_dword(cpu, mmu, 6).map_err(|t| trap_to_win32("CreateProcessA", t))?;
    let _cwd = arg_dword(cpu, mmu, 7).map_err(|t| trap_to_win32("CreateProcessA", t))?;
    let _si = arg_dword(cpu, mmu, 8).map_err(|t| trap_to_win32("CreateProcessA", t))?;
    let pi = arg_dword(cpu, mmu, 9).map_err(|t| trap_to_win32("CreateProcessA", t))?;

    let app = if p_app != 0 {
        read_cstr(mmu, p_app, 260).unwrap_or_default()
    } else {
        String::new()
    };
    let cmd = if p_cmd != 0 {
        read_cstr(mmu, p_cmd, 4096).unwrap_or_default()
    } else {
        String::new()
    };
    state
        .debug_log
        .push(format!("CreateProcessA(app={app:?}, cmd={cmd:?})"));

    // Phase 5c: try to load the target EXE as a real child PE
    // from the VFS. Falls through to the synthetic path on
    // any failure (file missing, no relocations, unresolved
    // imports, …).
    let target = if !app.is_empty() {
        app.clone()
    } else if !cmd.is_empty() {
        // The first whitespace-delimited token of lpCommandLine
        // is the EXE path. Strip optional surrounding quotes.
        let first = cmd.split_whitespace().next().unwrap_or("");
        first.trim_matches('"').to_string()
    } else {
        String::new()
    };
    // Recognise the msiexec.exe install path before falling
    // through to PE-load. Real msiexec needs the full
    // Windows-Installer COM surface (huge), so we route to a
    // host-side walker that parses the .msi referenced by
    // `/i <path>` and synthesises file + registry effects into
    // the attached VFS / VirtualRegistry.
    if super::msiexec::is_msiexec_target(&target) {
        super::msiexec::dispatch_msiexec_install(state, mmu, &target, &cmd);
        // Then fall through to the synthetic immediate-exit
        // child so the parent's WaitForSingleObject /
        // GetExitCodeProcess resolves with ERROR_SUCCESS.
    }
    let (child_pid, child_tid) = match (!target.is_empty())
        .then(|| try_spawn_child_pe(state, mmu, registry, &target, &cmd))
        .flatten()
    {
        Some(pair) => pair,
        None => {
            state.debug_log.push(format!(
                "CreateProcessA: child {target:?} not loadable from VFS — \
                 falling back to synthetic immediate-exit"
            ));
            // Mint a synthetic, pre-Terminated child process.
            let parent_pid = state.cur_thread().pid;
            let pid = state.next_pid;
            state.next_pid = state.next_pid.wrapping_add(1);
            let tid = state.next_tid;
            state.next_tid = state.next_tid.wrapping_add(1);
            let child_proc = crate::win32::ProcessState {
                pid,
                parent_pid,
                exit_code: Some(0),
                ..crate::win32::ProcessState::default()
            };
            state.processes.insert(pid, child_proc);
            let mut child_thread = crate::win32::ThreadState::new(tid, pid);
            child_thread.status = ThreadStatus::Terminated;
            state.threads.insert(tid, child_thread);
            (pid, tid)
        }
    };
    let h_process = state
        .scheduler
        .insert_object(WaitObject::Process { pid: child_pid });
    let h_thread = state
        .scheduler
        .insert_object(WaitObject::Thread { tid: child_tid });

    if pi != 0 {
        // PROCESS_INFORMATION layout (winbase.h):
        //   HANDLE hProcess;        // +0x00
        //   HANDLE hThread;         // +0x04
        //   DWORD  dwProcessId;     // +0x08
        //   DWORD  dwThreadId;      // +0x0C
        mmu.store32(pi, h_process)
            .map_err(|t| trap_to_win32("CreateProcessA", t))?;
        mmu.store32(pi + 4, h_thread)
            .map_err(|t| trap_to_win32("CreateProcessA", t))?;
        mmu.store32(pi + 8, child_pid)
            .map_err(|t| trap_to_win32("CreateProcessA", t))?;
        mmu.store32(pi + 12, child_tid)
            .map_err(|t| trap_to_win32("CreateProcessA", t))?;
    }
    Ok(1)
}

/// `BOOL GetExitCodeProcess(HANDLE hProcess, LPDWORD lpExitCode)`.
/// Looks up the Process WaitObject behind the handle and
/// reports the process's recorded exit code, or
/// `STILL_ACTIVE = 259` while the process is still running.
fn stub_get_exit_code_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("GetExitCodeProcess", t))?;
    let p = arg_dword(cpu, mmu, 1).map_err(|t| trap_to_win32("GetExitCodeProcess", t))?;
    let code = match state.scheduler.objects.get(&h) {
        Some(crate::sched::WaitObject::Process { pid }) => state
            .processes
            .get(pid)
            .and_then(|proc| proc.exit_code)
            .unwrap_or(259),
        _ => 259,
    };
    if p != 0 {
        mmu.store32(p, code)
            .map_err(|t| trap_to_win32("GetExitCodeProcess", t))?;
    }
    Ok(1)
}

/// `UINT GetConsoleCP(void)` / `UINT GetConsoleOutputCP(void)`.
/// CP_OEMCP = 437 — the historical US OEM code page. Installers
/// only consult this to choose a banner-string encoding.
fn stub_get_console_cp(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    Ok(437)
}

/// `BOOL GetConsoleMode(HANDLE hConsoleHandle, LPDWORD lpMode)`.
/// No console attached — report failure so the caller's
/// "redirected to file" branch runs.
fn stub_get_console_mode(
    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("GetConsoleMode", t))?;
    let p = arg_dword(cpu, mmu, 1).map_err(|t| trap_to_win32("GetConsoleMode", t))?;
    if p != 0 {
        mmu.store32(p, 0)
            .map_err(|t| trap_to_win32("GetConsoleMode", t))?;
    }
    state.last_error = ERROR_INVALID_HANDLE;
    Ok(0)
}

/// `BOOL LocalFileTimeToFileTime(const FILETIME *lpLocalFileTime,
/// LPFILETIME lpFileTime)`. Single-timezone sandbox — copy the
/// 8-byte FILETIME through unchanged.
fn stub_local_file_time_to_file_time(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let p_src = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("LocalFileTimeToFileTime", t))?;
    let p_dst = arg_dword(cpu, mmu, 1).map_err(|t| trap_to_win32("LocalFileTimeToFileTime", t))?;
    if p_src == 0 || p_dst == 0 {
        return Ok(0);
    }
    let lo = mmu
        .load32(p_src)
        .map_err(|t| trap_to_win32("LocalFileTimeToFileTime", t))?;
    let hi = mmu
        .load32(p_src + 4)
        .map_err(|t| trap_to_win32("LocalFileTimeToFileTime", t))?;
    mmu.store32(p_dst, lo)
        .map_err(|t| trap_to_win32("LocalFileTimeToFileTime", t))?;
    mmu.store32(p_dst + 4, hi)
        .map_err(|t| trap_to_win32("LocalFileTimeToFileTime", t))?;
    Ok(1)
}

/// `BOOL RemoveDirectoryA(LPCSTR lpPathName)`. Drops the
/// directory marker from the VFS; success either way.
fn stub_remove_directory_a(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let p_name = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("RemoveDirectoryA", t))?;
    if p_name == 0 {
        state.last_error = ERROR_FILE_NOT_FOUND;
        return Ok(0);
    }
    let name = read_cstr(mmu, p_name, 260)?;
    let marker = format!("{}\\.dir", name.trim_end_matches(['\\', '/']));
    if let Some(vfs) = state.context.vfs.as_mut() {
        vfs.remove(&marker);
    }
    Ok(1)
}

/// `BOOL WriteConsoleW(HANDLE hConsoleOutput, const VOID *lpBuffer,
/// DWORD nNumberOfCharsToWrite, LPDWORD lpNumberOfCharsWritten,
/// LPVOID lpReserved)`. Captures the UTF-16 buffer into the
/// `debug_log` so the monitor's "what did the installer say?"
/// view picks it up. Reports the full count as written.
fn stub_write_console_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("WriteConsoleW", t))?;
    let p_buf = arg_dword(cpu, mmu, 1).map_err(|t| trap_to_win32("WriteConsoleW", t))?;
    let n_chars = arg_dword(cpu, mmu, 2).map_err(|t| trap_to_win32("WriteConsoleW", t))?;
    let lp_written = arg_dword(cpu, mmu, 3).map_err(|t| trap_to_win32("WriteConsoleW", t))?;
    let _resv = arg_dword(cpu, mmu, 4).map_err(|t| trap_to_win32("WriteConsoleW", t))?;
    if p_buf != 0 && n_chars > 0 {
        let cap = (n_chars as usize).min(4096);
        let mut units = Vec::with_capacity(cap);
        for i in 0..cap {
            units.push(
                mmu.load16(p_buf + (i as u32) * 2)
                    .map_err(|t| trap_to_win32("WriteConsoleW", t))?,
            );
        }
        let s = String::from_utf16_lossy(&units);
        state.debug_log.push(s);
    }
    if lp_written != 0 {
        mmu.store32(lp_written, n_chars)
            .map_err(|t| trap_to_win32("WriteConsoleW", t))?;
    }
    Ok(1)
}

/// `BOOL DuplicateHandle(HANDLE hSourceProcessHandle,
/// HANDLE hSourceHandle, HANDLE hTargetProcessHandle,
/// LPHANDLE lpTargetHandle, DWORD dwDesiredAccess,
/// BOOL bInheritHandle, DWORD dwOptions)`. Writes the source
/// handle through `lpTargetHandle` (no actual cross-process
/// duplication; the shared-MMU model has each handle visible
/// to every process anyway) and returns TRUE.
fn stub_duplicate_handle(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let _sp = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("DuplicateHandle", t))?;
    let h_src = arg_dword(cpu, mmu, 1).map_err(|t| trap_to_win32("DuplicateHandle", t))?;
    let _tp = arg_dword(cpu, mmu, 2).map_err(|t| trap_to_win32("DuplicateHandle", t))?;
    let p_tgt = arg_dword(cpu, mmu, 3).map_err(|t| trap_to_win32("DuplicateHandle", t))?;
    if p_tgt != 0 {
        mmu.store32(p_tgt, h_src)
            .map_err(|t| trap_to_win32("DuplicateHandle", t))?;
    }
    Ok(1)
}

/// `HANDLE OpenEventA(DWORD dwDesiredAccess, BOOL bInheritHandle,
/// LPCSTR lpName)`. Looks up the named-object registry; if a
/// sibling thread created an event with this name the
/// existing handle is returned so they share the kernel
/// object. Otherwise mints a fresh auto-reset Event
/// pre-signaled (so an admin.exe-style child whose parent
/// hasn't actually staged the event still resolves and
/// proceeds, rather than blocking forever on a wait that
/// will never fire). The name is logged either way for
/// monitor visibility.
fn stub_open_event_a(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let _access = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("OpenEventA", t))?;
    let _inherit = arg_dword(cpu, mmu, 1).map_err(|t| trap_to_win32("OpenEventA", t))?;
    let p_name = arg_dword(cpu, mmu, 2).map_err(|t| trap_to_win32("OpenEventA", t))?;
    let name = if p_name != 0 {
        read_cstr(mmu, p_name, 260).unwrap_or_default()
    } else {
        String::new()
    };
    open_event_by_name(state, &name)
}

/// Recognise `\\.\pipe\<name>` (in either Win32 backslash or
/// forward-slash form) and return the canonical pipe name —
/// the key the named-object registry indexes named pipes
/// under. Returns `None` for non-pipe paths so the caller
/// falls through to the VFS open path.
fn parse_pipe_client_path(s: &str) -> Option<String> {
    let lower = s.to_ascii_lowercase().replace('\\', "/");
    let stripped = lower.strip_prefix("//./pipe/")?;
    Some(stripped.to_string())
}

/// `HANDLE CreateNamedPipeA(LPCSTR lpName, DWORD dwOpenMode,
/// DWORD dwPipeMode, DWORD nMaxInstances, DWORD nOutBufferSize,
/// DWORD nInBufferSize, DWORD nDefaultTimeOut,
/// LPSECURITY_ATTRIBUTES)`. Mints a fresh pipe buffer and
/// registers the server end's handle under
/// `\\.\pipe\<name>`'s canonical key so a client
/// `CreateFileA(\\.\pipe\<name>)` can attach the other end.
/// `dwOpenMode`'s `PIPE_ACCESS_INBOUND = 1` /
/// `PIPE_ACCESS_OUTBOUND = 2` axis selects which end the
/// server gets (default: duplex → server gets the read end).
fn stub_create_named_pipe_a(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let p_name = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("CreateNamedPipeA", t))?;
    let open_mode = arg_dword(cpu, mmu, 1).map_err(|t| trap_to_win32("CreateNamedPipeA", t))?;
    let _pipe_mode = arg_dword(cpu, mmu, 2).map_err(|t| trap_to_win32("CreateNamedPipeA", t))?;
    let _max = arg_dword(cpu, mmu, 3).map_err(|t| trap_to_win32("CreateNamedPipeA", t))?;
    let _out_size = arg_dword(cpu, mmu, 4).map_err(|t| trap_to_win32("CreateNamedPipeA", t))?;
    let _in_size = arg_dword(cpu, mmu, 5).map_err(|t| trap_to_win32("CreateNamedPipeA", t))?;
    let _timeout = arg_dword(cpu, mmu, 6).map_err(|t| trap_to_win32("CreateNamedPipeA", t))?;
    let _sa = arg_dword(cpu, mmu, 7).map_err(|t| trap_to_win32("CreateNamedPipeA", t))?;
    if p_name == 0 {
        state.last_error = 87; // ERROR_INVALID_PARAMETER
        return Ok(INVALID_HANDLE_VALUE);
    }
    let raw = read_cstr(mmu, p_name, 260)?;
    let Some(key) = parse_pipe_client_path(&raw) else {
        state.last_error = 87;
        return Ok(INVALID_HANDLE_VALUE);
    };
    // Server end: by default the read end (PIPE_ACCESS_DUPLEX
    // and PIPE_ACCESS_INBOUND both give the server the read
    // side). PIPE_ACCESS_OUTBOUND (= 2) flips it.
    const PIPE_ACCESS_OUTBOUND: u32 = 2;
    let server_is_read = (open_mode & PIPE_ACCESS_OUTBOUND) == 0;
    let pipe_id = state.scheduler.insert_pipe();
    let h = state
        .scheduler
        .insert_object(crate::sched::WaitObject::Pipe {
            pipe_id,
            is_read_end: server_is_read,
        });
    state.scheduler.register_named(&key, h);
    state
        .debug_log
        .push(format!("CreateNamedPipeA(name={raw:?})"));
    Ok(h)
}

/// `BOOL ConnectNamedPipe(HANDLE hNamedPipe, LPOVERLAPPED)`.
/// Returns TRUE when a client is already attached (we don't
/// model the not-yet-connected state — the buffer's existence
/// is enough). For overlapped (`lpOverlapped != NULL`),
/// returns FALSE with `ERROR_PIPE_CONNECTED = 535` indicating
/// the client is already attached.
fn stub_connect_named_pipe(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    state.last_error = 535; // ERROR_PIPE_CONNECTED
    Ok(1)
}

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

/// `BOOL CreatePipe(PHANDLE hReadPipe, PHANDLE hWritePipe,
/// LPSECURITY_ATTRIBUTES, DWORD nSize)`. Mints a fresh
/// in-memory pipe buffer and returns a paired read + write
/// `WaitObject::Pipe` handle. Both handles reference the
/// same underlying [`crate::sched::PipeBuffer`].
fn stub_create_pipe(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let p_read = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("CreatePipe", t))?;
    let p_write = arg_dword(cpu, mmu, 1).map_err(|t| trap_to_win32("CreatePipe", t))?;
    let _attrs = arg_dword(cpu, mmu, 2).map_err(|t| trap_to_win32("CreatePipe", t))?;
    let _size = arg_dword(cpu, mmu, 3).map_err(|t| trap_to_win32("CreatePipe", t))?;
    if p_read == 0 || p_write == 0 {
        state.last_error = 87; // ERROR_INVALID_PARAMETER
        return Ok(0);
    }
    let pipe_id = state.scheduler.insert_pipe();
    let h_read = state
        .scheduler
        .insert_object(crate::sched::WaitObject::Pipe {
            pipe_id,
            is_read_end: true,
        });
    let h_write = state
        .scheduler
        .insert_object(crate::sched::WaitObject::Pipe {
            pipe_id,
            is_read_end: false,
        });
    mmu.store32(p_read, h_read)
        .map_err(|t| trap_to_win32("CreatePipe", t))?;
    mmu.store32(p_write, h_write)
        .map_err(|t| trap_to_win32("CreatePipe", t))?;
    Ok(1)
}

/// UTF-16 twin of [`stub_open_event_a`].
fn stub_open_event_w(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let _access = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("OpenEventW", t))?;
    let _inherit = arg_dword(cpu, mmu, 1).map_err(|t| trap_to_win32("OpenEventW", t))?;
    let p_name = arg_dword(cpu, mmu, 2).map_err(|t| trap_to_win32("OpenEventW", t))?;
    let name = if p_name != 0 {
        super::read_wide_cstr_local(mmu, p_name, 260)
    } else {
        String::new()
    };
    open_event_by_name(state, &name)
}

/// Shared implementation: look the name up in the
/// named-object registry; if present return the existing
/// handle, otherwise mint a fresh pre-signaled auto-reset
/// Event and register it.
fn open_event_by_name(state: &mut HostState, name: &str) -> Result<u32, Win32Error> {
    state.debug_log.push(format!("OpenEvent(name={name:?})"));
    if !name.is_empty() {
        if let Some(h) = state.scheduler.lookup_named(name) {
            return Ok(h);
        }
    }
    let h = state
        .scheduler
        .insert_object(crate::sched::WaitObject::Event {
            signaled: true,
            manual_reset: false,
        });
    if !name.is_empty() {
        state.scheduler.register_named(name, h);
    }
    Ok(h)
}

/// `HANDLE OpenProcess(DWORD dwDesiredAccess, BOOL bInheritHandle,
/// DWORD dwProcessId)`. Looks up the PID in the process table;
/// returns the existing Process WaitObject handle if found, or
/// a fresh one minted on the fly. Failure returns NULL.
fn stub_open_process(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let _access = arg_dword(cpu, mmu, 0).map_err(|t| trap_to_win32("OpenProcess", t))?;
    let _inherit = arg_dword(cpu, mmu, 1).map_err(|t| trap_to_win32("OpenProcess", t))?;
    let pid = arg_dword(cpu, mmu, 2).map_err(|t| trap_to_win32("OpenProcess", t))?;
    if !state.processes.contains_key(&pid) {
        state.last_error = 87; // ERROR_INVALID_PARAMETER
        return Ok(0);
    }
    // Re-use an existing Process handle for the PID if one
    // exists; otherwise mint a fresh one.
    for (h, obj) in &state.scheduler.objects {
        if let crate::sched::WaitObject::Process { pid: p } = obj {
            if *p == pid {
                return Ok(*h);
            }
        }
    }
    Ok(state
        .scheduler
        .insert_object(crate::sched::WaitObject::Process { pid }))
}

#[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);
    }

    /// `VirtualProtect` must actually update the MMU page
    /// permissions. The previous version only returned success
    /// + a canned old-protection value, which caused
    /// `wmvdecod.dll` / `wmvsdecd.dll` / CamStudio's DllMain to
    /// fault on a self-patch into `.text` — they call
    /// `VirtualProtect(.text, _, PAGE_READWRITE)`, write a
    /// thunk, then flip back.
    #[test]
    fn virtual_protect_flips_text_page_to_writable_and_back() {
        let (mut cpu, mut mmu, registry, mut state) = make_env();
        // Mark a fake "code" page as R+X (mirrors how the PE
        // loader stamps a real .text section).
        let code = 0x20000u32;
        mmu.map(code, 0x1000, Perm::R | Perm::X);
        assert_eq!(mmu.perm_at(code), Some(Perm::R | Perm::X));

        // Out-param for old-protection.
        mmu.map(0x30000, 0x1000, Perm::R | Perm::W);
        let old_out = 0x30000u32;

        // Flip code → PAGE_READWRITE (0x04).
        push_args_and_call(
            &mut cpu,
            &mut mmu,
            &registry,
            &mut state,
            "kernel32.dll",
            "VirtualProtect",
            &[code, 0x100, 0x04, old_out],
        )
        .unwrap();
        assert_eq!(cpu.regs.get32(Reg32::Eax), 1, "should return TRUE");
        assert_eq!(mmu.perm_at(code), Some(Perm::R | Perm::W));
        // Old protection should encode the prior R+X state =
        // PAGE_EXECUTE_READ (0x20).
        assert_eq!(mmu.load32(old_out).unwrap(), 0x20);

        // Now the codec writes through the page — must not trap.
        mmu.store32(code, 0xDEAD_BEEF).expect("writable after flip");

        // Flip back to PAGE_EXECUTE_READ (0x20).
        push_args_and_call(
            &mut cpu,
            &mut mmu,
            &registry,
            &mut state,
            "kernel32.dll",
            "VirtualProtect",
            &[code, 0x100, 0x20, old_out],
        )
        .unwrap();
        assert_eq!(cpu.regs.get32(Reg32::Eax), 1);
        assert_eq!(mmu.perm_at(code), Some(Perm::R | Perm::X));
        // Old protection now reports PAGE_READWRITE (0x04).
        assert_eq!(mmu.load32(old_out).unwrap(), 0x04);

        // Bytes survive the flip-write-flip round-trip.
        assert_eq!(mmu.load32(code).unwrap(), 0xDEAD_BEEF);
    }

    /// `VirtualProtect` on an unmapped address must fail
    /// (`MSDN`: returns FALSE if any page in the range isn't
    /// committed).
    #[test]
    fn virtual_protect_rejects_unmapped_address() {
        let (mut cpu, mut mmu, registry, mut state) = make_env();
        // Out-param scratch.
        mmu.map(0x30000, 0x1000, Perm::R | Perm::W);
        push_args_and_call(
            &mut cpu,
            &mut mmu,
            &registry,
            &mut state,
            "kernel32.dll",
            "VirtualProtect",
            &[0x5000_0000, 0x100, 0x04, 0x30000],
        )
        .unwrap();
        assert_eq!(cpu.regs.get32(Reg32::Eax), 0, "should return FALSE");
    }

    /// Phase 2 of the scheduler refactor: `TlsAlloc` returns
    /// distinct process-scoped slot indices, and `TlsSetValue` /
    /// `TlsGetValue` round-trip a value through the current
    /// thread's `tls_slots` map.
    #[test]
    fn tls_alloc_set_get_value_round_trip() {
        let (mut cpu, mut mmu, registry, mut state) = make_env();
        // First TlsAlloc mints slot 0.
        push_args_and_call(
            &mut cpu,
            &mut mmu,
            &registry,
            &mut state,
            "kernel32.dll",
            "TlsAlloc",
            &[],
        )
        .unwrap();
        let slot = cpu.regs.get32(Reg32::Eax);
        // Second TlsAlloc mints slot 1 — the cursor is sticky.
        push_args_and_call(
            &mut cpu,
            &mut mmu,
            &registry,
            &mut state,
            "kernel32.dll",
            "TlsAlloc",
            &[],
        )
        .unwrap();
        assert_eq!(cpu.regs.get32(Reg32::Eax), slot + 1);

        // Fresh slot reads back zero.
        push_args_and_call(
            &mut cpu,
            &mut mmu,
            &registry,
            &mut state,
            "kernel32.dll",
            "TlsGetValue",
            &[slot],
        )
        .unwrap();
        assert_eq!(cpu.regs.get32(Reg32::Eax), 0);

        // Set + get the value back.
        push_args_and_call(
            &mut cpu,
            &mut mmu,
            &registry,
            &mut state,
            "kernel32.dll",
            "TlsSetValue",
            &[slot, 0xDEAD_F00D],
        )
        .unwrap();
        assert_eq!(cpu.regs.get32(Reg32::Eax), 1);
        push_args_and_call(
            &mut cpu,
            &mut mmu,
            &registry,
            &mut state,
            "kernel32.dll",
            "TlsGetValue",
            &[slot],
        )
        .unwrap();
        assert_eq!(cpu.regs.get32(Reg32::Eax), 0xDEAD_F00D);
    }

    /// Phase 3a of the scheduler refactor: `Sleep(ms)` parks
    /// the active thread on a sleep wait, the run loop advances
    /// the global instruction clock past the wake target, and
    /// the thread comes back to Ready. With a single thread we
    /// observe this through state inspection rather than via a
    /// real context switch.
    #[test]
    fn sleep_records_a_wait_on_the_current_thread() {
        let (mut cpu, mut mmu, registry, mut state) = make_env();
        let before = state.scheduler.instructions_global;
        push_args_and_call(
            &mut cpu,
            &mut mmu,
            &registry,
            &mut state,
            "kernel32.dll",
            "Sleep",
            &[100],
        )
        .unwrap();
        // Sleep returns the placeholder 0; the real semantics
        // are observable via the yield request the stub left
        // for the run loop.
        let yr = state.yield_requested.clone().expect("yield was requested");
        match yr {
            crate::sched::YieldRequest::Wait(crate::sched::WaitCondition::Sleep {
                resume_after_instructions,
            }) => {
                assert_eq!(
                    resume_after_instructions,
                    before.saturating_add(100 * crate::sched::INSTRUCTIONS_PER_MS),
                );
            }
            other => panic!("expected Sleep wait, got {other:?}"),
        }
        // Tick mirrors the requested duration so GetTickCount
        // sees an advance.
        assert_eq!(state.tick, 100);
    }

    /// TLS slots are isolated per thread: a value set on the
    /// active thread is invisible after the scheduler switches
    /// `active_tid` to a different thread (single-process model).
    #[test]
    fn tls_value_is_isolated_per_thread() {
        let (mut cpu, mut mmu, registry, mut state) = make_env();
        // Mint a slot + set a value on the bootstrap thread.
        push_args_and_call(
            &mut cpu,
            &mut mmu,
            &registry,
            &mut state,
            "kernel32.dll",
            "TlsAlloc",
            &[],
        )
        .unwrap();
        let slot = cpu.regs.get32(Reg32::Eax);
        push_args_and_call(
            &mut cpu,
            &mut mmu,
            &registry,
            &mut state,
            "kernel32.dll",
            "TlsSetValue",
            &[slot, 0x1234],
        )
        .unwrap();

        // Inject a second thread + switch the scheduler to it.
        // (Phase 3 will add CreateThread for guests; here we
        // just exercise the state directly to verify the
        // isolation property.)
        state
            .threads
            .insert(2, crate::win32::ThreadState::new(2, 1));
        state.active_tid = 2;

        push_args_and_call(
            &mut cpu,
            &mut mmu,
            &registry,
            &mut state,
            "kernel32.dll",
            "TlsGetValue",
            &[slot],
        )
        .unwrap();
        assert_eq!(
            cpu.regs.get32(Reg32::Eax),
            0,
            "the second thread must see a fresh (zero) slot"
        );

        // Switch back: bootstrap thread still has its value.
        state.active_tid = 1;
        push_args_and_call(
            &mut cpu,
            &mut mmu,
            &registry,
            &mut state,
            "kernel32.dll",
            "TlsGetValue",
            &[slot],
        )
        .unwrap();
        assert_eq!(cpu.regs.get32(Reg32::Eax), 0x1234);
    }
}