2 * COPYRIGHT: See COPYING in the top level directory
3 * PROJECT: ReactOS kernel
4 * FILE: ntoskrnl/ps/kill.c
5 * PURPOSE: Thread Termination and Reaping
7 * PROGRAMMERS: Alex Ionescu (alex@relsoft.net)
8 * David Welch (welch@cwcom.net)
11 /* INCLUDES *****************************************************************/
15 #include <internal/debug.h>
17 /* GLOBALS *******************************************************************/
19 PETHREAD PspReaperList
= NULL
;
20 WORK_QUEUE_ITEM PspReaperWorkItem
;
21 BOOLEAN PspReaping
= FALSE
;
22 extern LIST_ENTRY PsActiveProcessHead
;
23 extern FAST_MUTEX PspActiveProcessMutex
;
24 extern PHANDLE_TABLE PspCidTable
;
26 /* FUNCTIONS *****************************************************************/
30 PspReapRoutine(PVOID Context
)
33 PETHREAD Thread
, NewThread
;
36 DPRINT("Evil reaper running!!\n");
37 OldIrql
= KeAcquireDispatcherDatabaseLock();
39 /* Get the first Thread Entry */
40 Thread
= PspReaperList
;
42 DPRINT("PspReaperList: %x\n", Thread
);
44 /* Check to see if the list is empty */
47 /* Unlock the Dispatcher */
48 KeReleaseDispatcherDatabaseLock(OldIrql
);
50 /* Is there a thread on the list? */
53 /* Get the next Thread */
54 DPRINT("Thread: %x\n", Thread
);
55 DPRINT("Thread: %x\n", Thread
->ReaperLink
);
56 NewThread
= Thread
->ReaperLink
;
58 /* Remove reference to current thread */
59 ObDereferenceObject(Thread
);
61 /* Move to next Thread */
65 /* No more linked threads... Reacquire the Lock */
66 OldIrql
= KeAcquireDispatcherDatabaseLock();
68 /* Now try to get a new thread from the list */
69 Thread
= PspReaperList
;
71 DPRINT("PspReaperList: %x\n", Thread
);
73 /* Loop again if there is a new thread */
77 DPRINT("Done reaping\n");
78 KeReleaseDispatcherDatabaseLock(OldIrql
);
83 PspKillMostProcesses(VOID
)
85 PLIST_ENTRY current_entry
;
88 ASSERT(PsGetCurrentProcessId() == PsInitialSystemProcess
->UniqueProcessId
);
90 /* Acquire the Active Process Lock */
91 ExAcquireFastMutex(&PspActiveProcessMutex
);
93 /* Loop all processes on the list */
94 current_entry
= PsActiveProcessHead
.Flink
;
95 while (current_entry
!= &PsActiveProcessHead
)
97 current
= CONTAINING_RECORD(current_entry
, EPROCESS
, ActiveProcessLinks
);
98 current_entry
= current_entry
->Flink
;
100 if (current
->UniqueProcessId
!= PsInitialSystemProcess
->UniqueProcessId
)
102 /* Terminate all the Threads in this Process */
103 PspTerminateProcessThreads(current
, STATUS_SUCCESS
);
107 /* Release the lock */
108 ExReleaseFastMutex(&PspActiveProcessMutex
);
113 PspTerminateProcessThreads(PEPROCESS Process
,
116 PLIST_ENTRY CurrentEntry
;
117 PETHREAD Thread
, CurrentThread
= PsGetCurrentThread();
119 CurrentEntry
= Process
->ThreadListHead
.Flink
;
120 while (CurrentEntry
!= &Process
->ThreadListHead
) {
122 /* Get the Current Thread */
123 Thread
= CONTAINING_RECORD(CurrentEntry
, ETHREAD
, ThreadListEntry
);
125 /* Move to the Next Thread */
126 CurrentEntry
= CurrentEntry
->Flink
;
128 /* Make sure it's not the one we're in */
129 if (Thread
!= CurrentThread
) {
131 /* Make sure it didn't already terminate */
132 if (!Thread
->Terminated
) {
134 Thread
->Terminated
= TRUE
;
136 /* Terminate it by APC */
137 PspTerminateThreadByPointer(Thread
, ExitStatus
);
145 PspDeleteProcess(PVOID ObjectBody
)
147 PEPROCESS Process
= (PEPROCESS
)ObjectBody
;
149 DPRINT("PiDeleteProcess(ObjectBody %x)\n", ObjectBody
);
151 /* Remove it from the Active List */
152 ExAcquireFastMutex(&PspActiveProcessMutex
);
153 RemoveEntryList(&Process
->ActiveProcessLinks
);
154 ExReleaseFastMutex(&PspActiveProcessMutex
);
156 /* Delete the CID Handle */
157 if(Process
->UniqueProcessId
)
159 ExDestroyHandle(PspCidTable
, Process
->UniqueProcessId
);
163 KDB_DELETEPROCESS_HOOK(Process
);
165 /* Dereference the Token */
166 SeDeassignPrimaryToken(Process
);
168 /* Release Memory Information */
169 MmReleaseMmInfo(Process
);
171 /* Delete the W32PROCESS structure if there's one associated */
172 if(Process
->Win32Process
!= NULL
) ExFreePool(Process
->Win32Process
);
177 PspDeleteThread(PVOID ObjectBody
)
179 PETHREAD Thread
= (PETHREAD
)ObjectBody
;
180 PEPROCESS Process
= Thread
->ThreadsProcess
;
182 DPRINT("PiDeleteThread(ObjectBody 0x%x, process 0x%x)\n",ObjectBody
, Thread
->ThreadsProcess
);
184 /* Deassociate the Process */
185 Thread
->ThreadsProcess
= NULL
;
187 /* Delete the CID Handle */
188 if(Thread
->Cid
.UniqueThread
)
190 ExDestroyHandle(PspCidTable
, Thread
->Cid
.UniqueThread
);
193 /* Free the W32THREAD structure if present */
194 if(Thread
->Tcb
.Win32Thread
!= NULL
) ExFreePool (Thread
->Tcb
.Win32Thread
);
196 /* Release the Kernel Stack */
197 MmDeleteKernelStack((PVOID
)Thread
->Tcb
.StackLimit
, FALSE
);
199 /* Dereference the Process */
200 ObDereferenceObject(Process
);
204 * FUNCTION: Terminates the current thread
205 * See "Windows Internals" - Chapter 13, Page 50-53
209 PspExitThread(NTSTATUS ExitStatus
)
211 PETHREAD CurrentThread
;
213 PEPROCESS CurrentProcess
;
214 PTERMINATION_PORT TerminationPort
;
217 PLIST_ENTRY ApcEntry
;
220 DPRINT("PspExitThread(ExitStatus %x), Current: 0x%x\n", ExitStatus
, PsGetCurrentThread());
222 /* Get the Current Thread and Process */
223 CurrentThread
= PsGetCurrentThread();
224 CurrentProcess
= CurrentThread
->ThreadsProcess
;
226 /* Set the Exit Status and Exit Time */
227 CurrentThread
->ExitStatus
= ExitStatus
;
228 KeQuerySystemTime(&CurrentThread
->ExitTime
);
230 /* Can't terminate a thread if it attached another process */
231 if (KeIsAttachedProcess()) {
233 KEBUGCHECKEX(INVALID_PROCESS_ATTACH_ATTEMPT
, (ULONG
) CurrentProcess
,
234 (ULONG
) CurrentThread
->Tcb
.ApcState
.Process
,
235 (ULONG
) CurrentThread
->Tcb
.ApcStateIndex
,
236 (ULONG
) CurrentThread
);
239 /* Lower to Passive Level */
240 KeLowerIrql(PASSIVE_LEVEL
);
242 /* Lock the Process before we modify its thread entries */
243 PsLockProcess(CurrentProcess
, FALSE
);
245 /* wake up the thread so we don't deadlock on PsLockProcess */
246 KeForceResumeThread(&CurrentThread
->Tcb
);
248 /* Run Thread Notify Routines before we desintegrate the thread */
249 PspRunCreateThreadNotifyRoutines(CurrentThread
, FALSE
);
251 /* Remove the thread from the thread list of its process */
252 RemoveEntryList(&CurrentThread
->ThreadListEntry
);
253 Last
= IsListEmpty(&CurrentProcess
->ThreadListHead
);
255 /* Set the last Thread Exit Status */
256 CurrentProcess
->LastThreadExitStatus
= ExitStatus
;
260 /* Save the Exit Time if not already done by NtTerminateProcess. This
261 happens when the last thread just terminates without explicitly
262 terminating the process. */
263 CurrentProcess
->ExitTime
= CurrentThread
->ExitTime
;
264 CurrentProcess
->ExitStatus
= ExitStatus
;
267 /* Check if the process has a debug port */
268 if (CurrentProcess
->DebugPort
) {
270 /* Notify the Debug API. TODO */
271 //Last ? DbgkExitProcess(ExitStatus) : DbgkExitThread(ExitStatus);
274 /* Process the Termination Ports */
275 while ((TerminationPort
= CurrentThread
->TerminationPort
)) {
277 DPRINT("TerminationPort: %p\n", TerminationPort
);
279 /* Get the next one */
280 CurrentThread
->TerminationPort
= TerminationPort
->Next
;
282 /* Send the LPC Message */
283 LpcSendTerminationPort(TerminationPort
->Port
, CurrentThread
->CreateTime
);
286 ExFreePool(TerminationPort
);
289 /* Rundown Win32 Structures */
290 PsTerminateWin32Thread(CurrentThread
);
291 if (Last
) PsTerminateWin32Process(CurrentProcess
);
293 /* Rundown Registry Notifications. TODO (refers to NtChangeNotify, not Cm callbacks) */
294 //CmNotifyRunDown(CurrentThread);
297 if((Teb
= CurrentThread
->Tcb
.Teb
))
299 /* Clean up the stack first, if requested */
300 if (Teb
->FreeStackOnTermination
)
303 ZwFreeVirtualMemory(NtCurrentProcess(),
304 &Teb
->DeallocationStack
,
309 DPRINT("Decommit teb at %p\n", Teb
);
310 MmDeleteTeb(CurrentProcess
, Teb
);
311 CurrentThread
->Tcb
.Teb
= NULL
;
314 /* The last Thread shuts down the Process */
315 if (Last
) PspExitProcess(CurrentProcess
);
317 /* Unlock the Process */
318 PsUnlockProcess(CurrentProcess
);
320 /* Cancel I/O for the thread. */
321 IoCancelThreadIo(CurrentThread
);
325 KeCancelTimer(&CurrentThread
->Tcb
.Timer
);
327 /* If the Processor Control Block's NpxThread points to the current thread
330 KeRaiseIrql(DISPATCH_LEVEL
, &oldIrql
);
331 InterlockedCompareExchangePointer(&KeGetCurrentPrcb()->NpxThread
,
333 (PKPROCESS
)CurrentThread
);
334 KeLowerIrql(oldIrql
);
336 /* Rundown Mutexes */
339 /* Disable new APC Queuing, this is as far as we'll let them go */
340 KeDisableThreadApcQueueing(&CurrentThread
->Tcb
);
342 /* Flush the User APCs */
343 ApcEntry
= KeFlushQueueApc(&CurrentThread
->Tcb
, UserMode
);
347 Apc
= CONTAINING_RECORD(ApcEntry
, KAPC
, ApcListEntry
);
349 /* Move to the next one */
350 ApcEntry
= ApcEntry
->Flink
;
352 /* Rundown the APC or de-allocate it */
353 if (Apc
->RundownRoutine
)
355 /* Call its own routine */
356 (Apc
->RundownRoutine
)(Apc
);
360 /* Do it ourselves */
365 /* Call the Lego routine */
366 if (CurrentThread
->Tcb
.LegoData
) PspRunLegoRoutine(&CurrentThread
->Tcb
);
368 /* Flush the APC queue, which should be empty */
369 if ((ApcEntry
= KeFlushQueueApc(&CurrentThread
->Tcb
, KernelMode
)))
372 KEBUGCHECKEX(KERNEL_APC_PENDING_DURING_EXIT
,
374 CurrentThread
->Tcb
.KernelApcDisable
,
379 /* Terminate the Thread from the Scheduler */
380 KeTerminateThread(0);
381 DPRINT1("Unexpected return, CurrentThread %x PsGetCurrentThread() %x\n", CurrentThread
, PsGetCurrentThread());
387 PsExitSpecialApc(PKAPC Apc
,
388 PKNORMAL_ROUTINE
* NormalRoutine
,
389 PVOID
* NormalContext
,
390 PVOID
* SystemArgument1
,
391 PVOID
* SystemArguemnt2
)
393 DPRINT1("PsExitSpecialApc called: 0x%x (proc: 0x%x, '%.16s')\n",
394 PsGetCurrentThread(), PsGetCurrentProcess(), PsGetCurrentProcess()->ImageFileName
);
396 /* Don't do anything unless we are in User-Mode */
397 if (Apc
->SystemArgument2
)
399 NTSTATUS ExitStatus
= (NTSTATUS
)Apc
->NormalContext
;
404 /* Terminate the Thread */
405 PspExitThread(ExitStatus
);
407 /* we should never reach this point! */
414 PspExitNormalApc(PVOID NormalContext
,
415 PVOID SystemArgument1
,
416 PVOID SystemArgument2
)
418 PKAPC Apc
= (PKAPC
)SystemArgument1
;
419 PETHREAD Thread
= PsGetCurrentThread();
422 DPRINT1("PspExitNormalApc called: 0x%x (proc: 0x%x, '%.16s')\n",
423 PsGetCurrentThread(), PsGetCurrentProcess(), PsGetCurrentProcess()->ImageFileName
);
425 /* This should never happen */
426 ASSERT(!SystemArgument2
);
428 /* If this is a system thread, we can safely kill it from Kernel-Mode */
429 if (PsIsSystemThread(Thread
))
431 /* Get the Exit Status */
432 DPRINT1("Killing System Thread\n");
433 ExitStatus
= (NTSTATUS
)Apc
->NormalContext
;
438 /* Exit the Thread */
439 PspExitThread(ExitStatus
);
442 /* If we're here, this is not a System Thread, so kill it from User-Mode */
443 DPRINT1("Initializing User-Mode APC\n");
446 OriginalApcEnvironment
,
453 /* Now insert the APC with the User-Mode Flag */
454 KeInsertQueueApc(Apc
, Apc
, (PVOID
)UserMode
, 2);
456 /* Forcefully resume the thread */
457 KeForceResumeThread(&Thread
->Tcb
);
461 * See "Windows Internals" - Chapter 13, Page 49
465 PspTerminateThreadByPointer(PETHREAD Thread
,
470 DPRINT("PspTerminatedThreadByPointer(Thread %x, ExitStatus %x)\n",
473 /* Check if we are already in the right context */
474 if (PsGetCurrentThread() == Thread
) {
476 /* Directly terminate the thread */
477 PspExitThread(ExitStatus
);
479 /* we should never reach this point! */
483 /* Allocate the APC */
484 Apc
= ExAllocatePoolWithTag(NonPagedPool
, sizeof(KAPC
), TAG_TERMINATE_APC
);
486 /* Initialize a Kernel Mode APC to Kill the Thread */
489 OriginalApcEnvironment
,
496 /* Insert it into the APC Queue */
497 KeInsertQueueApc(Apc
,
502 /* Forcefully resume the thread */
503 KeForceResumeThread(&Thread
->Tcb
);
508 PspExitProcess(PEPROCESS Process
)
510 DPRINT("PspExitProcess 0x%x\n", Process
);
512 PspRunCreateProcessNotifyRoutines(Process
, FALSE
);
514 PspDestroyQuotaBlock(Process
);
516 /* close all handles associated with our process, this needs to be done
517 when the last thread still runs */
518 ObKillProcess(Process
);
520 KeSetProcess(&Process
->Pcb
, IO_NO_INCREMENT
);
522 return(STATUS_SUCCESS
);
527 NtTerminateProcess(IN HANDLE ProcessHandle OPTIONAL
,
528 IN NTSTATUS ExitStatus
)
532 PETHREAD CurrentThread
;
533 BOOLEAN KillByHandle
;
537 DPRINT("NtTerminateProcess(ProcessHandle %x, ExitStatus %x)\n",
538 ProcessHandle
, ExitStatus
);
540 KillByHandle
= (ProcessHandle
!= NULL
);
542 /* Get the Process Object */
543 Status
= ObReferenceObjectByHandle((KillByHandle
? ProcessHandle
: NtCurrentProcess()),
549 if (!NT_SUCCESS(Status
)) {
551 DPRINT1("Invalid handle to Process\n");
555 CurrentThread
= PsGetCurrentThread();
557 PsLockProcess(Process
, FALSE
);
559 if(Process
->ExitTime
.QuadPart
!= 0)
561 PsUnlockProcess(Process
);
562 ObDereferenceObject(Process
);
563 return STATUS_PROCESS_IS_TERMINATING
;
566 /* Terminate all the Process's Threads */
567 PspTerminateProcessThreads(Process
, ExitStatus
);
569 /* only kill the calling thread if it either passed a process handle or
570 NtCurrentProcess() */
573 /* set the exit time as we're about to release the process lock before
574 we kill ourselves to prevent threads outside of our process trying
576 KeQuerySystemTime(&Process
->ExitTime
);
577 Process
->ExitStatus
= ExitStatus
;
579 /* Only master thread remains... kill it off */
580 if (CurrentThread
->ThreadsProcess
== Process
) {
582 /* mark our thread as terminating so attempts to terminate it, when
583 unlocking the process, fail */
584 CurrentThread
->Terminated
= TRUE
;
586 PsUnlockProcess(Process
);
588 /* we can safely dereference the process because the current thread
589 holds a reference to it until it gets reaped */
590 ObDereferenceObject(Process
);
592 /* now the other threads get a chance to terminate, we don't wait but
593 just kill ourselves right now. The process will be run down when the
594 last thread terminates */
596 PspExitThread(ExitStatus
);
598 /* we should never reach this point! */
603 /* unlock and dereference the process so the threads can kill themselves */
604 PsUnlockProcess(Process
);
605 ObDereferenceObject(Process
);
607 return(STATUS_SUCCESS
);
612 NtTerminateThread(IN HANDLE ThreadHandle
,
613 IN NTSTATUS ExitStatus
)
620 /* Handle the special NULL case */
623 /* Check if we're the only thread left */
624 if (IsListEmpty(&PsGetCurrentProcess()->Pcb
.ThreadListHead
))
626 /* This is invalid */
627 DPRINT1("Can't terminate self\n");
628 return STATUS_CANT_TERMINATE_SELF
;
632 /* Use current handle */
633 ThreadHandle
= NtCurrentThread();
637 /* Get the Thread Object */
638 Status
= ObReferenceObjectByHandle(ThreadHandle
,
644 if (!NT_SUCCESS(Status
)) {
646 DPRINT1("Could not reference thread object\n");
650 /* Make sure this is not a system thread */
651 if (PsIsSystemThread(Thread
)) {
653 DPRINT1("Trying to Terminate a system thread!\n");
654 ObDereferenceObject(Thread
);
655 return STATUS_INVALID_PARAMETER
;
658 /* Check to see if we're running in the same thread */
659 if (Thread
!= PsGetCurrentThread()) {
661 /* we need to lock the process to make sure it's not already terminating */
662 PsLockProcess(Thread
->ThreadsProcess
, FALSE
);
664 /* This isn't our thread, terminate it if not already done */
665 if (!Thread
->Terminated
) {
667 Thread
->Terminated
= TRUE
;
670 PspTerminateThreadByPointer(Thread
, ExitStatus
);
673 PsUnlockProcess(Thread
->ThreadsProcess
);
675 /* Dereference the Thread and return */
676 ObDereferenceObject(Thread
);
680 Thread
->Terminated
= TRUE
;
682 /* it's safe to dereference thread, there's at least the keep-alive
683 reference which will be removed by the thread reaper causing the
684 thread to be finally destroyed */
685 ObDereferenceObject(Thread
);
687 /* Terminate him, he's ours */
688 PspExitThread(ExitStatus
);
690 /* We do never reach this point */
694 return(STATUS_SUCCESS
);
702 PsTerminateSystemThread(NTSTATUS ExitStatus
)
704 PETHREAD Thread
= PsGetCurrentThread();
706 /* Make sure this is a system thread */
707 if (!PsIsSystemThread(Thread
)) {
709 DPRINT1("Trying to Terminate a non-system thread!\n");
710 return STATUS_INVALID_PARAMETER
;
713 /* Terminate it for real */
714 PspExitThread(ExitStatus
);
716 /* we should never reach this point! */
719 return(STATUS_SUCCESS
);
724 NtRegisterThreadTerminatePort(HANDLE PortHandle
)
727 PTERMINATION_PORT TerminationPort
;
728 PVOID TerminationLpcPort
;
734 Status
= ObReferenceObjectByHandle(PortHandle
,
740 if (!NT_SUCCESS(Status
)) {
742 DPRINT1("Failed to reference Port\n");
746 /* Allocate the Port and make sure it suceeded */
747 if((TerminationPort
= ExAllocatePoolWithTag(NonPagedPool
,
748 sizeof(PTERMINATION_PORT
),
749 TAG('P', 's', 'T', '=')))) {
751 /* Associate the Port */
752 Thread
= PsGetCurrentThread();
753 TerminationPort
->Port
= TerminationLpcPort
;
754 DPRINT("TerminationPort: %p\n", TerminationPort
);
755 TerminationPort
->Next
= Thread
->TerminationPort
;
756 Thread
->TerminationPort
= TerminationPort
;
757 DPRINT("TerminationPort: %p\n", Thread
->TerminationPort
);
760 return(STATUS_SUCCESS
);
764 /* Dereference and Fail */
765 ObDereferenceObject(TerminationPort
);
766 return(STATUS_INSUFFICIENT_RESOURCES
);