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