首页
社区
课程
招聘
删除
发表于: 2024-3-19 19:45 4698

删除

2024-3-19 19:45
4698
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
/*++
 
Copyright (c) Microsoft Corporation. All rights reserved.
 
You may only use this code if you agree to the terms of the Windows Research Kernel Source Code License agreement (see License.txt).
If you do not agree to the terms, do not use the code.
 
 
Module Name:
 
    dbgkobj.c
 
Abstract:
 
    This module houses routines to handle the debug object
 
--*/
 
#include "dbgkp.h"
 
#pragma hdrstop
 
#ifdef ALLOC_PRAGMA
#pragma alloc_text(INIT, DbgkInitialize)
#pragma alloc_text(PAGE, NtCreateDebugObject)
#pragma alloc_text(PAGE, NtDebugActiveProcess)
#pragma alloc_text(PAGE, NtRemoveProcessDebug)
#pragma alloc_text(PAGE, NtWaitForDebugEvent)
#pragma alloc_text(PAGE, NtDebugContinue)
#pragma alloc_text(PAGE, NtSetInformationDebugObject)
#pragma alloc_text(PAGE, DbgkpDeleteObject)
#pragma alloc_text(PAGE, DbgkpCloseObject)
#pragma alloc_text(PAGE, DbgkCopyProcessDebugPort)
#pragma alloc_text(PAGE, DbgkOpenProcessDebugPort)
#pragma alloc_text(PAGE, DbgkpSetProcessDebugObject)
#pragma alloc_text(PAGE, DbgkpQueueMessage)
#pragma alloc_text(PAGE, DbgkpOpenHandles)
#pragma alloc_text(PAGE, DbgkClearProcessDebugObject)
#pragma alloc_text(PAGE, DbgkpConvertKernelToUserStateChange)
#pragma alloc_text(PAGE, DbgkpMarkProcessPeb)
#pragma alloc_text(PAGE, DbgkpFreeDebugEvent)
#pragma alloc_text(PAGE, DbgkpPostFakeProcessCreateMessages)
#pragma alloc_text(PAGE, DbgkpPostFakeModuleMessages)
#pragma alloc_text(PAGE, DbgkpPostFakeThreadMessages)
#pragma alloc_text(PAGE, DbgkpWakeTarget)
#pragma alloc_text(PAGE, DbgkpPostAdditionalThreadMessages)
#endif
 
//
// Non-pageable data
//
 
//
// This mutex protects the debug port object of processes.
//
FAST_MUTEX DbgkpProcessDebugPortMutex;
 
//
// Pageable data
//
 
//#ifdef ALLOC_PRAGMA
//#pragma data_seg("PAGEDATA")
//#endif
 
POBJECT_TYPE DbgkDebugObjectType = NULL;
 
 
//#ifdef ALLOC_PRAGMA
//#pragma data_seg()
//#endif
 
NTSTATUS
DbgkInitialize (
    VOID
    )
/*++
 
Routine Description:
 
    Initialize the debug system
 
Arguments:
 
    None
 
Return Value:
 
    NTSTATUS - Status of operation
 
--*/
{
    NTSTATUS Status;
    UNICODE_STRING Name;
    OBJECT_TYPE_INITIALIZER oti = {0};
    GENERIC_MAPPING GenericMapping = {STANDARD_RIGHTS_READ | DEBUG_READ_EVENT,
                                      STANDARD_RIGHTS_WRITE | DEBUG_PROCESS_ASSIGN,
                                      STANDARD_RIGHTS_EXECUTE | SYNCHRONIZE,
                                      DEBUG_ALL_ACCESS};
 
 
    PAGED_CODE ();
 
    ExInitializeFastMutex (&DbgkpProcessDebugPortMutex);
 
    RtlInitUnicodeString (&Name, L"DebugObject");
 
    oti.Length                    = sizeof (oti);
    oti.SecurityRequired          = TRUE;
    oti.InvalidAttributes         = 0;
    oti.PoolType                  = NonPagedPool;
    oti.DeleteProcedure           = DbgkpDeleteObject;
    oti.CloseProcedure            = DbgkpCloseObject;
    oti.ValidAccessMask           = DEBUG_ALL_ACCESS;
    oti.GenericMapping            = GenericMapping;
    oti.DefaultPagedPoolCharge    = 0;
    oti.DefaultNonPagedPoolCharge = 0;
 
    Status = ObCreateObjectType (&Name, &oti, NULL, &DbgkDebugObjectType);
    if (!NT_SUCCESS (Status)) {
        return Status;
    }
    return Status;
}
 
VOID
DbgkpDeleteObject (
    IN  PVOID   Object
    )
/*++
 
Routine Description:
 
    Called by the object manager when the last reference to the object goes away.
 
Arguments:
 
    Object - Debug object being deleted
 
Return Value:
 
    None.
 
--*/
{
#if DBG
    PDEBUG_OBJECT DebugObject;
#endif
 
    PAGED_CODE();
 
#if DBG
    DebugObject = Object;
 
    ASSERT (IsListEmpty (&DebugObject->EventList));
#else
    UNREFERENCED_PARAMETER(Object);
#endif
}
 
VOID
DbgkpMarkProcessPeb (
    PEPROCESS Process
    )
/*++
 
Routine Description:
 
    This routine writes the debug variable in the PEB
 
Arguments:
 
    Process - Process that needs its PEB modified
 
Return Value:
 
    None.
 
--*/
{
    KAPC_STATE ApcState;
 
    PAGED_CODE ();
 
    //
    // Acquire process rundown protection as we are about to look at the processes address space
    //
    if (ExAcquireRundownProtection (&Process->RundownProtect)) {
 
        if (Process->Peb != NULL) {
            KeStackAttachProcess(&Process->Pcb, &ApcState);
 
 
            ExAcquireFastMutex (&DbgkpProcessDebugPortMutex);
 
            try {
                Process->Peb->BeingDebugged = (BOOLEAN)(Process->DebugPort != NULL ? TRUE : FALSE);
#if defined(_WIN64)
                if (Process->Wow64Process != NULL) {
                    PPEB32 Peb32 = (PPEB32)Process->Wow64Process->Wow64;
                    if (Peb32 != NULL) {
                        Peb32->BeingDebugged = Process->Peb->BeingDebugged;
                    }
                }
#endif
            } except (EXCEPTION_EXECUTE_HANDLER) {
            }
            ExReleaseFastMutex (&DbgkpProcessDebugPortMutex);
 
            KeUnstackDetachProcess(&ApcState);
 
        }
 
        ExReleaseRundownProtection (&Process->RundownProtect);
    }
}
 
VOID
DbgkpWakeTarget (
    IN PDEBUG_EVENT DebugEvent
    )
{
    PETHREAD Thread;
 
    Thread = DebugEvent->Thread;
 
    if ((DebugEvent->Flags&DEBUG_EVENT_SUSPEND) != 0) {
        PsResumeThread (DebugEvent->Thread, NULL);
    }
 
    if (DebugEvent->Flags&DEBUG_EVENT_RELEASE) {
        ExReleaseRundownProtection (&Thread->RundownProtect);
    }
 
    //
    // If we have an actual thread waiting then wake it up else free the memory.
    //
    if ((DebugEvent->Flags&DEBUG_EVENT_NOWAIT) == 0) {
        KeSetEvent (&DebugEvent->ContinueEvent, 0, FALSE); // Wake up waiting process
    } else {
        DbgkpFreeDebugEvent (DebugEvent);
    }
}
 
VOID
DbgkpCloseObject (
    IN PEPROCESS Process,
    IN PVOID Object,
    IN ACCESS_MASK GrantedAccess,
    IN ULONG_PTR ProcessHandleCount,
    IN ULONG_PTR SystemHandleCount
    )
/*++
 
Routine Description:
 
    Called by the object manager when a handle is closed to the object.
 
Arguments:
 
    Process - Process doing the close
    Object - Debug object being deleted
    GrantedAccess - Access ranted for this handle
    ProcessHandleCount - Unused and unmaintained by OB
    SystemHandleCount - Current handle count for this object
 
Return Value:
 
    None.
 
--*/
{
    PDEBUG_OBJECT DebugObject = Object;
    PDEBUG_EVENT DebugEvent;
    PLIST_ENTRY ListPtr;
    BOOLEAN Deref;
 
    PAGED_CODE ();
 
    UNREFERENCED_PARAMETER (GrantedAccess);
    UNREFERENCED_PARAMETER (ProcessHandleCount);
 
    //
    // If this isn't the last handle then do nothing.
    //
    if (SystemHandleCount > 1) {
        return;
    }
 
    ExAcquireFastMutex (&DebugObject->Mutex);
 
    //
    // Mark this object as going away and wake up any processes that are waiting.
    //
    DebugObject->Flags |= DEBUG_OBJECT_DELETE_PENDING;
 
    //
    // Remove any events and queue them to a temporary queue
    //
    ListPtr = DebugObject->EventList.Flink;
    InitializeListHead (&DebugObject->EventList);
 
    ExReleaseFastMutex (&DebugObject->Mutex);
 
    //
    // Wake anyone waiting. They need to leave this object alone now as its deleting
    //
    KeSetEvent (&DebugObject->EventsPresent, 0, FALSE);
 
    //
    // Loop over all processes and remove the debug port from any that still have it.
    // Debug port propagation was disabled by setting the delete pending flag above so we only have to do this
    // once. No more refs can appear now.
    //
    for (Process = PsGetNextProcess (NULL);
         Process != NULL;
         Process = PsGetNextProcess (Process)) {
 
        if (Process->DebugPort == DebugObject) {
            Deref = FALSE;
            ExAcquireFastMutex (&DbgkpProcessDebugPortMutex);
            if (Process->DebugPort == DebugObject) {
                Process->DebugPort = NULL;
                Deref = TRUE;
            }
            ExReleaseFastMutex (&DbgkpProcessDebugPortMutex);
 
 
            if (Deref) {
                DbgkpMarkProcessPeb (Process);
                //
                // If the caller wanted process deletion on debugger dying (old interface) then kill off the process.
                //
                if (DebugObject->Flags&DEBUG_OBJECT_KILL_ON_CLOSE) {
                    PsTerminateProcess (Process, STATUS_DEBUGGER_INACTIVE);
                }
                ObDereferenceObject (DebugObject);
            }
        }
    }
    //
    // Wake up all the removed threads.
    //
    while (ListPtr != &DebugObject->EventList) {
        DebugEvent = CONTAINING_RECORD (ListPtr, DEBUG_EVENT, EventList);
        ListPtr = ListPtr->Flink;
        DebugEvent->Status = STATUS_DEBUGGER_INACTIVE;
        DbgkpWakeTarget (DebugEvent);
    }
 
}
 
VOID
DbgkCopyProcessDebugPort (
    IN PEPROCESS TargetProcess,
    IN PEPROCESS SourceProcess
    )
/*++
 
Routine Description:
 
    Copies a debug port from one process to another.
 
Arguments:
 
    TargetProcess - Process to move port to
    sourceProcess - Process to move port from
 
Return Value:
 
    None
 
--*/
{
    PDEBUG_OBJECT DebugObject;
 
    PAGED_CODE ();
 
    TargetProcess->DebugPort = NULL; // New process. Needs no locks.
 
    if (SourceProcess->DebugPort != NULL) {
        ExAcquireFastMutex (&DbgkpProcessDebugPortMutex);
        DebugObject = SourceProcess->DebugPort;
        if (DebugObject != NULL && (SourceProcess->Flags&PS_PROCESS_FLAGS_NO_DEBUG_INHERIT) == 0) {
            //
            // We must not propagate a debug port thats got no handles left.
            //
            ExAcquireFastMutex (&DebugObject->Mutex);
 
            //
            // If the object is delete pending then don't propagate this object.
            //
            if ((DebugObject->Flags&DEBUG_OBJECT_DELETE_PENDING) == 0) {
                ObReferenceObject (DebugObject);
                TargetProcess->DebugPort = DebugObject;
            }
 
            ExReleaseFastMutex (&DebugObject->Mutex);
        }
        ExReleaseFastMutex (&DbgkpProcessDebugPortMutex);
    }
}
 
NTSTATUS
DbgkOpenProcessDebugPort (
    IN PEPROCESS Process,
    IN KPROCESSOR_MODE PreviousMode,
    OUT HANDLE *pHandle
    )
/*++
 
Routine Description:
 
    References the target processes debug port.
 
Arguments:
 
    Process - Process to reference debug port
 
Return Value:
 
    PDEBUG_OBJECT - Referenced object or NULL
 
--*/
{
    PDEBUG_OBJECT DebugObject;
    NTSTATUS Status;
 
    PAGED_CODE ();
 
    Status = STATUS_PORT_NOT_SET;
    if (Process->DebugPort != NULL) {
        ExAcquireFastMutex (&DbgkpProcessDebugPortMutex);
        DebugObject = Process->DebugPort;
        if (DebugObject != NULL) {
            ObReferenceObject (DebugObject);
        }
        ExReleaseFastMutex (&DbgkpProcessDebugPortMutex);
 
        if (DebugObject != NULL) {
            Status = ObOpenObjectByPointer (DebugObject,
                                            0,
                                            NULL,
                                            MAXIMUM_ALLOWED,
                                            DbgkDebugObjectType,
                                            PreviousMode,
                                            pHandle);
            if (!NT_SUCCESS (Status)) {
                ObDereferenceObject (DebugObject);
            }
        }
    }
    return Status;
 
}
 
NTSTATUS
NtCreateDebugObject (
    OUT PHANDLE DebugObjectHandle,
    IN ACCESS_MASK DesiredAccess,
    IN POBJECT_ATTRIBUTES ObjectAttributes,
    IN ULONG Flags
    )
/*++
 
Routine Description:
 
    Creates a new debug object that maintains the context for a single debug session. Multiple processes may be
    associated with a single debug object.
 
Arguments:
 
    DebugObjectHandle - Pointer to a handle to recive the output objects handle
    DesiredAccess     - Required handle access
    ObjectAttributes  - Standard object attributes structure
    Flags             - Only one flag DEBUG_KILL_ON_CLOSE
 
Return Value:
 
    NTSTATUS - Status of call.
 
--*/
{
    NTSTATUS Status;
    HANDLE Handle;
    KPROCESSOR_MODE PreviousMode;
    PDEBUG_OBJECT DebugObject;
 
    PAGED_CODE();
 
    //
    // Get previous processor mode and probe output arguments if necessary.
    // Zero the handle for error paths.
    //
 
    PreviousMode = KeGetPreviousMode();
 
    try {
        if (PreviousMode != KernelMode) {
            ProbeForWriteHandle (DebugObjectHandle);
        }
        *DebugObjectHandle = NULL;
 
    } except (ExSystemExceptionFilter ()) { // If previous mode is kernel then don't handle the exception
        return GetExceptionCode ();
    }
 
    if (Flags & ~DEBUG_KILL_ON_CLOSE) {
        return STATUS_INVALID_PARAMETER;
    }
 
    //
    // Create a new debug object and initialize it.
    //
 
    Status = ObCreateObject (PreviousMode,
                             DbgkDebugObjectType,
                             ObjectAttributes,
                             PreviousMode,
                             NULL,
                             sizeof (DEBUG_OBJECT),
                             0,
                             0,
                             &DebugObject);
 
    if (!NT_SUCCESS (Status)) {
        return Status;
    }
 
    ExInitializeFastMutex (&DebugObject->Mutex);
    InitializeListHead (&DebugObject->EventList);
    KeInitializeEvent (&DebugObject->EventsPresent, NotificationEvent, FALSE);
 
    if (Flags & DEBUG_KILL_ON_CLOSE) {
        DebugObject->Flags = DEBUG_OBJECT_KILL_ON_CLOSE;
    } else {
        DebugObject->Flags = 0;
    }
 
    //
    // Insert the object into the handle table
    //
    Status = ObInsertObject (DebugObject,
                             NULL,
                             DesiredAccess,
                             0,
                             NULL,
                             &Handle);
 
 
    if (!NT_SUCCESS (Status)) {
        return Status;
    }
 
    try {
        *DebugObjectHandle = Handle;
    } except (ExSystemExceptionFilter ()) {
        //
        // The caller changed the page protection or deleted the memory for the handle.
        // No point closing the handle as process rundown will do that and we don't know its still the same handle
        //
        Status = GetExceptionCode ();
    }
 
    return Status;
}
 
VOID
DbgkpFreeDebugEvent (
    IN PDEBUG_EVENT DebugEvent
    )
{
    NTSTATUS Status;
 
    PAGED_CODE ();
 
    switch (DebugEvent->ApiMsg.ApiNumber) {
        case DbgKmCreateProcessApi :
            if (DebugEvent->ApiMsg.u.CreateProcessInfo.FileHandle != NULL) {
                Status = ObCloseHandle (DebugEvent->ApiMsg.u.CreateProcessInfo.FileHandle, KernelMode);
            }
            break;
 
        case DbgKmLoadDllApi :
            if (DebugEvent->ApiMsg.u.LoadDll.FileHandle != NULL) {
                Status = ObCloseHandle (DebugEvent->ApiMsg.u.LoadDll.FileHandle, KernelMode);
            }
            break;
 
    }
    ObDereferenceObject (DebugEvent->Process);
    ObDereferenceObject (DebugEvent->Thread);
    ExFreePool (DebugEvent);
}
 
 
NTSTATUS
DbgkpQueueMessage (
    IN PEPROCESS Process,
    IN PETHREAD Thread,
    IN OUT PDBGKM_APIMSG ApiMsg,
    IN ULONG Flags,
    IN PDEBUG_OBJECT TargetDebugObject
    )
/*++
 
Routine Description:
 
    Queues a debug message to the port for a user mode debugger to get.
 
Arguments:
 
    Process           - Process being debugged
    Thread            - Thread making call
    ApiMsg            - Message being sent and received
    NoWait            - Don't wait for a response. Buffer message and return.
    TargetDebugObject - Port to queue nowait messages to
 
Return Value:
 
    NTSTATUS - Status of call.
 
--*/
{
    PDEBUG_EVENT DebugEvent;
    DEBUG_EVENT StaticDebugEvent;
    PDEBUG_OBJECT DebugObject;
    NTSTATUS Status;
 
    PAGED_CODE ();
 
    if (Flags&DEBUG_EVENT_NOWAIT) {
        DebugEvent = ExAllocatePoolWithQuotaTag (NonPagedPool|POOL_QUOTA_FAIL_INSTEAD_OF_RAISE,
                                                 sizeof (*DebugEvent),
                                                 'EgbD');
        if (DebugEvent == NULL) {
            return STATUS_INSUFFICIENT_RESOURCES;
        }
        DebugEvent->Flags = Flags|DEBUG_EVENT_INACTIVE;
        ObReferenceObject (Process);
        ObReferenceObject (Thread);
        DebugEvent->BackoutThread = PsGetCurrentThread ();
        DebugObject = TargetDebugObject;
    } else {
        DebugEvent = &StaticDebugEvent;
        DebugEvent->Flags = Flags;
 
        ExAcquireFastMutex (&DbgkpProcessDebugPortMutex);
 
        DebugObject = Process->DebugPort;
 
        //
        // See if this create message has already been sent.
        //
        if (ApiMsg->ApiNumber == DbgKmCreateThreadApi ||
            ApiMsg->ApiNumber == DbgKmCreateProcessApi) {
            if (Thread->CrossThreadFlags&PS_CROSS_THREAD_FLAGS_SKIP_CREATION_MSG) {
                DebugObject = NULL;
            }
        }
 
        //
        // See if this exit message is for a thread that never had a create
        //
        if (ApiMsg->ApiNumber == DbgKmExitThreadApi ||
            ApiMsg->ApiNumber == DbgKmExitProcessApi) {
            if (Thread->CrossThreadFlags&PS_CROSS_THREAD_FLAGS_SKIP_TERMINATION_MSG) {
                DebugObject = NULL;
            }
        }
    }
 
    KeInitializeEvent (&DebugEvent->ContinueEvent, SynchronizationEvent, FALSE);
 
    DebugEvent->Process = Process;
    DebugEvent->Thread = Thread;
    DebugEvent->ApiMsg = *ApiMsg;
    DebugEvent->ClientId = Thread->Cid;
 
    if (DebugObject == NULL) {
        Status = STATUS_PORT_NOT_SET;
    } else {
 
        //
        // We must not use a debug port thats got no handles left.
        //
        ExAcquireFastMutex (&DebugObject->Mutex);
 
        //
        // If the object is delete pending then don't use this object.
        //
        if ((DebugObject->Flags&DEBUG_OBJECT_DELETE_PENDING) == 0) {
            InsertTailList (&DebugObject->EventList, &DebugEvent->EventList);
            //
            // Set the event to say there is an unread event in the object
            //
            if ((Flags&DEBUG_EVENT_NOWAIT) == 0) {
                KeSetEvent (&DebugObject->EventsPresent, 0, FALSE);
            }
            Status = STATUS_SUCCESS;
        } else {
            Status = STATUS_DEBUGGER_INACTIVE;
        }
 
        ExReleaseFastMutex (&DebugObject->Mutex);
    }
 
 
    if ((Flags&DEBUG_EVENT_NOWAIT) == 0) {
        ExReleaseFastMutex (&DbgkpProcessDebugPortMutex);
 
        if (NT_SUCCESS (Status)) {
            KeWaitForSingleObject (&DebugEvent->ContinueEvent,
                                   Executive,
                                   KernelMode,
                                   FALSE,
                                   NULL);
 
            Status = DebugEvent->Status;
            *ApiMsg = DebugEvent->ApiMsg;
        }
    } else {
        if (!NT_SUCCESS (Status)) {
            ObDereferenceObject (Process);
            ObDereferenceObject (Thread);
            ExFreePool (DebugEvent);
        }
    }
 
    return Status;
}
 
NTSTATUS
DbgkClearProcessDebugObject (
    IN PEPROCESS Process,
    IN PDEBUG_OBJECT SourceDebugObject
    )
