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