ud-emulator 0.1.4

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
//! `msvcrt.dll` stubs — round-20 surface for the MSMPEG4 v3
//! VfW decoder (`mpg4c32.dll`) and its DirectShow siblings.
//!
//! Every codec compiled with MSVC after 1996 imports a small
//! collection of CRT init / heap / C++-ABI symbols from the
//! Microsoft VC redistributable. This module satisfies the
//! minimum subset Milestone 3.1 (docs/winmf/winmf-emulator.md
//! §"Milestone 3.1 — MS-MPEG-4 v3 unblock plan") flagged across
//! the four MSMPEG4-related binaries:
//!
//! * `??2@YAPAXI@Z` — `operator new(size_t)`. Returns
//!   `nullptr` on `size == 0` per the Itanium / MSVC C++ ABI.
//! * `??3@YAXPAX@Z` — `operator delete(void*)`. No-op on
//!   `nullptr`; otherwise wraps `HeapFree`.
//! * `_adjust_fdiv` — Pentium-FDIV-erratum runtime fix-up (a
//!   data symbol on real CRTs; we stub as a function that
//!   returns zero — codecs only `cmp [_adjust_fdiv], 0` in
//!   the math library, which never runs in our decode path).
//! * `_except_handler3` — MSVC SEH frame handler. Returns
//!   `EXCEPTION_CONTINUE_SEARCH = 1`; codecs only ever
//!   register it as the chain head and we don't propagate
//!   exceptions through SEH (see `kernel32!RtlUnwind`).
//! * `_initterm(start, end)` — CRT static initialiser
//!   thunk-table walker; calls each non-null
//!   `void(*)()` between `start` and `end`.
//! * `_purecall` — abstract-virtual-call sentinel; in
//!   release builds this is a no-op on entry.
//! * `malloc` / `free` — wrap the existing `HeapAlloc`
//!   arena.
//!
//! Every stub here is **cdecl** (caller-cleanup) so we
//! register them with `arg_dwords = 0`. See
//! [`super::dispatch_stub`] for the calling-convention
//! contract.
//!
//! Reference docs (clean-room — no Wine / ReactOS source):
//! * MSDN "C run-time library reference" — function
//!   contracts.
//! * Itanium C++ ABI §"Mangling" + Microsoft C++ name-
//!   mangling reference (the `??2`/`??3` decorated names).
//! * MSDN "Structured Exception Handling" — `_except_handler3`
//!   ABI.

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

/// Register every msvcrt stub.
pub fn register(registry: &mut Registry) {
    // Standard `msvcrt.dll`. The same stub set lands under
    // `msvcr71.dll` and `pncrt.dll` via [`register_alias`] —
    // codecs from the wmfdist11 era link msvcr71 (MSVC 7.1
    // runtime); RealNetworks codecs link `pncrt.dll`, their
    // bundled CRT fork. Both export the same names as
    // msvcrt for the C-library surface we care about.
    register_for_dll(registry, "msvcrt.dll");
}

/// Register the same CRT stub set under an alternate dll
/// name. Used to cover `msvcr71.dll` (MSVC 7.1, wmfdist11
/// codecs) and `pncrt.dll` (RealNetworks bundled CRT).
pub fn register_alias(registry: &mut Registry, dll: &str) {
    register_for_dll(registry, dll);
}

