a54252e562055797217cf264fd2ccb4888dc9b39
[reactos.git] / reactos / ntoskrnl / ps / kill.c
1 /*
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
6 *
7 * PROGRAMMERS: Alex Ionescu (alex@relsoft.net)
8 * David Welch (welch@cwcom.net)
9 */
10
11 /* INCLUDES *****************************************************************/
12
13 #include <ntoskrnl.h>
14 #define NDEBUG
15 #include <internal/debug.h>
16
17 /* GLOBALS *******************************************************************/
18
19 PETHREAD PspReaperList = NULL;
20 WORK_QUEUE_ITEM PspReaperWorkItem;
21 BOOLEAN PspReaping = FALSE;
22 extern LIST_ENTRY PsActiveProcessHead;
23 extern FAST_MUTEX PspActiveProcessMutex;
24
25 /* FUNCTIONS *****************************************************************/
26
27 VOID
28 STDCALL
29 PspReapRoutine(PVOID Context)
30 {
31 KIRQL OldIrql;
32 PETHREAD Thread, NewThread;
33
34 /* Acquire lock */
35 DPRINT("Evil reaper running!!\n");
36 OldIrql = KeAcquireDispatcherDatabaseLock();
37
38 /* Get the first Thread Entry */
39 Thread = PspReaperList;
40 PspReaperList = NULL;
41 DPRINT("PspReaperList: %x\n", Thread);
42
43 /* Check to see if the list is empty */
44 do {
45
46 /* Unlock the Dispatcher */
47 KeReleaseDispatcherDatabaseLock(OldIrql);
48
49 /* Is there a thread on the list? */
50 while (Thread) {
51
52 /* Get the next Thread */
53 DPRINT("Thread: %x\n", Thread);
54 DPRINT("Thread: %x\n", Thread->ReaperLink);
55 NewThread = Thread->ReaperLink;
56
57 /* Remove reference to current thread */
58 ObDereferenceObject(Thread);
59
60 /* Move to next Thread */
61 Thread = NewThread;
62 }
63
64 /* No more linked threads... Reacquire the Lock */
65 OldIrql = KeAcquireDispatcherDatabaseLock();
66
67 /* Now try to get a new thread from the list */
68 Thread = PspReaperList;
69 PspReaperList = NULL;
70 DPRINT("PspReaperList: %x\n", Thread);
71
72 /* Loop again if there is a new thread */
73 } while (Thread);
74
75 PspReaping = FALSE;
76 DPRINT("Done reaping\n");
77 KeReleaseDispatcherDatabaseLock(OldIrql);
78 }
79
80 VOID
81 STDCALL
82 PspKillMostProcesses(VOID)
83 {
84 PLIST_ENTRY current_entry;
85 PEPROCESS current;
86
87 /* Acquire the Active Process Lock */
88 ExAcquireFastMutex(&PspActiveProcessMutex);
89
90 /* Loop all processes on the list */
91 current_entry = PsActiveProcessHead.Flink;
92 while (current_entry != &PsActiveProcessHead)
93 {
94 current = CONTAINING_RECORD(current_entry, EPROCESS, ActiveProcessLinks);
95 current_entry = current_entry->Flink;
96
97 if (current->UniqueProcessId != PsInitialSystemProcess->UniqueProcessId &&
98 current->UniqueProcessId != PsGetCurrentProcessId())
99 {
100 /* Terminate all the Threads in this Process */
101 PspTerminateProcessThreads(current, STATUS_SUCCESS);
102 }
103 }
104
105 /* Release the lock */
106 ExReleaseFastMutex(&PspActiveProcessMutex);
107 }
108
109 VOID
110 STDCALL
111 PspTerminateProcessThreads(PEPROCESS Process,
112 NTSTATUS ExitStatus)
113 {
114 PLIST_ENTRY CurrentEntry;
115 PETHREAD Thread, CurrentThread = PsGetCurrentThread();
116
117 CurrentEntry = Process->ThreadListHead.Flink;
118 while (CurrentEntry != &Process->ThreadListHead) {
119
120 /* Get the Current Thread */
121 Thread = CONTAINING_RECORD(CurrentEntry, ETHREAD, ThreadListEntry);
122
123 /* Move to the Next Thread */
124 CurrentEntry = CurrentEntry->Flink;
125
126 /* Make sure it's not the one we're in */
127 if (Thread != CurrentThread) {
128
129 /* Make sure it didn't already terminate */
130 if (!Thread->Terminated) {
131
132 Thread->Terminated = TRUE;
133
134 /* Terminate it by APC */
135 PspTerminateThreadByPointer(Thread, ExitStatus);
136 }
137 }
138 }
139 }
140
141 VOID
142 STDCALL
143 PspDeleteProcess(PVOID ObjectBody)
144 {
145 PEPROCESS Process = (PEPROCESS)ObjectBody;
146
147 DPRINT("PiDeleteProcess(ObjectBody %x)\n", ObjectBody);
148
149 /* Remove it from the Active List */
150 ExAcquireFastMutex(&PspActiveProcessMutex);
151 RemoveEntryList(&Process->ActiveProcessLinks);
152 ExReleaseFastMutex(&PspActiveProcessMutex);
153
154 /* Delete the CID Handle */
155 if(Process->UniqueProcessId != NULL) {
156
157 PsDeleteCidHandle(Process->UniqueProcessId, PsProcessType);
158 }
159
160 /* KDB hook */
161 KDB_DELETEPROCESS_HOOK(Process);
162
163 /* Dereference the Token */
164 SeDeassignPrimaryToken(Process);
165
166 /* Release Memory Information */
167 MmReleaseMmInfo(Process);
168
169 /* Delete the W32PROCESS structure if there's one associated */
170 if(Process->Win32Process != NULL) ExFreePool(Process->Win32Process);
171 }
172
173 VOID
174 STDCALL
175 PspDeleteThread(PVOID ObjectBody)
176 {
177 PETHREAD Thread = (PETHREAD)ObjectBody;
178 PEPROCESS Process = Thread->ThreadsProcess;
179
180 DPRINT("PiDeleteThread(ObjectBody 0x%x, process 0x%x)\n",ObjectBody, Thread->ThreadsProcess);
181
182 /* Deassociate the Process */
183 Thread->ThreadsProcess = NULL;
184
185 /* Delete the CID Handle */
186 if(Thread->Cid.UniqueThread != NULL) {
187
188 PsDeleteCidHandle(Thread->Cid.UniqueThread, PsThreadType);
189 }
190
191 /* Free the W32THREAD structure if present */
192 if(Thread->Tcb.Win32Thread != NULL) ExFreePool (Thread->Tcb.Win32Thread);
193
194 /* Release the Kernel Stack */
195 MmDeleteKernelStack((PVOID)Thread->Tcb.StackLimit, FALSE);
196
197 /* Dereference the Process */
198 ObDereferenceObject(Process);
199 }
200
201 /*
202 * FUNCTION: Terminates the current thread
203 * See "Windows Internals" - Chapter 13, Page 50-53
204 */
205 VOID
206 STDCALL
207 PspExitThread(NTSTATUS ExitStatus)
208 {
209 PETHREAD CurrentThread;
210 BOOLEAN Last;
211 PEPROCESS CurrentProcess;
212 PTERMINATION_PORT TerminationPort;
213 PTEB Teb;
214
215 DPRINT("PspExitThread(ExitStatus %x), Current: 0x%x\n", ExitStatus, PsGetCurrentThread());
216
217 /* Get the Current Thread and Process */
218 CurrentThread = PsGetCurrentThread();
219 CurrentProcess = CurrentThread->ThreadsProcess;
220
221 /* Set the Exit Status and Exit Time */
222 CurrentThread->ExitStatus = ExitStatus;
223 KeQuerySystemTime(&CurrentThread->ExitTime);
224
225 /* Can't terminate a thread if it attached another process */
226 if (KeIsAttachedProcess()) {
227
228 KEBUGCHECKEX(INVALID_PROCESS_ATTACH_ATTEMPT, (ULONG) CurrentProcess,
229 (ULONG) CurrentThread->Tcb.ApcState.Process,
230 (ULONG) CurrentThread->Tcb.ApcStateIndex,
231 (ULONG) CurrentThread);
232 }
233
234 /* Lower to Passive Level */
235 KeLowerIrql(PASSIVE_LEVEL);
236
237 /* Lock the Process before we modify its thread entries */
238 PsLockProcess(CurrentProcess, FALSE);
239
240 /* wake up the thread so we don't deadlock on PsLockProcess */
241 KeForceResumeThread(&CurrentThread->Tcb);
242
243 /* Run Thread Notify Routines before we desintegrate the thread */
244 PspRunCreateThreadNotifyRoutines(CurrentThread, FALSE);
245
246 /* Remove the thread from the thread list of its process */
247 RemoveEntryList(&CurrentThread->ThreadListEntry);
248 Last = IsListEmpty(&CurrentProcess->ThreadListHead);
249
250 /* Set the last Thread Exit Status */
251 CurrentProcess->LastThreadExitStatus = ExitStatus;
252
253 if (Last) {
254
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;
259 }
260
261 /* Check if the process has a debug port */
262 if (CurrentProcess->DebugPort) {
263
264 /* Notify the Debug API. TODO */
265 //Last ? DbgkExitProcess(ExitStatus) : DbgkExitThread(ExitStatus);
266 }
267
268 /* Process the Termination Ports */
269 while ((TerminationPort = CurrentThread->TerminationPort)) {
270
271 DPRINT("TerminationPort: %p\n", TerminationPort);
272
273 /* Get the next one */
274 CurrentThread->TerminationPort = TerminationPort->Next;
275
276 /* Send the LPC Message */
277 LpcSendTerminationPort(TerminationPort->Port, CurrentThread->CreateTime);
278
279 /* Free the Port */
280 ExFreePool(TerminationPort);
281 }
282
283 /* Rundown Win32 Structures */
284 PsTerminateWin32Thread(CurrentThread);
285 if (Last) PsTerminateWin32Process(CurrentProcess);
286
287 /* Rundown Registry Notifications. TODO (refers to NtChangeNotify, not Cm callbacks) */
288 //CmNotifyRunDown(CurrentThread);
289
290 /* Free the TEB */
291 if((Teb = CurrentThread->Tcb.Teb)) {
292
293 DPRINT("Decommit teb at %p\n", Teb);
294 MmDeleteTeb(CurrentProcess, Teb);
295 CurrentThread->Tcb.Teb = NULL;
296 }
297
298 /* The last Thread shuts down the Process */
299 if (Last) PspExitProcess(CurrentProcess);
300
301 /* Unlock the Process */
302 PsUnlockProcess(CurrentProcess);
303
304 /* Cancel I/O for the thread. */
305 IoCancelThreadIo(CurrentThread);
306
307 /* Rundown Timers */
308 ExTimerRundown();
309 KeCancelTimer(&CurrentThread->Tcb.Timer);
310
311 /* If the Processor Control Block's NpxThread points to the current thread
312 * unset it.
313 */
314 InterlockedCompareExchangePointer(&KeGetCurrentPrcb()->NpxThread,
315 NULL,
316 (PKPROCESS)CurrentThread);
317
318 /* Rundown Mutexes */
319 KeRundownThread();
320
321 /* Terminate the Thread from the Scheduler */
322 KeTerminateThread(0);
323 DPRINT1("Unexpected return, CurrentThread %x PsGetCurrentThread() %x\n", CurrentThread, PsGetCurrentThread());
324 KEBUGCHECK(0);
325 }
326
327 VOID
328 STDCALL
329 PsExitSpecialApc(PKAPC Apc,
330 PKNORMAL_ROUTINE* NormalRoutine,
331 PVOID* NormalContext,
332 PVOID* SystemArgument1,
333 PVOID* SystemArguemnt2)
334 {
335 NTSTATUS ExitStatus = (NTSTATUS)Apc->NormalContext;
336
337 DPRINT("PsExitSpecialApc called: 0x%x (proc: 0x%x)\n", PsGetCurrentThread(), PsGetCurrentProcess());
338
339 /* Free the APC */
340 ExFreePool(Apc);
341
342 /* Terminate the Thread */
343 PspExitThread(ExitStatus);
344
345 /* we should never reach this point! */
346 KEBUGCHECK(0);
347 }
348
349 VOID
350 STDCALL
351 PspExitNormalApc(PVOID NormalContext,
352 PVOID SystemArgument1,
353 PVOID SystemArgument2)
354 {
355 /* Not fully supported yet... must work out some issues that
356 * I don't understand yet -- Alex
357 */
358 DPRINT1("APC2\n");
359 PspExitThread((NTSTATUS)NormalContext);
360
361 /* we should never reach this point! */
362 KEBUGCHECK(0);
363 }
364
365 /*
366 * See "Windows Internals" - Chapter 13, Page 49
367 */
368 VOID
369 STDCALL
370 PspTerminateThreadByPointer(PETHREAD Thread,
371 NTSTATUS ExitStatus)
372 {
373 PKAPC Apc;
374
375 DPRINT("PspTerminatedThreadByPointer(Thread %x, ExitStatus %x)\n",
376 Thread, ExitStatus);
377
378 /* Check if we are already in the right context */
379 if (PsGetCurrentThread() == Thread) {
380
381 /* Directly terminate the thread */
382 PspExitThread(ExitStatus);
383
384 /* we should never reach this point! */
385 KEBUGCHECK(0);
386 }
387
388 /* Allocate the APC */
389 Apc = ExAllocatePoolWithTag(NonPagedPool, sizeof(KAPC), TAG_TERMINATE_APC);
390
391 /* Initialize a Kernel Mode APC to Kill the Thread */
392 KeInitializeApc(Apc,
393 &Thread->Tcb,
394 OriginalApcEnvironment,
395 PsExitSpecialApc,
396 NULL,
397 PspExitNormalApc,
398 KernelMode,
399 (PVOID)ExitStatus);
400
401 /* Insert it into the APC Queue */
402 KeInsertQueueApc(Apc,
403 Apc,
404 NULL,
405 2);
406
407 /* Forcefully resume the thread */
408 KeForceResumeThread(&Thread->Tcb);
409 }
410
411 NTSTATUS
412 STDCALL
413 PspExitProcess(PEPROCESS Process)
414 {
415 DPRINT("PspExitProcess 0x%x\n", Process);
416
417 PspRunCreateProcessNotifyRoutines(Process, FALSE);
418
419 /* close all handles associated with our process, this needs to be done
420 when the last thread still runs */
421 ObKillProcess(Process);
422
423 KeSetProcess(&Process->Pcb, IO_NO_INCREMENT);
424
425 return(STATUS_SUCCESS);
426 }
427
428 NTSTATUS
429 STDCALL
430 NtTerminateProcess(IN HANDLE ProcessHandle OPTIONAL,
431 IN NTSTATUS ExitStatus)
432 {
433 NTSTATUS Status;
434 PEPROCESS Process;
435 PETHREAD CurrentThread;
436 BOOLEAN KillByHandle;
437
438 PAGED_CODE();
439
440 DPRINT("NtTerminateProcess(ProcessHandle %x, ExitStatus %x)\n",
441 ProcessHandle, ExitStatus);
442
443 KillByHandle = (ProcessHandle != NULL);
444
445 /* Get the Process Object */
446 Status = ObReferenceObjectByHandle((KillByHandle ? ProcessHandle : NtCurrentProcess()),
447 PROCESS_TERMINATE,
448 PsProcessType,
449 KeGetPreviousMode(),
450 (PVOID*)&Process,
451 NULL);
452 if (!NT_SUCCESS(Status)) {
453
454 DPRINT1("Invalid handle to Process\n");
455 return(Status);
456 }
457
458 CurrentThread = PsGetCurrentThread();
459
460 PsLockProcess(Process, FALSE);
461
462 if(Process->ExitTime.QuadPart != 0)
463 {
464 PsUnlockProcess(Process);
465 ObDereferenceObject(Process);
466 return STATUS_PROCESS_IS_TERMINATING;
467 }
468
469 /* Terminate all the Process's Threads */
470 PspTerminateProcessThreads(Process, ExitStatus);
471
472 /* only kill the calling thread if it either passed a process handle or
473 NtCurrentProcess() */
474 if (KillByHandle) {
475
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
478 to kill us */
479 KeQuerySystemTime(&Process->ExitTime);
480
481 /* Only master thread remains... kill it off */
482 if (CurrentThread->ThreadsProcess == Process) {
483
484 /* mark our thread as terminating so attempts to terminate it, when
485 unlocking the process, fail */
486 CurrentThread->Terminated = TRUE;
487
488 PsUnlockProcess(Process);
489
490 /* we can safely dereference the process because the current thread
491 holds a reference to it until it gets reaped */
492 ObDereferenceObject(Process);
493
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 */
497
498 PspExitThread(ExitStatus);
499
500 /* we should never reach this point! */
501 KEBUGCHECK(0);
502 }
503 }
504
505 /* unlock and dereference the process so the threads can kill themselves */
506 PsUnlockProcess(Process);
507 ObDereferenceObject(Process);
508
509 return(STATUS_SUCCESS);
510 }
511
512 NTSTATUS
513 STDCALL
514 NtTerminateThread(IN HANDLE ThreadHandle,
515 IN NTSTATUS ExitStatus)
516 {
517 PETHREAD Thread;
518 NTSTATUS Status;
519
520 PAGED_CODE();
521
522 /* Get the Thread Object */
523 Status = ObReferenceObjectByHandle(ThreadHandle,
524 THREAD_TERMINATE,
525 PsThreadType,
526 KeGetPreviousMode(),
527 (PVOID*)&Thread,
528 NULL);
529 if (!NT_SUCCESS(Status)) {
530
531 DPRINT1("Could not reference thread object\n");
532 return(Status);
533 }
534
535 /* Make sure this is not a system thread */
536 if (PsIsSystemThread(Thread)) {
537
538 DPRINT1("Trying to Terminate a system thread!\n");
539 ObDereferenceObject(Thread);
540 return STATUS_INVALID_PARAMETER;
541 }
542
543 /* Check to see if we're running in the same thread */
544 if (Thread != PsGetCurrentThread()) {
545
546 /* we need to lock the process to make sure it's not already terminating */
547 PsLockProcess(Thread->ThreadsProcess, FALSE);
548
549 /* This isn't our thread, terminate it if not already done */
550 if (!Thread->Terminated) {
551
552 Thread->Terminated = TRUE;
553
554 /* Terminate it */
555 PspTerminateThreadByPointer(Thread, ExitStatus);
556 }
557
558 PsUnlockProcess(Thread->ThreadsProcess);
559
560 /* Dereference the Thread and return */
561 ObDereferenceObject(Thread);
562
563 } else {
564
565 Thread->Terminated = TRUE;
566
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);
571
572 /* Terminate him, he's ours */
573 PspExitThread(ExitStatus);
574
575 /* We do never reach this point */
576 KEBUGCHECK(0);
577 }
578
579 return(STATUS_SUCCESS);
580 }
581
582 /*
583 * @implemented
584 */
585 NTSTATUS
586 STDCALL
587 PsTerminateSystemThread(NTSTATUS ExitStatus)
588 {
589 PETHREAD Thread = PsGetCurrentThread();
590
591 /* Make sure this is a system thread */
592 if (!PsIsSystemThread(Thread)) {
593
594 DPRINT1("Trying to Terminate a non-system thread!\n");
595 return STATUS_INVALID_PARAMETER;
596 }
597
598 /* Terminate it for real */
599 PspExitThread(ExitStatus);
600
601 /* we should never reach this point! */
602 KEBUGCHECK(0);
603
604 return(STATUS_SUCCESS);
605 }
606
607 NTSTATUS
608 STDCALL
609 NtRegisterThreadTerminatePort(HANDLE PortHandle)
610 {
611 NTSTATUS Status;
612 PTERMINATION_PORT TerminationPort;
613 PVOID TerminationLpcPort;
614 PETHREAD Thread;
615
616 PAGED_CODE();
617
618 /* Get the Port */
619 Status = ObReferenceObjectByHandle(PortHandle,
620 PORT_ALL_ACCESS,
621 LpcPortObjectType,
622 KeGetPreviousMode(),
623 &TerminationLpcPort,
624 NULL);
625 if (!NT_SUCCESS(Status)) {
626
627 DPRINT1("Failed to reference Port\n");
628 return(Status);
629 }
630
631 /* Allocate the Port and make sure it suceeded */
632 if((TerminationPort = ExAllocatePoolWithTag(NonPagedPool,
633 sizeof(PTERMINATION_PORT),
634 TAG('P', 's', 'T', '=')))) {
635
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);
643
644 /* Return success */
645 return(STATUS_SUCCESS);
646
647 } else {
648
649 /* Dereference and Fail */
650 ObDereferenceObject(TerminationPort);
651 return(STATUS_INSUFFICIENT_RESOURCES);
652 }
653 }