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