summaryrefslogtreecommitdiffstats
path: root/private/ntos/ps/psdelete.c
blob: 4ac247d4b2d0025d447d811760732667128c5526 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
/*++

Copyright (c) 1989  Microsoft Corporation

Module Name:

    psdelete.c

Abstract:

    This module implements process and thread object termination and
    deletion.

Author:

    Mark Lucovsky (markl) 01-May-1989

Revision History:

--*/

#include "psp.h"

#ifdef ALLOC_PRAGMA
#pragma alloc_text(PAGE, PspTerminateThreadByPointer)
#pragma alloc_text(PAGE, NtTerminateProcess)
#pragma alloc_text(PAGE, NtTerminateThread)
#pragma alloc_text(PAGE, PspNullSpecialApc)
#pragma alloc_text(PAGE, PspExitNormalApc)
#pragma alloc_text(PAGE, PspExitProcess)
#pragma alloc_text(PAGE, PspProcessDelete)
#pragma alloc_text(PAGE, PspThreadDelete)
#pragma alloc_text(PAGE, NtRegisterThreadTerminatePort)
#pragma alloc_text(PAGE, PspExitThread)
#pragma alloc_text(PAGE, PsExitSpecialApc)
#pragma alloc_text(PAGE, PsGetProcessExitTime)
#pragma alloc_text(PAGE, PsSetLegoNotifyRoutine)
#endif

PLEGO_NOTIFY_ROUTINE PspLegoNotifyRoutine;

ULONG
PsSetLegoNotifyRoutine(
    PLEGO_NOTIFY_ROUTINE LegoNotifyRoutine
    )
{
    PAGED_CODE();

    PspLegoNotifyRoutine = LegoNotifyRoutine;

    return FIELD_OFFSET(KTHREAD,LegoData);
}

VOID
PspReaper(
    IN PVOID Context
    )

/*++

Routine Description:

    This routine implements the thread reaper. The reaper is responsible
    for processing terminated threads. This includes:

        - deallocating their kernel stacks

        - releasing their process' CreateDelete lock

        - dereferencing their process

        - dereferencing themselves

Arguments:

    Context - NOT USED

Return Value:

    None.

--*/

{

    PLIST_ENTRY NextEntry;
    KIRQL OldIrql, OldIrql2;
    PETHREAD Thread;
    PEPROCESS Process;

    //
    // Lock the dispatcher data and continually remove entries from the
    // reaper list until no more entries exist.
    //
    // N.B. The dispatcher database lock is used to synchronize access to
    //      the reaper list. This is done to avoid a race condition with
    //      the thread termination code.
    //

    KiLockDispatcherDatabase(&OldIrql);
    NextEntry = PsReaperListHead.Flink;
    while (NextEntry != &PsReaperListHead) {

        //
        // Remove the next thread from the reaper list, get the address of
        // the executive thread object, acquire the context swap lock, and
        // then release the both the context swap dispatcher database locks.
        //
        // N.B. The context swap lock is acquired and immediately released.
        //    This is necessary to ensure that the respective thread has
        //    completely passed through the context switch code before it
        //    is terminated.
        //

        RemoveEntryList(NextEntry);
        Thread = CONTAINING_RECORD(NextEntry, ETHREAD, TerminationPortList);

        KiLockContextSwap(&OldIrql2);
        KiUnlockContextSwap(OldIrql2);

        KiUnlockDispatcherDatabase(OldIrql);

        //
        // Get the address of the executive process object, release the
        // process' CreateDelete lock and then dereference the process
        // object.
        //

        Process = THREAD_TO_PROCESS(Thread);
        KeEnterCriticalRegion();
        PsUnlockProcess(Process);

        ASSERT(Thread->Tcb.KernelApcDisable == 0);

        //
        // Delete the kernel stack and dereference the thread.
        //

        MmDeleteKernelStack(Thread->Tcb.StackBase,(BOOLEAN)Thread->Tcb.LargeStack);
        Thread->Tcb.InitialStack = NULL;
        ObDereferenceObject(Thread);

        //
        // Lock the dispatcher database and get the address of the next
        // entry in the list.
        //

        KiLockDispatcherDatabase(&OldIrql);
        NextEntry = PsReaperListHead.Flink;
    }

    //
    // Set the reaper not active and unlock the dispatcher database.
    //

    PsReaperActive = FALSE;
    KiUnlockDispatcherDatabase(OldIrql);
    return;
}

NTSTATUS
PspTerminateThreadByPointer(
    IN PETHREAD Thread,
    IN NTSTATUS ExitStatus
    )

