summaryrefslogtreecommitdiffstats
path: root/private/windbg/newdm/kdapi.c
blob: ae237a175b5194231badeb169dcfe6fd603a8e98 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
/*++

Copyright (c) 1990  Microsoft Corporation

Module Name:

    api.c

Abstract:

    This module implements the all apis that simulate their
    WIN32 counterparts.

Author:

    Wesley Witt (wesw) 8-Mar-1992

Environment:

    NT 3.1

Revision History:

--*/
#include "precomp.h"
#pragma hdrstop

//
// structures & defines for queue management
//
typedef struct tagCQUEUE {
    struct tagCQUEUE  *next;
    DWORD             pid;
    DWORD             tid;
    DWORD             typ;
    DWORD             len;
    DWORD             data;
} CQUEUE, *LPCQUEUE;

LPCQUEUE           lpcqFirst;
LPCQUEUE           lpcqLast;
LPCQUEUE           lpcqFree;
CQUEUE             cqueue[200];
CRITICAL_SECTION   csContinueQueue;


//
// context cache
//
typedef struct _tagCONTEXTCACHE {
    CONTEXT                 Context;
#if defined(TARGET_i386) || defined(TARGET_PPC)
    KSPECIAL_REGISTERS      sregs;
    BOOL                    fSContextStale;
    BOOL                    fSContextDirty;
#endif // i386 || PPC
    BOOL                    fContextStale;
    BOOL                    fContextDirty;
} CONTEXTCACHE, *LPCONTEXTCACHE;

CONTEXTCACHE ContextCache[MAXIMUM_PROCESSORS];
DWORD        CacheProcessors = 1;                   // up machine by default

#if defined(TARGET_MIPS)
MIPSCONTEXTSIZE MipsContextSize;
#endif

extern MODULEALIAS  ModuleAlias[];

//
// globals
//
DWORD                    DmKdState = S_UNINITIALIZED;
BOOL                     DmKdExit;
DBGKD_WAIT_STATE_CHANGE  sc;
BOOL                     fScDirty;
BOOL                     ApiIsAllowed;
HANDLE                   hEventContinue;
BOOL                     fCrashDump;
DBGKD_WRITE_BREAKPOINT   bps[64];
BOOL                     bpcheck[64];
HANDLE                   hThreadDmPoll;
DBGKD_GET_VERSION        vs;
PDUMP_HEADER             DmpHeader;
char                     szProgName[MAX_PATH];
DWORD                    PollThreadId;
PKPRCB                   KiProcessors[MAXIMUM_PROCESSORS];
PCONTEXT                 DmpContext;
BOOL                     fPacketTrace;

//
// kernel symbol addresses
//
ULONG                    DcbAddr;
ULONG                    MmLoadedUserImageList;
ULONG                    KiPcrBaseAddress;
ULONG                    KiProcessorBlockAddr;




#define IsApiAllowed()       if (!ApiIsAllowed) return 0;
#define NoApiForCrashDump()  if (fCrashDump)    return 0;
#define ConsumeAllEvents()   DequeueAllEvents(FALSE,TRUE)

#define END_OF_CONTROL_SPACE    (sizeof(KPROCESSOR_STATE))

#define CRASH_BUGCHECK_CODE   0xDEADDEAD

//
// local prototypes
//
BOOL GenerateKernelModLoad(HPRCX hprc, LPSTR lpProgName);


//
// externs
//
extern jmp_buf    JumpBuffer;
extern BOOL       DmKdBreakIn;
extern BOOL       KdResync;
extern BOOL       InitialBreak;
extern HANDLE     hEventCreateProcess;
extern HANDLE     hEventCreateThread;
extern HANDLE     hEventRemoteQuit;
extern HANDLE     hEventContinue;
extern HPRCX      prcList;
extern BOOL       fDisconnected;

extern LPDM_MSG     LpDmMsg;

extern PKILLSTRUCT           KillQueue;
extern CRITICAL_SECTION      csKillQueue;

extern HTHDX        thdList;
extern HPRCX        prcList;
extern CRITICAL_SECTION csThreadProcList;

extern BOOL    fSmartRangeStep;
extern HANDLE hEventNoDebuggee;
extern HANDLE hEventRemoteQuit;
extern BOOL         fDisconnected;
extern BOOL         fUseRoot;
extern char       nameBuffer[];



DWORD GetSymbolAddress( LPSTR sym );
BOOL  UnloadModule( DWORD BaseOfDll, LPSTR NameOfDll );
VOID  UnloadAllModules( VOID );
VOID  DisableEmCache( VOID );
VOID  InitializeKiProcessor(VOID);
VOID  ProcessCacheCmd(LPSTR pchCommand);



BOOL
DbgReadMemory(
    HPRCX  hprc,
    PVOID  lpBaseAddress,
    PVOID  lpBuffer,
    DWORD  nSize,
    PDWORD lpcbRead
    )
{
    DWORD                         cb;
    int                           iDll;
    int                           iobj;
    static PIMAGE_SECTION_HEADER  s = NULL;
    BOOL                          non_discardable = FALSE;
    PDLLLOAD_ITEM                 d;


    IsApiAllowed();

    if (nSize == 0) {
        return TRUE;
    }

    //
    // the following code is necessary to determine if the requested
    // base address is in a read-only page or is in a page that contains
    // code.  if the base address meets these conditions then is is marked
    // as non-discardable and will never be purged from the cache.
    //
    if (s &&
        (DWORD)lpBaseAddress >= s->VirtualAddress &&
        (DWORD)lpBaseAddress < s->VirtualAddress+s->SizeOfRawData &&
            ((s->Characteristics & IMAGE_SCN_CNT_CODE) ||
             (!s->Characteristics & IMAGE_SCN_MEM_WRITE))) {

                non_discardable = TRUE;

    }
    else {
        d = prcList->next->rgDllList;
        for (iDll=0; iDll<prcList->next->cDllList; iDll++) {
            if ((DWORD)lpBaseAddress >= d[iDll].offBaseOfImage &&
                (DWORD)lpBaseAddress < d[iDll].offBaseOfImage+d[iDll].cbImage) {

                if (!d[iDll].Sections) {
                    if (d[iDll].sec) {
                        d[iDll].Sections = d[iDll].sec;
                        for (iobj=0; iobj<(int)d[iDll].NumberOfSections; iobj++) {
                            d[iDll].Sections[iobj].VirtualAddress += (DWORD)d[iDll].offBaseOfImage;
                        }
                    }
                }

                s = d[iDll].Sections;

                cb = d[iDll].NumberOfSections;
                while (cb) {
                    if ((DWORD)lpBaseAddress >= s->VirtualAddress &&
                        (DWORD)lpBaseAddress < s->VirtualAddress+s->SizeOfRawData &&
                        ((s->Characteristics & IMAGE_SCN_CNT_CODE) ||
                         (!s->Characteristics & IMAGE_SCN_MEM_WRITE))) {

                        non_discardable = TRUE;
                        break;

                    }
                    else {
                        s++;
                        cb--;
                    }
                }
                if (!cb) {
                    s = NULL;
                }

                break;
            }
        }
    }

    if (fCrashDump) {

        cb = DmpReadMemory( lpBaseAddress, lpBuffer, nSize );

    } else {

        if (DmKdReadCachedVirtualMemory( (DWORD) lpBaseAddress,
                                         nSize,
                                         (PUCHAR) lpBuffer,
                                         &cb,
                                         non_discardable) != STATUS_SUCCESS ) {
            cb = 0;
        }

    }

    if ( cb > 0 && non_discardable ) {
        BREAKPOINT *bp;
        ADDR        Addr;
        BP_UNIT     instr;
        DWORD       offset;
        LPVOID      lpb;

        AddrInit( &Addr, 0, 0, (UOFF32)lpBaseAddress, TRUE, TRUE, FALSE, FALSE );
        lpb = lpBuffer;

        for (bp=bpList->next; bp; bp=bp->next) {
            if (BPInRange((HPRCX)0, (HTHDX)0, bp, &Addr, cb, &offset, &instr)) {
                if (instr) {
                    if (offset < 0) {
                        memcpy(lpb, ((char *) &instr) - offset,
                               sizeof(BP_UNIT) + offset);
                    } else if (offset + sizeof(BP_UNIT) > cb) {
                        memcpy(((char *)lpb)+offset, &instr, cb - offset);
                    } else {
                        *((BP_UNIT UNALIGNED *)((char *)lpb+offset)) = instr;
                    }
                }
            }
        }
    }

    if (cb > 0) {
        if (lpcbRead) {
            *lpcbRead = cb;
        }
        return TRUE;
    } else {
        return FALSE;
    }
}


BOOL
DbgWriteMemory(
    HPRCX   hprc,
    PVOID  lpBaseAddress,
    PVOID  lpBuffer,
    DWORD   nSize,
    LPDWORD lpcbWrite
    )
{
    ULONG   cb;


    IsApiAllowed();

    if (nSize == 0) {
        return TRUE;
    }

    if (fCrashDump) {

        cb = DmpWriteMemory( lpBaseAddress, lpBuffer, nSize );

    } else {

        if (DmKdWriteVirtualMemory( lpBaseAddress,
                                    lpBuffer,
                                    nSize,
                                    &cb ) != STATUS_SUCCESS ) {
            cb = 0;
        }

    }

    if (cb > 0) {
        if (lpcbWrite) {
            *lpcbWrite = cb;
        }
        return TRUE;
    } else {
        return FALSE;
    }
}

BOOL
DbgGetThreadContext(
    IN  HTHDX     hthd,
    OUT LPCONTEXT lpContext
    )
{
    BOOL rc = TRUE;
    USHORT processor;
    DWORD Flags = lpContext->ContextFlags;

    DPRINT(1, ( "DbgGetThreadContext( 0x%x )\n", lpContext ));

    IsApiAllowed();

    if (!hthd) {
        return FALSE;
    }

    processor = (USHORT)hthd->tid - 1;

    if (fCrashDump) {
        if (processor == sc.Processor && KiProcessors[processor] == 0) {
            memcpy( lpContext, DmpContext, sizeof(CONTEXT) );
            rc = TRUE;
        } else {
            rc = DmpGetContext( processor, lpContext );
#if defined(TARGET_MIPS)
            if (rc) {
                if (DmpHeader->MajorVersion > 3) {
                    MipsContextSize = Ctx64Bit;
                } else {
                    MipsContextSize = Ctx32Bit;
                    CoerceContext32To64(&ContextCache[processor].Context);
                }
            }
#endif
        }

    } else {

        if (ContextCache[processor].fContextStale) {

            rc = (DmKdGetContext( processor, &ContextCache[processor].Context )
                                                            == STATUS_SUCCESS);
            if (rc) {
                ContextCache[processor].fContextDirty = FALSE;
                ContextCache[processor].fContextStale = FALSE;
#if defined(TARGET_MIPS)
                if ((ContextCache[processor].Context.ContextFlags &
                            CONTEXT_EXTENDED_INTEGER) == CONTEXT_EXTENDED_INTEGER) {
                    MipsContextSize = Ctx64Bit;
                } else {
                    MipsContextSize = Ctx32Bit;
                    CoerceContext32To64(&ContextCache[processor].Context);
                }
#endif
            }
        }

        if (rc) {
            memcpy( lpContext,
                    &ContextCache[processor].Context,
                    sizeof(ContextCache[processor].Context) );
        }

    }

#if defined(TARGET_MIPS)
    if (rc) {
        if ((Flags & CONTEXT_EXTENDED_INTEGER) == CONTEXT_EXTENDED_INTEGER) {
            CoerceContext32To64(lpContext);
        } else if ((Flags & CONTEXT_INTEGER) == CONTEXT_INTEGER) {
            CoerceContext64To32(lpContext);
        }
    }
#endif

    if (rc) {
        hthd->fContextStale = FALSE;
    }

    return rc;
}

BOOL
DbgSetThreadContext(
    IN HTHDX     hthd,
    IN LPCONTEXT lpContext
    )
{
    BOOL rc = TRUE;
    USHORT processor;
#if defined(TARGET_MIPS)
    CONTEXT LocalContext;
#endif


    DEBUG_PRINT_1( "DbgSetThreadContext( 0x%x )\n", lpContext );

    IsApiAllowed();
    NoApiForCrashDump();

    processor = (USHORT)hthd->tid - 1;
    memcpy( &ContextCache[processor].Context, lpContext, sizeof(CONTEXT) );

#if defined(TARGET_MIPS)
    CoerceContext32To64( &ContextCache[processor].Context );
#endif

    if (lpContext != &hthd->context) {
        memcpy(&hthd->context, &ContextCache[processor].Context, sizeof(CONTEXT));
    }

    ContextCache[processor].fContextDirty = FALSE;
    ContextCache[processor].fContextStale = FALSE;


#if defined(TARGET_MIPS)
    if (MipsContextSize == Ctx64Bit) {
        lpContext = &ContextCache[processor].Context;
    } else {
        memcpy( &LocalContext, lpContext, sizeof(CONTEXT) );
        CoerceContext32To64( &LocalContext );
        lpContext = &LocalContext;
    }
#endif

    if (DmKdSetContext( processor, lpContext ) != STATUS_SUCCESS) {
        rc = FALSE;
    }

    return rc;
}


BOOL
WriteBreakPoint(
    IN PBREAKPOINT Breakpoint
    )
{
    BOOL rc = TRUE;

    DEBUG_PRINT_2( "WriteBreakPoint( 0x%08x, 0x%08x )\n",
                   GetAddrOff(Breakpoint->addr),
                   Breakpoint->hBreakPoint);

    IsApiAllowed();
    NoApiForCrashDump();

    if (DmKdWriteBreakPoint( (PVOID)GetAddrOff(Breakpoint->addr),
                             &Breakpoint->hBreakPoint ) != STATUS_SUCCESS) {
        rc = FALSE;
    }

    return rc;
}

BOOL
WriteBreakPointEx(
    IN HTHDX  hthd,
    IN ULONG  BreakPointCount,
    IN OUT PDBGKD_WRITE_BREAKPOINT BreakPoints,
    IN ULONG ContinueStatus
    )
{
    BOOL rc = TRUE;

    assert( BreakPointCount > 0 );
    assert( BreakPoints );

    DEBUG_PRINT_2( "WriteBreakPointEx( %d, 0x%08x )\n",
                   BreakPointCount, BreakPoints );

    IsApiAllowed();
    NoApiForCrashDump();

    if (DmKdWriteBreakPointEx( BreakPointCount, BreakPoints, ContinueStatus ) != STATUS_SUCCESS) {
        rc = FALSE;
    }

    return rc;
}