fn register_for_dll(registry: &mut Registry, dll: &str) {
    // C++ operator new(size_t) — the Microsoft mangled name.
    registry.register(dll, "??2@YAPAXI@Z", stub_operator_new as StubFn, 0);
    // C++ operator delete(void*) — Microsoft mangled name.
    registry.register(dll, "??3@YAXPAX@Z", stub_operator_delete as StubFn, 0);
    // CRT init — fdiv erratum / SEH / static-ctor table /
    // pure-virtual sentinel.
    //
    // `_adjust_fdiv` is a **data symbol**, not a function:
    // codecs read it as `mov reg, [iat]; mov reg, [reg]`
    // (the IAT slot is the *address* of a 4-byte int, not a
    // function pointer). Register a 4-byte data slot
    // initialised to 0 — meaning "no Pentium-FDIV fix-up
    // needed", which is true for any post-1996 CPU and our
    // synthesised Pentium II.
    registry.register_data(dll, "_adjust_fdiv", 0);
    registry.register(dll, "_except_handler3", stub_except_handler3 as StubFn, 0);
    registry.register(dll, "_initterm", stub_initterm as StubFn, 0);
    registry.register(dll, "_purecall", stub_purecall as StubFn, 0);
    // CRT exit-handler registry (atexit / DLL-onexit hooks). Real
    // CRTs append the pointer to a per-module list; we let the
    // codec register handlers, then never actually run them
    // (DLL_PROCESS_DETACH is not driven through our sandbox).
    // Both stubs return their first argument verbatim — the MSVC
    // contract: `_onexit` returns the registered pointer on
    // success or NULL on failure. Round 21 — surfaced by the
    // mpg4ds32.ax / wmvds32.ax DirectShow filters.
    registry.register(dll, "_onexit", stub_onexit as StubFn, 0);
    registry.register(dll, "__dllonexit", stub_dllonexit as StubFn, 0);
    // CRT formatted-string family. We support the headline
    // `sprintf(buf, fmt, ...)` form with `%s`, `%d`, `%u`, `%x`,
    // `%c`, `%p`, `%%`. Codec messages aren't user-visible so
    // the formatter doesn't need to match Microsoft's exact
    // padding / locale behaviour — just a faithful conversion.
    registry.register(dll, "sprintf", stub_sprintf as StubFn, 0);
    // C heap.
    registry.register(dll, "malloc", stub_malloc as StubFn, 0);
    registry.register(dll, "free", stub_free as StubFn, 0);

    // ---- Round-48 addition: msadds32.ax PE-load surface --------
    //
    // After r47 (gdi32!StretchDIBits) the splitter (`msadds32.ax`)
    // advances its msvcrt import-table walk to `_endthreadex` —
    // the CRT thread-teardown terminator.  The codec sandbox never
    // actually spawns the splitter's worker thread on the decode
    // path we drive (we only exercise `DLL_PROCESS_ATTACH` /
    // `DriverProc` / `IPin::ReceiveConnection`); the named import
    // just needs to resolve to a thunk before `Sandbox::load`
    // returns the [`Image`].
    //
    // https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/endthread-endthreadex
    // void __cdecl _endthreadex(unsigned retval) — caller-cleanup.
    registry.register(dll, "_endthreadex", stub_end_thread_ex as StubFn, 0);

    // ---- Round-49 addition: msadds32.ax PE-load surface --------
    //
    // After r48 (`_endthreadex`) the splitter advances its msvcrt
    // import-table walk to `_strnicmp`, the case-insensitive
    // bounded ASCII string compare.  Unlike `_endthreadex` (which
    // the splitter never actually invokes from the
    // PE-load / DLL_PROCESS_ATTACH path), `_strnicmp` IS called
    // during init for FOURCC / header-magic matching, so a stub
    // that returns 0 (== "every string compares equal") would let
    // the codec take a wrong branch and silently misbehave during
    // a later decode.  We implement the real semantics: ASCII
    // tolower on each byte, return `(b1 - b2) as i32` at the
    // first mismatch or terminator, NUL-terminating early on
    // either side.
    //
    // https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/strnicmp-wcsnicmp-mbsnicmp-strnicmp-l-wcsnicmp-l-mbsnicmp-l
    // int __cdecl _strnicmp(const char *string1,
    //                       const char *string2,
    //                       size_t count) — caller-cleanup.
    registry.register(dll, "_strnicmp", stub_strnicmp as StubFn, 0);

    // ---- Round-50 addition: msadds32.ax PE-load surface --------
    //
    // After r49 (`_strnicmp`) the splitter advances its msvcrt
    // import-table walk to `_beginthreadex`, the CRT entry that
    // creates an `__stdcall` worker thread.  The codec sandbox
    // NEVER actually spawns the splitter's worker thread on the
    // decode path we drive (we only exercise
    // `DLL_PROCESS_ATTACH` / `DriverProc` /
    // `IPin::ReceiveConnection`).  Combined with the r48
    // `_endthreadex` no-op stub, a fail-soft no-op
    // `_beginthreadex` returning 0 (== "thread creation failed",
    // a normal failure mode documented in MSDN) closes the entire
    // CRT thread-lifecycle surface for `msadds32.ax`'s PE-load.
    //
    // The IAT slot just needs to resolve before `Sandbox::load`
    // returns the [`Image`]; real call sites in the splitter's
    // init layer check the return for non-zero and either fall
    // back or skip (the splitter's worker thread is the render
    // loop, which we never drive).
    //
    // https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/beginthread-beginthreadex
    // uintptr_t __cdecl _beginthreadex(void *security,
    //                                  unsigned stack_size,
    //                                  unsigned (__stdcall *start_address)(void *),
    //                                  void *arglist,
    //                                  unsigned initflag,
    //                                  unsigned *thrdaddr)
    //                                                  — caller-cleanup.
    registry.register(dll, "_beginthreadex", stub_begin_thread_ex as StubFn, 0);

    // ---- Round-52 addition: msadds32.ax PE-load surface --------
    //
    // After r50 (`_beginthreadex`) the splitter advances its msvcrt
    // import-table walk to `_ftol` — the MSVC x87-to-i32 truncate
    // helper used by code compiled without `/QIfist`.  Unlike the
    // r48/r50 fail-soft no-op pair (`_endthreadex` / `_beginthreadex`),
    // `_ftol` is actively called from filter-coefficient init paths
    // and MUST be a real implementation: returning a constant 0 (or
    // a wrong-sign truncation) would scramble every conversion of
    // a precomputed float coefficient back to the i32 the splitter's
    // FIR loops expect.
    //
    // https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/ftol
    // long __cdecl _ftol(double)
    //
    // ABI: cdecl from the C source's perspective, but the IA-32
    // calling convention puts the `double` argument on the x87
    // stack (the caller emits `FLD qword ptr [arg]` before the
    // CALL).  The function pops `ST(0)`, truncates toward zero,
    // and returns the i32 in `eax`.  cdecl means caller-cleanup
    // on the regular cdecl stack — but in this special case the
    // caller didn't push any args there, so `arg_dwords = 0` is
    // correct.
    //
    // Saturation: outside the i32 representable range
    // (`[-2^31, 2^31 - 1]`) and on NaN, return `i32::MIN` (matches
    // the MSVC runtime's documented "indefinite integer" sentinel,
    // `0x8000_0000`).  Rust's `f64 as i32` already saturates per
    // 2018-edition semantics; we still range-check explicitly so
    // the NaN branch returns `i32::MIN` deterministically.
    registry.register(dll, "_ftol", stub_ftol as StubFn, 0);

    // ---- Round-55 addition: msadds32.ax PE-load surface --------
    //
    // After r52 (`_ftol`) the splitter's msvcrt import walk advances
    // to `msvcrt!rand` (and its seed companion `msvcrt!srand`).  Per
    // MSDN (`rand`, `srand`):
    //
    //   int   __cdecl rand(void)            — RAND_MAX = 0x7FFF.
    //   void  __cdecl srand(unsigned int seed)
    //
    // MSVC implements `rand` as a linear-congruential generator with
    // the standard Knuth-style parameters (multiplier 214013, increment
    // 2531011, mod 2^32), returning the middle 15 bits as the output:
    //
    //   state = state * 214013 + 2531011   (mod 2^32)
    //   rand  = (state >> 16) & 0x7FFF
    //
    // The multiplier / increment / output-bit mask are public number-
    // theory constants found in many textbook LCG tables; no Microsoft
    // CRT source was consulted.
    //
    // Wiring the seed at the [`HostState`] level (`HostState::rand_state`)
    // gives the host control over reproducibility: a `Sandbox` seeded
    // identically twice will produce identical `rand` sequences, which
    // matters for encode-regression tests, fuzzing, and bug repros.
    // The seed defaults to 1 (MSVC's documented "no `srand` called yet"
    // state).  The guest's own `srand(s)` call overwrites the same
    // field, so the host can observe what the codec did to the state
    // via [`crate::Sandbox::rand_seed`].
    //
    // Both stubs are cdecl: caller-cleanup, `arg_dwords = 0`.
    registry.register(dll, "rand", stub_rand as StubFn, 0);
    registry.register(dll, "srand", stub_srand as StubFn, 0);

    // ---- Round-56 addition: msadds32.ax PE-load surface --------
    //
    // After r55 (`rand` / `srand`) the splitter's msvcrt import walk
    // advances to MSVC's `_CI*` compiler-intrinsic math helpers.
    // These differ from regular `<math.h>` entries: the argument(s)
    // are passed on the **x87 stack** (not the cdecl integer stack),
    // and the result is returned on the x87 stack (top-of-stack).
    // The same calling-convention quirk applies as `_ftol`
    // (r52): `arg_dwords = 0` because no dwords are on the regular
    // cdecl stack to be cleaned up.
    //
    // For each helper the pattern is:
    //   1. Pop N f64s from the x87 stack in reverse order (so a
    //      2-arg `_CIpow(base, exp)` pops `exp` first then `base`).
    //   2. Compute the standard IEEE 754 / `<math.h>` result via
    //      Rust's `f64` intrinsics — these are bit-correct by
    //      construction (`f64::powf` / `f64::sqrt` / `f64::ln` etc.).
    //   3. Push the result back on the x87 stack.
    //   4. Return 0 in `eax` (the result is in `ST(0)`, not `eax`,
    //      per the documented MSVC `_CI*` convention).
    //
    // References (clean-room):
    //   * MSDN `pow`, `sqrt`, `log`, `log10`, `exp`, `sin`, `cos`,
    //     `tan`, `atan`, `atan2`, `fmod`, `asin`, `acos`, `sinh`,
    //     `cosh`, `tanh`, `floor`, `ceil` — function contracts.
    //   * Intel SDM Vol. 1 §8 + Vol. 2A "FLD" / "FSTP" — x87 stack
    //     semantics for the calling convention.
    //   * IEEE 754-2008 — corner cases (NaN propagation, ±∞, ±0).
    //
    // `_CIpow(base, exp)` — 2 args on x87.  Headline blocker after
    // r55.  Rust's `f64::powf` follows IEEE 754: `1.0_f64.powf(NaN)
    // = 1.0`, `0.0_f64.powf(0.0) = 1.0`, `(-1.0_f64).powf(0.5) =
    // NaN`, `f64::INFINITY.powf(0.0) = 1.0`.
    registry.register(dll, "_CIpow", stub_ci_pow as StubFn, 0);

    // ---- Corpus-driven additions ----------------------------------
    // Imports flagged ≥ 6× by `tests/codec_corpus.rs`. All cdecl.

    // void __security_error_handler(int code, void *data) —
    // MSVC 7.1 buffer-overrun reporter. We return 0; the
    // codec's CRT never actually invokes it on the happy path.
    registry.register(dll, "__security_error_handler", stub_purecall as StubFn, 0);
    // void __CppXcptFilter(unsigned long, _EXCEPTION_POINTERS*)
    // — MSVC C++ exception filter. `EXCEPTION_CONTINUE_SEARCH = 1`.
    registry.register(dll, "__CppXcptFilter", stub_except_handler3 as StubFn, 0);
    // int _XcptFilter(unsigned long xc, EXCEPTION_POINTERS *ptr) —
    // CRT exception filter used by `__try`/`__except` blocks.
    // Returns `EXCEPTION_CONTINUE_SEARCH`.
    registry.register(dll, "_XcptFilter", stub_except_handler3 as StubFn, 0);
    // void __cdecl _amsg_exit(int rterrnum) — CRT abort path on
    // runtime errors. We treat it like `_purecall` (no-op,
    // returns 0) since the codec's CRT only hits it on
    // unrecoverable conditions (stack overflow, etc.) we don't
    // synthesise.
    registry.register(dll, "_amsg_exit", stub_purecall as StubFn, 0);
    // void _lock(int locknum) / void _unlock(int locknum) —
    // CRT multi-threaded-mode internal locks. Single-threaded
    // emulator → no-op.
    registry.register(dll, "_lock", stub_purecall as StubFn, 0);
    registry.register(dll, "_unlock", stub_purecall as StubFn, 0);
    // void *memcpy(void *dest, const void *src, size_t n).
    registry.register(dll, "memcpy", stub_memcpy as StubFn, 0);
    // void *memset(void *dest, int c, size_t n).
    registry.register(dll, "memset", stub_memset as StubFn, 0);
    // void *memmove(void *dest, const void *src, size_t n).
    registry.register(dll, "memmove", stub_memmove as StubFn, 0);
    // char *strncpy(char *dest, const char *src, size_t n).
    registry.register(dll, "strncpy", stub_strncpy as StubFn, 0);
    // double _CIsqrt(double x) — x87-stack sqrt (FLD x on
    // entry, FSTP result on exit). Cdecl with no stack args.
    registry.register(dll, "_CIsqrt", stub_ci_sqrt as StubFn, 0);
    // int _vsnwprintf(wchar_t *s, size_t n, const wchar_t *fmt,
    //                 va_list arg) — wide-char snprintf.
    // Stub: write a single NUL and return 0.
    registry.register(dll, "_vsnwprintf", stub_vsnwprintf as StubFn, 0);
    // FILE *fopen(const char *path, const char *mode) — no
    // file system mapped, so always NULL.
    registry.register(dll, "fopen", stub_returns_zero as StubFn, 0);
    registry.register(dll, "_wfopen", stub_returns_zero as StubFn, 0);
    // int fclose(FILE *stream) — no-op success (0 == clean
    // close); codecs that pair fopen→fclose typically
    // short-circuit on the NULL fopen return anyway.
    registry.register(dll, "fclose", stub_purecall as StubFn, 0);
    // time_t time(time_t *t) — synthetic monotonic seconds
    // since 1970-01-01 derived from `state.tick`.
    registry.register(dll, "time", stub_time as StubFn, 0);
    // struct tm *localtime(const time_t *t) — points to a
    // shared global `tm` struct. We hand back a fixed canned
    // pointer into the const arena.
    registry.register(dll, "localtime", stub_localtime as StubFn, 0);
    // `_iob` is the data symbol for the CRT's array of 32
    // `FILE` slots (stdin/stdout/stderr/…). Register a
    // 4-byte data slot whose value is a small region in
    // the data-import arena — codecs that read
    // `_iob[2]` (stderr) just need a non-NULL FILE* they
    // can pass to fprintf/etc., which we ignore.
    registry.register_data(dll, "_iob", 0);

    // ---- Corpus round 2 -------------------------------------------
    // Additional CRT entries flagged by the corpus runner after
    // the first batch of stubs landed.
    // `_errno()` in the MSVC CRT is a *function* returning a
    // pointer to the (thread-local) errno cell. Pre-AVX-codec
    // versions of this stub registered it as a data import,
    // which made the PE loader stuff the data-slot address into
    // the IAT — and the codec's `call [iat]` then fetched from
    // the data region (R+W, no X) and tripped an execute-protect
    // fault. Register as a function instead; the stub lazily
    // allocates a single u32 cell in the heap arena and returns
    // its address on every call.
    registry.register(dll, "_errno", stub_errno as StubFn, 0);
    registry.register_data(dll, "__mb_cur_max", 1);
    registry.register(dll, "_write", stub_returns_arg2 as StubFn, 0);
    registry.register(dll, "asctime", stub_asctime as StubFn, 0);
    registry.register(dll, "fflush", stub_purecall as StubFn, 0);
    registry.register(dll, "fprintf", stub_purecall as StubFn, 0);
    registry.register(dll, "puts", stub_purecall as StubFn, 0);
    registry.register(dll, "printf", stub_purecall as StubFn, 0);
    registry.register(dll, "abort", stub_purecall as StubFn, 0);
    registry.register(dll, "_snprintf", stub_snprintf as StubFn, 0);
    registry.register(dll, "_putenv", stub_purecall as StubFn, 0);
    registry.register(dll, "_stricmp", stub_stricmp as StubFn, 0);
    registry.register(dll, "strchr", stub_strchr as StubFn, 0);
    registry.register(dll, "isupper", stub_isupper as StubFn, 0);
    registry.register(dll, "tolower", stub_tolower as StubFn, 0);
    registry.register(dll, "ceil", stub_ceil as StubFn, 0);
    registry.register(dll, "_CIcos", stub_ci_cos as StubFn, 0);
    registry.register(dll, "_CIsin", stub_ci_sin as StubFn, 0);
    registry.register(dll, "_CIlog", stub_ci_log as StubFn, 0);

    // ---- Corpus round 3 -------------------------------------------
    // CRT surface flagged by the HuffYUV / Lagarith / MagicYUV
    // probe. All cdecl (arg_dwords = 0 — the caller cleans up).
    // ctype — real ASCII classification.
    registry.register(dll, "isalnum", stub_isalnum as StubFn, 0);
    registry.register(dll, "isspace", stub_isspace as StubFn, 0);
    registry.register(dll, "iswctype", stub_iswctype as StubFn, 0);
    registry.register(dll, "toupper", stub_toupper as StubFn, 0);
    registry.register(dll, "towlower", stub_towlower as StubFn, 0);
    registry.register(dll, "towupper", stub_towupper as StubFn, 0);
    // memory.
    registry.register(dll, "memchr", stub_memchr as StubFn, 0);
    registry.register(dll, "memcmp", stub_memcmp as StubFn, 0);
    // narrow strings.
    registry.register(dll, "strcat", stub_strcat as StubFn, 0);
    registry.register(dll, "strcmp", stub_strcmp as StubFn, 0);
    registry.register(dll, "strcoll", stub_strcmp as StubFn, 0);
    registry.register(dll, "strlen", stub_strlen as StubFn, 0);
    registry.register(dll, "strncmp", stub_strncmp as StubFn, 0);
    registry.register(dll, "strrchr", stub_strrchr as StubFn, 0);
    registry.register(dll, "strxfrm", stub_strxfrm as StubFn, 0);
    registry.register(dll, "strerror", stub_strerror as StubFn, 0);
    registry.register(dll, "strftime", stub_strftime as StubFn, 0);
    registry.register(dll, "strtoul", stub_strtoul as StubFn, 0);
    registry.register(dll, "atoi", stub_atoi as StubFn, 0);
    // wide strings.
    registry.register(dll, "wcslen", stub_wcslen as StubFn, 0);
    registry.register(dll, "wcscoll", stub_wcscoll as StubFn, 0);
    registry.register(dll, "wcsxfrm", stub_wcsxfrm as StubFn, 0);
    registry.register(dll, "wcsftime", stub_wcsftime as StubFn, 0);
    // buffered I/O — discarded; report success.
    registry.register(dll, "fputc", stub_fputc as StubFn, 0);
    registry.register(dll, "fputs", stub_purecall as StubFn, 0);
    registry.register(dll, "fwrite", stub_fwrite as StubFn, 0);
    registry.register(dll, "vfprintf", stub_purecall as StubFn, 0);
    registry.register(dll, "setvbuf", stub_purecall as StubFn, 0);
    // heap.
    registry.register(dll, "calloc", stub_calloc as StubFn, 0);
    registry.register(dll, "realloc", stub_realloc as StubFn, 0);
    // environment / locale / filesystem.
    registry.register(dll, "getenv", stub_returns_zero as StubFn, 0);
    registry.register(dll, "localeconv", stub_localeconv as StubFn, 0);
    registry.register(dll, "setlocale", stub_setlocale as StubFn, 0);
    registry.register(dll, "_wmkdir", stub_purecall as StubFn, 0);

    // ---- Corpus round 4 -------------------------------------------
    // MSVC 8 / MSVC 9 CRT additions (camstudio-1.4 links msvcr80,
    // camstudio-1.5 links msvcr90). All cdecl (arg_dwords = 0).
    //
    // RTTI cleanup hook + debugger hook + encoded-null sentinel —
    // no observable behaviour required, returning 0 is fine.
    registry.register(
        dll,
        "__clean_type_info_names_internal",
        stub_returns_zero as StubFn,
        0,
    );
    registry.register(dll, "_crt_debugger_hook", stub_returns_zero as StubFn, 0);
    registry.register_data(dll, "_encoded_null", 0);
    // CRT-internal pointer obfuscation. The encode/decode pair
    // is required to be inverse, so the identity transform is a
    // valid implementation.
    registry.register(dll, "_encode_pointer", stub_returns_arg0 as StubFn, 0);
    registry.register(dll, "_decode_pointer", stub_returns_arg0 as StubFn, 0);
    // SEH handler — chain past us, same as `_except_handler3`.
    registry.register(
        dll,
        "_except_handler4_common",
        stub_except_handler3 as StubFn,
        0,
    );
    // `_initterm_e` is the error-reporting variant of `_initterm`.
    // Each entry returns `int`; if any returns non-zero, the
    // walker stops and reports that code. For the probe path we
    // walk like `_initterm` and report success.
    registry.register(dll, "_initterm_e", stub_initterm as StubFn, 0);
    // `_malloc_crt` is the CRT-private allocator alias.
    registry.register(dll, "_malloc_crt", stub_malloc as StubFn, 0);
    // Secure printf / scanf variants. The probe path doesn't
    // need real formatting — write an empty string + return 0.
    registry.register(dll, "sprintf_s", stub_sprintf_s as StubFn, 0);
    registry.register(dll, "sscanf", stub_returns_zero as StubFn, 0);
    registry.register(dll, "sscanf_s", stub_returns_zero as StubFn, 0);
}