/*++

Routine Description:

    This function causes the specified thread to terminate.

Arguments:

    ThreadHandle - Supplies a referenced pointer to the thread to terminate.

    ExitStatus - Supplies the exit status associated with the thread.

Return Value:

    TBD

--*/

{

    PKAPC ExitApc;

    PAGED_CODE();

    if ( Thread == PsGetCurrentThread() ) {
        ObDereferenceObject(Thread);
        PspExitThread(ExitStatus);

        //
        // Never Returns
        //

    } else {
        ExitApc = ExAllocatePool(NonPagedPool,(ULONG)sizeof(KAPC));

        if ( !ExitApc ) {
            return STATUS_INSUFFICIENT_RESOURCES;
        }

        KeInitializeApc(
            ExitApc,
            &Thread->Tcb,
            OriginalApcEnvironment,
            PsExitSpecialApc,
            NULL,
            PspExitNormalApc,
            KernelMode,
            (PVOID) ExitStatus
            );


        if ( !KeInsertQueueApc(ExitApc,ExitApc,NULL, 2) ) {
            ExFreePool(ExitApc);

            return STATUS_UNSUCCESSFUL;
        }
    }

    return STATUS_SUCCESS;
}

NTSTATUS
NtTerminateProcess(
    IN HANDLE ProcessHandle OPTIONAL,
    IN NTSTATUS ExitStatus
    )

/*++

Routine Description:

    This function causes the specified process and all of
    its threads to terminate.

Arguments:

    ProcessHandle - Supplies a handle to the process to terminate.

    ExitStatus - Supplies the exit status associated with the process.

Return Value:

    TBD

--*/

{

    PETHREAD Thread,Self;
    PEPROCESS Process;
    PLIST_ENTRY Next;
    NTSTATUS st,xst;
    BOOLEAN ProcessHandleSpecified;
    PAGED_CODE();

    Self = PsGetCurrentThread();

    if ( ARGUMENT_PRESENT(ProcessHandle) ) {
        ProcessHandleSpecified = TRUE;
    } else {
        ProcessHandleSpecified = FALSE;
        ProcessHandle = NtCurrentProcess();
    }

    st = ObReferenceObjectByHandle(
            ProcessHandle,
            PROCESS_TERMINATE,
            PsProcessType,
            KeGetPreviousMode(),
            (PVOID *)&Process,
            NULL
            );

    if ( !NT_SUCCESS(st) ) {
        return(st);
    }

    //
    // If the exit status is DBG_TERMINATE_PROCESS, then fail the terminate
    // if the process is being debugged. This is for shutdown so that we can
    // kill debuggers and not debuggees reliably
    //

    if ( ExitStatus == DBG_TERMINATE_PROCESS && Process != PsGetCurrentProcess() ) {
        if ( Process->DebugPort ) {
            ObDereferenceObject( Process );
            return STATUS_ACCESS_DENIED;
            }
        else {
            ExitStatus = STATUS_SUCCESS;
            }
        }

    st = STATUS_SUCCESS;

#if DBG
    if ( ProcessHandleSpecified ) {
        RtlLogEvent( PspExitProcessEventId, 0, ExitStatus );
        RtlCloseEventLog();
    }
#endif // DBG

    //
    // the following allows NtTerminateProcess to fail properly if
    // called while the exiting process is blocked holding the
    // createdeletelock. This can happen during debugger/server
    // lpc transactions that occur in pspexitthread
    //

    xst = PsLockProcess(Process,KernelMode,PsLockPollOnTimeout);

    if ( xst != STATUS_SUCCESS ) {
        ObDereferenceObject( Process );
        return STATUS_PROCESS_IS_TERMINATING;
        }

    Next = Process->Pcb.ThreadListHead.Flink;

    while ( Next != &Process->Pcb.ThreadListHead) {

        Thread = (PETHREAD)(CONTAINING_RECORD(Next,KTHREAD,ThreadListEntry));

        if ( Thread != Self ) {

            if ( IS_SYSTEM_THREAD(Thread) ) {
                ObDereferenceObject(Process);
                PsUnlockProcess(Process);
                return STATUS_INVALID_PARAMETER;
            }

            if ( !Thread->HasTerminated ) {
                Thread->HasTerminated = TRUE;

                PspTerminateThreadByPointer(Thread, ExitStatus);

                if ( KeForceResumeThread(&Thread->Tcb) ) {
                    st = STATUS_THREAD_WAS_SUSPENDED;
                }
            }
        }
        Next = Next->Flink;
    }


    ObDereferenceObject(Process);

    if ( Process == PsGetCurrentProcess() && ProcessHandleSpecified ) {

        Self->HasTerminated = TRUE;

        PsUnlockProcess(Process);

        PspExitThread(ExitStatus);

        //
        // Never Returns
        //

    }

    PsUnlockProcess(Process);

    return st;
}


