2 * PROJECT: ReactOS Kernel
3 * LICENSE: GPL - See COPYING in the top level directory
4 * FILE: ntoskrnl/kd64/kdapi.c
5 * PURPOSE: KD64 Public Routines and Internal Support
6 * PROGRAMMERS: Alex Ionescu (alex.ionescu@reactos.org)
9 /* INCLUDES ******************************************************************/
15 /* PRIVATE FUNCTIONS *********************************************************/
19 KdpSetCommonState(IN ULONG NewState
,
21 IN PDBGKD_WAIT_STATE_CHANGE64 WaitStateChange
)
23 USHORT InstructionCount
;
24 BOOLEAN HadBreakpoints
;
26 /* Setup common stuff available for all CPU architectures */
27 WaitStateChange
->NewState
= NewState
;
28 WaitStateChange
->ProcessorLevel
= KeProcessorLevel
;
29 WaitStateChange
->Processor
= (USHORT
)KeGetCurrentPrcb()->Number
;
30 WaitStateChange
->NumberProcessors
= (ULONG
)KeNumberProcessors
;
31 WaitStateChange
->Thread
= (ULONG
)KeGetCurrentThread();
32 WaitStateChange
->ProgramCounter
= (ULONG64
)Context
->Eip
;
34 /* Zero out the Control Report */
35 RtlZeroMemory(&WaitStateChange
->ControlReport
,
36 sizeof(DBGKD_CONTROL_REPORT
));
38 /* Now copy the instruction stream and set the count */
39 RtlCopyMemory(&WaitStateChange
->ControlReport
.InstructionStream
[0],
40 (PVOID
)(ULONG_PTR
)WaitStateChange
->ProgramCounter
,
42 InstructionCount
= DBGKD_MAXSTREAM
;
43 WaitStateChange
->ControlReport
.InstructionCount
= InstructionCount
;
45 /* Clear all the breakpoints in this region */
46 HadBreakpoints
= FALSE
;
48 KdpDeleteBreakpointRange((PVOID
)WaitStateChange
->ProgramCounter
,
49 (PVOID
)(WaitStateChange
->ProgramCounter
+
50 WaitStateChange
->ControlReport
.
51 InstructionCount
- 1));
55 /* Copy the instruction stream again, this time without breakpoints */
56 RtlCopyMemory(&WaitStateChange
->ControlReport
.InstructionStream
[0],
57 (PVOID
)(ULONG_PTR
)WaitStateChange
->ProgramCounter
,
58 WaitStateChange
->ControlReport
.InstructionCount
);
64 KdpSetContextState(IN PDBGKD_WAIT_STATE_CHANGE64 WaitStateChange
,
67 PKPRCB Prcb
= KeGetCurrentPrcb();
69 /* Copy i386 specific debug registers */
70 WaitStateChange
->ControlReport
.Dr6
= Prcb
->ProcessorState
.SpecialRegisters
.
72 WaitStateChange
->ControlReport
.Dr7
= Prcb
->ProcessorState
.SpecialRegisters
.
75 /* Copy i386 specific segments */
76 WaitStateChange
->ControlReport
.SegCs
= (USHORT
)Context
->SegCs
;
77 WaitStateChange
->ControlReport
.SegDs
= (USHORT
)Context
->SegDs
;
78 WaitStateChange
->ControlReport
.SegEs
= (USHORT
)Context
->SegEs
;
79 WaitStateChange
->ControlReport
.SegFs
= (USHORT
)Context
->SegFs
;
82 WaitStateChange
->ControlReport
.EFlags
= Context
->EFlags
;
84 /* Set Report Flags */
85 WaitStateChange
->ControlReport
.ReportFlags
= REPORT_INCLUDES_SEGS
;
86 if (WaitStateChange
->ControlReport
.SegCs
== KGDT_R0_CODE
)
88 WaitStateChange
->ControlReport
.ReportFlags
= REPORT_INCLUDES_CS
;
94 KdpSysGetVersion(IN PDBGKD_GET_VERSION64 Version
)
96 /* Copy the version block */
97 RtlCopyMemory(Version
, &KdVersionBlock
, sizeof(DBGKD_GET_VERSION64
));
102 KdpGetVersion(IN PDBGKD_MANIPULATE_STATE64 State
)
106 /* Fill out the header */
107 Header
.Length
= sizeof(DBGKD_MANIPULATE_STATE64
);
108 Header
.Buffer
= (PCHAR
)State
;
110 /* Get the version block */
111 KdpSysGetVersion(&State
->u
.GetVersion64
);
113 /* Fill out the state */
114 State
->ApiNumber
= DbgKdGetVersionApi
;
115 State
->ReturnStatus
= STATUS_SUCCESS
;
117 /* Send the packet */
118 KdSendPacket(PACKET_TYPE_KD_STATE_MANIPULATE
,
125 BOOLEAN VirtCalled
= FALSE
;
129 KdpReadVirtualMemory(IN PDBGKD_MANIPULATE_STATE64 State
,
134 ULONG Length
= State
->u
.ReadMemory
.TransferCount
;
135 NTSTATUS Status
= STATUS_SUCCESS
;
137 /* Validate length */
138 if (Length
> (PACKET_MAX_SIZE
- sizeof(DBGKD_MANIPULATE_STATE64
)))
140 /* Overflow, set it to maximum possible */
141 Length
= PACKET_MAX_SIZE
- sizeof(DBGKD_MANIPULATE_STATE64
);
145 if (!MmIsAddressValid((PVOID
)(ULONG_PTR
)State
->u
.ReadMemory
.TargetBaseAddress
))
147 Ke386SetCr2(State
->u
.ReadMemory
.TargetBaseAddress
);
152 if ((ULONG_PTR
)State
->u
.ReadMemory
.TargetBaseAddress
< KSEG0_BASE
)
155 Status
= STATUS_UNSUCCESSFUL
;
157 else if ((ULONG_PTR
)State
->u
.ReadMemory
.TargetBaseAddress
>= (ULONG_PTR
)SharedUserData
)
160 Status
= STATUS_UNSUCCESSFUL
;
164 RtlCopyMemory(Data
->Buffer
,
165 (PVOID
)(ULONG_PTR
)State
->u
.ReadMemory
.TargetBaseAddress
,
169 /* Fill out the header */
170 Data
->Length
= Length
;
171 Header
.Length
= sizeof(DBGKD_MANIPULATE_STATE64
);
172 Header
.Buffer
= (PCHAR
)State
;
174 /* Fill out the state */
175 State
->ReturnStatus
= Status
;
176 State
->u
.ReadMemory
.ActualBytesRead
= Length
;
178 /* Send the packet */
179 KdSendPacket(PACKET_TYPE_KD_STATE_MANIPULATE
,
187 KdpReadControlSpace(IN PDBGKD_MANIPULATE_STATE64 State
,
191 PDBGKD_READ_MEMORY64 ReadMemory
= &State
->u
.ReadMemory
;
193 ULONG Length
, RealLength
;
196 /* Setup the header */
197 Header
.Length
= sizeof(DBGKD_MANIPULATE_STATE64
);
198 Header
.Buffer
= (PCHAR
)State
;
199 ASSERT(Data
->Length
== 0);
201 /* Check the length requested */
202 Length
= ReadMemory
->TransferCount
;
203 if (Length
> (PACKET_MAX_SIZE
- sizeof(DBGKD_MANIPULATE_STATE64
)))
205 /* Use maximum allowed */
206 Length
= PACKET_MAX_SIZE
- sizeof(DBGKD_MANIPULATE_STATE64
);
209 /* Make sure that this is a valid request */
210 if (((ULONG
)ReadMemory
->TargetBaseAddress
< sizeof(KPROCESSOR_STATE
)) &&
211 (State
->Processor
< KeNumberProcessors
))
213 /* Get the actual length */
214 RealLength
= sizeof(KPROCESSOR_STATE
) -
215 (ULONG_PTR
)ReadMemory
->TargetBaseAddress
;
216 if (RealLength
< Length
) Length
= RealLength
;
218 /* Set the proper address */
219 ControlStart
= (PVOID
)((ULONG_PTR
)ReadMemory
->TargetBaseAddress
+
220 (ULONG_PTR
)&KiProcessorBlock
[State
->Processor
]->
223 /* Copy the memory */
224 RtlCopyMemory(Data
->Buffer
, ControlStart
, Length
);
225 Data
->Length
= Length
;
228 State
->ReturnStatus
= STATUS_SUCCESS
;
229 ReadMemory
->ActualBytesRead
= Data
->Length
;
233 /* Invalid request */
235 State
->ReturnStatus
= STATUS_UNSUCCESSFUL
;
236 ReadMemory
->ActualBytesRead
= 0;
240 KdSendPacket(PACKET_TYPE_KD_STATE_MANIPULATE
,
248 KdpSendWaitContinue(IN ULONG PacketType
,
249 IN PSTRING SendHeader
,
250 IN PSTRING SendData OPTIONAL
,
251 IN OUT PCONTEXT Context
)
254 DBGKD_MANIPULATE_STATE64 ManipulateState
;
258 /* Setup the Manipulate State structure */
259 Header
.MaximumLength
= sizeof(DBGKD_MANIPULATE_STATE64
);
260 Header
.Buffer
= (PCHAR
)&ManipulateState
;
261 Data
.MaximumLength
= sizeof(KdpMessageBuffer
);
262 Data
.Buffer
= KdpMessageBuffer
;
263 //KdpContextSent = FALSE;
266 /* Send the Packet */
267 KdSendPacket(PacketType
, SendHeader
, SendData
, &KdpContext
);
269 /* If the debugger isn't present anymore, just return success */
270 if (KdDebuggerNotPresent
) return ContinueSuccess
;
272 /* Main processing Loop */
278 /* Wait to get a reply to our packet */
279 RecvCode
= KdReceivePacket(PACKET_TYPE_KD_STATE_MANIPULATE
,
285 /* If we got a resend request, do it */
286 if (RecvCode
== KdPacketNeedsResend
) goto SendPacket
;
287 } while (RecvCode
== KdPacketTimedOut
);
289 /* Now check what API we got */
290 switch (ManipulateState
.ApiNumber
)
292 case DbgKdReadVirtualMemoryApi
:
294 /* Read virtual memory */
295 KdpReadVirtualMemory(&ManipulateState
, &Data
, Context
);
299 case DbgKdWriteVirtualMemoryApi
:
302 Ke386SetCr2(DbgKdWriteVirtualMemoryApi
);
306 case DbgKdGetContextApi
:
309 Ke386SetCr2(DbgKdGetContextApi
);
313 case DbgKdSetContextApi
:
316 Ke386SetCr2(DbgKdSetContextApi
);
320 case DbgKdWriteBreakPointApi
:
323 Ke386SetCr2(DbgKdWriteBreakPointApi
);
327 case DbgKdRestoreBreakPointApi
:
330 Ke386SetCr2(DbgKdRestoreBreakPointApi
);
334 case DbgKdContinueApi
:
337 Ke386SetCr2(DbgKdContinueApi
);
341 case DbgKdReadControlSpaceApi
:
343 /* Read control space */
344 KdpReadControlSpace(&ManipulateState
, &Data
, Context
);
347 case DbgKdWriteControlSpaceApi
:
350 Ke386SetCr2(DbgKdWriteControlSpaceApi
);
354 case DbgKdReadIoSpaceApi
:
357 Ke386SetCr2(DbgKdReadIoSpaceApi
);
361 case DbgKdWriteIoSpaceApi
:
364 Ke386SetCr2(DbgKdWriteIoSpaceApi
);
371 Ke386SetCr2(DbgKdRebootApi
);
375 case DbgKdContinueApi2
:
378 Ke386SetCr2(DbgKdContinueApi2
);
382 case DbgKdReadPhysicalMemoryApi
:
385 Ke386SetCr2(DbgKdReadPhysicalMemoryApi
);
389 case DbgKdWritePhysicalMemoryApi
:
392 Ke386SetCr2(DbgKdWritePhysicalMemoryApi
);
396 case DbgKdQuerySpecialCallsApi
:
399 Ke386SetCr2(DbgKdQuerySpecialCallsApi
);
403 case DbgKdSetSpecialCallApi
:
406 Ke386SetCr2(DbgKdSetSpecialCallApi
);
410 case DbgKdClearSpecialCallsApi
:
413 Ke386SetCr2(DbgKdClearSpecialCallsApi
);
417 case DbgKdSetInternalBreakPointApi
:
420 Ke386SetCr2(DbgKdSetInternalBreakPointApi
);
424 case DbgKdGetInternalBreakPointApi
:
427 Ke386SetCr2(DbgKdGetInternalBreakPointApi
);
431 case DbgKdReadIoSpaceExtendedApi
:
434 Ke386SetCr2(DbgKdReadIoSpaceExtendedApi
);
438 case DbgKdWriteIoSpaceExtendedApi
:
441 Ke386SetCr2(DbgKdWriteIoSpaceExtendedApi
);
445 case DbgKdGetVersionApi
:
447 /* Get version data */
448 KdpGetVersion(&ManipulateState
);
451 case DbgKdWriteBreakPointExApi
:
454 Ke386SetCr2(DbgKdWriteBreakPointExApi
);
458 case DbgKdRestoreBreakPointExApi
:
461 Ke386SetCr2(DbgKdRestoreBreakPointExApi
);
465 case DbgKdCauseBugCheckApi
:
468 Ke386SetCr2(DbgKdCauseBugCheckApi
);
472 case DbgKdSwitchProcessor
:
475 Ke386SetCr2(DbgKdSwitchProcessor
);
482 Ke386SetCr2(DbgKdPageInApi
);
486 case DbgKdReadMachineSpecificRegister
:
489 Ke386SetCr2(DbgKdReadMachineSpecificRegister
);
493 case DbgKdWriteMachineSpecificRegister
:
496 Ke386SetCr2(DbgKdWriteMachineSpecificRegister
);
503 Ke386SetCr2(OldVlm1
);
510 Ke386SetCr2(OldVlm2
);
514 case DbgKdSearchMemoryApi
:
517 Ke386SetCr2(DbgKdSearchMemoryApi
);
521 case DbgKdGetBusDataApi
:
524 Ke386SetCr2(DbgKdGetBusDataApi
);
528 case DbgKdSetBusDataApi
:
531 Ke386SetCr2(DbgKdSetBusDataApi
);
535 case DbgKdCheckLowMemoryApi
:
538 Ke386SetCr2(DbgKdCheckLowMemoryApi
);
542 case DbgKdClearAllInternalBreakpointsApi
:
545 Ke386SetCr2(DbgKdClearAllInternalBreakpointsApi
);
549 case DbgKdFillMemoryApi
:
552 Ke386SetCr2(DbgKdFillMemoryApi
);
556 case DbgKdQueryMemoryApi
:
559 Ke386SetCr2(DbgKdQueryMemoryApi
);
563 case DbgKdSwitchPartition
:
566 Ke386SetCr2(DbgKdSwitchPartition
);
570 /* Unsupported Message */
573 /* Setup an empty message, with failure */
576 ManipulateState
.ReturnStatus
= STATUS_UNSUCCESSFUL
;
579 KdSendPacket(PACKET_TYPE_KD_STATE_MANIPULATE
,
590 KdpReportLoadSymbolsStateChange(IN PSTRING PathName
,
591 IN PKD_SYMBOLS_INFO SymbolInfo
,
593 IN OUT PCONTEXT Context
)
597 DBGKD_WAIT_STATE_CHANGE64 WaitStateChange
;
598 KCONTINUE_STATUS Status
;
600 /* Start wait loop */
603 /* Build the architecture common parts of the message */
604 KdpSetCommonState(DbgKdLoadSymbolsStateChange
,
608 /* Now finish creating the structure */
609 KdpSetContextState(&WaitStateChange
, Context
);
611 /* Fill out load data */
612 WaitStateChange
.u
.LoadSymbols
.UnloadSymbols
= Unload
;
613 WaitStateChange
.u
.LoadSymbols
.BaseOfDll
= (ULONG
)SymbolInfo
->BaseOfDll
;
614 WaitStateChange
.u
.LoadSymbols
.ProcessId
= SymbolInfo
->ProcessId
;
615 WaitStateChange
.u
.LoadSymbols
.CheckSum
= SymbolInfo
->CheckSum
;
616 WaitStateChange
.u
.LoadSymbols
.SizeOfImage
= SymbolInfo
->SizeOfImage
;
618 /* Check if we have a symbol name */
621 /* Setup the information */
622 WaitStateChange
.u
.LoadSymbols
.PathNameLength
= PathName
->Length
;
623 Data
.Buffer
= KdpPathBuffer
;
624 Data
.Length
= WaitStateChange
.u
.LoadSymbols
.PathNameLength
;
630 WaitStateChange
.u
.LoadSymbols
.PathNameLength
= 0;
634 /* Setup the header */
635 Header
.Length
= sizeof(DBGKD_WAIT_STATE_CHANGE64
);
636 Header
.Buffer
= (PCHAR
)&WaitStateChange
;
638 /* Send the packet */
639 Status
= KdpSendWaitContinue(PACKET_TYPE_KD_STATE_CHANGE64
,
643 } while(Status
== ContinueProcessorReselected
);
652 KdpTimeSlipDpcRoutine(IN PKDPC Dpc
,
653 IN PVOID DeferredContext
,
654 IN PVOID SystemArgument1
,
655 IN PVOID SystemArgument2
)
657 LONG OldSlip
, NewSlip
, PendingSlip
;
659 /* Get the current pending slip */
660 PendingSlip
= KdpTimeSlipPending
;
663 /* Save the old value and either disable or enable it now. */
664 OldSlip
= PendingSlip
;
665 NewSlip
= OldSlip
> 1 ? 1 : 0;
667 /* Try to change the value */
668 } while (InterlockedCompareExchange(&KdpTimeSlipPending
,
670 OldSlip
) != OldSlip
);
672 /* If the New Slip value is 1, then do the Time Slipping */
673 if (NewSlip
) ExQueueWorkItem(&KdpTimeSlipWorkItem
, DelayedWorkQueue
);
678 KdpTimeSlipWork(IN PVOID Context
)
681 LARGE_INTEGER DueTime
;
683 /* Update the System time from the CMOS */
684 ExAcquireTimeRefreshLock(FALSE
);
685 ExUpdateSystemTimeFromCmos(FALSE
, 0);
686 ExReleaseTimeRefreshLock();
688 /* Check if we have a registered Time Slip Event and signal it */
689 KeAcquireSpinLock(&KdpTimeSlipEventLock
, &OldIrql
);
690 if (KdpTimeSlipEvent
) KeSetEvent(KdpTimeSlipEvent
, 0, FALSE
);
691 KeReleaseSpinLock(&KdpTimeSlipEventLock
, OldIrql
);
693 /* Delay the DPC until it runs next time */
694 DueTime
.QuadPart
= -1800000000;
695 KeSetTimer(&KdpTimeSlipTimer
, DueTime
, &KdpTimeSlipDpc
);
700 KdpSwitchProcessor(IN PEXCEPTION_RECORD ExceptionRecord
,
701 IN OUT PCONTEXT ContextRecord
,
702 IN BOOLEAN SecondChanceException
)
706 /* Save the port data */
709 /* Report a state change */
711 Status
= KdpReportExceptionStateChange(ExceptionRecord
,
713 SecondChanceException
);
718 /* Restore the port data and return */
725 KdpQueryPerformanceCounter(IN PKTRAP_FRAME TrapFrame
)
727 LARGE_INTEGER Null
= {{0}};
729 /* Check if interrupts were disabled */
730 if (!(TrapFrame
->EFlags
& EFLAGS_INTERRUPT_MASK
))
732 /* Nothing to return */
736 /* Otherwise, do the call */
737 return KeQueryPerformanceCounter(NULL
);
742 KdEnterDebugger(IN PKTRAP_FRAME TrapFrame
,
743 IN PKEXCEPTION_FRAME ExceptionFrame
)
747 /* Check if we have a trap frame */
750 /* Calculate the time difference for the enter */
751 KdTimerStop
= KdpQueryPerformanceCounter(TrapFrame
);
752 KdTimerDifference
.QuadPart
= KdTimerStop
.QuadPart
-
753 KdTimerStart
.QuadPart
;
757 /* No trap frame, so can't calculate */
758 KdTimerStop
.QuadPart
= 0;
761 /* Save the current IRQL */
762 KeGetCurrentPrcb()->DebuggerSavedIRQL
= KeGetCurrentIrql();
764 /* Freeze all CPUs */
765 Entered
= KeFreezeExecution(TrapFrame
, ExceptionFrame
);
767 /* Lock the port, save the state and set debugger entered */
768 KdpPortLocked
= KeTryToAcquireSpinLockAtDpcLevel(&KdpDebuggerLock
);
770 KdEnteredDebugger
= TRUE
;
772 /* Check freeze flag */
773 if (KiFreezeFlag
& 1)
775 /* Print out errror */
776 DbgPrint("FreezeLock was jammed! Backup SpinLock was used!\n");
779 /* Check processor state */
780 if (KiFreezeFlag
& 2)
782 /* Print out errror */
783 DbgPrint("Some processors not frozen in debugger!\n");
786 /* Make sure we acquired the port */
787 if (!KdpPortLocked
) DbgPrint("Port lock was not acquired!\n");
789 /* Return enter state */
795 KdExitDebugger(IN BOOLEAN Entered
)
799 /* Restore the state and unlock the port */
801 if (KdpPortLocked
) KdpPortUnlock();
803 /* Unfreeze the CPUs */
804 KeThawExecution(Entered
);
806 /* Compare time with the one from KdEnterDebugger */
807 if (!KdTimerStop
.QuadPart
)
809 /* We didn't get a trap frame earlier in so never got the time */
810 KdTimerStart
= KdTimerStop
;
814 /* Query the timer */
815 KdTimerStart
= KeQueryPerformanceCounter(NULL
);
818 /* Check if a Time Slip was on queue */
819 TimeSlip
= InterlockedIncrement(&KdpTimeSlipPending
);
822 /* Queue a DPC for the time slip */
823 InterlockedIncrement(&KdpTimeSlipPending
);
824 KeInsertQueueDpc(&KdpTimeSlipDpc
, NULL
, NULL
);
830 KdEnableDebuggerWithLock(BOOLEAN NeedLock
)
834 /* Check if we need to acquire the lock */
838 KeRaiseIrql(DISPATCH_LEVEL
, &OldIrql
);
842 /* Check if we're not disabled */
845 /* Check if we had locked the port before */
849 KeLowerIrql(OldIrql
);
853 /* Fail: We're already enabled */
854 return STATUS_INVALID_PARAMETER
;
857 /* Decrease the disable count */
858 if (!(--KdDisableCount
))
860 /* We're now enabled again! Were we enabled before, too? */
861 if (KdPreviouslyEnabled
)
863 /* Reinitialize the Debugger */
864 KdInitSystem(0, NULL
) ;
865 //KdpRestoreAllBreakpoints();
869 /* Check if we had locked the port before */
872 /* Yes, now unlock it */
873 KeLowerIrql(OldIrql
);
878 return STATUS_SUCCESS
;
881 /* PUBLIC FUNCTIONS **********************************************************/
888 KdEnableDebugger(VOID
)
890 /* Use the internal routine */
892 return KdEnableDebuggerWithLock(TRUE
);