/// Generic stub that returns the caller's first dword argument
/// unchanged — the identity transform for CRT helpers like
/// `_encode_pointer` / `_decode_pointer`.
fn stub_returns_arg0(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    arg_dword(cpu, mmu, 0).map_err(|t| trap("_encode_pointer/_decode_pointer", t))
}

/// `int sprintf_s(char *buf, size_t size, const char *fmt, ...)`.
/// cdecl. Writes an empty NUL-terminated string and reports 0
/// chars written — good enough for codec diagnostic paths the
/// probe never reaches.
fn stub_sprintf_s(
    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("sprintf_s", t))?;
    if buf != 0 {
        mmu.store8(buf, 0).map_err(|t| trap("sprintf_s", t))?;
    }
    Ok(0)
}

/// `void* operator new(size_t)` (Microsoft mangling
/// `??2@YAPAXI@Z`). cdecl. Per the C++ ABI, returns
/// `nullptr` on `size == 0` rather than the smallest legal
/// allocation — codecs sometimes test for that.
fn stub_operator_new(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let size = arg_dword(cpu, mmu, 0).map_err(|t| trap("operator new", t))?;
    if size == 0 {
        return Ok(0);
    }
    let addr = state.arena_alloc(size)?;
    let zeros = vec![0u8; size as usize];
    mmu.write_initializer(addr, &zeros)
        .map_err(|t| trap("operator new", t))?;
    Ok(addr)
}

/// `void operator delete(void*)` (Microsoft mangling
/// `??3@YAXPAX@Z`). cdecl. No-op on `nullptr`.
fn stub_operator_delete(
    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("operator delete", t))?;
    if p == 0 {
        return Ok(0);
    }
    // Best-effort: drop the heap entry if known. Unknown
    // pointers (e.g. C++ codec frees something allocated via
    // GlobalAlloc through a base-class destructor) are
    // tolerated silently — symmetrical to `kernel32!HeapFree`.
    let _ = state.heap.remove(&p);
    Ok(0)
}

/// `int _except_handler3(EXCEPTION_RECORD*, EXCEPTION_REGISTRATION*,
/// CONTEXT*, void*)`. cdecl. We never raise SEH exceptions
/// inside the sandbox so the handler is never actually called;
/// this stub exists only so the IAT slot resolves at PE-load
/// time. Returns `EXCEPTION_CONTINUE_SEARCH = 1` which is the
/// "chain past me" outcome SEH expects when a handler can't
/// service the exception.
fn stub_except_handler3(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    Ok(1)
}

/// `void _initterm(_PVFV* pfbegin, _PVFV* pfend)`. cdecl.
/// Walks `[pfbegin, pfend)` calling every non-null function
/// pointer it finds, in order. Used by the MSVC CRT to drive
/// global C++ static-ctor / static-dtor lists.
///
/// Each `_PVFV` is `void (__cdecl*)(void)` — no args, no
/// return value. We invoke each entry through
/// [`call_guest`] so any sub-stubs they call (`malloc`,
/// `_initterm` recursively, etc.) dispatch through the host
/// runtime cleanly.
fn stub_initterm(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    registry: &Registry,
) -> Result<u32, Win32Error> {
    let begin = arg_dword(cpu, mmu, 0).map_err(|t| trap("_initterm", t))?;
    let end = arg_dword(cpu, mmu, 1).map_err(|t| trap("_initterm", t))?;
    if begin == 0 || end == 0 || end <= begin {
        return Ok(0);
    }
    // Bounds: cap iteration at 4096 entries to defend against
    // a malformed table.
    let span = end.saturating_sub(begin);
    let count = (span / 4).min(4096);
    for i in 0..count {
        let slot = begin.wrapping_add(i * 4);
        let fnptr = match mmu.load32(slot) {
            Ok(v) => v,
            Err(_) => break,
        };
        if fnptr == 0 {
            continue;
        }
        // Re-enter the run loop on this thunk-or-real-fn.
        // Errors stop the walk but don't fail the stub —
        // mirrors MSDN's contract that `_initterm` doesn't
        // diagnose ctor failure (the failing ctor is supposed
        // to terminate the process itself if it cares).
        match call_guest(cpu, mmu, registry, state, fnptr, &[]) {
            Ok(_) => {}
            Err(crate::Error::Win32(e)) => return Err(e),
            Err(_) => break,
        }
    }
    Ok(0)
}

/// `void _purecall(void)`. cdecl. Pure-virtual sentinel; in
/// real CRTs this aborts. The decode path doesn't call any
/// pure-virtual function — the symbol is imported only so the
/// vtable layout for codec C++ classes can include the
/// "abort if a non-implemented virtual is called" trap.
fn stub_purecall(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    Ok(0)
}

/// `void* malloc(size_t)`. cdecl. Wraps the heap arena.
/// Returns 0 (NULL) on size == 0 to match Microsoft's CRT
/// (POSIX permits a unique pointer instead — the codec only
/// cares that NULL means "did not allocate").
fn stub_malloc(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let size = arg_dword(cpu, mmu, 0).map_err(|t| trap("malloc", t))?;
    if size == 0 {
        return Ok(0);
    }
    let addr = state.arena_alloc(size)?;
    let zeros = vec![0u8; size as usize];
    mmu.write_initializer(addr, &zeros)
        .map_err(|t| trap("malloc", t))?;
    Ok(addr)
}

/// `void free(void*)`. cdecl. No-op on NULL.
fn stub_free(
    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("free", t))?;
    if p == 0 {
        return Ok(0);
    }
    let _ = state.heap.remove(&p);
    Ok(0)
}

/// `_onexit_t _onexit(_onexit_t func)`. cdecl. Real CRT
/// appends `func` to a per-module list of process-exit
/// handlers. We never invoke `DLL_PROCESS_DETACH`, so the
/// handlers never run — recording them is unnecessary. Return
/// the input pointer on success per MSDN.
fn stub_onexit(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let func = arg_dword(cpu, mmu, 0).map_err(|t| trap("_onexit", t))?;
    Ok(func)
}

/// `int __dllonexit(_PVFV func, _PVFV** pbegin, _PVFV** pend)`.
/// cdecl. The MSVC CRT helper that powers `atexit` /
/// `_onexit` for DLLs. Same shortcut as
/// [`stub_onexit`] — record nothing, return success.
fn stub_dllonexit(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let func = arg_dword(cpu, mmu, 0).map_err(|t| trap("__dllonexit", t))?;
    Ok(func)
}

