2 * PROJECT: ReactOS Kernel
3 * LICENSE: GPL - See COPYING in the top level directory
4 * FILE: ntoskrnl/dbgk/dbgkobj.c
5 * PURPOSE: User-Mode Debugging Support, Debug Object Management.
6 * PROGRAMMERS: Alex Ionescu (alex.ionescu@reactos.org)
9 /* INCLUDES ******************************************************************/
15 POBJECT_TYPE DbgkDebugObjectType
;
16 FAST_MUTEX DbgkpProcessDebugPortMutex
;
17 ULONG DbgkpTraceLevel
= 0;
19 GENERIC_MAPPING DbgkDebugObjectMapping
=
21 STANDARD_RIGHTS_READ
| DEBUG_OBJECT_WAIT_STATE_CHANGE
,
22 STANDARD_RIGHTS_WRITE
| DEBUG_OBJECT_ADD_REMOVE_PROCESS
,
23 STANDARD_RIGHTS_EXECUTE
| SYNCHRONIZE
,
24 DEBUG_OBJECT_ALL_ACCESS
27 static const INFORMATION_CLASS_INFO DbgkpDebugObjectInfoClass
[] =
29 /* DebugObjectUnusedInformation */
30 ICI_SQ_SAME(sizeof(ULONG
), sizeof(ULONG
), 0),
31 /* DebugObjectKillProcessOnExitInformation */
32 ICI_SQ_SAME(sizeof(DEBUG_OBJECT_KILL_PROCESS_ON_EXIT_INFORMATION
), sizeof(ULONG
), ICIF_SET
),
35 /* PRIVATE FUNCTIONS *********************************************************/
39 DbgkpQueueMessage(IN PEPROCESS Process
,
41 IN PDBGKM_MSG Message
,
43 IN PDEBUG_OBJECT TargetObject OPTIONAL
)
45 PDEBUG_EVENT DebugEvent
;
46 DEBUG_EVENT LocalDebugEvent
;
47 PDEBUG_OBJECT DebugObject
;
51 DBGKTRACE(DBGK_MESSAGE_DEBUG
,
52 "Process: %p Thread: %p Message: %p Flags: %lx\n",
53 Process
, Thread
, Message
, Flags
);
55 /* Check if we have to allocate a debug event */
56 NewEvent
= (Flags
& DEBUG_EVENT_NOWAIT
) ? TRUE
: FALSE
;
60 DebugEvent
= ExAllocatePoolWithTag(NonPagedPool
,
63 if (!DebugEvent
) return STATUS_INSUFFICIENT_RESOURCES
;
66 DebugEvent
->Flags
= Flags
| DEBUG_EVENT_INACTIVE
;
68 /* Reference the thread and process */
69 ObReferenceObject(Thread
);
70 ObReferenceObject(Process
);
72 /* Set the current thread */
73 DebugEvent
->BackoutThread
= PsGetCurrentThread();
75 /* Set the debug object */
76 DebugObject
= TargetObject
;
80 /* Use the debug event on the stack */
81 DebugEvent
= &LocalDebugEvent
;
82 DebugEvent
->Flags
= Flags
;
84 /* Acquire the port lock */
85 ExAcquireFastMutex(&DbgkpProcessDebugPortMutex
);
87 /* Get the debug object */
88 DebugObject
= Process
->DebugPort
;
90 /* Check what kind of API message this is */
91 switch (Message
->ApiNumber
)
93 /* Process or thread creation */
94 case DbgKmCreateThreadApi
:
95 case DbgKmCreateProcessApi
:
97 /* Make sure we're not skipping creation messages */
98 if (Thread
->SkipCreationMsg
) DebugObject
= NULL
;
101 /* Process or thread exit */
102 case DbgKmExitThreadApi
:
103 case DbgKmExitProcessApi
:
105 /* Make sure we're not skipping exit messages */
106 if (Thread
->SkipTerminationMsg
) DebugObject
= NULL
;
108 /* No special handling for other messages */
114 /* Setup the Debug Event */
115 KeInitializeEvent(&DebugEvent
->ContinueEvent
, SynchronizationEvent
, FALSE
);
116 DebugEvent
->Process
= Process
;
117 DebugEvent
->Thread
= Thread
;
118 DebugEvent
->ApiMsg
= *Message
;
119 DebugEvent
->ClientId
= Thread
->Cid
;
121 /* Check if we have a port object */
125 Status
= STATUS_PORT_NOT_SET
;
129 /* Acquire the debug object mutex */
130 ExAcquireFastMutex(&DebugObject
->Mutex
);
132 /* Check if a debugger is active */
133 if (!DebugObject
->DebuggerInactive
)
135 /* Add the event into the object's list */
136 DBGKTRACE(DBGK_MESSAGE_DEBUG
, "Inserting: %lx %p\n",
137 DebugEvent
, Message
->ApiNumber
);
138 InsertTailList(&DebugObject
->EventList
, &DebugEvent
->EventList
);
140 /* Check if we have to signal it */
144 KeSetEvent(&DebugObject
->EventsPresent
,
150 Status
= STATUS_SUCCESS
;
155 Status
= STATUS_DEBUGGER_INACTIVE
;
158 /* Release the object lock */
159 ExReleaseFastMutex(&DebugObject
->Mutex
);
162 /* Check if we had acquired the port lock */
166 ExReleaseFastMutex(&DbgkpProcessDebugPortMutex
);
168 /* Check if we got here through success */
169 if (NT_SUCCESS(Status
))
171 /* Wait on the continue event */
172 KeWaitForSingleObject(&DebugEvent
->ContinueEvent
,
178 /* Copy API Message back */
179 *Message
= DebugEvent
->ApiMsg
;
181 /* Set return status */
182 Status
= DebugEvent
->Status
;
187 /* Check if we failed */
188 if (!NT_SUCCESS(Status
))
190 /* Dereference the process and thread */
191 ObDereferenceObject(Thread
);
192 ObDereferenceObject(Process
);
194 /* Free the debug event */
195 ExFreePool(DebugEvent
);
200 DBGKTRACE(DBGK_MESSAGE_DEBUG
, "Status: %lx\n", Status
);
206 DbgkpSendApiMessageLpc(IN OUT PDBGKM_MSG Message
,
208 IN BOOLEAN SuspendProcess
)
211 UCHAR Buffer
[PORT_MAXIMUM_MESSAGE_LENGTH
];
212 BOOLEAN Suspended
= FALSE
;
215 /* Suspend process if required */
216 if (SuspendProcess
) Suspended
= DbgkpSuspendProcess();
218 /* Set return status */
219 Message
->ReturnedStatus
= STATUS_PENDING
;
221 /* Set create process reported state */
222 PspSetProcessFlag(PsGetCurrentProcess(), PSF_CREATE_REPORTED_BIT
);
224 /* Send the LPC command */
225 Status
= LpcRequestWaitReplyPort(Port
,
226 (PPORT_MESSAGE
)Message
,
227 (PPORT_MESSAGE
)&Buffer
[0]);
229 /* Flush the instruction cache */
230 ZwFlushInstructionCache(NtCurrentProcess(), NULL
, 0);
232 /* Copy the buffer back */
233 if (NT_SUCCESS(Status
)) RtlCopyMemory(Message
, Buffer
, sizeof(DBGKM_MSG
));
235 /* Resume the process if it was suspended */
236 if (Suspended
) DbgkpResumeProcess();
242 DbgkpSendApiMessage(IN OUT PDBGKM_MSG ApiMsg
,
243 IN BOOLEAN SuspendProcess
)
246 BOOLEAN Suspended
= FALSE
;
248 DBGKTRACE(DBGK_MESSAGE_DEBUG
, "ApiMsg: %p SuspendProcess: %lx\n", ApiMsg
, SuspendProcess
);
250 /* Suspend process if required */
251 if (SuspendProcess
) Suspended
= DbgkpSuspendProcess();
253 /* Set return status */
254 ApiMsg
->ReturnedStatus
= STATUS_PENDING
;
256 /* Set create process reported state */
257 PspSetProcessFlag(PsGetCurrentProcess(), PSF_CREATE_REPORTED_BIT
);
259 /* Send the LPC command */
260 Status
= DbgkpQueueMessage(PsGetCurrentProcess(),
261 PsGetCurrentThread(),
266 /* Flush the instruction cache */
267 ZwFlushInstructionCache(NtCurrentProcess(), NULL
, 0);
269 /* Resume the process if it was suspended */
270 if (Suspended
) DbgkpResumeProcess();
276 DbgkCopyProcessDebugPort(IN PEPROCESS Process
,
279 PDEBUG_OBJECT DebugObject
;
281 DBGKTRACE(DBGK_PROCESS_DEBUG
, "Process: %p Parent: %p\n", Process
, Parent
);
283 /* Clear this process's port */
284 Process
->DebugPort
= NULL
;
286 /* Check if the parent has one */
287 if (!Parent
->DebugPort
) return;
289 /* It does, acquire the mutex */
290 ExAcquireFastMutex(&DbgkpProcessDebugPortMutex
);
292 /* Make sure it still has one, and that we should inherit */
293 DebugObject
= Parent
->DebugPort
;
294 if ((DebugObject
) && !(Process
->NoDebugInherit
))
296 /* Acquire the debug object's lock */
297 ExAcquireFastMutex(&DebugObject
->Mutex
);
299 /* Make sure the debugger is active */
300 if (!DebugObject
->DebuggerInactive
)
302 /* Reference the object and set it */
303 ObReferenceObject(DebugObject
);
304 Process
->DebugPort
= DebugObject
;
307 /* Release the debug object */
308 ExReleaseFastMutex(&DebugObject
->Mutex
);
311 /* Release the port mutex */
312 ExReleaseFastMutex(&DbgkpProcessDebugPortMutex
);
317 DbgkForwardException(IN PEXCEPTION_RECORD ExceptionRecord
,
318 IN BOOLEAN DebugPort
,
319 IN BOOLEAN SecondChance
)
321 DBGKM_MSG ApiMessage
;
322 PDBGKM_EXCEPTION DbgKmException
= &ApiMessage
.Exception
;
324 PEPROCESS Process
= PsGetCurrentProcess();
326 BOOLEAN UseLpc
= FALSE
;
328 DBGKTRACE(DBGK_EXCEPTION_DEBUG
,
329 "ExceptionRecord: %p Port: %p\n", ExceptionRecord
, DebugPort
);
331 /* Setup the API Message */
332 ApiMessage
.h
.u1
.Length
= sizeof(DBGKM_MSG
) << 16 |
333 (8 + sizeof(DBGKM_EXCEPTION
));
334 ApiMessage
.h
.u2
.ZeroInit
= 0;
335 ApiMessage
.h
.u2
.s2
.Type
= LPC_DEBUG_EVENT
;
336 ApiMessage
.ApiNumber
= DbgKmExceptionApi
;
338 /* Check if this is to be sent on the debug port */
341 /* Use the debug port, unless the thread is being hidden */
342 Port
= PsGetCurrentThread()->HideFromDebugger
?
343 NULL
: Process
->DebugPort
;
347 /* Otherwise, use the exception port */
348 Port
= Process
->ExceptionPort
;
349 ApiMessage
.h
.u2
.ZeroInit
= 0;
350 ApiMessage
.h
.u2
.s2
.Type
= LPC_EXCEPTION
;
354 /* Break out if there's no port */
355 if (!Port
) return FALSE
;
357 /* Fill out the exception information */
358 DbgKmException
->ExceptionRecord
= *ExceptionRecord
;
359 DbgKmException
->FirstChance
= !SecondChance
;
361 /* Check if we should use LPC */
364 /* Send the message on the LPC Port */
365 Status
= DbgkpSendApiMessageLpc(&ApiMessage
, Port
, DebugPort
);
369 /* Use native debug object */
370 Status
= DbgkpSendApiMessage(&ApiMessage
, DebugPort
);
373 /* Check if we failed, and for a debug port, also check the return status */
374 if (!(NT_SUCCESS(Status
)) ||
376 (!(NT_SUCCESS(ApiMessage
.ReturnedStatus
)) ||
377 (ApiMessage
.ReturnedStatus
== DBG_EXCEPTION_NOT_HANDLED
))))
383 /* Otherwise, we're ok */
389 DbgkpFreeDebugEvent(IN PDEBUG_EVENT DebugEvent
)
391 PHANDLE Handle
= NULL
;
393 DBGKTRACE(DBGK_OBJECT_DEBUG
, "DebugEvent: %p\n", DebugEvent
);
395 /* Check if this event had a file handle */
396 switch (DebugEvent
->ApiMsg
.ApiNumber
)
398 /* Create process has a handle */
399 case DbgKmCreateProcessApi
:
401 /* Get the pointer */
402 Handle
= &DebugEvent
->ApiMsg
.CreateProcess
.FileHandle
;
405 /* As does DLL load */
406 case DbgKmLoadDllApi
:
408 /* Get the pointer */
409 Handle
= &DebugEvent
->ApiMsg
.LoadDll
.FileHandle
;
415 /* Close the handle if it exsts */
416 if ((Handle
) && (*Handle
)) ObCloseHandle(*Handle
, KernelMode
);
418 /* Dereference process and thread and free the event */
419 ObDereferenceObject(DebugEvent
->Process
);
420 ObDereferenceObject(DebugEvent
->Thread
);
421 ExFreePool(DebugEvent
);
426 DbgkpWakeTarget(IN PDEBUG_EVENT DebugEvent
)
428 PETHREAD Thread
= DebugEvent
->Thread
;
430 DBGKTRACE(DBGK_OBJECT_DEBUG
, "DebugEvent: %p\n", DebugEvent
);
432 /* Check if we have to wake the thread */
433 if (DebugEvent
->Flags
& DEBUG_EVENT_SUSPEND
) PsResumeThread(Thread
, NULL
);
435 /* Check if we had locked the thread */
436 if (DebugEvent
->Flags
& DEBUG_EVENT_RELEASE
)
439 ExReleaseRundownProtection(&Thread
->RundownProtect
);
442 /* Check if we have to wake up the event */
443 if (DebugEvent
->Flags
& DEBUG_EVENT_NOWAIT
)
445 /* Otherwise, free the debug event */
446 DbgkpFreeDebugEvent(DebugEvent
);
450 /* Signal the continue event */
451 KeSetEvent(&DebugEvent
->ContinueEvent
, IO_NO_INCREMENT
, FALSE
);
457 DbgkpPostFakeModuleMessages(IN PEPROCESS Process
,
459 IN PDEBUG_OBJECT DebugObject
)
461 PPEB Peb
= Process
->Peb
;
462 PPEB_LDR_DATA LdrData
;
463 PLDR_DATA_TABLE_ENTRY LdrEntry
;
464 PLIST_ENTRY ListHead
, NextEntry
;
465 DBGKM_MSG ApiMessage
;
466 PDBGKM_LOAD_DLL LoadDll
= &ApiMessage
.LoadDll
;
468 PIMAGE_NT_HEADERS NtHeader
;
469 UNICODE_STRING ModuleName
;
470 OBJECT_ATTRIBUTES ObjectAttributes
;
471 IO_STATUS_BLOCK IoStatusBlock
;
474 DBGKTRACE(DBGK_PROCESS_DEBUG
, "Process: %p Thread: %p DebugObject: %p\n",
475 Process
, Thread
, DebugObject
);
477 /* Quit if there's no PEB */
478 if (!Peb
) return STATUS_SUCCESS
;
480 /* Get the Loader Data List */
482 ListHead
= &LdrData
->InLoadOrderModuleList
;
483 NextEntry
= ListHead
->Flink
;
485 /* Loop the modules */
487 while ((NextEntry
!= ListHead
) && (i
< 500))
489 /* Skip the first entry */
492 /* Go to the next module */
493 NextEntry
= NextEntry
->Flink
;
499 LdrEntry
= CONTAINING_RECORD(NextEntry
,
500 LDR_DATA_TABLE_ENTRY
,
503 /* Setup the API Message */
504 RtlZeroMemory(&ApiMessage
, sizeof(DBGKM_MSG
));
505 ApiMessage
.ApiNumber
= DbgKmLoadDllApi
;
507 /* Set base and clear the name */
508 LoadDll
->BaseOfDll
= LdrEntry
->DllBase
;
509 LoadDll
->NamePointer
= NULL
;
511 /* Get the NT Headers */
512 NtHeader
= RtlImageNtHeader(LoadDll
->BaseOfDll
);
515 /* Save debug data */
516 LoadDll
->DebugInfoFileOffset
= NtHeader
->FileHeader
.
517 PointerToSymbolTable
;
518 LoadDll
->DebugInfoSize
= NtHeader
->FileHeader
.NumberOfSymbols
;
522 DBGKTRACE(DBGK_PROCESS_DEBUG
, "Name: %wZ. Base: %p\n",
523 &LdrEntry
->FullDllName
, LdrEntry
->DllBase
);
525 /* Get the name of the DLL */
526 Status
= MmGetFileNameForAddress(NtHeader
, &ModuleName
);
527 if (NT_SUCCESS(Status
))
529 /* Setup the object attributes */
530 InitializeObjectAttributes(&ObjectAttributes
,
532 OBJ_FORCE_ACCESS_CHECK
|
534 OBJ_CASE_INSENSITIVE
,
538 /* Open the file to get a handle to it */
539 Status
= ZwOpenFile(&LoadDll
->FileHandle
,
540 GENERIC_READ
| SYNCHRONIZE
,
546 FILE_SYNCHRONOUS_IO_NONALERT
);
547 if (!NT_SUCCESS(Status
)) LoadDll
->FileHandle
= NULL
;
549 /* Free the name now */
550 ExFreePool(ModuleName
.Buffer
);
553 /* Send the fake module load message */
554 Status
= DbgkpQueueMessage(Process
,
559 if (!NT_SUCCESS(Status
))
561 /* Message send failed, close the file handle if we had one */
562 if (LoadDll
->FileHandle
) ObCloseHandle(LoadDll
->FileHandle
,
566 /* Go to the next module */
567 NextEntry
= NextEntry
->Flink
;
572 return STATUS_SUCCESS
;
577 DbgkpPostFakeThreadMessages(IN PEPROCESS Process
,
578 IN PDEBUG_OBJECT DebugObject
,
579 IN PETHREAD StartThread
,
580 OUT PETHREAD
*FirstThread
,
581 OUT PETHREAD
*LastThread
)
583 PETHREAD pFirstThread
= NULL
, ThisThread
, OldThread
= NULL
, pLastThread
;
584 NTSTATUS Status
= STATUS_UNSUCCESSFUL
;
585 BOOLEAN IsFirstThread
;
587 DBGKM_MSG ApiMessage
;
588 PDBGKM_CREATE_THREAD CreateThread
= &ApiMessage
.CreateThread
;
589 PDBGKM_CREATE_PROCESS CreateProcess
= &ApiMessage
.CreateProcess
;
591 PIMAGE_NT_HEADERS NtHeader
;
593 DBGKTRACE(DBGK_THREAD_DEBUG
, "Process: %p StartThread: %p Object: %p\n",
594 Process
, StartThread
, DebugObject
);
596 /* Check if we have a start thread */
599 /* Then the one we'll find won't be the first one */
600 IsFirstThread
= FALSE
;
601 pFirstThread
= StartThread
;
602 ThisThread
= StartThread
;
605 ObReferenceObject(StartThread
);
609 /* Get the first thread ourselves */
610 ThisThread
= PsGetNextProcessThread(Process
, NULL
);
611 IsFirstThread
= TRUE
;
614 /* Start thread loop */
617 /* Dereference the previous thread if we had one */
618 if (OldThread
) ObDereferenceObject(OldThread
);
620 /* Set this as the last thread and lock it */
621 pLastThread
= ThisThread
;
622 ObReferenceObject(ThisThread
);
623 if (ExAcquireRundownProtection(&ThisThread
->RundownProtect
))
625 /* Acquire worked, set flags */
626 Flags
= DEBUG_EVENT_RELEASE
| DEBUG_EVENT_NOWAIT
;
628 /* Check if this is a user thread */
629 if (!ThisThread
->SystemThread
)
632 if (NT_SUCCESS(PsSuspendThread(ThisThread
, NULL
)))
635 Flags
|= DEBUG_EVENT_SUSPEND
;
641 /* Couldn't acquire rundown */
642 Flags
= DEBUG_EVENT_PROTECT_FAILED
| DEBUG_EVENT_NOWAIT
;
645 /* Clear the API Message */
646 RtlZeroMemory(&ApiMessage
, sizeof(ApiMessage
));
648 /* Check if this is the first thread */
649 if ((IsFirstThread
) &&
650 !(Flags
& DEBUG_EVENT_PROTECT_FAILED
) &&
651 !(ThisThread
->SystemThread
) &&
652 (ThisThread
->GrantedAccess
))
654 /* It is, save the flag */
659 /* It isn't, save the flag */
663 /* Check if this is the first */
666 /* So we'll start with the create process message */
667 ApiMessage
.ApiNumber
= DbgKmCreateProcessApi
;
669 /* Get the file handle */
670 if (Process
->SectionObject
)
672 /* Use the section object */
673 CreateProcess
->FileHandle
=
674 DbgkpSectionToFileHandle(Process
->SectionObject
);
678 /* Don't return any handle */
679 CreateProcess
->FileHandle
= NULL
;
682 /* Set the base address */
683 CreateProcess
->BaseOfImage
= Process
->SectionBaseAddress
;
685 /* Get the NT Header */
686 NtHeader
= RtlImageNtHeader(Process
->SectionBaseAddress
);
689 /* Fill out data from the header */
690 CreateProcess
->DebugInfoFileOffset
= NtHeader
->FileHeader
.
691 PointerToSymbolTable
;
692 CreateProcess
->DebugInfoSize
= NtHeader
->FileHeader
.
698 /* Otherwise it's a thread message */
699 ApiMessage
.ApiNumber
= DbgKmCreateThreadApi
;
700 CreateThread
->StartAddress
= ThisThread
->StartAddress
;
704 DBGKTRACE(DBGK_THREAD_DEBUG
, "Thread: %p. First: %lx, OldThread: %p\n",
705 ThisThread
, First
, OldThread
);
706 DBGKTRACE(DBGK_THREAD_DEBUG
, "Start Address: %p\n",
707 ThisThread
->StartAddress
);
709 /* Queue the message */
710 Status
= DbgkpQueueMessage(Process
,
715 if (!NT_SUCCESS(Status
))
717 /* Resume the thread if it was suspended */
718 if (Flags
& DEBUG_EVENT_SUSPEND
) PsResumeThread(ThisThread
, NULL
);
720 /* Check if we acquired rundown */
721 if (Flags
& DEBUG_EVENT_RELEASE
)
724 ExReleaseRundownProtection(&ThisThread
->RundownProtect
);
727 /* If this was a process create, check if we got a handle */
728 if ((ApiMessage
.ApiNumber
== DbgKmCreateProcessApi
) &&
729 (CreateProcess
->FileHandle
))
732 ObCloseHandle(CreateProcess
->FileHandle
, KernelMode
);
735 /* Release our reference and break out */
736 ObDereferenceObject(ThisThread
);
740 /* Check if this was the first message */
743 /* It isn't the first thread anymore */
744 IsFirstThread
= FALSE
;
746 /* Reference this thread and set it as first */
747 ObReferenceObject(ThisThread
);
748 pFirstThread
= ThisThread
;
751 /* Get the next thread */
752 ThisThread
= PsGetNextProcessThread(Process
, ThisThread
);
753 OldThread
= pLastThread
;
754 } while (ThisThread
);
756 /* Check the API status */
757 if (!NT_SUCCESS(Status
))
759 /* Dereference and fail */
760 if (pFirstThread
) ObDereferenceObject(pFirstThread
);
761 if (pLastThread
) ObDereferenceObject(pLastThread
);
765 /* Make sure we have a first thread */
766 if (!pFirstThread
) return STATUS_UNSUCCESSFUL
;
768 /* Return thread pointers */
769 *FirstThread
= pFirstThread
;
770 *LastThread
= pLastThread
;
776 DbgkpPostFakeProcessCreateMessages(IN PEPROCESS Process
,
777 IN PDEBUG_OBJECT DebugObject
,
778 OUT PETHREAD
*LastThread
)
781 PETHREAD FirstThread
, FinalThread
;
782 PETHREAD ReturnThread
= NULL
;
785 DBGKTRACE(DBGK_PROCESS_DEBUG
, "Process: %p DebugObject: %p\n",
786 Process
, DebugObject
);
788 /* Attach to the process */
789 KeStackAttachProcess(&Process
->Pcb
, &ApcState
);
791 /* Post the fake thread messages */
792 Status
= DbgkpPostFakeThreadMessages(Process
,
797 if (NT_SUCCESS(Status
))
799 /* Send the fake module messages too */
800 Status
= DbgkpPostFakeModuleMessages(Process
,
803 if (!NT_SUCCESS(Status
))
805 /* We failed, dereference the final thread */
806 ObDereferenceObject(FinalThread
);
810 /* Set the final thread */
811 ReturnThread
= FinalThread
;
814 /* Dereference the first thread */
815 ObDereferenceObject(FirstThread
);
818 /* Detach from the process */
819 KeUnstackDetachProcess(&ApcState
);
821 /* Return the last thread */
822 *LastThread
= ReturnThread
;
828 DbgkpConvertKernelToUserStateChange(IN PDBGUI_WAIT_STATE_CHANGE WaitStateChange
,
829 IN PDEBUG_EVENT DebugEvent
)
831 DBGKTRACE(DBGK_OBJECT_DEBUG
, "DebugEvent: %p\n", DebugEvent
);
833 /* Start by copying the client ID */
834 WaitStateChange
->AppClientId
= DebugEvent
->ClientId
;
836 /* Now check which kind of event this was */
837 switch (DebugEvent
->ApiMsg
.ApiNumber
)
840 case DbgKmCreateProcessApi
:
842 /* Set the right native code */
843 WaitStateChange
->NewState
= DbgCreateProcessStateChange
;
845 /* Copy the information */
846 WaitStateChange
->StateInfo
.CreateProcessInfo
.NewProcess
=
847 DebugEvent
->ApiMsg
.CreateProcess
;
849 /* Clear the file handle for us */
850 DebugEvent
->ApiMsg
.CreateProcess
.FileHandle
= NULL
;
854 case DbgKmCreateThreadApi
:
856 /* Set the right native code */
857 WaitStateChange
->NewState
= DbgCreateThreadStateChange
;
859 /* Copy information */
860 WaitStateChange
->StateInfo
.CreateThread
.NewThread
.StartAddress
=
861 DebugEvent
->ApiMsg
.CreateThread
.StartAddress
;
862 WaitStateChange
->StateInfo
.CreateThread
.NewThread
.SubSystemKey
=
863 DebugEvent
->ApiMsg
.CreateThread
.SubSystemKey
;
866 /* Exception (or breakpoint/step) */
867 case DbgKmExceptionApi
:
869 /* Look at the exception code */
870 if ((NTSTATUS
)DebugEvent
->ApiMsg
.Exception
.ExceptionRecord
.ExceptionCode
==
873 /* Update this as a breakpoint exception */
874 WaitStateChange
->NewState
= DbgBreakpointStateChange
;
876 else if ((NTSTATUS
)DebugEvent
->ApiMsg
.Exception
.ExceptionRecord
.ExceptionCode
==
879 /* Update this as a single step exception */
880 WaitStateChange
->NewState
= DbgSingleStepStateChange
;
884 /* Otherwise, set default exception */
885 WaitStateChange
->NewState
= DbgExceptionStateChange
;
888 /* Copy the exception record */
889 WaitStateChange
->StateInfo
.Exception
.ExceptionRecord
=
890 DebugEvent
->ApiMsg
.Exception
.ExceptionRecord
;
891 /* Copy FirstChance flag */
892 WaitStateChange
->StateInfo
.Exception
.FirstChance
=
893 DebugEvent
->ApiMsg
.Exception
.FirstChance
;
897 case DbgKmExitProcessApi
:
899 /* Set the right native code and copy the exit code */
900 WaitStateChange
->NewState
= DbgExitProcessStateChange
;
901 WaitStateChange
->StateInfo
.ExitProcess
.ExitStatus
=
902 DebugEvent
->ApiMsg
.ExitProcess
.ExitStatus
;
906 case DbgKmExitThreadApi
:
908 /* Set the right native code */
909 WaitStateChange
->NewState
= DbgExitThreadStateChange
;
910 WaitStateChange
->StateInfo
.ExitThread
.ExitStatus
=
911 DebugEvent
->ApiMsg
.ExitThread
.ExitStatus
;
915 case DbgKmLoadDllApi
:
917 /* Set the native code */
918 WaitStateChange
->NewState
= DbgLoadDllStateChange
;
921 WaitStateChange
->StateInfo
.LoadDll
= DebugEvent
->ApiMsg
.LoadDll
;
923 /* Clear the file handle for us */
924 DebugEvent
->ApiMsg
.LoadDll
.FileHandle
= NULL
;
928 case DbgKmUnloadDllApi
:
930 /* Set the native code and copy the address */
931 WaitStateChange
->NewState
= DbgUnloadDllStateChange
;
932 WaitStateChange
->StateInfo
.UnloadDll
.BaseAddress
=
933 DebugEvent
->ApiMsg
.UnloadDll
.BaseAddress
;
938 /* Shouldn't happen */
945 DbgkpMarkProcessPeb(IN PEPROCESS Process
)
949 DBGKTRACE(DBGK_PROCESS_DEBUG
, "Process: %p\n", Process
);
951 /* Acquire process rundown */
952 if (!ExAcquireRundownProtection(&Process
->RundownProtect
)) return;
954 /* Make sure we have a PEB */
957 /* Attach to the process */
958 KeStackAttachProcess(&Process
->Pcb
, &ApcState
);
960 /* Acquire the debug port mutex */
961 ExAcquireFastMutex(&DbgkpProcessDebugPortMutex
);
963 /* Set the IsBeingDebugged member of the PEB */
964 Process
->Peb
->BeingDebugged
= (Process
->DebugPort
) ? TRUE
: FALSE
;
967 ExReleaseFastMutex(&DbgkpProcessDebugPortMutex
);
969 /* Detach from the process */
970 KeUnstackDetachProcess(&ApcState
);
973 /* Release rundown protection */
974 ExReleaseRundownProtection(&Process
->RundownProtect
);
979 DbgkpOpenHandles(IN PDBGUI_WAIT_STATE_CHANGE WaitStateChange
,
980 IN PEPROCESS Process
,
987 DBGKTRACE(DBGK_OBJECT_DEBUG
, "Process: %p Thread: %p State: %lx\n",
988 Process
, Thread
, WaitStateChange
->NewState
);
990 /* Check which state this is */
991 switch (WaitStateChange
->NewState
)
994 case DbgCreateThreadStateChange
:
996 /* Get handle to thread */
997 Status
= ObOpenObjectByPointer(Thread
,
1004 if (NT_SUCCESS(Status
))
1006 /* Save the thread handle */
1008 StateInfo
.CreateThread
.HandleToThread
= Handle
;
1013 case DbgCreateProcessStateChange
:
1015 /* Get handle to thread */
1016 Status
= ObOpenObjectByPointer(Thread
,
1023 if (NT_SUCCESS(Status
))
1025 /* Save the thread handle */
1027 StateInfo
.CreateProcessInfo
.HandleToThread
= Handle
;
1030 /* Get handle to process */
1031 Status
= ObOpenObjectByPointer(Process
,
1038 if (NT_SUCCESS(Status
))
1040 /* Save the process handle */
1042 StateInfo
.CreateProcessInfo
.HandleToProcess
= Handle
;
1045 /* Fall through to duplicate file handle */
1046 DupHandle
= &WaitStateChange
->
1047 StateInfo
.CreateProcessInfo
.NewProcess
.FileHandle
;
1051 case DbgLoadDllStateChange
:
1053 /* Fall through to duplicate file handle */
1054 DupHandle
= &WaitStateChange
->StateInfo
.LoadDll
.FileHandle
;
1057 /* Anything else has no handles */
1062 /* If we got here, then we have to duplicate a handle, possibly */
1063 Handle
= *DupHandle
;
1067 Status
= ObDuplicateObject(PsGetCurrentProcess(),
1069 PsGetCurrentProcess(),
1073 DUPLICATE_SAME_ACCESS
,
1075 if (!NT_SUCCESS(Status
)) *DupHandle
= NULL
;
1077 /* Close the original handle */
1078 ObCloseHandle(Handle
, KernelMode
);
1084 DbgkpDeleteObject(IN PVOID DebugObject
)
1089 ASSERT(IsListEmpty(&((PDEBUG_OBJECT
)DebugObject
)->EventList
));
1094 DbgkpCloseObject(IN PEPROCESS OwnerProcess OPTIONAL
,
1095 IN PVOID ObjectBody
,
1096 IN ACCESS_MASK GrantedAccess
,
1097 IN ULONG HandleCount
,
1098 IN ULONG SystemHandleCount
)
1100 PDEBUG_OBJECT DebugObject
= ObjectBody
;
1101 PEPROCESS Process
= NULL
;
1102 BOOLEAN DebugPortCleared
= FALSE
;
1103 PLIST_ENTRY DebugEventList
;
1104 PDEBUG_EVENT DebugEvent
;
1106 DBGKTRACE(DBGK_OBJECT_DEBUG
, "OwnerProcess: %p DebugObject: %p\n",
1107 OwnerProcess
, DebugObject
);
1109 /* If this isn't the last handle, do nothing */
1110 if (SystemHandleCount
> 1) return;
1112 /* Otherwise, lock the debug object */
1113 ExAcquireFastMutex(&DebugObject
->Mutex
);
1115 /* Set it as inactive */
1116 DebugObject
->DebuggerInactive
= TRUE
;
1118 /* Remove it from the debug event list */
1119 DebugEventList
= DebugObject
->EventList
.Flink
;
1120 InitializeListHead(&DebugObject
->EventList
);
1122 /* Release the lock */
1123 ExReleaseFastMutex(&DebugObject
->Mutex
);
1125 /* Signal the wait event */
1126 KeSetEvent(&DebugObject
->EventsPresent
, IO_NO_INCREMENT
, FALSE
);
1128 /* Start looping each process */
1129 while ((Process
= PsGetNextProcess(Process
)))
1131 /* Check if the process has us as their debug port */
1132 if (Process
->DebugPort
== DebugObject
)
1134 /* Acquire the process debug port lock */
1135 ExAcquireFastMutex(&DbgkpProcessDebugPortMutex
);
1137 /* Check if it's still us */
1138 if (Process
->DebugPort
== DebugObject
)
1140 /* Clear it and remember */
1141 Process
->DebugPort
= NULL
;
1142 DebugPortCleared
= TRUE
;
1145 /* Release the port lock */
1146 ExReleaseFastMutex(&DbgkpProcessDebugPortMutex
);
1148 /* Check if we cleared the debug port */
1149 if (DebugPortCleared
)
1151 /* Mark this in the PEB */
1152 DbgkpMarkProcessPeb(Process
);
1154 /* Check if we terminate on exit */
1155 if (DebugObject
->KillProcessOnExit
)
1157 /* Terminate the process */
1158 PsTerminateProcess(Process
, STATUS_DEBUGGER_INACTIVE
);
1161 /* Dereference the debug object */
1162 ObDereferenceObject(DebugObject
);
1167 /* Loop debug events */
1168 while (DebugEventList
!= &DebugObject
->EventList
)
1170 /* Get the debug event */
1171 DebugEvent
= CONTAINING_RECORD(DebugEventList
, DEBUG_EVENT
, EventList
);
1173 /* Go to the next entry */
1174 DebugEventList
= DebugEventList
->Flink
;
1177 DebugEvent
->Status
= STATUS_DEBUGGER_INACTIVE
;
1178 DbgkpWakeTarget(DebugEvent
);
1184 DbgkpSetProcessDebugObject(IN PEPROCESS Process
,
1185 IN PDEBUG_OBJECT DebugObject
,
1186 IN NTSTATUS MsgStatus
,
1187 IN PETHREAD LastThread
)
1190 LIST_ENTRY TempList
;
1191 BOOLEAN GlobalHeld
= FALSE
, DoSetEvent
= TRUE
;
1192 PETHREAD ThisThread
, FirstThread
;
1193 PLIST_ENTRY NextEntry
;
1194 PDEBUG_EVENT DebugEvent
;
1195 PETHREAD EventThread
;
1197 DBGKTRACE(DBGK_PROCESS_DEBUG
, "Process: %p DebugObject: %p\n",
1198 Process
, DebugObject
);
1200 /* Initialize the temporary list */
1201 InitializeListHead(&TempList
);
1203 /* Check if we have a success message */
1204 if (NT_SUCCESS(MsgStatus
))
1206 /* Then default to STATUS_SUCCESS */
1207 Status
= STATUS_SUCCESS
;
1211 /* No last thread, and set the failure code */
1216 /* Now check what status we have here */
1217 if (NT_SUCCESS(Status
))
1219 /* Acquire the global lock */
1222 ExAcquireFastMutex(&DbgkpProcessDebugPortMutex
);
1224 /* Check if we already have a port */
1225 if (Process
->DebugPort
)
1228 Status
= STATUS_PORT_ALREADY_SET
;
1232 /* Otherwise, set the port and reference the thread */
1233 Process
->DebugPort
= DebugObject
;
1234 ObReferenceObject(LastThread
);
1236 /* Get the next thread */
1237 ThisThread
= PsGetNextProcessThread(Process
, LastThread
);
1240 /* Clear the debug port and release the lock */
1241 Process
->DebugPort
= NULL
;
1242 ExReleaseFastMutex(&DbgkpProcessDebugPortMutex
);
1245 /* Dereference the thread */
1246 ObDereferenceObject(LastThread
);
1248 /* Post fake messages */
1249 Status
= DbgkpPostFakeThreadMessages(Process
,
1254 if (!NT_SUCCESS(Status
))
1256 /* Clear the last thread */
1261 /* Dereference the first thread and re-acquire the lock */
1262 ObDereferenceObject(FirstThread
);
1269 /* Acquire the debug object's lock */
1270 ExAcquireFastMutex(&DebugObject
->Mutex
);
1272 /* Check our status here */
1273 if (NT_SUCCESS(Status
))
1275 /* Check if we're disconnected */
1276 if (DebugObject
->DebuggerInactive
)
1279 Process
->DebugPort
= NULL
;
1280 Status
= STATUS_DEBUGGER_INACTIVE
;
1284 /* Set the process flags */
1285 PspSetProcessFlag(Process
,
1286 PSF_NO_DEBUG_INHERIT_BIT
|
1287 PSF_CREATE_REPORTED_BIT
);
1289 /* Reference the debug object */
1290 ObReferenceObject(DebugObject
);
1294 /* Loop the events list */
1295 NextEntry
= DebugObject
->EventList
.Flink
;
1296 while (NextEntry
!= &DebugObject
->EventList
)
1298 /* Get the debug event and go to the next entry */
1299 DebugEvent
= CONTAINING_RECORD(NextEntry
, DEBUG_EVENT
, EventList
);
1300 NextEntry
= NextEntry
->Flink
;
1301 DBGKTRACE(DBGK_PROCESS_DEBUG
, "DebugEvent: %p Flags: %lx TH: %p/%p\n",
1302 DebugEvent
, DebugEvent
->Flags
,
1303 DebugEvent
->BackoutThread
, PsGetCurrentThread());
1305 /* Check for if the debug event queue needs flushing */
1306 if ((DebugEvent
->Flags
& DEBUG_EVENT_INACTIVE
) &&
1307 (DebugEvent
->BackoutThread
== PsGetCurrentThread()))
1309 /* Get the event's thread */
1310 EventThread
= DebugEvent
->Thread
;
1311 DBGKTRACE(DBGK_PROCESS_DEBUG
, "EventThread: %p MsgStatus: %lx\n",
1312 EventThread
, MsgStatus
);
1314 /* Check if the status is success */
1315 if ((MsgStatus
== STATUS_SUCCESS
) &&
1316 (EventThread
->GrantedAccess
) &&
1317 (!EventThread
->SystemThread
))
1319 /* Check if we couldn't acquire rundown for it */
1320 if (DebugEvent
->Flags
& DEBUG_EVENT_PROTECT_FAILED
)
1322 /* Set the skip termination flag */
1323 PspSetCrossThreadFlag(EventThread
, CT_SKIP_CREATION_MSG_BIT
);
1325 /* Insert it into the temp list */
1326 RemoveEntryList(&DebugEvent
->EventList
);
1327 InsertTailList(&TempList
, &DebugEvent
->EventList
);
1331 /* Do we need to signal the event */
1335 DebugEvent
->Flags
&= ~DEBUG_EVENT_INACTIVE
;
1336 KeSetEvent(&DebugObject
->EventsPresent
,
1342 /* Clear the backout thread */
1343 DebugEvent
->BackoutThread
= NULL
;
1346 PspSetCrossThreadFlag(EventThread
, CT_SKIP_CREATION_MSG_BIT
);
1351 /* Insert it into the temp list */
1352 RemoveEntryList(&DebugEvent
->EventList
);
1353 InsertTailList(&TempList
, &DebugEvent
->EventList
);
1356 /* Check if the lock is held */
1357 if (DebugEvent
->Flags
& DEBUG_EVENT_RELEASE
)
1360 DebugEvent
->Flags
&= ~DEBUG_EVENT_RELEASE
;
1361 ExReleaseRundownProtection(&EventThread
->RundownProtect
);
1366 /* Release the debug object */
1367 ExReleaseFastMutex(&DebugObject
->Mutex
);
1369 /* Release the global lock if acquired */
1370 if (GlobalHeld
) ExReleaseFastMutex(&DbgkpProcessDebugPortMutex
);
1372 /* Check if there's a thread to dereference */
1373 if (LastThread
) ObDereferenceObject(LastThread
);
1375 /* Loop our temporary list */
1376 while (!IsListEmpty(&TempList
))
1378 /* Remove the event */
1379 NextEntry
= RemoveHeadList(&TempList
);
1380 DebugEvent
= CONTAINING_RECORD(NextEntry
, DEBUG_EVENT
, EventList
);
1383 DbgkpWakeTarget(DebugEvent
);
1386 /* Check if we got here through success and mark the PEB, then return */
1387 if (NT_SUCCESS(Status
)) DbgkpMarkProcessPeb(Process
);
1393 DbgkClearProcessDebugObject(IN PEPROCESS Process
,
1394 IN PDEBUG_OBJECT SourceDebugObject OPTIONAL
)
1396 PDEBUG_OBJECT DebugObject
;
1397 PDEBUG_EVENT DebugEvent
;
1398 LIST_ENTRY TempList
;
1399 PLIST_ENTRY NextEntry
;
1401 DBGKTRACE(DBGK_OBJECT_DEBUG
, "Process: %p DebugObject: %p\n",
1402 Process
, SourceDebugObject
);
1404 /* Acquire the port lock */
1405 ExAcquireFastMutex(&DbgkpProcessDebugPortMutex
);
1407 /* Get the Process Debug Object */
1408 DebugObject
= Process
->DebugPort
;
1411 * Check if the process had an object and it matches,
1412 * or if the process had an object but none was specified
1413 * (in which we are called from NtTerminateProcess)
1415 if ((DebugObject
) &&
1416 ((DebugObject
== SourceDebugObject
) ||
1417 (SourceDebugObject
== NULL
)))
1419 /* Clear the debug port */
1420 Process
->DebugPort
= NULL
;
1422 /* Release the port lock and remove the PEB flag */
1423 ExReleaseFastMutex(&DbgkpProcessDebugPortMutex
);
1424 DbgkpMarkProcessPeb(Process
);
1428 /* Release the port lock and fail */
1429 ExReleaseFastMutex(&DbgkpProcessDebugPortMutex
);
1430 return STATUS_PORT_NOT_SET
;
1433 /* Initialize the temporary list */
1434 InitializeListHead(&TempList
);
1436 /* Acquire the Object */
1437 ExAcquireFastMutex(&DebugObject
->Mutex
);
1439 /* Loop the events */
1440 NextEntry
= DebugObject
->EventList
.Flink
;
1441 while (NextEntry
!= &DebugObject
->EventList
)
1443 /* Get the Event and go to the next entry */
1444 DebugEvent
= CONTAINING_RECORD(NextEntry
, DEBUG_EVENT
, EventList
);
1445 NextEntry
= NextEntry
->Flink
;
1447 /* Check that it belongs to the specified process */
1448 if (DebugEvent
->Process
== Process
)
1450 /* Insert it into the temporary list */
1451 RemoveEntryList(&DebugEvent
->EventList
);
1452 InsertTailList(&TempList
, &DebugEvent
->EventList
);
1456 /* Release the Object */
1457 ExReleaseFastMutex(&DebugObject
->Mutex
);
1459 /* Release the initial reference */
1460 ObDereferenceObject(DebugObject
);
1462 /* Loop our temporary list */
1463 while (!IsListEmpty(&TempList
))
1465 /* Remove the event */
1466 NextEntry
= RemoveHeadList(&TempList
);
1467 DebugEvent
= CONTAINING_RECORD(NextEntry
, DEBUG_EVENT
, EventList
);
1470 DebugEvent
->Status
= STATUS_DEBUGGER_INACTIVE
;
1471 DbgkpWakeTarget(DebugEvent
);
1474 /* Return Success */
1475 return STATUS_SUCCESS
;
1481 DbgkInitialize(VOID
)
1483 OBJECT_TYPE_INITIALIZER ObjectTypeInitializer
;
1484 UNICODE_STRING Name
;
1487 /* Initialize the process debug port mutex */
1488 ExInitializeFastMutex(&DbgkpProcessDebugPortMutex
);
1490 /* Create the Debug Object Type */
1491 RtlZeroMemory(&ObjectTypeInitializer
, sizeof(ObjectTypeInitializer
));
1492 RtlInitUnicodeString(&Name
, L
"DebugObject");
1493 ObjectTypeInitializer
.Length
= sizeof(ObjectTypeInitializer
);
1494 ObjectTypeInitializer
.DefaultNonPagedPoolCharge
= sizeof(DEBUG_OBJECT
);
1495 ObjectTypeInitializer
.GenericMapping
= DbgkDebugObjectMapping
;
1496 ObjectTypeInitializer
.PoolType
= NonPagedPool
;
1497 ObjectTypeInitializer
.ValidAccessMask
= DEBUG_OBJECT_ALL_ACCESS
;
1498 ObjectTypeInitializer
.UseDefaultObject
= TRUE
;
1499 ObjectTypeInitializer
.CloseProcedure
= DbgkpCloseObject
;
1500 ObjectTypeInitializer
.DeleteProcedure
= DbgkpDeleteObject
;
1501 ObCreateObjectType(&Name
,
1502 &ObjectTypeInitializer
,
1504 &DbgkDebugObjectType
);
1507 /* PUBLIC FUNCTIONS **********************************************************/
1514 NtCreateDebugObject(OUT PHANDLE DebugHandle
,
1515 IN ACCESS_MASK DesiredAccess
,
1516 IN POBJECT_ATTRIBUTES ObjectAttributes
,
1519 KPROCESSOR_MODE PreviousMode
= ExGetPreviousMode();
1520 PDEBUG_OBJECT DebugObject
;
1525 /* Check if we were called from user mode*/
1526 if (PreviousMode
!= KernelMode
)
1528 /* Enter SEH for probing */
1531 /* Probe the handle */
1532 ProbeForWriteHandle(DebugHandle
);
1534 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
1536 /* Return the exception code */
1537 _SEH2_YIELD(return _SEH2_GetExceptionCode());
1541 /* Check for invalid flags */
1542 if (Flags
& ~DBGK_ALL_FLAGS
) return STATUS_INVALID_PARAMETER
;
1544 /* Create the Object */
1545 Status
= ObCreateObject(PreviousMode
,
1546 DbgkDebugObjectType
,
1550 sizeof(DEBUG_OBJECT
),
1553 (PVOID
*)&DebugObject
);
1554 if (NT_SUCCESS(Status
))
1556 /* Initialize the Debug Object's Fast Mutex */
1557 ExInitializeFastMutex(&DebugObject
->Mutex
);
1559 /* Initialize the State Event List */
1560 InitializeListHead(&DebugObject
->EventList
);
1562 /* Initialize the Debug Object's Wait Event */
1563 KeInitializeEvent(&DebugObject
->EventsPresent
,
1568 DebugObject
->Flags
= 0;
1569 if (Flags
& DBGK_KILL_PROCESS_ON_EXIT
)
1571 DebugObject
->KillProcessOnExit
= TRUE
;
1575 Status
= ObInsertObject((PVOID
)DebugObject
,
1581 if (NT_SUCCESS(Status
))
1583 /* Enter SEH to protect the write */
1586 /* Return the handle */
1587 *DebugHandle
= hDebug
;
1589 _SEH2_EXCEPT(ExSystemExceptionFilter())
1591 /* Get the exception code */
1592 Status
= _SEH2_GetExceptionCode();
1598 DBGKTRACE(DBGK_OBJECT_DEBUG
, "Handle: %p DebugObject: %p\n",
1599 hDebug
, DebugObject
);
1608 NtDebugContinue(IN HANDLE DebugHandle
,
1609 IN PCLIENT_ID AppClientId
,
1610 IN NTSTATUS ContinueStatus
)
1612 KPROCESSOR_MODE PreviousMode
= ExGetPreviousMode();
1613 PDEBUG_OBJECT DebugObject
;
1615 PDEBUG_EVENT DebugEvent
= NULL
, DebugEventToWake
= NULL
;
1616 PLIST_ENTRY ListHead
, NextEntry
;
1617 BOOLEAN NeedsWake
= FALSE
;
1620 DBGKTRACE(DBGK_OBJECT_DEBUG
, "Handle: %p Status: %p\n",
1621 DebugHandle
, ContinueStatus
);
1623 /* Check if we were called from user mode*/
1624 if (PreviousMode
!= KernelMode
)
1626 /* Enter SEH for probing */
1629 /* Probe the handle */
1630 ProbeForRead(AppClientId
, sizeof(CLIENT_ID
), sizeof(ULONG
));
1631 ClientId
= *AppClientId
;
1632 AppClientId
= &ClientId
;
1634 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
1636 /* Return the exception code */
1637 _SEH2_YIELD(return _SEH2_GetExceptionCode());
1641 /* Make sure that the status is valid */
1642 if ((ContinueStatus
!= DBG_CONTINUE
) &&
1643 (ContinueStatus
!= DBG_EXCEPTION_HANDLED
) &&
1644 (ContinueStatus
!= DBG_EXCEPTION_NOT_HANDLED
) &&
1645 (ContinueStatus
!= DBG_TERMINATE_THREAD
) &&
1646 (ContinueStatus
!= DBG_TERMINATE_PROCESS
))
1648 /* Invalid status */
1649 Status
= STATUS_INVALID_PARAMETER
;
1653 /* Get the debug object */
1654 Status
= ObReferenceObjectByHandle(DebugHandle
,
1655 DEBUG_OBJECT_WAIT_STATE_CHANGE
,
1656 DbgkDebugObjectType
,
1658 (PVOID
*)&DebugObject
,
1660 if (NT_SUCCESS(Status
))
1662 /* Acquire the mutex */
1663 ExAcquireFastMutex(&DebugObject
->Mutex
);
1665 /* Loop the state list */
1666 ListHead
= &DebugObject
->EventList
;
1667 NextEntry
= ListHead
->Flink
;
1668 while (ListHead
!= NextEntry
)
1670 /* Get the current debug event */
1671 DebugEvent
= CONTAINING_RECORD(NextEntry
,
1675 /* Compare process ID */
1676 if (DebugEvent
->ClientId
.UniqueProcess
==
1677 AppClientId
->UniqueProcess
)
1679 /* Check if we already found a match */
1682 /* Wake it up and break out */
1683 DebugEvent
->Flags
&= ~DEBUG_EVENT_INACTIVE
;
1684 KeSetEvent(&DebugObject
->EventsPresent
,
1690 /* Compare thread ID and flag */
1691 if ((DebugEvent
->ClientId
.UniqueThread
==
1692 AppClientId
->UniqueThread
) && (DebugEvent
->Flags
& DEBUG_EVENT_READ
))
1694 /* Remove the event from the list */
1695 RemoveEntryList(NextEntry
);
1697 /* Remember who to wake */
1699 DebugEventToWake
= DebugEvent
;
1703 /* Go to the next entry */
1704 NextEntry
= NextEntry
->Flink
;
1707 /* Release the mutex */
1708 ExReleaseFastMutex(&DebugObject
->Mutex
);
1710 /* Dereference the object */
1711 ObDereferenceObject(DebugObject
);
1713 /* Check if need a wait */
1716 /* Set the continue status */
1717 DebugEventToWake
->ApiMsg
.ReturnedStatus
= ContinueStatus
;
1718 DebugEventToWake
->Status
= STATUS_SUCCESS
;
1720 /* Wake the target */
1721 DbgkpWakeTarget(DebugEventToWake
);
1726 Status
= STATUS_INVALID_PARAMETER
;
1740 NtDebugActiveProcess(IN HANDLE ProcessHandle
,
1741 IN HANDLE DebugHandle
)
1744 PDEBUG_OBJECT DebugObject
;
1745 KPROCESSOR_MODE PreviousMode
= ExGetPreviousMode();
1746 PETHREAD LastThread
;
1749 DBGKTRACE(DBGK_PROCESS_DEBUG
, "Process: %p Handle: %p\n",
1750 ProcessHandle
, DebugHandle
);
1752 /* Reference the process */
1753 Status
= ObReferenceObjectByHandle(ProcessHandle
,
1754 PROCESS_SUSPEND_RESUME
,
1759 if (!NT_SUCCESS(Status
)) return Status
;
1761 /* Don't allow debugging the current process or the system process */
1762 if ((Process
== PsGetCurrentProcess()) ||
1763 (Process
== PsInitialSystemProcess
))
1765 /* Dereference and fail */
1766 ObDereferenceObject(Process
);
1767 return STATUS_ACCESS_DENIED
;
1770 /* Reference the debug object */
1771 Status
= ObReferenceObjectByHandle(DebugHandle
,
1772 DEBUG_OBJECT_ADD_REMOVE_PROCESS
,
1773 DbgkDebugObjectType
,
1775 (PVOID
*)&DebugObject
,
1777 if (!NT_SUCCESS(Status
))
1779 /* Dereference the process and exit */
1780 ObDereferenceObject(Process
);
1784 /* Acquire process rundown protection */
1785 if (!ExAcquireRundownProtection(&Process
->RundownProtect
))
1787 /* Dereference the process and debug object and exit */
1788 ObDereferenceObject(Process
);
1789 ObDereferenceObject(DebugObject
);
1790 return STATUS_PROCESS_IS_TERMINATING
;
1793 /* Send fake create messages for debuggers to have a consistent state */
1794 Status
= DbgkpPostFakeProcessCreateMessages(Process
,
1797 Status
= DbgkpSetProcessDebugObject(Process
,
1802 /* Release rundown protection */
1803 ExReleaseRundownProtection(&Process
->RundownProtect
);
1805 /* Dereference the process and debug object and return status */
1806 ObDereferenceObject(Process
);
1807 ObDereferenceObject(DebugObject
);
1816 NtRemoveProcessDebug(IN HANDLE ProcessHandle
,
1817 IN HANDLE DebugHandle
)
1820 PDEBUG_OBJECT DebugObject
;
1821 KPROCESSOR_MODE PreviousMode
= ExGetPreviousMode();
1824 DBGKTRACE(DBGK_PROCESS_DEBUG
, "Process: %p Handle: %p\n",
1825 ProcessHandle
, DebugHandle
);
1827 /* Reference the process */
1828 Status
= ObReferenceObjectByHandle(ProcessHandle
,
1829 PROCESS_SUSPEND_RESUME
,
1834 if (!NT_SUCCESS(Status
)) return Status
;
1836 /* Reference the debug object */
1837 Status
= ObReferenceObjectByHandle(DebugHandle
,
1838 DEBUG_OBJECT_ADD_REMOVE_PROCESS
,
1839 DbgkDebugObjectType
,
1841 (PVOID
*)&DebugObject
,
1843 if (!NT_SUCCESS(Status
))
1845 /* Dereference the process and exit */
1846 ObDereferenceObject(Process
);
1850 /* Remove the debug object */
1851 Status
= DbgkClearProcessDebugObject(Process
, DebugObject
);
1853 /* Dereference the process and debug object and return status */
1854 ObDereferenceObject(Process
);
1855 ObDereferenceObject(DebugObject
);
1864 NtSetInformationDebugObject(IN HANDLE DebugHandle
,
1865 IN DEBUGOBJECTINFOCLASS DebugObjectInformationClass
,
1866 IN PVOID DebugInformation
,
1867 IN ULONG DebugInformationLength
,
1868 OUT PULONG ReturnLength OPTIONAL
)
1870 PDEBUG_OBJECT DebugObject
;
1871 KPROCESSOR_MODE PreviousMode
= ExGetPreviousMode();
1873 PDEBUG_OBJECT_KILL_PROCESS_ON_EXIT_INFORMATION DebugInfo
= DebugInformation
;
1876 /* Check buffers and parameters */
1877 Status
= DefaultSetInfoBufferCheck(DebugObjectInformationClass
,
1878 DbgkpDebugObjectInfoClass
,
1879 sizeof(DbgkpDebugObjectInfoClass
) /
1880 sizeof(DbgkpDebugObjectInfoClass
[0]),
1882 DebugInformationLength
,
1884 if (!NT_SUCCESS(Status
)) return Status
;
1886 /* Check if the caller wanted the return length */
1889 /* Enter SEH for probe */
1892 /* Return required length to user-mode */
1893 ProbeForWriteUlong(ReturnLength
);
1894 *ReturnLength
= sizeof(*DebugInfo
);
1896 _SEH2_EXCEPT(ExSystemExceptionFilter())
1898 /* Return the exception code */
1899 _SEH2_YIELD(return _SEH2_GetExceptionCode());
1904 /* Open the Object */
1905 Status
= ObReferenceObjectByHandle(DebugHandle
,
1906 DEBUG_OBJECT_WAIT_STATE_CHANGE
,
1907 DbgkDebugObjectType
,
1909 (PVOID
*)&DebugObject
,
1911 if (NT_SUCCESS(Status
))
1913 /* Acquire the object */
1914 ExAcquireFastMutex(&DebugObject
->Mutex
);
1916 /* Set the proper flag */
1917 if (DebugInfo
->KillProcessOnExit
)
1919 /* Enable killing the process */
1920 DebugObject
->KillProcessOnExit
= TRUE
;
1925 DebugObject
->KillProcessOnExit
= FALSE
;
1928 /* Release the mutex */
1929 ExReleaseFastMutex(&DebugObject
->Mutex
);
1931 /* Release the Object */
1932 ObDereferenceObject(DebugObject
);
1944 NtWaitForDebugEvent(IN HANDLE DebugHandle
,
1945 IN BOOLEAN Alertable
,
1946 IN PLARGE_INTEGER Timeout OPTIONAL
,
1947 OUT PDBGUI_WAIT_STATE_CHANGE StateChange
)
1949 KPROCESSOR_MODE PreviousMode
= ExGetPreviousMode();
1950 LARGE_INTEGER LocalTimeOut
;
1952 LARGE_INTEGER StartTime
;
1955 LARGE_INTEGER NewTime
;
1956 PDEBUG_OBJECT DebugObject
;
1957 DBGUI_WAIT_STATE_CHANGE WaitStateChange
;
1959 PDEBUG_EVENT DebugEvent
= NULL
, DebugEvent2
;
1960 PLIST_ENTRY ListHead
, NextEntry
, NextEntry2
;
1962 DBGKTRACE(DBGK_OBJECT_DEBUG
, "Handle: %p\n", DebugHandle
);
1964 /* Clear the initial wait state change structure and the timeout */
1965 RtlZeroMemory(&WaitStateChange
, sizeof(WaitStateChange
));
1966 LocalTimeOut
.QuadPart
= 0;
1968 /* Check if we were called from user mode */
1969 if (PreviousMode
!= KernelMode
)
1971 /* Protect probe in SEH */
1974 /* Check if we came with a timeout */
1978 ProbeForReadLargeInteger(Timeout
);
1980 /* Make a local copy */
1981 LocalTimeOut
= *Timeout
;
1982 Timeout
= &LocalTimeOut
;
1985 /* Probe the state change structure */
1986 ProbeForWrite(StateChange
, sizeof(*StateChange
), sizeof(ULONG
));
1988 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
1990 /* Return the exception code */
1991 _SEH2_YIELD(return _SEH2_GetExceptionCode());
1998 if (Timeout
) LocalTimeOut
= *Timeout
;
2001 /* If we were passed a timeout, query the current time */
2002 if (Timeout
) KeQuerySystemTime(&StartTime
);
2004 /* Get the debug object */
2005 Status
= ObReferenceObjectByHandle(DebugHandle
,
2006 DEBUG_OBJECT_WAIT_STATE_CHANGE
,
2007 DbgkDebugObjectType
,
2009 (PVOID
*)&DebugObject
,
2011 if (!NT_SUCCESS(Status
)) return Status
;
2013 /* Clear process and thread */
2017 /* Wait on the debug object given to us */
2020 Status
= KeWaitForSingleObject(&DebugObject
->EventsPresent
,
2025 if (!NT_SUCCESS(Status
) ||
2026 (Status
== STATUS_TIMEOUT
) ||
2027 (Status
== STATUS_ALERTED
) ||
2028 (Status
== STATUS_USER_APC
))
2030 /* Break out the wait */
2034 /* Lock the object */
2036 ExAcquireFastMutex(&DebugObject
->Mutex
);
2038 /* Check if a debugger is connected */
2039 if (DebugObject
->DebuggerInactive
)
2042 Status
= STATUS_DEBUGGER_INACTIVE
;
2046 /* Loop the events */
2047 ListHead
= &DebugObject
->EventList
;
2048 NextEntry
= ListHead
->Flink
;
2049 while (ListHead
!= NextEntry
)
2051 /* Get the debug event */
2052 DebugEvent
= CONTAINING_RECORD(NextEntry
,
2055 DBGKTRACE(DBGK_PROCESS_DEBUG
, "DebugEvent: %p Flags: %lx\n",
2056 DebugEvent
, DebugEvent
->Flags
);
2059 if (!(DebugEvent
->Flags
& (DEBUG_EVENT_INACTIVE
| DEBUG_EVENT_READ
)))
2061 /* We got an event */
2064 /* Loop the list internally */
2065 NextEntry2
= DebugObject
->EventList
.Flink
;
2066 while (NextEntry2
!= NextEntry
)
2068 /* Get the debug event */
2069 DebugEvent2
= CONTAINING_RECORD(NextEntry2
,
2073 /* Try to match process IDs */
2074 if (DebugEvent2
->ClientId
.UniqueProcess
==
2075 DebugEvent
->ClientId
.UniqueProcess
)
2077 /* Found it, break out */
2078 DebugEvent
->Flags
|= DEBUG_EVENT_INACTIVE
;
2079 DebugEvent
->BackoutThread
= NULL
;
2084 /* Move to the next entry */
2085 NextEntry2
= NextEntry2
->Flink
;
2088 /* Check if we still have a valid event */
2089 if (GotEvent
) break;
2092 /* Move to the next entry */
2093 NextEntry
= NextEntry
->Flink
;
2096 /* Check if we have an event */
2099 /* Save and reference the process and thread */
2100 Process
= DebugEvent
->Process
;
2101 Thread
= DebugEvent
->Thread
;
2102 ObReferenceObject(Process
);
2103 ObReferenceObject(Thread
);
2105 /* Convert to user-mode structure */
2106 DbgkpConvertKernelToUserStateChange(&WaitStateChange
,
2110 DebugEvent
->Flags
|= DEBUG_EVENT_READ
;
2114 /* Unsignal the event */
2115 KeClearEvent(&DebugObject
->EventsPresent
);
2119 Status
= STATUS_SUCCESS
;
2122 /* Release the mutex */
2123 ExReleaseFastMutex(&DebugObject
->Mutex
);
2124 if (!NT_SUCCESS(Status
)) break;
2126 /* Check if we got an event */
2129 /* Check if we can wait again */
2130 if (LocalTimeOut
.QuadPart
< 0)
2132 /* Query the new time */
2133 KeQuerySystemTime(&NewTime
);
2135 /* Substract times */
2136 LocalTimeOut
.QuadPart
+= (NewTime
.QuadPart
- StartTime
.QuadPart
);
2137 StartTime
= NewTime
;
2139 /* Check if we've timed out */
2140 if (LocalTimeOut
.QuadPart
>= 0)
2142 /* We have, break out of the loop */
2143 Status
= STATUS_TIMEOUT
;
2150 /* Open the handles and dereference the objects */
2151 DbgkpOpenHandles(&WaitStateChange
, Process
, Thread
);
2152 ObDereferenceObject(Process
);
2153 ObDereferenceObject(Thread
);
2158 /* We're done, dereference the object */
2159 ObDereferenceObject(DebugObject
);
2161 /* Protect write with SEH */
2164 /* Return our wait state change structure */
2165 *StateChange
= WaitStateChange
;
2167 _SEH2_EXCEPT(ExSystemExceptionFilter())
2169 /* Get SEH Exception code */
2170 Status
= _SEH2_GetExceptionCode();