Sync up to trunk head.
[reactos.git] / 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 along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
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 = MAXULONG;
451 else
452 set = MAXULONG;
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",Result);
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, Idtr;
652 USHORT Ldtr;
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(&Gdtr.Limit);
669 Ldtr = Ke386GetLocalDescriptorTable();
670 __sidt(&Idtr.Limit);
671
672 /* Display the control registers */
673 KdbpPrint("CR0 0x%08x ", Cr0);
674
675 for (i = 0; i < 32; i++)
676 {
677 if (!Cr0Bits[i])
678 continue;
679
680 if ((Cr0 & (1 << i)) != 0)
681 KdbpPrint(Cr0Bits[i]);
682 }
683
684 KdbpPrint("\nCR2 0x%08x\n", Cr2);
685 KdbpPrint("CR3 0x%08x Pagedir-Base 0x%08x %s%s\n", Cr3, (Cr3 & 0xfffff000),
686 (Cr3 & (1 << 3)) ? " PWT" : "", (Cr3 & (1 << 4)) ? " PCD" : "" );
687 KdbpPrint("CR4 0x%08x ", Cr4);
688
689 for (i = 0; i < 32; i++)
690 {
691 if (!Cr4Bits[i])
692 continue;
693
694 if ((Cr4 & (1 << i)) != 0)
695 KdbpPrint(Cr4Bits[i]);
696 }
697
698 /* Display the descriptor table regs */
699 KdbpPrint("\nGDTR Base 0x%08x Size 0x%04x\n", Gdtr.Base, Gdtr.Limit);
700 KdbpPrint("LDTR 0x%04x\n", Ldtr);
701 KdbpPrint("IDTR Base 0x%08x Size 0x%04x\n", Idtr.Base, Idtr.Limit);
702 }
703 else if (Argv[0][0] == 's') /* sregs */
704 {
705 KdbpPrint("CS 0x%04x Index 0x%04x %cDT RPL%d\n",
706 Tf->SegCs & 0xffff, (Tf->SegCs & 0xffff) >> 3,
707 (Tf->SegCs & (1 << 2)) ? 'L' : 'G', Tf->SegCs & 3);
708 KdbpPrint("DS 0x%04x Index 0x%04x %cDT RPL%d\n",
709 Tf->SegDs, Tf->SegDs >> 3, (Tf->SegDs & (1 << 2)) ? 'L' : 'G', Tf->SegDs & 3);
710 KdbpPrint("ES 0x%04x Index 0x%04x %cDT RPL%d\n",
711 Tf->SegEs, Tf->SegEs >> 3, (Tf->SegEs & (1 << 2)) ? 'L' : 'G', Tf->SegEs & 3);
712 KdbpPrint("FS 0x%04x Index 0x%04x %cDT RPL%d\n",
713 Tf->SegFs, Tf->SegFs >> 3, (Tf->SegFs & (1 << 2)) ? 'L' : 'G', Tf->SegFs & 3);
714 KdbpPrint("GS 0x%04x Index 0x%04x %cDT RPL%d\n",
715 Tf->SegGs, Tf->SegGs >> 3, (Tf->SegGs & (1 << 2)) ? 'L' : 'G', Tf->SegGs & 3);
716 KdbpPrint("SS 0x%04x Index 0x%04x %cDT RPL%d\n",
717 Tf->HardwareSegSs, Tf->HardwareSegSs >> 3, (Tf->HardwareSegSs & (1 << 2)) ? 'L' : 'G', Tf->HardwareSegSs & 3);
718 }
719 else /* dregs */
720 {
721 ASSERT(Argv[0][0] == 'd');
722 KdbpPrint("DR0 0x%08x\n"
723 "DR1 0x%08x\n"
724 "DR2 0x%08x\n"
725 "DR3 0x%08x\n"
726 "DR6 0x%08x\n"
727 "DR7 0x%08x\n",
728 Tf->Dr0, Tf->Dr1, Tf->Dr2, Tf->Dr3,
729 Tf->Dr6, Tf->Dr7);
730 }
731
732 return TRUE;
733 }
734
735 /*!\brief Displays a backtrace.
736 */
737 static BOOLEAN
738 KdbpCmdBackTrace(
739 ULONG Argc,
740 PCHAR Argv[])
741 {
742 ULONG Count;
743 ULONG ul;
744 ULONGLONG Result = 0;
745 ULONG_PTR Frame = KdbCurrentTrapFrame->Tf.Ebp;
746 ULONG_PTR Address;
747
748 if (Argc >= 2)
749 {
750 /* Check for [L count] part */
751 ul = 0;
752
753 if (strcmp(Argv[Argc-2], "L") == 0)
754 {
755 ul = strtoul(Argv[Argc-1], NULL, 0);
756 if (ul > 0)
757 {
758 Count = ul;
759 Argc -= 2;
760 }
761 }
762 else if (Argv[Argc-1][0] == 'L')
763 {
764 ul = strtoul(Argv[Argc-1] + 1, NULL, 0);
765 if (ul > 0)
766 {
767 Count = ul;
768 Argc--;
769 }
770 }
771
772 /* Put the remaining arguments back together */
773 Argc--;
774 for (ul = 1; ul < Argc; ul++)
775 {
776 Argv[ul][strlen(Argv[ul])] = ' ';
777 }
778 Argc++;
779 }
780
781 /* Check if frame addr or thread id is given. */
782 if (Argc > 1)
783 {
784 if (Argv[1][0] == '*')
785 {
786 Argv[1]++;
787
788 /* Evaluate the expression */
789 if (!KdbpEvaluateExpression(Argv[1], sizeof("kdb:> ")-1 + (Argv[1]-Argv[0]), &Result))
790 return TRUE;
791
792 if (Result > (ULONGLONG)(~((ULONG_PTR)0)))
793 KdbpPrint("Warning: Address %I64x is beeing truncated\n",Result);
794
795 Frame = (ULONG_PTR)Result;
796 }
797 else
798 {
799 KdbpPrint("Thread backtrace not supported yet!\n");
800 return TRUE;
801 }
802 }
803 else
804 {
805 KdbpPrint("Eip:\n");
806
807 /* Try printing the function at EIP */
808 if (!KdbSymPrintAddress((PVOID)KdbCurrentTrapFrame->Tf.Eip))
809 KdbpPrint("<%08x>\n", KdbCurrentTrapFrame->Tf.Eip);
810 else
811 KdbpPrint("\n");
812 }
813
814 KdbpPrint("Frames:\n");
815 for (;;)
816 {
817 if (Frame == 0)
818 break;
819
820 if (!NT_SUCCESS(KdbpSafeReadMemory(&Address, (PVOID)(Frame + sizeof(ULONG_PTR)), sizeof (ULONG_PTR))))
821 {
822 KdbpPrint("Couldn't access memory at 0x%p!\n", Frame + sizeof(ULONG_PTR));
823 break;
824 }
825
826 /* Print the location of the call instruction */
827 if (!KdbSymPrintAddress((PVOID)(Address - 5)))
828 KdbpPrint("<%08x>\n", Address);
829 else
830 KdbpPrint("\n");
831
832 if (Address == 0)
833 break;
834
835 if (!NT_SUCCESS(KdbpSafeReadMemory(&Frame, (PVOID)Frame, sizeof (ULONG_PTR))))
836 {
837 KdbpPrint("Couldn't access memory at 0x%p!\n", Frame);
838 break;
839 }
840 }
841
842 return TRUE;
843 }
844
845 /*!\brief Continues execution of the system/leaves KDB.
846 */
847 static BOOLEAN
848 KdbpCmdContinue(
849 ULONG Argc,
850 PCHAR Argv[])
851 {
852 /* Exit the main loop */
853 return FALSE;
854 }
855
856 /*!\brief Continues execution of the system/leaves KDB.
857 */
858 static BOOLEAN
859 KdbpCmdStep(
860 ULONG Argc,
861 PCHAR Argv[])
862 {
863 ULONG Count = 1;
864
865 if (Argc > 1)
866 {
867 Count = strtoul(Argv[1], NULL, 0);
868 if (Count == 0)
869 {
870 KdbpPrint("%s: Integer argument required\n", Argv[0]);
871 return TRUE;
872 }
873 }
874
875 if (Argv[0][0] == 'n')
876 KdbSingleStepOver = TRUE;
877 else
878 KdbSingleStepOver = FALSE;
879
880 /* Set the number of single steps and return to the interrupted code. */
881 KdbNumSingleSteps = Count;
882
883 return FALSE;
884 }
885
886 /*!\brief Lists breakpoints.
887 */
888 static BOOLEAN
889 KdbpCmdBreakPointList(
890 ULONG Argc,
891 PCHAR Argv[])
892 {
893 LONG l;
894 ULONG_PTR Address = 0;
895 KDB_BREAKPOINT_TYPE Type = 0;
896 KDB_ACCESS_TYPE AccessType = 0;
897 UCHAR Size = 0;
898 UCHAR DebugReg = 0;
899 BOOLEAN Enabled = FALSE;
900 BOOLEAN Global = FALSE;
901 PEPROCESS Process = NULL;
902 PCHAR str1, str2, ConditionExpr, GlobalOrLocal;
903 CHAR Buffer[20];
904
905 l = KdbpGetNextBreakPointNr(0);
906 if (l < 0)
907 {
908 KdbpPrint("No breakpoints.\n");
909 return TRUE;
910 }
911
912 KdbpPrint("Breakpoints:\n");
913 do
914 {
915 if (!KdbpGetBreakPointInfo(l, &Address, &Type, &Size, &AccessType, &DebugReg,
916 &Enabled, &Global, &Process, &ConditionExpr))
917 {
918 continue;
919 }
920
921 if (l == KdbLastBreakPointNr)
922 {
923 str1 = "\x1b[1m*";
924 str2 = "\x1b[0m";
925 }
926 else
927 {
928 str1 = " ";
929 str2 = "";
930 }
931
932 if (Global)
933 {
934 GlobalOrLocal = " global";
935 }
936 else
937 {
938 GlobalOrLocal = Buffer;
939 sprintf(Buffer, " PID 0x%08lx",
940 (ULONG)(Process ? Process->UniqueProcessId : INVALID_HANDLE_VALUE));
941 }
942
943 if (Type == KdbBreakPointSoftware || Type == KdbBreakPointTemporary)
944 {
945 KdbpPrint(" %s%03d BPX 0x%08x%s%s%s%s%s\n",
946 str1, l, Address,
947 Enabled ? "" : " disabled",
948 GlobalOrLocal,
949 ConditionExpr ? " IF " : "",
950 ConditionExpr ? ConditionExpr : "",
951 str2);
952 }
953 else if (Type == KdbBreakPointHardware)
954 {
955 if (!Enabled)
956 {
957 KdbpPrint(" %s%03d BPM 0x%08x %-5s %-5s disabled%s%s%s%s\n", str1, l, Address,
958 KDB_ACCESS_TYPE_TO_STRING(AccessType),
959 Size == 1 ? "byte" : (Size == 2 ? "word" : "dword"),
960 GlobalOrLocal,
961 ConditionExpr ? " IF " : "",
962 ConditionExpr ? ConditionExpr : "",
963 str2);
964 }
965 else
966 {
967 KdbpPrint(" %s%03d BPM 0x%08x %-5s %-5s DR%d%s%s%s%s\n", str1, l, Address,
968 KDB_ACCESS_TYPE_TO_STRING(AccessType),
969 Size == 1 ? "byte" : (Size == 2 ? "word" : "dword"),
970 DebugReg,
971 GlobalOrLocal,
972 ConditionExpr ? " IF " : "",
973 ConditionExpr ? ConditionExpr : "",
974 str2);
975 }
976 }
977 }
978 while ((l = KdbpGetNextBreakPointNr(l+1)) >= 0);
979
980 return TRUE;
981 }
982
983 /*!\brief Enables, disables or clears a breakpoint.
984 */
985 static BOOLEAN
986 KdbpCmdEnableDisableClearBreakPoint(
987 ULONG Argc,
988 PCHAR Argv[])
989 {
990 PCHAR pend;
991 ULONG BreakPointNr;
992
993 if (Argc < 2)
994 {
995 KdbpPrint("%s: argument required\n", Argv[0]);
996 return TRUE;
997 }
998
999 pend = Argv[1];
1000 BreakPointNr = strtoul(Argv[1], &pend, 0);
1001 if (pend == Argv[1] || *pend != '\0')
1002 {
1003 KdbpPrint("%s: integer argument required\n", Argv[0]);
1004 return TRUE;
1005 }
1006
1007 if (Argv[0][1] == 'e') /* enable */
1008 {
1009 KdbpEnableBreakPoint(BreakPointNr, NULL);
1010 }
1011 else if (Argv [0][1] == 'd') /* disable */
1012 {
1013 KdbpDisableBreakPoint(BreakPointNr, NULL);
1014 }
1015 else /* clear */
1016 {
1017 ASSERT(Argv[0][1] == 'c');
1018 KdbpDeleteBreakPoint(BreakPointNr, NULL);
1019 }
1020
1021 return TRUE;
1022 }
1023
1024 /*!\brief Sets a software or hardware (memory) breakpoint at the given address.
1025 */
1026 static BOOLEAN
1027 KdbpCmdBreakPoint(ULONG Argc, PCHAR Argv[])
1028 {
1029 ULONGLONG Result = 0;
1030 ULONG_PTR Address;
1031 KDB_BREAKPOINT_TYPE Type;
1032 UCHAR Size = 0;
1033 KDB_ACCESS_TYPE AccessType = 0;
1034 ULONG AddressArgIndex, i;
1035 LONG ConditionArgIndex;
1036 BOOLEAN Global = TRUE;
1037
1038 if (Argv[0][2] == 'x') /* software breakpoint */
1039 {
1040 if (Argc < 2)
1041 {
1042 KdbpPrint("bpx: Address argument required.\n");
1043 return TRUE;
1044 }
1045
1046 AddressArgIndex = 1;
1047 Type = KdbBreakPointSoftware;
1048 }
1049 else /* memory breakpoint */
1050 {
1051 ASSERT(Argv[0][2] == 'm');
1052
1053 if (Argc < 2)
1054 {
1055 KdbpPrint("bpm: Access type argument required (one of r, w, rw, x)\n");
1056 return TRUE;
1057 }
1058
1059 if (_stricmp(Argv[1], "x") == 0)
1060 AccessType = KdbAccessExec;
1061 else if (_stricmp(Argv[1], "r") == 0)
1062 AccessType = KdbAccessRead;
1063 else if (_stricmp(Argv[1], "w") == 0)
1064 AccessType = KdbAccessWrite;
1065 else if (_stricmp(Argv[1], "rw") == 0)
1066 AccessType = KdbAccessReadWrite;
1067 else
1068 {
1069 KdbpPrint("bpm: Unknown access type '%s'\n", Argv[1]);
1070 return TRUE;
1071 }
1072
1073 if (Argc < 3)
1074 {
1075 KdbpPrint("bpm: %s argument required.\n", AccessType == KdbAccessExec ? "Address" : "Memory size");
1076 return TRUE;
1077 }
1078
1079 AddressArgIndex = 3;
1080 if (_stricmp(Argv[2], "byte") == 0)
1081 Size = 1;
1082 else if (_stricmp(Argv[2], "word") == 0)
1083 Size = 2;
1084 else if (_stricmp(Argv[2], "dword") == 0)
1085 Size = 4;
1086 else if (AccessType == KdbAccessExec)
1087 {
1088 Size = 1;
1089 AddressArgIndex--;
1090 }
1091 else
1092 {
1093 KdbpPrint("bpm: Unknown memory size '%s'\n", Argv[2]);
1094 return TRUE;
1095 }
1096
1097 if (Argc <= AddressArgIndex)
1098 {
1099 KdbpPrint("bpm: Address argument required.\n");
1100 return TRUE;
1101 }
1102
1103 Type = KdbBreakPointHardware;
1104 }
1105
1106 /* Put the arguments back together */
1107 ConditionArgIndex = -1;
1108 for (i = AddressArgIndex; i < (Argc-1); i++)
1109 {
1110 if (strcmp(Argv[i+1], "IF") == 0) /* IF found */
1111 {
1112 ConditionArgIndex = i + 2;
1113 if (ConditionArgIndex >= Argc)
1114 {
1115 KdbpPrint("%s: IF requires condition expression.\n", Argv[0]);
1116 return TRUE;
1117 }
1118
1119 for (i = ConditionArgIndex; i < (Argc-1); i++)
1120 Argv[i][strlen(Argv[i])] = ' ';
1121
1122 break;
1123 }
1124
1125 Argv[i][strlen(Argv[i])] = ' ';
1126 }
1127
1128 /* Evaluate the address expression */
1129 if (!KdbpEvaluateExpression(Argv[AddressArgIndex],
1130 sizeof("kdb:> ")-1 + (Argv[AddressArgIndex]-Argv[0]),
1131 &Result))
1132 {
1133 return TRUE;
1134 }
1135
1136 if (Result > (ULONGLONG)(~((ULONG_PTR)0)))
1137 KdbpPrint("%s: Warning: Address %I64x is beeing truncated\n", Argv[0],Result);
1138
1139 Address = (ULONG_PTR)Result;
1140
1141 KdbpInsertBreakPoint(Address, Type, Size, AccessType,
1142 (ConditionArgIndex < 0) ? NULL : Argv[ConditionArgIndex],
1143 Global, NULL);
1144
1145 return TRUE;
1146 }
1147
1148 /*!\brief Lists threads or switches to another thread context.
1149 */
1150 static BOOLEAN
1151 KdbpCmdThread(
1152 ULONG Argc,
1153 PCHAR Argv[])
1154 {
1155 PLIST_ENTRY Entry;
1156 PETHREAD Thread = NULL;
1157 PEPROCESS Process = NULL;
1158 BOOLEAN ReferencedThread = FALSE, ReferencedProcess = FALSE;
1159 PULONG Esp;
1160 PULONG Ebp;
1161 ULONG Eip;
1162 ULONG ul = 0;
1163 PCHAR State, pend, str1, str2;
1164 static const PCHAR ThreadStateToString[DeferredReady+1] =
1165 {
1166 "Initialized", "Ready", "Running",
1167 "Standby", "Terminated", "Waiting",
1168 "Transition", "DeferredReady"
1169 };
1170
1171 ASSERT(KdbCurrentProcess);
1172
1173 if (Argc >= 2 && _stricmp(Argv[1], "list") == 0)
1174 {
1175 Process = KdbCurrentProcess;
1176
1177 if (Argc >= 3)
1178 {
1179 ul = strtoul(Argv[2], &pend, 0);
1180 if (Argv[2] == pend)
1181 {
1182 KdbpPrint("thread: '%s' is not a valid process id!\n", Argv[2]);
1183 return TRUE;
1184 }
1185
1186 if (!NT_SUCCESS(PsLookupProcessByProcessId((PVOID)ul, &Process)))
1187 {
1188 KdbpPrint("thread: Invalid process id!\n");
1189 return TRUE;
1190 }
1191
1192 /* Remember our reference */
1193 ReferencedProcess = TRUE;
1194 }
1195
1196 Entry = Process->ThreadListHead.Flink;
1197 if (Entry == &Process->ThreadListHead)
1198 {
1199 if (Argc >= 3)
1200 KdbpPrint("No threads in process 0x%08x!\n", ul);
1201 else
1202 KdbpPrint("No threads in current process!\n");
1203
1204 if (ReferencedProcess)
1205 ObDereferenceObject(Process);
1206
1207 return TRUE;
1208 }
1209
1210 KdbpPrint(" TID State Prior. Affinity EBP EIP\n");
1211 do
1212 {
1213 Thread = CONTAINING_RECORD(Entry, ETHREAD, ThreadListEntry);
1214
1215 if (Thread == KdbCurrentThread)
1216 {
1217 str1 = "\x1b[1m*";
1218 str2 = "\x1b[0m";
1219 }
1220 else
1221 {
1222 str1 = " ";
1223 str2 = "";
1224 }
1225
1226 if (!Thread->Tcb.InitialStack)
1227 {
1228 /* Thread has no kernel stack (probably terminated) */
1229 Esp = Ebp = NULL;
1230 Eip = 0;
1231 }
1232 else if (Thread->Tcb.TrapFrame)
1233 {
1234 if (Thread->Tcb.TrapFrame->PreviousPreviousMode == KernelMode)
1235 Esp = (PULONG)Thread->Tcb.TrapFrame->TempEsp;
1236 else
1237 Esp = (PULONG)Thread->Tcb.TrapFrame->HardwareEsp;
1238
1239 Ebp = (PULONG)Thread->Tcb.TrapFrame->Ebp;
1240 Eip = Thread->Tcb.TrapFrame->Eip;
1241 }
1242 else
1243 {
1244 Esp = (PULONG)Thread->Tcb.KernelStack;
1245 Ebp = (PULONG)Esp[4];
1246 Eip = 0;
1247
1248 if (Ebp) /* FIXME: Should we attach to the process to read Ebp[1]? */
1249 KdbpSafeReadMemory(&Eip, Ebp + 1, sizeof (Eip));
1250 }
1251
1252 if (Thread->Tcb.State < (DeferredReady + 1))
1253 State = ThreadStateToString[Thread->Tcb.State];
1254 else
1255 State = "Unknown";
1256
1257 KdbpPrint(" %s0x%08x %-11s %3d 0x%08x 0x%08x 0x%08x%s\n",
1258 str1,
1259 Thread->Cid.UniqueThread,
1260 State,
1261 Thread->Tcb.Priority,
1262 Thread->Tcb.Affinity,
1263 Ebp,
1264 Eip,
1265 str2);
1266
1267 Entry = Entry->Flink;
1268 }
1269 while (Entry != &Process->ThreadListHead);
1270
1271 /* Release our reference, if any */
1272 if (ReferencedProcess)
1273 ObDereferenceObject(Process);
1274 }
1275 else if (Argc >= 2 && _stricmp(Argv[1], "attach") == 0)
1276 {
1277 if (Argc < 3)
1278 {
1279 KdbpPrint("thread attach: thread id argument required!\n");
1280 return TRUE;
1281 }
1282
1283 ul = strtoul(Argv[2], &pend, 0);
1284 if (Argv[2] == pend)
1285 {
1286 KdbpPrint("thread attach: '%s' is not a valid thread id!\n", Argv[2]);
1287 return TRUE;
1288 }
1289
1290 if (!KdbpAttachToThread((PVOID)ul))
1291 {
1292 return TRUE;
1293 }
1294
1295 KdbpPrint("Attached to thread 0x%08x.\n", ul);
1296 }
1297 else
1298 {
1299 Thread = KdbCurrentThread;
1300
1301 if (Argc >= 2)
1302 {
1303 ul = strtoul(Argv[1], &pend, 0);
1304 if (Argv[1] == pend)
1305 {
1306 KdbpPrint("thread: '%s' is not a valid thread id!\n", Argv[1]);
1307 return TRUE;
1308 }
1309
1310 if (!NT_SUCCESS(PsLookupThreadByThreadId((PVOID)ul, &Thread)))
1311 {
1312 KdbpPrint("thread: Invalid thread id!\n");
1313 return TRUE;
1314 }
1315
1316 /* Remember our reference */
1317 ReferencedThread = TRUE;
1318 }
1319
1320 if (Thread->Tcb.State < (DeferredReady + 1))
1321 State = ThreadStateToString[Thread->Tcb.State];
1322 else
1323 State = "Unknown";
1324
1325 KdbpPrint("%s"
1326 " TID: 0x%08x\n"
1327 " State: %s (0x%x)\n"
1328 " Priority: %d\n"
1329 " Affinity: 0x%08x\n"
1330 " Initial Stack: 0x%08x\n"
1331 " Stack Limit: 0x%08x\n"
1332 " Stack Base: 0x%08x\n"
1333 " Kernel Stack: 0x%08x\n"
1334 " Trap Frame: 0x%08x\n"
1335 " NPX State: %s (0x%x)\n",
1336 (Argc < 2) ? "Current Thread:\n" : "",
1337 Thread->Cid.UniqueThread,
1338 State, Thread->Tcb.State,
1339 Thread->Tcb.Priority,
1340 Thread->Tcb.Affinity,
1341 Thread->Tcb.InitialStack,
1342 Thread->Tcb.StackLimit,
1343 Thread->Tcb.StackBase,
1344 Thread->Tcb.KernelStack,
1345 Thread->Tcb.TrapFrame,
1346 NPX_STATE_TO_STRING(Thread->Tcb.NpxState), Thread->Tcb.NpxState);
1347
1348 /* Release our reference if we had one */
1349 if (ReferencedThread)
1350 ObDereferenceObject(Thread);
1351 }
1352
1353 return TRUE;
1354 }
1355
1356 /*!\brief Lists processes or switches to another process context.
1357 */
1358 static BOOLEAN
1359 KdbpCmdProc(
1360 ULONG Argc,
1361 PCHAR Argv[])
1362 {
1363 PLIST_ENTRY Entry;
1364 PEPROCESS Process;
1365 BOOLEAN ReferencedProcess = FALSE;
1366 PCHAR State, pend, str1, str2;
1367 ULONG ul;
1368 extern LIST_ENTRY PsActiveProcessHead;
1369
1370 if (Argc >= 2 && _stricmp(Argv[1], "list") == 0)
1371 {
1372 Entry = PsActiveProcessHead.Flink;
1373 if (!Entry || Entry == &PsActiveProcessHead)
1374 {
1375 KdbpPrint("No processes in the system!\n");
1376 return TRUE;
1377 }
1378
1379 KdbpPrint(" PID State Filename\n");
1380 do
1381 {
1382 Process = CONTAINING_RECORD(Entry, EPROCESS, ActiveProcessLinks);
1383
1384 if (Process == KdbCurrentProcess)
1385 {
1386 str1 = "\x1b[1m*";
1387 str2 = "\x1b[0m";
1388 }
1389 else
1390 {
1391 str1 = " ";
1392 str2 = "";
1393 }
1394
1395 State = ((Process->Pcb.State == ProcessInMemory) ? "In Memory" :
1396 ((Process->Pcb.State == ProcessOutOfMemory) ? "Out of Memory" : "In Transition"));
1397
1398 KdbpPrint(" %s0x%08x %-10s %s%s\n",
1399 str1,
1400 Process->UniqueProcessId,
1401 State,
1402 Process->ImageFileName,
1403 str2);
1404
1405 Entry = Entry->Flink;
1406 }
1407 while(Entry != &PsActiveProcessHead);
1408 }
1409 else if (Argc >= 2 && _stricmp(Argv[1], "attach") == 0)
1410 {
1411 if (Argc < 3)
1412 {
1413 KdbpPrint("process attach: process id argument required!\n");
1414 return TRUE;
1415 }
1416
1417 ul = strtoul(Argv[2], &pend, 0);
1418 if (Argv[2] == pend)
1419 {
1420 KdbpPrint("process attach: '%s' is not a valid process id!\n", Argv[2]);
1421 return TRUE;
1422 }
1423
1424 if (!KdbpAttachToProcess((PVOID)ul))
1425 {
1426 return TRUE;
1427 }
1428
1429 KdbpPrint("Attached to process 0x%08x, thread 0x%08x.\n", (ULONG)ul,
1430 (ULONG)KdbCurrentThread->Cid.UniqueThread);
1431 }
1432 else
1433 {
1434 Process = KdbCurrentProcess;
1435
1436 if (Argc >= 2)
1437 {
1438 ul = strtoul(Argv[1], &pend, 0);
1439 if (Argv[1] == pend)
1440 {
1441 KdbpPrint("proc: '%s' is not a valid process id!\n", Argv[1]);
1442 return TRUE;
1443 }
1444
1445 if (!NT_SUCCESS(PsLookupProcessByProcessId((PVOID)ul, &Process)))
1446 {
1447 KdbpPrint("proc: Invalid process id!\n");
1448 return TRUE;
1449 }
1450
1451 /* Remember our reference */
1452 ReferencedProcess = TRUE;
1453 }
1454
1455 State = ((Process->Pcb.State == ProcessInMemory) ? "In Memory" :
1456 ((Process->Pcb.State == ProcessOutOfMemory) ? "Out of Memory" : "In Transition"));
1457 KdbpPrint("%s"
1458 " PID: 0x%08x\n"
1459 " State: %s (0x%x)\n"
1460 " Image Filename: %s\n",
1461 (Argc < 2) ? "Current process:\n" : "",
1462 Process->UniqueProcessId,
1463 State, Process->Pcb.State,
1464 Process->ImageFileName);
1465
1466 /* Release our reference, if any */
1467 if (ReferencedProcess)
1468 ObDereferenceObject(Process);
1469 }
1470
1471 return TRUE;
1472 }
1473
1474 /*!\brief Lists loaded modules or the one containing the specified address.
1475 */
1476 static BOOLEAN
1477 KdbpCmdMod(
1478 ULONG Argc,
1479 PCHAR Argv[])
1480 {
1481 ULONGLONG Result = 0;
1482 ULONG_PTR Address;
1483 PLDR_DATA_TABLE_ENTRY LdrEntry;
1484 BOOLEAN DisplayOnlyOneModule = FALSE;
1485 INT i = 0;
1486
1487 if (Argc >= 2)
1488 {
1489 /* Put the arguments back together */
1490 Argc--;
1491 while (--Argc >= 1)
1492 Argv[Argc][strlen(Argv[Argc])] = ' ';
1493
1494 /* Evaluate the expression */
1495 if (!KdbpEvaluateExpression(Argv[1], sizeof("kdb:> ")-1 + (Argv[1]-Argv[0]), &Result))
1496 {
1497 return TRUE;
1498 }
1499
1500 if (Result > (ULONGLONG)(~((ULONG_PTR)0)))
1501 KdbpPrint("%s: Warning: Address %I64x is beeing truncated\n", Argv[0],Result);
1502
1503 Address = (ULONG_PTR)Result;
1504
1505 if (!KdbpSymFindModule((PVOID)Address, NULL, -1, &LdrEntry))
1506 {
1507 KdbpPrint("No module containing address 0x%p found!\n", Address);
1508 return TRUE;
1509 }
1510
1511 DisplayOnlyOneModule = TRUE;
1512 }
1513 else
1514 {
1515 if (!KdbpSymFindModule(NULL, NULL, 0, &LdrEntry))
1516 {
1517 ULONG_PTR ntoskrnlBase = ((ULONG_PTR)KdbpCmdMod) & 0xfff00000;
1518 KdbpPrint(" Base Size Name\n");
1519 KdbpPrint(" %08x %08x %s\n", ntoskrnlBase, 0, "ntoskrnl.exe");
1520 return TRUE;
1521 }
1522
1523 i = 1;
1524 }
1525
1526 KdbpPrint(" Base Size Name\n");
1527 for (;;)
1528 {
1529 KdbpPrint(" %08x %08x %wZ\n", LdrEntry->DllBase, LdrEntry->SizeOfImage, &LdrEntry->BaseDllName);
1530
1531 if(DisplayOnlyOneModule || !KdbpSymFindModule(NULL, NULL, i++, &LdrEntry))
1532 break;
1533 }
1534
1535 return TRUE;
1536 }
1537
1538 /*!\brief Displays GDT, LDT or IDTd.
1539 */
1540 static BOOLEAN
1541 KdbpCmdGdtLdtIdt(
1542 ULONG Argc,
1543 PCHAR Argv[])
1544 {
1545 KDESCRIPTOR Reg;
1546 ULONG SegDesc[2];
1547 ULONG SegBase;
1548 ULONG SegLimit;
1549 PCHAR SegType;
1550 USHORT SegSel;
1551 UCHAR Type, Dpl;
1552 INT i;
1553 ULONG ul;
1554
1555 if (Argv[0][0] == 'i')
1556 {
1557 /* Read IDTR */
1558 __sidt(&Reg.Limit);
1559
1560 if (Reg.Limit < 7)
1561 {
1562 KdbpPrint("Interrupt descriptor table is empty.\n");
1563 return TRUE;
1564 }
1565
1566 KdbpPrint("IDT Base: 0x%08x Limit: 0x%04x\n", Reg.Base, Reg.Limit);
1567 KdbpPrint(" Idx Type Seg. Sel. Offset DPL\n");
1568
1569 for (i = 0; (i + sizeof(SegDesc) - 1) <= Reg.Limit; i += 8)
1570 {
1571 if (!NT_SUCCESS(KdbpSafeReadMemory(SegDesc, (PVOID)(Reg.Base + i), sizeof(SegDesc))))
1572 {
1573 KdbpPrint("Couldn't access memory at 0x%08x!\n", Reg.Base + i);
1574 return TRUE;
1575 }
1576
1577 Dpl = ((SegDesc[1] >> 13) & 3);
1578 if ((SegDesc[1] & 0x1f00) == 0x0500) /* Task gate */
1579 SegType = "TASKGATE";
1580 else if ((SegDesc[1] & 0x1fe0) == 0x0e00) /* 32 bit Interrupt gate */
1581 SegType = "INTGATE32";
1582 else if ((SegDesc[1] & 0x1fe0) == 0x0600) /* 16 bit Interrupt gate */
1583 SegType = "INTGATE16";
1584 else if ((SegDesc[1] & 0x1fe0) == 0x0f00) /* 32 bit Trap gate */
1585 SegType = "TRAPGATE32";
1586 else if ((SegDesc[1] & 0x1fe0) == 0x0700) /* 16 bit Trap gate */
1587 SegType = "TRAPGATE16";
1588 else
1589 SegType = "UNKNOWN";
1590
1591 if ((SegDesc[1] & (1 << 15)) == 0) /* not present */
1592 {
1593 KdbpPrint(" %03d %-10s [NP] [NP] %02d\n",
1594 i / 8, SegType, Dpl);
1595 }
1596 else if ((SegDesc[1] & 0x1f00) == 0x0500) /* Task gate */
1597 {
1598 SegSel = SegDesc[0] >> 16;
1599 KdbpPrint(" %03d %-10s 0x%04x %02d\n",
1600 i / 8, SegType, SegSel, Dpl);
1601 }
1602 else
1603 {
1604 SegSel = SegDesc[0] >> 16;
1605 SegBase = (SegDesc[1] & 0xffff0000) | (SegDesc[0] & 0x0000ffff);
1606 KdbpPrint(" %03d %-10s 0x%04x 0x%08x %02d\n",
1607 i / 8, SegType, SegSel, SegBase, Dpl);
1608 }
1609 }
1610 }
1611 else
1612 {
1613 ul = 0;
1614
1615 if (Argv[0][0] == 'g')
1616 {
1617 /* Read GDTR */
1618 Ke386GetGlobalDescriptorTable(&Reg.Limit);
1619 i = 8;
1620 }
1621 else
1622 {
1623 ASSERT(Argv[0][0] == 'l');
1624
1625 /* Read LDTR */
1626 Reg.Limit = Ke386GetLocalDescriptorTable();
1627 Reg.Base = 0;
1628 i = 0;
1629 ul = 1 << 2;
1630 }
1631
1632 if (Reg.Limit < 7)
1633 {
1634 KdbpPrint("%s descriptor table is empty.\n",
1635 Argv[0][0] == 'g' ? "Global" : "Local");
1636 return TRUE;
1637 }
1638
1639 KdbpPrint("%cDT Base: 0x%08x Limit: 0x%04x\n",
1640 Argv[0][0] == 'g' ? 'G' : 'L', Reg.Base, Reg.Limit);
1641 KdbpPrint(" Idx Sel. Type Base Limit DPL Attribs\n");
1642
1643 for (; (i + sizeof(SegDesc) - 1) <= Reg.Limit; i += 8)
1644 {
1645 if (!NT_SUCCESS(KdbpSafeReadMemory(SegDesc, (PVOID)(Reg.Base + i), sizeof(SegDesc))))
1646 {
1647 KdbpPrint("Couldn't access memory at 0x%08x!\n", Reg.Base + i);
1648 return TRUE;
1649 }
1650
1651 Dpl = ((SegDesc[1] >> 13) & 3);
1652 Type = ((SegDesc[1] >> 8) & 0xf);
1653
1654 SegBase = SegDesc[0] >> 16;
1655 SegBase |= (SegDesc[1] & 0xff) << 16;
1656 SegBase |= SegDesc[1] & 0xff000000;
1657 SegLimit = SegDesc[0] & 0x0000ffff;
1658 SegLimit |= (SegDesc[1] >> 16) & 0xf;
1659
1660 if ((SegDesc[1] & (1 << 23)) != 0)
1661 {
1662 SegLimit *= 4096;
1663 SegLimit += 4095;
1664 }
1665 else
1666 {
1667 SegLimit++;
1668 }
1669
1670 if ((SegDesc[1] & (1 << 12)) == 0) /* System segment */
1671 {
1672 switch (Type)
1673 {
1674 case 1: SegType = "TSS16(Avl)"; break;
1675 case 2: SegType = "LDT"; break;
1676 case 3: SegType = "TSS16(Busy)"; break;
1677 case 4: SegType = "CALLGATE16"; break;
1678 case 5: SegType = "TASKGATE"; break;
1679 case 6: SegType = "INTGATE16"; break;
1680 case 7: SegType = "TRAPGATE16"; break;
1681 case 9: SegType = "TSS32(Avl)"; break;
1682 case 11: SegType = "TSS32(Busy)"; break;
1683 case 12: SegType = "CALLGATE32"; break;
1684 case 14: SegType = "INTGATE32"; break;
1685 case 15: SegType = "INTGATE32"; break;
1686 default: SegType = "UNKNOWN"; break;
1687 }
1688
1689 if (!(Type >= 1 && Type <= 3) &&
1690 Type != 9 && Type != 11)
1691 {
1692 SegBase = 0;
1693 SegLimit = 0;
1694 }
1695 }
1696 else if ((SegDesc[1] & (1 << 11)) == 0) /* Data segment */
1697 {
1698 if ((SegDesc[1] & (1 << 22)) != 0)
1699 SegType = "DATA32";
1700 else
1701 SegType = "DATA16";
1702 }
1703 else /* Code segment */
1704 {
1705 if ((SegDesc[1] & (1 << 22)) != 0)
1706 SegType = "CODE32";
1707 else
1708 SegType = "CODE16";
1709 }
1710
1711 if ((SegDesc[1] & (1 << 15)) == 0) /* not present */
1712 {
1713 KdbpPrint(" %03d 0x%04x %-11s [NP] [NP] %02d NP\n",
1714 i / 8, i | Dpl | ul, SegType, Dpl);
1715 }
1716 else
1717 {
1718 KdbpPrint(" %03d 0x%04x %-11s 0x%08x 0x%08x %02d ",
1719 i / 8, i | Dpl | ul, SegType, SegBase, SegLimit, Dpl);
1720
1721 if ((SegDesc[1] & (1 << 12)) == 0) /* System segment */
1722 {
1723 /* FIXME: Display system segment */
1724 }
1725 else if ((SegDesc[1] & (1 << 11)) == 0) /* Data segment */
1726 {
1727 if ((SegDesc[1] & (1 << 10)) != 0) /* Expand-down */
1728 KdbpPrint(" E");
1729
1730 KdbpPrint((SegDesc[1] & (1 << 9)) ? " R/W" : " R");
1731
1732 if ((SegDesc[1] & (1 << 8)) != 0)
1733 KdbpPrint(" A");
1734 }
1735 else /* Code segment */
1736 {
1737 if ((SegDesc[1] & (1 << 10)) != 0) /* Conforming */
1738 KdbpPrint(" C");
1739
1740 KdbpPrint((SegDesc[1] & (1 << 9)) ? " R/X" : " X");
1741
1742 if ((SegDesc[1] & (1 << 8)) != 0)
1743 KdbpPrint(" A");
1744 }
1745
1746 if ((SegDesc[1] & (1 << 20)) != 0)
1747 KdbpPrint(" AVL");
1748
1749 KdbpPrint("\n");
1750 }
1751 }
1752 }
1753
1754 return TRUE;
1755 }
1756
1757 /*!\brief Displays the KPCR
1758 */
1759 static BOOLEAN
1760 KdbpCmdPcr(
1761 ULONG Argc,
1762 PCHAR Argv[])
1763 {
1764 PKIPCR Pcr = (PKIPCR)KeGetPcr();
1765
1766 KdbpPrint("Current PCR is at 0x%08x.\n", (INT)Pcr);
1767 KdbpPrint(" Tib.ExceptionList: 0x%08x\n"
1768 " Tib.StackBase: 0x%08x\n"
1769 " Tib.StackLimit: 0x%08x\n"
1770 " Tib.SubSystemTib: 0x%08x\n"
1771 " Tib.FiberData/Version: 0x%08x\n"
1772 " Tib.ArbitraryUserPointer: 0x%08x\n"
1773 " Tib.Self: 0x%08x\n"
1774 " Self: 0x%08x\n"
1775 " PCRCB: 0x%08x\n"
1776 " Irql: 0x%02x\n"
1777 " IRR: 0x%08x\n"
1778 " IrrActive: 0x%08x\n"
1779 " IDR: 0x%08x\n"
1780 " KdVersionBlock: 0x%08x\n"
1781 " IDT: 0x%08x\n"
1782 " GDT: 0x%08x\n"
1783 " TSS: 0x%08x\n"
1784 " MajorVersion: 0x%04x\n"
1785 " MinorVersion: 0x%04x\n"
1786 " SetMember: 0x%08x\n"
1787 " StallScaleFactor: 0x%08x\n"
1788 " Number: 0x%02x\n"
1789 " L2CacheAssociativity: 0x%02x\n"
1790 " VdmAlert: 0x%08x\n"
1791 " L2CacheSize: 0x%08x\n"
1792 " InterruptMode: 0x%08x\n",
1793 Pcr->NtTib.ExceptionList, Pcr->NtTib.StackBase, Pcr->NtTib.StackLimit,
1794 Pcr->NtTib.SubSystemTib, Pcr->NtTib.FiberData, Pcr->NtTib.ArbitraryUserPointer,
1795 Pcr->NtTib.Self, Pcr->Self, Pcr->Prcb, Pcr->Irql, Pcr->IRR, Pcr->IrrActive,
1796 Pcr->IDR, Pcr->KdVersionBlock, Pcr->IDT, Pcr->GDT, Pcr->TSS,
1797 Pcr->MajorVersion, Pcr->MinorVersion, Pcr->SetMember, Pcr->StallScaleFactor,
1798 Pcr->Number, Pcr->SecondLevelCacheAssociativity,
1799 Pcr->VdmAlert, Pcr->SecondLevelCacheSize, Pcr->InterruptMode);
1800
1801 return TRUE;
1802 }
1803
1804 /*!\brief Displays the TSS
1805 */
1806 static BOOLEAN
1807 KdbpCmdTss(
1808 ULONG Argc,
1809 PCHAR Argv[])
1810 {
1811 KTSS *Tss = KeGetPcr()->TSS;
1812
1813 KdbpPrint("Current TSS is at 0x%08x.\n", (INT)Tss);
1814 KdbpPrint(" Eip: 0x%08x\n"
1815 " Es: 0x%04x\n"
1816 " Cs: 0x%04x\n"
1817 " Ss: 0x%04x\n"
1818 " Ds: 0x%04x\n"
1819 " Fs: 0x%04x\n"
1820 " Gs: 0x%04x\n"
1821 " IoMapBase: 0x%04x\n",
1822 Tss->Eip, Tss->Es, Tss->Cs, Tss->Ds, Tss->Fs, Tss->Gs, Tss->IoMapBase);
1823
1824 return TRUE;
1825 }
1826
1827 /*!\brief Bugchecks the system.
1828 */
1829 static BOOLEAN
1830 KdbpCmdBugCheck(
1831 ULONG Argc,
1832 PCHAR Argv[])
1833 {
1834 /* Set the flag and quit looping */
1835 KdbpBugCheckRequested = TRUE;
1836
1837 return FALSE;
1838 }
1839
1840 /*!\brief Sets or displays a config variables value.
1841 */
1842 static BOOLEAN
1843 KdbpCmdSet(
1844 ULONG Argc,
1845 PCHAR Argv[])
1846 {
1847 LONG l;
1848 BOOLEAN First;
1849 PCHAR pend = 0;
1850 KDB_ENTER_CONDITION ConditionFirst = KdbDoNotEnter;
1851 KDB_ENTER_CONDITION ConditionLast = KdbDoNotEnter;
1852
1853 static const PCHAR ExceptionNames[21] =
1854 {
1855 "ZERODEVIDE", "DEBUGTRAP", "NMI", "INT3", "OVERFLOW", "BOUND", "INVALIDOP",
1856 "NOMATHCOP", "DOUBLEFAULT", "RESERVED(9)", "INVALIDTSS", "SEGMENTNOTPRESENT",
1857 "STACKFAULT", "GPF", "PAGEFAULT", "RESERVED(15)", "MATHFAULT", "ALIGNMENTCHECK",
1858 "MACHINECHECK", "SIMDFAULT", "OTHERS"
1859 };
1860
1861 if (Argc == 1)
1862 {
1863 KdbpPrint("Available settings:\n");
1864 KdbpPrint(" syntax [intel|at&t]\n");
1865 KdbpPrint(" condition [exception|*] [first|last] [never|always|kmode|umode]\n");
1866 KdbpPrint(" break_on_module_load [true|false]\n");
1867 }
1868 else if (strcmp(Argv[1], "syntax") == 0)
1869 {
1870 if (Argc == 2)
1871 {
1872 KdbpPrint("syntax = %s\n", KdbUseIntelSyntax ? "intel" : "at&t");
1873 }
1874 else if (Argc >= 3)
1875 {
1876 if (_stricmp(Argv[2], "intel") == 0)
1877 KdbUseIntelSyntax = TRUE;
1878 else if (_stricmp(Argv[2], "at&t") == 0)
1879 KdbUseIntelSyntax = FALSE;
1880 else
1881 KdbpPrint("Unknown syntax '%s'.\n", Argv[2]);
1882 }
1883 }
1884 else if (strcmp(Argv[1], "condition") == 0)
1885 {
1886 if (Argc == 2)
1887 {
1888 KdbpPrint("Conditions: (First) (Last)\n");
1889 for (l = 0; l < RTL_NUMBER_OF(ExceptionNames) - 1; l++)
1890 {
1891 if (!ExceptionNames[l])
1892 continue;
1893
1894 if (!KdbpGetEnterCondition(l, TRUE, &ConditionFirst))
1895 ASSERT(0);
1896
1897 if (!KdbpGetEnterCondition(l, FALSE, &ConditionLast))
1898 ASSERT(0);
1899
1900 KdbpPrint(" #%02d %-20s %-8s %-8s\n", l, ExceptionNames[l],
1901 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst),
1902 KDB_ENTER_CONDITION_TO_STRING(ConditionLast));
1903 }
1904
1905 ASSERT(l == (RTL_NUMBER_OF(ExceptionNames) - 1));
1906 KdbpPrint(" %-20s %-8s %-8s\n", ExceptionNames[l],
1907 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst),
1908 KDB_ENTER_CONDITION_TO_STRING(ConditionLast));
1909 }
1910 else
1911 {
1912 if (Argc >= 5 && strcmp(Argv[2], "*") == 0) /* Allow * only when setting condition */
1913 {
1914 l = -1;
1915 }
1916 else
1917 {
1918 l = strtoul(Argv[2], &pend, 0);
1919
1920 if (Argv[2] == pend)
1921 {
1922 for (l = 0; l < RTL_NUMBER_OF(ExceptionNames); l++)
1923 {
1924 if (!ExceptionNames[l])
1925 continue;
1926
1927 if (_stricmp(ExceptionNames[l], Argv[2]) == 0)
1928 break;
1929 }
1930 }
1931
1932 if (l >= RTL_NUMBER_OF(ExceptionNames))
1933 {
1934 KdbpPrint("Unknown exception '%s'.\n", Argv[2]);
1935 return TRUE;
1936 }
1937 }
1938
1939 if (Argc > 4)
1940 {
1941 if (_stricmp(Argv[3], "first") == 0)
1942 First = TRUE;
1943 else if (_stricmp(Argv[3], "last") == 0)
1944 First = FALSE;
1945 else
1946 {
1947 KdbpPrint("set condition: second argument must be 'first' or 'last'\n");
1948 return TRUE;
1949 }
1950
1951 if (_stricmp(Argv[4], "never") == 0)
1952 ConditionFirst = KdbDoNotEnter;
1953 else if (_stricmp(Argv[4], "always") == 0)
1954 ConditionFirst = KdbEnterAlways;
1955 else if (_stricmp(Argv[4], "umode") == 0)
1956 ConditionFirst = KdbEnterFromUmode;
1957 else if (_stricmp(Argv[4], "kmode") == 0)
1958 ConditionFirst = KdbEnterFromKmode;
1959 else
1960 {
1961 KdbpPrint("set condition: third argument must be 'never', 'always', 'umode' or 'kmode'\n");
1962 return TRUE;
1963 }
1964
1965 if (!KdbpSetEnterCondition(l, First, ConditionFirst))
1966 {
1967 if (l >= 0)
1968 KdbpPrint("Couldn't change condition for exception #%02d\n", l);
1969 else
1970 KdbpPrint("Couldn't change condition for all exceptions\n", l);
1971 }
1972 }
1973 else /* Argc >= 3 */
1974 {
1975 if (!KdbpGetEnterCondition(l, TRUE, &ConditionFirst))
1976 ASSERT(0);
1977
1978 if (!KdbpGetEnterCondition(l, FALSE, &ConditionLast))
1979 ASSERT(0);
1980
1981 if (l < (RTL_NUMBER_OF(ExceptionNames) - 1))
1982 {
1983 KdbpPrint("Condition for exception #%02d (%s): FirstChance %s LastChance %s\n",
1984 l, ExceptionNames[l],
1985 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst),
1986 KDB_ENTER_CONDITION_TO_STRING(ConditionLast));
1987 }
1988 else
1989 {
1990 KdbpPrint("Condition for all other exceptions: FirstChance %s LastChance %s\n",
1991 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst),
1992 KDB_ENTER_CONDITION_TO_STRING(ConditionLast));
1993 }
1994 }
1995 }
1996 }
1997 else if (strcmp(Argv[1], "break_on_module_load") == 0)
1998 {
1999 if (Argc == 2)
2000 KdbpPrint("break_on_module_load = %s\n", KdbBreakOnModuleLoad ? "enabled" : "disabled");
2001 else if (Argc >= 3)
2002 {
2003 if (_stricmp(Argv[2], "enable") == 0 || _stricmp(Argv[2], "enabled") == 0 || _stricmp(Argv[2], "true") == 0)
2004 KdbBreakOnModuleLoad = TRUE;
2005 else if (_stricmp(Argv[2], "disable") == 0 || _stricmp(Argv[2], "disabled") == 0 || _stricmp(Argv[2], "false") == 0)
2006 KdbBreakOnModuleLoad = FALSE;
2007 else
2008 KdbpPrint("Unknown setting '%s'.\n", Argv[2]);
2009 }
2010 }
2011 else
2012 {
2013 KdbpPrint("Unknown setting '%s'.\n", Argv[1]);
2014 }
2015
2016 return TRUE;
2017 }
2018
2019 /*!\brief Displays help screen.
2020 */
2021 static BOOLEAN
2022 KdbpCmdHelp(
2023 ULONG Argc,
2024 PCHAR Argv[])
2025 {
2026 ULONG i;
2027
2028 KdbpPrint("Kernel debugger commands:\n");
2029 for (i = 0; i < RTL_NUMBER_OF(KdbDebuggerCommands); i++)
2030 {
2031 if (!KdbDebuggerCommands[i].Syntax) /* Command group */
2032 {
2033 if (i > 0)
2034 KdbpPrint("\n");
2035
2036 KdbpPrint("\x1b[7m* %s:\x1b[0m\n", KdbDebuggerCommands[i].Help);
2037 continue;
2038 }
2039
2040 KdbpPrint(" %-20s - %s\n",
2041 KdbDebuggerCommands[i].Syntax,
2042 KdbDebuggerCommands[i].Help);
2043 }
2044
2045 return TRUE;
2046 }
2047
2048 /*!\brief Prints the given string with printf-like formatting.
2049 *
2050 * \param Format Format of the string/arguments.
2051 * \param ... Variable number of arguments matching the format specified in \a Format.
2052 *
2053 * \note Doesn't correctly handle \\t and terminal escape sequences when calculating the
2054 * number of lines required to print a single line from the Buffer in the terminal.
2055 */
2056 VOID
2057 KdbpPrint(
2058 IN PCHAR Format,
2059 IN ... OPTIONAL)
2060 {
2061 static CHAR Buffer[4096];
2062 static BOOLEAN TerminalInitialized = FALSE;
2063 static BOOLEAN TerminalConnected = FALSE;
2064 static BOOLEAN TerminalReportsSize = TRUE;
2065 CHAR c = '\0';
2066 PCHAR p, p2;
2067 ULONG Length;
2068 ULONG i, j;
2069 LONG RowsPrintedByTerminal;
2070 ULONG ScanCode;
2071 va_list ap;
2072
2073 /* Check if the user has aborted output of the current command */
2074 if (KdbOutputAborted)
2075 return;
2076
2077 /* Initialize the terminal */
2078 if (!TerminalInitialized)
2079 {
2080 DbgPrint("\x1b[7h"); /* Enable linewrap */
2081
2082 /* Query terminal type */
2083 /*DbgPrint("\x1b[Z");*/
2084 DbgPrint("\x05");
2085
2086 TerminalInitialized = TRUE;
2087 Length = 0;
2088 KeStallExecutionProcessor(100000);
2089
2090 for (;;)
2091 {
2092 c = KdbpTryGetCharSerial(5000);
2093 if (c == -1)
2094 break;
2095
2096 Buffer[Length++] = c;
2097 if (Length >= (sizeof (Buffer) - 1))
2098 break;
2099 }
2100
2101 Buffer[Length] = '\0';
2102 if (Length > 0)
2103 TerminalConnected = TRUE;
2104 }
2105
2106 /* Get number of rows and columns in terminal */
2107 if ((KdbNumberOfRowsTerminal < 0) || (KdbNumberOfColsTerminal < 0) ||
2108 (KdbNumberOfRowsPrinted) == 0) /* Refresh terminal size each time when number of rows printed is 0 */
2109 {
2110 if ((KdbDebugState & KD_DEBUG_KDSERIAL) && TerminalConnected && TerminalReportsSize)
2111 {
2112 /* Try to query number of rows from terminal. A reply looks like "\x1b[8;24;80t" */
2113 TerminalReportsSize = FALSE;
2114 KeStallExecutionProcessor(100000);
2115 DbgPrint("\x1b[18t");
2116 c = KdbpTryGetCharSerial(5000);
2117
2118 if (c == KEY_ESC)
2119 {
2120 c = KdbpTryGetCharSerial(5000);
2121 if (c == '[')
2122 {
2123 Length = 0;
2124
2125 for (;;)
2126 {
2127 c = KdbpTryGetCharSerial(5000);
2128 if (c == -1)
2129 break;
2130
2131 Buffer[Length++] = c;
2132 if (isalpha(c) || Length >= (sizeof (Buffer) - 1))
2133 break;
2134 }
2135
2136 Buffer[Length] = '\0';
2137 if (Buffer[0] == '8' && Buffer[1] == ';')
2138 {
2139 for (i = 2; (i < Length) && (Buffer[i] != ';'); i++);
2140
2141 if (Buffer[i] == ';')
2142 {
2143 Buffer[i++] = '\0';
2144
2145 /* Number of rows is now at Buffer + 2 and number of cols at Buffer + i */
2146 KdbNumberOfRowsTerminal = strtoul(Buffer + 2, NULL, 0);
2147 KdbNumberOfColsTerminal = strtoul(Buffer + i, NULL, 0);
2148 TerminalReportsSize = TRUE;
2149 }
2150 }
2151 }
2152 /* Clear further characters */
2153 while ((c = KdbpTryGetCharSerial(5000)) != -1);
2154 }
2155 }
2156
2157 if (KdbNumberOfRowsTerminal <= 0)
2158 {
2159 /* Set number of rows to the default. */
2160 KdbNumberOfRowsTerminal = 24;
2161 }
2162 else if (KdbNumberOfColsTerminal <= 0)
2163 {
2164 /* Set number of cols to the default. */
2165 KdbNumberOfColsTerminal = 80;
2166 }
2167 }
2168
2169 /* Get the string */
2170 va_start(ap, Format);
2171 Length = _vsnprintf(Buffer, sizeof (Buffer) - 1, Format, ap);
2172 Buffer[Length] = '\0';
2173 va_end(ap);
2174
2175 p = Buffer;
2176 while (p[0] != '\0')
2177 {
2178 i = strcspn(p, "\n");
2179
2180 /* Calculate the number of lines which will be printed in the terminal
2181 * when outputting the current line
2182 */
2183 if (i > 0)
2184 RowsPrintedByTerminal = (i + KdbNumberOfColsPrinted - 1) / KdbNumberOfColsTerminal;
2185 else
2186 RowsPrintedByTerminal = 0;
2187
2188 if (p[i] == '\n')
2189 RowsPrintedByTerminal++;
2190
2191 /*DbgPrint("!%d!%d!%d!%d!", KdbNumberOfRowsPrinted, KdbNumberOfColsPrinted, i, RowsPrintedByTerminal);*/
2192
2193 /* Display a prompt if we printed one screen full of text */
2194 if (KdbNumberOfRowsTerminal > 0 &&
2195 (LONG)(KdbNumberOfRowsPrinted + RowsPrintedByTerminal) >= KdbNumberOfRowsTerminal)
2196 {
2197 if (KdbNumberOfColsPrinted > 0)
2198 DbgPrint("\n");
2199
2200 DbgPrint("--- Press q to abort, any other key to continue ---");
2201
2202 if (KdbDebugState & KD_DEBUG_KDSERIAL)
2203 c = KdbpGetCharSerial();
2204 else
2205 c = KdbpGetCharKeyboard(&ScanCode);
2206
2207 if (c == '\r')
2208 {
2209 /* Try to read '\n' which might follow '\r' - if \n is not received here
2210 * it will be interpreted as "return" when the next command should be read.
2211 */
2212 if (KdbDebugState & KD_DEBUG_KDSERIAL)
2213 c = KdbpTryGetCharSerial(5);
2214 else
2215 c = KdbpTryGetCharKeyboard(&ScanCode, 5);
2216 }
2217
2218 DbgPrint("\n");
2219 if (c == 'q')
2220 {
2221 KdbOutputAborted = TRUE;
2222 return;
2223 }
2224
2225 KdbNumberOfRowsPrinted = 0;
2226 KdbNumberOfColsPrinted = 0;
2227 }
2228
2229 /* Insert a NUL after the line and print only the current line. */
2230 if (p[i] == '\n' && p[i + 1] != '\0')
2231 {
2232 c = p[i + 1];
2233 p[i + 1] = '\0';
2234 }
2235 else
2236 {
2237 c = '\0';
2238 }
2239
2240 /* Remove escape sequences from the line if there's no terminal connected */
2241 if (!TerminalConnected)
2242 {
2243 while ((p2 = strrchr(p, '\x1b'))) /* Look for escape character */
2244 {
2245 if (p2[1] == '[')
2246 {
2247 j = 2;
2248 while (!isalpha(p2[j++]));
2249 strcpy(p2, p2 + j);
2250 }
2251 else
2252 {
2253 strcpy(p2, p2 + 1);
2254 }
2255 }
2256 }
2257
2258 DbgPrint("%s", p);
2259
2260 if (c != '\0')
2261 p[i + 1] = c;
2262
2263 /* Set p to the start of the next line and
2264 * remember the number of rows/cols printed
2265 */
2266 p += i;
2267 if (p[0] == '\n')
2268 {
2269 p++;
2270 KdbNumberOfColsPrinted = 0;
2271 }
2272 else
2273 {
2274 ASSERT(p[0] == '\0');
2275 KdbNumberOfColsPrinted += i;
2276 }
2277
2278 KdbNumberOfRowsPrinted += RowsPrintedByTerminal;
2279 }
2280 }
2281
2282 /*!\brief Appends a command to the command history
2283 *
2284 * \param Command Pointer to the command to append to the history.
2285 */
2286 static VOID
2287 KdbpCommandHistoryAppend(
2288 IN PCHAR Command)
2289 {
2290 ULONG Length1 = strlen(Command) + 1;
2291 ULONG Length2 = 0;
2292 INT i;
2293 PCHAR Buffer;
2294
2295 ASSERT(Length1 <= RTL_NUMBER_OF(KdbCommandHistoryBuffer));
2296
2297 if (Length1 <= 1 ||
2298 (KdbCommandHistory[KdbCommandHistoryIndex] &&
2299 strcmp(KdbCommandHistory[KdbCommandHistoryIndex], Command) == 0))
2300 {
2301 return;
2302 }
2303
2304 /* Calculate Length1 and Length2 */
2305 Buffer = KdbCommandHistoryBuffer + KdbCommandHistoryBufferIndex;
2306 KdbCommandHistoryBufferIndex += Length1;
2307 if (KdbCommandHistoryBufferIndex >= (LONG)RTL_NUMBER_OF(KdbCommandHistoryBuffer))
2308 {
2309 KdbCommandHistoryBufferIndex -= RTL_NUMBER_OF(KdbCommandHistoryBuffer);
2310 Length2 = KdbCommandHistoryBufferIndex;
2311 Length1 -= Length2;
2312 }
2313
2314 /* Remove previous commands until there is enough space to append the new command */
2315 for (i = KdbCommandHistoryIndex; KdbCommandHistory[i];)
2316 {
2317 if ((Length2 > 0 &&
2318 (KdbCommandHistory[i] >= Buffer ||
2319 KdbCommandHistory[i] < (KdbCommandHistoryBuffer + KdbCommandHistoryBufferIndex))) ||
2320 (Length2 <= 0 &&
2321 (KdbCommandHistory[i] >= Buffer &&
2322 KdbCommandHistory[i] < (KdbCommandHistoryBuffer + KdbCommandHistoryBufferIndex))))
2323 {
2324 KdbCommandHistory[i] = NULL;
2325 }
2326
2327 i--;
2328 if (i < 0)
2329 i = RTL_NUMBER_OF(KdbCommandHistory) - 1;
2330
2331 if (i == KdbCommandHistoryIndex)
2332 break;
2333 }
2334
2335 /* Make sure the new command history entry is free */
2336 KdbCommandHistoryIndex++;
2337 KdbCommandHistoryIndex %= RTL_NUMBER_OF(KdbCommandHistory);
2338 if (KdbCommandHistory[KdbCommandHistoryIndex])
2339 {
2340 KdbCommandHistory[KdbCommandHistoryIndex] = NULL;
2341 }
2342
2343 /* Append command */
2344 KdbCommandHistory[KdbCommandHistoryIndex] = Buffer;
2345 ASSERT((KdbCommandHistory[KdbCommandHistoryIndex] + Length1) <= KdbCommandHistoryBuffer + RTL_NUMBER_OF(KdbCommandHistoryBuffer));
2346 memcpy(KdbCommandHistory[KdbCommandHistoryIndex], Command, Length1);
2347 if (Length2 > 0)
2348 {
2349 memcpy(KdbCommandHistoryBuffer, Command + Length1, Length2);
2350 }
2351 }
2352
2353 /*!\brief Reads a line of user-input.
2354 *
2355 * \param Buffer Buffer to store the input into. Trailing newlines are removed.
2356 * \param Size Size of \a Buffer.
2357 *
2358 * \note Accepts only \n newlines, \r is ignored.
2359 */
2360 static VOID
2361 KdbpReadCommand(
2362 OUT PCHAR Buffer,
2363 IN ULONG Size)
2364 {
2365 CHAR Key;
2366 PCHAR Orig = Buffer;
2367 ULONG ScanCode = 0;
2368 BOOLEAN EchoOn;
2369 static CHAR LastCommand[1024] = "";
2370 static CHAR NextKey = '\0';
2371 INT CmdHistIndex = -1;
2372 INT i;
2373
2374 EchoOn = !((KdbDebugState & KD_DEBUG_KDNOECHO) != 0);
2375
2376 for (;;)
2377 {
2378 if (KdbDebugState & KD_DEBUG_KDSERIAL)
2379 {
2380 Key = (NextKey == '\0') ? KdbpGetCharSerial() : NextKey;
2381 NextKey = '\0';
2382 ScanCode = 0;
2383 if (Key == KEY_ESC) /* ESC */
2384 {
2385 Key = KdbpGetCharSerial();
2386 if (Key == '[')
2387 {
2388 Key = KdbpGetCharSerial();
2389
2390 switch (Key)
2391 {
2392 case 'A':
2393 ScanCode = KEY_SCAN_UP;
2394 break;
2395 case 'B':
2396 ScanCode = KEY_SCAN_DOWN;
2397 break;
2398 case 'C':
2399 break;
2400 case 'D':
2401 break;
2402 }
2403 }
2404 }
2405 }
2406 else
2407 {
2408 ScanCode = 0;
2409 Key = (NextKey == '\0') ? KdbpGetCharKeyboard(&ScanCode) : NextKey;
2410 NextKey = '\0';
2411 }
2412
2413 if ((ULONG)(Buffer - Orig) >= (Size - 1))
2414 {
2415 /* Buffer is full, accept only newlines */
2416 if (Key != '\n')
2417 continue;
2418 }
2419
2420 if (Key == '\r')
2421 {
2422 /* Read the next char - this is to throw away a \n which most clients should
2423 * send after \r.
2424 */
2425 KeStallExecutionProcessor(100000);
2426
2427 if (KdbDebugState & KD_DEBUG_KDSERIAL)
2428 NextKey = KdbpTryGetCharSerial(5);
2429 else
2430 NextKey = KdbpTryGetCharKeyboard(&ScanCode, 5);
2431
2432 if (NextKey == '\n' || NextKey == -1) /* \n or no response at all */
2433 NextKey = '\0';
2434
2435 KdbpPrint("\n");
2436
2437 /*
2438 * Repeat the last command if the user presses enter. Reduces the
2439 * risk of RSI when single-stepping.
2440 */
2441 if (Buffer == Orig)
2442 {
2443 strncpy(Buffer, LastCommand, Size);
2444 Buffer[Size - 1] = '\0';
2445 }
2446 else
2447 {
2448 *Buffer = '\0';
2449 strncpy(LastCommand, Orig, sizeof (LastCommand));
2450 LastCommand[sizeof (LastCommand) - 1] = '\0';
2451 }
2452
2453 return;
2454 }
2455 else if (Key == KEY_BS || Key == KEY_DEL)
2456 {
2457 if (Buffer > Orig)
2458 {
2459 Buffer--;
2460 *Buffer = 0;
2461
2462 if (EchoOn)
2463 KdbpPrint("%c %c", KEY_BS, KEY_BS);
2464 else
2465 KdbpPrint(" %c", KEY_BS);
2466 }
2467 }
2468 else if (ScanCode == KEY_SCAN_UP)
2469 {
2470 BOOLEAN Print = TRUE;
2471
2472 if (CmdHistIndex < 0)
2473 {
2474 CmdHistIndex = KdbCommandHistoryIndex;
2475 }
2476 else
2477 {
2478 i = CmdHistIndex - 1;
2479
2480 if (i < 0)
2481 CmdHistIndex = RTL_NUMBER_OF(KdbCommandHistory) - 1;
2482
2483 if (KdbCommandHistory[i] && i != KdbCommandHistoryIndex)
2484 CmdHistIndex = i;
2485 else
2486 Print = FALSE;
2487 }
2488
2489 if (Print && KdbCommandHistory[CmdHistIndex])
2490 {
2491 while (Buffer > Orig)
2492 {
2493 Buffer--;
2494 *Buffer = 0;
2495
2496 if (EchoOn)
2497 KdbpPrint("%c %c", KEY_BS, KEY_BS);
2498 else
2499 KdbpPrint(" %c", KEY_BS);
2500 }
2501
2502 i = min(strlen(KdbCommandHistory[CmdHistIndex]), Size - 1);
2503 memcpy(Orig, KdbCommandHistory[CmdHistIndex], i);
2504 Orig[i] = '\0';
2505 Buffer = Orig + i;
2506 KdbpPrint("%s", Orig);
2507 }
2508 }
2509 else if (ScanCode == KEY_SCAN_DOWN)
2510 {
2511 if (CmdHistIndex > 0 && CmdHistIndex != KdbCommandHistoryIndex)
2512 {
2513 i = CmdHistIndex + 1;
2514 if (i >= (INT)RTL_NUMBER_OF(KdbCommandHistory))
2515 i = 0;
2516
2517 if (KdbCommandHistory[i])
2518 {
2519 CmdHistIndex = i;
2520 while (Buffer > Orig)
2521 {
2522 Buffer--;
2523 *Buffer = 0;
2524
2525 if (EchoOn)
2526 KdbpPrint("%c %c", KEY_BS, KEY_BS);
2527 else
2528 KdbpPrint(" %c", KEY_BS);
2529 }
2530
2531 i = min(strlen(KdbCommandHistory[CmdHistIndex]), Size - 1);
2532 memcpy(Orig, KdbCommandHistory[CmdHistIndex], i);
2533 Orig[i] = '\0';
2534 Buffer = Orig + i;
2535 KdbpPrint("%s", Orig);
2536 }
2537 }
2538 }
2539 else
2540 {
2541 if (EchoOn)
2542 KdbpPrint("%c", Key);
2543
2544 *Buffer = Key;
2545 Buffer++;
2546 }
2547 }
2548 }
2549
2550 /*!\brief Parses command line and executes command if found
2551 *
2552 * \param Command Command line to parse and execute if possible.
2553 *
2554 * \retval TRUE Don't continue execution.
2555 * \retval FALSE Continue execution (leave KDB)
2556 */
2557 static BOOLEAN
2558 KdbpDoCommand(
2559 IN PCHAR Command)
2560 {
2561 ULONG i;
2562 PCHAR p;
2563 ULONG Argc;
2564 static PCH Argv[256];
2565 static CHAR OrigCommand[1024];
2566
2567 strncpy(OrigCommand, Command, sizeof(OrigCommand) - 1);
2568 OrigCommand[sizeof(OrigCommand) - 1] = '\0';
2569
2570 Argc = 0;
2571 p = Command;
2572
2573 for (;;)
2574 {
2575 while (*p == '\t' || *p == ' ')
2576 p++;
2577
2578 if (*p == '\0')
2579 break;
2580
2581 i = strcspn(p, "\t ");
2582 Argv[Argc++] = p;
2583 p += i;
2584 if (*p == '\0')
2585 break;
2586
2587 *p = '\0';
2588 p++;
2589 }
2590
2591 if (Argc < 1)
2592 return TRUE;
2593
2594 for (i = 0; i < RTL_NUMBER_OF(KdbDebuggerCommands); i++)
2595 {
2596 if (!KdbDebuggerCommands[i].Name)
2597 continue;
2598
2599 if (strcmp(KdbDebuggerCommands[i].Name, Argv[0]) == 0)
2600 {
2601 return KdbDebuggerCommands[i].Fn(Argc, Argv);
2602 }
2603 }
2604
2605 KdbpPrint("Command '%s' is unknown.\n", OrigCommand);
2606 return TRUE;
2607 }
2608
2609 /*!\brief KDB Main Loop.
2610 *
2611 * \param EnteredOnSingleStep TRUE if KDB was entered on single step.
2612 */
2613 VOID
2614 KdbpCliMainLoop(
2615 IN BOOLEAN EnteredOnSingleStep)
2616 {
2617 static CHAR Command[1024];
2618 BOOLEAN Continue;
2619
2620 if (EnteredOnSingleStep)
2621 {
2622 if (!KdbSymPrintAddress((PVOID)KdbCurrentTrapFrame->Tf.Eip))
2623 {
2624 KdbpPrint("<%x>", KdbCurrentTrapFrame->Tf.Eip);
2625 }
2626
2627 KdbpPrint(": ");
2628 if (KdbpDisassemble(KdbCurrentTrapFrame->Tf.Eip, KdbUseIntelSyntax) < 0)
2629 {
2630 KdbpPrint("<INVALID>");
2631 }
2632 KdbpPrint("\n");
2633 }
2634
2635 /* Flush the input buffer */
2636 if (KdbDebugState & KD_DEBUG_KDSERIAL)
2637 {
2638 while (KdbpTryGetCharSerial(1) != -1);
2639 }
2640 else
2641 {
2642 ULONG ScanCode;
2643 while (KdbpTryGetCharKeyboard(&ScanCode, 1) != -1);
2644 }
2645
2646 /* Main loop */
2647 do
2648 {
2649 /* Print the prompt */
2650 KdbpPrint("kdb:> ");
2651
2652 /* Read a command and remember it */
2653 KdbpReadCommand(Command, sizeof (Command));
2654 KdbpCommandHistoryAppend(Command);
2655
2656 /* Reset the number of rows/cols printed and output aborted state */
2657 KdbNumberOfRowsPrinted = KdbNumberOfColsPrinted = 0;
2658 KdbOutputAborted = FALSE;
2659
2660 /* Call the command */
2661 Continue = KdbpDoCommand(Command);
2662 }
2663 while (Continue);
2664 }
2665
2666 /*!\brief Called when a module is loaded.
2667 *
2668 * \param Name Filename of the module which was loaded.
2669 */
2670 VOID
2671 KdbpCliModuleLoaded(
2672 IN PUNICODE_STRING Name)
2673 {
2674 if (!KdbBreakOnModuleLoad)
2675 return;
2676
2677 KdbpPrint("Module %wZ loaded.\n", Name);
2678 DbgBreakPointWithStatus(DBG_STATUS_CONTROL_C);
2679 }
2680
2681 /*!\brief This function is called by KdbEnterDebuggerException...
2682 *
2683 * Used to interpret the init file in a context with a trapframe setup
2684 * (KdbpCliInit call KdbEnter which will call KdbEnterDebuggerException which will
2685 * call this function if KdbInitFileBuffer is not NULL.
2686 */
2687 VOID
2688 KdbpCliInterpretInitFile()
2689 {
2690 PCHAR p1, p2;
2691 INT i;
2692 CHAR c;
2693
2694 /* Execute the commands in the init file */
2695 DPRINT("KDB: Executing KDBinit file...\n");
2696 p1 = KdbInitFileBuffer;
2697 while (p1[0] != '\0')
2698 {
2699 i = strcspn(p1, "\r\n");
2700 if (i > 0)
2701 {
2702 c = p1[i];
2703 p1[i] = '\0';
2704
2705 /* Look for "break" command and comments */
2706 p2 = p1;
2707
2708 while (isspace(p2[0]))
2709 p2++;
2710
2711 if (strncmp(p2, "break", sizeof("break")-1) == 0 &&
2712 (p2[sizeof("break")-1] == '\0' || isspace(p2[sizeof("break")-1])))
2713 {
2714 /* break into the debugger */
2715 KdbpCliMainLoop(FALSE);
2716 }
2717 else if (p2[0] != '#' && p2[0] != '\0') /* Ignore empty lines and comments */
2718 {
2719 KdbpDoCommand(p1);
2720 }
2721
2722 p1[i] = c;
2723 }
2724
2725 p1 += i;
2726 while (p1[0] == '\r' || p1[0] == '\n')
2727 p1++;
2728 }
2729 DPRINT("KDB: KDBinit executed\n");
2730 }
2731
2732 /*!\brief Called when KDB is initialized
2733 *
2734 * Reads the KDBinit file from the SystemRoot\system32\drivers\etc directory and executes it.
2735 */
2736 VOID
2737 KdbpCliInit()
2738 {
2739 NTSTATUS Status;
2740 OBJECT_ATTRIBUTES ObjectAttributes;
2741 UNICODE_STRING FileName;
2742 IO_STATUS_BLOCK Iosb;
2743 FILE_STANDARD_INFORMATION FileStdInfo;
2744 HANDLE hFile = NULL;
2745 INT FileSize;
2746 PCHAR FileBuffer;
2747 ULONG OldEflags;
2748
2749 /* Initialize the object attributes */
2750 RtlInitUnicodeString(&FileName, L"\\SystemRoot\\system32\\drivers\\etc\\KDBinit");
2751 InitializeObjectAttributes(&ObjectAttributes, &FileName, 0, NULL, NULL);
2752
2753 /* Open the file */
2754 Status = ZwOpenFile(&hFile, FILE_READ_DATA, &ObjectAttributes, &Iosb, 0,
2755 FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT |
2756 FILE_NO_INTERMEDIATE_BUFFERING);
2757 if (!NT_SUCCESS(Status))
2758 {
2759 DPRINT("Could not open \\SystemRoot\\system32\\drivers\\etc\\KDBinit (Status 0x%x)", Status);
2760 return;
2761 }
2762
2763 /* Get the size of the file */
2764 Status = ZwQueryInformationFile(hFile, &Iosb, &FileStdInfo, sizeof (FileStdInfo),
2765 FileStandardInformation);
2766 if (!NT_SUCCESS(Status))
2767 {
2768 ZwClose(hFile);
2769 DPRINT("Could not query size of \\SystemRoot\\system32\\drivers\\etc\\KDBinit (Status 0x%x)", Status);
2770 return;
2771 }
2772 FileSize = FileStdInfo.EndOfFile.u.LowPart;
2773
2774 /* Allocate memory for the file */
2775 FileBuffer = ExAllocatePool(PagedPool, FileSize + 1); /* add 1 byte for terminating '\0' */
2776 if (!FileBuffer)
2777 {
2778 ZwClose(hFile);
2779 DPRINT("Could not allocate %d bytes for KDBinit file\n", FileSize);
2780 return;
2781 }
2782
2783 /* Load file into memory */
2784 Status = ZwReadFile(hFile, 0, 0, 0, &Iosb, FileBuffer, FileSize, 0, 0);
2785 ZwClose(hFile);
2786
2787 if (!NT_SUCCESS(Status) && Status != STATUS_END_OF_FILE)
2788 {
2789 ExFreePool(FileBuffer);
2790 DPRINT("Could not read KDBinit file into memory (Status 0x%lx)\n", Status);
2791 return;
2792 }
2793
2794 FileSize = min(FileSize, (INT)Iosb.Information);
2795 FileBuffer[FileSize] = '\0';
2796
2797 /* Enter critical section */
2798 OldEflags = __readeflags();
2799 _disable();
2800
2801 /* Interpret the init file... */
2802 KdbInitFileBuffer = FileBuffer;
2803 KdbEnter();
2804 KdbInitFileBuffer = NULL;
2805
2806 /* Leave critical section */
2807 __writeeflags(OldEflags);
2808
2809 ExFreePool(FileBuffer);
2810 }
2811
2812 VOID
2813 NTAPI
2814 KdpSerialDebugPrint(
2815 LPSTR Message,
2816 ULONG Length
2817 );
2818
2819 STRING KdpPromptString = RTL_CONSTANT_STRING("kdb:> ");
2820 extern KSPIN_LOCK KdpSerialSpinLock;
2821
2822 ULONG
2823 NTAPI
2824 KdpPrompt(IN LPSTR InString,
2825 IN USHORT InStringLength,
2826 OUT LPSTR OutString,
2827 IN USHORT OutStringLength)
2828 {
2829 USHORT i;
2830 CHAR Response;
2831 ULONG DummyScanCode;
2832 KIRQL OldIrql;
2833
2834 /* Acquire the printing spinlock without waiting at raised IRQL */
2835 while (TRUE)
2836 {
2837 /* Wait when the spinlock becomes available */
2838 while (!KeTestSpinLock(&KdpSerialSpinLock));
2839
2840 /* Spinlock was free, raise IRQL */
2841 KeRaiseIrql(HIGH_LEVEL, &OldIrql);
2842
2843 /* Try to get the spinlock */
2844 if (KeTryToAcquireSpinLockAtDpcLevel(&KdpSerialSpinLock))
2845 break;
2846
2847 /* Someone else got the spinlock, lower IRQL back */
2848 KeLowerIrql(OldIrql);
2849 }
2850
2851 /* Loop the string to send */
2852 for (i = 0; i < InStringLength; i++)
2853 {
2854 /* Print it to serial */
2855 KdPortPutByteEx(&SerialPortInfo, *(PCHAR)(InString + i));
2856 }
2857
2858 /* Print a new line for log neatness */
2859 KdPortPutByteEx(&SerialPortInfo, '\r');
2860 KdPortPutByteEx(&SerialPortInfo, '\n');
2861
2862 /* Print the kdb prompt */
2863 for (i = 0; i < KdpPromptString.Length; i++)
2864 {
2865 /* Print it to serial */
2866 KdPortPutByteEx(&SerialPortInfo,
2867 *(KdpPromptString.Buffer + i));
2868 }
2869
2870 /* Loop the whole string */
2871 for (i = 0; i < OutStringLength; i++)
2872 {
2873 /* Check if this is serial debugging mode */
2874 if (KdbDebugState & KD_DEBUG_KDSERIAL)
2875 {
2876 /* Get the character from serial */
2877 do
2878 {
2879 Response = KdbpTryGetCharSerial(MAXULONG);
2880 } while (Response == -1);
2881 }
2882 else
2883 {
2884 /* Get the response from the keyboard */
2885 do
2886 {
2887 Response = KdbpTryGetCharKeyboard(&DummyScanCode, MAXULONG);
2888 } while (Response == -1);
2889 }
2890
2891 /* Check for return */
2892 if (Response == '\r')
2893 {
2894 /*
2895 * We might need to discard the next '\n'.
2896 * Wait a bit to make sure we receive it.
2897 */
2898 KeStallExecutionProcessor(100000);
2899
2900 /* Check the mode */
2901 if (KdbDebugState & KD_DEBUG_KDSERIAL)
2902 {
2903 /* Read and discard the next character, if any */
2904 KdbpTryGetCharSerial(5);
2905 }
2906 else
2907 {
2908 /* Read and discard the next character, if any */
2909 KdbpTryGetCharKeyboard(&DummyScanCode, 5);
2910 }
2911
2912 /*
2913 * Null terminate the output string -- documentation states that
2914 * DbgPrompt does not null terminate, but it does
2915 */
2916 *(PCHAR)(OutString + i) = 0;
2917
2918 /* Print a new line */
2919 KdPortPutByteEx(&SerialPortInfo, '\r');
2920 KdPortPutByteEx(&SerialPortInfo, '\n');
2921
2922 /* Release spinlock */
2923 KiReleaseSpinLock(&KdpSerialSpinLock);
2924
2925 /* Lower IRQL back */
2926 KeLowerIrql(OldIrql);
2927
2928 /* Return the length */
2929 return OutStringLength + 1;
2930 }
2931
2932 /* Write it back and print it to the log */
2933 *(PCHAR)(OutString + i) = Response;
2934 KdPortPutByteEx(&SerialPortInfo, Response);
2935 }
2936
2937 /* Print a new line */
2938 KdPortPutByteEx(&SerialPortInfo, '\r');
2939 KdPortPutByteEx(&SerialPortInfo, '\n');
2940
2941 /* Release spinlock */
2942 KiReleaseSpinLock(&KdpSerialSpinLock);
2943
2944 /* Lower IRQL back */
2945 KeLowerIrql(OldIrql);
2946
2947 /* Return the length */
2948 return OutStringLength;
2949 }