2 * PROJECT: ReactOS Kernel
3 * LICENSE: GPL - See COPYING in the top level directory
4 * FILE: ntoskrnl/ps/kill.c
5 * PURPOSE: Process Manager: Process and Thread Termination
6 * PROGRAMMERS: Alex Ionescu (alex.ionescu@reactos.org)
7 * Filip Navara (xnavara@reactos.org)
8 * Thomas Weidenmueller (w3seek@reactos.org
11 /* INCLUDES *****************************************************************/
17 /* GLOBALS *******************************************************************/
19 LIST_ENTRY PspReaperListHead
= { NULL
, NULL
};
20 WORK_QUEUE_ITEM PspReaperWorkItem
;
21 LARGE_INTEGER ShortTime
= {{-10 * 100 * 1000, -1}};
23 /* PRIVATE FUNCTIONS *********************************************************/
27 PspCatchCriticalBreak(IN PCHAR Message
,
28 IN PVOID ProcessOrThread
,
32 BOOLEAN Handled
= FALSE
;
35 /* Check if a debugger is enabled */
36 if (KdDebuggerEnabled
)
38 /* Print out the message */
39 DbgPrint(Message
, ProcessOrThread
, ImageName
);
42 /* If a debugger isn't present, don't prompt */
43 if (KdDebuggerNotPresent
) break;
45 /* A debuger is active, prompt for action */
46 DbgPrompt("Break, or Ignore (bi)?", Action
, sizeof(Action
));
68 /* Did we ultimately handle this? */
71 /* We didn't, bugcheck */
72 KeBugCheckEx(CRITICAL_OBJECT_TERMINATION
,
73 ((PKPROCESS
)ProcessOrThread
)->Header
.Type
,
74 (ULONG_PTR
)ProcessOrThread
,
82 PspTerminateProcess(IN PEPROCESS Process
,
83 IN NTSTATUS ExitStatus
)
86 NTSTATUS Status
= STATUS_NOTHING_TO_TERMINATE
;
88 PSTRACE(PS_KILL_DEBUG
,
89 "Process: %p ExitStatus: %p\n", Process
, ExitStatus
);
92 /* Check if this is a Critical Process */
93 if (Process
->BreakOnTermination
)
95 /* Break to debugger */
96 PspCatchCriticalBreak("Terminating critical process 0x%p (%s)\n",
98 Process
->ImageFileName
);
101 /* Set the delete flag */
102 InterlockedOr((PLONG
)&Process
->Flags
, PSF_PROCESS_DELETE_BIT
);
104 /* Get the first thread */
105 Thread
= PsGetNextProcessThread(Process
, NULL
);
109 PspTerminateThreadByPointer(Thread
, ExitStatus
, FALSE
);
110 Thread
= PsGetNextProcessThread(Process
, Thread
);
112 /* We had at least one thread, so termination is OK */
113 Status
= STATUS_SUCCESS
;
116 /* Check if there was nothing to terminate or if we have a debug port */
117 if ((Status
== STATUS_NOTHING_TO_TERMINATE
) || (Process
->DebugPort
))
119 /* Clear the handle table anyway */
120 ObClearProcessHandleTable(Process
);
129 PsTerminateProcess(IN PEPROCESS Process
,
130 IN NTSTATUS ExitStatus
)
132 /* Call the internal API */
133 return PspTerminateProcess(Process
, ExitStatus
);
138 PspShutdownProcessManager(VOID
)
140 PEPROCESS Process
= NULL
;
142 /* Loop every process */
143 Process
= PsGetNextProcess(Process
);
146 /* Make sure this isn't the idle or initial process */
147 if ((Process
!= PsInitialSystemProcess
) && (Process
!= PsIdleProcess
))
150 PspTerminateProcess(Process
, STATUS_SYSTEM_SHUTDOWN
);
153 /* Get the next process */
154 Process
= PsGetNextProcess(Process
);
160 PspExitApcRundown(IN PKAPC Apc
)
170 PspReapRoutine(IN PVOID Context
)
172 PSINGLE_LIST_ENTRY NextEntry
;
174 PSTRACE(PS_KILL_DEBUG
, "Context: %p\n", Context
);
176 /* Start main loop */
179 /* Write magic value and return the next entry to process */
180 NextEntry
= InterlockedExchangePointer(&PspReaperListHead
.Flink
,
182 ASSERT((NextEntry
!= NULL
) && (NextEntry
!= (PVOID
)1));
184 /* Start inner loop */
187 /* Get the first Thread Entry */
188 Thread
= CONTAINING_RECORD(NextEntry
, ETHREAD
, ReaperLink
);
190 /* Delete this entry's kernel stack */
191 MmDeleteKernelStack((PVOID
)Thread
->Tcb
.StackBase
,
192 Thread
->Tcb
.LargeStack
);
193 Thread
->Tcb
.InitialStack
= NULL
;
195 /* Move to the next entry */
196 NextEntry
= NextEntry
->Next
;
198 /* Dereference this thread */
199 ObDereferenceObject(Thread
);
200 } while ((NextEntry
!= NULL
) && (NextEntry
!= (PVOID
)1));
202 /* Remove magic value, keep looping if it got changed */
203 } while (InterlockedCompareExchangePointer(&PspReaperListHead
.Flink
,
210 PspDeleteProcess(IN PVOID ObjectBody
)
212 PEPROCESS Process
= (PEPROCESS
)ObjectBody
;
215 PSTRACE(PS_KILL_DEBUG
, "ObjectBody: %p\n", ObjectBody
);
218 /* Check if it has an Active Process Link */
219 if (Process
->ActiveProcessLinks
.Flink
)
221 /* Remove it from the Active List */
222 KeAcquireGuardedMutex(&PspActiveProcessMutex
);
223 RemoveEntryList(&Process
->ActiveProcessLinks
);
224 KeReleaseGuardedMutex(&PspActiveProcessMutex
);
227 /* Check for Auditing information */
228 if (Process
->SeAuditProcessCreationInfo
.ImageFileName
)
231 ExFreePool(Process
->SeAuditProcessCreationInfo
.ImageFileName
);
232 Process
->SeAuditProcessCreationInfo
.ImageFileName
= NULL
;
235 /* Check if we have a job */
238 /* Remove the process from the job */
239 PspRemoveProcessFromJob(Process
, Process
->Job
);
242 ObDereferenceObject(Process
->Job
);
246 /* Increase the stack count */
247 Process
->Pcb
.StackCount
++;
249 /* Check if we have a debug port */
250 if (Process
->DebugPort
)
252 /* Deference the Debug Port */
253 ObDereferenceObject(Process
->DebugPort
);
254 Process
->DebugPort
= NULL
;
257 /* Check if we have an exception port */
258 if (Process
->ExceptionPort
)
260 /* Deference the Exception Port */
261 ObDereferenceObject(Process
->ExceptionPort
);
262 Process
->ExceptionPort
= NULL
;
265 /* Check if we have a section object */
266 if (Process
->SectionObject
)
268 /* Deference the Section Object */
269 ObDereferenceObject(Process
->SectionObject
);
270 Process
->SectionObject
= NULL
;
273 /* Clean LDT and VDM_OBJECTS */
274 PspDeleteLdt(Process
);
275 PspDeleteVdmObjects(Process
);
277 /* Delete the Object Table */
278 if (Process
->ObjectTable
)
280 /* Attach to the process */
281 KeStackAttachProcess(&Process
->Pcb
, &ApcState
);
283 /* Kill the Object Info */
284 ObKillProcess(Process
);
287 KeUnstackDetachProcess(&ApcState
);
290 /* Check if we have an address space, and clean it */
291 if (Process
->HasAddressSpace
)
293 /* Attach to the process */
294 KeStackAttachProcess(&Process
->Pcb
, &ApcState
);
296 /* Clean the Address Space */
297 PspExitProcess(FALSE
, Process
);
300 KeUnstackDetachProcess(&ApcState
);
302 /* Completely delete the Address Space */
303 MmDeleteProcessAddressSpace(Process
);
306 /* See if we have a PID */
307 if (Process
->UniqueProcessId
)
310 if (!(ExDestroyHandle(PspCidTable
, Process
->UniqueProcessId
, NULL
)))
312 /* Something wrong happened, bugcheck */
313 KeBugCheck(CID_HANDLE_DELETION
);
317 /* Cleanup security information */
318 PspDeleteProcessSecurity(Process
);
320 /* Check if we have kept information on the Working Set */
321 if (Process
->WorkingSetWatch
)
324 ExFreePool(Process
->WorkingSetWatch
);
326 /* And return the quota it was taking up */
327 PsReturnProcessNonPagedPoolQuota(Process
, 0x2000);
330 /* Dereference the Device Map */
331 ObDereferenceDeviceMap(Process
);
333 /* Destroy the Quota Block */
334 PspDestroyQuotaBlock(Process
);
339 PspDeleteThread(IN PVOID ObjectBody
)
341 PETHREAD Thread
= (PETHREAD
)ObjectBody
;
342 PEPROCESS Process
= Thread
->ThreadsProcess
;
344 PSTRACE(PS_KILL_DEBUG
, "ObjectBody: %p\n", ObjectBody
);
346 ASSERT(Thread
->Tcb
.Win32Thread
== NULL
);
348 /* Check if we have a stack */
349 if (Thread
->Tcb
.InitialStack
)
352 MmDeleteKernelStack((PVOID
)Thread
->Tcb
.StackBase
,
353 Thread
->Tcb
.LargeStack
);
356 /* Check if we have a CID Handle */
357 if (Thread
->Cid
.UniqueThread
)
359 /* Delete the CID Handle */
360 if (!(ExDestroyHandle(PspCidTable
, Thread
->Cid
.UniqueThread
, NULL
)))
362 /* Something wrong happened, bugcheck */
363 KeBugCheck(CID_HANDLE_DELETION
);
367 /* Cleanup impersionation information */
368 PspDeleteThreadSecurity(Thread
);
370 /* Make sure the thread was inserted, before continuing */
371 if (!Process
) return;
373 /* Check if the thread list is valid */
374 if (Thread
->ThreadListEntry
.Flink
)
376 /* Lock the thread's process */
377 KeEnterCriticalRegion();
378 ExAcquirePushLockExclusive(&Process
->ProcessLock
);
380 /* Remove us from the list */
381 RemoveEntryList(&Thread
->ThreadListEntry
);
383 /* Release the lock */
384 ExReleasePushLockExclusive(&Process
->ProcessLock
);
385 KeLeaveCriticalRegion();
388 /* Dereference the Process */
389 ObDereferenceObject(Process
);
393 * FUNCTION: Terminates the current thread
394 * See "Windows Internals" - Chapter 13, Page 50-53
398 PspExitThread(IN NTSTATUS ExitStatus
)
400 CLIENT_DIED_MSG TerminationMsg
;
403 PEPROCESS CurrentProcess
;
404 PETHREAD Thread
, OtherThread
, PreviousThread
= NULL
;
405 PVOID DeallocationStack
;
407 BOOLEAN Last
= FALSE
;
408 PTERMINATION_PORT TerminationPort
, NextPort
;
409 PLIST_ENTRY FirstEntry
, CurrentEntry
;
413 PSTRACE(PS_KILL_DEBUG
, "ExitStatus: %p\n", ExitStatus
);
415 /* Get the Current Thread and Process */
416 Thread
= PsGetCurrentThread();
417 CurrentProcess
= Thread
->ThreadsProcess
;
418 ASSERT((Thread
) == PsGetCurrentThread());
420 /* Can't terminate a thread if it attached another process */
421 if (KeIsAttachedProcess())
424 KeBugCheckEx(INVALID_PROCESS_ATTACH_ATTEMPT
,
425 (ULONG_PTR
)CurrentProcess
,
426 (ULONG_PTR
)Thread
->Tcb
.ApcState
.Process
,
427 (ULONG_PTR
)Thread
->Tcb
.ApcStateIndex
,
431 /* Lower to Passive Level */
432 KeLowerIrql(PASSIVE_LEVEL
);
434 /* Can't be a worker thread */
435 if (Thread
->ActiveExWorker
)
438 KeBugCheckEx(ACTIVE_EX_WORKER_THREAD_TERMINATION
,
445 /* Can't have pending APCs */
446 if (Thread
->Tcb
.CombinedApcDisable
!= 0)
449 KeBugCheckEx(KERNEL_APC_PENDING_DURING_EXIT
,
451 Thread
->Tcb
.CombinedApcDisable
,
456 /* Lock the thread */
457 ExWaitForRundownProtectionRelease(&Thread
->RundownProtect
);
459 /* Cleanup the power state */
460 PopCleanupPowerState((PPOWER_STATE
)&Thread
->Tcb
.PowerState
);
462 /* Call the WMI Callback for Threads */
463 //WmiTraceThread(Thread, NULL, FALSE);
465 /* Run Thread Notify Routines before we desintegrate the thread */
466 PspRunCreateThreadNotifyRoutines(Thread
, FALSE
);
468 /* Lock the Process before we modify its thread entries */
469 KeEnterCriticalRegion();
470 ExAcquirePushLockExclusive(&CurrentProcess
->ProcessLock
);
472 /* Decrease the active thread count, and check if it's 0 */
473 if (!(--CurrentProcess
->ActiveThreads
))
475 /* Set the delete flag */
476 InterlockedOr((PLONG
)&CurrentProcess
->Flags
, PSF_PROCESS_DELETE_BIT
);
478 /* Remember we are last */
481 /* Check if this termination is due to the thread dying */
482 if (ExitStatus
== STATUS_THREAD_IS_TERMINATING
)
484 /* Check if the last thread was pending */
485 if (CurrentProcess
->ExitStatus
== STATUS_PENDING
)
487 /* Use the last exit status */
488 CurrentProcess
->ExitStatus
= CurrentProcess
->
489 LastThreadExitStatus
;
494 /* Just a normal exit, write the code */
495 CurrentProcess
->ExitStatus
= ExitStatus
;
498 /* Loop all the current threads */
499 FirstEntry
= &CurrentProcess
->ThreadListHead
;
500 CurrentEntry
= FirstEntry
->Flink
;
501 while (FirstEntry
!= CurrentEntry
)
503 /* Get the thread on the list */
504 OtherThread
= CONTAINING_RECORD(CurrentEntry
,
508 /* Check if it's a thread that's still alive */
509 if ((OtherThread
!= Thread
) &&
510 !(KeReadStateThread(&OtherThread
->Tcb
)) &&
511 (ObReferenceObjectSafe(OtherThread
)))
513 /* It's a live thread and we referenced it, unlock process */
514 ExReleasePushLockExclusive(&CurrentProcess
->ProcessLock
);
515 KeLeaveCriticalRegion();
517 /* Wait on the thread */
518 KeWaitForSingleObject(OtherThread
,
524 /* Check if we had a previous thread to dereference */
525 if (PreviousThread
) ObDereferenceObject(PreviousThread
);
527 /* Remember the thread and re-lock the process */
528 PreviousThread
= OtherThread
;
529 KeEnterCriticalRegion();
530 ExAcquirePushLockExclusive(&CurrentProcess
->ProcessLock
);
533 /* Go to the next thread */
534 CurrentEntry
= CurrentEntry
->Flink
;
537 else if (ExitStatus
!= STATUS_THREAD_IS_TERMINATING
)
539 /* Write down the exit status of the last thread to get killed */
540 CurrentProcess
->LastThreadExitStatus
= ExitStatus
;
543 /* Unlock the Process */
544 ExReleasePushLockExclusive(&CurrentProcess
->ProcessLock
);
545 KeLeaveCriticalRegion();
547 /* Check if we had a previous thread to dereference */
548 if (PreviousThread
) ObDereferenceObject(PreviousThread
);
550 /* Check if the process has a debug port and if this is a user thread */
551 if ((CurrentProcess
->DebugPort
) && !(Thread
->SystemThread
))
553 /* Notify the Debug API. */
554 Last
? DbgkExitProcess(CurrentProcess
->ExitStatus
) :
555 DbgkExitThread(ExitStatus
);
558 /* Check if this is a Critical Thread */
559 if ((KdDebuggerEnabled
) && (Thread
->BreakOnTermination
))
561 /* Break to debugger */
562 PspCatchCriticalBreak("Critical thread 0x%p (in %s) exited\n",
564 CurrentProcess
->ImageFileName
);
567 /* Check if it's the last thread and this is a Critical Process */
568 if ((Last
) && (CurrentProcess
->BreakOnTermination
))
570 /* Check if a debugger is here to handle this */
571 if (KdDebuggerEnabled
)
573 /* Break to debugger */
574 PspCatchCriticalBreak("Critical process 0x%p (in %s) exited\n",
576 CurrentProcess
->ImageFileName
);
580 /* Bugcheck, we can't allow this */
581 KeBugCheckEx(CRITICAL_PROCESS_DIED
,
582 (ULONG_PTR
)CurrentProcess
,
590 ASSERT(Thread
->Tcb
.CombinedApcDisable
== 0);
592 /* Process the Termination Ports */
593 TerminationPort
= Thread
->TerminationPort
;
596 /* Setup the message header */
597 TerminationMsg
.h
.u2
.s2
.Type
= LPC_CLIENT_DIED
;
598 TerminationMsg
.h
.u1
.s1
.TotalLength
= sizeof(TerminationMsg
);
599 TerminationMsg
.h
.u1
.s1
.DataLength
= sizeof(TerminationMsg
) -
600 sizeof(PORT_MESSAGE
);
605 /* Save the Create Time */
606 TerminationMsg
.CreateTime
= Thread
->CreateTime
;
608 /* Loop trying to send message */
611 /* Send the LPC Message */
612 Status
= LpcRequestPort(TerminationPort
->Port
,
614 if ((Status
== STATUS_NO_MEMORY
) ||
615 (Status
== STATUS_INSUFFICIENT_RESOURCES
))
617 /* Wait a bit and try again */
618 KeDelayExecutionThread(KernelMode
, FALSE
, &ShortTime
);
624 /* Dereference this LPC Port */
625 ObDereferenceObject(TerminationPort
->Port
);
627 /* Move to the next one */
628 NextPort
= TerminationPort
->Next
;
630 /* Free the Termination Port Object */
631 ExFreePool(TerminationPort
);
633 /* Keep looping as long as there is a port */
634 TerminationPort
= NextPort
;
635 } while (TerminationPort
);
637 else if (((ExitStatus
== STATUS_THREAD_IS_TERMINATING
) &&
638 (Thread
->DeadThread
)) ||
639 !(Thread
->DeadThread
))
642 * This case is special and deserves some extra comments. What
643 * basically happens here is that this thread doesn't have a termination
644 * port, which means that it died before being fully created. Since we
645 * still have to notify an LPC Server, we'll use the exception port,
646 * which we know exists. However, we need to know how far the thread
647 * actually got created. We have three possibilites:
649 * - NtCreateThread returned an error really early: DeadThread is set.
650 * - NtCreateThread managed to create the thread: DeadThread is off.
651 * - NtCreateThread was creating the thread (with Deadthread set,
652 * but the thread got killed prematurely: STATUS_THREAD_IS_TERMINATING
655 * For the 2 & 3rd scenarios, the thread has been created far enough to
656 * warrant notification to the LPC Server.
659 /* Setup the message header */
660 TerminationMsg
.h
.u2
.s2
.Type
= LPC_CLIENT_DIED
;
661 TerminationMsg
.h
.u1
.s1
.TotalLength
= sizeof(TerminationMsg
);
662 TerminationMsg
.h
.u1
.s1
.DataLength
= sizeof(TerminationMsg
) -
663 sizeof(PORT_MESSAGE
);
665 /* Make sure the process has an exception port */
666 if (CurrentProcess
->ExceptionPort
)
668 /* Save the Create Time */
669 TerminationMsg
.CreateTime
= Thread
->CreateTime
;
671 /* Loop trying to send message */
674 /* Send the LPC Message */
675 Status
= LpcRequestPort(CurrentProcess
->ExceptionPort
,
677 if ((Status
== STATUS_NO_MEMORY
) ||
678 (Status
== STATUS_INSUFFICIENT_RESOURCES
))
680 /* Wait a bit and try again */
681 KeDelayExecutionThread(KernelMode
, FALSE
, &ShortTime
);
689 /* Rundown Win32 Thread if there is one */
690 if (Thread
->Tcb
.Win32Thread
) PspW32ThreadCallout(Thread
,
691 PsW32ThreadCalloutExit
);
693 /* If we are the last thread and have a W32 Process */
694 if ((Last
) && (CurrentProcess
->Win32Process
))
696 /* Run it down too */
697 PspW32ProcessCallout(CurrentProcess
, FALSE
);
700 /* Make sure Stack Swap is enabled */
701 if (!Thread
->Tcb
.EnableStackSwap
)
703 /* Stack swap really shouldn't be disabled during exit! */
704 KeBugCheckEx(KERNEL_STACK_LOCKED_AT_EXIT
, 0, 0, 0, 0);
707 /* Cancel I/O for the thread. */
708 IoCancelThreadIo(Thread
);
713 /* FIXME: Rundown Registry Notifications (NtChangeNotify)
714 CmNotifyRunDown(Thread); */
716 /* Rundown Mutexes */
719 /* Check if we have a TEB */
720 Teb
= Thread
->Tcb
.Teb
;
723 /* Check if the thread is still alive */
724 if (!Thread
->DeadThread
)
726 /* Check if we need to free its stack */
727 if (Teb
->FreeStackOnTermination
)
729 /* Set the TEB's Deallocation Stack as the Base Address */
731 DeallocationStack
= Teb
->DeallocationStack
;
733 /* Free the Thread's Stack */
734 ZwFreeVirtualMemory(NtCurrentProcess(),
740 /* Free the debug handle */
741 if (Teb
->DbgSsReserved
[1]) ObCloseHandle(Teb
->DbgSsReserved
[1],
745 /* Decommit the TEB */
746 MmDeleteTeb(CurrentProcess
, Teb
);
747 Thread
->Tcb
.Teb
= NULL
;
751 LpcExitThread(Thread
);
753 /* Save the exit status and exit time */
754 Thread
->ExitStatus
= ExitStatus
;
755 KeQuerySystemTime(&Thread
->ExitTime
);
758 ASSERT(Thread
->Tcb
.CombinedApcDisable
== 0);
760 /* Check if this is the final thread or not */
763 /* Set the process exit time */
764 CurrentProcess
->ExitTime
= Thread
->ExitTime
;
766 /* Exit the process */
767 PspExitProcess(TRUE
, CurrentProcess
);
769 /* Get the process token and check if we need to audit */
770 PrimaryToken
= PsReferencePrimaryToken(CurrentProcess
);
771 if (SeDetailedAuditingWithToken(PrimaryToken
))
774 SeAuditProcessExit(CurrentProcess
);
777 /* Dereference the process token */
778 ObFastDereferenceObject(&CurrentProcess
->Token
, PrimaryToken
);
780 /* Check if this is a VDM Process and rundown the VDM DPCs if so */
781 if (CurrentProcess
->VdmObjects
) { /* VdmRundownDpcs(CurrentProcess); */ }
783 /* Kill the process in the Object Manager */
784 ObKillProcess(CurrentProcess
);
786 /* Check if we have a section object */
787 if (CurrentProcess
->SectionObject
)
789 /* Dereference and clear the Section Object */
790 ObDereferenceObject(CurrentProcess
->SectionObject
);
791 CurrentProcess
->SectionObject
= NULL
;
794 /* Check if the process is part of a job */
795 if (CurrentProcess
->Job
)
797 /* Remove the process from the job */
798 PspExitProcessFromJob(CurrentProcess
->Job
, CurrentProcess
);
803 KeEnterCriticalRegion();
805 /* Disable APC queueing, force a resumption */
806 Thread
->Tcb
.ApcQueueable
= FALSE
;
807 KeForceResumeThread(&Thread
->Tcb
);
810 KeLeaveCriticalRegion();
812 /* Flush the User APCs */
813 FirstEntry
= KeFlushQueueApc(&Thread
->Tcb
, UserMode
);
816 /* Start with the first entry */
817 CurrentEntry
= FirstEntry
;
821 Apc
= CONTAINING_RECORD(CurrentEntry
, KAPC
, ApcListEntry
);
823 /* Move to the next one */
824 CurrentEntry
= CurrentEntry
->Flink
;
826 /* Rundown the APC or de-allocate it */
827 if (Apc
->RundownRoutine
)
829 /* Call its own routine */
830 Apc
->RundownRoutine(Apc
);
834 /* Do it ourselves */
838 while (CurrentEntry
!= FirstEntry
);
841 /* Clean address space if this was the last thread */
842 if (Last
) MmCleanProcessAddressSpace(CurrentProcess
);
844 /* Call the Lego routine */
845 if (Thread
->Tcb
.LegoData
) PspRunLegoRoutine(&Thread
->Tcb
);
847 /* Flush the APC queue, which should be empty */
848 FirstEntry
= KeFlushQueueApc(&Thread
->Tcb
, KernelMode
);
849 if ((FirstEntry
) || (Thread
->Tcb
.CombinedApcDisable
!= 0))
852 KeBugCheckEx(KERNEL_APC_PENDING_DURING_EXIT
,
853 (ULONG_PTR
)FirstEntry
,
854 Thread
->Tcb
.CombinedApcDisable
,
859 /* Signal the process if this was the last thread */
860 if (Last
) KeSetProcess(&CurrentProcess
->Pcb
, 0, FALSE
);
862 /* Terminate the Thread from the Scheduler */
863 KeTerminateThread(0);
868 PsExitSpecialApc(IN PKAPC Apc
,
869 IN OUT PKNORMAL_ROUTINE
* NormalRoutine
,
870 IN OUT PVOID
* NormalContext
,
871 IN OUT PVOID
* SystemArgument1
,
872 IN OUT PVOID
* SystemArgument2
)
876 PSTRACE(PS_KILL_DEBUG
,
877 "Apc: %p SystemArgument2: %p \n", Apc
, SystemArgument2
);
879 /* Don't do anything unless we are in User-Mode */
880 if (Apc
->SystemArgument2
)
883 Status
= (NTSTATUS
)Apc
->NormalContext
;
884 PspExitApcRundown(Apc
);
886 /* Terminate the Thread */
887 PspExitThread(Status
);
893 PspExitNormalApc(IN PVOID NormalContext
,
894 IN PVOID SystemArgument1
,
895 IN PVOID SystemArgument2
)
897 PKAPC Apc
= (PKAPC
)SystemArgument1
;
898 PETHREAD Thread
= PsGetCurrentThread();
900 PSTRACE(PS_KILL_DEBUG
, "SystemArgument2: %p \n", SystemArgument2
);
902 /* This should never happen */
903 ASSERT(!(((ULONG_PTR
)SystemArgument2
) & 1));
905 /* If we're here, this is not a System Thread, so kill it from User-Mode */
908 OriginalApcEnvironment
,
915 /* Now insert the APC with the User-Mode Flag */
916 if (!(KeInsertQueueApc(Apc
,
918 (PVOID
)((ULONG_PTR
)SystemArgument2
| 1),
921 /* Failed to insert, free the APC */
922 PspExitApcRundown(Apc
);
925 /* Set the APC Pending flag */
926 Thread
->Tcb
.ApcState
.UserApcPending
= TRUE
;
930 * See "Windows Internals" - Chapter 13, Page 49
934 PspTerminateThreadByPointer(IN PETHREAD Thread
,
935 IN NTSTATUS ExitStatus
,
939 NTSTATUS Status
= STATUS_SUCCESS
;
942 PSTRACE(PS_KILL_DEBUG
, "Thread: %p ExitStatus: %p\n", Thread
, ExitStatus
);
945 /* Check if this is a Critical Thread, and Bugcheck */
946 if (Thread
->BreakOnTermination
)
948 /* Break to debugger */
949 PspCatchCriticalBreak("Terminating critical thread 0x%p (%s)\n",
951 Thread
->ThreadsProcess
->ImageFileName
);
954 /* Check if we are already inside the thread */
955 if ((bSelf
) || (PsGetCurrentThread() == Thread
))
957 /* This should only happen at passive */
958 ASSERT_IRQL_EQUAL(PASSIVE_LEVEL
);
960 /* Mark it as terminated */
961 PspSetCrossThreadFlag(Thread
, CT_TERMINATED_BIT
);
963 /* Directly terminate the thread */
964 PspExitThread(ExitStatus
);
967 /* This shouldn't be a system thread */
968 if (Thread
->SystemThread
) return STATUS_ACCESS_DENIED
;
970 /* Allocate the APC */
971 Apc
= ExAllocatePoolWithTag(NonPagedPool
, sizeof(KAPC
), TAG_TERMINATE_APC
);
973 /* Set the Terminated Flag */
974 Flags
= Thread
->CrossThreadFlags
| CT_TERMINATED_BIT
;
976 /* Set it, and check if it was already set while we were running */
977 if (!(InterlockedExchange((PLONG
)&Thread
->CrossThreadFlags
, Flags
) &
980 /* Initialize a Kernel Mode APC to Kill the Thread */
983 OriginalApcEnvironment
,
990 /* Insert it into the APC Queue */
991 if (!KeInsertQueueApc(Apc
, Apc
, NULL
, 2))
993 /* The APC was already in the queue, fail */
994 Status
= STATUS_UNSUCCESSFUL
;
998 /* Forcefully resume the thread and return */
999 KeForceResumeThread(&Thread
->Tcb
);
1004 /* We failed, free the APC */
1013 PspExitProcess(IN BOOLEAN LastThread
,
1014 IN PEPROCESS Process
)
1018 PSTRACE(PS_KILL_DEBUG
,
1019 "LastThread: %p Process: %p\n", LastThread
, Process
);
1020 PSREFTRACE(Process
);
1022 /* Set Process Exit flag */
1023 InterlockedOr((PLONG
)&Process
->Flags
, PSF_PROCESS_EXITING_BIT
);
1025 /* Check if we are the last thread */
1028 /* Notify the WMI Process Callback */
1029 //WmiTraceProcess(Process, FALSE);
1031 /* Run the Notification Routines */
1032 PspRunCreateProcessNotifyRoutines(Process
, FALSE
);
1035 /* Cleanup the power state */
1036 PopCleanupPowerState((PPOWER_STATE
)&Process
->Pcb
.PowerState
);
1038 /* Clear the security port */
1039 if (!Process
->SecurityPort
)
1041 /* So we don't double-dereference */
1042 Process
->SecurityPort
= (PVOID
)1;
1044 else if (Process
->SecurityPort
!= (PVOID
)1)
1046 /* Dereference it */
1047 ObDereferenceObject(Process
->SecurityPort
);
1048 Process
->SecurityPort
= (PVOID
)1;
1051 /* Check if we are the last thread */
1054 /* Check if we have to set the Timer Resolution */
1055 if (Process
->SetTimerResolution
)
1057 /* Set it to default */
1058 ZwSetTimerResolution(KeMaximumIncrement
, 0, &Actual
);
1061 /* Check if we are part of a Job that has a completion port */
1062 if ((Process
->Job
) && (Process
->Job
->CompletionPort
))
1064 /* FIXME: Check job status code and do I/O completion if needed */
1067 /* FIXME: Notify the Prefetcher */
1071 /* Clear process' address space here */
1072 MmCleanProcessAddressSpace(Process
);
1076 /* PUBLIC FUNCTIONS **********************************************************/
1083 PsTerminateSystemThread(IN NTSTATUS ExitStatus
)
1085 PETHREAD Thread
= PsGetCurrentThread();
1087 /* Make sure this is a system thread */
1088 if (!Thread
->SystemThread
) return STATUS_INVALID_PARAMETER
;
1090 /* Terminate it for real */
1091 return PspTerminateThreadByPointer(Thread
, ExitStatus
, TRUE
);
1099 NtTerminateProcess(IN HANDLE ProcessHandle OPTIONAL
,
1100 IN NTSTATUS ExitStatus
)
1103 PEPROCESS Process
, CurrentProcess
= PsGetCurrentProcess();
1104 PETHREAD Thread
, CurrentThread
= PsGetCurrentThread();
1105 BOOLEAN KillByHandle
;
1107 PSTRACE(PS_KILL_DEBUG
,
1108 "ProcessHandle: %p ExitStatus: %p\n", ProcessHandle
, ExitStatus
);
1110 /* Were we passed a process handle? */
1113 /* Yes we were, use it */
1114 KillByHandle
= TRUE
;
1118 /* We weren't... we assume this is suicide */
1119 KillByHandle
= FALSE
;
1120 ProcessHandle
= NtCurrentProcess();
1123 /* Get the Process Object */
1124 Status
= ObReferenceObjectByHandle(ProcessHandle
,
1127 KeGetPreviousMode(),
1130 if (!NT_SUCCESS(Status
)) return(Status
);
1132 /* Check if this is a Critical Process, and Bugcheck */
1133 if (Process
->BreakOnTermination
)
1135 /* Break to debugger */
1136 PspCatchCriticalBreak("Terminating critical process 0x%p (%s)\n",
1138 Process
->ImageFileName
);
1141 /* Lock the Process */
1142 if (!ExAcquireRundownProtection(&Process
->RundownProtect
))
1144 /* Failed to lock, fail */
1145 ObDereferenceObject (Process
);
1146 return STATUS_PROCESS_IS_TERMINATING
;
1149 /* Set the delete flag, unless the process is comitting suicide */
1150 if (KillByHandle
) PspSetProcessFlag(Process
, PSF_PROCESS_DELETE_BIT
);
1152 /* Get the first thread */
1153 Status
= STATUS_NOTHING_TO_TERMINATE
;
1154 Thread
= PsGetNextProcessThread(Process
, NULL
);
1157 /* We know we have at least a thread */
1158 Status
= STATUS_SUCCESS
;
1160 /* Loop and kill the others */
1163 /* Ensure it's not ours*/
1164 if (Thread
!= CurrentThread
)
1167 PspTerminateThreadByPointer(Thread
, ExitStatus
, FALSE
);
1170 /* Move to the next thread */
1171 Thread
= PsGetNextProcessThread(Process
, Thread
);
1175 /* Unlock the process */
1176 ExReleaseRundownProtection(&Process
->RundownProtect
);
1178 /* Check if we are killing ourselves */
1179 if (Process
== CurrentProcess
)
1181 /* Also make sure the caller gave us our handle */
1184 /* Dereference the process */
1185 ObDereferenceObject(Process
);
1187 /* Terminate ourselves */
1188 PspTerminateThreadByPointer(CurrentThread
, ExitStatus
, TRUE
);
1191 else if (ExitStatus
== DBG_TERMINATE_PROCESS
)
1193 /* Disable debugging on this process */
1194 DbgkClearProcessDebugObject(Process
, NULL
);
1197 /* Check if there was nothing to terminate, or if we have a Debug Port */
1198 if ((Status
== STATUS_NOTHING_TO_TERMINATE
) ||
1199 ((Process
->DebugPort
) && (KillByHandle
)))
1201 /* Clear the handle table */
1202 ObClearProcessHandleTable(Process
);
1204 /* Return status now */
1205 Status
= STATUS_SUCCESS
;
1208 /* Decrease the reference count we added */
1209 ObDereferenceObject(Process
);
1217 NtTerminateThread(IN HANDLE ThreadHandle
,
1218 IN NTSTATUS ExitStatus
)
1221 PETHREAD CurrentThread
= PsGetCurrentThread();
1224 PSTRACE(PS_KILL_DEBUG
,
1225 "ThreadHandle: %p ExitStatus: %p\n", ThreadHandle
, ExitStatus
);
1227 /* Handle the special NULL case */
1230 /* Check if we're the only thread left */
1231 if (PsGetCurrentProcess()->ActiveThreads
== 1)
1233 /* This is invalid */
1234 return STATUS_CANT_TERMINATE_SELF
;
1237 /* Terminate us directly */
1240 else if (ThreadHandle
== NtCurrentThread())
1243 /* Terminate this thread */
1244 return PspTerminateThreadByPointer(CurrentThread
,
1249 /* We are terminating another thread, get the Thread Object */
1250 Status
= ObReferenceObjectByHandle(ThreadHandle
,
1253 KeGetPreviousMode(),
1256 if (!NT_SUCCESS(Status
)) return Status
;
1258 /* Check to see if we're running in the same thread */
1259 if (Thread
!= CurrentThread
)
1262 Status
= PspTerminateThreadByPointer(Thread
, ExitStatus
, FALSE
);
1264 /* Dereference the Thread and return */
1265 ObDereferenceObject(Thread
);
1269 /* Dereference the thread and terminate ourselves */
1270 ObDereferenceObject(Thread
);
1280 NtRegisterThreadTerminatePort(IN HANDLE PortHandle
)
1283 PTERMINATION_PORT TerminationPort
;
1284 PVOID TerminationLpcPort
;
1287 PSTRACE(PS_KILL_DEBUG
, "PortHandle: %p\n", PortHandle
);
1290 Status
= ObReferenceObjectByHandle(PortHandle
,
1293 KeGetPreviousMode(),
1294 &TerminationLpcPort
,
1296 if (!NT_SUCCESS(Status
)) return(Status
);
1298 /* Allocate the Port and make sure it suceeded */
1299 TerminationPort
= ExAllocatePoolWithTag(NonPagedPool
,
1300 sizeof(TERMINATION_PORT
),
1301 TAG('P', 's', 'T', '='));
1304 /* Associate the Port */
1305 Thread
= PsGetCurrentThread();
1306 TerminationPort
->Port
= TerminationLpcPort
;
1307 TerminationPort
->Next
= Thread
->TerminationPort
;
1308 Thread
->TerminationPort
= TerminationPort
;
1310 /* Return success */
1311 return STATUS_SUCCESS
;
1314 /* Dereference and Fail */
1315 ObDereferenceObject(TerminationPort
);
1316 return STATUS_INSUFFICIENT_RESOURCES
;