NTSTATUS
NtTerminateThread(
    IN HANDLE ThreadHandle OPTIONAL,
    IN NTSTATUS ExitStatus
    )

/*++

Routine Description:

    This function causes the specified thread to terminate.

Arguments:

    ThreadHandle - Supplies a handle to the thread to terminate.

    ExitStatus - Supplies the exit status associated with the thread.

Return Value:

    TBD

--*/

{

    PETHREAD Thread;
    NTSTATUS st;

    PAGED_CODE();

    if ( !ARGUMENT_PRESENT(ThreadHandle) ) {
        if ( (PsGetCurrentProcess()->Pcb.ThreadListHead.Flink ==
              PsGetCurrentProcess()->Pcb.ThreadListHead.Blink
             )
                &&
             (PsGetCurrentProcess()->Pcb.ThreadListHead.Flink ==
              &PsGetCurrentThread()->Tcb.ThreadListEntry
             )
           ) {
            return( STATUS_CANT_TERMINATE_SELF );
        } else {
            ThreadHandle = NtCurrentThread();
        }
    }

    st = ObReferenceObjectByHandle(
            ThreadHandle,
            THREAD_TERMINATE,
            PsThreadType,
            KeGetPreviousMode(),
            (PVOID *)&Thread,
            NULL
            );

    if ( !NT_SUCCESS(st) ) {
        return(st);
    }

    if ( IS_SYSTEM_THREAD(Thread) ) {
        ObDereferenceObject(Thread);
        return STATUS_INVALID_PARAMETER;
    }

    if ( Thread != PsGetCurrentThread() ) {

        if (!Thread->HasTerminated) {
            PsLockProcess(THREAD_TO_PROCESS(Thread),KernelMode,PsLockWaitForever);

            Thread->HasTerminated = TRUE;
            st = PspTerminateThreadByPointer(Thread,ExitStatus);
            if ( NT_SUCCESS(st) ) {
                if ( KeForceResumeThread(&Thread->Tcb) ) {
                    st = STATUS_THREAD_WAS_SUSPENDED;
                }
            }
            PsUnlockProcess(THREAD_TO_PROCESS(Thread));
        }
    } else {
        Thread->HasTerminated = TRUE;
        PspTerminateThreadByPointer(Thread,ExitStatus);
    }
    ObDereferenceObject(Thread);

    return st;
}

NTSTATUS
PsTerminateSystemThread(
    IN NTSTATUS ExitStatus
    )

/*++

Routine Description:

    This function causes the current thread, which must be a system
    thread, to terminate.

Arguments:

    ExitStatus - Supplies the exit status associated with the thread.

Return Value:

    None.

--*/

{
    PETHREAD Thread = PsGetCurrentThread();

    if ( !IS_SYSTEM_THREAD(Thread) ) {
        return STATUS_INVALID_PARAMETER;
    }

    Thread->HasTerminated = TRUE;
    PspExitThread(ExitStatus);
}


VOID
PspNullSpecialApc(
    IN PKAPC Apc,
    IN PKNORMAL_ROUTINE *NormalRoutine,
    IN PVOID *NormalContext,
    IN PVOID *SystemArgument1,
    IN PVOID *SystemArgument2
    )

{

    PAGED_CODE();

    UNREFERENCED_PARAMETER(NormalContext);
    UNREFERENCED_PARAMETER(SystemArgument1);
    UNREFERENCED_PARAMETER(SystemArgument2);

    if ( PsGetCurrentThread()->HasTerminated ) {
        *NormalRoutine = NULL;
    }
    ExFreePool(Apc);
}

VOID
PsExitSpecialApc(
    IN PKAPC Apc,
    IN PKNORMAL_ROUTINE *NormalRoutine,
    IN PVOID *NormalContext,
    IN PVOID *SystemArgument1,
    IN PVOID *SystemArgument2
    )