BOOL
RestoreBreakPoint(
    IN PBREAKPOINT Breakpoint
    )
{
    BOOL rc = TRUE;

    DEBUG_PRINT_1( "RestoreBreakPoint( 0x%08x )\n", Breakpoint->hBreakPoint );

    IsApiAllowed();
    NoApiForCrashDump();

    if (DmKdRestoreBreakPoint( Breakpoint->hBreakPoint ) != STATUS_SUCCESS) {
        rc = FALSE;
    }

    return rc;
}


BOOL
RestoreBreakPointEx(
    IN ULONG  BreakPointCount,
    IN PDBGKD_RESTORE_BREAKPOINT BreakPointHandles
    )
{
    BOOL rc = TRUE;

    assert( BreakPointCount > 0 );
    assert( BreakPointHandles );

    DEBUG_PRINT_2( "WriteBreakPointEx( %d, 0x%08x )\n",
                   BreakPointCount, BreakPointHandles );

    IsApiAllowed();
    NoApiForCrashDump();

    if (DmKdRestoreBreakPointEx( BreakPointCount, BreakPointHandles ) != STATUS_SUCCESS) {
        rc = FALSE;
    }

    return rc;
}

BOOL
ReadControlSpace(
    USHORT  Processor,
    PVOID   TargetBaseAddress,
    PVOID   UserInterfaceBuffer,
    ULONG   TransferCount,
    PULONG  ActualBytesRead
    )
{
    DWORD Status;


    IsApiAllowed();

    if (fCrashDump) {
        return DmpReadControlSpace(
            Processor,
            TargetBaseAddress,
            UserInterfaceBuffer,
            TransferCount,
            ActualBytesRead
            );
    }

    Status = DmKdReadControlSpace(
        Processor,
        TargetBaseAddress,
        UserInterfaceBuffer,
        TransferCount,
        ActualBytesRead
        );

    if (Status || (ActualBytesRead && *ActualBytesRead != TransferCount)) {
        return FALSE;
    }

    return TRUE;
}

VOID
ContinueTargetSystem(
    DWORD               ContinueStatus,
    PDBGKD_CONTROL_SET  ControlSet
    )
{
    DWORD   rc;

    ApiIsAllowed = FALSE;

    if (ControlSet) {

        rc = DmKdContinue2( ContinueStatus, ControlSet );

    } else {

        rc = DmKdContinue( ContinueStatus );

    }
}

ULONG
UnicodeStringToAnsiString(
    PANSI_STRING    DestinationString,
    PUNICODE_STRING SourceString,
    BOOLEAN         AllocateDestinationString
    )
{
    if (AllocateDestinationString) {
        DestinationString->Buffer = malloc( DestinationString->MaximumLength );
        if (!DestinationString->Buffer) {
            return 1;
        }
    }

    DestinationString->Length = WideCharToMultiByte(
        CP_ACP,
        WC_COMPOSITECHECK,
        SourceString->Buffer,
        SourceString->Length / 2,
        DestinationString->Buffer,
        DestinationString->MaximumLength,
        NULL,
        NULL
        );

    return 0;
}


VOID
InitUnicodeString(
    PUNICODE_STRING DestinationString,
    PCWSTR          SourceString
    )
{
    wcsncpy( DestinationString->Buffer, SourceString, DestinationString->MaximumLength );
    DestinationString->Length = wcslen( DestinationString->Buffer ) * 2;
}


BOOL
ReloadModule(
    HTHDX                  hthd,
    PLDR_DATA_TABLE_ENTRY  DataTableBuffer,
    BOOL                   fDontUseLoadAddr,
    BOOL                   fLocalBuffer
    )
{
    UNICODE_STRING              BaseName;
    CHAR                        AnsiBuffer[512];
    WCHAR                       UnicodeBuffer[512];
    ANSI_STRING                 AnsiString;
    NTSTATUS                    Status;
    DEBUG_EVENT                 de;
    CHAR                        fname[_MAX_FNAME];
    CHAR                        ext[_MAX_EXT];
    ULONG                       cb;


    //
    // Get the base DLL name.
    //
    if (DataTableBuffer->BaseDllName.Length != 0 &&
        DataTableBuffer->BaseDllName.Buffer != NULL ) {

        BaseName = DataTableBuffer->BaseDllName;

    } else
    if (DataTableBuffer->FullDllName.Length != 0 &&
        DataTableBuffer->FullDllName.Buffer != NULL ) {

        BaseName = DataTableBuffer->FullDllName;

    } else {

        return FALSE;

    }

    if (BaseName.Length > sizeof(UnicodeBuffer)) {
        DMPrintShellMsg( "cannot complete modload %08x\n", BaseName.Length );
        return FALSE;
    }

    if (!fLocalBuffer) {
        if (!DbgReadMemory( hthd->hprc, (PVOID)BaseName.Buffer, (PVOID)UnicodeBuffer, BaseName.Length, &cb )) {
            return FALSE;
        }
        BaseName.Buffer = UnicodeBuffer;
        BaseName.Length = (USHORT)cb;
        BaseName.MaximumLength = (USHORT)(cb + sizeof( UNICODE_NULL ));
        UnicodeBuffer[ cb / sizeof( WCHAR ) ] = UNICODE_NULL;
    }

    AnsiString.Buffer = AnsiBuffer;
    AnsiString.MaximumLength = 256;
    Status = UnicodeStringToAnsiString(&AnsiString, &BaseName, FALSE);
    if (!NT_SUCCESS(Status)) {
        return FALSE;
    }
    AnsiString.Buffer[AnsiString.Length] = '\0';

    _splitpath( AnsiString.Buffer, NULL, NULL, fname, ext );
    _makepath( AnsiString.Buffer, NULL, NULL, fname, ext );

    de.dwDebugEventCode                 = LOAD_DLL_DEBUG_EVENT;
    de.dwProcessId                      = KD_PROCESSID;
    de.dwThreadId                       = KD_THREADID;
    de.u.LoadDll.hFile                  = (HANDLE)DataTableBuffer->CheckSum;
    de.u.LoadDll.lpBaseOfDll            = fDontUseLoadAddr ? 0 : (LPVOID) DataTableBuffer->DllBase;
    de.u.LoadDll.lpImageName            = AnsiString.Buffer;
    de.u.LoadDll.dwDebugInfoFileOffset  = DataTableBuffer->SizeOfImage;
    de.u.LoadDll.fUnicode               = FALSE;
    de.u.LoadDll.nDebugInfoSize         = 0;

    NotifyEM(&de, hthd, 0, (LPVOID)0);

    return TRUE;
}


BOOL
ReloadModulesFromList(
    HTHDX hthd,
    DWORD ListAddr,
    BOOL  fDontUseLoadAddr,
    LPSTR JustLoadThisOne,
    ULONG UseThisAddress
    )
{
    LIST_ENTRY                  List;
    PLIST_ENTRY                 Next;
    ULONG                       len = 0;
    PLDR_DATA_TABLE_ENTRY       DataTable;
    LDR_DATA_TABLE_ENTRY        DataTableBuffer;
    WCHAR                       UnicodeBuffer[_MAX_PATH];
    WCHAR                       UnicodeBuffer2[_MAX_PATH];
    int                         Len;
    BOOL                        LoadedSomething;


    if (!ListAddr) {
        return FALSE;
    }

    //
    // convert the module name to unicode
    //

    *UnicodeBuffer = 0;

    if (JustLoadThisOne) {


        Len = strlen(JustLoadThisOne);
        MultiByteToWideChar(
            CP_OEMCP,
            0,
            JustLoadThisOne,
            Len,
            UnicodeBuffer,
            sizeof(UnicodeBuffer)
            );
    }

    if (!DbgReadMemory( hthd->hprc, (PVOID)ListAddr, (PVOID)&List, sizeof(LIST_ENTRY), NULL)) {
        return FALSE;
    }

    Next = List.Flink;
    if (Next == NULL) {
        return FALSE;
    }

    LoadedSomething = FALSE;

    while ((ULONG)Next != ListAddr) {
        DataTable = CONTAINING_RECORD( Next,
                                       LDR_DATA_TABLE_ENTRY,
                                       InLoadOrderLinks
                                     );

        if (!DbgReadMemory( hthd->hprc, (PVOID)DataTable, (PVOID)&DataTableBuffer, sizeof(LDR_DATA_TABLE_ENTRY), NULL)) {
            break;
        }

        Next = DataTableBuffer.InLoadOrderLinks.Flink;

        if (!JustLoadThisOne) {
            ReloadModule( hthd, &DataTableBuffer, fDontUseLoadAddr, FALSE );
            LoadedSomething = TRUE;
        } else {
            if (2*Len == DataTableBuffer.BaseDllName.Length) {
                if (!DbgReadMemory( hthd->hprc,
                                    (PVOID)DataTableBuffer.BaseDllName.Buffer,
                                    (PVOID)UnicodeBuffer2,
                                    DataTableBuffer.BaseDllName.Length,
                                    NULL )) {
                    continue;
                }
                if (_wcsnicmp(UnicodeBuffer, UnicodeBuffer2, Len) == 0) {
                    if (UseThisAddress) {
                        DataTableBuffer.DllBase = (PVOID)UseThisAddress;
                    }
                    ReloadModule( hthd, &DataTableBuffer, fDontUseLoadAddr, FALSE );
                    LoadedSomething = TRUE;
                    break;
                }
            }
        }
    }

    return LoadedSomething;
}


BOOL
ReloadCrashModules(
    HTHDX hthd
    )
{
    ULONG                       ListAddr;
    ULONG                       DcbPtr;
    ULONG                       i;
    DUMP_CONTROL_BLOCK          dcb;
    PLIST_ENTRY                 Next;
    ULONG                       len = 0;
    PMINIPORT_NODE              mpNode;
    MINIPORT_NODE               mpNodeBuf;
    PLDR_DATA_TABLE_ENTRY       DataTable;
    LDR_DATA_TABLE_ENTRY        DataTableBuffer;
    CHAR                        AnsiBuffer[512];
    WCHAR                       UnicodeBuffer[512];


    if (!DcbAddr) {
        //
        // kernel symbols are hosed
        //
        return FALSE;
    }

    if (!DbgReadMemory( hthd->hprc, (PVOID)DcbAddr, (PVOID)&DcbPtr, sizeof(DWORD), NULL)) {
        return FALSE;
    }

    if (!DcbPtr) {
        //
        // crash dumps are not enabled
        //
        return FALSE;
    }

    if (!DbgReadMemory( hthd->hprc, (PVOID)DcbPtr, (PVOID)&dcb, sizeof(dcb), NULL)) {
        return FALSE;
    }

    ListAddr = DcbPtr + FIELD_OFFSET( DUMP_CONTROL_BLOCK, MiniportQueue );

    Next = dcb.MiniportQueue.Flink;
    if (Next == NULL) {
        return FALSE;
    }

    while ((ULONG)Next != ListAddr) {
        mpNode = CONTAINING_RECORD( Next, MINIPORT_NODE, ListEntry );

        if (!DbgReadMemory( hthd->hprc, (PVOID)mpNode, (PVOID)&mpNodeBuf, sizeof(MINIPORT_NODE), NULL )) {
            return FALSE;
        }

        Next = mpNodeBuf.ListEntry.Flink;

        DataTable = mpNodeBuf.DriverEntry;
        if (!DataTable) {
            continue;
        }

        if (!DbgReadMemory( hthd->hprc, (PVOID)DataTable, (PVOID)&DataTableBuffer, sizeof(LDR_DATA_TABLE_ENTRY), NULL)) {
            return FALSE;
        }

        //
        // find an empty module alias slot
        //
        for (i=0; i<MAX_MODULEALIAS; i++) {
            if (ModuleAlias[i].ModuleName[0] == 0) {
                break;
            }
         }

        if (i == MAX_MODULEALIAS) {
            //
            // module alias table is full, ignore this module
            //
            continue;
        }

        //
        // convert the module name to ansi
        //

        ZeroMemory( UnicodeBuffer, sizeof(UnicodeBuffer) );
        ZeroMemory( AnsiBuffer, sizeof(AnsiBuffer) );

        if (!DbgReadMemory( hthd->hprc,
                            (PVOID)DataTableBuffer.BaseDllName.Buffer,
                            (PVOID)UnicodeBuffer,
                            DataTableBuffer.BaseDllName.Length,
                            NULL )) {
            continue;
        }

        WideCharToMultiByte(
            CP_OEMCP,
            0,
            UnicodeBuffer,
            DataTableBuffer.BaseDllName.Length / 2,
            AnsiBuffer,
            sizeof(AnsiBuffer),
            NULL,
            NULL
            );

        //
        // establish an alias for the crash driver
        //
        strcpy( ModuleAlias[i].Alias, AnsiBuffer );
        ModuleAlias[i].ModuleName[0] = 'c';
        _splitpath( AnsiBuffer, NULL, NULL, &ModuleAlias[i].ModuleName[1], NULL );
        ModuleAlias[i].ModuleName[8] = 0;
        ModuleAlias[i].Special = 2;     // One shot alias...

        //
        // reload the module
        //
        ReloadModule( hthd, &DataTableBuffer, FALSE, FALSE );
    }

    //
    // now do the magic diskdump.sys driver
    //
    if (!DbgReadMemory( hthd->hprc, (PVOID)dcb.DiskDumpDriver, (PVOID)&DataTableBuffer, sizeof(LDR_DATA_TABLE_ENTRY), NULL)) {
        return FALSE;
    }

    //
    // change the driver name from scsiport.sys to diskdump.sys
    //
    DataTableBuffer.BaseDllName.Buffer = UnicodeBuffer;
    InitUnicodeString( &DataTableBuffer.BaseDllName, L"diskdump.sys" );

    //
    // load the module
    //
    ReloadModule( hthd, &DataTableBuffer, FALSE, TRUE );

    return TRUE;
}


