3 * Copyright (C) 2005 ReactOS Team
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 * PROJECT: ReactOS kernel
21 * FILE: ntoskrnl/dbg/kdb_cli.c
22 * PURPOSE: Kernel debugger command line interface
23 * PROGRAMMER: Gregor Anich (blight@blight.eu.org)
29 /* INCLUDES ******************************************************************/
36 /* DEFINES *******************************************************************/
42 #define KEY_SCAN_UP 72
43 #define KEY_SCAN_DOWN 80
45 /* Scan codes of keyboard keys: */
46 #define KEYSC_END 0x004f
47 #define KEYSC_PAGEUP 0x0049
48 #define KEYSC_PAGEDOWN 0x0051
49 #define KEYSC_HOME 0x0047
50 #define KEYSC_ARROWUP 0x0048
52 #define KDB_ENTER_CONDITION_TO_STRING(cond) \
53 ((cond) == KdbDoNotEnter ? "never" : \
54 ((cond) == KdbEnterAlways ? "always" : \
55 ((cond) == KdbEnterFromKmode ? "kmode" : "umode")))
57 #define KDB_ACCESS_TYPE_TO_STRING(type) \
58 ((type) == KdbAccessRead ? "read" : \
59 ((type) == KdbAccessWrite ? "write" : \
60 ((type) == KdbAccessReadWrite ? "rdwr" : "exec")))
62 #define NPX_STATE_TO_STRING(state) \
63 ((state) == NPX_STATE_LOADED ? "Loaded" : \
64 ((state) == NPX_STATE_NOT_LOADED ? "Not loaded" : "Unknown"))
66 /* PROTOTYPES ****************************************************************/
68 static BOOLEAN
KdbpCmdEvalExpression(ULONG Argc
, PCHAR Argv
[]);
69 static BOOLEAN
KdbpCmdDisassembleX(ULONG Argc
, PCHAR Argv
[]);
70 static BOOLEAN
KdbpCmdRegs(ULONG Argc
, PCHAR Argv
[]);
71 static BOOLEAN
KdbpCmdBackTrace(ULONG Argc
, PCHAR Argv
[]);
73 static BOOLEAN
KdbpCmdContinue(ULONG Argc
, PCHAR Argv
[]);
74 static BOOLEAN
KdbpCmdStep(ULONG Argc
, PCHAR Argv
[]);
75 static BOOLEAN
KdbpCmdBreakPointList(ULONG Argc
, PCHAR Argv
[]);
76 static BOOLEAN
KdbpCmdEnableDisableClearBreakPoint(ULONG Argc
, PCHAR Argv
[]);
77 static BOOLEAN
KdbpCmdBreakPoint(ULONG Argc
, PCHAR Argv
[]);
79 static BOOLEAN
KdbpCmdThread(ULONG Argc
, PCHAR Argv
[]);
80 static BOOLEAN
KdbpCmdProc(ULONG Argc
, PCHAR Argv
[]);
82 static BOOLEAN
KdbpCmdMod(ULONG Argc
, PCHAR Argv
[]);
83 static BOOLEAN
KdbpCmdGdtLdtIdt(ULONG Argc
, PCHAR Argv
[]);
84 static BOOLEAN
KdbpCmdPcr(ULONG Argc
, PCHAR Argv
[]);
85 static BOOLEAN
KdbpCmdTss(ULONG Argc
, PCHAR Argv
[]);
87 static BOOLEAN
KdbpCmdBugCheck(ULONG Argc
, PCHAR Argv
[]);
88 static BOOLEAN
KdbpCmdFilter(ULONG Argc
, PCHAR Argv
[]);
89 static BOOLEAN
KdbpCmdSet(ULONG Argc
, PCHAR Argv
[]);
90 static BOOLEAN
KdbpCmdHelp(ULONG Argc
, PCHAR Argv
[]);
91 static BOOLEAN
KdbpCmdDmesg(ULONG Argc
, PCHAR Argv
[]);
94 static BOOLEAN
KdbpCmdPrintStruct(ULONG Argc
, PCHAR Argv
[]);
97 /* GLOBALS *******************************************************************/
99 static PKDBG_CLI_ROUTINE KdbCliCallbacks
[10];
100 static BOOLEAN KdbUseIntelSyntax
= FALSE
; /* Set to TRUE for intel syntax */
101 static BOOLEAN KdbBreakOnModuleLoad
= FALSE
; /* Set to TRUE to break into KDB when a module is loaded */
103 static CHAR KdbCommandHistoryBuffer
[2048]; /* Command history string ringbuffer */
104 static PCHAR KdbCommandHistory
[sizeof(KdbCommandHistoryBuffer
) / 8] = { NULL
}; /* Command history ringbuffer */
105 static LONG KdbCommandHistoryBufferIndex
= 0;
106 static LONG KdbCommandHistoryIndex
= 0;
108 static ULONG KdbNumberOfRowsPrinted
= 0;
109 static ULONG KdbNumberOfColsPrinted
= 0;
110 static BOOLEAN KdbOutputAborted
= FALSE
;
111 static BOOLEAN KdbRepeatLastCommand
= FALSE
;
112 static LONG KdbNumberOfRowsTerminal
= -1;
113 static LONG KdbNumberOfColsTerminal
= -1;
115 PCHAR KdbInitFileBuffer
= NULL
; /* Buffer where KDBinit file is loaded into during initialization */
116 BOOLEAN KdbpBugCheckRequested
= FALSE
;
119 /* defined in ../kd/kdio.c, declare here: */
120 extern volatile BOOLEAN KdbpIsInDmesgMode
;
121 extern const ULONG KdpDmesgBufferSize
;
122 extern PCHAR KdpDmesgBuffer
;
123 extern volatile ULONG KdpDmesgCurrentPosition
;
124 extern volatile ULONG KdpDmesgFreeBytes
;
125 extern volatile ULONG KdbDmesgTotalWritten
;
132 BOOLEAN (*Fn
)(ULONG Argc
, PCHAR Argv
[]);
133 } KdbDebuggerCommands
[] = {
135 { NULL
, NULL
, "Data", NULL
},
136 { "?", "? expression", "Evaluate expression.", KdbpCmdEvalExpression
},
137 { "disasm", "disasm [address] [L count]", "Disassemble count instructions at address.", KdbpCmdDisassembleX
},
138 { "x", "x [address] [L count]", "Display count dwords, starting at addr.", KdbpCmdDisassembleX
},
139 { "regs", "regs", "Display general purpose registers.", KdbpCmdRegs
},
140 { "cregs", "cregs", "Display control registers.", KdbpCmdRegs
},
141 { "sregs", "sregs", "Display status registers.", KdbpCmdRegs
},
142 { "dregs", "dregs", "Display debug registers.", KdbpCmdRegs
},
143 { "bt", "bt [*frameaddr|thread id]", "Prints current backtrace or from given frame addr", KdbpCmdBackTrace
},
145 { "dt", "dt [mod] [type] [addr]", "Print a struct. Addr is optional.", KdbpCmdPrintStruct
},
149 { NULL
, NULL
, "Flow control", NULL
},
150 { "cont", "cont", "Continue execution (leave debugger)", KdbpCmdContinue
},
151 { "step", "step [count]", "Execute single instructions, stepping into interrupts.", KdbpCmdStep
},
152 { "next", "next [count]", "Execute single instructions, skipping calls and reps.", KdbpCmdStep
},
153 { "bl", "bl", "List breakpoints.", KdbpCmdBreakPointList
},
154 { "be", "be [breakpoint]", "Enable breakpoint.", KdbpCmdEnableDisableClearBreakPoint
},
155 { "bd", "bd [breakpoint]", "Disable breakpoint.", KdbpCmdEnableDisableClearBreakPoint
},
156 { "bc", "bc [breakpoint]", "Clear breakpoint.", KdbpCmdEnableDisableClearBreakPoint
},
157 { "bpx", "bpx [address] [IF condition]", "Set software execution breakpoint at address.", KdbpCmdBreakPoint
},
158 { "bpm", "bpm [r|w|rw|x] [byte|word|dword] [address] [IF condition]", "Set memory breakpoint at address.", KdbpCmdBreakPoint
},
161 { NULL
, NULL
, "Process/Thread", NULL
},
162 { "thread", "thread [list[ pid]|[attach ]tid]", "List threads in current or specified process, display thread with given id or attach to thread.", KdbpCmdThread
},
163 { "proc", "proc [list|[attach ]pid]", "List processes, display process with given id or attach to process.", KdbpCmdProc
},
165 /* System information */
166 { NULL
, NULL
, "System info", NULL
},
167 { "mod", "mod [address]", "List all modules or the one containing address.", KdbpCmdMod
},
168 { "gdt", "gdt", "Display global descriptor table.", KdbpCmdGdtLdtIdt
},
169 { "ldt", "ldt", "Display local descriptor table.", KdbpCmdGdtLdtIdt
},
170 { "idt", "idt", "Display interrupt descriptor table.", KdbpCmdGdtLdtIdt
},
171 { "pcr", "pcr", "Display processor control region.", KdbpCmdPcr
},
172 { "tss", "tss", "Display task state segment.", KdbpCmdTss
},
175 { NULL
, NULL
, "Others", NULL
},
176 { "bugcheck", "bugcheck", "Bugchecks the system.", KdbpCmdBugCheck
},
177 { "filter", "filter [error|warning|trace|info|level]+|-[componentname|default]", "Enable/disable debug channels", KdbpCmdFilter
},
178 { "set", "set [var] [value]", "Sets var to value or displays value of var.", KdbpCmdSet
},
179 { "dmesg", "dmesg", "Display debug messages on screen, with navigation on pages.", KdbpCmdDmesg
},
180 { "kmsg", "kmsg", "Kernel dmesg. Alias for dmesg.", KdbpCmdDmesg
},
181 { "help", "help", "Display help screen.", KdbpCmdHelp
}
184 /* FUNCTIONS *****************************************************************/
186 /*!\brief Transform a component name to an integer
188 * \param ComponentName The name of the component.
189 * \param ComponentId Receives the component id on success.
191 * \retval TRUE Success.
192 * \retval FALSE Failure.
196 IN PCCH ComponentName
,
197 OUT PULONG ComponentId
)
208 { "DEFAULT", DPFLTR_DEFAULT_ID
},
209 { "SYSTEM", DPFLTR_SYSTEM_ID
},
210 { "SMSS", DPFLTR_SMSS_ID
},
211 { "SETUP", DPFLTR_SETUP_ID
},
212 { "NTFS", DPFLTR_NTFS_ID
},
213 { "FSTUB", DPFLTR_FSTUB_ID
},
214 { "CRASHDUMP", DPFLTR_CRASHDUMP_ID
},
215 { "CDAUDIO", DPFLTR_CDAUDIO_ID
},
216 { "CDROM", DPFLTR_CDROM_ID
},
217 { "CLASSPNP", DPFLTR_CLASSPNP_ID
},
218 { "DISK", DPFLTR_DISK_ID
},
219 { "REDBOOK", DPFLTR_REDBOOK_ID
},
220 { "STORPROP", DPFLTR_STORPROP_ID
},
221 { "SCSIPORT", DPFLTR_SCSIPORT_ID
},
222 { "SCSIMINIPORT", DPFLTR_SCSIMINIPORT_ID
},
223 { "CONFIG", DPFLTR_CONFIG_ID
},
224 { "I8042PRT", DPFLTR_I8042PRT_ID
},
225 { "SERMOUSE", DPFLTR_SERMOUSE_ID
},
226 { "LSERMOUS", DPFLTR_LSERMOUS_ID
},
227 { "KBDHID", DPFLTR_KBDHID_ID
},
228 { "MOUHID", DPFLTR_MOUHID_ID
},
229 { "KBDCLASS", DPFLTR_KBDCLASS_ID
},
230 { "MOUCLASS", DPFLTR_MOUCLASS_ID
},
231 { "TWOTRACK", DPFLTR_TWOTRACK_ID
},
232 { "WMILIB", DPFLTR_WMILIB_ID
},
233 { "ACPI", DPFLTR_ACPI_ID
},
234 { "AMLI", DPFLTR_AMLI_ID
},
235 { "HALIA64", DPFLTR_HALIA64_ID
},
236 { "VIDEO", DPFLTR_VIDEO_ID
},
237 { "SVCHOST", DPFLTR_SVCHOST_ID
},
238 { "VIDEOPRT", DPFLTR_VIDEOPRT_ID
},
239 { "TCPIP", DPFLTR_TCPIP_ID
},
240 { "DMSYNTH", DPFLTR_DMSYNTH_ID
},
241 { "NTOSPNP", DPFLTR_NTOSPNP_ID
},
242 { "FASTFAT", DPFLTR_FASTFAT_ID
},
243 { "SAMSS", DPFLTR_SAMSS_ID
},
244 { "PNPMGR", DPFLTR_PNPMGR_ID
},
245 { "NETAPI", DPFLTR_NETAPI_ID
},
246 { "SCSERVER", DPFLTR_SCSERVER_ID
},
247 { "SCCLIENT", DPFLTR_SCCLIENT_ID
},
248 { "SERIAL", DPFLTR_SERIAL_ID
},
249 { "SERENUM", DPFLTR_SERENUM_ID
},
250 { "UHCD", DPFLTR_UHCD_ID
},
251 { "RPCPROXY", DPFLTR_RPCPROXY_ID
},
252 { "AUTOCHK", DPFLTR_AUTOCHK_ID
},
253 { "DCOMSS", DPFLTR_DCOMSS_ID
},
254 { "UNIMODEM", DPFLTR_UNIMODEM_ID
},
255 { "SIS", DPFLTR_SIS_ID
},
256 { "FLTMGR", DPFLTR_FLTMGR_ID
},
257 { "WMICORE", DPFLTR_WMICORE_ID
},
258 { "BURNENG", DPFLTR_BURNENG_ID
},
259 { "IMAPI", DPFLTR_IMAPI_ID
},
260 { "SXS", DPFLTR_SXS_ID
},
261 { "FUSION", DPFLTR_FUSION_ID
},
262 { "IDLETASK", DPFLTR_IDLETASK_ID
},
263 { "SOFTPCI", DPFLTR_SOFTPCI_ID
},
264 { "TAPE", DPFLTR_TAPE_ID
},
265 { "MCHGR", DPFLTR_MCHGR_ID
},
266 { "IDEP", DPFLTR_IDEP_ID
},
267 { "PCIIDE", DPFLTR_PCIIDE_ID
},
268 { "FLOPPY", DPFLTR_FLOPPY_ID
},
269 { "FDC", DPFLTR_FDC_ID
},
270 { "TERMSRV", DPFLTR_TERMSRV_ID
},
271 { "W32TIME", DPFLTR_W32TIME_ID
},
272 { "PREFETCHER", DPFLTR_PREFETCHER_ID
},
273 { "RSFILTER", DPFLTR_RSFILTER_ID
},
274 { "FCPORT", DPFLTR_FCPORT_ID
},
275 { "PCI", DPFLTR_PCI_ID
},
276 { "DMIO", DPFLTR_DMIO_ID
},
277 { "DMCONFIG", DPFLTR_DMCONFIG_ID
},
278 { "DMADMIN", DPFLTR_DMADMIN_ID
},
279 { "WSOCKTRANSPORT", DPFLTR_WSOCKTRANSPORT_ID
},
280 { "VSS", DPFLTR_VSS_ID
},
281 { "PNPMEM", DPFLTR_PNPMEM_ID
},
282 { "PROCESSOR", DPFLTR_PROCESSOR_ID
},
283 { "DMSERVER", DPFLTR_DMSERVER_ID
},
284 { "SR", DPFLTR_SR_ID
},
285 { "INFINIBAND", DPFLTR_INFINIBAND_ID
},
286 { "IHVDRIVER", DPFLTR_IHVDRIVER_ID
},
287 { "IHVVIDEO", DPFLTR_IHVVIDEO_ID
},
288 { "IHVAUDIO", DPFLTR_IHVAUDIO_ID
},
289 { "IHVNETWORK", DPFLTR_IHVNETWORK_ID
},
290 { "IHVSTREAMING", DPFLTR_IHVSTREAMING_ID
},
291 { "IHVBUS", DPFLTR_IHVBUS_ID
},
292 { "HPS", DPFLTR_HPS_ID
},
293 { "RTLTHREADPOOL", DPFLTR_RTLTHREADPOOL_ID
},
294 { "LDR", DPFLTR_LDR_ID
},
295 { "TCPIP6", DPFLTR_TCPIP6_ID
},
296 { "ISAPNP", DPFLTR_ISAPNP_ID
},
297 { "SHPC", DPFLTR_SHPC_ID
},
298 { "STORPORT", DPFLTR_STORPORT_ID
},
299 { "STORMINIPORT", DPFLTR_STORMINIPORT_ID
},
300 { "PRINTSPOOLER", DPFLTR_PRINTSPOOLER_ID
},
301 { "VSSDYNDISK", DPFLTR_VSSDYNDISK_ID
},
302 { "VERIFIER", DPFLTR_VERIFIER_ID
},
303 { "VDS", DPFLTR_VDS_ID
},
304 { "VDSBAS", DPFLTR_VDSBAS_ID
},
305 { "VDSDYN", DPFLTR_VDSDYN_ID
},
306 { "VDSDYNDR", DPFLTR_VDSDYNDR_ID
},
307 { "VDSLDR", DPFLTR_VDSLDR_ID
},
308 { "VDSUTIL", DPFLTR_VDSUTIL_ID
},
309 { "DFRGIFC", DPFLTR_DFRGIFC_ID
},
310 { "MM", DPFLTR_MM_ID
},
311 { "DFSC", DPFLTR_DFSC_ID
},
312 { "WOW64", DPFLTR_WOW64_ID
},
313 { "ALPC", DPFLTR_ALPC_ID
},
314 { "WDI", DPFLTR_WDI_ID
},
315 { "PERFLIB", DPFLTR_PERFLIB_ID
},
316 { "KTM", DPFLTR_KTM_ID
},
317 { "IOSTRESS", DPFLTR_IOSTRESS_ID
},
318 { "HEAP", DPFLTR_HEAP_ID
},
319 { "WHEA", DPFLTR_WHEA_ID
},
320 { "USERGDI", DPFLTR_USERGDI_ID
},
321 { "MMCSS", DPFLTR_MMCSS_ID
},
322 { "TPM", DPFLTR_TPM_ID
},
323 { "THREADORDER", DPFLTR_THREADORDER_ID
},
324 { "ENVIRON", DPFLTR_ENVIRON_ID
},
325 { "EMS", DPFLTR_EMS_ID
},
326 { "WDT", DPFLTR_WDT_ID
},
327 { "FVEVOL", DPFLTR_FVEVOL_ID
},
328 { "NDIS", DPFLTR_NDIS_ID
},
329 { "NVCTRACE", DPFLTR_NVCTRACE_ID
},
330 { "LUAFV", DPFLTR_LUAFV_ID
},
331 { "APPCOMPAT", DPFLTR_APPCOMPAT_ID
},
332 { "USBSTOR", DPFLTR_USBSTOR_ID
},
333 { "SBP2PORT", DPFLTR_SBP2PORT_ID
},
334 { "COVERAGE", DPFLTR_COVERAGE_ID
},
335 { "CACHEMGR", DPFLTR_CACHEMGR_ID
},
336 { "MOUNTMGR", DPFLTR_MOUNTMGR_ID
},
337 { "CFR", DPFLTR_CFR_ID
},
338 { "TXF", DPFLTR_TXF_ID
},
339 { "KSECDD", DPFLTR_KSECDD_ID
},
340 { "FLTREGRESS", DPFLTR_FLTREGRESS_ID
},
341 { "MPIO", DPFLTR_MPIO_ID
},
342 { "MSDSM", DPFLTR_MSDSM_ID
},
343 { "UDFS", DPFLTR_UDFS_ID
},
344 { "PSHED", DPFLTR_PSHED_ID
},
345 { "STORVSP", DPFLTR_STORVSP_ID
},
346 { "LSASS", DPFLTR_LSASS_ID
},
347 { "SSPICLI", DPFLTR_SSPICLI_ID
},
348 { "CNG", DPFLTR_CNG_ID
},
349 { "EXFAT", DPFLTR_EXFAT_ID
},
350 { "FILETRACE", DPFLTR_FILETRACE_ID
},
351 { "XSAVE", DPFLTR_XSAVE_ID
},
352 { "SE", DPFLTR_SE_ID
},
353 { "DRIVEEXTENDER", DPFLTR_DRIVEEXTENDER_ID
},
356 for (i
= 0; i
< sizeof(ComponentTable
) / sizeof(ComponentTable
[0]); i
++)
358 if (_stricmp(ComponentName
, ComponentTable
[i
].Name
) == 0)
360 *ComponentId
= ComponentTable
[i
].Id
;
368 /*!\brief Evaluates an expression...
370 * Much like KdbpRpnEvaluateExpression, but prints the error message (if any)
371 * at the given offset.
373 * \param Expression Expression to evaluate.
374 * \param ErrOffset Offset (in characters) to print the error message at.
375 * \param Result Receives the result on success.
377 * \retval TRUE Success.
378 * \retval FALSE Failure.
381 KdbpEvaluateExpression(
384 OUT PULONGLONG Result
)
386 static CHAR ErrMsgBuffer
[130] = "^ ";
387 LONG ExpressionErrOffset
= -1;
388 PCHAR ErrMsg
= ErrMsgBuffer
;
391 Ok
= KdbpRpnEvaluateExpression(Expression
, KdbCurrentTrapFrame
, Result
,
392 &ExpressionErrOffset
, ErrMsgBuffer
+ 2);
395 if (ExpressionErrOffset
>= 0)
396 ExpressionErrOffset
+= ErrOffset
;
400 KdbpPrint("%*s%s\n", ExpressionErrOffset
, "", ErrMsg
);
406 /*!\brief Evaluates an expression and displays the result.
409 KdbpCmdEvalExpression(
414 ULONGLONG Result
= 0;
421 KdbpPrint("?: Argument required\n");
425 /* Put the arguments back together */
427 for (i
= 1; i
< Argc
; i
++)
429 len
= strlen(Argv
[i
]);
433 /* Evaluate the expression */
434 Ok
= KdbpEvaluateExpression(Argv
[1], sizeof("kdb:> ")-1 + (Argv
[1]-Argv
[0]), &Result
);
437 if (Result
> 0x00000000ffffffffLL
)
439 if (Result
& 0x8000000000000000LL
)
440 KdbpPrint("0x%016I64x %20I64u %20I64d\n", Result
, Result
, Result
);
442 KdbpPrint("0x%016I64x %20I64u\n", Result
, Result
);
448 if (ul
<= 0xff && ul
>= 0x80)
449 l
= (LONG
)((CHAR
)ul
);
450 else if (ul
<= 0xffff && ul
>= 0x8000)
451 l
= (LONG
)((SHORT
)ul
);
456 KdbpPrint("0x%08lx %10lu %10ld\n", ul
, ul
, l
);
458 KdbpPrint("0x%08lx %10lu\n", ul
, ul
);
467 /*!\brief Print a struct
470 KdbpPrintStructInternal
475 PROSSYM_AGGREGATE Aggregate
)
479 PROSSYM_AGGREGATE_MEMBER Member
;
480 ULONG IndentLen
= strlen(Indent
);
481 ROSSYM_AGGREGATE MemberAggregate
= {0 };
483 for (i
= 0; i
< Aggregate
->NumElements
; i
++) {
484 Member
= &Aggregate
->Elements
[i
];
485 KdbpPrint("%s%p+%x: %s", Indent
, ((PCHAR
)BaseAddress
) + Member
->BaseOffset
, Member
->Size
, Member
->Name
? Member
->Name
: "<anoymous>");
487 if (!strcmp(Member
->Type
, "_UNICODE_STRING")) {
488 KdbpPrint("\"%wZ\"\n", ((PCHAR
)BaseAddress
) + Member
->BaseOffset
);
490 } else if (!strcmp(Member
->Type
, "PUNICODE_STRING")) {
491 KdbpPrint("\"%wZ\"\n", *(((PUNICODE_STRING
*)((PCHAR
)BaseAddress
) + Member
->BaseOffset
)));
494 switch (Member
->Size
) {
500 if (NT_SUCCESS(KdbpSafeReadMemory(&Result
, ((PCHAR
)BaseAddress
) + Member
->BaseOffset
, Member
->Size
))) {
502 Result
>>= Member
->FirstBit
;
503 Result
&= ((1 << Member
->Bits
) - 1);
505 KdbpPrint(" %lx\n", Result
);
511 if (Member
->Size
< 8) {
512 if (NT_SUCCESS(KdbpSafeReadMemory(&Result
, ((PCHAR
)BaseAddress
) + Member
->BaseOffset
, Member
->Size
))) {
514 for (j
= 0; j
< Member
->Size
; j
++) {
515 KdbpPrint(" %02x", (int)(Result
& 0xff));
518 } else goto readfail
;
520 KdbpPrint(" %s @ %p {\n", Member
->Type
, ((PCHAR
)BaseAddress
) + Member
->BaseOffset
);
521 Indent
[IndentLen
] = ' ';
522 if (RosSymAggregate(Info
, Member
->Type
, &MemberAggregate
)) {
523 KdbpPrintStructInternal(Info
, Indent
, DoRead
, ((PCHAR
)BaseAddress
) + Member
->BaseOffset
, &MemberAggregate
);
524 RosSymFreeAggregate(&MemberAggregate
);
526 Indent
[IndentLen
] = 0;
527 KdbpPrint("%s}\n", Indent
);
533 if (Member
->Size
<= 8) {
536 KdbpPrint(" %s @ %x {\n", Member
->Type
, Member
->BaseOffset
);
537 Indent
[IndentLen
] = ' ';
538 if (RosSymAggregate(Info
, Member
->Type
, &MemberAggregate
)) {
539 KdbpPrintStructInternal(Info
, Indent
, DoRead
, BaseAddress
, &MemberAggregate
);
540 RosSymFreeAggregate(&MemberAggregate
);
542 Indent
[IndentLen
] = 0;
543 KdbpPrint("%s}\n", Indent
);
549 PROSSYM_INFO
KdbpSymFindCachedFile(PUNICODE_STRING ModName
);
557 ULONGLONG Result
= 0;
558 PVOID BaseAddress
= 0;
559 ROSSYM_AGGREGATE Aggregate
= {0};
560 UNICODE_STRING ModName
= {0};
561 ANSI_STRING AnsiName
= {0};
562 CHAR Indent
[100] = {0};
565 if (Argc
< 3) goto end
;
566 AnsiName
.Length
= AnsiName
.MaximumLength
= strlen(Argv
[1]);
567 AnsiName
.Buffer
= Argv
[1];
568 RtlAnsiStringToUnicodeString(&ModName
, &AnsiName
, TRUE
);
569 Info
= KdbpSymFindCachedFile(&ModName
);
571 if (!Info
|| !RosSymAggregate(Info
, Argv
[2], &Aggregate
)) {
572 DPRINT1("Could not get aggregate\n");
576 // Get an argument for location if it was given
579 PCHAR ArgStart
= Argv
[3];
580 DPRINT1("Trying to get expression\n");
581 for (i
= 3; i
< Argc
- 1; i
++)
583 len
= strlen(Argv
[i
]);
587 /* Evaluate the expression */
588 DPRINT1("Arg: %s\n", ArgStart
);
589 if (KdbpEvaluateExpression(ArgStart
, strlen(ArgStart
), &Result
)) {
590 BaseAddress
= (PVOID
)(ULONG_PTR
)Result
;
591 DPRINT1("BaseAddress: %p\n", BaseAddress
);
594 DPRINT1("BaseAddress %p\n", BaseAddress
);
595 KdbpPrintStructInternal(Info
, Indent
, !!BaseAddress
, BaseAddress
, &Aggregate
);
597 RosSymFreeAggregate(&Aggregate
);
598 RtlFreeUnicodeString(&ModName
);
603 /*!\brief Display list of active debug channels
610 ULONG i
, j
, ComponentId
, Level
;
611 ULONG set
= DPFLTR_MASK
, clear
= DPFLTR_MASK
;
622 { "error", 1 << DPFLTR_ERROR_LEVEL
},
623 { "warning", 1 << DPFLTR_WARNING_LEVEL
},
624 { "trace", 1 << DPFLTR_TRACE_LEVEL
},
625 { "info", 1 << DPFLTR_INFO_LEVEL
},
628 for (i
= 1; i
< Argc
; i
++)
631 p
= opt
+ strcspn(opt
, "+-");
632 if (!p
[0]) p
= opt
; /* assume it's a debug channel name */
636 for (j
= 0; j
< sizeof(debug_classes
) / sizeof(debug_classes
[0]); j
++)
638 SIZE_T len
= strlen(debug_classes
[j
].Name
);
639 if (len
!= (p
- opt
))
641 if (_strnicmp(opt
, debug_classes
[j
].Name
, len
) == 0) /* found it */
644 set
|= debug_classes
[j
].Level
;
646 clear
|= debug_classes
[j
].Level
;
650 if (j
== sizeof(debug_classes
) / sizeof(debug_classes
[0]))
652 Level
= strtoul(opt
, &pend
, 0);
655 KdbpPrint("filter: bad class name '%.*s'\n", p
- opt
, opt
);
671 if (*p
== '+' || *p
== '-')
674 if (!KdbpGetComponentId(p
, &ComponentId
))
676 KdbpPrint("filter: '%s' is not a valid component name!\n", p
);
680 /* Get current mask value */
681 NtSetDebugFilterState(ComponentId
, set
, TRUE
);
682 NtSetDebugFilterState(ComponentId
, clear
, FALSE
);
688 /*!\brief Disassembles 10 instructions at eip or given address or
689 * displays 16 dwords from memory at given address.
699 ULONGLONG Result
= 0;
700 ULONG_PTR Address
= KdbCurrentTrapFrame
->Tf
.Eip
;
703 if (Argv
[0][0] == 'x') /* display memory */
705 else /* disassemble */
710 /* Check for [L count] part */
712 if (strcmp(Argv
[Argc
-2], "L") == 0)
714 ul
= strtoul(Argv
[Argc
-1], NULL
, 0);
721 else if (Argv
[Argc
-1][0] == 'L')
723 ul
= strtoul(Argv
[Argc
-1] + 1, NULL
, 0);
731 /* Put the remaining arguments back together */
733 for (ul
= 1; ul
< Argc
; ul
++)
735 Argv
[ul
][strlen(Argv
[ul
])] = ' ';
740 /* Evaluate the expression */
743 if (!KdbpEvaluateExpression(Argv
[1], sizeof("kdb:> ")-1 + (Argv
[1]-Argv
[0]), &Result
))
746 if (Result
> (ULONGLONG
)(~((ULONG_PTR
)0)))
747 KdbpPrint("Warning: Address %I64x is beeing truncated\n",Result
);
749 Address
= (ULONG_PTR
)Result
;
751 else if (Argv
[0][0] == 'x')
753 KdbpPrint("x: Address argument required.\n");
757 if (Argv
[0][0] == 'x')
764 if (!KdbSymPrintAddress((PVOID
)Address
, NULL
))
765 KdbpPrint("<%x>:", Address
);
774 if (!NT_SUCCESS(KdbpSafeReadMemory(&ul
, (PVOID
)Address
, sizeof(ul
))))
775 KdbpPrint(" ????????");
777 KdbpPrint(" %08x", ul
);
779 Address
+= sizeof(ul
);
790 if (!KdbSymPrintAddress((PVOID
)Address
, NULL
))
791 KdbpPrint("<%08x>: ", Address
);
795 InstLen
= KdbpDisassemble(Address
, KdbUseIntelSyntax
);
798 KdbpPrint("<INVALID>\n");
810 /*!\brief Displays CPU registers.
817 PKTRAP_FRAME Tf
= &KdbCurrentTrapFrame
->Tf
;
819 static const PCHAR EflagsBits
[32] = { " CF", NULL
, " PF", " BIT3", " AF", " BIT5",
820 " ZF", " SF", " TF", " IF", " DF", " OF",
821 NULL
, NULL
, " NT", " BIT15", " RF", " VF",
822 " AC", " VIF", " VIP", " ID", " BIT22",
823 " BIT23", " BIT24", " BIT25", " BIT26",
824 " BIT27", " BIT28", " BIT29", " BIT30",
827 if (Argv
[0][0] == 'r') /* regs */
829 KdbpPrint("CS:EIP 0x%04x:0x%08x\n"
830 "SS:ESP 0x%04x:0x%08x\n"
831 " EAX 0x%08x EBX 0x%08x\n"
832 " ECX 0x%08x EDX 0x%08x\n"
833 " ESI 0x%08x EDI 0x%08x\n"
835 Tf
->SegCs
& 0xFFFF, Tf
->Eip
,
836 Tf
->HardwareSegSs
, Tf
->HardwareEsp
,
841 KdbpPrint("EFLAGS 0x%08x ", Tf
->EFlags
);
843 for (i
= 0; i
< 32; i
++)
847 if ((Tf
->EFlags
& (1 << 1)) == 0)
852 KdbpPrint(" IOPL%d", (Tf
->EFlags
>> 12) & 3);
857 else if ((Tf
->EFlags
& (1 << i
)) != 0)
859 KdbpPrint(EflagsBits
[i
]);
865 else if (Argv
[0][0] == 'c') /* cregs */
867 ULONG Cr0
, Cr2
, Cr3
, Cr4
;
868 KDESCRIPTOR Gdtr
= {0, 0, 0}, Idtr
= {0, 0, 0};
870 static const PCHAR Cr0Bits
[32] = { " PE", " MP", " EM", " TS", " ET", " NE", NULL
, NULL
,
871 NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
,
872 " WP", NULL
, " AM", NULL
, NULL
, NULL
, NULL
, NULL
,
873 NULL
, NULL
, NULL
, NULL
, NULL
, " NW", " CD", " PG" };
874 static const PCHAR Cr4Bits
[32] = { " VME", " PVI", " TSD", " DE", " PSE", " PAE", " MCE", " PGE",
875 " PCE", " OSFXSR", " OSXMMEXCPT", NULL
, NULL
, NULL
, NULL
, NULL
,
876 NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
,
877 NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
};
879 Cr0
= KdbCurrentTrapFrame
->Cr0
;
880 Cr2
= KdbCurrentTrapFrame
->Cr2
;
881 Cr3
= KdbCurrentTrapFrame
->Cr3
;
882 Cr4
= KdbCurrentTrapFrame
->Cr4
;
884 /* Get descriptor table regs */
885 Ke386GetGlobalDescriptorTable(&Gdtr
.Limit
);
886 Ldtr
= Ke386GetLocalDescriptorTable();
889 /* Display the control registers */
890 KdbpPrint("CR0 0x%08x ", Cr0
);
892 for (i
= 0; i
< 32; i
++)
897 if ((Cr0
& (1 << i
)) != 0)
898 KdbpPrint(Cr0Bits
[i
]);
901 KdbpPrint("\nCR2 0x%08x\n", Cr2
);
902 KdbpPrint("CR3 0x%08x Pagedir-Base 0x%08x %s%s\n", Cr3
, (Cr3
& 0xfffff000),
903 (Cr3
& (1 << 3)) ? " PWT" : "", (Cr3
& (1 << 4)) ? " PCD" : "" );
904 KdbpPrint("CR4 0x%08x ", Cr4
);
906 for (i
= 0; i
< 32; i
++)
911 if ((Cr4
& (1 << i
)) != 0)
912 KdbpPrint(Cr4Bits
[i
]);
915 /* Display the descriptor table regs */
916 KdbpPrint("\nGDTR Base 0x%08x Size 0x%04x\n", Gdtr
.Base
, Gdtr
.Limit
);
917 KdbpPrint("LDTR 0x%04x\n", Ldtr
);
918 KdbpPrint("IDTR Base 0x%08x Size 0x%04x\n", Idtr
.Base
, Idtr
.Limit
);
920 else if (Argv
[0][0] == 's') /* sregs */
922 KdbpPrint("CS 0x%04x Index 0x%04x %cDT RPL%d\n",
923 Tf
->SegCs
& 0xffff, (Tf
->SegCs
& 0xffff) >> 3,
924 (Tf
->SegCs
& (1 << 2)) ? 'L' : 'G', Tf
->SegCs
& 3);
925 KdbpPrint("DS 0x%04x Index 0x%04x %cDT RPL%d\n",
926 Tf
->SegDs
, Tf
->SegDs
>> 3, (Tf
->SegDs
& (1 << 2)) ? 'L' : 'G', Tf
->SegDs
& 3);
927 KdbpPrint("ES 0x%04x Index 0x%04x %cDT RPL%d\n",
928 Tf
->SegEs
, Tf
->SegEs
>> 3, (Tf
->SegEs
& (1 << 2)) ? 'L' : 'G', Tf
->SegEs
& 3);
929 KdbpPrint("FS 0x%04x Index 0x%04x %cDT RPL%d\n",
930 Tf
->SegFs
, Tf
->SegFs
>> 3, (Tf
->SegFs
& (1 << 2)) ? 'L' : 'G', Tf
->SegFs
& 3);
931 KdbpPrint("GS 0x%04x Index 0x%04x %cDT RPL%d\n",
932 Tf
->SegGs
, Tf
->SegGs
>> 3, (Tf
->SegGs
& (1 << 2)) ? 'L' : 'G', Tf
->SegGs
& 3);
933 KdbpPrint("SS 0x%04x Index 0x%04x %cDT RPL%d\n",
934 Tf
->HardwareSegSs
, Tf
->HardwareSegSs
>> 3, (Tf
->HardwareSegSs
& (1 << 2)) ? 'L' : 'G', Tf
->HardwareSegSs
& 3);
938 ASSERT(Argv
[0][0] == 'd');
939 KdbpPrint("DR0 0x%08x\n"
945 Tf
->Dr0
, Tf
->Dr1
, Tf
->Dr2
, Tf
->Dr3
,
953 KdbpTrapFrameFromPrevTss(
954 PKTRAP_FRAME TrapFrame
)
962 Ke386GetGlobalDescriptorTable(&Gdtr
.Limit
);
965 if ((Sel
& (sizeof(KGDTENTRY
) - 1)) ||
966 (Sel
< sizeof(KGDTENTRY
)) ||
967 (Sel
+ sizeof(KGDTENTRY
) - 1 > Gdtr
.Limit
))
970 if (!NT_SUCCESS(KdbpSafeReadMemory(&Desc
,
971 (PVOID
)(Gdtr
.Base
+ Sel
),
975 if (Desc
.HighWord
.Bits
.Type
!= 0xB)
978 Tss
= (PKTSS
)(ULONG_PTR
)(Desc
.BaseLow
|
979 Desc
.HighWord
.Bytes
.BaseMid
<< 16 |
980 Desc
.HighWord
.Bytes
.BaseHi
<< 24);
982 if (!NT_SUCCESS(KdbpSafeReadMemory(&Sel
,
983 (PVOID
)&Tss
->Backlink
,
987 if ((Sel
& (sizeof(KGDTENTRY
) - 1)) ||
988 (Sel
< sizeof(KGDTENTRY
)) ||
989 (Sel
+ sizeof(KGDTENTRY
) - 1 > Gdtr
.Limit
))
992 if (!NT_SUCCESS(KdbpSafeReadMemory(&Desc
,
993 (PVOID
)(Gdtr
.Base
+ Sel
),
997 if (Desc
.HighWord
.Bits
.Type
!= 0xB)
1000 Tss
= (PKTSS
)(ULONG_PTR
)(Desc
.BaseLow
|
1001 Desc
.HighWord
.Bytes
.BaseMid
<< 16 |
1002 Desc
.HighWord
.Bytes
.BaseHi
<< 24);
1004 if (!NT_SUCCESS(KdbpSafeReadMemory(&Eip
,
1006 sizeof(ULONG_PTR
))))
1009 if (!NT_SUCCESS(KdbpSafeReadMemory(&Ebp
,
1011 sizeof(ULONG_PTR
))))
1014 TrapFrame
->Eip
= Eip
;
1015 TrapFrame
->Ebp
= Ebp
;
1019 VOID __cdecl
KiTrap02(VOID
);
1020 VOID FASTCALL
KiTrap03Handler(IN PKTRAP_FRAME
);
1021 VOID __cdecl
KiTrap08(VOID
);
1022 VOID __cdecl
KiTrap09(VOID
);
1025 KdbpInNmiOrDoubleFaultHandler(
1028 return (Address
> (ULONG_PTR
)KiTrap02
&& Address
< (ULONG_PTR
)KiTrap03Handler
) ||
1029 (Address
> (ULONG_PTR
)KiTrap08
&& Address
< (ULONG_PTR
)KiTrap09
);
1032 /*!\brief Displays a backtrace.
1040 ULONGLONG Result
= 0;
1041 ULONG_PTR Frame
= KdbCurrentTrapFrame
->Tf
.Ebp
;
1043 KTRAP_FRAME TrapFrame
;
1047 /* Check for [L count] part */
1050 if (strcmp(Argv
[Argc
-2], "L") == 0)
1052 ul
= strtoul(Argv
[Argc
-1], NULL
, 0);
1058 else if (Argv
[Argc
-1][0] == 'L')
1060 ul
= strtoul(Argv
[Argc
-1] + 1, NULL
, 0);
1067 /* Put the remaining arguments back together */
1069 for (ul
= 1; ul
< Argc
; ul
++)
1071 Argv
[ul
][strlen(Argv
[ul
])] = ' ';
1076 /* Check if frame addr or thread id is given. */
1079 if (Argv
[1][0] == '*')
1083 /* Evaluate the expression */
1084 if (!KdbpEvaluateExpression(Argv
[1], sizeof("kdb:> ")-1 + (Argv
[1]-Argv
[0]), &Result
))
1087 if (Result
> (ULONGLONG
)(~((ULONG_PTR
)0)))
1088 KdbpPrint("Warning: Address %I64x is beeing truncated\n",Result
);
1090 Frame
= (ULONG_PTR
)Result
;
1094 KdbpPrint("Thread backtrace not supported yet!\n");
1100 KdbpPrint("Eip:\n");
1102 /* Try printing the function at EIP */
1103 if (!KdbSymPrintAddress((PVOID
)KdbCurrentTrapFrame
->Tf
.Eip
, &KdbCurrentTrapFrame
->Tf
))
1104 KdbpPrint("<%08x>\n", KdbCurrentTrapFrame
->Tf
.Eip
);
1109 TrapFrame
= KdbCurrentTrapFrame
->Tf
;
1110 KdbpPrint("Frames:\n");
1114 BOOLEAN GotNextFrame
;
1119 if (!NT_SUCCESS(KdbpSafeReadMemory(&Address
, (PVOID
)(Frame
+ sizeof(ULONG_PTR
)), sizeof (ULONG_PTR
))))
1121 KdbpPrint("Couldn't access memory at 0x%p!\n", Frame
+ sizeof(ULONG_PTR
));
1125 if ((GotNextFrame
= NT_SUCCESS(KdbpSafeReadMemory(&Frame
, (PVOID
)Frame
, sizeof (ULONG_PTR
)))))
1126 TrapFrame
.Ebp
= Frame
;
1128 /* Print the location of the call instruction */
1129 if (!KdbSymPrintAddress((PVOID
)(Address
- 5), &TrapFrame
))
1130 KdbpPrint("<%08x>\n", Address
);
1134 if (KdbOutputAborted
) break;
1139 if (KdbpInNmiOrDoubleFaultHandler(Address
))
1141 if ((GotNextFrame
= KdbpTrapFrameFromPrevTss(&TrapFrame
)))
1143 Address
= TrapFrame
.Eip
;
1144 Frame
= TrapFrame
.Ebp
;
1146 if (!KdbSymPrintAddress((PVOID
)Address
, &TrapFrame
))
1147 KdbpPrint("<%08x>\n", Address
);
1155 KdbpPrint("Couldn't access memory at 0x%p!\n", Frame
);
1163 /*!\brief Continues execution of the system/leaves KDB.
1170 /* Exit the main loop */
1174 /*!\brief Continues execution of the system/leaves KDB.
1185 Count
= strtoul(Argv
[1], NULL
, 0);
1188 KdbpPrint("%s: Integer argument required\n", Argv
[0]);
1193 if (Argv
[0][0] == 'n')
1194 KdbSingleStepOver
= TRUE
;
1196 KdbSingleStepOver
= FALSE
;
1198 /* Set the number of single steps and return to the interrupted code. */
1199 KdbNumSingleSteps
= Count
;
1204 /*!\brief Lists breakpoints.
1207 KdbpCmdBreakPointList(
1212 ULONG_PTR Address
= 0;
1213 KDB_BREAKPOINT_TYPE Type
= 0;
1214 KDB_ACCESS_TYPE AccessType
= 0;
1217 BOOLEAN Enabled
= FALSE
;
1218 BOOLEAN Global
= FALSE
;
1219 PEPROCESS Process
= NULL
;
1220 PCHAR str1
, str2
, ConditionExpr
, GlobalOrLocal
;
1223 l
= KdbpGetNextBreakPointNr(0);
1226 KdbpPrint("No breakpoints.\n");
1230 KdbpPrint("Breakpoints:\n");
1233 if (!KdbpGetBreakPointInfo(l
, &Address
, &Type
, &Size
, &AccessType
, &DebugReg
,
1234 &Enabled
, &Global
, &Process
, &ConditionExpr
))
1239 if (l
== KdbLastBreakPointNr
)
1252 GlobalOrLocal
= " global";
1256 GlobalOrLocal
= Buffer
;
1257 sprintf(Buffer
, " PID 0x%08lx",
1258 (ULONG
)(Process
? Process
->UniqueProcessId
: INVALID_HANDLE_VALUE
));
1261 if (Type
== KdbBreakPointSoftware
|| Type
== KdbBreakPointTemporary
)
1263 KdbpPrint(" %s%03d BPX 0x%08x%s%s%s%s%s\n",
1265 Enabled
? "" : " disabled",
1267 ConditionExpr
? " IF " : "",
1268 ConditionExpr
? ConditionExpr
: "",
1271 else if (Type
== KdbBreakPointHardware
)
1275 KdbpPrint(" %s%03d BPM 0x%08x %-5s %-5s disabled%s%s%s%s\n", str1
, l
, Address
,
1276 KDB_ACCESS_TYPE_TO_STRING(AccessType
),
1277 Size
== 1 ? "byte" : (Size
== 2 ? "word" : "dword"),
1279 ConditionExpr
? " IF " : "",
1280 ConditionExpr
? ConditionExpr
: "",
1285 KdbpPrint(" %s%03d BPM 0x%08x %-5s %-5s DR%d%s%s%s%s\n", str1
, l
, Address
,
1286 KDB_ACCESS_TYPE_TO_STRING(AccessType
),
1287 Size
== 1 ? "byte" : (Size
== 2 ? "word" : "dword"),
1290 ConditionExpr
? " IF " : "",
1291 ConditionExpr
? ConditionExpr
: "",
1296 while ((l
= KdbpGetNextBreakPointNr(l
+1)) >= 0);
1301 /*!\brief Enables, disables or clears a breakpoint.
1304 KdbpCmdEnableDisableClearBreakPoint(
1313 KdbpPrint("%s: argument required\n", Argv
[0]);
1318 BreakPointNr
= strtoul(Argv
[1], &pend
, 0);
1319 if (pend
== Argv
[1] || *pend
!= '\0')
1321 KdbpPrint("%s: integer argument required\n", Argv
[0]);
1325 if (Argv
[0][1] == 'e') /* enable */
1327 KdbpEnableBreakPoint(BreakPointNr
, NULL
);
1329 else if (Argv
[0][1] == 'd') /* disable */
1331 KdbpDisableBreakPoint(BreakPointNr
, NULL
);
1335 ASSERT(Argv
[0][1] == 'c');
1336 KdbpDeleteBreakPoint(BreakPointNr
, NULL
);
1342 /*!\brief Sets a software or hardware (memory) breakpoint at the given address.
1345 KdbpCmdBreakPoint(ULONG Argc
, PCHAR Argv
[])
1347 ULONGLONG Result
= 0;
1349 KDB_BREAKPOINT_TYPE Type
;
1351 KDB_ACCESS_TYPE AccessType
= 0;
1352 ULONG AddressArgIndex
, i
;
1353 LONG ConditionArgIndex
;
1354 BOOLEAN Global
= TRUE
;
1356 if (Argv
[0][2] == 'x') /* software breakpoint */
1360 KdbpPrint("bpx: Address argument required.\n");
1364 AddressArgIndex
= 1;
1365 Type
= KdbBreakPointSoftware
;
1367 else /* memory breakpoint */
1369 ASSERT(Argv
[0][2] == 'm');
1373 KdbpPrint("bpm: Access type argument required (one of r, w, rw, x)\n");
1377 if (_stricmp(Argv
[1], "x") == 0)
1378 AccessType
= KdbAccessExec
;
1379 else if (_stricmp(Argv
[1], "r") == 0)
1380 AccessType
= KdbAccessRead
;
1381 else if (_stricmp(Argv
[1], "w") == 0)
1382 AccessType
= KdbAccessWrite
;
1383 else if (_stricmp(Argv
[1], "rw") == 0)
1384 AccessType
= KdbAccessReadWrite
;
1387 KdbpPrint("bpm: Unknown access type '%s'\n", Argv
[1]);
1393 KdbpPrint("bpm: %s argument required.\n", AccessType
== KdbAccessExec
? "Address" : "Memory size");
1397 AddressArgIndex
= 3;
1398 if (_stricmp(Argv
[2], "byte") == 0)
1400 else if (_stricmp(Argv
[2], "word") == 0)
1402 else if (_stricmp(Argv
[2], "dword") == 0)
1404 else if (AccessType
== KdbAccessExec
)
1411 KdbpPrint("bpm: Unknown memory size '%s'\n", Argv
[2]);
1415 if (Argc
<= AddressArgIndex
)
1417 KdbpPrint("bpm: Address argument required.\n");
1421 Type
= KdbBreakPointHardware
;
1424 /* Put the arguments back together */
1425 ConditionArgIndex
= -1;
1426 for (i
= AddressArgIndex
; i
< (Argc
-1); i
++)
1428 if (strcmp(Argv
[i
+1], "IF") == 0) /* IF found */
1430 ConditionArgIndex
= i
+ 2;
1431 if ((ULONG
)ConditionArgIndex
>= Argc
)
1433 KdbpPrint("%s: IF requires condition expression.\n", Argv
[0]);
1437 for (i
= ConditionArgIndex
; i
< (Argc
-1); i
++)
1438 Argv
[i
][strlen(Argv
[i
])] = ' ';
1443 Argv
[i
][strlen(Argv
[i
])] = ' ';
1446 /* Evaluate the address expression */
1447 if (!KdbpEvaluateExpression(Argv
[AddressArgIndex
],
1448 sizeof("kdb:> ")-1 + (Argv
[AddressArgIndex
]-Argv
[0]),
1454 if (Result
> (ULONGLONG
)(~((ULONG_PTR
)0)))
1455 KdbpPrint("%s: Warning: Address %I64x is beeing truncated\n", Argv
[0],Result
);
1457 Address
= (ULONG_PTR
)Result
;
1459 KdbpInsertBreakPoint(Address
, Type
, Size
, AccessType
,
1460 (ConditionArgIndex
< 0) ? NULL
: Argv
[ConditionArgIndex
],
1466 /*!\brief Lists threads or switches to another thread context.
1474 PETHREAD Thread
= NULL
;
1475 PEPROCESS Process
= NULL
;
1476 BOOLEAN ReferencedThread
= FALSE
, ReferencedProcess
= FALSE
;
1481 PCHAR State
, pend
, str1
, str2
;
1482 static const PCHAR ThreadStateToString
[DeferredReady
+1] =
1484 "Initialized", "Ready", "Running",
1485 "Standby", "Terminated", "Waiting",
1486 "Transition", "DeferredReady"
1489 ASSERT(KdbCurrentProcess
);
1491 if (Argc
>= 2 && _stricmp(Argv
[1], "list") == 0)
1493 Process
= KdbCurrentProcess
;
1497 ul
= strtoul(Argv
[2], &pend
, 0);
1498 if (Argv
[2] == pend
)
1500 KdbpPrint("thread: '%s' is not a valid process id!\n", Argv
[2]);
1504 if (!NT_SUCCESS(PsLookupProcessByProcessId((PVOID
)ul
, &Process
)))
1506 KdbpPrint("thread: Invalid process id!\n");
1510 /* Remember our reference */
1511 ReferencedProcess
= TRUE
;
1514 Entry
= Process
->ThreadListHead
.Flink
;
1515 if (Entry
== &Process
->ThreadListHead
)
1518 KdbpPrint("No threads in process 0x%08x!\n", ul
);
1520 KdbpPrint("No threads in current process!\n");
1522 if (ReferencedProcess
)
1523 ObDereferenceObject(Process
);
1528 KdbpPrint(" TID State Prior. Affinity EBP EIP\n");
1531 Thread
= CONTAINING_RECORD(Entry
, ETHREAD
, ThreadListEntry
);
1533 if (Thread
== KdbCurrentThread
)
1544 if (!Thread
->Tcb
.InitialStack
)
1546 /* Thread has no kernel stack (probably terminated) */
1550 else if (Thread
->Tcb
.TrapFrame
)
1552 if (Thread
->Tcb
.TrapFrame
->PreviousPreviousMode
== KernelMode
)
1553 Esp
= (PULONG
)Thread
->Tcb
.TrapFrame
->TempEsp
;
1555 Esp
= (PULONG
)Thread
->Tcb
.TrapFrame
->HardwareEsp
;
1557 Ebp
= (PULONG
)Thread
->Tcb
.TrapFrame
->Ebp
;
1558 Eip
= Thread
->Tcb
.TrapFrame
->Eip
;
1562 Esp
= (PULONG
)Thread
->Tcb
.KernelStack
;
1563 Ebp
= (PULONG
)Esp
[4];
1566 if (Ebp
) /* FIXME: Should we attach to the process to read Ebp[1]? */
1567 KdbpSafeReadMemory(&Eip
, Ebp
+ 1, sizeof (Eip
));
1570 if (Thread
->Tcb
.State
< (DeferredReady
+ 1))
1571 State
= ThreadStateToString
[Thread
->Tcb
.State
];
1575 KdbpPrint(" %s0x%08x %-11s %3d 0x%08x 0x%08x 0x%08x%s\n",
1577 Thread
->Cid
.UniqueThread
,
1579 Thread
->Tcb
.Priority
,
1580 Thread
->Tcb
.Affinity
,
1585 Entry
= Entry
->Flink
;
1587 while (Entry
!= &Process
->ThreadListHead
);
1589 /* Release our reference, if any */
1590 if (ReferencedProcess
)
1591 ObDereferenceObject(Process
);
1593 else if (Argc
>= 2 && _stricmp(Argv
[1], "attach") == 0)
1597 KdbpPrint("thread attach: thread id argument required!\n");
1601 ul
= strtoul(Argv
[2], &pend
, 0);
1602 if (Argv
[2] == pend
)
1604 KdbpPrint("thread attach: '%s' is not a valid thread id!\n", Argv
[2]);
1608 if (!KdbpAttachToThread((PVOID
)ul
))
1613 KdbpPrint("Attached to thread 0x%08x.\n", ul
);
1617 Thread
= KdbCurrentThread
;
1621 ul
= strtoul(Argv
[1], &pend
, 0);
1622 if (Argv
[1] == pend
)
1624 KdbpPrint("thread: '%s' is not a valid thread id!\n", Argv
[1]);
1628 if (!NT_SUCCESS(PsLookupThreadByThreadId((PVOID
)ul
, &Thread
)))
1630 KdbpPrint("thread: Invalid thread id!\n");
1634 /* Remember our reference */
1635 ReferencedThread
= TRUE
;
1638 if (Thread
->Tcb
.State
< (DeferredReady
+ 1))
1639 State
= ThreadStateToString
[Thread
->Tcb
.State
];
1645 " State: %s (0x%x)\n"
1647 " Affinity: 0x%08x\n"
1648 " Initial Stack: 0x%08x\n"
1649 " Stack Limit: 0x%08x\n"
1650 " Stack Base: 0x%08x\n"
1651 " Kernel Stack: 0x%08x\n"
1652 " Trap Frame: 0x%08x\n"
1653 " NPX State: %s (0x%x)\n",
1654 (Argc
< 2) ? "Current Thread:\n" : "",
1655 Thread
->Cid
.UniqueThread
,
1656 State
, Thread
->Tcb
.State
,
1657 Thread
->Tcb
.Priority
,
1658 Thread
->Tcb
.Affinity
,
1659 Thread
->Tcb
.InitialStack
,
1660 Thread
->Tcb
.StackLimit
,
1661 Thread
->Tcb
.StackBase
,
1662 Thread
->Tcb
.KernelStack
,
1663 Thread
->Tcb
.TrapFrame
,
1664 NPX_STATE_TO_STRING(Thread
->Tcb
.NpxState
), Thread
->Tcb
.NpxState
);
1666 /* Release our reference if we had one */
1667 if (ReferencedThread
)
1668 ObDereferenceObject(Thread
);
1674 /*!\brief Lists processes or switches to another process context.
1683 BOOLEAN ReferencedProcess
= FALSE
;
1684 PCHAR State
, pend
, str1
, str2
;
1686 extern LIST_ENTRY PsActiveProcessHead
;
1688 if (Argc
>= 2 && _stricmp(Argv
[1], "list") == 0)
1690 Entry
= PsActiveProcessHead
.Flink
;
1691 if (!Entry
|| Entry
== &PsActiveProcessHead
)
1693 KdbpPrint("No processes in the system!\n");
1697 KdbpPrint(" PID State Filename\n");
1700 Process
= CONTAINING_RECORD(Entry
, EPROCESS
, ActiveProcessLinks
);
1702 if (Process
== KdbCurrentProcess
)
1713 State
= ((Process
->Pcb
.State
== ProcessInMemory
) ? "In Memory" :
1714 ((Process
->Pcb
.State
== ProcessOutOfMemory
) ? "Out of Memory" : "In Transition"));
1716 KdbpPrint(" %s0x%08x %-10s %s%s\n",
1718 Process
->UniqueProcessId
,
1720 Process
->ImageFileName
,
1723 Entry
= Entry
->Flink
;
1725 while(Entry
!= &PsActiveProcessHead
);
1727 else if (Argc
>= 2 && _stricmp(Argv
[1], "attach") == 0)
1731 KdbpPrint("process attach: process id argument required!\n");
1735 ul
= strtoul(Argv
[2], &pend
, 0);
1736 if (Argv
[2] == pend
)
1738 KdbpPrint("process attach: '%s' is not a valid process id!\n", Argv
[2]);
1742 if (!KdbpAttachToProcess((PVOID
)ul
))
1747 KdbpPrint("Attached to process 0x%08x, thread 0x%08x.\n", (ULONG
)ul
,
1748 (ULONG
)KdbCurrentThread
->Cid
.UniqueThread
);
1752 Process
= KdbCurrentProcess
;
1756 ul
= strtoul(Argv
[1], &pend
, 0);
1757 if (Argv
[1] == pend
)
1759 KdbpPrint("proc: '%s' is not a valid process id!\n", Argv
[1]);
1763 if (!NT_SUCCESS(PsLookupProcessByProcessId((PVOID
)ul
, &Process
)))
1765 KdbpPrint("proc: Invalid process id!\n");
1769 /* Remember our reference */
1770 ReferencedProcess
= TRUE
;
1773 State
= ((Process
->Pcb
.State
== ProcessInMemory
) ? "In Memory" :
1774 ((Process
->Pcb
.State
== ProcessOutOfMemory
) ? "Out of Memory" : "In Transition"));
1777 " State: %s (0x%x)\n"
1778 " Image Filename: %s\n",
1779 (Argc
< 2) ? "Current process:\n" : "",
1780 Process
->UniqueProcessId
,
1781 State
, Process
->Pcb
.State
,
1782 Process
->ImageFileName
);
1784 /* Release our reference, if any */
1785 if (ReferencedProcess
)
1786 ObDereferenceObject(Process
);
1792 /*!\brief Lists loaded modules or the one containing the specified address.
1799 ULONGLONG Result
= 0;
1801 PLDR_DATA_TABLE_ENTRY LdrEntry
;
1802 BOOLEAN DisplayOnlyOneModule
= FALSE
;
1807 /* Put the arguments back together */
1810 Argv
[Argc
][strlen(Argv
[Argc
])] = ' ';
1812 /* Evaluate the expression */
1813 if (!KdbpEvaluateExpression(Argv
[1], sizeof("kdb:> ")-1 + (Argv
[1]-Argv
[0]), &Result
))
1818 if (Result
> (ULONGLONG
)(~((ULONG_PTR
)0)))
1819 KdbpPrint("%s: Warning: Address %I64x is beeing truncated\n", Argv
[0],Result
);
1821 Address
= (ULONG_PTR
)Result
;
1823 if (!KdbpSymFindModule((PVOID
)Address
, NULL
, -1, &LdrEntry
))
1825 KdbpPrint("No module containing address 0x%p found!\n", Address
);
1829 DisplayOnlyOneModule
= TRUE
;
1833 if (!KdbpSymFindModule(NULL
, NULL
, 0, &LdrEntry
))
1835 ULONG_PTR ntoskrnlBase
= ((ULONG_PTR
)KdbpCmdMod
) & 0xfff00000;
1836 KdbpPrint(" Base Size Name\n");
1837 KdbpPrint(" %08x %08x %s\n", ntoskrnlBase
, 0, "ntoskrnl.exe");
1844 KdbpPrint(" Base Size Name\n");
1847 KdbpPrint(" %08x %08x %wZ\n", LdrEntry
->DllBase
, LdrEntry
->SizeOfImage
, &LdrEntry
->BaseDllName
);
1849 if(DisplayOnlyOneModule
|| !KdbpSymFindModule(NULL
, NULL
, i
++, &LdrEntry
))
1856 /*!\brief Displays GDT, LDT or IDTd.
1873 if (Argv
[0][0] == 'i')
1880 KdbpPrint("Interrupt descriptor table is empty.\n");
1884 KdbpPrint("IDT Base: 0x%08x Limit: 0x%04x\n", Reg
.Base
, Reg
.Limit
);
1885 KdbpPrint(" Idx Type Seg. Sel. Offset DPL\n");
1887 for (i
= 0; (i
+ sizeof(SegDesc
) - 1) <= Reg
.Limit
; i
+= 8)
1889 if (!NT_SUCCESS(KdbpSafeReadMemory(SegDesc
, (PVOID
)(Reg
.Base
+ i
), sizeof(SegDesc
))))
1891 KdbpPrint("Couldn't access memory at 0x%08x!\n", Reg
.Base
+ i
);
1895 Dpl
= ((SegDesc
[1] >> 13) & 3);
1896 if ((SegDesc
[1] & 0x1f00) == 0x0500) /* Task gate */
1897 SegType
= "TASKGATE";
1898 else if ((SegDesc
[1] & 0x1fe0) == 0x0e00) /* 32 bit Interrupt gate */
1899 SegType
= "INTGATE32";
1900 else if ((SegDesc
[1] & 0x1fe0) == 0x0600) /* 16 bit Interrupt gate */
1901 SegType
= "INTGATE16";
1902 else if ((SegDesc
[1] & 0x1fe0) == 0x0f00) /* 32 bit Trap gate */
1903 SegType
= "TRAPGATE32";
1904 else if ((SegDesc
[1] & 0x1fe0) == 0x0700) /* 16 bit Trap gate */
1905 SegType
= "TRAPGATE16";
1907 SegType
= "UNKNOWN";
1909 if ((SegDesc
[1] & (1 << 15)) == 0) /* not present */
1911 KdbpPrint(" %03d %-10s [NP] [NP] %02d\n",
1912 i
/ 8, SegType
, Dpl
);
1914 else if ((SegDesc
[1] & 0x1f00) == 0x0500) /* Task gate */
1916 SegSel
= SegDesc
[0] >> 16;
1917 KdbpPrint(" %03d %-10s 0x%04x %02d\n",
1918 i
/ 8, SegType
, SegSel
, Dpl
);
1922 SegSel
= SegDesc
[0] >> 16;
1923 SegBase
= (SegDesc
[1] & 0xffff0000) | (SegDesc
[0] & 0x0000ffff);
1924 KdbpPrint(" %03d %-10s 0x%04x 0x%08x %02d\n",
1925 i
/ 8, SegType
, SegSel
, SegBase
, Dpl
);
1933 if (Argv
[0][0] == 'g')
1936 Ke386GetGlobalDescriptorTable(&Reg
.Limit
);
1941 ASSERT(Argv
[0][0] == 'l');
1944 Reg
.Limit
= Ke386GetLocalDescriptorTable();
1952 KdbpPrint("%s descriptor table is empty.\n",
1953 Argv
[0][0] == 'g' ? "Global" : "Local");
1957 KdbpPrint("%cDT Base: 0x%08x Limit: 0x%04x\n",
1958 Argv
[0][0] == 'g' ? 'G' : 'L', Reg
.Base
, Reg
.Limit
);
1959 KdbpPrint(" Idx Sel. Type Base Limit DPL Attribs\n");
1961 for (; (i
+ sizeof(SegDesc
) - 1) <= Reg
.Limit
; i
+= 8)
1963 if (!NT_SUCCESS(KdbpSafeReadMemory(SegDesc
, (PVOID
)(Reg
.Base
+ i
), sizeof(SegDesc
))))
1965 KdbpPrint("Couldn't access memory at 0x%08x!\n", Reg
.Base
+ i
);
1969 Dpl
= ((SegDesc
[1] >> 13) & 3);
1970 Type
= ((SegDesc
[1] >> 8) & 0xf);
1972 SegBase
= SegDesc
[0] >> 16;
1973 SegBase
|= (SegDesc
[1] & 0xff) << 16;
1974 SegBase
|= SegDesc
[1] & 0xff000000;
1975 SegLimit
= SegDesc
[0] & 0x0000ffff;
1976 SegLimit
|= (SegDesc
[1] >> 16) & 0xf;
1978 if ((SegDesc
[1] & (1 << 23)) != 0)
1988 if ((SegDesc
[1] & (1 << 12)) == 0) /* System segment */
1992 case 1: SegType
= "TSS16(Avl)"; break;
1993 case 2: SegType
= "LDT"; break;
1994 case 3: SegType
= "TSS16(Busy)"; break;
1995 case 4: SegType
= "CALLGATE16"; break;
1996 case 5: SegType
= "TASKGATE"; break;
1997 case 6: SegType
= "INTGATE16"; break;
1998 case 7: SegType
= "TRAPGATE16"; break;
1999 case 9: SegType
= "TSS32(Avl)"; break;
2000 case 11: SegType
= "TSS32(Busy)"; break;
2001 case 12: SegType
= "CALLGATE32"; break;
2002 case 14: SegType
= "INTGATE32"; break;
2003 case 15: SegType
= "INTGATE32"; break;
2004 default: SegType
= "UNKNOWN"; break;
2007 if (!(Type
>= 1 && Type
<= 3) &&
2008 Type
!= 9 && Type
!= 11)
2014 else if ((SegDesc
[1] & (1 << 11)) == 0) /* Data segment */
2016 if ((SegDesc
[1] & (1 << 22)) != 0)
2021 else /* Code segment */
2023 if ((SegDesc
[1] & (1 << 22)) != 0)
2029 if ((SegDesc
[1] & (1 << 15)) == 0) /* not present */
2031 KdbpPrint(" %03d 0x%04x %-11s [NP] [NP] %02d NP\n",
2032 i
/ 8, i
| Dpl
| ul
, SegType
, Dpl
);
2036 KdbpPrint(" %03d 0x%04x %-11s 0x%08x 0x%08x %02d ",
2037 i
/ 8, i
| Dpl
| ul
, SegType
, SegBase
, SegLimit
, Dpl
);
2039 if ((SegDesc
[1] & (1 << 12)) == 0) /* System segment */
2041 /* FIXME: Display system segment */
2043 else if ((SegDesc
[1] & (1 << 11)) == 0) /* Data segment */
2045 if ((SegDesc
[1] & (1 << 10)) != 0) /* Expand-down */
2048 KdbpPrint((SegDesc
[1] & (1 << 9)) ? " R/W" : " R");
2050 if ((SegDesc
[1] & (1 << 8)) != 0)
2053 else /* Code segment */
2055 if ((SegDesc
[1] & (1 << 10)) != 0) /* Conforming */
2058 KdbpPrint((SegDesc
[1] & (1 << 9)) ? " R/X" : " X");
2060 if ((SegDesc
[1] & (1 << 8)) != 0)
2064 if ((SegDesc
[1] & (1 << 20)) != 0)
2075 /*!\brief Displays the KPCR
2082 PKIPCR Pcr
= (PKIPCR
)KeGetPcr();
2084 KdbpPrint("Current PCR is at 0x%08x.\n", (INT
)Pcr
);
2085 KdbpPrint(" Tib.ExceptionList: 0x%08x\n"
2086 " Tib.StackBase: 0x%08x\n"
2087 " Tib.StackLimit: 0x%08x\n"
2088 " Tib.SubSystemTib: 0x%08x\n"
2089 " Tib.FiberData/Version: 0x%08x\n"
2090 " Tib.ArbitraryUserPointer: 0x%08x\n"
2091 " Tib.Self: 0x%08x\n"
2096 " IrrActive: 0x%08x\n"
2098 " KdVersionBlock: 0x%08x\n"
2102 " MajorVersion: 0x%04x\n"
2103 " MinorVersion: 0x%04x\n"
2104 " SetMember: 0x%08x\n"
2105 " StallScaleFactor: 0x%08x\n"
2107 " L2CacheAssociativity: 0x%02x\n"
2108 " VdmAlert: 0x%08x\n"
2109 " L2CacheSize: 0x%08x\n"
2110 " InterruptMode: 0x%08x\n",
2111 Pcr
->NtTib
.ExceptionList
, Pcr
->NtTib
.StackBase
, Pcr
->NtTib
.StackLimit
,
2112 Pcr
->NtTib
.SubSystemTib
, Pcr
->NtTib
.FiberData
, Pcr
->NtTib
.ArbitraryUserPointer
,
2113 Pcr
->NtTib
.Self
, Pcr
->Self
, Pcr
->Prcb
, Pcr
->Irql
, Pcr
->IRR
, Pcr
->IrrActive
,
2114 Pcr
->IDR
, Pcr
->KdVersionBlock
, Pcr
->IDT
, Pcr
->GDT
, Pcr
->TSS
,
2115 Pcr
->MajorVersion
, Pcr
->MinorVersion
, Pcr
->SetMember
, Pcr
->StallScaleFactor
,
2116 Pcr
->Number
, Pcr
->SecondLevelCacheAssociativity
,
2117 Pcr
->VdmAlert
, Pcr
->SecondLevelCacheSize
, Pcr
->InterruptMode
);
2122 /*!\brief Displays the TSS
2129 KTSS
*Tss
= KeGetPcr()->TSS
;
2131 KdbpPrint("Current TSS is at 0x%08x.\n", (INT
)Tss
);
2132 KdbpPrint(" Eip: 0x%08x\n"
2139 " IoMapBase: 0x%04x\n",
2140 Tss
->Eip
, Tss
->Es
, Tss
->Cs
, Tss
->Ds
, Tss
->Fs
, Tss
->Gs
, Tss
->IoMapBase
);
2145 /*!\brief Bugchecks the system.
2152 /* Set the flag and quit looping */
2153 KdbpBugCheckRequested
= TRUE
;
2161 IN ULONG BufLength
);
2163 /*!\brief Display debug messages on screen, with paging.
2165 * Keys for per-page view: Home, End, PageUp, Arrow Up, PageDown,
2166 * all others are as PageDown.
2175 KdbpIsInDmesgMode
= TRUE
; /* Toggle logging flag */
2176 if (!KdpDmesgBuffer
)
2178 KdbpPrint("Dmesg: error, buffer is not allocated! /DEBUGPORT=SCREEN kernel param required for dmesg.\n");
2182 KdbpPrint("*** Dmesg *** TotalWritten=%lu, BufferSize=%lu, CurrentPosition=%lu\n",
2183 KdbDmesgTotalWritten
, KdpDmesgBufferSize
, KdpDmesgCurrentPosition
);
2185 // Pass data to the pager:
2186 end
= KdpDmesgCurrentPosition
;
2187 beg
= (end
+ KdpDmesgFreeBytes
) % KdpDmesgBufferSize
;
2189 // no roll-overs, and overwritten=lost bytes
2190 if (KdbDmesgTotalWritten
<= KdpDmesgBufferSize
)
2192 // show buffer (KdpDmesgBuffer + beg, num)
2193 KdbpPager(KdpDmesgBuffer
, KdpDmesgCurrentPosition
);
2197 // show 2 buffers: (KdpDmesgBuffer + beg, KdpDmesgBufferSize - beg)
2198 // and: (KdpDmesgBuffer, end)
2199 KdbpPager(KdpDmesgBuffer
+ beg
, KdpDmesgBufferSize
- beg
);
2200 KdbpPrint("*** Dmesg: buffer rollup ***\n");
2201 KdbpPager(KdpDmesgBuffer
, end
);
2203 KdbpPrint("*** Dmesg: end of output ***\n");
2205 KdbpIsInDmesgMode
= FALSE
; /* Toggle logging flag */
2210 /*!\brief Sets or displays a config variables value.
2220 KDB_ENTER_CONDITION ConditionFirst
= KdbDoNotEnter
;
2221 KDB_ENTER_CONDITION ConditionLast
= KdbDoNotEnter
;
2223 static const PCHAR ExceptionNames
[21] =
2225 "ZERODEVIDE", "DEBUGTRAP", "NMI", "INT3", "OVERFLOW", "BOUND", "INVALIDOP",
2226 "NOMATHCOP", "DOUBLEFAULT", "RESERVED(9)", "INVALIDTSS", "SEGMENTNOTPRESENT",
2227 "STACKFAULT", "GPF", "PAGEFAULT", "RESERVED(15)", "MATHFAULT", "ALIGNMENTCHECK",
2228 "MACHINECHECK", "SIMDFAULT", "OTHERS"
2233 KdbpPrint("Available settings:\n");
2234 KdbpPrint(" syntax [intel|at&t]\n");
2235 KdbpPrint(" condition [exception|*] [first|last] [never|always|kmode|umode]\n");
2236 KdbpPrint(" break_on_module_load [true|false]\n");
2238 else if (strcmp(Argv
[1], "syntax") == 0)
2242 KdbpPrint("syntax = %s\n", KdbUseIntelSyntax
? "intel" : "at&t");
2246 if (_stricmp(Argv
[2], "intel") == 0)
2247 KdbUseIntelSyntax
= TRUE
;
2248 else if (_stricmp(Argv
[2], "at&t") == 0)
2249 KdbUseIntelSyntax
= FALSE
;
2251 KdbpPrint("Unknown syntax '%s'.\n", Argv
[2]);
2254 else if (strcmp(Argv
[1], "condition") == 0)
2258 KdbpPrint("Conditions: (First) (Last)\n");
2259 for (l
= 0; l
< RTL_NUMBER_OF(ExceptionNames
) - 1; l
++)
2261 if (!ExceptionNames
[l
])
2264 if (!KdbpGetEnterCondition(l
, TRUE
, &ConditionFirst
))
2267 if (!KdbpGetEnterCondition(l
, FALSE
, &ConditionLast
))
2270 KdbpPrint(" #%02d %-20s %-8s %-8s\n", l
, ExceptionNames
[l
],
2271 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst
),
2272 KDB_ENTER_CONDITION_TO_STRING(ConditionLast
));
2275 ASSERT(l
== (RTL_NUMBER_OF(ExceptionNames
) - 1));
2276 KdbpPrint(" %-20s %-8s %-8s\n", ExceptionNames
[l
],
2277 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst
),
2278 KDB_ENTER_CONDITION_TO_STRING(ConditionLast
));
2282 if (Argc
>= 5 && strcmp(Argv
[2], "*") == 0) /* Allow * only when setting condition */
2288 l
= strtoul(Argv
[2], &pend
, 0);
2290 if (Argv
[2] == pend
)
2292 for (l
= 0; l
< RTL_NUMBER_OF(ExceptionNames
); l
++)
2294 if (!ExceptionNames
[l
])
2297 if (_stricmp(ExceptionNames
[l
], Argv
[2]) == 0)
2302 if (l
>= RTL_NUMBER_OF(ExceptionNames
))
2304 KdbpPrint("Unknown exception '%s'.\n", Argv
[2]);
2311 if (_stricmp(Argv
[3], "first") == 0)
2313 else if (_stricmp(Argv
[3], "last") == 0)
2317 KdbpPrint("set condition: second argument must be 'first' or 'last'\n");
2321 if (_stricmp(Argv
[4], "never") == 0)
2322 ConditionFirst
= KdbDoNotEnter
;
2323 else if (_stricmp(Argv
[4], "always") == 0)
2324 ConditionFirst
= KdbEnterAlways
;
2325 else if (_stricmp(Argv
[4], "umode") == 0)
2326 ConditionFirst
= KdbEnterFromUmode
;
2327 else if (_stricmp(Argv
[4], "kmode") == 0)
2328 ConditionFirst
= KdbEnterFromKmode
;
2331 KdbpPrint("set condition: third argument must be 'never', 'always', 'umode' or 'kmode'\n");
2335 if (!KdbpSetEnterCondition(l
, First
, ConditionFirst
))
2338 KdbpPrint("Couldn't change condition for exception #%02d\n", l
);
2340 KdbpPrint("Couldn't change condition for all exceptions\n", l
);
2343 else /* Argc >= 3 */
2345 if (!KdbpGetEnterCondition(l
, TRUE
, &ConditionFirst
))
2348 if (!KdbpGetEnterCondition(l
, FALSE
, &ConditionLast
))
2351 if (l
< (RTL_NUMBER_OF(ExceptionNames
) - 1))
2353 KdbpPrint("Condition for exception #%02d (%s): FirstChance %s LastChance %s\n",
2354 l
, ExceptionNames
[l
],
2355 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst
),
2356 KDB_ENTER_CONDITION_TO_STRING(ConditionLast
));
2360 KdbpPrint("Condition for all other exceptions: FirstChance %s LastChance %s\n",
2361 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst
),
2362 KDB_ENTER_CONDITION_TO_STRING(ConditionLast
));
2367 else if (strcmp(Argv
[1], "break_on_module_load") == 0)
2370 KdbpPrint("break_on_module_load = %s\n", KdbBreakOnModuleLoad
? "enabled" : "disabled");
2373 if (_stricmp(Argv
[2], "enable") == 0 || _stricmp(Argv
[2], "enabled") == 0 || _stricmp(Argv
[2], "true") == 0)
2374 KdbBreakOnModuleLoad
= TRUE
;
2375 else if (_stricmp(Argv
[2], "disable") == 0 || _stricmp(Argv
[2], "disabled") == 0 || _stricmp(Argv
[2], "false") == 0)
2376 KdbBreakOnModuleLoad
= FALSE
;
2378 KdbpPrint("Unknown setting '%s'.\n", Argv
[2]);
2383 KdbpPrint("Unknown setting '%s'.\n", Argv
[1]);
2389 /*!\brief Displays help screen.
2398 KdbpPrint("Kernel debugger commands:\n");
2399 for (i
= 0; i
< RTL_NUMBER_OF(KdbDebuggerCommands
); i
++)
2401 if (!KdbDebuggerCommands
[i
].Syntax
) /* Command group */
2406 KdbpPrint("\x1b[7m* %s:\x1b[0m\n", KdbDebuggerCommands
[i
].Help
);
2410 KdbpPrint(" %-20s - %s\n",
2411 KdbDebuggerCommands
[i
].Syntax
,
2412 KdbDebuggerCommands
[i
].Help
);
2418 /*!\brief Prints the given string with printf-like formatting.
2420 * \param Format Format of the string/arguments.
2421 * \param ... Variable number of arguments matching the format specified in \a Format.
2423 * \note Doesn't correctly handle \\t and terminal escape sequences when calculating the
2424 * number of lines required to print a single line from the Buffer in the terminal.
2425 * Prints maximum 4096 chars, because of its buffer size.
2432 static CHAR Buffer
[4096];
2433 static BOOLEAN TerminalInitialized
= FALSE
;
2434 static BOOLEAN TerminalConnected
= FALSE
;
2435 static BOOLEAN TerminalReportsSize
= TRUE
;
2440 LONG RowsPrintedByTerminal
;
2444 /* Check if the user has aborted output of the current command */
2445 if (KdbOutputAborted
)
2448 /* Initialize the terminal */
2449 if (!TerminalInitialized
)
2451 DbgPrint("\x1b[7h"); /* Enable linewrap */
2453 /* Query terminal type */
2454 /*DbgPrint("\x1b[Z");*/
2457 TerminalInitialized
= TRUE
;
2459 KeStallExecutionProcessor(100000);
2463 c
= KdbpTryGetCharSerial(5000);
2467 Buffer
[Length
++] = c
;
2468 if (Length
>= (sizeof (Buffer
) - 1))
2472 Buffer
[Length
] = '\0';
2474 TerminalConnected
= TRUE
;
2477 /* Get number of rows and columns in terminal */
2478 if ((KdbNumberOfRowsTerminal
< 0) || (KdbNumberOfColsTerminal
< 0) ||
2479 (KdbNumberOfRowsPrinted
) == 0) /* Refresh terminal size each time when number of rows printed is 0 */
2481 if ((KdbDebugState
& KD_DEBUG_KDSERIAL
) && TerminalConnected
&& TerminalReportsSize
)
2483 /* Try to query number of rows from terminal. A reply looks like "\x1b[8;24;80t" */
2484 TerminalReportsSize
= FALSE
;
2485 KeStallExecutionProcessor(100000);
2486 DbgPrint("\x1b[18t");
2487 c
= KdbpTryGetCharSerial(5000);
2491 c
= KdbpTryGetCharSerial(5000);
2498 c
= KdbpTryGetCharSerial(5000);
2502 Buffer
[Length
++] = c
;
2503 if (isalpha(c
) || Length
>= (sizeof (Buffer
) - 1))
2507 Buffer
[Length
] = '\0';
2508 if (Buffer
[0] == '8' && Buffer
[1] == ';')
2510 for (i
= 2; (i
< Length
) && (Buffer
[i
] != ';'); i
++);
2512 if (Buffer
[i
] == ';')
2516 /* Number of rows is now at Buffer + 2 and number of cols at Buffer + i */
2517 KdbNumberOfRowsTerminal
= strtoul(Buffer
+ 2, NULL
, 0);
2518 KdbNumberOfColsTerminal
= strtoul(Buffer
+ i
, NULL
, 0);
2519 TerminalReportsSize
= TRUE
;
2523 /* Clear further characters */
2524 while ((c
= KdbpTryGetCharSerial(5000)) != -1);
2528 if (KdbNumberOfRowsTerminal
<= 0)
2530 /* Set number of rows to the default. */
2531 KdbNumberOfRowsTerminal
= 23; //24; //Mna.: 23 for SCREEN debugport
2533 else if (KdbNumberOfColsTerminal
<= 0)
2535 /* Set number of cols to the default. */
2536 KdbNumberOfColsTerminal
= 75; //80; //Mna.: 75 for SCREEN debugport
2540 /* Get the string */
2541 va_start(ap
, Format
);
2542 Length
= _vsnprintf(Buffer
, sizeof (Buffer
) - 1, Format
, ap
);
2543 Buffer
[Length
] = '\0';
2547 while (p
[0] != '\0')
2549 i
= strcspn(p
, "\n");
2551 /* Calculate the number of lines which will be printed in the terminal
2552 * when outputting the current line
2555 RowsPrintedByTerminal
= (i
+ KdbNumberOfColsPrinted
- 1) / KdbNumberOfColsTerminal
;
2557 RowsPrintedByTerminal
= 0;
2560 RowsPrintedByTerminal
++;
2562 /*DbgPrint("!%d!%d!%d!%d!", KdbNumberOfRowsPrinted, KdbNumberOfColsPrinted, i, RowsPrintedByTerminal);*/
2564 /* Display a prompt if we printed one screen full of text */
2565 if (KdbNumberOfRowsTerminal
> 0 &&
2566 (LONG
)(KdbNumberOfRowsPrinted
+ RowsPrintedByTerminal
) >= KdbNumberOfRowsTerminal
)
2568 KdbRepeatLastCommand
= FALSE
;
2570 if (KdbNumberOfColsPrinted
> 0)
2573 DbgPrint("--- Press q to abort, any other key to continue ---");
2574 RowsPrintedByTerminal
++; /* added by Mna. */
2576 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
2577 c
= KdbpGetCharSerial();
2579 c
= KdbpGetCharKeyboard(&ScanCode
);
2583 /* Try to read '\n' which might follow '\r' - if \n is not received here
2584 * it will be interpreted as "return" when the next command should be read.
2586 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
2587 c
= KdbpTryGetCharSerial(5);
2589 c
= KdbpTryGetCharKeyboard(&ScanCode
, 5);
2595 KdbOutputAborted
= TRUE
;
2599 KdbNumberOfRowsPrinted
= 0;
2600 KdbNumberOfColsPrinted
= 0;
2603 /* Insert a NUL after the line and print only the current line. */
2604 if (p
[i
] == '\n' && p
[i
+ 1] != '\0')
2614 /* Remove escape sequences from the line if there's no terminal connected */
2615 if (!TerminalConnected
)
2617 while ((p2
= strrchr(p
, '\x1b'))) /* Look for escape character */
2622 while (!isalpha(p2
[j
++]));
2637 /* Set p to the start of the next line and
2638 * remember the number of rows/cols printed
2644 KdbNumberOfColsPrinted
= 0;
2648 ASSERT(p
[0] == '\0');
2649 KdbNumberOfColsPrinted
+= i
;
2652 KdbNumberOfRowsPrinted
+= RowsPrintedByTerminal
;
2656 /** memrchr(), explicitly defined, since was absent in MinGW of RosBE. */
2659 * Find the last occurrence of 'c' in the buffer 's' of size 'n'.
2662 memrchr(const void *s
, int c
, size_t n
)
2664 const unsigned char *cp
;
2668 cp
= (unsigned char *)s
+ n
;
2671 if (*(--cp
) == (unsigned char)c
)
2678 /*!\brief Calculate pointer position for N lines upper of current position.
2680 * \param Buffer Characters buffer to operate on.
2681 * \param BufLength Buffer size.
2683 * \note Calculate pointer position for N lines upper of current displaying
2684 * position within the given buffer.
2686 * Used by KdbpPager().
2687 * Now N lines count is hardcoded to KdbNumberOfRowsTerminal.
2690 CountOnePageUp(PCHAR Buffer
, ULONG BufLength
, PCHAR pCurPos
)
2693 // p0 is initial guess of Page Start
2694 ULONG p0len
= KdbNumberOfRowsTerminal
* KdbNumberOfColsTerminal
;
2695 PCHAR p0
= pCurPos
- p0len
;
2696 PCHAR prev_p
= p0
, p1
;
2699 if (pCurPos
< Buffer
)
2701 ASSERT(pCurPos
<= Buffer
+ BufLength
);
2703 p
= memrchr(p0
, '\n', p0len
);
2706 for (j
= KdbNumberOfRowsTerminal
; j
--; )
2709 p1
= memrchr(p0
, '\n', p
-p0
);
2719 linesCnt
= (KdbNumberOfColsTerminal
+prev_p
-p
-2) / KdbNumberOfColsTerminal
;
2729 /*!\brief Prints the given string with, page by page.
2731 * \param Buffer Characters buffer to print.
2732 * \param BufferLen Buffer size.
2734 * \note Doesn't correctly handle \\t and terminal escape sequences when calculating the
2735 * number of lines required to print a single line from the Buffer in the terminal.
2736 * Maximum length of buffer is limited only by memory size.
2738 * Note: BufLength should be greater then (KdbNumberOfRowsTerminal * KdbNumberOfColsTerminal).
2746 static CHAR InBuffer
[4096];
2747 static BOOLEAN TerminalInitialized
= FALSE
;
2748 static BOOLEAN TerminalConnected
= FALSE
;
2749 static BOOLEAN TerminalReportsSize
= TRUE
;
2754 LONG RowsPrintedByTerminal
;
2760 /* Check if the user has aborted output of the current command */
2761 if (KdbOutputAborted
)
2764 /* Initialize the terminal */
2765 if (!TerminalInitialized
)
2767 DbgPrint("\x1b[7h"); /* Enable linewrap */
2769 /* Query terminal type */
2770 /*DbgPrint("\x1b[Z");*/
2773 TerminalInitialized
= TRUE
;
2775 KeStallExecutionProcessor(100000);
2779 c
= KdbpTryGetCharSerial(5000);
2783 InBuffer
[Length
++] = c
;
2784 if (Length
>= (sizeof (InBuffer
) - 1))
2788 InBuffer
[Length
] = '\0';
2790 TerminalConnected
= TRUE
;
2793 /* Get number of rows and columns in terminal */
2794 if ((KdbNumberOfRowsTerminal
< 0) || (KdbNumberOfColsTerminal
< 0) ||
2795 (KdbNumberOfRowsPrinted
) == 0) /* Refresh terminal size each time when number of rows printed is 0 */
2797 if ((KdbDebugState
& KD_DEBUG_KDSERIAL
) && TerminalConnected
&& TerminalReportsSize
)
2799 /* Try to query number of rows from terminal. A reply looks like "\x1b[8;24;80t" */
2800 TerminalReportsSize
= FALSE
;
2801 KeStallExecutionProcessor(100000);
2802 DbgPrint("\x1b[18t");
2803 c
= KdbpTryGetCharSerial(5000);
2807 c
= KdbpTryGetCharSerial(5000);
2814 c
= KdbpTryGetCharSerial(5000);
2818 InBuffer
[Length
++] = c
;
2819 if (isalpha(c
) || Length
>= (sizeof (InBuffer
) - 1))
2823 InBuffer
[Length
] = '\0';
2824 if (InBuffer
[0] == '8' && InBuffer
[1] == ';')
2826 for (i
= 2; (i
< Length
) && (InBuffer
[i
] != ';'); i
++);
2828 if (Buffer
[i
] == ';')
2832 /* Number of rows is now at Buffer + 2 and number of cols at Buffer + i */
2833 KdbNumberOfRowsTerminal
= strtoul(InBuffer
+ 2, NULL
, 0);
2834 KdbNumberOfColsTerminal
= strtoul(InBuffer
+ i
, NULL
, 0);
2835 TerminalReportsSize
= TRUE
;
2839 /* Clear further characters */
2840 while ((c
= KdbpTryGetCharSerial(5000)) != -1);
2844 if (KdbNumberOfRowsTerminal
<= 0)
2846 /* Set number of rows to the default. */
2847 KdbNumberOfRowsTerminal
= 24;
2849 else if (KdbNumberOfColsTerminal
<= 0)
2851 /* Set number of cols to the default. */
2852 KdbNumberOfColsTerminal
= 80;
2856 /* Get the string */
2859 while (p
[0] != '\0')
2861 if ( p
> Buffer
+BufLength
)
2863 DbgPrint("Dmesg: error, p > Buffer+BufLength,d=%d", p
- (Buffer
+BufLength
));
2866 i
= strcspn(p
, "\n");
2868 // Are we out of buffer?
2869 if (p
+ i
> Buffer
+ BufLength
)
2870 // Leaving pager function:
2873 /* Calculate the number of lines which will be printed in the terminal
2874 * when outputting the current line
2877 RowsPrintedByTerminal
= (i
+ KdbNumberOfColsPrinted
- 1) / KdbNumberOfColsTerminal
;
2879 RowsPrintedByTerminal
= 0;
2882 RowsPrintedByTerminal
++;
2884 /*DbgPrint("!%d!%d!%d!%d!", KdbNumberOfRowsPrinted, KdbNumberOfColsPrinted, i, RowsPrintedByTerminal);*/
2886 /* Display a prompt if we printed one screen full of text */
2887 if (KdbNumberOfRowsTerminal
> 0 &&
2888 (LONG
)(KdbNumberOfRowsPrinted
+ RowsPrintedByTerminal
) >= KdbNumberOfRowsTerminal
)
2890 KdbRepeatLastCommand
= FALSE
;
2892 if (KdbNumberOfColsPrinted
> 0)
2895 DbgPrint("--- Press q to abort, e/End,h/Home,u/PgUp, other key/PgDn ---");
2896 RowsPrintedByTerminal
++;
2898 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
2899 c
= KdbpGetCharSerial();
2901 c
= KdbpGetCharKeyboard(&ScanCode
);
2905 /* Try to read '\n' which might follow '\r' - if \n is not received here
2906 * it will be interpreted as "return" when the next command should be read.
2908 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
2909 c
= KdbpTryGetCharSerial(5);
2911 c
= KdbpTryGetCharKeyboard(&ScanCode
, 5);
2914 //DbgPrint("\n"); //Consize version: don't show pressed key
2915 DbgPrint(" '%c'/scan=%04x\n", c
, ScanCode
); // Shows pressed key
2919 KdbOutputAborted
= TRUE
;
2922 if ( ScanCode
== KEYSC_END
|| c
=='e')
2924 PCHAR pBufEnd
= Buffer
+ BufLength
;
2925 p
= CountOnePageUp(Buffer
, BufLength
, pBufEnd
);
2926 i
= strcspn(p
, "\n");
2928 else if (ScanCode
== KEYSC_PAGEUP
|| c
=='u')
2930 p
= CountOnePageUp(Buffer
, BufLength
, p
);
2931 i
= strcspn(p
, "\n");
2933 else if (ScanCode
== KEYSC_HOME
|| c
=='h')
2936 i
= strcspn(p
, "\n");
2938 else if (ScanCode
== KEYSC_ARROWUP
)
2940 p
= CountOnePageUp(Buffer
, BufLength
, p
);
2941 i
= strcspn(p
, "\n");
2944 KdbNumberOfRowsPrinted
= 0;
2945 KdbNumberOfColsPrinted
= 0;
2948 /* Insert a NUL after the line and print only the current line. */
2949 if (p
[i
] == '\n' && p
[i
+ 1] != '\0')
2959 /* Remove escape sequences from the line if there's no terminal connected */
2960 if (!TerminalConnected
)
2962 while ((p2
= strrchr(p
, '\x1b'))) /* Look for escape character */
2967 while (!isalpha(p2
[j
++]));
2977 // The main printing of the current line:
2980 // restore not null char with saved:
2984 /* Set p to the start of the next line and
2985 * remember the number of rows/cols printed
2991 KdbNumberOfColsPrinted
= 0;
2995 ASSERT(p
[0] == '\0');
2996 KdbNumberOfColsPrinted
+= i
;
2999 KdbNumberOfRowsPrinted
+= RowsPrintedByTerminal
;
3003 /*!\brief Appends a command to the command history
3005 * \param Command Pointer to the command to append to the history.
3008 KdbpCommandHistoryAppend(
3011 ULONG Length1
= strlen(Command
) + 1;
3016 ASSERT(Length1
<= RTL_NUMBER_OF(KdbCommandHistoryBuffer
));
3019 (KdbCommandHistory
[KdbCommandHistoryIndex
] &&
3020 strcmp(KdbCommandHistory
[KdbCommandHistoryIndex
], Command
) == 0))
3025 /* Calculate Length1 and Length2 */
3026 Buffer
= KdbCommandHistoryBuffer
+ KdbCommandHistoryBufferIndex
;
3027 KdbCommandHistoryBufferIndex
+= Length1
;
3028 if (KdbCommandHistoryBufferIndex
>= (LONG
)RTL_NUMBER_OF(KdbCommandHistoryBuffer
))
3030 KdbCommandHistoryBufferIndex
-= RTL_NUMBER_OF(KdbCommandHistoryBuffer
);
3031 Length2
= KdbCommandHistoryBufferIndex
;
3035 /* Remove previous commands until there is enough space to append the new command */
3036 for (i
= KdbCommandHistoryIndex
; KdbCommandHistory
[i
];)
3039 (KdbCommandHistory
[i
] >= Buffer
||
3040 KdbCommandHistory
[i
] < (KdbCommandHistoryBuffer
+ KdbCommandHistoryBufferIndex
))) ||
3042 (KdbCommandHistory
[i
] >= Buffer
&&
3043 KdbCommandHistory
[i
] < (KdbCommandHistoryBuffer
+ KdbCommandHistoryBufferIndex
))))
3045 KdbCommandHistory
[i
] = NULL
;
3050 i
= RTL_NUMBER_OF(KdbCommandHistory
) - 1;
3052 if (i
== KdbCommandHistoryIndex
)
3056 /* Make sure the new command history entry is free */
3057 KdbCommandHistoryIndex
++;
3058 KdbCommandHistoryIndex
%= RTL_NUMBER_OF(KdbCommandHistory
);
3059 if (KdbCommandHistory
[KdbCommandHistoryIndex
])
3061 KdbCommandHistory
[KdbCommandHistoryIndex
] = NULL
;
3064 /* Append command */
3065 KdbCommandHistory
[KdbCommandHistoryIndex
] = Buffer
;
3066 ASSERT((KdbCommandHistory
[KdbCommandHistoryIndex
] + Length1
) <= KdbCommandHistoryBuffer
+ RTL_NUMBER_OF(KdbCommandHistoryBuffer
));
3067 memcpy(KdbCommandHistory
[KdbCommandHistoryIndex
], Command
, Length1
);
3070 memcpy(KdbCommandHistoryBuffer
, Command
+ Length1
, Length2
);
3074 /*!\brief Reads a line of user-input.
3076 * \param Buffer Buffer to store the input into. Trailing newlines are removed.
3077 * \param Size Size of \a Buffer.
3079 * \note Accepts only \n newlines, \r is ignored.
3087 PCHAR Orig
= Buffer
;
3090 static CHAR LastCommand
[1024];
3091 static CHAR NextKey
= '\0';
3092 INT CmdHistIndex
= -1;
3095 EchoOn
= !((KdbDebugState
& KD_DEBUG_KDNOECHO
) != 0);
3099 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
3101 Key
= (NextKey
== '\0') ? KdbpGetCharSerial() : NextKey
;
3104 if (Key
== KEY_ESC
) /* ESC */
3106 Key
= KdbpGetCharSerial();
3109 Key
= KdbpGetCharSerial();
3114 ScanCode
= KEY_SCAN_UP
;
3117 ScanCode
= KEY_SCAN_DOWN
;
3130 Key
= (NextKey
== '\0') ? KdbpGetCharKeyboard(&ScanCode
) : NextKey
;
3134 if ((ULONG
)(Buffer
- Orig
) >= (Size
- 1))
3136 /* Buffer is full, accept only newlines */
3143 /* Read the next char - this is to throw away a \n which most clients should
3146 KeStallExecutionProcessor(100000);
3148 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
3149 NextKey
= KdbpTryGetCharSerial(5);
3151 NextKey
= KdbpTryGetCharKeyboard(&ScanCode
, 5);
3153 if (NextKey
== '\n' || NextKey
== -1) /* \n or no response at all */
3159 * Repeat the last command if the user presses enter. Reduces the
3160 * risk of RSI when single-stepping.
3164 KdbRepeatLastCommand
= TRUE
;
3166 RtlStringCbCopyA(LastCommand
, sizeof(LastCommand
), Orig
);
3168 else if (KdbRepeatLastCommand
)
3169 RtlStringCbCopyA(Buffer
, Size
, LastCommand
);
3175 else if (Key
== KEY_BS
|| Key
== KEY_DEL
)
3183 KdbpPrint("%c %c", KEY_BS
, KEY_BS
);
3185 KdbpPrint(" %c", KEY_BS
);
3188 else if (ScanCode
== KEY_SCAN_UP
)
3190 BOOLEAN Print
= TRUE
;
3192 if (CmdHistIndex
< 0)
3194 CmdHistIndex
= KdbCommandHistoryIndex
;
3198 i
= CmdHistIndex
- 1;
3201 CmdHistIndex
= RTL_NUMBER_OF(KdbCommandHistory
) - 1;
3203 if (KdbCommandHistory
[i
] && i
!= KdbCommandHistoryIndex
)
3209 if (Print
&& KdbCommandHistory
[CmdHistIndex
])
3211 while (Buffer
> Orig
)
3217 KdbpPrint("%c %c", KEY_BS
, KEY_BS
);
3219 KdbpPrint(" %c", KEY_BS
);
3222 i
= min(strlen(KdbCommandHistory
[CmdHistIndex
]), Size
- 1);
3223 memcpy(Orig
, KdbCommandHistory
[CmdHistIndex
], i
);
3226 KdbpPrint("%s", Orig
);
3229 else if (ScanCode
== KEY_SCAN_DOWN
)
3231 if (CmdHistIndex
> 0 && CmdHistIndex
!= KdbCommandHistoryIndex
)
3233 i
= CmdHistIndex
+ 1;
3234 if (i
>= (INT
)RTL_NUMBER_OF(KdbCommandHistory
))
3237 if (KdbCommandHistory
[i
])
3240 while (Buffer
> Orig
)
3246 KdbpPrint("%c %c", KEY_BS
, KEY_BS
);
3248 KdbpPrint(" %c", KEY_BS
);
3251 i
= min(strlen(KdbCommandHistory
[CmdHistIndex
]), Size
- 1);
3252 memcpy(Orig
, KdbCommandHistory
[CmdHistIndex
], i
);
3255 KdbpPrint("%s", Orig
);
3262 KdbpPrint("%c", Key
);
3273 KdbRegisterCliCallback(
3279 /* Loop all entries */
3280 for (i
= 0; i
< _countof(KdbCliCallbacks
); i
++)
3282 /* Check if deregistering was requested */
3285 /* Check if this entry is the one that was registered */
3286 if (KdbCliCallbacks
[i
] == Callback
)
3288 /* Delete it and report success */
3289 KdbCliCallbacks
[i
] = NULL
;
3295 /* Check if this entry is free */
3296 if (KdbCliCallbacks
[i
] == NULL
)
3298 /* Set it and and report success */
3299 KdbCliCallbacks
[i
] = Callback
;
3309 /*! \brief Invokes registered CLI callbacks until one of them handled the
3312 * \param Command - Command line to parse and execute if possible.
3313 * \param Argc - Number of arguments in Argv
3314 * \param Argv - Array of strings, each of them containing one argument.
3316 * \return TRUE, if the command was handled, FALSE if it was not handled.
3320 KdbpInvokeCliCallbacks(
3327 /* Loop all entries */
3328 for (i
= 0; i
< _countof(KdbCliCallbacks
); i
++)
3330 /* Check if this entry is registered */
3331 if (KdbCliCallbacks
[i
])
3333 /* Invoke the callback and check if it handled the command */
3334 if (KdbCliCallbacks
[i
](Command
, Argc
, Argv
))
3341 /* None of the callbacks handled the command */
3346 /*!\brief Parses command line and executes command if found
3348 * \param Command Command line to parse and execute if possible.
3350 * \retval TRUE Don't continue execution.
3351 * \retval FALSE Continue execution (leave KDB)
3360 // FIXME: for what do we need a 1024 characters command line and 256 tokens?
3361 static PCH Argv
[256];
3362 static CHAR OrigCommand
[1024];
3364 RtlStringCbCopyA(OrigCommand
, sizeof(OrigCommand
), Command
);
3371 while (*p
== '\t' || *p
== ' ')
3377 i
= strcspn(p
, "\t ");
3390 for (i
= 0; i
< RTL_NUMBER_OF(KdbDebuggerCommands
); i
++)
3392 if (!KdbDebuggerCommands
[i
].Name
)
3395 if (strcmp(KdbDebuggerCommands
[i
].Name
, Argv
[0]) == 0)
3397 return KdbDebuggerCommands
[i
].Fn(Argc
, Argv
);
3401 /* Now invoke the registered callbacks */
3402 if (KdbpInvokeCliCallbacks(Command
, Argc
, Argv
))
3407 KdbpPrint("Command '%s' is unknown.\n", OrigCommand
);
3411 /*!\brief KDB Main Loop.
3413 * \param EnteredOnSingleStep TRUE if KDB was entered on single step.
3417 IN BOOLEAN EnteredOnSingleStep
)
3419 static CHAR Command
[1024];
3422 if (EnteredOnSingleStep
)
3424 if (!KdbSymPrintAddress((PVOID
)KdbCurrentTrapFrame
->Tf
.Eip
, &KdbCurrentTrapFrame
->Tf
))
3426 KdbpPrint("<%x>", KdbCurrentTrapFrame
->Tf
.Eip
);
3430 if (KdbpDisassemble(KdbCurrentTrapFrame
->Tf
.Eip
, KdbUseIntelSyntax
) < 0)
3432 KdbpPrint("<INVALID>");
3437 /* Flush the input buffer */
3438 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
3440 while (KdbpTryGetCharSerial(1) != -1);
3445 while (KdbpTryGetCharKeyboard(&ScanCode
, 1) != -1);
3451 /* Reset the number of rows/cols printed */
3452 KdbNumberOfRowsPrinted
= KdbNumberOfColsPrinted
= 0;
3454 /* Print the prompt */
3455 KdbpPrint("kdb:> ");
3457 /* Read a command and remember it */
3458 KdbpReadCommand(Command
, sizeof (Command
));
3459 KdbpCommandHistoryAppend(Command
);
3461 /* Reset the number of rows/cols printed and output aborted state */
3462 KdbNumberOfRowsPrinted
= KdbNumberOfColsPrinted
= 0;
3463 KdbOutputAborted
= FALSE
;
3465 /* Call the command */
3466 Continue
= KdbpDoCommand(Command
);
3467 KdbOutputAborted
= FALSE
;
3472 /*!\brief Called when a module is loaded.
3474 * \param Name Filename of the module which was loaded.
3477 KdbpCliModuleLoaded(
3478 IN PUNICODE_STRING Name
)
3480 if (!KdbBreakOnModuleLoad
)
3483 KdbpPrint("Module %wZ loaded.\n", Name
);
3484 DbgBreakPointWithStatus(DBG_STATUS_CONTROL_C
);
3487 /*!\brief This function is called by KdbEnterDebuggerException...
3489 * Used to interpret the init file in a context with a trapframe setup
3490 * (KdbpCliInit call KdbEnter which will call KdbEnterDebuggerException which will
3491 * call this function if KdbInitFileBuffer is not NULL.
3494 KdbpCliInterpretInitFile()
3500 /* Execute the commands in the init file */
3501 DPRINT("KDB: Executing KDBinit file...\n");
3502 p1
= KdbInitFileBuffer
;
3503 while (p1
[0] != '\0')
3505 i
= strcspn(p1
, "\r\n");
3511 /* Look for "break" command and comments */
3514 while (isspace(p2
[0]))
3517 if (strncmp(p2
, "break", sizeof("break")-1) == 0 &&
3518 (p2
[sizeof("break")-1] == '\0' || isspace(p2
[sizeof("break")-1])))
3520 /* break into the debugger */
3521 KdbpCliMainLoop(FALSE
);
3523 else if (p2
[0] != '#' && p2
[0] != '\0') /* Ignore empty lines and comments */
3532 while (p1
[0] == '\r' || p1
[0] == '\n')
3535 DPRINT("KDB: KDBinit executed\n");
3538 /*!\brief Called when KDB is initialized
3540 * Reads the KDBinit file from the SystemRoot\system32\drivers\etc directory and executes it.
3546 OBJECT_ATTRIBUTES ObjectAttributes
;
3547 UNICODE_STRING FileName
;
3548 IO_STATUS_BLOCK Iosb
;
3549 FILE_STANDARD_INFORMATION FileStdInfo
;
3550 HANDLE hFile
= NULL
;
3555 /* Initialize the object attributes */
3556 RtlInitUnicodeString(&FileName
, L
"\\SystemRoot\\system32\\drivers\\etc\\KDBinit");
3557 InitializeObjectAttributes(&ObjectAttributes
, &FileName
, 0, NULL
, NULL
);
3560 Status
= ZwOpenFile(&hFile
, FILE_READ_DATA
, &ObjectAttributes
, &Iosb
, 0,
3561 FILE_NON_DIRECTORY_FILE
| FILE_SYNCHRONOUS_IO_NONALERT
|
3562 FILE_NO_INTERMEDIATE_BUFFERING
);
3563 if (!NT_SUCCESS(Status
))
3565 DPRINT("Could not open \\SystemRoot\\system32\\drivers\\etc\\KDBinit (Status 0x%x)", Status
);
3569 /* Get the size of the file */
3570 Status
= ZwQueryInformationFile(hFile
, &Iosb
, &FileStdInfo
, sizeof (FileStdInfo
),
3571 FileStandardInformation
);
3572 if (!NT_SUCCESS(Status
))
3575 DPRINT("Could not query size of \\SystemRoot\\system32\\drivers\\etc\\KDBinit (Status 0x%x)", Status
);
3578 FileSize
= FileStdInfo
.EndOfFile
.u
.LowPart
;
3580 /* Allocate memory for the file */
3581 FileBuffer
= ExAllocatePool(PagedPool
, FileSize
+ 1); /* add 1 byte for terminating '\0' */
3585 DPRINT("Could not allocate %d bytes for KDBinit file\n", FileSize
);
3589 /* Load file into memory */
3590 Status
= ZwReadFile(hFile
, 0, 0, 0, &Iosb
, FileBuffer
, FileSize
, 0, 0);
3593 if (!NT_SUCCESS(Status
) && Status
!= STATUS_END_OF_FILE
)
3595 ExFreePool(FileBuffer
);
3596 DPRINT("Could not read KDBinit file into memory (Status 0x%lx)\n", Status
);
3600 FileSize
= min(FileSize
, (INT
)Iosb
.Information
);
3601 FileBuffer
[FileSize
] = '\0';
3603 /* Enter critical section */
3604 OldEflags
= __readeflags();
3607 /* Interpret the init file... */
3608 KdbInitFileBuffer
= FileBuffer
;
3610 KdbInitFileBuffer
= NULL
;
3612 /* Leave critical section */
3613 __writeeflags(OldEflags
);
3615 ExFreePool(FileBuffer
);
3620 KdpSerialDebugPrint(
3625 STRING KdpPromptString
= RTL_CONSTANT_STRING("kdb:> ");
3626 extern KSPIN_LOCK KdpSerialSpinLock
;
3630 KdpPrompt(IN LPSTR InString
,
3631 IN USHORT InStringLength
,
3632 OUT LPSTR OutString
,
3633 IN USHORT OutStringLength
)
3637 ULONG DummyScanCode
;
3640 /* Acquire the printing spinlock without waiting at raised IRQL */
3643 /* Wait when the spinlock becomes available */
3644 while (!KeTestSpinLock(&KdpSerialSpinLock
));
3646 /* Spinlock was free, raise IRQL */
3647 KeRaiseIrql(HIGH_LEVEL
, &OldIrql
);
3649 /* Try to get the spinlock */
3650 if (KeTryToAcquireSpinLockAtDpcLevel(&KdpSerialSpinLock
))
3653 /* Someone else got the spinlock, lower IRQL back */
3654 KeLowerIrql(OldIrql
);
3657 /* Loop the string to send */
3658 for (i
= 0; i
< InStringLength
; i
++)
3660 /* Print it to serial */
3661 KdPortPutByteEx(&SerialPortInfo
, *(PCHAR
)(InString
+ i
));
3664 /* Print a new line for log neatness */
3665 KdPortPutByteEx(&SerialPortInfo
, '\r');
3666 KdPortPutByteEx(&SerialPortInfo
, '\n');
3668 /* Print the kdb prompt */
3669 for (i
= 0; i
< KdpPromptString
.Length
; i
++)
3671 /* Print it to serial */
3672 KdPortPutByteEx(&SerialPortInfo
,
3673 *(KdpPromptString
.Buffer
+ i
));
3676 if (!(KdbDebugState
& KD_DEBUG_KDSERIAL
))
3679 /* Loop the whole string */
3680 for (i
= 0; i
< OutStringLength
; i
++)
3682 /* Check if this is serial debugging mode */
3683 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
3685 /* Get the character from serial */
3688 Response
= KdbpTryGetCharSerial(MAXULONG
);
3689 } while (Response
== -1);
3693 /* Get the response from the keyboard */
3696 Response
= KdbpTryGetCharKeyboard(&DummyScanCode
, MAXULONG
);
3697 } while (Response
== -1);
3700 /* Check for return */
3701 if (Response
== '\r')
3704 * We might need to discard the next '\n'.
3705 * Wait a bit to make sure we receive it.
3707 KeStallExecutionProcessor(100000);
3709 /* Check the mode */
3710 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
3712 /* Read and discard the next character, if any */
3713 KdbpTryGetCharSerial(5);
3717 /* Read and discard the next character, if any */
3718 KdbpTryGetCharKeyboard(&DummyScanCode
, 5);
3722 * Null terminate the output string -- documentation states that
3723 * DbgPrompt does not null terminate, but it does
3725 *(PCHAR
)(OutString
+ i
) = 0;
3727 /* Print a new line */
3728 KdPortPutByteEx(&SerialPortInfo
, '\r');
3729 KdPortPutByteEx(&SerialPortInfo
, '\n');
3731 /* Release spinlock */
3732 KiReleaseSpinLock(&KdpSerialSpinLock
);
3734 /* Lower IRQL back */
3735 KeLowerIrql(OldIrql
);
3737 /* Return the length */
3738 return OutStringLength
+ 1;
3741 /* Write it back and print it to the log */
3742 *(PCHAR
)(OutString
+ i
) = Response
;
3743 KdPortPutByteEx(&SerialPortInfo
, Response
);
3746 if (!(KdbDebugState
& KD_DEBUG_KDSERIAL
))
3749 /* Print a new line */
3750 KdPortPutByteEx(&SerialPortInfo
, '\r');
3751 KdPortPutByteEx(&SerialPortInfo
, '\n');
3753 /* Release spinlock */
3754 KiReleaseSpinLock(&KdpSerialSpinLock
);
3756 /* Lower IRQL back */
3757 KeLowerIrql(OldIrql
);
3759 /* Return the length */
3760 return OutStringLength
;