{
    NTSTATUS ExitStatus;

    PAGED_CODE();

    UNREFERENCED_PARAMETER(NormalRoutine);
    UNREFERENCED_PARAMETER(NormalContext);
    UNREFERENCED_PARAMETER(SystemArgument1);
    UNREFERENCED_PARAMETER(SystemArgument2);

    if ( Apc->SystemArgument2 ) {
        ExitStatus = (NTSTATUS) Apc->NormalContext;
        ExFreePool(Apc);
        PspExitThread(ExitStatus);
    }

}


VOID
PspExitNormalApc(
    IN PVOID NormalContext,
    IN PVOID SystemArgument1,
    IN PVOID SystemArgument2
    )

{
    PETHREAD Thread;
    PKAPC ExitApc;
    NTSTATUS ExitStatus;

    PAGED_CODE();

    Thread = PsGetCurrentThread();

    if ( SystemArgument2 ) {
        KeBugCheck(0x12345678);
    }

    ExitApc = (PKAPC) SystemArgument1;

    if ( IS_SYSTEM_THREAD(Thread) ) {
        ExitStatus = (NTSTATUS) ExitApc->NormalContext;
        ExFreePool(ExitApc);
        PspExitThread(ExitStatus);
    } else {

        KeInitializeApc(
            ExitApc,
            &Thread->Tcb,
            OriginalApcEnvironment,
            PsExitSpecialApc,
            NULL,
            PspExitNormalApc,
            UserMode,
            NormalContext
            );

        if ( !KeInsertQueueApc(ExitApc,ExitApc,(PVOID) 1, 2) ) {
            ExFreePool(ExitApc);
        }
    }
}

VOID
PspDereferenceEventPair(
    IN PETHREAD Thread
    )
{
    KIRQL OldIrql;

    //
    // Dereference the client/server event pair object if one is associated
    // with the thread.
    //

    ExAcquireSpinLock(&PspEventPairLock, &OldIrql);
    if (Thread->EventPair != NULL) {
        ObDereferenceObject(Thread->EventPair);
        Thread->EventPair = (PVOID)1;
    }
    ExReleaseSpinLock(&PspEventPairLock, OldIrql);
}


BOOLEAN
PspMarkCidInvalid(
    IN PHANDLE_ENTRY HandleEntry,
    IN ULONG Parameter
    )
{
    HandleEntry->Object = (PVOID)Parameter;
    return TRUE;
}

VOID
PspExitThread(
    IN NTSTATUS ExitStatus
    )

/*++

Routine Description:

    This function causes the currently executing thread to terminate.  This
    function is only called from within the process structure.  It is called
    either from mainline exit code to exit the current thread, or from
    PsExitSpecialApc (as a piggyback to user-mode PspExitNormalApc).

Arguments:

    ExitStatus - Supplies the exit status associated with the current thread.

Return Value:

    None.

--*/