BOOL
FindModuleInList(
    HPRCX                  hprc,
    LPSTR                  lpModName,
    DWORD                  ListAddr,
    LPIMAGEINFO            ii
    )
{
    LIST_ENTRY                  List;
    PLIST_ENTRY                 Next;
    ULONG                       len = 0;
    ULONG                       cb;
    PLDR_DATA_TABLE_ENTRY       DataTable;
    LDR_DATA_TABLE_ENTRY        DataTableBuffer;
    UNICODE_STRING              BaseName;
    CHAR                        AnsiBuffer[512];
    WCHAR                       UnicodeBuffer[512];
    ANSI_STRING                 AnsiString;
    NTSTATUS                    Status;


    ii->CheckSum     = 0;
    ii->SizeOfImage  = 0;
    ii->BaseOfImage  = 0;

    if (!ListAddr) {
        return FALSE;
    }

    if (!DbgReadMemory( hprc, (PVOID)ListAddr, (PVOID)&List, sizeof(LIST_ENTRY), NULL)) {
        return FALSE;
    }

    Next = List.Flink;
    if (Next == NULL) {
        return FALSE;
    }

    while ((ULONG)Next != ListAddr) {
        DataTable = CONTAINING_RECORD( Next,
                                       LDR_DATA_TABLE_ENTRY,
                                       InLoadOrderLinks
                                     );
        if (!DbgReadMemory( hprc, (PVOID)DataTable, (PVOID)&DataTableBuffer, sizeof(LDR_DATA_TABLE_ENTRY), NULL)) {
            return FALSE;
        }

        Next = DataTableBuffer.InLoadOrderLinks.Flink;

        //
        // Get the base DLL name.
        //
        if (DataTableBuffer.BaseDllName.Length != 0 &&
            DataTableBuffer.BaseDllName.Buffer != NULL
           ) {
            BaseName = DataTableBuffer.BaseDllName;
        }
        else
        if (DataTableBuffer.FullDllName.Length != 0 &&
            DataTableBuffer.FullDllName.Buffer != NULL
           ) {
            BaseName = DataTableBuffer.FullDllName;
        }
        else {
            continue;
        }

        if (BaseName.Length > sizeof(UnicodeBuffer)) {
            continue;
        }

        cb = DbgReadMemory( hprc,
                            (PVOID)BaseName.Buffer,
                            (PVOID)UnicodeBuffer,
                            BaseName.Length,
                            NULL );
        if (!cb) {
            return FALSE;
        }

        BaseName.Buffer = UnicodeBuffer;
        BaseName.Length = (USHORT)cb;
        BaseName.MaximumLength = (USHORT)(cb + sizeof( UNICODE_NULL ));
        UnicodeBuffer[ cb / sizeof( WCHAR ) ] = UNICODE_NULL;
        AnsiString.Buffer = AnsiBuffer;
        AnsiString.MaximumLength = 256;
        Status = UnicodeStringToAnsiString(&AnsiString, &BaseName, FALSE);
        if (!NT_SUCCESS(Status)) {
            return FALSE;
        }
        AnsiString.Buffer[AnsiString.Length] = '\0';

        if (_stricmp(AnsiString.Buffer, lpModName) == 0) {
            ii->BaseOfImage = (DWORD)DataTableBuffer.DllBase;
            ii->SizeOfImage = (DWORD)DataTableBuffer.SizeOfImage;
            ii->CheckSum    = (DWORD)DataTableBuffer.CheckSum;
            return TRUE;
        }
    }

    return FALSE;
}


BOOL
ReadImageInfo(
    LPSTR                  lpImageName,
    LPSTR                  lpFoundName,
    LPSTR                  lpPath,
    LPIMAGEINFO            ii
    )

/*++

Routine Description:

    This routine locates the file specified by lpImageName and reads the
    IMAGE_NT_HEADERS and the IMAGE_SECTION_HEADER from the image.

Arguments:


Return Value:

    True on success and FALSE on failure

--*/

{
    HANDLE                      hFile;
    IMAGE_DOS_HEADER            dh;
    IMAGE_NT_HEADERS            nh;
    IMAGE_SEPARATE_DEBUG_HEADER sdh;
    IMAGE_ROM_OPTIONAL_HEADER   rom;
    DWORD                       sig;
    DWORD                       cb;
    char                        rgch[MAX_PATH];
    CHAR                        fname[_MAX_FNAME];
    CHAR                        ext[_MAX_EXT];
    CHAR                        drive[_MAX_DRIVE];
    CHAR                        dir[_MAX_DIR];
    CHAR                        modname[MAX_PATH];


    hFile = FindExecutableImage( lpImageName, lpPath, rgch );
    if (hFile) {

        if (lpFoundName) {
            strcpy(lpFoundName, rgch);
        }
        //
        // read in the pe/file headers from the EXE file
        //
        SetFilePointer( hFile, 0, 0, FILE_BEGIN );
        ReadFile( hFile, &dh, sizeof(IMAGE_DOS_HEADER), &cb, NULL );

        if (dh.e_magic == IMAGE_DOS_SIGNATURE) {
            SetFilePointer( hFile, dh.e_lfanew, 0, FILE_BEGIN );
        } else {
            SetFilePointer( hFile, 0, 0, FILE_BEGIN );
        }

        ReadFile( hFile, &sig, sizeof(sig), &cb, NULL );
        SetFilePointer( hFile, -4, NULL, FILE_CURRENT );

        if (sig != IMAGE_NT_SIGNATURE) {
            ReadFile( hFile, &nh.FileHeader, sizeof(IMAGE_FILE_HEADER), &cb, NULL );
            if (nh.FileHeader.SizeOfOptionalHeader == IMAGE_SIZEOF_ROM_OPTIONAL_HEADER) {
                ReadFile( hFile, &rom, sizeof(rom), &cb, NULL );
                ZeroMemory( &nh.OptionalHeader, sizeof(nh.OptionalHeader) );
                nh.OptionalHeader.SizeOfImage      = rom.SizeOfCode;
                nh.OptionalHeader.ImageBase        = rom.BaseOfCode;
            } else {
                CloseHandle( hFile );
                return FALSE;
            }
        } else {
            ReadFile( hFile, &nh, sizeof(nh), &cb, NULL );
        }

        ii->TimeStamp    = nh.FileHeader.TimeDateStamp;
        ii->CheckSum     = nh.OptionalHeader.CheckSum;
        ii->SizeOfImage  = nh.OptionalHeader.SizeOfImage;
        ii->BaseOfImage  = nh.OptionalHeader.ImageBase;

    } else {

        if (lpFoundName) {
            *lpFoundName = 0;
        }
        //
        // read in the pe/file headers from the DBG file
        //
        hFile = FindDebugInfoFile( lpImageName, lpPath, rgch );
        if (!hFile) {
            _splitpath( lpImageName, NULL, NULL, fname, NULL );
            sprintf( modname, "%s.dbg", fname );
            hFile = FindExecutableImage( modname, lpPath, rgch );
            if (!hFile) {
                return FALSE;
            }
        }

        SetFilePointer( hFile, 0, 0, FILE_BEGIN );
        ReadFile( hFile, &sdh, sizeof(IMAGE_SEPARATE_DEBUG_HEADER), &cb, NULL );

        nh.FileHeader.NumberOfSections = (USHORT)sdh.NumberOfSections;

        ii->CheckSum     = sdh.CheckSum;
        ii->TimeStamp    = sdh.TimeDateStamp;
        ii->SizeOfImage  = sdh.SizeOfImage;
        ii->BaseOfImage  = sdh.ImageBase;
    }

    cb = nh.FileHeader.NumberOfSections * IMAGE_SIZEOF_SECTION_HEADER;
    ii->NumberOfSections = nh.FileHeader.NumberOfSections;
    ii->Sections = malloc( cb );
    ReadFile( hFile, ii->Sections, cb, &cb, NULL );

    CloseHandle( hFile );
    return TRUE;
}


BOOL
LookupImageByAddress(
    IN DWORD Address,
    OUT PSTR ImageName
    )
/*++

Routine Description:

    Look in rebase.log and coffbase.txt for an image which
    contains the address provided.

Arguments:

    Address - Supplies the address to look for.

    ImageName - Returns the name of the image if found.

Return Value:

    TRUE for success, FALSE for failure.  ImageName is not modified
    if the search fails.

--*/
{
    LPSTR RootPath;
    LPSTR pstr;
    char FileName[_MAX_PATH];
    char Buffer[_MAX_PATH];
    BOOL Replace;
    DWORD ImageAddress;
    DWORD Size;
    FILE *File;

    //
    // Locate rebase.log file
    //
    // SymbolPath or %SystemRoot%\Symbols
    //

    RootPath = pstr = (LPSTR)KdOptions[KDO_SYMBOLPATH].value;

    Replace = FALSE;
    File = NULL;

    while (File == NULL && *pstr) {

        while (*pstr) {
            if (*pstr == ';') {
                *pstr = 0;
                Replace = TRUE;
                break;
            }
            pstr++;
        }

        if (SearchTreeForFile(RootPath, "rebase.log", FileName)) {
            File = fopen(FileName, "r");
        }

        if (Replace) {
            *pstr = ';';
            RootPath = ++pstr;
        }
    }

    if (!File) {
        return FALSE;
    }

    //
    // Search file for image
    //
    while (fgets(Buffer, sizeof(Buffer), File)) {
        ImageAddress = 0xffffffff;
        Size = 0xffffffff;
        sscanf( Buffer, "%s %*s %*s 0x%x (size 0x%x)",
                 FileName, &ImageAddress, &Size);
        if (Size == 0xffffffff) {
            continue;
        }
        if (Address >= ImageAddress && Address < ImageAddress + Size) {
            strcpy(ImageName, FileName);
            fclose(File);
            return TRUE;
        }
    }

    fclose(File);

    return FALSE;
}

VOID
ReloadModules(
    HTHDX hthd,
    LPSTR args
    )
{
    DEBUG_EVENT                 de;
    ULONG                       len = 0;
    int                         i;
    HPRCX                       hprc;
    LPRTP                       rtp;
    CHAR                        fname[_MAX_FNAME];
    CHAR                        ext[_MAX_EXT];
    CHAR                        drive[_MAX_DRIVE];
    CHAR                        dir[_MAX_DIR];
    CHAR                        modname[MAX_PATH];
    CHAR                        modpath[MAX_PATH*2];
    ULONG                       Address;
    ULONG                       LoadAddress;
    BOOL                        UnloadOnly = FALSE;
    PCHAR                       p;


    //
    // this is to handle the ".reload foo.exe" command
    //
    // we search thru the module list and find the desired module.
    // the module is then unloaded and re-loaded.  the module is re-loaded
    // at its preferred load address.
    //
    if (args && *args) {

        //
        //  skip over any white space
        //
        while (*args == ' ' || *args == '\t') {
            args++;
        }

        if (args[0] == '/' && args[1] == 'u') {
            UnloadOnly = TRUE;
            args += 2;
            while (*args == ' ' || *args == '\t') {
                args++;
            }
        }

        LoadAddress = 0;
        if (p = strchr(args, '=')) {
            *p = 0;
            sscanf(p+1, "%x", &LoadAddress);
        }

        _splitpath( args, drive, dir, fname, ext );

        if (p) {
            *p = '=';
        }

        _makepath( modname, NULL, NULL, fname, ext );

        if (isdigit(*args)) {
            sscanf(args, "%x", &Address);
            if (LookupImageByAddress(Address, modname)) {
                _splitpath( modname, drive, dir, fname, ext );
            }
        }

        hprc = HPRCFromPID( KD_PROCESSID );

        for (i=0; i<hprc->cDllList; i++) {
            if ((hprc->rgDllList[i].fValidDll) &&
                (_stricmp(hprc->rgDllList[i].szDllName, modname) == 0)) {

                UnloadModule( (DWORD)hprc->rgDllList[i].offBaseOfImage, modname );
                break;

            }
        }


        if (!UnloadOnly) {

            if (dir[0]) {
                sprintf( modpath, "%s%s", drive, dir );
            } else {
                strcpy( modpath, (LPSTR)KdOptions[KDO_SYMBOLPATH].value );
            }

            _makepath( modname, drive, dir, fname, ext );

            if (!ReloadModulesFromList(hthd,
                                       vs.PsLoadedModuleList,
                                       FALSE,
                                       modname,
                                       LoadAddress)) {
                if (!ReloadModulesFromList(hthd,
                                           MmLoadedUserImageList,
                                           FALSE,
                                           modname,
                                           LoadAddress)) {
                    de.dwDebugEventCode                = LOAD_DLL_DEBUG_EVENT;
                    de.dwProcessId                     = KD_PROCESSID;
                    de.dwThreadId                      = KD_THREADID;
                    de.u.LoadDll.hFile                 = NULL;
                    de.u.LoadDll.lpBaseOfDll           = (LPVOID)LoadAddress;
                    de.u.LoadDll.lpImageName           = modname;
                    de.u.LoadDll.fUnicode              = FALSE;
                    de.u.LoadDll.nDebugInfoSize        = 0;
                    de.u.LoadDll.dwDebugInfoFileOffset = 0;
                    NotifyEM(&de, hthd, 0, (LPVOID)0);

                }
            }
        }

    } else {

        UnloadAllModules();

        ReloadModulesFromList( hthd, vs.PsLoadedModuleList, FALSE, NULL, 0 );
        ReloadModulesFromList( hthd, MmLoadedUserImageList, FALSE, NULL, 0 );

        ReloadCrashModules( hthd );

        InitializeKiProcessor();
    }

    DMPrintShellMsg( "Finished re-loading kernel modules\n" );

    //
    // tell the shell that the !reload is finished
    //
    rtp = (LPRTP)malloc(sizeof(RTP)+sizeof(DWORD));
    rtp->hpid = hthd->hprc->hpid;
    rtp->htid = hthd->htid;
    rtp->dbc = dbcIoctlDone;
    rtp->cb = sizeof(DWORD);
    *(LPDWORD)rtp->rgbVar = 1;
    DmTlFunc( tlfDebugPacket, rtp->hpid, sizeof(RTP)+rtp->cb, (LONG)rtp );
    free( rtp );

    ConsumeAllEvents();
    return;
}

VOID
ClearBps( VOID )
{
    DBGKD_RESTORE_BREAKPOINT    bps[MAX_KD_BPS];
    DWORD                       i;

    //
    // clean out the kernel's bp list
    //
    for (i=0; i<MAX_KD_BPS; i++) {
        bps[i].BreakPointHandle = i + 1;
    }

    RestoreBreakPointEx( MAX_KD_BPS, bps );

    return;
}

