univdreams 0.4.0

Byte-identical binary <-> source round-tripping: binary formats, multi-arch decode/encode, a .ud decompiler/compiler, and an x86 emulator with Win16/Win32/Linux hosts.
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
//! Win16 (16-bit Windows) API stubs, imported by **ordinal** through
//! the `KERNEL` / `USER` / `GDI` / … modules and called with the
//! **FAR PASCAL** convention (arguments pushed left-to-right, callee
//! cleans the stack with `RETF n`, result in `DX:AX`).
//!
//! This is the 16-bit sibling of [`crate::emulator::win32`]. The dispatch ABI is
//! handled in [`crate::emulator::win32::dispatch_stub`] (it branches on the CPU's
//! 16-bit mode); here we register the stubs and implement them.
//!
//! Phase 2 scope: enough of the Win16 task-startup surface for an MFC /
//! C-runtime NE app to run *past* its entry prologue. The keystone is
//! `KERNEL.91` (`InitTask`), whose register outputs the C startup
//! consumes (`AX` ok-flag, `CX` stack top, `DX` nCmdShow, `SI`
//! hPrevInstance, `DI` hInstance, `ES:BX` command line).

pub mod gui;

use std::collections::BTreeMap;

use crate::emulator::emulator::mmu::Perm;
use crate::emulator::emulator::regs::{Reg8, Reg16};
use crate::emulator::emulator::{Cpu, Mmu};
use crate::emulator::win32::{HostState, Registry, Win32Error};

/// Linear base of the Win16 global-heap arena (above the segment
/// windows and PSP).
const WIN16_HEAP_BASE: u32 = 0x0040_0000;
/// First selector handed out for a `GlobalAlloc` block (avoids the
/// segment numbers, HINSTANCE, import/PSP/sentinel selectors).
const WIN16_HEAP_FIRST_SEL: u16 = 0x0200;
/// Per-block window size: a Win16 selector addresses up to 64 KiB.
const WIN16_HEAP_WINDOW: u32 = 0x0001_0000;

/// A simple Win16 global heap. Each `GlobalAlloc` gets its own linear
/// window and a unique selector (handle == selector, GMEM_FIXED-style);
/// `GlobalLock` just hands back `selector:0000`.
#[derive(Debug, Default, Clone)]
pub struct Win16Heap {
    next_base: u32,
    next_selector: u16,
    /// selector → (linear base, requested size).
    pub blocks: BTreeMap<u16, (u32, u32)>,
}

impl Win16Heap {
    /// Allocate `size` bytes: map a fresh window, assign a selector,
    /// register it on the CPU, and return the selector (the handle). Each
    /// block gets a full 64 KiB window — a Win16 selector addresses up to
    /// 64 KiB, and programs routinely read/write the whole segment.
    fn alloc(&mut self, cpu: &mut Cpu, mmu: &mut Mmu, size: u32) -> u16 {
        if self.next_base < WIN16_HEAP_BASE {
            self.next_base = WIN16_HEAP_BASE;
            self.next_selector = WIN16_HEAP_FIRST_SEL;
        }
        let page_rounded = size.max(1).wrapping_add(0xFFF) & !0xFFF;
        let mapped = page_rounded.max(WIN16_HEAP_WINDOW);
        let base = self.next_base;
        let sel = self.next_selector;
        mmu.map(base, mapped, Perm::R | Perm::W | Perm::X);
        cpu.define_selector(sel, base);
        self.blocks.insert(sel, (base, size));
        if std::env::var("UD_NE_HEAP_DEBUG").is_ok() {
            eprintln!(
                "win16_heap: alloc sel={sel:#06x} base={base:#010x}..{:#010x} \
                 (asked={size:#x}, mapped={mapped:#x})",
                base.wrapping_add(mapped)
            );
        }
        self.next_base = self.next_base.wrapping_add(mapped);
        self.next_selector = self.next_selector.wrapping_add(8);
        sel
    }

    /// Resize the block at `sel`, **keeping the same selector** (handle).
    /// Win16 programs check that `GlobalReAlloc` returns the original handle
    /// (the memory may move underneath, but the handle is stable). If it
    /// fits in the already-mapped window, update in place; otherwise map a
    /// fresh window, copy the data, and rebase the selector to it.
    fn realloc(&mut self, cpu: &mut Cpu, mmu: &mut Mmu, sel: u16, new_size: u32) -> u16 {
        let Some(&(old_base, old_size)) = self.blocks.get(&sel) else {
            return self.alloc(cpu, mmu, new_size);
        };
        // Fits in the existing 64 KiB window → resize in place.
        if new_size <= WIN16_HEAP_WINDOW {
            self.blocks.insert(sel, (old_base, new_size));
            return sel;
        }
        // Huge (>64 KiB) grow: move to a fresh window and copy the contents.
        let new_window = new_size.wrapping_add(0xFFF) & !0xFFF;
        if self.next_base < WIN16_HEAP_BASE {
            self.next_base = WIN16_HEAP_BASE;
            self.next_selector = WIN16_HEAP_FIRST_SEL;
        }
        let new_base = self.next_base;
        mmu.map(new_base, new_window, Perm::R | Perm::W | Perm::X);
        for i in 0..old_size.min(new_size) {
            let b = mmu.load8(old_base.wrapping_add(i)).unwrap_or(0);
            let _ = mmu.store8(new_base.wrapping_add(i), b);
        }
        cpu.define_selector(sel, new_base); // same selector, new base
        self.blocks.insert(sel, (new_base, new_size));
        self.next_base = self.next_base.wrapping_add(new_window);
        sel
    }
}

/// Synthetic instance handle handed to the task (Win16 `HINSTANCE`).
/// Real Windows hands back the module's DGROUP selector; any stable
/// non-zero value works for a single-task sandbox.
pub const WIN16_HINSTANCE: u16 = 0x0100;
/// Synthetic current-task handle (`GetCurrentTask`).
pub const WIN16_HTASK: u16 = 0x0200;
/// `SW_SHOWNORMAL` — the default `nCmdShow` for a launched app.
const SW_SHOWNORMAL: u16 = 1;

/// Call a guest 16-bit **FAR PASCAL** callback (a window or dialog
/// procedure) from the host and return its `DX:AX` result. This is how
/// the headless GUI delivers messages — `WM_INITDIALOG`, `WM_COMMAND`,
/// … — into the program's own code so its handlers actually run.
///
/// `args` are pushed left-to-right (PASCAL order); a `WndProc`/`DlgProc`
/// is invoked as `&[hwnd, msg, wparam, lparam_hi, lparam_lo]`. A far
/// return sentinel is pushed so the callee's `RETF n` lands back here;
/// the call is stack-balanced (the callee cleans its own args).
///
/// # Errors
/// Propagates any trap raised while the callback runs.
pub fn call_guest_far16(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    registry: &mut Registry,
    state: &mut HostState,
    proc_sel: u16,
    proc_off: u16,
    args: &[u16],
) -> Result<u32, crate::emulator::Error> {
    use crate::emulator::emulator::isa_int::RET_SENTINEL;

    cpu.define_selector(crate::emulator::ne::SENTINEL_SELECTOR, RET_SENTINEL);
    for &a in args {
        cpu.push16(mmu, a)?;
    }
    // Far-return sentinel: CS = sentinel selector (base RET_SENTINEL),
    // IP = 0, so the callee's RETF returns to RET_SENTINEL and the run
    // loop halts.
    cpu.push16(mmu, crate::emulator::ne::SENTINEL_SELECTOR)?;
    cpu.push16(mmu, 0)?;
    cpu.set_cs_ip(proc_sel, proc_off);

    crate::emulator::win32::run_until_sentinel(cpu, mmu, registry, state)?;

    let ax = u32::from(cpu.regs.get16(Reg16::Ax));
    let dx = u32::from(cpu.regs.get16(Reg16::Dx));
    Ok((dx << 16) | ax)
}

/// Register the Win16 stub surface with `registry`. Safe to call once
/// per sandbox before loading an NE module; the loader's relocation
/// pass then resolves imported ordinals to these thunks (falling back
/// to trap-on-call for anything unimplemented).
pub fn register_all(registry: &mut Registry) {
    register_kernel(registry);
    register_user(registry);
    register_gdi(registry);
    register_commdlg(registry);
}

/// `COMMDLG` (common dialogs) ordinal stubs.
fn register_commdlg(registry: &mut Registry) {
    // COMMDLG.27 GetFileTitle(lpszFile far, lpszTitle far, cbBuf word).
    registry.register_far_pascal("commdlg", "@27", stub_get_file_title, 10);
}

/// `GDI` ordinal stubs.
fn register_gdi(registry: &mut Registry) {
    // GDI.80 GetDeviceCaps(hDC, index) — display capabilities MFC reads
    // off the screen DC during startup.
    registry.register_far_pascal("gdi", "@80", stub_get_device_caps, 4);
    // GDI.91 GetTextExtent(hDC, lpString far, cbString) → DWORD extent
    // (width in AX, height in DX). Return a fixed 8×16 cell metric.
    registry.register_far_pascal("gdi", "@91", stub_get_text_extent, 8);
    // GDI.66 CreateSolidBrush(COLORREF) → HBRUSH. MFC builds brushes for
    // the system colours during startup.
    registry.register_far_pascal("gdi", "@66", stub_create_object, 4);
    // GDI.61 CreatePen(style, width, COLORREF) → HPEN.
    registry.register_far_pascal("gdi", "@61", stub_create_object, 8);
    // GDI.69 DeleteObject(hObject) → BOOL success.
    registry.register_far_pascal("gdi", "@69", stub_ret1_1word, 2);
    // GDI.87 GetStockObject(fnObject) → HGDIOBJ.
    registry.register_far_pascal("gdi", "@87", stub_create_object, 2);
    // GDI.442 CreateDIBitmap(hdc, lpbmih, init, lpInit, lpbmi, usage) → HBITMAP.
    registry.register_far_pascal("gdi", "@442", stub_create_object, 20);
    // GDI.36 CreateCompatibleDC(hdc) / GDI.72 CreateBitmap / GDI.444
    // SetDIBits / GDI.27 BitBlt — bitmap plumbing the splash uses.
    registry.register_far_pascal("gdi", "@36", stub_create_object, 2);
    registry.register_far_pascal("gdi", "@72", stub_create_object, 10);
}

/// Generic GDI object factory → a fresh unique object handle. The
/// argument layout doesn't matter (the handle is opaque); the cleanup
/// byte count is supplied per-registration.
fn stub_create_object(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &mut Registry,
) -> Result<u32, Win32Error> {
    Ok(u32::from(state.gui.alloc_obj_handle()))
}

/// `GDI.91 GetTextExtent` → a plausible fixed-pitch extent so MFC's font
/// measurement proceeds. width = 8·cbString, height = 16.
fn stub_get_text_extent(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &mut Registry,
) -> Result<u32, Win32Error> {
    let cb = cpu.stack_word(mmu, 4).unwrap_or(1); // cbString (last arg)
    let width = 8u32.wrapping_mul(u32::from(cb)) & 0xFFFF;
    Ok((16u32 << 16) | width)
}

/// `GDI.80 GetDeviceCaps(hDC, nIndex)` → plausible 640×480 8bpp,
/// 96-DPI VGA values.
fn stub_get_device_caps(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &mut Registry,
) -> Result<u32, Win32Error> {
    // PASCAL: hDC pushed first (SP+6), nIndex pushed last (SP+4).
    let index = cpu.stack_word(mmu, 4).unwrap_or(0);
    let v: u16 = match index {
        8 => 640,      // HORZRES
        10 => 480,     // VERTRES
        12 => 8,       // BITSPIXEL
        14 => 1,       // PLANES
        88 | 90 => 96, // LOGPIXELSX / LOGPIXELSY
        24 => 20,      // NUMCOLORS
        _ => 0,
    };
    Ok(u32::from(v))
}