{

    PETHREAD Thread;
    PEPROCESS Process;
    PKAPC Apc;
    PLIST_ENTRY FirstEntry;
    PLIST_ENTRY NextEntry;
    PTERMINATION_PORT TerminationPort;
    LPC_CLIENT_DIED_MSG CdMsg;
    BOOLEAN LastThread;
    PVOID W32ThreadToDelete;

    PAGED_CODE();

    Thread = PsGetCurrentThread();
    Process = THREAD_TO_PROCESS(Thread);

    KeLowerIrql(PASSIVE_LEVEL);

    if (Thread->Tcb.Priority < LOW_REALTIME_PRIORITY) {
        KeSetPriorityThread (&Thread->Tcb, LOW_REALTIME_PRIORITY);
    }

    PsLockProcess(Process,KernelMode,PsLockWaitForever);

    //
    // Notify registered callout routines of thread deletion.
    //

    if (PspCreateThreadNotifyRoutineCount != 0) {
        ULONG i;

        for (i=0; i<PSP_MAX_CREATE_THREAD_NOTIFY; i++) {
            if (PspCreateThreadNotifyRoutine[i] != NULL) {
                (*PspCreateThreadNotifyRoutine[i])(Process->UniqueProcessId,
                                                   Thread->Cid.UniqueThread,
                                                     FALSE
                                                   );
            }
        }
    }

    LastThread = FALSE;

    if ( (Process->Pcb.ThreadListHead.Flink == Process->Pcb.ThreadListHead.Blink)
         && (Process->Pcb.ThreadListHead.Flink == &Thread->Tcb.ThreadListEntry) ) {
        LastThread = TRUE;
        if ( ExitStatus == STATUS_THREAD_IS_TERMINATING ) {
            if ( Process->ExitStatus == STATUS_PENDING ) {
                Process->ExitStatus = Process->LastThreadExitStatus;
            }
        } else {
            Process->ExitStatus = ExitStatus;
        }

        DbgkExitProcess(ExitStatus);

    } else {
        if ( ExitStatus != STATUS_THREAD_IS_TERMINATING ) {
            Process->LastThreadExitStatus = ExitStatus;
        }

        DbgkExitThread(ExitStatus);
    }

    KeLeaveCriticalRegion();
    ASSERT(Thread->Tcb.KernelApcDisable == 0);

    Thread->Tcb.KernelApcDisable = 0;

    //
    // Process the TerminationPortList
    //
    if ( !IsListEmpty(&Thread->TerminationPortList) ) {

        CdMsg.PortMsg.u1.s1.DataLength = sizeof(LARGE_INTEGER);
        CdMsg.PortMsg.u1.s1.TotalLength = sizeof(LPC_CLIENT_DIED_MSG);
        CdMsg.PortMsg.u2.s2.Type = LPC_CLIENT_DIED;
        CdMsg.PortMsg.u2.s2.DataInfoOffset = 0;

        while ( !IsListEmpty(&Thread->TerminationPortList) ) {

            NextEntry = RemoveHeadList(&Thread->TerminationPortList);
            TerminationPort = CONTAINING_RECORD(NextEntry,TERMINATION_PORT,Links);
            CdMsg.CreateTime = Thread->CreateTime;
            LpcRequestPort(TerminationPort->Port, (PPORT_MESSAGE)&CdMsg);
            ObDereferenceObject(TerminationPort->Port);
            ExFreePool(TerminationPort);
        }
    } else {

        //
        // If there are no ports to send notifications to,
        // but there is an exception port, then we have to
        // send a client died message through the exception
        // port. This will allow a server a chance to get notification
        // if an app/thread dies before it even starts
        //
        //
        // We only send the exception if the thread creation really worked.
        // DeadThread is set when an NtCreateThread returns an error, but
        // the thread will actually execute this path. If DeadThread is not
        // set than the thread creation succeeded. The other place DeadThread
        // is set is when we were terminated without having any chance to move.
        // in this case, DeadThread is set and the exit status is set to
        // STATUS_THREAD_IS_TERMINATING
        //

        if ( (ExitStatus == STATUS_THREAD_IS_TERMINATING && Thread->DeadThread) ||
             !Thread->DeadThread ) {

            CdMsg.PortMsg.u1.s1.DataLength = sizeof(LARGE_INTEGER);
            CdMsg.PortMsg.u1.s1.TotalLength = sizeof(LPC_CLIENT_DIED_MSG);
            CdMsg.PortMsg.u2.s2.Type = LPC_CLIENT_DIED;
            CdMsg.PortMsg.u2.s2.DataInfoOffset = 0;
            if ( PsGetCurrentProcess()->ExceptionPort ) {
                CdMsg.CreateTime = Thread->CreateTime;
                LpcRequestPort(PsGetCurrentProcess()->ExceptionPort, (PPORT_MESSAGE)&CdMsg);
                }
            }
    }

    //
    // rundown the Win32 structures
    //

    if ( W32ThreadToDelete = Thread->Tcb.Win32Thread ) {
        (PspW32ThreadCallout)(Thread->Tcb.Win32Thread,PsW32ThreadCalloutExit);
        }

    if ( LastThread && Process->Win32Process ) {
        (PspW32ProcessCallout)(Process->Win32Process,FALSE);
        ExFreePool(Process->Win32Process);
        Process->Win32Process = NULL;
        }

    if ( W32ThreadToDelete ) {
        ObDereferenceObject(Thread);
        }

    //
    // User/Gdi has been given a chance to clean up. Now make sure they didn't
    // leave the kernel stack locked which would happen if data was still live on
    // this stack, but was being used by another thread
    //

    if ( !Thread->Tcb.EnableStackSwap ) {
        KeBugCheckEx(KERNEL_STACK_LOCKED_AT_EXIT,0,0,0,0);
        }

    //
    // Delete the thread's TEB.  If the address of the TEB is in user
    // space, then this is a real user mode TEB.  If the address is in
    // system space, then this is a special system thread TEB allocated
    // from paged or nonpaged pool.
    //


    if (Thread->Tcb.Teb) {
        if ( IS_SYSTEM_THREAD(Thread) ) {
            ExFreePool( Thread->Tcb.Teb );
        } else {

            //
            // The thread is a user-mode thread. Look to see if the thread
            // owns the loader lock (and any other key peb-based critical
            // sections. If so, do our best to release the locks.
            //
            // Since the LoaderLock used to be a mutant, releasing the lock
            // like this is very similar to mutant abandonment and the loader
            // never did anything with abandoned status anyway
            //

            try {
                PTEB Teb;
                PPEB Peb;
                PRTL_CRITICAL_SECTION Cs;
                int DecrementCount;

                Teb = Thread->Tcb.Teb;
                Peb = Process->Peb;
                Cs = Peb->LoaderLock;
                if ( Cs ) {
                    if ( Cs->OwningThread == Thread->Cid.UniqueThread ) {

                        //
                        // x86 uses a 1 based recursion count
                        //

#if defined(_X86_)
                        DecrementCount = Cs->RecursionCount;
#else
                        DecrementCount = Cs->RecursionCount + 1;
#endif
                        Cs->RecursionCount = 0;
                        Cs->OwningThread = 0;

                        //
                        // undo lock count increments for recursion cases
                        //

                        while(DecrementCount > 1){
                            InterlockedDecrement(&Cs->LockCount);
                            DecrementCount--;
                            }

                        //
                        // undo final lock count
                        //

                        if ( InterlockedDecrement(&Cs->LockCount) >= 0 ){
                            ZwReleaseSemaphore(Cs->LockSemaphore,1,NULL);
                            }
                        }

                    //
                    // if the thread exited while waiting on the loader
                    // lock clean it up. There is still a potential race
                    // here since we can not safely know what happens to
                    // a thread after it interlocked increments the lock count
                    // but before it sets the waiting on loader lock flag. On the
                    // release side, it it safe since we mark ownership of the lock
                    // before clearing the flag. This triggers the first part of this
                    // test. The only thing out of whack is the recursion count, but this
                    // is also safe since in this state, recursion count is 0.
                    //

                    else if ( Teb->WaitingOnLoaderLock ) {
                        if ( InterlockedDecrement(&Cs->LockCount) >= 0 ){
                            ZwReleaseSemaphore(Cs->LockSemaphore,1,NULL);
                            }
                        }
                    }
#if 0
                //
                // debug code to see who is exiting while holding the PEB lock
                //

                Cs = Peb->FastPebLock;
                if ( Cs ) {
                    if ( Cs->OwningThread == Thread->Cid.UniqueThread ) {
                        if ( !LastThread ) {
                            DbgPrint("PS: Thread Exiting While Holding the PebLock\n");
                            DbgBreakPoint();
                            }
                        }
                    }
#endif
                }
            except (EXCEPTION_EXECUTE_HANDLER) {
                ;
                }

            MmDeleteTeb(Process, Thread->Tcb.Teb);
            Thread->Tcb.Teb = NULL;
        }
    }

    //
    // Dereference the client/server event pair object if one is associated
    // with the thread.
    //

    PspDereferenceEventPair(Thread);

    //
    // Rundown The Lists:
    //
    //      - Cancel Io By Thread
    //      - Cancel Timers
    //      - Cancel Registry Notify Requests pending against this thread
    //      - Perform kernel thread rundown
    //

    IoCancelThreadIo(Thread);
    ExTimerRundown();
    CmNotifyRunDown(Thread);
    KeRundownThread();

    //
    // delete the Client Id and decrement the reference count for it.
    //

    if (!(ExChangeHandle(PspCidTable, Thread->Cid.UniqueThread, PspMarkCidInvalid, PSP_INVALID_ID))) {
        KeBugCheck(CID_HANDLE_DELETION);
    }
    ObDereferenceObject(Thread);

    //
    // Let LPC component deal with message stack in Thread->LpcReplyMessage
    // but do it after the client ID becomes invalid.
    //

    LpcExitThread(Thread);

    //
    // If this is the last thread in the process, then clean the address space
    //

    if ( LastThread ) {
        if (!(ExChangeHandle(PspCidTable,Process->UniqueProcessId, PspMarkCidInvalid, PSP_INVALID_ID))) {
            KeBugCheck(CID_HANDLE_DELETION);
        }
        KeQuerySystemTime(&Process->ExitTime);
        PspExitProcess(TRUE,Process);
    }

    //
    // Rundown pending APCs
    //

    (VOID) KeDisableApcQueuingThread(&Thread->Tcb);

    //
    // flush user-mode APC queue
    //

    FirstEntry = KeFlushQueueApc(&Thread->Tcb,UserMode);

    if ( FirstEntry ) {

        NextEntry = FirstEntry;
        do {
            Apc = CONTAINING_RECORD(NextEntry, KAPC, ApcListEntry);
            NextEntry = NextEntry->Flink;

            //
            // If the APC has a rundown routine then call it. Otherwise
            // deallocate the APC
            //

            if ( Apc->RundownRoutine ) {
                (Apc->RundownRoutine)(Apc);
            } else {
                ExFreePool(Apc);
            }

        } while (NextEntry != FirstEntry);
    }

    if ( LastThread ) {
        MmCleanProcessAddressSpace();
    }

    if ( Thread->Tcb.LegoData && PspLegoNotifyRoutine ) {
        (PspLegoNotifyRoutine)(&Thread->Tcb);
        }

    //
    // flush kernel-mode APC queue
    // There should never be any kernel mode APCs found this far
    // into thread termination. Since we go to PASSIVE_LEVEL upon
    // entering exit.
    //

    FirstEntry = KeFlushQueueApc(&Thread->Tcb,KernelMode);

    if ( FirstEntry ) {
        KeBugCheckEx(
            KERNEL_APC_PENDING_DURING_EXIT,
            (ULONG)FirstEntry,
            (ULONG)Thread->Tcb.KernelApcDisable,
            (ULONG)KeGetCurrentIrql(),
            0
            );
    }

    Thread->ExitStatus = ExitStatus;
    KeQuerySystemTime(&Thread->ExitTime);

    //
    // Terminate the thread.
    //
    // N.B. There is no return from this call.
    //
    // N.B. The kernel inserts the current thread in the reaper list and
    //      activates a thread, if necessary, to reap the terminating thread.
    //

    KeTerminateThread(0L);
}

