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