void
AddQueue(
    DWORD   dwType,
    DWORD   dwProcessId,
    DWORD   dwThreadId,
    DWORD   dwData,
    DWORD   dwLen
    )
{
    LPCQUEUE lpcq;


    EnterCriticalSection(&csContinueQueue);

    lpcq = lpcqFree;
    assert(lpcq);

    lpcqFree = lpcq->next;

    lpcq->next = NULL;
    if (lpcqLast) {
        lpcqLast->next = lpcq;
    }
    lpcqLast = lpcq;

    if (!lpcqFirst) {
        lpcqFirst = lpcq;
    }

    lpcq->pid  = dwProcessId;
    lpcq->tid  = dwThreadId;
    lpcq->typ  = dwType;
    lpcq->len  = dwLen;

    if (lpcq->typ == QT_RELOAD_MODULES || lpcq->typ == QT_DEBUGSTRING) {
        if (dwLen) {
            lpcq->data = (DWORD) malloc( dwLen );
            memcpy( (LPVOID)lpcq->data, (LPVOID)dwData, dwLen );
        }
        else {
            lpcq->data = 0;
        }

    }
    else {
        lpcq->data = dwData;
    }

    if (lpcq->typ == QT_CONTINUE_DEBUG_EVENT) {
        SetEvent( hEventContinue );
    }

    LeaveCriticalSection(&csContinueQueue);
    return;
}

BOOL
DequeueOneEvent(
    LPCQUEUE lpcqReturn
    )
{
    LPCQUEUE           lpcq;

    EnterCriticalSection(&csContinueQueue);

    if (!lpcqFirst) {
        LeaveCriticalSection(&csContinueQueue);
        return FALSE;
    }

    lpcq = lpcqFirst;

    lpcqFirst = lpcq->next;
    if (lpcqFirst == NULL) {
        lpcqLast = NULL;
    }

    lpcq->next = lpcqFree;
    lpcqFree   = lpcq;

    if (lpcq->pid == 0 || lpcq->tid == 0) {
        lpcq->pid = KD_PROCESSID;
        lpcq->tid = KD_THREADID;
    }

    *lpcqReturn = *lpcq;

    LeaveCriticalSection(&csContinueQueue);

    return TRUE;
}


BOOL
DequeueAllEvents(
    BOOL fForce,       // force a dequeue even if the dm isn't initialized
    BOOL fConsume      // delete all events from the queue with no action
    )
{
    CQUEUE             qitem;
    LPCQUEUE           lpcq = &qitem;
    BOOL               fDid = FALSE;
    HTHDX              hthd;
    DBGKD_CONTROL_SET  cs = {0};
    LPSTR              d;


    ResetEvent(hEventContinue);

    while ( DequeueOneEvent(&qitem) ) {

        if (fConsume) {
            if (lpcq->typ == QT_CONTINUE_DEBUG_EVENT) {
                fDid = TRUE;
            }
            continue;
        }

        hthd = HTHDXFromPIDTID(lpcq->pid, lpcq->tid);
        if (hthd && hthd->fContextDirty) {
            DbgSetThreadContext( hthd, &hthd->context );
            hthd->fContextDirty = FALSE;
        }

        d = (LPSTR)lpcq->data;

        switch (lpcq->typ) {
            case QT_CONTINUE_DEBUG_EVENT:
                if (fCrashDump) {
                    break;
                }
                if (DmKdState >= S_READY || fForce) {
                    if (!fDid) {
                        fDid = TRUE;
                        ContinueTargetSystem( (DWORD)d, NULL );
                    }
                }
                break;

            case QT_TRACE_DEBUG_EVENT:
                if (fCrashDump) {
                    break;
                }
                if (DmKdState >= S_READY || fForce) {
                    if (!fDid) {
                        fDid = TRUE;
#ifdef TARGET_i386
                        cs.TraceFlag = 1;
                        cs.Dr7 = sc.ControlReport.Dr7;
                        cs.CurrentSymbolStart = 1;
                        cs.CurrentSymbolEnd = 1;
                        ContinueTargetSystem( (DWORD)d, &cs );
#else
                        ContinueTargetSystem( (DWORD)d, NULL );
#endif
                    }
                }
                break;

            case QT_RELOAD_MODULES:
                ReloadModules( hthd, d );
                free( (LPVOID)d );
                break;

            case QT_REBOOT:
                if (fCrashDump) {
                    break;
                }
                DMPrintShellMsg( "Target system rebooting...\n" );
                DmKdPurgeCachedVirtualMemory( TRUE );
                UnloadAllModules();
                ZeroMemory( ContextCache, sizeof(ContextCache) );
                DmKdState = S_REBOOTED;
                DmKdReboot();
                InitialBreak = (BOOL) KdOptions[KDO_INITIALBP].value;
                KdResync = TRUE;
                break;

            case QT_CRASH:
                if (fCrashDump) {
                    break;
                }
                DMPrintShellMsg( "Target system crashing...\n" );
                DmKdCrash( (DWORD)d );
                InitialBreak = (BOOL) KdOptions[KDO_INITIALBP].value;
                KdResync = TRUE;
                fDid = TRUE;
                break;

            case QT_RESYNC:
                if (fCrashDump) {
                    break;
                }
                DMPrintShellMsg( "Host and target systems resynchronizing...\n" );
                KdResync = TRUE;
                break;

            case QT_DEBUGSTRING:
                DMPrintShellMsg( "%s", (LPSTR)d );
                free( (LPVOID)d );
                break;

        }

    }

    return fDid;
}

VOID
WriteKernBase(
    DWORD KernBase
    )
{
    HKEY  hKeyKd;


    if ( RegOpenKey( HKEY_CURRENT_USER,
                     "software\\microsoft\\windbg\\0012\\programs\\ntoskrnl",
                     &hKeyKd ) == ERROR_SUCCESS ) {
        RegSetValueEx( hKeyKd, "KernBase", 0, REG_DWORD, (LPBYTE)&KernBase, sizeof(DWORD) );
        RegCloseKey( hKeyKd );
    }

    return;
}

DWORD
ReadKernBase(
    VOID
    )
{
    HKEY   hKeyKd;
    DWORD  dwType;
    DWORD  KernBase;
    DWORD  dwSize;


    if ( RegOpenKey( HKEY_CURRENT_USER,
                     "software\\microsoft\\windbg\\0012\\programs\\ntoskrnl",
                     &hKeyKd ) == ERROR_SUCCESS ) {
        dwSize = sizeof(DWORD);
        RegQueryValueEx( hKeyKd, "KernBase", NULL, &dwType, (LPBYTE)&KernBase, &dwSize );
        RegCloseKey( hKeyKd );
        return KernBase;
    }

    return KernBase;
}

VOID
GetVersionInfo(
    DWORD KernBase
    )
{
    CHAR                        buf[MAX_PATH];


    if (!fCrashDump) {
        ZeroMemory( &vs, sizeof(vs) );
        if (DmKdGetVersion( &vs ) == STATUS_SUCCESS) {
            if (!vs.KernBase) {
                vs.KernBase = KernBase;
            }
        }
    }

    sprintf( buf, "Kernel Version %d", vs.MinorVersion  );
    if (vs.MajorVersion == 0xC) {
        strcat( buf, " Checked" );
    } else if (vs.MajorVersion == 0xF) {
        strcat( buf, " Free" );
    }
    sprintf( &buf[strlen(buf)], " loaded @ 0x%08x", vs.KernBase  );

    DMPrintShellMsg( "%s\n", buf );

    return;
}

VOID
InitializeExtraProcessors(
    VOID
    )
{
    HTHDX               hthd;
    DWORD               i;
    DEBUG_EVENT         de;


    CacheProcessors = sc.NumberProcessors;
    for (i = 1; i < sc.NumberProcessors; i++) {
        //
        // initialize the hthd
        //
        hthd = HTHDXFromPIDTID( KD_PROCESSID, i );

        //
        // refresh the context cache for this processor
        //
#if defined(TARGET_i386) || defined(TARGET_PPC)
        ContextCache[i].fSContextDirty = FALSE;
        ContextCache[i].fSContextStale = TRUE;
#endif
        ContextCache[i].fContextDirty = FALSE;
        ContextCache[i].fContextStale = TRUE;

        //
        // tell debugger to create the thread (processor)
        //
        de.dwDebugEventCode = CREATE_THREAD_DEBUG_EVENT;
        de.dwProcessId = KD_PROCESSID;
        de.dwThreadId  = i + 1;
        de.u.CreateThread.hThread = (HANDLE)(i + 1);
        de.u.CreateThread.lpThreadLocalBase = NULL;
        de.u.CreateThread.lpStartAddress = NULL;
        ProcessDebugEvent(&de, &sc);
        WaitForSingleObject(hEventContinue,INFINITE);
    }



    //
    // consume any continues that may have been queued
    //
    ConsumeAllEvents();

    //
    // get out of here
    //
    return;
}