VOID
PspExitProcess(
    IN BOOLEAN TrimAddressSpace,
    IN PEPROCESS Process
    )
{

    ULONG ActualTime;

    PAGED_CODE();

    if (!Process->ExitProcessCalled && PspCreateProcessNotifyRoutineCount != 0) {
        ULONG i;

        for (i=0; i<PSP_MAX_CREATE_PROCESS_NOTIFY; i++) {
            if (PspCreateProcessNotifyRoutine[i] != NULL) {
                (*PspCreateProcessNotifyRoutine[i])( Process->InheritedFromUniqueProcessId,
                                                     Process->UniqueProcessId,
                                                     FALSE
                                                   );
            }
        }
    }

    Process->ExitProcessCalled = TRUE;

    ObKillProcess(TrimAddressSpace, Process);

    KeSetProcess(&Process->Pcb,0,FALSE);

    if ( TrimAddressSpace ) {


        //
        // If the current process has previously set the timer resolution,
        // then reset it.
        //

        if (Process->SetTimerResolution != FALSE) {
            ZwSetTimerResolution(KeMaximumIncrement, FALSE, &ActualTime);
        }

        ExAcquireFastMutex(&PspActiveProcessMutex);
        RemoveEntryList(&Process->ActiveProcessLinks);
        Process->ActiveProcessLinks.Flink = NULL;
        Process->ActiveProcessLinks.Blink = NULL;
        ExReleaseFastMutex(&PspActiveProcessMutex);

    } else {

        //
        // If this is being executed because of delete routine,
        // then process might have to be removed from the active
        // process list. Normally, this is done when the last
        // thread in the process exits. If a thread has never
        // run in the process, and if the process is actually
        // on the list, then it is removed here.

        if (IsListEmpty(&Process->Pcb.ThreadListHead) &&
            ( Process->ActiveProcessLinks.Flink != NULL &&
              Process->ActiveProcessLinks.Blink != NULL) ) {

            ExAcquireFastMutex(&PspActiveProcessMutex);
            RemoveEntryList(&Process->ActiveProcessLinks);
            ExReleaseFastMutex(&PspActiveProcessMutex);

        }
        MmCleanProcessAddressSpace();
    }

}