/// `int sprintf(char* buffer, const char* format, ...)`. cdecl
/// variadic. Implements the small subset of conversion specs
/// codec DLLs actually emit (debug / FOURCC / driver name
/// strings): `%s %d %u %x %X %c %p %%`. Width and precision
/// modifiers are accepted and applied with simple
/// space-padding. Returns the byte count (not including the
/// terminating NUL) on success.
fn stub_sprintf(
    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("sprintf", t))?;
    let fmt = arg_dword(cpu, mmu, 1).map_err(|t| trap("sprintf", t))?;
    let mut arg_idx: u32 = 2;
    let mut out: Vec<u8> = Vec::with_capacity(64);
    let mut p = fmt;
    loop {
        let b = mmu.load8(p).map_err(|t| trap("sprintf", t))?;
        if b == 0 {
            break;
        }
        p = p.wrapping_add(1);
        if b != b'%' {
            out.push(b);
            continue;
        }
        // Flags/width/precision parsing — we accept and drop
        // most of them; for `%s` we honour width via padding.
        let mut left_align = false;
        let mut zero_pad = false;
        let mut width: usize = 0;
        let mut precision: Option<usize> = None;
        // Flags
        loop {
            let c = mmu.load8(p).map_err(|t| trap("sprintf", t))?;
            match c {
                b'-' => {
                    left_align = true;
                    p = p.wrapping_add(1);
                }
                b'0' => {
                    zero_pad = true;
                    p = p.wrapping_add(1);
                }
                b'+' | b' ' | b'#' => {
                    p = p.wrapping_add(1);
                }
                _ => break,
            }
        }
        // Width
        loop {
            let c = mmu.load8(p).map_err(|t| trap("sprintf", t))?;
            if c.is_ascii_digit() {
                width = width.saturating_mul(10) + (c - b'0') as usize;
                p = p.wrapping_add(1);
            } else {
                break;
            }
        }
        // Precision
        let mut prec_seen = false;
        if mmu.load8(p).map_err(|t| trap("sprintf", t))? == b'.' {
            p = p.wrapping_add(1);
            prec_seen = true;
            let mut prec: usize = 0;
            loop {
                let c = mmu.load8(p).map_err(|t| trap("sprintf", t))?;
                if c.is_ascii_digit() {
                    prec = prec.saturating_mul(10) + (c - b'0') as usize;
                    p = p.wrapping_add(1);
                } else {
                    break;
                }
            }
            precision = Some(prec);
        }
        // Length modifiers we silently drop (`l`, `h`, `ll`,
        // `I32`, `I64`, …) — the codec only uses dword args.
        loop {
            let c = mmu.load8(p).map_err(|t| trap("sprintf", t))?;
            match c {
                b'l' | b'h' | b'L' | b'I' | b'j' | b'z' | b't' => p = p.wrapping_add(1),
                _ => break,
            }
        }
        let spec = mmu.load8(p).map_err(|t| trap("sprintf", t))?;
        p = p.wrapping_add(1);
        let _ = prec_seen;
        let formatted: Vec<u8> = match spec {
            b'%' => vec![b'%'],
            b's' => {
                let s_addr = arg_dword(cpu, mmu, arg_idx).map_err(|t| trap("sprintf", t))?;
                arg_idx += 1;
                let mut s = Vec::new();
                let mut q = s_addr;
                let limit = precision.unwrap_or(8192);
                for _ in 0..limit {
                    let c = mmu.load8(q).map_err(|t| trap("sprintf", t))?;
                    if c == 0 {
                        break;
                    }
                    s.push(c);
                    q = q.wrapping_add(1);
                }
                s
            }
            b'c' => {
                let v = arg_dword(cpu, mmu, arg_idx).map_err(|t| trap("sprintf", t))?;
                arg_idx += 1;
                vec![v as u8]
            }
            b'd' | b'i' => {
                let v = arg_dword(cpu, mmu, arg_idx).map_err(|t| trap("sprintf", t))? as i32;
                arg_idx += 1;
                format!("{v}").into_bytes()
            }
            b'u' => {
                let v = arg_dword(cpu, mmu, arg_idx).map_err(|t| trap("sprintf", t))?;
                arg_idx += 1;
                format!("{v}").into_bytes()
            }
            b'x' => {
                let v = arg_dword(cpu, mmu, arg_idx).map_err(|t| trap("sprintf", t))?;
                arg_idx += 1;
                format!("{v:x}").into_bytes()
            }
            b'X' => {
                let v = arg_dword(cpu, mmu, arg_idx).map_err(|t| trap("sprintf", t))?;
                arg_idx += 1;
                format!("{v:X}").into_bytes()
            }
            b'p' => {
                let v = arg_dword(cpu, mmu, arg_idx).map_err(|t| trap("sprintf", t))?;
                arg_idx += 1;
                format!("{v:08X}").into_bytes()
            }
            other => {
                // Unknown spec — emit the raw `%X` literal so the
                // text isn't silently lost.
                arg_idx += 1;
                vec![b'%', other]
            }
        };
        // Apply width padding.
        let pad = width.saturating_sub(formatted.len());
        if !left_align {
            let fill = if zero_pad { b'0' } else { b' ' };
            out.resize(out.len() + pad, fill);
        }
        out.extend_from_slice(&formatted);
        if left_align {
            out.resize(out.len() + pad, b' ');
        }
    }
    // NUL-terminate.
    out.push(0);
    // Write to guest buffer.
    for (i, byte) in out.iter().enumerate() {
        mmu.store8(buf.wrapping_add(i as u32), *byte)
            .map_err(|t| trap("sprintf", t))?;
    }
    Ok((out.len() as u32).saturating_sub(1))
}

/// `void __cdecl _endthreadex(unsigned retval)` — fail-soft.
///
/// Per MSDN (`_endthread`, `_endthreadex`): "Ends a thread; …
/// `_endthreadex` is more flexible … `retval` is the exit code
/// for the thread.  `_endthreadex` does not call `_endthread`
/// and does not close the thread handle".  Documented as
/// `__declspec(noreturn)`; in the real CRT control never returns
/// to the caller after `_endthreadex` runs.
///
/// The codec sandbox never spawns the splitter's worker thread
/// on the decode path we drive — we only exercise
/// `DLL_PROCESS_ATTACH` / `DriverProc` / `IPin::ReceiveConnection`.
/// The IAT slot just needs to resolve at PE-load time; if the
/// codec ever did reach `_endthreadex` we'd want to fall back to
/// the caller's return-address rather than terminate the host
/// process, so a no-op stub returning 0 (`eax` = `retval`'s
/// numeric width truncated to a `DWORD`, never actually
/// inspected by the codec since the documented contract says
/// the function doesn't return) is the natural fail-soft
/// shape.  cdecl: caller cleans up `retval`, so `arg_dwords = 0`.
fn stub_end_thread_ex(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    // Pull `retval` defensively so a stack-bounds trap surfaces
    // as a proper `Win32Error` rather than a silent under-read;
    // we don't actually surface it to the caller (the MSDN
    // contract is `__declspec(noreturn)`).
    let _retval = arg_dword(cpu, mmu, 0).map_err(|t| trap("_endthreadex", t))?;
    Ok(0)
}

/// `int __cdecl _strnicmp(const char *string1, const char *string2,
/// size_t count)` — case-insensitive ASCII bounded compare.
///
/// Per MSDN (`_strnicmp, _wcsnicmp, _mbsnicmp, _strnicmp_l,
/// _wcsnicmp_l, _mbsnicmp_l`): "Compares, at most, the first
/// `count` characters of two strings.  The comparison is not
/// case-sensitive."  Return value: `< 0` if `string1` is less
/// than `string2`, `0` if equal up to `count`, `> 0` if greater.
///
/// Calling convention: cdecl (caller-cleanup), 3 dwords on the
/// stack (`string1`, `string2`, `count`).  `arg_dwords = 0`.
///
/// Implementation contract:
///
/// * `count == 0` returns 0 (vacuously equal — MSDN explicit).
/// * Each byte is folded to lowercase by the ASCII rule
///   `b'A'..=b'Z' → +0x20`; bytes ≥ `0x80` are compared
///   byte-for-byte (no Unicode tolower).  This matches the
///   single-byte `_strnicmp` documented behaviour for the C
///   locale, which is the only locale the codec init path is
///   ever run under.
/// * Comparison terminates early at the first NUL on EITHER
///   string within `count` bytes; if both reach NUL at the same
///   index, the strings are equal (return 0).  The byte that
///   triggered the termination is included in the returned
///   difference (`b1 - b2`), so `"AVI\0"` vs `"AVIX"` returns a
///   negative value (NUL is less than `'X'`).
/// * Return value is a signed difference of unsigned bytes, cast
///   to `i32` and re-cast to `u32` so the dispatcher can place
///   it in `eax` (the codec re-interprets it as a signed `int`).
///
/// Fail-soft envelope:
///
/// * `count > 1 MiB` → return 0.  No legitimate FOURCC / header
///   compare exceeds a few dozen bytes; an absurdly large count
///   is almost certainly a fuzz-shaped argument or an
///   uninitialised stack slot, and "treat as equal" is the
///   safest non-panicking outcome.
/// * Either pointer reading out-of-bounds (MMU `MemoryFault` or
///   any other [`Trap`]) → return 0.  The MSDN contract has no
///   way to surface a fault back to the caller, and panicking
///   would tear down the host process; the alternative would be
///   to return `Err(Win32Error::InvalidArgument)`, which would
///   then propagate as a sandbox-side trap and abort the decode.
///   Fail-soft (== treat as equal) keeps the boundary case
///   tractable while a real error path is still emitted via
///   tracing.
fn stub_strnicmp(
    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("_strnicmp", t))?;
    let s2 = arg_dword(cpu, mmu, 1).map_err(|t| trap("_strnicmp", t))?;
    let count = arg_dword(cpu, mmu, 2).map_err(|t| trap("_strnicmp", t))?;

    // count == 0 → vacuously equal.
    if count == 0 {
        return Ok(0);
    }
    // Absurdly large `count` (more than 1 MiB) is almost
    // certainly fuzz-shaped or an uninitialised stack slot;
    // fail-soft to "equal" rather than panicking on the
    // unbounded loop.
    const MAX_COUNT: u32 = 1 << 20;
    if count > MAX_COUNT {
        return Ok(0);
    }

    fn ascii_tolower(b: u8) -> u8 {
        if b.is_ascii_uppercase() {
            b + 0x20
        } else {
            b
        }
    }

    for i in 0..count {
        let p1 = s1.wrapping_add(i);
        let p2 = s2.wrapping_add(i);
        // Bounds-check by trying the load; on any trap, fail-soft
        // (treat as equal).  Mirrors the MSDN-incompatible-but-
        // sandbox-safe envelope documented above.
        let b1 = match mmu.load8(p1) {
            Ok(v) => v,
            Err(_) => return Ok(0),
        };
        let b2 = match mmu.load8(p2) {
            Ok(v) => v,
            Err(_) => return Ok(0),
        };
        // NUL on EITHER side terminates the compare.  If both are
        // NUL at the same index, the difference is 0 → equal.
        // If only one side is NUL, the difference picks up the
        // sign correctly (NUL < any non-NUL byte).
        if b1 == 0 || b2 == 0 {
            let diff = (b1 as i32) - (b2 as i32);
            return Ok(diff as u32);
        }
        let l1 = ascii_tolower(b1);
        let l2 = ascii_tolower(b2);
        if l1 != l2 {
            let diff = (l1 as i32) - (l2 as i32);
            return Ok(diff as u32);
        }
    }
    // Reached `count` bytes with no NUL and no mismatch → equal.
    Ok(0)
}

