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
;
25 /* FUNCTIONS *****************************************************************/
29 PspReapRoutine(PVOID Context
)
32 PETHREAD Thread
, NewThread
;
35 DPRINT("Evil reaper running!!\n");
36 OldIrql
= KeAcquireDispatcherDatabaseLock();
38 /* Get the first Thread Entry */
39 Thread
= PspReaperList
;
41 DPRINT("PspReaperList: %x\n", Thread
);
43 /* Check to see if the list is empty */
46 /* Unlock the Dispatcher */
47 KeReleaseDispatcherDatabaseLock(OldIrql
);
49 /* Is there a thread on the list? */
52 /* Get the next Thread */
53 DPRINT("Thread: %x\n", Thread
);
54 DPRINT("Thread: %x\n", Thread
->ReaperLink
);
55 NewThread
= Thread
->ReaperLink
;
57 /* Remove reference to current thread */
58 ObDereferenceObject(Thread
);
60 /* Move to next Thread */
64 /* No more linked threads... Reacquire the Lock */
65 OldIrql
= KeAcquireDispatcherDatabaseLock();
67 /* Now try to get a new thread from the list */
68 Thread
= PspReaperList
;
70 DPRINT("PspReaperList: %x\n", Thread
);
72 /* Loop again if there is a new thread */
76 DPRINT("Done reaping\n");
77 KeReleaseDispatcherDatabaseLock(OldIrql
);
82 PspKillMostProcesses(VOID
)
84 PLIST_ENTRY current_entry
;
87 /* Acquire the Active Process Lock */
88 ExAcquireFastMutex(&PspActiveProcessMutex
);
90 /* Loop all processes on the list */
91 current_entry
= PsActiveProcessHead
.Flink
;
92 while (current_entry
!= &PsActiveProcessHead
)
94 current
= CONTAINING_RECORD(current_entry
, EPROCESS
, ActiveProcessLinks
);
95 current_entry
= current_entry
->Flink
;
97 if (current
->UniqueProcessId
!= PsInitialSystemProcess
->UniqueProcessId
&&
98 current
->UniqueProcessId
!= PsGetCurrentProcessId())
100 /* Terminate all the Threads in this Process */
101 PspTerminateProcessThreads(current
, STATUS_SUCCESS
);
105 /* Release the lock */
106 ExReleaseFastMutex(&PspActiveProcessMutex
);
111 PspTerminateProcessThreads(PEPROCESS Process
,
114 PLIST_ENTRY CurrentEntry
;
115 PETHREAD Thread
, CurrentThread
= PsGetCurrentThread();
117 CurrentEntry
= Process
->ThreadListHead
.Flink
;
118 while (CurrentEntry
!= &Process
->ThreadListHead
) {
120 /* Get the Current Thread */
121 Thread
= CONTAINING_RECORD(CurrentEntry
, ETHREAD
, ThreadListEntry
);
123 /* Move to the Next Thread */
124 CurrentEntry
= CurrentEntry
->Flink
;
126 /* Make sure it's not the one we're in */
127 if (Thread
!= CurrentThread
) {
129 /* Make sure it didn't already terminate */
130 if (!Thread
->Terminated
) {
132 Thread
->Terminated
= TRUE
;
134 /* Terminate it by APC */
135 PspTerminateThreadByPointer(Thread
, ExitStatus
);
143 PspDeleteProcess(PVOID ObjectBody
)
145 PEPROCESS Process
= (PEPROCESS
)ObjectBody
;
147 DPRINT("PiDeleteProcess(ObjectBody %x)\n", ObjectBody
);
149 /* Remove it from the Active List */
150 ExAcquireFastMutex(&PspActiveProcessMutex
);
151 RemoveEntryList(&Process
->ActiveProcessLinks
);
152 ExReleaseFastMutex(&PspActiveProcessMutex
);
154 /* Delete the CID Handle */
155 if(Process
->UniqueProcessId
!= NULL
) {
157 PsDeleteCidHandle(Process
->UniqueProcessId
, PsProcessType
);
161 KDB_DELETEPROCESS_HOOK(Process
);
163 /* Dereference the Token */
164 SeDeassignPrimaryToken(Process
);
166 /* Release Memory Information */
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 while ((TerminationPort
= CurrentThread
->TerminationPort
)) {
271 DPRINT("TerminationPort: %p\n", TerminationPort
);
273 /* Get the next one */
274 CurrentThread
->TerminationPort
= TerminationPort
->Next
;
276 /* Send the LPC Message */
277 LpcSendTerminationPort(TerminationPort
->Port
, CurrentThread
->CreateTime
);
280 ExFreePool(TerminationPort
);
283 /* Rundown Win32 Structures */
284 PsTerminateWin32Thread(CurrentThread
);
285 if (Last
) PsTerminateWin32Process(CurrentProcess
);
287 /* Rundown Registry Notifications. TODO (refers to NtChangeNotify, not Cm callbacks) */
288 //CmNotifyRunDown(CurrentThread);
291 if((Teb
= CurrentThread
->Tcb
.Teb
)) {
293 DPRINT("Decommit teb at %p\n", Teb
);
294 MmDeleteTeb(CurrentProcess
, Teb
);
295 CurrentThread
->Tcb
.Teb
= NULL
;
298 /* The last Thread shuts down the Process */
299 if (Last
) PspExitProcess(CurrentProcess
);
301 /* Unlock the Process */
302 PsUnlockProcess(CurrentProcess
);
304 /* Cancel I/O for the thread. */
305 IoCancelThreadIo(CurrentThread
);
309 KeCancelTimer(&CurrentThread
->Tcb
.Timer
);
311 /* If the Processor Control Block's NpxThread points to the current thread
314 InterlockedCompareExchangePointer(&KeGetCurrentPrcb()->NpxThread
,
316 (PKPROCESS
)CurrentThread
);
318 /* Rundown Mutexes */
321 /* Terminate the Thread from the Scheduler */
322 KeTerminateThread(0);
323 DPRINT1("Unexpected return, CurrentThread %x PsGetCurrentThread() %x\n", CurrentThread
, PsGetCurrentThread());
329 PsExitSpecialApc(PKAPC Apc
,
330 PKNORMAL_ROUTINE
* NormalRoutine
,
331 PVOID
* NormalContext
,
332 PVOID
* SystemArgument1
,
333 PVOID
* SystemArguemnt2
)
335 NTSTATUS ExitStatus
= (NTSTATUS
)Apc
->NormalContext
;
337 DPRINT("PsExitSpecialApc called: 0x%x (proc: 0x%x)\n", PsGetCurrentThread(), PsGetCurrentProcess());
342 /* Terminate the Thread */
343 PspExitThread(ExitStatus
);
345 /* we should never reach this point! */
351 PspExitNormalApc(PVOID NormalContext
,
352 PVOID SystemArgument1
,
353 PVOID SystemArgument2
)
355 /* Not fully supported yet... must work out some issues that
356 * I don't understand yet -- Alex
359 PspExitThread((NTSTATUS
)NormalContext
);
361 /* we should never reach this point! */
366 * See "Windows Internals" - Chapter 13, Page 49
370 PspTerminateThreadByPointer(PETHREAD Thread
,
375 DPRINT("PspTerminatedThreadByPointer(Thread %x, ExitStatus %x)\n",
378 /* Check if we are already in the right context */
379 if (PsGetCurrentThread() == Thread
) {
381 /* Directly terminate the thread */
382 PspExitThread(ExitStatus
);
384 /* we should never reach this point! */
388 /* Allocate the APC */
389 Apc
= ExAllocatePoolWithTag(NonPagedPool
, sizeof(KAPC
), TAG_TERMINATE_APC
);
391 /* Initialize a Kernel Mode APC to Kill the Thread */
394 OriginalApcEnvironment
,
401 /* Insert it into the APC Queue */
402 KeInsertQueueApc(Apc
,
407 /* Forcefully resume the thread */
408 KeForceResumeThread(&Thread
->Tcb
);
413 PspExitProcess(PEPROCESS Process
)
415 DPRINT("PspExitProcess 0x%x\n", Process
);
417 PspRunCreateProcessNotifyRoutines(Process
, FALSE
);
419 /* close all handles associated with our process, this needs to be done
420 when the last thread still runs */
421 ObKillProcess(Process
);
423 KeSetProcess(&Process
->Pcb
, IO_NO_INCREMENT
);
425 return(STATUS_SUCCESS
);
430 NtTerminateProcess(IN HANDLE ProcessHandle OPTIONAL
,
431 IN NTSTATUS ExitStatus
)
435 PETHREAD CurrentThread
;
436 BOOLEAN KillByHandle
;
440 DPRINT("NtTerminateProcess(ProcessHandle %x, ExitStatus %x)\n",
441 ProcessHandle
, ExitStatus
);
443 KillByHandle
= (ProcessHandle
!= NULL
);
445 /* Get the Process Object */
446 Status
= ObReferenceObjectByHandle((KillByHandle
? ProcessHandle
: NtCurrentProcess()),
452 if (!NT_SUCCESS(Status
)) {
454 DPRINT1("Invalid handle to Process\n");
458 CurrentThread
= PsGetCurrentThread();
460 PsLockProcess(Process
, FALSE
);
462 if(Process
->ExitTime
.QuadPart
!= 0)
464 PsUnlockProcess(Process
);
465 ObDereferenceObject(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
->Terminated
= 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
->Terminated
) {
552 Thread
->Terminated
= TRUE
;
555 PspTerminateThreadByPointer(Thread
, ExitStatus
);
558 PsUnlockProcess(Thread
->ThreadsProcess
);
560 /* Dereference the Thread and return */
561 ObDereferenceObject(Thread
);
565 Thread
->Terminated
= 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
);