/// `USER` ordinal stubs.
fn register_user(registry: &mut Registry) {
    // USER.5 InitApp(hInstance) — set up the task's message queue.
    // Must return non-zero or the C startup aborts.
    registry.register_far_pascal("user", "@5", stub_ret1_1word, 2);
    // USER.66 GetDC(hWnd) — MFC grabs the screen DC at startup to read
    // display metrics, then releases it. Return a non-zero DC handle.
    registry.register_far_pascal("user", "@66", stub_ret_handle_1word, 2);
    // USER.68 ReleaseDC(hWnd, hDC) — release the screen DC; return 1.
    registry.register_far_pascal("user", "@68", stub_ret1_2word, 4);
    // USER.69 SetCursor(hCursor) → previous HCURSOR. Callers want a
    // non-zero handle they can pass back later to "restore" the cursor;
    // a fixed synthetic handle is fine for a sandboxed installer.
    registry.register_far_pascal("user", "@69", stub_ret_handle_1word, 2);
    // USER.179 GetSystemMetrics(index).
    registry.register_far_pascal("user", "@179", stub_get_system_metrics, 2);
    // USER.180 GetSysColor(index) → COLORREF.
    registry.register_far_pascal("user", "@180", stub_get_sys_color, 2);
    // USER.173 LoadCursor(hInstance, lpCursorName far) → HCURSOR.
    registry.register_far_pascal("user", "@173", stub_create_object, 6);
    // USER.174 LoadIcon(hInstance, lpIconName far) → HICON.
    registry.register_far_pascal("user", "@174", stub_create_object, 6);
    // USER.266 SetMessageQueue(cMsg) → BOOL success. We have no real queue
    // sizing, so always succeed (non-zero).
    registry.register_far_pascal("user", "@266", stub_ret1_1word, 2);
    // USER.176 LoadString(hInst, uID, lpBuffer far, nBufferMax) → length.
    registry.register_far_pascal("user", "@176", stub_load_string, 10);
    // USER.291 SetWindowsHookEx(idHook, lpfn far, hMod, hTask) → HHOOK.
    registry.register_far_pascal("user", "@291", stub_set_windows_hook_ex, 10);
    // USER.57 RegisterClass(lpWndClass far) → ATOM.
    registry.register_far_pascal("user", "@57", stub_register_class, 4);
    // USER.87 DialogBox(hInst, lpTemplate far, hWndParent, lpDialogFunc far).
    registry.register_far_pascal("user", "@87", stub_dialog_box, 12);
    // USER.88 EndDialog(hDlg, nResult).
    registry.register_far_pascal("user", "@88", stub_end_dialog, 4);
    // USER.89 CreateDialog(hInst, lpTemplate far, hWndParent, lpDialogFunc far).
    registry.register_far_pascal("user", "@89", stub_create_dialog, 12);
    // USER.292 UnhookWindowsHookEx(hHook far) → BOOL.
    registry.register_far_pascal("user", "@292", stub_ret1_2word, 4);
    // USER.1 MessageBox(hWnd, lpText far, lpCaption far, wType) → int.
    registry.register_far_pascal("user", "@1", stub_message_box, 12);
    // USER.229 GetTopWindow(hWnd) → first child HWND (none in our model).
    registry.register_far_pascal("user", "@229", stub_ret0_1word, 2);
    // USER.69 SetCursor(hCursor) → previous HCURSOR.
    registry.register_far_pascal("user", "@69", stub_create_object, 2);
    // USER.42 ShowWindow(hWnd, nCmdShow) → previous visibility.
    registry.register_far_pascal("user", "@42", stub_ret1_2word, 4);
    // USER.262 GetWindow(hWnd, uCmd) → related HWND (none in our model).
    registry.register_far_pascal("user", "@262", stub_ret0_1word, 4);
    // USER.32 GetWindowRect(hWnd, lpRect far).
    registry.register_far_pascal("user", "@32", stub_get_window_rect, 6);
    // USER.232 SetWindowPos(hWnd, after, x, y, cx, cy, flags) → BOOL.
    registry.register_far_pascal("user", "@232", stub_ret1_1word, 14);
    // USER.111 SendMessage(hWnd, msg, wParam, lParam long).
    registry.register_far_pascal("user", "@111", stub_send_message, 10);
    // Dialog control accessors.
    registry.register_far_pascal("user", "@91", stub_get_dlg_item, 4);
    registry.register_far_pascal("user", "@36", stub_get_window_text, 8);
    registry.register_far_pascal("user", "@37", stub_set_window_text, 6);
    registry.register_far_pascal("user", "@38", stub_get_window_text_length, 2);
    registry.register_far_pascal("user", "@92", stub_set_dlg_item_text, 8);
    registry.register_far_pascal("user", "@93", stub_get_dlg_item_text, 10);
    // USER.404 GetClassInfo(hInst, lpClassName far, lpWndClass far) → BOOL.
    registry.register_far_pascal("user", "@404", stub_get_class_info, 10);
    // USER.268 GlobalAddAtom(lpString far) → ATOM.
    registry.register_far_pascal("user", "@268", stub_global_add_atom, 4);
    // USER.269 GlobalDeleteAtom(atom) → 0 on success.
    registry.register_far_pascal("user", "@269", stub_ret0_1word, 2);
}

/// `USER.180 GetSysColor(nIndex)` → a plausible 3-D grey scheme.
fn stub_get_sys_color(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &mut Registry,
) -> Result<u32, Win32Error> {
    let index = cpu.stack_word(mmu, 4).unwrap_or(0);
    let color: u32 = match index {
        15 => 0x00C0_C0C0,     // COLOR_BTNFACE
        16 => 0x0080_8080,     // COLOR_BTNSHADOW
        20 => 0x00FF_FFFF,     // COLOR_BTNHIGHLIGHT
        18 | 8 => 0x0000_0000, // COLOR_BTNTEXT / WINDOWTEXT
        5 => 0x00FF_FFFF,      // COLOR_WINDOW
        _ => 0x0080_8080,
    };
    Ok(color)
}

/// Generic FAR PASCAL stub: clean two words of args, return 1 (success).
fn stub_ret1_2word(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &mut Registry,
) -> Result<u32, Win32Error> {
    Ok(1)
}

/// Generic FAR PASCAL stub returning a fixed non-zero handle (one word
/// of args). Used for HDC / HCURSOR / HICON-returning calls whose value
/// the program only checks for non-NULL and later releases.
fn stub_ret_handle_1word(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &mut Registry,
) -> Result<u32, Win32Error> {
    Ok(0x0010)
}

/// `USER.179 GetSystemMetrics(nIndex)` — return plausible 640×480 VGA
/// metrics so MFC's layout math doesn't divide by zero.
fn stub_get_system_metrics(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &mut Registry,
) -> Result<u32, Win32Error> {
    // FAR PASCAL: the single word arg sits above the 4-byte far return.
    let index = cpu.stack_word(mmu, 4).unwrap_or(0);
    let v: u16 = match index {
        0 => 640,   // SM_CXSCREEN
        1 => 480,   // SM_CYSCREEN
        2 => 16,    // SM_CXVSCROLL
        3 => 16,    // SM_CYHSCROLL
        4 => 19,    // SM_CYCAPTION
        5 | 6 => 1, // SM_CXBORDER / SM_CYBORDER
        11 => 32,   // SM_CXICON
        12 => 32,   // SM_CYICON
        _ => 0,
    };
    Ok(u32::from(v))
}

/// Generic FAR PASCAL stub: clean one word of args, return 1 (success).
fn stub_ret1_1word(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &mut Registry,
) -> Result<u32, Win32Error> {
    Ok(1)
}

/// Service a software interrupt raised in 16-bit mode. Returns `true`
/// if handled (the run loop then resumes), `false` if the vector is
/// unknown (the run loop surfaces it as a trap).
///
/// Win16 apps still reach DOS through `INT 21h` for a handful of
/// services (get version, get/set vectors, get current drive, …). We
/// service the common ones and clear the carry flag (success);
/// anything unrecognised clears carry and returns 0 so a probe doesn't
/// derail the run.
pub fn service_interrupt(num: u8, cpu: &mut Cpu, mmu: &mut Mmu, state: &mut HostState) -> bool {
    match num {
        0x21 => {
            dos_int21(cpu, mmu, state);
            true
        }
        // INT 3 (breakpoint) / INT 0x3F (Win16 inter-segment call thunk,
        // already handled at load) — ignore and continue.
        0x03 => true,
        _ => false,
    }
}

/// DOS `INT 21h` dispatcher. Handles the version/date stubs plus the file
/// I/O handle functions (open/create/read/write/seek/close/mkdir), wired
/// to the [`crate::emulator::context::VirtualFs`] so an installer's extraction writes
/// land where `--dump-vfs` can collect them.
fn dos_int21(cpu: &mut Cpu, mmu: &mut Mmu, state: &mut HostState) {
    use crate::emulator::emulator::isa_int::Seg;
    let ah = cpu.regs.get8(Reg8::Ah);
    if std::env::var("UD_NE_DOS_DEBUG").is_ok() {
        eprintln!("DOS INT21 AH={ah:#04x}");
    }
    cpu.regs.flags.cf = false; // default: success
    match ah {
        // AH=0x30 Get DOS version → AL=major, AH=minor, BX:CX OEM/serial.
        0x30 => {
            cpu.regs.set8(Reg8::Al, 6); // DOS 6.x
            cpu.regs.set8(Reg8::Ah, 0);
            cpu.regs.set16(Reg16::Bx, 0);
            cpu.regs.set16(Reg16::Cx, 0);
        }
        // AH=0x19 Get current default drive → AL = drive (0=A, 2=C).
        0x19 => cpu.regs.set8(Reg8::Al, 2),
        // AH=0x25 Set interrupt vector — accept and ignore.
        0x25 => {}
        // AH=0x1A Set DTA (DS:DX) — remember where FindFirst writes.
        0x1A => {
            state.dos_dta = (cpu.segment_selector(Seg::Ds), cpu.regs.get16(Reg16::Dx));
        }
        // AH=0x2F Get DTA → ES:BX.
        0x2F => {
            cpu.set_segment_reg(0 /* ES */, state.dos_dta.0);
            cpu.regs.set16(Reg16::Bx, state.dos_dta.1);
        }
        // AH=0x4E FindFirst(DS:DX pathspec, CX attr) → fill the DTA with the
        // matching file's directory entry (notably its size at +0x1A) so a
        // copy/CRC loop reads the right number of bytes.
        0x4E => {
            let lin = cpu
                .seg_base(Seg::Ds)
                .wrapping_add(u32::from(cpu.regs.get16(Reg16::Dx)));
            let spec = String::from_utf8_lossy(&read_guest_cstr(mmu, lin, 260)).into_owned();
            // Resolve a concrete match (exact path, or first VFS file whose
            // base name matches a `*.*`-style pattern's directory).
            let size = state
                .context
                .vfs
                .as_ref()
                .and_then(|v| dos_find_match(v, &spec));
            match size {
                Some((name, sz)) => {
                    let dta = cpu.far_to_linear(state.dos_dta.0, state.dos_dta.1);
                    let _ = mmu.store8(dta.wrapping_add(0x15), 0x20); // attr=archive
                    for o in [0x16u32, 0x18] {
                        let _ = mmu.store16(dta.wrapping_add(o), 0);
                    }
                    let _ = mmu.store16(dta.wrapping_add(0x1A), sz as u16);
                    let _ = mmu.store16(dta.wrapping_add(0x1C), (sz >> 16) as u16);
                    write_guest_cstr(mmu, dta.wrapping_add(0x1E), 13, name.as_bytes()).ok();
                }
                None => dos_error(cpu, 18), // no more files
            }
        }
        // AH=0x4F FindNext — single match only; report "no more files".
        0x4F => dos_error(cpu, 18),
        // AH=0x35 Get interrupt vector → ES:BX = 0:0.
        0x35 => {
            cpu.regs.set16(Reg16::Bx, 0);
            cpu.set_segment_reg(0, 0);
        }
        // AH=0x2A Get date / 0x2C Get time — return zeros (epoch).
        0x2A | 0x2C => {
            cpu.regs.set16(Reg16::Cx, 0);
            cpu.regs.set16(Reg16::Dx, 0);
        }
        // AH=0x3C Create or truncate file: CX=attrs, DS:DX=path → AX=handle.
        // AH=0x3D Open existing file:    AL=mode, DS:DX=path → AX=handle.
        0x3C | 0x3D => dos_open_or_create(cpu, mmu, state, ah == 0x3C),
        // AH=0x3E Close file: BX=handle.
        0x3E => dos_close(cpu, state),
        // AH=0x3F Read from file:  BX=handle, CX=count, DS:DX=buf → AX=bytes.
        0x3F => dos_read(cpu, mmu, state),
        // AH=0x40 Write to file:   BX=handle, CX=count, DS:DX=buf → AX=bytes.
        0x40 => dos_write(cpu, mmu, state),
        // AH=0x42 LSeek: AL=origin (0=SET,1=CUR,2=END), BX=handle,
        // CX:DX=offset → DX:AX=new pos.
        0x42 => dos_seek(cpu, state),
        // AH=0x43 Get/Set file attributes. AL=0 returns CX=attrs;
        // AL=1 sets them. For VFS files we always return
        // FILE_ATTRIBUTE_ARCHIVE (0x20) and accept any set.
        0x43 => dos_file_attribs(cpu, mmu, state),
        // AH=0x44 IOCTL: AL=subfn. The MSVC-Win16 CRT calls this with
        // AL=0 immediately after open to discover whether the handle
        // is a device or a file — the result governs whether _filbuf
        // honours EOF semantics or treats the handle as an unbounded
        // character stream. Reporting "device" turns sequential
        // reads into an infinite EOF-less loop, so report "file on
        // drive C" instead.
        0x44 => dos_ioctl(cpu, state),
        // AH=0x39 MkDir / 0x3A RmDir / 0x3B ChDir — the VFS is flat; just succeed.
        0x39 | 0x3B | 0x3A => {}
        // Anything else: report success with AX cleared. The startup
        // code stores the result but does not branch on it here.
        _ => cpu.regs.set16(Reg16::Ax, 0),
    }
}

/// Build the linear address `DS:DX` points at, the canonical DOS
/// pointer for path / buffer arguments to `INT 21h` services.
fn dos_ds_dx_linear(cpu: &Cpu) -> u32 {
    let ds = cpu.segment_selector(crate::emulator::emulator::isa_int::Seg::Ds);
    let dx = cpu.regs.get16(Reg16::Dx);
    cpu.far_to_linear(ds, dx)
}