/// `uintptr_t __cdecl _beginthreadex(void *security, unsigned
/// stack_size, unsigned (__stdcall *start_address)(void *), void
/// *arglist, unsigned initflag, unsigned *thrdaddr)` — fail-soft.
///
/// Per MSDN (`_beginthread, _beginthreadex`): "Creates a thread.
/// … Returns a handle to the newly created thread if successful;
/// otherwise, `_beginthreadex` returns 0 and sets `errno` to a
/// nonzero value".  The MSDN failure contract — return 0 — IS
/// the fail-soft shape we want: callers that respect the
/// documented "thread creation can fail" branch fall back or
/// skip the worker-thread codepath cleanly.
///
/// Calling convention: cdecl (caller-cleanup), 6 dwords on the
/// stack (`security`, `stack_size`, `start_address`, `arglist`,
/// `initflag`, `thrdaddr`).  `arg_dwords = 0`.
///
/// The codec sandbox never actually spawns the splitter's worker
/// thread on the decode path we drive — we only exercise
/// `DLL_PROCESS_ATTACH` / `DriverProc` /
/// `IPin::ReceiveConnection`; the IAT slot just needs to resolve
/// at PE-load time.  Combined with the r48 `_endthreadex` no-op
/// stub, this closes the entire CRT thread-lifecycle surface for
/// `msadds32.ax`'s PE-load.
///
/// Implementation contract:
///
/// * Returns 0 (NULL handle) — the MSDN "thread creation failed"
///   sentinel.  `start_address` is never invoked host-side.
/// * If `thrdaddr` is non-NULL and in-bounds, write 0 through it
///   so the caller's "did the OS assign a thread id" probe sees
///   a deterministic value.  If the store traps (OOB pointer),
///   silently swallow the trap and still return 0 — the MSDN
///   contract has no way to surface a fault back to the caller,
///   and panicking would tear down the host process.
fn stub_begin_thread_ex(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    // Pull all 6 cdecl dwords defensively so a stack-bounds trap
    // surfaces as a proper `Win32Error::InvalidArgument` rather
    // than a silent under-read.  Only `thrdaddr` is actually
    // consumed; the others are pulled for symmetry with the MSDN
    // signature and to keep the trace inventory complete.
    let _security = arg_dword(cpu, mmu, 0).map_err(|t| trap("_beginthreadex", t))?;
    let _stack_size = arg_dword(cpu, mmu, 1).map_err(|t| trap("_beginthreadex", t))?;
    let _start_address = arg_dword(cpu, mmu, 2).map_err(|t| trap("_beginthreadex", t))?;
    let _arglist = arg_dword(cpu, mmu, 3).map_err(|t| trap("_beginthreadex", t))?;
    let _initflag = arg_dword(cpu, mmu, 4).map_err(|t| trap("_beginthreadex", t))?;
    let thrdaddr = arg_dword(cpu, mmu, 5).map_err(|t| trap("_beginthreadex", t))?;

    // Optionally clear `*thrdaddr` to 0 — fail-soft on OOB
    // pointer (silently swallow the trap, still return 0).
    if thrdaddr != 0 {
        let _ = mmu.store32(thrdaddr, 0);
    }

    // Return 0 = MSDN "thread creation failed" sentinel.
    Ok(0)
}

/// `long __cdecl _ftol(double)` — MSVC's "convert double to long
/// (i32) with truncation toward zero" helper for code compiled
/// without `/QIfist`.
///
/// Per the MSVC ABI the `double` argument is passed on the x87
/// stack: the caller emits `FLD qword ptr [arg]` immediately before
/// the CALL, leaving the value as `ST(0)`.  `_ftol` then:
///
///  1. Reads `ST(0)`.
///  2. Truncates toward zero (i.e. `f64 as i32` semantics in Rust,
///     NOT `floor`).
///  3. Pops `ST(0)` off the x87 stack.
///  4. Returns the i32 in `eax`.
///
/// Saturation contract:
///
///  * `f.is_nan()`            → `i32::MIN` (the MSVC "indefinite
///    integer" sentinel, `0x8000_0000`).
///  * `f >= 2_147_483_648.0`  → `i32::MAX`.
///  * `f <= -2_147_483_649.0` → `i32::MIN`.
///  * Otherwise               → `f as i32` (truncation toward zero).
///
/// (Rust's `f64 as i32` already saturates the over/underflow cases
/// and maps NaN to 0 per RFC 3324, but we want the deterministic
/// `i32::MIN` sentinel for NaN since that matches the contract real
/// MSVC programs occasionally inspect; explicit range-check sorts
/// both concerns out.)
///
/// `cdecl` from the C source's perspective: caller-cleanup on the
/// regular cdecl stack, but the *argument* is on the x87 stack and
/// not on the regular stack at all — so `arg_dwords = 0` is the
/// right registration shape (no dwords to clean).
fn stub_ftol(
    cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    // Read ST(0) and pop the x87 stack.  The pop is mandatory:
    // codecs that follow the documented ABI rely on the post-call
    // stack depth being one less than the pre-call depth.
    let f = cpu.fpu.st(0);
    let _ = cpu.fpu.pop();

    // Truncate toward zero with saturation envelope.
    let v: i32 = if f.is_nan() {
        i32::MIN
    } else if f >= 2_147_483_648.0_f64 {
        i32::MAX
    } else if f <= -2_147_483_649.0_f64 {
        i32::MIN
    } else {
        // `f as i32` truncates toward zero in Rust 2018+ semantics.
        f as i32
    };
    Ok(v as u32)
}

/// `int __cdecl rand(void)` — MSVC-CRT-compatible LCG.
///
/// Per MSDN (`rand`): "The `rand` function returns a pseudorandom
/// integer in the range 0 to `RAND_MAX` (32767).  Use the `srand`
/// function to seed the pseudorandom-number generator before
/// calling `rand`."
///
/// MSVC implements `rand` with a Knuth-style linear-congruential
/// generator.  The multiplier / increment / output-bit mask are
/// public number-theory constants from countless LCG references;
/// no Microsoft CRT source was consulted:
///
/// ```text
/// state = state * 214013 + 2531011   (mod 2^32)
/// rand  = (state >> 16) & 0x7FFF      (the middle 15 bits)
/// ```
///
/// Seeding contract: the LCG state lives at
/// [`HostState::rand_state`].  Both this stub and `srand` write
/// the same field, so the host can seed the sandbox before
/// `Sandbox::load` for reproducible output, and the codec can
/// re-seed at any time via its own `srand` call.  Default state
/// is `1` — MSVC's documented "no `srand` called yet" initial
/// value.
///
/// cdecl: caller-cleanup, no args on the stack — `arg_dwords = 0`.
fn stub_rand(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    state.rand_state = state.rand_state.wrapping_mul(214013).wrapping_add(2531011);
    let r = (state.rand_state >> 16) & 0x7FFF;
    Ok(r)
}

/// `void __cdecl srand(unsigned int seed)` — seeds the MSVC LCG.
///
/// Per MSDN (`srand`): "Sets the starting seed value for the
/// pseudorandom number generator.  Subsequent calls to `rand` use
/// the new seed value to generate the sequence."  The MSVC
/// implementation stores `seed` directly into the LCG state
/// (no XOR / no scrambling) — a public, observable convention
/// derived from the documented "`rand` is a Knuth-LCG" contract,
/// no MS CRT source consulted.
///
/// Writing to [`HostState::rand_state`] keeps the host-side seed
/// API and the guest-side `srand` call on the same field — the
/// host can call [`crate::Sandbox::set_rand_seed`] to force a
/// known state before driving the codec, and the codec's own
/// `srand` will overwrite it.  Either way,
/// [`crate::Sandbox::rand_seed`] reports the current value.
///
/// cdecl: caller-cleanup, one dword on the stack —
/// `arg_dwords = 0`.  Returns 0 (void function; `eax` is
/// unspecified per the MSDN contract).
fn stub_srand(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let seed = arg_dword(cpu, mmu, 0).map_err(|t| trap("srand", t))?;
    state.rand_state = seed;
    Ok(0)
}

/// `double __cdecl _CIpow(double base, double exp)` — MSVC's
/// compiler-intrinsic `pow` helper.
///
/// Per the MSVC `_CI*` ABI, **both** arguments are passed on the
/// x87 stack rather than on the regular cdecl integer stack: the
/// caller emits `FLD qword ptr [base]; FLD qword ptr [exp]` before
/// the CALL, leaving `ST(0) = exp`, `ST(1) = base`.  The function:
///
///  1. Pops `ST(0)` (the exponent).
///  2. Pops `ST(0)` (the base; was originally `ST(1)`).
///  3. Computes `base.powf(exp)` per IEEE 754.
///  4. Pushes the result back onto the x87 stack as the new
///     `ST(0)`.
///  5. Returns 0 in `eax` — the result is in `ST(0)`, not `eax`,
///     per the documented `_CI*` convention.
///
/// IEEE 754 corner cases (Rust `f64::powf` is bit-correct by
/// construction):
///
///  * `0.0_f64.powf(0.0)               → 1.0`     (IEEE default)
///  * `f64::NAN.powf(anything)         → NaN`     (except `.powf(0.0) = 1.0`)
///  * `1.0_f64.powf(f64::NAN)          → 1.0`
///  * `f64::INFINITY.powf(0.0)         → 1.0`
///  * `(-2.0_f64).powf(0.5)            → NaN`     (negative real, non-int exp)
///
/// `cdecl` from the C source's perspective: caller-cleanup on the
/// regular cdecl stack, but both *arguments* are on the x87 stack
/// and not on the regular stack at all — so `arg_dwords = 0` is
/// the right registration shape (no dwords to clean).
fn stub_ci_pow(
    cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    // Per the x87 stack ordering: top-of-stack is the *last*
    // pushed value.  Caller emitted FLD base; FLD exp; so
    // ST(0) = exp and ST(1) = base.  Pop `exp` first.
    let exp = cpu.fpu.st(0);
    let _ = cpu.fpu.pop();
    let base = cpu.fpu.st(0);
    let _ = cpu.fpu.pop();
    let result = base.powf(exp);
    cpu.fpu.push(result);
    Ok(0)
}

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

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

/// `int *_errno(void)` — returns a pointer to the C-CRT errno
/// cell. Real MSVC keeps this in TLS; we keep a single
/// process-global u32 lazily allocated in the heap arena.
/// Subsequent calls return the same pointer (the MSVC contract).
fn stub_errno(
    _cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    if let Some(addr) = state.errno_cell {
        return Ok(addr);
    }
    let addr = state.arena_alloc(4)?;
    mmu.write_initializer(addr, &0u32.to_le_bytes())
        .map_err(|t| trap("_errno", t))?;
    state.errno_cell = Some(addr);
    Ok(addr)
}

/// Trivially returns 0. Used for stubs whose only contract is
/// "return without exploding" (e.g. unused CRT internals).
fn stub_returns_zero(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    Ok(0)
}

/// `void *memcpy(void *dest, const void *src, size_t n)`.
/// Reads `n` bytes from `src` and writes them to `dest`. Returns
/// `dest`. Cdecl.
fn stub_memcpy(
    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("memcpy", t))?;
    let src = arg_dword(cpu, mmu, 1).map_err(|t| trap("memcpy", t))?;
    let n = arg_dword(cpu, mmu, 2).map_err(|t| trap("memcpy", t))?;
    let data = mmu.read(src, n as usize).map_err(|t| trap("memcpy", t))?;
    mmu.write(dest, &data).map_err(|t| trap("memcpy", t))?;
    Ok(dest)
}

