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
;
266 /* Check if the process has a debug port */
267 if (CurrentProcess
->DebugPort
) {
269 /* Notify the Debug API. TODO */
270 //Last ? DbgkExitProcess(ExitStatus) : DbgkExitThread(ExitStatus);
273 /* Process the Termination Ports */
274 while ((TerminationPort
= CurrentThread
->TerminationPort
)) {
276 DPRINT("TerminationPort: %p\n", TerminationPort
);
278 /* Get the next one */
279 CurrentThread
->TerminationPort
= TerminationPort
->Next
;
281 /* Send the LPC Message */
282 LpcSendTerminationPort(TerminationPort
->Port
, CurrentThread
->CreateTime
);
285 ExFreePool(TerminationPort
);
288 /* Rundown Win32 Structures */
289 PsTerminateWin32Thread(CurrentThread
);
290 if (Last
) PsTerminateWin32Process(CurrentProcess
);
292 /* Rundown Registry Notifications. TODO (refers to NtChangeNotify, not Cm callbacks) */
293 //CmNotifyRunDown(CurrentThread);
296 if((Teb
= CurrentThread
->Tcb
.Teb
))
298 /* Clean up the stack first, if requested */
299 if (Teb
->FreeStackOnTermination
)
302 ZwFreeVirtualMemory(NtCurrentProcess(),
303 &Teb
->DeallocationStack
,
308 DPRINT("Decommit teb at %p\n", Teb
);
309 MmDeleteTeb(CurrentProcess
, Teb
);
310 CurrentThread
->Tcb
.Teb
= NULL
;
313 /* The last Thread shuts down the Process */
314 if (Last
) PspExitProcess(CurrentProcess
);
316 /* Unlock the Process */
317 PsUnlockProcess(CurrentProcess
);
319 /* Cancel I/O for the thread. */
320 IoCancelThreadIo(CurrentThread
);
324 KeCancelTimer(&CurrentThread
->Tcb
.Timer
);
326 /* If the Processor Control Block's NpxThread points to the current thread
329 KeRaiseIrql(DISPATCH_LEVEL
, &oldIrql
);
330 InterlockedCompareExchangePointer(&KeGetCurrentPrcb()->NpxThread
,
332 (PKPROCESS
)CurrentThread
);
333 KeLowerIrql(oldIrql
);
335 /* Rundown Mutexes */
338 /* Disable new APC Queuing, this is as far as we'll let them go */
339 KeDisableThreadApcQueueing(&CurrentThread
->Tcb
);
341 /* Flush the User APCs */
342 ApcEntry
= KeFlushQueueApc(&CurrentThread
->Tcb
, UserMode
);
346 Apc
= CONTAINING_RECORD(ApcEntry
, KAPC
, ApcListEntry
);
348 /* Move to the next one */
349 ApcEntry
= ApcEntry
->Flink
;
351 /* Rundown the APC or de-allocate it */
352 if (Apc
->RundownRoutine
)
354 /* Call its own routine */
355 (Apc
->RundownRoutine
)(Apc
);
359 /* Do it ourselves */
364 /* Call the Lego routine */
365 if (CurrentThread
->Tcb
.LegoData
) PspRunLegoRoutine(&CurrentThread
->Tcb
);
367 /* Flush the APC queue, which should be empty */
368 if ((ApcEntry
= KeFlushQueueApc(&CurrentThread
->Tcb
, KernelMode
)))
371 KEBUGCHECKEX(KERNEL_APC_PENDING_DURING_EXIT
,
373 CurrentThread
->Tcb
.KernelApcDisable
,
378 /* Terminate the Thread from the Scheduler */
379 KeTerminateThread(0);
380 DPRINT1("Unexpected return, CurrentThread %x PsGetCurrentThread() %x\n", CurrentThread
, PsGetCurrentThread());
386 PsExitSpecialApc(PKAPC Apc
,
387 PKNORMAL_ROUTINE
* NormalRoutine
,
388 PVOID
* NormalContext
,
389 PVOID
* SystemArgument1
,
390 PVOID
* SystemArguemnt2
)
392 DPRINT1("PsExitSpecialApc called: 0x%x (proc: 0x%x, '%.16s')\n",
393 PsGetCurrentThread(), PsGetCurrentProcess(), PsGetCurrentProcess()->ImageFileName
);
395 /* Don't do anything unless we are in User-Mode */
396 if (Apc
->SystemArgument2
)
398 NTSTATUS ExitStatus
= (NTSTATUS
)Apc
->NormalContext
;
403 /* Terminate the Thread */
404 PspExitThread(ExitStatus
);
406 /* we should never reach this point! */
413 PspExitNormalApc(PVOID NormalContext
,
414 PVOID SystemArgument1
,
415 PVOID SystemArgument2
)
417 PKAPC Apc
= (PKAPC
)SystemArgument1
;
418 PETHREAD Thread
= PsGetCurrentThread();
421 DPRINT1("PspExitNormalApc called: 0x%x (proc: 0x%x, '%.16s')\n",
422 PsGetCurrentThread(), PsGetCurrentProcess(), PsGetCurrentProcess()->ImageFileName
);
424 /* This should never happen */
425 ASSERT(!SystemArgument2
);
427 /* If this is a system thread, we can safely kill it from Kernel-Mode */
428 if (PsIsSystemThread(Thread
))
430 /* Get the Exit Status */
431 DPRINT1("Killing System Thread\n");
432 ExitStatus
= (NTSTATUS
)Apc
->NormalContext
;
437 /* Exit the Thread */
438 PspExitThread(ExitStatus
);
441 /* If we're here, this is not a System Thread, so kill it from User-Mode */
442 DPRINT1("Initializing User-Mode APC\n");
445 OriginalApcEnvironment
,
452 /* Now insert the APC with the User-Mode Flag */
453 KeInsertQueueApc(Apc
, Apc
, (PVOID
)UserMode
, 2);
455 /* Forcefully resume the thread */
456 KeForceResumeThread(&Thread
->Tcb
);
460 * See "Windows Internals" - Chapter 13, Page 49
464 PspTerminateThreadByPointer(PETHREAD Thread
,
469 DPRINT("PspTerminatedThreadByPointer(Thread %x, ExitStatus %x)\n",
472 /* Check if we are already in the right context */
473 if (PsGetCurrentThread() == Thread
) {
475 /* Directly terminate the thread */
476 PspExitThread(ExitStatus
);
478 /* we should never reach this point! */
482 /* Allocate the APC */
483 Apc
= ExAllocatePoolWithTag(NonPagedPool
, sizeof(KAPC
), TAG_TERMINATE_APC
);
485 /* Initialize a Kernel Mode APC to Kill the Thread */
488 OriginalApcEnvironment
,
495 /* Insert it into the APC Queue */
496 KeInsertQueueApc(Apc
,
501 /* Forcefully resume the thread */
502 KeForceResumeThread(&Thread
->Tcb
);
507 PspExitProcess(PEPROCESS Process
)
509 DPRINT("PspExitProcess 0x%x\n", Process
);
511 PspRunCreateProcessNotifyRoutines(Process
, FALSE
);
513 PspDestroyQuotaBlock(Process
);
515 /* close all handles associated with our process, this needs to be done
516 when the last thread still runs */
517 ObKillProcess(Process
);
519 KeSetProcess(&Process
->Pcb
, IO_NO_INCREMENT
);
521 return(STATUS_SUCCESS
);
526 NtTerminateProcess(IN HANDLE ProcessHandle OPTIONAL
,
527 IN NTSTATUS ExitStatus
)
531 PETHREAD CurrentThread
;
532 BOOLEAN KillByHandle
;
536 DPRINT("NtTerminateProcess(ProcessHandle %x, ExitStatus %x)\n",
537 ProcessHandle
, ExitStatus
);
539 KillByHandle
= (ProcessHandle
!= NULL
);
541 /* Get the Process Object */
542 Status
= ObReferenceObjectByHandle((KillByHandle
? ProcessHandle
: NtCurrentProcess()),
548 if (!NT_SUCCESS(Status
)) {
550 DPRINT1("Invalid handle to Process\n");
554 CurrentThread
= PsGetCurrentThread();
556 PsLockProcess(Process
, FALSE
);
558 if(Process
->ExitTime
.QuadPart
!= 0)
560 PsUnlockProcess(Process
);
561 ObDereferenceObject(Process
);
562 return STATUS_PROCESS_IS_TERMINATING
;
565 /* Terminate all the Process's Threads */
566 PspTerminateProcessThreads(Process
, ExitStatus
);
568 /* only kill the calling thread if it either passed a process handle or
569 NtCurrentProcess() */
572 /* set the exit time as we're about to release the process lock before
573 we kill ourselves to prevent threads outside of our process trying
575 KeQuerySystemTime(&Process
->ExitTime
);
577 /* Only master thread remains... kill it off */
578 if (CurrentThread
->ThreadsProcess
== Process
) {
580 /* mark our thread as terminating so attempts to terminate it, when
581 unlocking the process, fail */
582 CurrentThread
->Terminated
= TRUE
;
584 PsUnlockProcess(Process
);
586 /* we can safely dereference the process because the current thread
587 holds a reference to it until it gets reaped */
588 ObDereferenceObject(Process
);
590 /* now the other threads get a chance to terminate, we don't wait but
591 just kill ourselves right now. The process will be run down when the
592 last thread terminates */
594 PspExitThread(ExitStatus
);
596 /* we should never reach this point! */
601 /* unlock and dereference the process so the threads can kill themselves */
602 PsUnlockProcess(Process
);
603 ObDereferenceObject(Process
);
605 return(STATUS_SUCCESS
);
610 NtTerminateThread(IN HANDLE ThreadHandle
,
611 IN NTSTATUS ExitStatus
)
618 /* Handle the special NULL case */
621 /* Check if we're the only thread left */
622 if (IsListEmpty(&PsGetCurrentProcess()->Pcb
.ThreadListHead
))
624 /* This is invalid */
625 DPRINT1("Can't terminate self\n");
626 return STATUS_CANT_TERMINATE_SELF
;
630 /* Use current handle */
631 ThreadHandle
= NtCurrentThread();
635 /* Get the Thread Object */
636 Status
= ObReferenceObjectByHandle(ThreadHandle
,
642 if (!NT_SUCCESS(Status
)) {
644 DPRINT1("Could not reference thread object\n");
648 /* Make sure this is not a system thread */
649 if (PsIsSystemThread(Thread
)) {
651 DPRINT1("Trying to Terminate a system thread!\n");
652 ObDereferenceObject(Thread
);
653 return STATUS_INVALID_PARAMETER
;
656 /* Check to see if we're running in the same thread */
657 if (Thread
!= PsGetCurrentThread()) {
659 /* we need to lock the process to make sure it's not already terminating */
660 PsLockProcess(Thread
->ThreadsProcess
, FALSE
);
662 /* This isn't our thread, terminate it if not already done */
663 if (!Thread
->Terminated
) {
665 Thread
->Terminated
= TRUE
;
668 PspTerminateThreadByPointer(Thread
, ExitStatus
);
671 PsUnlockProcess(Thread
->ThreadsProcess
);
673 /* Dereference the Thread and return */
674 ObDereferenceObject(Thread
);
678 Thread
->Terminated
= TRUE
;
680 /* it's safe to dereference thread, there's at least the keep-alive
681 reference which will be removed by the thread reaper causing the
682 thread to be finally destroyed */
683 ObDereferenceObject(Thread
);
685 /* Terminate him, he's ours */
686 PspExitThread(ExitStatus
);
688 /* We do never reach this point */
692 return(STATUS_SUCCESS
);
700 PsTerminateSystemThread(NTSTATUS ExitStatus
)
702 PETHREAD Thread
= PsGetCurrentThread();
704 /* Make sure this is a system thread */
705 if (!PsIsSystemThread(Thread
)) {
707 DPRINT1("Trying to Terminate a non-system thread!\n");
708 return STATUS_INVALID_PARAMETER
;
711 /* Terminate it for real */
712 PspExitThread(ExitStatus
);
714 /* we should never reach this point! */
717 return(STATUS_SUCCESS
);
722 NtRegisterThreadTerminatePort(HANDLE PortHandle
)
725 PTERMINATION_PORT TerminationPort
;
726 PVOID TerminationLpcPort
;
732 Status
= ObReferenceObjectByHandle(PortHandle
,
738 if (!NT_SUCCESS(Status
)) {
740 DPRINT1("Failed to reference Port\n");
744 /* Allocate the Port and make sure it suceeded */
745 if((TerminationPort
= ExAllocatePoolWithTag(NonPagedPool
,
746 sizeof(PTERMINATION_PORT
),
747 TAG('P', 's', 'T', '=')))) {
749 /* Associate the Port */
750 Thread
= PsGetCurrentThread();
751 TerminationPort
->Port
= TerminationLpcPort
;
752 DPRINT("TerminationPort: %p\n", TerminationPort
);
753 TerminationPort
->Next
= Thread
->TerminationPort
;
754 Thread
->TerminationPort
= TerminationPort
;
755 DPRINT("TerminationPort: %p\n", Thread
->TerminationPort
);
758 return(STATUS_SUCCESS
);
762 /* Dereference and Fail */
763 ObDereferenceObject(TerminationPort
);
764 return(STATUS_INSUFFICIENT_RESOURCES
);