/// Read a DOS-style NUL-terminated path string at `addr` (max 260).
/// Maps backslashes through verbatim — [`crate::emulator::context::VirtualFs`]
/// normalises on insert / lookup.
fn read_dos_path(mmu: &Mmu, addr: u32) -> String {
    String::from_utf8_lossy(&read_guest_cstr(mmu, addr, 260)).into_owned()
}

/// Set the carry flag and place a DOS error code in AX. Callers use
/// `0x02` (file not found), `0x06` (invalid handle), `0x1D`
/// (write fault), per the `INT 21h` error-code conventions.
fn dos_error(cpu: &mut Cpu, code: u16) {
    cpu.regs.flags.cf = true;
    cpu.regs.set16(Reg16::Ax, code);
}

/// `INT 21h AH=0x3C/3D` — open or create. Allocates the next free
/// DOS handle and routes the underlying file through the VFS so the
/// install-monitor's VFS-writes report captures everything the guest
/// writes.
fn dos_open_or_create(cpu: &mut Cpu, mmu: &mut Mmu, state: &mut HostState, create: bool) {
    use crate::emulator::context::FileAccess;
    let path_lin = dos_ds_dx_linear(cpu);
    let path = read_dos_path(mmu, path_lin);
    if std::env::var("UD_NE_DOS_DEBUG").is_ok() {
        let ds = cpu.segment_selector(crate::emulator::emulator::isa_int::Seg::Ds);
        let dx = cpu.regs.get16(Reg16::Dx);
        let al = cpu.regs.get8(Reg8::Al);
        eprintln!(
            "  DOS {} DS:DX={ds:#06x}:{dx:#06x} lin={path_lin:#x} AL={al:#04x} path={path:?}",
            if create { "create" } else { "open" }
        );
    }
    if path.is_empty() {
        dos_error(cpu, 0x02); // file not found
        return;
    }
    let access = if create {
        FileAccess::ReadWrite
    } else {
        match cpu.regs.get8(Reg8::Al) & 0x07 {
            0 => FileAccess::Read,
            1 => FileAccess::Write,
            2 => FileAccess::ReadWrite,
            _ => FileAccess::Read,
        }
    };
    let vfs = state
        .context
        .vfs
        .get_or_insert_with(crate::emulator::fsmount::MountTable::new);
    if create {
        vfs.write_path(&path, Vec::new());
    }
    let Some(vh) = vfs.open(&path, access) else {
        dos_error(cpu, 0x02); // file not found
        return;
    };
    let dh = state.next_dos_handle;
    state.next_dos_handle = state.next_dos_handle.wrapping_add(1);
    state.dos_handles.insert(dh, vh);
    cpu.regs.set16(Reg16::Ax, dh);
    if std::env::var("UD_NE_DOS_DEBUG").is_ok() {
        eprintln!(
            "DOS {} '{path}' → dh={dh:#06x} vh={vh:#x}",
            if create { "create" } else { "open" }
        );
    }
}

fn dos_close(cpu: &mut Cpu, state: &mut HostState) {
    let dh = cpu.regs.get16(Reg16::Bx);
    if let Some(vh) = state.dos_handles.remove(&dh) {
        if let Some(vfs) = state.context.vfs.as_mut() {
            vfs.close(vh);
        }
        cpu.regs.set16(Reg16::Ax, 0);
    } else {
        dos_error(cpu, 0x06); // invalid handle
    }
}

fn dos_read(cpu: &mut Cpu, mmu: &mut Mmu, state: &mut HostState) {
    let dh = cpu.regs.get16(Reg16::Bx);
    let count = usize::from(cpu.regs.get16(Reg16::Cx));
    let buf_lin = dos_ds_dx_linear(cpu);
    let Some(&vh) = state.dos_handles.get(&dh) else {
        dos_error(cpu, 0x06);
        return;
    };
    let Some(vfs) = state.context.vfs.as_mut() else {
        dos_error(cpu, 0x06);
        return;
    };
    let mut tmp = vec![0u8; count];
    let n = vfs.read_handle(vh, &mut tmp).unwrap_or(0);
    for (i, &b) in tmp[..n].iter().enumerate() {
        let _ = mmu.store8(buf_lin.wrapping_add(i as u32), b);
    }
    cpu.regs.set16(Reg16::Ax, n as u16);
    if std::env::var("UD_NE_DOS_DEBUG").is_ok() {
        eprintln!("  DOS read dh={dh:#06x} count={count} -> n={n}");
    }
}

fn dos_write(cpu: &mut Cpu, mmu: &mut Mmu, state: &mut HostState) {
    let dh = cpu.regs.get16(Reg16::Bx);
    let count = usize::from(cpu.regs.get16(Reg16::Cx));
    let buf_lin = dos_ds_dx_linear(cpu);
    let Some(&vh) = state.dos_handles.get(&dh) else {
        dos_error(cpu, 0x06);
        return;
    };
    let mut data = vec![0u8; count];
    for (i, b) in data.iter_mut().enumerate() {
        *b = mmu.load8(buf_lin.wrapping_add(i as u32)).unwrap_or(0);
    }
    let Some(vfs) = state.context.vfs.as_mut() else {
        dos_error(cpu, 0x06);
        return;
    };
    let n = vfs.write_handle(vh, &data).unwrap_or(0);
    cpu.regs.set16(Reg16::Ax, n as u16);
}

/// `INT 21h AH=0x43` — Get/Set file attributes. The MSVC Win16
/// CRT's `_open` calls this with `AL=0` right after opening to
/// confirm the file is reachable; returning `FILE_ATTRIBUTE_ARCHIVE`
/// keeps the CRT on its happy path. We ignore `AL=1` writes since
/// the VFS doesn't track DOS attribute bits.
fn dos_file_attribs(cpu: &mut Cpu, mmu: &mut Mmu, state: &mut HostState) {
    let al = cpu.regs.get8(Reg8::Al);
    let path_lin = dos_ds_dx_linear(cpu);
    let path = read_dos_path(mmu, path_lin);
    if path.is_empty() {
        dos_error(cpu, 0x02);
        return;
    }
    let vfs = state
        .context
        .vfs
        .get_or_insert_with(crate::emulator::fsmount::MountTable::new);
    if !vfs.contains(&path) {
        dos_error(cpu, 0x02);
        return;
    }
    if al == 0 {
        cpu.regs.set16(Reg16::Cx, 0x0020);
        cpu.regs.set16(Reg16::Ax, 0x0020);
    } else {
        cpu.regs.set16(Reg16::Ax, 0);
    }
}

/// `INT 21h AH=0x44 IOCTL` — only the `AL=0` "get device info"
/// subfunction is meaningful for the CRT-startup flow. For a VFS
/// file we report: regular file, drive C (bits 0..5 = 2), no special
/// flags, no EOF-on-input. Other subfunctions clear AX and CF.
fn dos_ioctl(cpu: &mut Cpu, state: &mut HostState) {
    let al = cpu.regs.get8(Reg8::Al);
    if al != 0x00 {
        cpu.regs.set16(Reg16::Ax, 0);
        return;
    }
    let dh = cpu.regs.get16(Reg16::Bx);
    if !state.dos_handles.contains_key(&dh) {
        dos_error(cpu, 0x06);
        return;
    }
    // Bit 15 = 0 (file, not device); bits 0..5 = 2 (drive C).
    cpu.regs.set16(Reg16::Dx, 0x0002);
    cpu.regs.set16(Reg16::Ax, 0x0002);
}

fn dos_seek(cpu: &mut Cpu, state: &mut HostState) {
    let dh = cpu.regs.get16(Reg16::Bx);
    let origin = cpu.regs.get8(Reg8::Al);
    let off = (u32::from(cpu.regs.get16(Reg16::Cx)) << 16) | u32::from(cpu.regs.get16(Reg16::Dx));
    let signed_off = off as i32;
    let Some(&vh) = state.dos_handles.get(&dh) else {
        dos_error(cpu, 0x06);
        return;
    };
    let Some(vfs) = state.context.vfs.as_mut() else {
        dos_error(cpu, 0x06);
        return;
    };
    if origin > 2 {
        dos_error(cpu, 0x01); // invalid function
        return;
    }
    let new_pos = vfs.seek_handle(vh, signed_off, origin).unwrap_or(0);
    cpu.regs.set16(Reg16::Ax, (new_pos & 0xFFFF) as u16);
    cpu.regs.set16(Reg16::Dx, ((new_pos >> 16) & 0xFFFF) as u16);
    if std::env::var("UD_NE_DOS_DEBUG").is_ok() {
        eprintln!("  DOS seek dh={dh:#06x} origin={origin} off={signed_off} -> pos={new_pos}");
    }
}

/// Resolve a DOS `FindFirst` pathspec to a `(basename, size)` match in the
/// VFS. Handles an exact path, and a `*`/`?` pattern by matching the first
/// file sharing the spec's directory prefix.
fn dos_find_match(vfs: &crate::emulator::fsmount::MountTable, spec: &str) -> Option<(String, u32)> {
    let base = |p: &str| {
        p.rsplit(['\\', '/'])
            .next()
            .unwrap_or(p)
            .to_ascii_uppercase()
    };
    if !spec.contains('*') && !spec.contains('?') {
        return vfs.read(spec).map(|b| (base(spec), b.len() as u32));
    }
    // Wildcard: compare directory prefixes case-insensitively, treating
    // '\' and '/' the same.
    let norm = |s: &str| s.replace('\\', "/").to_ascii_lowercase();
    let dir = norm(spec.rsplit_once(['\\', '/']).map_or("", |(d, _)| d));
    for (path, len) in vfs.list() {
        let p = norm(path);
        let pdir = p.rsplit_once('/').map_or("", |(d, _)| d);
        if pdir == dir.trim_start_matches(|c| c == 'c' || c == ':' || c == '/') {
            return Some((base(path), len as u32));
        }
    }
    None
}

/// `KERNEL` (KRNL286/KRNL386) ordinal stubs.
fn register_kernel(registry: &mut Registry) {
    // KERNEL.91 InitTask() — no args.
    registry.register_far_pascal("kernel", "@91", stub_init_task, 0);
    // KERNEL.23 LockSegment(seg) — lock a segment so it can't move; in
    // the sandbox segments never move, so just hand back a non-zero
    // selector (the current DGROUP) for success.
    registry.register_far_pascal("kernel", "@23", stub_lock_segment, 2);
    // KERNEL.24 UnlockSegment(seg) — inverse of LockSegment.
    registry.register_far_pascal("kernel", "@24", stub_ret0_1word, 2);
    // KERNEL.30 WaitEvent(HTASK) — yield until an event is posted; in
    // the single-task sandbox there is nothing to wait for.
    registry.register_far_pascal("kernel", "@30", stub_ret0_1word, 2);
    // KERNEL.3 GetVersion() → Windows 3.10 in AX (LOBYTE major, HIBYTE
    // minor), DOS version in DX.
    registry.register_far_pascal("kernel", "@3", stub_get_version, 0);
    // KERNEL.15 GlobalAlloc(wFlags, dwBytes) → HGLOBAL (a selector).
    registry.register_far_pascal("kernel", "@15", stub_global_alloc, 6);
    // KERNEL.16 GlobalReAlloc(hMem, dwBytes, wFlags) → HGLOBAL.
    registry.register_far_pascal("kernel", "@16", stub_global_realloc, 8);
    // KERNEL.17 GlobalFree(hMem) → 0 on success.
    registry.register_far_pascal("kernel", "@17", stub_ret0_1word, 2);
    // KERNEL.18 GlobalLock(hMem) → far pointer selector:0000.
    registry.register_far_pascal("kernel", "@18", stub_global_lock, 2);
    // KERNEL.19 GlobalUnlock(hMem) → 0.
    registry.register_far_pascal("kernel", "@19", stub_ret0_1word, 2);
    // KERNEL.20 GlobalSize(hMem) → block size in bytes (DX:AX).
    registry.register_far_pascal("kernel", "@20", stub_global_size, 2);
    // KERNEL.49 GetModuleFileName(hInst, lpFilename far, nSize) → length.
    registry.register_far_pascal("kernel", "@49", stub_get_module_filename, 8);
    // KERNEL.51 MakeProcInstance(lpProc far, hInst) — bind a function
    // pointer to a Win16 hInstance. In flat 16-bit emulation the proc
    // pointer is already self-contained; just echo it back via DX:AX
    // (the caller treats the result as a callable far pointer).
    registry.register_far_pascal("kernel", "@51", stub_make_proc_instance, 6);
    // KERNEL.52 FreeProcInstance(lpProc far) → BOOL. Counterpart to
    // MakeProcInstance; nothing to release in our model.
    registry.register_far_pascal("kernel", "@52", stub_ret1_2word, 4);
    // KERNEL.134 GetWindowsDirectory(lpBuffer far, uSize) → length.
    // SITEX10 plants temp files under the Windows directory; a
    // plausible "C:\\WINDOWS" satisfies its bookkeeping.
    registry.register_far_pascal("kernel", "@134", stub_get_windows_directory, 6);
    // KERNEL.135 GetSystemDirectory(lpBuffer far, uSize) → length.
    // Same shape as @134 but resolves the system directory.
    registry.register_far_pascal("kernel", "@135", stub_get_system_directory, 6);
    // KERNEL.131 GetExePtr(handle) → the owning module handle. Echo the
    // segment/handle back (non-zero) so the caller treats it as valid.
    registry.register_far_pascal("kernel", "@131", stub_echo_1word, 2);
    // KERNEL.89 lstrcat(lpString1 far, lpString2 far) → lpString1.
    registry.register_far_pascal("kernel", "@89", stub_lstrcat, 8);
    // KERNEL.90 lstrlen(lpString far) → length.
    registry.register_far_pascal("kernel", "@90", stub_lstrlen, 4);
    // KERNEL.137 FatalAppExit(uAction, lpMessageText far).
    registry.register_far_pascal("kernel", "@137", stub_fatal_app_exit, 6);
    // KERNEL.47 GetModuleHandle(lpModuleName far) → hModule.
    registry.register_far_pascal("kernel", "@47", stub_get_module_handle, 4);
    // KERNEL.36 GetCurrentTask() → hTask.
    registry.register_far_pascal("kernel", "@36", stub_get_current_task, 0);
    // KERNEL.55 Catch(lpCatchBuf) / KERNEL.56 Throw(lpCatchBuf, nThrowBack)
    // — MFC/C setjmp / longjmp.
    registry.register_far_pascal("kernel", "@55", stub_catch, 4);
    registry.register_far_pascal("kernel", "@56", stub_throw, 6);
    // KERNEL.107 SetErrorMode(word) → previous mode (0).
    registry.register_far_pascal("kernel", "@107", stub_ret0_1word, 2);
    // KERNEL.132 GetWinFlags() → system capability flags.
    registry.register_far_pascal("kernel", "@132", stub_get_win_flags, 0);
    // Resource access: FindResource/LoadResource/LockResource/…
    registry.register_far_pascal("kernel", "@60", stub_find_resource, 10);
    registry.register_far_pascal("kernel", "@61", stub_load_resource, 4);
    registry.register_far_pascal("kernel", "@62", stub_lock_resource, 2);
    registry.register_far_pascal("kernel", "@63", stub_free_resource, 2);
    registry.register_far_pascal("kernel", "@65", stub_sizeof_resource, 4);
    // KERNEL.134 GetWindowsDirectory / KERNEL.135 GetSystemDirectory.
    registry.register_far_pascal("kernel", "@134", stub_get_windows_dir, 6);
    registry.register_far_pascal("kernel", "@135", stub_get_system_dir, 6);
}