/// `void *memset(void *dest, int c, size_t n)`. Cdecl.
fn stub_memset(
    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("memset", t))?;
    let c = arg_dword(cpu, mmu, 1).map_err(|t| trap("memset", t))? as u8;
    let n = arg_dword(cpu, mmu, 2).map_err(|t| trap("memset", t))?;
    let buf = vec![c; n as usize];
    mmu.write(dest, &buf).map_err(|t| trap("memset", t))?;
    Ok(dest)
}

/// `void *memmove(void *dest, const void *src, size_t n)`.
/// Handles overlapping regions correctly. Cdecl.
fn stub_memmove(
    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("memmove", t))?;
    let src = arg_dword(cpu, mmu, 1).map_err(|t| trap("memmove", t))?;
    let n = arg_dword(cpu, mmu, 2).map_err(|t| trap("memmove", t))?;
    // Read everything first into a host buffer — that
    // takes care of the overlap case automatically.
    let data = mmu.read(src, n as usize).map_err(|t| trap("memmove", t))?;
    mmu.write(dest, &data).map_err(|t| trap("memmove", t))?;
    Ok(dest)
}

/// `char *strncpy(char *dest, const char *src, size_t n)`.
/// Writes up to `n` bytes from `src` to `dest`, NUL-padding
/// the remainder if `strlen(src) < n`. Returns `dest`. Cdecl.
fn stub_strncpy(
    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("strncpy", t))?;
    let src = arg_dword(cpu, mmu, 1).map_err(|t| trap("strncpy", t))?;
    let n = arg_dword(cpu, mmu, 2).map_err(|t| trap("strncpy", t))? as usize;
    let mut buf = vec![0u8; n];
    let mut hit_nul = false;
    for i in 0..n {
        if hit_nul {
            buf[i] = 0;
        } else {
            let b = mmu
                .load8(src.wrapping_add(i as u32))
                .map_err(|t| trap("strncpy", t))?;
            if b == 0 {
                hit_nul = true;
                buf[i] = 0;
            } else {
                buf[i] = b;
            }
        }
    }
    mmu.write(dest, &buf).map_err(|t| trap("strncpy", t))?;
    Ok(dest)
}

/// `double _CIsqrt(double)` — x87-stack square root. FLD x on
/// entry, FSTP result on exit. Cdecl, zero stack args.
fn stub_ci_sqrt(
    cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let x = cpu.fpu.st(0);
    let _ = cpu.fpu.pop();
    cpu.fpu.push(x.sqrt());
    Ok(0)
}

/// `int _vsnwprintf(wchar_t *s, size_t n, const wchar_t *fmt,
/// va_list arg)`. Stub: write a UTF-16 NUL terminator and
/// return 0. Codec build-info / debug-log strings flow through
/// this; an empty result is acceptable.
fn stub_vsnwprintf(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let s = arg_dword(cpu, mmu, 0).map_err(|t| trap("_vsnwprintf", t))?;
    let n = arg_dword(cpu, mmu, 1).map_err(|t| trap("_vsnwprintf", t))?;
    if s != 0 && n >= 1 {
        mmu.store16(s, 0).map_err(|t| trap("_vsnwprintf", t))?;
    }
    Ok(0)
}

/// `time_t time(time_t *t)`. Synthetic monotonic seconds-
/// since-1970 derived from `state.tick`. If `t` is non-NULL,
/// the value is also stored there.
fn stub_time(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    state.tick = state.tick.wrapping_add(1);
    // Anchor at 2024-01-01 00:00:00 UTC; bump by tick.
    let value = 1_704_067_200u32.wrapping_add(state.tick);
    let p = arg_dword(cpu, mmu, 0).map_err(|t| trap("time", t))?;
    if p != 0 {
        mmu.store32(p, value).map_err(|t| trap("time", t))?;
    }
    Ok(value)
}

/// `struct tm *localtime(const time_t *t)`. The C library
/// returns a pointer to a thread-local `tm` struct. We
/// allocate one in the heap arena the first time and reuse
/// it. Fields are zeroed (1970-01-01 epoch in 9-field tm
/// shape — `tm_sec, tm_min, tm_hour, tm_mday, tm_mon, tm_year,
/// tm_wday, tm_yday, tm_isdst`).
fn stub_localtime(
    _cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    // Use a fixed offset into the const arena. Reserve 36
    // bytes = 9 i32 fields.
    let p = state.arena_const_alloc(36)?;
    mmu.write_initializer(p, &[0u8; 36])
        .map_err(|t| trap("localtime", t))?;
    Ok(p)
}

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

/// Cdecl stub that returns the third argument verbatim. Used
/// for `_write(fd, buf, n)` — pretending the write succeeded.
fn stub_returns_arg2(
    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("_write", t))?;
    Ok(n)
}

/// `char *asctime(const struct tm *tp)`. Returns a 26-char
/// canned string in the const arena. Codecs that include the
/// build timestamp in a debug log use this; the exact format
/// doesn't matter for our purposes.
fn stub_asctime(
    _cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let p = state.arena_const_alloc(26)?;
    let canned = b"Mon Jan  1 00:00:00 2024\n\0";
    mmu.write_initializer(p, canned)
        .map_err(|t| trap("asctime", t))?;
    Ok(p)
}

/// `int _snprintf(char *buf, size_t n, const char *fmt, ...)`.
/// Stub: NUL-terminate the buffer and return 0.
fn stub_snprintf(
    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("_snprintf", t))?;
    let n = arg_dword(cpu, mmu, 1).map_err(|t| trap("_snprintf", t))?;
    if buf != 0 && n >= 1 {
        mmu.store8(buf, 0).map_err(|t| trap("_snprintf", t))?;
    }
    Ok(0)
}

/// `int _stricmp(const char *s1, const char *s2)`. Real ASCII
/// case-insensitive compare so codecs that gate on FOURCC
/// strings take the right branch.
fn stub_stricmp(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let p1 = arg_dword(cpu, mmu, 0).map_err(|t| trap("_stricmp", t))?;
    let p2 = arg_dword(cpu, mmu, 1).map_err(|t| trap("_stricmp", t))?;
    for i in 0..0x1_0000u32 {
        let a = mmu
            .load8(p1.wrapping_add(i))
            .map_err(|t| trap("_stricmp", t))?
            .to_ascii_lowercase();
        let b = mmu
            .load8(p2.wrapping_add(i))
            .map_err(|t| trap("_stricmp", t))?
            .to_ascii_lowercase();
        if a != b {
            return Ok((a as i32 - b as i32) as u32);
        }
        if a == 0 {
            return Ok(0);
        }
    }
    Ok(0)
}

/// `char *strchr(const char *s, int c)`. Scans `s` for the
/// first occurrence of `c`; returns its pointer or NULL.
fn stub_strchr(
    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("strchr", t))?;
    let needle = arg_dword(cpu, mmu, 1).map_err(|t| trap("strchr", t))? as u8;
    for i in 0..0x1_0000u32 {
        let b = mmu
            .load8(p.wrapping_add(i))
            .map_err(|t| trap("strchr", t))?;
        if b == needle {
            return Ok(p.wrapping_add(i));
        }
        if b == 0 {
            return Ok(0);
        }
    }
    Ok(0)
}

/// `int isupper(int c)`. Returns non-zero when `c` is an
/// uppercase ASCII letter. The CRT macro version reads a
/// per-character classification table; we just do the byte
/// test.
fn stub_isupper(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let c = arg_dword(cpu, mmu, 0).map_err(|t| trap("isupper", t))? as u8;
    Ok(u32::from(c.is_ascii_uppercase()))
}

/// `int tolower(int c)`. ASCII-only.
fn stub_tolower(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let c = arg_dword(cpu, mmu, 0).map_err(|t| trap("tolower", t))? as u8;
    Ok(u32::from(c.to_ascii_lowercase()))
}

/// `double ceil(double x)`. x87-stack — FLD on entry, FSTP
/// result on exit. Cdecl with no stack args.
fn stub_ceil(
    cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let x = cpu.fpu.st(0);
    let _ = cpu.fpu.pop();
    cpu.fpu.push(x.ceil());
    Ok(0)
}

/// `double _CIcos(double)` — x87-stack cosine.
fn stub_ci_cos(
    cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let x = cpu.fpu.st(0);
    let _ = cpu.fpu.pop();
    cpu.fpu.push(x.cos());
    Ok(0)
}

/// `double _CIsin(double)` — x87-stack sine.
fn stub_ci_sin(
    cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let x = cpu.fpu.st(0);
    let _ = cpu.fpu.pop();
    cpu.fpu.push(x.sin());
    Ok(0)
}

/// `double _CIlog(double)` — x87-stack natural log.
fn stub_ci_log(
    cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let x = cpu.fpu.st(0);
    let _ = cpu.fpu.pop();
    cpu.fpu.push(x.ln());
    Ok(0)
}

// ============================================================
// Corpus round 3 — CRT surface for HuffYUV / Lagarith / MagicYUV
// ============================================================

/// Scan bound for the in-stub C-string loops below.
const STR_SCAN_CAP: u32 = 0x1_0000;

/// `int isalnum(int c)` — ASCII alphanumeric test.
fn stub_isalnum(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let c = arg_dword(cpu, mmu, 0).map_err(|t| trap("isalnum", t))? as u8;
    Ok(u32::from(c.is_ascii_alphanumeric()))
}

/// `int isspace(int c)` — ASCII whitespace test.
fn stub_isspace(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let c = arg_dword(cpu, mmu, 0).map_err(|t| trap("isspace", t))? as u8;
    Ok(u32::from(c.is_ascii_whitespace()))
}

/// `int iswctype(wint_t c, wctype_t desc)`. The classification
/// mask is locale-specific; we report "not of that class" (0).
/// Codecs only reach this through CRT locale plumbing the
/// sandbox never exercises on the decode path.
fn stub_iswctype(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    Ok(0)
}

/// `int toupper(int c)` — ASCII upper-case.
fn stub_toupper(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let c = arg_dword(cpu, mmu, 0).map_err(|t| trap("toupper", t))?;
    Ok(u32::from((c as u8).to_ascii_uppercase()))
}

/// `wint_t towlower(wint_t c)` — ASCII-range lower-case; other
/// code points pass through unchanged.
fn stub_towlower(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let c = arg_dword(cpu, mmu, 0).map_err(|t| trap("towlower", t))?;
    Ok(if (b'A' as u32..=b'Z' as u32).contains(&c) {
        c + 32
    } else {
        c
    })
}

/// `wint_t towupper(wint_t c)` — ASCII-range upper-case.
fn stub_towupper(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let c = arg_dword(cpu, mmu, 0).map_err(|t| trap("towupper", t))?;
    Ok(if (b'a' as u32..=b'z' as u32).contains(&c) {
        c - 32
    } else {
        c
    })
}

/// `void *memchr(const void *buf, int c, size_t count)`.
fn stub_memchr(
    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("memchr", t))?;
    let c = arg_dword(cpu, mmu, 1).map_err(|t| trap("memchr", t))? as u8;
    let n = arg_dword(cpu, mmu, 2).map_err(|t| trap("memchr", t))?;
    for i in 0..n {
        if mmu
            .load8(buf.wrapping_add(i))
            .map_err(|t| trap("memchr", t))?
            == c
        {
            return Ok(buf.wrapping_add(i));
        }
    }
    Ok(0)
}