/*++
 
Routine Description:
 
    Remove a debug object from a process.
 
Arguments:
 
    Process           - Process to be debugged
    sourceDebugObject - Debug object to detach
 
Return Value:
 
    NTSTATUS - Status of call.
 
--*/
{
    NTSTATUS Status;
    PDEBUG_OBJECT DebugObject;
    PDEBUG_EVENT DebugEvent;
    LIST_ENTRY TempList;
    PLIST_ENTRY Entry;
 
    PAGED_CODE ();
 
    ExAcquireFastMutex (&DbgkpProcessDebugPortMutex);
 
    DebugObject = Process->DebugPort;
    if (DebugObject == NULL || (DebugObject != SourceDebugObject && SourceDebugObject != NULL)) {
        DebugObject = NULL;
        Status = STATUS_PORT_NOT_SET;
    } else {
        Process->DebugPort = NULL;
        Status = STATUS_SUCCESS;
    }
    ExReleaseFastMutex (&DbgkpProcessDebugPortMutex);
 
    if (NT_SUCCESS (Status)) {
        DbgkpMarkProcessPeb (Process);
    }
 
    //
    // Remove any events for this process and wake up the threads.
    //
    if (DebugObject) {
        //
        // Remove any events and queue them to a temporary queue
        //
        InitializeListHead (&TempList);
 
        ExAcquireFastMutex (&DebugObject->Mutex);
        for (Entry = DebugObject->EventList.Flink;
             Entry != &DebugObject->EventList;
             ) {
 
            DebugEvent = CONTAINING_RECORD (Entry, DEBUG_EVENT, EventList);
            Entry = Entry->Flink;
            if (DebugEvent->Process == Process) {
                RemoveEntryList (&DebugEvent->EventList);
                InsertTailList (&TempList, &DebugEvent->EventList);
            }
        }
        ExReleaseFastMutex (&DebugObject->Mutex);
 
        ObDereferenceObject (DebugObject);
 
        //
        // Wake up all the removed threads.
        //
        while (!IsListEmpty (&TempList)) {
            Entry = RemoveHeadList (&TempList);
            DebugEvent = CONTAINING_RECORD (Entry, DEBUG_EVENT, EventList);
            DebugEvent->Status = STATUS_DEBUGGER_INACTIVE;
            DbgkpWakeTarget (DebugEvent);
        }
    }
 
    return Status;
}
 
 
NTSTATUS
DbgkpSetProcessDebugObject (
    IN PEPROCESS Process,
    IN PDEBUG_OBJECT DebugObject,
    IN NTSTATUS MsgStatus,
    IN PETHREAD LastThread
    )
/*++
 
Routine Description:
 
    Attach a debug object to a process.
 
Arguments:
 
    Process     - Process to be debugged
    DebugObject - Debug object to attach
    MsgStatus   - Status from queing the messages
    LastThread  - Last thread seen in attach loop.
 
Return Value:
 
    NTSTATUS - Status of call.
 
--*/
{
    NTSTATUS Status;
    PETHREAD ThisThread;
    LIST_ENTRY TempList;
    PLIST_ENTRY Entry;
    PDEBUG_EVENT DebugEvent;
    BOOLEAN First;
    PETHREAD Thread;
    BOOLEAN GlobalHeld;
    PETHREAD FirstThread;
 
    PAGED_CODE ();
 
    ThisThread = PsGetCurrentThread ();
 
    InitializeListHead (&TempList);
 
    First = TRUE;
    GlobalHeld = FALSE;
 
    if (!NT_SUCCESS (MsgStatus)) {
        LastThread = NULL;
        Status = MsgStatus;
    } else {
        Status = STATUS_SUCCESS;
    }
 
    //
    // Pick up any threads we missed
    //
    if (NT_SUCCESS (Status)) {
 
        while (1) {
            //
            // Acquire the debug port mutex so we know that any new threads will
            // have to wait to behind us.
            //
            GlobalHeld = TRUE;
 
            ExAcquireFastMutex (&DbgkpProcessDebugPortMutex);
 
            //
            // If the port has been set then exit now.
            //
            if (Process->DebugPort != NULL) {
                Status = STATUS_PORT_ALREADY_SET;
                break;
            }
            //
            // Assign the debug port to the process to pick up any new threads
            //
            Process->DebugPort = DebugObject;
 
            //
            // Reference the last thread so we can deref outside the lock
            //
            ObReferenceObject (LastThread);
 
            //
            // Search forward for new threads
            //
            Thread = PsGetNextProcessThread (Process, LastThread);
            if (Thread != NULL) {
 
                //
                // Remove the debug port from the process as we are
                // about to drop the lock
                //
                Process->DebugPort = NULL;
 
                ExReleaseFastMutex (&DbgkpProcessDebugPortMutex);
 
                GlobalHeld = FALSE;
 
                ObDereferenceObject (LastThread);
 
                //
                // Queue any new thread messages and repeat.
                //
 
                Status = DbgkpPostFakeThreadMessages (Process,
                                                      DebugObject,
                                                      Thread,
                                                      &FirstThread,
                                                      &LastThread);
                if (!NT_SUCCESS (Status)) {
                    LastThread = NULL;
                    break;
                }
                ObDereferenceObject (FirstThread);
            } else {
                break;
            }
        }
    }
 
    //
    // Lock the debug object so we can check its deleted status
    //
    ExAcquireFastMutex (&DebugObject->Mutex);
 
    //
    // We must not propagate a debug port thats got no handles left.
    //
 
    if (NT_SUCCESS (Status)) {
        if ((DebugObject->Flags&DEBUG_OBJECT_DELETE_PENDING) == 0) {
            PS_SET_BITS (&Process->Flags, PS_PROCESS_FLAGS_NO_DEBUG_INHERIT|PS_PROCESS_FLAGS_CREATE_REPORTED);
            ObReferenceObject (DebugObject);
        } else {
            Process->DebugPort = NULL;
            Status = STATUS_DEBUGGER_INACTIVE;
        }
    }
 
    for (Entry = DebugObject->EventList.Flink;
         Entry != &DebugObject->EventList;
         ) {
 
        DebugEvent = CONTAINING_RECORD (Entry, DEBUG_EVENT, EventList);
        Entry = Entry->Flink;
 
        if ((DebugEvent->Flags&DEBUG_EVENT_INACTIVE) != 0 && DebugEvent->BackoutThread == ThisThread) {
            Thread = DebugEvent->Thread;
 
            //
            // If the thread has not been inserted by CreateThread yet then don't
            // create a handle. We skip system threads here also
            //
            if (NT_SUCCESS (Status) && Thread->GrantedAccess != 0 && !IS_SYSTEM_THREAD (Thread)) {
                //
                // If we could not acquire rundown protection on this
                // thread then we need to suppress its exit message.
                //
                if ((DebugEvent->Flags&DEBUG_EVENT_PROTECT_FAILED) != 0) {
                    PS_SET_BITS (&Thread->CrossThreadFlags,
                                 PS_CROSS_THREAD_FLAGS_SKIP_TERMINATION_MSG);
                    RemoveEntryList (&DebugEvent->EventList);
                    InsertTailList (&TempList, &DebugEvent->EventList);
                } else {
                    if (First) {
                         DebugEvent->Flags &= ~DEBUG_EVENT_INACTIVE;
                        KeSetEvent (&DebugObject->EventsPresent, 0, FALSE);
                        First = FALSE;
                    }
                    DebugEvent->BackoutThread = NULL;
                    PS_SET_BITS (&Thread->CrossThreadFlags,
                                 PS_CROSS_THREAD_FLAGS_SKIP_CREATION_MSG);
 
                }
            } else {
                RemoveEntryList (&DebugEvent->EventList);
                InsertTailList (&TempList, &DebugEvent->EventList);
            }
 
            if (DebugEvent->Flags&DEBUG_EVENT_RELEASE) {
                DebugEvent->Flags &= ~DEBUG_EVENT_RELEASE;
                ExReleaseRundownProtection (&Thread->RundownProtect);
            }
 
        }
    }
 
    ExReleaseFastMutex (&DebugObject->Mutex);
 
    if (GlobalHeld) {
        ExReleaseFastMutex (&DbgkpProcessDebugPortMutex);
    }
 
    if (LastThread != NULL) {
        ObDereferenceObject (LastThread);
    }
 
    while (!IsListEmpty (&TempList)) {
        Entry = RemoveHeadList (&TempList);
        DebugEvent = CONTAINING_RECORD (Entry, DEBUG_EVENT, EventList);
        DbgkpWakeTarget (DebugEvent);
    }
 
    if (NT_SUCCESS (Status)) {
        DbgkpMarkProcessPeb (Process);
    }
 
    return Status;
}
 
NTSTATUS
DbgkpPostFakeThreadMessages (
    IN PEPROCESS Process,
    IN PDEBUG_OBJECT DebugObject,
    IN PETHREAD StartThread,
    OUT PETHREAD *pFirstThread,
    OUT PETHREAD *pLastThread
    )
/*++
 
Routine Description:
 
    This routine posts the faked initial process create, thread create messages
 
Arguments:
 
    Process      - Process to be debugged
    DebugObject  - Debug object to queue messages to
    StartThread  - Thread to start search from
    pFirstThread - First thread found in the list
    pLastThread  - Last thread found in the list
 
Return Value:
 
    None.
 
--*/
{
    NTSTATUS Status;
    PETHREAD Thread, FirstThread, LastThread;
    DBGKM_APIMSG ApiMsg;
    BOOLEAN First = TRUE;
    BOOLEAN IsFirstThread;
    PIMAGE_NT_HEADERS NtHeaders;
    ULONG Flags;
    NTSTATUS Status1;
 
    PAGED_CODE ();
 
    LastThread = FirstThread = NULL;
 
    Status = STATUS_UNSUCCESSFUL;
 
    if (StartThread != NULL) {
        First = FALSE;
        FirstThread = StartThread;
        ObReferenceObject (FirstThread);
    } else {
        StartThread = PsGetNextProcessThread (Process, NULL);
        First = TRUE;
    }
 
    for (Thread = StartThread;
         Thread != NULL;
         Thread = PsGetNextProcessThread (Process, Thread)) {
 
        Flags = DEBUG_EVENT_NOWAIT;
 
        //
        // Keep a track ont he last thread we have seen.
        // We use this as a starting point for new threads after we
        // really attach so we can pick up any new threads.
        //
        if (LastThread != NULL) {
            ObDereferenceObject (LastThread);
        }
        LastThread = Thread;
        ObReferenceObject (LastThread);
 
        //
        // Acquire rundown protection of the thread.
        // This stops the thread exiting so we know it can't send
        // it's termination message
        //
        if (ExAcquireRundownProtection (&Thread->RundownProtect)) {
            Flags |= DEBUG_EVENT_RELEASE;
 
            //
            // Suspend the thread if we can for the debugger
            // We don't suspend terminating threads as we will not be giving details
            // of these to the debugger.
            //
 
            if (!IS_SYSTEM_THREAD (Thread)) {
                Status1 = PsSuspendThread (Thread, NULL);
                if (NT_SUCCESS (Status1)) {
                    Flags |= DEBUG_EVENT_SUSPEND;
                }
            }
        } else {
            //
            // Rundown protection failed for this thread.
            // This means the thread is exiting. We will mark this thread
            // later so it doesn't sent a thread termination message.
            // We can't do this now because this attach might fail.
            //
            Flags |= DEBUG_EVENT_PROTECT_FAILED;
        }
 
        RtlZeroMemory (&ApiMsg, sizeof (ApiMsg));
 
        if (First && (Flags&DEBUG_EVENT_PROTECT_FAILED) == 0 &&
            !IS_SYSTEM_THREAD (Thread) && Thread->GrantedAccess != 0) {
            IsFirstThread = TRUE;
        } else {
            IsFirstThread = FALSE;
        }
 
        if (IsFirstThread) {
            ApiMsg.ApiNumber = DbgKmCreateProcessApi;
            if (Process->SectionObject != NULL) { // system process doesn't have one of these!
                ApiMsg.u.CreateProcessInfo.FileHandle  = DbgkpSectionToFileHandle (Process->SectionObject);
            } else {
                ApiMsg.u.CreateProcessInfo.FileHandle = NULL;
            }
            ApiMsg.u.CreateProcessInfo.BaseOfImage = Process->SectionBaseAddress;
            try {
                NtHeaders = RtlImageNtHeader(Process->SectionBaseAddress);
                if (NtHeaders) {
                    ApiMsg.u.CreateProcessInfo.InitialThread.StartAddress = NULL; // Filling this in breaks MSDEV!
//                        (PVOID)(NtHeaders->OptionalHeader.ImageBase + NtHeaders->OptionalHeader.AddressOfEntryPoint);
                    ApiMsg.u.CreateProcessInfo.DebugInfoFileOffset = NtHeaders->FileHeader.PointerToSymbolTable;
                    ApiMsg.u.CreateProcessInfo.DebugInfoSize       = NtHeaders->FileHeader.NumberOfSymbols;
                }
            } except (EXCEPTION_EXECUTE_HANDLER) {
                ApiMsg.u.CreateProcessInfo.InitialThread.StartAddress = NULL;
                ApiMsg.u.CreateProcessInfo.DebugInfoFileOffset = 0;
                ApiMsg.u.CreateProcessInfo.DebugInfoSize = 0;
            }
        } else {
            ApiMsg.ApiNumber = DbgKmCreateThreadApi;
            ApiMsg.u.CreateThread.StartAddress = Thread->StartAddress;
        }
        Status = DbgkpQueueMessage (Process,
                                    Thread,
                                    &ApiMsg,
                                    Flags,
                                    DebugObject);
        if (!NT_SUCCESS (Status)) {
            if (Flags&DEBUG_EVENT_SUSPEND) {
                PsResumeThread (Thread, NULL);
            }
            if (Flags&DEBUG_EVENT_RELEASE) {
                ExReleaseRundownProtection (&Thread->RundownProtect);
            }
            if (ApiMsg.ApiNumber == DbgKmCreateProcessApi && ApiMsg.u.CreateProcessInfo.FileHandle != NULL) {
                ObCloseHandle (ApiMsg.u.CreateProcessInfo.FileHandle, KernelMode);
            }
            PsQuitNextProcessThread (Thread);
            break;
        } else if (IsFirstThread) {
            First = FALSE;
            ObReferenceObject (Thread);
            FirstThread = Thread;
        }
    }
 
 
    if (!NT_SUCCESS (Status)) {
        if (FirstThread) {
            ObDereferenceObject (FirstThread);
        }
        if (LastThread != NULL) {
            ObDereferenceObject (LastThread);
        }
    } else {
        if (FirstThread) {
            *pFirstThread = FirstThread;
            *pLastThread = LastThread;
        } else {
            Status = STATUS_UNSUCCESSFUL;
        }
    }
    return Status;
}
 
NTSTATUS
DbgkpPostFakeModuleMessages (
    IN PEPROCESS Process,
    IN PETHREAD Thread,
    IN PDEBUG_OBJECT DebugObject)
/*++
 
Routine Description:
 
    This routine posts the faked module load messages when we debug an active process.
 
Arguments:
 
    ProcessHandle     - Handle to a process to be debugged
    DebugObjectHandle - Handle to a debug object
 
Return Value:
 
    None.
 
--*/
{
    PPEB Peb = Process->Peb;
    PPEB_LDR_DATA Ldr;
    PLIST_ENTRY LdrHead, LdrNext;
    PLDR_DATA_TABLE_ENTRY LdrEntry;
    DBGKM_APIMSG ApiMsg;
    ULONG i;
    OBJECT_ATTRIBUTES oa;
    UNICODE_STRING Name;
    PIMAGE_NT_HEADERS NtHeaders;
    NTSTATUS Status;
    IO_STATUS_BLOCK iosb;
 
    PAGED_CODE ();
 
    if (Peb == NULL) {
        return STATUS_SUCCESS;
    }
 
    try {
        Ldr = Peb->Ldr;
 
        LdrHead = &Ldr->InLoadOrderModuleList;
 
        ProbeForReadSmallStructure (LdrHead, sizeof (LIST_ENTRY), sizeof (UCHAR));
        for (LdrNext = LdrHead->Flink, i = 0;
             LdrNext != LdrHead && i < 500;
             LdrNext = LdrNext->Flink, i++) {
 
            //
            // First image got send with process create message
            //
            if (i > 0) {
                RtlZeroMemory (&ApiMsg, sizeof (ApiMsg));
 
                LdrEntry = CONTAINING_RECORD (LdrNext, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks);
                ProbeForReadSmallStructure (LdrEntry, sizeof (LDR_DATA_TABLE_ENTRY), sizeof (UCHAR));
 
                ApiMsg.ApiNumber = DbgKmLoadDllApi;
                ApiMsg.u.LoadDll.BaseOfDll = LdrEntry->DllBase;
                ApiMsg.u.LoadDll.NamePointer = NULL;
 
                ProbeForReadSmallStructure (ApiMsg.u.LoadDll.BaseOfDll, sizeof (IMAGE_DOS_HEADER), sizeof (UCHAR));
 
                NtHeaders = RtlImageNtHeader (ApiMsg.u.LoadDll.BaseOfDll);
                if (NtHeaders) {
                    ApiMsg.u.LoadDll.DebugInfoFileOffset = NtHeaders->FileHeader.PointerToSymbolTable;
                    ApiMsg.u.LoadDll.DebugInfoSize = NtHeaders->FileHeader.NumberOfSymbols;
                }
                Status = MmGetFileNameForAddress (NtHeaders, &Name);
                if (NT_SUCCESS (Status)) {
                    InitializeObjectAttributes (&oa,
                                                &Name,
                                                OBJ_FORCE_ACCESS_CHECK|OBJ_CASE_INSENSITIVE|OBJ_KERNEL_HANDLE,
                                                NULL,
                                                NULL);
 
                    Status = ZwOpenFile (&ApiMsg.u.LoadDll.FileHandle,
                                         GENERIC_READ|SYNCHRONIZE,
                                         &oa,
                                         &iosb,
                                         FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
                                         FILE_SYNCHRONOUS_IO_NONALERT);
                    if (!NT_SUCCESS (Status)) {
                        ApiMsg.u.LoadDll.FileHandle = NULL;
                    }
                    ExFreePool (Name.Buffer);
                }
                Status = DbgkpQueueMessage (Process,
                                            Thread,
                                            &ApiMsg,
                                            DEBUG_EVENT_NOWAIT,
                                            DebugObject);
                if (!NT_SUCCESS (Status) && ApiMsg.u.LoadDll.FileHandle != NULL) {
                    ObCloseHandle (ApiMsg.u.LoadDll.FileHandle, KernelMode);
                }
 
            }
            ProbeForReadSmallStructure (LdrNext, sizeof (LIST_ENTRY), sizeof (UCHAR));
        }
    } except (EXCEPTION_EXECUTE_HANDLER) {
    }
 
#if defined(_WIN64)
    if (Process->Wow64Process != NULL && Process->Wow64Process->Wow64 != NULL) {
        PPEB32 Peb32;
        PPEB_LDR_DATA32 Ldr32;
        PLIST_ENTRY32 LdrHead32, LdrNext32;
        PLDR_DATA_TABLE_ENTRY32 LdrEntry32;
        PWCHAR pSys;
 
        Peb32 = (PPEB32)Process->Wow64Process->Wow64;
 
        try {
            Ldr32 = (PVOID) UlongToPtr(Peb32->Ldr);
 
            LdrHead32 = &Ldr32->InLoadOrderModuleList;
 
            ProbeForReadSmallStructure (LdrHead32, sizeof (LIST_ENTRY32), sizeof (UCHAR));
            for (LdrNext32 = (PVOID) UlongToPtr(LdrHead32->Flink), i = 0;
                 LdrNext32 != LdrHead32 && i < 500;
                 LdrNext32 = (PVOID) UlongToPtr(LdrNext32->Flink), i++) {
 
                if (i > 0) {
                    RtlZeroMemory (&ApiMsg, sizeof (ApiMsg));
 
                    LdrEntry32 = CONTAINING_RECORD (LdrNext32, LDR_DATA_TABLE_ENTRY32, InLoadOrderLinks);
                    ProbeForReadSmallStructure (LdrEntry32, sizeof (LDR_DATA_TABLE_ENTRY32), sizeof (UCHAR));
 
                    ApiMsg.ApiNumber = DbgKmLoadDllApi;
                    ApiMsg.u.LoadDll.BaseOfDll = (PVOID) UlongToPtr(LdrEntry32->DllBase);
                    ApiMsg.u.LoadDll.NamePointer = NULL;
 
                    ProbeForReadSmallStructure (ApiMsg.u.LoadDll.BaseOfDll, sizeof (IMAGE_DOS_HEADER), sizeof (UCHAR));
 
                    NtHeaders = RtlImageNtHeader(ApiMsg.u.LoadDll.BaseOfDll);
                    if (NtHeaders) {
                        ApiMsg.u.LoadDll.DebugInfoFileOffset = NtHeaders->FileHeader.PointerToSymbolTable;
                        ApiMsg.u.LoadDll.DebugInfoSize = NtHeaders->FileHeader.NumberOfSymbols;
                    }
 
                    Status = MmGetFileNameForAddress (NtHeaders, &Name);
                    if (NT_SUCCESS (Status)) {
                        ASSERT (sizeof (L"SYSTEM32") == sizeof (WOW64_SYSTEM_DIRECTORY_U));
                        pSys = wcsstr (Name.Buffer, L"\\SYSTEM32\\");
                        if (pSys != NULL) {
                            RtlCopyMemory (pSys+1,
                                           WOW64_SYSTEM_DIRECTORY_U,
                                           sizeof(WOW64_SYSTEM_DIRECTORY_U) - sizeof(UNICODE_NULL));
                        }
 
                        InitializeObjectAttributes (&oa,
                                                    &Name,
                                                    OBJ_FORCE_ACCESS_CHECK|OBJ_CASE_INSENSITIVE|OBJ_KERNEL_HANDLE,
                                                    NULL,
                                                    NULL);
 
                        Status = ZwOpenFile (&ApiMsg.u.LoadDll.FileHandle,
                                             GENERIC_READ|SYNCHRONIZE,
                                             &oa,
                                             &iosb,
                                             FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
                                             FILE_SYNCHRONOUS_IO_NONALERT);
                        if (!NT_SUCCESS (Status)) {
                            ApiMsg.u.LoadDll.FileHandle = NULL;
                        }
                        ExFreePool (Name.Buffer);
                    }
 
                    Status = DbgkpQueueMessage (Process,
                                                Thread,
                                                &ApiMsg,
                                                DEBUG_EVENT_NOWAIT,
                                                DebugObject);
                    if (!NT_SUCCESS (Status) && ApiMsg.u.LoadDll.FileHandle != NULL) {
                        ObCloseHandle (ApiMsg.u.LoadDll.FileHandle, KernelMode);
                    }
                }
 
                ProbeForReadSmallStructure (LdrNext32, sizeof (LIST_ENTRY32), sizeof (UCHAR));
            }
 
        } except (EXCEPTION_EXECUTE_HANDLER) {
        }
    }
 
#endif
    return STATUS_SUCCESS;
}
 