/// `KERNEL.134 GetWindowsDirectory(lpBuffer far, uSize)` → "C:\\WINDOWS".
fn stub_get_windows_dir(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &mut Registry,
) -> Result<u32, Win32Error> {
    let n = cpu.stack_word(mmu, 4).unwrap_or(0);
    let buf = far_arg_linear(cpu, mmu, 6);
    write_guest_cstr(mmu, buf, n, b"C:\\WINDOWS")
}

/// `KERNEL.135 GetSystemDirectory(lpBuffer far, uSize)` → "C:\\WINDOWS\\SYSTEM".
fn stub_get_system_dir(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &mut Registry,
) -> Result<u32, Win32Error> {
    let n = cpu.stack_word(mmu, 4).unwrap_or(0);
    let buf = far_arg_linear(cpu, mmu, 6);
    write_guest_cstr(mmu, buf, n, b"C:\\WINDOWS\\SYSTEM")
}

/// Generic FAR PASCAL stub returning its single word argument unchanged
/// (handle/selector echo functions like `GetExePtr`).
fn stub_echo_1word(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &mut Registry,
) -> Result<u32, Win32Error> {
    Ok(u32::from(cpu.stack_word(mmu, 4).unwrap_or(0)))
}

/// `KERNEL.51 MakeProcInstance(lpProc far, hInstance)` — on real
/// Win16, returns a thunk that prepends DS to a call into `lpProc`.
/// Our emulation already passes DS through the FAR PASCAL call path,
/// so the original far pointer is callable directly; echo it back as
/// the "thunk" in `DX:AX`.
fn stub_make_proc_instance(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &mut Registry,
) -> Result<u32, Win32Error> {
    // PASCAL: hInstance (SP+8), lpProc far (SP+4..7).
    cpu.stack_dword(mmu, 4)
        .map_err(|t| crate::emulator::win32::trap_to_win32_local("MakeProcInstance", t))
}

/// `KERNEL.49 GetModuleFileName(hInst, lpFilename, nSize)` — write a
/// plausible module path into the guest buffer and return its length.
fn stub_get_module_filename(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &mut Registry,
) -> Result<u32, Win32Error> {
    // PASCAL stack: nSize (SP+4), lpFilename off (SP+6) / sel (SP+8).
    let n_size = cpu.stack_word(mmu, 4).unwrap_or(0);
    let off = cpu.stack_word(mmu, 6).unwrap_or(0);
    let sel = cpu.stack_word(mmu, 8).unwrap_or(0);
    let lin = cpu.far_to_linear(sel, off);
    write_guest_cstr(mmu, lin, n_size, b"C:\\SITEX10.EXE")
}

/// `KERNEL.134 GetWindowsDirectory(lpBuffer far, uSize)` — write
/// `"C:\\WINDOWS"` into the guest buffer and return its length.
fn stub_get_windows_directory(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &mut Registry,
) -> Result<u32, Win32Error> {
    // PASCAL: uSize (SP+4), lpBuffer off (SP+6) / sel (SP+8).
    let n_size = cpu.stack_word(mmu, 4).unwrap_or(0);
    let off = cpu.stack_word(mmu, 6).unwrap_or(0);
    let sel = cpu.stack_word(mmu, 8).unwrap_or(0);
    let lin = cpu.far_to_linear(sel, off);
    write_guest_cstr(mmu, lin, n_size, b"C:\\WINDOWS")
}

/// `KERNEL.135 GetSystemDirectory(lpBuffer far, uSize)` — write
/// `"C:\\WINDOWS\\SYSTEM"` into the guest buffer and return its length.
fn stub_get_system_directory(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &mut Registry,
) -> Result<u32, Win32Error> {
    let n_size = cpu.stack_word(mmu, 4).unwrap_or(0);
    let off = cpu.stack_word(mmu, 6).unwrap_or(0);
    let sel = cpu.stack_word(mmu, 8).unwrap_or(0);
    let lin = cpu.far_to_linear(sel, off);
    write_guest_cstr(mmu, lin, n_size, b"C:\\WINDOWS\\SYSTEM")
}

/// Write `text` (NUL-terminated) into a guest buffer of `max` bytes at
/// linear `addr`; returns the number of characters written (excluding
/// the terminator).
fn write_guest_cstr(mmu: &mut Mmu, addr: u32, max: u16, text: &[u8]) -> Result<u32, Win32Error> {
    if max == 0 {
        return Ok(0);
    }
    let limit = usize::from(max).saturating_sub(1).min(text.len());
    for (i, &b) in text.iter().take(limit).enumerate() {
        let _ = mmu.store8(addr.wrapping_add(i as u32), b);
    }
    let _ = mmu.store8(addr.wrapping_add(limit as u32), 0);
    Ok(limit as u32)
}

/// Read a NUL-terminated guest string at linear `addr` (capped).
fn read_guest_cstr(mmu: &Mmu, addr: u32, max: usize) -> Vec<u8> {
    let mut out = Vec::new();
    for i in 0..max as u32 {
        match mmu.load8(addr.wrapping_add(i)) {
            Ok(0) | Err(_) => break,
            Ok(b) => out.push(b),
        }
    }
    out
}

/// Resolve a FAR PASCAL far-pointer arg (segment:offset packed as a stack
/// dword, offset in the low word) to a linear address.
fn far_arg_linear(cpu: &Cpu, mmu: &Mmu, byte_off: u32) -> u32 {
    let v = cpu.stack_dword(mmu, byte_off).unwrap_or(0);
    cpu.far_to_linear((v >> 16) as u16, v as u16)
}

/// `KERNEL.137 FatalAppExit(uAction, lpMessageText)` — the app has
/// already surfaced its failure (typically via `MessageBox` before
/// the call) and is asking Windows to terminate it. Record the
/// optional message and request a clean run-loop exit so the
/// install-monitor report shows the app's `FatalAppExit` exit
/// rather than a synthetic trap.
fn stub_fatal_app_exit(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &mut Registry,
) -> Result<u32, Win32Error> {
    // PASCAL: uAction(SP+8), lpMessageText far(SP+4).
    let lin = far_arg_linear(cpu, mmu, 4);
    let msg = if lin == 0 {
        String::new()
    } else {
        String::from_utf8_lossy(&read_guest_cstr(mmu, lin, 1024)).into_owned()
    };
    if msg.is_empty() {
        state.message_box_log.push("FatalAppExit".into());
    } else {
        state.message_box_log.push(format!("FatalAppExit: {msg}"));
    }
    state.exit_requested = Some(0);
    state.cur_process_mut().exit_code = Some(0);
    Ok(0)
}

/// `KERNEL.90 lstrlen(lpString far)` → the string length.
fn stub_lstrlen(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &mut Registry,
) -> Result<u32, Win32Error> {
    let lin = far_arg_linear(cpu, mmu, 4);
    Ok(read_guest_cstr(mmu, lin, 0x8000).len() as u32)
}

/// `KERNEL.89 lstrcat(lpString1, lpString2)` → append string2 to string1
/// in place; returns the far pointer to string1 (DX:AX).
fn stub_lstrcat(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &mut Registry,
) -> Result<u32, Win32Error> {
    // PASCAL: lpString1 pushed first (SP+8), lpString2 last (SP+4).
    let dst_ptr = cpu.stack_dword(mmu, 8).unwrap_or(0);
    let dst_lin = cpu.far_to_linear((dst_ptr >> 16) as u16, dst_ptr as u16);
    let src_lin = far_arg_linear(cpu, mmu, 4);
    let src = read_guest_cstr(mmu, src_lin, 0x4000);
    // Find the existing terminator of the destination.
    let mut end = dst_lin;
    while !matches!(mmu.load8(end), Ok(0) | Err(_)) {
        end = end.wrapping_add(1);
    }
    for (i, &b) in src.iter().enumerate() {
        let _ = mmu.store8(end.wrapping_add(i as u32), b);
    }
    let _ = mmu.store8(end.wrapping_add(src.len() as u32), 0);
    Ok(dst_ptr)
}

/// A FAR PASCAL default window procedure (`WndProc(hWnd, msg, wParam,
/// lParam)` — 10 arg bytes in Win16). Stands in for the "original" window
/// proc of predefined control classes that MFC subclasses; returns 0.
fn stub_def_window_proc(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &mut Registry,
) -> Result<u32, Win32Error> {
    Ok(0)
}

/// Far pointer (`selector:offset`) to the default window procedure thunk,
/// registering it on first use. Callable by the guest via the import
/// selector that maps onto the registry's thunk region.
fn default_wndproc_farptr(registry: &mut Registry) -> (u16, u16) {
    let thunk = registry.register_far_pascal("user", "@_defwndproc", stub_def_window_proc, 10);
    (
        crate::emulator::ne::IMPORT_SELECTOR,
        (thunk - crate::emulator::win32::THUNK_BASE) as u16,
    )
}

/// `USER.404 GetClassInfo(hInstance, lpClassName, lpWndClass)` → BOOL. We
/// report every queried class as registered and fill the caller's
/// `WNDCLASS` with a default window procedure so MFC's subclassing of
/// predefined controls has a valid proc to chain to.
fn stub_get_class_info(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    registry: &mut Registry,
) -> Result<u32, Win32Error> {
    // PASCAL: hInstance (SP+10), lpClassName far (SP+6), lpWndClass far (SP+4).
    let out = far_arg_linear(cpu, mmu, 4);
    let (sel, off) = default_wndproc_farptr(registry);
    // Win16 WNDCLASS: style@0, lpfnWndProc@2 (off@2, sel@4).
    let _ = mmu.load16(out); // touch to fault early if unmapped
    let _ = mmu.store16(out, 0); // style
    let _ = mmu.store16(out.wrapping_add(2), off);
    let _ = mmu.store16(out.wrapping_add(4), sel);
    Ok(1)
}

/// `USER.57 RegisterClass(lpWndClass far)` → an ATOM. Parses the Win16
/// `WNDCLASS` (16-bit `style`), records the class + its window procedure
/// in the headless GUI model, and returns a non-zero atom.
fn stub_register_class(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &mut Registry,
) -> Result<u32, Win32Error> {
    let wc = far_arg_linear(cpu, mmu, 4);
    // Win16 WNDCLASS: style WORD@0, lpfnWndProc FAR@2, cbClsExtra@6,
    // cbWndExtra@8, hInstance@10, hIcon@12, hCursor@14, hbrBackground@16,
    // lpszMenuName FAR@18, lpszClassName FAR@22.
    let style = u32::from(mmu.load16(wc).unwrap_or(0));
    let wndproc_off = mmu.load16(wc.wrapping_add(2)).unwrap_or(0);
    let wndproc_sel = mmu.load16(wc.wrapping_add(4)).unwrap_or(0);
    let name_off = mmu.load16(wc.wrapping_add(22)).unwrap_or(0);
    let name_sel = mmu.load16(wc.wrapping_add(24)).unwrap_or(0);
    let name_lin = cpu.far_to_linear(name_sel, name_off);
    let name = String::from_utf8_lossy(&read_guest_cstr(mmu, name_lin, 256)).into_owned();
    state
        .gui
        .register_class(&name, wndproc_sel, wndproc_off, style);
    Ok(u32::from(state.gui.alloc_obj_handle()))
}

