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/kdbg/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
KdbpCmdReboot(ULONG Argc
, PCHAR Argv
[]);
89 static BOOLEAN
KdbpCmdFilter(ULONG Argc
, PCHAR Argv
[]);
90 static BOOLEAN
KdbpCmdSet(ULONG Argc
, PCHAR Argv
[]);
91 static BOOLEAN
KdbpCmdHelp(ULONG Argc
, PCHAR Argv
[]);
92 static BOOLEAN
KdbpCmdDmesg(ULONG Argc
, PCHAR Argv
[]);
94 BOOLEAN
ExpKdbgExtPool(ULONG Argc
, PCHAR Argv
[]);
95 BOOLEAN
ExpKdbgExtPoolUsed(ULONG Argc
, PCHAR Argv
[]);
98 static BOOLEAN
KdbpCmdPrintStruct(ULONG Argc
, PCHAR Argv
[]);
101 /* GLOBALS *******************************************************************/
103 static PKDBG_CLI_ROUTINE KdbCliCallbacks
[10];
104 static BOOLEAN KdbUseIntelSyntax
= FALSE
; /* Set to TRUE for intel syntax */
105 static BOOLEAN KdbBreakOnModuleLoad
= FALSE
; /* Set to TRUE to break into KDB when a module is loaded */
107 static CHAR KdbCommandHistoryBuffer
[2048]; /* Command history string ringbuffer */
108 static PCHAR KdbCommandHistory
[sizeof(KdbCommandHistoryBuffer
) / 8] = { NULL
}; /* Command history ringbuffer */
109 static LONG KdbCommandHistoryBufferIndex
= 0;
110 static LONG KdbCommandHistoryIndex
= 0;
112 static ULONG KdbNumberOfRowsPrinted
= 0;
113 static ULONG KdbNumberOfColsPrinted
= 0;
114 static BOOLEAN KdbOutputAborted
= FALSE
;
115 static BOOLEAN KdbRepeatLastCommand
= FALSE
;
116 static LONG KdbNumberOfRowsTerminal
= -1;
117 static LONG KdbNumberOfColsTerminal
= -1;
119 PCHAR KdbInitFileBuffer
= NULL
; /* Buffer where KDBinit file is loaded into during initialization */
120 BOOLEAN KdbpBugCheckRequested
= FALSE
;
123 /* defined in ../kd/kdio.c, declare here: */
124 extern volatile BOOLEAN KdbpIsInDmesgMode
;
125 extern const ULONG KdpDmesgBufferSize
;
126 extern PCHAR KdpDmesgBuffer
;
127 extern volatile ULONG KdpDmesgCurrentPosition
;
128 extern volatile ULONG KdpDmesgFreeBytes
;
129 extern volatile ULONG KdbDmesgTotalWritten
;
136 BOOLEAN (*Fn
)(ULONG Argc
, PCHAR Argv
[]);
137 } KdbDebuggerCommands
[] = {
139 { NULL
, NULL
, "Data", NULL
},
140 { "?", "? expression", "Evaluate expression.", KdbpCmdEvalExpression
},
141 { "disasm", "disasm [address] [L count]", "Disassemble count instructions at address.", KdbpCmdDisassembleX
},
142 { "x", "x [address] [L count]", "Display count dwords, starting at addr.", KdbpCmdDisassembleX
},
143 { "regs", "regs", "Display general purpose registers.", KdbpCmdRegs
},
144 { "cregs", "cregs", "Display control registers.", KdbpCmdRegs
},
145 { "sregs", "sregs", "Display status registers.", KdbpCmdRegs
},
146 { "dregs", "dregs", "Display debug registers.", KdbpCmdRegs
},
147 { "bt", "bt [*frameaddr|thread id]", "Prints current backtrace or from given frame addr", KdbpCmdBackTrace
},
149 { "dt", "dt [mod] [type] [addr]", "Print a struct. Addr is optional.", KdbpCmdPrintStruct
},
153 { NULL
, NULL
, "Flow control", NULL
},
154 { "cont", "cont", "Continue execution (leave debugger)", KdbpCmdContinue
},
155 { "step", "step [count]", "Execute single instructions, stepping into interrupts.", KdbpCmdStep
},
156 { "next", "next [count]", "Execute single instructions, skipping calls and reps.", KdbpCmdStep
},
157 { "bl", "bl", "List breakpoints.", KdbpCmdBreakPointList
},
158 { "be", "be [breakpoint]", "Enable breakpoint.", KdbpCmdEnableDisableClearBreakPoint
},
159 { "bd", "bd [breakpoint]", "Disable breakpoint.", KdbpCmdEnableDisableClearBreakPoint
},
160 { "bc", "bc [breakpoint]", "Clear breakpoint.", KdbpCmdEnableDisableClearBreakPoint
},
161 { "bpx", "bpx [address] [IF condition]", "Set software execution breakpoint at address.", KdbpCmdBreakPoint
},
162 { "bpm", "bpm [r|w|rw|x] [byte|word|dword] [address] [IF condition]", "Set memory breakpoint at address.", KdbpCmdBreakPoint
},
165 { NULL
, NULL
, "Process/Thread", NULL
},
166 { "thread", "thread [list[ pid]|[attach ]tid]", "List threads in current or specified process, display thread with given id or attach to thread.", KdbpCmdThread
},
167 { "proc", "proc [list|[attach ]pid]", "List processes, display process with given id or attach to process.", KdbpCmdProc
},
169 /* System information */
170 { NULL
, NULL
, "System info", NULL
},
171 { "mod", "mod [address]", "List all modules or the one containing address.", KdbpCmdMod
},
172 { "gdt", "gdt", "Display global descriptor table.", KdbpCmdGdtLdtIdt
},
173 { "ldt", "ldt", "Display local descriptor table.", KdbpCmdGdtLdtIdt
},
174 { "idt", "idt", "Display interrupt descriptor table.", KdbpCmdGdtLdtIdt
},
175 { "pcr", "pcr", "Display processor control region.", KdbpCmdPcr
},
176 { "tss", "tss", "Display task state segment.", KdbpCmdTss
},
179 { NULL
, NULL
, "Others", NULL
},
180 { "bugcheck", "bugcheck", "Bugchecks the system.", KdbpCmdBugCheck
},
181 { "reboot", "reboot", "Reboots the system.", KdbpCmdReboot
},
182 { "filter", "filter [error|warning|trace|info|level]+|-[componentname|default]", "Enable/disable debug channels", KdbpCmdFilter
},
183 { "set", "set [var] [value]", "Sets var to value or displays value of var.", KdbpCmdSet
},
184 { "dmesg", "dmesg", "Display debug messages on screen, with navigation on pages.", KdbpCmdDmesg
},
185 { "kmsg", "kmsg", "Kernel dmesg. Alias for dmesg.", KdbpCmdDmesg
},
186 { "help", "help", "Display help screen.", KdbpCmdHelp
},
187 { "!pool", "!pool [Address [Flags]]", "Display information about pool allocations.", ExpKdbgExtPool
},
188 { "!poolused", "!poolused [Tag]", "Display pool usage.", ExpKdbgExtPoolUsed
},
191 /* FUNCTIONS *****************************************************************/
193 /*!\brief Transform a component name to an integer
195 * \param ComponentName The name of the component.
196 * \param ComponentId Receives the component id on success.
198 * \retval TRUE Success.
199 * \retval FALSE Failure.
203 IN PCCH ComponentName
,
204 OUT PULONG ComponentId
)
215 { "DEFAULT", MAXULONG
},
216 { "SYSTEM", DPFLTR_SYSTEM_ID
},
217 { "SMSS", DPFLTR_SMSS_ID
},
218 { "SETUP", DPFLTR_SETUP_ID
},
219 { "NTFS", DPFLTR_NTFS_ID
},
220 { "FSTUB", DPFLTR_FSTUB_ID
},
221 { "CRASHDUMP", DPFLTR_CRASHDUMP_ID
},
222 { "CDAUDIO", DPFLTR_CDAUDIO_ID
},
223 { "CDROM", DPFLTR_CDROM_ID
},
224 { "CLASSPNP", DPFLTR_CLASSPNP_ID
},
225 { "DISK", DPFLTR_DISK_ID
},
226 { "REDBOOK", DPFLTR_REDBOOK_ID
},
227 { "STORPROP", DPFLTR_STORPROP_ID
},
228 { "SCSIPORT", DPFLTR_SCSIPORT_ID
},
229 { "SCSIMINIPORT", DPFLTR_SCSIMINIPORT_ID
},
230 { "CONFIG", DPFLTR_CONFIG_ID
},
231 { "I8042PRT", DPFLTR_I8042PRT_ID
},
232 { "SERMOUSE", DPFLTR_SERMOUSE_ID
},
233 { "LSERMOUS", DPFLTR_LSERMOUS_ID
},
234 { "KBDHID", DPFLTR_KBDHID_ID
},
235 { "MOUHID", DPFLTR_MOUHID_ID
},
236 { "KBDCLASS", DPFLTR_KBDCLASS_ID
},
237 { "MOUCLASS", DPFLTR_MOUCLASS_ID
},
238 { "TWOTRACK", DPFLTR_TWOTRACK_ID
},
239 { "WMILIB", DPFLTR_WMILIB_ID
},
240 { "ACPI", DPFLTR_ACPI_ID
},
241 { "AMLI", DPFLTR_AMLI_ID
},
242 { "HALIA64", DPFLTR_HALIA64_ID
},
243 { "VIDEO", DPFLTR_VIDEO_ID
},
244 { "SVCHOST", DPFLTR_SVCHOST_ID
},
245 { "VIDEOPRT", DPFLTR_VIDEOPRT_ID
},
246 { "TCPIP", DPFLTR_TCPIP_ID
},
247 { "DMSYNTH", DPFLTR_DMSYNTH_ID
},
248 { "NTOSPNP", DPFLTR_NTOSPNP_ID
},
249 { "FASTFAT", DPFLTR_FASTFAT_ID
},
250 { "SAMSS", DPFLTR_SAMSS_ID
},
251 { "PNPMGR", DPFLTR_PNPMGR_ID
},
252 { "NETAPI", DPFLTR_NETAPI_ID
},
253 { "SCSERVER", DPFLTR_SCSERVER_ID
},
254 { "SCCLIENT", DPFLTR_SCCLIENT_ID
},
255 { "SERIAL", DPFLTR_SERIAL_ID
},
256 { "SERENUM", DPFLTR_SERENUM_ID
},
257 { "UHCD", DPFLTR_UHCD_ID
},
258 { "RPCPROXY", DPFLTR_RPCPROXY_ID
},
259 { "AUTOCHK", DPFLTR_AUTOCHK_ID
},
260 { "DCOMSS", DPFLTR_DCOMSS_ID
},
261 { "UNIMODEM", DPFLTR_UNIMODEM_ID
},
262 { "SIS", DPFLTR_SIS_ID
},
263 { "FLTMGR", DPFLTR_FLTMGR_ID
},
264 { "WMICORE", DPFLTR_WMICORE_ID
},
265 { "BURNENG", DPFLTR_BURNENG_ID
},
266 { "IMAPI", DPFLTR_IMAPI_ID
},
267 { "SXS", DPFLTR_SXS_ID
},
268 { "FUSION", DPFLTR_FUSION_ID
},
269 { "IDLETASK", DPFLTR_IDLETASK_ID
},
270 { "SOFTPCI", DPFLTR_SOFTPCI_ID
},
271 { "TAPE", DPFLTR_TAPE_ID
},
272 { "MCHGR", DPFLTR_MCHGR_ID
},
273 { "IDEP", DPFLTR_IDEP_ID
},
274 { "PCIIDE", DPFLTR_PCIIDE_ID
},
275 { "FLOPPY", DPFLTR_FLOPPY_ID
},
276 { "FDC", DPFLTR_FDC_ID
},
277 { "TERMSRV", DPFLTR_TERMSRV_ID
},
278 { "W32TIME", DPFLTR_W32TIME_ID
},
279 { "PREFETCHER", DPFLTR_PREFETCHER_ID
},
280 { "RSFILTER", DPFLTR_RSFILTER_ID
},
281 { "FCPORT", DPFLTR_FCPORT_ID
},
282 { "PCI", DPFLTR_PCI_ID
},
283 { "DMIO", DPFLTR_DMIO_ID
},
284 { "DMCONFIG", DPFLTR_DMCONFIG_ID
},
285 { "DMADMIN", DPFLTR_DMADMIN_ID
},
286 { "WSOCKTRANSPORT", DPFLTR_WSOCKTRANSPORT_ID
},
287 { "VSS", DPFLTR_VSS_ID
},
288 { "PNPMEM", DPFLTR_PNPMEM_ID
},
289 { "PROCESSOR", DPFLTR_PROCESSOR_ID
},
290 { "DMSERVER", DPFLTR_DMSERVER_ID
},
291 { "SR", DPFLTR_SR_ID
},
292 { "INFINIBAND", DPFLTR_INFINIBAND_ID
},
293 { "IHVDRIVER", DPFLTR_IHVDRIVER_ID
},
294 { "IHVVIDEO", DPFLTR_IHVVIDEO_ID
},
295 { "IHVAUDIO", DPFLTR_IHVAUDIO_ID
},
296 { "IHVNETWORK", DPFLTR_IHVNETWORK_ID
},
297 { "IHVSTREAMING", DPFLTR_IHVSTREAMING_ID
},
298 { "IHVBUS", DPFLTR_IHVBUS_ID
},
299 { "HPS", DPFLTR_HPS_ID
},
300 { "RTLTHREADPOOL", DPFLTR_RTLTHREADPOOL_ID
},
301 { "LDR", DPFLTR_LDR_ID
},
302 { "TCPIP6", DPFLTR_TCPIP6_ID
},
303 { "ISAPNP", DPFLTR_ISAPNP_ID
},
304 { "SHPC", DPFLTR_SHPC_ID
},
305 { "STORPORT", DPFLTR_STORPORT_ID
},
306 { "STORMINIPORT", DPFLTR_STORMINIPORT_ID
},
307 { "PRINTSPOOLER", DPFLTR_PRINTSPOOLER_ID
},
308 { "VSSDYNDISK", DPFLTR_VSSDYNDISK_ID
},
309 { "VERIFIER", DPFLTR_VERIFIER_ID
},
310 { "VDS", DPFLTR_VDS_ID
},
311 { "VDSBAS", DPFLTR_VDSBAS_ID
},
312 { "VDSDYN", DPFLTR_VDSDYN_ID
},
313 { "VDSDYNDR", DPFLTR_VDSDYNDR_ID
},
314 { "VDSLDR", DPFLTR_VDSLDR_ID
},
315 { "VDSUTIL", DPFLTR_VDSUTIL_ID
},
316 { "DFRGIFC", DPFLTR_DFRGIFC_ID
},
317 { "MM", DPFLTR_MM_ID
},
318 { "DFSC", DPFLTR_DFSC_ID
},
319 { "WOW64", DPFLTR_WOW64_ID
},
320 { "ALPC", DPFLTR_ALPC_ID
},
321 { "WDI", DPFLTR_WDI_ID
},
322 { "PERFLIB", DPFLTR_PERFLIB_ID
},
323 { "KTM", DPFLTR_KTM_ID
},
324 { "IOSTRESS", DPFLTR_IOSTRESS_ID
},
325 { "HEAP", DPFLTR_HEAP_ID
},
326 { "WHEA", DPFLTR_WHEA_ID
},
327 { "USERGDI", DPFLTR_USERGDI_ID
},
328 { "MMCSS", DPFLTR_MMCSS_ID
},
329 { "TPM", DPFLTR_TPM_ID
},
330 { "THREADORDER", DPFLTR_THREADORDER_ID
},
331 { "ENVIRON", DPFLTR_ENVIRON_ID
},
332 { "EMS", DPFLTR_EMS_ID
},
333 { "WDT", DPFLTR_WDT_ID
},
334 { "FVEVOL", DPFLTR_FVEVOL_ID
},
335 { "NDIS", DPFLTR_NDIS_ID
},
336 { "NVCTRACE", DPFLTR_NVCTRACE_ID
},
337 { "LUAFV", DPFLTR_LUAFV_ID
},
338 { "APPCOMPAT", DPFLTR_APPCOMPAT_ID
},
339 { "USBSTOR", DPFLTR_USBSTOR_ID
},
340 { "SBP2PORT", DPFLTR_SBP2PORT_ID
},
341 { "COVERAGE", DPFLTR_COVERAGE_ID
},
342 { "CACHEMGR", DPFLTR_CACHEMGR_ID
},
343 { "MOUNTMGR", DPFLTR_MOUNTMGR_ID
},
344 { "CFR", DPFLTR_CFR_ID
},
345 { "TXF", DPFLTR_TXF_ID
},
346 { "KSECDD", DPFLTR_KSECDD_ID
},
347 { "FLTREGRESS", DPFLTR_FLTREGRESS_ID
},
348 { "MPIO", DPFLTR_MPIO_ID
},
349 { "MSDSM", DPFLTR_MSDSM_ID
},
350 { "UDFS", DPFLTR_UDFS_ID
},
351 { "PSHED", DPFLTR_PSHED_ID
},
352 { "STORVSP", DPFLTR_STORVSP_ID
},
353 { "LSASS", DPFLTR_LSASS_ID
},
354 { "SSPICLI", DPFLTR_SSPICLI_ID
},
355 { "CNG", DPFLTR_CNG_ID
},
356 { "EXFAT", DPFLTR_EXFAT_ID
},
357 { "FILETRACE", DPFLTR_FILETRACE_ID
},
358 { "XSAVE", DPFLTR_XSAVE_ID
},
359 { "SE", DPFLTR_SE_ID
},
360 { "DRIVEEXTENDER", DPFLTR_DRIVEEXTENDER_ID
},
363 for (i
= 0; i
< sizeof(ComponentTable
) / sizeof(ComponentTable
[0]); i
++)
365 if (_stricmp(ComponentName
, ComponentTable
[i
].Name
) == 0)
367 *ComponentId
= ComponentTable
[i
].Id
;
375 /*!\brief Evaluates an expression...
377 * Much like KdbpRpnEvaluateExpression, but prints the error message (if any)
378 * at the given offset.
380 * \param Expression Expression to evaluate.
381 * \param ErrOffset Offset (in characters) to print the error message at.
382 * \param Result Receives the result on success.
384 * \retval TRUE Success.
385 * \retval FALSE Failure.
388 KdbpEvaluateExpression(
391 OUT PULONGLONG Result
)
393 static CHAR ErrMsgBuffer
[130] = "^ ";
394 LONG ExpressionErrOffset
= -1;
395 PCHAR ErrMsg
= ErrMsgBuffer
;
398 Ok
= KdbpRpnEvaluateExpression(Expression
, KdbCurrentTrapFrame
, Result
,
399 &ExpressionErrOffset
, ErrMsgBuffer
+ 2);
402 if (ExpressionErrOffset
>= 0)
403 ExpressionErrOffset
+= ErrOffset
;
407 KdbpPrint("%*s%s\n", ExpressionErrOffset
, "", ErrMsg
);
417 OUT ULONG_PTR
*pulValue
)
421 /* Skip optional '0x' prefix */
422 if ((pszNum
[0] == '0') && ((pszNum
[1] == 'x') || (pszNum
[1] == 'X')))
425 /* Make a number from the string (hex) */
426 *pulValue
= strtoul(pszNum
, &endptr
, 16);
428 return (*endptr
== '\0');
431 /*!\brief Evaluates an expression and displays the result.
434 KdbpCmdEvalExpression(
439 ULONGLONG Result
= 0;
446 KdbpPrint("?: Argument required\n");
450 /* Put the arguments back together */
452 for (i
= 1; i
< Argc
; i
++)
454 len
= strlen(Argv
[i
]);
458 /* Evaluate the expression */
459 Ok
= KdbpEvaluateExpression(Argv
[1], sizeof("kdb:> ")-1 + (Argv
[1]-Argv
[0]), &Result
);
462 if (Result
> 0x00000000ffffffffLL
)
464 if (Result
& 0x8000000000000000LL
)
465 KdbpPrint("0x%016I64x %20I64u %20I64d\n", Result
, Result
, Result
);
467 KdbpPrint("0x%016I64x %20I64u\n", Result
, Result
);
473 if (ul
<= 0xff && ul
>= 0x80)
474 l
= (LONG
)((CHAR
)ul
);
475 else if (ul
<= 0xffff && ul
>= 0x8000)
476 l
= (LONG
)((SHORT
)ul
);
481 KdbpPrint("0x%08lx %10lu %10ld\n", ul
, ul
, l
);
483 KdbpPrint("0x%08lx %10lu\n", ul
, ul
);
492 /*!\brief Print a struct
495 KdbpPrintStructInternal
500 PROSSYM_AGGREGATE Aggregate
)
504 PROSSYM_AGGREGATE_MEMBER Member
;
505 ULONG IndentLen
= strlen(Indent
);
506 ROSSYM_AGGREGATE MemberAggregate
= {0 };
508 for (i
= 0; i
< Aggregate
->NumElements
; i
++) {
509 Member
= &Aggregate
->Elements
[i
];
510 KdbpPrint("%s%p+%x: %s", Indent
, ((PCHAR
)BaseAddress
) + Member
->BaseOffset
, Member
->Size
, Member
->Name
? Member
->Name
: "<anoymous>");
512 if (!strcmp(Member
->Type
, "_UNICODE_STRING")) {
513 KdbpPrint("\"%wZ\"\n", ((PCHAR
)BaseAddress
) + Member
->BaseOffset
);
515 } else if (!strcmp(Member
->Type
, "PUNICODE_STRING")) {
516 KdbpPrint("\"%wZ\"\n", *(((PUNICODE_STRING
*)((PCHAR
)BaseAddress
) + Member
->BaseOffset
)));
519 switch (Member
->Size
) {
525 if (NT_SUCCESS(KdbpSafeReadMemory(&Result
, ((PCHAR
)BaseAddress
) + Member
->BaseOffset
, Member
->Size
))) {
527 Result
>>= Member
->FirstBit
;
528 Result
&= ((1 << Member
->Bits
) - 1);
530 KdbpPrint(" %lx\n", Result
);
536 if (Member
->Size
< 8) {
537 if (NT_SUCCESS(KdbpSafeReadMemory(&Result
, ((PCHAR
)BaseAddress
) + Member
->BaseOffset
, Member
->Size
))) {
539 for (j
= 0; j
< Member
->Size
; j
++) {
540 KdbpPrint(" %02x", (int)(Result
& 0xff));
543 } else goto readfail
;
545 KdbpPrint(" %s @ %p {\n", Member
->Type
, ((PCHAR
)BaseAddress
) + Member
->BaseOffset
);
546 Indent
[IndentLen
] = ' ';
547 if (RosSymAggregate(Info
, Member
->Type
, &MemberAggregate
)) {
548 KdbpPrintStructInternal(Info
, Indent
, DoRead
, ((PCHAR
)BaseAddress
) + Member
->BaseOffset
, &MemberAggregate
);
549 RosSymFreeAggregate(&MemberAggregate
);
551 Indent
[IndentLen
] = 0;
552 KdbpPrint("%s}\n", Indent
);
558 if (Member
->Size
<= 8) {
561 KdbpPrint(" %s @ %x {\n", Member
->Type
, Member
->BaseOffset
);
562 Indent
[IndentLen
] = ' ';
563 if (RosSymAggregate(Info
, Member
->Type
, &MemberAggregate
)) {
564 KdbpPrintStructInternal(Info
, Indent
, DoRead
, BaseAddress
, &MemberAggregate
);
565 RosSymFreeAggregate(&MemberAggregate
);
567 Indent
[IndentLen
] = 0;
568 KdbpPrint("%s}\n", Indent
);
574 PROSSYM_INFO
KdbpSymFindCachedFile(PUNICODE_STRING ModName
);
582 ULONGLONG Result
= 0;
583 PVOID BaseAddress
= 0;
584 ROSSYM_AGGREGATE Aggregate
= {0};
585 UNICODE_STRING ModName
= {0};
586 ANSI_STRING AnsiName
= {0};
587 CHAR Indent
[100] = {0};
590 if (Argc
< 3) goto end
;
591 AnsiName
.Length
= AnsiName
.MaximumLength
= strlen(Argv
[1]);
592 AnsiName
.Buffer
= Argv
[1];
593 RtlAnsiStringToUnicodeString(&ModName
, &AnsiName
, TRUE
);
594 Info
= KdbpSymFindCachedFile(&ModName
);
596 if (!Info
|| !RosSymAggregate(Info
, Argv
[2], &Aggregate
)) {
597 DPRINT1("Could not get aggregate\n");
601 // Get an argument for location if it was given
604 PCHAR ArgStart
= Argv
[3];
605 DPRINT1("Trying to get expression\n");
606 for (i
= 3; i
< Argc
- 1; i
++)
608 len
= strlen(Argv
[i
]);
612 /* Evaluate the expression */
613 DPRINT1("Arg: %s\n", ArgStart
);
614 if (KdbpEvaluateExpression(ArgStart
, strlen(ArgStart
), &Result
)) {
615 BaseAddress
= (PVOID
)(ULONG_PTR
)Result
;
616 DPRINT1("BaseAddress: %p\n", BaseAddress
);
619 DPRINT1("BaseAddress %p\n", BaseAddress
);
620 KdbpPrintStructInternal(Info
, Indent
, !!BaseAddress
, BaseAddress
, &Aggregate
);
622 RosSymFreeAggregate(&Aggregate
);
623 RtlFreeUnicodeString(&ModName
);
628 /*!\brief Display list of active debug channels
635 ULONG i
, j
, ComponentId
, Level
;
636 ULONG set
= DPFLTR_MASK
, clear
= DPFLTR_MASK
;
647 { "error", 1 << DPFLTR_ERROR_LEVEL
},
648 { "warning", 1 << DPFLTR_WARNING_LEVEL
},
649 { "trace", 1 << DPFLTR_TRACE_LEVEL
},
650 { "info", 1 << DPFLTR_INFO_LEVEL
},
653 for (i
= 1; i
< Argc
; i
++)
656 p
= opt
+ strcspn(opt
, "+-");
657 if (!p
[0]) p
= opt
; /* assume it's a debug channel name */
661 for (j
= 0; j
< sizeof(debug_classes
) / sizeof(debug_classes
[0]); j
++)
663 SIZE_T len
= strlen(debug_classes
[j
].Name
);
664 if (len
!= (p
- opt
))
666 if (_strnicmp(opt
, debug_classes
[j
].Name
, len
) == 0) /* found it */
669 set
|= debug_classes
[j
].Level
;
671 clear
|= debug_classes
[j
].Level
;
675 if (j
== sizeof(debug_classes
) / sizeof(debug_classes
[0]))
677 Level
= strtoul(opt
, &pend
, 0);
680 KdbpPrint("filter: bad class name '%.*s'\n", p
- opt
, opt
);
696 if (*p
== '+' || *p
== '-')
699 if (!KdbpGetComponentId(p
, &ComponentId
))
701 KdbpPrint("filter: '%s' is not a valid component name!\n", p
);
705 /* Get current mask value */
706 NtSetDebugFilterState(ComponentId
, set
, TRUE
);
707 NtSetDebugFilterState(ComponentId
, clear
, FALSE
);
713 /*!\brief Disassembles 10 instructions at eip or given address or
714 * displays 16 dwords from memory at given address.
724 ULONGLONG Result
= 0;
725 ULONG_PTR Address
= KdbCurrentTrapFrame
->Tf
.Eip
;
728 if (Argv
[0][0] == 'x') /* display memory */
730 else /* disassemble */
735 /* Check for [L count] part */
737 if (strcmp(Argv
[Argc
-2], "L") == 0)
739 ul
= strtoul(Argv
[Argc
-1], NULL
, 0);
746 else if (Argv
[Argc
-1][0] == 'L')
748 ul
= strtoul(Argv
[Argc
-1] + 1, NULL
, 0);
756 /* Put the remaining arguments back together */
758 for (ul
= 1; ul
< Argc
; ul
++)
760 Argv
[ul
][strlen(Argv
[ul
])] = ' ';
765 /* Evaluate the expression */
768 if (!KdbpEvaluateExpression(Argv
[1], sizeof("kdb:> ")-1 + (Argv
[1]-Argv
[0]), &Result
))
771 if (Result
> (ULONGLONG
)(~((ULONG_PTR
)0)))
772 KdbpPrint("Warning: Address %I64x is beeing truncated\n",Result
);
774 Address
= (ULONG_PTR
)Result
;
776 else if (Argv
[0][0] == 'x')
778 KdbpPrint("x: Address argument required.\n");
782 if (Argv
[0][0] == 'x')
789 if (!KdbSymPrintAddress((PVOID
)Address
, NULL
))
790 KdbpPrint("<%x>:", Address
);
799 if (!NT_SUCCESS(KdbpSafeReadMemory(&ul
, (PVOID
)Address
, sizeof(ul
))))
800 KdbpPrint(" ????????");
802 KdbpPrint(" %08x", ul
);
804 Address
+= sizeof(ul
);
815 if (!KdbSymPrintAddress((PVOID
)Address
, NULL
))
816 KdbpPrint("<%08x>: ", Address
);
820 InstLen
= KdbpDisassemble(Address
, KdbUseIntelSyntax
);
823 KdbpPrint("<INVALID>\n");
835 /*!\brief Displays CPU registers.
842 PKTRAP_FRAME Tf
= &KdbCurrentTrapFrame
->Tf
;
844 static const PCHAR EflagsBits
[32] = { " CF", NULL
, " PF", " BIT3", " AF", " BIT5",
845 " ZF", " SF", " TF", " IF", " DF", " OF",
846 NULL
, NULL
, " NT", " BIT15", " RF", " VF",
847 " AC", " VIF", " VIP", " ID", " BIT22",
848 " BIT23", " BIT24", " BIT25", " BIT26",
849 " BIT27", " BIT28", " BIT29", " BIT30",
852 if (Argv
[0][0] == 'r') /* regs */
854 KdbpPrint("CS:EIP 0x%04x:0x%08x\n"
855 "SS:ESP 0x%04x:0x%08x\n"
856 " EAX 0x%08x EBX 0x%08x\n"
857 " ECX 0x%08x EDX 0x%08x\n"
858 " ESI 0x%08x EDI 0x%08x\n"
860 Tf
->SegCs
& 0xFFFF, Tf
->Eip
,
861 Tf
->HardwareSegSs
, Tf
->HardwareEsp
,
866 KdbpPrint("EFLAGS 0x%08x ", Tf
->EFlags
);
868 for (i
= 0; i
< 32; i
++)
872 if ((Tf
->EFlags
& (1 << 1)) == 0)
877 KdbpPrint(" IOPL%d", (Tf
->EFlags
>> 12) & 3);
882 else if ((Tf
->EFlags
& (1 << i
)) != 0)
884 KdbpPrint(EflagsBits
[i
]);
890 else if (Argv
[0][0] == 'c') /* cregs */
892 ULONG Cr0
, Cr2
, Cr3
, Cr4
;
893 KDESCRIPTOR Gdtr
= {0, 0, 0}, Idtr
= {0, 0, 0};
895 static const PCHAR Cr0Bits
[32] = { " PE", " MP", " EM", " TS", " ET", " NE", NULL
, NULL
,
896 NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
,
897 " WP", NULL
, " AM", NULL
, NULL
, NULL
, NULL
, NULL
,
898 NULL
, NULL
, NULL
, NULL
, NULL
, " NW", " CD", " PG" };
899 static const PCHAR Cr4Bits
[32] = { " VME", " PVI", " TSD", " DE", " PSE", " PAE", " MCE", " PGE",
900 " PCE", " OSFXSR", " OSXMMEXCPT", NULL
, NULL
, NULL
, NULL
, NULL
,
901 NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
,
902 NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
};
904 Cr0
= KdbCurrentTrapFrame
->Cr0
;
905 Cr2
= KdbCurrentTrapFrame
->Cr2
;
906 Cr3
= KdbCurrentTrapFrame
->Cr3
;
907 Cr4
= KdbCurrentTrapFrame
->Cr4
;
909 /* Get descriptor table regs */
910 Ke386GetGlobalDescriptorTable(&Gdtr
.Limit
);
911 Ldtr
= Ke386GetLocalDescriptorTable();
914 /* Display the control registers */
915 KdbpPrint("CR0 0x%08x ", Cr0
);
917 for (i
= 0; i
< 32; i
++)
922 if ((Cr0
& (1 << i
)) != 0)
923 KdbpPrint(Cr0Bits
[i
]);
926 KdbpPrint("\nCR2 0x%08x\n", Cr2
);
927 KdbpPrint("CR3 0x%08x Pagedir-Base 0x%08x %s%s\n", Cr3
, (Cr3
& 0xfffff000),
928 (Cr3
& (1 << 3)) ? " PWT" : "", (Cr3
& (1 << 4)) ? " PCD" : "" );
929 KdbpPrint("CR4 0x%08x ", Cr4
);
931 for (i
= 0; i
< 32; i
++)
936 if ((Cr4
& (1 << i
)) != 0)
937 KdbpPrint(Cr4Bits
[i
]);
940 /* Display the descriptor table regs */
941 KdbpPrint("\nGDTR Base 0x%08x Size 0x%04x\n", Gdtr
.Base
, Gdtr
.Limit
);
942 KdbpPrint("LDTR 0x%04x\n", Ldtr
);
943 KdbpPrint("IDTR Base 0x%08x Size 0x%04x\n", Idtr
.Base
, Idtr
.Limit
);
945 else if (Argv
[0][0] == 's') /* sregs */
947 KdbpPrint("CS 0x%04x Index 0x%04x %cDT RPL%d\n",
948 Tf
->SegCs
& 0xffff, (Tf
->SegCs
& 0xffff) >> 3,
949 (Tf
->SegCs
& (1 << 2)) ? 'L' : 'G', Tf
->SegCs
& 3);
950 KdbpPrint("DS 0x%04x Index 0x%04x %cDT RPL%d\n",
951 Tf
->SegDs
, Tf
->SegDs
>> 3, (Tf
->SegDs
& (1 << 2)) ? 'L' : 'G', Tf
->SegDs
& 3);
952 KdbpPrint("ES 0x%04x Index 0x%04x %cDT RPL%d\n",
953 Tf
->SegEs
, Tf
->SegEs
>> 3, (Tf
->SegEs
& (1 << 2)) ? 'L' : 'G', Tf
->SegEs
& 3);
954 KdbpPrint("FS 0x%04x Index 0x%04x %cDT RPL%d\n",
955 Tf
->SegFs
, Tf
->SegFs
>> 3, (Tf
->SegFs
& (1 << 2)) ? 'L' : 'G', Tf
->SegFs
& 3);
956 KdbpPrint("GS 0x%04x Index 0x%04x %cDT RPL%d\n",
957 Tf
->SegGs
, Tf
->SegGs
>> 3, (Tf
->SegGs
& (1 << 2)) ? 'L' : 'G', Tf
->SegGs
& 3);
958 KdbpPrint("SS 0x%04x Index 0x%04x %cDT RPL%d\n",
959 Tf
->HardwareSegSs
, Tf
->HardwareSegSs
>> 3, (Tf
->HardwareSegSs
& (1 << 2)) ? 'L' : 'G', Tf
->HardwareSegSs
& 3);
963 ASSERT(Argv
[0][0] == 'd');
964 KdbpPrint("DR0 0x%08x\n"
970 Tf
->Dr0
, Tf
->Dr1
, Tf
->Dr2
, Tf
->Dr3
,
978 KdbpTrapFrameFromPrevTss(
979 PKTRAP_FRAME TrapFrame
)
987 Ke386GetGlobalDescriptorTable(&Gdtr
.Limit
);
990 if ((Sel
& (sizeof(KGDTENTRY
) - 1)) ||
991 (Sel
< sizeof(KGDTENTRY
)) ||
992 (Sel
+ sizeof(KGDTENTRY
) - 1 > Gdtr
.Limit
))
995 if (!NT_SUCCESS(KdbpSafeReadMemory(&Desc
,
996 (PVOID
)(Gdtr
.Base
+ Sel
),
1000 if (Desc
.HighWord
.Bits
.Type
!= 0xB)
1003 Tss
= (PKTSS
)(ULONG_PTR
)(Desc
.BaseLow
|
1004 Desc
.HighWord
.Bytes
.BaseMid
<< 16 |
1005 Desc
.HighWord
.Bytes
.BaseHi
<< 24);
1007 if (!NT_SUCCESS(KdbpSafeReadMemory(&Sel
,
1008 (PVOID
)&Tss
->Backlink
,
1012 if ((Sel
& (sizeof(KGDTENTRY
) - 1)) ||
1013 (Sel
< sizeof(KGDTENTRY
)) ||
1014 (Sel
+ sizeof(KGDTENTRY
) - 1 > Gdtr
.Limit
))
1017 if (!NT_SUCCESS(KdbpSafeReadMemory(&Desc
,
1018 (PVOID
)(Gdtr
.Base
+ Sel
),
1019 sizeof(KGDTENTRY
))))
1022 if (Desc
.HighWord
.Bits
.Type
!= 0xB)
1025 Tss
= (PKTSS
)(ULONG_PTR
)(Desc
.BaseLow
|
1026 Desc
.HighWord
.Bytes
.BaseMid
<< 16 |
1027 Desc
.HighWord
.Bytes
.BaseHi
<< 24);
1029 if (!NT_SUCCESS(KdbpSafeReadMemory(&Eip
,
1031 sizeof(ULONG_PTR
))))
1034 if (!NT_SUCCESS(KdbpSafeReadMemory(&Ebp
,
1036 sizeof(ULONG_PTR
))))
1039 TrapFrame
->Eip
= Eip
;
1040 TrapFrame
->Ebp
= Ebp
;
1044 VOID __cdecl
KiTrap02(VOID
);
1045 VOID FASTCALL
KiTrap03Handler(IN PKTRAP_FRAME
);
1046 VOID __cdecl
KiTrap08(VOID
);
1047 VOID __cdecl
KiTrap09(VOID
);
1050 KdbpInNmiOrDoubleFaultHandler(
1053 return (Address
> (ULONG_PTR
)KiTrap02
&& Address
< (ULONG_PTR
)KiTrap03Handler
) ||
1054 (Address
> (ULONG_PTR
)KiTrap08
&& Address
< (ULONG_PTR
)KiTrap09
);
1057 /*!\brief Displays a backtrace.
1065 ULONGLONG Result
= 0;
1066 ULONG_PTR Frame
= KdbCurrentTrapFrame
->Tf
.Ebp
;
1068 KTRAP_FRAME TrapFrame
;
1072 /* Check for [L count] part */
1075 if (strcmp(Argv
[Argc
-2], "L") == 0)
1077 ul
= strtoul(Argv
[Argc
-1], NULL
, 0);
1083 else if (Argv
[Argc
-1][0] == 'L')
1085 ul
= strtoul(Argv
[Argc
-1] + 1, NULL
, 0);
1092 /* Put the remaining arguments back together */
1094 for (ul
= 1; ul
< Argc
; ul
++)
1096 Argv
[ul
][strlen(Argv
[ul
])] = ' ';
1101 /* Check if frame addr or thread id is given. */
1104 if (Argv
[1][0] == '*')
1108 /* Evaluate the expression */
1109 if (!KdbpEvaluateExpression(Argv
[1], sizeof("kdb:> ")-1 + (Argv
[1]-Argv
[0]), &Result
))
1112 if (Result
> (ULONGLONG
)(~((ULONG_PTR
)0)))
1113 KdbpPrint("Warning: Address %I64x is beeing truncated\n",Result
);
1115 Frame
= (ULONG_PTR
)Result
;
1119 KdbpPrint("Thread backtrace not supported yet!\n");
1125 KdbpPrint("Eip:\n");
1127 /* Try printing the function at EIP */
1128 if (!KdbSymPrintAddress((PVOID
)KdbCurrentTrapFrame
->Tf
.Eip
, &KdbCurrentTrapFrame
->Tf
))
1129 KdbpPrint("<%08x>\n", KdbCurrentTrapFrame
->Tf
.Eip
);
1134 TrapFrame
= KdbCurrentTrapFrame
->Tf
;
1135 KdbpPrint("Frames:\n");
1139 BOOLEAN GotNextFrame
;
1144 if (!NT_SUCCESS(KdbpSafeReadMemory(&Address
, (PVOID
)(Frame
+ sizeof(ULONG_PTR
)), sizeof (ULONG_PTR
))))
1146 KdbpPrint("Couldn't access memory at 0x%p!\n", Frame
+ sizeof(ULONG_PTR
));
1150 if ((GotNextFrame
= NT_SUCCESS(KdbpSafeReadMemory(&Frame
, (PVOID
)Frame
, sizeof (ULONG_PTR
)))))
1151 TrapFrame
.Ebp
= Frame
;
1153 /* Print the location of the call instruction */
1154 if (!KdbSymPrintAddress((PVOID
)(Address
- 5), &TrapFrame
))
1155 KdbpPrint("<%08x>\n", Address
);
1159 if (KdbOutputAborted
) break;
1164 if (KdbpInNmiOrDoubleFaultHandler(Address
))
1166 if ((GotNextFrame
= KdbpTrapFrameFromPrevTss(&TrapFrame
)))
1168 Address
= TrapFrame
.Eip
;
1169 Frame
= TrapFrame
.Ebp
;
1171 if (!KdbSymPrintAddress((PVOID
)Address
, &TrapFrame
))
1172 KdbpPrint("<%08x>\n", Address
);
1180 KdbpPrint("Couldn't access memory at 0x%p!\n", Frame
);
1188 /*!\brief Continues execution of the system/leaves KDB.
1195 /* Exit the main loop */
1199 /*!\brief Continues execution of the system/leaves KDB.
1210 Count
= strtoul(Argv
[1], NULL
, 0);
1213 KdbpPrint("%s: Integer argument required\n", Argv
[0]);
1218 if (Argv
[0][0] == 'n')
1219 KdbSingleStepOver
= TRUE
;
1221 KdbSingleStepOver
= FALSE
;
1223 /* Set the number of single steps and return to the interrupted code. */
1224 KdbNumSingleSteps
= Count
;
1229 /*!\brief Lists breakpoints.
1232 KdbpCmdBreakPointList(
1237 ULONG_PTR Address
= 0;
1238 KDB_BREAKPOINT_TYPE Type
= 0;
1239 KDB_ACCESS_TYPE AccessType
= 0;
1242 BOOLEAN Enabled
= FALSE
;
1243 BOOLEAN Global
= FALSE
;
1244 PEPROCESS Process
= NULL
;
1245 PCHAR str1
, str2
, ConditionExpr
, GlobalOrLocal
;
1248 l
= KdbpGetNextBreakPointNr(0);
1251 KdbpPrint("No breakpoints.\n");
1255 KdbpPrint("Breakpoints:\n");
1258 if (!KdbpGetBreakPointInfo(l
, &Address
, &Type
, &Size
, &AccessType
, &DebugReg
,
1259 &Enabled
, &Global
, &Process
, &ConditionExpr
))
1264 if (l
== KdbLastBreakPointNr
)
1277 GlobalOrLocal
= " global";
1281 GlobalOrLocal
= Buffer
;
1282 sprintf(Buffer
, " PID 0x%08lx",
1283 (ULONG
)(Process
? Process
->UniqueProcessId
: INVALID_HANDLE_VALUE
));
1286 if (Type
== KdbBreakPointSoftware
|| Type
== KdbBreakPointTemporary
)
1288 KdbpPrint(" %s%03d BPX 0x%08x%s%s%s%s%s\n",
1290 Enabled
? "" : " disabled",
1292 ConditionExpr
? " IF " : "",
1293 ConditionExpr
? ConditionExpr
: "",
1296 else if (Type
== KdbBreakPointHardware
)
1300 KdbpPrint(" %s%03d BPM 0x%08x %-5s %-5s disabled%s%s%s%s\n", str1
, l
, Address
,
1301 KDB_ACCESS_TYPE_TO_STRING(AccessType
),
1302 Size
== 1 ? "byte" : (Size
== 2 ? "word" : "dword"),
1304 ConditionExpr
? " IF " : "",
1305 ConditionExpr
? ConditionExpr
: "",
1310 KdbpPrint(" %s%03d BPM 0x%08x %-5s %-5s DR%d%s%s%s%s\n", str1
, l
, Address
,
1311 KDB_ACCESS_TYPE_TO_STRING(AccessType
),
1312 Size
== 1 ? "byte" : (Size
== 2 ? "word" : "dword"),
1315 ConditionExpr
? " IF " : "",
1316 ConditionExpr
? ConditionExpr
: "",
1321 while ((l
= KdbpGetNextBreakPointNr(l
+1)) >= 0);
1326 /*!\brief Enables, disables or clears a breakpoint.
1329 KdbpCmdEnableDisableClearBreakPoint(
1338 KdbpPrint("%s: argument required\n", Argv
[0]);
1343 BreakPointNr
= strtoul(Argv
[1], &pend
, 0);
1344 if (pend
== Argv
[1] || *pend
!= '\0')
1346 KdbpPrint("%s: integer argument required\n", Argv
[0]);
1350 if (Argv
[0][1] == 'e') /* enable */
1352 KdbpEnableBreakPoint(BreakPointNr
, NULL
);
1354 else if (Argv
[0][1] == 'd') /* disable */
1356 KdbpDisableBreakPoint(BreakPointNr
, NULL
);
1360 ASSERT(Argv
[0][1] == 'c');
1361 KdbpDeleteBreakPoint(BreakPointNr
, NULL
);
1367 /*!\brief Sets a software or hardware (memory) breakpoint at the given address.
1370 KdbpCmdBreakPoint(ULONG Argc
, PCHAR Argv
[])
1372 ULONGLONG Result
= 0;
1374 KDB_BREAKPOINT_TYPE Type
;
1376 KDB_ACCESS_TYPE AccessType
= 0;
1377 ULONG AddressArgIndex
, i
;
1378 LONG ConditionArgIndex
;
1379 BOOLEAN Global
= TRUE
;
1381 if (Argv
[0][2] == 'x') /* software breakpoint */
1385 KdbpPrint("bpx: Address argument required.\n");
1389 AddressArgIndex
= 1;
1390 Type
= KdbBreakPointSoftware
;
1392 else /* memory breakpoint */
1394 ASSERT(Argv
[0][2] == 'm');
1398 KdbpPrint("bpm: Access type argument required (one of r, w, rw, x)\n");
1402 if (_stricmp(Argv
[1], "x") == 0)
1403 AccessType
= KdbAccessExec
;
1404 else if (_stricmp(Argv
[1], "r") == 0)
1405 AccessType
= KdbAccessRead
;
1406 else if (_stricmp(Argv
[1], "w") == 0)
1407 AccessType
= KdbAccessWrite
;
1408 else if (_stricmp(Argv
[1], "rw") == 0)
1409 AccessType
= KdbAccessReadWrite
;
1412 KdbpPrint("bpm: Unknown access type '%s'\n", Argv
[1]);
1418 KdbpPrint("bpm: %s argument required.\n", AccessType
== KdbAccessExec
? "Address" : "Memory size");
1422 AddressArgIndex
= 3;
1423 if (_stricmp(Argv
[2], "byte") == 0)
1425 else if (_stricmp(Argv
[2], "word") == 0)
1427 else if (_stricmp(Argv
[2], "dword") == 0)
1429 else if (AccessType
== KdbAccessExec
)
1436 KdbpPrint("bpm: Unknown memory size '%s'\n", Argv
[2]);
1440 if (Argc
<= AddressArgIndex
)
1442 KdbpPrint("bpm: Address argument required.\n");
1446 Type
= KdbBreakPointHardware
;
1449 /* Put the arguments back together */
1450 ConditionArgIndex
= -1;
1451 for (i
= AddressArgIndex
; i
< (Argc
-1); i
++)
1453 if (strcmp(Argv
[i
+1], "IF") == 0) /* IF found */
1455 ConditionArgIndex
= i
+ 2;
1456 if ((ULONG
)ConditionArgIndex
>= Argc
)
1458 KdbpPrint("%s: IF requires condition expression.\n", Argv
[0]);
1462 for (i
= ConditionArgIndex
; i
< (Argc
-1); i
++)
1463 Argv
[i
][strlen(Argv
[i
])] = ' ';
1468 Argv
[i
][strlen(Argv
[i
])] = ' ';
1471 /* Evaluate the address expression */
1472 if (!KdbpEvaluateExpression(Argv
[AddressArgIndex
],
1473 sizeof("kdb:> ")-1 + (Argv
[AddressArgIndex
]-Argv
[0]),
1479 if (Result
> (ULONGLONG
)(~((ULONG_PTR
)0)))
1480 KdbpPrint("%s: Warning: Address %I64x is beeing truncated\n", Argv
[0],Result
);
1482 Address
= (ULONG_PTR
)Result
;
1484 KdbpInsertBreakPoint(Address
, Type
, Size
, AccessType
,
1485 (ConditionArgIndex
< 0) ? NULL
: Argv
[ConditionArgIndex
],
1491 /*!\brief Lists threads or switches to another thread context.
1499 PETHREAD Thread
= NULL
;
1500 PEPROCESS Process
= NULL
;
1501 BOOLEAN ReferencedThread
= FALSE
, ReferencedProcess
= FALSE
;
1506 PCHAR State
, pend
, str1
, str2
;
1507 static const PCHAR ThreadStateToString
[DeferredReady
+1] =
1509 "Initialized", "Ready", "Running",
1510 "Standby", "Terminated", "Waiting",
1511 "Transition", "DeferredReady"
1514 ASSERT(KdbCurrentProcess
);
1516 if (Argc
>= 2 && _stricmp(Argv
[1], "list") == 0)
1518 Process
= KdbCurrentProcess
;
1522 ul
= strtoul(Argv
[2], &pend
, 0);
1523 if (Argv
[2] == pend
)
1525 KdbpPrint("thread: '%s' is not a valid process id!\n", Argv
[2]);
1529 if (!NT_SUCCESS(PsLookupProcessByProcessId((PVOID
)ul
, &Process
)))
1531 KdbpPrint("thread: Invalid process id!\n");
1535 /* Remember our reference */
1536 ReferencedProcess
= TRUE
;
1539 Entry
= Process
->ThreadListHead
.Flink
;
1540 if (Entry
== &Process
->ThreadListHead
)
1543 KdbpPrint("No threads in process 0x%08x!\n", ul
);
1545 KdbpPrint("No threads in current process!\n");
1547 if (ReferencedProcess
)
1548 ObDereferenceObject(Process
);
1553 KdbpPrint(" TID State Prior. Affinity EBP EIP\n");
1556 Thread
= CONTAINING_RECORD(Entry
, ETHREAD
, ThreadListEntry
);
1558 if (Thread
== KdbCurrentThread
)
1569 if (!Thread
->Tcb
.InitialStack
)
1571 /* Thread has no kernel stack (probably terminated) */
1575 else if (Thread
->Tcb
.TrapFrame
)
1577 if (Thread
->Tcb
.TrapFrame
->PreviousPreviousMode
== KernelMode
)
1578 Esp
= (PULONG
)Thread
->Tcb
.TrapFrame
->TempEsp
;
1580 Esp
= (PULONG
)Thread
->Tcb
.TrapFrame
->HardwareEsp
;
1582 Ebp
= (PULONG
)Thread
->Tcb
.TrapFrame
->Ebp
;
1583 Eip
= Thread
->Tcb
.TrapFrame
->Eip
;
1587 Esp
= (PULONG
)Thread
->Tcb
.KernelStack
;
1588 Ebp
= (PULONG
)Esp
[4];
1591 if (Ebp
) /* FIXME: Should we attach to the process to read Ebp[1]? */
1592 KdbpSafeReadMemory(&Eip
, Ebp
+ 1, sizeof (Eip
));
1595 if (Thread
->Tcb
.State
< (DeferredReady
+ 1))
1596 State
= ThreadStateToString
[Thread
->Tcb
.State
];
1600 KdbpPrint(" %s0x%08x %-11s %3d 0x%08x 0x%08x 0x%08x%s\n",
1602 Thread
->Cid
.UniqueThread
,
1604 Thread
->Tcb
.Priority
,
1605 Thread
->Tcb
.Affinity
,
1610 Entry
= Entry
->Flink
;
1612 while (Entry
!= &Process
->ThreadListHead
);
1614 /* Release our reference, if any */
1615 if (ReferencedProcess
)
1616 ObDereferenceObject(Process
);
1618 else if (Argc
>= 2 && _stricmp(Argv
[1], "attach") == 0)
1622 KdbpPrint("thread attach: thread id argument required!\n");
1626 ul
= strtoul(Argv
[2], &pend
, 0);
1627 if (Argv
[2] == pend
)
1629 KdbpPrint("thread attach: '%s' is not a valid thread id!\n", Argv
[2]);
1633 if (!KdbpAttachToThread((PVOID
)ul
))
1638 KdbpPrint("Attached to thread 0x%08x.\n", ul
);
1642 Thread
= KdbCurrentThread
;
1646 ul
= strtoul(Argv
[1], &pend
, 0);
1647 if (Argv
[1] == pend
)
1649 KdbpPrint("thread: '%s' is not a valid thread id!\n", Argv
[1]);
1653 if (!NT_SUCCESS(PsLookupThreadByThreadId((PVOID
)ul
, &Thread
)))
1655 KdbpPrint("thread: Invalid thread id!\n");
1659 /* Remember our reference */
1660 ReferencedThread
= TRUE
;
1663 if (Thread
->Tcb
.State
< (DeferredReady
+ 1))
1664 State
= ThreadStateToString
[Thread
->Tcb
.State
];
1670 " State: %s (0x%x)\n"
1672 " Affinity: 0x%08x\n"
1673 " Initial Stack: 0x%08x\n"
1674 " Stack Limit: 0x%08x\n"
1675 " Stack Base: 0x%08x\n"
1676 " Kernel Stack: 0x%08x\n"
1677 " Trap Frame: 0x%08x\n"
1678 " NPX State: %s (0x%x)\n",
1679 (Argc
< 2) ? "Current Thread:\n" : "",
1680 Thread
->Cid
.UniqueThread
,
1681 State
, Thread
->Tcb
.State
,
1682 Thread
->Tcb
.Priority
,
1683 Thread
->Tcb
.Affinity
,
1684 Thread
->Tcb
.InitialStack
,
1685 Thread
->Tcb
.StackLimit
,
1686 Thread
->Tcb
.StackBase
,
1687 Thread
->Tcb
.KernelStack
,
1688 Thread
->Tcb
.TrapFrame
,
1689 NPX_STATE_TO_STRING(Thread
->Tcb
.NpxState
), Thread
->Tcb
.NpxState
);
1691 /* Release our reference if we had one */
1692 if (ReferencedThread
)
1693 ObDereferenceObject(Thread
);
1699 /*!\brief Lists processes or switches to another process context.
1708 BOOLEAN ReferencedProcess
= FALSE
;
1709 PCHAR State
, pend
, str1
, str2
;
1711 extern LIST_ENTRY PsActiveProcessHead
;
1713 if (Argc
>= 2 && _stricmp(Argv
[1], "list") == 0)
1715 Entry
= PsActiveProcessHead
.Flink
;
1716 if (!Entry
|| Entry
== &PsActiveProcessHead
)
1718 KdbpPrint("No processes in the system!\n");
1722 KdbpPrint(" PID State Filename\n");
1725 Process
= CONTAINING_RECORD(Entry
, EPROCESS
, ActiveProcessLinks
);
1727 if (Process
== KdbCurrentProcess
)
1738 State
= ((Process
->Pcb
.State
== ProcessInMemory
) ? "In Memory" :
1739 ((Process
->Pcb
.State
== ProcessOutOfMemory
) ? "Out of Memory" : "In Transition"));
1741 KdbpPrint(" %s0x%08x %-10s %s%s\n",
1743 Process
->UniqueProcessId
,
1745 Process
->ImageFileName
,
1748 Entry
= Entry
->Flink
;
1750 while(Entry
!= &PsActiveProcessHead
);
1752 else if (Argc
>= 2 && _stricmp(Argv
[1], "attach") == 0)
1756 KdbpPrint("process attach: process id argument required!\n");
1760 ul
= strtoul(Argv
[2], &pend
, 0);
1761 if (Argv
[2] == pend
)
1763 KdbpPrint("process attach: '%s' is not a valid process id!\n", Argv
[2]);
1767 if (!KdbpAttachToProcess((PVOID
)ul
))
1772 KdbpPrint("Attached to process 0x%08x, thread 0x%08x.\n", (ULONG
)ul
,
1773 (ULONG
)KdbCurrentThread
->Cid
.UniqueThread
);
1777 Process
= KdbCurrentProcess
;
1781 ul
= strtoul(Argv
[1], &pend
, 0);
1782 if (Argv
[1] == pend
)
1784 KdbpPrint("proc: '%s' is not a valid process id!\n", Argv
[1]);
1788 if (!NT_SUCCESS(PsLookupProcessByProcessId((PVOID
)ul
, &Process
)))
1790 KdbpPrint("proc: Invalid process id!\n");
1794 /* Remember our reference */
1795 ReferencedProcess
= TRUE
;
1798 State
= ((Process
->Pcb
.State
== ProcessInMemory
) ? "In Memory" :
1799 ((Process
->Pcb
.State
== ProcessOutOfMemory
) ? "Out of Memory" : "In Transition"));
1802 " State: %s (0x%x)\n"
1803 " Image Filename: %s\n",
1804 (Argc
< 2) ? "Current process:\n" : "",
1805 Process
->UniqueProcessId
,
1806 State
, Process
->Pcb
.State
,
1807 Process
->ImageFileName
);
1809 /* Release our reference, if any */
1810 if (ReferencedProcess
)
1811 ObDereferenceObject(Process
);
1817 /*!\brief Lists loaded modules or the one containing the specified address.
1824 ULONGLONG Result
= 0;
1826 PLDR_DATA_TABLE_ENTRY LdrEntry
;
1827 BOOLEAN DisplayOnlyOneModule
= FALSE
;
1832 /* Put the arguments back together */
1835 Argv
[Argc
][strlen(Argv
[Argc
])] = ' ';
1837 /* Evaluate the expression */
1838 if (!KdbpEvaluateExpression(Argv
[1], sizeof("kdb:> ")-1 + (Argv
[1]-Argv
[0]), &Result
))
1843 if (Result
> (ULONGLONG
)(~((ULONG_PTR
)0)))
1844 KdbpPrint("%s: Warning: Address %I64x is beeing truncated\n", Argv
[0],Result
);
1846 Address
= (ULONG_PTR
)Result
;
1848 if (!KdbpSymFindModule((PVOID
)Address
, NULL
, -1, &LdrEntry
))
1850 KdbpPrint("No module containing address 0x%p found!\n", Address
);
1854 DisplayOnlyOneModule
= TRUE
;
1858 if (!KdbpSymFindModule(NULL
, NULL
, 0, &LdrEntry
))
1860 ULONG_PTR ntoskrnlBase
= ((ULONG_PTR
)KdbpCmdMod
) & 0xfff00000;
1861 KdbpPrint(" Base Size Name\n");
1862 KdbpPrint(" %08x %08x %s\n", ntoskrnlBase
, 0, "ntoskrnl.exe");
1869 KdbpPrint(" Base Size Name\n");
1872 KdbpPrint(" %08x %08x %wZ\n", LdrEntry
->DllBase
, LdrEntry
->SizeOfImage
, &LdrEntry
->BaseDllName
);
1874 if(DisplayOnlyOneModule
|| !KdbpSymFindModule(NULL
, NULL
, i
++, &LdrEntry
))
1881 /*!\brief Displays GDT, LDT or IDTd.
1898 if (Argv
[0][0] == 'i')
1905 KdbpPrint("Interrupt descriptor table is empty.\n");
1909 KdbpPrint("IDT Base: 0x%08x Limit: 0x%04x\n", Reg
.Base
, Reg
.Limit
);
1910 KdbpPrint(" Idx Type Seg. Sel. Offset DPL\n");
1912 for (i
= 0; (i
+ sizeof(SegDesc
) - 1) <= Reg
.Limit
; i
+= 8)
1914 if (!NT_SUCCESS(KdbpSafeReadMemory(SegDesc
, (PVOID
)(Reg
.Base
+ i
), sizeof(SegDesc
))))
1916 KdbpPrint("Couldn't access memory at 0x%08x!\n", Reg
.Base
+ i
);
1920 Dpl
= ((SegDesc
[1] >> 13) & 3);
1921 if ((SegDesc
[1] & 0x1f00) == 0x0500) /* Task gate */
1922 SegType
= "TASKGATE";
1923 else if ((SegDesc
[1] & 0x1fe0) == 0x0e00) /* 32 bit Interrupt gate */
1924 SegType
= "INTGATE32";
1925 else if ((SegDesc
[1] & 0x1fe0) == 0x0600) /* 16 bit Interrupt gate */
1926 SegType
= "INTGATE16";
1927 else if ((SegDesc
[1] & 0x1fe0) == 0x0f00) /* 32 bit Trap gate */
1928 SegType
= "TRAPGATE32";
1929 else if ((SegDesc
[1] & 0x1fe0) == 0x0700) /* 16 bit Trap gate */
1930 SegType
= "TRAPGATE16";
1932 SegType
= "UNKNOWN";
1934 if ((SegDesc
[1] & (1 << 15)) == 0) /* not present */
1936 KdbpPrint(" %03d %-10s [NP] [NP] %02d\n",
1937 i
/ 8, SegType
, Dpl
);
1939 else if ((SegDesc
[1] & 0x1f00) == 0x0500) /* Task gate */
1941 SegSel
= SegDesc
[0] >> 16;
1942 KdbpPrint(" %03d %-10s 0x%04x %02d\n",
1943 i
/ 8, SegType
, SegSel
, Dpl
);
1947 SegSel
= SegDesc
[0] >> 16;
1948 SegBase
= (SegDesc
[1] & 0xffff0000) | (SegDesc
[0] & 0x0000ffff);
1949 KdbpPrint(" %03d %-10s 0x%04x 0x%08x %02d\n",
1950 i
/ 8, SegType
, SegSel
, SegBase
, Dpl
);
1958 if (Argv
[0][0] == 'g')
1961 Ke386GetGlobalDescriptorTable(&Reg
.Limit
);
1966 ASSERT(Argv
[0][0] == 'l');
1969 Reg
.Limit
= Ke386GetLocalDescriptorTable();
1977 KdbpPrint("%s descriptor table is empty.\n",
1978 Argv
[0][0] == 'g' ? "Global" : "Local");
1982 KdbpPrint("%cDT Base: 0x%08x Limit: 0x%04x\n",
1983 Argv
[0][0] == 'g' ? 'G' : 'L', Reg
.Base
, Reg
.Limit
);
1984 KdbpPrint(" Idx Sel. Type Base Limit DPL Attribs\n");
1986 for (; (i
+ sizeof(SegDesc
) - 1) <= Reg
.Limit
; i
+= 8)
1988 if (!NT_SUCCESS(KdbpSafeReadMemory(SegDesc
, (PVOID
)(Reg
.Base
+ i
), sizeof(SegDesc
))))
1990 KdbpPrint("Couldn't access memory at 0x%08x!\n", Reg
.Base
+ i
);
1994 Dpl
= ((SegDesc
[1] >> 13) & 3);
1995 Type
= ((SegDesc
[1] >> 8) & 0xf);
1997 SegBase
= SegDesc
[0] >> 16;
1998 SegBase
|= (SegDesc
[1] & 0xff) << 16;
1999 SegBase
|= SegDesc
[1] & 0xff000000;
2000 SegLimit
= SegDesc
[0] & 0x0000ffff;
2001 SegLimit
|= (SegDesc
[1] >> 16) & 0xf;
2003 if ((SegDesc
[1] & (1 << 23)) != 0)
2013 if ((SegDesc
[1] & (1 << 12)) == 0) /* System segment */
2017 case 1: SegType
= "TSS16(Avl)"; break;
2018 case 2: SegType
= "LDT"; break;
2019 case 3: SegType
= "TSS16(Busy)"; break;
2020 case 4: SegType
= "CALLGATE16"; break;
2021 case 5: SegType
= "TASKGATE"; break;
2022 case 6: SegType
= "INTGATE16"; break;
2023 case 7: SegType
= "TRAPGATE16"; break;
2024 case 9: SegType
= "TSS32(Avl)"; break;
2025 case 11: SegType
= "TSS32(Busy)"; break;
2026 case 12: SegType
= "CALLGATE32"; break;
2027 case 14: SegType
= "INTGATE32"; break;
2028 case 15: SegType
= "INTGATE32"; break;
2029 default: SegType
= "UNKNOWN"; break;
2032 if (!(Type
>= 1 && Type
<= 3) &&
2033 Type
!= 9 && Type
!= 11)
2039 else if ((SegDesc
[1] & (1 << 11)) == 0) /* Data segment */
2041 if ((SegDesc
[1] & (1 << 22)) != 0)
2046 else /* Code segment */
2048 if ((SegDesc
[1] & (1 << 22)) != 0)
2054 if ((SegDesc
[1] & (1 << 15)) == 0) /* not present */
2056 KdbpPrint(" %03d 0x%04x %-11s [NP] [NP] %02d NP\n",
2057 i
/ 8, i
| Dpl
| ul
, SegType
, Dpl
);
2061 KdbpPrint(" %03d 0x%04x %-11s 0x%08x 0x%08x %02d ",
2062 i
/ 8, i
| Dpl
| ul
, SegType
, SegBase
, SegLimit
, Dpl
);
2064 if ((SegDesc
[1] & (1 << 12)) == 0) /* System segment */
2066 /* FIXME: Display system segment */
2068 else if ((SegDesc
[1] & (1 << 11)) == 0) /* Data segment */
2070 if ((SegDesc
[1] & (1 << 10)) != 0) /* Expand-down */
2073 KdbpPrint((SegDesc
[1] & (1 << 9)) ? " R/W" : " R");
2075 if ((SegDesc
[1] & (1 << 8)) != 0)
2078 else /* Code segment */
2080 if ((SegDesc
[1] & (1 << 10)) != 0) /* Conforming */
2083 KdbpPrint((SegDesc
[1] & (1 << 9)) ? " R/X" : " X");
2085 if ((SegDesc
[1] & (1 << 8)) != 0)
2089 if ((SegDesc
[1] & (1 << 20)) != 0)
2100 /*!\brief Displays the KPCR
2107 PKIPCR Pcr
= (PKIPCR
)KeGetPcr();
2109 KdbpPrint("Current PCR is at 0x%08x.\n", (INT
)Pcr
);
2110 KdbpPrint(" Tib.ExceptionList: 0x%08x\n"
2111 " Tib.StackBase: 0x%08x\n"
2112 " Tib.StackLimit: 0x%08x\n"
2113 " Tib.SubSystemTib: 0x%08x\n"
2114 " Tib.FiberData/Version: 0x%08x\n"
2115 " Tib.ArbitraryUserPointer: 0x%08x\n"
2116 " Tib.Self: 0x%08x\n"
2117 " SelfPcr: 0x%08x\n"
2121 " IrrActive: 0x%08x\n"
2123 " KdVersionBlock: 0x%08x\n"
2127 " MajorVersion: 0x%04x\n"
2128 " MinorVersion: 0x%04x\n"
2129 " SetMember: 0x%08x\n"
2130 " StallScaleFactor: 0x%08x\n"
2132 " L2CacheAssociativity: 0x%02x\n"
2133 " VdmAlert: 0x%08x\n"
2134 " L2CacheSize: 0x%08x\n"
2135 " InterruptMode: 0x%08x\n",
2136 Pcr
->NtTib
.ExceptionList
, Pcr
->NtTib
.StackBase
, Pcr
->NtTib
.StackLimit
,
2137 Pcr
->NtTib
.SubSystemTib
, Pcr
->NtTib
.FiberData
, Pcr
->NtTib
.ArbitraryUserPointer
,
2138 Pcr
->NtTib
.Self
, Pcr
->SelfPcr
, Pcr
->Prcb
, Pcr
->Irql
, Pcr
->IRR
, Pcr
->IrrActive
,
2139 Pcr
->IDR
, Pcr
->KdVersionBlock
, Pcr
->IDT
, Pcr
->GDT
, Pcr
->TSS
,
2140 Pcr
->MajorVersion
, Pcr
->MinorVersion
, Pcr
->SetMember
, Pcr
->StallScaleFactor
,
2141 Pcr
->Number
, Pcr
->SecondLevelCacheAssociativity
,
2142 Pcr
->VdmAlert
, Pcr
->SecondLevelCacheSize
, Pcr
->InterruptMode
);
2147 /*!\brief Displays the TSS
2154 KTSS
*Tss
= KeGetPcr()->TSS
;
2156 KdbpPrint("Current TSS is at 0x%08x.\n", (INT
)Tss
);
2157 KdbpPrint(" Eip: 0x%08x\n"
2164 " IoMapBase: 0x%04x\n",
2165 Tss
->Eip
, Tss
->Es
, Tss
->Cs
, Tss
->Ds
, Tss
->Fs
, Tss
->Gs
, Tss
->IoMapBase
);
2170 /*!\brief Bugchecks the system.
2177 /* Set the flag and quit looping */
2178 KdbpBugCheckRequested
= TRUE
;
2188 /* Reboot immediately (we do not return) */
2189 HalReturnToFirmware(HalRebootRoutine
);
2197 IN ULONG BufLength
);
2199 /*!\brief Display debug messages on screen, with paging.
2201 * Keys for per-page view: Home, End, PageUp, Arrow Up, PageDown,
2202 * all others are as PageDown.
2211 KdbpIsInDmesgMode
= TRUE
; /* Toggle logging flag */
2212 if (!KdpDmesgBuffer
)
2214 KdbpPrint("Dmesg: error, buffer is not allocated! /DEBUGPORT=SCREEN kernel param required for dmesg.\n");
2218 KdbpPrint("*** Dmesg *** TotalWritten=%lu, BufferSize=%lu, CurrentPosition=%lu\n",
2219 KdbDmesgTotalWritten
, KdpDmesgBufferSize
, KdpDmesgCurrentPosition
);
2221 // Pass data to the pager:
2222 end
= KdpDmesgCurrentPosition
;
2223 beg
= (end
+ KdpDmesgFreeBytes
) % KdpDmesgBufferSize
;
2225 // no roll-overs, and overwritten=lost bytes
2226 if (KdbDmesgTotalWritten
<= KdpDmesgBufferSize
)
2228 // show buffer (KdpDmesgBuffer + beg, num)
2229 KdbpPager(KdpDmesgBuffer
, KdpDmesgCurrentPosition
);
2233 // show 2 buffers: (KdpDmesgBuffer + beg, KdpDmesgBufferSize - beg)
2234 // and: (KdpDmesgBuffer, end)
2235 KdbpPager(KdpDmesgBuffer
+ beg
, KdpDmesgBufferSize
- beg
);
2236 KdbpPrint("*** Dmesg: buffer rollup ***\n");
2237 KdbpPager(KdpDmesgBuffer
, end
);
2239 KdbpPrint("*** Dmesg: end of output ***\n");
2241 KdbpIsInDmesgMode
= FALSE
; /* Toggle logging flag */
2246 /*!\brief Sets or displays a config variables value.
2256 KDB_ENTER_CONDITION ConditionFirst
= KdbDoNotEnter
;
2257 KDB_ENTER_CONDITION ConditionLast
= KdbDoNotEnter
;
2259 static const PCHAR ExceptionNames
[21] =
2261 "ZERODEVIDE", "DEBUGTRAP", "NMI", "INT3", "OVERFLOW", "BOUND", "INVALIDOP",
2262 "NOMATHCOP", "DOUBLEFAULT", "RESERVED(9)", "INVALIDTSS", "SEGMENTNOTPRESENT",
2263 "STACKFAULT", "GPF", "PAGEFAULT", "RESERVED(15)", "MATHFAULT", "ALIGNMENTCHECK",
2264 "MACHINECHECK", "SIMDFAULT", "OTHERS"
2269 KdbpPrint("Available settings:\n");
2270 KdbpPrint(" syntax [intel|at&t]\n");
2271 KdbpPrint(" condition [exception|*] [first|last] [never|always|kmode|umode]\n");
2272 KdbpPrint(" break_on_module_load [true|false]\n");
2274 else if (strcmp(Argv
[1], "syntax") == 0)
2278 KdbpPrint("syntax = %s\n", KdbUseIntelSyntax
? "intel" : "at&t");
2282 if (_stricmp(Argv
[2], "intel") == 0)
2283 KdbUseIntelSyntax
= TRUE
;
2284 else if (_stricmp(Argv
[2], "at&t") == 0)
2285 KdbUseIntelSyntax
= FALSE
;
2287 KdbpPrint("Unknown syntax '%s'.\n", Argv
[2]);
2290 else if (strcmp(Argv
[1], "condition") == 0)
2294 KdbpPrint("Conditions: (First) (Last)\n");
2295 for (l
= 0; l
< RTL_NUMBER_OF(ExceptionNames
) - 1; l
++)
2297 if (!ExceptionNames
[l
])
2300 if (!KdbpGetEnterCondition(l
, TRUE
, &ConditionFirst
))
2303 if (!KdbpGetEnterCondition(l
, FALSE
, &ConditionLast
))
2306 KdbpPrint(" #%02d %-20s %-8s %-8s\n", l
, ExceptionNames
[l
],
2307 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst
),
2308 KDB_ENTER_CONDITION_TO_STRING(ConditionLast
));
2311 ASSERT(l
== (RTL_NUMBER_OF(ExceptionNames
) - 1));
2312 KdbpPrint(" %-20s %-8s %-8s\n", ExceptionNames
[l
],
2313 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst
),
2314 KDB_ENTER_CONDITION_TO_STRING(ConditionLast
));
2318 if (Argc
>= 5 && strcmp(Argv
[2], "*") == 0) /* Allow * only when setting condition */
2324 l
= strtoul(Argv
[2], &pend
, 0);
2326 if (Argv
[2] == pend
)
2328 for (l
= 0; l
< RTL_NUMBER_OF(ExceptionNames
); l
++)
2330 if (!ExceptionNames
[l
])
2333 if (_stricmp(ExceptionNames
[l
], Argv
[2]) == 0)
2338 if (l
>= RTL_NUMBER_OF(ExceptionNames
))
2340 KdbpPrint("Unknown exception '%s'.\n", Argv
[2]);
2347 if (_stricmp(Argv
[3], "first") == 0)
2349 else if (_stricmp(Argv
[3], "last") == 0)
2353 KdbpPrint("set condition: second argument must be 'first' or 'last'\n");
2357 if (_stricmp(Argv
[4], "never") == 0)
2358 ConditionFirst
= KdbDoNotEnter
;
2359 else if (_stricmp(Argv
[4], "always") == 0)
2360 ConditionFirst
= KdbEnterAlways
;
2361 else if (_stricmp(Argv
[4], "umode") == 0)
2362 ConditionFirst
= KdbEnterFromUmode
;
2363 else if (_stricmp(Argv
[4], "kmode") == 0)
2364 ConditionFirst
= KdbEnterFromKmode
;
2367 KdbpPrint("set condition: third argument must be 'never', 'always', 'umode' or 'kmode'\n");
2371 if (!KdbpSetEnterCondition(l
, First
, ConditionFirst
))
2374 KdbpPrint("Couldn't change condition for exception #%02d\n", l
);
2376 KdbpPrint("Couldn't change condition for all exceptions\n", l
);
2379 else /* Argc >= 3 */
2381 if (!KdbpGetEnterCondition(l
, TRUE
, &ConditionFirst
))
2384 if (!KdbpGetEnterCondition(l
, FALSE
, &ConditionLast
))
2387 if (l
< (RTL_NUMBER_OF(ExceptionNames
) - 1))
2389 KdbpPrint("Condition for exception #%02d (%s): FirstChance %s LastChance %s\n",
2390 l
, ExceptionNames
[l
],
2391 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst
),
2392 KDB_ENTER_CONDITION_TO_STRING(ConditionLast
));
2396 KdbpPrint("Condition for all other exceptions: FirstChance %s LastChance %s\n",
2397 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst
),
2398 KDB_ENTER_CONDITION_TO_STRING(ConditionLast
));
2403 else if (strcmp(Argv
[1], "break_on_module_load") == 0)
2406 KdbpPrint("break_on_module_load = %s\n", KdbBreakOnModuleLoad
? "enabled" : "disabled");
2409 if (_stricmp(Argv
[2], "enable") == 0 || _stricmp(Argv
[2], "enabled") == 0 || _stricmp(Argv
[2], "true") == 0)
2410 KdbBreakOnModuleLoad
= TRUE
;
2411 else if (_stricmp(Argv
[2], "disable") == 0 || _stricmp(Argv
[2], "disabled") == 0 || _stricmp(Argv
[2], "false") == 0)
2412 KdbBreakOnModuleLoad
= FALSE
;
2414 KdbpPrint("Unknown setting '%s'.\n", Argv
[2]);
2419 KdbpPrint("Unknown setting '%s'.\n", Argv
[1]);
2425 /*!\brief Displays help screen.
2434 KdbpPrint("Kernel debugger commands:\n");
2435 for (i
= 0; i
< RTL_NUMBER_OF(KdbDebuggerCommands
); i
++)
2437 if (!KdbDebuggerCommands
[i
].Syntax
) /* Command group */
2442 KdbpPrint("\x1b[7m* %s:\x1b[0m\n", KdbDebuggerCommands
[i
].Help
);
2446 KdbpPrint(" %-20s - %s\n",
2447 KdbDebuggerCommands
[i
].Syntax
,
2448 KdbDebuggerCommands
[i
].Help
);
2454 /*!\brief Prints the given string with printf-like formatting.
2456 * \param Format Format of the string/arguments.
2457 * \param ... Variable number of arguments matching the format specified in \a Format.
2459 * \note Doesn't correctly handle \\t and terminal escape sequences when calculating the
2460 * number of lines required to print a single line from the Buffer in the terminal.
2461 * Prints maximum 4096 chars, because of its buffer size.
2468 static CHAR Buffer
[4096];
2469 static BOOLEAN TerminalInitialized
= FALSE
;
2470 static BOOLEAN TerminalConnected
= FALSE
;
2471 static BOOLEAN TerminalReportsSize
= TRUE
;
2476 LONG RowsPrintedByTerminal
;
2480 /* Check if the user has aborted output of the current command */
2481 if (KdbOutputAborted
)
2484 /* Initialize the terminal */
2485 if (!TerminalInitialized
)
2487 DbgPrint("\x1b[7h"); /* Enable linewrap */
2489 /* Query terminal type */
2490 /*DbgPrint("\x1b[Z");*/
2493 TerminalInitialized
= TRUE
;
2495 KeStallExecutionProcessor(100000);
2499 c
= KdbpTryGetCharSerial(5000);
2503 Buffer
[Length
++] = c
;
2504 if (Length
>= (sizeof (Buffer
) - 1))
2508 Buffer
[Length
] = '\0';
2510 TerminalConnected
= TRUE
;
2513 /* Get number of rows and columns in terminal */
2514 if ((KdbNumberOfRowsTerminal
< 0) || (KdbNumberOfColsTerminal
< 0) ||
2515 (KdbNumberOfRowsPrinted
) == 0) /* Refresh terminal size each time when number of rows printed is 0 */
2517 if ((KdbDebugState
& KD_DEBUG_KDSERIAL
) && TerminalConnected
&& TerminalReportsSize
)
2519 /* Try to query number of rows from terminal. A reply looks like "\x1b[8;24;80t" */
2520 TerminalReportsSize
= FALSE
;
2521 KeStallExecutionProcessor(100000);
2522 DbgPrint("\x1b[18t");
2523 c
= KdbpTryGetCharSerial(5000);
2527 c
= KdbpTryGetCharSerial(5000);
2534 c
= KdbpTryGetCharSerial(5000);
2538 Buffer
[Length
++] = c
;
2539 if (isalpha(c
) || Length
>= (sizeof (Buffer
) - 1))
2543 Buffer
[Length
] = '\0';
2544 if (Buffer
[0] == '8' && Buffer
[1] == ';')
2546 for (i
= 2; (i
< Length
) && (Buffer
[i
] != ';'); i
++);
2548 if (Buffer
[i
] == ';')
2552 /* Number of rows is now at Buffer + 2 and number of cols at Buffer + i */
2553 KdbNumberOfRowsTerminal
= strtoul(Buffer
+ 2, NULL
, 0);
2554 KdbNumberOfColsTerminal
= strtoul(Buffer
+ i
, NULL
, 0);
2555 TerminalReportsSize
= TRUE
;
2559 /* Clear further characters */
2560 while ((c
= KdbpTryGetCharSerial(5000)) != -1);
2564 if (KdbNumberOfRowsTerminal
<= 0)
2566 /* Set number of rows to the default. */
2567 KdbNumberOfRowsTerminal
= 23; //24; //Mna.: 23 for SCREEN debugport
2569 else if (KdbNumberOfColsTerminal
<= 0)
2571 /* Set number of cols to the default. */
2572 KdbNumberOfColsTerminal
= 75; //80; //Mna.: 75 for SCREEN debugport
2576 /* Get the string */
2577 va_start(ap
, Format
);
2578 Length
= _vsnprintf(Buffer
, sizeof (Buffer
) - 1, Format
, ap
);
2579 Buffer
[Length
] = '\0';
2583 while (p
[0] != '\0')
2585 i
= strcspn(p
, "\n");
2587 /* Calculate the number of lines which will be printed in the terminal
2588 * when outputting the current line
2591 RowsPrintedByTerminal
= (i
+ KdbNumberOfColsPrinted
- 1) / KdbNumberOfColsTerminal
;
2593 RowsPrintedByTerminal
= 0;
2596 RowsPrintedByTerminal
++;
2598 /*DbgPrint("!%d!%d!%d!%d!", KdbNumberOfRowsPrinted, KdbNumberOfColsPrinted, i, RowsPrintedByTerminal);*/
2600 /* Display a prompt if we printed one screen full of text */
2601 if (KdbNumberOfRowsTerminal
> 0 &&
2602 (LONG
)(KdbNumberOfRowsPrinted
+ RowsPrintedByTerminal
) >= KdbNumberOfRowsTerminal
)
2604 KdbRepeatLastCommand
= FALSE
;
2606 if (KdbNumberOfColsPrinted
> 0)
2609 DbgPrint("--- Press q to abort, any other key to continue ---");
2610 RowsPrintedByTerminal
++; /* added by Mna. */
2612 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
2613 c
= KdbpGetCharSerial();
2615 c
= KdbpGetCharKeyboard(&ScanCode
);
2619 /* Try to read '\n' which might follow '\r' - if \n is not received here
2620 * it will be interpreted as "return" when the next command should be read.
2622 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
2623 c
= KdbpTryGetCharSerial(5);
2625 c
= KdbpTryGetCharKeyboard(&ScanCode
, 5);
2631 KdbOutputAborted
= TRUE
;
2635 KdbNumberOfRowsPrinted
= 0;
2636 KdbNumberOfColsPrinted
= 0;
2639 /* Insert a NUL after the line and print only the current line. */
2640 if (p
[i
] == '\n' && p
[i
+ 1] != '\0')
2650 /* Remove escape sequences from the line if there's no terminal connected */
2651 if (!TerminalConnected
)
2653 while ((p2
= strrchr(p
, '\x1b'))) /* Look for escape character */
2658 while (!isalpha(p2
[j
++]));
2673 /* Set p to the start of the next line and
2674 * remember the number of rows/cols printed
2680 KdbNumberOfColsPrinted
= 0;
2684 ASSERT(p
[0] == '\0');
2685 KdbNumberOfColsPrinted
+= i
;
2688 KdbNumberOfRowsPrinted
+= RowsPrintedByTerminal
;
2692 /** memrchr(), explicitly defined, since was absent in MinGW of RosBE. */
2695 * Find the last occurrence of 'c' in the buffer 's' of size 'n'.
2698 memrchr(const void *s
, int c
, size_t n
)
2700 const unsigned char *cp
;
2704 cp
= (unsigned char *)s
+ n
;
2707 if (*(--cp
) == (unsigned char)c
)
2714 /*!\brief Calculate pointer position for N lines upper of current position.
2716 * \param Buffer Characters buffer to operate on.
2717 * \param BufLength Buffer size.
2719 * \note Calculate pointer position for N lines upper of current displaying
2720 * position within the given buffer.
2722 * Used by KdbpPager().
2723 * Now N lines count is hardcoded to KdbNumberOfRowsTerminal.
2726 CountOnePageUp(PCHAR Buffer
, ULONG BufLength
, PCHAR pCurPos
)
2729 // p0 is initial guess of Page Start
2730 ULONG p0len
= KdbNumberOfRowsTerminal
* KdbNumberOfColsTerminal
;
2731 PCHAR p0
= pCurPos
- p0len
;
2732 PCHAR prev_p
= p0
, p1
;
2735 if (pCurPos
< Buffer
)
2737 ASSERT(pCurPos
<= Buffer
+ BufLength
);
2739 p
= memrchr(p0
, '\n', p0len
);
2742 for (j
= KdbNumberOfRowsTerminal
; j
--; )
2745 p1
= memrchr(p0
, '\n', p
-p0
);
2755 linesCnt
= (KdbNumberOfColsTerminal
+prev_p
-p
-2) / KdbNumberOfColsTerminal
;
2765 /*!\brief Prints the given string with, page by page.
2767 * \param Buffer Characters buffer to print.
2768 * \param BufferLen Buffer size.
2770 * \note Doesn't correctly handle \\t and terminal escape sequences when calculating the
2771 * number of lines required to print a single line from the Buffer in the terminal.
2772 * Maximum length of buffer is limited only by memory size.
2774 * Note: BufLength should be greater then (KdbNumberOfRowsTerminal * KdbNumberOfColsTerminal).
2782 static CHAR InBuffer
[4096];
2783 static BOOLEAN TerminalInitialized
= FALSE
;
2784 static BOOLEAN TerminalConnected
= FALSE
;
2785 static BOOLEAN TerminalReportsSize
= TRUE
;
2790 LONG RowsPrintedByTerminal
;
2796 /* Check if the user has aborted output of the current command */
2797 if (KdbOutputAborted
)
2800 /* Initialize the terminal */
2801 if (!TerminalInitialized
)
2803 DbgPrint("\x1b[7h"); /* Enable linewrap */
2805 /* Query terminal type */
2806 /*DbgPrint("\x1b[Z");*/
2809 TerminalInitialized
= TRUE
;
2811 KeStallExecutionProcessor(100000);
2815 c
= KdbpTryGetCharSerial(5000);
2819 InBuffer
[Length
++] = c
;
2820 if (Length
>= (sizeof (InBuffer
) - 1))
2824 InBuffer
[Length
] = '\0';
2826 TerminalConnected
= TRUE
;
2829 /* Get number of rows and columns in terminal */
2830 if ((KdbNumberOfRowsTerminal
< 0) || (KdbNumberOfColsTerminal
< 0) ||
2831 (KdbNumberOfRowsPrinted
) == 0) /* Refresh terminal size each time when number of rows printed is 0 */
2833 if ((KdbDebugState
& KD_DEBUG_KDSERIAL
) && TerminalConnected
&& TerminalReportsSize
)
2835 /* Try to query number of rows from terminal. A reply looks like "\x1b[8;24;80t" */
2836 TerminalReportsSize
= FALSE
;
2837 KeStallExecutionProcessor(100000);
2838 DbgPrint("\x1b[18t");
2839 c
= KdbpTryGetCharSerial(5000);
2843 c
= KdbpTryGetCharSerial(5000);
2850 c
= KdbpTryGetCharSerial(5000);
2854 InBuffer
[Length
++] = c
;
2855 if (isalpha(c
) || Length
>= (sizeof (InBuffer
) - 1))
2859 InBuffer
[Length
] = '\0';
2860 if (InBuffer
[0] == '8' && InBuffer
[1] == ';')
2862 for (i
= 2; (i
< Length
) && (InBuffer
[i
] != ';'); i
++);
2864 if (Buffer
[i
] == ';')
2868 /* Number of rows is now at Buffer + 2 and number of cols at Buffer + i */
2869 KdbNumberOfRowsTerminal
= strtoul(InBuffer
+ 2, NULL
, 0);
2870 KdbNumberOfColsTerminal
= strtoul(InBuffer
+ i
, NULL
, 0);
2871 TerminalReportsSize
= TRUE
;
2875 /* Clear further characters */
2876 while ((c
= KdbpTryGetCharSerial(5000)) != -1);
2880 if (KdbNumberOfRowsTerminal
<= 0)
2882 /* Set number of rows to the default. */
2883 KdbNumberOfRowsTerminal
= 24;
2885 else if (KdbNumberOfColsTerminal
<= 0)
2887 /* Set number of cols to the default. */
2888 KdbNumberOfColsTerminal
= 80;
2892 /* Get the string */
2895 while (p
[0] != '\0')
2897 if ( p
> Buffer
+BufLength
)
2899 DbgPrint("Dmesg: error, p > Buffer+BufLength,d=%d", p
- (Buffer
+BufLength
));
2902 i
= strcspn(p
, "\n");
2904 // Are we out of buffer?
2905 if (p
+ i
> Buffer
+ BufLength
)
2906 // Leaving pager function:
2909 /* Calculate the number of lines which will be printed in the terminal
2910 * when outputting the current line
2913 RowsPrintedByTerminal
= (i
+ KdbNumberOfColsPrinted
- 1) / KdbNumberOfColsTerminal
;
2915 RowsPrintedByTerminal
= 0;
2918 RowsPrintedByTerminal
++;
2920 /*DbgPrint("!%d!%d!%d!%d!", KdbNumberOfRowsPrinted, KdbNumberOfColsPrinted, i, RowsPrintedByTerminal);*/
2922 /* Display a prompt if we printed one screen full of text */
2923 if (KdbNumberOfRowsTerminal
> 0 &&
2924 (LONG
)(KdbNumberOfRowsPrinted
+ RowsPrintedByTerminal
) >= KdbNumberOfRowsTerminal
)
2926 KdbRepeatLastCommand
= FALSE
;
2928 if (KdbNumberOfColsPrinted
> 0)
2931 DbgPrint("--- Press q to abort, e/End,h/Home,u/PgUp, other key/PgDn ---");
2932 RowsPrintedByTerminal
++;
2934 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
2935 c
= KdbpGetCharSerial();
2937 c
= KdbpGetCharKeyboard(&ScanCode
);
2941 /* Try to read '\n' which might follow '\r' - if \n is not received here
2942 * it will be interpreted as "return" when the next command should be read.
2944 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
2945 c
= KdbpTryGetCharSerial(5);
2947 c
= KdbpTryGetCharKeyboard(&ScanCode
, 5);
2950 //DbgPrint("\n"); //Consize version: don't show pressed key
2951 DbgPrint(" '%c'/scan=%04x\n", c
, ScanCode
); // Shows pressed key
2955 KdbOutputAborted
= TRUE
;
2958 if ( ScanCode
== KEYSC_END
|| c
=='e')
2960 PCHAR pBufEnd
= Buffer
+ BufLength
;
2961 p
= CountOnePageUp(Buffer
, BufLength
, pBufEnd
);
2962 i
= strcspn(p
, "\n");
2964 else if (ScanCode
== KEYSC_PAGEUP
|| c
=='u')
2966 p
= CountOnePageUp(Buffer
, BufLength
, p
);
2967 i
= strcspn(p
, "\n");
2969 else if (ScanCode
== KEYSC_HOME
|| c
=='h')
2972 i
= strcspn(p
, "\n");
2974 else if (ScanCode
== KEYSC_ARROWUP
)
2976 p
= CountOnePageUp(Buffer
, BufLength
, p
);
2977 i
= strcspn(p
, "\n");
2980 KdbNumberOfRowsPrinted
= 0;
2981 KdbNumberOfColsPrinted
= 0;
2984 /* Insert a NUL after the line and print only the current line. */
2985 if (p
[i
] == '\n' && p
[i
+ 1] != '\0')
2995 /* Remove escape sequences from the line if there's no terminal connected */
2996 if (!TerminalConnected
)
2998 while ((p2
= strrchr(p
, '\x1b'))) /* Look for escape character */
3003 while (!isalpha(p2
[j
++]));
3013 // The main printing of the current line:
3016 // restore not null char with saved:
3020 /* Set p to the start of the next line and
3021 * remember the number of rows/cols printed
3027 KdbNumberOfColsPrinted
= 0;
3031 ASSERT(p
[0] == '\0');
3032 KdbNumberOfColsPrinted
+= i
;
3035 KdbNumberOfRowsPrinted
+= RowsPrintedByTerminal
;
3039 /*!\brief Appends a command to the command history
3041 * \param Command Pointer to the command to append to the history.
3044 KdbpCommandHistoryAppend(
3047 ULONG Length1
= strlen(Command
) + 1;
3052 ASSERT(Length1
<= RTL_NUMBER_OF(KdbCommandHistoryBuffer
));
3055 (KdbCommandHistory
[KdbCommandHistoryIndex
] &&
3056 strcmp(KdbCommandHistory
[KdbCommandHistoryIndex
], Command
) == 0))
3061 /* Calculate Length1 and Length2 */
3062 Buffer
= KdbCommandHistoryBuffer
+ KdbCommandHistoryBufferIndex
;
3063 KdbCommandHistoryBufferIndex
+= Length1
;
3064 if (KdbCommandHistoryBufferIndex
>= (LONG
)RTL_NUMBER_OF(KdbCommandHistoryBuffer
))
3066 KdbCommandHistoryBufferIndex
-= RTL_NUMBER_OF(KdbCommandHistoryBuffer
);
3067 Length2
= KdbCommandHistoryBufferIndex
;
3071 /* Remove previous commands until there is enough space to append the new command */
3072 for (i
= KdbCommandHistoryIndex
; KdbCommandHistory
[i
];)
3075 (KdbCommandHistory
[i
] >= Buffer
||
3076 KdbCommandHistory
[i
] < (KdbCommandHistoryBuffer
+ KdbCommandHistoryBufferIndex
))) ||
3078 (KdbCommandHistory
[i
] >= Buffer
&&
3079 KdbCommandHistory
[i
] < (KdbCommandHistoryBuffer
+ KdbCommandHistoryBufferIndex
))))
3081 KdbCommandHistory
[i
] = NULL
;
3086 i
= RTL_NUMBER_OF(KdbCommandHistory
) - 1;
3088 if (i
== KdbCommandHistoryIndex
)
3092 /* Make sure the new command history entry is free */
3093 KdbCommandHistoryIndex
++;
3094 KdbCommandHistoryIndex
%= RTL_NUMBER_OF(KdbCommandHistory
);
3095 if (KdbCommandHistory
[KdbCommandHistoryIndex
])
3097 KdbCommandHistory
[KdbCommandHistoryIndex
] = NULL
;
3100 /* Append command */
3101 KdbCommandHistory
[KdbCommandHistoryIndex
] = Buffer
;
3102 ASSERT((KdbCommandHistory
[KdbCommandHistoryIndex
] + Length1
) <= KdbCommandHistoryBuffer
+ RTL_NUMBER_OF(KdbCommandHistoryBuffer
));
3103 memcpy(KdbCommandHistory
[KdbCommandHistoryIndex
], Command
, Length1
);
3106 memcpy(KdbCommandHistoryBuffer
, Command
+ Length1
, Length2
);
3110 /*!\brief Reads a line of user-input.
3112 * \param Buffer Buffer to store the input into. Trailing newlines are removed.
3113 * \param Size Size of \a Buffer.
3115 * \note Accepts only \n newlines, \r is ignored.
3123 PCHAR Orig
= Buffer
;
3126 static CHAR LastCommand
[1024];
3127 static CHAR NextKey
= '\0';
3128 INT CmdHistIndex
= -1;
3131 EchoOn
= !((KdbDebugState
& KD_DEBUG_KDNOECHO
) != 0);
3135 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
3137 Key
= (NextKey
== '\0') ? KdbpGetCharSerial() : NextKey
;
3140 if (Key
== KEY_ESC
) /* ESC */
3142 Key
= KdbpGetCharSerial();
3145 Key
= KdbpGetCharSerial();
3150 ScanCode
= KEY_SCAN_UP
;
3153 ScanCode
= KEY_SCAN_DOWN
;
3166 Key
= (NextKey
== '\0') ? KdbpGetCharKeyboard(&ScanCode
) : NextKey
;
3170 if ((ULONG
)(Buffer
- Orig
) >= (Size
- 1))
3172 /* Buffer is full, accept only newlines */
3179 /* Read the next char - this is to throw away a \n which most clients should
3182 KeStallExecutionProcessor(100000);
3184 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
3185 NextKey
= KdbpTryGetCharSerial(5);
3187 NextKey
= KdbpTryGetCharKeyboard(&ScanCode
, 5);
3189 if (NextKey
== '\n' || NextKey
== -1) /* \n or no response at all */
3195 * Repeat the last command if the user presses enter. Reduces the
3196 * risk of RSI when single-stepping.
3200 KdbRepeatLastCommand
= TRUE
;
3202 RtlStringCbCopyA(LastCommand
, sizeof(LastCommand
), Orig
);
3204 else if (KdbRepeatLastCommand
)
3205 RtlStringCbCopyA(Buffer
, Size
, LastCommand
);
3211 else if (Key
== KEY_BS
|| Key
== KEY_DEL
)
3219 KdbpPrint("%c %c", KEY_BS
, KEY_BS
);
3221 KdbpPrint(" %c", KEY_BS
);
3224 else if (ScanCode
== KEY_SCAN_UP
)
3226 BOOLEAN Print
= TRUE
;
3228 if (CmdHistIndex
< 0)
3230 CmdHistIndex
= KdbCommandHistoryIndex
;
3234 i
= CmdHistIndex
- 1;
3237 CmdHistIndex
= RTL_NUMBER_OF(KdbCommandHistory
) - 1;
3239 if (KdbCommandHistory
[i
] && i
!= KdbCommandHistoryIndex
)
3245 if (Print
&& KdbCommandHistory
[CmdHistIndex
])
3247 while (Buffer
> Orig
)
3253 KdbpPrint("%c %c", KEY_BS
, KEY_BS
);
3255 KdbpPrint(" %c", KEY_BS
);
3258 i
= min(strlen(KdbCommandHistory
[CmdHistIndex
]), Size
- 1);
3259 memcpy(Orig
, KdbCommandHistory
[CmdHistIndex
], i
);
3262 KdbpPrint("%s", Orig
);
3265 else if (ScanCode
== KEY_SCAN_DOWN
)
3267 if (CmdHistIndex
> 0 && CmdHistIndex
!= KdbCommandHistoryIndex
)
3269 i
= CmdHistIndex
+ 1;
3270 if (i
>= (INT
)RTL_NUMBER_OF(KdbCommandHistory
))
3273 if (KdbCommandHistory
[i
])
3276 while (Buffer
> Orig
)
3282 KdbpPrint("%c %c", KEY_BS
, KEY_BS
);
3284 KdbpPrint(" %c", KEY_BS
);
3287 i
= min(strlen(KdbCommandHistory
[CmdHistIndex
]), Size
- 1);
3288 memcpy(Orig
, KdbCommandHistory
[CmdHistIndex
], i
);
3291 KdbpPrint("%s", Orig
);
3298 KdbpPrint("%c", Key
);
3309 KdbRegisterCliCallback(
3315 /* Loop all entries */
3316 for (i
= 0; i
< _countof(KdbCliCallbacks
); i
++)
3318 /* Check if deregistering was requested */
3321 /* Check if this entry is the one that was registered */
3322 if (KdbCliCallbacks
[i
] == Callback
)
3324 /* Delete it and report success */
3325 KdbCliCallbacks
[i
] = NULL
;
3331 /* Check if this entry is free */
3332 if (KdbCliCallbacks
[i
] == NULL
)
3334 /* Set it and and report success */
3335 KdbCliCallbacks
[i
] = Callback
;
3345 /*! \brief Invokes registered CLI callbacks until one of them handled the
3348 * \param Command - Command line to parse and execute if possible.
3349 * \param Argc - Number of arguments in Argv
3350 * \param Argv - Array of strings, each of them containing one argument.
3352 * \return TRUE, if the command was handled, FALSE if it was not handled.
3356 KdbpInvokeCliCallbacks(
3363 /* Loop all entries */
3364 for (i
= 0; i
< _countof(KdbCliCallbacks
); i
++)
3366 /* Check if this entry is registered */
3367 if (KdbCliCallbacks
[i
])
3369 /* Invoke the callback and check if it handled the command */
3370 if (KdbCliCallbacks
[i
](Command
, Argc
, Argv
))
3377 /* None of the callbacks handled the command */
3382 /*!\brief Parses command line and executes command if found
3384 * \param Command Command line to parse and execute if possible.
3386 * \retval TRUE Don't continue execution.
3387 * \retval FALSE Continue execution (leave KDB)
3396 // FIXME: for what do we need a 1024 characters command line and 256 tokens?
3397 static PCH Argv
[256];
3398 static CHAR OrigCommand
[1024];
3400 RtlStringCbCopyA(OrigCommand
, sizeof(OrigCommand
), Command
);
3407 while (*p
== '\t' || *p
== ' ')
3413 i
= strcspn(p
, "\t ");
3426 for (i
= 0; i
< RTL_NUMBER_OF(KdbDebuggerCommands
); i
++)
3428 if (!KdbDebuggerCommands
[i
].Name
)
3431 if (strcmp(KdbDebuggerCommands
[i
].Name
, Argv
[0]) == 0)
3433 return KdbDebuggerCommands
[i
].Fn(Argc
, Argv
);
3437 /* Now invoke the registered callbacks */
3438 if (KdbpInvokeCliCallbacks(Command
, Argc
, Argv
))
3443 KdbpPrint("Command '%s' is unknown.\n", OrigCommand
);
3447 /*!\brief KDB Main Loop.
3449 * \param EnteredOnSingleStep TRUE if KDB was entered on single step.
3453 IN BOOLEAN EnteredOnSingleStep
)
3455 static CHAR Command
[1024];
3458 if (EnteredOnSingleStep
)
3460 if (!KdbSymPrintAddress((PVOID
)KdbCurrentTrapFrame
->Tf
.Eip
, &KdbCurrentTrapFrame
->Tf
))
3462 KdbpPrint("<%x>", KdbCurrentTrapFrame
->Tf
.Eip
);
3466 if (KdbpDisassemble(KdbCurrentTrapFrame
->Tf
.Eip
, KdbUseIntelSyntax
) < 0)
3468 KdbpPrint("<INVALID>");
3473 /* Flush the input buffer */
3474 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
3476 while (KdbpTryGetCharSerial(1) != -1);
3481 while (KdbpTryGetCharKeyboard(&ScanCode
, 1) != -1);
3487 /* Reset the number of rows/cols printed */
3488 KdbNumberOfRowsPrinted
= KdbNumberOfColsPrinted
= 0;
3490 /* Print the prompt */
3491 KdbpPrint("kdb:> ");
3493 /* Read a command and remember it */
3494 KdbpReadCommand(Command
, sizeof (Command
));
3495 KdbpCommandHistoryAppend(Command
);
3497 /* Reset the number of rows/cols printed and output aborted state */
3498 KdbNumberOfRowsPrinted
= KdbNumberOfColsPrinted
= 0;
3499 KdbOutputAborted
= FALSE
;
3501 /* Call the command */
3502 Continue
= KdbpDoCommand(Command
);
3503 KdbOutputAborted
= FALSE
;
3508 /*!\brief Called when a module is loaded.
3510 * \param Name Filename of the module which was loaded.
3513 KdbpCliModuleLoaded(
3514 IN PUNICODE_STRING Name
)
3516 if (!KdbBreakOnModuleLoad
)
3519 KdbpPrint("Module %wZ loaded.\n", Name
);
3520 DbgBreakPointWithStatus(DBG_STATUS_CONTROL_C
);
3523 /*!\brief This function is called by KdbEnterDebuggerException...
3525 * Used to interpret the init file in a context with a trapframe setup
3526 * (KdbpCliInit call KdbEnter which will call KdbEnterDebuggerException which will
3527 * call this function if KdbInitFileBuffer is not NULL.
3530 KdbpCliInterpretInitFile(VOID
)
3536 /* Execute the commands in the init file */
3537 DPRINT("KDB: Executing KDBinit file...\n");
3538 p1
= KdbInitFileBuffer
;
3539 while (p1
[0] != '\0')
3541 i
= strcspn(p1
, "\r\n");
3547 /* Look for "break" command and comments */
3550 while (isspace(p2
[0]))
3553 if (strncmp(p2
, "break", sizeof("break")-1) == 0 &&
3554 (p2
[sizeof("break")-1] == '\0' || isspace(p2
[sizeof("break")-1])))
3556 /* break into the debugger */
3557 KdbpCliMainLoop(FALSE
);
3559 else if (p2
[0] != '#' && p2
[0] != '\0') /* Ignore empty lines and comments */
3568 while (p1
[0] == '\r' || p1
[0] == '\n')
3571 DPRINT("KDB: KDBinit executed\n");
3574 /*!\brief Called when KDB is initialized
3576 * Reads the KDBinit file from the SystemRoot\System32\drivers\etc directory and executes it.
3582 OBJECT_ATTRIBUTES ObjectAttributes
;
3583 UNICODE_STRING FileName
;
3584 IO_STATUS_BLOCK Iosb
;
3585 FILE_STANDARD_INFORMATION FileStdInfo
;
3586 HANDLE hFile
= NULL
;
3591 /* Initialize the object attributes */
3592 RtlInitUnicodeString(&FileName
, L
"\\SystemRoot\\System32\\drivers\\etc\\KDBinit");
3593 InitializeObjectAttributes(&ObjectAttributes
, &FileName
, 0, NULL
, NULL
);
3596 Status
= ZwOpenFile(&hFile
, FILE_READ_DATA
| SYNCHRONIZE
,
3597 &ObjectAttributes
, &Iosb
, 0,
3598 FILE_NON_DIRECTORY_FILE
| FILE_SYNCHRONOUS_IO_NONALERT
|
3599 FILE_NO_INTERMEDIATE_BUFFERING
);
3600 if (!NT_SUCCESS(Status
))
3602 DPRINT("Could not open \\SystemRoot\\System32\\drivers\\etc\\KDBinit (Status 0x%x)", Status
);
3606 /* Get the size of the file */
3607 Status
= ZwQueryInformationFile(hFile
, &Iosb
, &FileStdInfo
, sizeof (FileStdInfo
),
3608 FileStandardInformation
);
3609 if (!NT_SUCCESS(Status
))
3612 DPRINT("Could not query size of \\SystemRoot\\System32\\drivers\\etc\\KDBinit (Status 0x%x)", Status
);
3615 FileSize
= FileStdInfo
.EndOfFile
.u
.LowPart
;
3617 /* Allocate memory for the file */
3618 FileBuffer
= ExAllocatePool(PagedPool
, FileSize
+ 1); /* add 1 byte for terminating '\0' */
3622 DPRINT("Could not allocate %d bytes for KDBinit file\n", FileSize
);
3626 /* Load file into memory */
3627 Status
= ZwReadFile(hFile
, NULL
, NULL
, NULL
, &Iosb
, FileBuffer
, FileSize
, NULL
, NULL
);
3630 if (!NT_SUCCESS(Status
) && Status
!= STATUS_END_OF_FILE
)
3632 ExFreePool(FileBuffer
);
3633 DPRINT("Could not read KDBinit file into memory (Status 0x%lx)\n", Status
);
3637 FileSize
= min(FileSize
, (INT
)Iosb
.Information
);
3638 FileBuffer
[FileSize
] = '\0';
3640 /* Enter critical section */
3641 OldEflags
= __readeflags();
3644 /* Interpret the init file... */
3645 KdbInitFileBuffer
= FileBuffer
;
3647 KdbInitFileBuffer
= NULL
;
3649 /* Leave critical section */
3650 __writeeflags(OldEflags
);
3652 ExFreePool(FileBuffer
);
3657 KdpSerialDebugPrint(
3662 STRING KdpPromptString
= RTL_CONSTANT_STRING("kdb:> ");
3663 extern KSPIN_LOCK KdpSerialSpinLock
;
3668 _In_reads_bytes_(InStringLength
) PCHAR UnsafeInString
,
3669 _In_ USHORT InStringLength
,
3670 _Out_writes_bytes_(OutStringLength
) PCHAR UnsafeOutString
,
3671 _In_ USHORT OutStringLength
,
3672 _In_ KPROCESSOR_MODE PreviousMode
)
3676 ULONG DummyScanCode
;
3680 CHAR InStringBuffer
[512];
3681 CHAR OutStringBuffer
[512];
3683 /* Normalize the lengths */
3684 InStringLength
= min(InStringLength
,
3685 sizeof(InStringBuffer
));
3686 OutStringLength
= min(OutStringLength
,
3687 sizeof(OutStringBuffer
));
3689 /* Check if we need to verify the string */
3690 if (PreviousMode
!= KernelMode
)
3692 /* Handle user-mode buffers safely */
3695 /* Probe the prompt */
3696 ProbeForRead(UnsafeInString
,
3700 /* Capture prompt */
3701 InString
= InStringBuffer
;
3702 RtlCopyMemory(InString
,
3706 /* Probe and make room for response */
3707 ProbeForWrite(UnsafeOutString
,
3710 OutString
= OutStringBuffer
;
3712 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
3714 /* Bad string pointer, bail out */
3715 _SEH2_YIELD(return 0);
3721 InString
= UnsafeInString
;
3722 OutString
= UnsafeOutString
;
3725 /* Acquire the printing spinlock without waiting at raised IRQL */
3728 /* Wait when the spinlock becomes available */
3729 while (!KeTestSpinLock(&KdpSerialSpinLock
));
3731 /* Spinlock was free, raise IRQL */
3732 KeRaiseIrql(HIGH_LEVEL
, &OldIrql
);
3734 /* Try to get the spinlock */
3735 if (KeTryToAcquireSpinLockAtDpcLevel(&KdpSerialSpinLock
))
3738 /* Someone else got the spinlock, lower IRQL back */
3739 KeLowerIrql(OldIrql
);
3742 /* Loop the string to send */
3743 for (i
= 0; i
< InStringLength
; i
++)
3745 /* Print it to serial */
3746 KdPortPutByteEx(&SerialPortInfo
, *(PCHAR
)(InString
+ i
));
3749 /* Print a new line for log neatness */
3750 KdPortPutByteEx(&SerialPortInfo
, '\r');
3751 KdPortPutByteEx(&SerialPortInfo
, '\n');
3753 /* Print the kdb prompt */
3754 for (i
= 0; i
< KdpPromptString
.Length
; i
++)
3756 /* Print it to serial */
3757 KdPortPutByteEx(&SerialPortInfo
,
3758 *(KdpPromptString
.Buffer
+ i
));
3761 if (!(KdbDebugState
& KD_DEBUG_KDSERIAL
))
3764 /* Loop the whole string */
3765 for (i
= 0; i
< OutStringLength
; i
++)
3767 /* Check if this is serial debugging mode */
3768 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
3770 /* Get the character from serial */
3773 Response
= KdbpTryGetCharSerial(MAXULONG
);
3774 } while (Response
== -1);
3778 /* Get the response from the keyboard */
3781 Response
= KdbpTryGetCharKeyboard(&DummyScanCode
, MAXULONG
);
3782 } while (Response
== -1);
3785 /* Check for return */
3786 if (Response
== '\r')
3789 * We might need to discard the next '\n'.
3790 * Wait a bit to make sure we receive it.
3792 KeStallExecutionProcessor(100000);
3794 /* Check the mode */
3795 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
3797 /* Read and discard the next character, if any */
3798 KdbpTryGetCharSerial(5);
3802 /* Read and discard the next character, if any */
3803 KdbpTryGetCharKeyboard(&DummyScanCode
, 5);
3807 * Null terminate the output string -- documentation states that
3808 * DbgPrompt does not null terminate, but it does
3810 *(PCHAR
)(OutString
+ i
) = 0;
3814 /* Write it back and print it to the log */
3815 *(PCHAR
)(OutString
+ i
) = Response
;
3816 KdPortPutByteEx(&SerialPortInfo
, Response
);
3819 if (!(KdbDebugState
& KD_DEBUG_KDSERIAL
))
3822 /* Print a new line */
3823 KdPortPutByteEx(&SerialPortInfo
, '\r');
3824 KdPortPutByteEx(&SerialPortInfo
, '\n');
3826 /* Release spinlock */
3827 KiReleaseSpinLock(&KdpSerialSpinLock
);
3829 /* Lower IRQL back */
3830 KeLowerIrql(OldIrql
);
3832 /* Copy back response if required */
3833 if (PreviousMode
!= KernelMode
)
3837 /* Safely copy back response to user mode */
3838 RtlCopyMemory(UnsafeOutString
,
3842 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
3844 /* String became invalid after we exited, fail */
3845 _SEH2_YIELD(return 0);
3850 /* Return the length */