NTSTATUS
DbgkpPostFakeProcessCreateMessages (
    IN PEPROCESS Process,
    IN PDEBUG_OBJECT DebugObject,
    IN PETHREAD *pLastThread
    )
/*++
 
Routine Description:
 
    This routine posts the faked initial process create, thread create and mudule load messages
 
Arguments:
 
    ProcessHandle     - Handle to a process to be debugged
    DebugObjectHandle - Handle to a debug object
 
Return Value:
 
    None.
 
--*/
{
    NTSTATUS Status;
    KAPC_STATE ApcState;
    PETHREAD Thread;
    PETHREAD LastThread;
 
    PAGED_CODE ();
 
    //
    // Attach to the process so we can touch its address space
    //
    KeStackAttachProcess(&Process->Pcb, &ApcState);
 
    Status = DbgkpPostFakeThreadMessages (Process,
                                          DebugObject,
                                          NULL,
                                          &Thread,
                                          &LastThread);
 
    if (NT_SUCCESS (Status)) {
        Status = DbgkpPostFakeModuleMessages (Process, Thread, DebugObject);
        if (!NT_SUCCESS (Status)) {
            ObDereferenceObject (LastThread);
            LastThread = NULL;
        }
        ObDereferenceObject (Thread);
    } else {
        LastThread = NULL;
    }
 
    KeUnstackDetachProcess(&ApcState);
 
    *pLastThread = LastThread;
 
    return Status;
}
 
NTSTATUS
NtDebugActiveProcess (
    IN HANDLE ProcessHandle,
    IN HANDLE DebugObjectHandle
    )
/*++
 
Routine Description:
 
    Attach a debug object to a process.
 
Arguments:
 
    ProcessHandle     - Handle to a process to be debugged
    DebugObjectHandle - Handle to a debug object
 
Return Value:
 
    NTSTATUS - Status of call.
 
--*/
{
    NTSTATUS Status;
    KPROCESSOR_MODE PreviousMode;
    PDEBUG_OBJECT DebugObject;
    PEPROCESS Process;
    PETHREAD LastThread;
 
    PAGED_CODE ();
 
    PreviousMode = KeGetPreviousMode();
 
    Status = ObReferenceObjectByHandle (ProcessHandle,
                                        PROCESS_SET_PORT,
                                        PsProcessType,
                                        PreviousMode,
                                        &Process,
                                        NULL);
    if (!NT_SUCCESS (Status)) {
        return Status;
    }
 
    //
    // Don't let us debug ourselves or the system process.
    //
    if (Process == PsGetCurrentProcess () || Process == PsInitialSystemProcess) {
        ObDereferenceObject (Process);
        return STATUS_ACCESS_DENIED;
    }
 
 
    Status = ObReferenceObjectByHandle (DebugObjectHandle,
                                        DEBUG_PROCESS_ASSIGN,
                                        DbgkDebugObjectType,
                                        PreviousMode,
                                        &DebugObject,
                                        NULL);
 
    if (NT_SUCCESS (Status)) {
        //
        // We will be touching process address space. Block process rundown.
        //
        if (ExAcquireRundownProtection (&Process->RundownProtect)) {
 
            //
            // Post the fake process create messages etc.
            //
            Status = DbgkpPostFakeProcessCreateMessages (Process,
                                                         DebugObject,
                                                         &LastThread);
 
            //
            // Set the debug port. If this fails it will remove any faked messages.
            //
            Status = DbgkpSetProcessDebugObject (Process,
                                                 DebugObject,
                                                 Status,
                                                 LastThread);
 
            ExReleaseRundownProtection (&Process->RundownProtect);
        } else {
            Status = STATUS_PROCESS_IS_TERMINATING;
        }
 
        ObDereferenceObject (DebugObject);
    }
    ObDereferenceObject (Process);
 
    return Status;
}
 
NTSTATUS
NtRemoveProcessDebug (
    IN HANDLE ProcessHandle,
    IN HANDLE DebugObjectHandle
    )
/*++
 
Routine Description:
 
    Remove a debug object from a process.
 
Arguments:
 
    ProcessHandle - Handle to a process currently being debugged
 
Return Value:
 
    NTSTATUS - Status of call.
 
--*/
{
    NTSTATUS Status;
    KPROCESSOR_MODE PreviousMode;
    PDEBUG_OBJECT DebugObject;
    PEPROCESS Process;
 
    PAGED_CODE ();
 
    PreviousMode = KeGetPreviousMode();
 
    Status = ObReferenceObjectByHandle (ProcessHandle,
                                        PROCESS_SET_PORT,
                                        PsProcessType,
                                        PreviousMode,
                                        &Process,
                                        NULL);
    if (!NT_SUCCESS (Status)) {
        return Status;
    }
    Status = ObReferenceObjectByHandle (DebugObjectHandle,
                                        DEBUG_PROCESS_ASSIGN,
                                        DbgkDebugObjectType,
                                        PreviousMode,
                                        &DebugObject,
                                        NULL);
    if (NT_SUCCESS (Status)) {
        Status = DbgkClearProcessDebugObject (Process,
                                               DebugObject);
        ObDereferenceObject (DebugObject);
    }
 
    ObDereferenceObject (Process);
    return Status;
}
 
VOID
DbgkpOpenHandles (
    PDBGUI_WAIT_STATE_CHANGE WaitStateChange,
    PEPROCESS Process,
    PETHREAD Thread
    )
/*++
 
Routine Description:
 
    Opens up process, thread and filehandles if need be for some of the requests
 
Arguments:
 
    WaitStateChange - User mode format change block
    Process - Pointer to target process
    Thread - Pointer to target thread
 
Return Value:
 
    None
 
--*/
{
    NTSTATUS Status;
    PEPROCESS CurrentProcess;
    HANDLE OldHandle;
 
    PAGED_CODE ();
 
    switch (WaitStateChange->NewState) {
        case DbgCreateThreadStateChange :
            //
            // We have the right to open up any thread in the process if we are allowed to debug it.
            // Use kernel mode here so we are always granted it regardless of protection.
            //
            Status = ObOpenObjectByPointer (Thread,
                                            0,
                                            NULL,
                                            THREAD_GET_CONTEXT | THREAD_SET_CONTEXT | THREAD_SUSPEND_RESUME | \
                                               THREAD_QUERY_INFORMATION | THREAD_SET_INFORMATION | THREAD_TERMINATE |
                                               READ_CONTROL | SYNCHRONIZE,
                                            PsThreadType,
                                            KernelMode,
                                            &WaitStateChange->StateInfo.CreateThread.HandleToThread);
            if (!NT_SUCCESS (Status)) {
                WaitStateChange->StateInfo.CreateThread.HandleToThread = NULL;
            }
            break;
 
        case DbgCreateProcessStateChange :
 
            Status = ObOpenObjectByPointer (Thread,
                                            0,
                                            NULL,
                                            THREAD_GET_CONTEXT | THREAD_SET_CONTEXT | THREAD_SUSPEND_RESUME | \
                                               THREAD_QUERY_INFORMATION | THREAD_SET_INFORMATION | THREAD_TERMINATE |
                                               READ_CONTROL | SYNCHRONIZE,
                                            PsThreadType,
                                            KernelMode,
                                            &WaitStateChange->StateInfo.CreateProcessInfo.HandleToThread);
            if (!NT_SUCCESS (Status)) {
                WaitStateChange->StateInfo.CreateProcessInfo.HandleToThread = NULL;
            }
            Status = ObOpenObjectByPointer (Process,
                                            0,
                                            NULL,
                                            PROCESS_VM_READ | PROCESS_VM_WRITE | PROCESS_VM_OPERATION |
                                               PROCESS_DUP_HANDLE | PROCESS_QUERY_INFORMATION | PROCESS_SET_INFORMATION |
                                               PROCESS_CREATE_THREAD | PROCESS_TERMINATE |
                                               READ_CONTROL | SYNCHRONIZE,
                                            PsProcessType,
                                            KernelMode,
                                            &WaitStateChange->StateInfo.CreateProcessInfo.HandleToProcess);
            if (!NT_SUCCESS (Status)) {
                WaitStateChange->StateInfo.CreateProcessInfo.HandleToProcess = NULL;
            }
 
            OldHandle = WaitStateChange->StateInfo.CreateProcessInfo.NewProcess.FileHandle;
            if (OldHandle != NULL) {
                CurrentProcess = PsGetCurrentProcess ();
                Status = ObDuplicateObject (CurrentProcess,
                                            OldHandle,
                                            CurrentProcess,
                                            &WaitStateChange->StateInfo.CreateProcessInfo.NewProcess.FileHandle,
                                            0,
                                            0,
                                            DUPLICATE_SAME_ACCESS,
                                            KernelMode);
                if (!NT_SUCCESS (Status)) {
                    WaitStateChange->StateInfo.CreateProcessInfo.NewProcess.FileHandle = NULL;
                }
                ObCloseHandle (OldHandle, KernelMode);
            }
            break;
 
        case DbgLoadDllStateChange :
 
            OldHandle = WaitStateChange->StateInfo.LoadDll.FileHandle;
            if (OldHandle != NULL) {
                CurrentProcess = PsGetCurrentProcess ();
                Status = ObDuplicateObject (CurrentProcess,
                                            OldHandle,
                                            CurrentProcess,
                                            &WaitStateChange->StateInfo.LoadDll.FileHandle,
                                            0,
                                            0,
                                            DUPLICATE_SAME_ACCESS,
                                            KernelMode);
                if (!NT_SUCCESS (Status)) {
                    WaitStateChange->StateInfo.LoadDll.FileHandle = NULL;
                }
                ObCloseHandle (OldHandle, KernelMode);
            }
 
            break;
 
        default :
            break;
    }
}
 
VOID
DbgkpConvertKernelToUserStateChange (
     PDBGUI_WAIT_STATE_CHANGE WaitStateChange,
     PDEBUG_EVENT DebugEvent)
/*++
 
Routine Description:
 
    Converts a kernel message to one the user expects
 
Arguments:
 
    WaitStateChange - User mode format
    DebugEvent      - Debug event block to copy from
 
Return Value:
 
    None
 
--*/
{
 
    PAGED_CODE ();
 
    WaitStateChange->AppClientId = DebugEvent->ClientId;
    switch (DebugEvent->ApiMsg.ApiNumber) {
        case DbgKmExceptionApi :
 
            switch (DebugEvent->ApiMsg.u.Exception.ExceptionRecord.ExceptionCode) {
                case STATUS_BREAKPOINT :
                    WaitStateChange->NewState = DbgBreakpointStateChange;
                    break;
 
                case STATUS_SINGLE_STEP :
                    WaitStateChange->NewState = DbgSingleStepStateChange;
                    break;
 
                default :
                    WaitStateChange->NewState = DbgExceptionStateChange;
                    break;
            }
            WaitStateChange->StateInfo.Exception = DebugEvent->ApiMsg.u.Exception;
            break;
 
        case DbgKmCreateThreadApi :
            WaitStateChange->NewState = DbgCreateThreadStateChange;
            WaitStateChange->StateInfo.CreateThread.NewThread = DebugEvent->ApiMsg.u.CreateThread;
            break;
 
        case DbgKmCreateProcessApi :
            WaitStateChange->NewState = DbgCreateProcessStateChange;
            WaitStateChange->StateInfo.CreateProcessInfo.NewProcess = DebugEvent->ApiMsg.u.CreateProcessInfo;
            //
            // clear out the handle in the message as we will close this when we duplicate.
            //
            DebugEvent->ApiMsg.u.CreateProcessInfo.FileHandle = NULL;
            break;
 
        case DbgKmExitThreadApi :
            WaitStateChange->NewState = DbgExitThreadStateChange;
            WaitStateChange->StateInfo.ExitThread = DebugEvent->ApiMsg.u.ExitThread;
            break;
 
        case DbgKmExitProcessApi :
            WaitStateChange->NewState = DbgExitProcessStateChange;
            WaitStateChange->StateInfo.ExitProcess = DebugEvent->ApiMsg.u.ExitProcess;
            break;
 
        case DbgKmLoadDllApi :
            WaitStateChange->NewState = DbgLoadDllStateChange;
            WaitStateChange->StateInfo.LoadDll = DebugEvent->ApiMsg.u.LoadDll;
            //
            // clear out the handle in the message as we will close this when we duplicate.
            //
            DebugEvent->ApiMsg.u.LoadDll.FileHandle = NULL;
            break;
 
        case DbgKmUnloadDllApi :
            WaitStateChange->NewState = DbgUnloadDllStateChange;
            WaitStateChange->StateInfo.UnloadDll = DebugEvent->ApiMsg.u.UnloadDll;
            break;
 
        default :
            ASSERT (FALSE);
    }
}
 
NTSTATUS
NtWaitForDebugEvent (
    IN HANDLE DebugObjectHandle,
    IN BOOLEAN Alertable,
    IN PLARGE_INTEGER Timeout OPTIONAL,
    OUT PDBGUI_WAIT_STATE_CHANGE WaitStateChange
    )
/*++
 
Routine Description:
 
    Waits for a debug event and returns it to the user if one arrives
 
Arguments:
 
    DebugObjectHandle - Handle to a debug object
    Alertable - TRUE is the wait is to be alertable
    Timeout - Operation timeout value
    WaitStateChange - Returned debug event
 
Return Value:
 
    Status of operation
 
--*/
{
    NTSTATUS Status;
    KPROCESSOR_MODE PreviousMode;
    PDEBUG_OBJECT DebugObject;
    LARGE_INTEGER Tmo = {0};
    LARGE_INTEGER StartTime = {0};
    DBGUI_WAIT_STATE_CHANGE tWaitStateChange = {0};
    PEPROCESS Process;
    PETHREAD Thread;
    PLIST_ENTRY Entry, Entry2;
    PDEBUG_EVENT DebugEvent, DebugEvent2;
    BOOLEAN GotEvent;
 
    PAGED_CODE ();
 
    PreviousMode = KeGetPreviousMode();
 
    try {
        if (ARGUMENT_PRESENT (Timeout)) {
            if (PreviousMode != KernelMode) {
                ProbeForReadSmallStructure (Timeout, sizeof (*Timeout), sizeof (UCHAR));
            }
            Tmo = *Timeout;
            Timeout = &Tmo;
            KeQuerySystemTime (&StartTime);
        }
        if (PreviousMode != KernelMode) {
            ProbeForWriteSmallStructure (WaitStateChange, sizeof (*WaitStateChange), sizeof (UCHAR));
        }
 
    } except (ExSystemExceptionFilter ()) { // If previous mode is kernel then don't handle the exception
        return GetExceptionCode ();
    }
 
 
    Status = ObReferenceObjectByHandle (DebugObjectHandle,
                                        DEBUG_READ_EVENT,
                                        DbgkDebugObjectType,
                                        PreviousMode,
                                        &DebugObject,
                                        NULL);
 
    if (!NT_SUCCESS (Status)) {
        return Status;
    }
 
    Process = NULL;
    Thread = NULL;
 
    while (1) {
        Status = KeWaitForSingleObject (&DebugObject->EventsPresent,
                                        Executive,
                                        PreviousMode,
                                        Alertable,
                                        Timeout);
        if (!NT_SUCCESS (Status) || Status == STATUS_TIMEOUT || Status == STATUS_ALERTED || Status == STATUS_USER_APC) {
            break;
        }
 
        GotEvent = FALSE;
 
        DebugEvent = NULL;
 
        ExAcquireFastMutex (&DebugObject->Mutex);
 
        //
        // If the object is delete pending then return an error.
        //
        if ((DebugObject->Flags&DEBUG_OBJECT_DELETE_PENDING) == 0) {
 
 
            for (Entry = DebugObject->EventList.Flink;
                 Entry != &DebugObject->EventList;
                 Entry = Entry->Flink) {
 
                DebugEvent = CONTAINING_RECORD (Entry, DEBUG_EVENT, EventList);
 
                //
                // If this event has not been given back to the user yet and is not
                // inactive then pass it back.
                // We check to see if we have any other outstanding messages for this
                // thread as this confuses VC. You can only get multiple events
                // for the same thread for the attach faked messages.
                //
                if ((DebugEvent->Flags&(DEBUG_EVENT_READ|DEBUG_EVENT_INACTIVE)) == 0) {
                    GotEvent = TRUE;
                    for (Entry2 = DebugObject->EventList.Flink;
                         Entry2 != Entry;
                         Entry2 = Entry2->Flink) {
 
                        DebugEvent2 = CONTAINING_RECORD (Entry2, DEBUG_EVENT, EventList);
 
                        if (DebugEvent->ClientId.UniqueProcess == DebugEvent2->ClientId.UniqueProcess) {
                            //
                            // This event has the same process as an earlier event. Mark it as inactive.
                            //
                            DebugEvent->Flags |= DEBUG_EVENT_INACTIVE;
                            DebugEvent->BackoutThread = NULL;
                            GotEvent = FALSE;
                            break;
                        }
                    }
                    if (GotEvent) {
                        break;
                    }
                }
            }
 
            if (GotEvent) {
                Process = DebugEvent->Process;
                Thread = DebugEvent->Thread;
                ObReferenceObject (Thread);
                ObReferenceObject (Process);
                DbgkpConvertKernelToUserStateChange (&tWaitStateChange, DebugEvent);
                DebugEvent->Flags |= DEBUG_EVENT_READ;
            } else {
                //
                // No unread events there. Clear the event.
                //
                KeClearEvent (&DebugObject->EventsPresent);
            }
            Status = STATUS_SUCCESS;
 
        } else {
            Status = STATUS_DEBUGGER_INACTIVE;
        }
 
        ExReleaseFastMutex (&DebugObject->Mutex);
 
        if (NT_SUCCESS (Status)) {
            //
            // If we woke up and found nothing
            //
            if (GotEvent == FALSE) {
                //
                // If timeout is a delta time then adjust it for the wait so far.
                //
                if (Tmo.QuadPart < 0) {
                    LARGE_INTEGER NewTime;
                    KeQuerySystemTime (&NewTime);
                    Tmo.QuadPart = Tmo.QuadPart + (NewTime.QuadPart - StartTime.QuadPart);
                    StartTime = NewTime;
                    if (Tmo.QuadPart >= 0) {
                        Status = STATUS_TIMEOUT;
                        break;
                    }
                }
            } else {
                //
                // Fixup needed handles. The caller could have guessed the thread id etc by now and made the target thread
                // continue. This isn't a problem as we won't do anything damaging to the system in this case. The caller
                // won't get the correct results but they set out to break us.
                //
                DbgkpOpenHandles (&tWaitStateChange, Process, Thread);
                ObDereferenceObject (Thread);
                ObDereferenceObject (Process);
                break;
            }
        } else {
            break;
        }
    }
 
    ObDereferenceObject (DebugObject);
 
    try {
        *WaitStateChange = tWaitStateChange;
    } except (ExSystemExceptionFilter ()) { // If previous mode is kernel then don't handle the exception
        Status = GetExceptionCode ();
    }
    return Status;
}
 
NTSTATUS
NtDebugContinue (
    IN HANDLE DebugObjectHandle,
    IN PCLIENT_ID ClientId,
    IN NTSTATUS ContinueStatus
    )
/*++
 
Routine Description:
 
    Continues a stalled debugged thread
 
Arguments:
 
    DebugObjectHandle - Handle to a debug object
    ClientId - ClientId of thread tro continue
    ContinueStatus - Status of continue
 
Return Value:
 
    Status of operation
 
--*/
{
    NTSTATUS Status;
    PDEBUG_OBJECT DebugObject;
    PDEBUG_EVENT DebugEvent, FoundDebugEvent;
    KPROCESSOR_MODE PreviousMode;
    CLIENT_ID Clid;
    PLIST_ENTRY Entry;
    BOOLEAN GotEvent;
 
    PreviousMode = KeGetPreviousMode();
 
    try {
        if (PreviousMode != KernelMode) {
            ProbeForReadSmallStructure (ClientId, sizeof (*ClientId), sizeof (UCHAR));
        }
        Clid = *ClientId;
 
    } except (ExSystemExceptionFilter ()) { // If previous mode is kernel then don't handle the exception
        return GetExceptionCode ();
    }
 
    switch (ContinueStatus) {
        case DBG_EXCEPTION_HANDLED :
        case DBG_EXCEPTION_NOT_HANDLED :
        case DBG_TERMINATE_THREAD :
        case DBG_TERMINATE_PROCESS :
        case DBG_CONTINUE :
            break;
        default :
            return STATUS_INVALID_PARAMETER;
    }
 
    Status = ObReferenceObjectByHandle (DebugObjectHandle,
                                        DEBUG_READ_EVENT,
                                        DbgkDebugObjectType,
                                        PreviousMode,
                                        &DebugObject,
                                        NULL);
 
    if (!NT_SUCCESS (Status)) {
        return Status;
    }
 
    GotEvent = FALSE;
    FoundDebugEvent = NULL;
 
    ExAcquireFastMutex (&DebugObject->Mutex);
 
    for (Entry = DebugObject->EventList.Flink;
         Entry != &DebugObject->EventList;
         Entry = Entry->Flink) {
 
        DebugEvent = CONTAINING_RECORD (Entry, DEBUG_EVENT, EventList);
 
        //
        // Make sure the client ID matches and that the debugger saw all the events.
        // We don't allow the caller to start a thread that it never saw a message for.
        //
        if (DebugEvent->ClientId.UniqueProcess == Clid.UniqueProcess) {
            if (!GotEvent) {
                if (DebugEvent->ClientId.UniqueThread == Clid.UniqueThread &&
                    (DebugEvent->Flags&DEBUG_EVENT_READ) != 0) {
                    RemoveEntryList (Entry);
                    FoundDebugEvent = DebugEvent;
                    GotEvent = TRUE;
                }
            } else {
                //
                // VC breaks if it sees more than one event at a time
                // for the same process.
                //
                DebugEvent->Flags &= ~DEBUG_EVENT_INACTIVE;
                KeSetEvent (&DebugObject->EventsPresent, 0, FALSE);
                break;
            }
        }
    }
 
    ExReleaseFastMutex (&DebugObject->Mutex);
 
    ObDereferenceObject (DebugObject);
 
    if (GotEvent) {
        FoundDebugEvent->ApiMsg.ReturnedStatus = ContinueStatus;
        FoundDebugEvent->Status = STATUS_SUCCESS;
        DbgkpWakeTarget (FoundDebugEvent);
    } else {
        Status = STATUS_INVALID_PARAMETER;
    }
 
    return Status;
}
 