/// `USER.291 SetWindowsHookEx(idHook, lpfn, hMod, hTask)` → an HHOOK. We
/// don't actually dispatch hooks, but MFC stores the handle to unhook on
/// exit, so return a unique non-zero handle.
fn stub_set_windows_hook_ex(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &mut Registry,
) -> Result<u32, Win32Error> {
    Ok(u32::from(state.gui.alloc_obj_handle()))
}

/// A resource parsed from the loaded NE module, with its data.
#[derive(Debug, Clone)]
pub struct LoadedResource {
    pub type_id: crate::format::ne::ResId,
    pub name_id: crate::format::ne::ResId,
    pub data: Vec<u8>,
}

/// Read a FAR PASCAL resource-id argument (a `segment:offset` packed as a
/// stack dword): a zero selector means an integer id in the offset,
/// otherwise the offset points at a NUL-terminated name string.
fn res_id_arg(cpu: &Cpu, mmu: &Mmu, byte_off: u32) -> crate::format::ne::ResId {
    use crate::format::ne::ResId;
    let v = cpu.stack_dword(mmu, byte_off).unwrap_or(0);
    let selector = (v >> 16) as u16;
    if selector == 0 {
        ResId::Int(v as u16)
    } else {
        let lin = cpu.far_to_linear(selector, v as u16);
        ResId::Name(String::from_utf8_lossy(&read_guest_cstr(mmu, lin, 256)).into_owned())
    }
}

/// Compare two resource ids, treating names case-insensitively (Win16
/// resource lookup is case-insensitive).
fn res_id_eq(a: &crate::format::ne::ResId, b: &crate::format::ne::ResId) -> bool {
    use crate::format::ne::ResId;
    match (a, b) {
        (ResId::Int(x), ResId::Int(y)) => x == y,
        (ResId::Name(x), ResId::Name(y)) => x.eq_ignore_ascii_case(y),
        _ => false,
    }
}

/// `KERNEL.60 FindResource(hModule, lpName, lpType)` → an HRSRC (the
/// 1-based resource index, 0 if not found).
fn stub_find_resource(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &mut Registry,
) -> Result<u32, Win32Error> {
    // PASCAL push order (left-to-right): hModule (1 word), lpName (FAR
    // = 2 words), lpType (FAR = 2 words). After the FAR-return 4 bytes:
    //   SP+4..7:  lpType (last pushed, offset then segment)
    //   SP+8..11: lpName
    //   SP+12:    hModule
    let want_type = res_id_arg(cpu, mmu, 4);
    let want_name = res_id_arg(cpu, mmu, 8);
    let hrsrc = state
        .resources
        .iter()
        .position(|r| res_id_eq(&r.type_id, &want_type) && res_id_eq(&r.name_id, &want_name))
        .map_or(0, |i| i as u32 + 1);
    if std::env::var("UD_NE_STUB_DEBUG").is_ok() {
        eprintln!("FindResource type={want_type:?} name={want_name:?} -> {hrsrc}");
    }
    Ok(hrsrc)
}

/// `KERNEL.61 LoadResource(hModule, hResInfo)` → an HGLOBAL holding a copy
/// of the resource bytes (0 if the handle is invalid).
fn stub_load_resource(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &mut Registry,
) -> Result<u32, Win32Error> {
    // PASCAL: hModule (SP+6), hResInfo (SP+4).
    let hrsrc = cpu.stack_word(mmu, 4).unwrap_or(0);
    let Some(res) = state.resources.get(hrsrc.wrapping_sub(1) as usize) else {
        return Ok(0);
    };
    let data = res.data.clone();
    let sel = state.win16_heap.alloc(cpu, mmu, data.len() as u32);
    let base = cpu.far_to_linear(sel, 0);
    for (i, &b) in data.iter().enumerate() {
        let _ = mmu.store8(base.wrapping_add(i as u32), b);
    }
    Ok(u32::from(sel))
}

/// `KERNEL.62 LockResource(hResData)` → a far pointer to the resource
/// bytes. `hResData` is the HGLOBAL selector from `LoadResource`, so the
/// pointer is simply `selector:0`.
fn stub_lock_resource(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &mut Registry,
) -> Result<u32, Win32Error> {
    let sel = _cpu.stack_word(_mmu, 4).unwrap_or(0);
    // DX:AX = selector:offset → far pointer to offset 0 of the block.
    Ok(u32::from(sel) << 16)
}

/// `KERNEL.65 SizeofResource(hModule, hResInfo)` → the resource length.
fn stub_sizeof_resource(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &mut Registry,
) -> Result<u32, Win32Error> {
    let hrsrc = cpu.stack_word(mmu, 4).unwrap_or(0);
    let size = state
        .resources
        .get(hrsrc.wrapping_sub(1) as usize)
        .map_or(0, |r| r.data.len() as u32);
    Ok(size)
}

/// `KERNEL.63 FreeResource(hResData)` → 0 (we leave the global block
/// mapped; nothing to do).
fn stub_free_resource(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &mut Registry,
) -> Result<u32, Win32Error> {
    Ok(0)
}

/// `KERNEL.55 Catch(lpCatchBuf)` — MFC/C `setjmp`. Saves the resume
/// context (return `CS:IP`, `SS:SP`, `BP`, `SI`, `DI`, `DS`, `ES`) into
/// the caller's opaque buffer and returns 0. A later [`stub_throw`]
/// restores it. The buffer layout is private to this pair.
fn stub_catch(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &mut Registry,
) -> Result<u32, Win32Error> {
    use crate::emulator::emulator::isa_int::Seg;
    let ret_off = cpu.stack_word(mmu, 0).unwrap_or(0);
    let ret_seg = cpu.stack_word(mmu, 2).unwrap_or(0);
    let buf_off = cpu.stack_word(mmu, 4).unwrap_or(0);
    let buf_seg = cpu.stack_word(mmu, 6).unwrap_or(0);
    let buf = cpu.far_to_linear(buf_seg, buf_off);
    // SP the guest will have once Catch returns and cleans its 4 arg
    // bytes: current SP + 4 (far return addr) + 4 (arg).
    let sp_after = (cpu.regs.get16(Reg16::Sp)).wrapping_add(8);
    let w = |mmu: &mut Mmu, off: u32, v: u16| {
        let _ = mmu.store16(buf.wrapping_add(off), v);
    };
    w(mmu, 0, sp_after);
    w(mmu, 2, cpu.segment_selector(Seg::Ss));
    w(mmu, 4, cpu.regs.get16(Reg16::Bp));
    w(mmu, 6, cpu.regs.get16(Reg16::Si));
    w(mmu, 8, cpu.regs.get16(Reg16::Di));
    w(mmu, 10, cpu.segment_selector(Seg::Ds));
    w(mmu, 12, cpu.segment_selector(Seg::Es));
    w(mmu, 14, ret_off);
    w(mmu, 16, ret_seg);
    Ok(0)
}

/// `KERNEL.56 Throw(lpCatchBuf, nThrowBack)` — MFC/C `longjmp`. Restores
/// the context saved by [`stub_catch`] and resumes at the Catch site with
/// `AX = nThrowBack`. Implemented by restoring the registers and crafting
/// the stack so the dispatcher's far-return lands at the saved `CS:IP`.
fn stub_throw(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &mut Registry,
) -> Result<u32, Win32Error> {
    use crate::emulator::emulator::isa_int::Seg;
    // PASCAL: lpCatchBuf (SP+6), nThrowBack (SP+4).
    let throwback = cpu.stack_word(mmu, 4).unwrap_or(0);
    let buf_off = cpu.stack_word(mmu, 6).unwrap_or(0);
    let buf_seg = cpu.stack_word(mmu, 8).unwrap_or(0);
    let buf = cpu.far_to_linear(buf_seg, buf_off);
    let r = |mmu: &Mmu, off: u32| mmu.load16(buf.wrapping_add(off)).unwrap_or(0);
    let saved_sp = r(mmu, 0);
    let saved_ss = r(mmu, 2);
    let saved_bp = r(mmu, 4);
    let saved_si = r(mmu, 6);
    let saved_di = r(mmu, 8);
    let saved_ds = r(mmu, 10);
    let saved_es = r(mmu, 12);
    let ret_off = r(mmu, 14);
    let ret_seg = r(mmu, 16);
    cpu.regs.set16(Reg16::Bp, saved_bp);
    cpu.regs.set16(Reg16::Si, saved_si);
    cpu.regs.set16(Reg16::Di, saved_di);
    cpu.load_segment(Seg::Ds, saved_ds);
    cpu.load_segment(Seg::Es, saved_es);
    // Craft the stack so the dispatcher's far-return (which pops CS:IP and
    // cleans Throw's 6 arg bytes) lands at ret_seg:ret_off with SP =
    // saved_sp: final SP = sp_new + 4 + 6, so sp_new = saved_sp - 10.
    let sp_new = saved_sp.wrapping_sub(10);
    cpu.set_ss_sp(saved_ss, sp_new);
    let ss_base = cpu.seg_base(Seg::Ss);
    let _ = mmu.store16(ss_base.wrapping_add(u32::from(sp_new)), ret_off);
    let _ = mmu.store16(
        ss_base.wrapping_add(u32::from(sp_new)).wrapping_add(2),
        ret_seg,
    );
    // Returned in AX (DX cleared) — the value Catch "returns" the 2nd time.
    Ok(u32::from(throwback))
}

/// `USER.32 GetWindowRect(hWnd, lpRect far)` → fill a plausible screen
/// rectangle (the dialog uses it for centering).
fn stub_get_window_rect(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &mut Registry,
) -> Result<u32, Win32Error> {
    // PASCAL: hWnd(SP+8), lpRect far(SP+4). RECT = left,top,right,bottom.
    let r = far_arg_linear(cpu, mmu, 4);
    for (i, v) in [0u16, 0, 640, 480].iter().enumerate() {
        let _ = mmu.store16(r.wrapping_add(i as u32 * 2), *v);
    }
    Ok(1)
}

/// `USER.111 SendMessage(hWnd, msg, wParam, lParam)` → route a message to
/// our headless control model. Handles the text and button-check messages
/// the dialog uses; everything else returns 0.
fn stub_send_message(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &mut Registry,
) -> Result<u32, Win32Error> {
    // PASCAL (10 bytes): hWnd(SP+12), msg(SP+10), wParam(SP+8), lParam(SP+4).
    let hwnd = cpu.stack_word(mmu, 12).unwrap_or(0);
    let msg = cpu.stack_word(mmu, 10).unwrap_or(0);
    let wparam = cpu.stack_word(mmu, 8).unwrap_or(0);
    let lparam = cpu.stack_dword(mmu, 4).unwrap_or(0);
    let lp_lin = || cpu.far_to_linear((lparam >> 16) as u16, lparam as u16);
    match msg {
        0x000C => {
            // WM_SETTEXT: lParam → text.
            let text = String::from_utf8_lossy(&read_guest_cstr(mmu, lp_lin(), 1024)).into_owned();
            if let Some(w) = state.gui.windows.get_mut(&hwnd) {
                w.title = text;
            }
            Ok(1)
        }
        0x000D => {
            // WM_GETTEXT: wParam = max, lParam = buffer.
            let text = state
                .gui
                .windows
                .get(&hwnd)
                .map(|w| w.title.clone())
                .unwrap_or_default();
            write_guest_cstr(mmu, lp_lin(), wparam, text.as_bytes())
        }
        0x000E => {
            // WM_GETTEXTLENGTH.
            Ok(state
                .gui
                .windows
                .get(&hwnd)
                .map_or(0, |w| w.title.len() as u32))
        }
        0x00F0 => Ok(u32::from(
            state.dialog_checks.get(&hwnd).copied().unwrap_or(0),
        )), // BM_GETCHECK
        0x00F1 => {
            // BM_SETCHECK.
            state.dialog_checks.insert(hwnd, wparam);
            Ok(0)
        }
        _ => Ok(0),
    }
}

/// `USER.91 GetDlgItem(hDlg, nID)` → the child control's HWND (0 if none).
fn stub_get_dlg_item(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &mut Registry,
) -> Result<u32, Win32Error> {
    // PASCAL: hDlg (SP+6), nID (SP+4).
    let id = cpu.stack_word(mmu, 4).unwrap_or(0);
    Ok(u32::from(state.dialog_items.get(&id).copied().unwrap_or(0)))
}

/// `USER.93 GetDlgItemText(hDlg, nID, lpString far, nMax)` → copy a
/// control's text; returns the length copied.
fn stub_get_dlg_item_text(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &mut Registry,
) -> Result<u32, Win32Error> {
    // PASCAL: hDlg(SP+12), nID(SP+10), lpString far(SP+6), nMax(SP+4).
    let n_max = cpu.stack_word(mmu, 4).unwrap_or(0);
    let buf = far_arg_linear(cpu, mmu, 6);
    let id = cpu.stack_word(mmu, 10).unwrap_or(0);
    let text = state
        .dialog_items
        .get(&id)
        .and_then(|h| state.gui.windows.get(h))
        .map(|w| w.title.clone())
        .unwrap_or_default();
    if n_max == 0 {
        return Ok(0);
    }
    write_guest_cstr(mmu, buf, n_max, text.as_bytes())
}