DWORD
DmKdPollThread(
    LPSTR lpProgName
    )
{
    char                        buf[512];
    DWORD                       st;
    DWORD                       i;
    DWORD                       j;
    BOOL                        fFirstSc = FALSE;
    DEBUG_EVENT                 de;
    char                        fname[_MAX_FNAME];
    char                        ext[_MAX_EXT];
    HTHDX                       hthd;
    DWORD                       n;
    IMAGEINFO                   ii;
    HPRCX                       hprc;


    PollThreadId = GetCurrentThreadId();

    //
    // initialize the queue variables
    //
    n = sizeof(cqueue) / sizeof(CQUEUE);
    for (i = 0; i < n-1; i++) {
        cqueue[i].next = &cqueue[i+1];
    }
    --n;
    cqueue[n].next = NULL;
    lpcqFree = &cqueue[0];
    lpcqFirst = NULL;
    lpcqLast = NULL;
    InitializeCriticalSection(&csContinueQueue);

    DmKdSetMaxCacheSize( KdOptions[KDO_CACHE].value );
    InitialBreak = (BOOL) KdOptions[KDO_INITIALBP].value;

    //
    // simulate a create process debug event
    //
    de.dwDebugEventCode = CREATE_PROCESS_DEBUG_EVENT;
    de.dwProcessId = KD_PROCESSID;
    de.dwThreadId  = KD_THREADID;
    de.u.CreateProcessInfo.hFile = NULL;
    de.u.CreateProcessInfo.hProcess = NULL;
    de.u.CreateProcessInfo.hThread = NULL;
    de.u.CreateProcessInfo.lpBaseOfImage = 0;
    de.u.CreateProcessInfo.dwDebugInfoFileOffset = 0;
    de.u.CreateProcessInfo.nDebugInfoSize = 0;
    de.u.CreateProcessInfo.lpStartAddress = NULL;
    de.u.CreateProcessInfo.lpThreadLocalBase = NULL;
    de.u.CreateProcessInfo.lpImageName = lpProgName;
    de.u.CreateProcessInfo.fUnicode = 0;
    de.u.LoadDll.nDebugInfoSize = 0;
    ProcessDebugEvent(&de, &sc);
    WaitForSingleObject(hEventContinue,INFINITE);
    hprc = HPRCFromPID( KD_PROCESSID );
    ConsumeAllEvents();

    //
    // simulate a loader breakpoint event
    //
    de.dwDebugEventCode = BREAKPOINT_DEBUG_EVENT;
    de.dwProcessId = KD_PROCESSID;
    de.dwThreadId  = KD_THREADID;
    de.u.Exception.dwFirstChance = TRUE;
    de.u.Exception.ExceptionRecord.ExceptionCode = EXCEPTION_BREAKPOINT;
    de.u.Exception.ExceptionRecord.ExceptionFlags = 0;
    de.u.Exception.ExceptionRecord.ExceptionRecord = NULL;
    de.u.Exception.ExceptionRecord.ExceptionAddress = 0;
    de.u.Exception.ExceptionRecord.NumberParameters = 0;
    ProcessDebugEvent( &de, &sc );
    ConsumeAllEvents();

    DMPrintShellMsg( "Kernel debugger waiting to connect on com%d @ %d baud\n",
                     KdOptions[KDO_PORT].value,
                     KdOptions[KDO_BAUDRATE].value
                   );

    setjmp( JumpBuffer );

    while (TRUE) {

        if (DmKdExit) {
            return 0;
        }

        ApiIsAllowed = FALSE;

        st = DmKdWaitStateChange( &sc, buf, sizeof(buf) );

        if (st != STATUS_SUCCESS ) {
            DEBUG_PRINT_1( "DmKdWaitStateChange failed: %08lx\n", st );
            return 0;
        }

        ApiIsAllowed = TRUE;

        fFirstSc = FALSE;

        if (sc.NewState == DbgKdLoadSymbolsStateChange) {
            _splitpath( buf, NULL, NULL, fname, ext );
            _makepath( buf, NULL, NULL, fname, ext );
            if ((DmKdState == S_UNINITIALIZED) &&
                (_stricmp( buf, KERNEL_IMAGE_NAME ) == 0)) {
                WriteKernBase( (DWORD)sc.u.LoadSymbols.BaseOfDll );
                fFirstSc = TRUE;
            }
        }

        if ((DmKdState == S_UNINITIALIZED) ||
            (DmKdState == S_REBOOTED)) {
            hthd = HTHDXFromPIDTID( KD_PROCESSID, KD_THREADID );
            ContextCache[sc.Processor].fContextStale = TRUE;
            DbgGetThreadContext( hthd, &sc.Context );
#if defined(TARGET_i386) || defined(TARGET_PPC)
            ContextCache[sc.Processor].fSContextStale = TRUE;
#endif
        } else if (sc.NewState != DbgKdLoadSymbolsStateChange) {
#if defined(TARGET_i386) || defined(TARGET_PPC)
            ContextCache[sc.Processor].fSContextStale = TRUE;
#endif

            //
            // put the context record into the cache
            //
            memcpy( &ContextCache[sc.Processor].Context,
                    &sc.Context,
                    sizeof(sc.Context)
                  );

#if defined(TARGET_MIPS)
            if ((ContextCache[sc.Processor].Context.ContextFlags &
                        CONTEXT_EXTENDED_INTEGER) == CONTEXT_EXTENDED_INTEGER) {

                MipsContextSize = Ctx64Bit;
            } else {
                MipsContextSize = Ctx32Bit;
                CoerceContext32To64(&ContextCache[sc.Processor].Context);
            }
#endif  // MIPS
        }

        ContextCache[sc.Processor].fContextDirty = FALSE;
        ContextCache[sc.Processor].fContextStale = FALSE;

        if (sc.NumberProcessors > 1 && CacheProcessors == 1) {
            InitializeExtraProcessors();
        }

        if (DmKdState == S_REBOOTED) {

            DmKdState = S_INITIALIZED;

            //
            // get the version/info packet from the target
            //
            if (fFirstSc) {
                GetVersionInfo( (DWORD)sc.u.LoadSymbols.BaseOfDll );
            } else {
                GetVersionInfo( 0 );
            }

            InitialBreak = (BOOL) KdOptions[KDO_INITIALBP].value;

        } else
        if (DmKdState == S_UNINITIALIZED) {

            DMPrintShellMsg( "Kernel Debugger connection established on com%d @ %d baud\n",
                             KdOptions[KDO_PORT].value,
                             KdOptions[KDO_BAUDRATE].value
                           );

            //
            // we're now initialized
            //
            DmKdState = S_INITIALIZED;

            //
            // get the version/info packet from the target
            //
            if (fFirstSc) {
                GetVersionInfo( (DWORD)sc.u.LoadSymbols.BaseOfDll );
            } else {
                GetVersionInfo( 0 );
            }

            //
            // clean out the kernel's bp list
            //
            ClearBps();

            if (sc.NewState != DbgKdLoadSymbolsStateChange) {
                //
                // generate a mod load for the kernel/osloader
                //
                GenerateKernelModLoad( hprc, lpProgName );
            }

            DisableEmCache();
        }

        if (fDisconnected) {
            if (sc.NewState == DbgKdLoadSymbolsStateChange) {

                //
                // we can process these debug events very carefully
                // while disconnected from the shell.  the only requirement
                // is that the dm doesn't call NotifyEM while disconnected.
                //

            } else {

                WaitForSingleObject( hEventRemoteQuit, INFINITE );
                ResetEvent( hEventRemoteQuit );

            }
        }

        if (sc.NewState == DbgKdExceptionStateChange) {
            DmKdInitVirtualCacheEntry( (ULONG)sc.ProgramCounter,
                                       (ULONG)sc.ControlReport.InstructionCount,
                                       sc.ControlReport.InstructionStream,
                                       TRUE
                                     );

            de.dwDebugEventCode = EXCEPTION_DEBUG_EVENT;
            de.dwProcessId = KD_PROCESSID;
            de.dwThreadId  = KD_THREADID;
            de.u.Exception.ExceptionRecord = sc.u.Exception.ExceptionRecord;
            de.u.Exception.dwFirstChance = sc.u.Exception.FirstChance;

            //
            // HACK-HACK: this is here to wrongly handle the case where
            // the kernel delivers an exception during initialization
            // that is NOT a breakpoint exception.
            //
            if (DmKdState != S_READY) {
                de.u.Exception.ExceptionRecord.ExceptionCode = EXCEPTION_BREAKPOINT;
            }

            if (fDisconnected) {
                ReConnectDebugger( &de, DmKdState == S_INITIALIZED );
            }

            ProcessDebugEvent( &de, &sc );

            if (DmKdState == S_INITIALIZED) {
                free( lpProgName );
                DmKdState = S_READY;
            }
        }
        else
        if (sc.NewState == DbgKdLoadSymbolsStateChange) {
            if (sc.u.LoadSymbols.UnloadSymbols) {
                if (sc.u.LoadSymbols.PathNameLength == 0 &&
                    sc.u.LoadSymbols.BaseOfDll == (PVOID)-1 &&
                    sc.u.LoadSymbols.ProcessId == 0
                   ) {
                    //
                    // the target system was just restarted
                    //
                    DMPrintShellMsg( "Target system restarted...\n" );
                    DmKdPurgeCachedVirtualMemory( TRUE );
                    UnloadAllModules();
                    ContinueTargetSystem( DBG_CONTINUE, NULL );
                    InitialBreak = (BOOL) KdOptions[KDO_INITIALBP].value;
                    KdResync = TRUE;
                    DmKdState = S_REBOOTED;
                    continue;
                }
                de.dwDebugEventCode      = UNLOAD_DLL_DEBUG_EVENT;
                de.dwProcessId           = KD_PROCESSID;
                de.dwThreadId            = KD_THREADID;
                de.u.UnloadDll.lpBaseOfDll = (LPVOID)sc.u.LoadSymbols.BaseOfDll;

                if (fDisconnected) {
                    ReConnectDebugger( &de, DmKdState == S_INITIALIZED );
                }

                ProcessDebugEvent( &de, &sc );
                ConsumeAllEvents();
                ContinueTargetSystem( DBG_CONTINUE, NULL );
                continue;
            } else {
                //
                // if the mod load is for the kernel image then we must
                // assume that the target system was rebooted while
                // the debugger was connected.  in this case we need to
                // unload all modules.  this will allow the mod loads that
                // are forthcoming to work correctly and cause the shell to
                // reinstanciate all of it's breakpoints.
                //
                if (_stricmp( buf, KERNEL_IMAGE_NAME ) == 0) {
                    UnloadAllModules();
                    DeleteAllBps();
                    ConsumeAllEvents();
                }

                de.dwDebugEventCode                 = LOAD_DLL_DEBUG_EVENT;
                de.dwProcessId                      = KD_PROCESSID;
                de.dwThreadId                       = KD_THREADID;
                de.u.LoadDll.hFile                  = (HANDLE)sc.u.LoadSymbols.CheckSum;
                de.u.LoadDll.lpBaseOfDll            = (LPVOID)sc.u.LoadSymbols.BaseOfDll;
                de.u.LoadDll.lpImageName            = buf;
                de.u.LoadDll.fUnicode               = FALSE;
                de.u.LoadDll.nDebugInfoSize         = 0;
                if (sc.u.LoadSymbols.SizeOfImage == 0) {
                    //
                    // this is likely a firmware image.  in such cases the boot
                    // loader on the target may not be able to deliver the size.
                    //
                    if (!ReadImageInfo(
                        buf,
                        NULL,
                        (LPSTR)KdOptions[KDO_SYMBOLPATH].value,
                        &ii )) {
                        //
                        // can't read the image correctly
                        //
                        DMPrintShellMsg( "Module load failed, missing size & image [%s]\n", buf );
                        ContinueTargetSystem( DBG_CONTINUE, NULL );
                        continue;
                    }
                    de.u.LoadDll.dwDebugInfoFileOffset  = ii.SizeOfImage;
                } else {
                    de.u.LoadDll.dwDebugInfoFileOffset  = sc.u.LoadSymbols.SizeOfImage;
                }

                if (fDisconnected) {
                    ReConnectDebugger( &de, DmKdState == S_INITIALIZED );
                }

                //
                // HACK ALERT
                //
                // this code is here to allow the presence of the
                // mirrored disk drivers in a system that has crashdump
                // enabled.  if the modload is for a driver and the
                // image name for that driver is alread present in the
                // dm's module table then we alias the driver.
                //
                _splitpath( buf, NULL, NULL, fname, ext );
                if (_stricmp( ext, ".sys" ) == 0) {
                    UnloadModule( (DWORD)sc.u.LoadSymbols.BaseOfDll, NULL );
                    for (i=0; i<(DWORD)hprc->cDllList; i++) {
                        if (hprc->rgDllList[i].fValidDll &&
                            _stricmp(hprc->rgDllList[i].szDllName,buf)==0) {
                            break;
                        }
                    }
                    if (i < (DWORD)hprc->cDllList) {
                        for (j=0; j<MAX_MODULEALIAS; j++) {
                            if (ModuleAlias[j].ModuleName[0] == 0) {
                                break;
                            }
                        }
                        if (j < MAX_MODULEALIAS) {
                            strcpy( ModuleAlias[j].Alias, buf );
                            ModuleAlias[j].ModuleName[0] = 'c';
                            _splitpath( buf, NULL, NULL, &ModuleAlias[j].ModuleName[1], NULL );
                            ModuleAlias[j].ModuleName[8] = 0;
                            ModuleAlias[j].Special = 2;     // One shot alias...
                        }
                    }
                } else {
                    UnloadModule( (DWORD)sc.u.LoadSymbols.BaseOfDll, buf );
                }

                ProcessDebugEvent( &de, &sc );
                ConsumeAllEvents();
                ContinueTargetSystem( DBG_CONTINUE, NULL );
                continue;
            }
        }

        if (DequeueAllEvents(FALSE,FALSE)) {
            continue;
        }

        //
        // this loop is executed while the target system is not running
        // the dm sits here and processes queue event and waits for a go
        //
        while (TRUE) {
            WaitForSingleObject( hEventContinue, 100 );
            ResetEvent( hEventContinue );

            if (WaitForSingleObject( hEventRemoteQuit, 0 ) == WAIT_OBJECT_0) {
                fDisconnected = TRUE;
                DmKdBreakIn = TRUE;
            }

            if (DmKdExit) {
                return 0;
            }
            if (DmKdBreakIn || KdResync) {
                break;
            }
            if (DequeueAllEvents(FALSE,FALSE)) {
                break;
            }
        }
    }

    return 0;
}


VOID
InitializeKiProcessor(
    VOID
    )
{
    if (!fCrashDump) {
        return;
    }

    //
    // get the address of the KiProcessorBlock
    //
    if (!KiProcessorBlockAddr) {
        DMPrintShellMsg( "Could not get address of KiProcessorBlock\n" );
    }

    //
    // read the contents of the KiProcessorBlock
    //
    DmpReadMemory( (PVOID)KiProcessorBlockAddr, &KiProcessors, sizeof(KiProcessors) );
}


DWORD
DmKdPollThreadCrash(
    LPSTR lpProgName
    )
{
    DWORD                       i;
    BOOL                        fFirstSc = FALSE;
    DEBUG_EVENT                 de;
    DWORD                       n;
    PEXCEPTION_RECORD           Exception;
    LIST_ENTRY                  List;
    PLIST_ENTRY                 Next;
    PLDR_DATA_TABLE_ENTRY       DataTable;
    LDR_DATA_TABLE_ENTRY        DataTableBuffer;
    INT                         CurrProcessor;
    HPRCX                       hprc;



    PollThreadId = GetCurrentThreadId();

    hprc = HPRCFromPID( KD_PROCESSID );

    //
    // initialize the queue variables
    //
    n = sizeof(cqueue) / sizeof(CQUEUE);
    for (i = 0; i < n-1; i++) {
        cqueue[i].next = &cqueue[i+1];
    }
    --n;
    cqueue[n].next = NULL;
    lpcqFree = &cqueue[0];
    lpcqFirst = NULL;
    lpcqLast = NULL;
    InitializeCriticalSection(&csContinueQueue);

    DmKdSetMaxCacheSize( KdOptions[KDO_CACHE].value );
    InitialBreak = FALSE;

    //
    // initialize for crash debugging
    //
    if (!DmpInitialize( (LPSTR)KdOptions[KDO_CRASHDUMP].value,
                         &DmpContext,
                         &Exception,
                         &DmpHeader
                       )) {
        DMPrintShellMsg( "Could not initialize crash dump file %s\n",
                         (LPSTR)KdOptions[KDO_CRASHDUMP].value );
        return 0;
    }

#if defined(TARGET_MIPS)
    if (DmpHeader->MajorVersion > 3) {
        MipsContextSize = Ctx64Bit;
    } else {
        MipsContextSize = Ctx32Bit;
        CoerceContext32To64(DmpContext);
    }
#endif  // MIPS

    memcpy( &sc.Context, DmpContext, sizeof(CONTEXT) );
    memcpy( &ContextCache[0].Context, DmpContext, sizeof(CONTEXT) );

    ContextCache[0].fContextDirty  = FALSE;
    ContextCache[0].fContextStale  = FALSE;

#if defined(TARGET_i386) || defined(TARGET_PPC)
    ContextCache[0].fSContextDirty = FALSE;
    ContextCache[0].fSContextStale = TRUE;
#endif

    sc.NewState                         = DbgKdExceptionStateChange;
    sc.u.Exception.ExceptionRecord      = *Exception;
    sc.u.Exception.FirstChance          = FALSE;
    //
    // For the createprocess and loader bp, use cpu 0
    //
    CurrProcessor                       = 0;
    sc.Processor                        = 0;
    sc.NumberProcessors                 = DmpHeader->NumberProcessors;
    sc.ProgramCounter                   = Exception->ExceptionAddress;
    sc.ControlReport.InstructionCount   = 0;

    vs.MajorVersion                     = (USHORT)DmpHeader->MajorVersion;
    vs.MinorVersion                     = (USHORT)DmpHeader->MinorVersion;
    vs.KernBase                         = 0;
    vs.PsLoadedModuleList               = (DWORD) DmpHeader->PsLoadedModuleList;

    if (DmpReadMemory( DmpHeader->PsLoadedModuleList, (PVOID)&List, sizeof(LIST_ENTRY) )) {
        Next = List.Flink;
        DataTable = CONTAINING_RECORD( Next, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks );
        if (DmpReadMemory( (PVOID)DataTable, (PVOID)&DataTableBuffer, sizeof(LDR_DATA_TABLE_ENTRY) )) {
            vs.KernBase = (DWORD) DataTableBuffer.DllBase;
        }
    } else {
        DMPrintShellMsg( "Could not get base of kernel 0x%08x\n",
                         DmpHeader->PsLoadedModuleList );
    }

#if defined(TARGET_i386)
    if ( DmpHeader->MachineImageType != IMAGE_FILE_MACHINE_I386)
#elif defined(TARGET_MIPS)
    if ((DmpHeader->MachineImageType != IMAGE_FILE_MACHINE_R4000) &&
        (DmpHeader->MachineImageType != IMAGE_FILE_MACHINE_R10000) )
#elif defined(TARGET_ALPHA)
    if ( DmpHeader->MachineImageType != IMAGE_FILE_MACHINE_ALPHA)
#elif defined(TARGET_PPC)
    if ( DmpHeader->MachineImageType != IMAGE_FILE_MACHINE_POWERPC)
#else
#pragma error( "unknown target machine" );
#endif
    {
        DMPrintShellMsg( "Dumpfile is of an unknown machine type\n" );
    }

    ApiIsAllowed = TRUE;

    //
    // simulate a create process debug event
    //
    de.dwDebugEventCode = CREATE_PROCESS_DEBUG_EVENT;
    de.dwProcessId = KD_PROCESSID;
    de.dwThreadId  = KD_THREADID;
    de.u.CreateProcessInfo.hFile = NULL;
    de.u.CreateProcessInfo.hProcess = NULL;
    de.u.CreateProcessInfo.hThread = NULL;
    de.u.CreateProcessInfo.lpBaseOfImage = 0;
    de.u.CreateProcessInfo.dwDebugInfoFileOffset = 0;
    de.u.CreateProcessInfo.nDebugInfoSize = 0;
    de.u.CreateProcessInfo.lpStartAddress = NULL;
    de.u.CreateProcessInfo.lpThreadLocalBase = NULL;
    de.u.CreateProcessInfo.lpImageName = lpProgName;
    de.u.CreateProcessInfo.fUnicode = 0;
    ProcessDebugEvent(&de, &sc);
    WaitForSingleObject(hEventContinue,INFINITE);
    ConsumeAllEvents();

    //
    // LoadDll needs this to load the right kernel symbols:
    //
    CacheProcessors = DmpHeader->NumberProcessors;

    //
    // generate a mod load for the kernel/osloader
    //

    GenerateKernelModLoad( hprc, lpProgName );

    CurrProcessor                       = DmpGetCurrentProcessor();
    if (CurrProcessor == -1) {
        sc.Processor                    = 0;
    } else {
        sc.Processor                    = (USHORT)CurrProcessor;
    }

    //
    // initialize the other processors
    //
    InitializeKiProcessor();
    if (DmpHeader->NumberProcessors > 1) {
        InitializeExtraProcessors();
    }

    //
    // simulate a loader breakpoint event
    //
    de.dwDebugEventCode = BREAKPOINT_DEBUG_EVENT;
    de.dwProcessId = KD_PROCESSID;
    de.dwThreadId  = KD_THREADID;
    de.u.Exception.dwFirstChance = TRUE;
    de.u.Exception.ExceptionRecord.ExceptionCode = EXCEPTION_BREAKPOINT;
    de.u.Exception.ExceptionRecord.ExceptionFlags = 0;
    de.u.Exception.ExceptionRecord.ExceptionRecord = NULL;
    de.u.Exception.ExceptionRecord.ExceptionAddress = 0;
    de.u.Exception.ExceptionRecord.NumberParameters = 0;
    ProcessDebugEvent( &de, &sc );
    ConsumeAllEvents();

    DMPrintShellMsg( "Kernel Debugger connection established for %s\n",
                     (LPSTR)KdOptions[KDO_CRASHDUMP].value
                   );

    //
    // get the version/info packet from the target
    //
    GetVersionInfo( (DWORD)sc.u.LoadSymbols.BaseOfDll );

    DMPrintShellMsg( "Bugcheck %08x : %08x %08x %08x %08x\n",
                     DmpHeader->BugCheckCode,
                     DmpHeader->BugCheckParameter1,
                     DmpHeader->BugCheckParameter2,
                     DmpHeader->BugCheckParameter3,
                     DmpHeader->BugCheckParameter4 );


    DisableEmCache();

    DmKdInitVirtualCacheEntry( (ULONG)sc.ProgramCounter,
                               (ULONG)sc.ControlReport.InstructionCount,
                               sc.ControlReport.InstructionStream,
                               TRUE
                             );

    de.dwDebugEventCode = EXCEPTION_DEBUG_EVENT;
    de.dwProcessId = KD_PROCESSID;
    de.dwThreadId  = KD_THREADID;
    de.u.Exception.ExceptionRecord = sc.u.Exception.ExceptionRecord;
    de.u.Exception.dwFirstChance = sc.u.Exception.FirstChance;

    ProcessDebugEvent( &de, &sc );

    free( lpProgName );

    while (TRUE) {
        DequeueAllEvents(FALSE,FALSE);
        Sleep( 1000 );
    }

    return 0;
}