NTSTATUS
NtSetInformationDebugObject (
    IN HANDLE DebugObjectHandle,
    IN DEBUGOBJECTINFOCLASS DebugObjectInformationClass,
    IN PVOID DebugInformation,
    IN ULONG DebugInformationLength,
    OUT PULONG ReturnLength OPTIONAL
    )
/*++
 
Routine Description:
 
    This function sets the state of a debug object.
 
Arguments:
 
    ProcessHandle - Supplies a handle to a process object.
 
    ProcessInformationClass - Supplies the class of information being
        set.
 
    ProcessInformation - Supplies a pointer to a record that contains the
        information to set.
 
    ProcessInformationLength - Supplies the length of the record that contains
        the information to set.
 
Return Value:
 
    NTSTATUS - Status of call
 
--*/
{
    KPROCESSOR_MODE PreviousMode;
    NTSTATUS Status;
    PDEBUG_OBJECT DebugObject;
    ULONG Flags;
 
    PreviousMode = KeGetPreviousMode();
 
    try {
        if (PreviousMode != KernelMode) {
            ProbeForRead (DebugInformation,
                          DebugInformationLength,
                          sizeof (ULONG));
            if (ARGUMENT_PRESENT (ReturnLength)) {
                ProbeForWriteUlong (ReturnLength);
            }
        }
        if (ARGUMENT_PRESENT (ReturnLength)) {
            *ReturnLength = 0;
        }
 
        switch (DebugObjectInformationClass) {
            case DebugObjectFlags : {
 
                if (DebugInformationLength != sizeof (ULONG)) {
                    if (ARGUMENT_PRESENT (ReturnLength)) {
                        *ReturnLength = sizeof (ULONG);
                    }
                    return STATUS_INFO_LENGTH_MISMATCH;
                }
                Flags = *(PULONG) DebugInformation;
 
                break;
            }
            default : {
                return STATUS_INVALID_PARAMETER;
            }
        }
    } except (ExSystemExceptionFilter ()) {
        return GetExceptionCode ();
    }
 
 
    switch (DebugObjectInformationClass) {
        case DebugObjectFlags : {
            if (Flags & ~DEBUG_KILL_ON_CLOSE) {
                return STATUS_INVALID_PARAMETER;
            }
            Status = ObReferenceObjectByHandle (DebugObjectHandle,
                                                DEBUG_SET_INFORMATION,
                                                DbgkDebugObjectType,
                                                PreviousMode,
                                                &DebugObject,
                                                NULL);
 
            if (!NT_SUCCESS (Status)) {
                return Status;
            }
            ExAcquireFastMutex (&DebugObject->Mutex);
 
            if (Flags&DEBUG_KILL_ON_CLOSE) {
                DebugObject->Flags |= DEBUG_OBJECT_KILL_ON_CLOSE;
            } else {
                DebugObject->Flags &= ~DEBUG_OBJECT_KILL_ON_CLOSE;
            }
 
            ExReleaseFastMutex (&DebugObject->Mutex);
 
            ObDereferenceObject (DebugObject);
        }
    }
    return STATUS_SUCCESS;
}
## dbgkport.c
```c
/*++
 
Copyright (c) Microsoft Corporation. All rights reserved.
 
You may only use this code if you agree to the terms of the Windows Research Kernel Source Code License agreement (see License.txt).
If you do not agree to the terms, do not use the code.
 
 
Module Name:
 
    dbgkport.c
 
Abstract:
 
    This module implements the dbg primitives to access a process'
    DebugPort and ExceptionPort.
 
--*/
 
#include "dbgkp.h"
 
#ifdef ALLOC_PRAGMA
#pragma alloc_text(PAGE, DbgkpSendApiMessage)
#pragma alloc_text(PAGE, DbgkForwardException)
#pragma alloc_text(PAGE, DbgkpSendApiMessageLpc)
#endif
 
 
NTSTATUS
DbgkpSendApiMessage(
    IN OUT PDBGKM_APIMSG ApiMsg,
    IN BOOLEAN SuspendProcess
    )
 
/*++
 
Routine Description:
 
    This function sends the specified API message over the specified
    port. It is the caller's responsibility to format the API message
    prior to calling this function.
 
    If the SuspendProcess flag is supplied, then all threads in the
    calling process are first suspended. Upon receipt of the reply
    message, the threads are resumed.
 
Arguments:
 
    ApiMsg - Supplies the API message to send.
 
    SuspendProcess - A flag that if set to true, causes all of the
        threads in the process to be suspended prior to the call,
        and resumed upon receipt of a reply.
 
Return Value:
 
    NTSTATUS.
 
--*/
 
{
    NTSTATUS st;
    PEPROCESS Process;
 
    PAGED_CODE();
 
    if ( SuspendProcess ) {
        SuspendProcess = DbgkpSuspendProcess();
    }
 
    ApiMsg->ReturnedStatus = STATUS_PENDING;
 
    Process = PsGetCurrentProcess();
 
    PS_SET_BITS (&Process->Flags, PS_PROCESS_FLAGS_CREATE_REPORTED);
 
    st = DbgkpQueueMessage (Process, PsGetCurrentThread (), ApiMsg, 0, NULL);
 
    ZwFlushInstructionCache (NtCurrentProcess (), NULL, 0);
    if ( SuspendProcess ) {
        DbgkpResumeProcess();
    }
 
    return st;
}
 
NTSTATUS
DbgkpSendApiMessageLpc(
    IN OUT PDBGKM_APIMSG ApiMsg,
    IN PVOID Port,
    IN BOOLEAN SuspendProcess
    )
 
/*++
 
Routine Description:
 
    This function sends the specified API message over the specified
    port. It is the caller's responsibility to format the API message
    prior to calling this function.
 
    If the SuspendProcess flag is supplied, then all threads in the
    calling process are first suspended. Upon receipt of the reply
    message, the threads are resumed.
 
Arguments:
 
    ApiMsg - Supplies the API message to send.
 
    Port - Supplies the address of a port to send the api message.
 
    SuspendProcess - A flag that if set to true, causes all of the
        threads in the process to be suspended prior to the call,
        and resumed upon receipt of a reply.
 
Return Value:
 
    NTSTATUS.
 
--*/
 
{
    NTSTATUS st;
    ULONG_PTR MessageBuffer[PORT_TOTAL_MAXIMUM_MESSAGE_LENGTH/sizeof (ULONG_PTR)];
 
 
    PAGED_CODE();
 
    if ( SuspendProcess ) {
        SuspendProcess = DbgkpSuspendProcess();
    }
 
    ApiMsg->ReturnedStatus = STATUS_PENDING;
 
    PS_SET_BITS (&PsGetCurrentProcess()->Flags, PS_PROCESS_FLAGS_CREATE_REPORTED);
 
    st = LpcRequestWaitReplyPortEx (Port,
                    (PPORT_MESSAGE) ApiMsg,
                    (PPORT_MESSAGE) &MessageBuffer[0]);
 
    ZwFlushInstructionCache(NtCurrentProcess(), NULL, 0);
    if (NT_SUCCESS (st)) {
        RtlCopyMemory(ApiMsg,MessageBuffer,sizeof(*ApiMsg));
    }
 
    if (SuspendProcess) {
        DbgkpResumeProcess();
    }
 
    return st;
}
 
DECLSPEC_NOINLINE
BOOLEAN
DbgkForwardException(
    IN PEXCEPTION_RECORD ExceptionRecord,
    IN BOOLEAN DebugException,
    IN BOOLEAN SecondChance
    )
 
/*++
 
Routine Description:
 
    This function is called forward an exception to the calling process's
    debug or subsystem exception port.
 
Arguments:
 
    ExceptionRecord - Supplies a pointer to an exception record.
 
    DebugException - Supplies a boolean variable that specifies whether
        this exception is to be forwarded to the process's
        DebugPort(TRUE), or to its ExceptionPort(FALSE).
 
Return Value:
 
    TRUE - The process has a DebugPort or an ExceptionPort, and the reply
        received from the port indicated that the exception was handled.
 
    FALSE - The process either does not have a DebugPort or
        ExceptionPort, or the process has a port, but the reply received
        from the port indicated that the exception was not handled.
 
--*/
 
{
    PEPROCESS Process;
    PVOID Port;
    DBGKM_APIMSG m;
    PDBGKM_EXCEPTION args;
    NTSTATUS st;
    BOOLEAN LpcPort;
 
    PAGED_CODE();
 
    args = &m.u.Exception;
 
    //
    // Initialize the debug LPC message with default information.
    //
 
    DBGKM_FORMAT_API_MSG(m,DbgKmExceptionApi,sizeof(*args));
 
    //
    // Get the address of the destination LPC port.
    //
 
    Process = PsGetCurrentProcess();
    if (DebugException) {
        if (PsGetCurrentThread()->CrossThreadFlags&PS_CROSS_THREAD_FLAGS_HIDEFROMDBG) {
            Port = NULL;
        } else {
            Port = Process->DebugPort;
        }
        LpcPort = FALSE;
    } else {
        Port = Process->ExceptionPort;
        m.h.u2.ZeroInit = LPC_EXCEPTION;
        LpcPort = TRUE;
    }
 
    //
    // If the destination LPC port address is NULL, then return FALSE.
    //
 
    if (Port == NULL) {
        return FALSE;
    }
 
    //
    // Fill in the remainder of the debug LPC message.
    //
 
    args->ExceptionRecord = *ExceptionRecord;
    args->FirstChance = !SecondChance;
 
    //
    // Send the debug message to the destination LPC port.
    //
 
    if (LpcPort) {
        st = DbgkpSendApiMessageLpc(&m,Port,DebugException);
    } else {
        st = DbgkpSendApiMessage(&m,DebugException);
    }
 
 
    //
    // If the send was not successful, then return a FALSE indicating that
    // the port did not handle the exception. Otherwise, if the debug port
    // is specified, then look at the return status in the message.
    //
 
    if (!NT_SUCCESS(st) ||
        ((DebugException) &&
        (m.ReturnedStatus == DBG_EXCEPTION_NOT_HANDLED || !NT_SUCCESS(m.ReturnedStatus)))) {
        return FALSE;
 
    } else {
        return TRUE;
    }
}

dbgkport.c

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
/*++
 
Copyright (c) Microsoft Corporation. All rights reserved.
 
You may only use this code if you agree to the terms of the Windows Research Kernel Source Code License agreement (see License.txt).
If you do not agree to the terms, do not use the code.
 
 
Module Name:
 
    dbgkport.c
 
Abstract:
 
    This module implements the dbg primitives to access a process'
    DebugPort and ExceptionPort.
 
--*/
 
#include "dbgkp.h"
 
#ifdef ALLOC_PRAGMA
#pragma alloc_text(PAGE, DbgkpSendApiMessage)
#pragma alloc_text(PAGE, DbgkForwardException)
#pragma alloc_text(PAGE, DbgkpSendApiMessageLpc)
#endif
 
 
NTSTATUS
DbgkpSendApiMessage(
    IN OUT PDBGKM_APIMSG ApiMsg,
    IN BOOLEAN SuspendProcess
    )
 
/*++
 
Routine Description:
 
    This function sends the specified API message over the specified
    port. It is the caller's responsibility to format the API message
    prior to calling this function.
 
    If the SuspendProcess flag is supplied, then all threads in the
    calling process are first suspended. Upon receipt of the reply
    message, the threads are resumed.
 
Arguments:
 
    ApiMsg - Supplies the API message to send.
 
    SuspendProcess - A flag that if set to true, causes all of the
        threads in the process to be suspended prior to the call,
        and resumed upon receipt of a reply.
 
Return Value:
 
    NTSTATUS.
 
--*/
 
{
    NTSTATUS st;
    PEPROCESS Process;
 
    PAGED_CODE();
 
    if ( SuspendProcess ) {
        SuspendProcess = DbgkpSuspendProcess();
    }
 
    ApiMsg->ReturnedStatus = STATUS_PENDING;
 
    Process = PsGetCurrentProcess();
 
    PS_SET_BITS (&Process->Flags, PS_PROCESS_FLAGS_CREATE_REPORTED);
 
    st = DbgkpQueueMessage (Process, PsGetCurrentThread (), ApiMsg, 0, NULL);
 
    ZwFlushInstructionCache (NtCurrentProcess (), NULL, 0);
    if ( SuspendProcess ) {
        DbgkpResumeProcess();
    }
 
    return st;
}
 
NTSTATUS
DbgkpSendApiMessageLpc(
    IN OUT PDBGKM_APIMSG ApiMsg,
    IN PVOID Port,
    IN BOOLEAN SuspendProcess
    )
 
/*++
 
Routine Description:
 
    This function sends the specified API message over the specified
    port. It is the caller's responsibility to format the API message
    prior to calling this function.
 
    If the SuspendProcess flag is supplied, then all threads in the
    calling process are first suspended. Upon receipt of the reply
    message, the threads are resumed.
 
Arguments:
 
    ApiMsg - Supplies the API message to send.
 
    Port - Supplies the address of a port to send the api message.
 
    SuspendProcess - A flag that if set to true, causes all of the
        threads in the process to be suspended prior to the call,
        and resumed upon receipt of a reply.
 
Return Value:
 
    NTSTATUS.
 
--*/
 
{
    NTSTATUS st;
    ULONG_PTR MessageBuffer[PORT_TOTAL_MAXIMUM_MESSAGE_LENGTH/sizeof (ULONG_PTR)];
 
 
    PAGED_CODE();
 
    if ( SuspendProcess ) {
        SuspendProcess = DbgkpSuspendProcess();
    }
 
    ApiMsg->ReturnedStatus = STATUS_PENDING;
 
    PS_SET_BITS (&PsGetCurrentProcess()->Flags, PS_PROCESS_FLAGS_CREATE_REPORTED);
 
    st = LpcRequestWaitReplyPortEx (Port,
                    (PPORT_MESSAGE) ApiMsg,
                    (PPORT_MESSAGE) &MessageBuffer[0]);
 
    ZwFlushInstructionCache(NtCurrentProcess(), NULL, 0);
    if (NT_SUCCESS (st)) {
        RtlCopyMemory(ApiMsg,MessageBuffer,sizeof(*ApiMsg));
    }
 
    if (SuspendProcess) {
        DbgkpResumeProcess();
    }
 
    return st;
}
 
DECLSPEC_NOINLINE
BOOLEAN
DbgkForwardException(
    IN PEXCEPTION_RECORD ExceptionRecord,
    IN BOOLEAN DebugException,
    IN BOOLEAN SecondChance
    )
 
/*++
 
Routine Description:
 
    This function is called forward an exception to the calling process's
    debug or subsystem exception port.
 
Arguments:
 
    ExceptionRecord - Supplies a pointer to an exception record.
 
    DebugException - Supplies a boolean variable that specifies whether
        this exception is to be forwarded to the process's
        DebugPort(TRUE), or to its ExceptionPort(FALSE).
 
Return Value:
 
    TRUE - The process has a DebugPort or an ExceptionPort, and the reply
        received from the port indicated that the exception was handled.
 
    FALSE - The process either does not have a DebugPort or
        ExceptionPort, or the process has a port, but the reply received
        from the port indicated that the exception was not handled.
 
--*/
 
{
    PEPROCESS Process;
    PVOID Port;
    DBGKM_APIMSG m;
    PDBGKM_EXCEPTION args;
    NTSTATUS st;
    BOOLEAN LpcPort;
 
    PAGED_CODE();
 
    args = &m.u.Exception;
 
    //
    // Initialize the debug LPC message with default information.
    //
 
    DBGKM_FORMAT_API_MSG(m,DbgKmExceptionApi,sizeof(*args));
 
    //
    // Get the address of the destination LPC port.
    //
 
    Process = PsGetCurrentProcess();
    if (DebugException) {
        if (PsGetCurrentThread()->CrossThreadFlags&PS_CROSS_THREAD_FLAGS_HIDEFROMDBG) {
            Port = NULL;
        } else {
            Port = Process->DebugPort;
        }
        LpcPort = FALSE;
    } else {
        Port = Process->ExceptionPort;
        m.h.u2.ZeroInit = LPC_EXCEPTION;
        LpcPort = TRUE;
    }
 
    //
    // If the destination LPC port address is NULL, then return FALSE.
    //
 
    if (Port == NULL) {
        return FALSE;
    }
 
    //
    // Fill in the remainder of the debug LPC message.
    //
 
    args->ExceptionRecord = *ExceptionRecord;
    args->FirstChance = !SecondChance;
 
    //
    // Send the debug message to the destination LPC port.
    //
 
    if (LpcPort) {
        st = DbgkpSendApiMessageLpc(&m,Port,DebugException);
    } else {
        st = DbgkpSendApiMessage(&m,DebugException);
    }
 
 
    //
    // If the send was not successful, then return a FALSE indicating that
    // the port did not handle the exception. Otherwise, if the debug port
    // is specified, then look at the return status in the message.
    //
 
    if (!NT_SUCCESS(st) ||
        ((DebugException) &&
        (m.ReturnedStatus == DBG_EXCEPTION_NOT_HANDLED || !NT_SUCCESS(m.ReturnedStatus)))) {
        return FALSE;
 
    } else {
        return TRUE;
    }
}

dbgkpro

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
/*++
 
Copyright (c) Microsoft Corporation. All rights reserved.
 
You may only use this code if you agree to the terms of the Windows Research Kernel Source Code License agreement (see License.txt).
If you do not agree to the terms, do not use the code.
 
 
Module Name:
 
    dbgkproc.c
 
Abstract:
 
    This module implements process control primitives for the
    Dbg component of NT
 
--*/
 
#include "dbgkp.h"
 
#ifdef ALLOC_PRAGMA
#pragma alloc_text(PAGE, DbgkpSuspendProcess)
#pragma alloc_text(PAGE, DbgkpResumeProcess)
#pragma alloc_text(PAGE, DbgkpSectionToFileHandle)
#pragma alloc_text(PAGE, DbgkCreateThread)
#pragma alloc_text(PAGE, DbgkExitThread)
#pragma alloc_text(PAGE, DbgkExitProcess)
#pragma alloc_text(PAGE, DbgkMapViewOfSection)
#pragma alloc_text(PAGE, DbgkUnMapViewOfSection)
#endif
 
                  
 
BOOLEAN
DbgkpSuspendProcess (
    VOID
    )
 
/*++
 
Routine Description:
 
    This function causes all threads in the calling process except for
    the calling thread to suspend.
 
Arguments:
 
    None.
 
Return Value:
 
    None.
 
--*/
 
{
    PAGED_CODE();
 
    //
    // Freeze the execution of all threads in the current process, but the
    // calling thread. If we are in the process of being deleted don't do this.
    //
    if ((PsGetCurrentProcess()->Flags&PS_PROCESS_FLAGS_PROCESS_DELETE) == 0) {
        KeFreezeAllThreads();
        return TRUE;
    }
 
    return FALSE;
}
 
VOID
DbgkpResumeProcess (
    VOID
    )
 
/*++
 
Routine Description:
 
    This function causes all threads in the calling process except for
    the calling thread to resume.
 
Arguments:
 
    None.
 
Return Value:
 
    None.
 
--*/
 
{
 
    PAGED_CODE();
 
    //
    // Thaw the execution of all threads in the current process, but
    // the calling thread.
    //
 
    KeThawAllThreads();
 
    return;
}
 
HANDLE
DbgkpSectionToFileHandle(
    IN PVOID SectionObject
    )
 
/*++
 
Routine Description:
 
    This function opens a handle to the file associated with the processes
    section. The file is opened such that it can be duplicated all the way to
    the UI where the UI can either map the file or read the file to get
    the debug info.
 
Arguments:
 
    SectionObject - Supplies the section whose associated file is to be opened.
 
Return Value:
 
    NULL - The file could not be opened.
 
    NON-NULL - Returns a handle to the file associated with the specified
        section.
 
--*/
 
{
    NTSTATUS Status;
    OBJECT_ATTRIBUTES Obja;
    IO_STATUS_BLOCK IoStatusBlock;
    HANDLE Handle;
    POBJECT_NAME_INFORMATION FileNameInfo;
 
    PAGED_CODE();
 
    Status = MmGetFileNameForSection(SectionObject, &FileNameInfo);
    if ( !NT_SUCCESS(Status) ) {
        return NULL;
    }
 
    InitializeObjectAttributes(
        &Obja,
        &FileNameInfo->Name,
        OBJ_CASE_INSENSITIVE | OBJ_FORCE_ACCESS_CHECK | OBJ_KERNEL_HANDLE,
        NULL,
        NULL
        );
 
    Status = ZwOpenFile(
                &Handle,
                (ACCESS_MASK)(GENERIC_READ | SYNCHRONIZE),
                &Obja,
                &IoStatusBlock,
                FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
                FILE_SYNCHRONOUS_IO_NONALERT
                );
    ExFreePool(FileNameInfo);
    if ( !NT_SUCCESS(Status) ) {
        return NULL;
    } else {
        return Handle;
    }
}
 
 
VOID
DbgkCreateThread(
    PETHREAD Thread,
    PVOID StartAddress
    )
 
/*++
 
Routine Description:
 
    This function is called when a new thread begins to execute. If the
    thread has an associated DebugPort, then a message is sent thru the
    port.
 
    If this thread is the first thread in the process, then this event
    is translated into a CreateProcessInfo message.
 
    If a message is sent, then while the thread is awaiting a reply,
    all other threads in the process are suspended.
 
Arguments:
 
    Thread - New thread just being started
 
    StartAddress - Supplies the start address for the thread that is
        starting.
 
Return Value:
 
    None.
 
--*/
 
{
    PVOID Port;
    DBGKM_APIMSG m;
    PDBGKM_CREATE_THREAD CreateThreadArgs;
    PDBGKM_CREATE_PROCESS CreateProcessArgs;
    PEPROCESS Process;
    PDBGKM_LOAD_DLL LoadDllArgs;
    NTSTATUS Status;
    OBJECT_ATTRIBUTES Obja;
    IO_STATUS_BLOCK IoStatusBlock;
    PIMAGE_NT_HEADERS NtHeaders;
    PTEB Teb;
    ULONG OldFlags;
#if defined(_WIN64)
    PVOID Wow64Process;
#endif
 
    PAGED_CODE();
 
    Process = PsGetCurrentProcessByThread (Thread);
 
#if defined(_WIN64)
    Wow64Process = Process->Wow64Process;
#endif
 
    OldFlags = PS_TEST_SET_BITS (&Process->Flags, PS_PROCESS_FLAGS_CREATE_REPORTED|PS_PROCESS_FLAGS_IMAGE_NOTIFY_DONE);
 
    if ((OldFlags&PS_PROCESS_FLAGS_IMAGE_NOTIFY_DONE) == 0 && PsImageNotifyEnabled) {
        IMAGE_INFO ImageInfo;
        UNICODE_STRING UnicodeFileName;
        POBJECT_NAME_INFORMATION FileNameInfo;
 
        //
        // notification of main .exe
        //
        ImageInfo.Properties = 0;
        ImageInfo.ImageAddressingMode = IMAGE_ADDRESSING_MODE_32BIT;
        ImageInfo.ImageBase = Process->SectionBaseAddress;
        ImageInfo.ImageSize = 0;
 
        try {
            NtHeaders = RtlImageNtHeader (Process->SectionBaseAddress);
     
            if (NtHeaders) {
#if defined(_WIN64)
                if (Wow64Process != NULL) {
                    ImageInfo.ImageSize = DBGKP_FIELD_FROM_IMAGE_OPTIONAL_HEADER ((PIMAGE_NT_HEADERS32)NtHeaders, SizeOfImage);
                } else {
#endif
                    ImageInfo.ImageSize = DBGKP_FIELD_FROM_IMAGE_OPTIONAL_HEADER (NtHeaders, SizeOfImage);
#if defined(_WIN64)
                }
#endif
            }
        } except (EXCEPTION_EXECUTE_HANDLER) {
            ImageInfo.ImageSize = 0;
        }
        ImageInfo.ImageSelector = 0;
        ImageInfo.ImageSectionNumber = 0;
 
        Status = MmGetFileNameForSection (Process->SectionObject, &FileNameInfo);
        if (FileNameInfo != NULL) {
            PsCallImageNotifyRoutines (&FileNameInfo->Name,
                                       Process->UniqueProcessId,
                                       &ImageInfo);
            ExFreePool (FileNameInfo);
        } else {
            PsCallImageNotifyRoutines (NULL,
                                       Process->UniqueProcessId,
                                       &ImageInfo);
        }
 
        //
        // and of ntdll.dll
        //
        ImageInfo.Properties = 0;
        ImageInfo.ImageAddressingMode = IMAGE_ADDRESSING_MODE_32BIT;
        ImageInfo.ImageBase = PsSystemDllBase;
        ImageInfo.ImageSize = 0;
 
        try {
            NtHeaders = RtlImageNtHeader (PsSystemDllBase);
            if ( NtHeaders ) {
#if defined(_WIN64)
                if (Wow64Process != NULL) {
                    ImageInfo.ImageSize = DBGKP_FIELD_FROM_IMAGE_OPTIONAL_HEADER ((PIMAGE_NT_HEADERS32)NtHeaders, SizeOfImage);
                } else {
#endif
                    ImageInfo.ImageSize = DBGKP_FIELD_FROM_IMAGE_OPTIONAL_HEADER (NtHeaders, SizeOfImage);
#if defined(_WIN64)
                }
#endif
            }
        } except(EXCEPTION_EXECUTE_HANDLER) {
            ImageInfo.ImageSize = 0;
        }
 
        ImageInfo.ImageSelector = 0;
        ImageInfo.ImageSectionNumber = 0;
 
        RtlInitUnicodeString (&UnicodeFileName,
                              L"\\SystemRoot\\System32\\ntdll.dll");
        PsCallImageNotifyRoutines (&UnicodeFileName,
                                   Process->UniqueProcessId,
                                   &ImageInfo);
    }
 
 
    Port = Process->DebugPort;
 
    if (Port == NULL) {
        return;
    }
 
    //
    // Make sure we only get one create process message
    //
 
    if ((OldFlags&PS_PROCESS_FLAGS_CREATE_REPORTED) == 0) {
 
        //
        // This is a create process
        //
 
        CreateThreadArgs = &m.u.CreateProcessInfo.InitialThread;
        CreateThreadArgs->SubSystemKey = 0;
 
        CreateProcessArgs = &m.u.CreateProcessInfo;
        CreateProcessArgs->SubSystemKey = 0;
        CreateProcessArgs->FileHandle = DbgkpSectionToFileHandle(
                                            Process->SectionObject
                                            );
        CreateProcessArgs->BaseOfImage = Process->SectionBaseAddress;
        CreateThreadArgs->StartAddress = NULL;
        CreateProcessArgs->DebugInfoFileOffset = 0;
        CreateProcessArgs->DebugInfoSize = 0;
 
        try {
                         
            NtHeaders = RtlImageNtHeader(Process->SectionBaseAddress);
 
            if ( NtHeaders ) {
 
#if defined(_WIN64)
                if (Wow64Process != NULL) {
                    CreateThreadArgs->StartAddress = UlongToPtr (DBGKP_FIELD_FROM_IMAGE_OPTIONAL_HEADER ((PIMAGE_NT_HEADERS32)NtHeaders, ImageBase) +
                        DBGKP_FIELD_FROM_IMAGE_OPTIONAL_HEADER ((PIMAGE_NT_HEADERS32)NtHeaders, AddressOfEntryPoint));
                } else {
#endif
                    CreateThreadArgs->StartAddress = (PVOID) (DBGKP_FIELD_FROM_IMAGE_OPTIONAL_HEADER (NtHeaders, ImageBase) +
                        DBGKP_FIELD_FROM_IMAGE_OPTIONAL_HEADER (NtHeaders, AddressOfEntryPoint));
#if defined(_WIN64)
                }
#endif
 
                //
                // The following fields are safe for Wow64 as the offsets
                // are the same for a PE32+ as a PE32 header.
                //
                 
                CreateProcessArgs->DebugInfoFileOffset = NtHeaders->FileHeader.PointerToSymbolTable;
                CreateProcessArgs->DebugInfoSize = NtHeaders->FileHeader.NumberOfSymbols;
            }
        } except (EXCEPTION_EXECUTE_HANDLER) {
            CreateThreadArgs->StartAddress = NULL;
            CreateProcessArgs->DebugInfoFileOffset = 0;
            CreateProcessArgs->DebugInfoSize = 0;
        }
 
        DBGKM_FORMAT_API_MSG(m,DbgKmCreateProcessApi,sizeof(*CreateProcessArgs));
 
        DbgkpSendApiMessage(&m,FALSE);
 
        if (CreateProcessArgs->FileHandle != NULL) {
            ObCloseHandle(CreateProcessArgs->FileHandle, KernelMode);
        }
 
        LoadDllArgs = &m.u.LoadDll;
        LoadDllArgs->BaseOfDll = PsSystemDllBase;
        LoadDllArgs->DebugInfoFileOffset = 0;
        LoadDllArgs->DebugInfoSize = 0;
        LoadDllArgs->NamePointer = NULL;
 
        Teb = NULL;
        try {
            NtHeaders = RtlImageNtHeader(PsSystemDllBase);
            if ( NtHeaders ) {
                LoadDllArgs->DebugInfoFileOffset = NtHeaders->FileHeader.PointerToSymbolTable;
                LoadDllArgs->DebugInfoSize = NtHeaders->FileHeader.NumberOfSymbols;
            }
 
            //
            // Normaly the ntdll loaded fills in this pointer for the debug API's. We fake it here
            // as ntdll isn't loaded yet and it can't load itself.
            //
 
            Teb = Thread->Tcb.Teb;
            if (Teb != NULL) {
                wcsncpy (Teb->StaticUnicodeBuffer,
                         L"ntdll.dll",
                         sizeof (Teb->StaticUnicodeBuffer) / sizeof (Teb->StaticUnicodeBuffer[0]));
                Teb->NtTib.ArbitraryUserPointer = Teb->StaticUnicodeBuffer;
                LoadDllArgs->NamePointer = &Teb->NtTib.ArbitraryUserPointer;
            }
             
        } except (EXCEPTION_EXECUTE_HANDLER) {
            LoadDllArgs->DebugInfoFileOffset = 0;
            LoadDllArgs->DebugInfoSize = 0;
            LoadDllArgs->NamePointer = NULL;
        }
 
        //
        // Send load dll section for NT dll !
        //
 
        InitializeObjectAttributes(
            &Obja,
            (PUNICODE_STRING)&PsNtDllPathName,
            OBJ_CASE_INSENSITIVE | OBJ_FORCE_ACCESS_CHECK | OBJ_KERNEL_HANDLE,
            NULL,
            NULL
            );
 
        Status = ZwOpenFile(
                    &LoadDllArgs->FileHandle,
                    (ACCESS_MASK)(GENERIC_READ | SYNCHRONIZE),
                    &Obja,
                    &IoStatusBlock,
                    FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
                    FILE_SYNCHRONOUS_IO_NONALERT
                    );
 
        if (!NT_SUCCESS (Status)) {
            LoadDllArgs->FileHandle = NULL;
        }
 
        DBGKM_FORMAT_API_MSG(m,DbgKmLoadDllApi,sizeof(*LoadDllArgs));
        DbgkpSendApiMessage(&m,TRUE);
 
        if (LoadDllArgs->FileHandle != NULL) {
            ObCloseHandle(LoadDllArgs->FileHandle, KernelMode);
        }
 
        try {
            if (Teb != NULL) {
                Teb->NtTib.ArbitraryUserPointer = NULL;
            }
        } except (EXCEPTION_EXECUTE_HANDLER) {
        }
 
    } else {
 
        CreateThreadArgs = &m.u.CreateThread;
        CreateThreadArgs->SubSystemKey = 0;
        CreateThreadArgs->StartAddress = StartAddress;
 
        DBGKM_FORMAT_API_MSG (m,DbgKmCreateThreadApi,sizeof(*CreateThreadArgs));
 
        DbgkpSendApiMessage (&m,TRUE);
    }
}
 
VOID
DbgkExitThread(
    NTSTATUS ExitStatus
    )
 
/*++
 
Routine Description:
 
    This function is called when a new thread terminates. At this
    point, the thread will no longer execute in user-mode. No other
    exit processing has occured.
 
    If a message is sent, then while the thread is awaiting a reply,
    all other threads in the process are suspended.
 
Arguments:
 
    ExitStatus - Supplies the ExitStatus of the exiting thread.
 
Return Value:
 
    None.
 
--*/
 
{
    PVOID Port;
    DBGKM_APIMSG m;
    PDBGKM_EXIT_THREAD args;
    PEPROCESS Process;
    BOOLEAN Frozen;
 
    PAGED_CODE();
 
    Process = PsGetCurrentProcess();
    if (PsGetCurrentThread()->CrossThreadFlags&PS_CROSS_THREAD_FLAGS_HIDEFROMDBG) {
        Port = NULL;
    } else {
        Port = Process->DebugPort;
    }
 
    if ( !Port ) {
        return;
    }
 
    if (PsGetCurrentThread()->CrossThreadFlags&PS_CROSS_THREAD_FLAGS_DEADTHREAD) {
        return;
    }
 
    args = &m.u.ExitThread;
    args->ExitStatus = ExitStatus;
 
    DBGKM_FORMAT_API_MSG(m,DbgKmExitThreadApi,sizeof(*args));
 
    Frozen = DbgkpSuspendProcess();
 
    DbgkpSendApiMessage(&m,FALSE);
 
    if (Frozen) {
        DbgkpResumeProcess();
    }
}
 
VOID
DbgkExitProcess(
    NTSTATUS ExitStatus
    )
 
/*++
 
Routine Description:
 
    This function is called when a process terminates. The address
    space of the process is still intact, but no threads exist in
    the process.
 
Arguments:
 
    ExitStatus - Supplies the ExitStatus of the exiting process.
 
Return Value:
 
    None.
 
--*/
 
{
    PVOID Port;
    DBGKM_APIMSG m;
    PDBGKM_EXIT_PROCESS args;
    PEPROCESS Process;
 
    PAGED_CODE();
 
    Process = PsGetCurrentProcess();
 
    if (PsGetCurrentThread()->CrossThreadFlags&PS_CROSS_THREAD_FLAGS_HIDEFROMDBG) {
        Port = NULL;
    } else {
        Port = Process->DebugPort;
    }
 
    if ( !Port ) {
        return;
    }
 
    if (PsGetCurrentThread()->CrossThreadFlags&PS_CROSS_THREAD_FLAGS_DEADTHREAD) {
        return;
    }
 
    //
    // this ensures that other timed lockers of the process will bail
    // since this call is done while holding the process lock, and lock duration
    // is controlled by debugger
    //
    KeQuerySystemTime(&Process->ExitTime);
 
    args = &m.u.ExitProcess;
    args->ExitStatus = ExitStatus;
 
    DBGKM_FORMAT_API_MSG(m,DbgKmExitProcessApi,sizeof(*args));
 
    DbgkpSendApiMessage(&m,FALSE);
 
}
 
VOID
DbgkMapViewOfSection(
    IN PVOID SectionObject,
    IN PVOID BaseAddress,
    IN ULONG SectionOffset,
    IN ULONG_PTR ViewSize
    )
 
/*++
 
Routine Description:
 
    This function is called when the current process successfully
    maps a view of an image section. If the process has an associated
    debug port, then a load dll message is sent.
 
Arguments:
 
    SectionObject - Supplies a pointer to the section mapped by the
        process.
 
    BaseAddress - Supplies the base address of where the section is
        mapped in the current process address space.
 
    SectionOffset - Supplies the offset in the section where the
        process' mapped view begins.
 
    ViewSize - Supplies the size of the mapped view.
 
Return Value:
 
    None.
 
--*/
 
{
 
    PVOID Port;
    DBGKM_APIMSG m;
    PDBGKM_LOAD_DLL LoadDllArgs;
    PEPROCESS Process;
    PIMAGE_NT_HEADERS NtHeaders;
 
    PAGED_CODE();
 
    UNREFERENCED_PARAMETER (SectionOffset);
    UNREFERENCED_PARAMETER (ViewSize);
 
    if ( KeGetPreviousMode() == KernelMode ) {
        return;
    }
 
    Process = PsGetCurrentProcess();
 
    if (PsGetCurrentThread()->CrossThreadFlags&PS_CROSS_THREAD_FLAGS_HIDEFROMDBG) {
        Port = NULL;
    } else {
        Port = Process->DebugPort;
    }
 
    if ( !Port ) {
        return;
    }
 
    LoadDllArgs = &m.u.LoadDll;
    LoadDllArgs->FileHandle = DbgkpSectionToFileHandle(SectionObject);
    LoadDllArgs->BaseOfDll = BaseAddress;
    LoadDllArgs->DebugInfoFileOffset = 0;
    LoadDllArgs->DebugInfoSize = 0;
 
    //
    // The loader fills in the module name in this pointer before mapping
    // the section.  It's a very poor linkage.
    //
 
    LoadDllArgs->NamePointer = &NtCurrentTeb()->NtTib.ArbitraryUserPointer;
 
    try {
 
        NtHeaders = RtlImageNtHeader (BaseAddress);
 
        if (NtHeaders != NULL) {
            LoadDllArgs->DebugInfoFileOffset = NtHeaders->FileHeader.PointerToSymbolTable;
            LoadDllArgs->DebugInfoSize = NtHeaders->FileHeader.NumberOfSymbols;
        }
 
    } except (EXCEPTION_EXECUTE_HANDLER) {
 
        LoadDllArgs->DebugInfoFileOffset = 0;
        LoadDllArgs->DebugInfoSize = 0;
        LoadDllArgs->NamePointer = NULL;
 
    }
 
    DBGKM_FORMAT_API_MSG(m,DbgKmLoadDllApi,sizeof(*LoadDllArgs));
 
    DbgkpSendApiMessage(&m,TRUE);
    if (LoadDllArgs->FileHandle != NULL) {
        ObCloseHandle(LoadDllArgs->FileHandle, KernelMode);
    }
}
 
VOID
DbgkUnMapViewOfSection(
    IN PVOID BaseAddress
    )
 
/*++
 
Routine Description:
 
    This function is called when the current process successfully
    un maps a view of an image section. If the process has an associated
    debug port, then an "unmap view of section" message is sent.
 
Arguments:
 
    BaseAddress - Supplies the base address of the section being unmapped.
 
Return Value:
 
    None.
 
--*/
 
{
 
    PVOID Port;
    DBGKM_APIMSG m;
    PDBGKM_UNLOAD_DLL UnloadDllArgs;
 
    PAGED_CODE();
 
    if ( KeGetPreviousMode() == KernelMode ) {
        return;
    }
 
    if (PsGetCurrentThread()->CrossThreadFlags&PS_CROSS_THREAD_FLAGS_HIDEFROMDBG) {
        Port = NULL;
    } else {
        Port = PsGetCurrentProcess()->DebugPort;
    }
 
    if ( !Port ) {
        return;
    }
 
    UnloadDllArgs = &m.u.UnloadDll;
    UnloadDllArgs->BaseAddress = BaseAddress;
 
    DBGKM_FORMAT_API_MSG(m,DbgKmUnloadDllApi,sizeof(*UnloadDllArgs));
 
    DbgkpSendApiMessage(&m,TRUE);
}

exception

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
/*++
 
Copyright (c) Microsoft Corporation. All rights reserved.
 
You may only use this code if you agree to the terms of the Windows Research Kernel Source Code License agreement (see License.txt).
If you do not agree to the terms, do not use the code.
 
 
Module Name:
 
    dbgkproc.c
 
Abstract:
 
    This module implements process control primitives for the
    Dbg component of NT
 
--*/
 
#include "dbgkp.h"
 
#ifdef ALLOC_PRAGMA
#pragma alloc_text(PAGE, DbgkpSuspendProcess)
#pragma alloc_text(PAGE, DbgkpResumeProcess)
#pragma alloc_text(PAGE, DbgkpSectionToFileHandle)
#pragma alloc_text(PAGE, DbgkCreateThread)
#pragma alloc_text(PAGE, DbgkExitThread)
#pragma alloc_text(PAGE, DbgkExitProcess)
#pragma alloc_text(PAGE, DbgkMapViewOfSection)
#pragma alloc_text(PAGE, DbgkUnMapViewOfSection)
#endif
 
                  
 
BOOLEAN
DbgkpSuspendProcess (
    VOID
    )
 
/*++
 
Routine Description:
 
    This function causes all threads in the calling process except for
    the calling thread to suspend.
 
Arguments:
 
    None.
 
Return Value:
 
    None.
 
--*/
 
{
    PAGED_CODE();
 
    //
    // Freeze the execution of all threads in the current process, but the
    // calling thread. If we are in the process of being deleted don't do this.
    //
    if ((PsGetCurrentProcess()->Flags&PS_PROCESS_FLAGS_PROCESS_DELETE) == 0) {
        KeFreezeAllThreads();
        return TRUE;
    }
 
    return FALSE;
}
 
VOID
DbgkpResumeProcess (
    VOID
    )
 
/*++
 
Routine Description:
 
    This function causes all threads in the calling process except for
    the calling thread to resume.
 
Arguments:
 
    None.
 
Return Value:
 
    None.
 
--*/
 
{
 
    PAGED_CODE();
 
    //
    // Thaw the execution of all threads in the current process, but
    // the calling thread.
    //
 
    KeThawAllThreads();
 
    return;
}
 
HANDLE
DbgkpSectionToFileHandle(
    IN PVOID SectionObject
    )
 
/*++
 
Routine Description:
 
    This function opens a handle to the file associated with the processes
    section. The file is opened such that it can be duplicated all the way to
    the UI where the UI can either map the file or read the file to get
    the debug info.
 
Arguments:
 
    SectionObject - Supplies the section whose associated file is to be opened.
 
Return Value:
 
    NULL - The file could not be opened.
 
    NON-NULL - Returns a handle to the file associated with the specified
        section.
 
--*/
 
{
    NTSTATUS Status;
    OBJECT_ATTRIBUTES Obja;
    IO_STATUS_BLOCK IoStatusBlock;
    HANDLE Handle;
    POBJECT_NAME_INFORMATION FileNameInfo;
 
    PAGED_CODE();
 
    Status = MmGetFileNameForSection(SectionObject, &FileNameInfo);
    if ( !NT_SUCCESS(Status) ) {
        return NULL;
    }
 
    InitializeObjectAttributes(
        &Obja,
        &FileNameInfo->Name,
        OBJ_CASE_INSENSITIVE | OBJ_FORCE_ACCESS_CHECK | OBJ_KERNEL_HANDLE,
        NULL,
        NULL
        );
 
    Status = ZwOpenFile(
                &Handle,
                (ACCESS_MASK)(GENERIC_READ | SYNCHRONIZE),
                &Obja,
                &IoStatusBlock,
                FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
                FILE_SYNCHRONOUS_IO_NONALERT
                );
    ExFreePool(FileNameInfo);
    if ( !NT_SUCCESS(Status) ) {
        return NULL;
    } else {
        return Handle;
    }
}
 
 
VOID
DbgkCreateThread(
    PETHREAD Thread,
    PVOID StartAddress
    )
 
/*++
 
Routine Description:
 
    This function is called when a new thread begins to execute. If the
    thread has an associated DebugPort, then a message is sent thru the
    port.
 
    If this thread is the first thread in the process, then this event
    is translated into a CreateProcessInfo message.
 
    If a message is sent, then while the thread is awaiting a reply,
    all other threads in the process are suspended.
 
Arguments:
 
    Thread - New thread just being started
 
    StartAddress - Supplies the start address for the thread that is
        starting.
 
Return Value:
 
    None.
 
--*/
 
{
    PVOID Port;
    DBGKM_APIMSG m;
    PDBGKM_CREATE_THREAD CreateThreadArgs;
    PDBGKM_CREATE_PROCESS CreateProcessArgs;
    PEPROCESS Process;
    PDBGKM_LOAD_DLL LoadDllArgs;
    NTSTATUS Status;
    OBJECT_ATTRIBUTES Obja;
    IO_STATUS_BLOCK IoStatusBlock;
    PIMAGE_NT_HEADERS NtHeaders;
    PTEB Teb;
    ULONG OldFlags;
#if defined(_WIN64)
    PVOID Wow64Process;
#endif
 
    PAGED_CODE();
 
    Process = PsGetCurrentProcessByThread (Thread);
 
#if defined(_WIN64)
    Wow64Process = Process->Wow64Process;
#endif
 
    OldFlags = PS_TEST_SET_BITS (&Process->Flags, PS_PROCESS_FLAGS_CREATE_REPORTED|PS_PROCESS_FLAGS_IMAGE_NOTIFY_DONE);
 
    if ((OldFlags&PS_PROCESS_FLAGS_IMAGE_NOTIFY_DONE) == 0 && PsImageNotifyEnabled) {
        IMAGE_INFO ImageInfo;
        UNICODE_STRING UnicodeFileName;
        POBJECT_NAME_INFORMATION FileNameInfo;
 
        //
        // notification of main .exe
        //
        ImageInfo.Properties = 0;
        ImageInfo.ImageAddressingMode = IMAGE_ADDRESSING_MODE_32BIT;
        ImageInfo.ImageBase = Process->SectionBaseAddress;
        ImageInfo.ImageSize = 0;
 
        try {
            NtHeaders = RtlImageNtHeader (Process->SectionBaseAddress);
     
            if (NtHeaders) {
#if defined(_WIN64)
                if (Wow64Process != NULL) {
                    ImageInfo.ImageSize = DBGKP_FIELD_FROM_IMAGE_OPTIONAL_HEADER ((PIMAGE_NT_HEADERS32)NtHeaders, SizeOfImage);
                } else {
#endif
                    ImageInfo.ImageSize = DBGKP_FIELD_FROM_IMAGE_OPTIONAL_HEADER (NtHeaders, SizeOfImage);
#if defined(_WIN64)
                }
#endif
            }
        } except (EXCEPTION_EXECUTE_HANDLER) {
            ImageInfo.ImageSize = 0;
        }
        ImageInfo.ImageSelector = 0;
        ImageInfo.ImageSectionNumber = 0;
 
        Status = MmGetFileNameForSection (Process->SectionObject, &FileNameInfo);
        if (FileNameInfo != NULL) {
            PsCallImageNotifyRoutines (&FileNameInfo->Name,
                                       Process->UniqueProcessId,
                                       &ImageInfo);
            ExFreePool (FileNameInfo);
        } else {
            PsCallImageNotifyRoutines (NULL,
                                       Process->UniqueProcessId,
                                       &ImageInfo);
        }
 
        //
        // and of ntdll.dll
        //
        ImageInfo.Properties = 0;
        ImageInfo.ImageAddressingMode = IMAGE_ADDRESSING_MODE_32BIT;
        ImageInfo.ImageBase = PsSystemDllBase;
        ImageInfo.ImageSize = 0;
 
        try {
            NtHeaders = RtlImageNtHeader (PsSystemDllBase);
            if ( NtHeaders ) {
#if defined(_WIN64)
                if (Wow64Process != NULL) {
                    ImageInfo.ImageSize = DBGKP_FIELD_FROM_IMAGE_OPTIONAL_HEADER ((PIMAGE_NT_HEADERS32)NtHeaders, SizeOfImage);
                } else {
#endif
                    ImageInfo.ImageSize = DBGKP_FIELD_FROM_IMAGE_OPTIONAL_HEADER (NtHeaders, SizeOfImage);
#if defined(_WIN64)
                }
#endif
            }
        } except(EXCEPTION_EXECUTE_HANDLER) {
            ImageInfo.ImageSize = 0;
        }
 
        ImageInfo.ImageSelector = 0;
        ImageInfo.ImageSectionNumber = 0;
 
        RtlInitUnicodeString (&UnicodeFileName,
                              L"\\SystemRoot\\System32\\ntdll.dll");
        PsCallImageNotifyRoutines (&UnicodeFileName,
                                   Process->UniqueProcessId,
                                   &ImageInfo);
    }
 
 
    Port = Process->DebugPort;
 
    if (Port == NULL) {
        return;
    }
 
    //
    // Make sure we only get one create process message
    //
 
    if ((OldFlags&PS_PROCESS_FLAGS_CREATE_REPORTED) == 0) {
 
        //
        // This is a create process
        //
 
        CreateThreadArgs = &m.u.CreateProcessInfo.InitialThread;
        CreateThreadArgs->SubSystemKey = 0;
 
        CreateProcessArgs = &m.u.CreateProcessInfo;
        CreateProcessArgs->SubSystemKey = 0;
        CreateProcessArgs->FileHandle = DbgkpSectionToFileHandle(
                                            Process->SectionObject
                                            );
        CreateProcessArgs->BaseOfImage = Process->SectionBaseAddress;
        CreateThreadArgs->StartAddress = NULL;
        CreateProcessArgs->DebugInfoFileOffset = 0;
        CreateProcessArgs->DebugInfoSize = 0;
 
        try {
                         
            NtHeaders = RtlImageNtHeader(Process->SectionBaseAddress);
 
            if ( NtHeaders ) {
 
#if defined(_WIN64)
                if (Wow64Process != NULL) {
                    CreateThreadArgs->StartAddress = UlongToPtr (DBGKP_FIELD_FROM_IMAGE_OPTIONAL_HEADER ((PIMAGE_NT_HEADERS32)NtHeaders, ImageBase) +
                        DBGKP_FIELD_FROM_IMAGE_OPTIONAL_HEADER ((PIMAGE_NT_HEADERS32)NtHeaders, AddressOfEntryPoint));
                } else {
#endif
                    CreateThreadArgs->StartAddress = (PVOID) (DBGKP_FIELD_FROM_IMAGE_OPTIONAL_HEADER (NtHeaders, ImageBase) +
                        DBGKP_FIELD_FROM_IMAGE_OPTIONAL_HEADER (NtHeaders, AddressOfEntryPoint));
#if defined(_WIN64)
                }
#endif
 
                //
                // The following fields are safe for Wow64 as the offsets
                // are the same for a PE32+ as a PE32 header.
                //
                 
                CreateProcessArgs->DebugInfoFileOffset = NtHeaders->FileHeader.PointerToSymbolTable;
                CreateProcessArgs->DebugInfoSize = NtHeaders->FileHeader.NumberOfSymbols;
            }
        } except (EXCEPTION_EXECUTE_HANDLER) {
            CreateThreadArgs->StartAddress = NULL;
            CreateProcessArgs->DebugInfoFileOffset = 0;
            CreateProcessArgs->DebugInfoSize = 0;
        }
 
        DBGKM_FORMAT_API_MSG(m,DbgKmCreateProcessApi,sizeof(*CreateProcessArgs));
 
        DbgkpSendApiMessage(&m,FALSE);
 
        if (CreateProcessArgs->FileHandle != NULL) {
            ObCloseHandle(CreateProcessArgs->FileHandle, KernelMode);
        }
 
        LoadDllArgs = &m.u.LoadDll;
        LoadDllArgs->BaseOfDll = PsSystemDllBase;
        LoadDllArgs->DebugInfoFileOffset = 0;
        LoadDllArgs->DebugInfoSize = 0;
        LoadDllArgs->NamePointer = NULL;
 
        Teb = NULL;
        try {
            NtHeaders = RtlImageNtHeader(PsSystemDllBase);
            if ( NtHeaders ) {
                LoadDllArgs->DebugInfoFileOffset = NtHeaders->FileHeader.PointerToSymbolTable;
                LoadDllArgs->DebugInfoSize = NtHeaders->FileHeader.NumberOfSymbols;
            }
 
            //
            // Normaly the ntdll loaded fills in this pointer for the debug API's. We fake it here
            // as ntdll isn't loaded yet and it can't load itself.
            //
 
            Teb = Thread->Tcb.Teb;
            if (Teb != NULL) {
                wcsncpy (Teb->StaticUnicodeBuffer,
                         L"ntdll.dll",
                         sizeof (Teb->StaticUnicodeBuffer) / sizeof (Teb->StaticUnicodeBuffer[0]));
                Teb->NtTib.ArbitraryUserPointer = Teb->StaticUnicodeBuffer;
                LoadDllArgs->NamePointer = &Teb->NtTib.ArbitraryUserPointer;
            }
             
        } except (EXCEPTION_EXECUTE_HANDLER) {
            LoadDllArgs->DebugInfoFileOffset = 0;
            LoadDllArgs->DebugInfoSize = 0;
            LoadDllArgs->NamePointer = NULL;
        }
 
        //
        // Send load dll section for NT dll !
        //
 
        InitializeObjectAttributes(
            &Obja,
            (PUNICODE_STRING)&PsNtDllPathName,
            OBJ_CASE_INSENSITIVE | OBJ_FORCE_ACCESS_CHECK | OBJ_KERNEL_HANDLE,
            NULL,
            NULL
            );
 
        Status = ZwOpenFile(
                    &LoadDllArgs->FileHandle,
                    (ACCESS_MASK)(GENERIC_READ | SYNCHRONIZE),
                    &Obja,
                    &IoStatusBlock,
                    FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
                    FILE_SYNCHRONOUS_IO_NONALERT
                    );
 
        if (!NT_SUCCESS (Status)) {
            LoadDllArgs->FileHandle = NULL;
        }
 
        DBGKM_FORMAT_API_MSG(m,DbgKmLoadDllApi,sizeof(*LoadDllArgs));
        DbgkpSendApiMessage(&m,TRUE);
 
        if (LoadDllArgs->FileHandle != NULL) {
            ObCloseHandle(LoadDllArgs->FileHandle, KernelMode);
        }
 
        try {
            if (Teb != NULL) {
                Teb->NtTib.ArbitraryUserPointer = NULL;
            }
        } except (EXCEPTION_EXECUTE_HANDLER) {
        }
 
    } else {
 
        CreateThreadArgs = &m.u.CreateThread;
        CreateThreadArgs->SubSystemKey = 0;
        CreateThreadArgs->StartAddress = StartAddress;
 
        DBGKM_FORMAT_API_MSG (m,DbgKmCreateThreadApi,sizeof(*CreateThreadArgs));
 
        DbgkpSendApiMessage (&m,TRUE);
    }
}
 
VOID
DbgkExitThread(
    NTSTATUS ExitStatus
    )
 
/*++
 
Routine Description:
 
    This function is called when a new thread terminates. At this
    point, the thread will no longer execute in user-mode. No other
    exit processing has occured.
 
    If a message is sent, then while the thread is awaiting a reply,
    all other threads in the process are suspended.
 
Arguments:
 
    ExitStatus - Supplies the ExitStatus of the exiting thread.
 
Return Value:
 
    None.
 
--*/
 
{
    PVOID Port;
    DBGKM_APIMSG m;
    PDBGKM_EXIT_THREAD args;
    PEPROCESS Process;
    BOOLEAN Frozen;
 
    PAGED_CODE();
 
    Process = PsGetCurrentProcess();
    if (PsGetCurrentThread()->CrossThreadFlags&PS_CROSS_THREAD_FLAGS_HIDEFROMDBG) {
        Port = NULL;
    } else {
        Port = Process->DebugPort;
    }
 
    if ( !Port ) {
        return;
    }
 
    if (PsGetCurrentThread()->CrossThreadFlags&PS_CROSS_THREAD_FLAGS_DEADTHREAD) {
        return;
    }
 
    args = &m.u.ExitThread;
    args->ExitStatus = ExitStatus;
 
    DBGKM_FORMAT_API_MSG(m,DbgKmExitThreadApi,sizeof(*args));
 
    Frozen = DbgkpSuspendProcess();
 
    DbgkpSendApiMessage(&m,FALSE);
 
    if (Frozen) {
        DbgkpResumeProcess();
    }
}
 
VOID
DbgkExitProcess(
    NTSTATUS ExitStatus
    )
 
/*++
 
Routine Description:
 
    This function is called when a process terminates. The address
    space of the process is still intact, but no threads exist in
    the process.
 
Arguments:
 
    ExitStatus - Supplies the ExitStatus of the exiting process.
 
Return Value:
 
    None.
 
--*/
 
{
    PVOID Port;
    DBGKM_APIMSG m;
    PDBGKM_EXIT_PROCESS args;
    PEPROCESS Process;
 
    PAGED_CODE();
 
    Process = PsGetCurrentProcess();
 
    if (PsGetCurrentThread()->CrossThreadFlags&PS_CROSS_THREAD_FLAGS_HIDEFROMDBG) {
        Port = NULL;
    } else {
        Port = Process->DebugPort;
    }
 
    if ( !Port ) {
        return;
    }
 
    if (PsGetCurrentThread()->CrossThreadFlags&PS_CROSS_THREAD_FLAGS_DEADTHREAD) {
        return;
    }
 
    //
    // this ensures that other timed lockers of the process will bail
    // since this call is done while holding the process lock, and lock duration
    // is controlled by debugger
    //
    KeQuerySystemTime(&Process->ExitTime);
 
    args = &m.u.ExitProcess;
    args->ExitStatus = ExitStatus;
 
    DBGKM_FORMAT_API_MSG(m,DbgKmExitProcessApi,sizeof(*args));
 
    DbgkpSendApiMessage(&m,FALSE);
 
}
 
VOID
DbgkMapViewOfSection(
    IN PVOID SectionObject,
    IN PVOID BaseAddress,
    IN ULONG SectionOffset,
    IN ULONG_PTR ViewSize
    )
 
/*++
 
Routine Description:
 
    This function is called when the current process successfully
    maps a view of an image section. If the process has an associated
    debug port, then a load dll message is sent.
 
Arguments:
 
    SectionObject - Supplies a pointer to the section mapped by the
        process.
 
    BaseAddress - Supplies the base address of where the section is
        mapped in the current process address space.
 
    SectionOffset - Supplies the offset in the section where the
        process' mapped view begins.
 
    ViewSize - Supplies the size of the mapped view.
 
Return Value:
 
    None.
 
--*/
 
{
 
    PVOID Port;
    DBGKM_APIMSG m;
    PDBGKM_LOAD_DLL LoadDllArgs;
    PEPROCESS Process;
    PIMAGE_NT_HEADERS NtHeaders;
 
    PAGED_CODE();
 
    UNREFERENCED_PARAMETER (SectionOffset);
    UNREFERENCED_PARAMETER (ViewSize);
 
    if ( KeGetPreviousMode() == KernelMode ) {
        return;
    }
 
    Process = PsGetCurrentProcess();
 
    if (PsGetCurrentThread()->CrossThreadFlags&PS_CROSS_THREAD_FLAGS_HIDEFROMDBG) {
        Port = NULL;
    } else {
        Port = Process->DebugPort;
    }
 
    if ( !Port ) {
        return;
    }
 
    LoadDllArgs = &m.u.LoadDll;
    LoadDllArgs->FileHandle = DbgkpSectionToFileHandle(SectionObject);
    LoadDllArgs->BaseOfDll = BaseAddress;
    LoadDllArgs->DebugInfoFileOffset = 0;
    LoadDllArgs->DebugInfoSize = 0;
 
    //
    // The loader fills in the module name in this pointer before mapping
    // the section.  It's a very poor linkage.
    //
 
    LoadDllArgs->NamePointer = &NtCurrentTeb()->NtTib.ArbitraryUserPointer;
 
    try {
 
        NtHeaders = RtlImageNtHeader (BaseAddress);
 
        if (NtHeaders != NULL) {
            LoadDllArgs->DebugInfoFileOffset = NtHeaders->FileHeader.PointerToSymbolTable;
            LoadDllArgs->DebugInfoSize = NtHeaders->FileHeader.NumberOfSymbols;
        }
 
    } except (EXCEPTION_EXECUTE_HANDLER) {
 
        LoadDllArgs->DebugInfoFileOffset = 0;
        LoadDllArgs->DebugInfoSize = 0;
        LoadDllArgs->NamePointer = NULL;
 
    }
 
    DBGKM_FORMAT_API_MSG(m,DbgKmLoadDllApi,sizeof(*LoadDllArgs));
 
    DbgkpSendApiMessage(&m,TRUE);
    if (LoadDllArgs->FileHandle != NULL) {
        ObCloseHandle(LoadDllArgs->FileHandle, KernelMode);
    }
}
 
VOID
DbgkUnMapViewOfSection(
    IN PVOID BaseAddress
    )
 
/*++
 
Routine Description:
 
    This function is called when the current process successfully
    un maps a view of an image section. If the process has an associated
    debug port, then an "unmap view of section" message is sent.
 
Arguments:
 
    BaseAddress - Supplies the base address of the section being unmapped.
 
Return Value:
 
    None.
 
--*/
 
{
 
    PVOID Port;
    DBGKM_APIMSG m;
    PDBGKM_UNLOAD_DLL UnloadDllArgs;
 
    PAGED_CODE();
 
    if ( KeGetPreviousMode() == KernelMode ) {
        return;
    }
 
    if (PsGetCurrentThread()->CrossThreadFlags&PS_CROSS_THREAD_FLAGS_HIDEFROMDBG) {
        Port = NULL;
    } else {
        Port = PsGetCurrentProcess()->DebugPort;
    }
 
    if ( !Port ) {
        return;
    }
 
    UnloadDllArgs = &m.u.UnloadDll;
    UnloadDllArgs->BaseAddress = BaseAddress;
 
    DBGKM_FORMAT_API_MSG(m,DbgKmUnloadDllApi,sizeof(*UnloadDllArgs));
 
    DbgkpSendApiMessage(&m,TRUE);
}

obtype.c

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
/*++
 
Copyright (c) Microsoft Corporation. All rights reserved.
 
You may only use this code if you agree to the terms of the Windows Research Kernel Source Code License agreement (see License.txt).
If you do not agree to the terms, do not use the code.
 
 
Module Name:
 
    obtype.c
 
Abstract:
 
    Object type routines.
 
--*/
 
#include "obp.h"
 
typedef struct _OBJECT_TYPE_ARRAY {
 
    ULONG   Size;
    POBJECT_HEADER_CREATOR_INFO CreatorInfoArray[1];
 
} OBJECT_TYPE_ARRAY, *POBJECT_TYPE_ARRAY;
 
POBJECT_TYPE_ARRAY
ObpCreateTypeArray (
    IN POBJECT_TYPE ObjectType
    );
VOID
ObpDestroyTypeArray (
    IN POBJECT_TYPE_ARRAY ObjectArray
    );
#ifdef ALLOC_PRAGMA
#pragma alloc_text(PAGE,ObCreateObjectType)
#pragma alloc_text(PAGE,ObEnumerateObjectsByType)
#pragma alloc_text(PAGE,ObpCreateTypeArray)
#pragma alloc_text(PAGE,ObpDestroyTypeArray)
#pragma alloc_text(PAGE,ObGetObjectInformation)
#pragma alloc_text(PAGE,ObpDeleteObjectType)
#endif
 
/*
 
 IMPORTANT IMPORTANT IMPORTANT IMPORTANT IMPORTANT IMPORTANT
 
 There is currently no system service that permits changing
 the security on an object type object.  Consequently, the object
 manager does not check to make sure that a subject is allowed
 to create an object of a given type.
 
 Should such a system service be added, the following section of
 code must be re-enabled in obhandle.c:
 
        //
        // Perform access check to see if we are allowed to create
        // an instance of this object type.
        //
        // This routine will audit the attempt to create the
        // object as appropriate.  Note that this is different
        // from auditing the creation of the object itself.
        //
 
        if (!ObCheckCreateInstanceAccess( ObjectType,
                                          OBJECT_TYPE_CREATE,
                                          AccessState,
                                          TRUE,
                                          AccessMode,
                                          &Status
                                        ) ) {
            return( Status );
 
            }
 
 The code is already there, but is not compiled.
 
 This will ensure that someone who is denied access to an object
 type is not permitted to create an object of that type.
 
*/
 
NTSTATUS
ObCreateObjectType (
    __in PUNICODE_STRING TypeName,
    __in POBJECT_TYPE_INITIALIZER ObjectTypeInitializer,
    __in_opt PSECURITY_DESCRIPTOR SecurityDescriptor,
    __out POBJECT_TYPE *ObjectType
    )
 
/*++
 
Routine Description:
 
    This routine creates a new object type.
 
Arguments:
 
    TypeName - Supplies the name of the new object type
 
    ObjectTypeInitializer - Supplies a object initialization
        structure.  This structure denotes the default object
        behavior including callbacks.
 
    SecurityDescriptor - Currently ignored
 
    ObjectType - Receives a pointer to the newly created object
        type.
 
Return Value:
 
    An appropriate NTSTATUS value.
 
--*/
 
{
    POOL_TYPE PoolType;
    POBJECT_HEADER_CREATOR_INFO CreatorInfo;
    POBJECT_HEADER NewObjectTypeHeader;
    POBJECT_TYPE NewObjectType;
    ULONG i;
    UNICODE_STRING ObjectName;
    PWCH s;
    NTSTATUS Status;
    ULONG StandardHeaderCharge;
    OBP_LOOKUP_CONTEXT LookupContext;
 
    UNREFERENCED_PARAMETER (SecurityDescriptor);
 
    ObpValidateIrql( "ObCreateObjectType" );
 
    //
    //  Return an error if invalid type attributes or no type name specified.
    //  No type name is okay if the type directory object does not exist
    //  yet (see init.c).
    //
 
    PoolType = ObjectTypeInitializer->PoolType;
 
    if ((!TypeName)
 
            ||
 
        (!TypeName->Length)
 
            ||
 
        (TypeName->Length % sizeof( WCHAR ))
 
            ||
 
        (ObjectTypeInitializer == NULL)
 
            ||
 
        (ObjectTypeInitializer->InvalidAttributes & ~OBJ_ALL_VALID_ATTRIBUTES)
 
            ||
 
        (ObjectTypeInitializer->Length != sizeof( *ObjectTypeInitializer ))
 
            ||
 
        (ObjectTypeInitializer->MaintainHandleCount &&
            (ObjectTypeInitializer->OpenProcedure == NULL &&
             ObjectTypeInitializer->CloseProcedure == NULL ))
 
            ||
 
        ((!ObjectTypeInitializer->UseDefaultObject) &&
            (PoolType != NonPagedPool))) {
 
        return( STATUS_INVALID_PARAMETER );
    }
 
    //
    //  Make sure that the type name does not contain an
    //  path name separator
    //
 
    s = TypeName->Buffer;
    i = TypeName->Length / sizeof( WCHAR );
 
    while (i--) {
 
        if (*s++ == OBJ_NAME_PATH_SEPARATOR) {
 
            return( STATUS_OBJECT_NAME_INVALID );
        }
    }
 
    //
    //  See if TypeName string already exists in the \ObjectTypes directory
    //  Return an error if it does.  Otherwise add the name to the directory.
    //  Note that there may not necessarily be a type directory.
    //
 
    ObpInitializeLookupContext( &LookupContext );
 
    if (ObpTypeDirectoryObject) {
 
        ObpLockLookupContext( &LookupContext, ObpTypeDirectoryObject);
 
        if (ObpLookupDirectoryEntry( ObpTypeDirectoryObject,
                                     TypeName,
                                     OBJ_CASE_INSENSITIVE,
                                     FALSE,
                                     &LookupContext )) {
 
            ObpReleaseLookupContext( &LookupContext );
 
            return( STATUS_OBJECT_NAME_COLLISION );
        }
    }
 
    //
    //  Allocate a buffer for the type name and then
    //  copy over the name
    //
 
    ObjectName.Buffer = ExAllocatePoolWithTag( PagedPool,
                                               (ULONG)TypeName->MaximumLength,
                                               'mNbO' );
 
    if (ObjectName.Buffer == NULL) {
 
        ObpReleaseLookupContext( &LookupContext );
 
        return STATUS_INSUFFICIENT_RESOURCES;
    }
 
    ObjectName.MaximumLength = TypeName->MaximumLength;
 
    RtlCopyUnicodeString( &ObjectName, TypeName );
 
    //
    //  Allocate memory for the object
    //
 
    Status = ObpAllocateObject( NULL,
                                KernelMode,
                                ObpTypeObjectType,
                                &ObjectName,
                                sizeof( OBJECT_TYPE ),
                                &NewObjectTypeHeader );
 
    if (!NT_SUCCESS( Status )) {
 
        ObpReleaseLookupContext( &LookupContext );
        ExFreePool(ObjectName.Buffer);
 
        return( Status );
    }
 
    //
    //  Initialize the create attributes, object ownership. parse context,
    //  and object body pointer.
    //
    //  N.B. This is required since these fields are not initialized.
    //
 
    NewObjectTypeHeader->Flags |= OB_FLAG_KERNEL_OBJECT |
                                  OB_FLAG_PERMANENT_OBJECT;
 
    NewObjectType = (POBJECT_TYPE)&NewObjectTypeHeader->Body;
    NewObjectType->Name = ObjectName;
 
    //
    //  The following call zeros out the number of handles and objects
    //  field plus high water marks
    //
 
    RtlZeroMemory( &NewObjectType->TotalNumberOfObjects,
                   FIELD_OFFSET( OBJECT_TYPE, TypeInfo ) -
                   FIELD_OFFSET( OBJECT_TYPE, TotalNumberOfObjects ));
 
    //
    //  If there is not a type object type yet then this must be
    //  that type (i.e., type object type must be the first object type
    //  ever created.  Consequently we'll need to setup some self
    //  referencing pointers.
    //
 
    if (!ObpTypeObjectType) {
 
        ObpTypeObjectType = NewObjectType;
        NewObjectTypeHeader->Type = ObpTypeObjectType;
        NewObjectType->TotalNumberOfObjects = 1;
 
#ifdef POOL_TAGGING
 
        NewObjectType->Key = 'TjbO';
 
    } else {
 
        //
        //  Otherwise this is not the type object type so we'll
        //  try and generate a tag for the new object type provided
        //  pool tagging is turned on.
        //
 
        ANSI_STRING AnsiName;
 
        if (NT_SUCCESS( RtlUnicodeStringToAnsiString( &AnsiName, TypeName, TRUE ) )) {
 
            for (i=3; i>=AnsiName.Length; i--) {
 
                AnsiName.Buffer[ i ] = ' ';
 
            }
 
            NewObjectType->Key = *(PULONG)AnsiName.Buffer;
            ExFreePool( AnsiName.Buffer );
 
        } else {
 
            NewObjectType->Key = *(PULONG)TypeName->Buffer;
        }
 
#endif //POOL_TAGGING
 
    }
 
    //
    //  Continue initializing the new object type fields
    //
 
    NewObjectType->TypeInfo = *ObjectTypeInitializer;
    NewObjectType->TypeInfo.PoolType = PoolType;
 
    if (NtGlobalFlag & FLG_MAINTAIN_OBJECT_TYPELIST) {
 
        NewObjectType->TypeInfo.MaintainTypeList = TRUE;
    }
 
    //
    //  Whack quotas passed in so that headers are properly charged
    //
    //  Quota for object name is charged independently
    //
 
    StandardHeaderCharge = sizeof( OBJECT_HEADER ) +
                           sizeof( OBJECT_HEADER_NAME_INFO ) +
                           (ObjectTypeInitializer->MaintainHandleCount ?
                                sizeof( OBJECT_HEADER_HANDLE_INFO )
                              : 0 );
 
    if ( PoolType == NonPagedPool ) {
 
        NewObjectType->TypeInfo.DefaultNonPagedPoolCharge += StandardHeaderCharge;
 
    } else {
 
        NewObjectType->TypeInfo.DefaultPagedPoolCharge += StandardHeaderCharge;
    }
 
    //
    //  If there is not an object type specific security procedure then set
    //  the default one supplied by Se.
    //
 
    if (ObjectTypeInitializer->SecurityProcedure == NULL) {
 
        NewObjectType->TypeInfo.SecurityProcedure = SeDefaultObjectMethod;
    }
 
    //
    //  Initialize the object type lock and its list of objects created
    //  of this type
    //
 
    ExInitializeResourceLite( &NewObjectType->Mutex );
 
    for (i = 0; i < OBJECT_LOCK_COUNT; i++) {
 
        ExInitializeResourceLite( &NewObjectType->ObjectLocks[i] );
    }
 
    InitializeListHead( &NewObjectType->TypeList );
    PERFINFO_INITIALIZE_OBJECT_ALLOCATED_TYPE_LIST_HEAD(NewObjectType);
 
    //
    //  If we are to use the default object (meaning that we'll have our
    //  private event as our default object) then the type must allow
    //  synchronize and we'll set the default object
    //
 
    if (NewObjectType->TypeInfo.UseDefaultObject) {
 
        NewObjectType->TypeInfo.ValidAccessMask |= SYNCHRONIZE;
        NewObjectType->DefaultObject = &ObpDefaultObject;
 
    //
    //  Otherwise if this is the type file object then we'll put
    //  in the offset to the event of a file object.
    //
 
    } else if (ObjectName.Length == 8 && !wcscmp( ObjectName.Buffer, L"File" )) {
 
        NewObjectType->DefaultObject = ULongToPtr( FIELD_OFFSET( FILE_OBJECT, Event ) );
 
 
    //
    // If this is a waitable port, set the offset to the event in the
    // waitableport object.  Another hack
    //
 
    } else if ( ObjectName.Length == 24 && !wcscmp( ObjectName.Buffer, L"WaitablePort")) {
 
        NewObjectType->DefaultObject = ULongToPtr( FIELD_OFFSET( LPCP_PORT_OBJECT, WaitEvent ) );
 
    //
    //  Otherwise indicate that there isn't a default object to wait
    //  on
    //
 
    } else {
 
        NewObjectType->DefaultObject = NULL;
    }
 
    //
    //  Lock down the type object type and if there is a creator info
    //  record then insert this object on that list
    //
 
    ObpEnterObjectTypeMutex( ObpTypeObjectType );
 
    CreatorInfo = OBJECT_HEADER_TO_CREATOR_INFO( NewObjectTypeHeader );
 
    if (CreatorInfo != NULL) {
 
        InsertTailList( &ObpTypeObjectType->TypeList, &CreatorInfo->TypeList );
    }
 
    //
    //  Store a pointer to this new object type in the
    //  global object types array.  We'll use the index from
    //  the type object type number of objects count
    //
 
    NewObjectType->Index = ObpTypeObjectType->TotalNumberOfObjects;
 
    if (NewObjectType->Index < OBP_MAX_DEFINED_OBJECT_TYPES) {
 
        ObpObjectTypes[ NewObjectType->Index - 1 ] = NewObjectType;
    }
 
    //
    //  Unlock the type object type lock
    //
 
    ObpLeaveObjectTypeMutex( ObpTypeObjectType );
 
    //
    //  Lastly if there is not a directory object type yet then the following
    //  code will actually drop through and set the output object type
    //  and return success.
    //
    //  Otherwise, there is a directory object type and we try to insert the
    //  new type into the directory.  If this succeeds then we'll reference
    //  the directory type object, unlock the root directory, set the
    //  output type and return success
    //
 
    if (!ObpTypeDirectoryObject ||
        ObpInsertDirectoryEntry( ObpTypeDirectoryObject, &LookupContext, NewObjectTypeHeader )) {
 
        if (ObpTypeDirectoryObject) {
 
            ObReferenceObject( ObpTypeDirectoryObject );
        }
 
        ObpReleaseLookupContext( &LookupContext );
 
        *ObjectType = NewObjectType;
 
        return( STATUS_SUCCESS );
 
    } else {
 
        //
        //  Otherwise there is a directory object type and
        //  the insertion failed.  So release the root directory
        //  and return failure to our caller.
        //
 
        ObpReleaseLookupContext( &LookupContext );
 
        return( STATUS_INSUFFICIENT_RESOURCES );
    }
}
 
VOID
ObpDeleteObjectType (
    IN  PVOID   Object
    )
 
/*++
 
Routine Description:
 
    This routine is called when a reference to a type object goes to zero.
 
Arguments:
 
    Object - Supplies a pointer to the type object being deleted
 
Return Value:
 
    None.
 
--*/
 
{
    ULONG i;
    POBJECT_TYPE ObjectType = (POBJECT_TYPE)Object;
 
    //
    //  The only cleaning up we need to do is to delete the type resource
    //
 
    for (i = 0; i < OBJECT_LOCK_COUNT; i++) {
 
        ExDeleteResourceLite( &ObjectType->ObjectLocks[i] );
    }
 
    ExDeleteResourceLite( &ObjectType->Mutex );
 
    //
    //  And return to our caller
    //
 
    return;
}
 
NTSTATUS
ObEnumerateObjectsByType(
    IN POBJECT_TYPE ObjectType,
    IN OB_ENUM_OBJECT_TYPE_ROUTINE EnumerationRoutine,
    IN PVOID Parameter
    )
 
/*++
 
Routine Description:
 
    This routine, via a callback, will enumerate through all
    the objects of a specified type.  This only works on objects
    that maintain the type list (i.e., have an object creator
    info record).
 
Arguments:
 
    ObjectType - Supplies the object type being enumerated
 
    EnumerationRoutine - Supplies the callback routine to use
 
    Parameter - Supplies a parameter to pass through to the callback
        routine
 
Return Value:
 
    STATUS_SUCCESS if the enumeration finishes because the
    end of the list is reached and STATUS_NO_MORE_ENTRIES if
    the enmeration callback routine ever returns false.
 
--*/
 
{
    NTSTATUS Status;
    UNICODE_STRING ObjectName;
    POBJECT_HEADER_CREATOR_INFO CreatorInfo;
    POBJECT_HEADER_NAME_INFO NameInfo;
    POBJECT_HEADER ObjectHeader;
    POBJECT_TYPE_ARRAY ObjectTypeArray;
    ULONG i;
 
    Status = STATUS_SUCCESS;
 
    //
    //  Capture the  object type array
    //
 
    ObjectTypeArray = ObpCreateTypeArray ( ObjectType );
 
    //
    //  If it is any object in that queue, start
    //  quering information about it
    //
 
    if (ObjectTypeArray != NULL) {
 
        //
        //  The following loop iterates through each object
        //  of the specified type.
        //
 
        for ( i = 0; i < ObjectTypeArray->Size; i++) {
 
            //
            //  For each object we'll grab its creator info record,
            //  its object header, and its object body
            //
 
            CreatorInfo = ObjectTypeArray->CreatorInfoArray[i];
 
            //
            //  If the object is being deleted, the creator info
            //  will be NULL in the array. Jump then to the next object
            //
 
            if (!CreatorInfo) {
 
                continue;
            }
 
            ObjectHeader = (POBJECT_HEADER)(CreatorInfo+1);
 
            //
            //  From the object header see if there is a name for the
            //  object. If there is not a name then we'll supply an
            //  empty name.
            //
 
            NameInfo = OBJECT_HEADER_TO_NAME_INFO( ObjectHeader );
 
            if (NameInfo != NULL) {
 
                ObjectName = NameInfo->Name;
 
            } else {
 
                RtlZeroMemory( &ObjectName, sizeof( ObjectName ) );
            }
 
            //
            //  Now invoke the callback and if it returns false then
            //  we're done with the enumeration and will return
            //  an alternate ntstatus value
            //
 
            if (!(EnumerationRoutine)( &ObjectHeader->Body,
                                       &ObjectName,
                                       ObjectHeader->HandleCount,
                                       ObjectHeader->PointerCount,
                                       Parameter )) {
 
                Status = STATUS_NO_MORE_ENTRIES;
 
                break;
            }
        }
 
        ObpDestroyTypeArray(ObjectTypeArray);
    }
 
    return Status;
}
 
PERFINFO_DEFINE_OB_ENUMERATE_ALLOCATED_OBJECTS_BY_TYPE()
 
POBJECT_TYPE_ARRAY
ObpCreateTypeArray (
    IN POBJECT_TYPE ObjectType
    )
 
/*++
 
Routine Description:
 
    This routine create an array with pointers to all objects queued
    for a given ObjectType. All objects are referenced when are stored
    in the array.
 
Arguments:
 
    ObjectType - Supplies the object type for which we make copy
    for all objects.
 
 
Return Value:
 
    The array with objects created. returns NULL if the specified ObjectType
    has the TypeList empty.
 
--*/
 
{
    ULONG Count;
    POBJECT_TYPE_ARRAY ObjectArray;
    PLIST_ENTRY Next1, Head1;
    POBJECT_HEADER_CREATOR_INFO CreatorInfo;
    POBJECT_HEADER ObjectHeader;
    PVOID Object;
 
    //
    //  Acquire the ObjectType mutex
    //
 
    ObpEnterObjectTypeMutex( ObjectType );
 
    ObjectArray = NULL;
 
    //
    //  Count the number of elements into the list
    //
 
    Count = 0;
 
    Head1 = &ObjectType->TypeList;
    Next1 = Head1->Flink;
 
    while (Next1 != Head1) {
 
        Next1 = Next1->Flink;
        Count += 1;
    }
 
    //
    //  If we have a number of objects > 0 then we'll create an array
    //  and copy all pointers into that array
    //
 
    if ( Count > 0 ) {
 
        //
        //  Allocate the memory for array
        //
 
        ObjectArray = ExAllocatePoolWithTag( PagedPool,
                                             sizeof(OBJECT_TYPE_ARRAY) + sizeof(POBJECT_HEADER_CREATOR_INFO) * (Count - 1),
                                             'rAbO' );
        if ( ObjectArray != NULL ) {
 
            ObjectArray->Size = Count;
 
            Count = 0;
 
            //
            //  Start parsing the TypeList
            //
 
            Head1 = &ObjectType->TypeList;
            Next1 = Head1->Flink;
 
            while (Next1 != Head1) {
 
                ASSERT( Count < ObjectArray->Size );
 
                //
                //  For each object we'll grab its creator info record,
                //  its object header, and its object body
                //
 
                CreatorInfo = CONTAINING_RECORD( Next1,
                                                 OBJECT_HEADER_CREATOR_INFO,
                                                 TypeList );
 
                //
                //  We'll store the CreatorInfo into the ObjectArray
                //
 
                ObjectArray->CreatorInfoArray[Count] = CreatorInfo;
 
                //
                //  Find the Object and increment the references to that object
                //  to avoid deleting while are stored copy in this array
                //
 
                ObjectHeader = (POBJECT_HEADER)(CreatorInfo+1);
 
                Object = &ObjectHeader->Body;
 
                if (!ObReferenceObjectSafe( Object))
                {
                    //
                    //  We can't reference the object because it is being deleted
                    //
 
                    ObjectArray->CreatorInfoArray[Count] = NULL;
                }
 
                Next1 = Next1->Flink;
                Count++;
            }
        }
    }
 
    //
    //  Release the ObjectType mutex
    //
 
    ObpLeaveObjectTypeMutex( ObjectType );
 
    return ObjectArray;
}
 
VOID
ObpDestroyTypeArray (
    IN POBJECT_TYPE_ARRAY ObjectArray
    )
 
/*++
 
Routine Description:
 
    This routine destroy an array with pointers to objects, created by
    ObpCreateTypeArray. Each object is dereferenced before releasing the
    array memory.
 
Arguments:
 
    ObjectArray - Supplies the array to be freed
 
Return Value:
 
 
--*/
 
{
    POBJECT_HEADER_CREATOR_INFO CreatorInfo;
    POBJECT_HEADER ObjectHeader;
    PVOID Object;
    ULONG i;
 
    if (ObjectArray != NULL) {
 
        //
        //  Go through array and dereference all objects.
        //
 
        for (i = 0; i < ObjectArray->Size; i++) {
 
            //
            //  Retrieving the Object from the CreatorInfo
            //
 
            CreatorInfo = ObjectArray->CreatorInfoArray[i];
 
            if (CreatorInfo) {
 
                ObjectHeader = (POBJECT_HEADER)(CreatorInfo+1);
 
                Object = &ObjectHeader->Body;
 
                //
                //  Dereference the object
                //
 
                ObDereferenceObject( Object );
            }
        }
 
        //
        //  Free the memory allocated for this array
        //
 
        ExFreePoolWithTag( ObjectArray, 'rAbO' );
    }
}
 
NTSTATUS
ObGetObjectInformation(
    IN PCHAR UserModeBufferAddress,
    OUT PSYSTEM_OBJECTTYPE_INFORMATION ObjectInformation,
    IN ULONG Length,
    OUT PULONG ReturnLength OPTIONAL
    )
 
/*++
 
Routine Description:
 
    This routine returns information for all the object in the
    system.  It enumerates through all the object types and in
    each type it enumerates through their type list.
 
Arguments:
 
    UserModeBufferAddress - Supplies the address of the query buffer
        as specified by the user.
 
    ObjectInformation - Supplies a buffer to receive the object
        type information.  This is essentially the same as the first
        parameter except that one is a system address and the other
        is in the user's address space.
 
    Length - Supplies the length, in bytes, of the object information
        buffer
 
    ReturnLength - Optionally receives the total length, in bytes,
        needed to store the object information
 
 
Return Value:
 
    An appropriate status value
 
--*/
 
{
    #define OBGETINFO_MAXFILENAME (260 * sizeof(WCHAR))
     
    NTSTATUS ReturnStatus, Status;
    POBJECT_TYPE ObjectType;
    POBJECT_HEADER ObjectHeader;
    POBJECT_HEADER_CREATOR_INFO CreatorInfo;
    POBJECT_HEADER_QUOTA_INFO QuotaInfo;
    PVOID Object;
    BOOLEAN FirstObjectForType;
    PSYSTEM_OBJECTTYPE_INFORMATION TypeInfo;
    PSYSTEM_OBJECT_INFORMATION ObjectInfo = NULL;
    ULONG TotalSize, NameSize;
    POBJECT_HEADER ObjectTypeHeader;
    PVOID TmpBuffer = NULL;
    SIZE_T TmpBufferSize = OBGETINFO_MAXFILENAME + sizeof(UNICODE_STRING);
    POBJECT_NAME_INFORMATION NameInformation;
    extern POBJECT_TYPE IoFileObjectType;
    PWSTR TempBuffer;
    USHORT TempMaximumLength;
    POBJECT_TYPE_ARRAY ObjectTypeArray = NULL;
    POBJECT_TYPE_ARRAY TypeObjectTypeArray;
    ULONG i, TypeIndex;
 
    PAGED_CODE();
 
    //
    //  Initialize some local variables
    //
 
    TmpBuffer = ExAllocatePoolWithTag( PagedPool,
                                       TmpBufferSize,
                                       'rAbO' );
 
    if (TmpBuffer == NULL) {
 
        return STATUS_INSUFFICIENT_RESOURCES;
    }
 
    NameInformation = (POBJECT_NAME_INFORMATION)TmpBuffer;
    ReturnStatus = STATUS_SUCCESS;
    TotalSize = 0;
    TypeInfo = NULL;
 
    //
    //  Capture the object types into an array
    //
 
    TypeObjectTypeArray = ObpCreateTypeArray ( ObpTypeObjectType );
 
    if (!TypeObjectTypeArray) {
 
        ExFreePoolWithTag( TmpBuffer, 'rAbO' );
        return STATUS_UNSUCCESSFUL;
    }
 
    try {
 
        for ( TypeIndex = 0; TypeIndex < TypeObjectTypeArray->Size; TypeIndex++ ) {
 
            //
            //  For each object type object we'll grab its creator
            //  info record and which must directly precede the
            //  object header followed by the object body
            //
 
            CreatorInfo = TypeObjectTypeArray->CreatorInfoArray[ TypeIndex ];
 
            //
            //  If the object type is being deleted, the creator info
            //  will be NULL in the array. Jump then to the next object
            //
 
            if (!CreatorInfo) {
 
                continue;
            }
 
            ObjectTypeHeader = (POBJECT_HEADER)(CreatorInfo+1);
            ObjectType = (POBJECT_TYPE)&ObjectTypeHeader->Body;
 
            //
            //  Now if this is not the object type object, which is what
            //  the outer loop is going through then we'll jump in one
            //  more loop
            //
 
            if (ObjectType != ObpTypeObjectType) {
 
                //
                //  Capture the array with objects queued in the TypeList
                //
 
                ObjectTypeArray = ObpCreateTypeArray ( ObjectType );
 
                //
                //  If it is any object in that queue, start
                //  quering information about it
                //
 
                if (ObjectTypeArray != NULL) {
 
                    //
                    //  The following loop iterates through each object
                    //  of the specified type.
                    //
 
                    FirstObjectForType = TRUE;
 
                    for ( i = 0; i < ObjectTypeArray->Size; i++) {
 
                        //
                        //  For each object we'll grab its creator info record,
                        //  its object header, and its object body
                        //
 
                        CreatorInfo = ObjectTypeArray->CreatorInfoArray[i];
 
                        //
                        //  If the object is being deleted, the creator info
                        //  will be NULL in the array. Jump then to the next object
                        //
 
                        if (!CreatorInfo) {
 
                            continue;
                        }
 
                        ObjectHeader = (POBJECT_HEADER)(CreatorInfo+1);
 
                        Object = &ObjectHeader->Body;
 
                        //
                        //  If this is the first time through the inner loop for this
                        //  type then we'll fill in the type info buffer
                        //
 
                        if (FirstObjectForType) {
 
                            FirstObjectForType = FALSE;
 
                            //
                            //  If the pointer it not null (i.e., we've been through
                            //  this loop before) and the total size we've used so
                            //  far hasn't exhausted the output buffer then
                            //  set the previous type info record to point to the
                            //  next type info record
                            //
 
                            if ((TypeInfo != NULL) && (TotalSize < Length)) {
 
                                TypeInfo->NextEntryOffset = TotalSize;
                            }
 
                            //
                            //  Set the current type info record to point to the next
                            //  free spot in the output buffer, and adjust the total
                            //  size used so far to account for the object type info
                            //  buffer
                            //
 
                            TypeInfo = (PSYSTEM_OBJECTTYPE_INFORMATION)((PCHAR)ObjectInformation + TotalSize);
 
                            TotalSize += FIELD_OFFSET( SYSTEM_OBJECTTYPE_INFORMATION, TypeName );
 
                            //
                            //  See if the data will fit into the info buffer, and if
                            //  so then fill in the record
                            //
 
                            if (TotalSize >= Length) {
 
                                ReturnStatus = STATUS_INFO_LENGTH_MISMATCH;
 
                            } else {
 
                                TypeInfo->NextEntryOffset   = 0;
                                TypeInfo->NumberOfObjects   = ObjectType->TotalNumberOfObjects;
                                TypeInfo->NumberOfHandles   = ObjectType->TotalNumberOfHandles;
                                TypeInfo->TypeIndex         = ObjectType->Index;
                                TypeInfo->InvalidAttributes = ObjectType->TypeInfo.InvalidAttributes;
                                TypeInfo->GenericMapping    = ObjectType->TypeInfo.GenericMapping;
                                TypeInfo->ValidAccessMask   = ObjectType->TypeInfo.ValidAccessMask;
                                TypeInfo->PoolType          = ObjectType->TypeInfo.PoolType;
                                TypeInfo->SecurityRequired  = ObjectType->TypeInfo.SecurityRequired;
                            }
 
                            //
                            //  Now we need to do the object's type name. The name
                            //  goes right after the type info field.  The following
                            //  query type name call knows to take the address of a
                            //  unicode string and assumes that the buffer to stuff
                            //  the string is right after the unicode string structure.
                            //  The routine also assumes that name size is the number
                            //  of bytes already use in the buffer and add to it the
                            //  number of bytes it uses.  That is why we need to
                            //  initialize it to zero before doing the call.
                            //
 
                            NameSize = 0;
 
                            Status = ObQueryTypeName( Object,
                                                      &TypeInfo->TypeName,
                                                      TotalSize < Length ? Length - TotalSize : 0,
                                                      &NameSize );
 
                            //
                            //  Round the name size up to the next ulong boundary
                            //
 
                            NameSize = (NameSize + TYPE_ALIGNMENT (SYSTEM_OBJECTTYPE_INFORMATION) - 1) &
                                                   (~(TYPE_ALIGNMENT (SYSTEM_OBJECTTYPE_INFORMATION) - 1));
 
                            //
                            //  If we were able to successfully get the type name then
                            //  set the max length to the rounded ulong that does not
                            //  include the heading unicode string structure.  Also set
                            //  the buffer to the address that the user would use to
                            //  access the string.
                            //
 
                            if (NT_SUCCESS( Status )) {
 
                                TypeInfo->TypeName.MaximumLength = (USHORT)
                                    (NameSize - sizeof( TypeInfo->TypeName ));
                                TypeInfo->TypeName.Buffer = (PWSTR)
                                    (UserModeBufferAddress +
                                     ((PCHAR)TypeInfo->TypeName.Buffer - (PCHAR)ObjectInformation)
                                    );
 
                            } else {
 
                                ReturnStatus = Status;
                            }
 
                            //
                            //  Now we need to bias the total size we've used by the
                            //  size of the object name
                            //
 
                            TotalSize += NameSize;
 
                        } else {
 
                            //
                            //  Otherwise this is not the first time through the inner
                            //  loop for this object type so the only thing we need to
                            //  do is set the previous object info record to "point via
                            //  relative offset" to the next object info record
                            //
 
                            if (TotalSize < Length) {
 
                                ObjectInfo->NextEntryOffset = TotalSize;
                            }
                        }
 
                        //
                        //  We still have an object info record to fill in for this
                        //  record.  The only thing we've done so far is the type info
                        //  record.  So now get a pointer to the new object info record
                        //  and adjust the total size to account for the object record
                        //
 
                        ObjectInfo = (PSYSTEM_OBJECT_INFORMATION)((PCHAR)ObjectInformation + TotalSize);
 
                        TotalSize += FIELD_OFFSET( SYSTEM_OBJECT_INFORMATION, NameInfo );
 
                        //
                        //  If there is room for the object info record then fill
                        //  in the record
                        //
 
                        if (TotalSize >= Length) {
 
                            ReturnStatus = STATUS_INFO_LENGTH_MISMATCH;
 
                        } else {
 
                            ObjectInfo->NextEntryOffset       = 0;
                            ObjectInfo->Object                = Object;
                            ObjectInfo->CreatorUniqueProcess  = CreatorInfo->CreatorUniqueProcess;
                            ObjectInfo->CreatorBackTraceIndex = CreatorInfo->CreatorBackTraceIndex;
                            ObjectInfo->PointerCount          = (ULONG)ObjectHeader->PointerCount;
                            ObjectInfo->HandleCount           = (ULONG)ObjectHeader->HandleCount;
                            ObjectInfo->Flags                 = (USHORT)ObjectHeader->Flags;
                            ObjectInfo->SecurityDescriptor    =
                                ExFastRefGetObject (*(PEX_FAST_REF) &ObjectHeader->SecurityDescriptor);
 
                            //
                            //  Fill in the appropriate quota information if there is
                            //  any quota information available
                            //
 
                            QuotaInfo = OBJECT_HEADER_TO_QUOTA_INFO( ObjectHeader );
 
                            if (QuotaInfo != NULL) {
 
                                ObjectInfo->PagedPoolCharge    = QuotaInfo->PagedPoolCharge;
                                ObjectInfo->NonPagedPoolCharge = QuotaInfo->NonPagedPoolCharge;
 
                                if (QuotaInfo->ExclusiveProcess != NULL) {
 
                                    ObjectInfo->ExclusiveProcessId = QuotaInfo->ExclusiveProcess->UniqueProcessId;
                                }
 
                            } else {
 
                                ObjectInfo->PagedPoolCharge    = ObjectType->TypeInfo.DefaultPagedPoolCharge;
                                ObjectInfo->NonPagedPoolCharge = ObjectType->TypeInfo.DefaultNonPagedPoolCharge;
                            }
                        }
 
                        //
                        //  Now we are ready to get the object name.  If there is not a
                        //  private routine to get the object name then we can call our
                        //  ob routine to query the object name.  Also if this is not
                        //  a file object we can do the query call.  The call will
                        //  fill in our local name buffer.
                        //
 
                        NameSize = 0;
                        Status = STATUS_SUCCESS;
 
                        if ((ObjectType->TypeInfo.QueryNameProcedure == NULL) ||
                            (ObjectType != IoFileObjectType)) {
 
                            Status = ObQueryNameString( Object,
                                                        NameInformation,
                                                        (ULONG)TmpBufferSize,
                                                        &NameSize );
 
                            //
                            //  Increase the temporary buffer, if the name does not fit
                            //
 
                            if ((Status == STATUS_INFO_LENGTH_MISMATCH)
                                    &&
                                (NameSize > TmpBufferSize)  //  just sanity checking to not shrink the buffer
                                    &&
                                ((NameSize + TotalSize) < Length)) {
 
                                PVOID PreviousBuffer = TmpBuffer;
 
                                TmpBuffer = ExAllocatePoolWithTag( PagedPool,
                                                                   NameSize,
                                                                   'rAbO' );
 
                                if (TmpBuffer) {
                                     
                                    ExFreePoolWithTag( PreviousBuffer, 'rAbO' );
                                    TmpBufferSize = NameSize;
                                    NameInformation = (POBJECT_NAME_INFORMATION)TmpBuffer;
                                     
                                    //
                                    //  Retry the query.
                                    //
 
                                    Status = ObQueryNameString( Object,
                                                                NameInformation,
                                                                (ULONG)TmpBufferSize,
                                                                &NameSize );
 
                                } else {
 
                                    //
                                    //  The allocation failed. Continue to use the previous buffer
                                    //
 
                                    TmpBuffer = PreviousBuffer;
                                    Status = STATUS_INSUFFICIENT_RESOURCES;
                                }
                            }
 
                        //
                        //  If this is a file object then we can get the
                        //  name directly from the file object.  We start by
                        //  directly copying the file object unicode string structure
                        //  into our local memory and then adjust the lengths, copy
                        //  the buffer and modify the pointers as necessary.
                        //
 
                        } else if (ObjectType == IoFileObjectType) {
 
                            NameInformation->Name = ((PFILE_OBJECT)Object)->FileName;
 
                            if ((NameInformation->Name.Length != 0) &&
                                (NameInformation->Name.Buffer != NULL)) {
 
                                NameSize = NameInformation->Name.Length + sizeof( UNICODE_NULL );
 
                                //
                                //  We will trim down names that are longer than 260 unicode
                                //  characters in length
                                //
 
                                if (NameSize > OBGETINFO_MAXFILENAME) {
 
                                    NameSize = OBGETINFO_MAXFILENAME;
                                    NameInformation->Name.Length = (USHORT)(NameSize - sizeof( UNICODE_NULL ));
                                }
 
                                //
                                //  Now copy over the name from the buffer used by the
                                //  file object into our local buffer, adjust the
                                //  fields in the unicode string structure and null
                                //  terminate the string.  In the copy we cannot copy
                                //  the null character from the filename because it
                                //  may not be valid memory
                                //
 
                                RtlMoveMemory( (NameInformation+1),
                                               NameInformation->Name.Buffer,
                                               NameSize - sizeof( UNICODE_NULL) );
 
                                NameInformation->Name.Buffer = (PWSTR)(NameInformation+1);
                                NameInformation->Name.MaximumLength = (USHORT)NameSize;
                                NameInformation->Name.Buffer[ NameInformation->Name.Length / sizeof( WCHAR )] = UNICODE_NULL;
 
                                //
                                //  Adjust the name size to account for the unicode
                                //  string structure
                                //
 
                                NameSize += sizeof( *NameInformation );
 
                            } else {
 
                                //
                                //  The file object does not have a name so the name
                                //  size stays zero
                                //
                            }
                        }
 
                        //
                        //  At this point if we have a name then the name size will
                        //  not be zero and the name is stored in our local name
                        //  information variable
                        //
 
                        if (NameSize != 0) {
 
                            //
                            //  Adjust the size of the name up to the next ulong
                            //  boundary and modify the total size required when
                            //  we add in the object name
                            //
                            NameSize = (NameSize + TYPE_ALIGNMENT (SYSTEM_OBJECTTYPE_INFORMATION) - 1) &
                                                   (~(TYPE_ALIGNMENT (SYSTEM_OBJECTTYPE_INFORMATION) - 1));
 
                            TotalSize += NameSize;
 
                            //
                            //  If everything has been successful so far, and we have
                            //  a non empty name, and everything fits in the output
                            //  buffer then copy over the name from our local buffer
                            //  into the caller supplied output buffer, append on the
                            //  null terminating character, and adjust the buffer point
                            //  to use the user's buffer
                            //
 
                            if ((NT_SUCCESS( Status )) &&
                                (NameInformation->Name.Length != 0) &&
                                (TotalSize < Length)) {
 
                                //
                                //  Use temporary local variable for RltMoveMemory
                                //
 
                                TempBuffer = (PWSTR)((&ObjectInfo->NameInfo)+1);
                                TempMaximumLength = (USHORT)
                                    (NameInformation->Name.Length + sizeof( UNICODE_NULL ));
 
                                ObjectInfo->NameInfo.Name.Length = NameInformation->Name.Length;
 
                                RtlMoveMemory( TempBuffer,
                                               NameInformation->Name.Buffer,
                                               TempMaximumLength);
 
                                ObjectInfo->NameInfo.Name.Buffer = (PWSTR)
                                    (UserModeBufferAddress +
                                     ((PCHAR)TempBuffer - (PCHAR)ObjectInformation));
                                ObjectInfo->NameInfo.Name.MaximumLength = TempMaximumLength;
 
                            //
                            //  Otherwise if we've been successful so far but for some
                            //  reason we weren't able to store the object name then
                            //  decide if it was because of an not enough space or
                            //  because the object name is null
                            //
 
                            } else if (NT_SUCCESS( Status )) {
 
                                if ((NameInformation->Name.Length != 0) ||
                                    (TotalSize >= Length)) {
 
                                    ReturnStatus = STATUS_INFO_LENGTH_MISMATCH;
 
                                } else {
 
                                    RtlInitUnicodeString( &ObjectInfo->NameInfo.Name, NULL );
                                }
 
                            //
                            //  Otherwise we have not been successful so far, we'll
                            //  adjust the total size to account for a null unicode
                            //  string, and if it doesn't fit then that's an error
                            //  otherwise we'll put in the null object name
                            //
 
                            } else {
 
                                TotalSize += sizeof( ObjectInfo->NameInfo.Name );
 
                                if (TotalSize >= Length) {
 
                                    ReturnStatus = STATUS_INFO_LENGTH_MISMATCH;
 
                                } else {
 
                                    RtlInitUnicodeString( &ObjectInfo->NameInfo.Name, NULL );
 
                                    ReturnStatus = Status;
                                }
                            }
 
                        //
                        //  Otherwise the name size is zero meaning we have not found
                        //  an object name, so we'll adjust total size for the null
                        //  unicode string, and check that it fits in the output
                        //  buffer.  If it fits we'll output a null object name
                        //
 
                        } else {
 
                            TotalSize += sizeof( ObjectInfo->NameInfo.Name );
 
                            if (TotalSize >= Length) {
 
                                ReturnStatus = STATUS_INFO_LENGTH_MISMATCH;
 
                            } else {
 
                                RtlInitUnicodeString( &ObjectInfo->NameInfo.Name, NULL );
                            }
                        }
 
                    }
 
                    //
                    //  Release the array with objects
                    //
 
                    ObpDestroyTypeArray(ObjectTypeArray);
                    ObjectTypeArray = NULL;
                }
            }
        }
 
        //
        //  Fill in the total size needed to store the buffer if the user wants
        //  that information.  And return to our caller
        //
 
        if (ARGUMENT_PRESENT( ReturnLength )) {
 
            *ReturnLength = TotalSize;
        }
 
 
    } finally {
 
        if (ObjectTypeArray != NULL) {
 
            ObpDestroyTypeArray(ObjectTypeArray);
        }
 
        ObpDestroyTypeArray( TypeObjectTypeArray );
         
        ExFreePoolWithTag( TmpBuffer, 'rAbO' );
    }
     
    if (TypeInfo == NULL) {
 
        return STATUS_UNSUCCESSFUL;
    }
 
    return( ReturnStatus );
}

[招生]科锐逆向工程师培训(2024年11月15日实地,远程教学同时开班, 第51期)

最后于 2024-9-9 01:33 被zhang_derek编辑 ,原因:
收藏
免费 4
支持
分享
最新回复 (32)
雪    币: 4926
活跃值: (389737)
能力值: ( LV2,RANK:10 )
在线值:
发帖
回帖
粉丝
2

最后于 2024-3-20 12:29 被一笑人间万事编辑 ,原因:
2024-3-19 19:55
0
雪    币: 3514
活跃值: (2375)
能力值: ( LV2,RANK:10 )
在线值:
发帖
回帖
粉丝
3
笔记可以分享下啊,学习学习,用心了,谢谢。
2024-3-19 20:28
0
雪    币: 5137
活跃值: (6863)
能力值: ( LV2,RANK:10 )
在线值:
发帖
回帖
粉丝
4
求分享
2024-3-19 22:00
0
雪    币: 2293
活跃值: (2055)
能力值: ( LV2,RANK:10 )
在线值:
发帖
回帖
粉丝
5
求分享
2024-3-19 22:41
0
雪    币: 9024
活跃值: (6245)
能力值: ( LV3,RANK:20 )
在线值:
发帖
回帖
粉丝
6
发出来,大家都有了就卖不成了
2024-3-19 22:44
0
雪    币: 1065
活跃值: (1435)
能力值: ( LV3,RANK:20 )
在线值:
发帖
回帖
粉丝
7
卧槽
2024-3-19 22:57
0
雪    币: 256
活跃值: (753)
能力值: ( LV4,RANK:50 )
在线值:
发帖
回帖
粉丝
8
大学生?自称大学生就是大学生了吗?这种人见过的不少了。要么不拿出来了,要么就直接免费分享好了,闹心眼子的。
2024-3-19 23:18
0
雪    币: 7352
活跃值: (4552)
能力值: ( LV2,RANK:10 )
在线值:
发帖
回帖
粉丝
9
无图无真相
2024-3-20 06:55
0
雪    币: 9917
活跃值: (6744)
能力值: ( LV2,RANK:10 )
在线值:
发帖
回帖
粉丝
10
速速分享一波
2024-3-20 07:38
0
雪    币: 673
活跃值: (2083)
能力值: ( LV2,RANK:10 )
在线值:
发帖
回帖
粉丝
11
这就是中文互联网
2024-3-20 07:55
0
雪    币: 9
能力值: ( LV1,RANK:0 )
在线值:
发帖
回帖
粉丝
12
为了打击这种无良行为,请lz速度公开笔记。
2024-3-20 07:56
0
雪    币: 6230
活跃值: (4236)
能力值: ( LV2,RANK:15 )
在线值:
发帖
回帖
粉丝
13
求分享
2024-3-20 08:29
0
雪    币: 6096
活跃值: (5515)
能力值: ( LV5,RANK:65 )
在线值:
发帖
回帖
粉丝
14
什么笔记?
2024-3-20 09:25
0
雪    币: 3574
活跃值: (3955)
能力值: ( LV2,RANK:10 )
在线值:
发帖
回帖
粉丝
15
这这,太缺德了吧。
2024-3-20 12:39
0
雪    币: 4719
活跃值: (3708)
能力值: ( LV2,RANK:10 )
在线值:
发帖
回帖
粉丝
16
盗墓笔记?
2024-3-20 15:18
0
雪    币: 626
活跃值: (3926)
能力值: ( LV2,RANK:10 )
在线值:
发帖
回帖
粉丝
17
什么笔记 还能卖钱、?
2024-3-20 16:09
0
雪    币: 7018
活跃值: (9199)
能力值: ( LV10,RANK:160 )
在线值:
发帖
回帖
粉丝
18
比写书还详细的笔记
2024-3-20 17:44
0
雪    币: 5137
活跃值: (6863)
能力值: ( LV2,RANK:10 )
在线值:
发帖
回帖
粉丝
19
zhang_derek 比写书还详细的笔记
求私发,我也想学习
2024-3-20 18:05
0
雪    币: 268
活跃值: (3238)
能力值: ( LV3,RANK:30 )
在线值:
发帖
回帖
粉丝
20
求私发,我也想学习,打击买卖
2024-3-20 18:15
0
雪    币: 3836
活跃值: (4142)
能力值: ( LV2,RANK:10 )
在线值:
发帖
回帖
粉丝
21
百度文库?
2024-3-20 19:01
0
雪    币: 4071
活跃值: (4812)
能力值: ( LV2,RANK:10 )
在线值:
发帖
回帖
粉丝
22
说得我也好奇笔记写得有多好了
2024-3-20 19:28
0
雪    币: 6124
活跃值: (4661)
能力值: ( LV6,RANK:80 )
在线值:
发帖
回帖
粉丝
23
闲鱼上很多卖笔记的,不过这种东西一般叫cheat paper
2024-3-20 20:21
0
雪    币: 2421
活跃值: (2301)
能力值: ( LV2,RANK:10 )
在线值:
发帖
回帖
粉丝
24
只能说大佬的笔记有深度和水平
2024-3-21 15:57
0
雪    币: 6536
活跃值: (2384)
能力值: ( LV2,RANK:10 )
在线值:
发帖
回帖
粉丝
25
共享了吧
2024-3-21 16:28
0
游客
登录 | 注册 方可回帖
返回
//