/// `int memcmp(const void *p1, const void *p2, size_t count)`.
fn stub_memcmp(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let p1 = arg_dword(cpu, mmu, 0).map_err(|t| trap("memcmp", t))?;
    let p2 = arg_dword(cpu, mmu, 1).map_err(|t| trap("memcmp", t))?;
    let n = arg_dword(cpu, mmu, 2).map_err(|t| trap("memcmp", t))?;
    for i in 0..n {
        let a = mmu
            .load8(p1.wrapping_add(i))
            .map_err(|t| trap("memcmp", t))?;
        let b = mmu
            .load8(p2.wrapping_add(i))
            .map_err(|t| trap("memcmp", t))?;
        if a != b {
            return Ok(if a < b { (-1i32) as u32 } else { 1 });
        }
    }
    Ok(0)
}

/// Read a NUL-terminated string from guest memory (bounded).
fn read_c(mmu: &Mmu, base: u32, stub: &'static str) -> Result<Vec<u8>, Win32Error> {
    let mut out = Vec::new();
    if base == 0 {
        return Ok(out);
    }
    for i in 0..STR_SCAN_CAP {
        let b = mmu.load8(base.wrapping_add(i)).map_err(|t| trap(stub, t))?;
        if b == 0 {
            break;
        }
        out.push(b);
    }
    Ok(out)
}

/// `char *strcat(char *dest, const char *src)`.
fn stub_strcat(
    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("strcat", t))?;
    let src = arg_dword(cpu, mmu, 1).map_err(|t| trap("strcat", t))?;
    let mut end = dest;
    let mut scanned = 0u32;
    while scanned < STR_SCAN_CAP && mmu.load8(end).map_err(|t| trap("strcat", t))? != 0 {
        end = end.wrapping_add(1);
        scanned += 1;
    }
    let mut bytes = read_c(mmu, src, "strcat")?;
    bytes.push(0);
    mmu.write(end, &bytes).map_err(|t| trap("strcat", t))?;
    Ok(dest)
}

/// `int strcmp(const char *s1, const char *s2)` — also wired as
/// `strcoll` (ordinal collation in the sandbox's "C" locale).
fn stub_strcmp(
    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("strcmp", t))?;
    let s2 = arg_dword(cpu, mmu, 1).map_err(|t| trap("strcmp", t))?;
    let a = read_c(mmu, s1, "strcmp")?;
    let b = read_c(mmu, s2, "strcmp")?;
    Ok(match a.cmp(&b) {
        std::cmp::Ordering::Less => (-1i32) as u32,
        std::cmp::Ordering::Equal => 0,
        std::cmp::Ordering::Greater => 1,
    })
}

/// `size_t strlen(const char *s)`.
fn stub_strlen(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let s = arg_dword(cpu, mmu, 0).map_err(|t| trap("strlen", t))?;
    Ok(read_c(mmu, s, "strlen")?.len() as u32)
}

/// `int strncmp(const char *s1, const char *s2, size_t n)`.
fn stub_strncmp(
    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("strncmp", t))?;
    let s2 = arg_dword(cpu, mmu, 1).map_err(|t| trap("strncmp", t))?;
    let n = arg_dword(cpu, mmu, 2).map_err(|t| trap("strncmp", t))?;
    for i in 0..n {
        let a = mmu
            .load8(s1.wrapping_add(i))
            .map_err(|t| trap("strncmp", t))?;
        let b = mmu
            .load8(s2.wrapping_add(i))
            .map_err(|t| trap("strncmp", t))?;
        if a != b {
            return Ok(if a < b { (-1i32) as u32 } else { 1 });
        }
        if a == 0 {
            break;
        }
    }
    Ok(0)
}

/// `char *strrchr(const char *s, int c)` — last occurrence.
fn stub_strrchr(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let s = arg_dword(cpu, mmu, 0).map_err(|t| trap("strrchr", t))?;
    let c = arg_dword(cpu, mmu, 1).map_err(|t| trap("strrchr", t))? as u8;
    let mut hit = 0u32;
    for i in 0..STR_SCAN_CAP {
        let b = mmu
            .load8(s.wrapping_add(i))
            .map_err(|t| trap("strrchr", t))?;
        if b == c {
            hit = s.wrapping_add(i);
        }
        if b == 0 {
            break;
        }
    }
    Ok(hit)
}

/// `size_t strxfrm(char *dest, const char *src, size_t n)`. In
/// the "C" locale the collation transform is the identity, so
/// this is a length-bounded copy. Returns `strlen(src)`.
fn stub_strxfrm(
    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("strxfrm", t))?;
    let src = arg_dword(cpu, mmu, 1).map_err(|t| trap("strxfrm", t))?;
    let n = arg_dword(cpu, mmu, 2).map_err(|t| trap("strxfrm", t))?;
    let bytes = read_c(mmu, src, "strxfrm")?;
    let src_len = bytes.len() as u32;
    if dest != 0 && n > 0 {
        let take = (n as usize - 1).min(bytes.len());
        let mut buf = bytes[..take].to_vec();
        buf.push(0);
        mmu.write(dest, &buf).map_err(|t| trap("strxfrm", t))?;
    }
    Ok(src_len)
}

/// `char *strerror(int errnum)`. Allocates a small guest buffer
/// holding a generic message and returns a pointer to it — a
/// non-NULL result is the contract a caller relies on.
fn stub_strerror(
    _cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let msg = b"Error\0";
    let addr = state.arena_alloc(msg.len() as u32)?;
    mmu.write_initializer(addr, msg)
        .map_err(|t| trap("strerror", t))?;
    Ok(addr)
}

/// `size_t strftime(char *dest, size_t maxsize, const char *fmt,
/// const struct tm *tm)`. Writes an empty string and reports a
/// length of 0 — codecs reach this only through diagnostic
/// paths the sandbox never surfaces.
fn stub_strftime(
    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("strftime", t))?;
    if dest != 0 {
        mmu.store8(dest, 0).map_err(|t| trap("strftime", t))?;
    }
    Ok(0)
}

/// Skip leading ASCII whitespace, returning the new offset.
fn skip_ws(bytes: &[u8], mut i: usize) -> usize {
    while i < bytes.len() && bytes[i].is_ascii_whitespace() {
        i += 1;
    }
    i
}

/// `unsigned long strtoul(const char *nptr, char **endptr,
/// int base)`. Supports base 0 (auto-detect `0x` / `0`) and any
/// explicit base 2..=36. Writes the parse-end pointer through
/// `endptr` when non-NULL.
fn stub_strtoul(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let nptr = arg_dword(cpu, mmu, 0).map_err(|t| trap("strtoul", t))?;
    let endptr = arg_dword(cpu, mmu, 1).map_err(|t| trap("strtoul", t))?;
    let mut base = arg_dword(cpu, mmu, 2).map_err(|t| trap("strtoul", t))?;
    let bytes = read_c(mmu, nptr, "strtoul")?;
    let mut i = skip_ws(&bytes, 0);
    let mut negate = false;
    if i < bytes.len() && (bytes[i] == b'+' || bytes[i] == b'-') {
        negate = bytes[i] == b'-';
        i += 1;
    }
    // Base 0 / 16 prefix handling.
    if (base == 0 || base == 16)
        && i + 1 < bytes.len()
        && bytes[i] == b'0'
        && (bytes[i + 1] | 0x20) == b'x'
    {
        i += 2;
        base = 16;
    } else if base == 0 && i < bytes.len() && bytes[i] == b'0' {
        base = 8;
    } else if base == 0 {
        base = 10;
    }
    let mut value: u32 = 0;
    while i < bytes.len() {
        let d = match bytes[i] {
            c @ b'0'..=b'9' => u32::from(c - b'0'),
            c @ b'a'..=b'z' => u32::from(c - b'a') + 10,
            c @ b'A'..=b'Z' => u32::from(c - b'A') + 10,
            _ => break,
        };
        if d >= base {
            break;
        }
        value = value.wrapping_mul(base).wrapping_add(d);
        i += 1;
    }
    if endptr != 0 {
        mmu.store32(endptr, nptr.wrapping_add(i as u32))
            .map_err(|t| trap("strtoul", t))?;
    }
    Ok(if negate { value.wrapping_neg() } else { value })
}

/// `int atoi(const char *nptr)`.
fn stub_atoi(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let nptr = arg_dword(cpu, mmu, 0).map_err(|t| trap("atoi", t))?;
    let bytes = read_c(mmu, nptr, "atoi")?;
    let mut i = skip_ws(&bytes, 0);
    let mut negate = false;
    if i < bytes.len() && (bytes[i] == b'+' || bytes[i] == b'-') {
        negate = bytes[i] == b'-';
        i += 1;
    }
    let mut value: i32 = 0;
    while i < bytes.len() && bytes[i].is_ascii_digit() {
        value = value
            .wrapping_mul(10)
            .wrapping_add(i32::from(bytes[i] - b'0'));
        i += 1;
    }
    Ok((if negate { -value } else { value }) as u32)
}

/// Read a NUL-terminated wide (UTF-16) string from guest memory.
fn read_w(mmu: &Mmu, base: u32, stub: &'static str) -> Result<Vec<u16>, Win32Error> {
    let mut out = Vec::new();
    if base == 0 {
        return Ok(out);
    }
    for i in 0..STR_SCAN_CAP {
        let c = mmu
            .load16(base.wrapping_add(i * 2))
            .map_err(|t| trap(stub, t))?;
        if c == 0 {
            break;
        }
        out.push(c);
    }
    Ok(out)
}

/// `size_t wcslen(const wchar_t *s)`.
fn stub_wcslen(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let s = arg_dword(cpu, mmu, 0).map_err(|t| trap("wcslen", t))?;
    Ok(read_w(mmu, s, "wcslen")?.len() as u32)
}

/// `int wcscoll(const wchar_t *s1, const wchar_t *s2)` — ordinal
/// wide compare.
fn stub_wcscoll(
    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("wcscoll", t))?;
    let s2 = arg_dword(cpu, mmu, 1).map_err(|t| trap("wcscoll", t))?;
    let a = read_w(mmu, s1, "wcscoll")?;
    let b = read_w(mmu, s2, "wcscoll")?;
    Ok(match a.cmp(&b) {
        std::cmp::Ordering::Less => (-1i32) as u32,
        std::cmp::Ordering::Equal => 0,
        std::cmp::Ordering::Greater => 1,
    })
}

/// `size_t wcsxfrm(wchar_t *dest, const wchar_t *src, size_t n)`.
/// Identity transform in the "C" locale — a length-bounded wide
/// copy returning `wcslen(src)`.
fn stub_wcsxfrm(
    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("wcsxfrm", t))?;
    let src = arg_dword(cpu, mmu, 1).map_err(|t| trap("wcsxfrm", t))?;
    let n = arg_dword(cpu, mmu, 2).map_err(|t| trap("wcsxfrm", t))?;
    let chars = read_w(mmu, src, "wcsxfrm")?;
    let src_len = chars.len() as u32;
    if dest != 0 && n > 0 {
        let take = (n as usize - 1).min(chars.len());
        for (i, c) in chars[..take].iter().enumerate() {
            mmu.store16(dest.wrapping_add(i as u32 * 2), *c)
                .map_err(|t| trap("wcsxfrm", t))?;
        }
        mmu.store16(dest.wrapping_add(take as u32 * 2), 0)
            .map_err(|t| trap("wcsxfrm", t))?;
    }
    Ok(src_len)
}