BOOLEAN
DmKdConnectAndInitialize( LPSTR lpProgName )
{
    DWORD      dwThreadId;
    LPSTR      szProgName = malloc( MAX_PATH );


    //
    // bail out if we're already initialized
    //
    if (DmKdState != S_UNINITIALIZED) {
        return TRUE;
    }


    szProgName[0] = '\0';
    if (lpProgName) {
        strcpy( szProgName, lpProgName );
    }

    fCrashDump = (BOOL) (KdOptions[KDO_CRASHDUMP].value != 0);

    if (fCrashDump) {
        hThreadDmPoll = CreateThread( NULL,
                                      16000,
                                      (LPTHREAD_START_ROUTINE)DmKdPollThreadCrash,
                                      (LPVOID)szProgName,
                                      THREAD_SET_INFORMATION,
                                      (LPDWORD)&dwThreadId
                                    );
    } else {

        //
        // initialize the com port
        //

        if (!DmKdInitComPort( (BOOLEAN) KdOptions[KDO_USEMODEM].value )) {
            DMPrintShellMsg( "Could not initialize COM%d @ %d baud, error == 0x%x\n",
                             KdOptions[KDO_PORT].value,
                             KdOptions[KDO_BAUDRATE].value,
                             GetLastError()
                           );
            return FALSE;
        }

        hThreadDmPoll = CreateThread( NULL,
                                      16000,
                                      (LPTHREAD_START_ROUTINE)DmKdPollThread,
                                      (LPVOID)szProgName,
                                      THREAD_SET_INFORMATION,
                                      (LPDWORD)&dwThreadId
                                    );
    }


    if ( hThreadDmPoll == (HANDLE)NULL ) {
        return FALSE;
    }

    if (!SetThreadPriority(hThreadDmPoll, THREAD_PRIORITY_ABOVE_NORMAL)) {
        return FALSE;
    }

    KdResync = TRUE;
    return TRUE;
}

VOID
DmPollTerminate( VOID )
{
    extern HANDLE DmKdComPort;
    extern ULONG  MaxRetries;

    if (hThreadDmPoll) {
        DmKdExit = TRUE;
        WaitForSingleObject(hThreadDmPoll, INFINITE);

        DmKdState = S_UNINITIALIZED;
        DeleteCriticalSection(&csContinueQueue);
        ResetEvent( hEventContinue );
        if (fCrashDump) {
            DmpUnInitialize();
        } else {
            CloseHandle( DmKdComPort );
            MaxRetries = 5;
        }
        DmKdExit = FALSE;
    }

    return;
}

VOID
DisableEmCache( VOID )
{
    LPRTP       rtp;
    HTHDX       hthd;


    hthd = HTHDXFromPIDTID(1, 1);

    rtp = (LPRTP)malloc(sizeof(RTP)+sizeof(DWORD));

    rtp->hpid    = hthd->hprc->hpid;
    rtp->htid    = hthd->htid;
    rtp->dbc     = dbceEnableCache;
    rtp->cb      = sizeof(DWORD);

    *(LPDWORD)rtp->rgbVar = 1;

    DmTlFunc( tlfRequest, rtp->hpid, sizeof(RTP)+rtp->cb, (LONG)rtp );

    free( rtp );

    return;
}

DWORD
GetSymbolAddress( LPSTR sym )
{
    extern char abEMReplyBuf[];
    LPRTP       rtp;
    HTHDX       hthd;
    DWORD       offset;
    BOOL        fUseUnderBar = FALSE;


    __try {

try_underbar:
        hthd = HTHDXFromPIDTID(1, 1);

        rtp = (LPRTP)malloc(sizeof(RTP)+strlen(sym)+16);

        rtp->hpid    = hthd->hprc->hpid;
        rtp->htid    = hthd->htid;
        rtp->dbc     = dbceGetOffsetFromSymbol;
        rtp->cb      = strlen(sym) + (fUseUnderBar ? 2 : 1);

        if (fUseUnderBar) {
            ((LPSTR)rtp->rgbVar)[0] = '_';
            memcpy( (LPSTR)rtp->rgbVar+1, sym, rtp->cb-1 );
        } else {
            memcpy( rtp->rgbVar, sym, rtp->cb );
        }

        DmTlFunc( tlfRequest, rtp->hpid, sizeof(RTP)+rtp->cb, (LONG)rtp );

        free( rtp );

        offset = *(LPDWORD)abEMReplyBuf;
        if (!offset && !fUseUnderBar) {
            fUseUnderBar = TRUE;
            goto try_underbar;
        }

    } __except(EXCEPTION_EXECUTE_HANDLER) {

        offset = 0;

    }

    return offset;
}

BOOL
UnloadModule(
    DWORD   BaseOfDll,
    LPSTR   NameOfDll
    )
{
    HPRCX           hprc;
    HTHDX           hthd;
    DEBUG_EVENT     de;
    DWORD           i;
    BOOL            fUnloaded = FALSE;


    hprc = HPRCFromPID( KD_PROCESSID );
    hthd = HTHDXFromPIDTID( KD_PROCESSID, KD_THREADID );

    //
    // first lets look for the image by dll base
    //
    for (i=0; i<(DWORD)hprc->cDllList; i++) {
        if (hprc->rgDllList[i].fValidDll && hprc->rgDllList[i].offBaseOfImage == BaseOfDll) {
            de.dwDebugEventCode        = UNLOAD_DLL_DEBUG_EVENT;
            de.dwProcessId             = KD_PROCESSID;
            de.dwThreadId              = KD_THREADID;
            de.u.UnloadDll.lpBaseOfDll = (LPVOID)hprc->rgDllList[i].offBaseOfImage;
            NotifyEM( &de, hthd, 0, (LPVOID)0);
            DestroyDllLoadItem(&hprc->rgDllList[i]);
            fUnloaded = TRUE;
            break;
        }
    }

    //
    // now we look by dll name
    //
    if (NameOfDll) {
        for (i=0; i<(DWORD)hprc->cDllList; i++) {
            if (hprc->rgDllList[i].fValidDll &&
                _stricmp(hprc->rgDllList[i].szDllName,NameOfDll)==0) {

                de.dwDebugEventCode        = UNLOAD_DLL_DEBUG_EVENT;
                de.dwProcessId             = KD_PROCESSID;
                de.dwThreadId              = KD_THREADID;
                de.u.UnloadDll.lpBaseOfDll = (LPVOID)hprc->rgDllList[i].offBaseOfImage;
                NotifyEM( &de, hthd, 0, (LPVOID)0);
                DestroyDllLoadItem(&hprc->rgDllList[i]);
                fUnloaded = TRUE;
                break;

            }
        }
    }

    return fUnloaded;
}

VOID
UnloadAllModules(
    VOID
    )
{
    HPRCX           hprc;
    HTHDX           hthd;
    DEBUG_EVENT     de;
    DWORD           i;


    hprc = HPRCFromPID( KD_PROCESSID );
    hthd = HTHDXFromPIDTID( KD_PROCESSID, KD_THREADID );

    for (i=0; i<(DWORD)hprc->cDllList; i++) {
        if (hprc->rgDllList[i].fValidDll) {
            de.dwDebugEventCode        = UNLOAD_DLL_DEBUG_EVENT;
            de.dwProcessId             = KD_PROCESSID;
            de.dwThreadId              = KD_THREADID;
            de.u.UnloadDll.lpBaseOfDll = (LPVOID)hprc->rgDllList[i].offBaseOfImage;
            NotifyEM( &de, hthd, 0, (LPVOID)0);
            DestroyDllLoadItem(&hprc->rgDllList[i]);
        }
    }

    return;
}


BOOL
GenerateKernelModLoad(
    HPRCX hprc,
    LPSTR lpProgName
    )
{
    DEBUG_EVENT                 de;
    LIST_ENTRY                  List;
    PLDR_DATA_TABLE_ENTRY       DataTable;
    LDR_DATA_TABLE_ENTRY        DataTableBuffer;



    if (!DbgReadMemory( hprc, (PVOID)vs.PsLoadedModuleList, (PVOID)&List, sizeof(LIST_ENTRY), NULL)) {
        return FALSE;
    }

    DataTable = CONTAINING_RECORD( List.Flink,
                                   LDR_DATA_TABLE_ENTRY,
                                   InLoadOrderLinks
                                 );
    if (!DbgReadMemory( hprc, (PVOID)DataTable, (PVOID)&DataTableBuffer, sizeof(LDR_DATA_TABLE_ENTRY), NULL)) {
        return FALSE;
    }

    de.dwDebugEventCode                = LOAD_DLL_DEBUG_EVENT;
    de.dwProcessId                     = KD_PROCESSID;
    de.dwThreadId                      = KD_THREADID;
    de.u.LoadDll.hFile                 = (HANDLE)DataTableBuffer.CheckSum;
    de.u.LoadDll.lpBaseOfDll           = (LPVOID)vs.KernBase;
    de.u.LoadDll.lpImageName           = lpProgName;
    de.u.LoadDll.fUnicode              = FALSE;
    de.u.LoadDll.nDebugInfoSize        = 0;
    de.u.LoadDll.dwDebugInfoFileOffset = DataTableBuffer.SizeOfImage;

    ProcessDebugEvent( &de, &sc );
    ConsumeAllEvents();

    return TRUE;
}

VOID
GetKernelSymbolAddresses(
    VOID
    )
{
    DcbAddr = GetSymbolAddress( "IopDumpControlBlock" );
    MmLoadedUserImageList = GetSymbolAddress( "MmLoadedUserImageList" );
    KiProcessorBlockAddr = GetSymbolAddress( "KiProcessorBlock" );
#if defined(TARGET_ALPHA)
    KiPcrBaseAddress = GetSymbolAddress( "KiPcrBaseAddress" );
#endif
}

VOID
GetMachineType(
    LPPROCESSOR p
    )
{
#if defined(TARGET_i386)

    if (DmKdState != S_INITIALIZED) {
        p->Level = 3;
    } else {
        p->Level = sc.ProcessorLevel;
    }

    p->Type = mptix86;
    p->Endian = endLittle;

#elif defined(TARGET_PPC)

    if (DmKdState != S_INITIALIZED) {
        p->Level = 601;
    } else {
        p->Level = sc.ProcessorLevel + 600;
    }

    p->Type = mptmppc;
    p->Endian = endLittle;

#elif defined(TARGET_MIPS)

// BUGBUG handle R10000
    p->Level = 4000;
    p->Type = mptmips;
    p->Endian = endLittle;

#elif defined(TARGET_ALPHA)

    p->Type = mptdaxp;
    p->Endian = endLittle;
    p->Level = 21064;

#else
#pragma error( "unknown target machine" );
#endif

}