/// `USER.92 SetDlgItemText(hDlg, nID, lpString far)` → set a control's text.
fn stub_set_dlg_item_text(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &mut Registry,
) -> Result<u32, Win32Error> {
    // PASCAL: hDlg(SP+8), nID(SP+6), lpString far(SP+4).
    let lin = far_arg_linear(cpu, mmu, 4);
    let id = cpu.stack_word(mmu, 6).unwrap_or(0);
    let text = String::from_utf8_lossy(&read_guest_cstr(mmu, lin, 1024)).into_owned();
    if let Some(&hwnd) = state.dialog_items.get(&id) {
        if let Some(w) = state.gui.windows.get_mut(&hwnd) {
            w.title = text.clone();
        }
        state
            .gui
            .events
            .push(gui::GuiEvent::SetWindowText { hwnd, text });
    }
    Ok(1)
}

/// `USER.38 GetWindowTextLength(hWnd)` → the window text length.
fn stub_get_window_text_length(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &mut Registry,
) -> Result<u32, Win32Error> {
    let hwnd = cpu.stack_word(mmu, 4).unwrap_or(0);
    Ok(state
        .gui
        .windows
        .get(&hwnd)
        .map_or(0, |w| w.title.len() as u32))
}

/// `USER.36 GetWindowText(hWnd, lpString far, nMax)` → copy the window's
/// text into the buffer; returns the length copied.
fn stub_get_window_text(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &mut Registry,
) -> Result<u32, Win32Error> {
    // PASCAL: hWnd (SP+8), lpString far (SP+4), nMax (... )? Layout:
    // hWnd(SP+8), lpString off(SP+6)/sel(SP+? ) — GetWindowText(hwnd, lp, max):
    // hWnd(SP+10), lpString far(SP+6), nMax(SP+4).
    let n_max = cpu.stack_word(mmu, 4).unwrap_or(0);
    let buf = far_arg_linear(cpu, mmu, 6);
    let hwnd = cpu.stack_word(mmu, 10).unwrap_or(0);
    let text = state
        .gui
        .windows
        .get(&hwnd)
        .map(|w| w.title.clone())
        .unwrap_or_default();
    if n_max == 0 {
        return Ok(0);
    }
    write_guest_cstr(mmu, buf, n_max, text.as_bytes())
}

/// `USER.37 SetWindowText(hWnd, lpString far)` → set the window text.
fn stub_set_window_text(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &mut Registry,
) -> Result<u32, Win32Error> {
    // PASCAL: hWnd (SP+8), lpString far (SP+4).
    let lin = far_arg_linear(cpu, mmu, 4);
    let hwnd = cpu.stack_word(mmu, 8).unwrap_or(0);
    let text = String::from_utf8_lossy(&read_guest_cstr(mmu, lin, 1024)).into_owned();
    if let Some(w) = state.gui.windows.get_mut(&hwnd) {
        w.title = text.clone();
    }
    state
        .gui
        .events
        .push(gui::GuiEvent::SetWindowText { hwnd, text });
    Ok(1)
}

/// `USER.1 MessageBox(hWnd, lpText, lpCaption, wType)` → record the prompt
/// in the GUI transcript and answer affirmatively (IDOK/IDYES) so the
/// installer proceeds.
fn stub_message_box(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &mut Registry,
) -> Result<u32, Win32Error> {
    // PASCAL (12 bytes): hWnd(SP+14), lpText far(SP+10), lpCaption far(SP+6),
    // wType(SP+4).
    let wtype = cpu.stack_word(mmu, 4).unwrap_or(0);
    let cap_lin = far_arg_linear(cpu, mmu, 6);
    let text_lin = far_arg_linear(cpu, mmu, 10);
    let caption = String::from_utf8_lossy(&read_guest_cstr(mmu, cap_lin, 512)).into_owned();
    let text = String::from_utf8_lossy(&read_guest_cstr(mmu, text_lin, 2048)).into_owned();
    // Affirmative default per button set (low nibble of wType).
    let result: u16 = match wtype & 0x000F {
        3 | 4 => 6, // MB_YESNO[CANCEL] → IDYES
        5 => 4,     // MB_RETRYCANCEL → IDRETRY
        _ => 1,     // → IDOK
    };
    state.message_box_log.push(format!("[{caption}] {text}"));
    state.gui.events.push(gui::GuiEvent::MessageBox {
        caption,
        text,
        flags: wtype,
        result,
    });
    Ok(u32::from(result))
}

/// `WM_INITDIALOG` / `WM_COMMAND` message ids.
const WM_INITDIALOG: u16 = 0x0110;
const WM_COMMAND: u16 = 0x0111;

/// `USER.87 DialogBox(hInstance, lpTemplate, hWndParent, lpDialogFunc)` →
/// run a modal dialog. We parse its template into the headless GUI model,
/// invoke the dialog procedure for `WM_INITDIALOG`, then auto-drive it by
/// posting the default command until it calls `EndDialog`. Returns the
/// `EndDialog` result.
/// `USER.89 CreateDialog(hInstance, lpTemplate, hWndParent, lpDialogFunc)`
/// → HWND of a *modeless* dialog (e.g. the install progress box). Records
/// it, creates its controls, attaches the MFC CWnd and delivers
/// WM_INITDIALOG, then returns the window handle (the program pumps it
/// itself). Off the drive path it just records the dialog.
fn stub_create_dialog(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    registry: &mut Registry,
) -> Result<u32, Win32Error> {
    let proc_off = cpu.stack_word(mmu, 4).unwrap_or(0);
    let proc_sel = cpu.stack_word(mmu, 6).unwrap_or(0);
    let tmpl_off = cpu.stack_word(mmu, 10).unwrap_or(0);
    let tmpl_sel = cpu.stack_word(mmu, 12).unwrap_or(0);
    let this_sel = cpu.segment_selector(crate::emulator::emulator::isa_int::Seg::Es);
    let this_off = cpu.regs.get16(Reg16::Bx);
    let want = if tmpl_sel == 0 {
        crate::format::ne::ResId::Int(tmpl_off)
    } else {
        let lin = cpu.far_to_linear(tmpl_sel, tmpl_off);
        crate::format::ne::ResId::Name(
            String::from_utf8_lossy(&read_guest_cstr(mmu, lin, 256)).into_owned(),
        )
    };
    let dlg = state
        .resources
        .iter()
        .find(|r| r.type_id == crate::format::ne::ResId::Int(5) && res_id_eq(&r.name_id, &want))
        .map(|r| r.data.clone());
    let (title, controls) = dlg
        .as_deref()
        .map_or_else(|| (String::new(), Vec::new()), gui::parse_dialog_template);
    state.gui.events.push(gui::GuiEvent::DialogStart {
        title,
        controls: controls.clone(),
    });
    let hdlg = state.gui.alloc_hwnd();
    // Record the controls so GetDlgItem on the modeless dialog resolves
    // (the installer updates the progress text via SetDlgItemText). We
    // don't run the dialog procedure here — a modeless dialog is pumped by
    // the program's own message loop, and the progress UI isn't needed for
    // the extraction to proceed.
    for c in &controls {
        let chwnd = state
            .gui
            .create_window(&c.class, &c.text, hdlg, c.id, c.style);
        state.dialog_items.insert(c.id, chwnd);
    }
    let _ = (proc_sel, proc_off, this_sel, this_off, registry);
    Ok(u32::from(hdlg))
}

fn stub_dialog_box(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    registry: &mut Registry,
) -> Result<u32, Win32Error> {
    // PASCAL (12 bytes): hInstance(SP+14), lpTemplate far(off SP+10/sel SP+12),
    // hWndParent(SP+8), lpDialogFunc far(off SP+4/sel SP+6).
    let proc_off = cpu.stack_word(mmu, 4).unwrap_or(0);
    let proc_sel = cpu.stack_word(mmu, 6).unwrap_or(0);
    let tmpl_off = cpu.stack_word(mmu, 10).unwrap_or(0);
    let tmpl_sel = cpu.stack_word(mmu, 12).unwrap_or(0);
    // MFC's `CWnd::DoModal` keeps the dialog object (`this`) in ES:BX right
    // up to the `DialogBox` call; capture it so the drive path can attach
    // it to the synthetic HWND in MFC's handle map.
    let this_sel = cpu.segment_selector(crate::emulator::emulator::isa_int::Seg::Es);
    let this_off = cpu.regs.get16(Reg16::Bx);

    // Resolve the template id (integer resource or a name string).
    let want = if tmpl_sel == 0 {
        crate::format::ne::ResId::Int(tmpl_off)
    } else {
        let lin = cpu.far_to_linear(tmpl_sel, tmpl_off);
        crate::format::ne::ResId::Name(
            String::from_utf8_lossy(&read_guest_cstr(mmu, lin, 256)).into_owned(),
        )
    };
    // Find the RT_DIALOG (type 5) resource whose name matches.
    let dlg = state
        .resources
        .iter()
        .find(|r| r.type_id == crate::format::ne::ResId::Int(5) && res_id_eq(&r.name_id, &want))
        .map(|r| r.data.clone());
    let (title, controls) = dlg
        .as_deref()
        .map_or_else(|| (String::new(), Vec::new()), gui::parse_dialog_template);
    state.gui.events.push(gui::GuiEvent::DialogStart {
        title,
        controls: controls.clone(),
    });

    // Driving the dialog procedure requires MFC's HWND→CWnd handle map
    // (populated by its CBT hook during real window creation), which we
    // don't yet emulate — the proc dereferences a null CWnd on
    // WM_INITDIALOG. So by default we only record the dialog and report
    // success (IDOK), letting the installer's main flow proceed. Set
    // UD_NE_DRIVE_DIALOG=1 to attempt the (currently incomplete) drive.
    if std::env::var("UD_NE_DRIVE_DIALOG").is_ok() {
        let hdlg = state.gui.alloc_hwnd();
        state.dialog_ended = false;
        state.dialog_result = 0;
        // Create a child window for every control so GetDlgItem resolves,
        // mapping control id → HWND. Seed the destination-directory edit
        // control with a default install path (the dialog input an
        // expect-style driver would supply).
        state.dialog_items.clear();
        let dest_dir = std::env::var("UD_NE_INSTALL_DIR").unwrap_or_else(|_| "C:\\EXPANDER".into());
        for c in &controls {
            let initial = if c.class.eq_ignore_ascii_case("Edit") {
                dest_dir.as_str()
            } else {
                c.text.as_str()
            };
            let chwnd = state
                .gui
                .create_window(&c.class, initial, hdlg, c.id, c.style);
            state.dialog_items.insert(c.id, chwnd);
        }
        // Replicate MFC's CBT-hook attach: register hdlg → the dialog
        // object in the handle map by calling CWnd::Attach (the function
        // right after FromHandle in the same code segment), so the proc's
        // FromHandle(hdlg) resolves. Args (FAR PASCAL): this.off, this.sel,
        // hwnd.
        let attach_off = mfc_attach_offset();
        call_guest_far16(
            cpu,
            mmu,
            registry,
            state,
            proc_sel,
            attach_off,
            &[hdlg, this_sel, this_off],
        )
        .map_err(|e| Win32Error::InvalidArgument {
            stub: "DialogBox/attach",
            reason: e.to_string(),
        })?;
        // WM_SETFONT then WM_INITDIALOG, then drive the default / OK / Cancel
        // commands until the proc calls EndDialog.
        deliver_message(
            cpu, mmu, registry, state, proc_sel, proc_off, hdlg, 0x0030, 0, 0,
        )?;
        deliver_message(
            cpu,
            mmu,
            registry,
            state,
            proc_sel,
            proc_off,
            hdlg,
            WM_INITDIALOG,
            0,
            0,
        )?;
        let mut order: Vec<u16> = controls
            .iter()
            .filter(|c| c.class.eq_ignore_ascii_case("Button") && c.style & 0x000F == 1)
            .map(|c| c.id)
            .collect();
        order.extend([1u16, 2u16]); // IDOK, IDCANCEL
        let dbg = std::env::var("UD_NE_DOS_DEBUG").is_ok();
        // The dialog-init proc (lpDialogFunc) only handles WM_INITDIALOG /
        // WM_SETFONT; it subclasses the window to MFC's AfxWndProc, which
        // is what routes WM_COMMAND through the message map to OnOK. Deliver
        // commands there (the wndproc MFC registered for the AfxWnd class).
        let (cmd_sel, cmd_off) = state
            .gui
            .classes
            .get("AfxWnd")
            .map_or((proc_sel, proc_off), |c| (c.wndproc_sel, c.wndproc_off));
        for &id in &order {
            if state.dialog_ended {
                break;
            }
            // WM_COMMAND lParam = MAKELONG(hwndCtl, BN_CLICKED=0).
            let ctl = u32::from(state.dialog_items.get(&id).copied().unwrap_or(0));
            let r = deliver_message(
                cpu, mmu, registry, state, cmd_sel, cmd_off, hdlg, WM_COMMAND, id, ctl,
            )?;
            if dbg {
                eprintln!(
                    "DRIVE WM_COMMAND id={id} -> {r:#x}, dialog_ended={}",
                    state.dialog_ended
                );
            }
        }
        return Ok(u32::from(state.dialog_result as u16));
    }
    let _ = (proc_sel, proc_off, this_sel, this_off);
    Ok(1) // IDOK
}

