- Make Kdbg "bugcheck" command work -- Kdbg isn't re-entrant, so defer the bugcheck...
[reactos.git] / reactos / ntoskrnl / kdbg / kdb_cli.c
1 /*
2 * ReactOS kernel
3 * Copyright (C) 2005 ReactOS Team
4 *
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.
9 *
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.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18 */
19 /*
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)
24 * Hervé Poussineau
25 * UPDATE HISTORY:
26 * Created 16/01/2005
27 */
28
29 /* INCLUDES ******************************************************************/
30
31 #include <ntoskrnl.h>
32
33 #define NDEBUG
34 #include <debug.h>
35
36 /* DEFINES *******************************************************************/
37
38 #define KEY_BS 8
39 #define KEY_ESC 27
40 #define KEY_DEL 127
41
42 #define KEY_SCAN_UP 72
43 #define KEY_SCAN_DOWN 80
44
45 #define KDB_ENTER_CONDITION_TO_STRING(cond) \
46 ((cond) == KdbDoNotEnter ? "never" : \
47 ((cond) == KdbEnterAlways ? "always" : \
48 ((cond) == KdbEnterFromKmode ? "kmode" : "umode")))
49
50 #define KDB_ACCESS_TYPE_TO_STRING(type) \
51 ((type) == KdbAccessRead ? "read" : \
52 ((type) == KdbAccessWrite ? "write" : \
53 ((type) == KdbAccessReadWrite ? "rdwr" : "exec")))
54
55 #define NPX_STATE_TO_STRING(state) \
56 ((state) == NPX_STATE_LOADED ? "Loaded" : \
57 ((state) == NPX_STATE_NOT_LOADED ? "Not loaded" : "Unknown"))
58
59 /* PROTOTYPES ****************************************************************/
60
61 STATIC BOOLEAN KdbpCmdEvalExpression(ULONG Argc, PCHAR Argv[]);
62 STATIC BOOLEAN KdbpCmdDisassembleX(ULONG Argc, PCHAR Argv[]);
63 STATIC BOOLEAN KdbpCmdRegs(ULONG Argc, PCHAR Argv[]);
64 STATIC BOOLEAN KdbpCmdBackTrace(ULONG Argc, PCHAR Argv[]);
65
66 STATIC BOOLEAN KdbpCmdContinue(ULONG Argc, PCHAR Argv[]);
67 STATIC BOOLEAN KdbpCmdStep(ULONG Argc, PCHAR Argv[]);
68 STATIC BOOLEAN KdbpCmdBreakPointList(ULONG Argc, PCHAR Argv[]);
69 STATIC BOOLEAN KdbpCmdEnableDisableClearBreakPoint(ULONG Argc, PCHAR Argv[]);
70 STATIC BOOLEAN KdbpCmdBreakPoint(ULONG Argc, PCHAR Argv[]);
71
72 STATIC BOOLEAN KdbpCmdThread(ULONG Argc, PCHAR Argv[]);
73 STATIC BOOLEAN KdbpCmdProc(ULONG Argc, PCHAR Argv[]);
74
75 STATIC BOOLEAN KdbpCmdMod(ULONG Argc, PCHAR Argv[]);
76 STATIC BOOLEAN KdbpCmdGdtLdtIdt(ULONG Argc, PCHAR Argv[]);
77 STATIC BOOLEAN KdbpCmdPcr(ULONG Argc, PCHAR Argv[]);
78 STATIC BOOLEAN KdbpCmdTss(ULONG Argc, PCHAR Argv[]);
79
80 STATIC BOOLEAN KdbpCmdBugCheck(ULONG Argc, PCHAR Argv[]);
81 STATIC BOOLEAN KdbpCmdFilter(ULONG Argc, PCHAR Argv[]);
82 STATIC BOOLEAN KdbpCmdSet(ULONG Argc, PCHAR Argv[]);
83 STATIC BOOLEAN KdbpCmdHelp(ULONG Argc, PCHAR Argv[]);
84
85 /* GLOBALS *******************************************************************/
86
87 STATIC BOOLEAN KdbUseIntelSyntax = FALSE; /* Set to TRUE for intel syntax */
88 STATIC BOOLEAN KdbBreakOnModuleLoad = FALSE; /* Set to TRUE to break into KDB when a module is loaded */
89
90 STATIC CHAR KdbCommandHistoryBuffer[2048]; /* Command history string ringbuffer */
91 STATIC PCHAR KdbCommandHistory[sizeof(KdbCommandHistoryBuffer) / 8] = { NULL }; /* Command history ringbuffer */
92 STATIC LONG KdbCommandHistoryBufferIndex = 0;
93 STATIC LONG KdbCommandHistoryIndex = 0;
94
95 STATIC ULONG KdbNumberOfRowsPrinted = 0;
96 STATIC ULONG KdbNumberOfColsPrinted = 0;
97 STATIC BOOLEAN KdbOutputAborted = FALSE;
98 STATIC LONG KdbNumberOfRowsTerminal = -1;
99 STATIC LONG KdbNumberOfColsTerminal = -1;
100
101 PCHAR KdbInitFileBuffer = NULL; /* Buffer where KDBinit file is loaded into during initialization */
102 BOOLEAN KdbpBugCheckRequested = FALSE;
103
104 STATIC CONST struct
105 {
106 PCHAR Name;
107 PCHAR Syntax;
108 PCHAR Help;
109 BOOLEAN (*Fn)(ULONG Argc, PCHAR Argv[]);
110 } KdbDebuggerCommands[] = {
111 /* Data */
112 { NULL, NULL, "Data", NULL },
113 { "?", "? expression", "Evaluate expression.", KdbpCmdEvalExpression },
114 { "disasm", "disasm [address] [L count]", "Disassemble count instructions at address.", KdbpCmdDisassembleX },
115 { "x", "x [address] [L count]", "Display count dwords, starting at addr.", KdbpCmdDisassembleX },
116 { "regs", "regs", "Display general purpose registers.", KdbpCmdRegs },
117 { "cregs", "cregs", "Display control registers.", KdbpCmdRegs },
118 { "sregs", "sregs", "Display status registers.", KdbpCmdRegs },
119 { "dregs", "dregs", "Display debug registers.", KdbpCmdRegs },
120 { "bt", "bt [*frameaddr|thread id]", "Prints current backtrace or from given frame addr", KdbpCmdBackTrace },
121
122 /* Flow control */
123 { NULL, NULL, "Flow control", NULL },
124 { "cont", "cont", "Continue execution (leave debugger)", KdbpCmdContinue },
125 { "step", "step [count]", "Execute single instructions, stepping into interrupts.", KdbpCmdStep },
126 { "next", "next [count]", "Execute single instructions, skipping calls and reps.", KdbpCmdStep },
127 { "bl", "bl", "List breakpoints.", KdbpCmdBreakPointList },
128 { "be", "be [breakpoint]", "Enable breakpoint.", KdbpCmdEnableDisableClearBreakPoint },
129 { "bd", "bd [breakpoint]", "Disable breakpoint.", KdbpCmdEnableDisableClearBreakPoint },
130 { "bc", "bc [breakpoint]", "Clear breakpoint.", KdbpCmdEnableDisableClearBreakPoint },
131 { "bpx", "bpx [address] [IF condition]", "Set software execution breakpoint at address.", KdbpCmdBreakPoint },
132 { "bpm", "bpm [r|w|rw|x] [byte|word|dword] [address] [IF condition]", "Set memory breakpoint at address.", KdbpCmdBreakPoint },
133
134 /* Process/Thread */
135 { NULL, NULL, "Process/Thread", NULL },
136 { "thread", "thread [list[ pid]|[attach ]tid]", "List threads in current or specified process, display thread with given id or attach to thread.", KdbpCmdThread },
137 { "proc", "proc [list|[attach ]pid]", "List processes, display process with given id or attach to process.", KdbpCmdProc },
138
139 /* System information */
140 { NULL, NULL, "System info", NULL },
141 { "mod", "mod [address]", "List all modules or the one containing address.", KdbpCmdMod },
142 { "gdt", "gdt", "Display global descriptor table.", KdbpCmdGdtLdtIdt },
143 { "ldt", "ldt", "Display local descriptor table.", KdbpCmdGdtLdtIdt },
144 { "idt", "idt", "Display interrupt descriptor table.", KdbpCmdGdtLdtIdt },
145 { "pcr", "pcr", "Display processor control region.", KdbpCmdPcr },
146 { "tss", "tss", "Display task state segment.", KdbpCmdTss },
147
148 /* Others */
149 { NULL, NULL, "Others", NULL },
150 { "bugcheck", "bugcheck", "Bugchecks the system.", KdbpCmdBugCheck },
151 { "filter", "filter [error|warning|trace|info|level]+|-[componentname|default]", "Enable/disable debug channels", KdbpCmdFilter },
152 { "set", "set [var] [value]", "Sets var to value or displays value of var.", KdbpCmdSet },
153 { "help", "help", "Display help screen.", KdbpCmdHelp }
154 };
155
156 /* FUNCTIONS *****************************************************************/
157
158 /*!\brief Transform a component name to an integer
159 *
160 * \param ComponentName The name of the component.
161 * \param ComponentId Receives the component id on success.
162 *
163 * \retval TRUE Success.
164 * \retval FALSE Failure.
165 */
166 STATIC BOOLEAN
167 KdbpGetComponentId(
168 IN PCCH ComponentName,
169 OUT PULONG ComponentId)
170 {
171 ULONG i;
172
173 static struct {
174 PCCH Name;
175 ULONG Id;
176 } ComponentTable[] = {
177 { "DEFAULT", DPFLTR_DEFAULT_ID },
178 { "SYSTEM", DPFLTR_SYSTEM_ID },
179 { "SMSS", DPFLTR_SMSS_ID },
180 { "SETUP", DPFLTR_SETUP_ID },
181 { "NTFS", DPFLTR_NTFS_ID },
182 { "FSTUB", DPFLTR_FSTUB_ID },
183 { "CRASHDUMP", DPFLTR_CRASHDUMP_ID },
184 { "CDAUDIO", DPFLTR_CDAUDIO_ID },
185 { "CDROM", DPFLTR_CDROM_ID },
186 { "CLASSPNP", DPFLTR_CLASSPNP_ID },
187 { "DISK", DPFLTR_DISK_ID },
188 { "REDBOOK", DPFLTR_REDBOOK_ID },
189 { "STORPROP", DPFLTR_STORPROP_ID },
190 { "SCSIPORT", DPFLTR_SCSIPORT_ID },
191 { "SCSIMINIPORT", DPFLTR_SCSIMINIPORT_ID },
192 { "CONFIG", DPFLTR_CONFIG_ID },
193 { "I8042PRT", DPFLTR_I8042PRT_ID },
194 { "SERMOUSE", DPFLTR_SERMOUSE_ID },
195 { "LSERMOUS", DPFLTR_LSERMOUS_ID },
196 { "KBDHID", DPFLTR_KBDHID_ID },
197 { "MOUHID", DPFLTR_MOUHID_ID },
198 { "KBDCLASS", DPFLTR_KBDCLASS_ID },
199 { "MOUCLASS", DPFLTR_MOUCLASS_ID },
200 { "TWOTRACK", DPFLTR_TWOTRACK_ID },
201 { "WMILIB", DPFLTR_WMILIB_ID },
202 { "ACPI", DPFLTR_ACPI_ID },
203 { "AMLI", DPFLTR_AMLI_ID },
204 { "HALIA64", DPFLTR_HALIA64_ID },
205 { "VIDEO", DPFLTR_VIDEO_ID },
206 { "SVCHOST", DPFLTR_SVCHOST_ID },
207 { "VIDEOPRT", DPFLTR_VIDEOPRT_ID },
208 { "TCPIP", DPFLTR_TCPIP_ID },
209 { "DMSYNTH", DPFLTR_DMSYNTH_ID },
210 { "NTOSPNP", DPFLTR_NTOSPNP_ID },
211 { "FASTFAT", DPFLTR_FASTFAT_ID },
212 { "SAMSS", DPFLTR_SAMSS_ID },
213 { "PNPMGR", DPFLTR_PNPMGR_ID },
214 { "NETAPI", DPFLTR_NETAPI_ID },
215 { "SCSERVER", DPFLTR_SCSERVER_ID },
216 { "SCCLIENT", DPFLTR_SCCLIENT_ID },
217 { "SERIAL", DPFLTR_SERIAL_ID },
218 { "SERENUM", DPFLTR_SERENUM_ID },
219 { "UHCD", DPFLTR_UHCD_ID },
220 { "BOOTOK", DPFLTR_BOOTOK_ID },
221 { "BOOTVRFY", DPFLTR_BOOTVRFY_ID },
222 { "RPCPROXY", DPFLTR_RPCPROXY_ID },
223 { "AUTOCHK", DPFLTR_AUTOCHK_ID },
224 { "DCOMSS", DPFLTR_DCOMSS_ID },
225 { "UNIMODEM", DPFLTR_UNIMODEM_ID },
226 { "SIS", DPFLTR_SIS_ID },
227 { "FLTMGR", DPFLTR_FLTMGR_ID },
228 { "WMICORE", DPFLTR_WMICORE_ID },
229 { "BURNENG", DPFLTR_BURNENG_ID },
230 { "IMAPI", DPFLTR_IMAPI_ID },
231 { "SXS", DPFLTR_SXS_ID },
232 { "FUSION", DPFLTR_FUSION_ID },
233 { "IDLETASK", DPFLTR_IDLETASK_ID },
234 { "SOFTPCI", DPFLTR_SOFTPCI_ID },
235 { "TAPE", DPFLTR_TAPE_ID },
236 { "MCHGR", DPFLTR_MCHGR_ID },
237 { "IDEP", DPFLTR_IDEP_ID },
238 { "PCIIDE", DPFLTR_PCIIDE_ID },
239 { "FLOPPY", DPFLTR_FLOPPY_ID },
240 { "FDC", DPFLTR_FDC_ID },
241 { "TERMSRV", DPFLTR_TERMSRV_ID },
242 { "W32TIME", DPFLTR_W32TIME_ID },
243 { "PREFETCHER", DPFLTR_PREFETCHER_ID },
244 { "RSFILTER", DPFLTR_RSFILTER_ID },
245 { "FCPORT", DPFLTR_FCPORT_ID },
246 { "PCI", DPFLTR_PCI_ID },
247 { "DMIO", DPFLTR_DMIO_ID },
248 { "DMCONFIG", DPFLTR_DMCONFIG_ID },
249 { "DMADMIN", DPFLTR_DMADMIN_ID },
250 { "WSOCKTRANSPORT", DPFLTR_WSOCKTRANSPORT_ID },
251 { "VSS", DPFLTR_VSS_ID },
252 { "PNPMEM", DPFLTR_PNPMEM_ID },
253 { "PROCESSOR", DPFLTR_PROCESSOR_ID },
254 { "DMSERVER", DPFLTR_DMSERVER_ID },
255 { "SR", DPFLTR_SR_ID },
256 { "INFINIBAND", DPFLTR_INFINIBAND_ID },
257 { "IHVDRIVER", DPFLTR_IHVDRIVER_ID },
258 { "IHVVIDEO", DPFLTR_IHVVIDEO_ID },
259 { "IHVAUDIO", DPFLTR_IHVAUDIO_ID },
260 { "IHVNETWORK", DPFLTR_IHVNETWORK_ID },
261 { "IHVSTREAMING", DPFLTR_IHVSTREAMING_ID },
262 { "IHVBUS", DPFLTR_IHVBUS_ID },
263 { "HPS", DPFLTR_HPS_ID },
264 { "RTLTHREADPOOL", DPFLTR_RTLTHREADPOOL_ID },
265 { "LDR", DPFLTR_LDR_ID },
266 { "TCPIP6", DPFLTR_TCPIP6_ID },
267 { "ISAPNP", DPFLTR_ISAPNP_ID },
268 { "SHPC", DPFLTR_SHPC_ID },
269 { "STORPORT", DPFLTR_STORPORT_ID },
270 { "STORMINIPORT", DPFLTR_STORMINIPORT_ID },
271 { "PRINTSPOOLER", DPFLTR_PRINTSPOOLER_ID },
272 };
273
274 for (i = 0; i < sizeof(ComponentTable) / sizeof(ComponentTable[0]); i++)
275 if (_stricmp(ComponentName, ComponentTable[i].Name) == 0)
276 {
277 *ComponentId = ComponentTable[i].Id;
278 return TRUE;
279 }
280
281 return FALSE;
282 }
283
284 /*!\brief Evaluates an expression...
285 *
286 * Much like KdbpRpnEvaluateExpression, but prints the error message (if any)
287 * at the given offset.
288 *
289 * \param Expression Expression to evaluate.
290 * \param ErrOffset Offset (in characters) to print the error message at.
291 * \param Result Receives the result on success.
292 *
293 * \retval TRUE Success.
294 * \retval FALSE Failure.
295 */
296 STATIC BOOLEAN
297 KdbpEvaluateExpression(
298 IN PCHAR Expression,
299 IN LONG ErrOffset,
300 OUT PULONGLONG Result)
301 {
302 STATIC CHAR ErrMsgBuffer[130] = "^ ";
303 LONG ExpressionErrOffset = -1;
304 PCHAR ErrMsg = ErrMsgBuffer;
305 BOOLEAN Ok;
306
307 Ok = KdbpRpnEvaluateExpression(Expression, KdbCurrentTrapFrame, Result,
308 &ExpressionErrOffset, ErrMsgBuffer + 2);
309 if (!Ok)
310 {
311 if (ExpressionErrOffset >= 0)
312 ExpressionErrOffset += ErrOffset;
313 else
314 ErrMsg += 2;
315 KdbpPrint("%*s%s\n", ExpressionErrOffset, "", ErrMsg);
316 }
317
318 return Ok;
319 }
320
321 /*!\brief Evaluates an expression and displays the result.
322 */
323 STATIC BOOLEAN
324 KdbpCmdEvalExpression(ULONG Argc, PCHAR Argv[])
325 {
326 ULONG i, len;
327 ULONGLONG Result = 0;
328 ULONG ul;
329 LONG l = 0;
330 BOOLEAN Ok;
331
332 if (Argc < 2)
333 {
334 KdbpPrint("?: Argument required\n");
335 return TRUE;
336 }
337
338 /* Put the arguments back together */
339 Argc--;
340 for (i = 1; i < Argc; i++)
341 {
342 len = strlen(Argv[i]);
343 Argv[i][len] = ' ';
344 }
345
346 /* Evaluate the expression */
347 Ok = KdbpEvaluateExpression(Argv[1], sizeof("kdb:> ")-1 + (Argv[1]-Argv[0]), &Result);
348 if (Ok)
349 {
350 if (Result > 0x00000000ffffffffLL)
351 {
352 if (Result & 0x8000000000000000LL)
353 KdbpPrint("0x%016I64x %20I64u %20I64d\n", Result, Result, Result);
354 else
355 KdbpPrint("0x%016I64x %20I64u\n", Result, Result);
356 }
357 else
358 {
359 ul = (ULONG)Result;
360 if (ul <= 0xff && ul >= 0x80)
361 l = (LONG)((CHAR)ul);
362 else if (ul <= 0xffff && ul >= 0x8000)
363 l = (LONG)((SHORT)ul);
364 else
365 l = (LONG)ul;
366 if (l < 0)
367 KdbpPrint("0x%08lx %10lu %10ld\n", ul, ul, l);
368 else
369 KdbpPrint("0x%08lx %10lu\n", ul, ul);
370 }
371 }
372
373 return TRUE;
374 }
375
376 /*!\brief Display list of active debug channels
377 */
378 STATIC BOOLEAN
379 KdbpCmdFilter(ULONG Argc, PCHAR Argv[])
380 {
381 ULONG i, j, ComponentId, Level;
382 ULONG set = DPFLTR_MASK, clear = DPFLTR_MASK;
383 PCHAR pend;
384 LPCSTR opt, p;
385 static struct {
386 LPCSTR Name;
387 ULONG Level;
388 } debug_classes[] = {
389 { "error", 1 << DPFLTR_ERROR_LEVEL },
390 { "warning", 1 << DPFLTR_WARNING_LEVEL },
391 { "trace", 1 << DPFLTR_TRACE_LEVEL },
392 { "info", 1 << DPFLTR_INFO_LEVEL },
393 };
394
395 for (i = 1; i < Argc; i++)
396 {
397 opt = Argv[i];
398 p = opt + strcspn(opt, "+-");
399 if (!p[0]) p = opt; /* assume it's a debug channel name */
400
401 if (p > opt)
402 {
403 for (j = 0; j < sizeof(debug_classes) / sizeof(debug_classes[0]); j++)
404 {
405 SIZE_T len = strlen(debug_classes[j].Name);
406 if (len != (p - opt))
407 continue;
408 if (_strnicmp(opt, debug_classes[j].Name, len) == 0) /* found it */
409 {
410 if (*p == '+')
411 set |= debug_classes[j].Level;
412 else
413 clear |= debug_classes[j].Level;
414 break;
415 }
416 }
417 if (j == sizeof(debug_classes) / sizeof(debug_classes[0]))
418 {
419 Level = strtoul(opt, &pend, 0);
420 if (pend != p)
421 {
422 KdbpPrint("filter: bad class name '%.*s'\n", p - opt, opt);
423 continue;
424 }
425 if (*p == '+')
426 set |= Level;
427 else
428 clear |= Level;
429 }
430 }
431 else
432 {
433 if (*p == '-')
434 clear = ~0;
435 else
436 set = ~0;
437 }
438 if (*p == '+' || *p == '-')
439 p++;
440
441 if (!KdbpGetComponentId(p, &ComponentId))
442 {
443 KdbpPrint("filter: '%s' is not a valid component name!\n", p);
444 return TRUE;
445 }
446
447 /* Get current mask value */
448 NtSetDebugFilterState(ComponentId, set, TRUE);
449 NtSetDebugFilterState(ComponentId, clear, FALSE);
450 }
451
452 return TRUE;
453 }
454
455 /*!\brief Disassembles 10 instructions at eip or given address or
456 * displays 16 dwords from memory at given address.
457 */
458 STATIC BOOLEAN
459 KdbpCmdDisassembleX(ULONG Argc, PCHAR Argv[])
460 {
461 ULONG Count;
462 ULONG ul;
463 INT i;
464 ULONGLONG Result = 0;
465 ULONG_PTR Address = KdbCurrentTrapFrame->Tf.Eip;
466 LONG InstLen;
467
468 if (Argv[0][0] == 'x') /* display memory */
469 Count = 16;
470 else /* disassemble */
471 Count = 10;
472
473 if (Argc >= 2)
474 {
475 /* Check for [L count] part */
476 ul = 0;
477 if (strcmp(Argv[Argc-2], "L") == 0)
478 {
479 ul = strtoul(Argv[Argc-1], NULL, 0);
480 if (ul > 0)
481 {
482 Count = ul;
483 Argc -= 2;
484 }
485 }
486 else if (Argv[Argc-1][0] == 'L')
487 {
488 ul = strtoul(Argv[Argc-1] + 1, NULL, 0);
489 if (ul > 0)
490 {
491 Count = ul;
492 Argc--;
493 }
494 }
495
496 /* Put the remaining arguments back together */
497 Argc--;
498 for (ul = 1; ul < Argc; ul++)
499 {
500 Argv[ul][strlen(Argv[ul])] = ' ';
501 }
502 Argc++;
503 }
504
505 /* Evaluate the expression */
506 if (Argc > 1)
507 {
508 if (!KdbpEvaluateExpression(Argv[1], sizeof("kdb:> ")-1 + (Argv[1]-Argv[0]), &Result))
509 return TRUE;
510 if (Result > (ULONGLONG)(~((ULONG_PTR)0)))
511 KdbpPrint("Warning: Address %I64x is beeing truncated\n");
512 Address = (ULONG_PTR)Result;
513 }
514 else if (Argv[0][0] == 'x')
515 {
516 KdbpPrint("x: Address argument required.\n");
517 return TRUE;
518 }
519
520 if (Argv[0][0] == 'x')
521 {
522 /* Display dwords */
523 ul = 0;
524 while (Count > 0)
525 {
526 if (!KdbSymPrintAddress((PVOID)Address))
527 KdbpPrint("<%x>:", Address);
528 else
529 KdbpPrint(":");
530 i = min(4, Count);
531 Count -= i;
532 while (--i >= 0)
533 {
534 if (!NT_SUCCESS(KdbpSafeReadMemory(&ul, (PVOID)Address, sizeof(ul))))
535 KdbpPrint(" ????????");
536 else
537 KdbpPrint(" %08x", ul);
538 Address += sizeof(ul);
539 }
540 KdbpPrint("\n");
541 }
542 }
543 else
544 {
545 /* Disassemble */
546 while (Count-- > 0)
547 {
548 if (!KdbSymPrintAddress((PVOID)Address))
549 KdbpPrint("<%08x>: ", Address);
550 else
551 KdbpPrint(": ");
552 InstLen = KdbpDisassemble(Address, KdbUseIntelSyntax);
553 if (InstLen < 0)
554 {
555 KdbpPrint("<INVALID>\n");
556 return TRUE;
557 }
558 KdbpPrint("\n");
559 Address += InstLen;
560 }
561 }
562
563 return TRUE;
564 }
565
566 /*!\brief Displays CPU registers.
567 */
568 STATIC BOOLEAN
569 KdbpCmdRegs(ULONG Argc, PCHAR Argv[])
570 {
571 PKTRAP_FRAME Tf = &KdbCurrentTrapFrame->Tf;
572 INT i;
573 STATIC CONST PCHAR EflagsBits[32] = { " CF", NULL, " PF", " BIT3", " AF", " BIT5",
574 " ZF", " SF", " TF", " IF", " DF", " OF",
575 NULL, NULL, " NT", " BIT15", " RF", " VF",
576 " AC", " VIF", " VIP", " ID", " BIT22",
577 " BIT23", " BIT24", " BIT25", " BIT26",
578 " BIT27", " BIT28", " BIT29", " BIT30",
579 " BIT31" };
580
581 if (Argv[0][0] == 'r') /* regs */
582 {
583 KdbpPrint("CS:EIP 0x%04x:0x%08x\n"
584 "SS:ESP 0x%04x:0x%08x\n"
585 " EAX 0x%08x EBX 0x%08x\n"
586 " ECX 0x%08x EDX 0x%08x\n"
587 " ESI 0x%08x EDI 0x%08x\n"
588 " EBP 0x%08x\n",
589 Tf->SegCs & 0xFFFF, Tf->Eip,
590 Tf->HardwareSegSs, Tf->HardwareEsp,
591 Tf->Eax, Tf->Ebx,
592 Tf->Ecx, Tf->Edx,
593 Tf->Esi, Tf->Edi,
594 Tf->Ebp);
595 KdbpPrint("EFLAGS 0x%08x ", Tf->EFlags);
596 for (i = 0; i < 32; i++)
597 {
598 if (i == 1)
599 {
600 if ((Tf->EFlags & (1 << 1)) == 0)
601 KdbpPrint(" !BIT1");
602 }
603 else if (i == 12)
604 {
605 KdbpPrint(" IOPL%d", (Tf->EFlags >> 12) & 3);
606 }
607 else if (i == 13)
608 {
609 }
610 else if ((Tf->EFlags & (1 << i)) != 0)
611 KdbpPrint(EflagsBits[i]);
612 }
613 KdbpPrint("\n");
614 }
615 else if (Argv[0][0] == 'c') /* cregs */
616 {
617 ULONG Cr0, Cr2, Cr3, Cr4;
618 KDESCRIPTOR Gdtr = {0}, Ldtr = {0}, Idtr = {0};
619 ULONG Tr = 0;
620 STATIC CONST PCHAR Cr0Bits[32] = { " PE", " MP", " EM", " TS", " ET", " NE", NULL, NULL,
621 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
622 " WP", NULL, " AM", NULL, NULL, NULL, NULL, NULL,
623 NULL, NULL, NULL, NULL, NULL, " NW", " CD", " PG" };
624 STATIC CONST PCHAR Cr4Bits[32] = { " VME", " PVI", " TSD", " DE", " PSE", " PAE", " MCE", " PGE",
625 " PCE", " OSFXSR", " OSXMMEXCPT", NULL, NULL, NULL, NULL, NULL,
626 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
627 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL };
628
629 Cr0 = KdbCurrentTrapFrame->Cr0;
630 Cr2 = KdbCurrentTrapFrame->Cr2;
631 Cr3 = KdbCurrentTrapFrame->Cr3;
632 Cr4 = KdbCurrentTrapFrame->Cr4;
633
634 /* Get descriptor table regs */
635 Ke386GetGlobalDescriptorTable(*(PKDESCRIPTOR)&Gdtr.Limit);
636 Ke386GetLocalDescriptorTable(Ldtr.Limit);
637 Ke386GetInterruptDescriptorTable(*(PKDESCRIPTOR)&Idtr.Limit);
638
639 /* Get the task register */
640 Ke386GetTr(Tr);
641
642 /* Display the control registers */
643 KdbpPrint("CR0 0x%08x ", Cr0);
644 for (i = 0; i < 32; i++)
645 {
646 if (Cr0Bits[i] == NULL)
647 continue;
648 if ((Cr0 & (1 << i)) != 0)
649 KdbpPrint(Cr0Bits[i]);
650 }
651 KdbpPrint("\nCR2 0x%08x\n", Cr2);
652 KdbpPrint("CR3 0x%08x Pagedir-Base 0x%08x %s%s\n", Cr3, (Cr3 & 0xfffff000),
653 (Cr3 & (1 << 3)) ? " PWT" : "", (Cr3 & (1 << 4)) ? " PCD" : "" );
654 KdbpPrint("CR4 0x%08x ", Cr4);
655 for (i = 0; i < 32; i++)
656 {
657 if (Cr4Bits[i] == NULL)
658 continue;
659 if ((Cr4 & (1 << i)) != 0)
660 KdbpPrint(Cr4Bits[i]);
661 }
662
663 /* Display the descriptor table regs */
664 KdbpPrint("\nGDTR Base 0x%08x Size 0x%04x\n", Gdtr.Base, Gdtr.Limit);
665 KdbpPrint("LDTR Base 0x%08x Size 0x%04x\n", Ldtr.Base, Ldtr.Limit);
666 KdbpPrint("IDTR Base 0x%08x Size 0x%04x\n", Idtr.Base, Idtr.Limit);
667 }
668 else if (Argv[0][0] == 's') /* sregs */
669 {
670 KdbpPrint("CS 0x%04x Index 0x%04x %cDT RPL%d\n",
671 Tf->SegCs & 0xffff, (Tf->SegCs & 0xffff) >> 3,
672 (Tf->SegCs & (1 << 2)) ? 'L' : 'G', Tf->SegCs & 3);
673 KdbpPrint("DS 0x%04x Index 0x%04x %cDT RPL%d\n",
674 Tf->SegDs, Tf->SegDs >> 3, (Tf->SegDs & (1 << 2)) ? 'L' : 'G', Tf->SegDs & 3);
675 KdbpPrint("ES 0x%04x Index 0x%04x %cDT RPL%d\n",
676 Tf->SegEs, Tf->SegEs >> 3, (Tf->SegEs & (1 << 2)) ? 'L' : 'G', Tf->SegEs & 3);
677 KdbpPrint("FS 0x%04x Index 0x%04x %cDT RPL%d\n",
678 Tf->SegFs, Tf->SegFs >> 3, (Tf->SegFs & (1 << 2)) ? 'L' : 'G', Tf->SegFs & 3);
679 KdbpPrint("GS 0x%04x Index 0x%04x %cDT RPL%d\n",
680 Tf->SegGs, Tf->SegGs >> 3, (Tf->SegGs & (1 << 2)) ? 'L' : 'G', Tf->SegGs & 3);
681 KdbpPrint("SS 0x%04x Index 0x%04x %cDT RPL%d\n",
682 Tf->HardwareSegSs, Tf->HardwareSegSs >> 3, (Tf->HardwareSegSs & (1 << 2)) ? 'L' : 'G', Tf->HardwareSegSs & 3);
683 }
684 else /* dregs */
685 {
686 ASSERT(Argv[0][0] == 'd');
687 KdbpPrint("DR0 0x%08x\n"
688 "DR1 0x%08x\n"
689 "DR2 0x%08x\n"
690 "DR3 0x%08x\n"
691 "DR6 0x%08x\n"
692 "DR7 0x%08x\n",
693 Tf->Dr0, Tf->Dr1, Tf->Dr2, Tf->Dr3,
694 Tf->Dr6, Tf->Dr7);
695 }
696 return TRUE;
697 }
698
699 /*!\brief Displays a backtrace.
700 */
701 STATIC BOOLEAN
702 KdbpCmdBackTrace(ULONG Argc, PCHAR Argv[])
703 {
704 ULONG Count;
705 ULONG ul;
706 ULONGLONG Result = 0;
707 ULONG_PTR Frame = KdbCurrentTrapFrame->Tf.Ebp;
708 ULONG_PTR Address;
709
710 if (Argc >= 2)
711 {
712 /* Check for [L count] part */
713 ul = 0;
714 if (strcmp(Argv[Argc-2], "L") == 0)
715 {
716 ul = strtoul(Argv[Argc-1], NULL, 0);
717 if (ul > 0)
718 {
719 Count = ul;
720 Argc -= 2;
721 }
722 }
723 else if (Argv[Argc-1][0] == 'L')
724 {
725 ul = strtoul(Argv[Argc-1] + 1, NULL, 0);
726 if (ul > 0)
727 {
728 Count = ul;
729 Argc--;
730 }
731 }
732
733 /* Put the remaining arguments back together */
734 Argc--;
735 for (ul = 1; ul < Argc; ul++)
736 {
737 Argv[ul][strlen(Argv[ul])] = ' ';
738 }
739 Argc++;
740 }
741
742 /* Check if frame addr or thread id is given. */
743 if (Argc > 1)
744 {
745 if (Argv[1][0] == '*')
746 {
747 Argv[1]++;
748 /* Evaluate the expression */
749 if (!KdbpEvaluateExpression(Argv[1], sizeof("kdb:> ")-1 + (Argv[1]-Argv[0]), &Result))
750 return TRUE;
751 if (Result > (ULONGLONG)(~((ULONG_PTR)0)))
752 KdbpPrint("Warning: Address %I64x is beeing truncated\n");
753 Frame = (ULONG_PTR)Result;
754 }
755 else
756 {
757
758 KdbpPrint("Thread backtrace not supported yet!\n");
759 return TRUE;
760 }
761 }
762 else
763 {
764 KdbpPrint("Eip:\n");
765 /* Try printing the function at EIP */
766 if (!KdbSymPrintAddress((PVOID)KdbCurrentTrapFrame->Tf.Eip))
767 KdbpPrint("<%08x>\n", KdbCurrentTrapFrame->Tf.Eip);
768 else
769 KdbpPrint("\n");
770 }
771
772 KdbpPrint("Frames:\n");
773 for (;;)
774 {
775 if (Frame == 0)
776 break;
777 if (!NT_SUCCESS(KdbpSafeReadMemory(&Address, (PVOID)(Frame + sizeof(ULONG_PTR)), sizeof (ULONG_PTR))))
778 {
779 KdbpPrint("Couldn't access memory at 0x%p!\n", Frame + sizeof(ULONG_PTR));
780 break;
781 }
782 if (!KdbSymPrintAddress((PVOID)Address))
783 KdbpPrint("<%08x>\n", Address);
784 else
785 KdbpPrint("\n");
786 if (Address == 0)
787 break;
788 if (!NT_SUCCESS(KdbpSafeReadMemory(&Frame, (PVOID)Frame, sizeof (ULONG_PTR))))
789 {
790 KdbpPrint("Couldn't access memory at 0x%p!\n", Frame);
791 break;
792 }
793 }
794
795 return TRUE;
796 }
797
798 /*!\brief Continues execution of the system/leaves KDB.
799 */
800 STATIC BOOLEAN
801 KdbpCmdContinue(ULONG Argc, PCHAR Argv[])
802 {
803 /* Exit the main loop */
804 return FALSE;
805 }
806
807 /*!\brief Continues execution of the system/leaves KDB.
808 */
809 STATIC BOOLEAN
810 KdbpCmdStep(ULONG Argc, PCHAR Argv[])
811 {
812 ULONG Count = 1;
813
814 if (Argc > 1)
815 {
816 Count = strtoul(Argv[1], NULL, 0);
817 if (Count == 0)
818 {
819 KdbpPrint("%s: Integer argument required\n", Argv[0]);
820 return TRUE;
821 }
822 }
823
824 if (Argv[0][0] == 'n')
825 KdbSingleStepOver = TRUE;
826 else
827 KdbSingleStepOver = FALSE;
828
829 /* Set the number of single steps and return to the interrupted code. */
830 KdbNumSingleSteps = Count;
831
832 return FALSE;
833 }
834
835 /*!\brief Lists breakpoints.
836 */
837 STATIC BOOLEAN
838 KdbpCmdBreakPointList(ULONG Argc, PCHAR Argv[])
839 {
840 LONG l;
841 ULONG_PTR Address = 0;
842 KDB_BREAKPOINT_TYPE Type = 0;
843 KDB_ACCESS_TYPE AccessType = 0;
844 UCHAR Size = 0;
845 UCHAR DebugReg = 0;
846 BOOLEAN Enabled = FALSE;
847 BOOLEAN Global = FALSE;
848 PEPROCESS Process = NULL;
849 PCHAR str1, str2, ConditionExpr, GlobalOrLocal;
850 CHAR Buffer[20];
851
852 l = KdbpGetNextBreakPointNr(0);
853 if (l < 0)
854 {
855 KdbpPrint("No breakpoints.\n");
856 return TRUE;
857 }
858
859 KdbpPrint("Breakpoints:\n");
860 do
861 {
862 if (!KdbpGetBreakPointInfo(l, &Address, &Type, &Size, &AccessType, &DebugReg,
863 &Enabled, &Global, &Process, &ConditionExpr))
864 {
865 continue;
866 }
867
868 if (l == KdbLastBreakPointNr)
869 {
870 str1 = "\x1b[1m*";
871 str2 = "\x1b[0m";
872 }
873 else
874 {
875 str1 = " ";
876 str2 = "";
877 }
878
879 if (Global)
880 GlobalOrLocal = " global";
881 else
882 {
883 GlobalOrLocal = Buffer;
884 sprintf(Buffer, " PID 0x%08lx",
885 (ULONG)(Process ? Process->UniqueProcessId : INVALID_HANDLE_VALUE));
886 }
887
888 if (Type == KdbBreakPointSoftware || Type == KdbBreakPointTemporary)
889 {
890 KdbpPrint(" %s%03d BPX 0x%08x%s%s%s%s%s\n",
891 str1, l, Address,
892 Enabled ? "" : " disabled",
893 GlobalOrLocal,
894 ConditionExpr ? " IF " : "",
895 ConditionExpr ? ConditionExpr : "",
896 str2);
897 }
898 else if (Type == KdbBreakPointHardware)
899 {
900 if (!Enabled)
901 {
902 KdbpPrint(" %s%03d BPM 0x%08x %-5s %-5s disabled%s%s%s%s\n", str1, l, Address,
903 KDB_ACCESS_TYPE_TO_STRING(AccessType),
904 Size == 1 ? "byte" : (Size == 2 ? "word" : "dword"),
905 GlobalOrLocal,
906 ConditionExpr ? " IF " : "",
907 ConditionExpr ? ConditionExpr : "",
908 str2);
909 }
910 else
911 {
912 KdbpPrint(" %s%03d BPM 0x%08x %-5s %-5s DR%d%s%s%s%s\n", str1, l, Address,
913 KDB_ACCESS_TYPE_TO_STRING(AccessType),
914 Size == 1 ? "byte" : (Size == 2 ? "word" : "dword"),
915 DebugReg,
916 GlobalOrLocal,
917 ConditionExpr ? " IF " : "",
918 ConditionExpr ? ConditionExpr : "",
919 str2);
920 }
921 }
922 }
923 while ((l = KdbpGetNextBreakPointNr(l+1)) >= 0);
924
925 return TRUE;
926 }
927
928 /*!\brief Enables, disables or clears a breakpoint.
929 */
930 STATIC BOOLEAN
931 KdbpCmdEnableDisableClearBreakPoint(ULONG Argc, PCHAR Argv[])
932 {
933 PCHAR pend;
934 ULONG BreakPointNr;
935
936 if (Argc < 2)
937 {
938 KdbpPrint("%s: argument required\n", Argv[0]);
939 return TRUE;
940 }
941
942 pend = Argv[1];
943 BreakPointNr = strtoul(Argv[1], &pend, 0);
944 if (pend == Argv[1] || *pend != '\0')
945 {
946 KdbpPrint("%s: integer argument required\n", Argv[0]);
947 return TRUE;
948 }
949
950 if (Argv[0][1] == 'e') /* enable */
951 {
952 KdbpEnableBreakPoint(BreakPointNr, NULL);
953 }
954 else if (Argv [0][1] == 'd') /* disable */
955 {
956 KdbpDisableBreakPoint(BreakPointNr, NULL);
957 }
958 else /* clear */
959 {
960 ASSERT(Argv[0][1] == 'c');
961 KdbpDeleteBreakPoint(BreakPointNr, NULL);
962 }
963
964 return TRUE;
965 }
966
967 /*!\brief Sets a software or hardware (memory) breakpoint at the given address.
968 */
969 STATIC BOOLEAN
970 KdbpCmdBreakPoint(ULONG Argc, PCHAR Argv[])
971 {
972 ULONGLONG Result = 0;
973 ULONG_PTR Address;
974 KDB_BREAKPOINT_TYPE Type;
975 UCHAR Size = 0;
976 KDB_ACCESS_TYPE AccessType = 0;
977 ULONG AddressArgIndex, i;
978 LONG ConditionArgIndex;
979 BOOLEAN Global = TRUE;
980
981 if (Argv[0][2] == 'x') /* software breakpoint */
982 {
983 if (Argc < 2)
984 {
985 KdbpPrint("bpx: Address argument required.\n");
986 return TRUE;
987 }
988
989 AddressArgIndex = 1;
990 Type = KdbBreakPointSoftware;
991 }
992 else /* memory breakpoint */
993 {
994 ASSERT(Argv[0][2] == 'm');
995
996 if (Argc < 2)
997 {
998 KdbpPrint("bpm: Access type argument required (one of r, w, rw, x)\n");
999 return TRUE;
1000 }
1001
1002 if (_stricmp(Argv[1], "x") == 0)
1003 AccessType = KdbAccessExec;
1004 else if (_stricmp(Argv[1], "r") == 0)
1005 AccessType = KdbAccessRead;
1006 else if (_stricmp(Argv[1], "w") == 0)
1007 AccessType = KdbAccessWrite;
1008 else if (_stricmp(Argv[1], "rw") == 0)
1009 AccessType = KdbAccessReadWrite;
1010 else
1011 {
1012 KdbpPrint("bpm: Unknown access type '%s'\n", Argv[1]);
1013 return TRUE;
1014 }
1015
1016 if (Argc < 3)
1017 {
1018 KdbpPrint("bpm: %s argument required.\n", AccessType == KdbAccessExec ? "Address" : "Memory size");
1019 return TRUE;
1020 }
1021 AddressArgIndex = 3;
1022 if (_stricmp(Argv[2], "byte") == 0)
1023 Size = 1;
1024 else if (_stricmp(Argv[2], "word") == 0)
1025 Size = 2;
1026 else if (_stricmp(Argv[2], "dword") == 0)
1027 Size = 4;
1028 else if (AccessType == KdbAccessExec)
1029 {
1030 Size = 1;
1031 AddressArgIndex--;
1032 }
1033 else
1034 {
1035 KdbpPrint("bpm: Unknown memory size '%s'\n", Argv[2]);
1036 return TRUE;
1037 }
1038
1039 if (Argc <= AddressArgIndex)
1040 {
1041 KdbpPrint("bpm: Address argument required.\n");
1042 return TRUE;
1043 }
1044
1045 Type = KdbBreakPointHardware;
1046 }
1047
1048 /* Put the arguments back together */
1049 ConditionArgIndex = -1;
1050 for (i = AddressArgIndex; i < (Argc-1); i++)
1051 {
1052 if (strcmp(Argv[i+1], "IF") == 0) /* IF found */
1053 {
1054 ConditionArgIndex = i + 2;
1055 if (ConditionArgIndex >= Argc)
1056 {
1057 KdbpPrint("%s: IF requires condition expression.\n", Argv[0]);
1058 return TRUE;
1059 }
1060 for (i = ConditionArgIndex; i < (Argc-1); i++)
1061 Argv[i][strlen(Argv[i])] = ' ';
1062 break;
1063 }
1064 Argv[i][strlen(Argv[i])] = ' ';
1065 }
1066
1067 /* Evaluate the address expression */
1068 if (!KdbpEvaluateExpression(Argv[AddressArgIndex],
1069 sizeof("kdb:> ")-1 + (Argv[AddressArgIndex]-Argv[0]),
1070 &Result))
1071 {
1072 return TRUE;
1073 }
1074 if (Result > (ULONGLONG)(~((ULONG_PTR)0)))
1075 KdbpPrint("%s: Warning: Address %I64x is beeing truncated\n", Argv[0]);
1076 Address = (ULONG_PTR)Result;
1077
1078 KdbpInsertBreakPoint(Address, Type, Size, AccessType,
1079 (ConditionArgIndex < 0) ? NULL : Argv[ConditionArgIndex],
1080 Global, NULL);
1081
1082 return TRUE;
1083 }
1084
1085 /*!\brief Lists threads or switches to another thread context.
1086 */
1087 STATIC BOOLEAN
1088 KdbpCmdThread(ULONG Argc, PCHAR Argv[])
1089 {
1090 PLIST_ENTRY Entry;
1091 PETHREAD Thread = NULL;
1092 PEPROCESS Process = NULL;
1093 PULONG Esp;
1094 PULONG Ebp;
1095 ULONG Eip;
1096 ULONG ul = 0;
1097 PCHAR State, pend, str1, str2;
1098 STATIC CONST PCHAR ThreadStateToString[DeferredReady+1] =
1099 { "Initialized", "Ready", "Running",
1100 "Standby", "Terminated", "Waiting",
1101 "Transition", "DeferredReady" };
1102 ASSERT(KdbCurrentProcess != NULL);
1103
1104 if (Argc >= 2 && _stricmp(Argv[1], "list") == 0)
1105 {
1106 Process = KdbCurrentProcess;
1107
1108 if (Argc >= 3)
1109 {
1110 ul = strtoul(Argv[2], &pend, 0);
1111 if (Argv[2] == pend)
1112 {
1113 KdbpPrint("thread: '%s' is not a valid process id!\n", Argv[2]);
1114 return TRUE;
1115 }
1116 if (!NT_SUCCESS(PsLookupProcessByProcessId((PVOID)ul, &Process)))
1117 {
1118 KdbpPrint("thread: Invalid process id!\n");
1119 return TRUE;
1120 }
1121 }
1122
1123 Entry = Process->ThreadListHead.Flink;
1124 if (Entry == &Process->ThreadListHead)
1125 {
1126 if (Argc >= 3)
1127 KdbpPrint("No threads in process 0x%08x!\n", ul);
1128 else
1129 KdbpPrint("No threads in current process!\n");
1130 return TRUE;
1131 }
1132
1133 KdbpPrint(" TID State Prior. Affinity EBP EIP\n");
1134 do
1135 {
1136 Thread = CONTAINING_RECORD(Entry, ETHREAD, ThreadListEntry);
1137
1138 if (Thread == KdbCurrentThread)
1139 {
1140 str1 = "\x1b[1m*";
1141 str2 = "\x1b[0m";
1142 }
1143 else
1144 {
1145 str1 = " ";
1146 str2 = "";
1147 }
1148
1149 if (Thread->Tcb.TrapFrame != NULL)
1150 {
1151 if (Thread->Tcb.TrapFrame->PreviousPreviousMode == KernelMode)
1152 Esp = (PULONG)Thread->Tcb.TrapFrame->TempEsp;
1153 else
1154 Esp = (PULONG)Thread->Tcb.TrapFrame->HardwareEsp;
1155 Ebp = (PULONG)Thread->Tcb.TrapFrame->Ebp;
1156 Eip = Thread->Tcb.TrapFrame->Eip;
1157 }
1158 else
1159 {
1160 Esp = (PULONG)Thread->Tcb.KernelStack;
1161 Ebp = (PULONG)Esp[4];
1162 Eip = 0;
1163 if (Ebp != NULL) /* FIXME: Should we attach to the process to read Ebp[1]? */
1164 KdbpSafeReadMemory(&Eip, Ebp + 1, sizeof (Eip));
1165 }
1166 if (Thread->Tcb.State < (DeferredReady + 1))
1167 State = ThreadStateToString[Thread->Tcb.State];
1168 else
1169 State = "Unknown";
1170
1171 KdbpPrint(" %s0x%08x %-11s %3d 0x%08x 0x%08x 0x%08x%s\n",
1172 str1,
1173 Thread->Cid.UniqueThread,
1174 State,
1175 Thread->Tcb.Priority,
1176 Thread->Tcb.Affinity,
1177 Ebp,
1178 Eip,
1179 str2);
1180
1181 Entry = Entry->Flink;
1182 }
1183 while (Entry != &Process->ThreadListHead);
1184 }
1185 else if (Argc >= 2 && _stricmp(Argv[1], "attach") == 0)
1186 {
1187 if (Argc < 3)
1188 {
1189 KdbpPrint("thread attach: thread id argument required!\n");
1190 return TRUE;
1191 }
1192
1193 ul = strtoul(Argv[2], &pend, 0);
1194 if (Argv[2] == pend)
1195 {
1196 KdbpPrint("thread attach: '%s' is not a valid thread id!\n", Argv[2]);
1197 return TRUE;
1198 }
1199 if (!KdbpAttachToThread((PVOID)ul))
1200 {
1201 return TRUE;
1202 }
1203 KdbpPrint("Attached to thread 0x%08x.\n", ul);
1204 }
1205 else
1206 {
1207 Thread = KdbCurrentThread;
1208
1209 if (Argc >= 2)
1210 {
1211 ul = strtoul(Argv[1], &pend, 0);
1212 if (Argv[1] == pend)
1213 {
1214 KdbpPrint("thread: '%s' is not a valid thread id!\n", Argv[1]);
1215 return TRUE;
1216 }
1217 if (!NT_SUCCESS(PsLookupThreadByThreadId((PVOID)ul, &Thread)))
1218 {
1219 KdbpPrint("thread: Invalid thread id!\n");
1220 return TRUE;
1221 }
1222 }
1223
1224 if (Thread->Tcb.State < (DeferredReady + 1))
1225 State = ThreadStateToString[Thread->Tcb.State];
1226 else
1227 State = "Unknown";
1228 KdbpPrint("%s"
1229 " TID: 0x%08x\n"
1230 " State: %s (0x%x)\n"
1231 " Priority: %d\n"
1232 " Affinity: 0x%08x\n"
1233 " Initial Stack: 0x%08x\n"
1234 " Stack Limit: 0x%08x\n"
1235 " Stack Base: 0x%08x\n"
1236 " Kernel Stack: 0x%08x\n"
1237 " Trap Frame: 0x%08x\n"
1238 " NPX State: %s (0x%x)\n",
1239 (Argc < 2) ? "Current Thread:\n" : "",
1240 Thread->Cid.UniqueThread,
1241 State, Thread->Tcb.State,
1242 Thread->Tcb.Priority,
1243 Thread->Tcb.Affinity,
1244 Thread->Tcb.InitialStack,
1245 Thread->Tcb.StackLimit,
1246 Thread->Tcb.StackBase,
1247 Thread->Tcb.KernelStack,
1248 Thread->Tcb.TrapFrame,
1249 NPX_STATE_TO_STRING(Thread->Tcb.NpxState), Thread->Tcb.NpxState);
1250
1251 }
1252
1253 return TRUE;
1254 }
1255
1256 /*!\brief Lists processes or switches to another process context.
1257 */
1258 STATIC BOOLEAN
1259 KdbpCmdProc(ULONG Argc, PCHAR Argv[])
1260 {
1261 PLIST_ENTRY Entry;
1262 PEPROCESS Process;
1263 PCHAR State, pend, str1, str2;
1264 ULONG ul;
1265 extern LIST_ENTRY PsActiveProcessHead;
1266
1267 if (Argc >= 2 && _stricmp(Argv[1], "list") == 0)
1268 {
1269 Entry = PsActiveProcessHead.Flink;
1270 if (!Entry || Entry == &PsActiveProcessHead)
1271 {
1272 KdbpPrint("No processes in the system!\n");
1273 return TRUE;
1274 }
1275
1276 KdbpPrint(" PID State Filename\n");
1277 do
1278 {
1279 Process = CONTAINING_RECORD(Entry, EPROCESS, ActiveProcessLinks);
1280
1281 if (Process == KdbCurrentProcess)
1282 {
1283 str1 = "\x1b[1m*";
1284 str2 = "\x1b[0m";
1285 }
1286 else
1287 {
1288 str1 = " ";
1289 str2 = "";
1290 }
1291
1292 State = ((Process->Pcb.State == ProcessInMemory) ? "In Memory" :
1293 ((Process->Pcb.State == ProcessOutOfMemory) ? "Out of Memory" : "In Transition"));
1294
1295 KdbpPrint(" %s0x%08x %-10s %s%s\n",
1296 str1,
1297 Process->UniqueProcessId,
1298 State,
1299 Process->ImageFileName,
1300 str2);
1301
1302 Entry = Entry->Flink;
1303 }
1304 while(Entry != &PsActiveProcessHead);
1305 }
1306 else if (Argc >= 2 && _stricmp(Argv[1], "attach") == 0)
1307 {
1308 if (Argc < 3)
1309 {
1310 KdbpPrint("process attach: process id argument required!\n");
1311 return TRUE;
1312 }
1313
1314 ul = strtoul(Argv[2], &pend, 0);
1315 if (Argv[2] == pend)
1316 {
1317 KdbpPrint("process attach: '%s' is not a valid process id!\n", Argv[2]);
1318 return TRUE;
1319 }
1320 if (!KdbpAttachToProcess((PVOID)ul))
1321 {
1322 return TRUE;
1323 }
1324 KdbpPrint("Attached to process 0x%08x, thread 0x%08x.\n", (ULONG)ul,
1325 (ULONG)KdbCurrentThread->Cid.UniqueThread);
1326 }
1327 else
1328 {
1329 Process = KdbCurrentProcess;
1330
1331 if (Argc >= 2)
1332 {
1333 ul = strtoul(Argv[1], &pend, 0);
1334 if (Argv[1] == pend)
1335 {
1336 KdbpPrint("proc: '%s' is not a valid process id!\n", Argv[1]);
1337 return TRUE;
1338 }
1339 if (!NT_SUCCESS(PsLookupProcessByProcessId((PVOID)ul, &Process)))
1340 {
1341 KdbpPrint("proc: Invalid process id!\n");
1342 return TRUE;
1343 }
1344 }
1345
1346 State = ((Process->Pcb.State == ProcessInMemory) ? "In Memory" :
1347 ((Process->Pcb.State == ProcessOutOfMemory) ? "Out of Memory" : "In Transition"));
1348 KdbpPrint("%s"
1349 " PID: 0x%08x\n"
1350 " State: %s (0x%x)\n"
1351 " Image Filename: %s\n",
1352 (Argc < 2) ? "Current process:\n" : "",
1353 Process->UniqueProcessId,
1354 State, Process->Pcb.State,
1355 Process->ImageFileName);
1356 }
1357
1358 return TRUE;
1359 }
1360
1361 /*!\brief Lists loaded modules or the one containing the specified address.
1362 */
1363 STATIC BOOLEAN
1364 KdbpCmdMod(ULONG Argc, PCHAR Argv[])
1365 {
1366 ULONGLONG Result = 0;
1367 ULONG_PTR Address;
1368 KDB_MODULE_INFO Info;
1369 BOOLEAN DisplayOnlyOneModule = FALSE;
1370 INT i = 0;
1371
1372 if (Argc >= 2)
1373 {
1374 /* Put the arguments back together */
1375 Argc--;
1376 while (--Argc >= 1)
1377 Argv[Argc][strlen(Argv[Argc])] = ' ';
1378
1379 /* Evaluate the expression */
1380 if (!KdbpEvaluateExpression(Argv[1], sizeof("kdb:> ")-1 + (Argv[1]-Argv[0]), &Result))
1381 {
1382 return TRUE;
1383 }
1384 if (Result > (ULONGLONG)(~((ULONG_PTR)0)))
1385 KdbpPrint("%s: Warning: Address %I64x is beeing truncated\n", Argv[0]);
1386 Address = (ULONG_PTR)Result;
1387
1388 if (!KdbpSymFindModuleByAddress((PVOID)Address, &Info))
1389 {
1390 KdbpPrint("No module containing address 0x%p found!\n", Address);
1391 return TRUE;
1392 }
1393 DisplayOnlyOneModule = TRUE;
1394 }
1395 else
1396 {
1397 if (!KdbpSymFindModuleByIndex(0, &Info))
1398 {
1399 ULONG_PTR ntoskrnlBase = ((ULONG_PTR)KdbpCmdMod) & 0xfff00000;
1400 KdbpPrint(" Base Size Name\n");
1401 KdbpPrint(" %08x %08x %s\n", ntoskrnlBase, 0, "ntoskrnl.exe");
1402 return TRUE;
1403 }
1404 i = 1;
1405 }
1406
1407 KdbpPrint(" Base Size Name\n");
1408 for (;;)
1409 {
1410 KdbpPrint(" %08x %08x %ws\n", Info.Base, Info.Size, Info.Name);
1411
1412 if ((!DisplayOnlyOneModule && !KdbpSymFindModuleByIndex(i++, &Info)) ||
1413 DisplayOnlyOneModule)
1414 {
1415 break;
1416 }
1417 }
1418
1419 return TRUE;
1420 }
1421
1422 /*!\brief Displays GDT, LDT or IDTd.
1423 */
1424 STATIC BOOLEAN
1425 KdbpCmdGdtLdtIdt(ULONG Argc, PCHAR Argv[])
1426 {
1427 KDESCRIPTOR Reg = {0};
1428 ULONG SegDesc[2];
1429 ULONG SegBase;
1430 ULONG SegLimit;
1431 PCHAR SegType;
1432 USHORT SegSel;
1433 UCHAR Type, Dpl;
1434 INT i;
1435 ULONG ul;
1436
1437 if (Argv[0][0] == 'i')
1438 {
1439 /* Read IDTR */
1440 Ke386GetInterruptDescriptorTable(*(PKDESCRIPTOR)&Reg.Limit);
1441
1442 if (Reg.Limit < 7)
1443 {
1444 KdbpPrint("Interrupt descriptor table is empty.\n");
1445 return TRUE;
1446 }
1447 KdbpPrint("IDT Base: 0x%08x Limit: 0x%04x\n", Reg.Base, Reg.Limit);
1448 KdbpPrint(" Idx Type Seg. Sel. Offset DPL\n");
1449 for (i = 0; (i + sizeof(SegDesc) - 1) <= Reg.Limit; i += 8)
1450 {
1451 if (!NT_SUCCESS(KdbpSafeReadMemory(SegDesc, (PVOID)(Reg.Base + i), sizeof(SegDesc))))
1452 {
1453 KdbpPrint("Couldn't access memory at 0x%08x!\n", Reg.Base + i);
1454 return TRUE;
1455 }
1456
1457 Dpl = ((SegDesc[1] >> 13) & 3);
1458 if ((SegDesc[1] & 0x1f00) == 0x0500) /* Task gate */
1459 SegType = "TASKGATE";
1460 else if ((SegDesc[1] & 0x1fe0) == 0x0e00) /* 32 bit Interrupt gate */
1461 SegType = "INTGATE32";
1462 else if ((SegDesc[1] & 0x1fe0) == 0x0600) /* 16 bit Interrupt gate */
1463 SegType = "INTGATE16";
1464 else if ((SegDesc[1] & 0x1fe0) == 0x0f00) /* 32 bit Trap gate */
1465 SegType = "TRAPGATE32";
1466 else if ((SegDesc[1] & 0x1fe0) == 0x0700) /* 16 bit Trap gate */
1467 SegType = "TRAPGATE16";
1468 else
1469 SegType = "UNKNOWN";
1470
1471 if ((SegDesc[1] & (1 << 15)) == 0) /* not present */
1472 {
1473 KdbpPrint(" %03d %-10s [NP] [NP] %02d\n",
1474 i / 8, SegType, Dpl);
1475 }
1476 else if ((SegDesc[1] & 0x1f00) == 0x0500) /* Task gate */
1477 {
1478 SegSel = SegDesc[0] >> 16;
1479 KdbpPrint(" %03d %-10s 0x%04x %02d\n",
1480 i / 8, SegType, SegSel, Dpl);
1481 }
1482 else
1483 {
1484 SegSel = SegDesc[0] >> 16;
1485 SegBase = (SegDesc[1] & 0xffff0000) | (SegDesc[0] & 0x0000ffff);
1486 KdbpPrint(" %03d %-10s 0x%04x 0x%08x %02d\n",
1487 i / 8, SegType, SegSel, SegBase, Dpl);
1488 }
1489 }
1490 }
1491 else
1492 {
1493 ul = 0;
1494 if (Argv[0][0] == 'g')
1495 {
1496 /* Read GDTR */
1497 Ke386GetGlobalDescriptorTable(*(PKDESCRIPTOR)&Reg.Limit);
1498 i = 8;
1499 }
1500 else
1501 {
1502 ASSERT(Argv[0][0] == 'l');
1503 /* Read LDTR */
1504 Ke386GetLocalDescriptorTable(Reg.Limit);
1505 i = 0;
1506 ul = 1 << 2;
1507 }
1508
1509 if (Reg.Limit < 7)
1510 {
1511 KdbpPrint("%s descriptor table is empty.\n",
1512 Argv[0][0] == 'g' ? "Global" : "Local");
1513 return TRUE;
1514 }
1515 KdbpPrint("%cDT Base: 0x%08x Limit: 0x%04x\n",
1516 Argv[0][0] == 'g' ? 'G' : 'L', Reg.Base, Reg.Limit);
1517 KdbpPrint(" Idx Sel. Type Base Limit DPL Attribs\n");
1518 for ( ; (i + sizeof(SegDesc) - 1) <= Reg.Limit; i += 8)
1519 {
1520 if (!NT_SUCCESS(KdbpSafeReadMemory(SegDesc, (PVOID)(Reg.Base + i), sizeof(SegDesc))))
1521 {
1522 KdbpPrint("Couldn't access memory at 0x%08x!\n", Reg.Base + i);
1523 return TRUE;
1524 }
1525 Dpl = ((SegDesc[1] >> 13) & 3);
1526 Type = ((SegDesc[1] >> 8) & 0xf);
1527
1528 SegBase = SegDesc[0] >> 16;
1529 SegBase |= (SegDesc[1] & 0xff) << 16;
1530 SegBase |= SegDesc[1] & 0xff000000;
1531 SegLimit = SegDesc[0] & 0x0000ffff;
1532 SegLimit |= (SegDesc[1] >> 16) & 0xf;
1533 if ((SegDesc[1] & (1 << 23)) != 0)
1534 {
1535 SegLimit *= 4096;
1536 SegLimit += 4095;
1537 }
1538 else
1539 {
1540 SegLimit++;
1541 }
1542
1543 if ((SegDesc[1] & (1 << 12)) == 0) /* System segment */
1544 {
1545 switch (Type)
1546 {
1547 case 1: SegType = "TSS16(Avl)"; break;
1548 case 2: SegType = "LDT"; break;
1549 case 3: SegType = "TSS16(Busy)"; break;
1550 case 4: SegType = "CALLGATE16"; break;
1551 case 5: SegType = "TASKGATE"; break;
1552 case 6: SegType = "INTGATE16"; break;
1553 case 7: SegType = "TRAPGATE16"; break;
1554 case 9: SegType = "TSS32(Avl)"; break;
1555 case 11: SegType = "TSS32(Busy)"; break;
1556 case 12: SegType = "CALLGATE32"; break;
1557 case 14: SegType = "INTGATE32"; break;
1558 case 15: SegType = "INTGATE32"; break;
1559 default: SegType = "UNKNOWN"; break;
1560 }
1561 if (!(Type >= 1 && Type <= 3) &&
1562 Type != 9 && Type != 11)
1563 {
1564 SegBase = 0;
1565 SegLimit = 0;
1566 }
1567 }
1568 else if ((SegDesc[1] & (1 << 11)) == 0) /* Data segment */
1569 {
1570 if ((SegDesc[1] & (1 << 22)) != 0)
1571 SegType = "DATA32";
1572 else
1573 SegType = "DATA16";
1574
1575 }
1576 else /* Code segment */
1577 {
1578 if ((SegDesc[1] & (1 << 22)) != 0)
1579 SegType = "CODE32";
1580 else
1581 SegType = "CODE16";
1582 }
1583
1584 if ((SegDesc[1] & (1 << 15)) == 0) /* not present */
1585 {
1586 KdbpPrint(" %03d 0x%04x %-11s [NP] [NP] %02d NP\n",
1587 i / 8, i | Dpl | ul, SegType, Dpl);
1588 }
1589 else
1590 {
1591 KdbpPrint(" %03d 0x%04x %-11s 0x%08x 0x%08x %02d ",
1592 i / 8, i | Dpl | ul, SegType, SegBase, SegLimit, Dpl);
1593 if ((SegDesc[1] & (1 << 12)) == 0) /* System segment */
1594 {
1595 /* FIXME: Display system segment */
1596 }
1597 else if ((SegDesc[1] & (1 << 11)) == 0) /* Data segment */
1598 {
1599 if ((SegDesc[1] & (1 << 10)) != 0) /* Expand-down */
1600 KdbpPrint(" E");
1601 KdbpPrint((SegDesc[1] & (1 << 9)) ? " R/W" : " R");
1602 if ((SegDesc[1] & (1 << 8)) != 0)
1603 KdbpPrint(" A");
1604 }
1605 else /* Code segment */
1606 {
1607 if ((SegDesc[1] & (1 << 10)) != 0) /* Conforming */
1608 KdbpPrint(" C");
1609 KdbpPrint((SegDesc[1] & (1 << 9)) ? " R/X" : " X");
1610 if ((SegDesc[1] & (1 << 8)) != 0)
1611 KdbpPrint(" A");
1612 }
1613 if ((SegDesc[1] & (1 << 20)) != 0)
1614 KdbpPrint(" AVL");
1615 KdbpPrint("\n");
1616 }
1617 }
1618 }
1619
1620 return TRUE;
1621 }
1622
1623 /*!\brief Displays the KPCR
1624 */
1625 STATIC BOOLEAN
1626 KdbpCmdPcr(ULONG Argc, PCHAR Argv[])
1627 {
1628 PKIPCR Pcr = (PKIPCR)KeGetPcr();
1629
1630 KdbpPrint("Current PCR is at 0x%08x.\n", (INT)Pcr);
1631 KdbpPrint(" Tib.ExceptionList: 0x%08x\n"
1632 " Tib.StackBase: 0x%08x\n"
1633 " Tib.StackLimit: 0x%08x\n"
1634 " Tib.SubSystemTib: 0x%08x\n"
1635 " Tib.FiberData/Version: 0x%08x\n"
1636 " Tib.ArbitraryUserPointer: 0x%08x\n"
1637 " Tib.Self: 0x%08x\n"
1638 " Self: 0x%08x\n"
1639 " PCRCB: 0x%08x\n"
1640 " Irql: 0x%02x\n"
1641 " IRR: 0x%08x\n"
1642 " IrrActive: 0x%08x\n"
1643 " IDR: 0x%08x\n"
1644 " KdVersionBlock: 0x%08x\n"
1645 " IDT: 0x%08x\n"
1646 " GDT: 0x%08x\n"
1647 " TSS: 0x%08x\n"
1648 " MajorVersion: 0x%04x\n"
1649 " MinorVersion: 0x%04x\n"
1650 " SetMember: 0x%08x\n"
1651 " StallScaleFactor: 0x%08x\n"
1652 " Number: 0x%02x\n"
1653 " L2CacheAssociativity: 0x%02x\n"
1654 " VdmAlert: 0x%08x\n"
1655 " L2CacheSize: 0x%08x\n"
1656 " InterruptMode: 0x%08x\n",
1657 Pcr->NtTib.ExceptionList, Pcr->NtTib.StackBase, Pcr->NtTib.StackLimit,
1658 Pcr->NtTib.SubSystemTib, Pcr->NtTib.FiberData, Pcr->NtTib.ArbitraryUserPointer,
1659 Pcr->NtTib.Self, Pcr->Self, Pcr->Prcb, Pcr->Irql, Pcr->IRR, Pcr->IrrActive,
1660 Pcr->IDR, Pcr->KdVersionBlock, Pcr->IDT, Pcr->GDT, Pcr->TSS,
1661 Pcr->MajorVersion, Pcr->MinorVersion, Pcr->SetMember, Pcr->StallScaleFactor,
1662 Pcr->Number, Pcr->L2CacheAssociativity,
1663 Pcr->VdmAlert, Pcr->SecondLevelCacheSize, Pcr->InterruptMode);
1664
1665 return TRUE;
1666 }
1667
1668 /*!\brief Displays the TSS
1669 */
1670 STATIC BOOLEAN
1671 KdbpCmdTss(ULONG Argc, PCHAR Argv[])
1672 {
1673 KTSS *Tss = KeGetPcr()->TSS;
1674
1675 KdbpPrint("Current TSS is at 0x%08x.\n", (INT)Tss);
1676 KdbpPrint(" Eip: 0x%08x\n"
1677 " Es: 0x%04x\n"
1678 " Cs: 0x%04x\n"
1679 " Ss: 0x%04x\n"
1680 " Ds: 0x%04x\n"
1681 " Fs: 0x%04x\n"
1682 " Gs: 0x%04x\n"
1683 " IoMapBase: 0x%04x\n",
1684 Tss->Eip, Tss->Es, Tss->Cs, Tss->Ds, Tss->Fs, Tss->Gs, Tss->IoMapBase);
1685 return TRUE;
1686 }
1687
1688 /*!\brief Bugchecks the system.
1689 */
1690 STATIC BOOLEAN
1691 KdbpCmdBugCheck(ULONG Argc, PCHAR Argv[])
1692 {
1693 /* Set the flag and quit looping */
1694 KdbpBugCheckRequested = TRUE;
1695 return FALSE;
1696 }
1697
1698 /*!\brief Sets or displays a config variables value.
1699 */
1700 STATIC BOOLEAN
1701 KdbpCmdSet(ULONG Argc, PCHAR Argv[])
1702 {
1703 LONG l;
1704 BOOLEAN First;
1705 PCHAR pend = 0;
1706 KDB_ENTER_CONDITION ConditionFirst = KdbDoNotEnter;
1707 KDB_ENTER_CONDITION ConditionLast = KdbDoNotEnter;
1708 STATIC CONST PCHAR ExceptionNames[21] =
1709 { "ZERODEVIDE", "DEBUGTRAP", "NMI", "INT3", "OVERFLOW", "BOUND", "INVALIDOP",
1710 "NOMATHCOP", "DOUBLEFAULT", "RESERVED(9)", "INVALIDTSS", "SEGMENTNOTPRESENT",
1711 "STACKFAULT", "GPF", "PAGEFAULT", "RESERVED(15)", "MATHFAULT", "ALIGNMENTCHECK",
1712 "MACHINECHECK", "SIMDFAULT", "OTHERS" };
1713
1714 if (Argc == 1)
1715 {
1716 KdbpPrint("Available settings:\n");
1717 KdbpPrint(" syntax [intel|at&t]\n");
1718 KdbpPrint(" condition [exception|*] [first|last] [never|always|kmode|umode]\n");
1719 KdbpPrint(" break_on_module_load [true|false]\n");
1720 }
1721 else if (strcmp(Argv[1], "syntax") == 0)
1722 {
1723 if (Argc == 2)
1724 KdbpPrint("syntax = %s\n", KdbUseIntelSyntax ? "intel" : "at&t");
1725 else if (Argc >= 3)
1726 {
1727 if (_stricmp(Argv[2], "intel") == 0)
1728 KdbUseIntelSyntax = TRUE;
1729 else if (_stricmp(Argv[2], "at&t") == 0)
1730 KdbUseIntelSyntax = FALSE;
1731 else
1732 KdbpPrint("Unknown syntax '%s'.\n", Argv[2]);
1733 }
1734 }
1735 else if (strcmp(Argv[1], "condition") == 0)
1736 {
1737 if (Argc == 2)
1738 {
1739 KdbpPrint("Conditions: (First) (Last)\n");
1740 for (l = 0; l < RTL_NUMBER_OF(ExceptionNames) - 1; l++)
1741 {
1742 if (ExceptionNames[l] == NULL)
1743 continue;
1744 if (!KdbpGetEnterCondition(l, TRUE, &ConditionFirst))
1745 ASSERT(0);
1746 if (!KdbpGetEnterCondition(l, FALSE, &ConditionLast))
1747 ASSERT(0);
1748 KdbpPrint(" #%02d %-20s %-8s %-8s\n", l, ExceptionNames[l],
1749 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst),
1750 KDB_ENTER_CONDITION_TO_STRING(ConditionLast));
1751 }
1752 ASSERT(l == (RTL_NUMBER_OF(ExceptionNames) - 1));
1753 KdbpPrint(" %-20s %-8s %-8s\n", ExceptionNames[l],
1754 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst),
1755 KDB_ENTER_CONDITION_TO_STRING(ConditionLast));
1756 }
1757 else
1758 {
1759 if (Argc >= 5 && strcmp(Argv[2], "*") == 0) /* Allow * only when setting condition */
1760 l = -1;
1761 else
1762 {
1763 l = strtoul(Argv[2], &pend, 0);
1764 if (Argv[2] == pend)
1765 {
1766 for (l = 0; l < RTL_NUMBER_OF(ExceptionNames); l++)
1767 {
1768 if (ExceptionNames[l] == NULL)
1769 continue;
1770 if (_stricmp(ExceptionNames[l], Argv[2]) == 0)
1771 break;
1772 }
1773 }
1774 if (l >= RTL_NUMBER_OF(ExceptionNames))
1775 {
1776 KdbpPrint("Unknown exception '%s'.\n", Argv[2]);
1777 return TRUE;
1778 }
1779 }
1780 if (Argc > 4)
1781 {
1782 if (_stricmp(Argv[3], "first") == 0)
1783 First = TRUE;
1784 else if (_stricmp(Argv[3], "last") == 0)
1785 First = FALSE;
1786 else
1787 {
1788 KdbpPrint("set condition: second argument must be 'first' or 'last'\n");
1789 return TRUE;
1790 }
1791 if (_stricmp(Argv[4], "never") == 0)
1792 ConditionFirst = KdbDoNotEnter;
1793 else if (_stricmp(Argv[4], "always") == 0)
1794 ConditionFirst = KdbEnterAlways;
1795 else if (_stricmp(Argv[4], "umode") == 0)
1796 ConditionFirst = KdbEnterFromUmode;
1797 else if (_stricmp(Argv[4], "kmode") == 0)
1798 ConditionFirst = KdbEnterFromKmode;
1799 else
1800 {
1801 KdbpPrint("set condition: third argument must be 'never', 'always', 'umode' or 'kmode'\n");
1802 return TRUE;
1803 }
1804 if (!KdbpSetEnterCondition(l, First, ConditionFirst))
1805 {
1806 if (l >= 0)
1807 KdbpPrint("Couldn't change condition for exception #%02d\n", l);
1808 else
1809 KdbpPrint("Couldn't change condition for all exceptions\n", l);
1810 }
1811 }
1812 else /* Argc >= 3 */
1813 {
1814 if (!KdbpGetEnterCondition(l, TRUE, &ConditionFirst))
1815 ASSERT(0);
1816 if (!KdbpGetEnterCondition(l, FALSE, &ConditionLast))
1817 ASSERT(0);
1818 if (l < (RTL_NUMBER_OF(ExceptionNames) - 1))
1819 {
1820 KdbpPrint("Condition for exception #%02d (%s): FirstChance %s LastChance %s\n",
1821 l, ExceptionNames[l],
1822 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst),
1823 KDB_ENTER_CONDITION_TO_STRING(ConditionLast));
1824 }
1825 else
1826 {
1827 KdbpPrint("Condition for all other exceptions: FirstChance %s LastChance %s\n",
1828 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst),
1829 KDB_ENTER_CONDITION_TO_STRING(ConditionLast));
1830 }
1831 }
1832 }
1833 }
1834 else if (strcmp(Argv[1], "break_on_module_load") == 0)
1835 {
1836 if (Argc == 2)
1837 KdbpPrint("break_on_module_load = %s\n", KdbBreakOnModuleLoad ? "enabled" : "disabled");
1838 else if (Argc >= 3)
1839 {
1840 if (_stricmp(Argv[2], "enable") == 0 || _stricmp(Argv[2], "enabled") == 0 ||
1841 _stricmp(Argv[2], "true") == 0)
1842 KdbBreakOnModuleLoad = TRUE;
1843 else if (_stricmp(Argv[2], "disable") == 0 || _stricmp(Argv[2], "disabled") == 0 ||
1844 _stricmp(Argv[2], "false") == 0)
1845 KdbBreakOnModuleLoad = FALSE;
1846 else
1847 KdbpPrint("Unknown setting '%s'.\n", Argv[2]);
1848 }
1849 }
1850 else
1851 KdbpPrint("Unknown setting '%s'.\n", Argv[1]);
1852
1853 return TRUE;
1854 }
1855
1856 /*!\brief Displays help screen.
1857 */
1858 STATIC BOOLEAN
1859 KdbpCmdHelp(ULONG Argc, PCHAR Argv[])
1860 {
1861 ULONG i;
1862
1863 KdbpPrint("Kernel debugger commands:\n");
1864 for (i = 0; i < RTL_NUMBER_OF(KdbDebuggerCommands); i++)
1865 {
1866 if (KdbDebuggerCommands[i].Syntax == NULL) /* Command group */
1867 {
1868 if (i > 0)
1869 KdbpPrint("\n");
1870 KdbpPrint("\x1b[7m* %s:\x1b[0m\n", KdbDebuggerCommands[i].Help);
1871 continue;
1872 }
1873
1874 KdbpPrint(" %-20s - %s\n",
1875 KdbDebuggerCommands[i].Syntax,
1876 KdbDebuggerCommands[i].Help);
1877 }
1878
1879 return TRUE;
1880 }
1881
1882 /*!\brief Prints the given string with printf-like formatting.
1883 *
1884 * \param Format Format of the string/arguments.
1885 * \param ... Variable number of arguments matching the format specified in \a Format.
1886 *
1887 * \note Doesn't correctly handle \\t and terminal escape sequences when calculating the
1888 * number of lines required to print a single line from the Buffer in the terminal.
1889 */
1890 VOID
1891 KdbpPrint(
1892 IN PCHAR Format,
1893 IN ... OPTIONAL)
1894 {
1895 STATIC CHAR Buffer[4096];
1896 STATIC BOOLEAN TerminalInitialized = FALSE;
1897 STATIC BOOLEAN TerminalConnected = FALSE;
1898 STATIC BOOLEAN TerminalReportsSize = TRUE;
1899 CHAR c = '\0';
1900 PCHAR p, p2;
1901 ULONG Length;
1902 ULONG i, j;
1903 LONG RowsPrintedByTerminal;
1904 ULONG ScanCode;
1905 va_list ap;
1906
1907 /* Check if the user has aborted output of the current command */
1908 if (KdbOutputAborted)
1909 return;
1910
1911 /* Initialize the terminal */
1912 if (!TerminalInitialized)
1913 {
1914 DbgPrint("\x1b[7h"); /* Enable linewrap */
1915
1916 /* Query terminal type */
1917 /*DbgPrint("\x1b[Z");*/
1918 DbgPrint("\x05");
1919
1920 TerminalInitialized = TRUE;
1921 Length = 0;
1922 KeStallExecutionProcessor(100000);
1923
1924 for (;;)
1925 {
1926 c = KdbpTryGetCharSerial(5000);
1927 if (c == -1)
1928 break;
1929 Buffer[Length++] = c;
1930 if (Length >= (sizeof (Buffer) - 1))
1931 break;
1932 }
1933 Buffer[Length] = '\0';
1934 if (Length > 0)
1935 TerminalConnected = TRUE;
1936 }
1937
1938 /* Get number of rows and columns in terminal */
1939 if ((KdbNumberOfRowsTerminal < 0) || (KdbNumberOfColsTerminal < 0) ||
1940 (KdbNumberOfRowsPrinted) == 0) /* Refresh terminal size each time when number of rows printed is 0 */
1941 {
1942 if ((KdbDebugState & KD_DEBUG_KDSERIAL) && TerminalConnected && TerminalReportsSize)
1943 {
1944 /* Try to query number of rows from terminal. A reply looks like "\x1b[8;24;80t" */
1945 TerminalReportsSize = FALSE;
1946 KeStallExecutionProcessor(100000);
1947 DbgPrint("\x1b[18t");
1948 c = KdbpTryGetCharSerial(5000);
1949 if (c == KEY_ESC)
1950 {
1951 c = KdbpTryGetCharSerial(5000);
1952 if (c == '[')
1953 {
1954 Length = 0;
1955 for (;;)
1956 {
1957 c = KdbpTryGetCharSerial(5000);
1958 if (c == -1)
1959 break;
1960 Buffer[Length++] = c;
1961 if (isalpha(c) || Length >= (sizeof (Buffer) - 1))
1962 break;
1963 }
1964 Buffer[Length] = '\0';
1965 if (Buffer[0] == '8' && Buffer[1] == ';')
1966 {
1967 for (i = 2; (i < Length) && (Buffer[i] != ';'); i++);
1968 if (Buffer[i] == ';')
1969 {
1970 Buffer[i++] = '\0';
1971 /* Number of rows is now at Buffer + 2 and number of cols at Buffer + i */
1972 KdbNumberOfRowsTerminal = strtoul(Buffer + 2, NULL, 0);
1973 KdbNumberOfColsTerminal = strtoul(Buffer + i, NULL, 0);
1974 TerminalReportsSize = TRUE;
1975 }
1976 }
1977 }
1978 /* Clear further characters */
1979 while ((c = KdbpTryGetCharSerial(5000)) != -1);
1980 }
1981 }
1982
1983 if (KdbNumberOfRowsTerminal <= 0)
1984 {
1985 /* Set number of rows to the default. */
1986 KdbNumberOfRowsTerminal = 24;
1987 }
1988 else if (KdbNumberOfColsTerminal <= 0)
1989 {
1990 /* Set number of cols to the default. */
1991 KdbNumberOfColsTerminal = 80;
1992 }
1993 }
1994
1995 /* Get the string */
1996 va_start(ap, Format);
1997 Length = _vsnprintf(Buffer, sizeof (Buffer) - 1, Format, ap);
1998 Buffer[Length] = '\0';
1999 va_end(ap);
2000
2001 p = Buffer;
2002 while (p[0] != '\0')
2003 {
2004 i = strcspn(p, "\n");
2005
2006 /* Calculate the number of lines which will be printed in the terminal
2007 * when outputting the current line
2008 */
2009 if (i > 0)
2010 RowsPrintedByTerminal = (i + KdbNumberOfColsPrinted - 1) / KdbNumberOfColsTerminal;
2011 else
2012 RowsPrintedByTerminal = 0;
2013 if (p[i] == '\n')
2014 RowsPrintedByTerminal++;
2015
2016 /*DbgPrint("!%d!%d!%d!%d!", KdbNumberOfRowsPrinted, KdbNumberOfColsPrinted, i, RowsPrintedByTerminal);*/
2017
2018 /* Display a prompt if we printed one screen full of text */
2019 if (KdbNumberOfRowsTerminal > 0 &&
2020 (LONG)(KdbNumberOfRowsPrinted + RowsPrintedByTerminal) >= KdbNumberOfRowsTerminal)
2021 {
2022 if (KdbNumberOfColsPrinted > 0)
2023 DbgPrint("\n");
2024 DbgPrint("--- Press q to abort, any other key to continue ---");
2025 if (KdbDebugState & KD_DEBUG_KDSERIAL)
2026 c = KdbpGetCharSerial();
2027 else
2028 c = KdbpGetCharKeyboard(&ScanCode);
2029 if (c == '\r')
2030 {
2031 /* Try to read '\n' which might follow '\r' - if \n is not received here
2032 * it will be interpreted as "return" when the next command should be read.
2033 */
2034 if (KdbDebugState & KD_DEBUG_KDSERIAL)
2035 c = KdbpTryGetCharSerial(5);
2036 else
2037 c = KdbpTryGetCharKeyboard(&ScanCode, 5);
2038 }
2039 DbgPrint("\n");
2040 if (c == 'q')
2041 {
2042 KdbOutputAborted = TRUE;
2043 return;
2044 }
2045 KdbNumberOfRowsPrinted = 0;
2046 KdbNumberOfColsPrinted = 0;
2047 }
2048
2049 /* Insert a NUL after the line and print only the current line. */
2050 if (p[i] == '\n' && p[i + 1] != '\0')
2051 {
2052 c = p[i + 1];
2053 p[i + 1] = '\0';
2054 }
2055 else
2056 {
2057 c = '\0';
2058 }
2059
2060 /* Remove escape sequences from the line if there's no terminal connected */
2061 if (!TerminalConnected)
2062 {
2063 while ((p2 = strrchr(p, '\x1b')) != NULL) /* Look for escape character */
2064 {
2065 if (p2[1] == '[')
2066 {
2067 j = 2;
2068 while (!isalpha(p2[j++]));
2069 strcpy(p2, p2 + j);
2070 }
2071 else
2072 {
2073 strcpy(p2, p2 + 1);
2074 }
2075 }
2076 }
2077
2078 DbgPrint("%s", p);
2079
2080 if (c != '\0')
2081 p[i + 1] = c;
2082
2083 /* Set p to the start of the next line and
2084 * remember the number of rows/cols printed
2085 */
2086 p += i;
2087 if (p[0] == '\n')
2088 {
2089 p++;
2090 KdbNumberOfColsPrinted = 0;
2091 }
2092 else
2093 {
2094 ASSERT(p[0] == '\0');
2095 KdbNumberOfColsPrinted += i;
2096 }
2097 KdbNumberOfRowsPrinted += RowsPrintedByTerminal;
2098 }
2099 }
2100
2101 /*!\brief Appends a command to the command history
2102 *
2103 * \param Command Pointer to the command to append to the history.
2104 */
2105 STATIC VOID
2106 KdbpCommandHistoryAppend(
2107 IN PCHAR Command)
2108 {
2109 ULONG Length1 = strlen(Command) + 1;
2110 ULONG Length2 = 0;
2111 INT i;
2112 PCHAR Buffer;
2113
2114 ASSERT(Length1 <= RTL_NUMBER_OF(KdbCommandHistoryBuffer));
2115
2116 if (Length1 <= 1 ||
2117 (KdbCommandHistory[KdbCommandHistoryIndex] != NULL &&
2118 strcmp(KdbCommandHistory[KdbCommandHistoryIndex], Command) == 0))
2119 {
2120 return;
2121 }
2122
2123 /* Calculate Length1 and Length2 */
2124 Buffer = KdbCommandHistoryBuffer + KdbCommandHistoryBufferIndex;
2125 KdbCommandHistoryBufferIndex += Length1;
2126 if (KdbCommandHistoryBufferIndex >= (LONG)RTL_NUMBER_OF(KdbCommandHistoryBuffer))
2127 {
2128 KdbCommandHistoryBufferIndex -= RTL_NUMBER_OF(KdbCommandHistoryBuffer);
2129 Length2 = KdbCommandHistoryBufferIndex;
2130 Length1 -= Length2;
2131 }
2132
2133 /* Remove previous commands until there is enough space to append the new command */
2134 for (i = KdbCommandHistoryIndex; KdbCommandHistory[i] != NULL;)
2135 {
2136 if ((Length2 > 0 &&
2137 (KdbCommandHistory[i] >= Buffer ||
2138 KdbCommandHistory[i] < (KdbCommandHistoryBuffer + KdbCommandHistoryBufferIndex))) ||
2139 (Length2 <= 0 &&
2140 (KdbCommandHistory[i] >= Buffer &&
2141 KdbCommandHistory[i] < (KdbCommandHistoryBuffer + KdbCommandHistoryBufferIndex))))
2142 {
2143 KdbCommandHistory[i] = NULL;
2144 }
2145 i--;
2146 if (i < 0)
2147 i = RTL_NUMBER_OF(KdbCommandHistory) - 1;
2148 if (i == KdbCommandHistoryIndex)
2149 break;
2150 }
2151
2152 /* Make sure the new command history entry is free */
2153 KdbCommandHistoryIndex++;
2154 KdbCommandHistoryIndex %= RTL_NUMBER_OF(KdbCommandHistory);
2155 if (KdbCommandHistory[KdbCommandHistoryIndex] != NULL)
2156 {
2157 KdbCommandHistory[KdbCommandHistoryIndex] = NULL;
2158 }
2159
2160 /* Append command */
2161 KdbCommandHistory[KdbCommandHistoryIndex] = Buffer;
2162 ASSERT((KdbCommandHistory[KdbCommandHistoryIndex] + Length1) <= KdbCommandHistoryBuffer + RTL_NUMBER_OF(KdbCommandHistoryBuffer));
2163 memcpy(KdbCommandHistory[KdbCommandHistoryIndex], Command, Length1);
2164 if (Length2 > 0)
2165 {
2166 memcpy(KdbCommandHistoryBuffer, Command + Length1, Length2);
2167 }
2168 }
2169
2170 /*!\brief Reads a line of user-input.
2171 *
2172 * \param Buffer Buffer to store the input into. Trailing newlines are removed.
2173 * \param Size Size of \a Buffer.
2174 *
2175 * \note Accepts only \n newlines, \r is ignored.
2176 */
2177 STATIC VOID
2178 KdbpReadCommand(
2179 OUT PCHAR Buffer,
2180 IN ULONG Size)
2181 {
2182 CHAR Key;
2183 PCHAR Orig = Buffer;
2184 ULONG ScanCode = 0;
2185 BOOLEAN EchoOn;
2186 STATIC CHAR LastCommand[1024] = "";
2187 STATIC CHAR NextKey = '\0';
2188 INT CmdHistIndex = -1;
2189 INT i;
2190
2191 EchoOn = !((KdbDebugState & KD_DEBUG_KDNOECHO) != 0);
2192
2193 for (;;)
2194 {
2195 if (KdbDebugState & KD_DEBUG_KDSERIAL)
2196 {
2197 Key = (NextKey == '\0') ? KdbpGetCharSerial() : NextKey;
2198 NextKey = '\0';
2199 ScanCode = 0;
2200 if (Key == KEY_ESC) /* ESC */
2201 {
2202 Key = KdbpGetCharSerial();
2203 if (Key == '[')
2204 {
2205 Key = KdbpGetCharSerial();
2206 switch (Key)
2207 {
2208 case 'A':
2209 ScanCode = KEY_SCAN_UP;
2210 break;
2211 case 'B':
2212 ScanCode = KEY_SCAN_DOWN;
2213 break;
2214 case 'C':
2215 break;
2216 case 'D':
2217 break;
2218 }
2219 }
2220 }
2221 }
2222 else
2223 {
2224 ScanCode = 0;
2225 Key = (NextKey == '\0') ? KdbpGetCharKeyboard(&ScanCode) : NextKey;
2226 NextKey = '\0';
2227 }
2228
2229 if ((ULONG)(Buffer - Orig) >= (Size - 1))
2230 {
2231 /* Buffer is full, accept only newlines */
2232 if (Key != '\n')
2233 continue;
2234 }
2235
2236 if (Key == '\r')
2237 {
2238 /* Read the next char - this is to throw away a \n which most clients should
2239 * send after \r.
2240 */
2241 KeStallExecutionProcessor(100000);
2242 if (KdbDebugState & KD_DEBUG_KDSERIAL)
2243 NextKey = KdbpTryGetCharSerial(5);
2244 else
2245 NextKey = KdbpTryGetCharKeyboard(&ScanCode, 5);
2246 if (NextKey == '\n' || NextKey == -1) /* \n or no response at all */
2247 NextKey = '\0';
2248 KdbpPrint("\n");
2249 /*
2250 * Repeat the last command if the user presses enter. Reduces the
2251 * risk of RSI when single-stepping.
2252 */
2253 if (Buffer == Orig)
2254 {
2255 strncpy(Buffer, LastCommand, Size);
2256 Buffer[Size - 1] = '\0';
2257 }
2258 else
2259 {
2260 *Buffer = '\0';
2261 strncpy(LastCommand, Orig, sizeof (LastCommand));
2262 LastCommand[sizeof (LastCommand) - 1] = '\0';
2263 }
2264 return;
2265 }
2266 else if (Key == KEY_BS || Key == KEY_DEL)
2267 {
2268 if (Buffer > Orig)
2269 {
2270 Buffer--;
2271 *Buffer = 0;
2272 if (EchoOn)
2273 KdbpPrint("%c %c", KEY_BS, KEY_BS);
2274 else
2275 KdbpPrint(" %c", KEY_BS);
2276 }
2277 }
2278 else if (ScanCode == KEY_SCAN_UP)
2279 {
2280 BOOLEAN Print = TRUE;
2281 if (CmdHistIndex < 0)
2282 CmdHistIndex = KdbCommandHistoryIndex;
2283 else
2284 {
2285 i = CmdHistIndex - 1;
2286 if (i < 0)
2287 CmdHistIndex = RTL_NUMBER_OF(KdbCommandHistory) - 1;
2288 if (KdbCommandHistory[i] != NULL && i != KdbCommandHistoryIndex)
2289 CmdHistIndex = i;
2290 else
2291 Print = FALSE;
2292 }
2293 if (Print && KdbCommandHistory[CmdHistIndex] != NULL)
2294 {
2295 while (Buffer > Orig)
2296 {
2297 Buffer--;
2298 *Buffer = 0;
2299 if (EchoOn)
2300 KdbpPrint("%c %c", KEY_BS, KEY_BS);
2301 else
2302 KdbpPrint(" %c", KEY_BS);
2303 }
2304 i = min(strlen(KdbCommandHistory[CmdHistIndex]), Size - 1);
2305 memcpy(Orig, KdbCommandHistory[CmdHistIndex], i);
2306 Orig[i] = '\0';
2307 Buffer = Orig + i;
2308 KdbpPrint("%s", Orig);
2309 }
2310 }
2311 else if (ScanCode == KEY_SCAN_DOWN)
2312 {
2313 if (CmdHistIndex > 0 && CmdHistIndex != KdbCommandHistoryIndex)
2314 {
2315 i = CmdHistIndex + 1;
2316 if (i >= (INT)RTL_NUMBER_OF(KdbCommandHistory))
2317 i = 0;
2318 if (KdbCommandHistory[i] != NULL)
2319 {
2320 CmdHistIndex = i;
2321 while (Buffer > Orig)
2322 {
2323 Buffer--;
2324 *Buffer = 0;
2325 if (EchoOn)
2326 KdbpPrint("%c %c", KEY_BS, KEY_BS);
2327 else
2328 KdbpPrint(" %c", KEY_BS);
2329 }
2330 i = min(strlen(KdbCommandHistory[CmdHistIndex]), Size - 1);
2331 memcpy(Orig, KdbCommandHistory[CmdHistIndex], i);
2332 Orig[i] = '\0';
2333 Buffer = Orig + i;
2334 KdbpPrint("%s", Orig);
2335 }
2336 }
2337 }
2338 else
2339 {
2340 if (EchoOn)
2341 KdbpPrint("%c", Key);
2342
2343 *Buffer = Key;
2344 Buffer++;
2345 }
2346 }
2347 }
2348
2349 /*!\brief Parses command line and executes command if found
2350 *
2351 * \param Command Command line to parse and execute if possible.
2352 *
2353 * \retval TRUE Don't continue execution.
2354 * \retval FALSE Continue execution (leave KDB)
2355 */
2356 STATIC BOOLEAN
2357 KdbpDoCommand(
2358 IN PCHAR Command)
2359 {
2360 ULONG i;
2361 PCHAR p;
2362 ULONG Argc;
2363 STATIC PCH Argv[256];
2364 STATIC CHAR OrigCommand[1024];
2365
2366 strncpy(OrigCommand, Command, sizeof(OrigCommand) - 1);
2367 OrigCommand[sizeof(OrigCommand) - 1] = '\0';
2368
2369 Argc = 0;
2370 p = Command;
2371 for (;;)
2372 {
2373 while (*p == '\t' || *p == ' ')
2374 p++;
2375 if (*p == '\0')
2376 break;
2377
2378 i = strcspn(p, "\t ");
2379 Argv[Argc++] = p;
2380 p += i;
2381 if (*p == '\0')
2382 break;
2383 *p = '\0';
2384 p++;
2385 }
2386 if (Argc < 1)
2387 return TRUE;
2388
2389 for (i = 0; i < RTL_NUMBER_OF(KdbDebuggerCommands); i++)
2390 {
2391 if (KdbDebuggerCommands[i].Name == NULL)
2392 continue;
2393
2394 if (strcmp(KdbDebuggerCommands[i].Name, Argv[0]) == 0)
2395 {
2396 return KdbDebuggerCommands[i].Fn(Argc, Argv);
2397 }
2398 }
2399
2400 KdbpPrint("Command '%s' is unknown.\n", OrigCommand);
2401 return TRUE;
2402 }
2403
2404 /*!\brief KDB Main Loop.
2405 *
2406 * \param EnteredOnSingleStep TRUE if KDB was entered on single step.
2407 */
2408 VOID
2409 KdbpCliMainLoop(
2410 IN BOOLEAN EnteredOnSingleStep)
2411 {
2412 STATIC CHAR Command[1024];
2413 BOOLEAN Continue;
2414
2415 if (EnteredOnSingleStep)
2416 {
2417 if (!KdbSymPrintAddress((PVOID)KdbCurrentTrapFrame->Tf.Eip))
2418 {
2419 KdbpPrint("<%x>", KdbCurrentTrapFrame->Tf.Eip);
2420 }
2421 KdbpPrint(": ");
2422 if (KdbpDisassemble(KdbCurrentTrapFrame->Tf.Eip, KdbUseIntelSyntax) < 0)
2423 {
2424 KdbpPrint("<INVALID>");
2425 }
2426 KdbpPrint("\n");
2427 }
2428
2429 /* Flush the input buffer */
2430 if (KdbDebugState & KD_DEBUG_KDSERIAL)
2431 {
2432 while (KdbpTryGetCharSerial(1) != -1);
2433 }
2434 else
2435 {
2436 ULONG ScanCode;
2437 while (KdbpTryGetCharKeyboard(&ScanCode, 1) != -1);
2438 }
2439
2440 /* Main loop */
2441 do
2442 {
2443 /* Print the prompt */
2444 KdbpPrint("kdb:> ");
2445
2446 /* Read a command and remember it */
2447 KdbpReadCommand(Command, sizeof (Command));
2448 KdbpCommandHistoryAppend(Command);
2449
2450 /* Reset the number of rows/cols printed and output aborted state */
2451 KdbNumberOfRowsPrinted = KdbNumberOfColsPrinted = 0;
2452 KdbOutputAborted = FALSE;
2453
2454 /* Call the command */
2455 Continue = KdbpDoCommand(Command);
2456 } while (Continue);
2457 }
2458
2459 /*!\brief Called when a module is loaded.
2460 *
2461 * \param Name Filename of the module which was loaded.
2462 */
2463 VOID
2464 KdbpCliModuleLoaded(IN PUNICODE_STRING Name)
2465 {
2466 if (!KdbBreakOnModuleLoad)
2467 return;
2468
2469 KdbpPrint("Module %wZ loaded.\n", Name);
2470 DbgBreakPointWithStatus(DBG_STATUS_CONTROL_C);
2471 }
2472
2473 /*!\brief This function is called by KdbEnterDebuggerException...
2474 *
2475 * Used to interpret the init file in a context with a trapframe setup
2476 * (KdbpCliInit call KdbEnter which will call KdbEnterDebuggerException which will
2477 * call this function if KdbInitFileBuffer is not NULL.
2478 */
2479 VOID
2480 KdbpCliInterpretInitFile()
2481 {
2482 PCHAR p1, p2;
2483 INT i;
2484 CHAR c;
2485
2486 /* Execute the commands in the init file */
2487 DPRINT("KDB: Executing KDBinit file...\n");
2488 p1 = KdbInitFileBuffer;
2489 while (p1[0] != '\0')
2490 {
2491 i = strcspn(p1, "\r\n");
2492 if (i > 0)
2493 {
2494 c = p1[i];
2495 p1[i] = '\0';
2496
2497 /* Look for "break" command and comments */
2498 p2 = p1;
2499 while (isspace(p2[0]))
2500 p2++;
2501 if (strncmp(p2, "break", sizeof("break")-1) == 0 &&
2502 (p2[sizeof("break")-1] == '\0' || isspace(p2[sizeof("break")-1])))
2503 {
2504 /* break into the debugger */
2505 KdbpCliMainLoop(FALSE);
2506 }
2507 else if (p2[0] != '#' && p2[0] != '\0') /* Ignore empty lines and comments */
2508 {
2509 KdbpDoCommand(p1);
2510 }
2511
2512 p1[i] = c;
2513 }
2514 p1 += i;
2515 while (p1[0] == '\r' || p1[0] == '\n')
2516 p1++;
2517 }
2518 DPRINT("KDB: KDBinit executed\n");
2519 }
2520
2521 /*!\brief Called when KDB is initialized
2522 *
2523 * Reads the KDBinit file from the SystemRoot\system32\drivers\etc directory and executes it.
2524 */
2525 VOID
2526 KdbpCliInit()
2527 {
2528 NTSTATUS Status;
2529 OBJECT_ATTRIBUTES ObjectAttributes;
2530 UNICODE_STRING FileName;
2531 IO_STATUS_BLOCK Iosb;
2532 FILE_STANDARD_INFORMATION FileStdInfo;
2533 HANDLE hFile = NULL;
2534 INT FileSize;
2535 PCHAR FileBuffer;
2536 ULONG OldEflags = 0;
2537
2538 /* Initialize the object attributes */
2539 RtlInitUnicodeString(&FileName, L"\\SystemRoot\\system32\\drivers\\etc\\KDBinit");
2540 InitializeObjectAttributes(&ObjectAttributes, &FileName, 0, NULL, NULL);
2541
2542 /* Open the file */
2543 Status = ZwOpenFile(&hFile, FILE_READ_DATA, &ObjectAttributes, &Iosb, 0,
2544 FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT |
2545 FILE_NO_INTERMEDIATE_BUFFERING);
2546 if (!NT_SUCCESS(Status))
2547 {
2548 DPRINT("Could not open \\SystemRoot\\system32\\drivers\\etc\\KDBinit (Status 0x%x)", Status);
2549 return;
2550 }
2551
2552 /* Get the size of the file */
2553 Status = ZwQueryInformationFile(hFile, &Iosb, &FileStdInfo, sizeof (FileStdInfo),
2554 FileStandardInformation);
2555 if (!NT_SUCCESS(Status))
2556 {
2557 ZwClose(hFile);
2558 DPRINT("Could not query size of \\SystemRoot\\system32\\drivers\\etc\\KDBinit (Status 0x%x)", Status);
2559 return;
2560 }
2561 FileSize = FileStdInfo.EndOfFile.u.LowPart;
2562
2563 /* Allocate memory for the file */
2564 FileBuffer = ExAllocatePool(PagedPool, FileSize + 1); /* add 1 byte for terminating '\0' */
2565 if (FileBuffer == NULL)
2566 {
2567 ZwClose(hFile);
2568 DPRINT("Could not allocate %d bytes for KDBinit file\n", FileSize);
2569 return;
2570 }
2571
2572 /* Load file into memory */
2573 Status = ZwReadFile(hFile, 0, 0, 0, &Iosb, FileBuffer, FileSize, 0, 0);
2574 ZwClose(hFile);
2575 if (!NT_SUCCESS(Status) && Status != STATUS_END_OF_FILE)
2576 {
2577 ExFreePool(FileBuffer);
2578 DPRINT("Could not read KDBinit file into memory (Status 0x%lx)\n", Status);
2579 return;
2580 }
2581 FileSize = min(FileSize, (INT)Iosb.Information);
2582 FileBuffer[FileSize] = '\0';
2583
2584 /* Enter critical section */
2585 Ke386SaveFlags(OldEflags);
2586 _disable();
2587
2588 /* Interpret the init file... */
2589 KdbInitFileBuffer = FileBuffer;
2590 KdbEnter();
2591 KdbInitFileBuffer = NULL;
2592
2593 /* Leave critical section */
2594 Ke386RestoreFlags(OldEflags);
2595
2596 ExFreePool(FileBuffer);
2597 }
2598