#if defined(TARGET_i386) || defined(TARGET_PPC)
BOOL
GetExtendedContext(
    HTHDX               hthd,
    PKSPECIAL_REGISTERS pksr
    )
{
    DWORD  cb;
    DWORD  Status;
    USHORT processor;


    IsApiAllowed();
    NoApiForCrashDump();

    if (!hthd) {
        return FALSE;
    }

    processor = (USHORT)(hthd->tid - 1);
    if (ContextCache[processor].fSContextStale) {
        if (!ReadControlSpace( processor,
                               (PVOID)sizeof(CONTEXT),
                               (PVOID)pksr,
                               sizeof(KSPECIAL_REGISTERS),
                               &cb
                             )) {
            return FALSE;
        }
        memcpy( &ContextCache[processor].sregs,
                pksr,
                sizeof(KSPECIAL_REGISTERS)
              );
        ContextCache[processor].fSContextStale = FALSE;
        ContextCache[processor].fSContextDirty = FALSE;
        return TRUE;
    } else {
        memcpy( pksr,
                &ContextCache[processor].sregs,
                sizeof(KSPECIAL_REGISTERS)
              );
        return TRUE;
    }

    return FALSE;
}

BOOL
SetExtendedContext(
    HTHDX               hthd,
    PKSPECIAL_REGISTERS pksr
    )
{
    DWORD  cb;
    DWORD  Status;
    USHORT processor;


    IsApiAllowed();
    NoApiForCrashDump();

    processor = (USHORT)(hthd->tid - 1);
    Status = DmKdWriteControlSpace( processor,
                                    (PVOID)sizeof(CONTEXT),
                                    (PVOID)pksr,
                                    sizeof(KSPECIAL_REGISTERS),
                                    &cb
                                  );

    if (Status || cb != sizeof(KSPECIAL_REGISTERS)) {
        return FALSE;
    }

    memcpy( &ContextCache[processor].sregs, pksr, sizeof(KSPECIAL_REGISTERS) );
    ContextCache[processor].fSContextStale = FALSE;
    ContextCache[processor].fSContextDirty = FALSE;
    return TRUE;
}
#endif // i386 || PPC



DWORD
ProcessTerminateProcessCmd(
    HPRCX hprc,
    HTHDX hthd,
    LPDBB lpdbb
    )
{
    extern ULONG      MaxRetries;
    BREAKPOINT        *pbpT;
    BREAKPOINT        *pbp;
    HTHDX             hthdT;


    DEBUG_PRINT_2("ProcessTerminateProcessCmd called hprc=0x%x, hthd=0x%x\n",
                  hprc, hthd);

    MaxRetries = 1;

    if (!ApiIsAllowed) {
        return TRUE;
    }

    if (hprc) {
        hprc->pstate |= ps_dead;
        hprc->dwExitCode = 0;
        ConsumeAllProcessEvents(hprc, TRUE);

        for (pbp = BPNextHprcPbp(hprc, NULL); pbp; pbp = pbpT) {
            pbpT = BPNextHprcPbp(hprc, pbp);
            RemoveBP(pbp);
        }

        for (hthdT = hprc->hthdChild; hthdT; hthdT = hthdT->nextSibling) {
            if ( !(hthdT->tstate & ts_dead) ) {
                hthdT->tstate |= ts_dead;
                hthdT->tstate &= ~ts_stopped;
            }
        }
    }

    return TRUE;
}


VOID
ProcessAllProgFreeCmd(
    HPRCX hprc,
    HTHDX hthd,
    LPDBB lpdbb
    )
{
    ProcessTerminateProcessCmd(hprc, hthd, lpdbb);
}



DWORD
ProcessAsyncGoCmd(
    HPRCX hprc,
    HTHDX hthd,
    LPDBB lpdbb
    )
{
    XOSD       xosd = xosdNone;

    DEBUG_PRINT("ProcessAsyncGoCmd called\n");

    hthd->tstate &= ~ts_frozen;
    Reply(0, &xosd, lpdbb->hpid);
    return(xosd);
}


VOID
ProcessAsyncStopCmd(
                    HPRCX       hprc,
                    HTHDX       hthd,
                    LPDBB       lpdbb
                    )

/*++

Routine Description:

    This function is called in response to a asynchronous stop request.
    In order to do this we will set breakpoints the current PC for
    every thread in the system and wait for the fireworks to start.

Arguments:

    hprc        - Supplies a process handle
    hthd        - Supplies a thread handle
    lpdbb       - Supplies the command information packet

Return Value:

    None.

--*/

{
    DmKdBreakIn = TRUE;
    LpDmMsg->xosdRet = xosdNone;
    Reply(0, LpDmMsg, lpdbb->hpid);
    return;
}                            /* ProcessAsyncStopCmd() */


VOID
ProcessDebugActiveCmd(
    HPRCX hprc,
    HTHDX hthd,
    LPDBB lpdbb
    )
{
    if (!DmKdConnectAndInitialize( KERNEL_IMAGE_NAME )) {
        LpDmMsg->xosdRet = xosdFileNotFound;
    } else {
        LpDmMsg->xosdRet = xosdNone;
    }

    if (fDisconnected) {
        DmKdBreakIn = TRUE;
        SetEvent( hEventRemoteQuit );
    }

    LpDmMsg->xosdRet = xosdNone;
    Reply(0, LpDmMsg, lpdbb->hpid);
}


VOID
ProcessQueryTlsBaseCmd(
    HPRCX    hprcx,
    HTHDX    hthdx,
    LPDBB    lpdbb
    )

/*++

Routine Description:

    This function is called in response to an EM request to get the base
    of the thread local storage for a given thread and DLL.

Arguments:

    hprcx       - Supplies a process handle

    hthdx       - Supplies a thread handle

    lpdbb       - Supplies the command information packet

Return Value:

    None.

--*/

{
    LpDmMsg->xosdRet = xosdUnknown;
    Reply( sizeof(ADDR), LpDmMsg, lpdbb->hpid );
    return;
}                               /* ProcessQueryTlsBaseCmd() */


VOID
ProcessQuerySelectorCmd(
    HPRCX   hprcx,
    HTHDX   hthdx,
    LPDBB   lpdbb
    )

/*++

Routine Description:

    This command is send from the EM to fill-in a LDT_ENTRY structure
    for a given selector.

Arguments:

    hprcx  - Supplies the handle to the process

    hthdx  - Supplies the handle to the thread and is optional

    lpdbb  - Supplies the pointer to the full query packet

Return Value:

    None.

--*/

{
    XOSD               xosd;

    xosd = xosdInvalidSelector;
    Reply( sizeof(xosd), &xosd, lpdbb->hpid);

    return;
}


VOID
ProcessReloadModulesCmd(
    HPRCX   hprc,
    HTHDX   hthd,
    LPDBB   lpdbb
    )

/*++

Routine Description:

    This command is send from the EM to cause all modules to be reloaded.

Arguments:

    hprcx  - Supplies the handle to the process
    hthdx  - Supplies the handle to the thread and is optional
    lpdbb  - Supplies the pointer to the full query packet

Return Value:

    None.

--*/

{
    XOSD      xosd;
    LPIOL     lpiol = (LPIOL) lpdbb->rgbVar;

    AddQueue( QT_RELOAD_MODULES,
              hprc->pid,
              hthd->tid,
              *((PULONG)lpiol->rgbVar),
              0
            );

    xosd = xosdNone;
    Reply( sizeof(xosd), &xosd, lpdbb->hpid);

    return;
}


VOID
ProcessVirtualQueryCmd(
    HPRCX hprc,
    LPDBB lpdbb
    )
/*++

Routine Description:


Arguments:


Return Value:


--*/
{
#define vaddr(va) ((hprc->fRomImage) ? d[iDll].offBaseOfImage+(va) : (va))

    ADDR                 addr;
    DWORD                cb;
    PDLLLOAD_ITEM        d = prcList->next->rgDllList;

    PMEMORY_BASIC_INFORMATION lpmbi = (PMEMORY_BASIC_INFORMATION)LpDmMsg->rgb;
    XOSD xosd = xosdNone;

    static int                    iDll = 0;
    static PIMAGE_SECTION_HEADER  s    = NULL;


    addr = *(LPADDR)(lpdbb->rgbVar);

    lpmbi->BaseAddress = (LPVOID)(addr.addr.off & (PAGE_SIZE - 1));
    lpmbi->RegionSize = PAGE_SIZE;

    // first guess
    lpmbi->AllocationBase = lpmbi->BaseAddress;

    lpmbi->Protect = PAGE_READWRITE;
    lpmbi->AllocationProtect = PAGE_READWRITE;
    lpmbi->State = MEM_COMMIT;
    lpmbi->Type = MEM_PRIVATE;

    //
    // the following code is necessary to determine if the requested
    // base address is in a page that contains code.  if the base address
    // meets these conditions then reply that it is executable.
    //

    if ( !s ||
         addr.addr.off < vaddr(s->VirtualAddress) ||
         addr.addr.off >= vaddr(s->VirtualAddress+s->SizeOfRawData) ) {

        for (iDll=0; iDll<prcList->next->cDllList; iDll++) {

            if (addr.addr.off >= d[iDll].offBaseOfImage &&
                addr.addr.off < d[iDll].offBaseOfImage+d[iDll].cbImage) {

                s = d[iDll].Sections;
                cb = d[iDll].NumberOfSections;
                while (cb) {
                    if (addr.addr.off >= vaddr(s->VirtualAddress) &&
                        addr.addr.off < vaddr(s->VirtualAddress+s->SizeOfRawData) )
                    {
                        break;
                    }
                    else {
                        s++;
                        cb--;
                    }
                }
                if (cb == 0) {
                    s = NULL;
                }
                break;
            }
        }
    }

    if (s) {
        lpmbi->BaseAddress = (LPVOID)(vaddr(s->VirtualAddress));
        lpmbi->RegionSize = vaddr(s->VirtualAddress);

        switch ( s->Characteristics & (IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_CNT_CODE |
                                  IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE) ) {

          case  IMAGE_SCN_MEM_EXECUTE:
            lpmbi->Protect =
            lpmbi->AllocationProtect = PAGE_EXECUTE;
            break;

          case  IMAGE_SCN_CNT_CODE:
          case  (IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_CODE):
            lpmbi->Protect =
            lpmbi->AllocationProtect = PAGE_EXECUTE_READ;
            break;

          case  (IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ |
                                              IMAGE_SCN_MEM_WRITE):
            lpmbi->Protect =
            lpmbi->AllocationProtect = PAGE_EXECUTE_READWRITE;
            break;

             // This one probably never happens
          case  (IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_WRITE):
            lpmbi->Protect =
            lpmbi->AllocationProtect = PAGE_EXECUTE_READWRITE;
            break;

          case  IMAGE_SCN_MEM_READ:
            lpmbi->Protect =
            lpmbi->AllocationProtect = PAGE_READONLY;
            break;

          case  (IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE):
            lpmbi->Protect =
            lpmbi->AllocationProtect = PAGE_READWRITE;
            break;

             // This one probably never happens
          case IMAGE_SCN_MEM_WRITE:
            lpmbi->Protect =
            lpmbi->AllocationProtect = PAGE_READWRITE;
            break;

          case 0:
            lpmbi->Protect =
            lpmbi->AllocationProtect = PAGE_NOACCESS;
            break;

        }
    }

    LpDmMsg->xosdRet = xosd;
    Reply( sizeof(MEMORY_BASIC_INFORMATION), LpDmMsg, lpdbb->hpid );

    return;
}

VOID
ProcessGetDmInfoCmd(
    HPRCX hprc,
    LPDBB lpdbb,
    DWORD cb
    )
{
    extern DBGKD_GET_VERSION vs;
    LPDMINFO lpi = (LPDMINFO)LpDmMsg->rgb;

    LpDmMsg->xosdRet = xosdNone;

    lpi->fAsync = 0;
    lpi->fHasThreads = 1;
    lpi->fReturnStep = 0;
    //lpi->fRemote = ???
    lpi->fAsyncStop = 1;
    lpi->fAlwaysFlat = 1;
    lpi->fHasReload = 1;

#ifdef HAS_DEBUG_REGS
    lpi->cbSpecialRegs = sizeof(KSPECIAL_REGISTERS);
#else
    lpi->cbSpecialRegs = 0;
#endif

    lpi->MajorVersion = vs.MajorVersion;
    lpi->MinorVersion = vs.MinorVersion;

    lpi->Breakpoints = bptsExec |
                       bptsDataC |
                       bptsDataW |
                       bptsDataR |
                       bptsDataExec;

    GetMachineType(&lpi->Processor);

    //
    // hack so that TL can call tlfGetVersion before
    // reply buffer is initialized.
    //
    if ( cb >= (sizeof(DBB) + sizeof(DMINFO)) ) {
        memcpy(lpdbb->rgbVar, lpi, sizeof(DMINFO));
    }

    Reply( sizeof(DMINFO), LpDmMsg, lpdbb->hpid );
}

#ifdef HAS_DEBUG_REGS
VOID
ProcessGetExtendedContextCmd(
    HPRCX hprc,
    HTHDX hthd,
    LPDBB lpdbb
    )
{
    PKSPECIAL_REGISTERS pksr = (PKSPECIAL_REGISTERS)LpDmMsg->rgb;


    if (GetExtendedContext( hthd, pksr )) {
        LpDmMsg->xosdRet = xosdUnknown;
    } else {
        LpDmMsg->xosdRet = xosdNone;
    }

    Reply(sizeof(KSPECIAL_REGISTERS), LpDmMsg, lpdbb->hpid);
}

void
ProcessSetExtendedContextCmd(
    HPRCX hprc,
    HTHDX hthd,
    LPDBB lpdbb
    )
{
    PKSPECIAL_REGISTERS pksr = (PKSPECIAL_REGISTERS)lpdbb->rgbVar;


    if (SetExtendedContext( hthd, pksr )) {
        LpDmMsg->xosdRet = xosdUnknown;
    } else {
        LpDmMsg->xosdRet = xosdNone;
    }

    Reply(0, LpDmMsg, lpdbb->hpid);
}
#endif  // HAS_DEBUG_REGS