/// Offset of MFC's `CWnd::Attach` in the StuffIt installer's code segment.
/// Driving the dialog is binary-specific (gated behind UD_NE_DRIVE_DIALOG);
/// this lets the synthetic HWND be registered in MFC's handle map.
fn mfc_attach_offset() -> u16 {
    std::env::var("UD_NE_ATTACH_OFF")
        .ok()
        .and_then(|s| u16::from_str_radix(s.trim_start_matches("0x"), 16).ok())
        .unwrap_or(0x91a6)
}

/// Deliver one window message to a guest dialog/window procedure
/// (`hwnd, msg, wParam, lParam`) via the FAR PASCAL callback path.
#[allow(clippy::too_many_arguments)]
fn deliver_message(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    registry: &mut Registry,
    state: &mut HostState,
    proc_sel: u16,
    proc_off: u16,
    hwnd: u16,
    msg: u16,
    wparam: u16,
    lparam: u32,
) -> Result<u32, Win32Error> {
    let args = [hwnd, msg, wparam, (lparam >> 16) as u16, lparam as u16];
    call_guest_far16(cpu, mmu, registry, state, proc_sel, proc_off, &args).map_err(|e| {
        Win32Error::InvalidArgument {
            stub: "DialogBox/dlgproc",
            reason: e.to_string(),
        }
    })
}

/// `USER.88 EndDialog(hDlg, nResult)` — mark the active modal dialog as
/// finished with `nResult`; the `DialogBox` driver returns it.
fn stub_end_dialog(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &mut Registry,
) -> Result<u32, Win32Error> {
    // PASCAL: hDlg (SP+6), nResult (SP+4).
    let result = cpu.stack_word(mmu, 4).unwrap_or(0);
    if std::env::var("UD_NE_DOS_DEBUG").is_ok() {
        eprintln!("EndDialog(result={result})");
    }
    state.dialog_ended = true;
    state.dialog_result = result as i16;
    Ok(1)
}

/// First global atom value (matches Win16's `MAXINTATOM`).
const ATOM_BASE: u16 = 0xC000;

/// `USER.268 GlobalAddAtom(lpString far)` → an ATOM. Interns the string in
/// the global atom table (case-insensitive) and returns its atom.
fn stub_global_add_atom(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &mut Registry,
) -> Result<u32, Win32Error> {
    let lin = far_arg_linear(cpu, mmu, 4);
    let s = String::from_utf8_lossy(&read_guest_cstr(mmu, lin, 256)).into_owned();
    let atom = match state.atoms.iter().position(|a| a.eq_ignore_ascii_case(&s)) {
        Some(i) => ATOM_BASE + i as u16,
        None => {
            state.atoms.push(s);
            ATOM_BASE + (state.atoms.len() as u16 - 1)
        }
    };
    Ok(u32::from(atom))
}

/// `KERNEL.132 GetWinFlags()` → the system capability flags (DWORD).
/// Report protected mode, a 386, enhanced mode and an FPU.
fn stub_get_win_flags(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &mut Registry,
) -> Result<u32, Win32Error> {
    // WF_PMODE | WF_CPU386 | WF_ENHANCED | WF_80x87.
    Ok(0x0001 | 0x0004 | 0x0020 | 0x0400)
}

/// `KERNEL.36 GetCurrentTask()` → the current task handle (HTASK). We run
/// a single synthetic task.
fn stub_get_current_task(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &mut Registry,
) -> Result<u32, Win32Error> {
    Ok(u32::from(WIN16_HTASK))
}

/// `KERNEL.47 GetModuleHandle(lpModuleName far)` → the module handle. If
/// the pointer's selector is 0, Win16 treats the offset as a handle and
/// echoes it; otherwise we return our single module's hInstance.
fn stub_get_module_handle(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &mut Registry,
) -> Result<u32, Win32Error> {
    let v = cpu.stack_dword(mmu, 4).unwrap_or(0);
    let selector = (v >> 16) as u16;
    if selector == 0 {
        return Ok(u32::from(v as u16));
    }
    Ok(u32::from(WIN16_HINSTANCE))
}

/// `USER.176 LoadString(hInstance, uID, lpBuffer, nBufferMax)` → copy a
/// string-table resource into `lpBuffer`; returns the length copied (0 if
/// the id is absent).
fn stub_load_string(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &mut Registry,
) -> Result<u32, Win32Error> {
    // PASCAL: hInstance (SP+12), uID (SP+10), lpBuffer far (SP+6), nMax (SP+4).
    let n_max = cpu.stack_word(mmu, 4).unwrap_or(0);
    let buf_lin = far_arg_linear(cpu, mmu, 6);
    let uid = cpu.stack_word(mmu, 10).unwrap_or(0);
    let text = state
        .string_resources
        .get(&uid)
        .cloned()
        .unwrap_or_default();
    if n_max == 0 {
        return Ok(0);
    }
    write_guest_cstr(mmu, buf_lin, n_max, text.as_bytes())
}

/// `COMMDLG.27 GetFileTitle(lpszFile, lpszTitle, cbBuf)` → copy just the
/// filename portion of a path into `lpszTitle`; returns 0 on success.
fn stub_get_file_title(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &mut Registry,
) -> Result<u32, Win32Error> {
    // PASCAL: lpszFile (SP+10), lpszTitle (SP+6), cbBuf (SP+4).
    let cb_buf = cpu.stack_word(mmu, 4).unwrap_or(0);
    let title_lin = far_arg_linear(cpu, mmu, 6);
    let file_lin = far_arg_linear(cpu, mmu, 10);
    let path = read_guest_cstr(mmu, file_lin, 0x1000);
    // The title is the run after the last path separator (\ / :).
    let start = path
        .iter()
        .rposition(|&b| b == b'\\' || b == b'/' || b == b':')
        .map_or(0, |p| p + 1);
    let title = &path[start..];
    if u32::from(cb_buf) <= title.len() as u32 {
        // Buffer too small: return required size (incl. terminator).
        return Ok(title.len() as u32 + 1);
    }
    write_guest_cstr(mmu, title_lin, cb_buf, title)?;
    Ok(0)
}

/// `KERNEL.20 GlobalSize(hMem)` → the requested size of the block.
fn stub_global_size(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &mut Registry,
) -> Result<u32, Win32Error> {
    let handle = cpu.stack_word(mmu, 4).unwrap_or(0);
    let size = state
        .win16_heap
        .blocks
        .get(&handle)
        .map_or(0x1000, |&(_, s)| s);
    Ok(size)
}

/// `KERNEL.15 GlobalAlloc(wFlags, dwBytes)` → a fresh selector/handle
/// backed by a newly-mapped window.
fn stub_global_alloc(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &mut Registry,
) -> Result<u32, Win32Error> {
    // PASCAL: wFlags pushed first (SP+8), dwBytes (4) last (SP+4).
    let flags = cpu.stack_word(mmu, 8).unwrap_or(0);
    let size = cpu.stack_dword(mmu, 4).unwrap_or(0);
    let sel = state.win16_heap.alloc(cpu, mmu, size);
    if std::env::var("UD_NE_HEAP_DEBUG").is_ok() {
        eprintln!("  GlobalAlloc(flags={flags:#06x}, size={size:#x}) → sel={sel:#06x}");
    }
    Ok(u32::from(sel))
}

/// `KERNEL.16 GlobalReAlloc(hMem, dwBytes, wFlags)` — grow `hMem` in
/// place when it fits the existing 64 KiB selector window, otherwise
/// fall back to a fresh selector. Real Win16 keeps the handle stable
/// when the heap manager doesn't need to relocate; guests stash the
/// original selector in `DS`/`ES` and keep using it across resizes.
fn stub_global_realloc(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    state: &mut HostState,
    _registry: &mut Registry,
) -> Result<u32, Win32Error> {
    // PASCAL: hMem (SP+10), dwBytes (4) (SP+6), wFlags (SP+4).
    let h_mem = cpu.stack_word(mmu, 10).unwrap_or(0);
    let size = cpu.stack_dword(mmu, 6).unwrap_or(0);
    let flags = cpu.stack_word(mmu, 4).unwrap_or(0);
    let sel = state.win16_heap.realloc(cpu, mmu, h_mem, size);
    if std::env::var("UD_NE_HEAP_DEBUG").is_ok() {
        eprintln!(
            "  GlobalReAlloc(hMem={h_mem:#06x}, size={size:#x}, flags={flags:#06x}) \
             → sel={sel:#06x}"
        );
    }
    Ok(u32::from(sel))
}

/// `KERNEL.18 GlobalLock(hMem)` → the far pointer `selector:0000`
/// (DX = selector, AX = 0).
fn stub_global_lock(
    cpu: &mut Cpu,
    mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &mut Registry,
) -> Result<u32, Win32Error> {
    let handle = cpu.stack_word(mmu, 4).unwrap_or(0);
    Ok(u32::from(handle) << 16)
}

/// `KERNEL.23 LockSegment(seg)` → return a non-zero selector (the
/// DGROUP) so the caller treats the lock as successful.
fn stub_lock_segment(
    cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &mut Registry,
) -> Result<u32, Win32Error> {
    Ok(u32::from(cpu.ds_selector()))
}

/// Generic FAR PASCAL stub that cleans one word of args and returns 0.
fn stub_ret0_1word(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &mut Registry,
) -> Result<u32, Win32Error> {
    Ok(0)
}

/// `KERNEL.3 GetVersion()` → `0x0A03` (Windows 3.10) in AX.
fn stub_get_version(
    _cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &mut Registry,
) -> Result<u32, Win32Error> {
    // AX = 0x0A03: major = 0x03, minor = 0x0A (10) → 3.10.
    Ok(0x0003_0A03)
}

