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
;
29 MmDeleteTeb(PEPROCESS Process
,
32 /* FUNCTIONS *****************************************************************/
36 PspReapRoutine(PVOID Context
)
39 PETHREAD Thread
, NewThread
;
42 DPRINT("Evil reaper running!!\n");
43 OldIrql
= KeAcquireDispatcherDatabaseLock();
45 /* Get the first Thread Entry */
46 Thread
= PspReaperList
;
48 DPRINT("PspReaperList: %x\n", Thread
);
50 /* Check to see if the list is empty */
53 /* Unlock the Dispatcher */
54 KeReleaseDispatcherDatabaseLock(OldIrql
);
56 /* Is there a thread on the list? */
59 /* Get the next Thread */
60 DPRINT("Thread: %x\n", Thread
);
61 DPRINT("Thread: %x\n", Thread
->ReaperLink
);
62 NewThread
= Thread
->ReaperLink
;
64 /* Remove reference to current thread */
65 ObDereferenceObject(Thread
);
67 /* Move to next Thread */
71 /* No more linked threads... Reacquire the Lock */
72 OldIrql
= KeAcquireDispatcherDatabaseLock();
74 /* Now try to get a new thread from the list */
75 Thread
= PspReaperList
;
77 DPRINT("PspReaperList: %x\n", Thread
);
79 /* Loop again if there is a new thread */
83 DPRINT("Done reaping\n");
84 KeReleaseDispatcherDatabaseLock(OldIrql
);
89 PspKillMostProcesses(VOID
)
91 PLIST_ENTRY current_entry
;
94 /* Acquire the Active Process Lock */
95 ExAcquireFastMutex(&PspActiveProcessMutex
);
97 /* Loop all processes on the list */
98 current_entry
= PsActiveProcessHead
.Flink
;
99 while (current_entry
!= &PsActiveProcessHead
)
101 current
= CONTAINING_RECORD(current_entry
, EPROCESS
, ProcessListEntry
);
102 current_entry
= current_entry
->Flink
;
104 if (current
->UniqueProcessId
!= PsInitialSystemProcess
->UniqueProcessId
&&
105 current
->UniqueProcessId
!= PsGetCurrentProcessId())
107 /* Terminate all the Threads in this Process */
108 PspTerminateProcessThreads(current
, STATUS_SUCCESS
);
112 /* Release the lock */
113 ExReleaseFastMutex(&PspActiveProcessMutex
);
118 PspTerminateProcessThreads(PEPROCESS Process
,
121 PLIST_ENTRY CurrentEntry
;
122 PETHREAD Thread
, CurrentThread
= PsGetCurrentThread();
124 CurrentEntry
= Process
->ThreadListHead
.Flink
;
125 while (CurrentEntry
!= &Process
->ThreadListHead
) {
127 /* Get the Current Thread */
128 Thread
= CONTAINING_RECORD(CurrentEntry
, ETHREAD
, ThreadListEntry
);
130 /* Move to the Next Thread */
131 CurrentEntry
= CurrentEntry
->Flink
;
133 /* Make sure it's not the one we're in */
134 if (Thread
!= CurrentThread
) {
136 /* Make sure it didn't already terminate */
137 if (!Thread
->HasTerminated
) {
139 Thread
->HasTerminated
= TRUE
;
141 /* Terminate it by APC */
142 PspTerminateThreadByPointer(Thread
, ExitStatus
);
150 PspDeleteProcess(PVOID ObjectBody
)
152 PEPROCESS Process
= (PEPROCESS
)ObjectBody
;
154 DPRINT("PiDeleteProcess(ObjectBody %x)\n", ObjectBody
);
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 Thread */
195 KeReleaseThread(ETHREAD_TO_KTHREAD(Thread
));
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 /* Remove it from the Active List */
421 ExAcquireFastMutex(&PspActiveProcessMutex
);
422 RemoveEntryList(&Process
->ProcessListEntry
);
423 ExReleaseFastMutex(&PspActiveProcessMutex
);
425 /* close all handles associated with our process, this needs to be done
426 when the last thread still runs */
427 ObKillProcess(Process
);
429 KeSetProcess(&Process
->Pcb
, IO_NO_INCREMENT
);
431 return(STATUS_SUCCESS
);
436 NtTerminateProcess(IN HANDLE ProcessHandle OPTIONAL
,
437 IN NTSTATUS ExitStatus
)
441 PETHREAD CurrentThread
;
442 BOOLEAN KillByHandle
;
446 DPRINT("NtTerminateProcess(ProcessHandle %x, ExitStatus %x)\n",
447 ProcessHandle
, ExitStatus
);
449 KillByHandle
= (ProcessHandle
!= NULL
);
451 /* Get the Process Object */
452 Status
= ObReferenceObjectByHandle((KillByHandle
? ProcessHandle
: NtCurrentProcess()),
458 if (!NT_SUCCESS(Status
)) {
460 DPRINT1("Invalid handle to Process\n");
464 CurrentThread
= PsGetCurrentThread();
466 PsLockProcess(Process
, FALSE
);
468 if(Process
->ExitTime
.QuadPart
!= 0)
470 PsUnlockProcess(Process
);
471 return STATUS_PROCESS_IS_TERMINATING
;
474 /* Terminate all the Process's Threads */
475 PspTerminateProcessThreads(Process
, ExitStatus
);
477 /* only kill the calling thread if it either passed a process handle or
478 NtCurrentProcess() */
481 /* set the exit time as we're about to release the process lock before
482 we kill ourselves to prevent threads outside of our process trying
484 KeQuerySystemTime(&Process
->ExitTime
);
486 /* Only master thread remains... kill it off */
487 if (CurrentThread
->ThreadsProcess
== Process
) {
489 /* mark our thread as terminating so attempts to terminate it, when
490 unlocking the process, fail */
491 CurrentThread
->HasTerminated
= TRUE
;
493 PsUnlockProcess(Process
);
495 /* we can safely dereference the process because the current thread
496 holds a reference to it until it gets reaped */
497 ObDereferenceObject(Process
);
499 /* now the other threads get a chance to terminate, we don't wait but
500 just kill ourselves right now. The process will be run down when the
501 last thread terminates */
503 PspExitThread(ExitStatus
);
505 /* we should never reach this point! */
510 /* unlock and dereference the process so the threads can kill themselves */
511 PsUnlockProcess(Process
);
512 ObDereferenceObject(Process
);
514 return(STATUS_SUCCESS
);
519 NtTerminateThread(IN HANDLE ThreadHandle
,
520 IN NTSTATUS ExitStatus
)
527 /* Get the Thread Object */
528 Status
= ObReferenceObjectByHandle(ThreadHandle
,
534 if (!NT_SUCCESS(Status
)) {
536 DPRINT1("Could not reference thread object\n");
540 /* Make sure this is not a system thread */
541 if (PsIsSystemThread(Thread
)) {
543 DPRINT1("Trying to Terminate a system thread!\n");
544 ObDereferenceObject(Thread
);
545 return STATUS_INVALID_PARAMETER
;
548 /* Check to see if we're running in the same thread */
549 if (Thread
!= PsGetCurrentThread()) {
551 /* we need to lock the process to make sure it's not already terminating */
552 PsLockProcess(Thread
->ThreadsProcess
, FALSE
);
554 /* This isn't our thread, terminate it if not already done */
555 if (!Thread
->HasTerminated
) {
557 Thread
->HasTerminated
= TRUE
;
560 PspTerminateThreadByPointer(Thread
, ExitStatus
);
563 PsUnlockProcess(Thread
->ThreadsProcess
);
565 /* Dereference the Thread and return */
566 ObDereferenceObject(Thread
);
570 Thread
->HasTerminated
= TRUE
;
572 /* it's safe to dereference thread, there's at least the keep-alive
573 reference which will be removed by the thread reaper causing the
574 thread to be finally destroyed */
575 ObDereferenceObject(Thread
);
577 /* Terminate him, he's ours */
578 PspExitThread(ExitStatus
);
580 /* We do never reach this point */
584 return(STATUS_SUCCESS
);
592 PsTerminateSystemThread(NTSTATUS ExitStatus
)
594 PETHREAD Thread
= PsGetCurrentThread();
596 /* Make sure this is a system thread */
597 if (!PsIsSystemThread(Thread
)) {
599 DPRINT1("Trying to Terminate a non-system thread!\n");
600 return STATUS_INVALID_PARAMETER
;
603 /* Terminate it for real */
604 PspExitThread(ExitStatus
);
606 /* we should never reach this point! */
609 return(STATUS_SUCCESS
);
614 NtRegisterThreadTerminatePort(HANDLE PortHandle
)
617 PTERMINATION_PORT TerminationPort
;
618 PVOID TerminationLpcPort
;
624 Status
= ObReferenceObjectByHandle(PortHandle
,
630 if (!NT_SUCCESS(Status
)) {
632 DPRINT1("Failed to reference Port\n");
636 /* Allocate the Port and make sure it suceeded */
637 if((TerminationPort
= ExAllocatePoolWithTag(NonPagedPool
,
638 sizeof(PTERMINATION_PORT
),
639 TAG('P', 's', 'T', '=')))) {
641 /* Associate the Port */
642 Thread
= PsGetCurrentThread();
643 TerminationPort
->Port
= TerminationLpcPort
;
644 DPRINT("TerminationPort: %p\n", TerminationPort
);
645 TerminationPort
->Next
= Thread
->TerminationPort
;
646 Thread
->TerminationPort
= TerminationPort
;
647 DPRINT("TerminationPort: %p\n", Thread
->TerminationPort
);
650 return(STATUS_SUCCESS
);
654 /* Dereference and Fail */
655 ObDereferenceObject(TerminationPort
);
656 return(STATUS_INSUFFICIENT_RESOURCES
);