void
ProcessGetSectionsCmd(
    HPRCX hprc,
    HTHDX hthd,
    LPDBB lpdbb
    )
{
    DWORD                       dwBaseOfDll = *((LPDWORD) lpdbb->rgbVar);
    LPOBJD                      rgobjd = (LPOBJD) LpDmMsg->rgb;
    IMAGE_DOS_HEADER            dh;
    IMAGE_NT_HEADERS            nh;
    PIMAGE_SECTION_HEADER       sec;
    IMAGE_ROM_OPTIONAL_HEADER   rom;
    DWORD                       fpos;
    DWORD                       iobj;
    DWORD                       offset;
    DWORD                       cbObject;
    DWORD                       iDll;
    DWORD                       sig;
    IMAGEINFO                   ii;


    //
    // find the module
    //
    for (iDll=0; iDll<(DWORD)hprc->cDllList; iDll++) {
        if (hprc->rgDllList[iDll].offBaseOfImage == dwBaseOfDll) {

            if (hprc->rgDllList[iDll].sec) {

                sec = hprc->rgDllList[iDll].sec;
                nh.FileHeader.NumberOfSections =
                                (USHORT)hprc->rgDllList[iDll].NumberOfSections;

            } else {
                fpos = dwBaseOfDll;

                if (!DbgReadMemory( hprc, (LPVOID)fpos, &dh, sizeof(IMAGE_DOS_HEADER), NULL )) {
                    break;
                }

                if (dh.e_magic == IMAGE_DOS_SIGNATURE) {
                    fpos += dh.e_lfanew;
                } else {
                    fpos = dwBaseOfDll;
                }

                if (!DbgReadMemory( hprc, (LPVOID)fpos, &sig, sizeof(sig), NULL )) {
                    break;
                }

                if (sig != IMAGE_NT_SIGNATURE) {
                    if (!DbgReadMemory( hprc, (LPVOID)fpos, &nh.FileHeader, sizeof(IMAGE_FILE_HEADER), NULL )) {
                        break;
                    }
                    fpos += sizeof(IMAGE_FILE_HEADER);
                    if (nh.FileHeader.SizeOfOptionalHeader == IMAGE_SIZEOF_ROM_OPTIONAL_HEADER) {
                        if (!DbgReadMemory( hprc, (LPVOID)fpos, &rom, sizeof(rom), NULL )) {
                            break;
                        }
                        ZeroMemory( &nh.OptionalHeader, sizeof(nh.OptionalHeader) );
                        nh.OptionalHeader.SizeOfImage      = rom.SizeOfCode;
                        nh.OptionalHeader.ImageBase        = rom.BaseOfCode;
                    } else {
                        //
                        // maybe its a firmware image?
                        //
                        if (! ReadImageInfo(
                            hprc->rgDllList[iDll].szDllName,
                            NULL,
                            (LPSTR)KdOptions[KDO_SYMBOLPATH].value,
                            &ii )) {
                            //
                            // can't read the image correctly
                            //
                            LpDmMsg->xosdRet = xosdUnknown;
                            Reply(0, LpDmMsg, lpdbb->hpid);
                            return;
                        }
                        sec = ii.Sections;
                        nh.FileHeader.NumberOfSections = (USHORT)ii.NumberOfSections;
                        nh.FileHeader.SizeOfOptionalHeader = IMAGE_SIZEOF_ROM_OPTIONAL_HEADER;
                    }
                } else {
                    if (!DbgReadMemory( hprc, (LPVOID)fpos, &nh, sizeof(IMAGE_NT_HEADERS), NULL )) {
                        break;
                    }

                    fpos += sizeof(IMAGE_NT_HEADERS);

                    if (nh.Signature != IMAGE_NT_SIGNATURE) {
                        break;
                    }

                    if (hprc->rgDllList[iDll].TimeStamp == 0) {
                        hprc->rgDllList[iDll].TimeStamp = nh.FileHeader.TimeDateStamp;
                    }

                    if (hprc->rgDllList[iDll].CheckSum == 0) {
                        hprc->rgDllList[iDll].CheckSum = nh.OptionalHeader.CheckSum;
                    }

                    sec = malloc( nh.FileHeader.NumberOfSections * IMAGE_SIZEOF_SECTION_HEADER );
                    if (!sec) {
                        break;
                    }

                    DbgReadMemory( hprc, (LPVOID)fpos, sec, nh.FileHeader.NumberOfSections * IMAGE_SIZEOF_SECTION_HEADER, NULL );
                }
            }

            if (hprc->rgDllList[iDll].Sections == NULL) {
                hprc->rgDllList[iDll].Sections = sec;
                hprc->rgDllList[iDll].NumberOfSections =
                                                nh.FileHeader.NumberOfSections;

                if (nh.FileHeader.SizeOfOptionalHeader !=
                                            IMAGE_SIZEOF_ROM_OPTIONAL_HEADER) {
                    for (iobj=0; iobj<nh.FileHeader.NumberOfSections; iobj++) {
                        hprc->rgDllList[iDll].Sections[iobj].VirtualAddress +=
                                                            (DWORD)dwBaseOfDll;
                    }
                }
            }

            *((LPDWORD)LpDmMsg->rgb) = nh.FileHeader.NumberOfSections;
            rgobjd = (LPOBJD) (LpDmMsg->rgb + sizeof(DWORD));
            //
            //  Set up the descriptors for each of the section headers
            //  so that the EM can map between section numbers and flat
            //  addresses.
            //
            for (iobj=0; iobj<nh.FileHeader.NumberOfSections; iobj++) {
                offset = hprc->rgDllList[iDll].Sections[iobj].VirtualAddress;
                cbObject =
                         hprc->rgDllList[iDll].Sections[iobj].Misc.VirtualSize;
                if (cbObject == 0) {
                    cbObject =
                            hprc->rgDllList[iDll].Sections[iobj].SizeOfRawData;
                }
                rgobjd[iobj].offset = offset;
                rgobjd[iobj].cb = cbObject;
                rgobjd[iobj].wPad = 1;
#ifdef TARGET_i386
                if (IMAGE_SCN_CNT_CODE &
                       hprc->rgDllList[iDll].Sections[iobj].Characteristics) {
                    rgobjd[iobj].wSel = (WORD) hprc->rgDllList[iDll].SegCs;
                } else {
                    rgobjd[iobj].wSel = (WORD) hprc->rgDllList[iDll].SegDs;
                }
#else
                rgobjd[iobj].wSel = 0;
#endif
            }

            LpDmMsg->xosdRet = xosdNone;
            Reply( sizeof(DWORD) +
                       (hprc->rgDllList[iDll].NumberOfSections * sizeof(OBJD)),
                   LpDmMsg,
                   lpdbb->hpid);

            return;
        }
    }


    LpDmMsg->xosdRet = xosdUnknown;
    Reply(0, LpDmMsg, lpdbb->hpid);
}



VOID
ProcessIoctlGenericCmd(
    HPRCX   hprc,
    HTHDX   hthd,
    LPDBB   lpdbb
    )
{
    static USHORT      Processor = (USHORT)-1;
    LPIOL              lpiol  = (LPIOL)lpdbb->rgbVar;
    PIOCTLGENERIC      pig    = (PIOCTLGENERIC)lpiol->rgbVar;
    PPROCESSORINFO     pi;
    PREADCONTROLSPACE  prc;
    PIOSPACE           pis;
    PIOSPACE_EX        pisex;
    PPHYSICAL          phy;
    DWORD              len;
    PKDHELP            KdHelp;

    static ULONG SavedThread;


    if (!ApiIsAllowed) {
        LpDmMsg->xosdRet = xosdUnknown;
        Reply( sizeof(IOCTLGENERIC)+pig->length, LpDmMsg, lpdbb->hpid );
        return;
    }

    switch( pig->ioctlSubType ) {
        case IG_READ_CONTROL_SPACE:
            prc = (PREADCONTROLSPACE) pig->data;
            if ((SHORT)prc->Processor == -1) {
                if (Processor == (USHORT)-1) {
                    prc->Processor = sc.Processor;
                } else {
                    prc->Processor = Processor;
                }
            }
            if (!ReadControlSpace( (USHORT)prc->Processor,
                                   (PVOID)prc->Address,
                                   (PVOID)prc->Buf,
                                   prc->BufLen,
                                   &len
                                 )) {
                LpDmMsg->xosdRet = xosdUnknown;
                Reply(0, LpDmMsg, lpdbb->hpid);
            }
            prc->BufLen = len;
            break;

        case IG_WRITE_CONTROL_SPACE:
            Reply(0, LpDmMsg, lpdbb->hpid);
            return;

        case IG_READ_IO_SPACE:
            pis = (PIOSPACE) pig->data;
            if (DmKdReadIoSpace( (PVOID)pis->Address,
                             &pis->Data, pis->Length ) != STATUS_SUCCESS) {
                pis->Length = 0;
            }
            break;

        case IG_WRITE_IO_SPACE:
            pis = (PIOSPACE) pig->data;
            if (DmKdWriteIoSpace( (PVOID)pis->Address,
                             pis->Data, pis->Length ) != STATUS_SUCCESS) {
                pis->Length = 0;
            }
            break;

        case IG_READ_IO_SPACE_EX:
            pisex = (PIOSPACE_EX) pig->data;
            if (DmKdReadIoSpaceEx(
                             (PVOID)pisex->Address,
                             &pisex->Data,
                             pisex->Length,
                             pisex->InterfaceType,
                             pisex->BusNumber,
                             pisex->AddressSpace
                             ) != STATUS_SUCCESS) {
                pisex->Length = 0;
            }
            break;

        case IG_WRITE_IO_SPACE_EX:
            pisex = (PIOSPACE_EX) pig->data;
            if (DmKdWriteIoSpaceEx(
                             (PVOID)pisex->Address,
                             pisex->Data,
                             pisex->Length,
                             pisex->InterfaceType,
                             pisex->BusNumber,
                             pisex->AddressSpace
                             ) != STATUS_SUCCESS) {
                pisex->Length = 0;
            }
            break;

        case IG_READ_PHYSICAL:
            phy = (PPHYSICAL) pig->data;
            if (DmKdReadPhysicalMemory( phy->Address, phy->Buf, phy->BufLen, &len )) {
                phy->BufLen = 0;
            }
            break;

        case IG_WRITE_PHYSICAL:
            phy = (PPHYSICAL) pig->data;
            if (DmKdWritePhysicalMemory( phy->Address, phy->Buf, phy->BufLen, &len )) {
                phy->BufLen = 0;
            }
            break;

        case IG_DM_PARAMS:
            ParseDmParams( (LPSTR)pig->data );
            Reply(0, LpDmMsg, lpdbb->hpid);
            return;

        case IG_KD_CONTEXT:
            pi = (PPROCESSORINFO) pig->data;
            pi->Processor = sc.Processor;
            pi->NumberProcessors = (USHORT)sc.NumberProcessors;
            break;

        case IG_RELOAD:
            AddQueue( QT_RELOAD_MODULES,
                      0,
                      0,
                      (DWORD)pig->data,
                      strlen((LPSTR)pig->data)+1 );
            break;

        case IG_PAGEIN:
            if (DmKdPageIn( ((PULONG)pig->data)[0] ) == STATUS_SUCCESS) {
                LpDmMsg->xosdRet = xosdNone;
            } else {
                LpDmMsg->xosdRet = xosdUnknown;
            }
            break;

        case IG_CHANGE_PROC:
            Processor = (USHORT)((PULONG)pig->data)[0];
            break;

        case IG_KSTACK_HELP:
            KdHelp = (PKDHELP)pig->data;
            KdHelp->Thread = SavedThread? SavedThread : (DWORD)sc.Thread;
            SavedThread = 0;
            KdHelp->KiCallUserMode = vs.KiCallUserMode;
            KdHelp->ThCallbackStack = vs.ThCallbackStack;
            KdHelp->NextCallback = vs.NextCallback;
            KdHelp->FramePointer = vs.FramePointer;
            KdHelp->KeUserCallbackDispatcher = vs.KeUserCallbackDispatcher;
            break;

        case IG_SET_THREAD:
            memcpy(&SavedThread, pig->data, sizeof(ULONG));
            break;

        default:
            LpDmMsg->xosdRet = xosdUnknown;
            Reply(0, LpDmMsg, lpdbb->hpid);
            return;
    }

    len = sizeof(IOCTLGENERIC) + pig->length;
    memcpy( LpDmMsg->rgb, pig, len );
    LpDmMsg->xosdRet = xosdNone;
    Reply( sizeof(IOCTLGENERIC)+pig->length, LpDmMsg, lpdbb->hpid );
}


VOID
ProcessIoctlCustomCmd(
    HPRCX   hprc,
    HTHDX   hthd,
    LPDBB   lpdbb
    )
{
    LPIOL   lpiol  = (LPIOL)lpdbb->rgbVar;
    LPSTR   p      = lpiol->rgbVar;


    LpDmMsg->xosdRet = xosdUnsupported;

    //
    // parse the command
    //
    while (*p && !isspace(*p++));
    if (*p) {
        *(p-1) = '\0';
    }

    //
    // process the command
    //
    if (_stricmp( lpiol->rgbVar, "resync" ) == 0) {
        DMPrintShellMsg( "Host and target systems resynchronizing...\n" );
        KdResync = TRUE;
        LpDmMsg->xosdRet = xosdNone;
    } else
    if (_stricmp( lpiol->rgbVar, "cache" ) == 0) {
        ProcessCacheCmd(p);
        LpDmMsg->xosdRet = xosdNone;
    } else
    if (_stricmp( lpiol->rgbVar, "reboot" ) == 0) {
        if (ApiIsAllowed) {
            AddQueue( QT_REBOOT, 0, 0, 0, 0 );
            LpDmMsg->xosdRet = xosdNone;
        } else {
            LpDmMsg->xosdRet = xosdUnknown;
        }
    } else
    if (_stricmp( lpiol->rgbVar, "crash" ) == 0) {
        if (ApiIsAllowed) {
            AddQueue( QT_CRASH, 0, 0, CRASH_BUGCHECK_CODE, 0 );
            LpDmMsg->xosdRet = xosdNone;
        } else {
            LpDmMsg->xosdRet = xosdUnknown;
        }
    } else
    if ( !_stricmp(lpiol->rgbVar, "FastStep") ) {
        fSmartRangeStep = TRUE;
        LpDmMsg->xosdRet = xosdNone;
    } else
    if ( !_stricmp(lpiol->rgbVar, "SlowStep") ) {
        fSmartRangeStep = FALSE;
        LpDmMsg->xosdRet = xosdNone;
    } else
    if ( !_stricmp(lpiol->rgbVar, "trace") ) {
        fPacketTrace = !fPacketTrace;
        LpDmMsg->xosdRet = xosdNone;
    }

    //
    // send back our response
    //
    Reply(0, LpDmMsg, lpdbb->hpid);
}