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