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
,
62 TAG('D', 'b', 'g', 'E'));
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 PsGetCurrentProcess()->CreateReported
= TRUE
;
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 PsGetCurrentProcess()->CreateReported
= TRUE
;
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
= LPC_DEBUG_EVENT
;
335 ApiMessage
.ApiNumber
= DbgKmExceptionApi
;
337 /* Check if this is to be sent on the debug port */
340 /* Use the debug port, unless the thread is being hidden */
341 Port
= PsGetCurrentThread()->HideFromDebugger
?
342 NULL
: Process
->DebugPort
;
346 /* Otherwise, use the exception port */
347 Port
= Process
->ExceptionPort
;
348 ApiMessage
.h
.u2
.ZeroInit
= LPC_EXCEPTION
;
352 /* Break out if there's no port */
353 if (!Port
) return FALSE
;
355 /* Fill out the exception information */
356 DbgKmException
->ExceptionRecord
= *ExceptionRecord
;
357 DbgKmException
->FirstChance
= !SecondChance
;
359 /* Check if we should use LPC */
362 /* Send the message on the LPC Port */
363 Status
= DbgkpSendApiMessageLpc(&ApiMessage
, Port
, DebugPort
);
367 /* Use native debug object */
368 Status
= DbgkpSendApiMessage(&ApiMessage
, DebugPort
);
371 /* Check if we failed, and for a debug port, also check the return status */
372 if (!(NT_SUCCESS(Status
)) ||
374 (!(NT_SUCCESS(ApiMessage
.ReturnedStatus
)) ||
375 (ApiMessage
.ReturnedStatus
== DBG_EXCEPTION_NOT_HANDLED
))))
381 /* Otherwise, we're ok */
387 DbgkpFreeDebugEvent(IN PDEBUG_EVENT DebugEvent
)
389 PHANDLE Handle
= NULL
;
391 DBGKTRACE(DBGK_OBJECT_DEBUG
, "DebugEvent: %p\n", DebugEvent
);
393 /* Check if this event had a file handle */
394 switch (DebugEvent
->ApiMsg
.ApiNumber
)
396 /* Create process has a handle */
397 case DbgKmCreateProcessApi
:
399 /* Get the pointer */
400 Handle
= &DebugEvent
->ApiMsg
.CreateProcess
.FileHandle
;
403 /* As does DLL load */
404 case DbgKmLoadDllApi
:
406 /* Get the pointer */
407 Handle
= &DebugEvent
->ApiMsg
.LoadDll
.FileHandle
;
413 /* Close the handle if it exsts */
414 if ((Handle
) && (*Handle
)) ObCloseHandle(*Handle
, KernelMode
);
416 /* Dereference process and thread and free the event */
417 ObDereferenceObject(DebugEvent
->Process
);
418 ObDereferenceObject(DebugEvent
->Thread
);
419 ExFreePool(DebugEvent
);
424 DbgkpWakeTarget(IN PDEBUG_EVENT DebugEvent
)
426 PETHREAD Thread
= DebugEvent
->Thread
;
428 DBGKTRACE(DBGK_OBJECT_DEBUG
, "DebugEvent: %p\n", DebugEvent
);
430 /* Check if we have to wake the thread */
431 if (DebugEvent
->Flags
& DEBUG_EVENT_SUSPEND
) PsResumeThread(Thread
, NULL
);
433 /* Check if we had locked the thread */
434 if (DebugEvent
->Flags
& DEBUG_EVENT_RELEASE
)
437 ExReleaseRundownProtection(&Thread
->RundownProtect
);
440 /* Check if we have to wake up the event */
441 if (DebugEvent
->Flags
& DEBUG_EVENT_NOWAIT
)
443 /* Otherwise, free the debug event */
444 DbgkpFreeDebugEvent(DebugEvent
);
448 /* Signal the continue event */
449 KeSetEvent(&DebugEvent
->ContinueEvent
, IO_NO_INCREMENT
, FALSE
);
455 DbgkpPostFakeModuleMessages(IN PEPROCESS Process
,
457 IN PDEBUG_OBJECT DebugObject
)
459 PPEB Peb
= Process
->Peb
;
460 PPEB_LDR_DATA LdrData
;
461 PLDR_DATA_TABLE_ENTRY LdrEntry
;
462 PLIST_ENTRY ListHead
, NextEntry
;
463 DBGKM_MSG ApiMessage
;
464 PDBGKM_LOAD_DLL LoadDll
= &ApiMessage
.LoadDll
;
466 PIMAGE_NT_HEADERS NtHeader
;
467 UNICODE_STRING ModuleName
;
468 OBJECT_ATTRIBUTES ObjectAttributes
;
469 IO_STATUS_BLOCK IoStatusBlock
;
472 DBGKTRACE(DBGK_PROCESS_DEBUG
, "Process: %p Thread: %p DebugObject: %p\n",
473 Process
, Thread
, DebugObject
);
475 /* Quit if there's no PEB */
476 if (!Peb
) return STATUS_SUCCESS
;
478 /* Get the Loader Data List */
480 ListHead
= &LdrData
->InLoadOrderModuleList
;
481 NextEntry
= ListHead
->Flink
;
483 /* Loop the modules */
485 while ((NextEntry
!= ListHead
) && (i
< 500))
487 /* Skip the first entry */
490 /* Go to the next module */
491 NextEntry
= NextEntry
->Flink
;
497 LdrEntry
= CONTAINING_RECORD(NextEntry
,
498 LDR_DATA_TABLE_ENTRY
,
501 /* Setup the API Message */
502 RtlZeroMemory(&ApiMessage
, sizeof(DBGKM_MSG
));
503 ApiMessage
.ApiNumber
= DbgKmLoadDllApi
;
505 /* Set base and clear the name */
506 LoadDll
->BaseOfDll
= LdrEntry
->DllBase
;
507 LoadDll
->NamePointer
= NULL
;
509 /* Get the NT Headers */
510 NtHeader
= RtlImageNtHeader(LoadDll
->BaseOfDll
);
513 /* Save debug data */
514 LoadDll
->DebugInfoFileOffset
= NtHeader
->FileHeader
.
515 PointerToSymbolTable
;
516 LoadDll
->DebugInfoSize
= NtHeader
->FileHeader
.NumberOfSymbols
;
520 DBGKTRACE(DBGK_PROCESS_DEBUG
, "Name: %wZ. Base: %p\n",
521 &LdrEntry
->FullDllName
, LdrEntry
->DllBase
);
523 /* Get the name of the DLL */
524 Status
= MmGetFileNameForAddress(NtHeader
, &ModuleName
);
525 if (NT_SUCCESS(Status
))
527 /* Setup the object attributes */
528 InitializeObjectAttributes(&ObjectAttributes
,
530 OBJ_FORCE_ACCESS_CHECK
|
532 OBJ_CASE_INSENSITIVE
,
536 /* Open the file to get a handle to it */
537 Status
= ZwOpenFile(&LoadDll
->FileHandle
,
538 GENERIC_READ
| SYNCHRONIZE
,
544 FILE_SYNCHRONOUS_IO_NONALERT
);
545 if (!NT_SUCCESS(Status
)) LoadDll
->FileHandle
= NULL
;
547 /* Free the name now */
548 ExFreePool(ModuleName
.Buffer
);
551 /* Send the fake module load message */
552 Status
= DbgkpQueueMessage(Process
,
557 if (!NT_SUCCESS(Status
))
559 /* Message send failed, close the file handle if we had one */
560 if (LoadDll
->FileHandle
) ObCloseHandle(LoadDll
->FileHandle
,
564 /* Go to the next module */
565 NextEntry
= NextEntry
->Flink
;
570 return STATUS_SUCCESS
;
575 DbgkpPostFakeThreadMessages(IN PEPROCESS Process
,
576 IN PDEBUG_OBJECT DebugObject
,
577 IN PETHREAD StartThread
,
578 OUT PETHREAD
*FirstThread
,
579 OUT PETHREAD
*LastThread
)
581 PETHREAD pFirstThread
= NULL
, ThisThread
, OldThread
= NULL
, pLastThread
;
582 NTSTATUS Status
= STATUS_UNSUCCESSFUL
;
583 BOOLEAN IsFirstThread
;
585 DBGKM_MSG ApiMessage
;
586 PDBGKM_CREATE_THREAD CreateThread
= &ApiMessage
.CreateThread
;
587 PDBGKM_CREATE_PROCESS CreateProcess
= &ApiMessage
.CreateProcess
;
589 PIMAGE_NT_HEADERS NtHeader
;
591 DBGKTRACE(DBGK_THREAD_DEBUG
, "Process: %p StartThread: %p Object: %p\n",
592 Process
, StartThread
, DebugObject
);
594 /* Check if we have a start thread */
597 /* Then the one we'll find won't be the first one */
598 IsFirstThread
= FALSE
;
599 pFirstThread
= StartThread
;
600 ThisThread
= StartThread
;
603 ObReferenceObject(StartThread
);
607 /* Get the first thread ourselves */
608 ThisThread
= PsGetNextProcessThread(Process
, NULL
);
609 IsFirstThread
= TRUE
;
612 /* Start thread loop */
615 /* Dereference the previous thread if we had one */
616 if (OldThread
) ObDereferenceObject(OldThread
);
618 /* Set this as the last thread and lock it */
619 pLastThread
= ThisThread
;
620 ObReferenceObject(ThisThread
);
621 if (ExAcquireRundownProtection(&ThisThread
->RundownProtect
))
623 /* Acquire worked, set flags */
624 Flags
= DEBUG_EVENT_RELEASE
| DEBUG_EVENT_NOWAIT
;
626 /* Check if this is a user thread */
627 if (!ThisThread
->SystemThread
)
630 if (NT_SUCCESS(PsSuspendThread(ThisThread
, NULL
)))
633 Flags
|= DEBUG_EVENT_SUSPEND
;
639 /* Couldn't acquire rundown */
640 Flags
= DEBUG_EVENT_PROTECT_FAILED
| DEBUG_EVENT_NOWAIT
;
643 /* Clear the API Message */
644 RtlZeroMemory(&ApiMessage
, sizeof(ApiMessage
));
646 /* Check if this is the first thread */
647 if ((IsFirstThread
) &&
648 !(Flags
& DEBUG_EVENT_PROTECT_FAILED
) &&
649 !(ThisThread
->SystemThread
) &&
650 (ThisThread
->GrantedAccess
))
652 /* It is, save the flag */
657 /* It isn't, save the flag */
661 /* Check if this is the first */
664 /* So we'll start with the create process message */
665 ApiMessage
.ApiNumber
= DbgKmCreateProcessApi
;
667 /* Get the file handle */
668 if (Process
->SectionObject
)
670 /* Use the section object */
671 CreateProcess
->FileHandle
=
672 DbgkpSectionToFileHandle(Process
->SectionObject
);
676 /* Don't return any handle */
677 CreateProcess
->FileHandle
= NULL
;
680 /* Set the base address */
681 CreateProcess
->BaseOfImage
= Process
->SectionBaseAddress
;
683 /* Get the NT Header */
684 NtHeader
= RtlImageNtHeader(Process
->SectionBaseAddress
);
687 /* Fill out data from the header */
688 CreateProcess
->DebugInfoFileOffset
= NtHeader
->FileHeader
.
689 PointerToSymbolTable
;
690 CreateProcess
->DebugInfoSize
= NtHeader
->FileHeader
.
696 /* Otherwise it's a thread message */
697 ApiMessage
.ApiNumber
= DbgKmCreateThreadApi
;
698 CreateThread
->StartAddress
= ThisThread
->StartAddress
;
702 DBGKTRACE(DBGK_THREAD_DEBUG
, "Thread: %p. First: %lx, OldThread: %p\n",
703 ThisThread
, First
, OldThread
);
704 DBGKTRACE(DBGK_THREAD_DEBUG
, "Start Address: %p\n",
705 ThisThread
->StartAddress
);
707 /* Queue the message */
708 Status
= DbgkpQueueMessage(Process
,
713 if (!NT_SUCCESS(Status
))
715 /* We failed. FIXME: Handle this */
716 DPRINT1("Unhandled Dbgk codepath!\n");
720 /* Check if this was the first message */
723 /* It isn't the first thread anymore */
724 IsFirstThread
= FALSE
;
726 /* Reference this thread and set it as first */
727 ObReferenceObject(ThisThread
);
728 pFirstThread
= ThisThread
;
731 /* Get the next thread */
732 ThisThread
= PsGetNextProcessThread(Process
, ThisThread
);
733 OldThread
= pLastThread
;
734 } while (ThisThread
);
736 /* Check the API status */
737 if (!NT_SUCCESS(Status
))
739 /* We failed. FIXME: Handle this */
740 DPRINT1("Unhandled Dbgk codepath!\n");
744 /* Make sure we have a first thread */
745 if (!pFirstThread
) return STATUS_UNSUCCESSFUL
;
747 /* Return thread pointers */
748 *FirstThread
= pFirstThread
;
749 *LastThread
= pLastThread
;
755 DbgkpPostFakeProcessCreateMessages(IN PEPROCESS Process
,
756 IN PDEBUG_OBJECT DebugObject
,
757 OUT PETHREAD
*LastThread
)
760 PETHREAD FirstThread
, FinalThread
;
761 PETHREAD ReturnThread
= NULL
;
764 DBGKTRACE(DBGK_PROCESS_DEBUG
, "Process: %p DebugObject: %p\n",
765 Process
, DebugObject
);
767 /* Attach to the process */
768 KeStackAttachProcess(&Process
->Pcb
, &ApcState
);
770 /* Post the fake thread messages */
771 Status
= DbgkpPostFakeThreadMessages(Process
,
776 if (NT_SUCCESS(Status
))
778 /* Send the fake module messages too */
779 Status
= DbgkpPostFakeModuleMessages(Process
,
782 if (!NT_SUCCESS(Status
))
784 /* We failed, dereference the final thread */
785 ObDereferenceObject(FinalThread
);
789 /* Set the final thread */
790 ReturnThread
= FinalThread
;
793 /* Dereference the first thread */
794 ObDereferenceObject(FirstThread
);
797 /* Detach from the process */
798 KeUnstackDetachProcess(&ApcState
);
800 /* Return the last thread */
801 *LastThread
= ReturnThread
;
807 DbgkpConvertKernelToUserStateChange(IN PDBGUI_WAIT_STATE_CHANGE WaitStateChange
,
808 IN PDEBUG_EVENT DebugEvent
)
810 DBGKTRACE(DBGK_OBJECT_DEBUG
, "DebugEvent: %p\n", DebugEvent
);
812 /* Start by copying the client ID */
813 WaitStateChange
->AppClientId
= DebugEvent
->ClientId
;
815 /* Now check which kind of event this was */
816 switch (DebugEvent
->ApiMsg
.ApiNumber
)
819 case DbgKmCreateProcessApi
:
821 /* Set the right native code */
822 WaitStateChange
->NewState
= DbgCreateProcessStateChange
;
824 /* Copy the information */
825 WaitStateChange
->StateInfo
.CreateProcessInfo
.NewProcess
=
826 DebugEvent
->ApiMsg
.CreateProcess
;
828 /* Clear the file handle for us */
829 DebugEvent
->ApiMsg
.CreateProcess
.FileHandle
= NULL
;
833 case DbgKmCreateThreadApi
:
835 /* Set the right native code */
836 WaitStateChange
->NewState
= DbgCreateThreadStateChange
;
838 /* Copy information */
839 WaitStateChange
->StateInfo
.CreateThread
.NewThread
.StartAddress
=
840 DebugEvent
->ApiMsg
.CreateThread
.StartAddress
;
841 WaitStateChange
->StateInfo
.CreateThread
.NewThread
.SubSystemKey
=
842 DebugEvent
->ApiMsg
.CreateThread
.SubSystemKey
;
845 /* Exception (or breakpoint/step) */
846 case DbgKmExceptionApi
:
848 /* Look at the exception code */
849 if ((NTSTATUS
)DebugEvent
->ApiMsg
.Exception
.ExceptionRecord
.ExceptionCode
==
852 /* Update this as a breakpoint exception */
853 WaitStateChange
->NewState
= DbgBreakpointStateChange
;
855 else if ((NTSTATUS
)DebugEvent
->ApiMsg
.Exception
.ExceptionRecord
.ExceptionCode
==
858 /* Update this as a single step exception */
859 WaitStateChange
->NewState
= DbgSingleStepStateChange
;
863 /* Otherwise, set default exception */
864 WaitStateChange
->NewState
= DbgExceptionStateChange
;
867 /* Copy the exception record */
868 WaitStateChange
->StateInfo
.Exception
.ExceptionRecord
=
869 DebugEvent
->ApiMsg
.Exception
.ExceptionRecord
;
870 /* Copy FirstChance flag */
871 WaitStateChange
->StateInfo
.Exception
.FirstChance
=
872 DebugEvent
->ApiMsg
.Exception
.FirstChance
;
876 case DbgKmExitProcessApi
:
878 /* Set the right native code and copy the exit code */
879 WaitStateChange
->NewState
= DbgExitProcessStateChange
;
880 WaitStateChange
->StateInfo
.ExitProcess
.ExitStatus
=
881 DebugEvent
->ApiMsg
.ExitProcess
.ExitStatus
;
885 case DbgKmExitThreadApi
:
887 /* Set the right native code */
888 WaitStateChange
->NewState
= DbgExitThreadStateChange
;
889 WaitStateChange
->StateInfo
.ExitThread
.ExitStatus
=
890 DebugEvent
->ApiMsg
.ExitThread
.ExitStatus
;
894 case DbgKmLoadDllApi
:
896 /* Set the native code */
897 WaitStateChange
->NewState
= DbgLoadDllStateChange
;
900 WaitStateChange
->StateInfo
.LoadDll
= DebugEvent
->ApiMsg
.LoadDll
;
902 /* Clear the file handle for us */
903 DebugEvent
->ApiMsg
.LoadDll
.FileHandle
= NULL
;
907 case DbgKmUnloadDllApi
:
909 /* Set the native code and copy the address */
910 WaitStateChange
->NewState
= DbgUnloadDllStateChange
;
911 WaitStateChange
->StateInfo
.UnloadDll
.BaseAddress
=
912 DebugEvent
->ApiMsg
.UnloadDll
.BaseAddress
;
917 /* Shouldn't happen */
924 DbgkpMarkProcessPeb(IN PEPROCESS Process
)
928 DBGKTRACE(DBGK_PROCESS_DEBUG
, "Process: %p\n", Process
);
930 /* Acquire process rundown */
931 if (!ExAcquireRundownProtection(&Process
->RundownProtect
)) return;
933 /* Make sure we have a PEB */
936 /* Attach to the process */
937 KeStackAttachProcess(&Process
->Pcb
, &ApcState
);
939 /* Acquire the debug port mutex */
940 ExAcquireFastMutex(&DbgkpProcessDebugPortMutex
);
942 /* Set the IsBeingDebugged member of the PEB */
943 Process
->Peb
->BeingDebugged
= (Process
->DebugPort
) ? TRUE
: FALSE
;
946 ExReleaseFastMutex(&DbgkpProcessDebugPortMutex
);
948 /* Detach from the process */
949 KeUnstackDetachProcess(&ApcState
);
952 /* Release rundown protection */
953 ExReleaseRundownProtection(&Process
->RundownProtect
);
958 DbgkpOpenHandles(IN PDBGUI_WAIT_STATE_CHANGE WaitStateChange
,
959 IN PEPROCESS Process
,
966 DBGKTRACE(DBGK_OBJECT_DEBUG
, "Process: %p Thread: %p State: %lx\n",
967 Process
, Thread
, WaitStateChange
->NewState
);
969 /* Check which state this is */
970 switch (WaitStateChange
->NewState
)
973 case DbgCreateThreadStateChange
:
975 /* Get handle to thread */
976 Status
= ObOpenObjectByPointer(Thread
,
983 if (NT_SUCCESS(Status
))
985 /* Save the thread handle */
987 StateInfo
.CreateThread
.HandleToThread
= Handle
;
992 case DbgCreateProcessStateChange
:
994 /* Get handle to thread */
995 Status
= ObOpenObjectByPointer(Thread
,
1002 if (NT_SUCCESS(Status
))
1004 /* Save the thread handle */
1006 StateInfo
.CreateProcessInfo
.HandleToThread
= Handle
;
1009 /* Get handle to process */
1010 Status
= ObOpenObjectByPointer(Process
,
1017 if (NT_SUCCESS(Status
))
1019 /* Save the process handle */
1021 StateInfo
.CreateProcessInfo
.HandleToProcess
= Handle
;
1024 /* Fall through to duplicate file handle */
1025 DupHandle
= &WaitStateChange
->
1026 StateInfo
.CreateProcessInfo
.NewProcess
.FileHandle
;
1030 case DbgLoadDllStateChange
:
1032 /* Fall through to duplicate file handle */
1033 DupHandle
= &WaitStateChange
->StateInfo
.LoadDll
.FileHandle
;
1036 /* Anything else has no handles */
1041 /* If we got here, then we have to duplicate a handle, possibly */
1042 Handle
= *DupHandle
;
1046 Status
= ObDuplicateObject(PsGetCurrentProcess(),
1048 PsGetCurrentProcess(),
1052 DUPLICATE_SAME_ACCESS
,
1054 if (!NT_SUCCESS(Status
)) *DupHandle
= NULL
;
1056 /* Close the original handle */
1057 ObCloseHandle(Handle
, KernelMode
);
1063 DbgkpDeleteObject(IN PVOID DebugObject
)
1068 ASSERT(IsListEmpty(&((PDEBUG_OBJECT
)DebugObject
)->EventList
));
1073 DbgkpCloseObject(IN PEPROCESS OwnerProcess OPTIONAL
,
1074 IN PVOID ObjectBody
,
1075 IN ACCESS_MASK GrantedAccess
,
1076 IN ULONG HandleCount
,
1077 IN ULONG SystemHandleCount
)
1079 PDEBUG_OBJECT DebugObject
= ObjectBody
;
1080 PEPROCESS Process
= NULL
;
1081 BOOLEAN DebugPortCleared
= FALSE
;
1082 PLIST_ENTRY DebugEventList
;
1083 PDEBUG_EVENT DebugEvent
;
1084 DBGKTRACE(DBGK_OBJECT_DEBUG
, "OwnerProcess: %p DebugObject: %p\n",
1085 OwnerProcess
, DebugObject
);
1087 /* If this isn't the last handle, do nothing */
1088 if (SystemHandleCount
> 1) return;
1090 /* Otherwise, lock the debug object */
1091 ExAcquireFastMutex(&DebugObject
->Mutex
);
1093 /* Set it as inactive */
1094 DebugObject
->DebuggerInactive
= TRUE
;
1096 /* Remove it from the debug event list */
1097 DebugEventList
= DebugObject
->EventList
.Flink
;
1098 InitializeListHead(&DebugObject
->EventList
);
1100 /* Release the lock */
1101 ExReleaseFastMutex(&DebugObject
->Mutex
);
1103 /* Signal the wait event */
1104 KeSetEvent(&DebugObject
->EventsPresent
, IO_NO_INCREMENT
, FALSE
);
1106 /* Start looping each process */
1107 while ((Process
= PsGetNextProcess(Process
)))
1109 /* Check if the process has us as their debug port */
1110 if (Process
->DebugPort
== DebugObject
)
1112 /* Acquire the process debug port lock */
1113 ExAcquireFastMutex(&DbgkpProcessDebugPortMutex
);
1115 /* Check if it's still us */
1116 if (Process
->DebugPort
== DebugObject
)
1118 /* Clear it and remember */
1119 Process
->DebugPort
= NULL
;
1120 DebugPortCleared
= TRUE
;
1123 /* Release the port lock */
1124 ExReleaseFastMutex(&DbgkpProcessDebugPortMutex
);
1126 /* Check if we cleared the debug port */
1127 if (DebugPortCleared
)
1129 /* Mark this in the PEB */
1130 DbgkpMarkProcessPeb(Process
);
1132 /* Check if we terminate on exit */
1133 if (DebugObject
->KillProcessOnExit
)
1135 /* Terminate the process */
1136 PsTerminateProcess(Process
, STATUS_DEBUGGER_INACTIVE
);
1139 /* Dereference the debug object */
1140 ObDereferenceObject(DebugObject
);
1145 /* Loop debug events */
1146 while (DebugEventList
!= &DebugObject
->EventList
)
1148 /* Get the debug event */
1149 DebugEvent
= CONTAINING_RECORD(DebugEventList
, DEBUG_EVENT
, EventList
);
1151 /* Go to the next entry */
1152 DebugEventList
= DebugEventList
->Flink
;
1155 DebugEvent
->Status
= STATUS_DEBUGGER_INACTIVE
;
1156 DbgkpWakeTarget(DebugEvent
);
1162 DbgkpSetProcessDebugObject(IN PEPROCESS Process
,
1163 IN PDEBUG_OBJECT DebugObject
,
1164 IN NTSTATUS MsgStatus
,
1165 IN PETHREAD LastThread
)
1168 LIST_ENTRY TempList
;
1169 BOOLEAN GlobalHeld
= FALSE
, DoSetEvent
= TRUE
;
1170 PETHREAD ThisThread
, FirstThread
;
1171 PLIST_ENTRY NextEntry
;
1172 PDEBUG_EVENT DebugEvent
;
1173 PETHREAD EventThread
;
1175 DBGKTRACE(DBGK_PROCESS_DEBUG
, "Process: %p DebugObject: %p\n",
1176 Process
, DebugObject
);
1178 /* Initialize the temporary list */
1179 InitializeListHead(&TempList
);
1181 /* Check if we have a success message */
1182 if (NT_SUCCESS(MsgStatus
))
1184 /* Then default to STATUS_SUCCESS */
1185 Status
= STATUS_SUCCESS
;
1189 /* No last thread, and set the failure code */
1194 /* Now check what status we have here */
1195 if (NT_SUCCESS(Status
))
1197 /* Acquire the global lock */
1200 ExAcquireFastMutex(&DbgkpProcessDebugPortMutex
);
1202 /* Check if we already have a port */
1203 if (Process
->DebugPort
)
1206 Status
= STATUS_PORT_ALREADY_SET
;
1210 /* Otherwise, set the port and reference the thread */
1211 Process
->DebugPort
= DebugObject
;
1212 ObReferenceObject(LastThread
);
1214 /* Get the next thread */
1215 ThisThread
= PsGetNextProcessThread(Process
, LastThread
);
1218 /* Clear the debug port and release the lock */
1219 Process
->DebugPort
= NULL
;
1220 ExReleaseFastMutex(&DbgkpProcessDebugPortMutex
);
1223 /* Dereference the thread */
1224 ObDereferenceObject(LastThread
);
1226 /* Post fake messages */
1227 Status
= DbgkpPostFakeThreadMessages(Process
,
1232 if (!NT_SUCCESS(Status
))
1234 /* Clear the last thread */
1239 /* Dereference the first thread and re-acquire the lock */
1240 ObDereferenceObject(FirstThread
);
1247 /* Acquire the debug object's lock */
1248 ExAcquireFastMutex(&DebugObject
->Mutex
);
1250 /* Check our status here */
1251 if (NT_SUCCESS(Status
))
1253 /* Check if we're disconnected */
1254 if (DebugObject
->DebuggerInactive
)
1257 Process
->DebugPort
= NULL
;
1258 Status
= STATUS_DEBUGGER_INACTIVE
;
1262 /* Set the process flags */
1263 InterlockedOr((PLONG
)&Process
->Flags
,
1264 PSF_NO_DEBUG_INHERIT_BIT
| PSF_CREATE_REPORTED_BIT
);
1266 /* Reference the debug object */
1267 ObReferenceObject(DebugObject
);
1271 /* Loop the events list */
1272 NextEntry
= DebugObject
->EventList
.Flink
;
1273 while (NextEntry
!= &DebugObject
->EventList
)
1275 /* Get the debug event */
1276 DebugEvent
= CONTAINING_RECORD(NextEntry
, DEBUG_EVENT
, EventList
);
1277 DBGKTRACE(DBGK_PROCESS_DEBUG
, "DebugEvent: %p Flags: %lx TH: %p/%p\n",
1278 DebugEvent
, DebugEvent
->Flags
,
1279 DebugEvent
->BackoutThread
, PsGetCurrentThread());
1281 /* Check for if the debug event queue needs flushing */
1282 if ((DebugEvent
->Flags
& DEBUG_EVENT_INACTIVE
) &&
1283 (DebugEvent
->BackoutThread
== PsGetCurrentThread()))
1285 /* Get the event's thread */
1286 EventThread
= DebugEvent
->Thread
;
1287 DBGKTRACE(DBGK_PROCESS_DEBUG
, "EventThread: %p MsgStatus: %lx\n",
1288 EventThread
, MsgStatus
);
1290 /* Check if the status is success */
1291 if ((MsgStatus
== STATUS_SUCCESS
) &&
1292 (EventThread
->GrantedAccess
) &&
1293 (!EventThread
->SystemThread
))
1295 /* Check if we couldn't acquire rundown for it */
1296 if (DebugEvent
->Flags
& DEBUG_EVENT_PROTECT_FAILED
)
1298 /* Set the skip termination flag */
1299 PspSetCrossThreadFlag(EventThread
, CT_SKIP_CREATION_MSG_BIT
);
1301 /* Insert it into the temp list */
1302 RemoveEntryList(&DebugEvent
->EventList
);
1303 InsertTailList(&TempList
, &DebugEvent
->EventList
);
1307 /* Do we need to signal the event */
1311 DebugEvent
->Flags
&= ~DEBUG_EVENT_INACTIVE
;
1312 KeSetEvent(&DebugObject
->EventsPresent
,
1318 /* Clear the backout thread */
1319 DebugEvent
->BackoutThread
= NULL
;
1322 PspSetCrossThreadFlag(EventThread
, CT_SKIP_CREATION_MSG_BIT
);
1327 /* Insert it into the temp list */
1328 RemoveEntryList(&DebugEvent
->EventList
);
1329 InsertTailList(&TempList
, &DebugEvent
->EventList
);
1332 /* Check if the lock is held */
1333 if (DebugEvent
->Flags
& DEBUG_EVENT_RELEASE
)
1336 DebugEvent
->Flags
&= ~DEBUG_EVENT_RELEASE
;
1337 ExReleaseRundownProtection(&EventThread
->RundownProtect
);
1341 /* Go to the next entry */
1342 NextEntry
= NextEntry
->Flink
;
1345 /* Release the debug object */
1346 ExReleaseFastMutex(&DebugObject
->Mutex
);
1348 /* Release the global lock if acquired */
1349 if (GlobalHeld
) ExReleaseFastMutex(&DbgkpProcessDebugPortMutex
);
1351 /* Check if there's a thread to dereference */
1352 if (LastThread
) ObDereferenceObject(LastThread
);
1354 /* Loop our temporary list */
1355 while (!IsListEmpty(&TempList
))
1357 /* Remove the event */
1358 NextEntry
= RemoveHeadList(&TempList
);
1359 DebugEvent
= CONTAINING_RECORD (NextEntry
, DEBUG_EVENT
, EventList
);
1362 DbgkpWakeTarget(DebugEvent
);
1365 /* Check if we got here through success and mark the PEB, then return */
1366 if (NT_SUCCESS(Status
)) DbgkpMarkProcessPeb(Process
);
1372 DbgkClearProcessDebugObject(IN PEPROCESS Process
,
1373 IN PDEBUG_OBJECT SourceDebugObject
)
1376 DBGKTRACE(DBGK_PROCESS_DEBUG
, "Process: %p DebugObject: %p\n",
1377 Process
, SourceDebugObject
);
1378 return STATUS_UNSUCCESSFUL
;
1384 DbgkInitialize(VOID
)
1386 OBJECT_TYPE_INITIALIZER ObjectTypeInitializer
;
1387 UNICODE_STRING Name
;
1390 /* Initialize the process debug port mutex */
1391 ExInitializeFastMutex(&DbgkpProcessDebugPortMutex
);
1393 /* Create the Debug Object Type */
1394 RtlZeroMemory(&ObjectTypeInitializer
, sizeof(ObjectTypeInitializer
));
1395 RtlInitUnicodeString(&Name
, L
"DebugObject");
1396 ObjectTypeInitializer
.Length
= sizeof(ObjectTypeInitializer
);
1397 ObjectTypeInitializer
.DefaultNonPagedPoolCharge
= sizeof(DEBUG_OBJECT
);
1398 ObjectTypeInitializer
.GenericMapping
= DbgkDebugObjectMapping
;
1399 ObjectTypeInitializer
.PoolType
= NonPagedPool
;
1400 ObjectTypeInitializer
.ValidAccessMask
= DEBUG_OBJECT_ALL_ACCESS
;
1401 ObjectTypeInitializer
.UseDefaultObject
= TRUE
;
1402 ObjectTypeInitializer
.CloseProcedure
= DbgkpCloseObject
;
1403 ObjectTypeInitializer
.DeleteProcedure
= DbgkpDeleteObject
;
1404 ObCreateObjectType(&Name
,
1405 &ObjectTypeInitializer
,
1407 &DbgkDebugObjectType
);
1410 /* PUBLIC FUNCTIONS **********************************************************/
1414 NtCreateDebugObject(OUT PHANDLE DebugHandle
,
1415 IN ACCESS_MASK DesiredAccess
,
1416 IN POBJECT_ATTRIBUTES ObjectAttributes
,
1417 IN BOOLEAN KillProcessOnExit
)
1419 KPROCESSOR_MODE PreviousMode
= ExGetPreviousMode();
1420 PDEBUG_OBJECT DebugObject
;
1422 NTSTATUS Status
= STATUS_SUCCESS
;
1425 /* Check if we were called from user mode*/
1426 if (PreviousMode
!= KernelMode
)
1428 /* Enter SEH for probing */
1431 /* Probe the handle */
1432 ProbeForWriteHandle(DebugHandle
);
1434 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
1436 /* Get exception error */
1437 Status
= _SEH2_GetExceptionCode();
1439 if (!NT_SUCCESS(Status
)) return Status
;
1442 /* Create the Object */
1443 Status
= ObCreateObject(PreviousMode
,
1444 DbgkDebugObjectType
,
1448 sizeof(DEBUG_OBJECT
),
1451 (PVOID
*)&DebugObject
);
1452 if (NT_SUCCESS(Status
))
1454 /* Initialize the Debug Object's Fast Mutex */
1455 ExInitializeFastMutex(&DebugObject
->Mutex
);
1457 /* Initialize the State Event List */
1458 InitializeListHead(&DebugObject
->EventList
);
1460 /* Initialize the Debug Object's Wait Event */
1461 KeInitializeEvent(&DebugObject
->EventsPresent
,
1466 DebugObject
->KillProcessOnExit
= KillProcessOnExit
;
1469 Status
= ObInsertObject((PVOID
)DebugObject
,
1475 if (NT_SUCCESS(Status
))
1479 *DebugHandle
= hDebug
;
1481 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
1483 Status
= _SEH2_GetExceptionCode();
1489 DBGKTRACE(DBGK_OBJECT_DEBUG
, "Handle: %p DebugObject: %p\n",
1490 hDebug
, DebugObject
);
1496 NtDebugContinue(IN HANDLE DebugHandle
,
1497 IN PCLIENT_ID AppClientId
,
1498 IN NTSTATUS ContinueStatus
)
1500 KPROCESSOR_MODE PreviousMode
= ExGetPreviousMode();
1501 PDEBUG_OBJECT DebugObject
;
1502 NTSTATUS Status
= STATUS_SUCCESS
;
1503 PDEBUG_EVENT DebugEvent
= NULL
, DebugEventToWake
= NULL
;
1504 PLIST_ENTRY ListHead
, NextEntry
;
1505 BOOLEAN NeedsWake
= FALSE
;
1508 DBGKTRACE(DBGK_OBJECT_DEBUG
, "Handle: %p Status: %p\n",
1509 DebugHandle
, ContinueStatus
);
1511 /* Check if we were called from user mode*/
1512 if (PreviousMode
!= KernelMode
)
1514 /* Enter SEH for probing */
1517 /* Probe the handle */
1518 ProbeForRead(AppClientId
, sizeof(CLIENT_ID
), sizeof(ULONG
));
1519 ClientId
= *AppClientId
;
1520 AppClientId
= &ClientId
;
1522 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
1524 /* Get exception error */
1525 Status
= _SEH2_GetExceptionCode();
1527 if (!NT_SUCCESS(Status
)) return Status
;
1530 /* Make sure that the status is valid */
1531 if ((ContinueStatus
!= DBG_CONTINUE
) &&
1532 (ContinueStatus
!= DBG_EXCEPTION_HANDLED
) &&
1533 (ContinueStatus
!= DBG_EXCEPTION_NOT_HANDLED
) &&
1534 (ContinueStatus
!= DBG_TERMINATE_THREAD
) &&
1535 (ContinueStatus
!= DBG_TERMINATE_PROCESS
))
1537 /* Invalid status */
1538 Status
= STATUS_INVALID_PARAMETER
;
1542 /* Get the debug object */
1543 Status
= ObReferenceObjectByHandle(DebugHandle
,
1544 DEBUG_OBJECT_WAIT_STATE_CHANGE
,
1545 DbgkDebugObjectType
,
1547 (PVOID
*)&DebugObject
,
1549 if (NT_SUCCESS(Status
))
1551 /* Acquire the mutex */
1552 ExAcquireFastMutex(&DebugObject
->Mutex
);
1554 /* Loop the state list */
1555 ListHead
= &DebugObject
->EventList
;
1556 NextEntry
= ListHead
->Flink
;
1557 while (ListHead
!= NextEntry
)
1559 /* Get the current debug event */
1560 DebugEvent
= CONTAINING_RECORD(NextEntry
,
1564 /* Compare process ID */
1565 if (DebugEvent
->ClientId
.UniqueProcess
==
1566 AppClientId
->UniqueProcess
)
1568 /* Check if we already found a match */
1571 /* Wake it up and break out */
1572 DebugEvent
->Flags
&= ~DEBUG_EVENT_INACTIVE
;
1573 KeSetEvent(&DebugEvent
->ContinueEvent
,
1579 /* Compare thread ID and flag */
1580 if ((DebugEvent
->ClientId
.UniqueThread
==
1581 AppClientId
->UniqueThread
) && (DebugEvent
->Flags
& DEBUG_EVENT_READ
))
1583 /* Remove the event from the list */
1584 RemoveEntryList(NextEntry
);
1586 /* Remember who to wake */
1588 DebugEventToWake
= DebugEvent
;
1592 /* Go to the next entry */
1593 NextEntry
= NextEntry
->Flink
;
1596 /* Release the mutex */
1597 ExReleaseFastMutex(&DebugObject
->Mutex
);
1599 /* Dereference the object */
1600 ObDereferenceObject(DebugObject
);
1602 /* Check if need a wait */
1605 /* Set the continue status */
1606 DebugEvent
->ApiMsg
.ReturnedStatus
= ContinueStatus
;
1607 DebugEvent
->Status
= STATUS_SUCCESS
;
1609 /* Wake the target */
1610 DbgkpWakeTarget(DebugEvent
);
1615 Status
= STATUS_INVALID_PARAMETER
;
1626 NtDebugActiveProcess(IN HANDLE ProcessHandle
,
1627 IN HANDLE DebugHandle
)
1630 PDEBUG_OBJECT DebugObject
;
1631 KPROCESSOR_MODE PreviousMode
= KeGetPreviousMode();
1632 PETHREAD LastThread
;
1635 DBGKTRACE(DBGK_PROCESS_DEBUG
, "Process: %p Handle: %p\n",
1636 ProcessHandle
, DebugHandle
);
1638 /* Reference the process */
1639 Status
= ObReferenceObjectByHandle(ProcessHandle
,
1640 PROCESS_SUSPEND_RESUME
,
1645 if (!NT_SUCCESS(Status
)) return Status
;
1647 /* Don't allow debugging the initial system process */
1648 if (Process
== PsInitialSystemProcess
)
1650 /* Dereference and fail */
1651 ObDereferenceObject(Process
);
1652 return STATUS_ACCESS_DENIED
;
1655 /* Reference the debug object */
1656 Status
= ObReferenceObjectByHandle(DebugHandle
,
1657 DEBUG_OBJECT_ADD_REMOVE_PROCESS
,
1658 DbgkDebugObjectType
,
1660 (PVOID
*)&DebugObject
,
1662 if (!NT_SUCCESS(Status
))
1664 /* Dereference the process and exit */
1665 ObDereferenceObject(Process
);
1669 /* Acquire process rundown protection */
1670 if (!ExAcquireRundownProtection(&Process
->RundownProtect
))
1672 /* Dereference the process and debug object and exit */
1673 ObDereferenceObject(Process
);
1674 ObDereferenceObject(DebugObject
);
1675 return STATUS_PROCESS_IS_TERMINATING
;
1678 /* Send fake create messages for debuggers to have a consistent state */
1679 Status
= DbgkpPostFakeProcessCreateMessages(Process
,
1682 Status
= DbgkpSetProcessDebugObject(Process
,
1687 /* Release rundown protection */
1688 ExReleaseRundownProtection(&Process
->RundownProtect
);
1690 /* Dereference the process and debug object and return status */
1691 ObDereferenceObject(Process
);
1692 ObDereferenceObject(DebugObject
);
1698 NtRemoveProcessDebug(IN HANDLE ProcessHandle
,
1699 IN HANDLE DebugHandle
)
1702 PDEBUG_OBJECT DebugObject
;
1703 KPROCESSOR_MODE PreviousMode
= KeGetPreviousMode();
1706 DBGKTRACE(DBGK_PROCESS_DEBUG
, "Process: %p Handle: %p\n",
1707 ProcessHandle
, DebugHandle
);
1709 /* Reference the process */
1710 Status
= ObReferenceObjectByHandle(ProcessHandle
,
1711 PROCESS_SUSPEND_RESUME
,
1716 if (!NT_SUCCESS(Status
)) return Status
;
1718 /* Reference the debug object */
1719 Status
= ObReferenceObjectByHandle(DebugHandle
,
1720 DEBUG_OBJECT_ADD_REMOVE_PROCESS
,
1721 DbgkDebugObjectType
,
1723 (PVOID
*)&DebugObject
,
1725 if (!NT_SUCCESS(Status
))
1727 /* Dereference the process and exit */
1728 ObDereferenceObject(Process
);
1732 /* Remove the debug object */
1733 Status
= DbgkClearProcessDebugObject(Process
, DebugObject
);
1735 /* Dereference the process and debug object and return status */
1736 ObDereferenceObject(Process
);
1737 ObDereferenceObject(DebugObject
);
1743 NtSetInformationDebugObject(IN HANDLE DebugHandle
,
1744 IN DEBUGOBJECTINFOCLASS DebugObjectInformationClass
,
1745 IN PVOID DebugInformation
,
1746 IN ULONG DebugInformationLength
,
1747 OUT PULONG ReturnLength OPTIONAL
)
1749 PDEBUG_OBJECT DebugObject
;
1750 KPROCESSOR_MODE PreviousMode
= ExGetPreviousMode();
1751 NTSTATUS Status
= STATUS_SUCCESS
;
1752 PDEBUG_OBJECT_KILL_PROCESS_ON_EXIT_INFORMATION DebugInfo
= DebugInformation
;
1755 /* Check buffers and parameters */
1756 Status
= DefaultSetInfoBufferCheck(DebugObjectInformationClass
,
1757 DbgkpDebugObjectInfoClass
,
1758 sizeof(DbgkpDebugObjectInfoClass
) /
1759 sizeof(DbgkpDebugObjectInfoClass
[0]),
1761 DebugInformationLength
,
1764 /* Check if the caller wanted the return length */
1767 /* Enter SEH for probe */
1770 /* Return required length to user-mode */
1771 ProbeForWriteUlong(ReturnLength
);
1772 *ReturnLength
= sizeof(*DebugInfo
);
1774 _SEH2_EXCEPT(ExSystemExceptionFilter())
1776 /* Get SEH Exception code */
1777 Status
= _SEH2_GetExceptionCode();
1781 if (!NT_SUCCESS(Status
)) return Status
;
1783 /* Open the Object */
1784 Status
= ObReferenceObjectByHandle(DebugHandle
,
1785 DEBUG_OBJECT_WAIT_STATE_CHANGE
,
1786 DbgkDebugObjectType
,
1788 (PVOID
*)&DebugObject
,
1790 if (NT_SUCCESS(Status
))
1792 /* Acquire the object */
1793 ExAcquireFastMutex(&DebugObject
->Mutex
);
1795 /* Set the proper flag */
1796 if (DebugInfo
->KillProcessOnExit
)
1798 /* Enable killing the process */
1799 DebugObject
->KillProcessOnExit
= TRUE
;
1804 DebugObject
->KillProcessOnExit
= FALSE
;
1807 /* Release the mutex */
1808 ExReleaseFastMutex(&DebugObject
->Mutex
);
1810 /* Release the Object */
1811 ObDereferenceObject(DebugObject
);
1820 NtWaitForDebugEvent(IN HANDLE DebugHandle
,
1821 IN BOOLEAN Alertable
,
1822 IN PLARGE_INTEGER Timeout OPTIONAL
,
1823 OUT PDBGUI_WAIT_STATE_CHANGE StateChange
)
1825 KPROCESSOR_MODE PreviousMode
= ExGetPreviousMode();
1826 LARGE_INTEGER SafeTimeOut
;
1828 LARGE_INTEGER StartTime
;
1831 LARGE_INTEGER NewTime
;
1832 PDEBUG_OBJECT DebugObject
;
1833 DBGUI_WAIT_STATE_CHANGE WaitStateChange
;
1834 NTSTATUS Status
= STATUS_SUCCESS
;
1835 PDEBUG_EVENT DebugEvent
= NULL
, DebugEvent2
;
1836 PLIST_ENTRY ListHead
, NextEntry
, NextEntry2
;
1838 DBGKTRACE(DBGK_OBJECT_DEBUG
, "Handle: %p\n", DebugHandle
);
1840 /* Clear the initial wait state change structure */
1841 RtlZeroMemory(&WaitStateChange
, sizeof(WaitStateChange
));
1843 /* Protect probe in SEH */
1846 /* Check if we came with a timeout */
1849 /* Check if the call was from user mode */
1850 if (PreviousMode
!= KernelMode
)
1853 ProbeForReadLargeInteger(Timeout
);
1856 /* Make a local copy */
1857 SafeTimeOut
= *Timeout
;
1858 Timeout
= &SafeTimeOut
;
1860 /* Query the current time */
1861 KeQuerySystemTime(&StartTime
);
1864 /* Check if the call was from user mode */
1865 if (PreviousMode
!= KernelMode
)
1867 /* Probe the state change structure */
1868 ProbeForWrite(StateChange
, sizeof(*StateChange
), sizeof(ULONG
));
1871 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
1873 /* Get the exception code */
1874 Status
= _SEH2_GetExceptionCode();
1877 if (!NT_SUCCESS(Status
)) return Status
;
1879 /* Get the debug object */
1880 Status
= ObReferenceObjectByHandle(DebugHandle
,
1881 DEBUG_OBJECT_WAIT_STATE_CHANGE
,
1882 DbgkDebugObjectType
,
1884 (PVOID
*)&DebugObject
,
1886 if (!NT_SUCCESS(Status
)) return Status
;
1888 /* Clear process and thread */
1892 /* Wait on the debug object given to us */
1895 Status
= KeWaitForSingleObject(DebugObject
,
1900 if (!NT_SUCCESS(Status
) ||
1901 (Status
== STATUS_TIMEOUT
) ||
1902 (Status
== STATUS_ALERTED
) ||
1903 (Status
== STATUS_USER_APC
))
1905 /* Break out the wait */
1909 /* Lock the object */
1911 ExAcquireFastMutex(&DebugObject
->Mutex
);
1913 /* Check if a debugger is connected */
1914 if (DebugObject
->DebuggerInactive
)
1917 Status
= STATUS_DEBUGGER_INACTIVE
;
1921 /* Loop the events */
1922 ListHead
= &DebugObject
->EventList
;
1923 NextEntry
= ListHead
->Flink
;
1924 while (ListHead
!= NextEntry
)
1926 /* Get the debug event */
1927 DebugEvent
= CONTAINING_RECORD(NextEntry
,
1930 DBGKTRACE(DBGK_PROCESS_DEBUG
, "DebugEvent: %p Flags: %lx\n",
1931 DebugEvent
, DebugEvent
->Flags
);
1934 if (!(DebugEvent
->Flags
& (DEBUG_EVENT_INACTIVE
| DEBUG_EVENT_READ
)))
1936 /* We got an event */
1939 /* Loop the list internally */
1940 NextEntry2
= DebugObject
->EventList
.Flink
;
1941 while (NextEntry2
!= NextEntry
)
1943 /* Get the debug event */
1944 DebugEvent2
= CONTAINING_RECORD(NextEntry2
,
1948 /* Try to match process IDs */
1949 if (DebugEvent2
->ClientId
.UniqueProcess
==
1950 DebugEvent
->ClientId
.UniqueProcess
)
1952 /* Found it, break out */
1953 DebugEvent
->Flags
|= DEBUG_EVENT_INACTIVE
;
1954 DebugEvent
->BackoutThread
= NULL
;
1959 /* Move to the next entry */
1960 NextEntry2
= NextEntry2
->Flink
;
1963 /* Check if we still have a valid event */
1964 if (GotEvent
) break;
1967 /* Move to the next entry */
1968 NextEntry
= NextEntry
->Flink
;
1971 /* Check if we have an event */
1974 /* Save and reference the process and thread */
1975 Process
= DebugEvent
->Process
;
1976 Thread
= DebugEvent
->Thread
;
1977 ObReferenceObject(Process
);
1978 ObReferenceObject(Thread
);
1980 /* Convert to user-mode structure */
1981 DbgkpConvertKernelToUserStateChange(&WaitStateChange
,
1985 DebugEvent
->Flags
|= DEBUG_EVENT_READ
;
1989 /* Unsignal the event */
1990 KeClearEvent(&DebugObject
->EventsPresent
);
1994 Status
= STATUS_SUCCESS
;
1997 /* Release the mutex */
1998 ExReleaseFastMutex(&DebugObject
->Mutex
);
1999 if (!NT_SUCCESS(Status
)) break;
2001 /* Check if we got an event */
2004 /* Check if we can wait again */
2005 if (SafeTimeOut
.QuadPart
< 0)
2007 /* Query the new time */
2008 KeQuerySystemTime(&NewTime
);
2010 /* Substract times */
2011 SafeTimeOut
.QuadPart
+= (NewTime
.QuadPart
- StartTime
.QuadPart
);
2012 StartTime
= NewTime
;
2014 /* Check if we've timed out */
2015 if (SafeTimeOut
.QuadPart
>= 0)
2017 /* We have, break out of the loop */
2018 Status
= STATUS_TIMEOUT
;
2025 /* Open the handles and dereference the objects */
2026 DbgkpOpenHandles(&WaitStateChange
, Process
, Thread
);
2027 ObDereferenceObject(Process
);
2028 ObDereferenceObject(Thread
);
2033 /* We're done, dereference the object */
2034 ObDereferenceObject(DebugObject
);
2036 /* Protect write with SEH */
2039 /* Return our wait state change structure */
2040 *StateChange
= WaitStateChange
;
2042 _SEH2_EXCEPT(ExSystemExceptionFilter())
2044 /* Get SEH Exception code */
2045 Status
= _SEH2_GetExceptionCode();