VOID
PspProcessDelete(
    IN PVOID Object
    )
{
    PEPROCESS Process;
    ULONG AddressSpace;

    PAGED_CODE();

    Process = (PEPROCESS)Object;

    if ( SeDetailedAuditing && Process->Token != NULL ) {
        SeAuditProcessExit(
            Process
            );
    }

    KeTerminateProcess((PKPROCESS)Process);
    AddressSpace =
        ((PHARDWARE_PTE)(&(Process->Pcb.DirectoryTableBase[0])))->PageFrameNumber;

    if (Process->DebugPort) {
        ObDereferenceObject(Process->DebugPort);
    }
    if (Process->ExceptionPort) {
        ObDereferenceObject(Process->ExceptionPort);
    }
    if ( Process->UniqueProcessId ) {
        if ( !(ExDestroyHandle(PspCidTable,Process->UniqueProcessId,FALSE))) {
            KeBugCheck(CID_HANDLE_DELETION);
        }
    }

    PspDeleteLdt( Process );
    PspDeleteVdmObjects( Process );

    if ( AddressSpace ) {

        //
        // Clean address space of the process
        //

        KeAttachProcess(&Process->Pcb);

        PspExitProcess(FALSE,Process);

        KeDetachProcess();
    }

    PspDeleteProcessSecurity( Process );

// Markl - please review the necessity of this if statement.
//         I don't understand why it made things work, so I suspect it
//         is just masking my symptoms.
    if (AddressSpace) {
        MmDeleteProcessAddressSpace(Process);
    }

#if DEVL
    if ( Process->WorkingSetWatch ) {
        ExFreePool(Process->WorkingSetWatch);
    }
#endif // DEVL
    PspDereferenceQuota(Process);
}

