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