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