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