fixed uninitialized variable warning
[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->Cs & 0xFFFF, Tf->Eip,
383 Tf->Ss, Tf->Esp,
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->Cs & 0xffff, (Tf->Cs & 0xffff) >> 3,
465 (Tf->Cs & (1 << 2)) ? 'L' : 'G', Tf->Cs & 3);
466 KdbpPrint("DS 0x%04x Index 0x%04x %cDT RPL%d\n",
467 Tf->Ds, Tf->Ds >> 3, (Tf->Ds & (1 << 2)) ? 'L' : 'G', Tf->Ds & 3);
468 KdbpPrint("ES 0x%04x Index 0x%04x %cDT RPL%d\n",
469 Tf->Es, Tf->Es >> 3, (Tf->Es & (1 << 2)) ? 'L' : 'G', Tf->Es & 3);
470 KdbpPrint("FS 0x%04x Index 0x%04x %cDT RPL%d\n",
471 Tf->Fs, Tf->Fs >> 3, (Tf->Fs & (1 << 2)) ? 'L' : 'G', Tf->Fs & 3);
472 KdbpPrint("GS 0x%04x Index 0x%04x %cDT RPL%d\n",
473 Tf->Gs, Tf->Gs >> 3, (Tf->Gs & (1 << 2)) ? 'L' : 'G', Tf->Gs & 3);
474 KdbpPrint("SS 0x%04x Index 0x%04x %cDT RPL%d\n",
475 Tf->Ss, Tf->Ss >> 3, (Tf->Ss & (1 << 2)) ? 'L' : 'G', Tf->Ss & 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->PreviousMode == KernelMode)
944 Esp = (PULONG)Thread->Tcb.TrapFrame->TempEsp;
945 else
946 Esp = (PULONG)Thread->Tcb.TrapFrame->Esp;
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(" PreviousTask: 0x%08x\n"
1470 " Ss0:Esp0: 0x%04x:0x%08x\n"
1471 " Ss1:Esp1: 0x%04x:0x%08x\n"
1472 " Ss2:Esp2: 0x%04x:0x%08x\n"
1473 " Cr3: 0x%08x\n"
1474 " Eip: 0x%08x\n"
1475 " Eflags: 0x%08x\n"
1476 " Eax: 0x%08x\n"
1477 " Ecx: 0x%08x\n"
1478 " Edx: 0x%08x\n"
1479 " Ebx: 0x%08x\n"
1480 " Esp: 0x%08x\n"
1481 " Ebp: 0x%08x\n"
1482 " Esi: 0x%08x\n"
1483 " Edi: 0x%08x\n"
1484 " Es: 0x%04x\n"
1485 " Cs: 0x%04x\n"
1486 " Ss: 0x%04x\n"
1487 " Ds: 0x%04x\n"
1488 " Fs: 0x%04x\n"
1489 " Gs: 0x%04x\n"
1490 " Ldt: 0x%04x\n"
1491 " Trap: 0x%04x\n"
1492 " IoMapBase: 0x%04x\n",
1493 Tss->PreviousTask, Tss->Ss0, Tss->Esp0, Tss->Ss1, Tss->Esp1,
1494 Tss->Ss2, Tss->Esp2, Tss->Cr3, Tss->Eip, Tss->Eflags, Tss->Eax,
1495 Tss->Ecx, Tss->Edx, Tss->Ebx, Tss->Esp, Tss->Ebp, Tss->Esi,
1496 Tss->Edi, Tss->Es, Tss->Cs, Tss->Ss, Tss->Ds, Tss->Fs, Tss->Gs,
1497 Tss->Ldt, Tss->Trap, Tss->IoMapBase);
1498 return TRUE;
1499 }
1500
1501 /*!\brief Bugchecks the system.
1502 */
1503 STATIC BOOLEAN
1504 KdbpCmdBugCheck(ULONG Argc, PCHAR Argv[])
1505 {
1506 KEBUGCHECK(0xDEADDEAD);
1507 return TRUE;
1508 }
1509
1510 /*!\brief Sets or displays a config variables value.
1511 */
1512 STATIC BOOLEAN
1513 KdbpCmdSet(ULONG Argc, PCHAR Argv[])
1514 {
1515 ULONG l;
1516 BOOLEAN First;
1517 PCHAR pend = 0;
1518 KDB_ENTER_CONDITION ConditionFirst = KdbDoNotEnter;
1519 KDB_ENTER_CONDITION ConditionLast = KdbDoNotEnter;
1520 STATIC CONST PCHAR ExceptionNames[21] =
1521 { "ZERODEVIDE", "DEBUGTRAP", "NMI", "INT3", "OVERFLOW", "BOUND", "INVALIDOP",
1522 "NOMATHCOP", "DOUBLEFAULT", "RESERVED(9)", "INVALIDTSS", "SEGMENTNOTPRESENT",
1523 "STACKFAULT", "GPF", "PAGEFAULT", "RESERVED(15)", "MATHFAULT", "ALIGNMENTCHECK",
1524 "MACHINECHECK", "SIMDFAULT", "OTHERS" };
1525
1526 if (Argc == 1)
1527 {
1528 KdbpPrint("Available settings:\n");
1529 KdbpPrint(" syntax [intel|at&t]\n");
1530 KdbpPrint(" condition [exception|*] [first|last] [never|always|kmode|umode]\n");
1531 KdbpPrint(" break_on_module_load [true|false]\n");
1532 }
1533 else if (strcmp(Argv[1], "syntax") == 0)
1534 {
1535 if (Argc == 2)
1536 KdbpPrint("syntax = %s\n", KdbUseIntelSyntax ? "intel" : "at&t");
1537 else if (Argc >= 3)
1538 {
1539 if (_stricmp(Argv[2], "intel") == 0)
1540 KdbUseIntelSyntax = TRUE;
1541 else if (_stricmp(Argv[2], "at&t") == 0)
1542 KdbUseIntelSyntax = FALSE;
1543 else
1544 KdbpPrint("Unknown syntax '%s'.\n", Argv[2]);
1545 }
1546 }
1547 else if (strcmp(Argv[1], "condition") == 0)
1548 {
1549 if (Argc == 2)
1550 {
1551 KdbpPrint("Conditions: (First) (Last)\n");
1552 for (l = 0; l < RTL_NUMBER_OF(ExceptionNames) - 1; l++)
1553 {
1554 if (ExceptionNames[l] == NULL)
1555 continue;
1556 if (!KdbpGetEnterCondition(l, TRUE, &ConditionFirst))
1557 ASSERT(0);
1558 if (!KdbpGetEnterCondition(l, FALSE, &ConditionLast))
1559 ASSERT(0);
1560 KdbpPrint(" #%02d %-20s %-8s %-8s\n", l, ExceptionNames[l],
1561 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst),
1562 KDB_ENTER_CONDITION_TO_STRING(ConditionLast));
1563 }
1564 ASSERT(l == (RTL_NUMBER_OF(ExceptionNames) - 1));
1565 KdbpPrint(" %-20s %-8s %-8s\n", ExceptionNames[l],
1566 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst),
1567 KDB_ENTER_CONDITION_TO_STRING(ConditionLast));
1568 }
1569 else
1570 {
1571 if (Argc >= 5 && strcmp(Argv[2], "*") == 0) /* Allow * only when setting condition */
1572 l = -1;
1573 else
1574 {
1575 l = strtoul(Argv[2], &pend, 0);
1576 if (Argv[2] == pend)
1577 {
1578 for (l = 0; l < RTL_NUMBER_OF(ExceptionNames); l++)
1579 {
1580 if (ExceptionNames[l] == NULL)
1581 continue;
1582 if (_stricmp(ExceptionNames[l], Argv[2]) == 0)
1583 break;
1584 }
1585 }
1586 if (l >= RTL_NUMBER_OF(ExceptionNames))
1587 {
1588 KdbpPrint("Unknown exception '%s'.\n", Argv[2]);
1589 return TRUE;
1590 }
1591 }
1592 if (Argc > 4)
1593 {
1594 if (_stricmp(Argv[3], "first") == 0)
1595 First = TRUE;
1596 else if (_stricmp(Argv[3], "last") == 0)
1597 First = FALSE;
1598 else
1599 {
1600 KdbpPrint("set condition: second argument must be 'first' or 'last'\n");
1601 return TRUE;
1602 }
1603 if (_stricmp(Argv[4], "never") == 0)
1604 ConditionFirst = KdbDoNotEnter;
1605 else if (_stricmp(Argv[4], "always") == 0)
1606 ConditionFirst = KdbEnterAlways;
1607 else if (_stricmp(Argv[4], "umode") == 0)
1608 ConditionFirst = KdbEnterFromUmode;
1609 else if (_stricmp(Argv[4], "kmode") == 0)
1610 ConditionFirst = KdbEnterFromKmode;
1611 else
1612 {
1613 KdbpPrint("set condition: third argument must be 'never', 'always', 'umode' or 'kmode'\n");
1614 return TRUE;
1615 }
1616 if (!KdbpSetEnterCondition(l, First, ConditionFirst))
1617 {
1618 if (l >= 0)
1619 KdbpPrint("Couldn't change condition for exception #%02d\n", l);
1620 else
1621 KdbpPrint("Couldn't change condition for all exceptions\n", l);
1622 }
1623 }
1624 else /* Argc >= 3 */
1625 {
1626 if (!KdbpGetEnterCondition(l, TRUE, &ConditionFirst))
1627 ASSERT(0);
1628 if (!KdbpGetEnterCondition(l, FALSE, &ConditionLast))
1629 ASSERT(0);
1630 if (l < (RTL_NUMBER_OF(ExceptionNames) - 1))
1631 {
1632 KdbpPrint("Condition for exception #%02d (%s): FirstChance %s LastChance %s\n",
1633 l, ExceptionNames[l],
1634 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst),
1635 KDB_ENTER_CONDITION_TO_STRING(ConditionLast));
1636 }
1637 else
1638 {
1639 KdbpPrint("Condition for all other exceptions: FirstChance %s LastChance %s\n",
1640 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst),
1641 KDB_ENTER_CONDITION_TO_STRING(ConditionLast));
1642 }
1643 }
1644 }
1645 }
1646 else if (strcmp(Argv[1], "break_on_module_load") == 0)
1647 {
1648 if (Argc == 2)
1649 KdbpPrint("break_on_module_load = %s\n", KdbBreakOnModuleLoad ? "enabled" : "disabled");
1650 else if (Argc >= 3)
1651 {
1652 if (_stricmp(Argv[2], "enable") == 0 || _stricmp(Argv[2], "enabled") == 0 ||
1653 _stricmp(Argv[2], "true") == 0)
1654 KdbBreakOnModuleLoad = TRUE;
1655 else if (_stricmp(Argv[2], "disable") == 0 || _stricmp(Argv[2], "disabled") == 0 ||
1656 _stricmp(Argv[2], "false") == 0)
1657 KdbBreakOnModuleLoad = FALSE;
1658 else
1659 KdbpPrint("Unknown setting '%s'.\n", Argv[2]);
1660 }
1661 }
1662 else
1663 KdbpPrint("Unknown setting '%s'.\n", Argv[1]);
1664
1665 return TRUE;
1666 }
1667
1668 /*!\brief Displays help screen.
1669 */
1670 STATIC BOOLEAN
1671 KdbpCmdHelp(ULONG Argc, PCHAR Argv[])
1672 {
1673 ULONG i;
1674
1675 KdbpPrint("Kernel debugger commands:\n");
1676 for (i = 0; i < RTL_NUMBER_OF(KdbDebuggerCommands); i++)
1677 {
1678 if (KdbDebuggerCommands[i].Syntax == NULL) /* Command group */
1679 {
1680 if (i > 0)
1681 KdbpPrint("\n");
1682 KdbpPrint("\x1b[7m* %s:\x1b[0m\n", KdbDebuggerCommands[i].Help);
1683 continue;
1684 }
1685
1686 KdbpPrint(" %-20s - %s\n",
1687 KdbDebuggerCommands[i].Syntax,
1688 KdbDebuggerCommands[i].Help);
1689 }
1690
1691 return TRUE;
1692 }
1693
1694 /*!\brief Prints the given string with printf-like formatting.
1695 *
1696 * \param Format Format of the string/arguments.
1697 * \param ... Variable number of arguments matching the format specified in \a Format.
1698 *
1699 * \note Doesn't correctly handle \\t and terminal escape sequences when calculating the
1700 * number of lines required to print a single line from the Buffer in the terminal.
1701 */
1702 VOID
1703 KdbpPrint(
1704 IN PCHAR Format,
1705 IN ... OPTIONAL)
1706 {
1707 STATIC CHAR Buffer[4096];
1708 STATIC BOOLEAN TerminalInitialized = FALSE;
1709 STATIC BOOLEAN TerminalConnected = FALSE;
1710 STATIC BOOLEAN TerminalReportsSize = TRUE;
1711 CHAR c = '\0';
1712 PCHAR p, p2;
1713 UINT Length;
1714 UINT i, j;
1715 INT RowsPrintedByTerminal;
1716 ULONG ScanCode;
1717 va_list ap;
1718
1719 /* Check if the user has aborted output of the current command */
1720 if (KdbOutputAborted)
1721 return;
1722
1723 /* Initialize the terminal */
1724 if (!TerminalInitialized)
1725 {
1726 DbgPrint("\x1b[7h"); /* Enable linewrap */
1727
1728 /* Query terminal type */
1729 /*DbgPrint("\x1b[Z");*/
1730 DbgPrint("\x05");
1731
1732 TerminalInitialized = TRUE;
1733 Length = 0;
1734 for (;;)
1735 {
1736 c = KdbpTryGetCharSerial(5000);
1737 if (c == -1)
1738 break;
1739 Buffer[Length++] = c;
1740 if (Length >= (sizeof (Buffer) - 1))
1741 break;
1742 }
1743 Buffer[Length] = '\0';
1744 if (Length > 0)
1745 TerminalConnected = TRUE;
1746 }
1747
1748 /* Get number of rows and columns in terminal */
1749 if ((KdbNumberOfRowsTerminal < 0) || (KdbNumberOfColsTerminal < 0) ||
1750 (KdbNumberOfRowsPrinted) == 0) /* Refresh terminal size each time when number of rows printed is 0 */
1751 {
1752 if ((KdbDebugState & KD_DEBUG_KDSERIAL) && TerminalConnected && TerminalReportsSize)
1753 {
1754 /* Try to query number of rows from terminal. A reply looks like "\x1b[8;24;80t" */
1755 TerminalReportsSize = FALSE;
1756 DbgPrint("\x1b[18t");
1757 c = KdbpTryGetCharSerial(5000);
1758 if (c == KEY_ESC)
1759 {
1760 c = KdbpTryGetCharSerial(5000);
1761 if (c == '[')
1762 {
1763 Length = 0;
1764 for (;;)
1765 {
1766 c = KdbpTryGetCharSerial(5000);
1767 if (c == -1)
1768 break;
1769 Buffer[Length++] = c;
1770 if (isalpha(c) || Length >= (sizeof (Buffer) - 1))
1771 break;
1772 }
1773 Buffer[Length] = '\0';
1774 if (Buffer[0] == '8' && Buffer[1] == ';')
1775 {
1776 for (i = 2; (i < Length) && (Buffer[i] != ';'); i++);
1777 if (Buffer[i] == ';')
1778 {
1779 Buffer[i++] = '\0';
1780 /* Number of rows is now at Buffer + 2 and number of cols at Buffer + i */
1781 KdbNumberOfRowsTerminal = strtoul(Buffer + 2, NULL, 0);
1782 KdbNumberOfColsTerminal = strtoul(Buffer + i, NULL, 0);
1783 TerminalReportsSize = TRUE;
1784 }
1785 }
1786 }
1787 }
1788 }
1789
1790 if (KdbNumberOfRowsTerminal <= 0)
1791 {
1792 /* Set number of rows to the default. */
1793 KdbNumberOfRowsTerminal = 24;
1794 }
1795 else if (KdbNumberOfColsTerminal <= 0)
1796 {
1797 /* Set number of cols to the default. */
1798 KdbNumberOfColsTerminal = 80;
1799 }
1800 }
1801
1802 /* Get the string */
1803 va_start(ap, Format);
1804 Length = _vsnprintf(Buffer, sizeof (Buffer) - 1, Format, ap);
1805 Buffer[Length] = '\0';
1806 va_end(ap);
1807
1808 p = Buffer;
1809 while (p[0] != '\0')
1810 {
1811 i = strcspn(p, "\n");
1812
1813 /* Calculate the number of lines which will be printed in the terminal
1814 * when outputting the current line
1815 */
1816 if (i > 0)
1817 RowsPrintedByTerminal = (i + KdbNumberOfColsPrinted - 1) / KdbNumberOfColsTerminal;
1818 else
1819 RowsPrintedByTerminal = 0;
1820 if (p[i] == '\n')
1821 RowsPrintedByTerminal++;
1822
1823 /*DbgPrint("!%d!%d!%d!%d!", KdbNumberOfRowsPrinted, KdbNumberOfColsPrinted, i, RowsPrintedByTerminal);*/
1824
1825 /* Display a prompt if we printed one screen full of text */
1826 if (KdbNumberOfRowsTerminal > 0 &&
1827 (LONG)(KdbNumberOfRowsPrinted + RowsPrintedByTerminal) >= KdbNumberOfRowsTerminal)
1828 {
1829 if (KdbNumberOfColsPrinted > 0)
1830 DbgPrint("\n");
1831 DbgPrint("--- Press q to abort, any other key to continue ---");
1832 if (KdbDebugState & KD_DEBUG_KDSERIAL)
1833 c = KdbpGetCharSerial();
1834 else
1835 c = KdbpGetCharKeyboard(&ScanCode);
1836 if (c == '\r')
1837 {
1838 /* Try to read '\n' which might follow '\r' - if \n is not received here
1839 * it will be interpreted as "return" when the next command should be read.
1840 */
1841 if (KdbDebugState & KD_DEBUG_KDSERIAL)
1842 c = KdbpTryGetCharSerial(5);
1843 else
1844 c = KdbpTryGetCharKeyboard(&ScanCode, 5);
1845 }
1846 DbgPrint("\n");
1847 if (c == 'q')
1848 {
1849 KdbOutputAborted = TRUE;
1850 return;
1851 }
1852 KdbNumberOfRowsPrinted = 0;
1853 KdbNumberOfColsPrinted = 0;
1854 }
1855
1856 /* Insert a NUL after the line and print only the current line. */
1857 if (p[i] == '\n' && p[i + 1] != '\0')
1858 {
1859 c = p[i + 1];
1860 p[i + 1] = '\0';
1861 }
1862 else
1863 {
1864 c = '\0';
1865 }
1866
1867 /* Remove escape sequences from the line if there's no terminal connected */
1868 if (!TerminalConnected)
1869 {
1870 while ((p2 = strrchr(p, '\x1b')) != NULL) /* Look for escape character */
1871 {
1872 if (p2[1] == '[')
1873 {
1874 j = 2;
1875 while (!isalpha(p2[j++]));
1876 strcpy(p2, p2 + j);
1877 }
1878 }
1879 }
1880
1881 DbgPrint("%s", p);
1882
1883 if (c != '\0')
1884 p[i + 1] = c;
1885
1886 /* Set p to the start of the next line and
1887 * remember the number of rows/cols printed
1888 */
1889 p += i;
1890 if (p[0] == '\n')
1891 {
1892 p++;
1893 KdbNumberOfColsPrinted = 0;
1894 }
1895 else
1896 {
1897 ASSERT(p[0] == '\0');
1898 KdbNumberOfColsPrinted += i;
1899 }
1900 KdbNumberOfRowsPrinted += RowsPrintedByTerminal;
1901 }
1902 }
1903
1904 /*!\brief Appends a command to the command history
1905 *
1906 * \param Command Pointer to the command to append to the history.
1907 */
1908 STATIC VOID
1909 KdbpCommandHistoryAppend(
1910 IN PCHAR Command)
1911 {
1912 ULONG Length1 = strlen(Command) + 1;
1913 ULONG Length2 = 0;
1914 INT i;
1915 PCHAR Buffer;
1916
1917 ASSERT(Length1 <= RTL_NUMBER_OF(KdbCommandHistoryBuffer));
1918
1919 if (Length1 <= 1 ||
1920 (KdbCommandHistory[KdbCommandHistoryIndex] != NULL &&
1921 strcmp(KdbCommandHistory[KdbCommandHistoryIndex], Command) == 0))
1922 {
1923 return;
1924 }
1925
1926 /* Calculate Length1 and Length2 */
1927 Buffer = KdbCommandHistoryBuffer + KdbCommandHistoryBufferIndex;
1928 KdbCommandHistoryBufferIndex += Length1;
1929 if (KdbCommandHistoryBufferIndex >= (LONG)RTL_NUMBER_OF(KdbCommandHistoryBuffer))
1930 {
1931 KdbCommandHistoryBufferIndex -= RTL_NUMBER_OF(KdbCommandHistoryBuffer);
1932 Length2 = KdbCommandHistoryBufferIndex;
1933 Length1 -= Length2;
1934 }
1935
1936 /* Remove previous commands until there is enough space to append the new command */
1937 for (i = KdbCommandHistoryIndex; KdbCommandHistory[i] != NULL;)
1938 {
1939 if ((Length2 > 0 &&
1940 (KdbCommandHistory[i] >= Buffer ||
1941 KdbCommandHistory[i] < (KdbCommandHistoryBuffer + KdbCommandHistoryBufferIndex))) ||
1942 (Length2 <= 0 &&
1943 (KdbCommandHistory[i] >= Buffer &&
1944 KdbCommandHistory[i] < (KdbCommandHistoryBuffer + KdbCommandHistoryBufferIndex))))
1945 {
1946 KdbCommandHistory[i] = NULL;
1947 }
1948 i--;
1949 if (i < 0)
1950 i = RTL_NUMBER_OF(KdbCommandHistory) - 1;
1951 if (i == KdbCommandHistoryIndex)
1952 break;
1953 }
1954
1955 /* Make sure the new command history entry is free */
1956 KdbCommandHistoryIndex++;
1957 KdbCommandHistoryIndex %= RTL_NUMBER_OF(KdbCommandHistory);
1958 if (KdbCommandHistory[KdbCommandHistoryIndex] != NULL)
1959 {
1960 KdbCommandHistory[KdbCommandHistoryIndex] = NULL;
1961 }
1962
1963 /* Append command */
1964 KdbCommandHistory[KdbCommandHistoryIndex] = Buffer;
1965 ASSERT((KdbCommandHistory[KdbCommandHistoryIndex] + Length1) <= KdbCommandHistoryBuffer + RTL_NUMBER_OF(KdbCommandHistoryBuffer));
1966 memcpy(KdbCommandHistory[KdbCommandHistoryIndex], Command, Length1);
1967 if (Length2 > 0)
1968 {
1969 memcpy(KdbCommandHistoryBuffer, Command + Length1, Length2);
1970 }
1971 }
1972
1973 /*!\brief Reads a line of user-input.
1974 *
1975 * \param Buffer Buffer to store the input into. Trailing newlines are removed.
1976 * \param Size Size of \a Buffer.
1977 *
1978 * \note Accepts only \n newlines, \r is ignored.
1979 */
1980 STATIC VOID
1981 KdbpReadCommand(
1982 OUT PCHAR Buffer,
1983 IN ULONG Size)
1984 {
1985 CHAR Key;
1986 PCHAR Orig = Buffer;
1987 ULONG ScanCode = 0;
1988 BOOLEAN EchoOn;
1989 STATIC CHAR LastCommand[1024] = "";
1990 STATIC CHAR NextKey = '\0';
1991 INT CmdHistIndex = -1;
1992 INT i;
1993
1994 EchoOn = !((KdbDebugState & KD_DEBUG_KDNOECHO) != 0);
1995
1996 for (;;)
1997 {
1998 if (KdbDebugState & KD_DEBUG_KDSERIAL)
1999 {
2000 Key = (NextKey == '\0') ? KdbpGetCharSerial() : NextKey;
2001 NextKey = '\0';
2002 ScanCode = 0;
2003 if (Key == KEY_ESC) /* ESC */
2004 {
2005 Key = KdbpGetCharSerial();
2006 if (Key == '[')
2007 {
2008 Key = KdbpGetCharSerial();
2009 switch (Key)
2010 {
2011 case 'A':
2012 ScanCode = KEY_SCAN_UP;
2013 break;
2014 case 'B':
2015 ScanCode = KEY_SCAN_DOWN;
2016 break;
2017 case 'C':
2018 break;
2019 case 'D':
2020 break;
2021 }
2022 }
2023 }
2024 }
2025 else
2026 {
2027 ScanCode = 0;
2028 Key = (NextKey == '\0') ? KdbpGetCharKeyboard(&ScanCode) : NextKey;
2029 NextKey = '\0';
2030 }
2031
2032 if ((ULONG)(Buffer - Orig) >= (Size - 1))
2033 {
2034 /* Buffer is full, accept only newlines */
2035 if (Key != '\n')
2036 continue;
2037 }
2038
2039 if (Key == '\r')
2040 {
2041 /* Read the next char - this is to throw away a \n which most clients should
2042 * send after \r.
2043 */
2044 if (KdbDebugState & KD_DEBUG_KDSERIAL)
2045 NextKey = KdbpTryGetCharSerial(5);
2046 else
2047 NextKey = KdbpTryGetCharKeyboard(&ScanCode, 5);
2048 if (NextKey == '\n' || NextKey == -1) /* \n or no response at all */
2049 NextKey = '\0';
2050 DbgPrint("\n");
2051 /*
2052 * Repeat the last command if the user presses enter. Reduces the
2053 * risk of RSI when single-stepping.
2054 */
2055 if (Buffer == Orig)
2056 {
2057 strncpy(Buffer, LastCommand, Size);
2058 Buffer[Size - 1] = '\0';
2059 }
2060 else
2061 {
2062 *Buffer = '\0';
2063 strncpy(LastCommand, Orig, sizeof (LastCommand));
2064 LastCommand[sizeof (LastCommand) - 1] = '\0';
2065 }
2066 return;
2067 }
2068 else if (Key == KEY_BS || Key == KEY_DEL)
2069 {
2070 if (Buffer > Orig)
2071 {
2072 Buffer--;
2073 *Buffer = 0;
2074 if (EchoOn)
2075 DbgPrint("%c %c", KEY_BS, KEY_BS);
2076 else
2077 DbgPrint(" %c", KEY_BS);
2078 }
2079 }
2080 else if (ScanCode == KEY_SCAN_UP)
2081 {
2082 BOOLEAN Print = TRUE;
2083 if (CmdHistIndex < 0)
2084 CmdHistIndex = KdbCommandHistoryIndex;
2085 else
2086 {
2087 i = CmdHistIndex - 1;
2088 if (i < 0)
2089 CmdHistIndex = RTL_NUMBER_OF(KdbCommandHistory) - 1;
2090 if (KdbCommandHistory[i] != NULL && i != KdbCommandHistoryIndex)
2091 CmdHistIndex = i;
2092 else
2093 Print = FALSE;
2094 }
2095 if (Print && KdbCommandHistory[CmdHistIndex] != NULL)
2096 {
2097 while (Buffer > Orig)
2098 {
2099 Buffer--;
2100 *Buffer = 0;
2101 if (EchoOn)
2102 DbgPrint("%c %c", KEY_BS, KEY_BS);
2103 else
2104 DbgPrint(" %c", KEY_BS);
2105 }
2106 i = min(strlen(KdbCommandHistory[CmdHistIndex]), Size - 1);
2107 memcpy(Orig, KdbCommandHistory[CmdHistIndex], i);
2108 Orig[i] = '\0';
2109 Buffer = Orig + i;
2110 DbgPrint("%s", Orig);
2111 }
2112 }
2113 else if (ScanCode == KEY_SCAN_DOWN)
2114 {
2115 if (CmdHistIndex > 0 && CmdHistIndex != KdbCommandHistoryIndex)
2116 {
2117 i = CmdHistIndex + 1;
2118 if (i >= (INT)RTL_NUMBER_OF(KdbCommandHistory))
2119 i = 0;
2120 if (KdbCommandHistory[i] != NULL)
2121 {
2122 CmdHistIndex = i;
2123 while (Buffer > Orig)
2124 {
2125 Buffer--;
2126 *Buffer = 0;
2127 if (EchoOn)
2128 DbgPrint("%c %c", KEY_BS, KEY_BS);
2129 else
2130 DbgPrint(" %c", KEY_BS);
2131 }
2132 i = min(strlen(KdbCommandHistory[CmdHistIndex]), Size - 1);
2133 memcpy(Orig, KdbCommandHistory[CmdHistIndex], i);
2134 Orig[i] = '\0';
2135 Buffer = Orig + i;
2136 DbgPrint("%s", Orig);
2137 }
2138 }
2139 }
2140 else
2141 {
2142 if (EchoOn)
2143 DbgPrint("%c", Key);
2144
2145 *Buffer = Key;
2146 Buffer++;
2147 }
2148 }
2149 }
2150
2151 /*!\brief Parses command line and executes command if found
2152 *
2153 * \param Command Command line to parse and execute if possible.
2154 *
2155 * \retval TRUE Don't continue execution.
2156 * \retval FALSE Continue execution (leave KDB)
2157 */
2158 STATIC BOOL
2159 KdbpDoCommand(
2160 IN PCHAR Command)
2161 {
2162 ULONG i;
2163 PCHAR p;
2164 ULONG Argc;
2165 STATIC PCH Argv[256];
2166 STATIC CHAR OrigCommand[1024];
2167
2168 strncpy(OrigCommand, Command, sizeof(OrigCommand) - 1);
2169 OrigCommand[sizeof(OrigCommand) - 1] = '\0';
2170
2171 Argc = 0;
2172 p = Command;
2173 for (;;)
2174 {
2175 while (*p == '\t' || *p == ' ')
2176 p++;
2177 if (*p == '\0')
2178 break;
2179
2180 i = strcspn(p, "\t ");
2181 Argv[Argc++] = p;
2182 p += i;
2183 if (*p == '\0')
2184 break;
2185 *p = '\0';
2186 p++;
2187 }
2188 if (Argc < 1)
2189 return TRUE;
2190
2191 for (i = 0; i < RTL_NUMBER_OF(KdbDebuggerCommands); i++)
2192 {
2193 if (KdbDebuggerCommands[i].Name == NULL)
2194 continue;
2195
2196 if (strcmp(KdbDebuggerCommands[i].Name, Argv[0]) == 0)
2197 {
2198 return KdbDebuggerCommands[i].Fn(Argc, Argv);
2199 }
2200 }
2201
2202 KdbpPrint("Command '%s' is unknown.\n", OrigCommand);
2203 return TRUE;
2204 }
2205
2206 /*!\brief KDB Main Loop.
2207 *
2208 * \param EnteredOnSingleStep TRUE if KDB was entered on single step.
2209 */
2210 VOID
2211 KdbpCliMainLoop(
2212 IN BOOLEAN EnteredOnSingleStep)
2213 {
2214 STATIC CHAR Command[1024];
2215 BOOLEAN Continue;
2216
2217 if (EnteredOnSingleStep)
2218 {
2219 if (!KdbSymPrintAddress((PVOID)KdbCurrentTrapFrame->Tf.Eip))
2220 {
2221 DbgPrint("<%x>", KdbCurrentTrapFrame->Tf.Eip);
2222 }
2223 DbgPrint(": ");
2224 if (KdbpDisassemble(KdbCurrentTrapFrame->Tf.Eip, KdbUseIntelSyntax) < 0)
2225 {
2226 DbgPrint("<INVALID>");
2227 }
2228 DbgPrint("\n");
2229 }
2230
2231 /* Flush the input buffer */
2232 if (KdbDebugState & KD_DEBUG_KDSERIAL)
2233 {
2234 while (KdbpTryGetCharSerial(1) != -1);
2235 }
2236 else
2237 {
2238 ULONG ScanCode;
2239 while (KdbpTryGetCharKeyboard(&ScanCode, 1) != -1);
2240 }
2241
2242 /* Main loop */
2243 do
2244 {
2245 /* Print the prompt */
2246 DbgPrint("kdb:> ");
2247
2248 /* Read a command and remember it */
2249 KdbpReadCommand(Command, sizeof (Command));
2250 KdbpCommandHistoryAppend(Command);
2251
2252 /* Reset the number of rows/cols printed and output aborted state */
2253 KdbNumberOfRowsPrinted = KdbNumberOfColsPrinted = 0;
2254 KdbOutputAborted = FALSE;
2255
2256 /* Call the command */
2257 Continue = KdbpDoCommand(Command);
2258 } while (Continue);
2259 }
2260
2261 /*!\brief Called when a module is loaded.
2262 *
2263 * \param Name Filename of the module which was loaded.
2264 */
2265 VOID
2266 KdbpCliModuleLoaded(IN PUNICODE_STRING Name)
2267 {
2268 if (!KdbBreakOnModuleLoad)
2269 return;
2270
2271 DbgPrint("Module %wZ loaded.\n", Name);
2272 DbgBreakPointWithStatus(DBG_STATUS_CONTROL_C);
2273 }
2274
2275 /*!\brief This function is called by KdbEnterDebuggerException...
2276 *
2277 * Used to interpret the init file in a context with a trapframe setup
2278 * (KdbpCliInit call KdbEnter which will call KdbEnterDebuggerException which will
2279 * call this function if KdbInitFileBuffer is not NULL.
2280 */
2281 VOID
2282 KdbpCliInterpretInitFile()
2283 {
2284 PCHAR p1, p2;
2285 INT i;
2286 CHAR c;
2287
2288 /* Execute the commands in the init file */
2289 DPRINT("KDB: Executing KDBinit file...\n");
2290 p1 = KdbInitFileBuffer;
2291 while (p1[0] != '\0')
2292 {
2293 i = strcspn(p1, "\r\n");
2294 if (i > 0)
2295 {
2296 c = p1[i];
2297 p1[i] = '\0';
2298
2299 /* Look for "break" command and comments */
2300 p2 = p1;
2301 while (isspace(p2[0]))
2302 p2++;
2303 if (strncmp(p2, "break", sizeof("break")-1) == 0 &&
2304 (p2[sizeof("break")-1] == '\0' || isspace(p2[sizeof("break")-1])))
2305 {
2306 /* break into the debugger */
2307 KdbpCliMainLoop(FALSE);
2308 }
2309 else if (p2[0] != '#' && p2[0] != '\0') /* Ignore empty lines and comments */
2310 {
2311 KdbpDoCommand(p1);
2312 }
2313
2314 p1[i] = c;
2315 }
2316 p1 += i;
2317 while (p1[0] == '\r' || p1[0] == '\n')
2318 p1++;
2319 }
2320 DPRINT("KDB: KDBinit executed\n");
2321 }
2322
2323 /*!\brief Called when KDB is initialized
2324 *
2325 * Reads the KDBinit file from the SystemRoot\system32\drivers\etc directory and executes it.
2326 */
2327 VOID
2328 KdbpCliInit()
2329 {
2330 NTSTATUS Status;
2331 OBJECT_ATTRIBUTES ObjectAttributes;
2332 UNICODE_STRING FileName;
2333 IO_STATUS_BLOCK Iosb;
2334 FILE_STANDARD_INFORMATION FileStdInfo;
2335 HANDLE hFile = NULL;
2336 INT FileSize;
2337 PCHAR FileBuffer;
2338 ULONG OldEflags;
2339
2340 /* Initialize the object attributes */
2341 RtlInitUnicodeString(&FileName, L"\\SystemRoot\\system32\\drivers\\etc\\KDBinit");
2342 InitializeObjectAttributes(&ObjectAttributes, &FileName, 0, NULL, NULL);
2343
2344 /* Open the file */
2345 Status = ZwOpenFile(&hFile, FILE_READ_DATA, &ObjectAttributes, &Iosb, 0,
2346 FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT |
2347 FILE_NO_INTERMEDIATE_BUFFERING);
2348 if (!NT_SUCCESS(Status))
2349 {
2350 DPRINT("Could not open \\SystemRoot\\system32\\drivers\\etc\\KDBinit (Status 0x%x)", Status);
2351 return;
2352 }
2353
2354 /* Get the size of the file */
2355 Status = ZwQueryInformationFile(hFile, &Iosb, &FileStdInfo, sizeof (FileStdInfo),
2356 FileStandardInformation);
2357 if (!NT_SUCCESS(Status))
2358 {
2359 ZwClose(hFile);
2360 DPRINT("Could not query size of \\SystemRoot\\system32\\drivers\\etc\\KDBinit (Status 0x%x)", Status);
2361 return;
2362 }
2363 FileSize = FileStdInfo.EndOfFile.u.LowPart;
2364
2365 /* Allocate memory for the file */
2366 FileBuffer = ExAllocatePool(PagedPool, FileSize + 1); /* add 1 byte for terminating '\0' */
2367 if (FileBuffer == NULL)
2368 {
2369 ZwClose(hFile);
2370 DPRINT("Could not allocate %d bytes for KDBinit file\n", FileSize);
2371 return;
2372 }
2373
2374 /* Load file into memory */
2375 Status = ZwReadFile(hFile, 0, 0, 0, &Iosb, FileBuffer, FileSize, 0, 0);
2376 ZwClose(hFile);
2377 if (!NT_SUCCESS(Status) && Status != STATUS_END_OF_FILE)
2378 {
2379 ExFreePool(FileBuffer);
2380 DPRINT("Could not read KDBinit file into memory (Status 0x%lx)\n", Status);
2381 return;
2382 }
2383 FileSize = min(FileSize, (INT)Iosb.Information);
2384 FileBuffer[FileSize] = '\0';
2385
2386 /* Enter critical section */
2387 Ke386SaveFlags(OldEflags);
2388 Ke386DisableInterrupts();
2389
2390 /* Interpret the init file... */
2391 KdbInitFileBuffer = FileBuffer;
2392 KdbEnter();
2393 KdbInitFileBuffer = NULL;
2394
2395 /* Leave critical section */
2396 Ke386RestoreFlags(OldEflags);
2397
2398 ExFreePool(FileBuffer);
2399 }
2400