[CMAKE]
[reactos.git] / 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 along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19 /*
20 * PROJECT: ReactOS kernel
21 * FILE: ntoskrnl/dbg/kdb_cli.c
22 * PURPOSE: Kernel debugger command line interface
23 * PROGRAMMER: Gregor Anich (blight@blight.eu.org)
24 * Hervé Poussineau
25 * UPDATE HISTORY:
26 * Created 16/01/2005
27 */
28
29 /* INCLUDES ******************************************************************/
30
31 #include <ntoskrnl.h>
32
33 #define NDEBUG
34 #include <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_LOADED ? "Loaded" : \
57 ((state) == NPX_STATE_NOT_LOADED ? "Not loaded" : "Unknown"))
58
59 /* PROTOTYPES ****************************************************************/
60
61 static BOOLEAN KdbpCmdEvalExpression(ULONG Argc, PCHAR Argv[]);
62 static BOOLEAN KdbpCmdDisassembleX(ULONG Argc, PCHAR Argv[]);
63 static BOOLEAN KdbpCmdRegs(ULONG Argc, PCHAR Argv[]);
64 static BOOLEAN KdbpCmdBackTrace(ULONG Argc, PCHAR Argv[]);
65
66 static BOOLEAN KdbpCmdContinue(ULONG Argc, PCHAR Argv[]);
67 static BOOLEAN KdbpCmdStep(ULONG Argc, PCHAR Argv[]);
68 static BOOLEAN KdbpCmdBreakPointList(ULONG Argc, PCHAR Argv[]);
69 static BOOLEAN KdbpCmdEnableDisableClearBreakPoint(ULONG Argc, PCHAR Argv[]);
70 static BOOLEAN KdbpCmdBreakPoint(ULONG Argc, PCHAR Argv[]);
71
72 static BOOLEAN KdbpCmdThread(ULONG Argc, PCHAR Argv[]);
73 static BOOLEAN KdbpCmdProc(ULONG Argc, PCHAR Argv[]);
74
75 static BOOLEAN KdbpCmdMod(ULONG Argc, PCHAR Argv[]);
76 static BOOLEAN KdbpCmdGdtLdtIdt(ULONG Argc, PCHAR Argv[]);
77 static BOOLEAN KdbpCmdPcr(ULONG Argc, PCHAR Argv[]);
78 static BOOLEAN KdbpCmdTss(ULONG Argc, PCHAR Argv[]);
79
80 static BOOLEAN KdbpCmdBugCheck(ULONG Argc, PCHAR Argv[]);
81 static BOOLEAN KdbpCmdFilter(ULONG Argc, PCHAR Argv[]);
82 static BOOLEAN KdbpCmdSet(ULONG Argc, PCHAR Argv[]);
83 static BOOLEAN KdbpCmdHelp(ULONG Argc, PCHAR Argv[]);
84
85 /* GLOBALS *******************************************************************/
86
87 static BOOLEAN KdbUseIntelSyntax = FALSE; /* Set to TRUE for intel syntax */
88 static BOOLEAN KdbBreakOnModuleLoad = FALSE; /* Set to TRUE to break into KDB when a module is loaded */
89
90 static CHAR KdbCommandHistoryBuffer[2048]; /* Command history string ringbuffer */
91 static PCHAR KdbCommandHistory[sizeof(KdbCommandHistoryBuffer) / 8] = { NULL }; /* Command history ringbuffer */
92 static LONG KdbCommandHistoryBufferIndex = 0;
93 static LONG KdbCommandHistoryIndex = 0;
94
95 static ULONG KdbNumberOfRowsPrinted = 0;
96 static ULONG KdbNumberOfColsPrinted = 0;
97 static BOOLEAN KdbOutputAborted = FALSE;
98 static LONG KdbNumberOfRowsTerminal = -1;
99 static LONG KdbNumberOfColsTerminal = -1;
100
101 PCHAR KdbInitFileBuffer = NULL; /* Buffer where KDBinit file is loaded into during initialization */
102 BOOLEAN KdbpBugCheckRequested = FALSE;
103
104 static const struct
105 {
106 PCHAR Name;
107 PCHAR Syntax;
108 PCHAR Help;
109 BOOLEAN (*Fn)(ULONG Argc, PCHAR Argv[]);
110 } KdbDebuggerCommands[] = {
111 /* Data */
112 { NULL, NULL, "Data", NULL },
113 { "?", "? expression", "Evaluate expression.", KdbpCmdEvalExpression },
114 { "disasm", "disasm [address] [L count]", "Disassemble count instructions at address.", KdbpCmdDisassembleX },
115 { "x", "x [address] [L count]", "Display count dwords, starting at addr.", KdbpCmdDisassembleX },
116 { "regs", "regs", "Display general purpose registers.", KdbpCmdRegs },
117 { "cregs", "cregs", "Display control registers.", KdbpCmdRegs },
118 { "sregs", "sregs", "Display status registers.", KdbpCmdRegs },
119 { "dregs", "dregs", "Display debug registers.", KdbpCmdRegs },
120 { "bt", "bt [*frameaddr|thread id]", "Prints current backtrace or from given frame addr", KdbpCmdBackTrace },
121
122 /* Flow control */
123 { NULL, NULL, "Flow control", NULL },
124 { "cont", "cont", "Continue execution (leave debugger)", KdbpCmdContinue },
125 { "step", "step [count]", "Execute single instructions, stepping into interrupts.", KdbpCmdStep },
126 { "next", "next [count]", "Execute single instructions, skipping calls and reps.", KdbpCmdStep },
127 { "bl", "bl", "List breakpoints.", KdbpCmdBreakPointList },
128 { "be", "be [breakpoint]", "Enable breakpoint.", KdbpCmdEnableDisableClearBreakPoint },
129 { "bd", "bd [breakpoint]", "Disable breakpoint.", KdbpCmdEnableDisableClearBreakPoint },
130 { "bc", "bc [breakpoint]", "Clear breakpoint.", KdbpCmdEnableDisableClearBreakPoint },
131 { "bpx", "bpx [address] [IF condition]", "Set software execution breakpoint at address.", KdbpCmdBreakPoint },
132 { "bpm", "bpm [r|w|rw|x] [byte|word|dword] [address] [IF condition]", "Set memory breakpoint at address.", KdbpCmdBreakPoint },
133
134 /* Process/Thread */
135 { NULL, NULL, "Process/Thread", NULL },
136 { "thread", "thread [list[ pid]|[attach ]tid]", "List threads in current or specified process, display thread with given id or attach to thread.", KdbpCmdThread },
137 { "proc", "proc [list|[attach ]pid]", "List processes, display process with given id or attach to process.", KdbpCmdProc },
138
139 /* System information */
140 { NULL, NULL, "System info", NULL },
141 { "mod", "mod [address]", "List all modules or the one containing address.", KdbpCmdMod },
142 { "gdt", "gdt", "Display global descriptor table.", KdbpCmdGdtLdtIdt },
143 { "ldt", "ldt", "Display local descriptor table.", KdbpCmdGdtLdtIdt },
144 { "idt", "idt", "Display interrupt descriptor table.", KdbpCmdGdtLdtIdt },
145 { "pcr", "pcr", "Display processor control region.", KdbpCmdPcr },
146 { "tss", "tss", "Display task state segment.", KdbpCmdTss },
147
148 /* Others */
149 { NULL, NULL, "Others", NULL },
150 { "bugcheck", "bugcheck", "Bugchecks the system.", KdbpCmdBugCheck },
151 { "filter", "filter [error|warning|trace|info|level]+|-[componentname|default]", "Enable/disable debug channels", KdbpCmdFilter },
152 { "set", "set [var] [value]", "Sets var to value or displays value of var.", KdbpCmdSet },
153 { "help", "help", "Display help screen.", KdbpCmdHelp }
154 };
155
156 /* FUNCTIONS *****************************************************************/
157
158 /*!\brief Transform a component name to an integer
159 *
160 * \param ComponentName The name of the component.
161 * \param ComponentId Receives the component id on success.
162 *
163 * \retval TRUE Success.
164 * \retval FALSE Failure.
165 */
166 static BOOLEAN
167 KdbpGetComponentId(
168 IN PCCH ComponentName,
169 OUT PULONG ComponentId)
170 {
171 ULONG i;
172
173 static struct
174 {
175 PCCH Name;
176 ULONG Id;
177 }
178 ComponentTable[] =
179 {
180 { "DEFAULT", DPFLTR_DEFAULT_ID },
181 { "SYSTEM", DPFLTR_SYSTEM_ID },
182 { "SMSS", DPFLTR_SMSS_ID },
183 { "SETUP", DPFLTR_SETUP_ID },
184 { "NTFS", DPFLTR_NTFS_ID },
185 { "FSTUB", DPFLTR_FSTUB_ID },
186 { "CRASHDUMP", DPFLTR_CRASHDUMP_ID },
187 { "CDAUDIO", DPFLTR_CDAUDIO_ID },
188 { "CDROM", DPFLTR_CDROM_ID },
189 { "CLASSPNP", DPFLTR_CLASSPNP_ID },
190 { "DISK", DPFLTR_DISK_ID },
191 { "REDBOOK", DPFLTR_REDBOOK_ID },
192 { "STORPROP", DPFLTR_STORPROP_ID },
193 { "SCSIPORT", DPFLTR_SCSIPORT_ID },
194 { "SCSIMINIPORT", DPFLTR_SCSIMINIPORT_ID },
195 { "CONFIG", DPFLTR_CONFIG_ID },
196 { "I8042PRT", DPFLTR_I8042PRT_ID },
197 { "SERMOUSE", DPFLTR_SERMOUSE_ID },
198 { "LSERMOUS", DPFLTR_LSERMOUS_ID },
199 { "KBDHID", DPFLTR_KBDHID_ID },
200 { "MOUHID", DPFLTR_MOUHID_ID },
201 { "KBDCLASS", DPFLTR_KBDCLASS_ID },
202 { "MOUCLASS", DPFLTR_MOUCLASS_ID },
203 { "TWOTRACK", DPFLTR_TWOTRACK_ID },
204 { "WMILIB", DPFLTR_WMILIB_ID },
205 { "ACPI", DPFLTR_ACPI_ID },
206 { "AMLI", DPFLTR_AMLI_ID },
207 { "HALIA64", DPFLTR_HALIA64_ID },
208 { "VIDEO", DPFLTR_VIDEO_ID },
209 { "SVCHOST", DPFLTR_SVCHOST_ID },
210 { "VIDEOPRT", DPFLTR_VIDEOPRT_ID },
211 { "TCPIP", DPFLTR_TCPIP_ID },
212 { "DMSYNTH", DPFLTR_DMSYNTH_ID },
213 { "NTOSPNP", DPFLTR_NTOSPNP_ID },
214 { "FASTFAT", DPFLTR_FASTFAT_ID },
215 { "SAMSS", DPFLTR_SAMSS_ID },
216 { "PNPMGR", DPFLTR_PNPMGR_ID },
217 { "NETAPI", DPFLTR_NETAPI_ID },
218 { "SCSERVER", DPFLTR_SCSERVER_ID },
219 { "SCCLIENT", DPFLTR_SCCLIENT_ID },
220 { "SERIAL", DPFLTR_SERIAL_ID },
221 { "SERENUM", DPFLTR_SERENUM_ID },
222 { "UHCD", DPFLTR_UHCD_ID },
223 { "RPCPROXY", DPFLTR_RPCPROXY_ID },
224 { "AUTOCHK", DPFLTR_AUTOCHK_ID },
225 { "DCOMSS", DPFLTR_DCOMSS_ID },
226 { "UNIMODEM", DPFLTR_UNIMODEM_ID },
227 { "SIS", DPFLTR_SIS_ID },
228 { "FLTMGR", DPFLTR_FLTMGR_ID },
229 { "WMICORE", DPFLTR_WMICORE_ID },
230 { "BURNENG", DPFLTR_BURNENG_ID },
231 { "IMAPI", DPFLTR_IMAPI_ID },
232 { "SXS", DPFLTR_SXS_ID },
233 { "FUSION", DPFLTR_FUSION_ID },
234 { "IDLETASK", DPFLTR_IDLETASK_ID },
235 { "SOFTPCI", DPFLTR_SOFTPCI_ID },
236 { "TAPE", DPFLTR_TAPE_ID },
237 { "MCHGR", DPFLTR_MCHGR_ID },
238 { "IDEP", DPFLTR_IDEP_ID },
239 { "PCIIDE", DPFLTR_PCIIDE_ID },
240 { "FLOPPY", DPFLTR_FLOPPY_ID },
241 { "FDC", DPFLTR_FDC_ID },
242 { "TERMSRV", DPFLTR_TERMSRV_ID },
243 { "W32TIME", DPFLTR_W32TIME_ID },
244 { "PREFETCHER", DPFLTR_PREFETCHER_ID },
245 { "RSFILTER", DPFLTR_RSFILTER_ID },
246 { "FCPORT", DPFLTR_FCPORT_ID },
247 { "PCI", DPFLTR_PCI_ID },
248 { "DMIO", DPFLTR_DMIO_ID },
249 { "DMCONFIG", DPFLTR_DMCONFIG_ID },
250 { "DMADMIN", DPFLTR_DMADMIN_ID },
251 { "WSOCKTRANSPORT", DPFLTR_WSOCKTRANSPORT_ID },
252 { "VSS", DPFLTR_VSS_ID },
253 { "PNPMEM", DPFLTR_PNPMEM_ID },
254 { "PROCESSOR", DPFLTR_PROCESSOR_ID },
255 { "DMSERVER", DPFLTR_DMSERVER_ID },
256 { "SR", DPFLTR_SR_ID },
257 { "INFINIBAND", DPFLTR_INFINIBAND_ID },
258 { "IHVDRIVER", DPFLTR_IHVDRIVER_ID },
259 { "IHVVIDEO", DPFLTR_IHVVIDEO_ID },
260 { "IHVAUDIO", DPFLTR_IHVAUDIO_ID },
261 { "IHVNETWORK", DPFLTR_IHVNETWORK_ID },
262 { "IHVSTREAMING", DPFLTR_IHVSTREAMING_ID },
263 { "IHVBUS", DPFLTR_IHVBUS_ID },
264 { "HPS", DPFLTR_HPS_ID },
265 { "RTLTHREADPOOL", DPFLTR_RTLTHREADPOOL_ID },
266 { "LDR", DPFLTR_LDR_ID },
267 { "TCPIP6", DPFLTR_TCPIP6_ID },
268 { "ISAPNP", DPFLTR_ISAPNP_ID },
269 { "SHPC", DPFLTR_SHPC_ID },
270 { "STORPORT", DPFLTR_STORPORT_ID },
271 { "STORMINIPORT", DPFLTR_STORMINIPORT_ID },
272 { "PRINTSPOOLER", DPFLTR_PRINTSPOOLER_ID },
273 { "VSSDYNDISK", DPFLTR_VSSDYNDISK_ID },
274 { "VERIFIER", DPFLTR_VERIFIER_ID },
275 { "VDS", DPFLTR_VDS_ID },
276 { "VDSBAS", DPFLTR_VDSBAS_ID },
277 { "VDSDYN", DPFLTR_VDSDYN_ID },
278 { "VDSDYNDR", DPFLTR_VDSDYNDR_ID },
279 { "VDSLDR", DPFLTR_VDSLDR_ID },
280 { "VDSUTIL", DPFLTR_VDSUTIL_ID },
281 { "DFRGIFC", DPFLTR_DFRGIFC_ID },
282 { "MM", DPFLTR_MM_ID },
283 { "DFSC", DPFLTR_DFSC_ID },
284 { "WOW64", DPFLTR_WOW64_ID },
285 { "ALPC", DPFLTR_ALPC_ID },
286 { "WDI", DPFLTR_WDI_ID },
287 { "PERFLIB", DPFLTR_PERFLIB_ID },
288 { "KTM", DPFLTR_KTM_ID },
289 { "IOSTRESS", DPFLTR_IOSTRESS_ID },
290 { "HEAP", DPFLTR_HEAP_ID },
291 { "WHEA", DPFLTR_WHEA_ID },
292 { "USERGDI", DPFLTR_USERGDI_ID },
293 { "MMCSS", DPFLTR_MMCSS_ID },
294 { "TPM", DPFLTR_TPM_ID },
295 { "THREADORDER", DPFLTR_THREADORDER_ID },
296 { "ENVIRON", DPFLTR_ENVIRON_ID },
297 { "EMS", DPFLTR_EMS_ID },
298 { "WDT", DPFLTR_WDT_ID },
299 { "FVEVOL", DPFLTR_FVEVOL_ID },
300 { "NDIS", DPFLTR_NDIS_ID },
301 { "NVCTRACE", DPFLTR_NVCTRACE_ID },
302 { "LUAFV", DPFLTR_LUAFV_ID },
303 { "APPCOMPAT", DPFLTR_APPCOMPAT_ID },
304 { "USBSTOR", DPFLTR_USBSTOR_ID },
305 { "SBP2PORT", DPFLTR_SBP2PORT_ID },
306 { "COVERAGE", DPFLTR_COVERAGE_ID },
307 { "CACHEMGR", DPFLTR_CACHEMGR_ID },
308 { "MOUNTMGR", DPFLTR_MOUNTMGR_ID },
309 { "CFR", DPFLTR_CFR_ID },
310 { "TXF", DPFLTR_TXF_ID },
311 { "KSECDD", DPFLTR_KSECDD_ID },
312 { "FLTREGRESS", DPFLTR_FLTREGRESS_ID },
313 { "MPIO", DPFLTR_MPIO_ID },
314 { "MSDSM", DPFLTR_MSDSM_ID },
315 { "UDFS", DPFLTR_UDFS_ID },
316 { "PSHED", DPFLTR_PSHED_ID },
317 { "STORVSP", DPFLTR_STORVSP_ID },
318 { "LSASS", DPFLTR_LSASS_ID },
319 { "SSPICLI", DPFLTR_SSPICLI_ID },
320 { "CNG", DPFLTR_CNG_ID },
321 { "EXFAT", DPFLTR_EXFAT_ID },
322 { "FILETRACE", DPFLTR_FILETRACE_ID },
323 { "XSAVE", DPFLTR_XSAVE_ID },
324 { "SE", DPFLTR_SE_ID },
325 { "DRIVEEXTENDER", DPFLTR_DRIVEEXTENDER_ID },
326 };
327
328 for (i = 0; i < sizeof(ComponentTable) / sizeof(ComponentTable[0]); i++)
329 {
330 if (_stricmp(ComponentName, ComponentTable[i].Name) == 0)
331 {
332 *ComponentId = ComponentTable[i].Id;
333 return TRUE;
334 }
335 }
336
337 return FALSE;
338 }
339
340 /*!\brief Evaluates an expression...
341 *
342 * Much like KdbpRpnEvaluateExpression, but prints the error message (if any)
343 * at the given offset.
344 *
345 * \param Expression Expression to evaluate.
346 * \param ErrOffset Offset (in characters) to print the error message at.
347 * \param Result Receives the result on success.
348 *
349 * \retval TRUE Success.
350 * \retval FALSE Failure.
351 */
352 static BOOLEAN
353 KdbpEvaluateExpression(
354 IN PCHAR Expression,
355 IN LONG ErrOffset,
356 OUT PULONGLONG Result)
357 {
358 static CHAR ErrMsgBuffer[130] = "^ ";
359 LONG ExpressionErrOffset = -1;
360 PCHAR ErrMsg = ErrMsgBuffer;
361 BOOLEAN Ok;
362
363 Ok = KdbpRpnEvaluateExpression(Expression, KdbCurrentTrapFrame, Result,
364 &ExpressionErrOffset, ErrMsgBuffer + 2);
365 if (!Ok)
366 {
367 if (ExpressionErrOffset >= 0)
368 ExpressionErrOffset += ErrOffset;
369 else
370 ErrMsg += 2;
371
372 KdbpPrint("%*s%s\n", ExpressionErrOffset, "", ErrMsg);
373 }
374
375 return Ok;
376 }
377
378 /*!\brief Evaluates an expression and displays the result.
379 */
380 static BOOLEAN
381 KdbpCmdEvalExpression(
382 ULONG Argc,
383 PCHAR Argv[])
384 {
385 ULONG i, len;
386 ULONGLONG Result = 0;
387 ULONG ul;
388 LONG l = 0;
389 BOOLEAN Ok;
390
391 if (Argc < 2)
392 {
393 KdbpPrint("?: Argument required\n");
394 return TRUE;
395 }
396
397 /* Put the arguments back together */
398 Argc--;
399 for (i = 1; i < Argc; i++)
400 {
401 len = strlen(Argv[i]);
402 Argv[i][len] = ' ';
403 }
404
405 /* Evaluate the expression */
406 Ok = KdbpEvaluateExpression(Argv[1], sizeof("kdb:> ")-1 + (Argv[1]-Argv[0]), &Result);
407 if (Ok)
408 {
409 if (Result > 0x00000000ffffffffLL)
410 {
411 if (Result & 0x8000000000000000LL)
412 KdbpPrint("0x%016I64x %20I64u %20I64d\n", Result, Result, Result);
413 else
414 KdbpPrint("0x%016I64x %20I64u\n", Result, Result);
415 }
416 else
417 {
418 ul = (ULONG)Result;
419
420 if (ul <= 0xff && ul >= 0x80)
421 l = (LONG)((CHAR)ul);
422 else if (ul <= 0xffff && ul >= 0x8000)
423 l = (LONG)((SHORT)ul);
424 else
425 l = (LONG)ul;
426
427 if (l < 0)
428 KdbpPrint("0x%08lx %10lu %10ld\n", ul, ul, l);
429 else
430 KdbpPrint("0x%08lx %10lu\n", ul, ul);
431 }
432 }
433
434 return TRUE;
435 }
436
437 /*!\brief Display list of active debug channels
438 */
439 static BOOLEAN
440 KdbpCmdFilter(
441 ULONG Argc,
442 PCHAR Argv[])
443 {
444 ULONG i, j, ComponentId, Level;
445 ULONG set = DPFLTR_MASK, clear = DPFLTR_MASK;
446 PCHAR pend;
447 LPCSTR opt, p;
448
449 static struct
450 {
451 LPCSTR Name;
452 ULONG Level;
453 }
454 debug_classes[] =
455 {
456 { "error", 1 << DPFLTR_ERROR_LEVEL },
457 { "warning", 1 << DPFLTR_WARNING_LEVEL },
458 { "trace", 1 << DPFLTR_TRACE_LEVEL },
459 { "info", 1 << DPFLTR_INFO_LEVEL },
460 };
461
462 for (i = 1; i < Argc; i++)
463 {
464 opt = Argv[i];
465 p = opt + strcspn(opt, "+-");
466 if (!p[0]) p = opt; /* assume it's a debug channel name */
467
468 if (p > opt)
469 {
470 for (j = 0; j < sizeof(debug_classes) / sizeof(debug_classes[0]); j++)
471 {
472 SIZE_T len = strlen(debug_classes[j].Name);
473 if (len != (p - opt))
474 continue;
475 if (_strnicmp(opt, debug_classes[j].Name, len) == 0) /* found it */
476 {
477 if (*p == '+')
478 set |= debug_classes[j].Level;
479 else
480 clear |= debug_classes[j].Level;
481 break;
482 }
483 }
484 if (j == sizeof(debug_classes) / sizeof(debug_classes[0]))
485 {
486 Level = strtoul(opt, &pend, 0);
487 if (pend != p)
488 {
489 KdbpPrint("filter: bad class name '%.*s'\n", p - opt, opt);
490 continue;
491 }
492 if (*p == '+')
493 set |= Level;
494 else
495 clear |= Level;
496 }
497 }
498 else
499 {
500 if (*p == '-')
501 clear = MAXULONG;
502 else
503 set = MAXULONG;
504 }
505 if (*p == '+' || *p == '-')
506 p++;
507
508 if (!KdbpGetComponentId(p, &ComponentId))
509 {
510 KdbpPrint("filter: '%s' is not a valid component name!\n", p);
511 return TRUE;
512 }
513
514 /* Get current mask value */
515 NtSetDebugFilterState(ComponentId, set, TRUE);
516 NtSetDebugFilterState(ComponentId, clear, FALSE);
517 }
518
519 return TRUE;
520 }
521
522 /*!\brief Disassembles 10 instructions at eip or given address or
523 * displays 16 dwords from memory at given address.
524 */
525 static BOOLEAN
526 KdbpCmdDisassembleX(
527 ULONG Argc,
528 PCHAR Argv[])
529 {
530 ULONG Count;
531 ULONG ul;
532 INT i;
533 ULONGLONG Result = 0;
534 ULONG_PTR Address = KdbCurrentTrapFrame->Tf.Eip;
535 LONG InstLen;
536
537 if (Argv[0][0] == 'x') /* display memory */
538 Count = 16;
539 else /* disassemble */
540 Count = 10;
541
542 if (Argc >= 2)
543 {
544 /* Check for [L count] part */
545 ul = 0;
546 if (strcmp(Argv[Argc-2], "L") == 0)
547 {
548 ul = strtoul(Argv[Argc-1], NULL, 0);
549 if (ul > 0)
550 {
551 Count = ul;
552 Argc -= 2;
553 }
554 }
555 else if (Argv[Argc-1][0] == 'L')
556 {
557 ul = strtoul(Argv[Argc-1] + 1, NULL, 0);
558 if (ul > 0)
559 {
560 Count = ul;
561 Argc--;
562 }
563 }
564
565 /* Put the remaining arguments back together */
566 Argc--;
567 for (ul = 1; ul < Argc; ul++)
568 {
569 Argv[ul][strlen(Argv[ul])] = ' ';
570 }
571 Argc++;
572 }
573
574 /* Evaluate the expression */
575 if (Argc > 1)
576 {
577 if (!KdbpEvaluateExpression(Argv[1], sizeof("kdb:> ")-1 + (Argv[1]-Argv[0]), &Result))
578 return TRUE;
579
580 if (Result > (ULONGLONG)(~((ULONG_PTR)0)))
581 KdbpPrint("Warning: Address %I64x is beeing truncated\n",Result);
582
583 Address = (ULONG_PTR)Result;
584 }
585 else if (Argv[0][0] == 'x')
586 {
587 KdbpPrint("x: Address argument required.\n");
588 return TRUE;
589 }
590
591 if (Argv[0][0] == 'x')
592 {
593 /* Display dwords */
594 ul = 0;
595
596 while (Count > 0)
597 {
598 if (!KdbSymPrintAddress((PVOID)Address, NULL))
599 KdbpPrint("<%x>:", Address);
600 else
601 KdbpPrint(":");
602
603 i = min(4, Count);
604 Count -= i;
605
606 while (--i >= 0)
607 {
608 if (!NT_SUCCESS(KdbpSafeReadMemory(&ul, (PVOID)Address, sizeof(ul))))
609 KdbpPrint(" ????????");
610 else
611 KdbpPrint(" %08x", ul);
612
613 Address += sizeof(ul);
614 }
615
616 KdbpPrint("\n");
617 }
618 }
619 else
620 {
621 /* Disassemble */
622 while (Count-- > 0)
623 {
624 if (!KdbSymPrintAddress((PVOID)Address, NULL))
625 KdbpPrint("<%08x>: ", Address);
626 else
627 KdbpPrint(": ");
628
629 InstLen = KdbpDisassemble(Address, KdbUseIntelSyntax);
630 if (InstLen < 0)
631 {
632 KdbpPrint("<INVALID>\n");
633 return TRUE;
634 }
635
636 KdbpPrint("\n");
637 Address += InstLen;
638 }
639 }
640
641 return TRUE;
642 }
643
644 /*!\brief Displays CPU registers.
645 */
646 static BOOLEAN
647 KdbpCmdRegs(
648 ULONG Argc,
649 PCHAR Argv[])
650 {
651 PKTRAP_FRAME Tf = &KdbCurrentTrapFrame->Tf;
652 INT i;
653 static const PCHAR EflagsBits[32] = { " CF", NULL, " PF", " BIT3", " AF", " BIT5",
654 " ZF", " SF", " TF", " IF", " DF", " OF",
655 NULL, NULL, " NT", " BIT15", " RF", " VF",
656 " AC", " VIF", " VIP", " ID", " BIT22",
657 " BIT23", " BIT24", " BIT25", " BIT26",
658 " BIT27", " BIT28", " BIT29", " BIT30",
659 " BIT31" };
660
661 if (Argv[0][0] == 'r') /* regs */
662 {
663 KdbpPrint("CS:EIP 0x%04x:0x%08x\n"
664 "SS:ESP 0x%04x:0x%08x\n"
665 " EAX 0x%08x EBX 0x%08x\n"
666 " ECX 0x%08x EDX 0x%08x\n"
667 " ESI 0x%08x EDI 0x%08x\n"
668 " EBP 0x%08x\n",
669 Tf->SegCs & 0xFFFF, Tf->Eip,
670 Tf->HardwareSegSs, Tf->HardwareEsp,
671 Tf->Eax, Tf->Ebx,
672 Tf->Ecx, Tf->Edx,
673 Tf->Esi, Tf->Edi,
674 Tf->Ebp);
675 KdbpPrint("EFLAGS 0x%08x ", Tf->EFlags);
676
677 for (i = 0; i < 32; i++)
678 {
679 if (i == 1)
680 {
681 if ((Tf->EFlags & (1 << 1)) == 0)
682 KdbpPrint(" !BIT1");
683 }
684 else if (i == 12)
685 {
686 KdbpPrint(" IOPL%d", (Tf->EFlags >> 12) & 3);
687 }
688 else if (i == 13)
689 {
690 }
691 else if ((Tf->EFlags & (1 << i)) != 0)
692 {
693 KdbpPrint(EflagsBits[i]);
694 }
695 }
696
697 KdbpPrint("\n");
698 }
699 else if (Argv[0][0] == 'c') /* cregs */
700 {
701 ULONG Cr0, Cr2, Cr3, Cr4;
702 KDESCRIPTOR Gdtr, Idtr;
703 USHORT Ldtr;
704 static const PCHAR Cr0Bits[32] = { " PE", " MP", " EM", " TS", " ET", " NE", NULL, NULL,
705 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
706 " WP", NULL, " AM", NULL, NULL, NULL, NULL, NULL,
707 NULL, NULL, NULL, NULL, NULL, " NW", " CD", " PG" };
708 static const PCHAR Cr4Bits[32] = { " VME", " PVI", " TSD", " DE", " PSE", " PAE", " MCE", " PGE",
709 " PCE", " OSFXSR", " OSXMMEXCPT", NULL, NULL, NULL, NULL, NULL,
710 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
711 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL };
712
713 Cr0 = KdbCurrentTrapFrame->Cr0;
714 Cr2 = KdbCurrentTrapFrame->Cr2;
715 Cr3 = KdbCurrentTrapFrame->Cr3;
716 Cr4 = KdbCurrentTrapFrame->Cr4;
717
718 /* Get descriptor table regs */
719 Ke386GetGlobalDescriptorTable(&Gdtr.Limit);
720 Ldtr = Ke386GetLocalDescriptorTable();
721 __sidt(&Idtr.Limit);
722
723 /* Display the control registers */
724 KdbpPrint("CR0 0x%08x ", Cr0);
725
726 for (i = 0; i < 32; i++)
727 {
728 if (!Cr0Bits[i])
729 continue;
730
731 if ((Cr0 & (1 << i)) != 0)
732 KdbpPrint(Cr0Bits[i]);
733 }
734
735 KdbpPrint("\nCR2 0x%08x\n", Cr2);
736 KdbpPrint("CR3 0x%08x Pagedir-Base 0x%08x %s%s\n", Cr3, (Cr3 & 0xfffff000),
737 (Cr3 & (1 << 3)) ? " PWT" : "", (Cr3 & (1 << 4)) ? " PCD" : "" );
738 KdbpPrint("CR4 0x%08x ", Cr4);
739
740 for (i = 0; i < 32; i++)
741 {
742 if (!Cr4Bits[i])
743 continue;
744
745 if ((Cr4 & (1 << i)) != 0)
746 KdbpPrint(Cr4Bits[i]);
747 }
748
749 /* Display the descriptor table regs */
750 KdbpPrint("\nGDTR Base 0x%08x Size 0x%04x\n", Gdtr.Base, Gdtr.Limit);
751 KdbpPrint("LDTR 0x%04x\n", Ldtr);
752 KdbpPrint("IDTR Base 0x%08x Size 0x%04x\n", Idtr.Base, Idtr.Limit);
753 }
754 else if (Argv[0][0] == 's') /* sregs */
755 {
756 KdbpPrint("CS 0x%04x Index 0x%04x %cDT RPL%d\n",
757 Tf->SegCs & 0xffff, (Tf->SegCs & 0xffff) >> 3,
758 (Tf->SegCs & (1 << 2)) ? 'L' : 'G', Tf->SegCs & 3);
759 KdbpPrint("DS 0x%04x Index 0x%04x %cDT RPL%d\n",
760 Tf->SegDs, Tf->SegDs >> 3, (Tf->SegDs & (1 << 2)) ? 'L' : 'G', Tf->SegDs & 3);
761 KdbpPrint("ES 0x%04x Index 0x%04x %cDT RPL%d\n",
762 Tf->SegEs, Tf->SegEs >> 3, (Tf->SegEs & (1 << 2)) ? 'L' : 'G', Tf->SegEs & 3);
763 KdbpPrint("FS 0x%04x Index 0x%04x %cDT RPL%d\n",
764 Tf->SegFs, Tf->SegFs >> 3, (Tf->SegFs & (1 << 2)) ? 'L' : 'G', Tf->SegFs & 3);
765 KdbpPrint("GS 0x%04x Index 0x%04x %cDT RPL%d\n",
766 Tf->SegGs, Tf->SegGs >> 3, (Tf->SegGs & (1 << 2)) ? 'L' : 'G', Tf->SegGs & 3);
767 KdbpPrint("SS 0x%04x Index 0x%04x %cDT RPL%d\n",
768 Tf->HardwareSegSs, Tf->HardwareSegSs >> 3, (Tf->HardwareSegSs & (1 << 2)) ? 'L' : 'G', Tf->HardwareSegSs & 3);
769 }
770 else /* dregs */
771 {
772 ASSERT(Argv[0][0] == 'd');
773 KdbpPrint("DR0 0x%08x\n"
774 "DR1 0x%08x\n"
775 "DR2 0x%08x\n"
776 "DR3 0x%08x\n"
777 "DR6 0x%08x\n"
778 "DR7 0x%08x\n",
779 Tf->Dr0, Tf->Dr1, Tf->Dr2, Tf->Dr3,
780 Tf->Dr6, Tf->Dr7);
781 }
782
783 return TRUE;
784 }
785
786 /*!\brief Displays a backtrace.
787 */
788 static BOOLEAN
789 KdbpCmdBackTrace(
790 ULONG Argc,
791 PCHAR Argv[])
792 {
793 ULONG ul;
794 ULONGLONG Result = 0;
795 ULONG_PTR Frame = KdbCurrentTrapFrame->Tf.Ebp;
796 ULONG_PTR Address;
797 KTRAP_FRAME TrapFrame;
798
799 if (Argc >= 2)
800 {
801 /* Check for [L count] part */
802 ul = 0;
803
804 if (strcmp(Argv[Argc-2], "L") == 0)
805 {
806 ul = strtoul(Argv[Argc-1], NULL, 0);
807 if (ul > 0)
808 {
809 Argc -= 2;
810 }
811 }
812 else if (Argv[Argc-1][0] == 'L')
813 {
814 ul = strtoul(Argv[Argc-1] + 1, NULL, 0);
815 if (ul > 0)
816 {
817 Argc--;
818 }
819 }
820
821 /* Put the remaining arguments back together */
822 Argc--;
823 for (ul = 1; ul < Argc; ul++)
824 {
825 Argv[ul][strlen(Argv[ul])] = ' ';
826 }
827 Argc++;
828 }
829
830 /* Check if frame addr or thread id is given. */
831 if (Argc > 1)
832 {
833 if (Argv[1][0] == '*')
834 {
835 Argv[1]++;
836
837 /* Evaluate the expression */
838 if (!KdbpEvaluateExpression(Argv[1], sizeof("kdb:> ")-1 + (Argv[1]-Argv[0]), &Result))
839 return TRUE;
840
841 if (Result > (ULONGLONG)(~((ULONG_PTR)0)))
842 KdbpPrint("Warning: Address %I64x is beeing truncated\n",Result);
843
844 Frame = (ULONG_PTR)Result;
845 }
846 else
847 {
848 KdbpPrint("Thread backtrace not supported yet!\n");
849 return TRUE;
850 }
851 }
852 else
853 {
854 KdbpPrint("Eip:\n");
855
856 /* Try printing the function at EIP */
857 if (!KdbSymPrintAddress((PVOID)KdbCurrentTrapFrame->Tf.Eip, &KdbCurrentTrapFrame->Tf))
858 KdbpPrint("<%08x>\n", KdbCurrentTrapFrame->Tf.Eip);
859 else
860 KdbpPrint("\n");
861 }
862
863 TrapFrame = KdbCurrentTrapFrame->Tf;
864 KdbpPrint("Frames:\n");
865
866 for (;;)
867 {
868 BOOLEAN GotNextFrame;
869
870 if (Frame == 0)
871 break;
872
873 if (!NT_SUCCESS(KdbpSafeReadMemory(&Address, (PVOID)(Frame + sizeof(ULONG_PTR)), sizeof (ULONG_PTR))))
874 {
875 KdbpPrint("Couldn't access memory at 0x%p!\n", Frame + sizeof(ULONG_PTR));
876 break;
877 }
878
879 if ((GotNextFrame = NT_SUCCESS(KdbpSafeReadMemory(&Frame, (PVOID)Frame, sizeof (ULONG_PTR)))))
880 TrapFrame.Ebp = Frame;
881
882 /* Print the location of the call instruction */
883 if (!KdbSymPrintAddress((PVOID)(Address - 5), &TrapFrame))
884 KdbpPrint("<%08x>\n", Address);
885 else
886 KdbpPrint("\n");
887
888 if (KdbOutputAborted) break;
889
890 if (Address == 0)
891 break;
892
893 if (!GotNextFrame)
894 {
895 KdbpPrint("Couldn't access memory at 0x%p!\n", Frame);
896 break;
897 }
898 }
899
900 return TRUE;
901 }
902
903 /*!\brief Continues execution of the system/leaves KDB.
904 */
905 static BOOLEAN
906 KdbpCmdContinue(
907 ULONG Argc,
908 PCHAR Argv[])
909 {
910 /* Exit the main loop */
911 return FALSE;
912 }
913
914 /*!\brief Continues execution of the system/leaves KDB.
915 */
916 static BOOLEAN
917 KdbpCmdStep(
918 ULONG Argc,
919 PCHAR Argv[])
920 {
921 ULONG Count = 1;
922
923 if (Argc > 1)
924 {
925 Count = strtoul(Argv[1], NULL, 0);
926 if (Count == 0)
927 {
928 KdbpPrint("%s: Integer argument required\n", Argv[0]);
929 return TRUE;
930 }
931 }
932
933 if (Argv[0][0] == 'n')
934 KdbSingleStepOver = TRUE;
935 else
936 KdbSingleStepOver = FALSE;
937
938 /* Set the number of single steps and return to the interrupted code. */
939 KdbNumSingleSteps = Count;
940
941 return FALSE;
942 }
943
944 /*!\brief Lists breakpoints.
945 */
946 static BOOLEAN
947 KdbpCmdBreakPointList(
948 ULONG Argc,
949 PCHAR Argv[])
950 {
951 LONG l;
952 ULONG_PTR Address = 0;
953 KDB_BREAKPOINT_TYPE Type = 0;
954 KDB_ACCESS_TYPE AccessType = 0;
955 UCHAR Size = 0;
956 UCHAR DebugReg = 0;
957 BOOLEAN Enabled = FALSE;
958 BOOLEAN Global = FALSE;
959 PEPROCESS Process = NULL;
960 PCHAR str1, str2, ConditionExpr, GlobalOrLocal;
961 CHAR Buffer[20];
962
963 l = KdbpGetNextBreakPointNr(0);
964 if (l < 0)
965 {
966 KdbpPrint("No breakpoints.\n");
967 return TRUE;
968 }
969
970 KdbpPrint("Breakpoints:\n");
971 do
972 {
973 if (!KdbpGetBreakPointInfo(l, &Address, &Type, &Size, &AccessType, &DebugReg,
974 &Enabled, &Global, &Process, &ConditionExpr))
975 {
976 continue;
977 }
978
979 if (l == KdbLastBreakPointNr)
980 {
981 str1 = "\x1b[1m*";
982 str2 = "\x1b[0m";
983 }
984 else
985 {
986 str1 = " ";
987 str2 = "";
988 }
989
990 if (Global)
991 {
992 GlobalOrLocal = " global";
993 }
994 else
995 {
996 GlobalOrLocal = Buffer;
997 sprintf(Buffer, " PID 0x%08lx",
998 (ULONG)(Process ? Process->UniqueProcessId : INVALID_HANDLE_VALUE));
999 }
1000
1001 if (Type == KdbBreakPointSoftware || Type == KdbBreakPointTemporary)
1002 {
1003 KdbpPrint(" %s%03d BPX 0x%08x%s%s%s%s%s\n",
1004 str1, l, Address,
1005 Enabled ? "" : " disabled",
1006 GlobalOrLocal,
1007 ConditionExpr ? " IF " : "",
1008 ConditionExpr ? ConditionExpr : "",
1009 str2);
1010 }
1011 else if (Type == KdbBreakPointHardware)
1012 {
1013 if (!Enabled)
1014 {
1015 KdbpPrint(" %s%03d BPM 0x%08x %-5s %-5s disabled%s%s%s%s\n", str1, l, Address,
1016 KDB_ACCESS_TYPE_TO_STRING(AccessType),
1017 Size == 1 ? "byte" : (Size == 2 ? "word" : "dword"),
1018 GlobalOrLocal,
1019 ConditionExpr ? " IF " : "",
1020 ConditionExpr ? ConditionExpr : "",
1021 str2);
1022 }
1023 else
1024 {
1025 KdbpPrint(" %s%03d BPM 0x%08x %-5s %-5s DR%d%s%s%s%s\n", str1, l, Address,
1026 KDB_ACCESS_TYPE_TO_STRING(AccessType),
1027 Size == 1 ? "byte" : (Size == 2 ? "word" : "dword"),
1028 DebugReg,
1029 GlobalOrLocal,
1030 ConditionExpr ? " IF " : "",
1031 ConditionExpr ? ConditionExpr : "",
1032 str2);
1033 }
1034 }
1035 }
1036 while ((l = KdbpGetNextBreakPointNr(l+1)) >= 0);
1037
1038 return TRUE;
1039 }
1040
1041 /*!\brief Enables, disables or clears a breakpoint.
1042 */
1043 static BOOLEAN
1044 KdbpCmdEnableDisableClearBreakPoint(
1045 ULONG Argc,
1046 PCHAR Argv[])
1047 {
1048 PCHAR pend;
1049 ULONG BreakPointNr;
1050
1051 if (Argc < 2)
1052 {
1053 KdbpPrint("%s: argument required\n", Argv[0]);
1054 return TRUE;
1055 }
1056
1057 pend = Argv[1];
1058 BreakPointNr = strtoul(Argv[1], &pend, 0);
1059 if (pend == Argv[1] || *pend != '\0')
1060 {
1061 KdbpPrint("%s: integer argument required\n", Argv[0]);
1062 return TRUE;
1063 }
1064
1065 if (Argv[0][1] == 'e') /* enable */
1066 {
1067 KdbpEnableBreakPoint(BreakPointNr, NULL);
1068 }
1069 else if (Argv [0][1] == 'd') /* disable */
1070 {
1071 KdbpDisableBreakPoint(BreakPointNr, NULL);
1072 }
1073 else /* clear */
1074 {
1075 ASSERT(Argv[0][1] == 'c');
1076 KdbpDeleteBreakPoint(BreakPointNr, NULL);
1077 }
1078
1079 return TRUE;
1080 }
1081
1082 /*!\brief Sets a software or hardware (memory) breakpoint at the given address.
1083 */
1084 static BOOLEAN
1085 KdbpCmdBreakPoint(ULONG Argc, PCHAR Argv[])
1086 {
1087 ULONGLONG Result = 0;
1088 ULONG_PTR Address;
1089 KDB_BREAKPOINT_TYPE Type;
1090 UCHAR Size = 0;
1091 KDB_ACCESS_TYPE AccessType = 0;
1092 ULONG AddressArgIndex, i;
1093 LONG ConditionArgIndex;
1094 BOOLEAN Global = TRUE;
1095
1096 if (Argv[0][2] == 'x') /* software breakpoint */
1097 {
1098 if (Argc < 2)
1099 {
1100 KdbpPrint("bpx: Address argument required.\n");
1101 return TRUE;
1102 }
1103
1104 AddressArgIndex = 1;
1105 Type = KdbBreakPointSoftware;
1106 }
1107 else /* memory breakpoint */
1108 {
1109 ASSERT(Argv[0][2] == 'm');
1110
1111 if (Argc < 2)
1112 {
1113 KdbpPrint("bpm: Access type argument required (one of r, w, rw, x)\n");
1114 return TRUE;
1115 }
1116
1117 if (_stricmp(Argv[1], "x") == 0)
1118 AccessType = KdbAccessExec;
1119 else if (_stricmp(Argv[1], "r") == 0)
1120 AccessType = KdbAccessRead;
1121 else if (_stricmp(Argv[1], "w") == 0)
1122 AccessType = KdbAccessWrite;
1123 else if (_stricmp(Argv[1], "rw") == 0)
1124 AccessType = KdbAccessReadWrite;
1125 else
1126 {
1127 KdbpPrint("bpm: Unknown access type '%s'\n", Argv[1]);
1128 return TRUE;
1129 }
1130
1131 if (Argc < 3)
1132 {
1133 KdbpPrint("bpm: %s argument required.\n", AccessType == KdbAccessExec ? "Address" : "Memory size");
1134 return TRUE;
1135 }
1136
1137 AddressArgIndex = 3;
1138 if (_stricmp(Argv[2], "byte") == 0)
1139 Size = 1;
1140 else if (_stricmp(Argv[2], "word") == 0)
1141 Size = 2;
1142 else if (_stricmp(Argv[2], "dword") == 0)
1143 Size = 4;
1144 else if (AccessType == KdbAccessExec)
1145 {
1146 Size = 1;
1147 AddressArgIndex--;
1148 }
1149 else
1150 {
1151 KdbpPrint("bpm: Unknown memory size '%s'\n", Argv[2]);
1152 return TRUE;
1153 }
1154
1155 if (Argc <= AddressArgIndex)
1156 {
1157 KdbpPrint("bpm: Address argument required.\n");
1158 return TRUE;
1159 }
1160
1161 Type = KdbBreakPointHardware;
1162 }
1163
1164 /* Put the arguments back together */
1165 ConditionArgIndex = -1;
1166 for (i = AddressArgIndex; i < (Argc-1); i++)
1167 {
1168 if (strcmp(Argv[i+1], "IF") == 0) /* IF found */
1169 {
1170 ConditionArgIndex = i + 2;
1171 if (ConditionArgIndex >= Argc)
1172 {
1173 KdbpPrint("%s: IF requires condition expression.\n", Argv[0]);
1174 return TRUE;
1175 }
1176
1177 for (i = ConditionArgIndex; i < (Argc-1); i++)
1178 Argv[i][strlen(Argv[i])] = ' ';
1179
1180 break;
1181 }
1182
1183 Argv[i][strlen(Argv[i])] = ' ';
1184 }
1185
1186 /* Evaluate the address expression */
1187 if (!KdbpEvaluateExpression(Argv[AddressArgIndex],
1188 sizeof("kdb:> ")-1 + (Argv[AddressArgIndex]-Argv[0]),
1189 &Result))
1190 {
1191 return TRUE;
1192 }
1193
1194 if (Result > (ULONGLONG)(~((ULONG_PTR)0)))
1195 KdbpPrint("%s: Warning: Address %I64x is beeing truncated\n", Argv[0],Result);
1196
1197 Address = (ULONG_PTR)Result;
1198
1199 KdbpInsertBreakPoint(Address, Type, Size, AccessType,
1200 (ConditionArgIndex < 0) ? NULL : Argv[ConditionArgIndex],
1201 Global, NULL);
1202
1203 return TRUE;
1204 }
1205
1206 /*!\brief Lists threads or switches to another thread context.
1207 */
1208 static BOOLEAN
1209 KdbpCmdThread(
1210 ULONG Argc,
1211 PCHAR Argv[])
1212 {
1213 PLIST_ENTRY Entry;
1214 PETHREAD Thread = NULL;
1215 PEPROCESS Process = NULL;
1216 BOOLEAN ReferencedThread = FALSE, ReferencedProcess = FALSE;
1217 PULONG Esp;
1218 PULONG Ebp;
1219 ULONG Eip;
1220 ULONG ul = 0;
1221 PCHAR State, pend, str1, str2;
1222 static const PCHAR ThreadStateToString[DeferredReady+1] =
1223 {
1224 "Initialized", "Ready", "Running",
1225 "Standby", "Terminated", "Waiting",
1226 "Transition", "DeferredReady"
1227 };
1228
1229 ASSERT(KdbCurrentProcess);
1230
1231 if (Argc >= 2 && _stricmp(Argv[1], "list") == 0)
1232 {
1233 Process = KdbCurrentProcess;
1234
1235 if (Argc >= 3)
1236 {
1237 ul = strtoul(Argv[2], &pend, 0);
1238 if (Argv[2] == pend)
1239 {
1240 KdbpPrint("thread: '%s' is not a valid process id!\n", Argv[2]);
1241 return TRUE;
1242 }
1243
1244 if (!NT_SUCCESS(PsLookupProcessByProcessId((PVOID)ul, &Process)))
1245 {
1246 KdbpPrint("thread: Invalid process id!\n");
1247 return TRUE;
1248 }
1249
1250 /* Remember our reference */
1251 ReferencedProcess = TRUE;
1252 }
1253
1254 Entry = Process->ThreadListHead.Flink;
1255 if (Entry == &Process->ThreadListHead)
1256 {
1257 if (Argc >= 3)
1258 KdbpPrint("No threads in process 0x%08x!\n", ul);
1259 else
1260 KdbpPrint("No threads in current process!\n");
1261
1262 if (ReferencedProcess)
1263 ObDereferenceObject(Process);
1264
1265 return TRUE;
1266 }
1267
1268 KdbpPrint(" TID State Prior. Affinity EBP EIP\n");
1269 do
1270 {
1271 Thread = CONTAINING_RECORD(Entry, ETHREAD, ThreadListEntry);
1272
1273 if (Thread == KdbCurrentThread)
1274 {
1275 str1 = "\x1b[1m*";
1276 str2 = "\x1b[0m";
1277 }
1278 else
1279 {
1280 str1 = " ";
1281 str2 = "";
1282 }
1283
1284 if (!Thread->Tcb.InitialStack)
1285 {
1286 /* Thread has no kernel stack (probably terminated) */
1287 Esp = Ebp = NULL;
1288 Eip = 0;
1289 }
1290 else if (Thread->Tcb.TrapFrame)
1291 {
1292 if (Thread->Tcb.TrapFrame->PreviousPreviousMode == KernelMode)
1293 Esp = (PULONG)Thread->Tcb.TrapFrame->TempEsp;
1294 else
1295 Esp = (PULONG)Thread->Tcb.TrapFrame->HardwareEsp;
1296
1297 Ebp = (PULONG)Thread->Tcb.TrapFrame->Ebp;
1298 Eip = Thread->Tcb.TrapFrame->Eip;
1299 }
1300 else
1301 {
1302 Esp = (PULONG)Thread->Tcb.KernelStack;
1303 Ebp = (PULONG)Esp[4];
1304 Eip = 0;
1305
1306 if (Ebp) /* FIXME: Should we attach to the process to read Ebp[1]? */
1307 KdbpSafeReadMemory(&Eip, Ebp + 1, sizeof (Eip));
1308 }
1309
1310 if (Thread->Tcb.State < (DeferredReady + 1))
1311 State = ThreadStateToString[Thread->Tcb.State];
1312 else
1313 State = "Unknown";
1314
1315 KdbpPrint(" %s0x%08x %-11s %3d 0x%08x 0x%08x 0x%08x%s\n",
1316 str1,
1317 Thread->Cid.UniqueThread,
1318 State,
1319 Thread->Tcb.Priority,
1320 Thread->Tcb.Affinity,
1321 Ebp,
1322 Eip,
1323 str2);
1324
1325 Entry = Entry->Flink;
1326 }
1327 while (Entry != &Process->ThreadListHead);
1328
1329 /* Release our reference, if any */
1330 if (ReferencedProcess)
1331 ObDereferenceObject(Process);
1332 }
1333 else if (Argc >= 2 && _stricmp(Argv[1], "attach") == 0)
1334 {
1335 if (Argc < 3)
1336 {
1337 KdbpPrint("thread attach: thread id argument required!\n");
1338 return TRUE;
1339 }
1340
1341 ul = strtoul(Argv[2], &pend, 0);
1342 if (Argv[2] == pend)
1343 {
1344 KdbpPrint("thread attach: '%s' is not a valid thread id!\n", Argv[2]);
1345 return TRUE;
1346 }
1347
1348 if (!KdbpAttachToThread((PVOID)ul))
1349 {
1350 return TRUE;
1351 }
1352
1353 KdbpPrint("Attached to thread 0x%08x.\n", ul);
1354 }
1355 else
1356 {
1357 Thread = KdbCurrentThread;
1358
1359 if (Argc >= 2)
1360 {
1361 ul = strtoul(Argv[1], &pend, 0);
1362 if (Argv[1] == pend)
1363 {
1364 KdbpPrint("thread: '%s' is not a valid thread id!\n", Argv[1]);
1365 return TRUE;
1366 }
1367
1368 if (!NT_SUCCESS(PsLookupThreadByThreadId((PVOID)ul, &Thread)))
1369 {
1370 KdbpPrint("thread: Invalid thread id!\n");
1371 return TRUE;
1372 }
1373
1374 /* Remember our reference */
1375 ReferencedThread = TRUE;
1376 }
1377
1378 if (Thread->Tcb.State < (DeferredReady + 1))
1379 State = ThreadStateToString[Thread->Tcb.State];
1380 else
1381 State = "Unknown";
1382
1383 KdbpPrint("%s"
1384 " TID: 0x%08x\n"
1385 " State: %s (0x%x)\n"
1386 " Priority: %d\n"
1387 " Affinity: 0x%08x\n"
1388 " Initial Stack: 0x%08x\n"
1389 " Stack Limit: 0x%08x\n"
1390 " Stack Base: 0x%08x\n"
1391 " Kernel Stack: 0x%08x\n"
1392 " Trap Frame: 0x%08x\n"
1393 " NPX State: %s (0x%x)\n",
1394 (Argc < 2) ? "Current Thread:\n" : "",
1395 Thread->Cid.UniqueThread,
1396 State, Thread->Tcb.State,
1397 Thread->Tcb.Priority,
1398 Thread->Tcb.Affinity,
1399 Thread->Tcb.InitialStack,
1400 Thread->Tcb.StackLimit,
1401 Thread->Tcb.StackBase,
1402 Thread->Tcb.KernelStack,
1403 Thread->Tcb.TrapFrame,
1404 NPX_STATE_TO_STRING(Thread->Tcb.NpxState), Thread->Tcb.NpxState);
1405
1406 /* Release our reference if we had one */
1407 if (ReferencedThread)
1408 ObDereferenceObject(Thread);
1409 }
1410
1411 return TRUE;
1412 }
1413
1414 /*!\brief Lists processes or switches to another process context.
1415 */
1416 static BOOLEAN
1417 KdbpCmdProc(
1418 ULONG Argc,
1419 PCHAR Argv[])
1420 {
1421 PLIST_ENTRY Entry;
1422 PEPROCESS Process;
1423 BOOLEAN ReferencedProcess = FALSE;
1424 PCHAR State, pend, str1, str2;
1425 ULONG ul;
1426 extern LIST_ENTRY PsActiveProcessHead;
1427
1428 if (Argc >= 2 && _stricmp(Argv[1], "list") == 0)
1429 {
1430 Entry = PsActiveProcessHead.Flink;
1431 if (!Entry || Entry == &PsActiveProcessHead)
1432 {
1433 KdbpPrint("No processes in the system!\n");
1434 return TRUE;
1435 }
1436
1437 KdbpPrint(" PID State Filename\n");
1438 do
1439 {
1440 Process = CONTAINING_RECORD(Entry, EPROCESS, ActiveProcessLinks);
1441
1442 if (Process == KdbCurrentProcess)
1443 {
1444 str1 = "\x1b[1m*";
1445 str2 = "\x1b[0m";
1446 }
1447 else
1448 {
1449 str1 = " ";
1450 str2 = "";
1451 }
1452
1453 State = ((Process->Pcb.State == ProcessInMemory) ? "In Memory" :
1454 ((Process->Pcb.State == ProcessOutOfMemory) ? "Out of Memory" : "In Transition"));
1455
1456 KdbpPrint(" %s0x%08x %-10s %s%s\n",
1457 str1,
1458 Process->UniqueProcessId,
1459 State,
1460 Process->ImageFileName,
1461 str2);
1462
1463 Entry = Entry->Flink;
1464 }
1465 while(Entry != &PsActiveProcessHead);
1466 }
1467 else if (Argc >= 2 && _stricmp(Argv[1], "attach") == 0)
1468 {
1469 if (Argc < 3)
1470 {
1471 KdbpPrint("process attach: process id argument required!\n");
1472 return TRUE;
1473 }
1474
1475 ul = strtoul(Argv[2], &pend, 0);
1476 if (Argv[2] == pend)
1477 {
1478 KdbpPrint("process attach: '%s' is not a valid process id!\n", Argv[2]);
1479 return TRUE;
1480 }
1481
1482 if (!KdbpAttachToProcess((PVOID)ul))
1483 {
1484 return TRUE;
1485 }
1486
1487 KdbpPrint("Attached to process 0x%08x, thread 0x%08x.\n", (ULONG)ul,
1488 (ULONG)KdbCurrentThread->Cid.UniqueThread);
1489 }
1490 else
1491 {
1492 Process = KdbCurrentProcess;
1493
1494 if (Argc >= 2)
1495 {
1496 ul = strtoul(Argv[1], &pend, 0);
1497 if (Argv[1] == pend)
1498 {
1499 KdbpPrint("proc: '%s' is not a valid process id!\n", Argv[1]);
1500 return TRUE;
1501 }
1502
1503 if (!NT_SUCCESS(PsLookupProcessByProcessId((PVOID)ul, &Process)))
1504 {
1505 KdbpPrint("proc: Invalid process id!\n");
1506 return TRUE;
1507 }
1508
1509 /* Remember our reference */
1510 ReferencedProcess = TRUE;
1511 }
1512
1513 State = ((Process->Pcb.State == ProcessInMemory) ? "In Memory" :
1514 ((Process->Pcb.State == ProcessOutOfMemory) ? "Out of Memory" : "In Transition"));
1515 KdbpPrint("%s"
1516 " PID: 0x%08x\n"
1517 " State: %s (0x%x)\n"
1518 " Image Filename: %s\n",
1519 (Argc < 2) ? "Current process:\n" : "",
1520 Process->UniqueProcessId,
1521 State, Process->Pcb.State,
1522 Process->ImageFileName);
1523
1524 /* Release our reference, if any */
1525 if (ReferencedProcess)
1526 ObDereferenceObject(Process);
1527 }
1528
1529 return TRUE;
1530 }
1531
1532 /*!\brief Lists loaded modules or the one containing the specified address.
1533 */
1534 static BOOLEAN
1535 KdbpCmdMod(
1536 ULONG Argc,
1537 PCHAR Argv[])
1538 {
1539 ULONGLONG Result = 0;
1540 ULONG_PTR Address;
1541 PLDR_DATA_TABLE_ENTRY LdrEntry;
1542 BOOLEAN DisplayOnlyOneModule = FALSE;
1543 INT i = 0;
1544
1545 if (Argc >= 2)
1546 {
1547 /* Put the arguments back together */
1548 Argc--;
1549 while (--Argc >= 1)
1550 Argv[Argc][strlen(Argv[Argc])] = ' ';
1551
1552 /* Evaluate the expression */
1553 if (!KdbpEvaluateExpression(Argv[1], sizeof("kdb:> ")-1 + (Argv[1]-Argv[0]), &Result))
1554 {
1555 return TRUE;
1556 }
1557
1558 if (Result > (ULONGLONG)(~((ULONG_PTR)0)))
1559 KdbpPrint("%s: Warning: Address %I64x is beeing truncated\n", Argv[0],Result);
1560
1561 Address = (ULONG_PTR)Result;
1562
1563 if (!KdbpSymFindModule((PVOID)Address, NULL, -1, &LdrEntry))
1564 {
1565 KdbpPrint("No module containing address 0x%p found!\n", Address);
1566 return TRUE;
1567 }
1568
1569 DisplayOnlyOneModule = TRUE;
1570 }
1571 else
1572 {
1573 if (!KdbpSymFindModule(NULL, NULL, 0, &LdrEntry))
1574 {
1575 ULONG_PTR ntoskrnlBase = ((ULONG_PTR)KdbpCmdMod) & 0xfff00000;
1576 KdbpPrint(" Base Size Name\n");
1577 KdbpPrint(" %08x %08x %s\n", ntoskrnlBase, 0, "ntoskrnl.exe");
1578 return TRUE;
1579 }
1580
1581 i = 1;
1582 }
1583
1584 KdbpPrint(" Base Size Name\n");
1585 for (;;)
1586 {
1587 KdbpPrint(" %08x %08x %wZ\n", LdrEntry->DllBase, LdrEntry->SizeOfImage, &LdrEntry->BaseDllName);
1588
1589 if(DisplayOnlyOneModule || !KdbpSymFindModule(NULL, NULL, i++, &LdrEntry))
1590 break;
1591 }
1592
1593 return TRUE;
1594 }
1595
1596 /*!\brief Displays GDT, LDT or IDTd.
1597 */
1598 static BOOLEAN
1599 KdbpCmdGdtLdtIdt(
1600 ULONG Argc,
1601 PCHAR Argv[])
1602 {
1603 KDESCRIPTOR Reg;
1604 ULONG SegDesc[2];
1605 ULONG SegBase;
1606 ULONG SegLimit;
1607 PCHAR SegType;
1608 USHORT SegSel;
1609 UCHAR Type, Dpl;
1610 INT i;
1611 ULONG ul;
1612
1613 if (Argv[0][0] == 'i')
1614 {
1615 /* Read IDTR */
1616 __sidt(&Reg.Limit);
1617
1618 if (Reg.Limit < 7)
1619 {
1620 KdbpPrint("Interrupt descriptor table is empty.\n");
1621 return TRUE;
1622 }
1623
1624 KdbpPrint("IDT Base: 0x%08x Limit: 0x%04x\n", Reg.Base, Reg.Limit);
1625 KdbpPrint(" Idx Type Seg. Sel. Offset DPL\n");
1626
1627 for (i = 0; (i + sizeof(SegDesc) - 1) <= Reg.Limit; i += 8)
1628 {
1629 if (!NT_SUCCESS(KdbpSafeReadMemory(SegDesc, (PVOID)(Reg.Base + i), sizeof(SegDesc))))
1630 {
1631 KdbpPrint("Couldn't access memory at 0x%08x!\n", Reg.Base + i);
1632 return TRUE;
1633 }
1634
1635 Dpl = ((SegDesc[1] >> 13) & 3);
1636 if ((SegDesc[1] & 0x1f00) == 0x0500) /* Task gate */
1637 SegType = "TASKGATE";
1638 else if ((SegDesc[1] & 0x1fe0) == 0x0e00) /* 32 bit Interrupt gate */
1639 SegType = "INTGATE32";
1640 else if ((SegDesc[1] & 0x1fe0) == 0x0600) /* 16 bit Interrupt gate */
1641 SegType = "INTGATE16";
1642 else if ((SegDesc[1] & 0x1fe0) == 0x0f00) /* 32 bit Trap gate */
1643 SegType = "TRAPGATE32";
1644 else if ((SegDesc[1] & 0x1fe0) == 0x0700) /* 16 bit Trap gate */
1645 SegType = "TRAPGATE16";
1646 else
1647 SegType = "UNKNOWN";
1648
1649 if ((SegDesc[1] & (1 << 15)) == 0) /* not present */
1650 {
1651 KdbpPrint(" %03d %-10s [NP] [NP] %02d\n",
1652 i / 8, SegType, Dpl);
1653 }
1654 else if ((SegDesc[1] & 0x1f00) == 0x0500) /* Task gate */
1655 {
1656 SegSel = SegDesc[0] >> 16;
1657 KdbpPrint(" %03d %-10s 0x%04x %02d\n",
1658 i / 8, SegType, SegSel, Dpl);
1659 }
1660 else
1661 {
1662 SegSel = SegDesc[0] >> 16;
1663 SegBase = (SegDesc[1] & 0xffff0000) | (SegDesc[0] & 0x0000ffff);
1664 KdbpPrint(" %03d %-10s 0x%04x 0x%08x %02d\n",
1665 i / 8, SegType, SegSel, SegBase, Dpl);
1666 }
1667 }
1668 }
1669 else
1670 {
1671 ul = 0;
1672
1673 if (Argv[0][0] == 'g')
1674 {
1675 /* Read GDTR */
1676 Ke386GetGlobalDescriptorTable(&Reg.Limit);
1677 i = 8;
1678 }
1679 else
1680 {
1681 ASSERT(Argv[0][0] == 'l');
1682
1683 /* Read LDTR */
1684 Reg.Limit = Ke386GetLocalDescriptorTable();
1685 Reg.Base = 0;
1686 i = 0;
1687 ul = 1 << 2;
1688 }
1689
1690 if (Reg.Limit < 7)
1691 {
1692 KdbpPrint("%s descriptor table is empty.\n",
1693 Argv[0][0] == 'g' ? "Global" : "Local");
1694 return TRUE;
1695 }
1696
1697 KdbpPrint("%cDT Base: 0x%08x Limit: 0x%04x\n",
1698 Argv[0][0] == 'g' ? 'G' : 'L', Reg.Base, Reg.Limit);
1699 KdbpPrint(" Idx Sel. Type Base Limit DPL Attribs\n");
1700
1701 for (; (i + sizeof(SegDesc) - 1) <= Reg.Limit; i += 8)
1702 {
1703 if (!NT_SUCCESS(KdbpSafeReadMemory(SegDesc, (PVOID)(Reg.Base + i), sizeof(SegDesc))))
1704 {
1705 KdbpPrint("Couldn't access memory at 0x%08x!\n", Reg.Base + i);
1706 return TRUE;
1707 }
1708
1709 Dpl = ((SegDesc[1] >> 13) & 3);
1710 Type = ((SegDesc[1] >> 8) & 0xf);
1711
1712 SegBase = SegDesc[0] >> 16;
1713 SegBase |= (SegDesc[1] & 0xff) << 16;
1714 SegBase |= SegDesc[1] & 0xff000000;
1715 SegLimit = SegDesc[0] & 0x0000ffff;
1716 SegLimit |= (SegDesc[1] >> 16) & 0xf;
1717
1718 if ((SegDesc[1] & (1 << 23)) != 0)
1719 {
1720 SegLimit *= 4096;
1721 SegLimit += 4095;
1722 }
1723 else
1724 {
1725 SegLimit++;
1726 }
1727
1728 if ((SegDesc[1] & (1 << 12)) == 0) /* System segment */
1729 {
1730 switch (Type)
1731 {
1732 case 1: SegType = "TSS16(Avl)"; break;
1733 case 2: SegType = "LDT"; break;
1734 case 3: SegType = "TSS16(Busy)"; break;
1735 case 4: SegType = "CALLGATE16"; break;
1736 case 5: SegType = "TASKGATE"; break;
1737 case 6: SegType = "INTGATE16"; break;
1738 case 7: SegType = "TRAPGATE16"; break;
1739 case 9: SegType = "TSS32(Avl)"; break;
1740 case 11: SegType = "TSS32(Busy)"; break;
1741 case 12: SegType = "CALLGATE32"; break;
1742 case 14: SegType = "INTGATE32"; break;
1743 case 15: SegType = "INTGATE32"; break;
1744 default: SegType = "UNKNOWN"; break;
1745 }
1746
1747 if (!(Type >= 1 && Type <= 3) &&
1748 Type != 9 && Type != 11)
1749 {
1750 SegBase = 0;
1751 SegLimit = 0;
1752 }
1753 }
1754 else if ((SegDesc[1] & (1 << 11)) == 0) /* Data segment */
1755 {
1756 if ((SegDesc[1] & (1 << 22)) != 0)
1757 SegType = "DATA32";
1758 else
1759 SegType = "DATA16";
1760 }
1761 else /* Code segment */
1762 {
1763 if ((SegDesc[1] & (1 << 22)) != 0)
1764 SegType = "CODE32";
1765 else
1766 SegType = "CODE16";
1767 }
1768
1769 if ((SegDesc[1] & (1 << 15)) == 0) /* not present */
1770 {
1771 KdbpPrint(" %03d 0x%04x %-11s [NP] [NP] %02d NP\n",
1772 i / 8, i | Dpl | ul, SegType, Dpl);
1773 }
1774 else
1775 {
1776 KdbpPrint(" %03d 0x%04x %-11s 0x%08x 0x%08x %02d ",
1777 i / 8, i | Dpl | ul, SegType, SegBase, SegLimit, Dpl);
1778
1779 if ((SegDesc[1] & (1 << 12)) == 0) /* System segment */
1780 {
1781 /* FIXME: Display system segment */
1782 }
1783 else if ((SegDesc[1] & (1 << 11)) == 0) /* Data segment */
1784 {
1785 if ((SegDesc[1] & (1 << 10)) != 0) /* Expand-down */
1786 KdbpPrint(" E");
1787
1788 KdbpPrint((SegDesc[1] & (1 << 9)) ? " R/W" : " R");
1789
1790 if ((SegDesc[1] & (1 << 8)) != 0)
1791 KdbpPrint(" A");
1792 }
1793 else /* Code segment */
1794 {
1795 if ((SegDesc[1] & (1 << 10)) != 0) /* Conforming */
1796 KdbpPrint(" C");
1797
1798 KdbpPrint((SegDesc[1] & (1 << 9)) ? " R/X" : " X");
1799
1800 if ((SegDesc[1] & (1 << 8)) != 0)
1801 KdbpPrint(" A");
1802 }
1803
1804 if ((SegDesc[1] & (1 << 20)) != 0)
1805 KdbpPrint(" AVL");
1806
1807 KdbpPrint("\n");
1808 }
1809 }
1810 }
1811
1812 return TRUE;
1813 }
1814
1815 /*!\brief Displays the KPCR
1816 */
1817 static BOOLEAN
1818 KdbpCmdPcr(
1819 ULONG Argc,
1820 PCHAR Argv[])
1821 {
1822 PKIPCR Pcr = (PKIPCR)KeGetPcr();
1823
1824 KdbpPrint("Current PCR is at 0x%08x.\n", (INT)Pcr);
1825 KdbpPrint(" Tib.ExceptionList: 0x%08x\n"
1826 " Tib.StackBase: 0x%08x\n"
1827 " Tib.StackLimit: 0x%08x\n"
1828 " Tib.SubSystemTib: 0x%08x\n"
1829 " Tib.FiberData/Version: 0x%08x\n"
1830 " Tib.ArbitraryUserPointer: 0x%08x\n"
1831 " Tib.Self: 0x%08x\n"
1832 " Self: 0x%08x\n"
1833 " PCRCB: 0x%08x\n"
1834 " Irql: 0x%02x\n"
1835 " IRR: 0x%08x\n"
1836 " IrrActive: 0x%08x\n"
1837 " IDR: 0x%08x\n"
1838 " KdVersionBlock: 0x%08x\n"
1839 " IDT: 0x%08x\n"
1840 " GDT: 0x%08x\n"
1841 " TSS: 0x%08x\n"
1842 " MajorVersion: 0x%04x\n"
1843 " MinorVersion: 0x%04x\n"
1844 " SetMember: 0x%08x\n"
1845 " StallScaleFactor: 0x%08x\n"
1846 " Number: 0x%02x\n"
1847 " L2CacheAssociativity: 0x%02x\n"
1848 " VdmAlert: 0x%08x\n"
1849 " L2CacheSize: 0x%08x\n"
1850 " InterruptMode: 0x%08x\n",
1851 Pcr->NtTib.ExceptionList, Pcr->NtTib.StackBase, Pcr->NtTib.StackLimit,
1852 Pcr->NtTib.SubSystemTib, Pcr->NtTib.FiberData, Pcr->NtTib.ArbitraryUserPointer,
1853 Pcr->NtTib.Self, Pcr->Self, Pcr->Prcb, Pcr->Irql, Pcr->IRR, Pcr->IrrActive,
1854 Pcr->IDR, Pcr->KdVersionBlock, Pcr->IDT, Pcr->GDT, Pcr->TSS,
1855 Pcr->MajorVersion, Pcr->MinorVersion, Pcr->SetMember, Pcr->StallScaleFactor,
1856 Pcr->Number, Pcr->SecondLevelCacheAssociativity,
1857 Pcr->VdmAlert, Pcr->SecondLevelCacheSize, Pcr->InterruptMode);
1858
1859 return TRUE;
1860 }
1861
1862 /*!\brief Displays the TSS
1863 */
1864 static BOOLEAN
1865 KdbpCmdTss(
1866 ULONG Argc,
1867 PCHAR Argv[])
1868 {
1869 KTSS *Tss = KeGetPcr()->TSS;
1870
1871 KdbpPrint("Current TSS is at 0x%08x.\n", (INT)Tss);
1872 KdbpPrint(" Eip: 0x%08x\n"
1873 " Es: 0x%04x\n"
1874 " Cs: 0x%04x\n"
1875 " Ss: 0x%04x\n"
1876 " Ds: 0x%04x\n"
1877 " Fs: 0x%04x\n"
1878 " Gs: 0x%04x\n"
1879 " IoMapBase: 0x%04x\n",
1880 Tss->Eip, Tss->Es, Tss->Cs, Tss->Ds, Tss->Fs, Tss->Gs, Tss->IoMapBase);
1881
1882 return TRUE;
1883 }
1884
1885 /*!\brief Bugchecks the system.
1886 */
1887 static BOOLEAN
1888 KdbpCmdBugCheck(
1889 ULONG Argc,
1890 PCHAR Argv[])
1891 {
1892 /* Set the flag and quit looping */
1893 KdbpBugCheckRequested = TRUE;
1894
1895 return FALSE;
1896 }
1897
1898 /*!\brief Sets or displays a config variables value.
1899 */
1900 static BOOLEAN
1901 KdbpCmdSet(
1902 ULONG Argc,
1903 PCHAR Argv[])
1904 {
1905 LONG l;
1906 BOOLEAN First;
1907 PCHAR pend = 0;
1908 KDB_ENTER_CONDITION ConditionFirst = KdbDoNotEnter;
1909 KDB_ENTER_CONDITION ConditionLast = KdbDoNotEnter;
1910
1911 static const PCHAR ExceptionNames[21] =
1912 {
1913 "ZERODEVIDE", "DEBUGTRAP", "NMI", "INT3", "OVERFLOW", "BOUND", "INVALIDOP",
1914 "NOMATHCOP", "DOUBLEFAULT", "RESERVED(9)", "INVALIDTSS", "SEGMENTNOTPRESENT",
1915 "STACKFAULT", "GPF", "PAGEFAULT", "RESERVED(15)", "MATHFAULT", "ALIGNMENTCHECK",
1916 "MACHINECHECK", "SIMDFAULT", "OTHERS"
1917 };
1918
1919 if (Argc == 1)
1920 {
1921 KdbpPrint("Available settings:\n");
1922 KdbpPrint(" syntax [intel|at&t]\n");
1923 KdbpPrint(" condition [exception|*] [first|last] [never|always|kmode|umode]\n");
1924 KdbpPrint(" break_on_module_load [true|false]\n");
1925 }
1926 else if (strcmp(Argv[1], "syntax") == 0)
1927 {
1928 if (Argc == 2)
1929 {
1930 KdbpPrint("syntax = %s\n", KdbUseIntelSyntax ? "intel" : "at&t");
1931 }
1932 else if (Argc >= 3)
1933 {
1934 if (_stricmp(Argv[2], "intel") == 0)
1935 KdbUseIntelSyntax = TRUE;
1936 else if (_stricmp(Argv[2], "at&t") == 0)
1937 KdbUseIntelSyntax = FALSE;
1938 else
1939 KdbpPrint("Unknown syntax '%s'.\n", Argv[2]);
1940 }
1941 }
1942 else if (strcmp(Argv[1], "condition") == 0)
1943 {
1944 if (Argc == 2)
1945 {
1946 KdbpPrint("Conditions: (First) (Last)\n");
1947 for (l = 0; l < RTL_NUMBER_OF(ExceptionNames) - 1; l++)
1948 {
1949 if (!ExceptionNames[l])
1950 continue;
1951
1952 if (!KdbpGetEnterCondition(l, TRUE, &ConditionFirst))
1953 ASSERT(0);
1954
1955 if (!KdbpGetEnterCondition(l, FALSE, &ConditionLast))
1956 ASSERT(0);
1957
1958 KdbpPrint(" #%02d %-20s %-8s %-8s\n", l, ExceptionNames[l],
1959 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst),
1960 KDB_ENTER_CONDITION_TO_STRING(ConditionLast));
1961 }
1962
1963 ASSERT(l == (RTL_NUMBER_OF(ExceptionNames) - 1));
1964 KdbpPrint(" %-20s %-8s %-8s\n", ExceptionNames[l],
1965 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst),
1966 KDB_ENTER_CONDITION_TO_STRING(ConditionLast));
1967 }
1968 else
1969 {
1970 if (Argc >= 5 && strcmp(Argv[2], "*") == 0) /* Allow * only when setting condition */
1971 {
1972 l = -1;
1973 }
1974 else
1975 {
1976 l = strtoul(Argv[2], &pend, 0);
1977
1978 if (Argv[2] == pend)
1979 {
1980 for (l = 0; l < RTL_NUMBER_OF(ExceptionNames); l++)
1981 {
1982 if (!ExceptionNames[l])
1983 continue;
1984
1985 if (_stricmp(ExceptionNames[l], Argv[2]) == 0)
1986 break;
1987 }
1988 }
1989
1990 if (l >= RTL_NUMBER_OF(ExceptionNames))
1991 {
1992 KdbpPrint("Unknown exception '%s'.\n", Argv[2]);
1993 return TRUE;
1994 }
1995 }
1996
1997 if (Argc > 4)
1998 {
1999 if (_stricmp(Argv[3], "first") == 0)
2000 First = TRUE;
2001 else if (_stricmp(Argv[3], "last") == 0)
2002 First = FALSE;
2003 else
2004 {
2005 KdbpPrint("set condition: second argument must be 'first' or 'last'\n");
2006 return TRUE;
2007 }
2008
2009 if (_stricmp(Argv[4], "never") == 0)
2010 ConditionFirst = KdbDoNotEnter;
2011 else if (_stricmp(Argv[4], "always") == 0)
2012 ConditionFirst = KdbEnterAlways;
2013 else if (_stricmp(Argv[4], "umode") == 0)
2014 ConditionFirst = KdbEnterFromUmode;
2015 else if (_stricmp(Argv[4], "kmode") == 0)
2016 ConditionFirst = KdbEnterFromKmode;
2017 else
2018 {
2019 KdbpPrint("set condition: third argument must be 'never', 'always', 'umode' or 'kmode'\n");
2020 return TRUE;
2021 }
2022
2023 if (!KdbpSetEnterCondition(l, First, ConditionFirst))
2024 {
2025 if (l >= 0)
2026 KdbpPrint("Couldn't change condition for exception #%02d\n", l);
2027 else
2028 KdbpPrint("Couldn't change condition for all exceptions\n", l);
2029 }
2030 }
2031 else /* Argc >= 3 */
2032 {
2033 if (!KdbpGetEnterCondition(l, TRUE, &ConditionFirst))
2034 ASSERT(0);
2035
2036 if (!KdbpGetEnterCondition(l, FALSE, &ConditionLast))
2037 ASSERT(0);
2038
2039 if (l < (RTL_NUMBER_OF(ExceptionNames) - 1))
2040 {
2041 KdbpPrint("Condition for exception #%02d (%s): FirstChance %s LastChance %s\n",
2042 l, ExceptionNames[l],
2043 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst),
2044 KDB_ENTER_CONDITION_TO_STRING(ConditionLast));
2045 }
2046 else
2047 {
2048 KdbpPrint("Condition for all other exceptions: FirstChance %s LastChance %s\n",
2049 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst),
2050 KDB_ENTER_CONDITION_TO_STRING(ConditionLast));
2051 }
2052 }
2053 }
2054 }
2055 else if (strcmp(Argv[1], "break_on_module_load") == 0)
2056 {
2057 if (Argc == 2)
2058 KdbpPrint("break_on_module_load = %s\n", KdbBreakOnModuleLoad ? "enabled" : "disabled");
2059 else if (Argc >= 3)
2060 {
2061 if (_stricmp(Argv[2], "enable") == 0 || _stricmp(Argv[2], "enabled") == 0 || _stricmp(Argv[2], "true") == 0)
2062 KdbBreakOnModuleLoad = TRUE;
2063 else if (_stricmp(Argv[2], "disable") == 0 || _stricmp(Argv[2], "disabled") == 0 || _stricmp(Argv[2], "false") == 0)
2064 KdbBreakOnModuleLoad = FALSE;
2065 else
2066 KdbpPrint("Unknown setting '%s'.\n", Argv[2]);
2067 }
2068 }
2069 else
2070 {
2071 KdbpPrint("Unknown setting '%s'.\n", Argv[1]);
2072 }
2073
2074 return TRUE;
2075 }
2076
2077 /*!\brief Displays help screen.
2078 */
2079 static BOOLEAN
2080 KdbpCmdHelp(
2081 ULONG Argc,
2082 PCHAR Argv[])
2083 {
2084 ULONG i;
2085
2086 KdbpPrint("Kernel debugger commands:\n");
2087 for (i = 0; i < RTL_NUMBER_OF(KdbDebuggerCommands); i++)
2088 {
2089 if (!KdbDebuggerCommands[i].Syntax) /* Command group */
2090 {
2091 if (i > 0)
2092 KdbpPrint("\n");
2093
2094 KdbpPrint("\x1b[7m* %s:\x1b[0m\n", KdbDebuggerCommands[i].Help);
2095 continue;
2096 }
2097
2098 KdbpPrint(" %-20s - %s\n",
2099 KdbDebuggerCommands[i].Syntax,
2100 KdbDebuggerCommands[i].Help);
2101 }
2102
2103 return TRUE;
2104 }
2105
2106 /*!\brief Prints the given string with printf-like formatting.
2107 *
2108 * \param Format Format of the string/arguments.
2109 * \param ... Variable number of arguments matching the format specified in \a Format.
2110 *
2111 * \note Doesn't correctly handle \\t and terminal escape sequences when calculating the
2112 * number of lines required to print a single line from the Buffer in the terminal.
2113 */
2114 VOID
2115 KdbpPrint(
2116 IN PCHAR Format,
2117 IN ... OPTIONAL)
2118 {
2119 static CHAR Buffer[4096];
2120 static BOOLEAN TerminalInitialized = FALSE;
2121 static BOOLEAN TerminalConnected = FALSE;
2122 static BOOLEAN TerminalReportsSize = TRUE;
2123 CHAR c = '\0';
2124 PCHAR p, p2;
2125 ULONG Length;
2126 ULONG i, j;
2127 LONG RowsPrintedByTerminal;
2128 ULONG ScanCode;
2129 va_list ap;
2130
2131 /* Check if the user has aborted output of the current command */
2132 if (KdbOutputAborted)
2133 return;
2134
2135 /* Initialize the terminal */
2136 if (!TerminalInitialized)
2137 {
2138 DbgPrint("\x1b[7h"); /* Enable linewrap */
2139
2140 /* Query terminal type */
2141 /*DbgPrint("\x1b[Z");*/
2142 DbgPrint("\x05");
2143
2144 TerminalInitialized = TRUE;
2145 Length = 0;
2146 KeStallExecutionProcessor(100000);
2147
2148 for (;;)
2149 {
2150 c = KdbpTryGetCharSerial(5000);
2151 if (c == -1)
2152 break;
2153
2154 Buffer[Length++] = c;
2155 if (Length >= (sizeof (Buffer) - 1))
2156 break;
2157 }
2158
2159 Buffer[Length] = '\0';
2160 if (Length > 0)
2161 TerminalConnected = TRUE;
2162 }
2163
2164 /* Get number of rows and columns in terminal */
2165 if ((KdbNumberOfRowsTerminal < 0) || (KdbNumberOfColsTerminal < 0) ||
2166 (KdbNumberOfRowsPrinted) == 0) /* Refresh terminal size each time when number of rows printed is 0 */
2167 {
2168 if ((KdbDebugState & KD_DEBUG_KDSERIAL) && TerminalConnected && TerminalReportsSize)
2169 {
2170 /* Try to query number of rows from terminal. A reply looks like "\x1b[8;24;80t" */
2171 TerminalReportsSize = FALSE;
2172 KeStallExecutionProcessor(100000);
2173 DbgPrint("\x1b[18t");
2174 c = KdbpTryGetCharSerial(5000);
2175
2176 if (c == KEY_ESC)
2177 {
2178 c = KdbpTryGetCharSerial(5000);
2179 if (c == '[')
2180 {
2181 Length = 0;
2182
2183 for (;;)
2184 {
2185 c = KdbpTryGetCharSerial(5000);
2186 if (c == -1)
2187 break;
2188
2189 Buffer[Length++] = c;
2190 if (isalpha(c) || Length >= (sizeof (Buffer) - 1))
2191 break;
2192 }
2193
2194 Buffer[Length] = '\0';
2195 if (Buffer[0] == '8' && Buffer[1] == ';')
2196 {
2197 for (i = 2; (i < Length) && (Buffer[i] != ';'); i++);
2198
2199 if (Buffer[i] == ';')
2200 {
2201 Buffer[i++] = '\0';
2202
2203 /* Number of rows is now at Buffer + 2 and number of cols at Buffer + i */
2204 KdbNumberOfRowsTerminal = strtoul(Buffer + 2, NULL, 0);
2205 KdbNumberOfColsTerminal = strtoul(Buffer + i, NULL, 0);
2206 TerminalReportsSize = TRUE;
2207 }
2208 }
2209 }
2210 /* Clear further characters */
2211 while ((c = KdbpTryGetCharSerial(5000)) != -1);
2212 }
2213 }
2214
2215 if (KdbNumberOfRowsTerminal <= 0)
2216 {
2217 /* Set number of rows to the default. */
2218 KdbNumberOfRowsTerminal = 24;
2219 }
2220 else if (KdbNumberOfColsTerminal <= 0)
2221 {
2222 /* Set number of cols to the default. */
2223 KdbNumberOfColsTerminal = 80;
2224 }
2225 }
2226
2227 /* Get the string */
2228 va_start(ap, Format);
2229 Length = _vsnprintf(Buffer, sizeof (Buffer) - 1, Format, ap);
2230 Buffer[Length] = '\0';
2231 va_end(ap);
2232
2233 p = Buffer;
2234 while (p[0] != '\0')
2235 {
2236 i = strcspn(p, "\n");
2237
2238 /* Calculate the number of lines which will be printed in the terminal
2239 * when outputting the current line
2240 */
2241 if (i > 0)
2242 RowsPrintedByTerminal = (i + KdbNumberOfColsPrinted - 1) / KdbNumberOfColsTerminal;
2243 else
2244 RowsPrintedByTerminal = 0;
2245
2246 if (p[i] == '\n')
2247 RowsPrintedByTerminal++;
2248
2249 /*DbgPrint("!%d!%d!%d!%d!", KdbNumberOfRowsPrinted, KdbNumberOfColsPrinted, i, RowsPrintedByTerminal);*/
2250
2251 /* Display a prompt if we printed one screen full of text */
2252 if (KdbNumberOfRowsTerminal > 0 &&
2253 (LONG)(KdbNumberOfRowsPrinted + RowsPrintedByTerminal) >= KdbNumberOfRowsTerminal)
2254 {
2255 if (KdbNumberOfColsPrinted > 0)
2256 DbgPrint("\n");
2257
2258 DbgPrint("--- Press q to abort, any other key to continue ---");
2259
2260 if (KdbDebugState & KD_DEBUG_KDSERIAL)
2261 c = KdbpGetCharSerial();
2262 else
2263 c = KdbpGetCharKeyboard(&ScanCode);
2264
2265 if (c == '\r')
2266 {
2267 /* Try to read '\n' which might follow '\r' - if \n is not received here
2268 * it will be interpreted as "return" when the next command should be read.
2269 */
2270 if (KdbDebugState & KD_DEBUG_KDSERIAL)
2271 c = KdbpTryGetCharSerial(5);
2272 else
2273 c = KdbpTryGetCharKeyboard(&ScanCode, 5);
2274 }
2275
2276 DbgPrint("\n");
2277 if (c == 'q')
2278 {
2279 KdbOutputAborted = TRUE;
2280 return;
2281 }
2282
2283 KdbNumberOfRowsPrinted = 0;
2284 KdbNumberOfColsPrinted = 0;
2285 }
2286
2287 /* Insert a NUL after the line and print only the current line. */
2288 if (p[i] == '\n' && p[i + 1] != '\0')
2289 {
2290 c = p[i + 1];
2291 p[i + 1] = '\0';
2292 }
2293 else
2294 {
2295 c = '\0';
2296 }
2297
2298 /* Remove escape sequences from the line if there's no terminal connected */
2299 if (!TerminalConnected)
2300 {
2301 while ((p2 = strrchr(p, '\x1b'))) /* Look for escape character */
2302 {
2303 if (p2[1] == '[')
2304 {
2305 j = 2;
2306 while (!isalpha(p2[j++]));
2307 strcpy(p2, p2 + j);
2308 }
2309 else
2310 {
2311 strcpy(p2, p2 + 1);
2312 }
2313 }
2314 }
2315
2316 DbgPrint("%s", p);
2317
2318 if (c != '\0')
2319 p[i + 1] = c;
2320
2321 /* Set p to the start of the next line and
2322 * remember the number of rows/cols printed
2323 */
2324 p += i;
2325 if (p[0] == '\n')
2326 {
2327 p++;
2328 KdbNumberOfColsPrinted = 0;
2329 }
2330 else
2331 {
2332 ASSERT(p[0] == '\0');
2333 KdbNumberOfColsPrinted += i;
2334 }
2335
2336 KdbNumberOfRowsPrinted += RowsPrintedByTerminal;
2337 }
2338 }
2339
2340 /*!\brief Appends a command to the command history
2341 *
2342 * \param Command Pointer to the command to append to the history.
2343 */
2344 static VOID
2345 KdbpCommandHistoryAppend(
2346 IN PCHAR Command)
2347 {
2348 ULONG Length1 = strlen(Command) + 1;
2349 ULONG Length2 = 0;
2350 INT i;
2351 PCHAR Buffer;
2352
2353 ASSERT(Length1 <= RTL_NUMBER_OF(KdbCommandHistoryBuffer));
2354
2355 if (Length1 <= 1 ||
2356 (KdbCommandHistory[KdbCommandHistoryIndex] &&
2357 strcmp(KdbCommandHistory[KdbCommandHistoryIndex], Command) == 0))
2358 {
2359 return;
2360 }
2361
2362 /* Calculate Length1 and Length2 */
2363 Buffer = KdbCommandHistoryBuffer + KdbCommandHistoryBufferIndex;
2364 KdbCommandHistoryBufferIndex += Length1;
2365 if (KdbCommandHistoryBufferIndex >= (LONG)RTL_NUMBER_OF(KdbCommandHistoryBuffer))
2366 {
2367 KdbCommandHistoryBufferIndex -= RTL_NUMBER_OF(KdbCommandHistoryBuffer);
2368 Length2 = KdbCommandHistoryBufferIndex;
2369 Length1 -= Length2;
2370 }
2371
2372 /* Remove previous commands until there is enough space to append the new command */
2373 for (i = KdbCommandHistoryIndex; KdbCommandHistory[i];)
2374 {
2375 if ((Length2 > 0 &&
2376 (KdbCommandHistory[i] >= Buffer ||
2377 KdbCommandHistory[i] < (KdbCommandHistoryBuffer + KdbCommandHistoryBufferIndex))) ||
2378 (Length2 <= 0 &&
2379 (KdbCommandHistory[i] >= Buffer &&
2380 KdbCommandHistory[i] < (KdbCommandHistoryBuffer + KdbCommandHistoryBufferIndex))))
2381 {
2382 KdbCommandHistory[i] = NULL;
2383 }
2384
2385 i--;
2386 if (i < 0)
2387 i = RTL_NUMBER_OF(KdbCommandHistory) - 1;
2388
2389 if (i == KdbCommandHistoryIndex)
2390 break;
2391 }
2392
2393 /* Make sure the new command history entry is free */
2394 KdbCommandHistoryIndex++;
2395 KdbCommandHistoryIndex %= RTL_NUMBER_OF(KdbCommandHistory);
2396 if (KdbCommandHistory[KdbCommandHistoryIndex])
2397 {
2398 KdbCommandHistory[KdbCommandHistoryIndex] = NULL;
2399 }
2400
2401 /* Append command */
2402 KdbCommandHistory[KdbCommandHistoryIndex] = Buffer;
2403 ASSERT((KdbCommandHistory[KdbCommandHistoryIndex] + Length1) <= KdbCommandHistoryBuffer + RTL_NUMBER_OF(KdbCommandHistoryBuffer));
2404 memcpy(KdbCommandHistory[KdbCommandHistoryIndex], Command, Length1);
2405 if (Length2 > 0)
2406 {
2407 memcpy(KdbCommandHistoryBuffer, Command + Length1, Length2);
2408 }
2409 }
2410
2411 /*!\brief Reads a line of user-input.
2412 *
2413 * \param Buffer Buffer to store the input into. Trailing newlines are removed.
2414 * \param Size Size of \a Buffer.
2415 *
2416 * \note Accepts only \n newlines, \r is ignored.
2417 */
2418 static VOID
2419 KdbpReadCommand(
2420 OUT PCHAR Buffer,
2421 IN ULONG Size)
2422 {
2423 CHAR Key;
2424 PCHAR Orig = Buffer;
2425 ULONG ScanCode = 0;
2426 BOOLEAN EchoOn;
2427 static CHAR LastCommand[1024] = "";
2428 static CHAR NextKey = '\0';
2429 INT CmdHistIndex = -1;
2430 INT i;
2431
2432 EchoOn = !((KdbDebugState & KD_DEBUG_KDNOECHO) != 0);
2433
2434 for (;;)
2435 {
2436 if (KdbDebugState & KD_DEBUG_KDSERIAL)
2437 {
2438 Key = (NextKey == '\0') ? KdbpGetCharSerial() : NextKey;
2439 NextKey = '\0';
2440 ScanCode = 0;
2441 if (Key == KEY_ESC) /* ESC */
2442 {
2443 Key = KdbpGetCharSerial();
2444 if (Key == '[')
2445 {
2446 Key = KdbpGetCharSerial();
2447
2448 switch (Key)
2449 {
2450 case 'A':
2451 ScanCode = KEY_SCAN_UP;
2452 break;
2453 case 'B':
2454 ScanCode = KEY_SCAN_DOWN;
2455 break;
2456 case 'C':
2457 break;
2458 case 'D':
2459 break;
2460 }
2461 }
2462 }
2463 }
2464 else
2465 {
2466 ScanCode = 0;
2467 Key = (NextKey == '\0') ? KdbpGetCharKeyboard(&ScanCode) : NextKey;
2468 NextKey = '\0';
2469 }
2470
2471 if ((ULONG)(Buffer - Orig) >= (Size - 1))
2472 {
2473 /* Buffer is full, accept only newlines */
2474 if (Key != '\n')
2475 continue;
2476 }
2477
2478 if (Key == '\r')
2479 {
2480 /* Read the next char - this is to throw away a \n which most clients should
2481 * send after \r.
2482 */
2483 KeStallExecutionProcessor(100000);
2484
2485 if (KdbDebugState & KD_DEBUG_KDSERIAL)
2486 NextKey = KdbpTryGetCharSerial(5);
2487 else
2488 NextKey = KdbpTryGetCharKeyboard(&ScanCode, 5);
2489
2490 if (NextKey == '\n' || NextKey == -1) /* \n or no response at all */
2491 NextKey = '\0';
2492
2493 KdbpPrint("\n");
2494
2495 /*
2496 * Repeat the last command if the user presses enter. Reduces the
2497 * risk of RSI when single-stepping.
2498 */
2499 if (Buffer == Orig)
2500 {
2501 RtlStringCbCopyA(Buffer, Size, LastCommand);
2502 }
2503 else
2504 {
2505 *Buffer = '\0';
2506 RtlStringCbCopyA(LastCommand, sizeof(LastCommand), Orig);
2507 }
2508
2509 return;
2510 }
2511 else if (Key == KEY_BS || Key == KEY_DEL)
2512 {
2513 if (Buffer > Orig)
2514 {
2515 Buffer--;
2516 *Buffer = 0;
2517
2518 if (EchoOn)
2519 KdbpPrint("%c %c", KEY_BS, KEY_BS);
2520 else
2521 KdbpPrint(" %c", KEY_BS);
2522 }
2523 }
2524 else if (ScanCode == KEY_SCAN_UP)
2525 {
2526 BOOLEAN Print = TRUE;
2527
2528 if (CmdHistIndex < 0)
2529 {
2530 CmdHistIndex = KdbCommandHistoryIndex;
2531 }
2532 else
2533 {
2534 i = CmdHistIndex - 1;
2535
2536 if (i < 0)
2537 CmdHistIndex = RTL_NUMBER_OF(KdbCommandHistory) - 1;
2538
2539 if (KdbCommandHistory[i] && i != KdbCommandHistoryIndex)
2540 CmdHistIndex = i;
2541 else
2542 Print = FALSE;
2543 }
2544
2545 if (Print && KdbCommandHistory[CmdHistIndex])
2546 {
2547 while (Buffer > Orig)
2548 {
2549 Buffer--;
2550 *Buffer = 0;
2551
2552 if (EchoOn)
2553 KdbpPrint("%c %c", KEY_BS, KEY_BS);
2554 else
2555 KdbpPrint(" %c", KEY_BS);
2556 }
2557
2558 i = min(strlen(KdbCommandHistory[CmdHistIndex]), Size - 1);
2559 memcpy(Orig, KdbCommandHistory[CmdHistIndex], i);
2560 Orig[i] = '\0';
2561 Buffer = Orig + i;
2562 KdbpPrint("%s", Orig);
2563 }
2564 }
2565 else if (ScanCode == KEY_SCAN_DOWN)
2566 {
2567 if (CmdHistIndex > 0 && CmdHistIndex != KdbCommandHistoryIndex)
2568 {
2569 i = CmdHistIndex + 1;
2570 if (i >= (INT)RTL_NUMBER_OF(KdbCommandHistory))
2571 i = 0;
2572
2573 if (KdbCommandHistory[i])
2574 {
2575 CmdHistIndex = i;
2576 while (Buffer > Orig)
2577 {
2578 Buffer--;
2579 *Buffer = 0;
2580
2581 if (EchoOn)
2582 KdbpPrint("%c %c", KEY_BS, KEY_BS);
2583 else
2584 KdbpPrint(" %c", KEY_BS);
2585 }
2586
2587 i = min(strlen(KdbCommandHistory[CmdHistIndex]), Size - 1);
2588 memcpy(Orig, KdbCommandHistory[CmdHistIndex], i);
2589 Orig[i] = '\0';
2590 Buffer = Orig + i;
2591 KdbpPrint("%s", Orig);
2592 }
2593 }
2594 }
2595 else
2596 {
2597 if (EchoOn)
2598 KdbpPrint("%c", Key);
2599
2600 *Buffer = Key;
2601 Buffer++;
2602 }
2603 }
2604 }
2605
2606 /*!\brief Parses command line and executes command if found
2607 *
2608 * \param Command Command line to parse and execute if possible.
2609 *
2610 * \retval TRUE Don't continue execution.
2611 * \retval FALSE Continue execution (leave KDB)
2612 */
2613 static BOOLEAN
2614 KdbpDoCommand(
2615 IN PCHAR Command)
2616 {
2617 ULONG i;
2618 PCHAR p;
2619 ULONG Argc;
2620 static PCH Argv[256];
2621 static CHAR OrigCommand[1024];
2622
2623 RtlStringCbCopyA(OrigCommand, sizeof(OrigCommand), Command);
2624
2625 Argc = 0;
2626 p = Command;
2627
2628 for (;;)
2629 {
2630 while (*p == '\t' || *p == ' ')
2631 p++;
2632
2633 if (*p == '\0')
2634 break;
2635
2636 i = strcspn(p, "\t ");
2637 Argv[Argc++] = p;
2638 p += i;
2639 if (*p == '\0')
2640 break;
2641
2642 *p = '\0';
2643 p++;
2644 }
2645
2646 if (Argc < 1)
2647 return TRUE;
2648
2649 for (i = 0; i < RTL_NUMBER_OF(KdbDebuggerCommands); i++)
2650 {
2651 if (!KdbDebuggerCommands[i].Name)
2652 continue;
2653
2654 if (strcmp(KdbDebuggerCommands[i].Name, Argv[0]) == 0)
2655 {
2656 return KdbDebuggerCommands[i].Fn(Argc, Argv);
2657 }
2658 }
2659
2660 KdbpPrint("Command '%s' is unknown.\n", OrigCommand);
2661 return TRUE;
2662 }
2663
2664 /*!\brief KDB Main Loop.
2665 *
2666 * \param EnteredOnSingleStep TRUE if KDB was entered on single step.
2667 */
2668 VOID
2669 KdbpCliMainLoop(
2670 IN BOOLEAN EnteredOnSingleStep)
2671 {
2672 static CHAR Command[1024];
2673 BOOLEAN Continue;
2674
2675 if (EnteredOnSingleStep)
2676 {
2677 if (!KdbSymPrintAddress((PVOID)KdbCurrentTrapFrame->Tf.Eip, &KdbCurrentTrapFrame->Tf))
2678 {
2679 KdbpPrint("<%x>", KdbCurrentTrapFrame->Tf.Eip);
2680 }
2681
2682 KdbpPrint(": ");
2683 if (KdbpDisassemble(KdbCurrentTrapFrame->Tf.Eip, KdbUseIntelSyntax) < 0)
2684 {
2685 KdbpPrint("<INVALID>");
2686 }
2687 KdbpPrint("\n");
2688 }
2689
2690 /* Flush the input buffer */
2691 if (KdbDebugState & KD_DEBUG_KDSERIAL)
2692 {
2693 while (KdbpTryGetCharSerial(1) != -1);
2694 }
2695 else
2696 {
2697 ULONG ScanCode;
2698 while (KdbpTryGetCharKeyboard(&ScanCode, 1) != -1);
2699 }
2700
2701 /* Main loop */
2702 do
2703 {
2704 /* Print the prompt */
2705 KdbpPrint("kdb:> ");
2706
2707 /* Read a command and remember it */
2708 KdbpReadCommand(Command, sizeof (Command));
2709 KdbpCommandHistoryAppend(Command);
2710
2711 /* Reset the number of rows/cols printed and output aborted state */
2712 KdbNumberOfRowsPrinted = KdbNumberOfColsPrinted = 0;
2713 KdbOutputAborted = FALSE;
2714
2715 /* Call the command */
2716 Continue = KdbpDoCommand(Command);
2717 KdbOutputAborted = FALSE;
2718 }
2719 while (Continue);
2720 }
2721
2722 /*!\brief Called when a module is loaded.
2723 *
2724 * \param Name Filename of the module which was loaded.
2725 */
2726 VOID
2727 KdbpCliModuleLoaded(
2728 IN PUNICODE_STRING Name)
2729 {
2730 if (!KdbBreakOnModuleLoad)
2731 return;
2732
2733 KdbpPrint("Module %wZ loaded.\n", Name);
2734 DbgBreakPointWithStatus(DBG_STATUS_CONTROL_C);
2735 }
2736
2737 /*!\brief This function is called by KdbEnterDebuggerException...
2738 *
2739 * Used to interpret the init file in a context with a trapframe setup
2740 * (KdbpCliInit call KdbEnter which will call KdbEnterDebuggerException which will
2741 * call this function if KdbInitFileBuffer is not NULL.
2742 */
2743 VOID
2744 KdbpCliInterpretInitFile()
2745 {
2746 PCHAR p1, p2;
2747 INT i;
2748 CHAR c;
2749
2750 /* Execute the commands in the init file */
2751 DPRINT("KDB: Executing KDBinit file...\n");
2752 p1 = KdbInitFileBuffer;
2753 while (p1[0] != '\0')
2754 {
2755 i = strcspn(p1, "\r\n");
2756 if (i > 0)
2757 {
2758 c = p1[i];
2759 p1[i] = '\0';
2760
2761 /* Look for "break" command and comments */
2762 p2 = p1;
2763
2764 while (isspace(p2[0]))
2765 p2++;
2766
2767 if (strncmp(p2, "break", sizeof("break")-1) == 0 &&
2768 (p2[sizeof("break")-1] == '\0' || isspace(p2[sizeof("break")-1])))
2769 {
2770 /* break into the debugger */
2771 KdbpCliMainLoop(FALSE);
2772 }
2773 else if (p2[0] != '#' && p2[0] != '\0') /* Ignore empty lines and comments */
2774 {
2775 KdbpDoCommand(p1);
2776 }
2777
2778 p1[i] = c;
2779 }
2780
2781 p1 += i;
2782 while (p1[0] == '\r' || p1[0] == '\n')
2783 p1++;
2784 }
2785 DPRINT("KDB: KDBinit executed\n");
2786 }
2787
2788 /*!\brief Called when KDB is initialized
2789 *
2790 * Reads the KDBinit file from the SystemRoot\system32\drivers\etc directory and executes it.
2791 */
2792 VOID
2793 KdbpCliInit()
2794 {
2795 NTSTATUS Status;
2796 OBJECT_ATTRIBUTES ObjectAttributes;
2797 UNICODE_STRING FileName;
2798 IO_STATUS_BLOCK Iosb;
2799 FILE_STANDARD_INFORMATION FileStdInfo;
2800 HANDLE hFile = NULL;
2801 INT FileSize;
2802 PCHAR FileBuffer;
2803 ULONG OldEflags;
2804
2805 /* Initialize the object attributes */
2806 RtlInitUnicodeString(&FileName, L"\\SystemRoot\\system32\\drivers\\etc\\KDBinit");
2807 InitializeObjectAttributes(&ObjectAttributes, &FileName, 0, NULL, NULL);
2808
2809 /* Open the file */
2810 Status = ZwOpenFile(&hFile, FILE_READ_DATA, &ObjectAttributes, &Iosb, 0,
2811 FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT |
2812 FILE_NO_INTERMEDIATE_BUFFERING);
2813 if (!NT_SUCCESS(Status))
2814 {
2815 DPRINT("Could not open \\SystemRoot\\system32\\drivers\\etc\\KDBinit (Status 0x%x)", Status);
2816 return;
2817 }
2818
2819 /* Get the size of the file */
2820 Status = ZwQueryInformationFile(hFile, &Iosb, &FileStdInfo, sizeof (FileStdInfo),
2821 FileStandardInformation);
2822 if (!NT_SUCCESS(Status))
2823 {
2824 ZwClose(hFile);
2825 DPRINT("Could not query size of \\SystemRoot\\system32\\drivers\\etc\\KDBinit (Status 0x%x)", Status);
2826 return;
2827 }
2828 FileSize = FileStdInfo.EndOfFile.u.LowPart;
2829
2830 /* Allocate memory for the file */
2831 FileBuffer = ExAllocatePool(PagedPool, FileSize + 1); /* add 1 byte for terminating '\0' */
2832 if (!FileBuffer)
2833 {
2834 ZwClose(hFile);
2835 DPRINT("Could not allocate %d bytes for KDBinit file\n", FileSize);
2836 return;
2837 }
2838
2839 /* Load file into memory */
2840 Status = ZwReadFile(hFile, 0, 0, 0, &Iosb, FileBuffer, FileSize, 0, 0);
2841 ZwClose(hFile);
2842
2843 if (!NT_SUCCESS(Status) && Status != STATUS_END_OF_FILE)
2844 {
2845 ExFreePool(FileBuffer);
2846 DPRINT("Could not read KDBinit file into memory (Status 0x%lx)\n", Status);
2847 return;
2848 }
2849
2850 FileSize = min(FileSize, (INT)Iosb.Information);
2851 FileBuffer[FileSize] = '\0';
2852
2853 /* Enter critical section */
2854 OldEflags = __readeflags();
2855 _disable();
2856
2857 /* Interpret the init file... */
2858 KdbInitFileBuffer = FileBuffer;
2859 KdbEnter();
2860 KdbInitFileBuffer = NULL;
2861
2862 /* Leave critical section */
2863 __writeeflags(OldEflags);
2864
2865 ExFreePool(FileBuffer);
2866 }
2867
2868 VOID
2869 NTAPI
2870 KdpSerialDebugPrint(
2871 LPSTR Message,
2872 ULONG Length
2873 );
2874
2875 STRING KdpPromptString = RTL_CONSTANT_STRING("kdb:> ");
2876 extern KSPIN_LOCK KdpSerialSpinLock;
2877
2878 ULONG
2879 NTAPI
2880 KdpPrompt(IN LPSTR InString,
2881 IN USHORT InStringLength,
2882 OUT LPSTR OutString,
2883 IN USHORT OutStringLength)
2884 {
2885 USHORT i;
2886 CHAR Response;
2887 ULONG DummyScanCode;
2888 KIRQL OldIrql;
2889
2890 /* Acquire the printing spinlock without waiting at raised IRQL */
2891 while (TRUE)
2892 {
2893 /* Wait when the spinlock becomes available */
2894 while (!KeTestSpinLock(&KdpSerialSpinLock));
2895
2896 /* Spinlock was free, raise IRQL */
2897 KeRaiseIrql(HIGH_LEVEL, &OldIrql);
2898
2899 /* Try to get the spinlock */
2900 if (KeTryToAcquireSpinLockAtDpcLevel(&KdpSerialSpinLock))
2901 break;
2902
2903 /* Someone else got the spinlock, lower IRQL back */
2904 KeLowerIrql(OldIrql);
2905 }
2906
2907 /* Loop the string to send */
2908 for (i = 0; i < InStringLength; i++)
2909 {
2910 /* Print it to serial */
2911 KdPortPutByteEx(&SerialPortInfo, *(PCHAR)(InString + i));
2912 }
2913
2914 /* Print a new line for log neatness */
2915 KdPortPutByteEx(&SerialPortInfo, '\r');
2916 KdPortPutByteEx(&SerialPortInfo, '\n');
2917
2918 /* Print the kdb prompt */
2919 for (i = 0; i < KdpPromptString.Length; i++)
2920 {
2921 /* Print it to serial */
2922 KdPortPutByteEx(&SerialPortInfo,
2923 *(KdpPromptString.Buffer + i));
2924 }
2925
2926 /* Loop the whole string */
2927 for (i = 0; i < OutStringLength; i++)
2928 {
2929 /* Check if this is serial debugging mode */
2930 if (KdbDebugState & KD_DEBUG_KDSERIAL)
2931 {
2932 /* Get the character from serial */
2933 do
2934 {
2935 Response = KdbpTryGetCharSerial(MAXULONG);
2936 } while (Response == -1);
2937 }
2938 else
2939 {
2940 /* Get the response from the keyboard */
2941 do
2942 {
2943 Response = KdbpTryGetCharKeyboard(&DummyScanCode, MAXULONG);
2944 } while (Response == -1);
2945 }
2946
2947 /* Check for return */
2948 if (Response == '\r')
2949 {
2950 /*
2951 * We might need to discard the next '\n'.
2952 * Wait a bit to make sure we receive it.
2953 */
2954 KeStallExecutionProcessor(100000);
2955
2956 /* Check the mode */
2957 if (KdbDebugState & KD_DEBUG_KDSERIAL)
2958 {
2959 /* Read and discard the next character, if any */
2960 KdbpTryGetCharSerial(5);
2961 }
2962 else
2963 {
2964 /* Read and discard the next character, if any */
2965 KdbpTryGetCharKeyboard(&DummyScanCode, 5);
2966 }
2967
2968 /*
2969 * Null terminate the output string -- documentation states that
2970 * DbgPrompt does not null terminate, but it does
2971 */
2972 *(PCHAR)(OutString + i) = 0;
2973
2974 /* Print a new line */
2975 KdPortPutByteEx(&SerialPortInfo, '\r');
2976 KdPortPutByteEx(&SerialPortInfo, '\n');
2977
2978 /* Release spinlock */
2979 KiReleaseSpinLock(&KdpSerialSpinLock);
2980
2981 /* Lower IRQL back */
2982 KeLowerIrql(OldIrql);
2983
2984 /* Return the length */
2985 return OutStringLength + 1;
2986 }
2987
2988 /* Write it back and print it to the log */
2989 *(PCHAR)(OutString + i) = Response;
2990 KdPortPutByteEx(&SerialPortInfo, Response);
2991 }
2992
2993 /* Print a new line */
2994 KdPortPutByteEx(&SerialPortInfo, '\r');
2995 KdPortPutByteEx(&SerialPortInfo, '\n');
2996
2997 /* Release spinlock */
2998 KiReleaseSpinLock(&KdpSerialSpinLock);
2999
3000 /* Lower IRQL back */
3001 KeLowerIrql(OldIrql);
3002
3003 /* Return the length */
3004 return OutStringLength;
3005 }