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
[]);
93 BOOLEAN
ExpKdbgExtPool(ULONG Argc
, PCHAR Argv
[]);
96 static BOOLEAN
KdbpCmdPrintStruct(ULONG Argc
, PCHAR Argv
[]);
99 /* GLOBALS *******************************************************************/
101 static PKDBG_CLI_ROUTINE KdbCliCallbacks
[10];
102 static BOOLEAN KdbUseIntelSyntax
= FALSE
; /* Set to TRUE for intel syntax */
103 static BOOLEAN KdbBreakOnModuleLoad
= FALSE
; /* Set to TRUE to break into KDB when a module is loaded */
105 static CHAR KdbCommandHistoryBuffer
[2048]; /* Command history string ringbuffer */
106 static PCHAR KdbCommandHistory
[sizeof(KdbCommandHistoryBuffer
) / 8] = { NULL
}; /* Command history ringbuffer */
107 static LONG KdbCommandHistoryBufferIndex
= 0;
108 static LONG KdbCommandHistoryIndex
= 0;
110 static ULONG KdbNumberOfRowsPrinted
= 0;
111 static ULONG KdbNumberOfColsPrinted
= 0;
112 static BOOLEAN KdbOutputAborted
= FALSE
;
113 static BOOLEAN KdbRepeatLastCommand
= FALSE
;
114 static LONG KdbNumberOfRowsTerminal
= -1;
115 static LONG KdbNumberOfColsTerminal
= -1;
117 PCHAR KdbInitFileBuffer
= NULL
; /* Buffer where KDBinit file is loaded into during initialization */
118 BOOLEAN KdbpBugCheckRequested
= FALSE
;
121 /* defined in ../kd/kdio.c, declare here: */
122 extern volatile BOOLEAN KdbpIsInDmesgMode
;
123 extern const ULONG KdpDmesgBufferSize
;
124 extern PCHAR KdpDmesgBuffer
;
125 extern volatile ULONG KdpDmesgCurrentPosition
;
126 extern volatile ULONG KdpDmesgFreeBytes
;
127 extern volatile ULONG KdbDmesgTotalWritten
;
134 BOOLEAN (*Fn
)(ULONG Argc
, PCHAR Argv
[]);
135 } KdbDebuggerCommands
[] = {
137 { NULL
, NULL
, "Data", NULL
},
138 { "?", "? expression", "Evaluate expression.", KdbpCmdEvalExpression
},
139 { "disasm", "disasm [address] [L count]", "Disassemble count instructions at address.", KdbpCmdDisassembleX
},
140 { "x", "x [address] [L count]", "Display count dwords, starting at addr.", KdbpCmdDisassembleX
},
141 { "regs", "regs", "Display general purpose registers.", KdbpCmdRegs
},
142 { "cregs", "cregs", "Display control registers.", KdbpCmdRegs
},
143 { "sregs", "sregs", "Display status registers.", KdbpCmdRegs
},
144 { "dregs", "dregs", "Display debug registers.", KdbpCmdRegs
},
145 { "bt", "bt [*frameaddr|thread id]", "Prints current backtrace or from given frame addr", KdbpCmdBackTrace
},
147 { "dt", "dt [mod] [type] [addr]", "Print a struct. Addr is optional.", KdbpCmdPrintStruct
},
151 { NULL
, NULL
, "Flow control", NULL
},
152 { "cont", "cont", "Continue execution (leave debugger)", KdbpCmdContinue
},
153 { "step", "step [count]", "Execute single instructions, stepping into interrupts.", KdbpCmdStep
},
154 { "next", "next [count]", "Execute single instructions, skipping calls and reps.", KdbpCmdStep
},
155 { "bl", "bl", "List breakpoints.", KdbpCmdBreakPointList
},
156 { "be", "be [breakpoint]", "Enable breakpoint.", KdbpCmdEnableDisableClearBreakPoint
},
157 { "bd", "bd [breakpoint]", "Disable breakpoint.", KdbpCmdEnableDisableClearBreakPoint
},
158 { "bc", "bc [breakpoint]", "Clear breakpoint.", KdbpCmdEnableDisableClearBreakPoint
},
159 { "bpx", "bpx [address] [IF condition]", "Set software execution breakpoint at address.", KdbpCmdBreakPoint
},
160 { "bpm", "bpm [r|w|rw|x] [byte|word|dword] [address] [IF condition]", "Set memory breakpoint at address.", KdbpCmdBreakPoint
},
163 { NULL
, NULL
, "Process/Thread", NULL
},
164 { "thread", "thread [list[ pid]|[attach ]tid]", "List threads in current or specified process, display thread with given id or attach to thread.", KdbpCmdThread
},
165 { "proc", "proc [list|[attach ]pid]", "List processes, display process with given id or attach to process.", KdbpCmdProc
},
167 /* System information */
168 { NULL
, NULL
, "System info", NULL
},
169 { "mod", "mod [address]", "List all modules or the one containing address.", KdbpCmdMod
},
170 { "gdt", "gdt", "Display global descriptor table.", KdbpCmdGdtLdtIdt
},
171 { "ldt", "ldt", "Display local descriptor table.", KdbpCmdGdtLdtIdt
},
172 { "idt", "idt", "Display interrupt descriptor table.", KdbpCmdGdtLdtIdt
},
173 { "pcr", "pcr", "Display processor control region.", KdbpCmdPcr
},
174 { "tss", "tss", "Display task state segment.", KdbpCmdTss
},
177 { NULL
, NULL
, "Others", NULL
},
178 { "bugcheck", "bugcheck", "Bugchecks the system.", KdbpCmdBugCheck
},
179 { "filter", "filter [error|warning|trace|info|level]+|-[componentname|default]", "Enable/disable debug channels", KdbpCmdFilter
},
180 { "set", "set [var] [value]", "Sets var to value or displays value of var.", KdbpCmdSet
},
181 { "dmesg", "dmesg", "Display debug messages on screen, with navigation on pages.", KdbpCmdDmesg
},
182 { "kmsg", "kmsg", "Kernel dmesg. Alias for dmesg.", KdbpCmdDmesg
},
183 { "help", "help", "Display help screen.", KdbpCmdHelp
},
184 { "!pool", "!pool [Address [Flags]]", "Display information about pool allocations.", ExpKdbgExtPool
}
187 /* FUNCTIONS *****************************************************************/
189 /*!\brief Transform a component name to an integer
191 * \param ComponentName The name of the component.
192 * \param ComponentId Receives the component id on success.
194 * \retval TRUE Success.
195 * \retval FALSE Failure.
199 IN PCCH ComponentName
,
200 OUT PULONG ComponentId
)
211 { "DEFAULT", DPFLTR_DEFAULT_ID
},
212 { "SYSTEM", DPFLTR_SYSTEM_ID
},
213 { "SMSS", DPFLTR_SMSS_ID
},
214 { "SETUP", DPFLTR_SETUP_ID
},
215 { "NTFS", DPFLTR_NTFS_ID
},
216 { "FSTUB", DPFLTR_FSTUB_ID
},
217 { "CRASHDUMP", DPFLTR_CRASHDUMP_ID
},
218 { "CDAUDIO", DPFLTR_CDAUDIO_ID
},
219 { "CDROM", DPFLTR_CDROM_ID
},
220 { "CLASSPNP", DPFLTR_CLASSPNP_ID
},
221 { "DISK", DPFLTR_DISK_ID
},
222 { "REDBOOK", DPFLTR_REDBOOK_ID
},
223 { "STORPROP", DPFLTR_STORPROP_ID
},
224 { "SCSIPORT", DPFLTR_SCSIPORT_ID
},
225 { "SCSIMINIPORT", DPFLTR_SCSIMINIPORT_ID
},
226 { "CONFIG", DPFLTR_CONFIG_ID
},
227 { "I8042PRT", DPFLTR_I8042PRT_ID
},
228 { "SERMOUSE", DPFLTR_SERMOUSE_ID
},
229 { "LSERMOUS", DPFLTR_LSERMOUS_ID
},
230 { "KBDHID", DPFLTR_KBDHID_ID
},
231 { "MOUHID", DPFLTR_MOUHID_ID
},
232 { "KBDCLASS", DPFLTR_KBDCLASS_ID
},
233 { "MOUCLASS", DPFLTR_MOUCLASS_ID
},
234 { "TWOTRACK", DPFLTR_TWOTRACK_ID
},
235 { "WMILIB", DPFLTR_WMILIB_ID
},
236 { "ACPI", DPFLTR_ACPI_ID
},
237 { "AMLI", DPFLTR_AMLI_ID
},
238 { "HALIA64", DPFLTR_HALIA64_ID
},
239 { "VIDEO", DPFLTR_VIDEO_ID
},
240 { "SVCHOST", DPFLTR_SVCHOST_ID
},
241 { "VIDEOPRT", DPFLTR_VIDEOPRT_ID
},
242 { "TCPIP", DPFLTR_TCPIP_ID
},
243 { "DMSYNTH", DPFLTR_DMSYNTH_ID
},
244 { "NTOSPNP", DPFLTR_NTOSPNP_ID
},
245 { "FASTFAT", DPFLTR_FASTFAT_ID
},
246 { "SAMSS", DPFLTR_SAMSS_ID
},
247 { "PNPMGR", DPFLTR_PNPMGR_ID
},
248 { "NETAPI", DPFLTR_NETAPI_ID
},
249 { "SCSERVER", DPFLTR_SCSERVER_ID
},
250 { "SCCLIENT", DPFLTR_SCCLIENT_ID
},
251 { "SERIAL", DPFLTR_SERIAL_ID
},
252 { "SERENUM", DPFLTR_SERENUM_ID
},
253 { "UHCD", DPFLTR_UHCD_ID
},
254 { "RPCPROXY", DPFLTR_RPCPROXY_ID
},
255 { "AUTOCHK", DPFLTR_AUTOCHK_ID
},
256 { "DCOMSS", DPFLTR_DCOMSS_ID
},
257 { "UNIMODEM", DPFLTR_UNIMODEM_ID
},
258 { "SIS", DPFLTR_SIS_ID
},
259 { "FLTMGR", DPFLTR_FLTMGR_ID
},
260 { "WMICORE", DPFLTR_WMICORE_ID
},
261 { "BURNENG", DPFLTR_BURNENG_ID
},
262 { "IMAPI", DPFLTR_IMAPI_ID
},
263 { "SXS", DPFLTR_SXS_ID
},
264 { "FUSION", DPFLTR_FUSION_ID
},
265 { "IDLETASK", DPFLTR_IDLETASK_ID
},
266 { "SOFTPCI", DPFLTR_SOFTPCI_ID
},
267 { "TAPE", DPFLTR_TAPE_ID
},
268 { "MCHGR", DPFLTR_MCHGR_ID
},
269 { "IDEP", DPFLTR_IDEP_ID
},
270 { "PCIIDE", DPFLTR_PCIIDE_ID
},
271 { "FLOPPY", DPFLTR_FLOPPY_ID
},
272 { "FDC", DPFLTR_FDC_ID
},
273 { "TERMSRV", DPFLTR_TERMSRV_ID
},
274 { "W32TIME", DPFLTR_W32TIME_ID
},
275 { "PREFETCHER", DPFLTR_PREFETCHER_ID
},
276 { "RSFILTER", DPFLTR_RSFILTER_ID
},
277 { "FCPORT", DPFLTR_FCPORT_ID
},
278 { "PCI", DPFLTR_PCI_ID
},
279 { "DMIO", DPFLTR_DMIO_ID
},
280 { "DMCONFIG", DPFLTR_DMCONFIG_ID
},
281 { "DMADMIN", DPFLTR_DMADMIN_ID
},
282 { "WSOCKTRANSPORT", DPFLTR_WSOCKTRANSPORT_ID
},
283 { "VSS", DPFLTR_VSS_ID
},
284 { "PNPMEM", DPFLTR_PNPMEM_ID
},
285 { "PROCESSOR", DPFLTR_PROCESSOR_ID
},
286 { "DMSERVER", DPFLTR_DMSERVER_ID
},
287 { "SR", DPFLTR_SR_ID
},
288 { "INFINIBAND", DPFLTR_INFINIBAND_ID
},
289 { "IHVDRIVER", DPFLTR_IHVDRIVER_ID
},
290 { "IHVVIDEO", DPFLTR_IHVVIDEO_ID
},
291 { "IHVAUDIO", DPFLTR_IHVAUDIO_ID
},
292 { "IHVNETWORK", DPFLTR_IHVNETWORK_ID
},
293 { "IHVSTREAMING", DPFLTR_IHVSTREAMING_ID
},
294 { "IHVBUS", DPFLTR_IHVBUS_ID
},
295 { "HPS", DPFLTR_HPS_ID
},
296 { "RTLTHREADPOOL", DPFLTR_RTLTHREADPOOL_ID
},
297 { "LDR", DPFLTR_LDR_ID
},
298 { "TCPIP6", DPFLTR_TCPIP6_ID
},
299 { "ISAPNP", DPFLTR_ISAPNP_ID
},
300 { "SHPC", DPFLTR_SHPC_ID
},
301 { "STORPORT", DPFLTR_STORPORT_ID
},
302 { "STORMINIPORT", DPFLTR_STORMINIPORT_ID
},
303 { "PRINTSPOOLER", DPFLTR_PRINTSPOOLER_ID
},
304 { "VSSDYNDISK", DPFLTR_VSSDYNDISK_ID
},
305 { "VERIFIER", DPFLTR_VERIFIER_ID
},
306 { "VDS", DPFLTR_VDS_ID
},
307 { "VDSBAS", DPFLTR_VDSBAS_ID
},
308 { "VDSDYN", DPFLTR_VDSDYN_ID
},
309 { "VDSDYNDR", DPFLTR_VDSDYNDR_ID
},
310 { "VDSLDR", DPFLTR_VDSLDR_ID
},
311 { "VDSUTIL", DPFLTR_VDSUTIL_ID
},
312 { "DFRGIFC", DPFLTR_DFRGIFC_ID
},
313 { "MM", DPFLTR_MM_ID
},
314 { "DFSC", DPFLTR_DFSC_ID
},
315 { "WOW64", DPFLTR_WOW64_ID
},
316 { "ALPC", DPFLTR_ALPC_ID
},
317 { "WDI", DPFLTR_WDI_ID
},
318 { "PERFLIB", DPFLTR_PERFLIB_ID
},
319 { "KTM", DPFLTR_KTM_ID
},
320 { "IOSTRESS", DPFLTR_IOSTRESS_ID
},
321 { "HEAP", DPFLTR_HEAP_ID
},
322 { "WHEA", DPFLTR_WHEA_ID
},
323 { "USERGDI", DPFLTR_USERGDI_ID
},
324 { "MMCSS", DPFLTR_MMCSS_ID
},
325 { "TPM", DPFLTR_TPM_ID
},
326 { "THREADORDER", DPFLTR_THREADORDER_ID
},
327 { "ENVIRON", DPFLTR_ENVIRON_ID
},
328 { "EMS", DPFLTR_EMS_ID
},
329 { "WDT", DPFLTR_WDT_ID
},
330 { "FVEVOL", DPFLTR_FVEVOL_ID
},
331 { "NDIS", DPFLTR_NDIS_ID
},
332 { "NVCTRACE", DPFLTR_NVCTRACE_ID
},
333 { "LUAFV", DPFLTR_LUAFV_ID
},
334 { "APPCOMPAT", DPFLTR_APPCOMPAT_ID
},
335 { "USBSTOR", DPFLTR_USBSTOR_ID
},
336 { "SBP2PORT", DPFLTR_SBP2PORT_ID
},
337 { "COVERAGE", DPFLTR_COVERAGE_ID
},
338 { "CACHEMGR", DPFLTR_CACHEMGR_ID
},
339 { "MOUNTMGR", DPFLTR_MOUNTMGR_ID
},
340 { "CFR", DPFLTR_CFR_ID
},
341 { "TXF", DPFLTR_TXF_ID
},
342 { "KSECDD", DPFLTR_KSECDD_ID
},
343 { "FLTREGRESS", DPFLTR_FLTREGRESS_ID
},
344 { "MPIO", DPFLTR_MPIO_ID
},
345 { "MSDSM", DPFLTR_MSDSM_ID
},
346 { "UDFS", DPFLTR_UDFS_ID
},
347 { "PSHED", DPFLTR_PSHED_ID
},
348 { "STORVSP", DPFLTR_STORVSP_ID
},
349 { "LSASS", DPFLTR_LSASS_ID
},
350 { "SSPICLI", DPFLTR_SSPICLI_ID
},
351 { "CNG", DPFLTR_CNG_ID
},
352 { "EXFAT", DPFLTR_EXFAT_ID
},
353 { "FILETRACE", DPFLTR_FILETRACE_ID
},
354 { "XSAVE", DPFLTR_XSAVE_ID
},
355 { "SE", DPFLTR_SE_ID
},
356 { "DRIVEEXTENDER", DPFLTR_DRIVEEXTENDER_ID
},
359 for (i
= 0; i
< sizeof(ComponentTable
) / sizeof(ComponentTable
[0]); i
++)
361 if (_stricmp(ComponentName
, ComponentTable
[i
].Name
) == 0)
363 *ComponentId
= ComponentTable
[i
].Id
;
371 /*!\brief Evaluates an expression...
373 * Much like KdbpRpnEvaluateExpression, but prints the error message (if any)
374 * at the given offset.
376 * \param Expression Expression to evaluate.
377 * \param ErrOffset Offset (in characters) to print the error message at.
378 * \param Result Receives the result on success.
380 * \retval TRUE Success.
381 * \retval FALSE Failure.
384 KdbpEvaluateExpression(
387 OUT PULONGLONG Result
)
389 static CHAR ErrMsgBuffer
[130] = "^ ";
390 LONG ExpressionErrOffset
= -1;
391 PCHAR ErrMsg
= ErrMsgBuffer
;
394 Ok
= KdbpRpnEvaluateExpression(Expression
, KdbCurrentTrapFrame
, Result
,
395 &ExpressionErrOffset
, ErrMsgBuffer
+ 2);
398 if (ExpressionErrOffset
>= 0)
399 ExpressionErrOffset
+= ErrOffset
;
403 KdbpPrint("%*s%s\n", ExpressionErrOffset
, "", ErrMsg
);
413 OUT ULONG_PTR
*pulValue
)
417 /* Skip optional '0x' prefix */
418 if ((pszNum
[0] == '0') && ((pszNum
[1] == 'x') || (pszNum
[1] == 'X')))
421 /* Make a number from the string (hex) */
422 *pulValue
= strtoul(pszNum
, &endptr
, 16);
424 return (*endptr
== '\0');
427 /*!\brief Evaluates an expression and displays the result.
430 KdbpCmdEvalExpression(
435 ULONGLONG Result
= 0;
442 KdbpPrint("?: Argument required\n");
446 /* Put the arguments back together */
448 for (i
= 1; i
< Argc
; i
++)
450 len
= strlen(Argv
[i
]);
454 /* Evaluate the expression */
455 Ok
= KdbpEvaluateExpression(Argv
[1], sizeof("kdb:> ")-1 + (Argv
[1]-Argv
[0]), &Result
);
458 if (Result
> 0x00000000ffffffffLL
)
460 if (Result
& 0x8000000000000000LL
)
461 KdbpPrint("0x%016I64x %20I64u %20I64d\n", Result
, Result
, Result
);
463 KdbpPrint("0x%016I64x %20I64u\n", Result
, Result
);
469 if (ul
<= 0xff && ul
>= 0x80)
470 l
= (LONG
)((CHAR
)ul
);
471 else if (ul
<= 0xffff && ul
>= 0x8000)
472 l
= (LONG
)((SHORT
)ul
);
477 KdbpPrint("0x%08lx %10lu %10ld\n", ul
, ul
, l
);
479 KdbpPrint("0x%08lx %10lu\n", ul
, ul
);
488 /*!\brief Print a struct
491 KdbpPrintStructInternal
496 PROSSYM_AGGREGATE Aggregate
)
500 PROSSYM_AGGREGATE_MEMBER Member
;
501 ULONG IndentLen
= strlen(Indent
);
502 ROSSYM_AGGREGATE MemberAggregate
= {0 };
504 for (i
= 0; i
< Aggregate
->NumElements
; i
++) {
505 Member
= &Aggregate
->Elements
[i
];
506 KdbpPrint("%s%p+%x: %s", Indent
, ((PCHAR
)BaseAddress
) + Member
->BaseOffset
, Member
->Size
, Member
->Name
? Member
->Name
: "<anoymous>");
508 if (!strcmp(Member
->Type
, "_UNICODE_STRING")) {
509 KdbpPrint("\"%wZ\"\n", ((PCHAR
)BaseAddress
) + Member
->BaseOffset
);
511 } else if (!strcmp(Member
->Type
, "PUNICODE_STRING")) {
512 KdbpPrint("\"%wZ\"\n", *(((PUNICODE_STRING
*)((PCHAR
)BaseAddress
) + Member
->BaseOffset
)));
515 switch (Member
->Size
) {
521 if (NT_SUCCESS(KdbpSafeReadMemory(&Result
, ((PCHAR
)BaseAddress
) + Member
->BaseOffset
, Member
->Size
))) {
523 Result
>>= Member
->FirstBit
;
524 Result
&= ((1 << Member
->Bits
) - 1);
526 KdbpPrint(" %lx\n", Result
);
532 if (Member
->Size
< 8) {
533 if (NT_SUCCESS(KdbpSafeReadMemory(&Result
, ((PCHAR
)BaseAddress
) + Member
->BaseOffset
, Member
->Size
))) {
535 for (j
= 0; j
< Member
->Size
; j
++) {
536 KdbpPrint(" %02x", (int)(Result
& 0xff));
539 } else goto readfail
;
541 KdbpPrint(" %s @ %p {\n", Member
->Type
, ((PCHAR
)BaseAddress
) + Member
->BaseOffset
);
542 Indent
[IndentLen
] = ' ';
543 if (RosSymAggregate(Info
, Member
->Type
, &MemberAggregate
)) {
544 KdbpPrintStructInternal(Info
, Indent
, DoRead
, ((PCHAR
)BaseAddress
) + Member
->BaseOffset
, &MemberAggregate
);
545 RosSymFreeAggregate(&MemberAggregate
);
547 Indent
[IndentLen
] = 0;
548 KdbpPrint("%s}\n", Indent
);
554 if (Member
->Size
<= 8) {
557 KdbpPrint(" %s @ %x {\n", Member
->Type
, Member
->BaseOffset
);
558 Indent
[IndentLen
] = ' ';
559 if (RosSymAggregate(Info
, Member
->Type
, &MemberAggregate
)) {
560 KdbpPrintStructInternal(Info
, Indent
, DoRead
, BaseAddress
, &MemberAggregate
);
561 RosSymFreeAggregate(&MemberAggregate
);
563 Indent
[IndentLen
] = 0;
564 KdbpPrint("%s}\n", Indent
);
570 PROSSYM_INFO
KdbpSymFindCachedFile(PUNICODE_STRING ModName
);
578 ULONGLONG Result
= 0;
579 PVOID BaseAddress
= 0;
580 ROSSYM_AGGREGATE Aggregate
= {0};
581 UNICODE_STRING ModName
= {0};
582 ANSI_STRING AnsiName
= {0};
583 CHAR Indent
[100] = {0};
586 if (Argc
< 3) goto end
;
587 AnsiName
.Length
= AnsiName
.MaximumLength
= strlen(Argv
[1]);
588 AnsiName
.Buffer
= Argv
[1];
589 RtlAnsiStringToUnicodeString(&ModName
, &AnsiName
, TRUE
);
590 Info
= KdbpSymFindCachedFile(&ModName
);
592 if (!Info
|| !RosSymAggregate(Info
, Argv
[2], &Aggregate
)) {
593 DPRINT1("Could not get aggregate\n");
597 // Get an argument for location if it was given
600 PCHAR ArgStart
= Argv
[3];
601 DPRINT1("Trying to get expression\n");
602 for (i
= 3; i
< Argc
- 1; i
++)
604 len
= strlen(Argv
[i
]);
608 /* Evaluate the expression */
609 DPRINT1("Arg: %s\n", ArgStart
);
610 if (KdbpEvaluateExpression(ArgStart
, strlen(ArgStart
), &Result
)) {
611 BaseAddress
= (PVOID
)(ULONG_PTR
)Result
;
612 DPRINT1("BaseAddress: %p\n", BaseAddress
);
615 DPRINT1("BaseAddress %p\n", BaseAddress
);
616 KdbpPrintStructInternal(Info
, Indent
, !!BaseAddress
, BaseAddress
, &Aggregate
);
618 RosSymFreeAggregate(&Aggregate
);
619 RtlFreeUnicodeString(&ModName
);
624 /*!\brief Display list of active debug channels
631 ULONG i
, j
, ComponentId
, Level
;
632 ULONG set
= DPFLTR_MASK
, clear
= DPFLTR_MASK
;
643 { "error", 1 << DPFLTR_ERROR_LEVEL
},
644 { "warning", 1 << DPFLTR_WARNING_LEVEL
},
645 { "trace", 1 << DPFLTR_TRACE_LEVEL
},
646 { "info", 1 << DPFLTR_INFO_LEVEL
},
649 for (i
= 1; i
< Argc
; i
++)
652 p
= opt
+ strcspn(opt
, "+-");
653 if (!p
[0]) p
= opt
; /* assume it's a debug channel name */
657 for (j
= 0; j
< sizeof(debug_classes
) / sizeof(debug_classes
[0]); j
++)
659 SIZE_T len
= strlen(debug_classes
[j
].Name
);
660 if (len
!= (p
- opt
))
662 if (_strnicmp(opt
, debug_classes
[j
].Name
, len
) == 0) /* found it */
665 set
|= debug_classes
[j
].Level
;
667 clear
|= debug_classes
[j
].Level
;
671 if (j
== sizeof(debug_classes
) / sizeof(debug_classes
[0]))
673 Level
= strtoul(opt
, &pend
, 0);
676 KdbpPrint("filter: bad class name '%.*s'\n", p
- opt
, opt
);
692 if (*p
== '+' || *p
== '-')
695 if (!KdbpGetComponentId(p
, &ComponentId
))
697 KdbpPrint("filter: '%s' is not a valid component name!\n", p
);
701 /* Get current mask value */
702 NtSetDebugFilterState(ComponentId
, set
, TRUE
);
703 NtSetDebugFilterState(ComponentId
, clear
, FALSE
);
709 /*!\brief Disassembles 10 instructions at eip or given address or
710 * displays 16 dwords from memory at given address.
720 ULONGLONG Result
= 0;
721 ULONG_PTR Address
= KdbCurrentTrapFrame
->Tf
.Eip
;
724 if (Argv
[0][0] == 'x') /* display memory */
726 else /* disassemble */
731 /* Check for [L count] part */
733 if (strcmp(Argv
[Argc
-2], "L") == 0)
735 ul
= strtoul(Argv
[Argc
-1], NULL
, 0);
742 else if (Argv
[Argc
-1][0] == 'L')
744 ul
= strtoul(Argv
[Argc
-1] + 1, NULL
, 0);
752 /* Put the remaining arguments back together */
754 for (ul
= 1; ul
< Argc
; ul
++)
756 Argv
[ul
][strlen(Argv
[ul
])] = ' ';
761 /* Evaluate the expression */
764 if (!KdbpEvaluateExpression(Argv
[1], sizeof("kdb:> ")-1 + (Argv
[1]-Argv
[0]), &Result
))
767 if (Result
> (ULONGLONG
)(~((ULONG_PTR
)0)))
768 KdbpPrint("Warning: Address %I64x is beeing truncated\n",Result
);
770 Address
= (ULONG_PTR
)Result
;
772 else if (Argv
[0][0] == 'x')
774 KdbpPrint("x: Address argument required.\n");
778 if (Argv
[0][0] == 'x')
785 if (!KdbSymPrintAddress((PVOID
)Address
, NULL
))
786 KdbpPrint("<%x>:", Address
);
795 if (!NT_SUCCESS(KdbpSafeReadMemory(&ul
, (PVOID
)Address
, sizeof(ul
))))
796 KdbpPrint(" ????????");
798 KdbpPrint(" %08x", ul
);
800 Address
+= sizeof(ul
);
811 if (!KdbSymPrintAddress((PVOID
)Address
, NULL
))
812 KdbpPrint("<%08x>: ", Address
);
816 InstLen
= KdbpDisassemble(Address
, KdbUseIntelSyntax
);
819 KdbpPrint("<INVALID>\n");
831 /*!\brief Displays CPU registers.
838 PKTRAP_FRAME Tf
= &KdbCurrentTrapFrame
->Tf
;
840 static const PCHAR EflagsBits
[32] = { " CF", NULL
, " PF", " BIT3", " AF", " BIT5",
841 " ZF", " SF", " TF", " IF", " DF", " OF",
842 NULL
, NULL
, " NT", " BIT15", " RF", " VF",
843 " AC", " VIF", " VIP", " ID", " BIT22",
844 " BIT23", " BIT24", " BIT25", " BIT26",
845 " BIT27", " BIT28", " BIT29", " BIT30",
848 if (Argv
[0][0] == 'r') /* regs */
850 KdbpPrint("CS:EIP 0x%04x:0x%08x\n"
851 "SS:ESP 0x%04x:0x%08x\n"
852 " EAX 0x%08x EBX 0x%08x\n"
853 " ECX 0x%08x EDX 0x%08x\n"
854 " ESI 0x%08x EDI 0x%08x\n"
856 Tf
->SegCs
& 0xFFFF, Tf
->Eip
,
857 Tf
->HardwareSegSs
, Tf
->HardwareEsp
,
862 KdbpPrint("EFLAGS 0x%08x ", Tf
->EFlags
);
864 for (i
= 0; i
< 32; i
++)
868 if ((Tf
->EFlags
& (1 << 1)) == 0)
873 KdbpPrint(" IOPL%d", (Tf
->EFlags
>> 12) & 3);
878 else if ((Tf
->EFlags
& (1 << i
)) != 0)
880 KdbpPrint(EflagsBits
[i
]);
886 else if (Argv
[0][0] == 'c') /* cregs */
888 ULONG Cr0
, Cr2
, Cr3
, Cr4
;
889 KDESCRIPTOR Gdtr
= {0, 0, 0}, Idtr
= {0, 0, 0};
891 static const PCHAR Cr0Bits
[32] = { " PE", " MP", " EM", " TS", " ET", " NE", NULL
, NULL
,
892 NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
,
893 " WP", NULL
, " AM", NULL
, NULL
, NULL
, NULL
, NULL
,
894 NULL
, NULL
, NULL
, NULL
, NULL
, " NW", " CD", " PG" };
895 static const PCHAR Cr4Bits
[32] = { " VME", " PVI", " TSD", " DE", " PSE", " PAE", " MCE", " PGE",
896 " PCE", " OSFXSR", " OSXMMEXCPT", NULL
, NULL
, NULL
, NULL
, NULL
,
897 NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
,
898 NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
};
900 Cr0
= KdbCurrentTrapFrame
->Cr0
;
901 Cr2
= KdbCurrentTrapFrame
->Cr2
;
902 Cr3
= KdbCurrentTrapFrame
->Cr3
;
903 Cr4
= KdbCurrentTrapFrame
->Cr4
;
905 /* Get descriptor table regs */
906 Ke386GetGlobalDescriptorTable(&Gdtr
.Limit
);
907 Ldtr
= Ke386GetLocalDescriptorTable();
910 /* Display the control registers */
911 KdbpPrint("CR0 0x%08x ", Cr0
);
913 for (i
= 0; i
< 32; i
++)
918 if ((Cr0
& (1 << i
)) != 0)
919 KdbpPrint(Cr0Bits
[i
]);
922 KdbpPrint("\nCR2 0x%08x\n", Cr2
);
923 KdbpPrint("CR3 0x%08x Pagedir-Base 0x%08x %s%s\n", Cr3
, (Cr3
& 0xfffff000),
924 (Cr3
& (1 << 3)) ? " PWT" : "", (Cr3
& (1 << 4)) ? " PCD" : "" );
925 KdbpPrint("CR4 0x%08x ", Cr4
);
927 for (i
= 0; i
< 32; i
++)
932 if ((Cr4
& (1 << i
)) != 0)
933 KdbpPrint(Cr4Bits
[i
]);
936 /* Display the descriptor table regs */
937 KdbpPrint("\nGDTR Base 0x%08x Size 0x%04x\n", Gdtr
.Base
, Gdtr
.Limit
);
938 KdbpPrint("LDTR 0x%04x\n", Ldtr
);
939 KdbpPrint("IDTR Base 0x%08x Size 0x%04x\n", Idtr
.Base
, Idtr
.Limit
);
941 else if (Argv
[0][0] == 's') /* sregs */
943 KdbpPrint("CS 0x%04x Index 0x%04x %cDT RPL%d\n",
944 Tf
->SegCs
& 0xffff, (Tf
->SegCs
& 0xffff) >> 3,
945 (Tf
->SegCs
& (1 << 2)) ? 'L' : 'G', Tf
->SegCs
& 3);
946 KdbpPrint("DS 0x%04x Index 0x%04x %cDT RPL%d\n",
947 Tf
->SegDs
, Tf
->SegDs
>> 3, (Tf
->SegDs
& (1 << 2)) ? 'L' : 'G', Tf
->SegDs
& 3);
948 KdbpPrint("ES 0x%04x Index 0x%04x %cDT RPL%d\n",
949 Tf
->SegEs
, Tf
->SegEs
>> 3, (Tf
->SegEs
& (1 << 2)) ? 'L' : 'G', Tf
->SegEs
& 3);
950 KdbpPrint("FS 0x%04x Index 0x%04x %cDT RPL%d\n",
951 Tf
->SegFs
, Tf
->SegFs
>> 3, (Tf
->SegFs
& (1 << 2)) ? 'L' : 'G', Tf
->SegFs
& 3);
952 KdbpPrint("GS 0x%04x Index 0x%04x %cDT RPL%d\n",
953 Tf
->SegGs
, Tf
->SegGs
>> 3, (Tf
->SegGs
& (1 << 2)) ? 'L' : 'G', Tf
->SegGs
& 3);
954 KdbpPrint("SS 0x%04x Index 0x%04x %cDT RPL%d\n",
955 Tf
->HardwareSegSs
, Tf
->HardwareSegSs
>> 3, (Tf
->HardwareSegSs
& (1 << 2)) ? 'L' : 'G', Tf
->HardwareSegSs
& 3);
959 ASSERT(Argv
[0][0] == 'd');
960 KdbpPrint("DR0 0x%08x\n"
966 Tf
->Dr0
, Tf
->Dr1
, Tf
->Dr2
, Tf
->Dr3
,
974 KdbpTrapFrameFromPrevTss(
975 PKTRAP_FRAME TrapFrame
)
983 Ke386GetGlobalDescriptorTable(&Gdtr
.Limit
);
986 if ((Sel
& (sizeof(KGDTENTRY
) - 1)) ||
987 (Sel
< sizeof(KGDTENTRY
)) ||
988 (Sel
+ sizeof(KGDTENTRY
) - 1 > Gdtr
.Limit
))
991 if (!NT_SUCCESS(KdbpSafeReadMemory(&Desc
,
992 (PVOID
)(Gdtr
.Base
+ Sel
),
996 if (Desc
.HighWord
.Bits
.Type
!= 0xB)
999 Tss
= (PKTSS
)(ULONG_PTR
)(Desc
.BaseLow
|
1000 Desc
.HighWord
.Bytes
.BaseMid
<< 16 |
1001 Desc
.HighWord
.Bytes
.BaseHi
<< 24);
1003 if (!NT_SUCCESS(KdbpSafeReadMemory(&Sel
,
1004 (PVOID
)&Tss
->Backlink
,
1008 if ((Sel
& (sizeof(KGDTENTRY
) - 1)) ||
1009 (Sel
< sizeof(KGDTENTRY
)) ||
1010 (Sel
+ sizeof(KGDTENTRY
) - 1 > Gdtr
.Limit
))
1013 if (!NT_SUCCESS(KdbpSafeReadMemory(&Desc
,
1014 (PVOID
)(Gdtr
.Base
+ Sel
),
1015 sizeof(KGDTENTRY
))))
1018 if (Desc
.HighWord
.Bits
.Type
!= 0xB)
1021 Tss
= (PKTSS
)(ULONG_PTR
)(Desc
.BaseLow
|
1022 Desc
.HighWord
.Bytes
.BaseMid
<< 16 |
1023 Desc
.HighWord
.Bytes
.BaseHi
<< 24);
1025 if (!NT_SUCCESS(KdbpSafeReadMemory(&Eip
,
1027 sizeof(ULONG_PTR
))))
1030 if (!NT_SUCCESS(KdbpSafeReadMemory(&Ebp
,
1032 sizeof(ULONG_PTR
))))
1035 TrapFrame
->Eip
= Eip
;
1036 TrapFrame
->Ebp
= Ebp
;
1040 VOID __cdecl
KiTrap02(VOID
);
1041 VOID FASTCALL
KiTrap03Handler(IN PKTRAP_FRAME
);
1042 VOID __cdecl
KiTrap08(VOID
);
1043 VOID __cdecl
KiTrap09(VOID
);
1046 KdbpInNmiOrDoubleFaultHandler(
1049 return (Address
> (ULONG_PTR
)KiTrap02
&& Address
< (ULONG_PTR
)KiTrap03Handler
) ||
1050 (Address
> (ULONG_PTR
)KiTrap08
&& Address
< (ULONG_PTR
)KiTrap09
);
1053 /*!\brief Displays a backtrace.
1061 ULONGLONG Result
= 0;
1062 ULONG_PTR Frame
= KdbCurrentTrapFrame
->Tf
.Ebp
;
1064 KTRAP_FRAME TrapFrame
;
1068 /* Check for [L count] part */
1071 if (strcmp(Argv
[Argc
-2], "L") == 0)
1073 ul
= strtoul(Argv
[Argc
-1], NULL
, 0);
1079 else if (Argv
[Argc
-1][0] == 'L')
1081 ul
= strtoul(Argv
[Argc
-1] + 1, NULL
, 0);
1088 /* Put the remaining arguments back together */
1090 for (ul
= 1; ul
< Argc
; ul
++)
1092 Argv
[ul
][strlen(Argv
[ul
])] = ' ';
1097 /* Check if frame addr or thread id is given. */
1100 if (Argv
[1][0] == '*')
1104 /* Evaluate the expression */
1105 if (!KdbpEvaluateExpression(Argv
[1], sizeof("kdb:> ")-1 + (Argv
[1]-Argv
[0]), &Result
))
1108 if (Result
> (ULONGLONG
)(~((ULONG_PTR
)0)))
1109 KdbpPrint("Warning: Address %I64x is beeing truncated\n",Result
);
1111 Frame
= (ULONG_PTR
)Result
;
1115 KdbpPrint("Thread backtrace not supported yet!\n");
1121 KdbpPrint("Eip:\n");
1123 /* Try printing the function at EIP */
1124 if (!KdbSymPrintAddress((PVOID
)KdbCurrentTrapFrame
->Tf
.Eip
, &KdbCurrentTrapFrame
->Tf
))
1125 KdbpPrint("<%08x>\n", KdbCurrentTrapFrame
->Tf
.Eip
);
1130 TrapFrame
= KdbCurrentTrapFrame
->Tf
;
1131 KdbpPrint("Frames:\n");
1135 BOOLEAN GotNextFrame
;
1140 if (!NT_SUCCESS(KdbpSafeReadMemory(&Address
, (PVOID
)(Frame
+ sizeof(ULONG_PTR
)), sizeof (ULONG_PTR
))))
1142 KdbpPrint("Couldn't access memory at 0x%p!\n", Frame
+ sizeof(ULONG_PTR
));
1146 if ((GotNextFrame
= NT_SUCCESS(KdbpSafeReadMemory(&Frame
, (PVOID
)Frame
, sizeof (ULONG_PTR
)))))
1147 TrapFrame
.Ebp
= Frame
;
1149 /* Print the location of the call instruction */
1150 if (!KdbSymPrintAddress((PVOID
)(Address
- 5), &TrapFrame
))
1151 KdbpPrint("<%08x>\n", Address
);
1155 if (KdbOutputAborted
) break;
1160 if (KdbpInNmiOrDoubleFaultHandler(Address
))
1162 if ((GotNextFrame
= KdbpTrapFrameFromPrevTss(&TrapFrame
)))
1164 Address
= TrapFrame
.Eip
;
1165 Frame
= TrapFrame
.Ebp
;
1167 if (!KdbSymPrintAddress((PVOID
)Address
, &TrapFrame
))
1168 KdbpPrint("<%08x>\n", Address
);
1176 KdbpPrint("Couldn't access memory at 0x%p!\n", Frame
);
1184 /*!\brief Continues execution of the system/leaves KDB.
1191 /* Exit the main loop */
1195 /*!\brief Continues execution of the system/leaves KDB.
1206 Count
= strtoul(Argv
[1], NULL
, 0);
1209 KdbpPrint("%s: Integer argument required\n", Argv
[0]);
1214 if (Argv
[0][0] == 'n')
1215 KdbSingleStepOver
= TRUE
;
1217 KdbSingleStepOver
= FALSE
;
1219 /* Set the number of single steps and return to the interrupted code. */
1220 KdbNumSingleSteps
= Count
;
1225 /*!\brief Lists breakpoints.
1228 KdbpCmdBreakPointList(
1233 ULONG_PTR Address
= 0;
1234 KDB_BREAKPOINT_TYPE Type
= 0;
1235 KDB_ACCESS_TYPE AccessType
= 0;
1238 BOOLEAN Enabled
= FALSE
;
1239 BOOLEAN Global
= FALSE
;
1240 PEPROCESS Process
= NULL
;
1241 PCHAR str1
, str2
, ConditionExpr
, GlobalOrLocal
;
1244 l
= KdbpGetNextBreakPointNr(0);
1247 KdbpPrint("No breakpoints.\n");
1251 KdbpPrint("Breakpoints:\n");
1254 if (!KdbpGetBreakPointInfo(l
, &Address
, &Type
, &Size
, &AccessType
, &DebugReg
,
1255 &Enabled
, &Global
, &Process
, &ConditionExpr
))
1260 if (l
== KdbLastBreakPointNr
)
1273 GlobalOrLocal
= " global";
1277 GlobalOrLocal
= Buffer
;
1278 sprintf(Buffer
, " PID 0x%08lx",
1279 (ULONG
)(Process
? Process
->UniqueProcessId
: INVALID_HANDLE_VALUE
));
1282 if (Type
== KdbBreakPointSoftware
|| Type
== KdbBreakPointTemporary
)
1284 KdbpPrint(" %s%03d BPX 0x%08x%s%s%s%s%s\n",
1286 Enabled
? "" : " disabled",
1288 ConditionExpr
? " IF " : "",
1289 ConditionExpr
? ConditionExpr
: "",
1292 else if (Type
== KdbBreakPointHardware
)
1296 KdbpPrint(" %s%03d BPM 0x%08x %-5s %-5s disabled%s%s%s%s\n", str1
, l
, Address
,
1297 KDB_ACCESS_TYPE_TO_STRING(AccessType
),
1298 Size
== 1 ? "byte" : (Size
== 2 ? "word" : "dword"),
1300 ConditionExpr
? " IF " : "",
1301 ConditionExpr
? ConditionExpr
: "",
1306 KdbpPrint(" %s%03d BPM 0x%08x %-5s %-5s DR%d%s%s%s%s\n", str1
, l
, Address
,
1307 KDB_ACCESS_TYPE_TO_STRING(AccessType
),
1308 Size
== 1 ? "byte" : (Size
== 2 ? "word" : "dword"),
1311 ConditionExpr
? " IF " : "",
1312 ConditionExpr
? ConditionExpr
: "",
1317 while ((l
= KdbpGetNextBreakPointNr(l
+1)) >= 0);
1322 /*!\brief Enables, disables or clears a breakpoint.
1325 KdbpCmdEnableDisableClearBreakPoint(
1334 KdbpPrint("%s: argument required\n", Argv
[0]);
1339 BreakPointNr
= strtoul(Argv
[1], &pend
, 0);
1340 if (pend
== Argv
[1] || *pend
!= '\0')
1342 KdbpPrint("%s: integer argument required\n", Argv
[0]);
1346 if (Argv
[0][1] == 'e') /* enable */
1348 KdbpEnableBreakPoint(BreakPointNr
, NULL
);
1350 else if (Argv
[0][1] == 'd') /* disable */
1352 KdbpDisableBreakPoint(BreakPointNr
, NULL
);
1356 ASSERT(Argv
[0][1] == 'c');
1357 KdbpDeleteBreakPoint(BreakPointNr
, NULL
);
1363 /*!\brief Sets a software or hardware (memory) breakpoint at the given address.
1366 KdbpCmdBreakPoint(ULONG Argc
, PCHAR Argv
[])
1368 ULONGLONG Result
= 0;
1370 KDB_BREAKPOINT_TYPE Type
;
1372 KDB_ACCESS_TYPE AccessType
= 0;
1373 ULONG AddressArgIndex
, i
;
1374 LONG ConditionArgIndex
;
1375 BOOLEAN Global
= TRUE
;
1377 if (Argv
[0][2] == 'x') /* software breakpoint */
1381 KdbpPrint("bpx: Address argument required.\n");
1385 AddressArgIndex
= 1;
1386 Type
= KdbBreakPointSoftware
;
1388 else /* memory breakpoint */
1390 ASSERT(Argv
[0][2] == 'm');
1394 KdbpPrint("bpm: Access type argument required (one of r, w, rw, x)\n");
1398 if (_stricmp(Argv
[1], "x") == 0)
1399 AccessType
= KdbAccessExec
;
1400 else if (_stricmp(Argv
[1], "r") == 0)
1401 AccessType
= KdbAccessRead
;
1402 else if (_stricmp(Argv
[1], "w") == 0)
1403 AccessType
= KdbAccessWrite
;
1404 else if (_stricmp(Argv
[1], "rw") == 0)
1405 AccessType
= KdbAccessReadWrite
;
1408 KdbpPrint("bpm: Unknown access type '%s'\n", Argv
[1]);
1414 KdbpPrint("bpm: %s argument required.\n", AccessType
== KdbAccessExec
? "Address" : "Memory size");
1418 AddressArgIndex
= 3;
1419 if (_stricmp(Argv
[2], "byte") == 0)
1421 else if (_stricmp(Argv
[2], "word") == 0)
1423 else if (_stricmp(Argv
[2], "dword") == 0)
1425 else if (AccessType
== KdbAccessExec
)
1432 KdbpPrint("bpm: Unknown memory size '%s'\n", Argv
[2]);
1436 if (Argc
<= AddressArgIndex
)
1438 KdbpPrint("bpm: Address argument required.\n");
1442 Type
= KdbBreakPointHardware
;
1445 /* Put the arguments back together */
1446 ConditionArgIndex
= -1;
1447 for (i
= AddressArgIndex
; i
< (Argc
-1); i
++)
1449 if (strcmp(Argv
[i
+1], "IF") == 0) /* IF found */
1451 ConditionArgIndex
= i
+ 2;
1452 if ((ULONG
)ConditionArgIndex
>= Argc
)
1454 KdbpPrint("%s: IF requires condition expression.\n", Argv
[0]);
1458 for (i
= ConditionArgIndex
; i
< (Argc
-1); i
++)
1459 Argv
[i
][strlen(Argv
[i
])] = ' ';
1464 Argv
[i
][strlen(Argv
[i
])] = ' ';
1467 /* Evaluate the address expression */
1468 if (!KdbpEvaluateExpression(Argv
[AddressArgIndex
],
1469 sizeof("kdb:> ")-1 + (Argv
[AddressArgIndex
]-Argv
[0]),
1475 if (Result
> (ULONGLONG
)(~((ULONG_PTR
)0)))
1476 KdbpPrint("%s: Warning: Address %I64x is beeing truncated\n", Argv
[0],Result
);
1478 Address
= (ULONG_PTR
)Result
;
1480 KdbpInsertBreakPoint(Address
, Type
, Size
, AccessType
,
1481 (ConditionArgIndex
< 0) ? NULL
: Argv
[ConditionArgIndex
],
1487 /*!\brief Lists threads or switches to another thread context.
1495 PETHREAD Thread
= NULL
;
1496 PEPROCESS Process
= NULL
;
1497 BOOLEAN ReferencedThread
= FALSE
, ReferencedProcess
= FALSE
;
1502 PCHAR State
, pend
, str1
, str2
;
1503 static const PCHAR ThreadStateToString
[DeferredReady
+1] =
1505 "Initialized", "Ready", "Running",
1506 "Standby", "Terminated", "Waiting",
1507 "Transition", "DeferredReady"
1510 ASSERT(KdbCurrentProcess
);
1512 if (Argc
>= 2 && _stricmp(Argv
[1], "list") == 0)
1514 Process
= KdbCurrentProcess
;
1518 ul
= strtoul(Argv
[2], &pend
, 0);
1519 if (Argv
[2] == pend
)
1521 KdbpPrint("thread: '%s' is not a valid process id!\n", Argv
[2]);
1525 if (!NT_SUCCESS(PsLookupProcessByProcessId((PVOID
)ul
, &Process
)))
1527 KdbpPrint("thread: Invalid process id!\n");
1531 /* Remember our reference */
1532 ReferencedProcess
= TRUE
;
1535 Entry
= Process
->ThreadListHead
.Flink
;
1536 if (Entry
== &Process
->ThreadListHead
)
1539 KdbpPrint("No threads in process 0x%08x!\n", ul
);
1541 KdbpPrint("No threads in current process!\n");
1543 if (ReferencedProcess
)
1544 ObDereferenceObject(Process
);
1549 KdbpPrint(" TID State Prior. Affinity EBP EIP\n");
1552 Thread
= CONTAINING_RECORD(Entry
, ETHREAD
, ThreadListEntry
);
1554 if (Thread
== KdbCurrentThread
)
1565 if (!Thread
->Tcb
.InitialStack
)
1567 /* Thread has no kernel stack (probably terminated) */
1571 else if (Thread
->Tcb
.TrapFrame
)
1573 if (Thread
->Tcb
.TrapFrame
->PreviousPreviousMode
== KernelMode
)
1574 Esp
= (PULONG
)Thread
->Tcb
.TrapFrame
->TempEsp
;
1576 Esp
= (PULONG
)Thread
->Tcb
.TrapFrame
->HardwareEsp
;
1578 Ebp
= (PULONG
)Thread
->Tcb
.TrapFrame
->Ebp
;
1579 Eip
= Thread
->Tcb
.TrapFrame
->Eip
;
1583 Esp
= (PULONG
)Thread
->Tcb
.KernelStack
;
1584 Ebp
= (PULONG
)Esp
[4];
1587 if (Ebp
) /* FIXME: Should we attach to the process to read Ebp[1]? */
1588 KdbpSafeReadMemory(&Eip
, Ebp
+ 1, sizeof (Eip
));
1591 if (Thread
->Tcb
.State
< (DeferredReady
+ 1))
1592 State
= ThreadStateToString
[Thread
->Tcb
.State
];
1596 KdbpPrint(" %s0x%08x %-11s %3d 0x%08x 0x%08x 0x%08x%s\n",
1598 Thread
->Cid
.UniqueThread
,
1600 Thread
->Tcb
.Priority
,
1601 Thread
->Tcb
.Affinity
,
1606 Entry
= Entry
->Flink
;
1608 while (Entry
!= &Process
->ThreadListHead
);
1610 /* Release our reference, if any */
1611 if (ReferencedProcess
)
1612 ObDereferenceObject(Process
);
1614 else if (Argc
>= 2 && _stricmp(Argv
[1], "attach") == 0)
1618 KdbpPrint("thread attach: thread id argument required!\n");
1622 ul
= strtoul(Argv
[2], &pend
, 0);
1623 if (Argv
[2] == pend
)
1625 KdbpPrint("thread attach: '%s' is not a valid thread id!\n", Argv
[2]);
1629 if (!KdbpAttachToThread((PVOID
)ul
))
1634 KdbpPrint("Attached to thread 0x%08x.\n", ul
);
1638 Thread
= KdbCurrentThread
;
1642 ul
= strtoul(Argv
[1], &pend
, 0);
1643 if (Argv
[1] == pend
)
1645 KdbpPrint("thread: '%s' is not a valid thread id!\n", Argv
[1]);
1649 if (!NT_SUCCESS(PsLookupThreadByThreadId((PVOID
)ul
, &Thread
)))
1651 KdbpPrint("thread: Invalid thread id!\n");
1655 /* Remember our reference */
1656 ReferencedThread
= TRUE
;
1659 if (Thread
->Tcb
.State
< (DeferredReady
+ 1))
1660 State
= ThreadStateToString
[Thread
->Tcb
.State
];
1666 " State: %s (0x%x)\n"
1668 " Affinity: 0x%08x\n"
1669 " Initial Stack: 0x%08x\n"
1670 " Stack Limit: 0x%08x\n"
1671 " Stack Base: 0x%08x\n"
1672 " Kernel Stack: 0x%08x\n"
1673 " Trap Frame: 0x%08x\n"
1674 " NPX State: %s (0x%x)\n",
1675 (Argc
< 2) ? "Current Thread:\n" : "",
1676 Thread
->Cid
.UniqueThread
,
1677 State
, Thread
->Tcb
.State
,
1678 Thread
->Tcb
.Priority
,
1679 Thread
->Tcb
.Affinity
,
1680 Thread
->Tcb
.InitialStack
,
1681 Thread
->Tcb
.StackLimit
,
1682 Thread
->Tcb
.StackBase
,
1683 Thread
->Tcb
.KernelStack
,
1684 Thread
->Tcb
.TrapFrame
,
1685 NPX_STATE_TO_STRING(Thread
->Tcb
.NpxState
), Thread
->Tcb
.NpxState
);
1687 /* Release our reference if we had one */
1688 if (ReferencedThread
)
1689 ObDereferenceObject(Thread
);
1695 /*!\brief Lists processes or switches to another process context.
1704 BOOLEAN ReferencedProcess
= FALSE
;
1705 PCHAR State
, pend
, str1
, str2
;
1707 extern LIST_ENTRY PsActiveProcessHead
;
1709 if (Argc
>= 2 && _stricmp(Argv
[1], "list") == 0)
1711 Entry
= PsActiveProcessHead
.Flink
;
1712 if (!Entry
|| Entry
== &PsActiveProcessHead
)
1714 KdbpPrint("No processes in the system!\n");
1718 KdbpPrint(" PID State Filename\n");
1721 Process
= CONTAINING_RECORD(Entry
, EPROCESS
, ActiveProcessLinks
);
1723 if (Process
== KdbCurrentProcess
)
1734 State
= ((Process
->Pcb
.State
== ProcessInMemory
) ? "In Memory" :
1735 ((Process
->Pcb
.State
== ProcessOutOfMemory
) ? "Out of Memory" : "In Transition"));
1737 KdbpPrint(" %s0x%08x %-10s %s%s\n",
1739 Process
->UniqueProcessId
,
1741 Process
->ImageFileName
,
1744 Entry
= Entry
->Flink
;
1746 while(Entry
!= &PsActiveProcessHead
);
1748 else if (Argc
>= 2 && _stricmp(Argv
[1], "attach") == 0)
1752 KdbpPrint("process attach: process id argument required!\n");
1756 ul
= strtoul(Argv
[2], &pend
, 0);
1757 if (Argv
[2] == pend
)
1759 KdbpPrint("process attach: '%s' is not a valid process id!\n", Argv
[2]);
1763 if (!KdbpAttachToProcess((PVOID
)ul
))
1768 KdbpPrint("Attached to process 0x%08x, thread 0x%08x.\n", (ULONG
)ul
,
1769 (ULONG
)KdbCurrentThread
->Cid
.UniqueThread
);
1773 Process
= KdbCurrentProcess
;
1777 ul
= strtoul(Argv
[1], &pend
, 0);
1778 if (Argv
[1] == pend
)
1780 KdbpPrint("proc: '%s' is not a valid process id!\n", Argv
[1]);
1784 if (!NT_SUCCESS(PsLookupProcessByProcessId((PVOID
)ul
, &Process
)))
1786 KdbpPrint("proc: Invalid process id!\n");
1790 /* Remember our reference */
1791 ReferencedProcess
= TRUE
;
1794 State
= ((Process
->Pcb
.State
== ProcessInMemory
) ? "In Memory" :
1795 ((Process
->Pcb
.State
== ProcessOutOfMemory
) ? "Out of Memory" : "In Transition"));
1798 " State: %s (0x%x)\n"
1799 " Image Filename: %s\n",
1800 (Argc
< 2) ? "Current process:\n" : "",
1801 Process
->UniqueProcessId
,
1802 State
, Process
->Pcb
.State
,
1803 Process
->ImageFileName
);
1805 /* Release our reference, if any */
1806 if (ReferencedProcess
)
1807 ObDereferenceObject(Process
);
1813 /*!\brief Lists loaded modules or the one containing the specified address.
1820 ULONGLONG Result
= 0;
1822 PLDR_DATA_TABLE_ENTRY LdrEntry
;
1823 BOOLEAN DisplayOnlyOneModule
= FALSE
;
1828 /* Put the arguments back together */
1831 Argv
[Argc
][strlen(Argv
[Argc
])] = ' ';
1833 /* Evaluate the expression */
1834 if (!KdbpEvaluateExpression(Argv
[1], sizeof("kdb:> ")-1 + (Argv
[1]-Argv
[0]), &Result
))
1839 if (Result
> (ULONGLONG
)(~((ULONG_PTR
)0)))
1840 KdbpPrint("%s: Warning: Address %I64x is beeing truncated\n", Argv
[0],Result
);
1842 Address
= (ULONG_PTR
)Result
;
1844 if (!KdbpSymFindModule((PVOID
)Address
, NULL
, -1, &LdrEntry
))
1846 KdbpPrint("No module containing address 0x%p found!\n", Address
);
1850 DisplayOnlyOneModule
= TRUE
;
1854 if (!KdbpSymFindModule(NULL
, NULL
, 0, &LdrEntry
))
1856 ULONG_PTR ntoskrnlBase
= ((ULONG_PTR
)KdbpCmdMod
) & 0xfff00000;
1857 KdbpPrint(" Base Size Name\n");
1858 KdbpPrint(" %08x %08x %s\n", ntoskrnlBase
, 0, "ntoskrnl.exe");
1865 KdbpPrint(" Base Size Name\n");
1868 KdbpPrint(" %08x %08x %wZ\n", LdrEntry
->DllBase
, LdrEntry
->SizeOfImage
, &LdrEntry
->BaseDllName
);
1870 if(DisplayOnlyOneModule
|| !KdbpSymFindModule(NULL
, NULL
, i
++, &LdrEntry
))
1877 /*!\brief Displays GDT, LDT or IDTd.
1894 if (Argv
[0][0] == 'i')
1901 KdbpPrint("Interrupt descriptor table is empty.\n");
1905 KdbpPrint("IDT Base: 0x%08x Limit: 0x%04x\n", Reg
.Base
, Reg
.Limit
);
1906 KdbpPrint(" Idx Type Seg. Sel. Offset DPL\n");
1908 for (i
= 0; (i
+ sizeof(SegDesc
) - 1) <= Reg
.Limit
; i
+= 8)
1910 if (!NT_SUCCESS(KdbpSafeReadMemory(SegDesc
, (PVOID
)(Reg
.Base
+ i
), sizeof(SegDesc
))))
1912 KdbpPrint("Couldn't access memory at 0x%08x!\n", Reg
.Base
+ i
);
1916 Dpl
= ((SegDesc
[1] >> 13) & 3);
1917 if ((SegDesc
[1] & 0x1f00) == 0x0500) /* Task gate */
1918 SegType
= "TASKGATE";
1919 else if ((SegDesc
[1] & 0x1fe0) == 0x0e00) /* 32 bit Interrupt gate */
1920 SegType
= "INTGATE32";
1921 else if ((SegDesc
[1] & 0x1fe0) == 0x0600) /* 16 bit Interrupt gate */
1922 SegType
= "INTGATE16";
1923 else if ((SegDesc
[1] & 0x1fe0) == 0x0f00) /* 32 bit Trap gate */
1924 SegType
= "TRAPGATE32";
1925 else if ((SegDesc
[1] & 0x1fe0) == 0x0700) /* 16 bit Trap gate */
1926 SegType
= "TRAPGATE16";
1928 SegType
= "UNKNOWN";
1930 if ((SegDesc
[1] & (1 << 15)) == 0) /* not present */
1932 KdbpPrint(" %03d %-10s [NP] [NP] %02d\n",
1933 i
/ 8, SegType
, Dpl
);
1935 else if ((SegDesc
[1] & 0x1f00) == 0x0500) /* Task gate */
1937 SegSel
= SegDesc
[0] >> 16;
1938 KdbpPrint(" %03d %-10s 0x%04x %02d\n",
1939 i
/ 8, SegType
, SegSel
, Dpl
);
1943 SegSel
= SegDesc
[0] >> 16;
1944 SegBase
= (SegDesc
[1] & 0xffff0000) | (SegDesc
[0] & 0x0000ffff);
1945 KdbpPrint(" %03d %-10s 0x%04x 0x%08x %02d\n",
1946 i
/ 8, SegType
, SegSel
, SegBase
, Dpl
);
1954 if (Argv
[0][0] == 'g')
1957 Ke386GetGlobalDescriptorTable(&Reg
.Limit
);
1962 ASSERT(Argv
[0][0] == 'l');
1965 Reg
.Limit
= Ke386GetLocalDescriptorTable();
1973 KdbpPrint("%s descriptor table is empty.\n",
1974 Argv
[0][0] == 'g' ? "Global" : "Local");
1978 KdbpPrint("%cDT Base: 0x%08x Limit: 0x%04x\n",
1979 Argv
[0][0] == 'g' ? 'G' : 'L', Reg
.Base
, Reg
.Limit
);
1980 KdbpPrint(" Idx Sel. Type Base Limit DPL Attribs\n");
1982 for (; (i
+ sizeof(SegDesc
) - 1) <= Reg
.Limit
; i
+= 8)
1984 if (!NT_SUCCESS(KdbpSafeReadMemory(SegDesc
, (PVOID
)(Reg
.Base
+ i
), sizeof(SegDesc
))))
1986 KdbpPrint("Couldn't access memory at 0x%08x!\n", Reg
.Base
+ i
);
1990 Dpl
= ((SegDesc
[1] >> 13) & 3);
1991 Type
= ((SegDesc
[1] >> 8) & 0xf);
1993 SegBase
= SegDesc
[0] >> 16;
1994 SegBase
|= (SegDesc
[1] & 0xff) << 16;
1995 SegBase
|= SegDesc
[1] & 0xff000000;
1996 SegLimit
= SegDesc
[0] & 0x0000ffff;
1997 SegLimit
|= (SegDesc
[1] >> 16) & 0xf;
1999 if ((SegDesc
[1] & (1 << 23)) != 0)
2009 if ((SegDesc
[1] & (1 << 12)) == 0) /* System segment */
2013 case 1: SegType
= "TSS16(Avl)"; break;
2014 case 2: SegType
= "LDT"; break;
2015 case 3: SegType
= "TSS16(Busy)"; break;
2016 case 4: SegType
= "CALLGATE16"; break;
2017 case 5: SegType
= "TASKGATE"; break;
2018 case 6: SegType
= "INTGATE16"; break;
2019 case 7: SegType
= "TRAPGATE16"; break;
2020 case 9: SegType
= "TSS32(Avl)"; break;
2021 case 11: SegType
= "TSS32(Busy)"; break;
2022 case 12: SegType
= "CALLGATE32"; break;
2023 case 14: SegType
= "INTGATE32"; break;
2024 case 15: SegType
= "INTGATE32"; break;
2025 default: SegType
= "UNKNOWN"; break;
2028 if (!(Type
>= 1 && Type
<= 3) &&
2029 Type
!= 9 && Type
!= 11)
2035 else if ((SegDesc
[1] & (1 << 11)) == 0) /* Data segment */
2037 if ((SegDesc
[1] & (1 << 22)) != 0)
2042 else /* Code segment */
2044 if ((SegDesc
[1] & (1 << 22)) != 0)
2050 if ((SegDesc
[1] & (1 << 15)) == 0) /* not present */
2052 KdbpPrint(" %03d 0x%04x %-11s [NP] [NP] %02d NP\n",
2053 i
/ 8, i
| Dpl
| ul
, SegType
, Dpl
);
2057 KdbpPrint(" %03d 0x%04x %-11s 0x%08x 0x%08x %02d ",
2058 i
/ 8, i
| Dpl
| ul
, SegType
, SegBase
, SegLimit
, Dpl
);
2060 if ((SegDesc
[1] & (1 << 12)) == 0) /* System segment */
2062 /* FIXME: Display system segment */
2064 else if ((SegDesc
[1] & (1 << 11)) == 0) /* Data segment */
2066 if ((SegDesc
[1] & (1 << 10)) != 0) /* Expand-down */
2069 KdbpPrint((SegDesc
[1] & (1 << 9)) ? " R/W" : " R");
2071 if ((SegDesc
[1] & (1 << 8)) != 0)
2074 else /* Code segment */
2076 if ((SegDesc
[1] & (1 << 10)) != 0) /* Conforming */
2079 KdbpPrint((SegDesc
[1] & (1 << 9)) ? " R/X" : " X");
2081 if ((SegDesc
[1] & (1 << 8)) != 0)
2085 if ((SegDesc
[1] & (1 << 20)) != 0)
2096 /*!\brief Displays the KPCR
2103 PKIPCR Pcr
= (PKIPCR
)KeGetPcr();
2105 KdbpPrint("Current PCR is at 0x%08x.\n", (INT
)Pcr
);
2106 KdbpPrint(" Tib.ExceptionList: 0x%08x\n"
2107 " Tib.StackBase: 0x%08x\n"
2108 " Tib.StackLimit: 0x%08x\n"
2109 " Tib.SubSystemTib: 0x%08x\n"
2110 " Tib.FiberData/Version: 0x%08x\n"
2111 " Tib.ArbitraryUserPointer: 0x%08x\n"
2112 " Tib.Self: 0x%08x\n"
2117 " IrrActive: 0x%08x\n"
2119 " KdVersionBlock: 0x%08x\n"
2123 " MajorVersion: 0x%04x\n"
2124 " MinorVersion: 0x%04x\n"
2125 " SetMember: 0x%08x\n"
2126 " StallScaleFactor: 0x%08x\n"
2128 " L2CacheAssociativity: 0x%02x\n"
2129 " VdmAlert: 0x%08x\n"
2130 " L2CacheSize: 0x%08x\n"
2131 " InterruptMode: 0x%08x\n",
2132 Pcr
->NtTib
.ExceptionList
, Pcr
->NtTib
.StackBase
, Pcr
->NtTib
.StackLimit
,
2133 Pcr
->NtTib
.SubSystemTib
, Pcr
->NtTib
.FiberData
, Pcr
->NtTib
.ArbitraryUserPointer
,
2134 Pcr
->NtTib
.Self
, Pcr
->Self
, Pcr
->Prcb
, Pcr
->Irql
, Pcr
->IRR
, Pcr
->IrrActive
,
2135 Pcr
->IDR
, Pcr
->KdVersionBlock
, Pcr
->IDT
, Pcr
->GDT
, Pcr
->TSS
,
2136 Pcr
->MajorVersion
, Pcr
->MinorVersion
, Pcr
->SetMember
, Pcr
->StallScaleFactor
,
2137 Pcr
->Number
, Pcr
->SecondLevelCacheAssociativity
,
2138 Pcr
->VdmAlert
, Pcr
->SecondLevelCacheSize
, Pcr
->InterruptMode
);
2143 /*!\brief Displays the TSS
2150 KTSS
*Tss
= KeGetPcr()->TSS
;
2152 KdbpPrint("Current TSS is at 0x%08x.\n", (INT
)Tss
);
2153 KdbpPrint(" Eip: 0x%08x\n"
2160 " IoMapBase: 0x%04x\n",
2161 Tss
->Eip
, Tss
->Es
, Tss
->Cs
, Tss
->Ds
, Tss
->Fs
, Tss
->Gs
, Tss
->IoMapBase
);
2166 /*!\brief Bugchecks the system.
2173 /* Set the flag and quit looping */
2174 KdbpBugCheckRequested
= TRUE
;
2182 IN ULONG BufLength
);
2184 /*!\brief Display debug messages on screen, with paging.
2186 * Keys for per-page view: Home, End, PageUp, Arrow Up, PageDown,
2187 * all others are as PageDown.
2196 KdbpIsInDmesgMode
= TRUE
; /* Toggle logging flag */
2197 if (!KdpDmesgBuffer
)
2199 KdbpPrint("Dmesg: error, buffer is not allocated! /DEBUGPORT=SCREEN kernel param required for dmesg.\n");
2203 KdbpPrint("*** Dmesg *** TotalWritten=%lu, BufferSize=%lu, CurrentPosition=%lu\n",
2204 KdbDmesgTotalWritten
, KdpDmesgBufferSize
, KdpDmesgCurrentPosition
);
2206 // Pass data to the pager:
2207 end
= KdpDmesgCurrentPosition
;
2208 beg
= (end
+ KdpDmesgFreeBytes
) % KdpDmesgBufferSize
;
2210 // no roll-overs, and overwritten=lost bytes
2211 if (KdbDmesgTotalWritten
<= KdpDmesgBufferSize
)
2213 // show buffer (KdpDmesgBuffer + beg, num)
2214 KdbpPager(KdpDmesgBuffer
, KdpDmesgCurrentPosition
);
2218 // show 2 buffers: (KdpDmesgBuffer + beg, KdpDmesgBufferSize - beg)
2219 // and: (KdpDmesgBuffer, end)
2220 KdbpPager(KdpDmesgBuffer
+ beg
, KdpDmesgBufferSize
- beg
);
2221 KdbpPrint("*** Dmesg: buffer rollup ***\n");
2222 KdbpPager(KdpDmesgBuffer
, end
);
2224 KdbpPrint("*** Dmesg: end of output ***\n");
2226 KdbpIsInDmesgMode
= FALSE
; /* Toggle logging flag */
2231 /*!\brief Sets or displays a config variables value.
2241 KDB_ENTER_CONDITION ConditionFirst
= KdbDoNotEnter
;
2242 KDB_ENTER_CONDITION ConditionLast
= KdbDoNotEnter
;
2244 static const PCHAR ExceptionNames
[21] =
2246 "ZERODEVIDE", "DEBUGTRAP", "NMI", "INT3", "OVERFLOW", "BOUND", "INVALIDOP",
2247 "NOMATHCOP", "DOUBLEFAULT", "RESERVED(9)", "INVALIDTSS", "SEGMENTNOTPRESENT",
2248 "STACKFAULT", "GPF", "PAGEFAULT", "RESERVED(15)", "MATHFAULT", "ALIGNMENTCHECK",
2249 "MACHINECHECK", "SIMDFAULT", "OTHERS"
2254 KdbpPrint("Available settings:\n");
2255 KdbpPrint(" syntax [intel|at&t]\n");
2256 KdbpPrint(" condition [exception|*] [first|last] [never|always|kmode|umode]\n");
2257 KdbpPrint(" break_on_module_load [true|false]\n");
2259 else if (strcmp(Argv
[1], "syntax") == 0)
2263 KdbpPrint("syntax = %s\n", KdbUseIntelSyntax
? "intel" : "at&t");
2267 if (_stricmp(Argv
[2], "intel") == 0)
2268 KdbUseIntelSyntax
= TRUE
;
2269 else if (_stricmp(Argv
[2], "at&t") == 0)
2270 KdbUseIntelSyntax
= FALSE
;
2272 KdbpPrint("Unknown syntax '%s'.\n", Argv
[2]);
2275 else if (strcmp(Argv
[1], "condition") == 0)
2279 KdbpPrint("Conditions: (First) (Last)\n");
2280 for (l
= 0; l
< RTL_NUMBER_OF(ExceptionNames
) - 1; l
++)
2282 if (!ExceptionNames
[l
])
2285 if (!KdbpGetEnterCondition(l
, TRUE
, &ConditionFirst
))
2288 if (!KdbpGetEnterCondition(l
, FALSE
, &ConditionLast
))
2291 KdbpPrint(" #%02d %-20s %-8s %-8s\n", l
, ExceptionNames
[l
],
2292 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst
),
2293 KDB_ENTER_CONDITION_TO_STRING(ConditionLast
));
2296 ASSERT(l
== (RTL_NUMBER_OF(ExceptionNames
) - 1));
2297 KdbpPrint(" %-20s %-8s %-8s\n", ExceptionNames
[l
],
2298 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst
),
2299 KDB_ENTER_CONDITION_TO_STRING(ConditionLast
));
2303 if (Argc
>= 5 && strcmp(Argv
[2], "*") == 0) /* Allow * only when setting condition */
2309 l
= strtoul(Argv
[2], &pend
, 0);
2311 if (Argv
[2] == pend
)
2313 for (l
= 0; l
< RTL_NUMBER_OF(ExceptionNames
); l
++)
2315 if (!ExceptionNames
[l
])
2318 if (_stricmp(ExceptionNames
[l
], Argv
[2]) == 0)
2323 if (l
>= RTL_NUMBER_OF(ExceptionNames
))
2325 KdbpPrint("Unknown exception '%s'.\n", Argv
[2]);
2332 if (_stricmp(Argv
[3], "first") == 0)
2334 else if (_stricmp(Argv
[3], "last") == 0)
2338 KdbpPrint("set condition: second argument must be 'first' or 'last'\n");
2342 if (_stricmp(Argv
[4], "never") == 0)
2343 ConditionFirst
= KdbDoNotEnter
;
2344 else if (_stricmp(Argv
[4], "always") == 0)
2345 ConditionFirst
= KdbEnterAlways
;
2346 else if (_stricmp(Argv
[4], "umode") == 0)
2347 ConditionFirst
= KdbEnterFromUmode
;
2348 else if (_stricmp(Argv
[4], "kmode") == 0)
2349 ConditionFirst
= KdbEnterFromKmode
;
2352 KdbpPrint("set condition: third argument must be 'never', 'always', 'umode' or 'kmode'\n");
2356 if (!KdbpSetEnterCondition(l
, First
, ConditionFirst
))
2359 KdbpPrint("Couldn't change condition for exception #%02d\n", l
);
2361 KdbpPrint("Couldn't change condition for all exceptions\n", l
);
2364 else /* Argc >= 3 */
2366 if (!KdbpGetEnterCondition(l
, TRUE
, &ConditionFirst
))
2369 if (!KdbpGetEnterCondition(l
, FALSE
, &ConditionLast
))
2372 if (l
< (RTL_NUMBER_OF(ExceptionNames
) - 1))
2374 KdbpPrint("Condition for exception #%02d (%s): FirstChance %s LastChance %s\n",
2375 l
, ExceptionNames
[l
],
2376 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst
),
2377 KDB_ENTER_CONDITION_TO_STRING(ConditionLast
));
2381 KdbpPrint("Condition for all other exceptions: FirstChance %s LastChance %s\n",
2382 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst
),
2383 KDB_ENTER_CONDITION_TO_STRING(ConditionLast
));
2388 else if (strcmp(Argv
[1], "break_on_module_load") == 0)
2391 KdbpPrint("break_on_module_load = %s\n", KdbBreakOnModuleLoad
? "enabled" : "disabled");
2394 if (_stricmp(Argv
[2], "enable") == 0 || _stricmp(Argv
[2], "enabled") == 0 || _stricmp(Argv
[2], "true") == 0)
2395 KdbBreakOnModuleLoad
= TRUE
;
2396 else if (_stricmp(Argv
[2], "disable") == 0 || _stricmp(Argv
[2], "disabled") == 0 || _stricmp(Argv
[2], "false") == 0)
2397 KdbBreakOnModuleLoad
= FALSE
;
2399 KdbpPrint("Unknown setting '%s'.\n", Argv
[2]);
2404 KdbpPrint("Unknown setting '%s'.\n", Argv
[1]);
2410 /*!\brief Displays help screen.
2419 KdbpPrint("Kernel debugger commands:\n");
2420 for (i
= 0; i
< RTL_NUMBER_OF(KdbDebuggerCommands
); i
++)
2422 if (!KdbDebuggerCommands
[i
].Syntax
) /* Command group */
2427 KdbpPrint("\x1b[7m* %s:\x1b[0m\n", KdbDebuggerCommands
[i
].Help
);
2431 KdbpPrint(" %-20s - %s\n",
2432 KdbDebuggerCommands
[i
].Syntax
,
2433 KdbDebuggerCommands
[i
].Help
);
2439 /*!\brief Prints the given string with printf-like formatting.
2441 * \param Format Format of the string/arguments.
2442 * \param ... Variable number of arguments matching the format specified in \a Format.
2444 * \note Doesn't correctly handle \\t and terminal escape sequences when calculating the
2445 * number of lines required to print a single line from the Buffer in the terminal.
2446 * Prints maximum 4096 chars, because of its buffer size.
2453 static CHAR Buffer
[4096];
2454 static BOOLEAN TerminalInitialized
= FALSE
;
2455 static BOOLEAN TerminalConnected
= FALSE
;
2456 static BOOLEAN TerminalReportsSize
= TRUE
;
2461 LONG RowsPrintedByTerminal
;
2465 /* Check if the user has aborted output of the current command */
2466 if (KdbOutputAborted
)
2469 /* Initialize the terminal */
2470 if (!TerminalInitialized
)
2472 DbgPrint("\x1b[7h"); /* Enable linewrap */
2474 /* Query terminal type */
2475 /*DbgPrint("\x1b[Z");*/
2478 TerminalInitialized
= TRUE
;
2480 KeStallExecutionProcessor(100000);
2484 c
= KdbpTryGetCharSerial(5000);
2488 Buffer
[Length
++] = c
;
2489 if (Length
>= (sizeof (Buffer
) - 1))
2493 Buffer
[Length
] = '\0';
2495 TerminalConnected
= TRUE
;
2498 /* Get number of rows and columns in terminal */
2499 if ((KdbNumberOfRowsTerminal
< 0) || (KdbNumberOfColsTerminal
< 0) ||
2500 (KdbNumberOfRowsPrinted
) == 0) /* Refresh terminal size each time when number of rows printed is 0 */
2502 if ((KdbDebugState
& KD_DEBUG_KDSERIAL
) && TerminalConnected
&& TerminalReportsSize
)
2504 /* Try to query number of rows from terminal. A reply looks like "\x1b[8;24;80t" */
2505 TerminalReportsSize
= FALSE
;
2506 KeStallExecutionProcessor(100000);
2507 DbgPrint("\x1b[18t");
2508 c
= KdbpTryGetCharSerial(5000);
2512 c
= KdbpTryGetCharSerial(5000);
2519 c
= KdbpTryGetCharSerial(5000);
2523 Buffer
[Length
++] = c
;
2524 if (isalpha(c
) || Length
>= (sizeof (Buffer
) - 1))
2528 Buffer
[Length
] = '\0';
2529 if (Buffer
[0] == '8' && Buffer
[1] == ';')
2531 for (i
= 2; (i
< Length
) && (Buffer
[i
] != ';'); i
++);
2533 if (Buffer
[i
] == ';')
2537 /* Number of rows is now at Buffer + 2 and number of cols at Buffer + i */
2538 KdbNumberOfRowsTerminal
= strtoul(Buffer
+ 2, NULL
, 0);
2539 KdbNumberOfColsTerminal
= strtoul(Buffer
+ i
, NULL
, 0);
2540 TerminalReportsSize
= TRUE
;
2544 /* Clear further characters */
2545 while ((c
= KdbpTryGetCharSerial(5000)) != -1);
2549 if (KdbNumberOfRowsTerminal
<= 0)
2551 /* Set number of rows to the default. */
2552 KdbNumberOfRowsTerminal
= 23; //24; //Mna.: 23 for SCREEN debugport
2554 else if (KdbNumberOfColsTerminal
<= 0)
2556 /* Set number of cols to the default. */
2557 KdbNumberOfColsTerminal
= 75; //80; //Mna.: 75 for SCREEN debugport
2561 /* Get the string */
2562 va_start(ap
, Format
);
2563 Length
= _vsnprintf(Buffer
, sizeof (Buffer
) - 1, Format
, ap
);
2564 Buffer
[Length
] = '\0';
2568 while (p
[0] != '\0')
2570 i
= strcspn(p
, "\n");
2572 /* Calculate the number of lines which will be printed in the terminal
2573 * when outputting the current line
2576 RowsPrintedByTerminal
= (i
+ KdbNumberOfColsPrinted
- 1) / KdbNumberOfColsTerminal
;
2578 RowsPrintedByTerminal
= 0;
2581 RowsPrintedByTerminal
++;
2583 /*DbgPrint("!%d!%d!%d!%d!", KdbNumberOfRowsPrinted, KdbNumberOfColsPrinted, i, RowsPrintedByTerminal);*/
2585 /* Display a prompt if we printed one screen full of text */
2586 if (KdbNumberOfRowsTerminal
> 0 &&
2587 (LONG
)(KdbNumberOfRowsPrinted
+ RowsPrintedByTerminal
) >= KdbNumberOfRowsTerminal
)
2589 KdbRepeatLastCommand
= FALSE
;
2591 if (KdbNumberOfColsPrinted
> 0)
2594 DbgPrint("--- Press q to abort, any other key to continue ---");
2595 RowsPrintedByTerminal
++; /* added by Mna. */
2597 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
2598 c
= KdbpGetCharSerial();
2600 c
= KdbpGetCharKeyboard(&ScanCode
);
2604 /* Try to read '\n' which might follow '\r' - if \n is not received here
2605 * it will be interpreted as "return" when the next command should be read.
2607 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
2608 c
= KdbpTryGetCharSerial(5);
2610 c
= KdbpTryGetCharKeyboard(&ScanCode
, 5);
2616 KdbOutputAborted
= TRUE
;
2620 KdbNumberOfRowsPrinted
= 0;
2621 KdbNumberOfColsPrinted
= 0;
2624 /* Insert a NUL after the line and print only the current line. */
2625 if (p
[i
] == '\n' && p
[i
+ 1] != '\0')
2635 /* Remove escape sequences from the line if there's no terminal connected */
2636 if (!TerminalConnected
)
2638 while ((p2
= strrchr(p
, '\x1b'))) /* Look for escape character */
2643 while (!isalpha(p2
[j
++]));
2658 /* Set p to the start of the next line and
2659 * remember the number of rows/cols printed
2665 KdbNumberOfColsPrinted
= 0;
2669 ASSERT(p
[0] == '\0');
2670 KdbNumberOfColsPrinted
+= i
;
2673 KdbNumberOfRowsPrinted
+= RowsPrintedByTerminal
;
2677 /** memrchr(), explicitly defined, since was absent in MinGW of RosBE. */
2680 * Find the last occurrence of 'c' in the buffer 's' of size 'n'.
2683 memrchr(const void *s
, int c
, size_t n
)
2685 const unsigned char *cp
;
2689 cp
= (unsigned char *)s
+ n
;
2692 if (*(--cp
) == (unsigned char)c
)
2699 /*!\brief Calculate pointer position for N lines upper of current position.
2701 * \param Buffer Characters buffer to operate on.
2702 * \param BufLength Buffer size.
2704 * \note Calculate pointer position for N lines upper of current displaying
2705 * position within the given buffer.
2707 * Used by KdbpPager().
2708 * Now N lines count is hardcoded to KdbNumberOfRowsTerminal.
2711 CountOnePageUp(PCHAR Buffer
, ULONG BufLength
, PCHAR pCurPos
)
2714 // p0 is initial guess of Page Start
2715 ULONG p0len
= KdbNumberOfRowsTerminal
* KdbNumberOfColsTerminal
;
2716 PCHAR p0
= pCurPos
- p0len
;
2717 PCHAR prev_p
= p0
, p1
;
2720 if (pCurPos
< Buffer
)
2722 ASSERT(pCurPos
<= Buffer
+ BufLength
);
2724 p
= memrchr(p0
, '\n', p0len
);
2727 for (j
= KdbNumberOfRowsTerminal
; j
--; )
2730 p1
= memrchr(p0
, '\n', p
-p0
);
2740 linesCnt
= (KdbNumberOfColsTerminal
+prev_p
-p
-2) / KdbNumberOfColsTerminal
;
2750 /*!\brief Prints the given string with, page by page.
2752 * \param Buffer Characters buffer to print.
2753 * \param BufferLen Buffer size.
2755 * \note Doesn't correctly handle \\t and terminal escape sequences when calculating the
2756 * number of lines required to print a single line from the Buffer in the terminal.
2757 * Maximum length of buffer is limited only by memory size.
2759 * Note: BufLength should be greater then (KdbNumberOfRowsTerminal * KdbNumberOfColsTerminal).
2767 static CHAR InBuffer
[4096];
2768 static BOOLEAN TerminalInitialized
= FALSE
;
2769 static BOOLEAN TerminalConnected
= FALSE
;
2770 static BOOLEAN TerminalReportsSize
= TRUE
;
2775 LONG RowsPrintedByTerminal
;
2781 /* Check if the user has aborted output of the current command */
2782 if (KdbOutputAborted
)
2785 /* Initialize the terminal */
2786 if (!TerminalInitialized
)
2788 DbgPrint("\x1b[7h"); /* Enable linewrap */
2790 /* Query terminal type */
2791 /*DbgPrint("\x1b[Z");*/
2794 TerminalInitialized
= TRUE
;
2796 KeStallExecutionProcessor(100000);
2800 c
= KdbpTryGetCharSerial(5000);
2804 InBuffer
[Length
++] = c
;
2805 if (Length
>= (sizeof (InBuffer
) - 1))
2809 InBuffer
[Length
] = '\0';
2811 TerminalConnected
= TRUE
;
2814 /* Get number of rows and columns in terminal */
2815 if ((KdbNumberOfRowsTerminal
< 0) || (KdbNumberOfColsTerminal
< 0) ||
2816 (KdbNumberOfRowsPrinted
) == 0) /* Refresh terminal size each time when number of rows printed is 0 */
2818 if ((KdbDebugState
& KD_DEBUG_KDSERIAL
) && TerminalConnected
&& TerminalReportsSize
)
2820 /* Try to query number of rows from terminal. A reply looks like "\x1b[8;24;80t" */
2821 TerminalReportsSize
= FALSE
;
2822 KeStallExecutionProcessor(100000);
2823 DbgPrint("\x1b[18t");
2824 c
= KdbpTryGetCharSerial(5000);
2828 c
= KdbpTryGetCharSerial(5000);
2835 c
= KdbpTryGetCharSerial(5000);
2839 InBuffer
[Length
++] = c
;
2840 if (isalpha(c
) || Length
>= (sizeof (InBuffer
) - 1))
2844 InBuffer
[Length
] = '\0';
2845 if (InBuffer
[0] == '8' && InBuffer
[1] == ';')
2847 for (i
= 2; (i
< Length
) && (InBuffer
[i
] != ';'); i
++);
2849 if (Buffer
[i
] == ';')
2853 /* Number of rows is now at Buffer + 2 and number of cols at Buffer + i */
2854 KdbNumberOfRowsTerminal
= strtoul(InBuffer
+ 2, NULL
, 0);
2855 KdbNumberOfColsTerminal
= strtoul(InBuffer
+ i
, NULL
, 0);
2856 TerminalReportsSize
= TRUE
;
2860 /* Clear further characters */
2861 while ((c
= KdbpTryGetCharSerial(5000)) != -1);
2865 if (KdbNumberOfRowsTerminal
<= 0)
2867 /* Set number of rows to the default. */
2868 KdbNumberOfRowsTerminal
= 24;
2870 else if (KdbNumberOfColsTerminal
<= 0)
2872 /* Set number of cols to the default. */
2873 KdbNumberOfColsTerminal
= 80;
2877 /* Get the string */
2880 while (p
[0] != '\0')
2882 if ( p
> Buffer
+BufLength
)
2884 DbgPrint("Dmesg: error, p > Buffer+BufLength,d=%d", p
- (Buffer
+BufLength
));
2887 i
= strcspn(p
, "\n");
2889 // Are we out of buffer?
2890 if (p
+ i
> Buffer
+ BufLength
)
2891 // Leaving pager function:
2894 /* Calculate the number of lines which will be printed in the terminal
2895 * when outputting the current line
2898 RowsPrintedByTerminal
= (i
+ KdbNumberOfColsPrinted
- 1) / KdbNumberOfColsTerminal
;
2900 RowsPrintedByTerminal
= 0;
2903 RowsPrintedByTerminal
++;
2905 /*DbgPrint("!%d!%d!%d!%d!", KdbNumberOfRowsPrinted, KdbNumberOfColsPrinted, i, RowsPrintedByTerminal);*/
2907 /* Display a prompt if we printed one screen full of text */
2908 if (KdbNumberOfRowsTerminal
> 0 &&
2909 (LONG
)(KdbNumberOfRowsPrinted
+ RowsPrintedByTerminal
) >= KdbNumberOfRowsTerminal
)
2911 KdbRepeatLastCommand
= FALSE
;
2913 if (KdbNumberOfColsPrinted
> 0)
2916 DbgPrint("--- Press q to abort, e/End,h/Home,u/PgUp, other key/PgDn ---");
2917 RowsPrintedByTerminal
++;
2919 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
2920 c
= KdbpGetCharSerial();
2922 c
= KdbpGetCharKeyboard(&ScanCode
);
2926 /* Try to read '\n' which might follow '\r' - if \n is not received here
2927 * it will be interpreted as "return" when the next command should be read.
2929 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
2930 c
= KdbpTryGetCharSerial(5);
2932 c
= KdbpTryGetCharKeyboard(&ScanCode
, 5);
2935 //DbgPrint("\n"); //Consize version: don't show pressed key
2936 DbgPrint(" '%c'/scan=%04x\n", c
, ScanCode
); // Shows pressed key
2940 KdbOutputAborted
= TRUE
;
2943 if ( ScanCode
== KEYSC_END
|| c
=='e')
2945 PCHAR pBufEnd
= Buffer
+ BufLength
;
2946 p
= CountOnePageUp(Buffer
, BufLength
, pBufEnd
);
2947 i
= strcspn(p
, "\n");
2949 else if (ScanCode
== KEYSC_PAGEUP
|| c
=='u')
2951 p
= CountOnePageUp(Buffer
, BufLength
, p
);
2952 i
= strcspn(p
, "\n");
2954 else if (ScanCode
== KEYSC_HOME
|| c
=='h')
2957 i
= strcspn(p
, "\n");
2959 else if (ScanCode
== KEYSC_ARROWUP
)
2961 p
= CountOnePageUp(Buffer
, BufLength
, p
);
2962 i
= strcspn(p
, "\n");
2965 KdbNumberOfRowsPrinted
= 0;
2966 KdbNumberOfColsPrinted
= 0;
2969 /* Insert a NUL after the line and print only the current line. */
2970 if (p
[i
] == '\n' && p
[i
+ 1] != '\0')
2980 /* Remove escape sequences from the line if there's no terminal connected */
2981 if (!TerminalConnected
)
2983 while ((p2
= strrchr(p
, '\x1b'))) /* Look for escape character */
2988 while (!isalpha(p2
[j
++]));
2998 // The main printing of the current line:
3001 // restore not null char with saved:
3005 /* Set p to the start of the next line and
3006 * remember the number of rows/cols printed
3012 KdbNumberOfColsPrinted
= 0;
3016 ASSERT(p
[0] == '\0');
3017 KdbNumberOfColsPrinted
+= i
;
3020 KdbNumberOfRowsPrinted
+= RowsPrintedByTerminal
;
3024 /*!\brief Appends a command to the command history
3026 * \param Command Pointer to the command to append to the history.
3029 KdbpCommandHistoryAppend(
3032 ULONG Length1
= strlen(Command
) + 1;
3037 ASSERT(Length1
<= RTL_NUMBER_OF(KdbCommandHistoryBuffer
));
3040 (KdbCommandHistory
[KdbCommandHistoryIndex
] &&
3041 strcmp(KdbCommandHistory
[KdbCommandHistoryIndex
], Command
) == 0))
3046 /* Calculate Length1 and Length2 */
3047 Buffer
= KdbCommandHistoryBuffer
+ KdbCommandHistoryBufferIndex
;
3048 KdbCommandHistoryBufferIndex
+= Length1
;
3049 if (KdbCommandHistoryBufferIndex
>= (LONG
)RTL_NUMBER_OF(KdbCommandHistoryBuffer
))
3051 KdbCommandHistoryBufferIndex
-= RTL_NUMBER_OF(KdbCommandHistoryBuffer
);
3052 Length2
= KdbCommandHistoryBufferIndex
;
3056 /* Remove previous commands until there is enough space to append the new command */
3057 for (i
= KdbCommandHistoryIndex
; KdbCommandHistory
[i
];)
3060 (KdbCommandHistory
[i
] >= Buffer
||
3061 KdbCommandHistory
[i
] < (KdbCommandHistoryBuffer
+ KdbCommandHistoryBufferIndex
))) ||
3063 (KdbCommandHistory
[i
] >= Buffer
&&
3064 KdbCommandHistory
[i
] < (KdbCommandHistoryBuffer
+ KdbCommandHistoryBufferIndex
))))
3066 KdbCommandHistory
[i
] = NULL
;
3071 i
= RTL_NUMBER_OF(KdbCommandHistory
) - 1;
3073 if (i
== KdbCommandHistoryIndex
)
3077 /* Make sure the new command history entry is free */
3078 KdbCommandHistoryIndex
++;
3079 KdbCommandHistoryIndex
%= RTL_NUMBER_OF(KdbCommandHistory
);
3080 if (KdbCommandHistory
[KdbCommandHistoryIndex
])
3082 KdbCommandHistory
[KdbCommandHistoryIndex
] = NULL
;
3085 /* Append command */
3086 KdbCommandHistory
[KdbCommandHistoryIndex
] = Buffer
;
3087 ASSERT((KdbCommandHistory
[KdbCommandHistoryIndex
] + Length1
) <= KdbCommandHistoryBuffer
+ RTL_NUMBER_OF(KdbCommandHistoryBuffer
));
3088 memcpy(KdbCommandHistory
[KdbCommandHistoryIndex
], Command
, Length1
);
3091 memcpy(KdbCommandHistoryBuffer
, Command
+ Length1
, Length2
);
3095 /*!\brief Reads a line of user-input.
3097 * \param Buffer Buffer to store the input into. Trailing newlines are removed.
3098 * \param Size Size of \a Buffer.
3100 * \note Accepts only \n newlines, \r is ignored.
3108 PCHAR Orig
= Buffer
;
3111 static CHAR LastCommand
[1024];
3112 static CHAR NextKey
= '\0';
3113 INT CmdHistIndex
= -1;
3116 EchoOn
= !((KdbDebugState
& KD_DEBUG_KDNOECHO
) != 0);
3120 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
3122 Key
= (NextKey
== '\0') ? KdbpGetCharSerial() : NextKey
;
3125 if (Key
== KEY_ESC
) /* ESC */
3127 Key
= KdbpGetCharSerial();
3130 Key
= KdbpGetCharSerial();
3135 ScanCode
= KEY_SCAN_UP
;
3138 ScanCode
= KEY_SCAN_DOWN
;
3151 Key
= (NextKey
== '\0') ? KdbpGetCharKeyboard(&ScanCode
) : NextKey
;
3155 if ((ULONG
)(Buffer
- Orig
) >= (Size
- 1))
3157 /* Buffer is full, accept only newlines */
3164 /* Read the next char - this is to throw away a \n which most clients should
3167 KeStallExecutionProcessor(100000);
3169 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
3170 NextKey
= KdbpTryGetCharSerial(5);
3172 NextKey
= KdbpTryGetCharKeyboard(&ScanCode
, 5);
3174 if (NextKey
== '\n' || NextKey
== -1) /* \n or no response at all */
3180 * Repeat the last command if the user presses enter. Reduces the
3181 * risk of RSI when single-stepping.
3185 KdbRepeatLastCommand
= TRUE
;
3187 RtlStringCbCopyA(LastCommand
, sizeof(LastCommand
), Orig
);
3189 else if (KdbRepeatLastCommand
)
3190 RtlStringCbCopyA(Buffer
, Size
, LastCommand
);
3196 else if (Key
== KEY_BS
|| Key
== KEY_DEL
)
3204 KdbpPrint("%c %c", KEY_BS
, KEY_BS
);
3206 KdbpPrint(" %c", KEY_BS
);
3209 else if (ScanCode
== KEY_SCAN_UP
)
3211 BOOLEAN Print
= TRUE
;
3213 if (CmdHistIndex
< 0)
3215 CmdHistIndex
= KdbCommandHistoryIndex
;
3219 i
= CmdHistIndex
- 1;
3222 CmdHistIndex
= RTL_NUMBER_OF(KdbCommandHistory
) - 1;
3224 if (KdbCommandHistory
[i
] && i
!= KdbCommandHistoryIndex
)
3230 if (Print
&& KdbCommandHistory
[CmdHistIndex
])
3232 while (Buffer
> Orig
)
3238 KdbpPrint("%c %c", KEY_BS
, KEY_BS
);
3240 KdbpPrint(" %c", KEY_BS
);
3243 i
= min(strlen(KdbCommandHistory
[CmdHistIndex
]), Size
- 1);
3244 memcpy(Orig
, KdbCommandHistory
[CmdHistIndex
], i
);
3247 KdbpPrint("%s", Orig
);
3250 else if (ScanCode
== KEY_SCAN_DOWN
)
3252 if (CmdHistIndex
> 0 && CmdHistIndex
!= KdbCommandHistoryIndex
)
3254 i
= CmdHistIndex
+ 1;
3255 if (i
>= (INT
)RTL_NUMBER_OF(KdbCommandHistory
))
3258 if (KdbCommandHistory
[i
])
3261 while (Buffer
> Orig
)
3267 KdbpPrint("%c %c", KEY_BS
, KEY_BS
);
3269 KdbpPrint(" %c", KEY_BS
);
3272 i
= min(strlen(KdbCommandHistory
[CmdHistIndex
]), Size
- 1);
3273 memcpy(Orig
, KdbCommandHistory
[CmdHistIndex
], i
);
3276 KdbpPrint("%s", Orig
);
3283 KdbpPrint("%c", Key
);
3294 KdbRegisterCliCallback(
3300 /* Loop all entries */
3301 for (i
= 0; i
< _countof(KdbCliCallbacks
); i
++)
3303 /* Check if deregistering was requested */
3306 /* Check if this entry is the one that was registered */
3307 if (KdbCliCallbacks
[i
] == Callback
)
3309 /* Delete it and report success */
3310 KdbCliCallbacks
[i
] = NULL
;
3316 /* Check if this entry is free */
3317 if (KdbCliCallbacks
[i
] == NULL
)
3319 /* Set it and and report success */
3320 KdbCliCallbacks
[i
] = Callback
;
3330 /*! \brief Invokes registered CLI callbacks until one of them handled the
3333 * \param Command - Command line to parse and execute if possible.
3334 * \param Argc - Number of arguments in Argv
3335 * \param Argv - Array of strings, each of them containing one argument.
3337 * \return TRUE, if the command was handled, FALSE if it was not handled.
3341 KdbpInvokeCliCallbacks(
3348 /* Loop all entries */
3349 for (i
= 0; i
< _countof(KdbCliCallbacks
); i
++)
3351 /* Check if this entry is registered */
3352 if (KdbCliCallbacks
[i
])
3354 /* Invoke the callback and check if it handled the command */
3355 if (KdbCliCallbacks
[i
](Command
, Argc
, Argv
))
3362 /* None of the callbacks handled the command */
3367 /*!\brief Parses command line and executes command if found
3369 * \param Command Command line to parse and execute if possible.
3371 * \retval TRUE Don't continue execution.
3372 * \retval FALSE Continue execution (leave KDB)
3381 // FIXME: for what do we need a 1024 characters command line and 256 tokens?
3382 static PCH Argv
[256];
3383 static CHAR OrigCommand
[1024];
3385 RtlStringCbCopyA(OrigCommand
, sizeof(OrigCommand
), Command
);
3392 while (*p
== '\t' || *p
== ' ')
3398 i
= strcspn(p
, "\t ");
3411 for (i
= 0; i
< RTL_NUMBER_OF(KdbDebuggerCommands
); i
++)
3413 if (!KdbDebuggerCommands
[i
].Name
)
3416 if (strcmp(KdbDebuggerCommands
[i
].Name
, Argv
[0]) == 0)
3418 return KdbDebuggerCommands
[i
].Fn(Argc
, Argv
);
3422 /* Now invoke the registered callbacks */
3423 if (KdbpInvokeCliCallbacks(Command
, Argc
, Argv
))
3428 KdbpPrint("Command '%s' is unknown.\n", OrigCommand
);
3432 /*!\brief KDB Main Loop.
3434 * \param EnteredOnSingleStep TRUE if KDB was entered on single step.
3438 IN BOOLEAN EnteredOnSingleStep
)
3440 static CHAR Command
[1024];
3443 if (EnteredOnSingleStep
)
3445 if (!KdbSymPrintAddress((PVOID
)KdbCurrentTrapFrame
->Tf
.Eip
, &KdbCurrentTrapFrame
->Tf
))
3447 KdbpPrint("<%x>", KdbCurrentTrapFrame
->Tf
.Eip
);
3451 if (KdbpDisassemble(KdbCurrentTrapFrame
->Tf
.Eip
, KdbUseIntelSyntax
) < 0)
3453 KdbpPrint("<INVALID>");
3458 /* Flush the input buffer */
3459 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
3461 while (KdbpTryGetCharSerial(1) != -1);
3466 while (KdbpTryGetCharKeyboard(&ScanCode
, 1) != -1);
3472 /* Reset the number of rows/cols printed */
3473 KdbNumberOfRowsPrinted
= KdbNumberOfColsPrinted
= 0;
3475 /* Print the prompt */
3476 KdbpPrint("kdb:> ");
3478 /* Read a command and remember it */
3479 KdbpReadCommand(Command
, sizeof (Command
));
3480 KdbpCommandHistoryAppend(Command
);
3482 /* Reset the number of rows/cols printed and output aborted state */
3483 KdbNumberOfRowsPrinted
= KdbNumberOfColsPrinted
= 0;
3484 KdbOutputAborted
= FALSE
;
3486 /* Call the command */
3487 Continue
= KdbpDoCommand(Command
);
3488 KdbOutputAborted
= FALSE
;
3493 /*!\brief Called when a module is loaded.
3495 * \param Name Filename of the module which was loaded.
3498 KdbpCliModuleLoaded(
3499 IN PUNICODE_STRING Name
)
3501 if (!KdbBreakOnModuleLoad
)
3504 KdbpPrint("Module %wZ loaded.\n", Name
);
3505 DbgBreakPointWithStatus(DBG_STATUS_CONTROL_C
);
3508 /*!\brief This function is called by KdbEnterDebuggerException...
3510 * Used to interpret the init file in a context with a trapframe setup
3511 * (KdbpCliInit call KdbEnter which will call KdbEnterDebuggerException which will
3512 * call this function if KdbInitFileBuffer is not NULL.
3515 KdbpCliInterpretInitFile()
3521 /* Execute the commands in the init file */
3522 DPRINT("KDB: Executing KDBinit file...\n");
3523 p1
= KdbInitFileBuffer
;
3524 while (p1
[0] != '\0')
3526 i
= strcspn(p1
, "\r\n");
3532 /* Look for "break" command and comments */
3535 while (isspace(p2
[0]))
3538 if (strncmp(p2
, "break", sizeof("break")-1) == 0 &&
3539 (p2
[sizeof("break")-1] == '\0' || isspace(p2
[sizeof("break")-1])))
3541 /* break into the debugger */
3542 KdbpCliMainLoop(FALSE
);
3544 else if (p2
[0] != '#' && p2
[0] != '\0') /* Ignore empty lines and comments */
3553 while (p1
[0] == '\r' || p1
[0] == '\n')
3556 DPRINT("KDB: KDBinit executed\n");
3559 /*!\brief Called when KDB is initialized
3561 * Reads the KDBinit file from the SystemRoot\system32\drivers\etc directory and executes it.
3567 OBJECT_ATTRIBUTES ObjectAttributes
;
3568 UNICODE_STRING FileName
;
3569 IO_STATUS_BLOCK Iosb
;
3570 FILE_STANDARD_INFORMATION FileStdInfo
;
3571 HANDLE hFile
= NULL
;
3576 /* Initialize the object attributes */
3577 RtlInitUnicodeString(&FileName
, L
"\\SystemRoot\\system32\\drivers\\etc\\KDBinit");
3578 InitializeObjectAttributes(&ObjectAttributes
, &FileName
, 0, NULL
, NULL
);
3581 Status
= ZwOpenFile(&hFile
, FILE_READ_DATA
| SYNCHRONIZE
,
3582 &ObjectAttributes
, &Iosb
, 0,
3583 FILE_NON_DIRECTORY_FILE
| FILE_SYNCHRONOUS_IO_NONALERT
|
3584 FILE_NO_INTERMEDIATE_BUFFERING
);
3585 if (!NT_SUCCESS(Status
))
3587 DPRINT("Could not open \\SystemRoot\\system32\\drivers\\etc\\KDBinit (Status 0x%x)", Status
);
3591 /* Get the size of the file */
3592 Status
= ZwQueryInformationFile(hFile
, &Iosb
, &FileStdInfo
, sizeof (FileStdInfo
),
3593 FileStandardInformation
);
3594 if (!NT_SUCCESS(Status
))
3597 DPRINT("Could not query size of \\SystemRoot\\system32\\drivers\\etc\\KDBinit (Status 0x%x)", Status
);
3600 FileSize
= FileStdInfo
.EndOfFile
.u
.LowPart
;
3602 /* Allocate memory for the file */
3603 FileBuffer
= ExAllocatePool(PagedPool
, FileSize
+ 1); /* add 1 byte for terminating '\0' */
3607 DPRINT("Could not allocate %d bytes for KDBinit file\n", FileSize
);
3611 /* Load file into memory */
3612 Status
= ZwReadFile(hFile
, 0, 0, 0, &Iosb
, FileBuffer
, FileSize
, 0, 0);
3615 if (!NT_SUCCESS(Status
) && Status
!= STATUS_END_OF_FILE
)
3617 ExFreePool(FileBuffer
);
3618 DPRINT("Could not read KDBinit file into memory (Status 0x%lx)\n", Status
);
3622 FileSize
= min(FileSize
, (INT
)Iosb
.Information
);
3623 FileBuffer
[FileSize
] = '\0';
3625 /* Enter critical section */
3626 OldEflags
= __readeflags();
3629 /* Interpret the init file... */
3630 KdbInitFileBuffer
= FileBuffer
;
3632 KdbInitFileBuffer
= NULL
;
3634 /* Leave critical section */
3635 __writeeflags(OldEflags
);
3637 ExFreePool(FileBuffer
);
3642 KdpSerialDebugPrint(
3647 STRING KdpPromptString
= RTL_CONSTANT_STRING("kdb:> ");
3648 extern KSPIN_LOCK KdpSerialSpinLock
;
3652 KdpPrompt(IN LPSTR InString
,
3653 IN USHORT InStringLength
,
3654 OUT LPSTR OutString
,
3655 IN USHORT OutStringLength
)
3659 ULONG DummyScanCode
;
3662 /* Acquire the printing spinlock without waiting at raised IRQL */
3665 /* Wait when the spinlock becomes available */
3666 while (!KeTestSpinLock(&KdpSerialSpinLock
));
3668 /* Spinlock was free, raise IRQL */
3669 KeRaiseIrql(HIGH_LEVEL
, &OldIrql
);
3671 /* Try to get the spinlock */
3672 if (KeTryToAcquireSpinLockAtDpcLevel(&KdpSerialSpinLock
))
3675 /* Someone else got the spinlock, lower IRQL back */
3676 KeLowerIrql(OldIrql
);
3679 /* Loop the string to send */
3680 for (i
= 0; i
< InStringLength
; i
++)
3682 /* Print it to serial */
3683 KdPortPutByteEx(&SerialPortInfo
, *(PCHAR
)(InString
+ i
));
3686 /* Print a new line for log neatness */
3687 KdPortPutByteEx(&SerialPortInfo
, '\r');
3688 KdPortPutByteEx(&SerialPortInfo
, '\n');
3690 /* Print the kdb prompt */
3691 for (i
= 0; i
< KdpPromptString
.Length
; i
++)
3693 /* Print it to serial */
3694 KdPortPutByteEx(&SerialPortInfo
,
3695 *(KdpPromptString
.Buffer
+ i
));
3698 if (!(KdbDebugState
& KD_DEBUG_KDSERIAL
))
3701 /* Loop the whole string */
3702 for (i
= 0; i
< OutStringLength
; i
++)
3704 /* Check if this is serial debugging mode */
3705 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
3707 /* Get the character from serial */
3710 Response
= KdbpTryGetCharSerial(MAXULONG
);
3711 } while (Response
== -1);
3715 /* Get the response from the keyboard */
3718 Response
= KdbpTryGetCharKeyboard(&DummyScanCode
, MAXULONG
);
3719 } while (Response
== -1);
3722 /* Check for return */
3723 if (Response
== '\r')
3726 * We might need to discard the next '\n'.
3727 * Wait a bit to make sure we receive it.
3729 KeStallExecutionProcessor(100000);
3731 /* Check the mode */
3732 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
3734 /* Read and discard the next character, if any */
3735 KdbpTryGetCharSerial(5);
3739 /* Read and discard the next character, if any */
3740 KdbpTryGetCharKeyboard(&DummyScanCode
, 5);
3744 * Null terminate the output string -- documentation states that
3745 * DbgPrompt does not null terminate, but it does
3747 *(PCHAR
)(OutString
+ i
) = 0;
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
+ 1;
3763 /* Write it back and print it to the log */
3764 *(PCHAR
)(OutString
+ i
) = Response
;
3765 KdPortPutByteEx(&SerialPortInfo
, Response
);
3768 if (!(KdbDebugState
& KD_DEBUG_KDSERIAL
))
3771 /* Print a new line */
3772 KdPortPutByteEx(&SerialPortInfo
, '\r');
3773 KdPortPutByteEx(&SerialPortInfo
, '\n');
3775 /* Release spinlock */
3776 KiReleaseSpinLock(&KdpSerialSpinLock
);
3778 /* Lower IRQL back */
3779 KeLowerIrql(OldIrql
);
3781 /* Return the length */
3782 return OutStringLength
;