1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
//! Top-level [`Sandbox`] — owns the MMU, the CPU, the Win32 stub
//! registry, and the per-emulator host state, and exposes the
//! "load this DLL and call its DllMain" workflow that the
//! integration tests + future codec wrapper layers drive.
//!
//! This is the highest-level public entry point in the crate.
//! Round-1 exposed [`Sandbox::load`] + [`Sandbox::call_dll_main`];
//! round-2 adds the generic [`Sandbox::call_export`] helper that
//! the `vfw32` host stubs use to invoke the codec's `DriverProc`
//! synchronously.
use crate::emulator::emulator::{Cpu, Mmu, mmu::Perm};
use crate::emulator::pe::{Image, Loader};
use crate::emulator::win32::{
DATA_IMPORT_BASE, HostState, Registry, call_guest,
run_until_sentinel as run_until_sentinel_free, vfw32,
};
/// `DllMain` reason code: process is loading the DLL.
pub const DLL_PROCESS_ATTACH: u32 = 1;
/// `DllMain` reason code: process is unloading the DLL.
pub const DLL_PROCESS_DETACH: u32 = 0;
/// Default region the loader can use as the kernel32 heap arena.
/// Shrunk to the lower 96 MiB of the 0x6000_0000-0x7000_0000
/// quarter so the upper half stays free for Apple framework DLLs
/// that hard-code preferred image bases in 0x66XX_XXXX-0x68XX_XXXX
/// (quicktime.qts at 0x6680_0000, the .qtx codecs at 0x677X_XXXX,
/// qtcf.dll at 0x6864_0000, AAS CoreVideo / CoreAudioToolbox /
/// CFNetwork at similar addresses). When the VFS-DLL fallback
/// loader maps a dependent at its preferred base, the heap arena
/// no longer collides.
const HEAP_ARENA_START: u32 = 0x6000_0000;
const HEAP_ARENA_END: u32 = 0x6600_0000;
/// Const-arena region — read-only canned strings handed back from
/// `GetCommandLineA` / `GetEnvironmentStrings` etc.
const CONST_ARENA_START: u32 = 0x7000_0000;
const CONST_ARENA_END: u32 = 0x7010_0000;
/// Data-import slot region — see [`crate::emulator::win32::DATA_IMPORT_BASE`].
/// Holds 4-byte values backing CRT data imports like
/// `msvcrt!_adjust_fdiv`. 4 KiB is plenty.
const DATA_IMPORT_REGION_SIZE: u32 = 0x0000_1000;
/// Default guest stack region — plenty of room above the heap.
const STACK_BOTTOM: u32 = 0x9000_0000;
const STACK_SIZE: u32 = 0x0010_0000; // 1 MiB
const STACK_TOP: u32 = STACK_BOTTOM + STACK_SIZE;
/// Thread-stack arena. `CreateThread` carves a 64 KiB region
/// out of this pool per spawned thread, walking down from the
/// top. 0x8000_0000 .. 0x9000_0000 = 256 MiB → ~4096 aux
/// threads, plenty for codec / installer corpora.
const THREAD_STACK_POOL_BOTTOM: u32 = 0x8000_0000;
const THREAD_STACK_POOL_SIZE: u32 = 0x1000_0000; // 256 MiB
const THREAD_STACK_POOL_TOP: u32 = THREAD_STACK_POOL_BOTTOM + THREAD_STACK_POOL_SIZE;
/// Thread Environment Block — Windows places its TEB at
/// `0x7FFD_E000` historically. We map a 4 KiB page here and
/// stage the SEH chain head (`FS:[0]`) to `0xFFFF_FFFF` ("end of
/// chain"). Real Windows fills many more fields; for the codec
/// CRT init we only need a writable page so the codec's SEH
/// `__try` setup can save the prior chain head, write its own,
/// and restore on exit.
const TEB_BASE: u32 = 0x7FFD_E000;
const TEB_SIZE: u32 = 0x0000_1000; // 4 KiB
/// `EXCEPTION_REGISTRATION_RECORD*` initialiser at FS:[0].
const SEH_END_OF_CHAIN: u32 = 0xFFFF_FFFF;
/// Per-thread TIB pool. `CreateThread` carves a 4 KiB TIB out
/// of this pool per spawned thread, walking down from the
/// top. 256 KiB → 64 aux thread TIBs, well above any plausible
/// codec / installer thread count.
const TIB_POOL_BOTTOM: u32 = 0x7FFC_0000;
const TIB_POOL_SIZE: u32 = 0x0001_E000; // ~120 KiB → 30 TIBs
const TIB_POOL_TOP: u32 = TIB_POOL_BOTTOM + TIB_POOL_SIZE;
/// Child-process pools. `CreateProcessA` loads each spawned PE
/// at [`CHILD_IMAGE_BASE_START`] + N * `CHILD_IMAGE_STRIDE` and
/// gives each child a private 16 MiB heap arena out of
/// `[CHILD_HEAP_POOL_START, CHILD_HEAP_POOL_END)`. Picked above
/// the parent's mapped regions but below TEB / stack-pool
/// addresses to keep guest pointers easy to read in traces.
const CHILD_IMAGE_BASE_START: u32 = 0x1000_0000;
const CHILD_HEAP_POOL_START: u32 = 0xA000_0000;
const CHILD_HEAP_POOL_SIZE: u32 = 0x1000_0000; // 256 MiB → 16 children
const CHILD_HEAP_POOL_END: u32 = CHILD_HEAP_POOL_START + CHILD_HEAP_POOL_SIZE;
/// A guest thread under the amd64 Linux scheduler: its own [`Cpu`] (register
/// file + `%fs` TLS base) over the process-shared [`Mmu`].
struct AmdThread {
cpu: Cpu,
tid: i32,
/// `Some(addr)` while parked in `FUTEX_WAIT` on `addr`.
blocked_on: Option<u32>,
/// `CLONE_CHILD_CLEARTID` address: on thread exit, zero it and futex-wake
/// (this is what `pthread_join` waits on). `0` if unset.
clear_child_tid: u32,
exited: bool,
/// True for a child **process** (clone without `CLONE_THREAD`, or
/// `fork`/`vfork`) — these are reapable by `wait4`. False for a sibling
/// thread of the same process (`pthread_create`).
is_process: bool,
/// `Some((pid, status_ptr))` while parked in `wait4` for a child to exit
/// (`pid == -1` waits for any child).
waiting: Option<(i32, u32)>,
}
/// Wake up to `n` threads parked in `FUTEX_WAIT` on `addr`; returns the count.
fn wake_futex(threads: &mut [AmdThread], addr: u32, n: i32) -> i32 {
let mut woke = 0;
for t in threads.iter_mut() {
if woke >= n {
break;
}
if t.blocked_on == Some(addr) {
t.blocked_on = None;
woke += 1;
}
}
woke
}
/// Format a normal-exit `wait4` status word: `(code & 0xff) << 8`.
fn exit_status(code: i32) -> i32 {
(code & 0xff) << 8
}
/// Does the thread at `widx` have any child it could still wait on (a live
/// child process or an unreaped zombie)?
fn has_child(threads: &[AmdThread], widx: usize) -> bool {
threads
.iter()
.enumerate()
.any(|(i, t)| i != widx && t.is_process && !t.exited)
}
/// Try to satisfy the `wait4` parked on thread `widx` from `zombies`. On a
/// match: write the status word, set the waiter's `rax` to the child tid, clear
/// its `waiting`, and return true.
fn reap_one(
threads: &mut [AmdThread],
zombies: &mut Vec<(i32, i32)>,
mmu: &mut crate::emulator::emulator::Mmu,
widx: usize,
) -> bool {
let Some((want, status_ptr)) = threads[widx].waiting else {
return false;
};
let Some(pos) = zombies
.iter()
.position(|(tid, _)| want == -1 || want == *tid)
else {
return false;
};
let (tid, status) = zombies.remove(pos);
if status_ptr != 0 {
let _ = mmu.store32(status_ptr, status as u32);
}
threads[widx].cpu.regs.gp64[0] = tid as u64; // rax = reaped child tid
threads[widx].waiting = None;
true
}
/// Re-check every parked `wait4` against the zombie list (called after a child
/// exits), reaping as many as match.
fn reap_waiters(
threads: &mut [AmdThread],
zombies: &mut Vec<(i32, i32)>,
mmu: &mut crate::emulator::emulator::Mmu,
) {
loop {
let mut progressed = false;
for i in 0..threads.len() {
if threads[i].waiting.is_some() && reap_one(threads, zombies, mmu, i) {
progressed = true;
}
}
if !progressed {
break;
}
}
}
/// Read a NUL-terminated C string from guest memory (for `execve`'s path arg).
fn read_cstr_guest(mmu: &crate::emulator::emulator::Mmu, addr: u32) -> Option<String> {
let mut out = Vec::new();
for i in 0..4096u32 {
match mmu.load8(addr.wrapping_add(i)) {
Ok(0) => return Some(String::from_utf8_lossy(&out).into_owned()),
Ok(b) => out.push(b),
Err(_) => return None,
}
}
Some(String::from_utf8_lossy(&out).into_owned())
}
/// Run `path argv…` to completion in a **fresh** [`Sandbox`] (its own address
/// space), sharing the same root filesystem (`vfs` is moved in and back).
/// Handles one level of `#!` shebang. Returns `(exit_code, stdout, stderr)`, or
/// `None` if the program can't be read / loaded (the caller's `execve` then
/// fails with `ENOENT`).
pub(crate) fn exec_nested(
vfs: &mut crate::emulator::fsmount::MountTable,
path: &str,
argv: &[String],
envp: &[String],
budget: u64,
) -> Option<(i32, Vec<u8>, Vec<u8>)> {
let bytes = vfs.read_file(path)?;
// Shebang: re-exec the named interpreter with the script as its argument.
if bytes.starts_with(b"#!") {
let line_end = bytes
.iter()
.position(|&b| b == b'\n')
.unwrap_or(bytes.len());
let line = String::from_utf8_lossy(&bytes[2..line_end]);
let mut parts = line.split_whitespace();
let interp = parts.next()?.to_string();
let interp_arg = parts.next().map(ToString::to_string);
let mut new_argv = vec![interp.clone()];
if let Some(a) = interp_arg {
new_argv.push(a);
}
new_argv.push(path.to_string());
new_argv.extend(argv.iter().skip(1).cloned());
return exec_nested(vfs, &interp, &new_argv, envp, budget);
}
if !crate::emulator::linux::loader::is_runnable(&bytes) {
return None;
}
let mut child = Sandbox::new_linux();
child.host.instruction_budget = Some(budget);
child.linux_default_mounts = false;
let name = argv.first().cloned().unwrap_or_else(|| path.to_string());
child.linux_argv = argv.iter().skip(1).cloned().collect();
child.linux_env = envp.to_vec();
child.host.context.vfs = Some(std::mem::replace(
vfs,
crate::emulator::fsmount::MountTable::new(),
));
let code = match child.load_linux_elf(&name, &bytes) {
Ok(_) => child.run_linux().unwrap_or(-1),
Err(_) => 127,
};
*vfs = child
.host
.context
.vfs
.take()
.unwrap_or_else(crate::emulator::fsmount::MountTable::new);
Some((code, child.linux.stdout, child.linux.stderr))
}
/// Synthetic `/proc/cpuinfo` — one generic x86-64 CPU.
const PROC_CPUINFO: &str = "processor\t: 0\nvendor_id\t: GenuineIntel\n\
cpu family\t: 6\nmodel\t\t: 158\nmodel name\t: univdreams virtual CPU\n\
flags\t\t: fpu tsc cmov mmx fxsr sse sse2\nbogomips\t: 8000.00\n\n";
/// Synthetic `/proc/meminfo` — a fixed 2 GiB.
const PROC_MEMINFO: &str = "MemTotal: 2097152 kB\nMemFree: 1048576 kB\n\
MemAvailable: 1572864 kB\nBuffers: 0 kB\nCached: 0 kB\n";
/// Install the default synthetic Linux mounts (`/proc`, `/dev`) into `mounts`,
/// populating `/proc` from the current process image (`name`) and the mapped
/// memory regions.
fn install_linux_synthetic(
mounts: &mut crate::emulator::fsmount::MountTable,
regions: &[(u32, u64, crate::emulator::emulator::Perm)],
name: &str,
) {
use crate::emulator::fsmount::{devfs::DevFs, procfs::ProcFs};
let exe = format!("/{}", name.trim_start_matches('/'));
let mut procfs = ProcFs::new();
procfs.set_file("/cpuinfo", PROC_CPUINFO.as_bytes().to_vec());
procfs.set_file("/meminfo", PROC_MEMINFO.as_bytes().to_vec());
procfs.set_file(
"/version",
b"Linux version 5.15.0 (univdreams) #1 SMP\n".to_vec(),
);
let mut cmdline = name.as_bytes().to_vec();
cmdline.push(0);
procfs.set_file("/self/cmdline", cmdline);
procfs.set_symlink("/self/exe", &exe);
procfs.set_file("/self/maps", ProcFs::render_maps(regions, &exe));
procfs.set_file(
"/self/stat",
format!("1 ({name}) R 0 1 1 0 -1 0 0 0 0 0 0 0\n").into_bytes(),
);
mounts.mount("/proc", Box::new(procfs));
mounts.mount("/dev", Box::new(DevFs::new()));
}
/// `PT_LOAD` regions of a static ELF as `(start, end, perm)` — renders
/// `/proc/self/maps` for the KVM path (its flat guest memory has no useful
/// page-granular region list).
#[cfg(feature = "kvm")]
fn elf_load_regions(bytes: &[u8]) -> Vec<(u32, u64, crate::emulator::emulator::Perm)> {
use crate::emulator::emulator::Perm;
let Ok(elf) = crate::format::elf::Elf64File::parse(bytes) else {
return Vec::new();
};
elf.phdrs
.iter()
.filter(|p| p.p_type == 1) // PT_LOAD
.map(|p| {
let mut perm = Perm::default();
if p.p_flags & 4 != 0 {
perm = perm | Perm::R;
}
if p.p_flags & 2 != 0 {
perm = perm | Perm::W;
}
if p.p_flags & 1 != 0 {
perm = perm | Perm::X;
}
let start = (p.p_vaddr as u32) & !0xFFF;
let end = (p.p_vaddr + p.p_memsz + 0xFFF) & !0xFFF;
(start, end, perm)
})
.collect()
}
/// One sandbox instance per loaded codec DLL.
pub struct Sandbox {
pub mmu: Mmu,
pub cpu: Cpu,
pub registry: Registry,
pub host: HostState,
/// Linux personality state (fd table, brk/mmap, captured output, exit
/// code). Default/empty for Windows runs; populated by
/// [`Sandbox::load_linux_elf`].
pub linux: crate::emulator::linux::LinuxKernel,
/// `e_machine` of the loaded Linux ELF (selects the run loop / ABI).
/// `0` until [`Sandbox::load_linux_elf`] runs.
pub linux_machine: u16,
/// The aarch64 CPU, allocated lazily when an `EM_AARCH64` image loads
/// (the x86 [`Cpu`] cannot host that ISA).
pub aarch64: Option<Box<crate::emulator::emulator::aarch64::Aarch64Cpu>>,
/// Auto-mount synthetic `/proc` + `/dev` for Linux runs. Default `true`;
/// the CLI's `--no-default-mounts` clears it.
pub linux_default_mounts: bool,
/// Extra guest `argv` (after `argv[0]`, the program name) and the guest
/// environment. Empty by default; the CLI fills these from `--args`.
pub linux_argv: Vec<String>,
pub linux_env: Vec<String>,
}
impl Default for Sandbox {
fn default() -> Self {
Self::new()
}
}
impl Sandbox {
/// Borrow the always-on coverage map populated by the
/// interpreter. Records every dispatched instruction's
/// entry EIP plus every guest memory write. See
/// [`crate::emulator::coverage::CoverageMap`] for the consumer
/// surface.
#[must_use]
pub fn coverage(&self) -> &crate::emulator::coverage::CoverageMap {
&self.mmu.coverage
}
/// Mutable accessor for the coverage map — useful for
/// per-export resets (`coverage_mut().clear()`) between
/// runs of the same sandbox.
pub fn coverage_mut(&mut self) -> &mut crate::emulator::coverage::CoverageMap {
&mut self.mmu.coverage
}
/// Borrow the emulation-context layer (virtual filesystem,
/// virtual registry, future surfaces). Always present;
/// the per-surface options decide whether the guest
/// observes synthetic state or the fail-soft Win32
/// default. See [`crate::emulator::context::Context`].
#[must_use]
pub fn context(&self) -> &crate::emulator::context::Context {
&self.host.context
}
/// Mutable accessor for the context.
pub fn context_mut(&mut self) -> &mut crate::emulator::context::Context {
&mut self.host.context
}
/// Builder: attach a virtual filesystem so guest file-API
/// calls land in-memory instead of fail-soft no-ops. See
/// [`crate::emulator::VirtualFs`] for the stage-some-files / capture-
/// what's-written workflow.
#[must_use]
pub fn with_vfs(mut self, vfs: crate::emulator::context::VirtualFs) -> Self {
self.host.context.vfs = Some(crate::emulator::fsmount::MountTable::with_root(vfs));
self
}
/// Builder: attach a virtual registry so guest `Reg*` calls
/// observe analyst-staged keys and writes land in-memory.
/// See [`crate::emulator::VirtualRegistry`].
#[must_use]
pub fn with_registry(mut self, reg: crate::emulator::context::VirtualRegistry) -> Self {
self.host.context.registry = Some(reg);
self
}
/// Create a fresh sandbox with the heap arena and stack
/// pre-mapped, the kernel32 stub set registered, and the
/// CPU's `esp` pointing at a freshly-allocated stack.
pub fn new() -> Self {
Self::new_with_heap_end(HEAP_ARENA_END)
}
/// Like [`Self::new`] but with a caller-chosen top for the
/// malloc / `HeapAlloc` bump arena, giving decoders more
/// allocation headroom. The arena spans
/// `[HEAP_ARENA_START, heap_end)`; `heap_end` is clamped to
/// `[HEAP_ARENA_END, CONST_ARENA_START)`, so it can only grow
/// past the 96 MiB default (never shrink) and never overruns
/// the const-arena / stack regions above it — the hard ceiling
/// is `CONST_ARENA_START` (a 256 MiB arena).
///
/// Caveat: the band above the default end is also where the
/// fixed-base QuickTime helper DLLs (`.qts` / `.qtx`) load, so
/// only raise it for single-DLL codecs that don't pull those in.
/// Default heap-arena size in MiB (the [`Self::new`] value).
pub const DEFAULT_HEAP_MB: u32 = (HEAP_ARENA_END - HEAP_ARENA_START) >> 20;
/// Largest heap-arena size in MiB before the const-arena
/// ceiling; `new_with_heap_mb` clamps to this.
pub const MAX_HEAP_MB: u32 = (CONST_ARENA_START - HEAP_ARENA_START) >> 20;
/// [`Self::new_with_heap_end`] addressed in MiB: the arena is
/// sized to `heap_mb` mebibytes, clamped to
/// `[DEFAULT_HEAP_MB, MAX_HEAP_MB]`.
#[must_use]
pub fn new_with_heap_mb(heap_mb: u32) -> Self {
let end = HEAP_ARENA_START.saturating_add(heap_mb.saturating_mul(1 << 20));
Self::new_with_heap_end(end)
}
#[must_use]
pub fn new_with_heap_end(heap_end: u32) -> Self {
let heap_end = heap_end.clamp(HEAP_ARENA_END, CONST_ARENA_START);
let mut mmu = Mmu::new();
// Heap arena (R+W+X). Old codecs (e.g. Cinepak) ship
// architecture-specific inner-loop assembly that they
// copy into `malloc`'d memory at init time and then call.
// On real Windows, `HeapAlloc(GetProcessHeap, ...)` returns
// executable memory by default; modelling the same is
// simpler than chasing per-codec `VirtualProtect(PAGE_EXEC)`
// calls. Bytes still respect `mmu.write_initializer`'s
// perm rules; only the X bit is broader.
mmu.map(
HEAP_ARENA_START,
heap_end - HEAP_ARENA_START,
Perm::R | Perm::W | Perm::X,
);
// Const-arena for canned strings (R+W mapped; the caller
// ABI treats it as R-only — we use write_initializer for
// population, then any reads honour the perm bits).
mmu.map(
CONST_ARENA_START,
CONST_ARENA_END - CONST_ARENA_START,
Perm::R | Perm::W,
);
// Data-import slot region (R+W) — holds the 4-byte
// values backing CRT data imports like
// `msvcrt!_adjust_fdiv`. Seeded with each registered
// import's `initial` value.
mmu.map(DATA_IMPORT_BASE, DATA_IMPORT_REGION_SIZE, Perm::R | Perm::W);
// Stack (R+W)
mmu.map(STACK_BOTTOM, STACK_SIZE, Perm::R | Perm::W);
// Thread-stack pool (R+W). `CreateThread` carves
// 64 KiB stacks out of the top of this pool, walking
// down with each thread.
mmu.map(
THREAD_STACK_POOL_BOTTOM,
THREAD_STACK_POOL_SIZE,
Perm::R | Perm::W,
);
// Stub-thunk region (R-only, zeroed). The run loop
// detects `eip == thunk_addr` via `Registry::is_thunk`
// *before* hitting the MMU, so execution still routes
// to the stub regardless of the X bit — but codecs that
// *read* a function pointer's bytes (a hot-patch /
// forwarder probe; CamStudio does this in DllMain) need
// a mapped region behind the address. Zeros pass every
// standard "is this byte E9/EB/CC/C3?" introspection.
mmu.map(crate::emulator::win32::THUNK_BASE, 0x1_0000, Perm::R);
// TEB / FS-segment data (R+W). Initialise FS:[0] = -1
// (no SEH handler installed) and FS:[0x18] = TEB self
// pointer per the Windows TEB ABI used by Win32 CRTs.
mmu.map(TEB_BASE, TEB_SIZE, Perm::R | Perm::W);
mmu.write_initializer(TEB_BASE, &SEH_END_OF_CHAIN.to_le_bytes())
.expect("seed TEB FS:[0]");
mmu.write_initializer(TEB_BASE + 0x18, &TEB_BASE.to_le_bytes())
.expect("seed TEB FS:[0x18] (self pointer)");
// Per-thread TIB pool (R+W). `CreateThread` carves a
// fresh TIB out of this pool for each spawned thread,
// setting the new thread's FS base to its own TIB.
mmu.map(TIB_POOL_BOTTOM, TIB_POOL_SIZE, Perm::R | Perm::W);
// KUSER_SHARED_DATA + the high-memory TEB scan shelf.
// QT's QTMLInitInternals walks the usermode region
// (0x7F000000..0x7FFFFFFF) looking for per-thread TEBs
// — Windows allocates TEBs from the top of usermode
// memory down in 64 KiB increments, and Apple's code
// probes each candidate 64 KiB-aligned address for a
// TEB self-pointer signature. The probe runs DOWN the
// region until it finds an unmapped page, so map the
// full 16 MiB shelf zero-filled (R+W since codecs
// sometimes write sentinel bytes back). 0x7FFE_0000 is
// the conventional KUSER_SHARED_DATA base; zero-fill
// for SystemTime / NtSystemRoot is fine for codecs
// that only consult these for diagnostic logging.
mmu.map(0x7F00_0000, 0x00FC_0000, Perm::R | Perm::W); // 0x7F00_0000..0x7FFC_0000
mmu.map(0x7FFD_F000, 0x0002_1000, Perm::R | Perm::W); // 0x7FFD_F000..0x8000_0000
// Child-process heap pool (R+W+X). Each `CreateProcessA`
// carves a 16 MiB heap arena from this region for the
// spawned child.
mmu.map(
CHILD_HEAP_POOL_START,
CHILD_HEAP_POOL_SIZE,
Perm::R | Perm::W | Perm::X,
);
// FS:[0x30] would be the PEB pointer — we leave it 0
// until a codec actually dereferences it.
let mut cpu = Cpu::new();
cpu.regs.set_esp(STACK_TOP - 0x100); // leave a guard at the top
cpu.set_fs_base(TEB_BASE);
let mut registry = Registry::new();
registry.register_all();
// Seed data-import slot values into the mapped region.
for (_dll, _name, d) in registry.data_imports() {
mmu.write_initializer(d.addr, &d.initial.to_le_bytes())
.expect("seed data import");
}
let mut host = HostState::new(HEAP_ARENA_START, heap_end)
.with_const_arena(CONST_ARENA_START, CONST_ARENA_END)
.with_thread_stack_pool(THREAD_STACK_POOL_BOTTOM, THREAD_STACK_POOL_TOP)
.with_tib_pool(TIB_POOL_BOTTOM, TIB_POOL_TOP)
.with_child_arena(
CHILD_IMAGE_BASE_START,
CHILD_HEAP_POOL_START,
CHILD_HEAP_POOL_END,
);
// Bootstrap thread's TIB lives at the runtime-owned
// TEB_BASE (already mapped + seeded above) — mirror
// its address into ThreadState so SetLastError /
// GetLastError can also write through `fs:[0x34]`.
if let Some(t) = host.threads.get_mut(&1) {
t.tib_addr = TEB_BASE;
}
// Pre-register the system DLLs whose stub registries we
// ship as "loaded modules". Real Windows always has these
// available, and codec CRTs commonly probe them via
// `GetModuleHandleW(L"KERNEL32.DLL")` before walking their
// exports (e.g. lagarith's `_CRT_INIT` rolls back its heap
// and bails if `KERNEL32.DLL`'s handle comes back NULL).
// The handles are synthetic, distinct, non-zero values in
// the otherwise-unmapped `0x7800_0000..0x7900_0000` band.
// Codecs use these handles for identity comparisons and
// as opaque arguments to `GetProcAddress`; the band is
// clear of every other mapped region (heap, const arena,
// TEB, stack, VirtualAlloc range, thunk space) so a
// codec that tries to *walk* the handle as if it were a
// PE image gets a clean `MemoryFault` rather than
// accidentally hitting some other arena.
for (i, dll) in [
"kernel32.dll",
"user32.dll",
"gdi32.dll",
"advapi32.dll",
"ole32.dll",
"shell32.dll",
"shlwapi.dll",
"comctl32.dll",
"winmm.dll",
"msvcrt.dll",
"msvcr71.dll",
"msvcr80.dll",
"msvcr90.dll",
"pncrt.dll",
"mfplat.dll",
"version.dll",
"vfw32.dll",
// Apple framework on Windows. The QT 7.7.9 + AAS install
// drops these into `c:\common files\apple\apple
// application support\`. Their real PE images participate
// in an intra-framework loader convention that our vanilla
// loader can't model (libdispatch writes into libicuuc's
// image; CF's DllMain runs ICU-string init that
// overwrites the call_guest return-address slot). We
// host-stub the surface that qtcf/qts actually reach so
// `GetModuleHandleA("CoreFoundation.dll")` and the
// subsequent `GetProcAddress`es resolve cleanly without
// running the real DllMain chain.
"corefoundation.dll",
]
.iter()
.enumerate()
{
let handle = 0x7800_0000u32.wrapping_add((i as u32) * 0x10_0000);
host.modules.insert((*dll).to_string(), handle);
}
// Round 35 — pre-register the canonical DirectShow memory
// allocator class factory in the in-process class-factory
// cache. Codecs that internally call
// `CoCreateInstance(CLSID_MemoryAllocator, NULL, _,
// IID_IMemAllocator, &alloc)` (e.g. mpg4ds32 from inside
// `IMemInputPin::GetAllocator`) will now hit our host
// factory rather than the round-34 baseline
// `CLASS_E_CLASSNOTAVAILABLE` (`0x80040111`) miss. CLSID
// value sourced from Windows SDK header `axextend.h`.
if let Ok(factory) = crate::emulator::com::mint_host_mem_allocator_class_factory(
&mut host,
&mut mmu,
&mut registry,
) {
host.com
.register_class_factory(crate::emulator::com::CLSID_MEMORY_ALLOCATOR, factory);
}
Sandbox {
mmu,
cpu,
registry,
host,
linux: crate::emulator::linux::LinuxKernel::default(),
linux_machine: 0,
aarch64: None,
linux_default_mounts: true,
linux_argv: Vec::new(),
linux_env: Vec::new(),
}
}
/// A bare sandbox for the **Linux** personality: a fresh empty MMU and
/// CPU with none of the Win32 arenas / TEB / stub registry mapped. The
/// ELF loader maps the program's own segments and stack; syscalls are
/// serviced by [`Self::run_linux`].
#[must_use]
pub fn new_linux() -> Self {
Sandbox {
mmu: Mmu::new(),
cpu: Cpu::new(),
registry: Registry::new(),
host: HostState::default(),
linux: crate::emulator::linux::LinuxKernel::default(),
linux_machine: 0,
aarch64: None,
linux_default_mounts: true,
linux_argv: Vec::new(),
linux_env: Vec::new(),
}
}
/// Load a static Linux ELF executable: map its `PT_LOAD` segments and
/// stack, prime the CPU (flat 32-bit, `esp`/`eip`), and initialise the
/// kernel's process state. Ensures a [`VirtualFs`](crate::emulator::context::VirtualFs)
/// is attached so file syscalls have somewhere to land.
///
/// # Errors
/// [`crate::emulator::Error::NeLoader`]-style wrapping of a
/// [`crate::emulator::linux::loader::LoadError`] (bad ELF, dynamic, etc.).
pub fn load_linux_elf(
&mut self,
name: &str,
bytes: &[u8],
) -> Result<crate::emulator::linux::loader::ElfImage, crate::emulator::Error> {
use crate::format::elf::{EM_386, EM_AARCH64, EM_X86_64};
// argv[0] is the program name, then any extra `--args`; envp is the
// configured guest environment.
let mut argv: Vec<&str> = vec![name];
argv.extend(self.linux_argv.iter().map(String::as_str));
let envp: Vec<&str> = self.linux_env.iter().map(String::as_str).collect();
// The mount table must exist before loading so the dynamic linker
// (`PT_INTERP`) can be read from the guest rootfs.
let mounts = self
.host
.context
.vfs
.get_or_insert_with(crate::emulator::fsmount::MountTable::new);
let image = crate::emulator::linux::loader::load_elf(
&mut self.mmu,
Some(mounts),
bytes,
&argv,
&envp,
)
.map_err(|e| crate::emulator::Error::NeLoader(e.to_string()))?;
self.linux_machine = image.machine;
match image.machine {
EM_X86_64 => {
// x86-64 long mode on the shared x86 CPU.
self.cpu.set_code16(false);
self.cpu.set_long64(true);
self.cpu.regs.gp64 = [0; 16];
self.cpu.regs.gp64[4] = u64::from(image.stack_ptr); // rsp
self.cpu.regs.rip = u64::from(image.entry);
}
EM_AARCH64 => {
let mut cpu = Box::new(crate::emulator::emulator::aarch64::Aarch64Cpu::new());
cpu.sp = u64::from(image.stack_ptr);
cpu.pc = u64::from(image.entry);
self.aarch64 = Some(cpu);
}
// EM_386 and anything else default to the 32-bit path.
_ => {
debug_assert_eq!(image.machine, EM_386);
self.cpu.set_code16(false);
self.cpu.set_long64(false);
self.cpu.regs.set_esp(image.stack_ptr);
self.cpu.regs.eip = image.entry;
}
}
self.linux.init(image.brk);
self.host
.context
.vfs
.get_or_insert_with(crate::emulator::fsmount::MountTable::new);
if self.linux_default_mounts {
let regions = self.mmu.regions();
if let Some(mounts) = self.host.context.vfs.as_mut() {
install_linux_synthetic(mounts, ®ions, name);
}
}
Ok(image)
}
/// Run an amd64 static ELF under **KVM** (native execution), servicing its
/// syscalls through the shared [`LinuxKernel`](crate::emulator::linux::LinuxKernel).
/// The ELF is loaded into the KVM guest-memory region directly, so this
/// does *not* require a prior [`Self::load_linux_elf`]. Returns the exit
/// code. Captured stdout/stderr live in `self.linux`.
///
/// Only built with the `kvm` cargo feature (Linux x86-64 host).
///
/// # Errors
/// [`crate::emulator::Error::NeLoader`]-wrapped string if KVM is unavailable or the
/// guest faults — the caller can fall back to [`Self::run_linux`].
#[cfg(feature = "kvm")]
pub fn run_linux_kvm(
&mut self,
name: &str,
bytes: &[u8],
) -> Result<i32, crate::emulator::Error> {
let mut vfs = self
.host
.context
.vfs
.take()
.unwrap_or_else(crate::emulator::fsmount::MountTable::new);
// The KVM loader runs inside `kvm::run`, so install the synthetic
// mounts here, deriving `/proc/self/maps` from the ELF's PT_LOADs.
if self.linux_default_mounts {
install_linux_synthetic(&mut vfs, &elf_load_regions(bytes), name);
}
let mut argv: Vec<&str> = vec![name];
argv.extend(self.linux_argv.iter().map(String::as_str));
let envp: Vec<&str> = self.linux_env.iter().map(String::as_str).collect();
let result =
crate::emulator::linux::kvm::run(&mut self.linux, &mut vfs, bytes, &argv, &envp)
.map_err(|e| crate::emulator::Error::NeLoader(format!("kvm: {e}")));
self.host.context.vfs = Some(vfs);
result
}
/// Run the loaded Linux program until it calls `exit`/`exit_group`,
/// faults, or hits the instruction budget. Returns the exit code.
/// Captured stdout/stderr and any unsupported syscalls live in
/// `self.linux`.
///
/// # Errors
/// [`crate::emulator::Error::Trap`] for a CPU fault that isn't the syscall gate.
pub fn run_linux(&mut self) -> Result<i32, crate::emulator::Error> {
use crate::format::elf::{EM_AARCH64, EM_X86_64};
let mut vfs = self
.host
.context
.vfs
.take()
.unwrap_or_else(crate::emulator::fsmount::MountTable::new);
let result = match self.linux_machine {
EM_X86_64 => self.run_linux_amd64(&mut vfs),
EM_AARCH64 => self.run_linux_aarch64(&mut vfs),
_ => self.run_linux_i386(&mut vfs),
};
self.host.context.vfs = Some(vfs);
result
}
/// i386 run loop: services the `int 0x80` gate via [`I386Abi`].
fn run_linux_i386(
&mut self,
vfs: &mut crate::emulator::fsmount::MountTable,
) -> Result<i32, crate::emulator::Error> {
use crate::emulator::emulator::Trap;
use crate::emulator::emulator::isa_int::StepOk;
let abi = crate::emulator::linux::abi::I386Abi;
let budget = self.host.instruction_budget.unwrap_or(u64::MAX);
loop {
if self.cpu.instr_count >= budget {
break Ok(self.linux.exit_code.unwrap_or(-1));
}
match self.cpu.step(&mut self.mmu) {
Ok(StepOk::Continued) => {}
Ok(StepOk::Halted) => break Ok(self.linux.exit_code.unwrap_or(0)),
Err(Trap::SoftwareInterrupt { num: 0x80, .. }) => {
self.linux.dispatch(&abi, &mut self.cpu, &mut self.mmu, vfs);
if let Some(code) = self.linux.exit_code {
break Ok(code);
}
}
Err(t) => break Err(crate::emulator::Error::Trap(t)),
}
}
}
/// x86-64 run loop with a cooperative **thread scheduler**.
///
/// Each guest thread is a [`Cpu`] sharing the one [`Mmu`]; the scheduler
/// round-robins them with an instruction quantum and services the
/// `syscall` gate. `clone` (no `clone3`; glibc falls back) spawns a child
/// CPU with its own stack + `%fs` TLS base; `futex` blocks/wakes threads;
/// thread `exit` honours `CLONE_CHILD_CLEARTID` (zero + futex-wake) so
/// `pthread_join` returns; `exit_group` ends the whole process.
fn run_linux_amd64(
&mut self,
vfs: &mut crate::emulator::fsmount::MountTable,
) -> Result<i32, crate::emulator::Error> {
use crate::emulator::emulator::isa_int::StepOk;
use crate::emulator::emulator::{Cpu, Trap};
use crate::emulator::linux::abi::{Amd64Abi, LinuxAbi, Sysno};
// clone(2) flag bits we honour.
const CLONE_SETTLS: u64 = 0x0008_0000;
const CLONE_PARENT_SETTID: u64 = 0x0010_0000;
const CLONE_CHILD_CLEARTID: u64 = 0x0020_0000;
const CLONE_CHILD_SETTID: u64 = 0x0100_0000;
let abi = Amd64Abi;
let budget = self.host.instruction_budget.unwrap_or(u64::MAX);
let trace = std::env::var("UD_LINUX_TRACE").is_ok();
const QUANTUM: u64 = 20_000;
// Thread 0 = main; take the prepared CPU out of `self.cpu`.
let main_cpu = std::mem::replace(&mut self.cpu, Cpu::new());
let mut threads: Vec<AmdThread> = vec![AmdThread {
cpu: main_cpu,
tid: 1,
blocked_on: None,
clear_child_tid: 0,
exited: false,
is_process: true,
waiting: None,
}];
let mut next_tid: i32 = 2;
let mut cur = 0usize;
// Reaped-but-not-yet-waited child processes: (tid, wait-status).
let mut zombies: Vec<(i32, i32)> = Vec::new();
let result = 'sched: loop {
if let Some(code) = self.linux.exit_code {
break 'sched Ok(code);
}
let total: u64 = threads.iter().map(|t| t.cpu.instr_count).sum();
if total >= budget {
break 'sched Ok(self.linux.exit_code.unwrap_or(-1));
}
// Round-robin to the next runnable (not exited, not blocked) thread.
let n = threads.len();
let mut pick = None;
for off in 0..n {
let i = (cur + off) % n;
if !threads[i].exited
&& threads[i].blocked_on.is_none()
&& threads[i].waiting.is_none()
{
pick = Some(i);
break;
}
}
let Some(idx) = pick else {
// Nothing runnable: clean finish if all exited, else deadlock.
let code = self.linux.exit_code.unwrap_or(0);
break 'sched Ok(code);
};
cur = (idx + 1) % n;
self.linux.current_tid = threads[idx].tid;
let start = threads[idx].cpu.instr_count;
let mut spawn: Option<AmdThread> = None;
loop {
if threads[idx].cpu.instr_count - start >= QUANTUM {
break;
}
match threads[idx].cpu.step(&mut self.mmu) {
Ok(StepOk::Continued) => {}
Ok(StepOk::Halted) => {
threads[idx].exited = true;
break;
}
Err(Trap::Syscall { .. }) => {
let nr = abi.syscall_nr(&threads[idx].cpu);
let a = abi.syscall_args(&threads[idx].cpu);
match abi.map_syscall(nr) {
Some(Sysno::ExitGroup | Sysno::Exit) => {
let code = a[0] as i32;
threads[idx].exited = true;
let cct = threads[idx].clear_child_tid;
if cct != 0 {
let _ = self.mmu.store32(cct, 0);
wake_futex(&mut threads, cct, i32::MAX);
}
if threads[idx].tid == 1 {
// The main process exiting ends the run.
self.linux.exit_code = Some(code);
} else if threads[idx].is_process {
// A child process: becomes a zombie for its
// parent's wait4, doesn't end the run.
zombies.push((threads[idx].tid, exit_status(code)));
reap_waiters(&mut threads, &mut zombies, &mut self.mmu);
}
if threads.iter().all(|t| t.exited) {
self.linux.exit_code.get_or_insert(0);
}
break;
}
Some(kind @ (Sysno::Clone | Sysno::Fork | Sysno::Vfork)) => {
// fork/vfork carry no args; clone gets flags +
// child stack.
const CLONE_THREAD: u64 = 0x0001_0000;
const CLONE_VM: u64 = 0x0000_0100;
let (flags, child_stack) = match kind {
Sysno::Clone => (a[0], a[1]),
_ => (0, 0),
};
let (ptid, ctid, newtls) = (a[2] as u32, a[3] as u32, a[4]);
let tid = next_tid;
next_tid += 1;
let mut child = threads[idx].cpu.clone();
child.regs.gp64[0] = 0; // child sees rax = 0
if child_stack != 0 {
child.regs.gp64[4] = child_stack; // rsp
}
if flags & CLONE_SETTLS != 0 {
child.set_fs_base(newtls as u32);
}
abi.set_return(&mut threads[idx].cpu, i64::from(tid));
if flags & CLONE_PARENT_SETTID != 0 && ptid != 0 {
let _ = self.mmu.store32(ptid, tid as u32);
}
if flags & CLONE_CHILD_SETTID != 0 && ctid != 0 {
let _ = self.mmu.store32(ctid, tid as u32);
}
if flags & CLONE_THREAD != 0 {
// A sibling thread: runs concurrently sharing
// this process's address space.
let cct = if flags & CLONE_CHILD_CLEARTID != 0 {
ctid
} else {
0
};
spawn = Some(AmdThread {
cpu: child,
tid,
blocked_on: None,
clear_child_tid: cct,
exited: false,
is_process: false,
waiting: None,
});
} else {
// A child **process**: run it to completion
// in its own copied address space, then it
// becomes a zombie for the parent's wait4.
// (CLONE_VM children get a copy too — they
// exec immediately, so it's equivalent.)
let _ = CLONE_VM;
let mut cmmu = self.mmu.fork_copy();
let st = self.run_amd64_child(
child,
&mut cmmu,
vfs,
budget,
&mut next_tid,
);
if let Some(code) = self.linux.exit_code {
// The child propagated a whole-process exit.
let _ = code;
}
zombies.push((tid, exit_status(st)));
reap_waiters(&mut threads, &mut zombies, &mut self.mmu);
}
break;
}
Some(Sysno::Execve) => {
// Replace this thread's image: run the new
// program to completion in a fresh address space
// (its own Sandbox), then exit the thread with
// that program's status.
let path = read_cstr_guest(&self.mmu, a[0] as u32);
let argv = self.linux.read_str_array(&self.mmu, a[1] as u32);
let envp = self.linux.read_str_array(&self.mmu, a[2] as u32);
if trace {
eprintln!("execve({path:?}, {argv:?})");
}
match path.and_then(|p| exec_nested(vfs, &p, &argv, &envp, budget))
{
Some((code, out, err)) => {
self.linux.stdout.extend_from_slice(&out);
self.linux.stderr.extend_from_slice(&err);
threads[idx].exited = true;
if threads[idx].tid == 1 {
self.linux.exit_code = Some(code);
} else if threads[idx].is_process {
zombies.push((threads[idx].tid, exit_status(code)));
reap_waiters(&mut threads, &mut zombies, &mut self.mmu);
}
if threads.iter().all(|t| t.exited) {
self.linux.exit_code.get_or_insert(0);
}
break;
}
// exec failed (no such file): returns to caller.
None => abi.set_return(&mut threads[idx].cpu, -2),
}
}
Some(Sysno::Wait4) => {
let want = a[0] as i32;
let status_ptr = a[1] as u32;
let options = a[2] as u32;
threads[idx].waiting = Some((want, status_ptr));
if reap_one(&mut threads, &mut zombies, &mut self.mmu, idx) {
// Reaped immediately; rax already set.
} else if options & 1 != 0 {
// WNOHANG: don't block.
threads[idx].waiting = None;
abi.set_return(&mut threads[idx].cpu, 0);
} else if !has_child(&threads, idx) {
threads[idx].waiting = None;
abi.set_return(&mut threads[idx].cpu, -10); // ECHILD
} else {
// Block until a child exits.
break;
}
}
Some(Sysno::Futex) => {
let uaddr = a[0] as u32;
let cmd = (a[1] as u32) & 0x7f;
let val = a[2] as u32;
match cmd {
0 | 9 => {
// WAIT: block iff the word still equals `val`.
if self.mmu.load32(uaddr).unwrap_or(!val) == val {
threads[idx].blocked_on = Some(uaddr);
abi.set_return(&mut threads[idx].cpu, 0);
break;
}
abi.set_return(&mut threads[idx].cpu, -11);
// EAGAIN
}
1 | 10 => {
let woke = wake_futex(&mut threads, uaddr, val as i32);
abi.set_return(&mut threads[idx].cpu, i64::from(woke));
}
_ => abi.set_return(&mut threads[idx].cpu, 0),
}
}
Some(Sysno::SchedYield) => {
abi.set_return(&mut threads[idx].cpu, 0);
break;
}
_ => {
self.linux.dispatch(
&abi,
&mut threads[idx].cpu,
&mut self.mmu,
vfs,
);
if self.linux.exit_code.is_some() {
break;
}
}
}
}
Err(t) => {
if trace {
let rip = threads[idx].cpu.regs.rip as u32;
let mut bytes = [0u8; 16];
for (i, b) in bytes.iter_mut().enumerate() {
*b = self.mmu.load8(rip.wrapping_add(i as u32)).unwrap_or(0);
}
let regs = &threads[idx].cpu.regs.gp64;
eprintln!(
"amd64 trap (tid {}) at rip={:#018x} (#{}): {t}\n bytes: {bytes:02x?}\n gp64={regs:#x?}",
threads[idx].tid,
threads[idx].cpu.regs.rip,
threads[idx].cpu.instr_count,
);
}
if let Some(m) = threads.iter().find(|t| t.tid == 1) {
self.cpu = m.cpu.clone();
}
break 'sched Err(crate::emulator::Error::Trap(t));
}
}
}
if let Some(child) = spawn {
threads.push(child);
}
};
// Restore the main thread's CPU for post-run inspection (instr count,
// captured state).
if let Some(m) = threads.into_iter().find(|t| t.tid == 1) {
self.cpu = m.cpu;
}
result
}
/// Run a forked **child process** to completion in its own copied address
/// space (`mmu`), synchronously, and return its exit code. The `fork`
/// model: the parent blocks until the child finishes, which fits our single
/// shared-MMU engine. Handles the child's `execve` (a fresh nested
/// [`Sandbox`]), nested `fork`+`wait4`, and ordinary syscalls (which share
/// the kernel fd table + captured output). Concurrent *threads* inside a
/// forked child are not modelled (rare before `exec`).
fn run_amd64_child(
&mut self,
mut cpu: crate::emulator::emulator::Cpu,
mmu: &mut crate::emulator::emulator::Mmu,
vfs: &mut crate::emulator::fsmount::MountTable,
budget: u64,
next_pid: &mut i32,
) -> i32 {
use crate::emulator::emulator::Trap;
use crate::emulator::emulator::isa_int::StepOk;
use crate::emulator::linux::abi::{Amd64Abi, LinuxAbi, Sysno};
const CLONE_SETTLS: u64 = 0x0008_0000;
const CLONE_THREAD: u64 = 0x0001_0000;
let abi = Amd64Abi;
let mut zombies: Vec<(i32, i32)> = Vec::new();
let mut steps = 0u64;
loop {
if steps >= budget {
return -1;
}
match cpu.step(mmu) {
Ok(StepOk::Continued) => steps += 1,
Ok(StepOk::Halted) => return 0,
Err(Trap::Syscall { .. }) => {
steps += 1;
let nr = abi.syscall_nr(&cpu);
let a = abi.syscall_args(&cpu);
match abi.map_syscall(nr) {
Some(Sysno::Exit | Sysno::ExitGroup) => return a[0] as i32,
Some(Sysno::Execve) => {
let path = read_cstr_guest(mmu, a[0] as u32);
let argv = self.linux.read_str_array(mmu, a[1] as u32);
let envp = self.linux.read_str_array(mmu, a[2] as u32);
match path.and_then(|p| exec_nested(vfs, &p, &argv, &envp, budget)) {
Some((code, out, err)) => {
self.linux.stdout.extend_from_slice(&out);
self.linux.stderr.extend_from_slice(&err);
return code;
}
None => abi.set_return(&mut cpu, -2),
}
}
Some(kind @ (Sysno::Fork | Sysno::Vfork | Sysno::Clone)) => {
let (flags, child_stack) = match kind {
Sysno::Clone => (a[0], a[1]),
_ => (0, 0),
};
if flags & CLONE_THREAD != 0 {
// A thread inside a forked child — not modelled.
abi.set_return(&mut cpu, -38); // ENOSYS
} else {
let mut gchild = cpu.clone();
gchild.regs.gp64[0] = 0;
if child_stack != 0 {
gchild.regs.gp64[4] = child_stack;
}
if flags & CLONE_SETTLS != 0 {
gchild.set_fs_base(a[4] as u32);
}
let mut gmmu = mmu.fork_copy();
let tid = *next_pid;
*next_pid += 1;
abi.set_return(&mut cpu, i64::from(tid));
let st =
self.run_amd64_child(gchild, &mut gmmu, vfs, budget, next_pid);
zombies.push((tid, exit_status(st)));
}
}
Some(Sysno::Wait4) => {
let want = a[0] as i32;
let status_ptr = a[1] as u32;
if let Some(pos) =
zombies.iter().position(|(t, _)| want == -1 || want == *t)
{
let (t, s) = zombies.remove(pos);
if status_ptr != 0 {
let _ = mmu.store32(status_ptr, s as u32);
}
abi.set_return(&mut cpu, i64::from(t));
} else {
abi.set_return(&mut cpu, -10); // ECHILD
}
}
_ => {
self.linux.dispatch(&abi, &mut cpu, mmu, vfs);
if let Some(code) = self.linux.exit_code {
return code;
}
}
}
}
Err(_) => return -1, // child fault: report failure to the parent
}
}
}
/// aarch64 run loop: steps the [`Aarch64Cpu`] and services the `svc`
/// gate ([`Trap::Syscall`]) via [`Aarch64Abi`].
fn run_linux_aarch64(
&mut self,
vfs: &mut crate::emulator::fsmount::MountTable,
) -> Result<i32, crate::emulator::Error> {
use crate::emulator::emulator::Trap;
use crate::emulator::emulator::isa_int::StepOk;
let abi = crate::emulator::linux::abi::Aarch64Abi;
let budget = self.host.instruction_budget.unwrap_or(u64::MAX);
let Some(cpu) = self.aarch64.as_mut() else {
return Err(crate::emulator::Error::NeLoader(
"no aarch64 CPU loaded".into(),
));
};
loop {
if cpu.instr_count >= budget {
break Ok(self.linux.exit_code.unwrap_or(-1));
}
match cpu.step(&mut self.mmu) {
Ok(StepOk::Continued) => {}
Ok(StepOk::Halted) => break Ok(self.linux.exit_code.unwrap_or(0)),
Err(Trap::Syscall { .. }) => {
self.linux.dispatch(&abi, cpu.as_mut(), &mut self.mmu, vfs);
if let Some(code) = self.linux.exit_code {
break Ok(code);
}
}
Err(t) => break Err(crate::emulator::Error::Trap(t)),
}
}
}
/// Builder-style seed setter for the `msvcrt!rand` LCG.
///
/// PRNG state for `msvcrt!rand` calls from sandboxed codec
/// code. Default `1` matches MSVC's documented "no `srand`
/// called yet" initial value. Set via `with_rand_seed` /
/// `set_rand_seed` for reproducible encode output: two
/// sandboxes seeded identically produce identical `rand`
/// sequences, which makes encode regression tests
/// deterministic across runs.
///
/// The guest's own `msvcrt!srand(seed)` call writes to the
/// same field, so the codec may re-seed at any time; in that
/// case [`Self::rand_seed`] will report whatever value the
/// codec last installed.
///
/// Round 55.
pub fn with_rand_seed(mut self, seed: u32) -> Self {
self.host.rand_state = seed;
self
}
/// Set the `msvcrt!rand` LCG state at runtime.
///
/// Same contract as [`Self::with_rand_seed`], but mutates an
/// already-constructed sandbox — useful for tests that drive
/// multiple encode runs with different seeds, or for fuzzing
/// harnesses that want to force the codec into a known state
/// before each iteration.
///
/// Round 55.
pub fn set_rand_seed(&mut self, seed: u32) {
self.host.rand_state = seed;
}
/// Override the value `kernel32!GetCommandLineA` returns to
/// the guest. The string is stashed (NUL-terminated) in the
/// host's const arena and a pointer to it is parked at
/// `command_line_ptr`. Installer-class binaries consult
/// this to pick up `/quiet`, `/qn`, `/S` and similar
/// silent-install flags.
pub fn set_command_line(&mut self, cmdline: &str) -> Result<(), crate::emulator::Error> {
let mut bytes = cmdline.as_bytes().to_vec();
bytes.push(0);
let addr = self
.host
.arena_const_alloc(bytes.len() as u32)
.map_err(crate::emulator::Error::Win32)?;
self.mmu.write_initializer(addr, &bytes)?;
self.host.command_line_ptr = addr;
Ok(())
}
/// Read the current `msvcrt!rand` LCG state.
///
/// Reflects whatever the host or the guest last wrote: a
/// fresh sandbox returns `1` (MSVC's documented "no `srand`
/// called yet" initial value); after host
/// [`Self::set_rand_seed`] / [`Self::with_rand_seed`] returns
/// that value; after a guest `msvcrt!srand(s)` call returns
/// `s`; after any number of `msvcrt!rand` calls returns the
/// post-step LCG state.
///
/// Round 55.
pub fn rand_seed(&self) -> u32 {
self.host.rand_state
}
/// Load a PE32 image from `bytes`, mapping it into the
/// sandbox's MMU. The returned [`Image`] holds the entry
/// point + export table.
///
/// Strict-resolution: any IAT entry the
/// [`crate::emulator::win32::Registry`] doesn't satisfy is a hard
/// load-time error. Use [`Sandbox::load_fail_soft`] for
/// EXEs whose import list exceeds the codec-class stub
/// surface (installers, GUI apps, etc.).
pub fn load(&mut self, name: &str, bytes: &[u8]) -> Result<Image, crate::emulator::Error> {
let mut loader = Loader::new(&mut self.mmu, &mut self.registry, &mut self.host);
let img = loader.load(name, bytes)?;
// Record primary module base so `GetModuleHandleA(NULL)`
// returns the right value.
self.host.primary_module_base = img.image_base;
// Also record the loaded module under its filename so
// `GetModuleHandleA("name.dll")` finds it. Lower-cased,
// matching the lookup in `stub_get_module_handle_a` /
// `_w`.
self.host
.modules
.insert(name.to_ascii_lowercase(), img.image_base);
// Cache exports for later re-resolution (e.g. the MSI
// CustomAction pump that loads a Binary-table DLL once
// then dispatches multiple named entries against the
// same image).
self.host
.loaded_dll_exports
.insert(img.image_base, img.exports.clone());
Ok(img)
}
/// VFS-DLL fallback load: walk the primary PE's import
/// directory, look up every dependent DLL the host stub
/// registry doesn't know about in the sandbox VFS, and
/// (recursively) load each one at a fresh image base
/// before loading the primary. The dependent DLL's exports
/// are registered in the [`Registry`] so subsequent IAT
/// resolution against the primary picks them up. Each
/// dependent's `DllMain(PROCESS_ATTACH)` is invoked after
/// it loads (best-effort: any trap is recorded in
/// `host.debug_log` and the load continues).
///
/// Returns the primary [`Image`] plus the list of
/// `(dll, name)` import pairs that *still* resolved to a
/// fail-soft trap thunk after all VFS deps were loaded.
/// These name the missing host-side APIs (e.g. CoreVideo
/// internals we haven't shimmed) that the next iteration
/// of stub work would target.
///
/// Cycle-safe: a `currently_loading` set prevents A→B→A
/// from looping. Search order for a dependent DLL is the
/// list returned by [`crate::emulator::win32::dll_vfs_search_paths`].
pub fn load_with_deps(
&mut self,
name: &str,
bytes: &[u8],
) -> Result<(Image, Vec<(String, String)>), crate::emulator::Error> {
let mut loading: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
loading.insert(name.to_ascii_lowercase());
self.preload_deps(bytes, &mut loading)?;
loading.remove(&name.to_ascii_lowercase());
// Now load the primary in fail-soft. If the PE's
// preferred image base collides with something already
// mapped (very common for Apple binaries that all hard-
// code 0x10000000 / 0x66800000), force a rebased load
// at a fresh slot from next_dll_image_base — otherwise
// map_sections_at would overwrite the prior occupant's
// sections, breaking the previously loaded module.
let parsed = crate::emulator::pe::header::parse(bytes)?;
let preferred = parsed.optional.image_base;
let image_size = parsed.optional.size_of_image;
if !self.mmu.region_is_unmapped(preferred, image_size) {
let aligned = (image_size + 0xFFFF) & !0xFFFF;
let base = self.host.next_dll_image_base;
self.host.next_dll_image_base = base.saturating_add(aligned);
let mut options = crate::emulator::pe::LoadOptions {
imports: crate::emulator::pe::imports::ResolveMode::FailSoft,
fail_soft_log: Some(Vec::new()),
target_image_base: Some(base),
};
let mut loader = Loader::new(&mut self.mmu, &mut self.registry, &mut self.host);
let img = loader.load_with_options(name, bytes, &mut options)?;
self.host.primary_module_base = img.image_base;
self.host
.modules
.insert(name.to_ascii_lowercase(), img.image_base);
// Register exports against the canonical name so
// GetProcAddress + IAT lookups resolve.
for (export_name, rva) in &img.exports {
self.registry.register_guest_export(
name,
export_name,
img.image_base.wrapping_add(*rva),
);
}
self.host
.loaded_dll_exports
.insert(img.image_base, img.exports.clone());
return Ok((img, options.fail_soft_log.unwrap_or_default()));
}
self.load_fail_soft(name, bytes)
}
/// Recursive helper: walk `bytes`'s import directory, for
/// each not-yet-loaded, non-stub DLL look it up in the VFS,
/// load it at a fresh image base in fail-soft mode, register
/// its exports, then invoke its `DllMain(PROCESS_ATTACH)`.
fn preload_deps(
&mut self,
bytes: &[u8],
loading: &mut std::collections::BTreeSet<String>,
) -> Result<(), crate::emulator::Error> {
use crate::emulator::pe;
let parsed = match pe::header::parse(bytes) {
Ok(p) => p,
Err(_) => return Ok(()),
};
let imported = pe::imports::list_imported_dlls(&parsed, bytes).unwrap_or_default();
for dll in imported {
let dll_lc = dll.to_ascii_lowercase();
if loading.contains(&dll_lc) {
continue; // cycle — already on the load stack
}
if crate::emulator::win32::is_host_stub_dll(&dll_lc) {
continue; // kernel32 / user32 / etc. are stubbed
}
if self.host.modules.contains_key(&dll_lc) {
continue; // already loaded
}
// Look up in VFS.
let bytes_dep = {
let vfs = match self.host.context.vfs.as_ref() {
Some(v) => v,
None => continue,
};
let mut found: Option<Vec<u8>> = None;
for prefix in crate::emulator::win32::dll_vfs_search_paths() {
let p = format!("{prefix}{dll_lc}");
if let Some(b) = vfs.read(&p) {
found = Some(b.to_vec());
break;
}
}
match found {
Some(b) => b,
None => continue,
}
};
// Recurse before loading this one — DFS order.
loading.insert(dll_lc.clone());
self.preload_deps(&bytes_dep, loading)?;
// Prefer the PE's preferred image base when it's
// free — relocations can subtly break codecs that
// store absolute addresses in spots the .reloc
// table doesn't cover (Apple's QT framework code
// does this in a couple of spots). If the preferred
// base would collide with something already mapped,
// fall back to a fresh slot from next_dll_image_base.
let parsed_dep = pe::header::parse(&bytes_dep)?;
let preferred = parsed_dep.optional.image_base;
let image_size = parsed_dep.optional.size_of_image;
let aligned = (image_size + 0xFFFF) & !0xFFFF;
let preferred_free = self.mmu.region_is_unmapped(preferred, image_size);
let base = if preferred_free {
preferred
} else {
let b = self.host.next_dll_image_base;
self.host.next_dll_image_base = b.saturating_add(aligned);
b
};
let mut options = pe::LoadOptions {
imports: pe::imports::ResolveMode::FailSoft,
fail_soft_log: Some(Vec::new()),
target_image_base: Some(base),
};
let mut loader = Loader::new(&mut self.mmu, &mut self.registry, &mut self.host);
let img = match loader.load_with_options(&dll_lc, &bytes_dep, &mut options) {
Ok(i) => i,
Err(e) => {
self.host
.debug_log
.push(format!("vfs-dll {dll_lc}: load failed: {e}"));
loading.remove(&dll_lc);
continue;
}
};
// Register the dep's exports so the primary's IAT
// can patch through. Same dll-name normalisation
// the import resolver uses.
for (export_name, rva) in &img.exports {
let addr = img.image_base.wrapping_add(*rva);
self.registry
.register_guest_export(&dll_lc, export_name, addr);
}
self.host
.loaded_dll_exports
.insert(img.image_base, img.exports.clone());
self.host.modules.insert(dll_lc.clone(), img.image_base);
self.host
.debug_log
.push(format!("vfs-dll {dll_lc}: loaded at {base:#010x}"));
// Invoke DllMain. Skip data-only DLLs (no DllMain
// export AND AddressOfEntryPoint == 0 — common for
// ICU resource bundles and similar). Errors from
// dep DllMain don't abort the parent load: most QT
// codecs reach their Component Manager entry without
// ever calling the framework DLL's TLS-touching
// init paths, so a half-init dep is often workable.
let has_dll_main = img.exports.contains_key("DllMain");
let has_entry = parsed_dep.optional.address_of_entry_point != 0;
if has_dll_main || has_entry {
if let Err(e) = self.call_dll_main(&img, DLL_PROCESS_ATTACH) {
self.host
.debug_log
.push(format!("vfs-dll {dll_lc}: DllMain trapped: {e}"));
}
} else {
self.host
.debug_log
.push(format!("vfs-dll {dll_lc}: data-only DLL, no DllMain"));
}
loading.remove(&dll_lc);
}
Ok(())
}
/// Load a PE32 image in fail-soft import-resolution mode.
/// Imports the codec-class stub registry doesn't satisfy
/// get a trap-on-call fallback thunk so the load succeeds.
/// Returns the loaded [`Image`] plus the list of
/// `(dll, name)` pairs that received a fallback — i.e.
/// the set of APIs the operator now knows the binary uses
/// but we don't yet stub.
///
/// Intended for the install-monitor workflow: load
/// QuickTimeInstaller.exe with fail-soft, drive the entry
/// point, watch the trap stream for the next missing API.
pub fn load_fail_soft(
&mut self,
name: &str,
bytes: &[u8],
) -> Result<(Image, Vec<(String, String)>), crate::emulator::Error> {
let mut options = crate::emulator::pe::LoadOptions {
imports: crate::emulator::pe::imports::ResolveMode::FailSoft,
fail_soft_log: Some(Vec::new()),
target_image_base: None,
};
let mut loader = Loader::new(&mut self.mmu, &mut self.registry, &mut self.host);
let img = loader.load_with_options(name, bytes, &mut options)?;
self.host.primary_module_base = img.image_base;
self.host
.modules
.insert(name.to_ascii_lowercase(), img.image_base);
// Cache exports so re-resolution against the loaded DLL
// (MSI CA pump, multiple GetProcAddress lookups) finds
// them.
self.host
.loaded_dll_exports
.insert(img.image_base, img.exports.clone());
Ok((img, options.fail_soft_log.unwrap_or_default()))
}
/// Synchronously call `DllMain(hModule, fdwReason, lpvReserved)`
/// inside the emulator and return the dword `eax` value at
/// the point the function returned to the synthetic
/// `RET_SENTINEL`.
///
/// The DllMain ABI is stdcall (callee-cleanup), so we push
/// `lpvReserved` first, then `fdwReason`, then `hModule`,
/// then the return-address sentinel. The callee's `RET 12`
/// (or equivalent) cleans the args.
///
/// Resolution: prefer the `DllMain` named export (Indeo
/// codecs); fall back to the PE `AddressOfEntryPoint`
/// (mpg4c32.dll and other CRT-startup-driven DLLs that
/// don't export `DllMain` by name). Both expose the same
/// stdcall (HINSTANCE, DWORD, LPVOID) ABI.
pub fn call_dll_main(
&mut self,
image: &Image,
reason: u32,
) -> Result<u32, crate::emulator::Error> {
let h_module = image.image_base;
let lpv_reserved = 0u32;
// Always prefer the PE `AddressOfEntryPoint` for DLLs: the
// OS loader calls THAT (typically `_DllMainCRTStartup`, the
// linker-generated wrapper) and it in turn runs the CRT
// init (_CRT_INIT / _initterm) before invoking the user's
// DllMain. Some DLLs additionally *export* a function
// literally named "DllMain" — qts does — but that's the
// bare user function, NOT the CRT wrapper. Calling it
// directly bypasses CRT init: FLS/TLS slot allocation,
// env block setup, etc., never run, and downstream
// qtmlclient!EnterMovies spins in an infinite
// `_getptd()` retry loop hitting `TlsGetValue(TLS_OUT_OF_INDEXES)`.
// Fall back to a `DllMain` export only when the PE has
// no entry point at all (rare; old hand-written DLLs).
let target = if image.entry_point != 0 {
image.entry_point
} else {
image.export("DllMain").unwrap_or(0)
};
if target == 0 {
return Err(crate::emulator::Error::Win32(
crate::emulator::win32::Win32Error::InvalidArgument {
stub: "call_dll_main",
reason: format!(
"no DllMain export and no PE entry point in {:?}",
image.name
),
},
));
}
call_guest(
&mut self.cpu,
&mut self.mmu,
&mut self.registry,
&mut self.host,
target,
&[h_module, reason, lpv_reserved],
)
}
/// Pump any deferred MSI CustomActions that the msiexec
/// walker queued during a previous `CreateProcessA(msiexec.exe)`
/// dispatch. For each pending DLL CA: load the Binary-table
/// DLL bytes into the sandbox at a fresh image base, set
/// up an `MsiSession` so the msi.dll stubs can answer
/// property queries against the walker's snapshot, and
/// call the CA's named export with `MSIHANDLE = 1`.
/// EXE / script CAs are logged + skipped (unsupported).
///
/// Returns the number of CAs successfully executed (CAs
/// that trapped or returned non-zero are counted as
/// attempted; the failure is captured in `host.debug_log`).
pub fn pump_pending_msi_install(&mut self) -> usize {
let Some(pending) = self.host.pending_msi_install.take() else {
return 0;
};
// Set up the in-process MSI session with our property
// snapshot. The MSIHANDLE is just an opaque token; we
// use 1 since there's at most one install at a time.
self.host.msi_session = Some(crate::emulator::win32::MsiSession {
handle: 1,
properties: pending.properties.clone(),
target_paths: pending
.properties
.iter()
.filter(|(k, _)| k.chars().next().is_some_and(char::is_uppercase))
.map(|(k, v)| (k.clone(), v.clone()))
.collect(),
});
let mut executed = 0;
for ca in pending.actions {
// Only DLL CAs of type 1 (immediate) / 0xC01 (deferred)
// and similar in-process DLL shapes are runnable here.
let kind = ca.action_type & 0x3F;
if kind != 1 && kind != 17 {
self.host.debug_log.push(format!(
"msiexec CA {:?}: skipped, type {:#x} (kind {:#x}) not a DLL CA",
ca.name, ca.action_type, kind
));
continue;
}
// For kind == 1 the Source column is a Binary-table
// key, for kind == 17 it's a File-table key. We
// only have Binary streams cached here.
let Some(bytes) = pending.binaries.get(&ca.source).cloned() else {
self.host.debug_log.push(format!(
"msiexec CA {:?}: Binary {:?} not in table, skipping",
ca.name, ca.source
));
continue;
};
// Load the DLL at a fresh image base. We register
// the loaded bytes against `ca.source` so subsequent
// CAs that reference the same binary share the load.
let dll_key = ca.source.to_ascii_lowercase();
let img = if let Some(&base) = self.host.modules.get(&dll_key) {
// Already loaded — synthesise an Image from the
// cached exports.
let exports = self
.host
.loaded_dll_exports
.get(&base)
.cloned()
.unwrap_or_default();
crate::emulator::pe::Image {
name: ca.source.clone(),
image_base: base,
entry_point: base,
size_of_image: 0,
sections: Vec::new(),
exports,
}
} else {
// Install-time DLLs (QTInstallCode, QTMSISupport,
// SxsUninstallCA, AppleApplicationSupport_CustomActions)
// share Apple's standard 0x10000000 preferred base.
// If we let them grab that, qtmlclient.dll has to
// rebase later and its absolute-addressed
// dispatcher slots break. Force-rebase install
// DLLs to next_dll_image_base so the preferred
// base stays free for the post-install runtime
// bring-up.
let parsed = match crate::emulator::pe::header::parse(&bytes) {
Ok(p) => p,
Err(e) => {
self.host.debug_log.push(format!(
"msiexec CA {:?}: parse {:?} failed: {e}",
ca.name, ca.source
));
continue;
}
};
let image_size = parsed.optional.size_of_image;
let aligned = (image_size + 0xFFFF) & !0xFFFF;
let install_base = self.host.next_dll_image_base;
self.host.next_dll_image_base = install_base.saturating_add(aligned);
let mut options = crate::emulator::pe::LoadOptions {
imports: crate::emulator::pe::imports::ResolveMode::FailSoft,
fail_soft_log: Some(Vec::new()),
target_image_base: Some(install_base),
};
let mut loader = Loader::new(&mut self.mmu, &mut self.registry, &mut self.host);
let img = match loader.load_with_options(&ca.source, &bytes, &mut options) {
Ok(i) => i,
Err(e) => {
self.host.debug_log.push(format!(
"msiexec CA {:?}: load {:?} failed: {e}",
ca.name, ca.source
));
continue;
}
};
self.host.primary_module_base = img.image_base;
self.host
.modules
.insert(ca.source.to_ascii_lowercase(), img.image_base);
self.host
.loaded_dll_exports
.insert(img.image_base, img.exports.clone());
for (name, rva) in &img.exports {
self.registry.register_guest_export(
&ca.source,
name,
img.image_base.wrapping_add(*rva),
);
}
// Best-effort DllMain.
if let Err(e) = self.call_dll_main(&img, crate::emulator::DLL_PROCESS_ATTACH) {
self.host.debug_log.push(format!(
"msiexec CA {:?}: {} DllMain trapped: {e}",
ca.name, ca.source
));
}
img
};
let Some(rva) = img.exports.get(&ca.target).copied() else {
self.host.debug_log.push(format!(
"msiexec CA {:?}: export {:?} not in {:?}",
ca.name, ca.target, ca.source
));
continue;
};
let entry = img.image_base.wrapping_add(rva);
// Call the CA's entry with MSIHANDLE = 1.
self.host.debug_log.push(format!(
"msiexec CA {:?}: calling {:?}({:?})",
ca.name, ca.target, 1
));
// Clear sticky exit_requested from the prior CA's
// TerminateProcess / ExitProcess so the next
// run_until_sentinel doesn't bail immediately.
self.host.exit_requested = None;
match crate::emulator::win32::call_guest(
&mut self.cpu,
&mut self.mmu,
&mut self.registry,
&mut self.host,
entry,
&[1],
) {
Ok(rc) => {
let signed = rc as i32;
self.host.debug_log.push(format!(
"msiexec CA {:?}: {:?} returned {rc:#x} ({signed})",
ca.name, ca.target
));
executed += 1;
}
Err(e) => {
self.host.debug_log.push(format!(
"msiexec CA {:?}: {:?} trapped: {e}",
ca.name, ca.target
));
}
}
}
self.host.msi_session = None;
executed
}
/// Generic stdcall guest-call helper. Resolves `name` against
/// `image`'s export table, pushes `args` right-to-left + the
/// `RET_SENTINEL`, and runs until the callee returns.
/// Returns `eax`.
///
/// Used both internally (by [`Self::call_dll_main`]) and by
/// future codec adapter layers that need to drive arbitrary
/// codec exports — `DriverProc`, `MyCodecGetVersion`,
/// `MyCodecExtraInit`, etc. The round-2 `vfw32::ic_*` host
/// surface uses [`crate::emulator::win32::call_guest`] directly with
/// the codec's `DriverProc` VA.
pub fn call_export(
&mut self,
image: &Image,
name: &str,
args: &[u32],
) -> Result<u32, crate::emulator::Error> {
let target = image.export(name).ok_or_else(|| {
crate::emulator::Error::Win32(crate::emulator::win32::Win32Error::InvalidArgument {
stub: "call_export",
reason: format!("export {name:?} not found in {:?}", image.name),
})
})?;
call_guest(
&mut self.cpu,
&mut self.mmu,
&mut self.registry,
&mut self.host,
target,
args,
)
}
/// Call the image's PE entry point (`AddressOfEntryPoint`).
/// For an EXE this is the CRT startup, which expects no
/// arguments and never returns under normal Windows
/// semantics (it calls `ExitProcess`). Here it runs until
/// the runtime returns to the synthetic `RET_SENTINEL` or
/// hits a trap (e.g. unresolved import, instruction limit).
pub fn call_entry_point(&mut self, image: &Image) -> Result<u32, crate::emulator::Error> {
if image.entry_point == 0 {
return Err(crate::emulator::Error::Win32(
crate::emulator::win32::Win32Error::InvalidArgument {
stub: "call_entry_point",
reason: format!("no PE entry point in {:?}", image.name),
},
));
}
call_guest(
&mut self.cpu,
&mut self.mmu,
&mut self.registry,
&mut self.host,
image.entry_point,
&[],
)
}
/// Call an arbitrary guest code address — an indirect / computed
/// call target the export table can't name. Pushes `args`
/// right-to-left + the `RET_SENTINEL` and runs until the callee
/// returns; returns `eax`.
///
/// This is the address-taking analogue of [`Self::call_export`]:
/// where `call_export` resolves a name against an image's export
/// table, `call_addr` takes the resolved VA directly. That lets a
/// script drive dispatch paths a name lookup can't reach — COM
/// vtable slots (walk `*ppv` → `*obj` → `*(vtbl + n*4)`), callback
/// thunks staged via `mapBlob`, or jump-table entries — by reading
/// the target pointer out of guest memory and calling through it.
///
/// # Errors
/// Returns [`crate::emulator::win32::Win32Error::InvalidArgument`] for a null
/// target, and propagates any CPU trap raised while running the
/// callee (unresolved import, instruction-budget exhaustion, …).
pub fn call_addr(&mut self, addr: u32, args: &[u32]) -> Result<u32, crate::emulator::Error> {
if addr == 0 {
return Err(crate::emulator::Error::Win32(
crate::emulator::win32::Win32Error::InvalidArgument {
stub: "call_addr",
reason: "null call target".into(),
},
));
}
call_guest(
&mut self.cpu,
&mut self.mmu,
&mut self.registry,
&mut self.host,
addr,
args,
)
}
/// Load a 16-bit Windows NE module in fail-soft mode: every
/// imported ordinal is wired to a trap-on-call thunk, so the run
/// stops at the first Win16 API the stub surface doesn't cover
/// (the NE analogue of [`Self::load_fail_soft`]). Returns the
/// [`crate::emulator::ne::NeImage`] describing how to enter it.
///
/// # Errors
/// Returns [`crate::emulator::Error::NeLoader`] if the bytes are not a valid
/// NE or a segment fails to map.
pub fn load_ne_fail_soft(
&mut self,
name: &str,
bytes: &[u8],
) -> Result<crate::emulator::ne::NeImage, crate::emulator::Error> {
// Register the Win16 API stub surface so the loader's
// relocation pass resolves known ordinals (KERNEL.91, …) to
// real stubs and only falls back to trap-on-call for the rest.
crate::emulator::win16::register_all(&mut self.registry);
let image = crate::emulator::ne::load_ne(&mut self.mmu, &mut self.registry, bytes)
.map_err(|e| crate::emulator::Error::NeLoader(e.to_string()))?;
self.host.modules.insert(
name.to_ascii_lowercase(),
crate::emulator::ne::WIN16_SEG_BASE,
);
// Stage the EXE's own bytes into the VFS at the path
// `GetModuleFileName` reports. Win16 installers (StuffIt
// SITEX10, classic InstallShield, …) fopen their own EXE
// to seek past the loaded module image and read an
// appended archive of bundled files. Without the EXE in
// the VFS, `INT 21h AH=0x3D` returns ENOFILE and the
// install's CRT marches through a null pointer into REP
// MOVSW. Set `UD_NE_NO_STAGE_SELF=1` to opt out (useful
// for installers whose integrity scan diverges into a
// multi-GB read loop when paired with a tamper bypass).
if std::env::var("UD_NE_NO_STAGE_SELF").is_err() {
let self_path = format!("C:\\{}", name.to_uppercase());
let vfs = self
.host
.context
.vfs
.get_or_insert_with(crate::emulator::fsmount::MountTable::new);
vfs.insert(&self_path, bytes.to_vec());
}
// Parse string + general resources for LoadString / FindResource.
if let Ok(ne) = crate::format::ne::NeFile::parse(bytes) {
self.host.string_resources = ne.string_resources();
self.host.resources = ne
.resources()
.into_iter()
.map(|r| {
let off = r.file_offset as usize;
let len = r.length as usize;
let data = bytes.get(off..off + len).unwrap_or(&[]).to_vec();
crate::emulator::win16::LoadedResource {
type_id: r.type_id,
name_id: r.name_id,
data,
}
})
.collect();
}
// SITEX10's installer runs a self-integrity / anti-tamper check
// early in InitInstance that CRCs its own loaded segments and
// compares against stored values; our memory layout (synthetic
// import selectors patched in by relocation) can never match, so it
// aborts with "This copy of Setup has been changed without
// authorization". With UD_NE_PATCH_TAMPER=1, force-bypass each
// tamper gate by rewriting its leading `75 rel` (JNZ on
// failure/show-messagebox-when-zero) to `EB rel` (unconditional
// skip to the success continuation).
//
// Sites and their pass-target relative offsets:
// seg2:0x2e01 / 0x2e21 — InitInstance integrity verify.
// seg2:0x2ea3 — re-runs in the Install-button click handler.
// seg2:0x2ef5 — the actual `if(SI==0) show_tamper_messagebox`
// guard; bypasses the GUI loop where the
// messagebox re-fires per Install click.
//
// In-memory only — the on-disk file is untouched.
if std::env::var("UD_NE_PATCH_TAMPER").is_ok() {
let seg2 = crate::emulator::ne::WIN16_SEG_BASE + crate::emulator::ne::WIN16_SEG_STRIDE;
for (off, rel) in [
(0x2e01u32, 0x14u8),
(0x2e21, 0x29),
(0x2ea3, 0x26),
(0x2ef5, 0x4b),
] {
let lin = seg2 + off;
if self.mmu.load8(lin) == Ok(0x75) {
let _ = self.mmu.store8(lin, 0xEB);
let _ = self.mmu.store8(lin + 1, rel);
}
}
}
Ok(image)
}
/// Drive a loaded NE module's entry point in 16-bit segmented
/// mode. Primes the CPU's selectors, `CS:IP`, `SS:SP` and DGROUP
/// data segments from `image`, pushes a far-return sentinel, then
/// runs until the entry returns or — in fail-soft mode — traps at
/// the first imported Win16 call. Mirrors [`Self::call_entry_point`].
///
/// # Errors
/// Propagates any CPU trap (including the fail-soft
/// [`crate::emulator::emulator::Trap::UnresolvedImport`] that marks the first
/// unimplemented Win16 API).
pub fn call_ne_entry(
&mut self,
image: &crate::emulator::ne::NeImage,
) -> Result<u32, crate::emulator::Error> {
use crate::emulator::emulator::isa_int::{RET_SENTINEL, Seg};
use crate::emulator::emulator::regs::Reg32;
// Enter 16-bit segmented mode and install the selector table.
self.cpu.set_code16(true);
for &(sel, base) in &image.selectors {
self.cpu.define_selector(sel, base);
}
// Far-return sentinel selector → RET_SENTINEL linear address.
self.cpu
.define_selector(crate::emulator::ne::SENTINEL_SELECTOR, RET_SENTINEL);
// Initial stack, then push a far-return sentinel (CS:IP) so a
// top-level RETF halts the run loop.
self.cpu.set_ss_sp(image.init_ss, image.init_sp);
self.cpu
.push16(&mut self.mmu, crate::emulator::ne::SENTINEL_SELECTOR)?;
self.cpu.push16(&mut self.mmu, 0)?;
// DGROUP: DS/ES point at the automatic data segment.
if image.auto_data != 0 {
self.cpu.load_segment(Seg::Ds, image.auto_data);
self.cpu.load_segment(Seg::Es, image.auto_data);
}
self.cpu.set_cs_ip(image.entry_cs, image.entry_ip);
// Reset the bootstrap thread to a clean runnable state — the
// same hygiene `call_guest` applies before a top-level entry.
if self.host.active_tid == 1 {
let quantum = self.host.scheduler.quantum_default;
let t = self.host.cur_thread_mut();
t.status = crate::emulator::sched::ThreadStatus::Ready;
t.wait = None;
t.quantum_remaining = quantum;
}
self.host.exit_requested = None;
run_until_sentinel_free(
&mut self.cpu,
&mut self.mmu,
&mut self.registry,
&mut self.host,
)?;
Ok(self.cpu.regs.get32(Reg32::Eax))
}
/// Drive the CPU until `eip == RET_SENTINEL`, dispatching to
/// Win32 stubs whenever `eip` lands on a registered thunk
/// address. Thin wrapper over [`crate::emulator::win32::run_until_sentinel`]
/// kept for API stability.
pub fn run_until_sentinel(&mut self) -> Result<(), crate::emulator::Error> {
run_until_sentinel_free(
&mut self.cpu,
&mut self.mmu,
&mut self.registry,
&mut self.host,
)
}
// ---- vfw32 IC* convenience wrappers ------------------------------
/// Mark `image` as the codec the next [`Self::ic_open`] call
/// should target.
///
/// Round 2 supports a single codec image per sandbox — round 3
/// will lift that into a multi-codec registry. The image must
/// export `DriverProc`.
pub fn install_codec(&mut self, image: &Image) -> Result<(), crate::emulator::Error> {
let dp = image.export("DriverProc").ok_or_else(|| {
crate::emulator::Error::Win32(crate::emulator::win32::Win32Error::InvalidArgument {
stub: "install_codec",
reason: format!("DriverProc not exported by {:?}", image.name),
})
})?;
self.host.default_driver_proc = dp;
Ok(())
}
/// Open the installed codec (`DRV_OPEN`).
pub fn ic_open(
&mut self,
fcc_type: u32,
fcc_handler: u32,
mode: u32,
) -> Result<u32, crate::emulator::Error> {
vfw32::ic_open(
&mut self.cpu,
&mut self.mmu,
&mut self.registry,
&mut self.host,
fcc_type,
fcc_handler,
mode,
)
}
/// Close a codec instance (`DRV_CLOSE`).
pub fn ic_close(&mut self, hic: u32) -> Result<u32, crate::emulator::Error> {
vfw32::ic_close(
&mut self.cpu,
&mut self.mmu,
&mut self.registry,
&mut self.host,
hic,
)
}
/// Read the codec's `ICINFO` block.
pub fn ic_get_info(&mut self, hic: u32, cb: u32) -> Result<Vec<u8>, crate::emulator::Error> {
vfw32::ic_get_info(
&mut self.cpu,
&mut self.mmu,
&mut self.registry,
&mut self.host,
hic,
cb,
)
}
/// `ICDecompressQuery` — does the codec accept this format?
pub fn ic_decompress_query(
&mut self,
hic: u32,
input: &vfw32::Bih,
output: Option<&vfw32::Bih>,
) -> Result<u32, crate::emulator::Error> {
vfw32::ic_decompress_query(
&mut self.cpu,
&mut self.mmu,
&mut self.registry,
&mut self.host,
hic,
input,
output,
)
}
/// `ICDecompressGetFormat` — ask the codec for the output BIH
/// matching `input`. Round 30 uses this to probe stream
/// dimensions when `CodecParameters` lacks them.
pub fn ic_decompress_get_format(
&mut self,
hic: u32,
input: &vfw32::Bih,
) -> Result<(u32, vfw32::Bih), crate::emulator::Error> {
vfw32::ic_decompress_get_format(
&mut self.cpu,
&mut self.mmu,
&mut self.registry,
&mut self.host,
hic,
input,
)
}
/// `ICDecompressBegin` — set up the decoder pipeline.
pub fn ic_decompress_begin(
&mut self,
hic: u32,
input: &vfw32::Bih,
output: &vfw32::Bih,
) -> Result<u32, crate::emulator::Error> {
vfw32::ic_decompress_begin(
&mut self.cpu,
&mut self.mmu,
&mut self.registry,
&mut self.host,
hic,
input,
output,
)
}
/// `ICDecompressEnd` — tear down the decoder pipeline.
pub fn ic_decompress_end(&mut self, hic: u32) -> Result<u32, crate::emulator::Error> {
vfw32::ic_decompress_end(
&mut self.cpu,
&mut self.mmu,
&mut self.registry,
&mut self.host,
hic,
)
}
// ---- Trace-mode programmatic API (gated on the `trace`
// ---- Cargo feature). Documented in
// ---- `docs/winmf/winmf-emulator.md` §"Trace mode".
/// Install a memory watchpoint covering `[addr, addr+size)`.
/// Any guest access whose address range intersects the
/// watchpoint emits a `kind=mem_write` (or `mem_read`) JSONL
/// event to the configured sink. Multiple watchpoints may
/// overlap; each fires independently.
#[cfg(feature = "trace")]
pub fn watch(&mut self, addr: u32, size: u32, mode: crate::emulator::trace::WatchMode) {
self.mmu.trace.watch(addr, size, mode);
}
/// Remove watchpoints whose `(addr, size)` exactly matches.
/// Mode is ignored for the match.
#[cfg(feature = "trace")]
pub fn unwatch(&mut self, addr: u32, size: u32) {
self.mmu.trace.unwatch(addr, size);
}
/// Toggle per-instruction execution trace at runtime. Has no
/// effect unless the crate was built with the `trace-exec`
/// sub-feature.
#[cfg(feature = "trace")]
pub fn set_exec_trace(&mut self, on: bool) {
self.mmu.trace.exec_on = on;
}
/// Override the trace JSONL sink at runtime. Defaults to
/// honouring `OXIDEAV_VFW_TRACE_FILE`.
#[cfg(feature = "trace")]
pub fn set_trace_sink(&mut self, sink: Box<dyn std::io::Write + Send>) {
self.mmu.trace.set_sink(sink);
}
// ---- COM / DirectShow surface (round 25) ------------------------
/// Drive `DllGetClassObject(rclsid, riid, ppv)` on `image`,
/// staging the GUID arguments + the `ppv` out-slot in a
/// freshly-allocated heap region inside the sandbox. On
/// success returns the guest pointer the codec wrote into
/// `*ppv` — typically a guest-side `IClassFactory`.
///
/// When `riid == IID_IClassFactory`, the returned pointer is
/// also registered with [`crate::emulator::com::ComObjectTable::register_class_factory`]
/// keyed under `clsid`, so subsequent
/// [`Self::co_create_instance`] calls can resolve `clsid`
/// without re-driving `DllGetClassObject`.
///
/// MSDN: `HRESULT DllGetClassObject(REFCLSID rclsid, REFIID
/// riid, LPVOID *ppv)` — every COM in-process server
/// exports it; DirectShow filter binaries (`.ax`) export it
/// instead of `DriverProc`.
pub fn dll_get_class_object(
&mut self,
image: &crate::emulator::pe::Image,
clsid: crate::emulator::com::Guid,
riid: crate::emulator::com::Guid,
) -> Result<u32, crate::emulator::Error> {
let target = image.export("DllGetClassObject").ok_or_else(|| {
crate::emulator::Error::Win32(crate::emulator::win32::Win32Error::InvalidArgument {
stub: "dll_get_class_object",
reason: format!("DllGetClassObject not exported by {:?}", image.name),
})
})?;
// Stage the two GUIDs + the out-pointer slot in
// contiguous arena memory: 16 + 16 + 4 = 36 bytes.
let scratch = self
.host
.arena_alloc(36)
.map_err(crate::emulator::Error::Win32)?;
clsid
.stage(&mut self.mmu, scratch)
.map_err(crate::emulator::Error::Trap)?;
riid.stage(&mut self.mmu, scratch + 16)
.map_err(crate::emulator::Error::Trap)?;
// Zero the ppv slot.
self.mmu
.write_initializer(scratch + 32, &0u32.to_le_bytes())
.map_err(crate::emulator::Error::Trap)?;
let hr = call_guest(
&mut self.cpu,
&mut self.mmu,
&mut self.registry,
&mut self.host,
target,
&[scratch, scratch + 16, scratch + 32],
)?;
if hr != crate::emulator::com::S_OK {
return Err(crate::emulator::Error::Win32(
crate::emulator::win32::Win32Error::InvalidArgument {
stub: "dll_get_class_object",
reason: format!("DllGetClassObject returned HRESULT {hr:#010x}"),
},
));
}
let out_ptr = self
.mmu
.load32(scratch + 32)
.map_err(crate::emulator::Error::Trap)?;
if out_ptr == 0 {
return Err(crate::emulator::Error::Win32(
crate::emulator::win32::Win32Error::InvalidArgument {
stub: "dll_get_class_object",
reason: "DllGetClassObject succeeded but *ppv is NULL".into(),
},
));
}
// Bookkeep the new object. If it is a class factory,
// also register it under `clsid` so `CoCreateInstance`
// can pick it up.
self.host.com.intern(out_ptr, Some(riid));
if riid == crate::emulator::com::IID_ICLASSFACTORY {
self.host.com.register_class_factory(clsid, out_ptr);
}
Ok(out_ptr)
}
/// Drive `CoCreateInstance(clsid, NULL, CLSCTX_INPROC_SERVER,
/// riid, ppv)` against the in-process class-factory cache.
/// The CLSID must already be registered (typically by a
/// prior [`Self::dll_get_class_object`] call); otherwise
/// surfaces `CLASS_E_CLASSNOTAVAILABLE` as an error.
pub fn co_create_instance(
&mut self,
clsid: crate::emulator::com::Guid,
riid: crate::emulator::com::Guid,
) -> Result<u32, crate::emulator::Error> {
let factory = self.host.com.lookup_class_factory(&clsid).ok_or_else(|| {
crate::emulator::Error::Win32(crate::emulator::win32::Win32Error::InvalidArgument {
stub: "co_create_instance",
reason: format!(
"CLSID {clsid} not registered; \
call dll_get_class_object first"
),
})
})?;
// Stage IID + out slot.
let scratch = self
.host
.arena_alloc(20)
.map_err(crate::emulator::Error::Win32)?;
riid.stage(&mut self.mmu, scratch)
.map_err(crate::emulator::Error::Trap)?;
self.mmu
.write_initializer(scratch + 16, &0u32.to_le_bytes())
.map_err(crate::emulator::Error::Trap)?;
let r = crate::emulator::com::call::call_method(
&mut self.cpu,
&mut self.mmu,
&mut self.registry,
&mut self.host,
factory,
crate::emulator::com::SLOT_CLASS_FACTORY_CREATE_INSTANCE,
&[0, scratch, scratch + 16],
)?;
if r != crate::emulator::com::S_OK {
return Err(crate::emulator::Error::Win32(
crate::emulator::win32::Win32Error::InvalidArgument {
stub: "co_create_instance",
reason: format!("CreateInstance returned HRESULT {r:#010x}"),
},
));
}
let out = self
.mmu
.load32(scratch + 16)
.map_err(crate::emulator::Error::Trap)?;
if out != 0 {
self.host.com.intern(out, Some(riid));
}
Ok(out)
}
/// Drive `obj->QueryInterface(riid, ppv)` on a guest COM
/// object, staging the IID + out-slot in arena memory.
/// Returns the new interface pointer on success, or surfaces
/// the HRESULT in an error message.
pub fn query_interface(
&mut self,
obj: u32,
riid: crate::emulator::com::Guid,
) -> Result<u32, crate::emulator::Error> {
let scratch = self
.host
.arena_alloc(20)
.map_err(crate::emulator::Error::Win32)?;
riid.stage(&mut self.mmu, scratch)
.map_err(crate::emulator::Error::Trap)?;
self.mmu
.write_initializer(scratch + 16, &0u32.to_le_bytes())
.map_err(crate::emulator::Error::Trap)?;
let r = crate::emulator::com::call::query_interface(
&mut self.cpu,
&mut self.mmu,
&mut self.registry,
&mut self.host,
obj,
scratch,
scratch + 16,
)?;
if r != crate::emulator::com::S_OK {
return Err(crate::emulator::Error::Win32(
crate::emulator::win32::Win32Error::InvalidArgument {
stub: "query_interface",
reason: format!("QueryInterface returned HRESULT {r:#010x}"),
},
));
}
let out = self
.mmu
.load32(scratch + 16)
.map_err(crate::emulator::Error::Trap)?;
if out != 0 {
self.host.com.intern(out, Some(riid));
}
Ok(out)
}
/// Round 27 — mint a host-side `IFilterGraph` stub so the
/// codec's `IBaseFilter::JoinFilterGraph(pGraph, pName)` call
/// has a non-NULL parent graph to record. The returned guest
/// pointer's vtable function-pointer slots are synthetic
/// thunk addresses that route into the host stubs registered
/// by [`crate::emulator::com::host_iface::register`].
///
/// `QueryInterface(IID_IUnknown | IID_IFilterGraph)` →
/// `S_OK + *ppv = obj`; every other IID returns
/// `E_NOINTERFACE`. All eight `IFilterGraph` methods return
/// `E_NOTIMPL` — none are exercised on the
/// `JoinFilterGraph → ReceiveConnection` path the round-27
/// probe takes.
pub fn mint_host_filter_graph(&mut self) -> Result<u32, crate::emulator::Error> {
crate::emulator::com::mint_host_filter_graph(
&mut self.host,
&mut self.mmu,
&mut self.registry,
)
}
/// Round 27 — mint a host-side `IPin` stub that pretends to
/// be an OUTPUT pin advertising `amt_addr` (a pointer to a
/// staged `AM_MEDIA_TYPE`). Suitable as the `pConnector`
/// argument of `IPin::ReceiveConnection`.
///
/// `QueryDirection` reports `PIN_OUTPUT`; `QueryAccept`
/// returns `S_OK`; `ConnectionMediaType` copies the staged
/// AMT; `EnumMediaTypes` vends an enumerator yielding the
/// staged AMT once.
pub fn mint_host_output_pin(&mut self, amt_addr: u32) -> Result<u32, crate::emulator::Error> {
crate::emulator::com::host_iface::mint_host_output_pin(
&mut self.host,
&mut self.mmu,
&mut self.registry,
amt_addr,
)
}
/// Round 37 — same as [`Self::mint_host_output_pin`] but also
/// stamps the codec's input-pin pointer (`connected_pin`) into
/// the new pin object so `IPin::ConnectedTo` can return it,
/// and synthesizes a parent `HostIBaseFilter` so
/// `IPin::QueryPinInfo` can fill in `PIN_INFO::pFilter`.
///
/// `connected_pin == 0` falls back to the round-30 behaviour
/// where the pin reports `VFW_E_NOT_CONNECTED` from
/// `ConnectedTo`.
pub fn mint_host_output_pin_with_connection(
&mut self,
amt_addr: u32,
connected_pin: u32,
) -> Result<u32, crate::emulator::Error> {
crate::emulator::com::host_iface::mint_host_output_pin_with_connection(
&mut self.host,
&mut self.mmu,
&mut self.registry,
amt_addr,
connected_pin,
)
}
/// Round 37 — number of `IPin::QueryPinInfo` calls the codec
/// has driven against any host pin during this sandbox's
/// lifetime.
pub fn query_pin_info_call_count(&self) -> usize {
crate::emulator::com::host_iface::query_pin_info_call_count(&self.host)
}
/// Round 37 — number of `IBaseFilter::QueryFilterInfo` calls
/// the codec has driven against any host filter during this
/// sandbox's lifetime.
pub fn query_filter_info_call_count(&self) -> usize {
crate::emulator::com::host_iface::query_filter_info_call_count(&self.host)
}
/// Round 37 — `this` pointers of every `IPin::QueryPinInfo`
/// call observed.
pub fn query_pin_info_calls(&self) -> Vec<u32> {
crate::emulator::com::host_iface::query_pin_info_calls(&self.host)
}
/// Round 37 — `this` pointers of every
/// `IBaseFilter::QueryFilterInfo` call observed.
pub fn query_filter_info_calls(&self) -> Vec<u32> {
crate::emulator::com::host_iface::query_filter_info_calls(&self.host)
}
/// Round 37 — drop every captured introspection call from this
/// sandbox's per-state log.
pub fn clear_query_info_log(&self) {
crate::emulator::com::host_iface::clear_query_info_log(&self.host)
}
/// Round 30 — mint a host-side `IMemAllocator` backed by a
/// pool of `pool_size` IMediaSample slots, each carrying a
/// fresh `sample_capacity`-byte data region. The returned
/// guest pointer is suitable as the `pAllocator` argument of
/// `IMemInputPin::NotifyAllocator`.
///
/// `media_type_ptr` is returned by every minted sample's
/// `IMediaSample::GetMediaType` — pass `0` if no AMT should
/// surface there (codecs then fall back to the upstream pin's
/// connection media type).
pub fn mint_host_mem_allocator(
&mut self,
pool_size: u32,
sample_capacity: u32,
media_type_ptr: u32,
) -> Result<u32, crate::emulator::Error> {
crate::emulator::com::mint_host_mem_allocator(
&mut self.host,
&mut self.mmu,
&mut self.registry,
pool_size,
sample_capacity,
media_type_ptr,
)
}
/// Round 35 — mint a host-side `IClassFactory` whose
/// `CreateInstance` mints fresh `HostIMemAllocator` instances.
///
/// Pre-registered in [`Sandbox::new`] under
/// [`crate::emulator::com::CLSID_MEMORY_ALLOCATOR`]; this method exists
/// for tests that want a raw factory pointer to drive
/// `IClassFactory::CreateInstance` directly without going
/// through the `ole32!CoCreateInstance` cascade.
pub fn mint_host_mem_allocator_class_factory(&mut self) -> Result<u32, crate::emulator::Error> {
crate::emulator::com::mint_host_mem_allocator_class_factory(
&mut self.host,
&mut self.mmu,
&mut self.registry,
)
}
/// Round 30 — mint a single host-side `IMediaSample` wrapping
/// a fresh `data_capacity`-byte data region. Useful for
/// stand-alone tests; production paths typically mint samples
/// implicitly via [`Self::mint_host_mem_allocator`].
pub fn mint_host_media_sample(
&mut self,
data_capacity: u32,
media_type_ptr: u32,
) -> Result<u32, crate::emulator::Error> {
crate::emulator::com::mint_host_media_sample(
&mut self.host,
&mut self.mmu,
&mut self.registry,
data_capacity,
media_type_ptr,
)
}
/// Round 30 — copy a payload into a previously-minted sample
/// + flag whether it is a sync (key) frame.
///
/// Wraps [`crate::emulator::com::media_sample_set_payload`].
pub fn media_sample_set_payload(
&mut self,
sample: u32,
payload: &[u8],
sync_point: bool,
) -> Result<(), crate::emulator::Error> {
crate::emulator::com::media_sample_set_payload(&mut self.mmu, sample, payload, sync_point)
}
/// Round 31 — mint a paired downstream `(HostIPin, HostIMemInputPin)`
/// for receiving samples the codec pushes from its output pin.
pub fn host_iface_r31_mint_input_pin_pair(
&mut self,
) -> Result<(u32, u32), crate::emulator::Error> {
crate::emulator::com::host_iface_r31::mint_host_input_pin_pair(
&mut self.host,
&mut self.mmu,
&mut self.registry,
)
}
/// Round 31 — mint a minimal HostIBaseFilter exposing
/// `input_pin`.
pub fn host_iface_r31_mint_base_filter(
&mut self,
input_pin: u32,
) -> Result<u32, crate::emulator::Error> {
crate::emulator::com::host_iface_r31::mint_host_base_filter(
&mut self.host,
&mut self.mmu,
&mut self.registry,
input_pin,
)
}
/// Round 31 — pop the oldest sample captured by the
/// downstream `HostIMemInputPin::Receive` callback.
pub fn pop_received_sample(
&self,
) -> Option<crate::emulator::com::host_iface_r31::ReceivedSample> {
crate::emulator::com::host_iface_r31::pop_sample(&self.host)
}
/// Round 31 — number of samples currently waiting in the
/// host-side queue.
pub fn received_samples_len(&self) -> usize {
crate::emulator::com::host_iface_r31::queue_len(&self.host)
}
/// Round 33 — return the most recent
/// `IMemAllocator::SetProperties` capture observed on this
/// sandbox, or `None` if no codec has called `SetProperties`
/// yet. See [`crate::emulator::com::AllocatorPropertiesCapture`] for
/// the captured field shape.
pub fn last_set_properties(&self) -> Option<crate::emulator::com::AllocatorPropertiesCapture> {
crate::emulator::com::last_set_properties(&self.host)
}
/// Round 33 — return every `SetProperties` capture observed on
/// this sandbox, in arrival order.
pub fn all_set_properties(&self) -> Vec<crate::emulator::com::AllocatorPropertiesCapture> {
crate::emulator::com::all_set_properties(&self.host)
}
/// Round 33 — drop every captured `SetProperties` for this
/// sandbox. Useful for resetting per-test state.
pub fn clear_set_properties_log(&self) {
crate::emulator::com::clear_set_properties_log(&self.host)
}
/// Drive `obj->AddRef()`. Returns the codec-reported new
/// refcount; the host's bookkeeping is updated automatically.
pub fn com_add_ref(&mut self, obj: u32) -> Result<u32, crate::emulator::Error> {
crate::emulator::com::call::add_ref(
&mut self.cpu,
&mut self.mmu,
&mut self.registry,
&mut self.host,
obj,
)
}
/// Drive `obj->Release()`. Returns the codec-reported new
/// refcount. The host's bookkeeping is updated automatically.
pub fn com_release(&mut self, obj: u32) -> Result<u32, crate::emulator::Error> {
crate::emulator::com::call::release(
&mut self.cpu,
&mut self.mmu,
&mut self.registry,
&mut self.host,
obj,
)
}
/// `ICDecompress` — decode one frame.
#[allow(clippy::too_many_arguments)]
pub fn ic_decompress(
&mut self,
hic: u32,
flags: u32,
input_bih: &vfw32::Bih,
input_bytes: &[u8],
output_bih: &vfw32::Bih,
output_capacity: u32,
) -> Result<(u32, Vec<u8>), crate::emulator::Error> {
vfw32::ic_decompress(
&mut self.cpu,
&mut self.mmu,
&mut self.registry,
&mut self.host,
hic,
flags,
input_bih,
input_bytes,
output_bih,
output_capacity,
)
}
// ---- Round 51: encode (compress) wrappers --------------------------
/// `ICCompressQuery` — does the codec accept this input/output
/// format pair? `output` may be `None` to defer the choice.
pub fn ic_compress_query(
&mut self,
hic: u32,
input: &vfw32::Bih,
output: Option<&vfw32::Bih>,
) -> Result<u32, crate::emulator::Error> {
vfw32::ic_compress_query(
&mut self.cpu,
&mut self.mmu,
&mut self.registry,
&mut self.host,
hic,
input,
output,
)
}
/// `ICCompressGetFormat` — ask the codec for the output BIH
/// describing what its compressed format looks like for the
/// supplied input.
pub fn ic_compress_get_format(
&mut self,
hic: u32,
input: &vfw32::Bih,
) -> Result<(u32, vfw32::Bih), crate::emulator::Error> {
vfw32::ic_compress_get_format(
&mut self.cpu,
&mut self.mmu,
&mut self.registry,
&mut self.host,
hic,
input,
)
}
/// `ICCompressGetSize` — max encoded-frame byte count for the
/// supplied input/output BIH pair.
pub fn ic_compress_get_size(
&mut self,
hic: u32,
input: &vfw32::Bih,
output: &vfw32::Bih,
) -> Result<u32, crate::emulator::Error> {
vfw32::ic_compress_get_size(
&mut self.cpu,
&mut self.mmu,
&mut self.registry,
&mut self.host,
hic,
input,
output,
)
}
/// `ICCompressBegin` — set up the encoder pipeline.
pub fn ic_compress_begin(
&mut self,
hic: u32,
input: &vfw32::Bih,
output: &vfw32::Bih,
) -> Result<u32, crate::emulator::Error> {
vfw32::ic_compress_begin(
&mut self.cpu,
&mut self.mmu,
&mut self.registry,
&mut self.host,
hic,
input,
output,
)
}
/// `ICCompressEnd` — tear down the encoder pipeline.
pub fn ic_compress_end(&mut self, hic: u32) -> Result<u32, crate::emulator::Error> {
vfw32::ic_compress_end(
&mut self.cpu,
&mut self.mmu,
&mut self.registry,
&mut self.host,
hic,
)
}
/// `ICCompress` — encode one frame. Returns the full encode
/// outcome: codec LRESULT, encoded bytes, the post-call output
/// BIH (whose `biSizeImage` holds the actual encoded byte
/// count), the codec-written `*lpdwFlags` (e.g. whether the
/// codec marked the emitted frame as a keyframe), and the
/// codec-written `*lpckid`.
///
/// `prev_bih_opt` / `prev_bytes_opt` are the previous
/// reconstructed frame (P-frame encoding). Pass `None` for
/// keyframes.
#[allow(clippy::too_many_arguments)]
pub fn ic_compress(
&mut self,
hic: u32,
flags: u32,
input_bih: &vfw32::Bih,
input_bytes: &[u8],
output_bih: &vfw32::Bih,
output_capacity: u32,
ckid: u32,
frame_num: i32,
frame_size_limit: u32,
quality: u32,
prev_bih_opt: Option<&vfw32::Bih>,
prev_bytes_opt: Option<&[u8]>,
) -> Result<vfw32::CompressOutcome, crate::emulator::Error> {
vfw32::ic_compress(
&mut self.cpu,
&mut self.mmu,
&mut self.registry,
&mut self.host,
hic,
flags,
input_bih,
input_bytes,
output_bih,
output_capacity,
ckid,
frame_num,
frame_size_limit,
quality,
prev_bih_opt,
prev_bytes_opt,
)
}
/// `ICGetState` — ask the codec to serialise its private
/// per-instance state into `dst_buf`. Returns the byte count
/// the codec actually wrote.
///
/// Round 70 — wraps `ICM_GETSTATE` (`0x5009`) per MSDN; required
/// by oxideav-tracevfw to drive the encoder's per-quality knob
/// round-trip alongside [`Self::ic_set_state`]. See MSDN
/// `ICGetState` topic page for the public contract.
pub fn ic_get_state(
&mut self,
hic: u32,
dst_buf: &mut [u8],
) -> Result<u32, crate::emulator::Error> {
vfw32::ic_get_state(
&mut self.cpu,
&mut self.mmu,
&mut self.registry,
&mut self.host,
hic,
dst_buf,
)
}
/// `ICSetState` — ask the codec to deserialise `src_buf` into
/// its private per-instance state. Returns `Ok(())` on
/// `ICERR_OK`, or [`crate::emulator::Error`] wrapping the codec's raw
/// `LRESULT` otherwise.
///
/// Round 70 — wraps `ICM_SETSTATE` (`0x500A`) per MSDN. See
/// MSDN `ICSetState` topic page for the public contract.
pub fn ic_set_state(&mut self, hic: u32, src_buf: &[u8]) -> Result<(), crate::emulator::Error> {
vfw32::ic_set_state(
&mut self.cpu,
&mut self.mmu,
&mut self.registry,
&mut self.host,
hic,
src_buf,
)
}
/// Round 63 — patch `msadds32.ax`'s `helper_addref` thunk (at
/// RVA `0x5cea`) to unconditionally return `value` (32-bit
/// integer).
///
/// **Why.** Round-62 forensics
/// (`docs/codec/msadds32-receive-null-0x20.md`) traced the
/// `IMemInputPin::Receive` NULL-deref trap at RVA `0x256a` to
/// a buffer-pool init that's handed a size of zero. The size
/// is `(h * 10) / size_calc(...)` where `h` is what
/// `helper_addref` returns. On a fresh codec instance the
/// helper-object field at `helper_90 + 0x3c` (the "initialised"
/// flag the addref checks) is zero, so `helper_addref` returns
/// `0`, the quotient is `0`, `operator new(0)` returns NULL,
/// `buffer_pool_init` fails, and the Receive cleanup branch
/// trips a NULL+0x20 deref.
///
/// In a real DirectShow host the flag is set during
/// `IFilterGraph::JoinFilterGraph` / `Pause` (the codec stamps
/// the field as part of its run-state machine). Until we
/// drive that path, the surgical workaround is to short-circuit
/// `helper_addref` to return a fixed non-zero value — which
/// empirically lifts the trap and lets Receive run to
/// completion (with HRESULT `0x8000ffff` from the decode body,
/// which is the next round's investigation surface).
///
/// **Encoding.** The original function (RVA `0x5cea`, 10 bytes)
/// is:
///
/// ```text
/// 0x5cea: 83 79 20 00 cmp [ecx+0x20], 0
/// 0x5cee: 74 04 jz +4
/// 0x5cf0: 8b 41 28 mov eax, [ecx+0x28]
/// 0x5cf3: c3 ret
/// 0x5cf4: 33 c0 xor eax, eax
/// 0x5cf6: c3 ret
/// ```
///
/// We overwrite the first 6 bytes with:
///
/// ```text
/// b8 XX XX XX XX mov eax, imm32
/// c3 ret
/// ```
///
/// The remaining bytes at `0x5cf0..0x5cf6` are unreachable
/// after the patch (no caller enters there directly), so the
/// dead-code is harmless.
///
/// `image_base` is the address the codec was loaded at; pass
/// the value returned by [`Self::load`] on `msadds32.ax`.
///
/// # Reference material (clean-room only)
///
/// * Intel SDM Vol. 2A — `MOV imm32` (`B8+rd`), `RET` (`C3`).
/// * Raw bytes of `msadds32.ax` from
/// `docs/video/msmpeg4/reference/binaries/wmpcdcs8-2001/`.
///
/// No Wine / ReactOS / MinGW / Microsoft DShow source consulted.
pub fn msadds32_patch_helper_addref(
&mut self,
image_base: u32,
value: u32,
) -> Result<(), crate::emulator::Error> {
const RVA_HELPER_ADDREF: u32 = 0x5cea;
let va = image_base.wrapping_add(RVA_HELPER_ADDREF);
let mut patch = [0u8; 6];
patch[0] = 0xb8; // mov eax, imm32
patch[1..5].copy_from_slice(&value.to_le_bytes());
patch[5] = 0xc3; // ret
self.mmu
.write_initializer(va, &patch)
.map_err(crate::emulator::Error::Trap)
}
}
/// Recursively load `bytes`'s static imports from the VFS. Mirrors
/// [`Sandbox::preload_deps`] but free-function shape so it can run
/// from a stub (which doesn't own a Sandbox).
fn preload_deps_free(
cpu: &mut crate::emulator::emulator::Cpu,
mmu: &mut crate::emulator::emulator::Mmu,
registry: &mut crate::emulator::win32::Registry,
state: &mut crate::emulator::win32::HostState,
bytes: &[u8],
loading: &mut std::collections::BTreeSet<String>,
) {
use crate::emulator::pe;
let parsed = match pe::header::parse(bytes) {
Ok(p) => p,
Err(_) => return,
};
let imported = pe::imports::list_imported_dlls(&parsed, bytes).unwrap_or_default();
for dll in imported {
let dll_lc = dll.to_ascii_lowercase();
if loading.contains(&dll_lc) {
continue;
}
if crate::emulator::win32::is_host_stub_dll(&dll_lc) {
continue;
}
if state.modules.contains_key(&dll_lc) {
continue;
}
let bytes_dep = {
let Some(vfs) = state.context.vfs.as_ref() else {
continue;
};
let mut found: Option<Vec<u8>> = None;
for prefix in crate::emulator::win32::dll_vfs_search_paths() {
let p = format!("{prefix}{dll_lc}");
if let Some(b) = vfs.read(&p) {
found = Some(b.to_vec());
break;
}
}
match found {
Some(b) => b,
None => continue,
}
};
loading.insert(dll_lc.clone());
preload_deps_free(cpu, mmu, registry, state, &bytes_dep, loading);
let Ok(parsed_dep) = pe::header::parse(&bytes_dep) else {
loading.remove(&dll_lc);
continue;
};
let preferred = parsed_dep.optional.image_base;
let image_size = parsed_dep.optional.size_of_image;
let aligned = (image_size + 0xFFFF) & !0xFFFF;
let base = if mmu.region_is_unmapped(preferred, image_size) {
preferred
} else {
let b = state.next_dll_image_base;
state.next_dll_image_base = b.saturating_add(aligned);
b
};
let mut options = pe::LoadOptions {
imports: pe::imports::ResolveMode::FailSoft,
fail_soft_log: Some(Vec::new()),
target_image_base: Some(base),
};
let mut loader = pe::Loader::new(mmu, registry, state);
let img = match loader.load_with_options(&dll_lc, &bytes_dep, &mut options) {
Ok(i) => i,
Err(e) => {
state
.debug_log
.push(format!("dynamic-load {dll_lc}: load failed: {e}"));
loading.remove(&dll_lc);
continue;
}
};
for (export_name, rva) in &img.exports {
registry.register_guest_export(&dll_lc, export_name, img.image_base.wrapping_add(*rva));
}
state
.loaded_dll_exports
.insert(img.image_base, img.exports.clone());
state.modules.insert(dll_lc.clone(), img.image_base);
let msg = format!("dynamic-load {dll_lc}: loaded at {base:#010x}");
eprintln!(" {msg}");
state.debug_log.push(msg);
let has_dll_main = img.exports.contains_key("DllMain");
let has_entry = parsed_dep.optional.address_of_entry_point != 0;
let target = if has_entry {
img.image_base
.wrapping_add(parsed_dep.optional.address_of_entry_point)
} else if has_dll_main {
img.image_base
.wrapping_add(*img.exports.get("DllMain").unwrap())
} else {
0
};
if target != 0 {
if std::env::var("UD_TRACE_WILD_JUMP").is_ok() {
eprintln!(" dynamic-load {dll_lc}: calling DllMain at {target:#010x}");
}
if let Err(e) = crate::emulator::win32::call_guest(
cpu,
mmu,
registry,
state,
target,
&[img.image_base, DLL_PROCESS_ATTACH, 0],
) {
let msg = format!("dynamic-load {dll_lc}: DllMain trapped: {e}");
eprintln!(" {msg}");
state.debug_log.push(msg);
}
}
loading.remove(&dll_lc);
}
}
/// Dynamic `LoadLibraryA`: find a DLL by name in the attached
/// VFS, load it (with its dependencies) at a fresh image base,
/// register its exports against the stub registry, and invoke
/// its `DllMain(PROCESS_ATTACH)`. Returns the new module's
/// image base on success, 0 if the DLL can't be found or fails
/// to load.
///
/// This lets `kernel32!LoadLibraryA` work for any DLL the
/// VFS contains — qtcf.dll's delay-load resolver hits
/// `LoadLibraryA("CoreFoundation.dll")` from inside qts's
/// CRT init chain, and we now load it on demand rather than
/// pre-staging everything.
pub fn load_dll_dynamic(
cpu: &mut crate::emulator::emulator::Cpu,
mmu: &mut crate::emulator::emulator::Mmu,
registry: &mut crate::emulator::win32::Registry,
state: &mut crate::emulator::win32::HostState,
name: &str,
) -> u32 {
use crate::emulator::pe;
let name_lc = name.to_ascii_lowercase();
let basename = name_lc
.rsplit(['\\', '/'])
.next()
.unwrap_or(&name_lc)
.to_string();
if let Some(b) = state.modules.get(&basename) {
return *b;
}
if let Some(b) = state.modules.get(&name_lc) {
return *b;
}
if crate::emulator::win32::is_host_stub_dll(&basename) {
return 0;
}
let bytes = {
let Some(vfs) = state.context.vfs.as_ref() else {
return 0;
};
let mut found: Option<Vec<u8>> = None;
for prefix in crate::emulator::win32::dll_vfs_search_paths() {
let p = format!("{prefix}{basename}");
if let Some(b) = vfs.read(&p) {
found = Some(b.to_vec());
break;
}
}
match found {
Some(b) => b,
None => return 0,
}
};
let mut loading: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
loading.insert(basename.clone());
preload_deps_free(cpu, mmu, registry, state, &bytes, &mut loading);
loading.remove(&basename);
let Ok(parsed) = pe::header::parse(&bytes) else {
return 0;
};
let preferred = parsed.optional.image_base;
let image_size = parsed.optional.size_of_image;
let aligned = (image_size + 0xFFFF) & !0xFFFF;
let base = if mmu.region_is_unmapped(preferred, image_size) {
preferred
} else {
let b = state.next_dll_image_base;
state.next_dll_image_base = b.saturating_add(aligned);
b
};
let mut options = pe::LoadOptions {
imports: pe::imports::ResolveMode::FailSoft,
fail_soft_log: Some(Vec::new()),
target_image_base: Some(base),
};
let mut loader = pe::Loader::new(mmu, registry, state);
let img = match loader.load_with_options(&basename, &bytes, &mut options) {
Ok(i) => i,
Err(_) => return 0,
};
for (export_name, rva) in &img.exports {
registry.register_guest_export(&basename, export_name, img.image_base.wrapping_add(*rva));
}
state
.loaded_dll_exports
.insert(img.image_base, img.exports.clone());
state.modules.insert(basename.clone(), img.image_base);
let msg = format!(
"dynamic-load {basename}: loaded at {:#010x}",
img.image_base
);
eprintln!(" {msg}");
state.debug_log.push(msg);
let has_dll_main = img.exports.contains_key("DllMain");
let has_entry = parsed.optional.address_of_entry_point != 0;
let target = if has_entry {
img.image_base
.wrapping_add(parsed.optional.address_of_entry_point)
} else if has_dll_main {
img.image_base
.wrapping_add(*img.exports.get("DllMain").unwrap())
} else {
0
};
if target != 0 {
if let Err(e) = crate::emulator::win32::call_guest(
cpu,
mmu,
registry,
state,
target,
&[img.image_base, DLL_PROCESS_ATTACH, 0],
) {
let msg = format!("dynamic-load {basename}: DllMain trapped: {e}");
eprintln!(" {msg}");
state.debug_log.push(msg);
}
}
img.image_base
}
#[cfg(test)]
mod tests {
use super::*;
use crate::emulator::emulator::isa_int::RET_SENTINEL;
use crate::emulator::emulator::regs::Reg32;
use crate::emulator::pe::test_image::build_minimal_dll;
#[test]
fn load_synth_dll_and_run_dll_main_returns_to_sentinel() {
let bytes = build_minimal_dll();
let mut sb = Sandbox::new();
let img = sb.load("synth.dll", &bytes).unwrap();
// Pre-set eax = 1 so we can confirm the synth DllMain
// returned without modifying it (it's just `ret 12`).
sb.cpu.regs.set32(Reg32::Eax, 1);
let ret = sb.call_dll_main(&img, DLL_PROCESS_ATTACH).unwrap();
assert_eq!(ret, 1);
assert_eq!(sb.cpu.regs.eip, RET_SENTINEL);
}
#[test]
fn calling_through_iat_thunk_invokes_kernel32_stub() {
// Emulator-only test: fabricate a code block that calls
// a kernel32!GetProcessHeap thunk and rets. Verifies the
// run loop's "is_thunk → dispatch" path.
let mut sb = Sandbox::new();
let thunk = sb
.registry
.resolve("kernel32.dll", "GetProcessHeap")
.unwrap();
// Map a code page at 0x1000.
sb.mmu.map(0x1000, 0x1000, Perm::R | Perm::X);
// call dword [thunk_slot]; ret 0
// Easier: set eip directly to the thunk after pushing
// the synthetic ret-sentinel.
sb.cpu.push32(&mut sb.mmu, RET_SENTINEL).unwrap();
sb.cpu.regs.eip = thunk;
sb.run_until_sentinel().unwrap();
assert_eq!(sb.cpu.regs.get32(Reg32::Eax), 0xDEAD_BEEF);
}
/// Phase 3c of the scheduler refactor: `WaitForSingleObject`
/// on an unsignalled auto-reset Event parks the calling
/// thread; `SetEvent` from a peer wakes exactly one waiter.
/// We exercise this directly through state mutation rather
/// than spawning guest threads (the kernel32 thunk path is
/// covered by the spawn test below).
#[test]
fn wait_for_single_object_blocks_until_set_event() {
let mut sb = Sandbox::new();
// Mint an auto-reset Event, initially unsignalled.
let h = sb
.host
.scheduler
.insert_object(crate::emulator::sched::WaitObject::Event {
signaled: false,
manual_reset: false,
});
// Inject a second thread parked on a wait for the event.
let mut t2 = crate::emulator::win32::ThreadState::new(2, 1);
t2.parked_cpu = Some(crate::emulator::emulator::Cpu::new());
t2.status = crate::emulator::sched::ThreadStatus::Waiting;
t2.wait = Some(crate::emulator::sched::WaitCondition::Object {
handle: h,
timeout_after: None,
});
sb.host.threads.insert(2, t2);
// Bootstrap drives SetEvent via the kernel32 thunk.
let set_event = sb.registry.resolve("kernel32.dll", "SetEvent").unwrap();
sb.cpu.push32(&mut sb.mmu, h).unwrap();
sb.cpu.push32(&mut sb.mmu, RET_SENTINEL).unwrap();
sb.cpu.regs.eip = set_event;
sb.run_until_sentinel().unwrap();
// Thread 2 should be back to Ready with no wait.
let t = sb.host.threads.get(&2).unwrap();
assert!(
matches!(t.status, crate::emulator::sched::ThreadStatus::Ready),
"expected thread 2 Ready, got {:?}",
t.status
);
assert!(t.wait.is_none(), "wait condition must be cleared");
// Auto-reset: the signal is consumed by the wake.
match sb.host.scheduler.objects.get(&h).unwrap() {
crate::emulator::sched::WaitObject::Event { signaled, .. } => assert!(!*signaled),
_ => panic!(),
}
}
/// Mutex round-trip: contention parks the second caller,
/// `ReleaseMutex` from the holder wakes them and transfers
/// ownership.
#[test]
fn mutex_transfers_ownership_on_release() {
let mut sb = Sandbox::new();
// Mint a Mutex owned by tid 1 (the bootstrap).
let h = sb
.host
.scheduler
.insert_object(crate::emulator::sched::WaitObject::Mutex {
owner: Some(1),
recursion: 1,
});
// Inject thread 2 waiting on the mutex.
let mut t2 = crate::emulator::win32::ThreadState::new(2, 1);
t2.parked_cpu = Some(crate::emulator::emulator::Cpu::new());
t2.status = crate::emulator::sched::ThreadStatus::Waiting;
t2.wait = Some(crate::emulator::sched::WaitCondition::Object {
handle: h,
timeout_after: None,
});
sb.host.threads.insert(2, t2);
// Bootstrap calls ReleaseMutex.
let release = sb.registry.resolve("kernel32.dll", "ReleaseMutex").unwrap();
sb.cpu.push32(&mut sb.mmu, h).unwrap();
sb.cpu.push32(&mut sb.mmu, RET_SENTINEL).unwrap();
sb.cpu.regs.eip = release;
sb.run_until_sentinel().unwrap();
assert_eq!(sb.cpu.regs.get32(Reg32::Eax), 1, "release succeeds");
// Ownership transferred to thread 2; thread 2 Ready.
match sb.host.scheduler.objects.get(&h).unwrap() {
crate::emulator::sched::WaitObject::Mutex { owner, recursion } => {
assert_eq!(*owner, Some(2));
assert_eq!(*recursion, 1);
}
_ => panic!(),
}
let t = sb.host.threads.get(&2).unwrap();
assert!(matches!(
t.status,
crate::emulator::sched::ThreadStatus::Ready
));
}
/// Semaphore round-trip: `ReleaseSemaphore(N)` wakes up to
/// N waiters and bumps the count.
#[test]
fn semaphore_release_wakes_waiters_and_bumps_count() {
let mut sb = Sandbox::new();
let h = sb
.host
.scheduler
.insert_object(crate::emulator::sched::WaitObject::Semaphore { count: 0, max: 10 });
// Two waiters.
for tid in [2u32, 3u32] {
let mut t = crate::emulator::win32::ThreadState::new(tid, 1);
t.parked_cpu = Some(crate::emulator::emulator::Cpu::new());
t.status = crate::emulator::sched::ThreadStatus::Waiting;
t.wait = Some(crate::emulator::sched::WaitCondition::Object {
handle: h,
timeout_after: None,
});
sb.host.threads.insert(tid, t);
}
// Bootstrap releases 2.
let release = sb
.registry
.resolve("kernel32.dll", "ReleaseSemaphore")
.unwrap();
sb.mmu.map(0x500_0000, 0x1000, Perm::R | Perm::W);
let p_prev = 0x500_0000u32;
sb.cpu.push32(&mut sb.mmu, p_prev).unwrap();
sb.cpu.push32(&mut sb.mmu, 2u32).unwrap();
sb.cpu.push32(&mut sb.mmu, h).unwrap();
sb.cpu.push32(&mut sb.mmu, RET_SENTINEL).unwrap();
sb.cpu.regs.eip = release;
sb.run_until_sentinel().unwrap();
assert_eq!(sb.cpu.regs.get32(Reg32::Eax), 1);
// Previous count was 0.
assert_eq!(sb.mmu.load32(p_prev).unwrap(), 0);
// Both waiters woke; each consumed one count → net count = 0.
match sb.host.scheduler.objects.get(&h).unwrap() {
crate::emulator::sched::WaitObject::Semaphore { count, .. } => {
assert_eq!(*count, 0, "both waiters consumed their signals");
}
_ => panic!(),
}
for tid in [2u32, 3u32] {
let t = sb.host.threads.get(&tid).unwrap();
assert!(matches!(
t.status,
crate::emulator::sched::ThreadStatus::Ready
));
}
}
/// Phase 5c: when the target EXE is staged in the
/// VirtualFs, `CreateProcessA` actually loads it at a
/// fresh image base and mints a Ready primary thread the
/// scheduler can run alongside the parent. The PE used
/// here is the synthetic-DLL fixture — it has a real PE
/// header and the only import (`kernel32!ExitProcess`) is
/// satisfied by our stub registry.
#[test]
fn create_process_a_loads_real_child_pe_from_vfs() {
use crate::emulator::pe::test_image::build_minimal_dll;
let mut sb = Sandbox::default();
// Stage a child binary in the VFS.
let dll_bytes = build_minimal_dll();
let child_path = "c:\\setup\\helper.exe";
let mut vfs = crate::emulator::fsmount::MountTable::new();
vfs.insert(child_path, dll_bytes);
sb.host.context.vfs = Some(vfs);
// Stage a PROCESS_INFORMATION scratch region.
sb.mmu.map(0x500_0000, 0x1000, Perm::R | Perm::W);
let pi = 0x500_0000u32;
// Stage the lpApplicationName string.
sb.mmu.map(0x500_1000, 0x1000, Perm::R | Perm::W);
let app_ptr = 0x500_1000u32;
sb.mmu
.write_initializer(app_ptr, child_path.as_bytes())
.unwrap();
sb.mmu.store8(app_ptr + child_path.len() as u32, 0).unwrap();
let create_proc = sb
.registry
.resolve("kernel32.dll", "CreateProcessA")
.unwrap();
for &a in [app_ptr, 0u32, 0, 0, 0, 0, 0, 0, 0, pi].iter().rev() {
sb.cpu.push32(&mut sb.mmu, a).unwrap();
}
sb.cpu.push32(&mut sb.mmu, RET_SENTINEL).unwrap();
sb.cpu.regs.eip = create_proc;
sb.run_until_sentinel().unwrap();
assert_eq!(sb.cpu.regs.get32(Reg32::Eax), 1, "CreateProcessA TRUE");
// The new process should be in the table, distinct PID,
// and its primary thread Ready (not Terminated like the
// fake-child fallback).
let child_pid = sb.mmu.load32(pi + 8).unwrap();
let child_tid = sb.mmu.load32(pi + 12).unwrap();
let p = sb
.host
.processes
.get(&child_pid)
.expect("child process present");
assert_ne!(
p.image_base, 0,
"child PE was rebased into a fresh image slot"
);
assert_eq!(p.parent_pid, 1);
let t = sb
.host
.threads
.get(&child_tid)
.expect("child primary thread present");
assert!(matches!(
t.status,
crate::emulator::sched::ThreadStatus::Ready
| crate::emulator::sched::ThreadStatus::Running
));
// The minimal-DLL entry just rets, so a subsequent
// run_until_sentinel will Halt it cleanly.
}
/// Phase 3d: `EnterCriticalSection` takes ownership of an
/// implicit Mutex keyed by `LPCRITICAL_SECTION`'s guest
/// address; recursion increments on re-entry by the same
/// thread; `LeaveCriticalSection` decrements and clears
/// ownership when the count reaches zero. Exercised through
/// IPC: `CreatePipe` mints a read/write handle pair;
/// `WriteFile` on the write end stages bytes that
/// `ReadFile` on the read end picks up. The two handles
/// share an in-memory buffer through the scheduler's
/// pipe table; closing the write end drains EOF on the
/// reader.
#[test]
fn create_pipe_write_read_round_trip() {
let mut sb = Sandbox::new();
// Scratch region for handle outputs + data buffers.
sb.mmu.map(0x500_0000, 0x1000, Perm::R | Perm::W);
let p_read_h = 0x500_0000u32;
let p_write_h = 0x500_0004u32;
let p_written = 0x500_0010u32;
let p_data_in = 0x500_0020u32; // bytes to write
let p_data_out = 0x500_0040u32; // bytes to read into
let p_n_read = 0x500_0080u32;
// CreatePipe(read, write, NULL, 0).
let create_pipe = sb.registry.resolve("kernel32.dll", "CreatePipe").unwrap();
for &a in [p_read_h, p_write_h, 0u32, 0u32].iter().rev() {
sb.cpu.push32(&mut sb.mmu, a).unwrap();
}
sb.cpu.push32(&mut sb.mmu, RET_SENTINEL).unwrap();
sb.cpu.regs.eip = create_pipe;
sb.run_until_sentinel().unwrap();
assert_eq!(sb.cpu.regs.get32(Reg32::Eax), 1, "CreatePipe TRUE");
let h_read = sb.mmu.load32(p_read_h).unwrap();
let h_write = sb.mmu.load32(p_write_h).unwrap();
assert!(h_read >= crate::emulator::sched::WAIT_OBJECT_HANDLE_BASE);
assert_ne!(h_read, h_write, "distinct ends");
// Stage data in MMU + WriteFile(write_handle, data, 5, &written, NULL).
sb.mmu.write_initializer(p_data_in, b"HELLO").unwrap();
let write_file = sb.registry.resolve("kernel32.dll", "WriteFile").unwrap();
for &a in [h_write, p_data_in, 5u32, p_written, 0u32].iter().rev() {
sb.cpu.push32(&mut sb.mmu, a).unwrap();
}
sb.cpu.push32(&mut sb.mmu, RET_SENTINEL).unwrap();
sb.cpu.regs.eip = write_file;
sb.run_until_sentinel().unwrap();
assert_eq!(sb.cpu.regs.get32(Reg32::Eax), 1);
assert_eq!(sb.mmu.load32(p_written).unwrap(), 5);
// ReadFile(read_handle, out_buf, 5, &n_read, NULL).
let read_file = sb.registry.resolve("kernel32.dll", "ReadFile").unwrap();
for &a in [h_read, p_data_out, 5u32, p_n_read, 0u32].iter().rev() {
sb.cpu.push32(&mut sb.mmu, a).unwrap();
}
sb.cpu.push32(&mut sb.mmu, RET_SENTINEL).unwrap();
sb.cpu.regs.eip = read_file;
sb.run_until_sentinel().unwrap();
assert_eq!(sb.cpu.regs.get32(Reg32::Eax), 1);
assert_eq!(sb.mmu.load32(p_n_read).unwrap(), 5);
// Verify the bytes round-tripped.
let mut got = [0u8; 5];
for i in 0..5 {
got[i] = sb.mmu.load8(p_data_out + i as u32).unwrap();
}
assert_eq!(&got, b"HELLO");
}
/// Named-pipe handshake: a `CreateNamedPipeA(\\.\pipe\X)`
/// server end + a `CreateFileA(\\.\pipe\X)` client end
/// reach each other through the named-object registry
/// and share a buffer for `WriteFile` / `ReadFile`.
#[test]
fn named_pipe_server_and_client_share_buffer() {
let mut sb = Sandbox::new();
sb.mmu.map(0x501_0000, 0x1000, Perm::R | Perm::W);
let p_name = 0x501_0000u32;
let pipe_path = b"\\\\.\\pipe\\test\0";
sb.mmu.write_initializer(p_name, pipe_path).unwrap();
let p_data_in = 0x501_0100u32;
let p_data_out = 0x501_0200u32;
let p_written = 0x501_0300u32;
let p_n_read = 0x501_0310u32;
// CreateNamedPipeA(name, PIPE_ACCESS_OUTBOUND, ...). With
// OUTBOUND, the server holds the write end.
let cnp = sb
.registry
.resolve("kernel32.dll", "CreateNamedPipeA")
.unwrap();
for &a in [p_name, 2u32, 0u32, 1u32, 4096u32, 4096u32, 0u32, 0u32]
.iter()
.rev()
{
sb.cpu.push32(&mut sb.mmu, a).unwrap();
}
sb.cpu.push32(&mut sb.mmu, RET_SENTINEL).unwrap();
sb.cpu.regs.eip = cnp;
sb.run_until_sentinel().unwrap();
let h_server = sb.cpu.regs.get32(Reg32::Eax);
assert!(h_server >= crate::emulator::sched::WAIT_OBJECT_HANDLE_BASE);
// Client: CreateFileA(\\.\pipe\test, GENERIC_READ, ...).
let cfa = sb.registry.resolve("kernel32.dll", "CreateFileA").unwrap();
for &a in [p_name, 0x8000_0000u32, 0u32, 0u32, 3u32, 0u32, 0u32]
.iter()
.rev()
{
sb.cpu.push32(&mut sb.mmu, a).unwrap();
}
sb.cpu.push32(&mut sb.mmu, RET_SENTINEL).unwrap();
sb.cpu.regs.eip = cfa;
sb.run_until_sentinel().unwrap();
let h_client = sb.cpu.regs.get32(Reg32::Eax);
assert_ne!(h_client, 0xFFFF_FFFF, "client open should succeed");
assert_ne!(h_client, h_server, "distinct handles");
// Server WriteFile.
sb.mmu.write_initializer(p_data_in, b"PING!").unwrap();
let wfile = sb.registry.resolve("kernel32.dll", "WriteFile").unwrap();
for &a in [h_server, p_data_in, 5u32, p_written, 0u32].iter().rev() {
sb.cpu.push32(&mut sb.mmu, a).unwrap();
}
sb.cpu.push32(&mut sb.mmu, RET_SENTINEL).unwrap();
sb.cpu.regs.eip = wfile;
sb.run_until_sentinel().unwrap();
assert_eq!(sb.cpu.regs.get32(Reg32::Eax), 1);
assert_eq!(sb.mmu.load32(p_written).unwrap(), 5);
// Client ReadFile.
let rfile = sb.registry.resolve("kernel32.dll", "ReadFile").unwrap();
for &a in [h_client, p_data_out, 5u32, p_n_read, 0u32].iter().rev() {
sb.cpu.push32(&mut sb.mmu, a).unwrap();
}
sb.cpu.push32(&mut sb.mmu, RET_SENTINEL).unwrap();
sb.cpu.regs.eip = rfile;
sb.run_until_sentinel().unwrap();
assert_eq!(sb.cpu.regs.get32(Reg32::Eax), 1);
assert_eq!(sb.mmu.load32(p_n_read).unwrap(), 5);
let mut got = [0u8; 5];
for i in 0..5 {
got[i] = sb.mmu.load8(p_data_out + i as u32).unwrap();
}
assert_eq!(&got, b"PING!");
}
/// the kernel32 thunk dispatch.
#[test]
fn enter_leave_critical_section_round_trip() {
let mut sb = Sandbox::new();
// Map a CRITICAL_SECTION scratch region.
sb.mmu.map(0x400_0000, 0x1000, Perm::R | Perm::W);
let cs = 0x400_0000u32;
let enter = sb
.registry
.resolve("kernel32.dll", "EnterCriticalSection")
.unwrap();
let leave = sb
.registry
.resolve("kernel32.dll", "LeaveCriticalSection")
.unwrap();
// First enter: take ownership, recursion=1.
sb.cpu.push32(&mut sb.mmu, cs).unwrap();
sb.cpu.push32(&mut sb.mmu, RET_SENTINEL).unwrap();
sb.cpu.regs.eip = enter;
sb.run_until_sentinel().unwrap();
let h = sb.host.scheduler.critical_sections[&cs];
match sb.host.scheduler.objects.get(&h).unwrap() {
crate::emulator::sched::WaitObject::CriticalSection {
owner, recursion, ..
} => {
assert_eq!(*owner, Some(1));
assert_eq!(*recursion, 1);
}
_ => panic!(),
}
// Re-entry by same thread: recursion=2.
sb.cpu.push32(&mut sb.mmu, cs).unwrap();
sb.cpu.push32(&mut sb.mmu, RET_SENTINEL).unwrap();
sb.cpu.regs.eip = enter;
sb.run_until_sentinel().unwrap();
match sb.host.scheduler.objects.get(&h).unwrap() {
crate::emulator::sched::WaitObject::CriticalSection { recursion, .. } => {
assert_eq!(*recursion, 2);
}
_ => panic!(),
}
// First leave: recursion→1.
sb.cpu.push32(&mut sb.mmu, cs).unwrap();
sb.cpu.push32(&mut sb.mmu, RET_SENTINEL).unwrap();
sb.cpu.regs.eip = leave;
sb.run_until_sentinel().unwrap();
// Second leave: recursion→0, owner cleared.
sb.cpu.push32(&mut sb.mmu, cs).unwrap();
sb.cpu.push32(&mut sb.mmu, RET_SENTINEL).unwrap();
sb.cpu.regs.eip = leave;
sb.run_until_sentinel().unwrap();
match sb.host.scheduler.objects.get(&h).unwrap() {
crate::emulator::sched::WaitObject::CriticalSection {
owner, recursion, ..
} => {
assert_eq!(*owner, None);
assert_eq!(*recursion, 0);
}
_ => panic!(),
}
}
/// Phase 3b of the scheduler refactor: `CreateThread` mints
/// a Ready thread, the scheduler context-switches into it
/// the first time the bootstrap thread yields, and the new
/// thread runs to its own RET_SENTINEL where it
/// terminates. Verifies both halves of the round trip.
#[test]
fn create_thread_spawns_a_real_runnable_thread() {
let mut sb = Sandbox::new();
// Map a code page for the synthetic thread proc.
sb.mmu.map(0x1000, 0x1000, Perm::R | Perm::X);
// Thread proc: `mov eax, 0x42; ret 4` (stdcall, one arg
// consumed; eax = exit code).
let proc_va = 0x1010u32;
let proc_code: [u8; 8] = [
0xb8, 0x42, 0x00, 0x00, 0x00, // mov eax, 0x42
0xc2, 0x04, 0x00, // ret 4
];
sb.mmu.write_initializer(proc_va, &proc_code).unwrap();
// Drive CreateThread via the kernel32 thunk so we exercise
// the same code path a real codec would.
let create_thread = sb.registry.resolve("kernel32.dll", "CreateThread").unwrap();
// Push args right-to-left: (attrs, stack, start, param,
// flags, p_tid) = (0, 0, proc_va, 0xCAFE, 0, 0).
for &a in [0u32, 0, proc_va, 0xCAFE, 0, 0].iter().rev() {
sb.cpu.push32(&mut sb.mmu, a).unwrap();
}
sb.cpu.push32(&mut sb.mmu, RET_SENTINEL).unwrap();
sb.cpu.regs.eip = create_thread;
sb.run_until_sentinel().unwrap();
let thread_handle = sb.cpu.regs.get32(Reg32::Eax);
assert!(thread_handle >= crate::emulator::sched::WAIT_OBJECT_HANDLE_BASE);
// The new thread is in the table, Ready, with its CPU
// parked. TID 2 (bootstrap is 1).
let t = sb.host.threads.get(&2).expect("new thread present");
assert!(matches!(
t.status,
crate::emulator::sched::ThreadStatus::Ready
));
assert!(t.parked_cpu.is_some());
assert_ne!(
t.parked_cpu.as_ref().unwrap().regs.esp(),
0,
"stack was carved from the pool"
);
// Bootstrap now Sleeps — the scheduler must context
// switch into the new thread, run it to its
// RET_SENTINEL, mark it Terminated, and then come
// back to the bootstrap (which wakes after the sleep
// clock advances).
let sleep_thunk = sb.registry.resolve("kernel32.dll", "Sleep").unwrap();
// Sleep(1ms)
sb.cpu.push32(&mut sb.mmu, 1u32).unwrap();
sb.cpu.push32(&mut sb.mmu, RET_SENTINEL).unwrap();
sb.cpu.regs.eip = sleep_thunk;
sb.run_until_sentinel().unwrap();
// After the run, the new thread should have ran to
// completion (status Terminated, eax = 0x42 on its
// parked CPU if any).
let t = sb.host.threads.get(&2).expect("new thread still present");
assert!(
matches!(t.status, crate::emulator::sched::ThreadStatus::Terminated),
"expected thread 2 Terminated, got {:?}",
t.status
);
}
}