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 KdpRestoreBreakpoint(IN PDBGKD_MANIPULATE_STATE64 State
,
252 PDBGKD_RESTORE_BREAKPOINT RestoreBp
= &State
->u
.RestoreBreakPoint
;
255 /* Fill out the header */
256 Header
.Length
= sizeof(DBGKD_MANIPULATE_STATE64
);
257 Header
.Buffer
= (PCHAR
)State
;
258 ASSERT(Data
->Length
== 0);
260 /* Get the version block */
261 if (KdpDeleteBreakpoint(RestoreBp
->BreakPointHandle
))
264 State
->ReturnStatus
= STATUS_SUCCESS
;
269 State
->ReturnStatus
= STATUS_UNSUCCESSFUL
;
272 /* Send the packet */
273 KdSendPacket(PACKET_TYPE_KD_STATE_MANIPULATE
,
281 KdpSendWaitContinue(IN ULONG PacketType
,
282 IN PSTRING SendHeader
,
283 IN PSTRING SendData OPTIONAL
,
284 IN OUT PCONTEXT Context
)
287 DBGKD_MANIPULATE_STATE64 ManipulateState
;
291 /* Setup the Manipulate State structure */
292 Header
.MaximumLength
= sizeof(DBGKD_MANIPULATE_STATE64
);
293 Header
.Buffer
= (PCHAR
)&ManipulateState
;
294 Data
.MaximumLength
= sizeof(KdpMessageBuffer
);
295 Data
.Buffer
= KdpMessageBuffer
;
296 //KdpContextSent = FALSE;
299 /* Send the Packet */
300 KdSendPacket(PacketType
, SendHeader
, SendData
, &KdpContext
);
302 /* If the debugger isn't present anymore, just return success */
303 if (KdDebuggerNotPresent
) return ContinueSuccess
;
305 /* Main processing Loop */
311 /* Wait to get a reply to our packet */
312 RecvCode
= KdReceivePacket(PACKET_TYPE_KD_STATE_MANIPULATE
,
318 /* If we got a resend request, do it */
319 if (RecvCode
== KdPacketNeedsResend
) goto SendPacket
;
320 } while (RecvCode
== KdPacketTimedOut
);
322 /* Now check what API we got */
323 switch (ManipulateState
.ApiNumber
)
325 case DbgKdReadVirtualMemoryApi
:
327 /* Read virtual memory */
328 KdpReadVirtualMemory(&ManipulateState
, &Data
, Context
);
332 case DbgKdWriteVirtualMemoryApi
:
335 Ke386SetCr2(DbgKdWriteVirtualMemoryApi
);
339 case DbgKdGetContextApi
:
342 Ke386SetCr2(DbgKdGetContextApi
);
346 case DbgKdSetContextApi
:
349 Ke386SetCr2(DbgKdSetContextApi
);
353 case DbgKdWriteBreakPointApi
:
356 Ke386SetCr2(DbgKdWriteBreakPointApi
);
360 case DbgKdRestoreBreakPointApi
:
363 KdpRestoreBreakpoint(&ManipulateState
, &Data
, Context
);
366 case DbgKdContinueApi
:
369 Ke386SetCr2(DbgKdContinueApi
);
373 case DbgKdReadControlSpaceApi
:
375 /* Read control space */
376 KdpReadControlSpace(&ManipulateState
, &Data
, Context
);
379 case DbgKdWriteControlSpaceApi
:
382 Ke386SetCr2(DbgKdWriteControlSpaceApi
);
386 case DbgKdReadIoSpaceApi
:
389 Ke386SetCr2(DbgKdReadIoSpaceApi
);
393 case DbgKdWriteIoSpaceApi
:
396 Ke386SetCr2(DbgKdWriteIoSpaceApi
);
403 Ke386SetCr2(DbgKdRebootApi
);
407 case DbgKdContinueApi2
:
410 Ke386SetCr2(DbgKdContinueApi2
);
414 case DbgKdReadPhysicalMemoryApi
:
417 Ke386SetCr2(DbgKdReadPhysicalMemoryApi
);
421 case DbgKdWritePhysicalMemoryApi
:
424 Ke386SetCr2(DbgKdWritePhysicalMemoryApi
);
428 case DbgKdQuerySpecialCallsApi
:
431 Ke386SetCr2(DbgKdQuerySpecialCallsApi
);
435 case DbgKdSetSpecialCallApi
:
438 Ke386SetCr2(DbgKdSetSpecialCallApi
);
442 case DbgKdClearSpecialCallsApi
:
445 Ke386SetCr2(DbgKdClearSpecialCallsApi
);
449 case DbgKdSetInternalBreakPointApi
:
452 Ke386SetCr2(DbgKdSetInternalBreakPointApi
);
456 case DbgKdGetInternalBreakPointApi
:
459 Ke386SetCr2(DbgKdGetInternalBreakPointApi
);
463 case DbgKdReadIoSpaceExtendedApi
:
466 Ke386SetCr2(DbgKdReadIoSpaceExtendedApi
);
470 case DbgKdWriteIoSpaceExtendedApi
:
473 Ke386SetCr2(DbgKdWriteIoSpaceExtendedApi
);
477 case DbgKdGetVersionApi
:
479 /* Get version data */
480 KdpGetVersion(&ManipulateState
);
483 case DbgKdWriteBreakPointExApi
:
486 Ke386SetCr2(DbgKdWriteBreakPointExApi
);
490 case DbgKdRestoreBreakPointExApi
:
493 Ke386SetCr2(DbgKdRestoreBreakPointExApi
);
497 case DbgKdCauseBugCheckApi
:
500 Ke386SetCr2(DbgKdCauseBugCheckApi
);
504 case DbgKdSwitchProcessor
:
507 Ke386SetCr2(DbgKdSwitchProcessor
);
514 Ke386SetCr2(DbgKdPageInApi
);
518 case DbgKdReadMachineSpecificRegister
:
521 Ke386SetCr2(DbgKdReadMachineSpecificRegister
);
525 case DbgKdWriteMachineSpecificRegister
:
528 Ke386SetCr2(DbgKdWriteMachineSpecificRegister
);
535 Ke386SetCr2(OldVlm1
);
542 Ke386SetCr2(OldVlm2
);
546 case DbgKdSearchMemoryApi
:
549 Ke386SetCr2(DbgKdSearchMemoryApi
);
553 case DbgKdGetBusDataApi
:
556 Ke386SetCr2(DbgKdGetBusDataApi
);
560 case DbgKdSetBusDataApi
:
563 Ke386SetCr2(DbgKdSetBusDataApi
);
567 case DbgKdCheckLowMemoryApi
:
570 Ke386SetCr2(DbgKdCheckLowMemoryApi
);
574 case DbgKdClearAllInternalBreakpointsApi
:
577 Ke386SetCr2(DbgKdClearAllInternalBreakpointsApi
);
581 case DbgKdFillMemoryApi
:
584 Ke386SetCr2(DbgKdFillMemoryApi
);
588 case DbgKdQueryMemoryApi
:
591 Ke386SetCr2(DbgKdQueryMemoryApi
);
595 case DbgKdSwitchPartition
:
598 Ke386SetCr2(DbgKdSwitchPartition
);
602 /* Unsupported Message */
605 /* Setup an empty message, with failure */
608 ManipulateState
.ReturnStatus
= STATUS_UNSUCCESSFUL
;
611 KdSendPacket(PACKET_TYPE_KD_STATE_MANIPULATE
,
622 KdpReportLoadSymbolsStateChange(IN PSTRING PathName
,
623 IN PKD_SYMBOLS_INFO SymbolInfo
,
625 IN OUT PCONTEXT Context
)
629 DBGKD_WAIT_STATE_CHANGE64 WaitStateChange
;
630 KCONTINUE_STATUS Status
;
632 /* Start wait loop */
635 /* Build the architecture common parts of the message */
636 KdpSetCommonState(DbgKdLoadSymbolsStateChange
,
640 /* Now finish creating the structure */
641 KdpSetContextState(&WaitStateChange
, Context
);
643 /* Fill out load data */
644 WaitStateChange
.u
.LoadSymbols
.UnloadSymbols
= Unload
;
645 WaitStateChange
.u
.LoadSymbols
.BaseOfDll
= (ULONG
)SymbolInfo
->BaseOfDll
;
646 WaitStateChange
.u
.LoadSymbols
.ProcessId
= SymbolInfo
->ProcessId
;
647 WaitStateChange
.u
.LoadSymbols
.CheckSum
= SymbolInfo
->CheckSum
;
648 WaitStateChange
.u
.LoadSymbols
.SizeOfImage
= SymbolInfo
->SizeOfImage
;
650 /* Check if we have a symbol name */
653 /* Setup the information */
654 WaitStateChange
.u
.LoadSymbols
.PathNameLength
= PathName
->Length
;
655 Data
.Buffer
= KdpPathBuffer
;
656 Data
.Length
= WaitStateChange
.u
.LoadSymbols
.PathNameLength
;
662 WaitStateChange
.u
.LoadSymbols
.PathNameLength
= 0;
666 /* Setup the header */
667 Header
.Length
= sizeof(DBGKD_WAIT_STATE_CHANGE64
);
668 Header
.Buffer
= (PCHAR
)&WaitStateChange
;
670 /* Send the packet */
671 Status
= KdpSendWaitContinue(PACKET_TYPE_KD_STATE_CHANGE64
,
675 } while(Status
== ContinueProcessorReselected
);
684 KdpTimeSlipDpcRoutine(IN PKDPC Dpc
,
685 IN PVOID DeferredContext
,
686 IN PVOID SystemArgument1
,
687 IN PVOID SystemArgument2
)
689 LONG OldSlip
, NewSlip
, PendingSlip
;
691 /* Get the current pending slip */
692 PendingSlip
= KdpTimeSlipPending
;
695 /* Save the old value and either disable or enable it now. */
696 OldSlip
= PendingSlip
;
697 NewSlip
= OldSlip
> 1 ? 1 : 0;
699 /* Try to change the value */
700 } while (InterlockedCompareExchange(&KdpTimeSlipPending
,
702 OldSlip
) != OldSlip
);
704 /* If the New Slip value is 1, then do the Time Slipping */
705 if (NewSlip
) ExQueueWorkItem(&KdpTimeSlipWorkItem
, DelayedWorkQueue
);
710 KdpTimeSlipWork(IN PVOID Context
)
713 LARGE_INTEGER DueTime
;
715 /* Update the System time from the CMOS */
716 ExAcquireTimeRefreshLock(FALSE
);
717 ExUpdateSystemTimeFromCmos(FALSE
, 0);
718 ExReleaseTimeRefreshLock();
720 /* Check if we have a registered Time Slip Event and signal it */
721 KeAcquireSpinLock(&KdpTimeSlipEventLock
, &OldIrql
);
722 if (KdpTimeSlipEvent
) KeSetEvent(KdpTimeSlipEvent
, 0, FALSE
);
723 KeReleaseSpinLock(&KdpTimeSlipEventLock
, OldIrql
);
725 /* Delay the DPC until it runs next time */
726 DueTime
.QuadPart
= -1800000000;
727 KeSetTimer(&KdpTimeSlipTimer
, DueTime
, &KdpTimeSlipDpc
);
732 KdpSwitchProcessor(IN PEXCEPTION_RECORD ExceptionRecord
,
733 IN OUT PCONTEXT ContextRecord
,
734 IN BOOLEAN SecondChanceException
)
738 /* Save the port data */
741 /* Report a state change */
743 Status
= KdpReportExceptionStateChange(ExceptionRecord
,
745 SecondChanceException
);
750 /* Restore the port data and return */
757 KdpQueryPerformanceCounter(IN PKTRAP_FRAME TrapFrame
)
759 LARGE_INTEGER Null
= {{0}};
761 /* Check if interrupts were disabled */
762 if (!(TrapFrame
->EFlags
& EFLAGS_INTERRUPT_MASK
))
764 /* Nothing to return */
768 /* Otherwise, do the call */
769 return KeQueryPerformanceCounter(NULL
);
774 KdEnterDebugger(IN PKTRAP_FRAME TrapFrame
,
775 IN PKEXCEPTION_FRAME ExceptionFrame
)
779 /* Check if we have a trap frame */
782 /* Calculate the time difference for the enter */
783 KdTimerStop
= KdpQueryPerformanceCounter(TrapFrame
);
784 KdTimerDifference
.QuadPart
= KdTimerStop
.QuadPart
-
785 KdTimerStart
.QuadPart
;
789 /* No trap frame, so can't calculate */
790 KdTimerStop
.QuadPart
= 0;
793 /* Save the current IRQL */
794 KeGetCurrentPrcb()->DebuggerSavedIRQL
= KeGetCurrentIrql();
796 /* Freeze all CPUs */
797 Entered
= KeFreezeExecution(TrapFrame
, ExceptionFrame
);
799 /* Lock the port, save the state and set debugger entered */
800 KdpPortLocked
= KeTryToAcquireSpinLockAtDpcLevel(&KdpDebuggerLock
);
802 KdEnteredDebugger
= TRUE
;
804 /* Check freeze flag */
805 if (KiFreezeFlag
& 1)
807 /* Print out errror */
808 DbgPrint("FreezeLock was jammed! Backup SpinLock was used!\n");
811 /* Check processor state */
812 if (KiFreezeFlag
& 2)
814 /* Print out errror */
815 DbgPrint("Some processors not frozen in debugger!\n");
818 /* Make sure we acquired the port */
819 if (!KdpPortLocked
) DbgPrint("Port lock was not acquired!\n");
821 /* Return enter state */
827 KdExitDebugger(IN BOOLEAN Entered
)
831 /* Restore the state and unlock the port */
833 if (KdpPortLocked
) KdpPortUnlock();
835 /* Unfreeze the CPUs */
836 KeThawExecution(Entered
);
838 /* Compare time with the one from KdEnterDebugger */
839 if (!KdTimerStop
.QuadPart
)
841 /* We didn't get a trap frame earlier in so never got the time */
842 KdTimerStart
= KdTimerStop
;
846 /* Query the timer */
847 KdTimerStart
= KeQueryPerformanceCounter(NULL
);
850 /* Check if a Time Slip was on queue */
851 TimeSlip
= InterlockedIncrement(&KdpTimeSlipPending
);
854 /* Queue a DPC for the time slip */
855 InterlockedIncrement(&KdpTimeSlipPending
);
856 KeInsertQueueDpc(&KdpTimeSlipDpc
, NULL
, NULL
);
862 KdEnableDebuggerWithLock(BOOLEAN NeedLock
)
866 /* Check if we need to acquire the lock */
870 KeRaiseIrql(DISPATCH_LEVEL
, &OldIrql
);
874 /* Check if we're not disabled */
877 /* Check if we had locked the port before */
881 KeLowerIrql(OldIrql
);
885 /* Fail: We're already enabled */
886 return STATUS_INVALID_PARAMETER
;
889 /* Decrease the disable count */
890 if (!(--KdDisableCount
))
892 /* We're now enabled again! Were we enabled before, too? */
893 if (KdPreviouslyEnabled
)
895 /* Reinitialize the Debugger */
896 KdInitSystem(0, NULL
) ;
897 KdpRestoreAllBreakpoints();
901 /* Check if we had locked the port before */
904 /* Yes, now unlock it */
905 KeLowerIrql(OldIrql
);
910 return STATUS_SUCCESS
;
913 /* PUBLIC FUNCTIONS **********************************************************/
920 KdEnableDebugger(VOID
)
922 /* Use the internal routine */
924 return KdEnableDebuggerWithLock(TRUE
);