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 #define TAG_TERMINATE_APC TAG('T', 'A', 'P', 'C')
21 PETHREAD PspReaperList
= NULL
;
22 WORK_QUEUE_ITEM PspReaperWorkItem
;
23 BOOLEAN PspReaping
= FALSE
;
24 extern LIST_ENTRY PsActiveProcessHead
;
25 extern FAST_MUTEX PspActiveProcessMutex
;
27 /* FUNCTIONS *****************************************************************/
31 PspReapRoutine(PVOID Context
)
34 PETHREAD Thread
, NewThread
;
37 DPRINT("Evil reaper running!!\n");
38 OldIrql
= KeAcquireDispatcherDatabaseLock();
40 /* Get the first Thread Entry */
41 Thread
= PspReaperList
;
43 DPRINT("PspReaperList: %x\n", Thread
);
45 /* Check to see if the list is empty */
48 /* Unlock the Dispatcher */
49 KeReleaseDispatcherDatabaseLock(OldIrql
);
51 /* Is there a thread on the list? */
54 /* Get the next Thread */
55 DPRINT("Thread: %x\n", Thread
);
56 DPRINT("Thread: %x\n", Thread
->ReaperLink
);
57 NewThread
= Thread
->ReaperLink
;
59 /* Remove reference to current thread */
60 ObDereferenceObject(Thread
);
62 /* Move to next Thread */
66 /* No more linked threads... Reacquire the Lock */
67 OldIrql
= KeAcquireDispatcherDatabaseLock();
69 /* Now try to get a new thread from the list */
70 Thread
= PspReaperList
;
72 DPRINT("PspReaperList: %x\n", Thread
);
74 /* Loop again if there is a new thread */
78 DPRINT("Done reaping\n");
79 KeReleaseDispatcherDatabaseLock(OldIrql
);
84 PspKillMostProcesses(VOID
)
86 PLIST_ENTRY current_entry
;
89 /* Acquire the Active Process Lock */
90 ExAcquireFastMutex(&PspActiveProcessMutex
);
92 /* Loop all processes on the list */
93 current_entry
= PsActiveProcessHead
.Flink
;
94 while (current_entry
!= &PsActiveProcessHead
)
96 current
= CONTAINING_RECORD(current_entry
, EPROCESS
, ProcessListEntry
);
97 current_entry
= current_entry
->Flink
;
99 if (current
->UniqueProcessId
!= PsInitialSystemProcess
->UniqueProcessId
&&
100 current
->UniqueProcessId
!= PsGetCurrentProcessId())
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
->HasTerminated
) {
134 Thread
->HasTerminated
= 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
->ProcessListEntry
);
154 ExReleaseFastMutex(&PspActiveProcessMutex
);
156 /* Delete the CID Handle */
157 if(Process
->UniqueProcessId
!= NULL
) {
159 PsDeleteCidHandle(Process
->UniqueProcessId
, PsProcessType
);
163 KDB_DELETEPROCESS_HOOK(Process
);
165 /* Dereference the Token and release Memory Information */
166 ObDereferenceObject(Process
->Token
);
167 MmReleaseMmInfo(Process
);
169 /* Delete the W32PROCESS structure if there's one associated */
170 if(Process
->Win32Process
!= NULL
) ExFreePool(Process
->Win32Process
);
175 PspDeleteThread(PVOID ObjectBody
)
177 PETHREAD Thread
= (PETHREAD
)ObjectBody
;
178 PEPROCESS Process
= Thread
->ThreadsProcess
;
180 DPRINT("PiDeleteThread(ObjectBody 0x%x, process 0x%x)\n",ObjectBody
, Thread
->ThreadsProcess
);
182 /* Deassociate the Process */
183 Thread
->ThreadsProcess
= NULL
;
185 /* Delete the CID Handle */
186 if(Thread
->Cid
.UniqueThread
!= NULL
) {
188 PsDeleteCidHandle(Thread
->Cid
.UniqueThread
, PsThreadType
);
191 /* Free the W32THREAD structure if present */
192 if(Thread
->Tcb
.Win32Thread
!= NULL
) ExFreePool (Thread
->Tcb
.Win32Thread
);
194 /* Release the Kernel Stack */
195 MmDeleteKernelStack((PVOID
)Thread
->Tcb
.StackLimit
, FALSE
);
197 /* Dereference the Process */
198 ObDereferenceObject(Process
);
202 * FUNCTION: Terminates the current thread
203 * See "Windows Internals" - Chapter 13, Page 50-53
207 PspExitThread(NTSTATUS ExitStatus
)
209 PETHREAD CurrentThread
;
211 PEPROCESS CurrentProcess
;
212 PTERMINATION_PORT TerminationPort
;
215 DPRINT("PspExitThread(ExitStatus %x), Current: 0x%x\n", ExitStatus
, PsGetCurrentThread());
217 /* Get the Current Thread and Process */
218 CurrentThread
= PsGetCurrentThread();
219 CurrentProcess
= CurrentThread
->ThreadsProcess
;
221 /* Set the Exit Status and Exit Time */
222 CurrentThread
->ExitStatus
= ExitStatus
;
223 KeQuerySystemTime(&CurrentThread
->ExitTime
);
225 /* Can't terminate a thread if it attached another process */
226 if (KeIsAttachedProcess()) {
228 KEBUGCHECKEX(INVALID_PROCESS_ATTACH_ATTEMPT
, (ULONG
) CurrentProcess
,
229 (ULONG
) CurrentThread
->Tcb
.ApcState
.Process
,
230 (ULONG
) CurrentThread
->Tcb
.ApcStateIndex
,
231 (ULONG
) CurrentThread
);
234 /* Lower to Passive Level */
235 KeLowerIrql(PASSIVE_LEVEL
);
237 /* Lock the Process before we modify its thread entries */
238 PsLockProcess(CurrentProcess
, FALSE
);
240 /* wake up the thread so we don't deadlock on PsLockProcess */
241 KeForceResumeThread(&CurrentThread
->Tcb
);
243 /* Run Thread Notify Routines before we desintegrate the thread */
244 PspRunCreateThreadNotifyRoutines(CurrentThread
, FALSE
);
246 /* Remove the thread from the thread list of its process */
247 RemoveEntryList(&CurrentThread
->ThreadListEntry
);
248 Last
= IsListEmpty(&CurrentProcess
->ThreadListHead
);
250 /* Set the last Thread Exit Status */
251 CurrentProcess
->LastThreadExitStatus
= ExitStatus
;
255 /* Save the Exit Time if not already done by NtTerminateProcess. This
256 happens when the last thread just terminates without explicitly
257 terminating the process. */
258 CurrentProcess
->ExitTime
= CurrentThread
->ExitTime
;
261 /* Check if the process has a debug port */
262 if (CurrentProcess
->DebugPort
) {
264 /* Notify the Debug API. TODO */
265 //Last ? DbgkExitProcess(ExitStatus) : DbgkExitThread(ExitStatus);
268 /* Process the Termination Ports */
269 TerminationPort
= CurrentThread
->TerminationPort
;
270 DPRINT("TerminationPort: %p\n", TerminationPort
);
271 while (TerminationPort
) {
273 /* Send the LPC Message */
274 LpcSendTerminationPort(TerminationPort
->Port
, CurrentThread
->CreateTime
);
277 ExFreePool(TerminationPort
);
279 /* Get the next one */
280 TerminationPort
= TerminationPort
->Next
;
281 DPRINT("TerminationPort: %p\n", TerminationPort
);
284 /* Rundown Win32 Structures */
285 PsTerminateWin32Thread(CurrentThread
);
286 if (Last
) PsTerminateWin32Process(CurrentProcess
);
288 /* Rundown Registry Notifications. TODO (refers to NtChangeNotify, not Cm callbacks) */
289 //CmNotifyRunDown(CurrentThread);
292 if((Teb
= CurrentThread
->Tcb
.Teb
)) {
294 DPRINT("Decommit teb at %p\n", Teb
);
295 MmDeleteTeb(CurrentProcess
, Teb
);
296 CurrentThread
->Tcb
.Teb
= NULL
;
299 /* The last Thread shuts down the Process */
300 if (Last
) PspExitProcess(CurrentProcess
);
302 /* Unlock the Process */
303 PsUnlockProcess(CurrentProcess
);
305 /* Cancel I/O for the thread. */
306 IoCancelThreadIo(CurrentThread
);
310 KeCancelTimer(&CurrentThread
->Tcb
.Timer
);
312 /* If the Processor Control Block's NpxThread points to the current thread
315 InterlockedCompareExchangePointer(&KeGetCurrentPrcb()->NpxThread
,
317 (PKPROCESS
)CurrentThread
);
319 /* Rundown Mutexes */
322 /* Terminate the Thread from the Scheduler */
323 KeTerminateThread(0);
324 DPRINT1("Unexpected return, CurrentThread %x PsGetCurrentThread() %x\n", CurrentThread
, PsGetCurrentThread());
330 PsExitSpecialApc(PKAPC Apc
,
331 PKNORMAL_ROUTINE
* NormalRoutine
,
332 PVOID
* NormalContext
,
333 PVOID
* SystemArgument1
,
334 PVOID
* SystemArguemnt2
)
336 NTSTATUS ExitStatus
= (NTSTATUS
)Apc
->NormalContext
;
338 DPRINT("PsExitSpecialApc called: 0x%x (proc: 0x%x)\n", PsGetCurrentThread(), PsGetCurrentProcess());
343 /* Terminate the Thread */
344 PspExitThread(ExitStatus
);
346 /* we should never reach this point! */
352 PspExitNormalApc(PVOID NormalContext
,
353 PVOID SystemArgument1
,
354 PVOID SystemArgument2
)
356 /* Not fully supported yet... must work out some issues that
357 * I don't understand yet -- Alex
360 PspExitThread((NTSTATUS
)NormalContext
);
362 /* we should never reach this point! */
367 * See "Windows Internals" - Chapter 13, Page 49
371 PspTerminateThreadByPointer(PETHREAD Thread
,
376 DPRINT("PspTerminatedThreadByPointer(Thread %x, ExitStatus %x)\n",
379 /* Check if we are already in the right context */
380 if (PsGetCurrentThread() == Thread
) {
382 /* Directly terminate the thread */
383 PspExitThread(ExitStatus
);
385 /* we should never reach this point! */
389 /* Allocate the APC */
390 Apc
= ExAllocatePoolWithTag(NonPagedPool
, sizeof(KAPC
), TAG_TERMINATE_APC
);
392 /* Initialize a Kernel Mode APC to Kill the Thread */
395 OriginalApcEnvironment
,
402 /* Insert it into the APC Queue */
403 KeInsertQueueApc(Apc
,
408 /* Forcefully resume the thread */
409 KeForceResumeThread(&Thread
->Tcb
);
414 PspExitProcess(PEPROCESS Process
)
416 DPRINT("PspExitProcess 0x%x\n", Process
);
418 PspRunCreateProcessNotifyRoutines(Process
, FALSE
);
420 /* close all handles associated with our process, this needs to be done
421 when the last thread still runs */
422 ObKillProcess(Process
);
424 KeSetProcess(&Process
->Pcb
, IO_NO_INCREMENT
);
426 return(STATUS_SUCCESS
);
431 NtTerminateProcess(IN HANDLE ProcessHandle OPTIONAL
,
432 IN NTSTATUS ExitStatus
)
436 PETHREAD CurrentThread
;
437 BOOLEAN KillByHandle
;
441 DPRINT("NtTerminateProcess(ProcessHandle %x, ExitStatus %x)\n",
442 ProcessHandle
, ExitStatus
);
444 KillByHandle
= (ProcessHandle
!= NULL
);
446 /* Get the Process Object */
447 Status
= ObReferenceObjectByHandle((KillByHandle
? ProcessHandle
: NtCurrentProcess()),
453 if (!NT_SUCCESS(Status
)) {
455 DPRINT1("Invalid handle to Process\n");
459 CurrentThread
= PsGetCurrentThread();
461 PsLockProcess(Process
, FALSE
);
463 if(Process
->ExitTime
.QuadPart
!= 0)
465 PsUnlockProcess(Process
);
466 return STATUS_PROCESS_IS_TERMINATING
;
469 /* Terminate all the Process's Threads */
470 PspTerminateProcessThreads(Process
, ExitStatus
);
472 /* only kill the calling thread if it either passed a process handle or
473 NtCurrentProcess() */
476 /* set the exit time as we're about to release the process lock before
477 we kill ourselves to prevent threads outside of our process trying
479 KeQuerySystemTime(&Process
->ExitTime
);
481 /* Only master thread remains... kill it off */
482 if (CurrentThread
->ThreadsProcess
== Process
) {
484 /* mark our thread as terminating so attempts to terminate it, when
485 unlocking the process, fail */
486 CurrentThread
->HasTerminated
= TRUE
;
488 PsUnlockProcess(Process
);
490 /* we can safely dereference the process because the current thread
491 holds a reference to it until it gets reaped */
492 ObDereferenceObject(Process
);
494 /* now the other threads get a chance to terminate, we don't wait but
495 just kill ourselves right now. The process will be run down when the
496 last thread terminates */
498 PspExitThread(ExitStatus
);
500 /* we should never reach this point! */
505 /* unlock and dereference the process so the threads can kill themselves */
506 PsUnlockProcess(Process
);
507 ObDereferenceObject(Process
);
509 return(STATUS_SUCCESS
);
514 NtTerminateThread(IN HANDLE ThreadHandle
,
515 IN NTSTATUS ExitStatus
)
522 /* Get the Thread Object */
523 Status
= ObReferenceObjectByHandle(ThreadHandle
,
529 if (!NT_SUCCESS(Status
)) {
531 DPRINT1("Could not reference thread object\n");
535 /* Make sure this is not a system thread */
536 if (PsIsSystemThread(Thread
)) {
538 DPRINT1("Trying to Terminate a system thread!\n");
539 ObDereferenceObject(Thread
);
540 return STATUS_INVALID_PARAMETER
;
543 /* Check to see if we're running in the same thread */
544 if (Thread
!= PsGetCurrentThread()) {
546 /* we need to lock the process to make sure it's not already terminating */
547 PsLockProcess(Thread
->ThreadsProcess
, FALSE
);
549 /* This isn't our thread, terminate it if not already done */
550 if (!Thread
->HasTerminated
) {
552 Thread
->HasTerminated
= TRUE
;
555 PspTerminateThreadByPointer(Thread
, ExitStatus
);
558 PsUnlockProcess(Thread
->ThreadsProcess
);
560 /* Dereference the Thread and return */
561 ObDereferenceObject(Thread
);
565 Thread
->HasTerminated
= TRUE
;
567 /* it's safe to dereference thread, there's at least the keep-alive
568 reference which will be removed by the thread reaper causing the
569 thread to be finally destroyed */
570 ObDereferenceObject(Thread
);
572 /* Terminate him, he's ours */
573 PspExitThread(ExitStatus
);
575 /* We do never reach this point */
579 return(STATUS_SUCCESS
);
587 PsTerminateSystemThread(NTSTATUS ExitStatus
)
589 PETHREAD Thread
= PsGetCurrentThread();
591 /* Make sure this is a system thread */
592 if (!PsIsSystemThread(Thread
)) {
594 DPRINT1("Trying to Terminate a non-system thread!\n");
595 return STATUS_INVALID_PARAMETER
;
598 /* Terminate it for real */
599 PspExitThread(ExitStatus
);
601 /* we should never reach this point! */
604 return(STATUS_SUCCESS
);
609 NtRegisterThreadTerminatePort(HANDLE PortHandle
)
612 PTERMINATION_PORT TerminationPort
;
613 PVOID TerminationLpcPort
;
619 Status
= ObReferenceObjectByHandle(PortHandle
,
625 if (!NT_SUCCESS(Status
)) {
627 DPRINT1("Failed to reference Port\n");
631 /* Allocate the Port and make sure it suceeded */
632 if((TerminationPort
= ExAllocatePoolWithTag(NonPagedPool
,
633 sizeof(PTERMINATION_PORT
),
634 TAG('P', 's', 'T', '=')))) {
636 /* Associate the Port */
637 Thread
= PsGetCurrentThread();
638 TerminationPort
->Port
= TerminationLpcPort
;
639 DPRINT("TerminationPort: %p\n", TerminationPort
);
640 TerminationPort
->Next
= Thread
->TerminationPort
;
641 Thread
->TerminationPort
= TerminationPort
;
642 DPRINT("TerminationPort: %p\n", Thread
->TerminationPort
);
645 return(STATUS_SUCCESS
);
649 /* Dereference and Fail */
650 ObDereferenceObject(TerminationPort
);
651 return(STATUS_INSUFFICIENT_RESOURCES
);