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