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