171374b8920159fb69315148d9ee33aafdcdf469
[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 #define TAG_TERMINATE_APC TAG('T', 'A', 'P', 'C')
20
21 PETHREAD PspReaperList = NULL;
22 WORK_QUEUE_ITEM PspReaperWorkItem;
23 BOOLEAN PspReaping = FALSE;
24 extern LIST_ENTRY PsActiveProcessHead;
25 extern FAST_MUTEX PspActiveProcessMutex;
26
27 /* FUNCTIONS *****************************************************************/
28
29 STDCALL
30 VOID
31 PspReapRoutine(PVOID Context)
32 {
33 KIRQL OldIrql;
34 PETHREAD Thread, NewThread;
35
36 /* Acquire lock */
37 DPRINT("Evil reaper running!!\n");
38 OldIrql = KeAcquireDispatcherDatabaseLock();
39
40 /* Get the first Thread Entry */
41 Thread = PspReaperList;
42 PspReaperList = NULL;
43 DPRINT("PspReaperList: %x\n", Thread);
44
45 /* Check to see if the list is empty */
46 do {
47
48 /* Unlock the Dispatcher */
49 KeReleaseDispatcherDatabaseLock(OldIrql);
50
51 /* Is there a thread on the list? */
52 while (Thread) {
53
54 /* Get the next Thread */
55 DPRINT("Thread: %x\n", Thread);
56 DPRINT("Thread: %x\n", Thread->ReaperLink);
57 NewThread = Thread->ReaperLink;
58
59 /* Remove reference to current thread */
60 ObDereferenceObject(Thread);
61
62 /* Move to next Thread */
63 Thread = NewThread;
64 }
65
66 /* No more linked threads... Reacquire the Lock */
67 OldIrql = KeAcquireDispatcherDatabaseLock();
68
69 /* Now try to get a new thread from the list */
70 Thread = PspReaperList;
71 PspReaperList = NULL;
72 DPRINT("PspReaperList: %x\n", Thread);
73
74 /* Loop again if there is a new thread */
75 } while (Thread);
76
77 PspReaping = FALSE;
78 DPRINT("Done reaping\n");
79 KeReleaseDispatcherDatabaseLock(OldIrql);
80 }
81
82 VOID
83 STDCALL
84 PspKillMostProcesses(VOID)
85 {
86 PLIST_ENTRY current_entry;
87 PEPROCESS current;
88
89 /* Acquire the Active Process Lock */
90 ExAcquireFastMutex(&PspActiveProcessMutex);
91
92 /* Loop all processes on the list */
93 current_entry = PsActiveProcessHead.Flink;
94 while (current_entry != &PsActiveProcessHead)
95 {
96 current = CONTAINING_RECORD(current_entry, EPROCESS, ProcessListEntry);
97 current_entry = current_entry->Flink;
98
99 if (current->UniqueProcessId != PsInitialSystemProcess->UniqueProcessId &&
100 current->UniqueProcessId != PsGetCurrentProcessId())
101 {
102 /* Terminate all the Threads in this Process */
103 PspTerminateProcessThreads(current, STATUS_SUCCESS);
104 }
105 }
106
107 /* Release the lock */
108 ExReleaseFastMutex(&PspActiveProcessMutex);
109 }
110
111 VOID
112 STDCALL
113 PspTerminateProcessThreads(PEPROCESS Process,
114 NTSTATUS ExitStatus)
115 {
116 PLIST_ENTRY CurrentEntry;
117 PETHREAD Thread, CurrentThread = PsGetCurrentThread();
118
119 CurrentEntry = Process->ThreadListHead.Flink;
120 while (CurrentEntry != &Process->ThreadListHead) {
121
122 /* Get the Current Thread */
123 Thread = CONTAINING_RECORD(CurrentEntry, ETHREAD, ThreadListEntry);
124
125 /* Move to the Next Thread */
126 CurrentEntry = CurrentEntry->Flink;
127
128 /* Make sure it's not the one we're in */
129 if (Thread != CurrentThread) {
130
131 /* Make sure it didn't already terminate */
132 if (!Thread->HasTerminated) {
133
134 Thread->HasTerminated = TRUE;
135
136 /* Terminate it by APC */
137 PspTerminateThreadByPointer(Thread, ExitStatus);
138 }
139 }
140 }
141 }
142
143 VOID
144 STDCALL
145 PspDeleteProcess(PVOID ObjectBody)
146 {
147 PEPROCESS Process = (PEPROCESS)ObjectBody;
148
149 DPRINT("PiDeleteProcess(ObjectBody %x)\n", ObjectBody);
150
151 /* Remove it from the Active List */
152 ExAcquireFastMutex(&PspActiveProcessMutex);
153 RemoveEntryList(&Process->ProcessListEntry);
154 ExReleaseFastMutex(&PspActiveProcessMutex);
155
156 /* Delete the CID Handle */
157 if(Process->UniqueProcessId != NULL) {
158
159 PsDeleteCidHandle(Process->UniqueProcessId, PsProcessType);
160 }
161
162 /* KDB hook */
163 KDB_DELETEPROCESS_HOOK(Process);
164
165 /* Dereference the Token and release Memory Information */
166 ObDereferenceObject(Process->Token);
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 TerminationPort = CurrentThread->TerminationPort;
270 DPRINT("TerminationPort: %p\n", TerminationPort);
271 while (TerminationPort) {
272
273 /* Send the LPC Message */
274 LpcSendTerminationPort(TerminationPort->Port, CurrentThread->CreateTime);
275
276 /* Free the Port */
277 ExFreePool(TerminationPort);
278
279 /* Get the next one */
280 TerminationPort = TerminationPort->Next;
281 DPRINT("TerminationPort: %p\n", TerminationPort);
282 }
283
284 /* Rundown Win32 Structures */
285 PsTerminateWin32Thread(CurrentThread);
286 if (Last) PsTerminateWin32Process(CurrentProcess);
287
288 /* Rundown Registry Notifications. TODO (refers to NtChangeNotify, not Cm callbacks) */
289 //CmNotifyRunDown(CurrentThread);
290
291 /* Free the TEB */
292 if((Teb = CurrentThread->Tcb.Teb)) {
293
294 DPRINT("Decommit teb at %p\n", Teb);
295 MmDeleteTeb(CurrentProcess, Teb);
296 CurrentThread->Tcb.Teb = NULL;
297 }
298
299 /* The last Thread shuts down the Process */
300 if (Last) PspExitProcess(CurrentProcess);
301
302 /* Unlock the Process */
303 PsUnlockProcess(CurrentProcess);
304
305 /* Cancel I/O for the thread. */
306 IoCancelThreadIo(CurrentThread);
307
308 /* Rundown Timers */
309 ExTimerRundown();
310 KeCancelTimer(&CurrentThread->Tcb.Timer);
311
312 /* If the Processor Control Block's NpxThread points to the current thread
313 * unset it.
314 */
315 InterlockedCompareExchangePointer(&KeGetCurrentPrcb()->NpxThread,
316 NULL,
317 (PKPROCESS)CurrentThread);
318
319 /* Rundown Mutexes */
320 KeRundownThread();
321
322 /* Terminate the Thread from the Scheduler */
323 KeTerminateThread(0);
324 DPRINT1("Unexpected return, CurrentThread %x PsGetCurrentThread() %x\n", CurrentThread, PsGetCurrentThread());
325 KEBUGCHECK(0);
326 }
327
328 VOID
329 STDCALL
330 PsExitSpecialApc(PKAPC Apc,
331 PKNORMAL_ROUTINE* NormalRoutine,
332 PVOID* NormalContext,
333 PVOID* SystemArgument1,
334 PVOID* SystemArguemnt2)
335 {
336 NTSTATUS ExitStatus = (NTSTATUS)Apc->NormalContext;
337
338 DPRINT("PsExitSpecialApc called: 0x%x (proc: 0x%x)\n", PsGetCurrentThread(), PsGetCurrentProcess());
339
340 /* Free the APC */
341 ExFreePool(Apc);
342
343 /* Terminate the Thread */
344 PspExitThread(ExitStatus);
345
346 /* we should never reach this point! */
347 KEBUGCHECK(0);
348 }
349
350 VOID
351 STDCALL
352 PspExitNormalApc(PVOID NormalContext,
353 PVOID SystemArgument1,
354 PVOID SystemArgument2)
355 {
356 /* Not fully supported yet... must work out some issues that
357 * I don't understand yet -- Alex
358 */
359 DPRINT1("APC2\n");
360 PspExitThread((NTSTATUS)NormalContext);
361
362 /* we should never reach this point! */
363 KEBUGCHECK(0);
364 }
365
366 /*
367 * See "Windows Internals" - Chapter 13, Page 49
368 */
369 VOID
370 STDCALL
371 PspTerminateThreadByPointer(PETHREAD Thread,
372 NTSTATUS ExitStatus)
373 {
374 PKAPC Apc;
375
376 DPRINT("PspTerminatedThreadByPointer(Thread %x, ExitStatus %x)\n",
377 Thread, ExitStatus);
378
379 /* Check if we are already in the right context */
380 if (PsGetCurrentThread() == Thread) {
381
382 /* Directly terminate the thread */
383 PspExitThread(ExitStatus);
384
385 /* we should never reach this point! */
386 KEBUGCHECK(0);
387 }
388
389 /* Allocate the APC */
390 Apc = ExAllocatePoolWithTag(NonPagedPool, sizeof(KAPC), TAG_TERMINATE_APC);
391
392 /* Initialize a Kernel Mode APC to Kill the Thread */
393 KeInitializeApc(Apc,
394 &Thread->Tcb,
395 OriginalApcEnvironment,
396 PsExitSpecialApc,
397 NULL,
398 PspExitNormalApc,
399 KernelMode,
400 (PVOID)ExitStatus);
401
402 /* Insert it into the APC Queue */
403 KeInsertQueueApc(Apc,
404 Apc,
405 NULL,
406 2);
407
408 /* Forcefully resume the thread */
409 KeForceResumeThread(&Thread->Tcb);
410 }
411
412 NTSTATUS
413 STDCALL
414 PspExitProcess(PEPROCESS Process)
415 {
416 DPRINT("PspExitProcess 0x%x\n", Process);
417
418 PspRunCreateProcessNotifyRoutines(Process, FALSE);
419
420 /* close all handles associated with our process, this needs to be done
421 when the last thread still runs */
422 ObKillProcess(Process);
423
424 KeSetProcess(&Process->Pcb, IO_NO_INCREMENT);
425
426 return(STATUS_SUCCESS);
427 }
428
429 NTSTATUS
430 STDCALL
431 NtTerminateProcess(IN HANDLE ProcessHandle OPTIONAL,
432 IN NTSTATUS ExitStatus)
433 {
434 NTSTATUS Status;
435 PEPROCESS Process;
436 PETHREAD CurrentThread;
437 BOOLEAN KillByHandle;
438
439 PAGED_CODE();
440
441 DPRINT("NtTerminateProcess(ProcessHandle %x, ExitStatus %x)\n",
442 ProcessHandle, ExitStatus);
443
444 KillByHandle = (ProcessHandle != NULL);
445
446 /* Get the Process Object */
447 Status = ObReferenceObjectByHandle((KillByHandle ? ProcessHandle : NtCurrentProcess()),
448 PROCESS_TERMINATE,
449 PsProcessType,
450 KeGetPreviousMode(),
451 (PVOID*)&Process,
452 NULL);
453 if (!NT_SUCCESS(Status)) {
454
455 DPRINT1("Invalid handle to Process\n");
456 return(Status);
457 }
458
459 CurrentThread = PsGetCurrentThread();
460
461 PsLockProcess(Process, FALSE);
462
463 if(Process->ExitTime.QuadPart != 0)
464 {
465 PsUnlockProcess(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->HasTerminated = 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->HasTerminated) {
551
552 Thread->HasTerminated = 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->HasTerminated = 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 }