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