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