VOID
PspThreadDelete(
    IN PVOID Object
    )
{
    PETHREAD Thread;
    PEPROCESS Process;

    PAGED_CODE();

    Thread = (PETHREAD) Object;
    if ( Thread->Tcb.Win32Thread ) {
        (PspW32ThreadCallout)(Thread->Tcb.Win32Thread,PsW32ThreadCalloutDelete);
        ExFreePool(Thread->Tcb.Win32Thread);
        Thread->Tcb.Win32Thread = NULL;
        }
    if ( Thread->Tcb.InitialStack ) {
        MmDeleteKernelStack(Thread->Tcb.InitialStack,(BOOLEAN)Thread->Tcb.LargeStack);
        }

    if ( Thread->Cid.UniqueThread ) {
        if (!(ExDestroyHandle(PspCidTable,Thread->Cid.UniqueThread,FALSE))) {
            KeBugCheck(CID_HANDLE_DELETION);
            }
        }

    PspDeleteThreadSecurity( Thread );

    Process = THREAD_TO_PROCESS(Thread);
    if (Process) {
        ObDereferenceObject(Process);
        }
}

NTSTATUS
NtRegisterThreadTerminatePort(
    IN HANDLE PortHandle
    )

/*++

Routine Description:

    This API allows a thread to register a port to be notified upon
    thread termination.

Arguments:

    PortHandle - Supplies an open handle to a port object that will be
        sent a termination message when the thread terminates.

Return Value:

    TBD

--*/

{

    PVOID Port;
    PTERMINATION_PORT TerminationPort;
    NTSTATUS st;

    PAGED_CODE();

    st = ObReferenceObjectByHandle (
            PortHandle,
            0,
            LpcPortObjectType,
            KeGetPreviousMode(),
            (PVOID *)&Port,
            NULL
            );

    if ( !NT_SUCCESS(st) ) {
        return st;

    }

    //
    // Catch exception and dereference port...
    //

    try {

        TerminationPort = NULL;
        TerminationPort = ExAllocatePoolWithQuota(PagedPool,sizeof(TERMINATION_PORT));

        TerminationPort->Port = Port;
        InsertTailList(&PsGetCurrentThread()->TerminationPortList,&TerminationPort->Links);

    } except(EXCEPTION_EXECUTE_HANDLER) {

        ObDereferenceObject(Port);

        return GetExceptionCode();
    }

    return STATUS_SUCCESS;
}

LARGE_INTEGER
PsGetProcessExitTime(
    VOID
    )

/*++

Routine Description:

    This routine returns the exit time for the current process.

Arguments:

    None.

Return Value:

    The function value is the exit time for the current process.

Note:

    This routine assumes that the caller wants an error log entry within the
    bounds of the maximum size.

--*/

{
    PAGED_CODE();

    //
    // Simply return the exit time for this process.
    //

    return PsGetCurrentProcess()->ExitTime;
}


#undef PsIsThreadTerminating

BOOLEAN
PsIsThreadTerminating(
    IN PETHREAD Thread
    )

/*++

Routine Description:

    This routine returns TRUE if the specified thread is in the process of
    terminating.

Arguments:

    Thread - Supplies a pointer to the thread to be checked for termination.

Return Value:

    TRUE is returned if the thread is terminating, else FALSE is returned.

--*/

{
    //
    // Simply return whether or not the thread is in the process of terminating.
    //

    return Thread->HasTerminated;
}