/// `KERNEL.91 InitTask()` — called once by the C startup. Sets up the
/// task and returns its parameters in registers. We populate the
/// outputs the startup reads:
///
/// * `AX` = 1 (success)        * `DX` = nCmdShow
/// * `CX` = stack top          * `SI` = hPrevInstance (0 = first)
/// * `DI` = hInstance          * `ES:BX` = command-line far pointer
fn stub_init_task(
    cpu: &mut Cpu,
    _mmu: &mut Mmu,
    _state: &mut HostState,
    _registry: &mut Registry,
) -> Result<u32, Win32Error> {
    // CX = top of the stack (the C startup does `add cx,0x100`; keep it
    // small so that add doesn't carry).
    cpu.regs.set16(Reg16::Cx, 0);
    // SI = hPrevInstance (0 → this is the first instance).
    cpu.regs.set16(Reg16::Si, 0);
    // DI = hInstance.
    cpu.regs.set16(Reg16::Di, WIN16_HINSTANCE);
    // ES:BX = the PSP and command tail. The C startup reads the
    // environment selector at PSP:0x2C (left 0) and the command tail at
    // PSP:0x80.
    cpu.regs.set16(Reg16::Bx, 0x80);
    cpu.set_segment_reg(0 /* ES */, crate::emulator::ne::PSP_SELECTOR);
    // DX:AX — AX = success (1), DX = nCmdShow.
    Ok((u32::from(SW_SHOWNORMAL) << 16) | 1)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::emulator::emulator::Cpu;

    #[test]
    fn dos_get_version_sets_al_and_clears_carry() {
        let mut cpu = Cpu::new();
        cpu.regs.flags.cf = true;
        cpu.regs.set8(Reg8::Ah, 0x30); // get DOS version
        let mut mmu = Mmu::new();
        let mut state = HostState::default();
        dos_int21(&mut cpu, &mut mmu, &mut state);
        assert_eq!(cpu.regs.get8(Reg8::Al), 6, "DOS major version in AL");
        assert!(!cpu.regs.flags.cf, "carry cleared on success");
    }

    #[test]
    fn dos_get_current_drive_returns_c() {
        let mut cpu = Cpu::new();
        cpu.regs.set8(Reg8::Ah, 0x19);
        let mut mmu = Mmu::new();
        let mut state = HostState::default();
        dos_int21(&mut cpu, &mut mmu, &mut state);
        assert_eq!(cpu.regs.get8(Reg8::Al), 2, "drive C: (0=A)");
    }

    #[test]
    fn service_interrupt_handles_21h_and_rejects_unknown() {
        let mut cpu = Cpu::new();
        let mut mmu = Mmu::new();
        let mut state = HostState::default();
        cpu.regs.set8(Reg8::Ah, 0x30);
        assert!(service_interrupt(0x21, &mut cpu, &mut mmu, &mut state));
        assert!(!service_interrupt(0x80, &mut cpu, &mut mmu, &mut state));
    }

    /// Set DS:DX to point at the host-side `path` bytes, NUL-terminated,
    /// inside a freshly-mapped buffer at `linear_base`. The DS selector
    /// is `1` and the offset is `0`, so a real `INT 21h AH=0x3D` reads
    /// the path through the standard far-pointer arg path.
    fn set_dos_ds_dx_to_path(cpu: &mut Cpu, mmu: &mut Mmu, linear_base: u32, path: &str) {
        use crate::emulator::emulator::mmu::Perm;
        mmu.map(linear_base, 0x1000, Perm::R | Perm::W);
        for (i, b) in path.bytes().enumerate() {
            mmu.store8(linear_base + i as u32, b).unwrap();
        }
        mmu.store8(linear_base + path.len() as u32, 0).unwrap();
        cpu.define_selector(1, linear_base);
        cpu.load_segment(crate::emulator::emulator::isa_int::Seg::Ds, 1);
        cpu.regs.set16(Reg16::Dx, 0);
    }

    #[test]
    fn dos_open_create_rejects_empty_path() {
        let mut cpu = Cpu::new();
        let mut mmu = Mmu::new();
        let mut state = HostState::default();
        // DS:DX = 0:0 with no selector defined → linear 0; path will be
        // empty since the address isn't mapped.
        cpu.regs.set8(Reg8::Ah, 0x3D);
        cpu.regs.set8(Reg8::Al, 0);
        dos_int21(&mut cpu, &mut mmu, &mut state);
        assert!(cpu.regs.flags.cf, "carry set on failed open");
        assert_eq!(cpu.regs.get16(Reg16::Ax), 0x02, "file-not-found");
    }

    #[test]
    fn dos_open_returns_handle_for_known_file() {
        use crate::emulator::context::{FileAccess, VirtualFs};
        let mut cpu = Cpu::new();
        let mut mmu = Mmu::new();
        let mut state = HostState::default();
        let mut vfs = VirtualFs::new();
        vfs.insert("c:\\hello.txt", b"hi".to_vec());
        state.context.vfs = Some(crate::emulator::fsmount::MountTable::with_root(vfs));
        set_dos_ds_dx_to_path(&mut cpu, &mut mmu, 0x10_0000, "C:\\HELLO.TXT");
        cpu.regs.set8(Reg8::Ah, 0x3D);
        cpu.regs.set8(Reg8::Al, 0); // read-only
        dos_int21(&mut cpu, &mut mmu, &mut state);
        assert!(!cpu.regs.flags.cf, "carry clear on successful open");
        let dh = cpu.regs.get16(Reg16::Bx); // re-read after copying handle in
        let dh_ax = cpu.regs.get16(Reg16::Ax);
        assert!(dh_ax >= 5, "DOS handle starts at 5; got {dh_ax:#x}");
        assert!(
            state.dos_handles.contains_key(&dh_ax),
            "handle table tracks it"
        );
        let _ = (FileAccess::Read, dh); // silence unused-import warning in some builds
    }

    #[test]
    fn dos_read_returns_bytes_advances_position() {
        use crate::emulator::context::VirtualFs;
        let mut cpu = Cpu::new();
        let mut mmu = Mmu::new();
        let mut state = HostState::default();
        let mut vfs = VirtualFs::new();
        vfs.insert("c:\\data.bin", b"ABCDEFGH".to_vec());
        state.context.vfs = Some(crate::emulator::fsmount::MountTable::with_root(vfs));
        // Open
        set_dos_ds_dx_to_path(&mut cpu, &mut mmu, 0x10_0000, "C:\\DATA.BIN");
        cpu.regs.set8(Reg8::Ah, 0x3D);
        cpu.regs.set8(Reg8::Al, 0);
        dos_int21(&mut cpu, &mut mmu, &mut state);
        let dh = cpu.regs.get16(Reg16::Ax);
        // Read 4 bytes into DS:DX (reuse the path buffer).
        cpu.regs.set8(Reg8::Ah, 0x3F);
        cpu.regs.set16(Reg16::Bx, dh);
        cpu.regs.set16(Reg16::Cx, 4);
        cpu.regs.set16(Reg16::Dx, 0x100); // an offset into the mapped page
        dos_int21(&mut cpu, &mut mmu, &mut state);
        assert!(!cpu.regs.flags.cf, "carry clear on successful read");
        assert_eq!(cpu.regs.get16(Reg16::Ax), 4, "read 4 bytes");
        let mut got = [0u8; 4];
        for i in 0..4 {
            got[i] = mmu.load8(0x10_0000 + 0x100 + i as u32).unwrap();
        }
        assert_eq!(&got, b"ABCD");
        // Second read should pick up where we left off.
        cpu.regs.set8(Reg8::Ah, 0x3F);
        cpu.regs.set16(Reg16::Bx, dh);
        cpu.regs.set16(Reg16::Cx, 4);
        cpu.regs.set16(Reg16::Dx, 0x100);
        dos_int21(&mut cpu, &mut mmu, &mut state);
        assert_eq!(cpu.regs.get16(Reg16::Ax), 4, "read 4 more bytes");
        for i in 0..4 {
            got[i] = mmu.load8(0x10_0000 + 0x100 + i as u32).unwrap();
        }
        assert_eq!(&got, b"EFGH");
        // Third read should return 0 (EOF).
        cpu.regs.set8(Reg8::Ah, 0x3F);
        cpu.regs.set16(Reg16::Bx, dh);
        cpu.regs.set16(Reg16::Cx, 4);
        dos_int21(&mut cpu, &mut mmu, &mut state);
        assert_eq!(cpu.regs.get16(Reg16::Ax), 0, "EOF read returns 0");
    }

    #[test]
    fn dos_write_then_read_round_trips_through_vfs() {
        let mut cpu = Cpu::new();
        let mut mmu = Mmu::new();
        let mut state = HostState::default();
        // Create a file
        set_dos_ds_dx_to_path(&mut cpu, &mut mmu, 0x10_0000, "C:\\OUT.BIN");
        cpu.regs.set8(Reg8::Ah, 0x3C); // create
        cpu.regs.set16(Reg16::Cx, 0); // attrs
        dos_int21(&mut cpu, &mut mmu, &mut state);
        assert!(!cpu.regs.flags.cf, "create succeeds");
        let dh = cpu.regs.get16(Reg16::Ax);
        // Write 4 bytes at DS:DX+0x200
        for (i, b) in b"WXYZ".iter().enumerate() {
            mmu.store8(0x10_0000 + 0x200 + i as u32, *b).unwrap();
        }
        cpu.regs.set8(Reg8::Ah, 0x40);
        cpu.regs.set16(Reg16::Bx, dh);
        cpu.regs.set16(Reg16::Cx, 4);
        cpu.regs.set16(Reg16::Dx, 0x200);
        dos_int21(&mut cpu, &mut mmu, &mut state);
        assert!(!cpu.regs.flags.cf, "write succeeds");
        assert_eq!(cpu.regs.get16(Reg16::Ax), 4, "wrote 4 bytes");
        // Seek to start
        cpu.regs.set8(Reg8::Ah, 0x42);
        cpu.regs.set8(Reg8::Al, 0); // SET
        cpu.regs.set16(Reg16::Bx, dh);
        cpu.regs.set16(Reg16::Cx, 0);
        cpu.regs.set16(Reg16::Dx, 0);
        dos_int21(&mut cpu, &mut mmu, &mut state);
        assert_eq!(cpu.regs.get16(Reg16::Ax), 0, "position low word = 0");
        // Read back
        cpu.regs.set8(Reg8::Ah, 0x3F);
        cpu.regs.set16(Reg16::Bx, dh);
        cpu.regs.set16(Reg16::Cx, 4);
        cpu.regs.set16(Reg16::Dx, 0x300);
        dos_int21(&mut cpu, &mut mmu, &mut state);
        assert_eq!(cpu.regs.get16(Reg16::Ax), 4, "read 4 bytes");
        for (i, want) in b"WXYZ".iter().enumerate() {
            assert_eq!(mmu.load8(0x10_0000 + 0x300 + i as u32).unwrap(), *want);
        }
    }

    #[test]
    fn dos_seek_end_returns_file_size() {
        use crate::emulator::context::VirtualFs;
        let mut cpu = Cpu::new();
        let mut mmu = Mmu::new();
        let mut state = HostState::default();
        let mut vfs = VirtualFs::new();
        vfs.insert("c:\\sized.bin", vec![0u8; 0x1234]); // 4660 bytes
        state.context.vfs = Some(crate::emulator::fsmount::MountTable::with_root(vfs));
        set_dos_ds_dx_to_path(&mut cpu, &mut mmu, 0x10_0000, "C:\\SIZED.BIN");
        cpu.regs.set8(Reg8::Ah, 0x3D);
        cpu.regs.set8(Reg8::Al, 0);
        dos_int21(&mut cpu, &mut mmu, &mut state);
        let dh = cpu.regs.get16(Reg16::Ax);
        // SEEK_END, offset 0 → returns file size in DX:AX.
        cpu.regs.set8(Reg8::Ah, 0x42);
        cpu.regs.set8(Reg8::Al, 2);
        cpu.regs.set16(Reg16::Bx, dh);
        cpu.regs.set16(Reg16::Cx, 0);
        cpu.regs.set16(Reg16::Dx, 0);
        dos_int21(&mut cpu, &mut mmu, &mut state);
        assert_eq!(cpu.regs.get16(Reg16::Ax), 0x1234);
        assert_eq!(cpu.regs.get16(Reg16::Dx), 0);
    }

    #[test]
    fn dos_file_attribs_reports_archive_for_known_file() {
        use crate::emulator::context::VirtualFs;
        let mut cpu = Cpu::new();
        let mut mmu = Mmu::new();
        let mut state = HostState::default();
        let mut vfs = VirtualFs::new();
        vfs.insert("c:\\flag.txt", vec![0u8; 1]);
        state.context.vfs = Some(crate::emulator::fsmount::MountTable::with_root(vfs));
        set_dos_ds_dx_to_path(&mut cpu, &mut mmu, 0x10_0000, "C:\\FLAG.TXT");
        cpu.regs.set8(Reg8::Ah, 0x43);
        cpu.regs.set8(Reg8::Al, 0); // get
        dos_int21(&mut cpu, &mut mmu, &mut state);
        assert!(!cpu.regs.flags.cf, "get-attrs succeeds for known file");
        assert_eq!(cpu.regs.get16(Reg16::Cx), 0x20, "FILE_ATTRIBUTE_ARCHIVE");
    }

    #[test]
    fn dos_file_attribs_fails_for_missing_file() {
        let mut cpu = Cpu::new();
        let mut mmu = Mmu::new();
        let mut state = HostState::default();
        set_dos_ds_dx_to_path(&mut cpu, &mut mmu, 0x10_0000, "C:\\NOPE.TXT");
        cpu.regs.set8(Reg8::Ah, 0x43);
        cpu.regs.set8(Reg8::Al, 0);
        dos_int21(&mut cpu, &mut mmu, &mut state);
        assert!(cpu.regs.flags.cf, "get-attrs fails for unknown file");
        assert_eq!(cpu.regs.get16(Reg16::Ax), 0x02, "file-not-found");
    }

    #[test]
    fn dos_ioctl_get_info_reports_regular_file() {
        use crate::emulator::context::VirtualFs;
        let mut cpu = Cpu::new();
        let mut mmu = Mmu::new();
        let mut state = HostState::default();
        let mut vfs = VirtualFs::new();
        vfs.insert("c:\\f.bin", vec![0u8; 1]);
        state.context.vfs = Some(crate::emulator::fsmount::MountTable::with_root(vfs));
        set_dos_ds_dx_to_path(&mut cpu, &mut mmu, 0x10_0000, "C:\\F.BIN");
        cpu.regs.set8(Reg8::Ah, 0x3D);
        cpu.regs.set8(Reg8::Al, 0);
        dos_int21(&mut cpu, &mut mmu, &mut state);
        let dh = cpu.regs.get16(Reg16::Ax);
        cpu.regs.set8(Reg8::Ah, 0x44);
        cpu.regs.set8(Reg8::Al, 0); // get device info
        cpu.regs.set16(Reg16::Bx, dh);
        dos_int21(&mut cpu, &mut mmu, &mut state);
        assert!(!cpu.regs.flags.cf, "ioctl succeeds for known handle");
        // Bit 15 clear = regular file (not character device).
        assert_eq!(
            cpu.regs.get16(Reg16::Dx) & 0x8000,
            0,
            "DX bit 15 clear (file, not device)"
        );
    }

    #[test]
    fn dos_close_removes_handle() {
        use crate::emulator::context::VirtualFs;
        let mut cpu = Cpu::new();
        let mut mmu = Mmu::new();
        let mut state = HostState::default();
        let mut vfs = VirtualFs::new();
        vfs.insert("c:\\x.bin", vec![0u8]);
        state.context.vfs = Some(crate::emulator::fsmount::MountTable::with_root(vfs));
        set_dos_ds_dx_to_path(&mut cpu, &mut mmu, 0x10_0000, "C:\\X.BIN");
        cpu.regs.set8(Reg8::Ah, 0x3D);
        cpu.regs.set8(Reg8::Al, 0);
        dos_int21(&mut cpu, &mut mmu, &mut state);
        let dh = cpu.regs.get16(Reg16::Ax);
        assert!(state.dos_handles.contains_key(&dh));
        cpu.regs.set8(Reg8::Ah, 0x3E);
        cpu.regs.set16(Reg16::Bx, dh);
        dos_int21(&mut cpu, &mut mmu, &mut state);
        assert!(!cpu.regs.flags.cf, "close succeeds");
        assert!(!state.dos_handles.contains_key(&dh), "handle removed");
        // Second close fails with invalid-handle.
        cpu.regs.set8(Reg8::Ah, 0x3E);
        cpu.regs.set16(Reg16::Bx, dh);
        dos_int21(&mut cpu, &mut mmu, &mut state);
        assert!(cpu.regs.flags.cf, "double-close errors");
        assert_eq!(cpu.regs.get16(Reg16::Ax), 0x06, "invalid-handle code");
    }
}