- KDBG: Correct the use of PsLookupThread/ProcessByThread/ProcessId -- the caller...
[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 BOOLEAN ReferencedThread = FALSE, ReferencedProcess = FALSE;
1094 PULONG Esp;
1095 PULONG Ebp;
1096 ULONG Eip;
1097 ULONG ul = 0;
1098 PCHAR State, pend, str1, str2;
1099 STATIC CONST PCHAR ThreadStateToString[DeferredReady+1] =
1100 { "Initialized", "Ready", "Running",
1101 "Standby", "Terminated", "Waiting",
1102 "Transition", "DeferredReady" };
1103 ASSERT(KdbCurrentProcess != NULL);
1104
1105 if (Argc >= 2 && _stricmp(Argv[1], "list") == 0)
1106 {
1107 Process = KdbCurrentProcess;
1108
1109 if (Argc >= 3)
1110 {
1111 ul = strtoul(Argv[2], &pend, 0);
1112 if (Argv[2] == pend)
1113 {
1114 KdbpPrint("thread: '%s' is not a valid process id!\n", Argv[2]);
1115 return TRUE;
1116 }
1117 if (!NT_SUCCESS(PsLookupProcessByProcessId((PVOID)ul, &Process)))
1118 {
1119 KdbpPrint("thread: Invalid process id!\n");
1120 return TRUE;
1121 }
1122
1123 /* Remember our reference */
1124 ReferencedProcess = TRUE;
1125 }
1126
1127 Entry = Process->ThreadListHead.Flink;
1128 if (Entry == &Process->ThreadListHead)
1129 {
1130 if (Argc >= 3)
1131 KdbpPrint("No threads in process 0x%08x!\n", ul);
1132 else
1133 KdbpPrint("No threads in current process!\n");
1134 if (ReferencedProcess) ObDereferenceObject(Process);
1135 return TRUE;
1136 }
1137
1138 KdbpPrint(" TID State Prior. Affinity EBP EIP\n");
1139 do
1140 {
1141 Thread = CONTAINING_RECORD(Entry, ETHREAD, ThreadListEntry);
1142
1143 if (Thread == KdbCurrentThread)
1144 {
1145 str1 = "\x1b[1m*";
1146 str2 = "\x1b[0m";
1147 }
1148 else
1149 {
1150 str1 = " ";
1151 str2 = "";
1152 }
1153
1154 if (Thread->Tcb.TrapFrame != NULL)
1155 {
1156 if (Thread->Tcb.TrapFrame->PreviousPreviousMode == KernelMode)
1157 Esp = (PULONG)Thread->Tcb.TrapFrame->TempEsp;
1158 else
1159 Esp = (PULONG)Thread->Tcb.TrapFrame->HardwareEsp;
1160 Ebp = (PULONG)Thread->Tcb.TrapFrame->Ebp;
1161 Eip = Thread->Tcb.TrapFrame->Eip;
1162 }
1163 else
1164 {
1165 Esp = (PULONG)Thread->Tcb.KernelStack;
1166 Ebp = (PULONG)Esp[4];
1167 Eip = 0;
1168 if (Ebp != NULL) /* FIXME: Should we attach to the process to read Ebp[1]? */
1169 KdbpSafeReadMemory(&Eip, Ebp + 1, sizeof (Eip));
1170 }
1171 if (Thread->Tcb.State < (DeferredReady + 1))
1172 State = ThreadStateToString[Thread->Tcb.State];
1173 else
1174 State = "Unknown";
1175
1176 KdbpPrint(" %s0x%08x %-11s %3d 0x%08x 0x%08x 0x%08x%s\n",
1177 str1,
1178 Thread->Cid.UniqueThread,
1179 State,
1180 Thread->Tcb.Priority,
1181 Thread->Tcb.Affinity,
1182 Ebp,
1183 Eip,
1184 str2);
1185
1186 Entry = Entry->Flink;
1187 }
1188 while (Entry != &Process->ThreadListHead);
1189
1190 /* Release our reference, if any */
1191 if (ReferencedProcess) ObDereferenceObject(Process);
1192 }
1193 else if (Argc >= 2 && _stricmp(Argv[1], "attach") == 0)
1194 {
1195 if (Argc < 3)
1196 {
1197 KdbpPrint("thread attach: thread id argument required!\n");
1198 return TRUE;
1199 }
1200
1201 ul = strtoul(Argv[2], &pend, 0);
1202 if (Argv[2] == pend)
1203 {
1204 KdbpPrint("thread attach: '%s' is not a valid thread id!\n", Argv[2]);
1205 return TRUE;
1206 }
1207 if (!KdbpAttachToThread((PVOID)ul))
1208 {
1209 return TRUE;
1210 }
1211 KdbpPrint("Attached to thread 0x%08x.\n", ul);
1212 }
1213 else
1214 {
1215 Thread = KdbCurrentThread;
1216
1217 if (Argc >= 2)
1218 {
1219 ul = strtoul(Argv[1], &pend, 0);
1220 if (Argv[1] == pend)
1221 {
1222 KdbpPrint("thread: '%s' is not a valid thread id!\n", Argv[1]);
1223 return TRUE;
1224 }
1225 if (!NT_SUCCESS(PsLookupThreadByThreadId((PVOID)ul, &Thread)))
1226 {
1227 KdbpPrint("thread: Invalid thread id!\n");
1228 return TRUE;
1229 }
1230
1231 /* Remember our reference */
1232 ReferencedThread = TRUE;
1233 }
1234
1235 if (Thread->Tcb.State < (DeferredReady + 1))
1236 State = ThreadStateToString[Thread->Tcb.State];
1237 else
1238 State = "Unknown";
1239 KdbpPrint("%s"
1240 " TID: 0x%08x\n"
1241 " State: %s (0x%x)\n"
1242 " Priority: %d\n"
1243 " Affinity: 0x%08x\n"
1244 " Initial Stack: 0x%08x\n"
1245 " Stack Limit: 0x%08x\n"
1246 " Stack Base: 0x%08x\n"
1247 " Kernel Stack: 0x%08x\n"
1248 " Trap Frame: 0x%08x\n"
1249 " NPX State: %s (0x%x)\n",
1250 (Argc < 2) ? "Current Thread:\n" : "",
1251 Thread->Cid.UniqueThread,
1252 State, Thread->Tcb.State,
1253 Thread->Tcb.Priority,
1254 Thread->Tcb.Affinity,
1255 Thread->Tcb.InitialStack,
1256 Thread->Tcb.StackLimit,
1257 Thread->Tcb.StackBase,
1258 Thread->Tcb.KernelStack,
1259 Thread->Tcb.TrapFrame,
1260 NPX_STATE_TO_STRING(Thread->Tcb.NpxState), Thread->Tcb.NpxState);
1261
1262 /* Release our reference if we had one */
1263 if (ReferencedThread) ObDereferenceObject(Thread);
1264 }
1265
1266 return TRUE;
1267 }
1268
1269 /*!\brief Lists processes or switches to another process context.
1270 */
1271 STATIC BOOLEAN
1272 KdbpCmdProc(ULONG Argc, PCHAR Argv[])
1273 {
1274 PLIST_ENTRY Entry;
1275 PEPROCESS Process;
1276 BOOLEAN ReferencedProcess = FALSE;
1277 PCHAR State, pend, str1, str2;
1278 ULONG ul;
1279 extern LIST_ENTRY PsActiveProcessHead;
1280
1281 if (Argc >= 2 && _stricmp(Argv[1], "list") == 0)
1282 {
1283 Entry = PsActiveProcessHead.Flink;
1284 if (!Entry || Entry == &PsActiveProcessHead)
1285 {
1286 KdbpPrint("No processes in the system!\n");
1287 return TRUE;
1288 }
1289
1290 KdbpPrint(" PID State Filename\n");
1291 do
1292 {
1293 Process = CONTAINING_RECORD(Entry, EPROCESS, ActiveProcessLinks);
1294
1295 if (Process == KdbCurrentProcess)
1296 {
1297 str1 = "\x1b[1m*";
1298 str2 = "\x1b[0m";
1299 }
1300 else
1301 {
1302 str1 = " ";
1303 str2 = "";
1304 }
1305
1306 State = ((Process->Pcb.State == ProcessInMemory) ? "In Memory" :
1307 ((Process->Pcb.State == ProcessOutOfMemory) ? "Out of Memory" : "In Transition"));
1308
1309 KdbpPrint(" %s0x%08x %-10s %s%s\n",
1310 str1,
1311 Process->UniqueProcessId,
1312 State,
1313 Process->ImageFileName,
1314 str2);
1315
1316 Entry = Entry->Flink;
1317 }
1318 while(Entry != &PsActiveProcessHead);
1319 }
1320 else if (Argc >= 2 && _stricmp(Argv[1], "attach") == 0)
1321 {
1322 if (Argc < 3)
1323 {
1324 KdbpPrint("process attach: process id argument required!\n");
1325 return TRUE;
1326 }
1327
1328 ul = strtoul(Argv[2], &pend, 0);
1329 if (Argv[2] == pend)
1330 {
1331 KdbpPrint("process attach: '%s' is not a valid process id!\n", Argv[2]);
1332 return TRUE;
1333 }
1334 if (!KdbpAttachToProcess((PVOID)ul))
1335 {
1336 return TRUE;
1337 }
1338 KdbpPrint("Attached to process 0x%08x, thread 0x%08x.\n", (ULONG)ul,
1339 (ULONG)KdbCurrentThread->Cid.UniqueThread);
1340 }
1341 else
1342 {
1343 Process = KdbCurrentProcess;
1344
1345 if (Argc >= 2)
1346 {
1347 ul = strtoul(Argv[1], &pend, 0);
1348 if (Argv[1] == pend)
1349 {
1350 KdbpPrint("proc: '%s' is not a valid process id!\n", Argv[1]);
1351 return TRUE;
1352 }
1353 if (!NT_SUCCESS(PsLookupProcessByProcessId((PVOID)ul, &Process)))
1354 {
1355 KdbpPrint("proc: Invalid process id!\n");
1356 return TRUE;
1357 }
1358
1359 /* Remember our reference */
1360 ReferencedProcess = TRUE;
1361 }
1362
1363 State = ((Process->Pcb.State == ProcessInMemory) ? "In Memory" :
1364 ((Process->Pcb.State == ProcessOutOfMemory) ? "Out of Memory" : "In Transition"));
1365 KdbpPrint("%s"
1366 " PID: 0x%08x\n"
1367 " State: %s (0x%x)\n"
1368 " Image Filename: %s\n",
1369 (Argc < 2) ? "Current process:\n" : "",
1370 Process->UniqueProcessId,
1371 State, Process->Pcb.State,
1372 Process->ImageFileName);
1373
1374 /* Release our reference, if any */
1375 if (ReferencedProcess) ObDereferenceObject(Process);
1376 }
1377
1378 return TRUE;
1379 }
1380
1381 /*!\brief Lists loaded modules or the one containing the specified address.
1382 */
1383 STATIC BOOLEAN
1384 KdbpCmdMod(ULONG Argc, PCHAR Argv[])
1385 {
1386 ULONGLONG Result = 0;
1387 ULONG_PTR Address;
1388 KDB_MODULE_INFO Info;
1389 BOOLEAN DisplayOnlyOneModule = FALSE;
1390 INT i = 0;
1391
1392 if (Argc >= 2)
1393 {
1394 /* Put the arguments back together */
1395 Argc--;
1396 while (--Argc >= 1)
1397 Argv[Argc][strlen(Argv[Argc])] = ' ';
1398
1399 /* Evaluate the expression */
1400 if (!KdbpEvaluateExpression(Argv[1], sizeof("kdb:> ")-1 + (Argv[1]-Argv[0]), &Result))
1401 {
1402 return TRUE;
1403 }
1404 if (Result > (ULONGLONG)(~((ULONG_PTR)0)))
1405 KdbpPrint("%s: Warning: Address %I64x is beeing truncated\n", Argv[0]);
1406 Address = (ULONG_PTR)Result;
1407
1408 if (!KdbpSymFindModuleByAddress((PVOID)Address, &Info))
1409 {
1410 KdbpPrint("No module containing address 0x%p found!\n", Address);
1411 return TRUE;
1412 }
1413 DisplayOnlyOneModule = TRUE;
1414 }
1415 else
1416 {
1417 if (!KdbpSymFindModuleByIndex(0, &Info))
1418 {
1419 ULONG_PTR ntoskrnlBase = ((ULONG_PTR)KdbpCmdMod) & 0xfff00000;
1420 KdbpPrint(" Base Size Name\n");
1421 KdbpPrint(" %08x %08x %s\n", ntoskrnlBase, 0, "ntoskrnl.exe");
1422 return TRUE;
1423 }
1424 i = 1;
1425 }
1426
1427 KdbpPrint(" Base Size Name\n");
1428 for (;;)
1429 {
1430 KdbpPrint(" %08x %08x %ws\n", Info.Base, Info.Size, Info.Name);
1431
1432 if ((!DisplayOnlyOneModule && !KdbpSymFindModuleByIndex(i++, &Info)) ||
1433 DisplayOnlyOneModule)
1434 {
1435 break;
1436 }
1437 }
1438
1439 return TRUE;
1440 }
1441
1442 /*!\brief Displays GDT, LDT or IDTd.
1443 */
1444 STATIC BOOLEAN
1445 KdbpCmdGdtLdtIdt(ULONG Argc, PCHAR Argv[])
1446 {
1447 KDESCRIPTOR Reg = {0};
1448 ULONG SegDesc[2];
1449 ULONG SegBase;
1450 ULONG SegLimit;
1451 PCHAR SegType;
1452 USHORT SegSel;
1453 UCHAR Type, Dpl;
1454 INT i;
1455 ULONG ul;
1456
1457 if (Argv[0][0] == 'i')
1458 {
1459 /* Read IDTR */
1460 Ke386GetInterruptDescriptorTable(*(PKDESCRIPTOR)&Reg.Limit);
1461
1462 if (Reg.Limit < 7)
1463 {
1464 KdbpPrint("Interrupt descriptor table is empty.\n");
1465 return TRUE;
1466 }
1467 KdbpPrint("IDT Base: 0x%08x Limit: 0x%04x\n", Reg.Base, Reg.Limit);
1468 KdbpPrint(" Idx Type Seg. Sel. Offset DPL\n");
1469 for (i = 0; (i + sizeof(SegDesc) - 1) <= Reg.Limit; i += 8)
1470 {
1471 if (!NT_SUCCESS(KdbpSafeReadMemory(SegDesc, (PVOID)(Reg.Base + i), sizeof(SegDesc))))
1472 {
1473 KdbpPrint("Couldn't access memory at 0x%08x!\n", Reg.Base + i);
1474 return TRUE;
1475 }
1476
1477 Dpl = ((SegDesc[1] >> 13) & 3);
1478 if ((SegDesc[1] & 0x1f00) == 0x0500) /* Task gate */
1479 SegType = "TASKGATE";
1480 else if ((SegDesc[1] & 0x1fe0) == 0x0e00) /* 32 bit Interrupt gate */
1481 SegType = "INTGATE32";
1482 else if ((SegDesc[1] & 0x1fe0) == 0x0600) /* 16 bit Interrupt gate */
1483 SegType = "INTGATE16";
1484 else if ((SegDesc[1] & 0x1fe0) == 0x0f00) /* 32 bit Trap gate */
1485 SegType = "TRAPGATE32";
1486 else if ((SegDesc[1] & 0x1fe0) == 0x0700) /* 16 bit Trap gate */
1487 SegType = "TRAPGATE16";
1488 else
1489 SegType = "UNKNOWN";
1490
1491 if ((SegDesc[1] & (1 << 15)) == 0) /* not present */
1492 {
1493 KdbpPrint(" %03d %-10s [NP] [NP] %02d\n",
1494 i / 8, SegType, Dpl);
1495 }
1496 else if ((SegDesc[1] & 0x1f00) == 0x0500) /* Task gate */
1497 {
1498 SegSel = SegDesc[0] >> 16;
1499 KdbpPrint(" %03d %-10s 0x%04x %02d\n",
1500 i / 8, SegType, SegSel, Dpl);
1501 }
1502 else
1503 {
1504 SegSel = SegDesc[0] >> 16;
1505 SegBase = (SegDesc[1] & 0xffff0000) | (SegDesc[0] & 0x0000ffff);
1506 KdbpPrint(" %03d %-10s 0x%04x 0x%08x %02d\n",
1507 i / 8, SegType, SegSel, SegBase, Dpl);
1508 }
1509 }
1510 }
1511 else
1512 {
1513 ul = 0;
1514 if (Argv[0][0] == 'g')
1515 {
1516 /* Read GDTR */
1517 Ke386GetGlobalDescriptorTable(*(PKDESCRIPTOR)&Reg.Limit);
1518 i = 8;
1519 }
1520 else
1521 {
1522 ASSERT(Argv[0][0] == 'l');
1523 /* Read LDTR */
1524 Ke386GetLocalDescriptorTable(Reg.Limit);
1525 i = 0;
1526 ul = 1 << 2;
1527 }
1528
1529 if (Reg.Limit < 7)
1530 {
1531 KdbpPrint("%s descriptor table is empty.\n",
1532 Argv[0][0] == 'g' ? "Global" : "Local");
1533 return TRUE;
1534 }
1535 KdbpPrint("%cDT Base: 0x%08x Limit: 0x%04x\n",
1536 Argv[0][0] == 'g' ? 'G' : 'L', Reg.Base, Reg.Limit);
1537 KdbpPrint(" Idx Sel. Type Base Limit DPL Attribs\n");
1538 for ( ; (i + sizeof(SegDesc) - 1) <= Reg.Limit; i += 8)
1539 {
1540 if (!NT_SUCCESS(KdbpSafeReadMemory(SegDesc, (PVOID)(Reg.Base + i), sizeof(SegDesc))))
1541 {
1542 KdbpPrint("Couldn't access memory at 0x%08x!\n", Reg.Base + i);
1543 return TRUE;
1544 }
1545 Dpl = ((SegDesc[1] >> 13) & 3);
1546 Type = ((SegDesc[1] >> 8) & 0xf);
1547
1548 SegBase = SegDesc[0] >> 16;
1549 SegBase |= (SegDesc[1] & 0xff) << 16;
1550 SegBase |= SegDesc[1] & 0xff000000;
1551 SegLimit = SegDesc[0] & 0x0000ffff;
1552 SegLimit |= (SegDesc[1] >> 16) & 0xf;
1553 if ((SegDesc[1] & (1 << 23)) != 0)
1554 {
1555 SegLimit *= 4096;
1556 SegLimit += 4095;
1557 }
1558 else
1559 {
1560 SegLimit++;
1561 }
1562
1563 if ((SegDesc[1] & (1 << 12)) == 0) /* System segment */
1564 {
1565 switch (Type)
1566 {
1567 case 1: SegType = "TSS16(Avl)"; break;
1568 case 2: SegType = "LDT"; break;
1569 case 3: SegType = "TSS16(Busy)"; break;
1570 case 4: SegType = "CALLGATE16"; break;
1571 case 5: SegType = "TASKGATE"; break;
1572 case 6: SegType = "INTGATE16"; break;
1573 case 7: SegType = "TRAPGATE16"; break;
1574 case 9: SegType = "TSS32(Avl)"; break;
1575 case 11: SegType = "TSS32(Busy)"; break;
1576 case 12: SegType = "CALLGATE32"; break;
1577 case 14: SegType = "INTGATE32"; break;
1578 case 15: SegType = "INTGATE32"; break;
1579 default: SegType = "UNKNOWN"; break;
1580 }
1581 if (!(Type >= 1 && Type <= 3) &&
1582 Type != 9 && Type != 11)
1583 {
1584 SegBase = 0;
1585 SegLimit = 0;
1586 }
1587 }
1588 else if ((SegDesc[1] & (1 << 11)) == 0) /* Data segment */
1589 {
1590 if ((SegDesc[1] & (1 << 22)) != 0)
1591 SegType = "DATA32";
1592 else
1593 SegType = "DATA16";
1594
1595 }
1596 else /* Code segment */
1597 {
1598 if ((SegDesc[1] & (1 << 22)) != 0)
1599 SegType = "CODE32";
1600 else
1601 SegType = "CODE16";
1602 }
1603
1604 if ((SegDesc[1] & (1 << 15)) == 0) /* not present */
1605 {
1606 KdbpPrint(" %03d 0x%04x %-11s [NP] [NP] %02d NP\n",
1607 i / 8, i | Dpl | ul, SegType, Dpl);
1608 }
1609 else
1610 {
1611 KdbpPrint(" %03d 0x%04x %-11s 0x%08x 0x%08x %02d ",
1612 i / 8, i | Dpl | ul, SegType, SegBase, SegLimit, Dpl);
1613 if ((SegDesc[1] & (1 << 12)) == 0) /* System segment */
1614 {
1615 /* FIXME: Display system segment */
1616 }
1617 else if ((SegDesc[1] & (1 << 11)) == 0) /* Data segment */
1618 {
1619 if ((SegDesc[1] & (1 << 10)) != 0) /* Expand-down */
1620 KdbpPrint(" E");
1621 KdbpPrint((SegDesc[1] & (1 << 9)) ? " R/W" : " R");
1622 if ((SegDesc[1] & (1 << 8)) != 0)
1623 KdbpPrint(" A");
1624 }
1625 else /* Code segment */
1626 {
1627 if ((SegDesc[1] & (1 << 10)) != 0) /* Conforming */
1628 KdbpPrint(" C");
1629 KdbpPrint((SegDesc[1] & (1 << 9)) ? " R/X" : " X");
1630 if ((SegDesc[1] & (1 << 8)) != 0)
1631 KdbpPrint(" A");
1632 }
1633 if ((SegDesc[1] & (1 << 20)) != 0)
1634 KdbpPrint(" AVL");
1635 KdbpPrint("\n");
1636 }
1637 }
1638 }
1639
1640 return TRUE;
1641 }
1642
1643 /*!\brief Displays the KPCR
1644 */
1645 STATIC BOOLEAN
1646 KdbpCmdPcr(ULONG Argc, PCHAR Argv[])
1647 {
1648 PKIPCR Pcr = (PKIPCR)KeGetPcr();
1649
1650 KdbpPrint("Current PCR is at 0x%08x.\n", (INT)Pcr);
1651 KdbpPrint(" Tib.ExceptionList: 0x%08x\n"
1652 " Tib.StackBase: 0x%08x\n"
1653 " Tib.StackLimit: 0x%08x\n"
1654 " Tib.SubSystemTib: 0x%08x\n"
1655 " Tib.FiberData/Version: 0x%08x\n"
1656 " Tib.ArbitraryUserPointer: 0x%08x\n"
1657 " Tib.Self: 0x%08x\n"
1658 " Self: 0x%08x\n"
1659 " PCRCB: 0x%08x\n"
1660 " Irql: 0x%02x\n"
1661 " IRR: 0x%08x\n"
1662 " IrrActive: 0x%08x\n"
1663 " IDR: 0x%08x\n"
1664 " KdVersionBlock: 0x%08x\n"
1665 " IDT: 0x%08x\n"
1666 " GDT: 0x%08x\n"
1667 " TSS: 0x%08x\n"
1668 " MajorVersion: 0x%04x\n"
1669 " MinorVersion: 0x%04x\n"
1670 " SetMember: 0x%08x\n"
1671 " StallScaleFactor: 0x%08x\n"
1672 " Number: 0x%02x\n"
1673 " L2CacheAssociativity: 0x%02x\n"
1674 " VdmAlert: 0x%08x\n"
1675 " L2CacheSize: 0x%08x\n"
1676 " InterruptMode: 0x%08x\n",
1677 Pcr->NtTib.ExceptionList, Pcr->NtTib.StackBase, Pcr->NtTib.StackLimit,
1678 Pcr->NtTib.SubSystemTib, Pcr->NtTib.FiberData, Pcr->NtTib.ArbitraryUserPointer,
1679 Pcr->NtTib.Self, Pcr->Self, Pcr->Prcb, Pcr->Irql, Pcr->IRR, Pcr->IrrActive,
1680 Pcr->IDR, Pcr->KdVersionBlock, Pcr->IDT, Pcr->GDT, Pcr->TSS,
1681 Pcr->MajorVersion, Pcr->MinorVersion, Pcr->SetMember, Pcr->StallScaleFactor,
1682 Pcr->Number, Pcr->L2CacheAssociativity,
1683 Pcr->VdmAlert, Pcr->SecondLevelCacheSize, Pcr->InterruptMode);
1684
1685 return TRUE;
1686 }
1687
1688 /*!\brief Displays the TSS
1689 */
1690 STATIC BOOLEAN
1691 KdbpCmdTss(ULONG Argc, PCHAR Argv[])
1692 {
1693 KTSS *Tss = KeGetPcr()->TSS;
1694
1695 KdbpPrint("Current TSS is at 0x%08x.\n", (INT)Tss);
1696 KdbpPrint(" Eip: 0x%08x\n"
1697 " Es: 0x%04x\n"
1698 " Cs: 0x%04x\n"
1699 " Ss: 0x%04x\n"
1700 " Ds: 0x%04x\n"
1701 " Fs: 0x%04x\n"
1702 " Gs: 0x%04x\n"
1703 " IoMapBase: 0x%04x\n",
1704 Tss->Eip, Tss->Es, Tss->Cs, Tss->Ds, Tss->Fs, Tss->Gs, Tss->IoMapBase);
1705 return TRUE;
1706 }
1707
1708 /*!\brief Bugchecks the system.
1709 */
1710 STATIC BOOLEAN
1711 KdbpCmdBugCheck(ULONG Argc, PCHAR Argv[])
1712 {
1713 /* Set the flag and quit looping */
1714 KdbpBugCheckRequested = TRUE;
1715 return FALSE;
1716 }
1717
1718 /*!\brief Sets or displays a config variables value.
1719 */
1720 STATIC BOOLEAN
1721 KdbpCmdSet(ULONG Argc, PCHAR Argv[])
1722 {
1723 LONG l;
1724 BOOLEAN First;
1725 PCHAR pend = 0;
1726 KDB_ENTER_CONDITION ConditionFirst = KdbDoNotEnter;
1727 KDB_ENTER_CONDITION ConditionLast = KdbDoNotEnter;
1728 STATIC CONST PCHAR ExceptionNames[21] =
1729 { "ZERODEVIDE", "DEBUGTRAP", "NMI", "INT3", "OVERFLOW", "BOUND", "INVALIDOP",
1730 "NOMATHCOP", "DOUBLEFAULT", "RESERVED(9)", "INVALIDTSS", "SEGMENTNOTPRESENT",
1731 "STACKFAULT", "GPF", "PAGEFAULT", "RESERVED(15)", "MATHFAULT", "ALIGNMENTCHECK",
1732 "MACHINECHECK", "SIMDFAULT", "OTHERS" };
1733
1734 if (Argc == 1)
1735 {
1736 KdbpPrint("Available settings:\n");
1737 KdbpPrint(" syntax [intel|at&t]\n");
1738 KdbpPrint(" condition [exception|*] [first|last] [never|always|kmode|umode]\n");
1739 KdbpPrint(" break_on_module_load [true|false]\n");
1740 }
1741 else if (strcmp(Argv[1], "syntax") == 0)
1742 {
1743 if (Argc == 2)
1744 KdbpPrint("syntax = %s\n", KdbUseIntelSyntax ? "intel" : "at&t");
1745 else if (Argc >= 3)
1746 {
1747 if (_stricmp(Argv[2], "intel") == 0)
1748 KdbUseIntelSyntax = TRUE;
1749 else if (_stricmp(Argv[2], "at&t") == 0)
1750 KdbUseIntelSyntax = FALSE;
1751 else
1752 KdbpPrint("Unknown syntax '%s'.\n", Argv[2]);
1753 }
1754 }
1755 else if (strcmp(Argv[1], "condition") == 0)
1756 {
1757 if (Argc == 2)
1758 {
1759 KdbpPrint("Conditions: (First) (Last)\n");
1760 for (l = 0; l < RTL_NUMBER_OF(ExceptionNames) - 1; l++)
1761 {
1762 if (ExceptionNames[l] == NULL)
1763 continue;
1764 if (!KdbpGetEnterCondition(l, TRUE, &ConditionFirst))
1765 ASSERT(0);
1766 if (!KdbpGetEnterCondition(l, FALSE, &ConditionLast))
1767 ASSERT(0);
1768 KdbpPrint(" #%02d %-20s %-8s %-8s\n", l, ExceptionNames[l],
1769 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst),
1770 KDB_ENTER_CONDITION_TO_STRING(ConditionLast));
1771 }
1772 ASSERT(l == (RTL_NUMBER_OF(ExceptionNames) - 1));
1773 KdbpPrint(" %-20s %-8s %-8s\n", ExceptionNames[l],
1774 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst),
1775 KDB_ENTER_CONDITION_TO_STRING(ConditionLast));
1776 }
1777 else
1778 {
1779 if (Argc >= 5 && strcmp(Argv[2], "*") == 0) /* Allow * only when setting condition */
1780 l = -1;
1781 else
1782 {
1783 l = strtoul(Argv[2], &pend, 0);
1784 if (Argv[2] == pend)
1785 {
1786 for (l = 0; l < RTL_NUMBER_OF(ExceptionNames); l++)
1787 {
1788 if (ExceptionNames[l] == NULL)
1789 continue;
1790 if (_stricmp(ExceptionNames[l], Argv[2]) == 0)
1791 break;
1792 }
1793 }
1794 if (l >= RTL_NUMBER_OF(ExceptionNames))
1795 {
1796 KdbpPrint("Unknown exception '%s'.\n", Argv[2]);
1797 return TRUE;
1798 }
1799 }
1800 if (Argc > 4)
1801 {
1802 if (_stricmp(Argv[3], "first") == 0)
1803 First = TRUE;
1804 else if (_stricmp(Argv[3], "last") == 0)
1805 First = FALSE;
1806 else
1807 {
1808 KdbpPrint("set condition: second argument must be 'first' or 'last'\n");
1809 return TRUE;
1810 }
1811 if (_stricmp(Argv[4], "never") == 0)
1812 ConditionFirst = KdbDoNotEnter;
1813 else if (_stricmp(Argv[4], "always") == 0)
1814 ConditionFirst = KdbEnterAlways;
1815 else if (_stricmp(Argv[4], "umode") == 0)
1816 ConditionFirst = KdbEnterFromUmode;
1817 else if (_stricmp(Argv[4], "kmode") == 0)
1818 ConditionFirst = KdbEnterFromKmode;
1819 else
1820 {
1821 KdbpPrint("set condition: third argument must be 'never', 'always', 'umode' or 'kmode'\n");
1822 return TRUE;
1823 }
1824 if (!KdbpSetEnterCondition(l, First, ConditionFirst))
1825 {
1826 if (l >= 0)
1827 KdbpPrint("Couldn't change condition for exception #%02d\n", l);
1828 else
1829 KdbpPrint("Couldn't change condition for all exceptions\n", l);
1830 }
1831 }
1832 else /* Argc >= 3 */
1833 {
1834 if (!KdbpGetEnterCondition(l, TRUE, &ConditionFirst))
1835 ASSERT(0);
1836 if (!KdbpGetEnterCondition(l, FALSE, &ConditionLast))
1837 ASSERT(0);
1838 if (l < (RTL_NUMBER_OF(ExceptionNames) - 1))
1839 {
1840 KdbpPrint("Condition for exception #%02d (%s): FirstChance %s LastChance %s\n",
1841 l, ExceptionNames[l],
1842 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst),
1843 KDB_ENTER_CONDITION_TO_STRING(ConditionLast));
1844 }
1845 else
1846 {
1847 KdbpPrint("Condition for all other exceptions: FirstChance %s LastChance %s\n",
1848 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst),
1849 KDB_ENTER_CONDITION_TO_STRING(ConditionLast));
1850 }
1851 }
1852 }
1853 }
1854 else if (strcmp(Argv[1], "break_on_module_load") == 0)
1855 {
1856 if (Argc == 2)
1857 KdbpPrint("break_on_module_load = %s\n", KdbBreakOnModuleLoad ? "enabled" : "disabled");
1858 else if (Argc >= 3)
1859 {
1860 if (_stricmp(Argv[2], "enable") == 0 || _stricmp(Argv[2], "enabled") == 0 ||
1861 _stricmp(Argv[2], "true") == 0)
1862 KdbBreakOnModuleLoad = TRUE;
1863 else if (_stricmp(Argv[2], "disable") == 0 || _stricmp(Argv[2], "disabled") == 0 ||
1864 _stricmp(Argv[2], "false") == 0)
1865 KdbBreakOnModuleLoad = FALSE;
1866 else
1867 KdbpPrint("Unknown setting '%s'.\n", Argv[2]);
1868 }
1869 }
1870 else
1871 KdbpPrint("Unknown setting '%s'.\n", Argv[1]);
1872
1873 return TRUE;
1874 }
1875
1876 /*!\brief Displays help screen.
1877 */
1878 STATIC BOOLEAN
1879 KdbpCmdHelp(ULONG Argc, PCHAR Argv[])
1880 {
1881 ULONG i;
1882
1883 KdbpPrint("Kernel debugger commands:\n");
1884 for (i = 0; i < RTL_NUMBER_OF(KdbDebuggerCommands); i++)
1885 {
1886 if (KdbDebuggerCommands[i].Syntax == NULL) /* Command group */
1887 {
1888 if (i > 0)
1889 KdbpPrint("\n");
1890 KdbpPrint("\x1b[7m* %s:\x1b[0m\n", KdbDebuggerCommands[i].Help);
1891 continue;
1892 }
1893
1894 KdbpPrint(" %-20s - %s\n",
1895 KdbDebuggerCommands[i].Syntax,
1896 KdbDebuggerCommands[i].Help);
1897 }
1898
1899 return TRUE;
1900 }
1901
1902 /*!\brief Prints the given string with printf-like formatting.
1903 *
1904 * \param Format Format of the string/arguments.
1905 * \param ... Variable number of arguments matching the format specified in \a Format.
1906 *
1907 * \note Doesn't correctly handle \\t and terminal escape sequences when calculating the
1908 * number of lines required to print a single line from the Buffer in the terminal.
1909 */
1910 VOID
1911 KdbpPrint(
1912 IN PCHAR Format,
1913 IN ... OPTIONAL)
1914 {
1915 STATIC CHAR Buffer[4096];
1916 STATIC BOOLEAN TerminalInitialized = FALSE;
1917 STATIC BOOLEAN TerminalConnected = FALSE;
1918 STATIC BOOLEAN TerminalReportsSize = TRUE;
1919 CHAR c = '\0';
1920 PCHAR p, p2;
1921 ULONG Length;
1922 ULONG i, j;
1923 LONG RowsPrintedByTerminal;
1924 ULONG ScanCode;
1925 va_list ap;
1926
1927 /* Check if the user has aborted output of the current command */
1928 if (KdbOutputAborted)
1929 return;
1930
1931 /* Initialize the terminal */
1932 if (!TerminalInitialized)
1933 {
1934 DbgPrint("\x1b[7h"); /* Enable linewrap */
1935
1936 /* Query terminal type */
1937 /*DbgPrint("\x1b[Z");*/
1938 DbgPrint("\x05");
1939
1940 TerminalInitialized = TRUE;
1941 Length = 0;
1942 KeStallExecutionProcessor(100000);
1943
1944 for (;;)
1945 {
1946 c = KdbpTryGetCharSerial(5000);
1947 if (c == -1)
1948 break;
1949 Buffer[Length++] = c;
1950 if (Length >= (sizeof (Buffer) - 1))
1951 break;
1952 }
1953 Buffer[Length] = '\0';
1954 if (Length > 0)
1955 TerminalConnected = TRUE;
1956 }
1957
1958 /* Get number of rows and columns in terminal */
1959 if ((KdbNumberOfRowsTerminal < 0) || (KdbNumberOfColsTerminal < 0) ||
1960 (KdbNumberOfRowsPrinted) == 0) /* Refresh terminal size each time when number of rows printed is 0 */
1961 {
1962 if ((KdbDebugState & KD_DEBUG_KDSERIAL) && TerminalConnected && TerminalReportsSize)
1963 {
1964 /* Try to query number of rows from terminal. A reply looks like "\x1b[8;24;80t" */
1965 TerminalReportsSize = FALSE;
1966 KeStallExecutionProcessor(100000);
1967 DbgPrint("\x1b[18t");
1968 c = KdbpTryGetCharSerial(5000);
1969 if (c == KEY_ESC)
1970 {
1971 c = KdbpTryGetCharSerial(5000);
1972 if (c == '[')
1973 {
1974 Length = 0;
1975 for (;;)
1976 {
1977 c = KdbpTryGetCharSerial(5000);
1978 if (c == -1)
1979 break;
1980 Buffer[Length++] = c;
1981 if (isalpha(c) || Length >= (sizeof (Buffer) - 1))
1982 break;
1983 }
1984 Buffer[Length] = '\0';
1985 if (Buffer[0] == '8' && Buffer[1] == ';')
1986 {
1987 for (i = 2; (i < Length) && (Buffer[i] != ';'); i++);
1988 if (Buffer[i] == ';')
1989 {
1990 Buffer[i++] = '\0';
1991 /* Number of rows is now at Buffer + 2 and number of cols at Buffer + i */
1992 KdbNumberOfRowsTerminal = strtoul(Buffer + 2, NULL, 0);
1993 KdbNumberOfColsTerminal = strtoul(Buffer + i, NULL, 0);
1994 TerminalReportsSize = TRUE;
1995 }
1996 }
1997 }
1998 /* Clear further characters */
1999 while ((c = KdbpTryGetCharSerial(5000)) != -1);
2000 }
2001 }
2002
2003 if (KdbNumberOfRowsTerminal <= 0)
2004 {
2005 /* Set number of rows to the default. */
2006 KdbNumberOfRowsTerminal = 24;
2007 }
2008 else if (KdbNumberOfColsTerminal <= 0)
2009 {
2010 /* Set number of cols to the default. */
2011 KdbNumberOfColsTerminal = 80;
2012 }
2013 }
2014
2015 /* Get the string */
2016 va_start(ap, Format);
2017 Length = _vsnprintf(Buffer, sizeof (Buffer) - 1, Format, ap);
2018 Buffer[Length] = '\0';
2019 va_end(ap);
2020
2021 p = Buffer;
2022 while (p[0] != '\0')
2023 {
2024 i = strcspn(p, "\n");
2025
2026 /* Calculate the number of lines which will be printed in the terminal
2027 * when outputting the current line
2028 */
2029 if (i > 0)
2030 RowsPrintedByTerminal = (i + KdbNumberOfColsPrinted - 1) / KdbNumberOfColsTerminal;
2031 else
2032 RowsPrintedByTerminal = 0;
2033 if (p[i] == '\n')
2034 RowsPrintedByTerminal++;
2035
2036 /*DbgPrint("!%d!%d!%d!%d!", KdbNumberOfRowsPrinted, KdbNumberOfColsPrinted, i, RowsPrintedByTerminal);*/
2037
2038 /* Display a prompt if we printed one screen full of text */
2039 if (KdbNumberOfRowsTerminal > 0 &&
2040 (LONG)(KdbNumberOfRowsPrinted + RowsPrintedByTerminal) >= KdbNumberOfRowsTerminal)
2041 {
2042 if (KdbNumberOfColsPrinted > 0)
2043 DbgPrint("\n");
2044 DbgPrint("--- Press q to abort, any other key to continue ---");
2045 if (KdbDebugState & KD_DEBUG_KDSERIAL)
2046 c = KdbpGetCharSerial();
2047 else
2048 c = KdbpGetCharKeyboard(&ScanCode);
2049 if (c == '\r')
2050 {
2051 /* Try to read '\n' which might follow '\r' - if \n is not received here
2052 * it will be interpreted as "return" when the next command should be read.
2053 */
2054 if (KdbDebugState & KD_DEBUG_KDSERIAL)
2055 c = KdbpTryGetCharSerial(5);
2056 else
2057 c = KdbpTryGetCharKeyboard(&ScanCode, 5);
2058 }
2059 DbgPrint("\n");
2060 if (c == 'q')
2061 {
2062 KdbOutputAborted = TRUE;
2063 return;
2064 }
2065 KdbNumberOfRowsPrinted = 0;
2066 KdbNumberOfColsPrinted = 0;
2067 }
2068
2069 /* Insert a NUL after the line and print only the current line. */
2070 if (p[i] == '\n' && p[i + 1] != '\0')
2071 {
2072 c = p[i + 1];
2073 p[i + 1] = '\0';
2074 }
2075 else
2076 {
2077 c = '\0';
2078 }
2079
2080 /* Remove escape sequences from the line if there's no terminal connected */
2081 if (!TerminalConnected)
2082 {
2083 while ((p2 = strrchr(p, '\x1b')) != NULL) /* Look for escape character */
2084 {
2085 if (p2[1] == '[')
2086 {
2087 j = 2;
2088 while (!isalpha(p2[j++]));
2089 strcpy(p2, p2 + j);
2090 }
2091 else
2092 {
2093 strcpy(p2, p2 + 1);
2094 }
2095 }
2096 }
2097
2098 DbgPrint("%s", p);
2099
2100 if (c != '\0')
2101 p[i + 1] = c;
2102
2103 /* Set p to the start of the next line and
2104 * remember the number of rows/cols printed
2105 */
2106 p += i;
2107 if (p[0] == '\n')
2108 {
2109 p++;
2110 KdbNumberOfColsPrinted = 0;
2111 }
2112 else
2113 {
2114 ASSERT(p[0] == '\0');
2115 KdbNumberOfColsPrinted += i;
2116 }
2117 KdbNumberOfRowsPrinted += RowsPrintedByTerminal;
2118 }
2119 }
2120
2121 /*!\brief Appends a command to the command history
2122 *
2123 * \param Command Pointer to the command to append to the history.
2124 */
2125 STATIC VOID
2126 KdbpCommandHistoryAppend(
2127 IN PCHAR Command)
2128 {
2129 ULONG Length1 = strlen(Command) + 1;
2130 ULONG Length2 = 0;
2131 INT i;
2132 PCHAR Buffer;
2133
2134 ASSERT(Length1 <= RTL_NUMBER_OF(KdbCommandHistoryBuffer));
2135
2136 if (Length1 <= 1 ||
2137 (KdbCommandHistory[KdbCommandHistoryIndex] != NULL &&
2138 strcmp(KdbCommandHistory[KdbCommandHistoryIndex], Command) == 0))
2139 {
2140 return;
2141 }
2142
2143 /* Calculate Length1 and Length2 */
2144 Buffer = KdbCommandHistoryBuffer + KdbCommandHistoryBufferIndex;
2145 KdbCommandHistoryBufferIndex += Length1;
2146 if (KdbCommandHistoryBufferIndex >= (LONG)RTL_NUMBER_OF(KdbCommandHistoryBuffer))
2147 {
2148 KdbCommandHistoryBufferIndex -= RTL_NUMBER_OF(KdbCommandHistoryBuffer);
2149 Length2 = KdbCommandHistoryBufferIndex;
2150 Length1 -= Length2;
2151 }
2152
2153 /* Remove previous commands until there is enough space to append the new command */
2154 for (i = KdbCommandHistoryIndex; KdbCommandHistory[i] != NULL;)
2155 {
2156 if ((Length2 > 0 &&
2157 (KdbCommandHistory[i] >= Buffer ||
2158 KdbCommandHistory[i] < (KdbCommandHistoryBuffer + KdbCommandHistoryBufferIndex))) ||
2159 (Length2 <= 0 &&
2160 (KdbCommandHistory[i] >= Buffer &&
2161 KdbCommandHistory[i] < (KdbCommandHistoryBuffer + KdbCommandHistoryBufferIndex))))
2162 {
2163 KdbCommandHistory[i] = NULL;
2164 }
2165 i--;
2166 if (i < 0)
2167 i = RTL_NUMBER_OF(KdbCommandHistory) - 1;
2168 if (i == KdbCommandHistoryIndex)
2169 break;
2170 }
2171
2172 /* Make sure the new command history entry is free */
2173 KdbCommandHistoryIndex++;
2174 KdbCommandHistoryIndex %= RTL_NUMBER_OF(KdbCommandHistory);
2175 if (KdbCommandHistory[KdbCommandHistoryIndex] != NULL)
2176 {
2177 KdbCommandHistory[KdbCommandHistoryIndex] = NULL;
2178 }
2179
2180 /* Append command */
2181 KdbCommandHistory[KdbCommandHistoryIndex] = Buffer;
2182 ASSERT((KdbCommandHistory[KdbCommandHistoryIndex] + Length1) <= KdbCommandHistoryBuffer + RTL_NUMBER_OF(KdbCommandHistoryBuffer));
2183 memcpy(KdbCommandHistory[KdbCommandHistoryIndex], Command, Length1);
2184 if (Length2 > 0)
2185 {
2186 memcpy(KdbCommandHistoryBuffer, Command + Length1, Length2);
2187 }
2188 }
2189
2190 /*!\brief Reads a line of user-input.
2191 *
2192 * \param Buffer Buffer to store the input into. Trailing newlines are removed.
2193 * \param Size Size of \a Buffer.
2194 *
2195 * \note Accepts only \n newlines, \r is ignored.
2196 */
2197 STATIC VOID
2198 KdbpReadCommand(
2199 OUT PCHAR Buffer,
2200 IN ULONG Size)
2201 {
2202 CHAR Key;
2203 PCHAR Orig = Buffer;
2204 ULONG ScanCode = 0;
2205 BOOLEAN EchoOn;
2206 STATIC CHAR LastCommand[1024] = "";
2207 STATIC CHAR NextKey = '\0';
2208 INT CmdHistIndex = -1;
2209 INT i;
2210
2211 EchoOn = !((KdbDebugState & KD_DEBUG_KDNOECHO) != 0);
2212
2213 for (;;)
2214 {
2215 if (KdbDebugState & KD_DEBUG_KDSERIAL)
2216 {
2217 Key = (NextKey == '\0') ? KdbpGetCharSerial() : NextKey;
2218 NextKey = '\0';
2219 ScanCode = 0;
2220 if (Key == KEY_ESC) /* ESC */
2221 {
2222 Key = KdbpGetCharSerial();
2223 if (Key == '[')
2224 {
2225 Key = KdbpGetCharSerial();
2226 switch (Key)
2227 {
2228 case 'A':
2229 ScanCode = KEY_SCAN_UP;
2230 break;
2231 case 'B':
2232 ScanCode = KEY_SCAN_DOWN;
2233 break;
2234 case 'C':
2235 break;
2236 case 'D':
2237 break;
2238 }
2239 }
2240 }
2241 }
2242 else
2243 {
2244 ScanCode = 0;
2245 Key = (NextKey == '\0') ? KdbpGetCharKeyboard(&ScanCode) : NextKey;
2246 NextKey = '\0';
2247 }
2248
2249 if ((ULONG)(Buffer - Orig) >= (Size - 1))
2250 {
2251 /* Buffer is full, accept only newlines */
2252 if (Key != '\n')
2253 continue;
2254 }
2255
2256 if (Key == '\r')
2257 {
2258 /* Read the next char - this is to throw away a \n which most clients should
2259 * send after \r.
2260 */
2261 KeStallExecutionProcessor(100000);
2262 if (KdbDebugState & KD_DEBUG_KDSERIAL)
2263 NextKey = KdbpTryGetCharSerial(5);
2264 else
2265 NextKey = KdbpTryGetCharKeyboard(&ScanCode, 5);
2266 if (NextKey == '\n' || NextKey == -1) /* \n or no response at all */
2267 NextKey = '\0';
2268 KdbpPrint("\n");
2269 /*
2270 * Repeat the last command if the user presses enter. Reduces the
2271 * risk of RSI when single-stepping.
2272 */
2273 if (Buffer == Orig)
2274 {
2275 strncpy(Buffer, LastCommand, Size);
2276 Buffer[Size - 1] = '\0';
2277 }
2278 else
2279 {
2280 *Buffer = '\0';
2281 strncpy(LastCommand, Orig, sizeof (LastCommand));
2282 LastCommand[sizeof (LastCommand) - 1] = '\0';
2283 }
2284 return;
2285 }
2286 else if (Key == KEY_BS || Key == KEY_DEL)
2287 {
2288 if (Buffer > Orig)
2289 {
2290 Buffer--;
2291 *Buffer = 0;
2292 if (EchoOn)
2293 KdbpPrint("%c %c", KEY_BS, KEY_BS);
2294 else
2295 KdbpPrint(" %c", KEY_BS);
2296 }
2297 }
2298 else if (ScanCode == KEY_SCAN_UP)
2299 {
2300 BOOLEAN Print = TRUE;
2301 if (CmdHistIndex < 0)
2302 CmdHistIndex = KdbCommandHistoryIndex;
2303 else
2304 {
2305 i = CmdHistIndex - 1;
2306 if (i < 0)
2307 CmdHistIndex = RTL_NUMBER_OF(KdbCommandHistory) - 1;
2308 if (KdbCommandHistory[i] != NULL && i != KdbCommandHistoryIndex)
2309 CmdHistIndex = i;
2310 else
2311 Print = FALSE;
2312 }
2313 if (Print && KdbCommandHistory[CmdHistIndex] != NULL)
2314 {
2315 while (Buffer > Orig)
2316 {
2317 Buffer--;
2318 *Buffer = 0;
2319 if (EchoOn)
2320 KdbpPrint("%c %c", KEY_BS, KEY_BS);
2321 else
2322 KdbpPrint(" %c", KEY_BS);
2323 }
2324 i = min(strlen(KdbCommandHistory[CmdHistIndex]), Size - 1);
2325 memcpy(Orig, KdbCommandHistory[CmdHistIndex], i);
2326 Orig[i] = '\0';
2327 Buffer = Orig + i;
2328 KdbpPrint("%s", Orig);
2329 }
2330 }
2331 else if (ScanCode == KEY_SCAN_DOWN)
2332 {
2333 if (CmdHistIndex > 0 && CmdHistIndex != KdbCommandHistoryIndex)
2334 {
2335 i = CmdHistIndex + 1;
2336 if (i >= (INT)RTL_NUMBER_OF(KdbCommandHistory))
2337 i = 0;
2338 if (KdbCommandHistory[i] != NULL)
2339 {
2340 CmdHistIndex = i;
2341 while (Buffer > Orig)
2342 {
2343 Buffer--;
2344 *Buffer = 0;
2345 if (EchoOn)
2346 KdbpPrint("%c %c", KEY_BS, KEY_BS);
2347 else
2348 KdbpPrint(" %c", KEY_BS);
2349 }
2350 i = min(strlen(KdbCommandHistory[CmdHistIndex]), Size - 1);
2351 memcpy(Orig, KdbCommandHistory[CmdHistIndex], i);
2352 Orig[i] = '\0';
2353 Buffer = Orig + i;
2354 KdbpPrint("%s", Orig);
2355 }
2356 }
2357 }
2358 else
2359 {
2360 if (EchoOn)
2361 KdbpPrint("%c", Key);
2362
2363 *Buffer = Key;
2364 Buffer++;
2365 }
2366 }
2367 }
2368
2369 /*!\brief Parses command line and executes command if found
2370 *
2371 * \param Command Command line to parse and execute if possible.
2372 *
2373 * \retval TRUE Don't continue execution.
2374 * \retval FALSE Continue execution (leave KDB)
2375 */
2376 STATIC BOOLEAN
2377 KdbpDoCommand(
2378 IN PCHAR Command)
2379 {
2380 ULONG i;
2381 PCHAR p;
2382 ULONG Argc;
2383 STATIC PCH Argv[256];
2384 STATIC CHAR OrigCommand[1024];
2385
2386 strncpy(OrigCommand, Command, sizeof(OrigCommand) - 1);
2387 OrigCommand[sizeof(OrigCommand) - 1] = '\0';
2388
2389 Argc = 0;
2390 p = Command;
2391 for (;;)
2392 {
2393 while (*p == '\t' || *p == ' ')
2394 p++;
2395 if (*p == '\0')
2396 break;
2397
2398 i = strcspn(p, "\t ");
2399 Argv[Argc++] = p;
2400 p += i;
2401 if (*p == '\0')
2402 break;
2403 *p = '\0';
2404 p++;
2405 }
2406 if (Argc < 1)
2407 return TRUE;
2408
2409 for (i = 0; i < RTL_NUMBER_OF(KdbDebuggerCommands); i++)
2410 {
2411 if (KdbDebuggerCommands[i].Name == NULL)
2412 continue;
2413
2414 if (strcmp(KdbDebuggerCommands[i].Name, Argv[0]) == 0)
2415 {
2416 return KdbDebuggerCommands[i].Fn(Argc, Argv);
2417 }
2418 }
2419
2420 KdbpPrint("Command '%s' is unknown.\n", OrigCommand);
2421 return TRUE;
2422 }
2423
2424 /*!\brief KDB Main Loop.
2425 *
2426 * \param EnteredOnSingleStep TRUE if KDB was entered on single step.
2427 */
2428 VOID
2429 KdbpCliMainLoop(
2430 IN BOOLEAN EnteredOnSingleStep)
2431 {
2432 STATIC CHAR Command[1024];
2433 BOOLEAN Continue;
2434
2435 if (EnteredOnSingleStep)
2436 {
2437 if (!KdbSymPrintAddress((PVOID)KdbCurrentTrapFrame->Tf.Eip))
2438 {
2439 KdbpPrint("<%x>", KdbCurrentTrapFrame->Tf.Eip);
2440 }
2441 KdbpPrint(": ");
2442 if (KdbpDisassemble(KdbCurrentTrapFrame->Tf.Eip, KdbUseIntelSyntax) < 0)
2443 {
2444 KdbpPrint("<INVALID>");
2445 }
2446 KdbpPrint("\n");
2447 }
2448
2449 /* Flush the input buffer */
2450 if (KdbDebugState & KD_DEBUG_KDSERIAL)
2451 {
2452 while (KdbpTryGetCharSerial(1) != -1);
2453 }
2454 else
2455 {
2456 ULONG ScanCode;
2457 while (KdbpTryGetCharKeyboard(&ScanCode, 1) != -1);
2458 }
2459
2460 /* Main loop */
2461 do
2462 {
2463 /* Print the prompt */
2464 KdbpPrint("kdb:> ");
2465
2466 /* Read a command and remember it */
2467 KdbpReadCommand(Command, sizeof (Command));
2468 KdbpCommandHistoryAppend(Command);
2469
2470 /* Reset the number of rows/cols printed and output aborted state */
2471 KdbNumberOfRowsPrinted = KdbNumberOfColsPrinted = 0;
2472 KdbOutputAborted = FALSE;
2473
2474 /* Call the command */
2475 Continue = KdbpDoCommand(Command);
2476 } while (Continue);
2477 }
2478
2479 /*!\brief Called when a module is loaded.
2480 *
2481 * \param Name Filename of the module which was loaded.
2482 */
2483 VOID
2484 KdbpCliModuleLoaded(IN PUNICODE_STRING Name)
2485 {
2486 if (!KdbBreakOnModuleLoad)
2487 return;
2488
2489 KdbpPrint("Module %wZ loaded.\n", Name);
2490 DbgBreakPointWithStatus(DBG_STATUS_CONTROL_C);
2491 }
2492
2493 /*!\brief This function is called by KdbEnterDebuggerException...
2494 *
2495 * Used to interpret the init file in a context with a trapframe setup
2496 * (KdbpCliInit call KdbEnter which will call KdbEnterDebuggerException which will
2497 * call this function if KdbInitFileBuffer is not NULL.
2498 */
2499 VOID
2500 KdbpCliInterpretInitFile()
2501 {
2502 PCHAR p1, p2;
2503 INT i;
2504 CHAR c;
2505
2506 /* Execute the commands in the init file */
2507 DPRINT("KDB: Executing KDBinit file...\n");
2508 p1 = KdbInitFileBuffer;
2509 while (p1[0] != '\0')
2510 {
2511 i = strcspn(p1, "\r\n");
2512 if (i > 0)
2513 {
2514 c = p1[i];
2515 p1[i] = '\0';
2516
2517 /* Look for "break" command and comments */
2518 p2 = p1;
2519 while (isspace(p2[0]))
2520 p2++;
2521 if (strncmp(p2, "break", sizeof("break")-1) == 0 &&
2522 (p2[sizeof("break")-1] == '\0' || isspace(p2[sizeof("break")-1])))
2523 {
2524 /* break into the debugger */
2525 KdbpCliMainLoop(FALSE);
2526 }
2527 else if (p2[0] != '#' && p2[0] != '\0') /* Ignore empty lines and comments */
2528 {
2529 KdbpDoCommand(p1);
2530 }
2531
2532 p1[i] = c;
2533 }
2534 p1 += i;
2535 while (p1[0] == '\r' || p1[0] == '\n')
2536 p1++;
2537 }
2538 DPRINT("KDB: KDBinit executed\n");
2539 }
2540
2541 /*!\brief Called when KDB is initialized
2542 *
2543 * Reads the KDBinit file from the SystemRoot\system32\drivers\etc directory and executes it.
2544 */
2545 VOID
2546 KdbpCliInit()
2547 {
2548 NTSTATUS Status;
2549 OBJECT_ATTRIBUTES ObjectAttributes;
2550 UNICODE_STRING FileName;
2551 IO_STATUS_BLOCK Iosb;
2552 FILE_STANDARD_INFORMATION FileStdInfo;
2553 HANDLE hFile = NULL;
2554 INT FileSize;
2555 PCHAR FileBuffer;
2556 ULONG OldEflags = 0;
2557
2558 /* Initialize the object attributes */
2559 RtlInitUnicodeString(&FileName, L"\\SystemRoot\\system32\\drivers\\etc\\KDBinit");
2560 InitializeObjectAttributes(&ObjectAttributes, &FileName, 0, NULL, NULL);
2561
2562 /* Open the file */
2563 Status = ZwOpenFile(&hFile, FILE_READ_DATA, &ObjectAttributes, &Iosb, 0,
2564 FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT |
2565 FILE_NO_INTERMEDIATE_BUFFERING);
2566 if (!NT_SUCCESS(Status))
2567 {
2568 DPRINT("Could not open \\SystemRoot\\system32\\drivers\\etc\\KDBinit (Status 0x%x)", Status);
2569 return;
2570 }
2571
2572 /* Get the size of the file */
2573 Status = ZwQueryInformationFile(hFile, &Iosb, &FileStdInfo, sizeof (FileStdInfo),
2574 FileStandardInformation);
2575 if (!NT_SUCCESS(Status))
2576 {
2577 ZwClose(hFile);
2578 DPRINT("Could not query size of \\SystemRoot\\system32\\drivers\\etc\\KDBinit (Status 0x%x)", Status);
2579 return;
2580 }
2581 FileSize = FileStdInfo.EndOfFile.u.LowPart;
2582
2583 /* Allocate memory for the file */
2584 FileBuffer = ExAllocatePool(PagedPool, FileSize + 1); /* add 1 byte for terminating '\0' */
2585 if (FileBuffer == NULL)
2586 {
2587 ZwClose(hFile);
2588 DPRINT("Could not allocate %d bytes for KDBinit file\n", FileSize);
2589 return;
2590 }
2591
2592 /* Load file into memory */
2593 Status = ZwReadFile(hFile, 0, 0, 0, &Iosb, FileBuffer, FileSize, 0, 0);
2594 ZwClose(hFile);
2595 if (!NT_SUCCESS(Status) && Status != STATUS_END_OF_FILE)
2596 {
2597 ExFreePool(FileBuffer);
2598 DPRINT("Could not read KDBinit file into memory (Status 0x%lx)\n", Status);
2599 return;
2600 }
2601 FileSize = min(FileSize, (INT)Iosb.Information);
2602 FileBuffer[FileSize] = '\0';
2603
2604 /* Enter critical section */
2605 Ke386SaveFlags(OldEflags);
2606 _disable();
2607
2608 /* Interpret the init file... */
2609 KdbInitFileBuffer = FileBuffer;
2610 KdbEnter();
2611 KdbInitFileBuffer = NULL;
2612
2613 /* Leave critical section */
2614 Ke386RestoreFlags(OldEflags);
2615
2616 ExFreePool(FileBuffer);
2617 }
2618