/// `size_t wcsftime(wchar_t *dest, size_t maxsize,
/// const wchar_t *fmt, const struct tm *tm)`. Writes an empty
/// wide string, reports length 0.
fn stub_wcsftime(
    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("wcsftime", t))?;
    if dest != 0 {
        mmu.store16(dest, 0).map_err(|t| trap("wcsftime", t))?;
    }
    Ok(0)
}

/// `int fputc(int c, FILE *stream)`. Output discarded; returns
/// `c` (the success contract).
fn stub_fputc(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    arg_dword(cpu, mmu, 0).map_err(|t| trap("fputc", t))
}

/// `size_t fwrite(const void *ptr, size_t size, size_t count,
/// FILE *stream)`. Output discarded; reports all `count`
/// elements written.
fn stub_fwrite(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    arg_dword(cpu, mmu, 2).map_err(|t| trap("fwrite", t))
}

/// `void *calloc(size_t num, size_t size)`. Zero-initialised
/// heap allocation.
fn stub_calloc(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let num = arg_dword(cpu, mmu, 0).map_err(|t| trap("calloc", t))?;
    let size = arg_dword(cpu, mmu, 1).map_err(|t| trap("calloc", t))?;
    let total = match num.checked_mul(size) {
        Some(0) | None => return Ok(0),
        Some(t) => t,
    };
    let addr = state.arena_alloc(total)?;
    mmu.write_initializer(addr, &vec![0u8; total as usize])
        .map_err(|t| trap("calloc", t))?;
    Ok(addr)
}

/// `void *realloc(void *ptr, size_t size)`. Allocates a fresh
/// block and copies the old contents across. The bump arena
/// never reclaims `ptr`, so the old block simply leaks — fine
/// for a bounded analysis run.
fn stub_realloc(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let ptr = arg_dword(cpu, mmu, 0).map_err(|t| trap("realloc", t))?;
    let size = arg_dword(cpu, mmu, 1).map_err(|t| trap("realloc", t))?;
    if size == 0 {
        let _ = state.heap.remove(&ptr);
        return Ok(0);
    }
    let addr = state.arena_alloc(size)?;
    mmu.write_initializer(addr, &vec![0u8; size as usize])
        .map_err(|t| trap("realloc", t))?;
    // Copy the old contents byte-by-byte, stopping at the first
    // unreadable address — the old block's true size is not
    // tracked, so this naturally bounds the copy to whatever is
    // mapped.
    if ptr != 0 {
        for i in 0..size {
            match mmu.load8(ptr.wrapping_add(i)) {
                Ok(b) => mmu
                    .store8(addr.wrapping_add(i), b)
                    .map_err(|t| trap("realloc", t))?,
                Err(_) => break,
            }
        }
    }
    Ok(addr)
}

/// `struct lconv *localeconv(void)`. Builds a minimal `lconv`
/// in guest memory: `decimal_point` points at `"."`, every
/// other string field at `""`, and the numeric `char` fields
/// are `CHAR_MAX` ("value not available", per the C standard).
/// The real CRT never returns NULL here, so neither do we.
fn stub_localeconv(
    _cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    // Layout (32-bit msvcrt): 10 char* (offsets 0..40) followed
    // by 8 signed-char fields (offsets 40..48). We append the
    // backing strings after the struct in the same block.
    const STRUCT_LEN: u32 = 48;
    const DOT_OFF: u32 = 48; // "." NUL
    const EMPTY_OFF: u32 = 50; // "" (a lone NUL)
    let block = state.arena_alloc(STRUCT_LEN + 3)?;
    let mut buf = vec![0u8; (STRUCT_LEN + 3) as usize];
    // decimal_point -> ".", the other nine pointers -> "".
    let dot = block + DOT_OFF;
    let empty = block + EMPTY_OFF;
    buf[0..4].copy_from_slice(&dot.to_le_bytes());
    for slot in 1..10 {
        let off = slot * 4;
        buf[off..off + 4].copy_from_slice(&empty.to_le_bytes());
    }
    // The eight numeric fields: CHAR_MAX = 0x7F.
    for b in buf.iter_mut().take(STRUCT_LEN as usize).skip(40) {
        *b = 0x7F;
    }
    buf[DOT_OFF as usize] = b'.';
    // DOT_OFF+1 and EMPTY_OFF already zero.
    mmu.write_initializer(block, &buf)
        .map_err(|t| trap("localeconv", t))?;
    Ok(block)
}

/// `char *setlocale(int category, const char *locale)`. Echoes
/// the requested locale back (a non-NULL "success" result); a
/// NULL query returns a pointer to the canonical `"C"` locale.
fn stub_setlocale(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &Registry,
) -> Result<u32, Win32Error> {
    let _category = arg_dword(cpu, mmu, 0).map_err(|t| trap("setlocale", t))?;
    let locale = arg_dword(cpu, mmu, 1).map_err(|t| trap("setlocale", t))?;
    if locale != 0 {
        return Ok(locale);
    }
    let addr = state.arena_alloc(2)?;
    mmu.write_initializer(addr, b"C\0")
        .map_err(|t| trap("setlocale", t))?;
    Ok(addr)
}

mod tests {
    use super::*;
    #[allow(unused_imports)]
    use crate::emulator::isa_int::RET_SENTINEL;
    use crate::emulator::mmu::Perm;
    #[allow(unused_imports)]
    use crate::emulator::regs::Reg32;

    #[allow(dead_code)]
    fn make_env() -> (Cpu, Mmu, Registry, HostState) {
        let mut mmu = Mmu::new();
        mmu.map(0x4000, 0x4000, Perm::R | Perm::W);
        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_all();
        let state = HostState::new(0x4000, 0x8000);
        (cpu, mmu, registry, state)
    }

    #[allow(dead_code)]
    fn call_cdecl(
        cpu: &mut Cpu,
        mmu: &mut Mmu,
        registry: &Registry,
        state: &mut HostState,
        name: &str,
        args: &[u32],
    ) -> Result<(), crate::Error> {
        // cdecl: caller pushes args + return addr; callee
        // does NOT pop args. We push the args, then the
        // synthetic ret addr (0xDEAD_DEAD), then dispatch.
        for a in args.iter().rev() {
            cpu.push32(mmu, *a)?;
        }
        cpu.push32(mmu, 0xDEAD_DEAD)?;
        cpu.regs.eip = registry.resolve("msvcrt.dll", name).unwrap();
        crate::win32::dispatch_stub(cpu, mmu, registry, state)
    }

    #[test]
    fn operator_new_zero_size_returns_null() {
        let (mut cpu, mut mmu, registry, mut state) = make_env();
        call_cdecl(
            &mut cpu,
            &mut mmu,
            &registry,
            &mut state,
            "??2@YAPAXI@Z",
            &[0],
        )
        .unwrap();
        assert_eq!(cpu.regs.get32(Reg32::Eax), 0);
    }

    #[test]
    fn operator_new_nonzero_returns_heap_addr() {
        let (mut cpu, mut mmu, registry, mut state) = make_env();
        call_cdecl(
            &mut cpu,
            &mut mmu,
            &registry,
            &mut state,
            "??2@YAPAXI@Z",
            &[64],
        )
        .unwrap();
        let p = cpu.regs.get32(Reg32::Eax);
        assert_ne!(p, 0);
        assert!(state.heap.contains_key(&p));
    }

    #[test]
    fn operator_delete_nullptr_is_noop() {
        let (mut cpu, mut mmu, registry, mut state) = make_env();
        call_cdecl(
            &mut cpu,
            &mut mmu,
            &registry,
            &mut state,
            "??3@YAXPAX@Z",
            &[0],
        )
        .unwrap();
        assert_eq!(cpu.regs.get32(Reg32::Eax), 0);
    }

    #[test]
    fn malloc_then_free_round_trip() {
        let (mut cpu, mut mmu, registry, mut state) = make_env();
        call_cdecl(&mut cpu, &mut mmu, &registry, &mut state, "malloc", &[128]).unwrap();
        let p = cpu.regs.get32(Reg32::Eax);
        assert_ne!(p, 0);
        assert!(state.heap.contains_key(&p));
        call_cdecl(&mut cpu, &mut mmu, &registry, &mut state, "free", &[p]).unwrap();
        assert!(!state.heap.contains_key(&p));
    }

    #[test]
    fn initterm_zero_args_is_noop() {
        let (mut cpu, mut mmu, registry, mut state) = make_env();
        call_cdecl(
            &mut cpu,
            &mut mmu,
            &registry,
            &mut state,
            "_initterm",
            &[0, 0],
        )
        .unwrap();
        assert_eq!(cpu.regs.get32(Reg32::Eax), 0);
    }

    #[test]
    fn initterm_walks_table_and_calls_non_null_entries() {
        // Build a fn-pointer table of three entries: null,
        // valid, null. The valid entry points at a tiny
        // hand-built guest function that just `ret`s.
        let mut mmu = Mmu::new();
        mmu.map(0x4000, 0x4000, Perm::R | Perm::W);
        mmu.map(0x8000, 0x1000, Perm::R | Perm::W);
        // Code page for the dummy function.
        mmu.map(0xA000, 0x1000, Perm::R | Perm::X);
        // Single `ret` (0xC3) at 0xA000. cdecl callee.
        mmu.write_initializer(0xA000, &[0xC3]).unwrap();
        // Three-slot table at 0x6000: [0, 0xA000, 0].
        mmu.write_initializer(0x6000, &0u32.to_le_bytes()).unwrap();
        mmu.write_initializer(0x6004, &0xA000u32.to_le_bytes())
            .unwrap();
        mmu.write_initializer(0x6008, &0u32.to_le_bytes()).unwrap();

        let mut cpu = Cpu::new();
        cpu.regs.set_esp(0x8F00);
        let mut registry = Registry::new();
        registry.register_all();
        let mut state = HostState::new(0x4000, 0x8000);

        // _initterm(0x6000, 0x600C)
        let _ = RET_SENTINEL; // referenced via call_guest internally
        for a in [0x600Cu32, 0x6000u32].iter() {
            cpu.push32(&mut mmu, *a).unwrap();
        }
        cpu.push32(&mut mmu, 0xDEAD_DEAD).unwrap();
        cpu.regs.eip = registry.resolve("msvcrt.dll", "_initterm").unwrap();
        crate::win32::dispatch_stub(&mut cpu, &mut mmu, &registry, &mut state).unwrap();
        // No assertion on a side-effect register here — the
        // contract is "did not trap" (the fn-pointer was
        // walked + invoked via `call_guest` and returned).
        assert_eq!(cpu.regs.eip, 0xDEAD_DEAD);
    }
}