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
, ActiveProcessLinks
);
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
->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
!= NULL
) {
159 PsDeleteCidHandle(Process
->UniqueProcessId
, PsProcessType
);
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
!= NULL
) {
190 PsDeleteCidHandle(Thread
->Cid
.UniqueThread
, PsThreadType
);
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 DPRINT("PspExitThread(ExitStatus %x), Current: 0x%x\n", ExitStatus
, PsGetCurrentThread());
219 /* Get the Current Thread and Process */
220 CurrentThread
= PsGetCurrentThread();
221 CurrentProcess
= CurrentThread
->ThreadsProcess
;
223 /* Set the Exit Status and Exit Time */
224 CurrentThread
->ExitStatus
= ExitStatus
;
225 KeQuerySystemTime(&CurrentThread
->ExitTime
);
227 /* Can't terminate a thread if it attached another process */
228 if (KeIsAttachedProcess()) {
230 KEBUGCHECKEX(INVALID_PROCESS_ATTACH_ATTEMPT
, (ULONG
) CurrentProcess
,
231 (ULONG
) CurrentThread
->Tcb
.ApcState
.Process
,
232 (ULONG
) CurrentThread
->Tcb
.ApcStateIndex
,
233 (ULONG
) CurrentThread
);
236 /* Lower to Passive Level */
237 KeLowerIrql(PASSIVE_LEVEL
);
239 /* Lock the Process before we modify its thread entries */
240 PsLockProcess(CurrentProcess
, FALSE
);
242 /* wake up the thread so we don't deadlock on PsLockProcess */
243 KeForceResumeThread(&CurrentThread
->Tcb
);
245 /* Run Thread Notify Routines before we desintegrate the thread */
246 PspRunCreateThreadNotifyRoutines(CurrentThread
, FALSE
);
248 /* Remove the thread from the thread list of its process */
249 RemoveEntryList(&CurrentThread
->ThreadListEntry
);
250 Last
= IsListEmpty(&CurrentProcess
->ThreadListHead
);
252 /* Set the last Thread Exit Status */
253 CurrentProcess
->LastThreadExitStatus
= ExitStatus
;
257 /* Save the Exit Time if not already done by NtTerminateProcess. This
258 happens when the last thread just terminates without explicitly
259 terminating the process. */
260 CurrentProcess
->ExitTime
= CurrentThread
->ExitTime
;
263 /* Check if the process has a debug port */
264 if (CurrentProcess
->DebugPort
) {
266 /* Notify the Debug API. TODO */
267 //Last ? DbgkExitProcess(ExitStatus) : DbgkExitThread(ExitStatus);
270 /* Process the Termination Ports */
271 TerminationPort
= CurrentThread
->TerminationPort
;
272 DPRINT("TerminationPort: %p\n", TerminationPort
);
273 while (TerminationPort
) {
275 /* Send the LPC Message */
276 LpcSendTerminationPort(TerminationPort
->Port
, CurrentThread
->CreateTime
);
279 ExFreePool(TerminationPort
);
281 /* Get the next one */
282 TerminationPort
= TerminationPort
->Next
;
283 DPRINT("TerminationPort: %p\n", TerminationPort
);
286 /* Rundown Win32 Structures */
287 PsTerminateWin32Thread(CurrentThread
);
288 if (Last
) PsTerminateWin32Process(CurrentProcess
);
290 /* Rundown Registry Notifications. TODO (refers to NtChangeNotify, not Cm callbacks) */
291 //CmNotifyRunDown(CurrentThread);
294 if((Teb
= CurrentThread
->Tcb
.Teb
)) {
296 DPRINT("Decommit teb at %p\n", Teb
);
297 MmDeleteTeb(CurrentProcess
, Teb
);
298 CurrentThread
->Tcb
.Teb
= NULL
;
301 /* The last Thread shuts down the Process */
302 if (Last
) PspExitProcess(CurrentProcess
);
304 /* Unlock the Process */
305 PsUnlockProcess(CurrentProcess
);
307 /* Cancel I/O for the thread. */
308 IoCancelThreadIo(CurrentThread
);
312 KeCancelTimer(&CurrentThread
->Tcb
.Timer
);
314 /* If the Processor Control Block's NpxThread points to the current thread
317 InterlockedCompareExchangePointer(&KeGetCurrentPrcb()->NpxThread
,
319 (PKPROCESS
)CurrentThread
);
321 /* Rundown Mutexes */
324 /* Terminate the Thread from the Scheduler */
325 KeTerminateThread(0);
326 DPRINT1("Unexpected return, CurrentThread %x PsGetCurrentThread() %x\n", CurrentThread
, PsGetCurrentThread());
332 PsExitSpecialApc(PKAPC Apc
,
333 PKNORMAL_ROUTINE
* NormalRoutine
,
334 PVOID
* NormalContext
,
335 PVOID
* SystemArgument1
,
336 PVOID
* SystemArguemnt2
)
338 NTSTATUS ExitStatus
= (NTSTATUS
)Apc
->NormalContext
;
340 DPRINT("PsExitSpecialApc called: 0x%x (proc: 0x%x)\n", PsGetCurrentThread(), PsGetCurrentProcess());
345 /* Terminate the Thread */
346 PspExitThread(ExitStatus
);
348 /* we should never reach this point! */
354 PspExitNormalApc(PVOID NormalContext
,
355 PVOID SystemArgument1
,
356 PVOID SystemArgument2
)
358 /* Not fully supported yet... must work out some issues that
359 * I don't understand yet -- Alex
362 PspExitThread((NTSTATUS
)NormalContext
);
364 /* we should never reach this point! */
369 * See "Windows Internals" - Chapter 13, Page 49
373 PspTerminateThreadByPointer(PETHREAD Thread
,
378 DPRINT("PspTerminatedThreadByPointer(Thread %x, ExitStatus %x)\n",
381 /* Check if we are already in the right context */
382 if (PsGetCurrentThread() == Thread
) {
384 /* Directly terminate the thread */
385 PspExitThread(ExitStatus
);
387 /* we should never reach this point! */
391 /* Allocate the APC */
392 Apc
= ExAllocatePoolWithTag(NonPagedPool
, sizeof(KAPC
), TAG_TERMINATE_APC
);
394 /* Initialize a Kernel Mode APC to Kill the Thread */
397 OriginalApcEnvironment
,
404 /* Insert it into the APC Queue */
405 KeInsertQueueApc(Apc
,
410 /* Forcefully resume the thread */
411 KeForceResumeThread(&Thread
->Tcb
);
416 PspExitProcess(PEPROCESS Process
)
418 DPRINT("PspExitProcess 0x%x\n", Process
);
420 PspRunCreateProcessNotifyRoutines(Process
, FALSE
);
422 /* close all handles associated with our process, this needs to be done
423 when the last thread still runs */
424 ObKillProcess(Process
);
426 KeSetProcess(&Process
->Pcb
, IO_NO_INCREMENT
);
428 return(STATUS_SUCCESS
);
433 NtTerminateProcess(IN HANDLE ProcessHandle OPTIONAL
,
434 IN NTSTATUS ExitStatus
)
438 PETHREAD CurrentThread
;
439 BOOLEAN KillByHandle
;
443 DPRINT("NtTerminateProcess(ProcessHandle %x, ExitStatus %x)\n",
444 ProcessHandle
, ExitStatus
);
446 KillByHandle
= (ProcessHandle
!= NULL
);
448 /* Get the Process Object */
449 Status
= ObReferenceObjectByHandle((KillByHandle
? ProcessHandle
: NtCurrentProcess()),
455 if (!NT_SUCCESS(Status
)) {
457 DPRINT1("Invalid handle to Process\n");
461 CurrentThread
= PsGetCurrentThread();
463 PsLockProcess(Process
, FALSE
);
465 if(Process
->ExitTime
.QuadPart
!= 0)
467 PsUnlockProcess(Process
);
468 return STATUS_PROCESS_IS_TERMINATING
;
471 /* Terminate all the Process's Threads */
472 PspTerminateProcessThreads(Process
, ExitStatus
);
474 /* only kill the calling thread if it either passed a process handle or
475 NtCurrentProcess() */
478 /* set the exit time as we're about to release the process lock before
479 we kill ourselves to prevent threads outside of our process trying
481 KeQuerySystemTime(&Process
->ExitTime
);
483 /* Only master thread remains... kill it off */
484 if (CurrentThread
->ThreadsProcess
== Process
) {
486 /* mark our thread as terminating so attempts to terminate it, when
487 unlocking the process, fail */
488 CurrentThread
->Terminated
= TRUE
;
490 PsUnlockProcess(Process
);
492 /* we can safely dereference the process because the current thread
493 holds a reference to it until it gets reaped */
494 ObDereferenceObject(Process
);
496 /* now the other threads get a chance to terminate, we don't wait but
497 just kill ourselves right now. The process will be run down when the
498 last thread terminates */
500 PspExitThread(ExitStatus
);
502 /* we should never reach this point! */
507 /* unlock and dereference the process so the threads can kill themselves */
508 PsUnlockProcess(Process
);
509 ObDereferenceObject(Process
);
511 return(STATUS_SUCCESS
);
516 NtTerminateThread(IN HANDLE ThreadHandle
,
517 IN NTSTATUS ExitStatus
)
524 /* Get the Thread Object */
525 Status
= ObReferenceObjectByHandle(ThreadHandle
,
531 if (!NT_SUCCESS(Status
)) {
533 DPRINT1("Could not reference thread object\n");
537 /* Make sure this is not a system thread */
538 if (PsIsSystemThread(Thread
)) {
540 DPRINT1("Trying to Terminate a system thread!\n");
541 ObDereferenceObject(Thread
);
542 return STATUS_INVALID_PARAMETER
;
545 /* Check to see if we're running in the same thread */
546 if (Thread
!= PsGetCurrentThread()) {
548 /* we need to lock the process to make sure it's not already terminating */
549 PsLockProcess(Thread
->ThreadsProcess
, FALSE
);
551 /* This isn't our thread, terminate it if not already done */
552 if (!Thread
->Terminated
) {
554 Thread
->Terminated
= TRUE
;
557 PspTerminateThreadByPointer(Thread
, ExitStatus
);
560 PsUnlockProcess(Thread
->ThreadsProcess
);
562 /* Dereference the Thread and return */
563 ObDereferenceObject(Thread
);
567 Thread
->Terminated
= TRUE
;
569 /* it's safe to dereference thread, there's at least the keep-alive
570 reference which will be removed by the thread reaper causing the
571 thread to be finally destroyed */
572 ObDereferenceObject(Thread
);
574 /* Terminate him, he's ours */
575 PspExitThread(ExitStatus
);
577 /* We do never reach this point */
581 return(STATUS_SUCCESS
);
589 PsTerminateSystemThread(NTSTATUS ExitStatus
)
591 PETHREAD Thread
= PsGetCurrentThread();
593 /* Make sure this is a system thread */
594 if (!PsIsSystemThread(Thread
)) {
596 DPRINT1("Trying to Terminate a non-system thread!\n");
597 return STATUS_INVALID_PARAMETER
;
600 /* Terminate it for real */
601 PspExitThread(ExitStatus
);
603 /* we should never reach this point! */
606 return(STATUS_SUCCESS
);
611 NtRegisterThreadTerminatePort(HANDLE PortHandle
)
614 PTERMINATION_PORT TerminationPort
;
615 PVOID TerminationLpcPort
;
621 Status
= ObReferenceObjectByHandle(PortHandle
,
627 if (!NT_SUCCESS(Status
)) {
629 DPRINT1("Failed to reference Port\n");
633 /* Allocate the Port and make sure it suceeded */
634 if((TerminationPort
= ExAllocatePoolWithTag(NonPagedPool
,
635 sizeof(PTERMINATION_PORT
),
636 TAG('P', 's', 'T', '=')))) {
638 /* Associate the Port */
639 Thread
= PsGetCurrentThread();
640 TerminationPort
->Port
= TerminationLpcPort
;
641 DPRINT("TerminationPort: %p\n", TerminationPort
);
642 TerminationPort
->Next
= Thread
->TerminationPort
;
643 Thread
->TerminationPort
= TerminationPort
;
644 DPRINT("TerminationPort: %p\n", Thread
->TerminationPort
);
647 return(STATUS_SUCCESS
);
651 /* Dereference and Fail */
652 ObDereferenceObject(TerminationPort
);
653 return(STATUS_INSUFFICIENT_RESOURCES
);