6835e41f42f5d94a1b26041330141972311fd521
[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;
877 ULONG ul = 0;
878 PCHAR State, pend, str1, str2;
879 STATIC CONST PCHAR ThreadStateToString[THREAD_STATE_MAX] =
880 { "Initialized", "Ready", "Running",
881 "Suspended", "Frozen", "Terminated1",
882 "Terminated2", "Blocked" };
883 ASSERT(KdbCurrentProcess != NULL);
884
885 if (Argc >= 2 && _stricmp(Argv[1], "list") == 0)
886 {
887 Process = KdbCurrentProcess;
888
889 if (Argc >= 3)
890 {
891 ul = strtoul(Argv[2], &pend, 0);
892 if (Argv[2] == pend)
893 {
894 KdbpPrint("thread: '%s' is not a valid process id!\n", Argv[2]);
895 return TRUE;
896 }
897 if (!NT_SUCCESS(PsLookupProcessByProcessId((PVOID)ul, &Process)))
898 {
899 KdbpPrint("thread: Invalid process id!\n");
900 return TRUE;
901 }
902 }
903
904 Entry = Process->ThreadListHead.Flink;
905 if (Entry == &Process->ThreadListHead)
906 {
907 if (Argc >= 3)
908 KdbpPrint("No threads in process 0x%08x!\n", ul);
909 else
910 KdbpPrint("No threads in current process!\n");
911 return TRUE;
912 }
913
914 KdbpPrint(" TID State Prior. Affinity EBP EIP\n");
915 do
916 {
917 Thread = CONTAINING_RECORD(Entry, ETHREAD, ThreadListEntry);
918
919 if (Thread == KdbCurrentThread)
920 {
921 str1 = "\x1b[1m*";
922 str2 = "\x1b[0m";
923 }
924 else
925 {
926 str1 = " ";
927 str2 = "";
928 }
929
930 if (Thread->Tcb.TrapFrame != NULL)
931 {
932 Esp = (PULONG)Thread->Tcb.TrapFrame->Esp;
933 Ebp = (PULONG)Thread->Tcb.TrapFrame->Ebp;
934 Eip = Thread->Tcb.TrapFrame->Eip;
935 }
936 else
937 {
938 Esp = (PULONG)Thread->Tcb.KernelStack;
939 Ebp = (PULONG)Esp[4];
940 Eip = 0;
941 if (Ebp != NULL) /* FIXME: Should we attach to the process to read Ebp[1]? */
942 KdbpSafeReadMemory(&Eip, Ebp + 1, sizeof (Eip));;
943 }
944 if (Thread->Tcb.State < THREAD_STATE_MAX)
945 State = ThreadStateToString[Thread->Tcb.State];
946 else
947 State = "Unknown";
948
949 KdbpPrint(" %s0x%08x %-11s %3d 0x%08x 0x%08x 0x%08x%s\n",
950 str1,
951 Thread->Cid.UniqueThread,
952 State,
953 Thread->Tcb.Priority,
954 Thread->Tcb.Affinity,
955 Ebp,
956 Eip,
957 str2);
958
959 Entry = Entry->Flink;
960 }
961 while (Entry != &Process->ThreadListHead);
962 }
963 else if (Argc >= 2 && _stricmp(Argv[1], "attach") == 0)
964 {
965 if (Argc < 3)
966 {
967 KdbpPrint("thread attach: thread id argument required!\n");
968 return TRUE;
969 }
970
971 ul = strtoul(Argv[2], &pend, 0);
972 if (Argv[2] == pend)
973 {
974 KdbpPrint("thread attach: '%s' is not a valid thread id!\n", Argv[2]);
975 return TRUE;
976 }
977 if (!KdbpAttachToThread((PVOID)ul))
978 {
979 return TRUE;
980 }
981 KdbpPrint("Attached to thread 0x%08x.\n", ul);
982 }
983 else
984 {
985 Thread = KdbCurrentThread;
986
987 if (Argc >= 2)
988 {
989 ul = strtoul(Argv[1], &pend, 0);
990 if (Argv[1] == pend)
991 {
992 KdbpPrint("thread: '%s' is not a valid thread id!\n", Argv[1]);
993 return TRUE;
994 }
995 if (!NT_SUCCESS(PsLookupThreadByThreadId((PVOID)ul, &Thread)))
996 {
997 KdbpPrint("thread: Invalid thread id!\n");
998 return TRUE;
999 }
1000 }
1001
1002 if (Thread->Tcb.State < THREAD_STATE_MAX)
1003 State = ThreadStateToString[Thread->Tcb.State];
1004 else
1005 State = "Unknown";
1006 KdbpPrint("%s"
1007 " TID: 0x%08x\n"
1008 " State: %s (0x%x)\n"
1009 " Priority: %d\n"
1010 " Affinity: 0x%08x\n"
1011 " Initial Stack: 0x%08x\n"
1012 " Stack Limit: 0x%08x\n"
1013 " Stack Base: 0x%08x\n"
1014 " Kernel Stack: 0x%08x\n"
1015 " Trap Frame: 0x%08x\n"
1016 " NPX State: %s (0x%x)\n",
1017 (Argc < 2) ? "Current Thread:\n" : "",
1018 Thread->Cid.UniqueThread,
1019 State, Thread->Tcb.State,
1020 Thread->Tcb.Priority,
1021 Thread->Tcb.Affinity,
1022 Thread->Tcb.InitialStack,
1023 Thread->Tcb.StackLimit,
1024 Thread->Tcb.StackBase,
1025 Thread->Tcb.KernelStack,
1026 Thread->Tcb.TrapFrame,
1027 NPX_STATE_TO_STRING(Thread->Tcb.NpxState), Thread->Tcb.NpxState);
1028
1029 }
1030
1031 return TRUE;
1032 }
1033
1034 /*!\brief Lists processes or switches to another process context.
1035 */
1036 STATIC BOOLEAN
1037 KdbpCmdProc(ULONG Argc, PCHAR Argv[])
1038 {
1039 PLIST_ENTRY Entry;
1040 PEPROCESS Process;
1041 PCHAR State, pend, str1, str2;
1042 ULONG ul;
1043 extern LIST_ENTRY PsActiveProcessHead;
1044
1045 if (Argc >= 2 && _stricmp(Argv[1], "list") == 0)
1046 {
1047 Entry = PsActiveProcessHead.Flink;
1048 if (Entry == &PsActiveProcessHead)
1049 {
1050 KdbpPrint("No processes in the system!\n");
1051 return TRUE;
1052 }
1053
1054 KdbpPrint(" PID State Filename\n");
1055 do
1056 {
1057 Process = CONTAINING_RECORD(Entry, EPROCESS, ProcessListEntry);
1058
1059 if (Process == KdbCurrentProcess)
1060 {
1061 str1 = "\x1b[1m*";
1062 str2 = "\x1b[0m";
1063 }
1064 else
1065 {
1066 str1 = " ";
1067 str2 = "";
1068 }
1069
1070 State = ((Process->Pcb.State == PROCESS_STATE_TERMINATED) ? "Terminated" :
1071 ((Process->Pcb.State == PROCESS_STATE_ACTIVE) ? "Active" : "Unknown"));
1072
1073 KdbpPrint(" %s0x%08x %-10s %s%s\n",
1074 str1,
1075 Process->UniqueProcessId,
1076 State,
1077 Process->ImageFileName,
1078 str2);
1079
1080 Entry = Entry->Flink;
1081 }
1082 while(Entry != &PsActiveProcessHead);
1083 }
1084 else if (Argc >= 2 && _stricmp(Argv[1], "attach") == 0)
1085 {
1086 if (Argc < 3)
1087 {
1088 KdbpPrint("process attach: process id argument required!\n");
1089 return TRUE;
1090 }
1091
1092 ul = strtoul(Argv[2], &pend, 0);
1093 if (Argv[2] == pend)
1094 {
1095 KdbpPrint("process attach: '%s' is not a valid process id!\n", Argv[2]);
1096 return TRUE;
1097 }
1098 if (!KdbpAttachToProcess((PVOID)ul))
1099 {
1100 return TRUE;
1101 }
1102 KdbpPrint("Attached to process 0x%08x, thread 0x%08x.\n", (UINT)ul,
1103 (UINT)KdbCurrentThread->Cid.UniqueThread);
1104 }
1105 else
1106 {
1107 Process = KdbCurrentProcess;
1108
1109 if (Argc >= 2)
1110 {
1111 ul = strtoul(Argv[1], &pend, 0);
1112 if (Argv[1] == pend)
1113 {
1114 KdbpPrint("proc: '%s' is not a valid process id!\n", Argv[1]);
1115 return TRUE;
1116 }
1117 if (!NT_SUCCESS(PsLookupProcessByProcessId((PVOID)ul, &Process)))
1118 {
1119 KdbpPrint("proc: Invalid process id!\n");
1120 return TRUE;
1121 }
1122 }
1123
1124 State = ((Process->Pcb.State == PROCESS_STATE_TERMINATED) ? "Terminated" :
1125 ((Process->Pcb.State == PROCESS_STATE_ACTIVE) ? "Active" : "Unknown"));
1126 KdbpPrint("%s"
1127 " PID: 0x%08x\n"
1128 " State: %s (0x%x)\n"
1129 " Image Filename: %s\n",
1130 (Argc < 2) ? "Current process:\n" : "",
1131 Process->UniqueProcessId,
1132 State, Process->Pcb.State,
1133 Process->ImageFileName);
1134 }
1135
1136 return TRUE;
1137 }
1138
1139 /*!\brief Lists loaded modules or the one containing the specified address.
1140 */
1141 STATIC BOOLEAN
1142 KdbpCmdMod(ULONG Argc, PCHAR Argv[])
1143 {
1144 ULONGLONG Result = 0;
1145 ULONG_PTR Address;
1146 KDB_MODULE_INFO Info;
1147 BOOLEAN DisplayOnlyOneModule = FALSE;
1148 INT i = 0;
1149
1150 if (Argc >= 2)
1151 {
1152 /* Put the arguments back together */
1153 Argc--;
1154 while (--Argc >= 1)
1155 Argv[Argc][strlen(Argv[Argc])] = ' ';
1156
1157 /* Evaluate the expression */
1158 if (!KdbpEvaluateExpression(Argv[1], sizeof("kdb:> ")-1 + (Argv[1]-Argv[0]), &Result))
1159 {
1160 return TRUE;
1161 }
1162 if (Result > (ULONGLONG)(~((ULONG_PTR)0)))
1163 KdbpPrint("%s: Warning: Address %I64x is beeing truncated\n", Argv[0]);
1164 Address = (ULONG_PTR)Result;
1165
1166 if (!KdbpSymFindModuleByAddress((PVOID)Address, &Info))
1167 {
1168 KdbpPrint("No module containing address 0x%x found!\n", Address);
1169 return TRUE;
1170 }
1171 DisplayOnlyOneModule = TRUE;
1172 }
1173 else
1174 {
1175 if (!KdbpSymFindModuleByIndex(0, &Info))
1176 {
1177 KdbpPrint("No modules.\n");
1178 return TRUE;
1179 }
1180 i = 1;
1181 }
1182
1183 KdbpPrint(" Base Size Name\n");
1184 for (;;)
1185 {
1186 KdbpPrint(" %08x %08x %ws\n", Info.Base, Info.Size, Info.Name);
1187
1188 if ((!DisplayOnlyOneModule && !KdbpSymFindModuleByIndex(i++, &Info)) ||
1189 DisplayOnlyOneModule)
1190 {
1191 break;
1192 }
1193 }
1194
1195 return TRUE;
1196 }
1197
1198 /*!\brief Displays GDT, LDT or IDTd.
1199 */
1200 STATIC BOOLEAN
1201 KdbpCmdGdtLdtIdt(ULONG Argc, PCHAR Argv[])
1202 {
1203 struct __attribute__((packed)) {
1204 USHORT Limit;
1205 ULONG Base;
1206 } Reg;
1207 ULONG SegDesc[2];
1208 ULONG SegBase;
1209 ULONG SegLimit;
1210 PCHAR SegType;
1211 USHORT SegSel;
1212 UCHAR Type, Dpl;
1213 INT i;
1214 ULONG ul;
1215
1216 if (Argv[0][0] == 'i')
1217 {
1218 /* Read IDTR */
1219 asm volatile("sidt %0" : : "m"(Reg));
1220
1221 if (Reg.Limit < 7)
1222 {
1223 KdbpPrint("Interrupt descriptor table is empty.\n");
1224 return TRUE;
1225 }
1226 KdbpPrint("IDT Base: 0x%08x Limit: 0x%04x\n", Reg.Base, Reg.Limit);
1227 KdbpPrint(" Idx Type Seg. Sel. Offset DPL\n");
1228 for (i = 0; (i + sizeof(SegDesc) - 1) <= Reg.Limit; i += 8)
1229 {
1230 if (!NT_SUCCESS(KdbpSafeReadMemory(SegDesc, (PVOID)(Reg.Base + i), sizeof(SegDesc))))
1231 {
1232 KdbpPrint("Couldn't access memory at 0x%08x!\n", Reg.Base + i);
1233 return TRUE;
1234 }
1235
1236 Dpl = ((SegDesc[1] >> 13) & 3);
1237 if ((SegDesc[1] & 0x1f00) == 0x0500) /* Task gate */
1238 SegType = "TASKGATE";
1239 else if ((SegDesc[1] & 0x1fe0) == 0x0e00) /* 32 bit Interrupt gate */
1240 SegType = "INTGATE32";
1241 else if ((SegDesc[1] & 0x1fe0) == 0x0600) /* 16 bit Interrupt gate */
1242 SegType = "INTGATE16";
1243 else if ((SegDesc[1] & 0x1fe0) == 0x0f00) /* 32 bit Trap gate */
1244 SegType = "TRAPGATE32";
1245 else if ((SegDesc[1] & 0x1fe0) == 0x0700) /* 16 bit Trap gate */
1246 SegType = "TRAPGATE16";
1247 else
1248 SegType = "UNKNOWN";
1249
1250 if ((SegDesc[1] & (1 << 15)) == 0) /* not present */
1251 {
1252 KdbpPrint(" %03d %-10s [NP] [NP] %02d\n",
1253 i / 8, SegType, Dpl);
1254 }
1255 else if ((SegDesc[1] & 0x1f00) == 0x0500) /* Task gate */
1256 {
1257 SegSel = SegDesc[0] >> 16;
1258 KdbpPrint(" %03d %-10s 0x%04x %02d\n",
1259 i / 8, SegType, SegSel, Dpl);
1260 }
1261 else
1262 {
1263 SegSel = SegDesc[0] >> 16;
1264 SegBase = (SegDesc[1] & 0xffff0000) | (SegDesc[0] & 0x0000ffff);
1265 KdbpPrint(" %03d %-10s 0x%04x 0x%08x %02d\n",
1266 i / 8, SegType, SegSel, SegBase, Dpl);
1267 }
1268 }
1269 }
1270 else
1271 {
1272 ul = 0;
1273 if (Argv[0][0] == 'g')
1274 {
1275 /* Read GDTR */
1276 asm volatile("sgdt %0" : : "m"(Reg));
1277 i = 8;
1278 }
1279 else
1280 {
1281 ASSERT(Argv[0][0] == 'l');
1282 /* Read LDTR */
1283 asm volatile("sldt %0" : : "m"(Reg));
1284 i = 0;
1285 ul = 1 << 2;
1286 }
1287
1288 if (Reg.Limit < 7)
1289 {
1290 KdbpPrint("%s descriptor table is empty.\n",
1291 Argv[0][0] == 'g' ? "Global" : "Local");
1292 return TRUE;
1293 }
1294 KdbpPrint("%cDT Base: 0x%08x Limit: 0x%04x\n",
1295 Argv[0][0] == 'g' ? 'G' : 'L', Reg.Base, Reg.Limit);
1296 KdbpPrint(" Idx Sel. Type Base Limit DPL Attribs\n");
1297 for ( ; (i + sizeof(SegDesc) - 1) <= Reg.Limit; i += 8)
1298 {
1299 if (!NT_SUCCESS(KdbpSafeReadMemory(SegDesc, (PVOID)(Reg.Base + i), sizeof(SegDesc))))
1300 {
1301 KdbpPrint("Couldn't access memory at 0x%08x!\n", Reg.Base + i);
1302 return TRUE;
1303 }
1304 Dpl = ((SegDesc[1] >> 13) & 3);
1305 Type = ((SegDesc[1] >> 8) & 0xf);
1306
1307 SegBase = SegDesc[0] >> 16;
1308 SegBase |= (SegDesc[1] & 0xff) << 16;
1309 SegBase |= SegDesc[1] & 0xff000000;
1310 SegLimit = SegDesc[0] & 0x0000ffff;
1311 SegLimit |= (SegDesc[1] >> 16) & 0xf;
1312 if ((SegDesc[1] & (1 << 23)) != 0)
1313 {
1314 SegLimit *= 4096;
1315 SegLimit += 4095;
1316 }
1317 else
1318 {
1319 SegLimit++;
1320 }
1321
1322 if ((SegDesc[1] & (1 << 12)) == 0) /* System segment */
1323 {
1324 switch (Type)
1325 {
1326 case 1: SegType = "TSS16(Avl)"; break;
1327 case 2: SegType = "LDT"; break;
1328 case 3: SegType = "TSS16(Busy)"; break;
1329 case 4: SegType = "CALLGATE16"; break;
1330 case 5: SegType = "TASKGATE"; break;
1331 case 6: SegType = "INTGATE16"; break;
1332 case 7: SegType = "TRAPGATE16"; break;
1333 case 9: SegType = "TSS32(Avl)"; break;
1334 case 11: SegType = "TSS32(Busy)"; break;
1335 case 12: SegType = "CALLGATE32"; break;
1336 case 14: SegType = "INTGATE32"; break;
1337 case 15: SegType = "INTGATE32"; break;
1338 default: SegType = "UNKNOWN"; break;
1339 }
1340 if (!(Type >= 1 && Type <= 3) &&
1341 Type != 9 && Type != 11)
1342 {
1343 SegBase = 0;
1344 SegLimit = 0;
1345 }
1346 }
1347 else if ((SegDesc[1] & (1 << 11)) == 0) /* Data segment */
1348 {
1349 if ((SegDesc[1] & (1 << 22)) != 0)
1350 SegType = "DATA32";
1351 else
1352 SegType = "DATA16";
1353
1354 }
1355 else /* Code segment */
1356 {
1357 if ((SegDesc[1] & (1 << 22)) != 0)
1358 SegType = "CODE32";
1359 else
1360 SegType = "CODE16";
1361 }
1362
1363 if ((SegDesc[1] & (1 << 15)) == 0) /* not present */
1364 {
1365 KdbpPrint(" %03d 0x%04x %-11s [NP] [NP] %02d NP\n",
1366 i / 8, i | Dpl | ul, SegType, Dpl);
1367 }
1368 else
1369 {
1370 KdbpPrint(" %03d 0x%04x %-11s 0x%08x 0x%08x %02d ",
1371 i / 8, i | Dpl | ul, SegType, SegBase, SegLimit, Dpl);
1372 if ((SegDesc[1] & (1 << 12)) == 0) /* System segment */
1373 {
1374 /* FIXME: Display system segment */
1375 }
1376 else if ((SegDesc[1] & (1 << 11)) == 0) /* Data segment */
1377 {
1378 if ((SegDesc[1] & (1 << 10)) != 0) /* Expand-down */
1379 KdbpPrint(" E");
1380 KdbpPrint((SegDesc[1] & (1 << 9)) ? " R/W" : " R");
1381 if ((SegDesc[1] & (1 << 8)) != 0)
1382 KdbpPrint(" A");
1383 }
1384 else /* Code segment */
1385 {
1386 if ((SegDesc[1] & (1 << 10)) != 0) /* Conforming */
1387 KdbpPrint(" C");
1388 KdbpPrint((SegDesc[1] & (1 << 9)) ? " R/X" : " X");
1389 if ((SegDesc[1] & (1 << 8)) != 0)
1390 KdbpPrint(" A");
1391 }
1392 if ((SegDesc[1] & (1 << 20)) != 0)
1393 KdbpPrint(" AVL");
1394 KdbpPrint("\n");
1395 }
1396 }
1397 }
1398
1399 return TRUE;
1400 }
1401
1402 /*!\brief Displays the KPCR
1403 */
1404 STATIC BOOLEAN
1405 KdbpCmdPcr(ULONG Argc, PCHAR Argv[])
1406 {
1407 PKPCR Pcr = KeGetCurrentKPCR();
1408
1409 KdbpPrint("Current PCR is at 0x%08x.\n", (INT)Pcr);
1410 KdbpPrint(" Tib.ExceptionList: 0x%08x\n"
1411 " Tib.StackBase: 0x%08x\n"
1412 " Tib.StackLimit: 0x%08x\n"
1413 " Tib.SubSystemTib: 0x%08x\n"
1414 " Tib.FiberData/Version: 0x%08x\n"
1415 " Tib.ArbitraryUserPointer: 0x%08x\n"
1416 " Tib.Self: 0x%08x\n"
1417 " Self: 0x%08x\n"
1418 " PCRCB: 0x%08x\n"
1419 " Irql: 0x%02x\n"
1420 " IRR: 0x%08x\n"
1421 " IrrActive: 0x%08x\n"
1422 " IDR: 0x%08x\n"
1423 " KdVersionBlock: 0x%08x\n"
1424 " IDT: 0x%08x\n"
1425 " GDT: 0x%08x\n"
1426 " TSS: 0x%08x\n"
1427 " MajorVersion: 0x%04x\n"
1428 " MinorVersion: 0x%04x\n"
1429 " SetMember: 0x%08x\n"
1430 " StallScaleFactor: 0x%08x\n"
1431 " DebugActive: 0x%02x\n"
1432 " ProcessorNumber: 0x%02x\n"
1433 " L2CacheAssociativity: 0x%02x\n"
1434 " VdmAlert: 0x%08x\n"
1435 " L2CacheSize: 0x%08x\n"
1436 " InterruptMode: 0x%08x\n",
1437 Pcr->Tib.ExceptionList, Pcr->Tib.StackBase, Pcr->Tib.StackLimit,
1438 Pcr->Tib.SubSystemTib, Pcr->Tib.FiberData, Pcr->Tib.ArbitraryUserPointer,
1439 Pcr->Tib.Self, Pcr->Self, Pcr->PCRCB, Pcr->Irql, Pcr->IRR, Pcr->IrrActive,
1440 Pcr->IDR, Pcr->KdVersionBlock, Pcr->IDT, Pcr->GDT, Pcr->TSS,
1441 Pcr->MajorVersion, Pcr->MinorVersion, Pcr->SetMember, Pcr->StallScaleFactor,
1442 Pcr->DebugActive, Pcr->ProcessorNumber, Pcr->L2CacheAssociativity,
1443 Pcr->VdmAlert, Pcr->L2CacheSize, Pcr->InterruptMode);
1444
1445 return TRUE;
1446 }
1447
1448 /*!\brief Displays the TSS
1449 */
1450 STATIC BOOLEAN
1451 KdbpCmdTss(ULONG Argc, PCHAR Argv[])
1452 {
1453 KTSS *Tss = KeGetCurrentKPCR()->TSS;
1454
1455 KdbpPrint("Current TSS is at 0x%08x.\n", (INT)Tss);
1456 KdbpPrint(" PreviousTask: 0x%08x\n"
1457 " Ss0:Esp0: 0x%04x:0x%08x\n"
1458 " Ss1:Esp1: 0x%04x:0x%08x\n"
1459 " Ss2:Esp2: 0x%04x:0x%08x\n"
1460 " Cr3: 0x%08x\n"
1461 " Eip: 0x%08x\n"
1462 " Eflags: 0x%08x\n"
1463 " Eax: 0x%08x\n"
1464 " Ecx: 0x%08x\n"
1465 " Edx: 0x%08x\n"
1466 " Ebx: 0x%08x\n"
1467 " Esp: 0x%08x\n"
1468 " Ebp: 0x%08x\n"
1469 " Esi: 0x%08x\n"
1470 " Edi: 0x%08x\n"
1471 " Es: 0x%04x\n"
1472 " Cs: 0x%04x\n"
1473 " Ss: 0x%04x\n"
1474 " Ds: 0x%04x\n"
1475 " Fs: 0x%04x\n"
1476 " Gs: 0x%04x\n"
1477 " Ldt: 0x%04x\n"
1478 " Trap: 0x%04x\n"
1479 " IoMapBase: 0x%04x\n",
1480 Tss->PreviousTask, Tss->Ss0, Tss->Esp0, Tss->Ss1, Tss->Esp1,
1481 Tss->Ss2, Tss->Esp2, Tss->Cr3, Tss->Eip, Tss->Eflags, Tss->Eax,
1482 Tss->Ecx, Tss->Edx, Tss->Ebx, Tss->Esp, Tss->Ebp, Tss->Esi,
1483 Tss->Edi, Tss->Es, Tss->Cs, Tss->Ss, Tss->Ds, Tss->Fs, Tss->Gs,
1484 Tss->Ldt, Tss->Trap, Tss->IoMapBase);
1485 return TRUE;
1486 }
1487
1488 /*!\brief Bugchecks the system.
1489 */
1490 STATIC BOOLEAN
1491 KdbpCmdBugCheck(ULONG Argc, PCHAR Argv[])
1492 {
1493 KEBUGCHECK(0xDEADDEAD);
1494 return TRUE;
1495 }
1496
1497 /*!\brief Sets or displays a config variables value.
1498 */
1499 STATIC BOOLEAN
1500 KdbpCmdSet(ULONG Argc, PCHAR Argv[])
1501 {
1502 LONG l;
1503 BOOLEAN First;
1504 PCHAR pend = 0;
1505 KDB_ENTER_CONDITION ConditionFirst = KdbDoNotEnter;
1506 KDB_ENTER_CONDITION ConditionLast = KdbDoNotEnter;
1507 STATIC CONST PCHAR ExceptionNames[21] =
1508 { "ZERODEVIDE", "DEBUGTRAP", "NMI", "INT3", "OVERFLOW", "BOUND", "INVALIDOP",
1509 "NOMATHCOP", "DOUBLEFAULT", "RESERVED(9)", "INVALIDTSS", "SEGMENTNOTPRESENT",
1510 "STACKFAULT", "GPF", "PAGEFAULT", "RESERVED(15)", "MATHFAULT", "ALIGNMENTCHECK",
1511 "MACHINECHECK", "SIMDFAULT", "OTHERS" };
1512
1513 if (Argc == 1)
1514 {
1515 KdbpPrint("Available settings:\n");
1516 KdbpPrint(" syntax [intel|at&t]\n");
1517 KdbpPrint(" condition [exception|*] [first|last] [never|always|kmode|umode]\n");
1518 }
1519 else if (strcmp(Argv[1], "syntax") == 0)
1520 {
1521 if (Argc == 2)
1522 KdbpPrint("syntax = %s\n", KdbUseIntelSyntax ? "intel" : "at&t");
1523 else if (Argc >= 3)
1524 {
1525 if (_stricmp(Argv[2], "intel") == 0)
1526 KdbUseIntelSyntax = TRUE;
1527 else if (_stricmp(Argv[2], "at&t") == 0)
1528 KdbUseIntelSyntax = FALSE;
1529 else
1530 KdbpPrint("Unknown syntax '%s'.\n", Argv[2]);
1531 }
1532 }
1533 else if (strcmp(Argv[1], "condition") == 0)
1534 {
1535 if (Argc == 2)
1536 {
1537 KdbpPrint("Conditions: (First) (Last)\n");
1538 for (l = 0; l < RTL_NUMBER_OF(ExceptionNames) - 1; l++)
1539 {
1540 if (ExceptionNames[l] == NULL)
1541 continue;
1542 if (!KdbpGetEnterCondition(l, TRUE, &ConditionFirst))
1543 ASSERT(0);
1544 if (!KdbpGetEnterCondition(l, FALSE, &ConditionLast))
1545 ASSERT(0);
1546 KdbpPrint(" #%02d %-20s %-8s %-8s\n", l, ExceptionNames[l],
1547 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst),
1548 KDB_ENTER_CONDITION_TO_STRING(ConditionLast));
1549 }
1550 ASSERT(l == (RTL_NUMBER_OF(ExceptionNames) - 1));
1551 KdbpPrint(" %-20s %-8s %-8s\n", ExceptionNames[l],
1552 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst),
1553 KDB_ENTER_CONDITION_TO_STRING(ConditionLast));
1554 }
1555 else
1556 {
1557 if (Argc >= 5 && strcmp(Argv[2], "*") == 0) /* Allow * only when setting condition */
1558 l = -1;
1559 else
1560 {
1561 l = (LONG)strtoul(Argv[2], &pend, 0);
1562 if (Argv[2] == pend)
1563 {
1564 for (l = 0; l < RTL_NUMBER_OF(ExceptionNames); l++)
1565 {
1566 if (ExceptionNames[l] == NULL)
1567 continue;
1568 if (_stricmp(ExceptionNames[l], Argv[2]) == 0)
1569 break;
1570 }
1571 }
1572 if (l >= RTL_NUMBER_OF(ExceptionNames))
1573 {
1574 KdbpPrint("Unknown exception '%s'.\n", Argv[2]);
1575 return TRUE;
1576 }
1577 }
1578 if (Argc > 4)
1579 {
1580 if (_stricmp(Argv[3], "first") == 0)
1581 First = TRUE;
1582 else if (_stricmp(Argv[3], "last") == 0)
1583 First = FALSE;
1584 else
1585 {
1586 KdbpPrint("set condition: second argument must be 'first' or 'last'\n");
1587 return TRUE;
1588 }
1589 if (_stricmp(Argv[4], "never") == 0)
1590 ConditionFirst = KdbDoNotEnter;
1591 else if (_stricmp(Argv[4], "always") == 0)
1592 ConditionFirst = KdbEnterAlways;
1593 else if (_stricmp(Argv[4], "umode") == 0)
1594 ConditionFirst = KdbEnterFromUmode;
1595 else if (_stricmp(Argv[4], "kmode") == 0)
1596 ConditionFirst = KdbEnterFromKmode;
1597 else
1598 {
1599 KdbpPrint("set condition: third argument must be 'never', 'always', 'umode' or 'kmode'\n");
1600 return TRUE;
1601 }
1602 if (!KdbpSetEnterCondition(l, First, ConditionFirst))
1603 {
1604 if (l >= 0)
1605 KdbpPrint("Couldn't change condition for exception #%02d\n", l);
1606 else
1607 KdbpPrint("Couldn't change condition for all exceptions\n", l);
1608 }
1609 }
1610 else /* Argc >= 3 */
1611 {
1612 if (!KdbpGetEnterCondition(l, TRUE, &ConditionFirst))
1613 ASSERT(0);
1614 if (!KdbpGetEnterCondition(l, FALSE, &ConditionLast))
1615 ASSERT(0);
1616 if (l < (RTL_NUMBER_OF(ExceptionNames) - 1))
1617 {
1618 KdbpPrint("Condition for exception #%02d (%s): FirstChance %s LastChance %s\n",
1619 l, ExceptionNames[l],
1620 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst),
1621 KDB_ENTER_CONDITION_TO_STRING(ConditionLast));
1622 }
1623 else
1624 {
1625 KdbpPrint("Condition for all other exceptions: FirstChance %s LastChance %s\n",
1626 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst),
1627 KDB_ENTER_CONDITION_TO_STRING(ConditionLast));
1628 }
1629 }
1630 }
1631 }
1632 else
1633 KdbpPrint("Unknown setting '%s'.\n", Argv[1]);
1634
1635 return TRUE;
1636 }
1637
1638 /*!\brief Displays help screen.
1639 */
1640 STATIC BOOLEAN
1641 KdbpCmdHelp(ULONG Argc, PCHAR Argv[])
1642 {
1643 ULONG i;
1644
1645 KdbpPrint("Kernel debugger commands:\n");
1646 for (i = 0; i < RTL_NUMBER_OF(KdbDebuggerCommands); i++)
1647 {
1648 if (KdbDebuggerCommands[i].Syntax == NULL) /* Command group */
1649 {
1650 if (i > 0)
1651 KdbpPrint("\n");
1652 KdbpPrint("\x1b[7m* %s:\x1b[0m\n", KdbDebuggerCommands[i].Help);
1653 continue;
1654 }
1655
1656 KdbpPrint(" %-20s - %s\n",
1657 KdbDebuggerCommands[i].Syntax,
1658 KdbDebuggerCommands[i].Help);
1659 }
1660
1661 return TRUE;
1662 }
1663
1664 /*!\brief Prints the given string with printf-like formatting.
1665 *
1666 * \param Format Format of the string/arguments.
1667 * \param ... Variable number of arguments matching the format specified in \a Format.
1668 *
1669 * \note Doesn't correctly handle \\t and terminal escape sequences when calculating the
1670 * number of lines required to print a single line from the Buffer in the terminal.
1671 */
1672 VOID
1673 KdbpPrint(
1674 IN PCHAR Format,
1675 IN ... OPTIONAL)
1676 {
1677 STATIC CHAR Buffer[4096];
1678 STATIC BOOLEAN TerminalInitialized = FALSE;
1679 STATIC BOOLEAN TerminalReportsSize = TRUE;
1680 CHAR c = '\0';
1681 PCHAR p;
1682 INT Length;
1683 INT i;
1684 INT RowsPrintedByTerminal;
1685 ULONG ScanCode;
1686 va_list ap;
1687
1688 /* Check if the user has aborted output of the current command */
1689 if (KdbOutputAborted)
1690 return;
1691
1692 /* Initialize the terminal */
1693 if (!TerminalInitialized)
1694 {
1695 DbgPrint("\x1b[7h"); /* Enable linewrap */
1696 TerminalInitialized = TRUE;
1697 }
1698
1699 /* Get number of rows and columns in terminal */
1700 if ((KdbNumberOfRowsTerminal < 0) || (KdbNumberOfColsTerminal < 0) ||
1701 (KdbNumberOfRowsPrinted) == 0) /* Refresh terminal size each time when number of rows printed is 0 */
1702 {
1703 if ((KdDebugState & KD_DEBUG_KDSERIAL) && TerminalReportsSize)
1704 {
1705 /* Try to query number of rows from terminal. A reply looks like "\x1b[8;24;80t" */
1706 TerminalReportsSize = FALSE;
1707 //DbgPrint("\x1b[18t");
1708 c = KdbpTryGetCharSerial(10);
1709 if (c == KEY_ESC)
1710 {
1711 c = KdbpTryGetCharSerial(5);
1712 if (c == '[')
1713 {
1714 Length = 0;
1715 for (;;)
1716 {
1717 c = KdbpTryGetCharSerial(5);
1718 if (c == -1)
1719 break;
1720 Buffer[Length++] = c;
1721 if (isalpha(c) || Length >= (sizeof (Buffer) - 1))
1722 break;
1723 }
1724 Buffer[Length] = '\0';
1725 if (Buffer[0] == '8' && Buffer[1] == ';')
1726 {
1727 for (i = 2; (i < Length) && (Buffer[i] != ';'); i++);
1728 if (Buffer[i] == ';')
1729 {
1730 Buffer[i++] = '\0';
1731 /* Number of rows is now at Buffer + 2 and number of cols at Buffer + i */
1732 KdbNumberOfRowsTerminal = strtoul(Buffer + 2, NULL, 0);
1733 KdbNumberOfColsTerminal = strtoul(Buffer + i, NULL, 0);
1734 TerminalReportsSize = TRUE;
1735 }
1736 }
1737 }
1738 }
1739 }
1740
1741 if (KdbNumberOfRowsTerminal <= 0)
1742 {
1743 /* Set number of rows to the default. */
1744 KdbNumberOfRowsTerminal = 24;
1745 }
1746 else if (KdbNumberOfColsTerminal <= 0)
1747 {
1748 /* Set number of cols to the default. */
1749 KdbNumberOfColsTerminal = 80;
1750 }
1751 }
1752
1753 /* Get the string */
1754 va_start(ap, Format);
1755 Length = _vsnprintf(Buffer, sizeof (Buffer) - 1, Format, ap);
1756 Buffer[Length] = '\0';
1757 va_end(ap);
1758
1759 p = Buffer;
1760 while (p[0] != '\0')
1761 {
1762 i = strcspn(p, "\n");
1763
1764 /* Calculate the number of lines which will be printed in the terminal
1765 * when outputting the current line
1766 */
1767 if (i > 0)
1768 RowsPrintedByTerminal = (i + KdbNumberOfColsPrinted - 1) / KdbNumberOfColsTerminal;
1769 else
1770 RowsPrintedByTerminal = 0;
1771 if (p[i] == '\n')
1772 RowsPrintedByTerminal++;
1773
1774 /*DbgPrint("!%d!%d!%d!%d!", KdbNumberOfRowsPrinted, KdbNumberOfColsPrinted, i, RowsPrintedByTerminal);*/
1775
1776 /* Display a prompt if we printed one screen full of text */
1777 if ((KdbNumberOfRowsPrinted + RowsPrintedByTerminal) >= KdbNumberOfRowsTerminal)
1778 {
1779 if (KdbNumberOfColsPrinted > 0)
1780 DbgPrint("\n");
1781 DbgPrint("--- Press q to abort, any other key to continue ---");
1782 if (KdDebugState & KD_DEBUG_KDSERIAL)
1783 c = KdbpGetCharSerial();
1784 else
1785 c = KdbpGetCharKeyboard(&ScanCode);
1786 if (c == '\r')
1787 {
1788 /* Try to read '\n' which might follow '\r' - if \n is not received here
1789 * it will be interpreted as "return" when the next command should be read.
1790 */
1791 if (KdDebugState & KD_DEBUG_KDSERIAL)
1792 c = KdbpTryGetCharSerial(5);
1793 else
1794 c = KdbpTryGetCharKeyboard(&ScanCode, 5);
1795 }
1796 DbgPrint("\n");
1797 if (c == 'q')
1798 {
1799 KdbOutputAborted = TRUE;
1800 return;
1801 }
1802 KdbNumberOfRowsPrinted = 0;
1803 KdbNumberOfColsPrinted = 0;
1804 }
1805
1806 /* Insert a NUL after the line and print only the current line. */
1807 if (p[i] == '\n' && p[i + 1] != '\0')
1808 {
1809 c = p[i + 1];
1810 p[i + 1] = '\0';
1811 }
1812 else
1813 {
1814 c = '\0';
1815 }
1816
1817 DbgPrint("%s", p);
1818
1819 if (c != '\0')
1820 p[i + 1] = c;
1821
1822 /* Set p to the start of the next line and
1823 * remember the number of rows/cols printed
1824 */
1825 p += i;
1826 if (p[0] == '\n')
1827 {
1828 p++;
1829 KdbNumberOfColsPrinted = 0;
1830 }
1831 else
1832 {
1833 ASSERT(p[0] == '\0');
1834 KdbNumberOfColsPrinted += i;
1835 }
1836 KdbNumberOfRowsPrinted += RowsPrintedByTerminal;
1837 }
1838 }
1839
1840 /*!\brief Appends a command to the command history
1841 *
1842 * \param Command Pointer to the command to append to the history.
1843 */
1844 STATIC VOID
1845 KdbpCommandHistoryAppend(
1846 IN PCHAR Command)
1847 {
1848 LONG Length1 = strlen(Command) + 1;
1849 LONG Length2 = 0;
1850 INT i;
1851 PCHAR Buffer;
1852
1853 ASSERT(Length1 <= RTL_NUMBER_OF(KdbCommandHistoryBuffer));
1854
1855 if (Length1 <= 1 ||
1856 (KdbCommandHistory[KdbCommandHistoryIndex] != NULL &&
1857 strcmp(KdbCommandHistory[KdbCommandHistoryIndex], Command) == 0))
1858 {
1859 return;
1860 }
1861
1862 /* Calculate Length1 and Length2 */
1863 Buffer = KdbCommandHistoryBuffer + KdbCommandHistoryBufferIndex;
1864 KdbCommandHistoryBufferIndex += Length1;
1865 if (KdbCommandHistoryBufferIndex >= RTL_NUMBER_OF(KdbCommandHistoryBuffer))
1866 {
1867 KdbCommandHistoryBufferIndex -= RTL_NUMBER_OF(KdbCommandHistoryBuffer);
1868 Length2 = KdbCommandHistoryBufferIndex;
1869 Length1 -= Length2;
1870 }
1871
1872 /* Remove previous commands until there is enough space to append the new command */
1873 for (i = KdbCommandHistoryIndex; KdbCommandHistory[i] != NULL;)
1874 {
1875 if ((Length2 > 0 &&
1876 (KdbCommandHistory[i] >= Buffer ||
1877 KdbCommandHistory[i] < (KdbCommandHistoryBuffer + KdbCommandHistoryBufferIndex))) ||
1878 (Length2 <= 0 &&
1879 (KdbCommandHistory[i] >= Buffer &&
1880 KdbCommandHistory[i] < (KdbCommandHistoryBuffer + KdbCommandHistoryBufferIndex))))
1881 {
1882 KdbCommandHistory[i] = NULL;
1883 }
1884 i--;
1885 if (i < 0)
1886 i = RTL_NUMBER_OF(KdbCommandHistory) - 1;
1887 if (i == KdbCommandHistoryIndex)
1888 break;
1889 }
1890
1891 /* Make sure the new command history entry is free */
1892 KdbCommandHistoryIndex++;
1893 KdbCommandHistoryIndex %= RTL_NUMBER_OF(KdbCommandHistory);
1894 if (KdbCommandHistory[KdbCommandHistoryIndex] != NULL)
1895 {
1896 KdbCommandHistory[KdbCommandHistoryIndex] = NULL;
1897 }
1898
1899 /* Append command */
1900 KdbCommandHistory[KdbCommandHistoryIndex] = Buffer;
1901 ASSERT((KdbCommandHistory[KdbCommandHistoryIndex] + Length1) <= KdbCommandHistoryBuffer + RTL_NUMBER_OF(KdbCommandHistoryBuffer));
1902 memcpy(KdbCommandHistory[KdbCommandHistoryIndex], Command, Length1);
1903 if (Length2 > 0)
1904 {
1905 memcpy(KdbCommandHistoryBuffer, Command + Length1, Length2);
1906 }
1907 }
1908
1909 /*!\brief Reads a line of user-input.
1910 *
1911 * \param Buffer Buffer to store the input into. Trailing newlines are removed.
1912 * \param Size Size of \a Buffer.
1913 *
1914 * \note Accepts only \n newlines, \r is ignored.
1915 */
1916 STATIC VOID
1917 KdbpReadCommand(
1918 OUT PCHAR Buffer,
1919 IN ULONG Size)
1920 {
1921 CHAR Key, NextKey;
1922 PCHAR Orig = Buffer;
1923 ULONG ScanCode = 0;
1924 BOOLEAN EchoOn;
1925 STATIC CHAR LastCommand[1024] = "";
1926 STATIC CHAR LastKey = '\0';
1927 INT CmdHistIndex = -1;
1928 INT i;
1929
1930 EchoOn = !((KdDebugState & KD_DEBUG_KDNOECHO) != 0);
1931
1932 for (;;)
1933 {
1934 if (KdDebugState & KD_DEBUG_KDSERIAL)
1935 {
1936 Key = KdbpGetCharSerial();
1937 ScanCode = 0;
1938 if (Key == KEY_ESC) /* ESC */
1939 {
1940 Key = KdbpGetCharSerial();
1941 if (Key == '[')
1942 {
1943 Key = KdbpGetCharSerial();
1944 switch (Key)
1945 {
1946 case 'A':
1947 ScanCode = KEY_SCAN_UP;
1948 break;
1949 case 'B':
1950 ScanCode = KEY_SCAN_DOWN;
1951 break;
1952 case 'C':
1953 break;
1954 case 'D':
1955 break;
1956 }
1957 }
1958 }
1959 }
1960 else
1961 {
1962 Key = KdbpGetCharKeyboard(&ScanCode);
1963 }
1964
1965 if ((Buffer - Orig) >= (Size - 1))
1966 {
1967 /* Buffer is full, accept only newlines */
1968 if (Key != '\n')
1969 continue;
1970 }
1971
1972 if (Key == '\r')
1973 {
1974 /* Read the next char - this is to throw away a \n which most clients should
1975 * send after \r.
1976 */
1977 if (KdDebugState & KD_DEBUG_KDSERIAL)
1978 NextKey = KdbpTryGetCharSerial(5);
1979 else
1980 NextKey = KdbpTryGetCharKeyboard(&ScanCode, 5);
1981 DbgPrint("\n");
1982 /*
1983 * Repeat the last command if the user presses enter. Reduces the
1984 * risk of RSI when single-stepping.
1985 */
1986 if (Buffer == Orig)
1987 {
1988 strncpy(Buffer, LastCommand, Size);
1989 Buffer[Size - 1] = '\0';
1990 }
1991 else
1992 {
1993 *Buffer = '\0';
1994 strncpy(LastCommand, Orig, sizeof (LastCommand));
1995 LastCommand[sizeof (LastCommand) - 1] = '\0';
1996 }
1997 LastKey = Key;
1998 return;
1999 }
2000 else if (Key == KEY_BS || Key == KEY_DEL)
2001 {
2002 if (Buffer > Orig)
2003 {
2004 Buffer--;
2005 *Buffer = 0;
2006 if (EchoOn)
2007 DbgPrint("%c %c", KEY_BS, KEY_BS);
2008 else
2009 DbgPrint(" %c", KEY_BS);
2010 }
2011 }
2012 else if (ScanCode == KEY_SCAN_UP)
2013 {
2014 BOOLEAN Print = TRUE;
2015 if (CmdHistIndex < 0)
2016 CmdHistIndex = KdbCommandHistoryIndex;
2017 else
2018 {
2019 i = CmdHistIndex - 1;
2020 if (i < 0)
2021 CmdHistIndex = RTL_NUMBER_OF(KdbCommandHistory) - 1;
2022 if (KdbCommandHistory[i] != NULL && i != KdbCommandHistoryIndex)
2023 CmdHistIndex = i;
2024 else
2025 Print = FALSE;
2026 }
2027 if (Print && KdbCommandHistory[CmdHistIndex] != NULL)
2028 {
2029 while (Buffer > Orig)
2030 {
2031 Buffer--;
2032 *Buffer = 0;
2033 if (EchoOn)
2034 DbgPrint("%c %c", KEY_BS, KEY_BS);
2035 else
2036 DbgPrint(" %c", KEY_BS);
2037 }
2038 i = min(strlen(KdbCommandHistory[CmdHistIndex]), Size - 1);
2039 memcpy(Orig, KdbCommandHistory[CmdHistIndex], i);
2040 Orig[i] = '\0';
2041 Buffer = Orig + i;
2042 DbgPrint("%s", Orig);
2043 }
2044 }
2045 else if (ScanCode == KEY_SCAN_DOWN)
2046 {
2047 if (CmdHistIndex > 0 && CmdHistIndex != KdbCommandHistoryIndex)
2048 {
2049 i = CmdHistIndex + 1;
2050 if (i >= RTL_NUMBER_OF(KdbCommandHistory))
2051 i = 0;
2052 if (KdbCommandHistory[i] != NULL)
2053 {
2054 CmdHistIndex = i;
2055 while (Buffer > Orig)
2056 {
2057 Buffer--;
2058 *Buffer = 0;
2059 if (EchoOn)
2060 DbgPrint("%c %c", KEY_BS, KEY_BS);
2061 else
2062 DbgPrint(" %c", KEY_BS);
2063 }
2064 i = min(strlen(KdbCommandHistory[CmdHistIndex]), Size - 1);
2065 memcpy(Orig, KdbCommandHistory[CmdHistIndex], i);
2066 Orig[i] = '\0';
2067 Buffer = Orig + i;
2068 DbgPrint("%s", Orig);
2069 }
2070 }
2071 }
2072 else
2073 {
2074 if (EchoOn)
2075 DbgPrint("%c", Key);
2076
2077 *Buffer = Key;
2078 Buffer++;
2079 }
2080 LastKey = Key;
2081 }
2082 }
2083
2084 /*!\brief Parses command line and executes command if found
2085 *
2086 * \param Command Command line to parse and execute if possible.
2087 *
2088 * \retval TRUE Don't continue execution.
2089 * \retval FALSE Continue execution (leave KDB)
2090 */
2091 STATIC BOOL
2092 KdbpDoCommand(
2093 IN PCHAR Command)
2094 {
2095 ULONG i;
2096 PCHAR p;
2097 ULONG Argc;
2098 STATIC PCH Argv[256];
2099 STATIC CHAR OrigCommand[1024];
2100
2101 strncpy(OrigCommand, Command, sizeof(OrigCommand) - 1);
2102 OrigCommand[sizeof(OrigCommand) - 1] = '\0';
2103
2104 Argc = 0;
2105 p = Command;
2106 for (;;)
2107 {
2108 while (*p == '\t' || *p == ' ')
2109 p++;
2110 if (*p == '\0')
2111 break;
2112
2113 i = strcspn(p, "\t ");
2114 Argv[Argc++] = p;
2115 p += i;
2116 if (*p == '\0')
2117 break;
2118 *p = '\0';
2119 p++;
2120 }
2121 if (Argc < 1)
2122 return TRUE;
2123
2124 for (i = 0; i < RTL_NUMBER_OF(KdbDebuggerCommands); i++)
2125 {
2126 if (KdbDebuggerCommands[i].Name == NULL)
2127 continue;
2128
2129 if (strcmp(KdbDebuggerCommands[i].Name, Argv[0]) == 0)
2130 {
2131 return KdbDebuggerCommands[i].Fn(Argc, Argv);
2132 }
2133 }
2134
2135 KdbpPrint("Command '%s' is unknown.\n", OrigCommand);
2136 return TRUE;
2137 }
2138
2139 /*!\brief KDB Main Loop.
2140 *
2141 * \param EnteredOnSingleStep TRUE if KDB was entered on single step.
2142 */
2143 VOID
2144 KdbpCliMainLoop(
2145 IN BOOLEAN EnteredOnSingleStep)
2146 {
2147 STATIC CHAR Command[1024];
2148 BOOLEAN Continue;
2149
2150 if (EnteredOnSingleStep)
2151 {
2152 if (!KdbSymPrintAddress((PVOID)KdbCurrentTrapFrame->Tf.Eip))
2153 {
2154 DbgPrint("<%x>", KdbCurrentTrapFrame->Tf.Eip);
2155 }
2156 DbgPrint(": ");
2157 if (KdbpDisassemble(KdbCurrentTrapFrame->Tf.Eip, KdbUseIntelSyntax) < 0)
2158 {
2159 DbgPrint("<INVALID>");
2160 }
2161 DbgPrint("\n");
2162 }
2163
2164 do
2165 {
2166 /* Print the prompt */
2167 DbgPrint("kdb:> ");
2168
2169 /* Read a command and remember it */
2170 KdbpReadCommand(Command, sizeof (Command));
2171 KdbpCommandHistoryAppend(Command);
2172
2173 /* Reset the number of rows/cols printed and output aborted state */
2174 KdbNumberOfRowsPrinted = KdbNumberOfColsPrinted = 0;
2175 KdbOutputAborted = FALSE;
2176
2177 /* Call the command */
2178 Continue = KdbpDoCommand(Command);
2179 } while (Continue);
2180 }
2181
2182 /*!\brief Called when a module is loaded.
2183 *
2184 * \param Name Filename of the module which was loaded.
2185 */
2186 VOID
2187 KdbpCliModuleLoaded(IN PUNICODE_STRING Name)
2188 {
2189 return;
2190
2191 DbgPrint("Module %wZ loaded.\n", Name);
2192 DbgBreakPointWithStatus(DBG_STATUS_CONTROL_C);
2193 }
2194
2195 /*!\brief This function is called by KdbEnterDebuggerException...
2196 *
2197 * Used to interpret the init file in a context with a trapframe setup
2198 * (KdbpCliInit call KdbEnter which will call KdbEnterDebuggerException which will
2199 * call this function if KdbInitFileBuffer is not NULL.
2200 */
2201 VOID
2202 KdbpCliInterpretInitFile()
2203 {
2204 PCHAR p1, p2;
2205 INT i;
2206 CHAR c;
2207
2208 /* Execute the commands in the init file */
2209 DbgPrint("KDB: Executing KDB.init file...\n");
2210 p1 = KdbInitFileBuffer;
2211 while (p1[0] != '\0')
2212 {
2213 i = strcspn(p1, "\r\n");
2214 if (i > 0)
2215 {
2216 c = p1[i];
2217 p1[i] = '\0';
2218
2219 /* Look for "break" command and comments */
2220 p2 = p1;
2221 while (isspace(p2[0]))
2222 p2++;
2223 if (strncmp(p2, "break", sizeof("break")-1) == 0 &&
2224 (p2[sizeof("break")-1] == '\0' || isspace(p2[sizeof("break")-1])))
2225 {
2226 /* break into the debugger */
2227 KdbpCliMainLoop(FALSE);
2228 }
2229 else if (p2[0] != '#' && p2[0] != '\0') /* Ignore empty lines and comments */
2230 {
2231 KdbpDoCommand(p1);
2232 }
2233
2234 p1[i] = c;
2235 }
2236 p1 += i;
2237 while (p1[0] == '\r' || p1[0] == '\n')
2238 p1++;
2239 }
2240 DbgPrint("KDB: KDB.init executed\n");
2241 }
2242
2243 /*!\brief Called when KDB is initialized
2244 *
2245 * Reads the KDB.init file from the SystemRoot\system32\drivers\etc directory and executes it.
2246 */
2247 VOID
2248 KdbpCliInit()
2249 {
2250 NTSTATUS Status;
2251 OBJECT_ATTRIBUTES ObjectAttributes;
2252 UNICODE_STRING FileName;
2253 IO_STATUS_BLOCK Iosb;
2254 FILE_STANDARD_INFORMATION FileStdInfo;
2255 HANDLE hFile = NULL;
2256 INT FileSize;
2257 PCHAR FileBuffer;
2258 ULONG OldEflags;
2259
2260 /* Initialize the object attributes */
2261 RtlInitUnicodeString(&FileName, L"\\SystemRoot\\system32\\drivers\\etc\\KDB.init");
2262 InitializeObjectAttributes(&ObjectAttributes, &FileName, 0, NULL, NULL);
2263
2264 /* Open the file */
2265 Status = ZwOpenFile(&hFile, FILE_READ_DATA, &ObjectAttributes, &Iosb, 0,
2266 FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT |
2267 FILE_NO_INTERMEDIATE_BUFFERING);
2268 if (!NT_SUCCESS(Status))
2269 {
2270 DPRINT("Could not open \\SystemRoot\\system32\\drivers\\etc\\KDB.init (Status 0x%x)", Status);
2271 return;
2272 }
2273
2274 /* Get the size of the file */
2275 Status = ZwQueryInformationFile(hFile, &Iosb, &FileStdInfo, sizeof (FileStdInfo),
2276 FileStandardInformation);
2277 if (!NT_SUCCESS(Status))
2278 {
2279 ZwClose(hFile);
2280 DPRINT("Could not query size of \\SystemRoot\\system32\\drivers\\etc\\KDB.init (Status 0x%x)", Status);
2281 return;
2282 }
2283 FileSize = FileStdInfo.EndOfFile.u.LowPart;
2284
2285 /* Allocate memory for the file */
2286 FileBuffer = ExAllocatePool(PagedPool, FileSize + 1); /* add 1 byte for terminating '\0' */
2287 if (FileBuffer == NULL)
2288 {
2289 ZwClose(hFile);
2290 DPRINT("Could not allocate %d bytes for KDB.init file\n", FileSize);
2291 return;
2292 }
2293
2294 /* Load file into memory */
2295 Status = ZwReadFile(hFile, 0, 0, 0, &Iosb, FileBuffer, FileSize, 0, 0);
2296 ZwClose(hFile);
2297 if (!NT_SUCCESS(Status) && Status != STATUS_END_OF_FILE)
2298 {
2299 ExFreePool(FileBuffer);
2300 DPRINT("Could not read KDB.init file into memory (Status 0x%lx)\n", Status);
2301 return;
2302 }
2303 FileSize = min(FileSize, Iosb.Information);
2304 FileBuffer[FileSize] = '\0';
2305
2306 /* Enter critical section */
2307 Ke386SaveFlags(OldEflags);
2308 Ke386DisableInterrupts();
2309
2310 /* Interpret the init file... */
2311 KdbInitFileBuffer = FileBuffer;
2312 KdbEnter();
2313 KdbInitFileBuffer = NULL;
2314
2315 /* Leave critical section */
2316 Ke386RestoreFlags(OldEflags);
2317
2318 ExFreePool(FileBuffer);
2319 }
2320