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