- Merge audio components from head
[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))
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))
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
798 if (Argc >= 2)
799 {
800 /* Check for [L count] part */
801 ul = 0;
802
803 if (strcmp(Argv[Argc-2], "L") == 0)
804 {
805 ul = strtoul(Argv[Argc-1], NULL, 0);
806 if (ul > 0)
807 {
808 Argc -= 2;
809 }
810 }
811 else if (Argv[Argc-1][0] == 'L')
812 {
813 ul = strtoul(Argv[Argc-1] + 1, NULL, 0);
814 if (ul > 0)
815 {
816 Argc--;
817 }
818 }
819
820 /* Put the remaining arguments back together */
821 Argc--;
822 for (ul = 1; ul < Argc; ul++)
823 {
824 Argv[ul][strlen(Argv[ul])] = ' ';
825 }
826 Argc++;
827 }
828
829 /* Check if frame addr or thread id is given. */
830 if (Argc > 1)
831 {
832 if (Argv[1][0] == '*')
833 {
834 Argv[1]++;
835
836 /* Evaluate the expression */
837 if (!KdbpEvaluateExpression(Argv[1], sizeof("kdb:> ")-1 + (Argv[1]-Argv[0]), &Result))
838 return TRUE;
839
840 if (Result > (ULONGLONG)(~((ULONG_PTR)0)))
841 KdbpPrint("Warning: Address %I64x is beeing truncated\n",Result);
842
843 Frame = (ULONG_PTR)Result;
844 }
845 else
846 {
847 KdbpPrint("Thread backtrace not supported yet!\n");
848 return TRUE;
849 }
850 }
851 else
852 {
853 KdbpPrint("Eip:\n");
854
855 /* Try printing the function at EIP */
856 if (!KdbSymPrintAddress((PVOID)KdbCurrentTrapFrame->Tf.Eip))
857 KdbpPrint("<%08x>\n", KdbCurrentTrapFrame->Tf.Eip);
858 else
859 KdbpPrint("\n");
860 }
861
862 KdbpPrint("Frames:\n");
863 for (;;)
864 {
865 if (Frame == 0)
866 break;
867
868 if (!NT_SUCCESS(KdbpSafeReadMemory(&Address, (PVOID)(Frame + sizeof(ULONG_PTR)), sizeof (ULONG_PTR))))
869 {
870 KdbpPrint("Couldn't access memory at 0x%p!\n", Frame + sizeof(ULONG_PTR));
871 break;
872 }
873
874 /* Print the location of the call instruction */
875 if (!KdbSymPrintAddress((PVOID)(Address - 5)))
876 KdbpPrint("<%08x>\n", Address);
877 else
878 KdbpPrint("\n");
879
880 if (Address == 0)
881 break;
882
883 if (!NT_SUCCESS(KdbpSafeReadMemory(&Frame, (PVOID)Frame, sizeof (ULONG_PTR))))
884 {
885 KdbpPrint("Couldn't access memory at 0x%p!\n", Frame);
886 break;
887 }
888 }
889
890 return TRUE;
891 }
892
893 /*!\brief Continues execution of the system/leaves KDB.
894 */
895 static BOOLEAN
896 KdbpCmdContinue(
897 ULONG Argc,
898 PCHAR Argv[])
899 {
900 /* Exit the main loop */
901 return FALSE;
902 }
903
904 /*!\brief Continues execution of the system/leaves KDB.
905 */
906 static BOOLEAN
907 KdbpCmdStep(
908 ULONG Argc,
909 PCHAR Argv[])
910 {
911 ULONG Count = 1;
912
913 if (Argc > 1)
914 {
915 Count = strtoul(Argv[1], NULL, 0);
916 if (Count == 0)
917 {
918 KdbpPrint("%s: Integer argument required\n", Argv[0]);
919 return TRUE;
920 }
921 }
922
923 if (Argv[0][0] == 'n')
924 KdbSingleStepOver = TRUE;
925 else
926 KdbSingleStepOver = FALSE;
927
928 /* Set the number of single steps and return to the interrupted code. */
929 KdbNumSingleSteps = Count;
930
931 return FALSE;
932 }
933
934 /*!\brief Lists breakpoints.
935 */
936 static BOOLEAN
937 KdbpCmdBreakPointList(
938 ULONG Argc,
939 PCHAR Argv[])
940 {
941 LONG l;
942 ULONG_PTR Address = 0;
943 KDB_BREAKPOINT_TYPE Type = 0;
944 KDB_ACCESS_TYPE AccessType = 0;
945 UCHAR Size = 0;
946 UCHAR DebugReg = 0;
947 BOOLEAN Enabled = FALSE;
948 BOOLEAN Global = FALSE;
949 PEPROCESS Process = NULL;
950 PCHAR str1, str2, ConditionExpr, GlobalOrLocal;
951 CHAR Buffer[20];
952
953 l = KdbpGetNextBreakPointNr(0);
954 if (l < 0)
955 {
956 KdbpPrint("No breakpoints.\n");
957 return TRUE;
958 }
959
960 KdbpPrint("Breakpoints:\n");
961 do
962 {
963 if (!KdbpGetBreakPointInfo(l, &Address, &Type, &Size, &AccessType, &DebugReg,
964 &Enabled, &Global, &Process, &ConditionExpr))
965 {
966 continue;
967 }
968
969 if (l == KdbLastBreakPointNr)
970 {
971 str1 = "\x1b[1m*";
972 str2 = "\x1b[0m";
973 }
974 else
975 {
976 str1 = " ";
977 str2 = "";
978 }
979
980 if (Global)
981 {
982 GlobalOrLocal = " global";
983 }
984 else
985 {
986 GlobalOrLocal = Buffer;
987 sprintf(Buffer, " PID 0x%08lx",
988 (ULONG)(Process ? Process->UniqueProcessId : INVALID_HANDLE_VALUE));
989 }
990
991 if (Type == KdbBreakPointSoftware || Type == KdbBreakPointTemporary)
992 {
993 KdbpPrint(" %s%03d BPX 0x%08x%s%s%s%s%s\n",
994 str1, l, Address,
995 Enabled ? "" : " disabled",
996 GlobalOrLocal,
997 ConditionExpr ? " IF " : "",
998 ConditionExpr ? ConditionExpr : "",
999 str2);
1000 }
1001 else if (Type == KdbBreakPointHardware)
1002 {
1003 if (!Enabled)
1004 {
1005 KdbpPrint(" %s%03d BPM 0x%08x %-5s %-5s disabled%s%s%s%s\n", str1, l, Address,
1006 KDB_ACCESS_TYPE_TO_STRING(AccessType),
1007 Size == 1 ? "byte" : (Size == 2 ? "word" : "dword"),
1008 GlobalOrLocal,
1009 ConditionExpr ? " IF " : "",
1010 ConditionExpr ? ConditionExpr : "",
1011 str2);
1012 }
1013 else
1014 {
1015 KdbpPrint(" %s%03d BPM 0x%08x %-5s %-5s DR%d%s%s%s%s\n", str1, l, Address,
1016 KDB_ACCESS_TYPE_TO_STRING(AccessType),
1017 Size == 1 ? "byte" : (Size == 2 ? "word" : "dword"),
1018 DebugReg,
1019 GlobalOrLocal,
1020 ConditionExpr ? " IF " : "",
1021 ConditionExpr ? ConditionExpr : "",
1022 str2);
1023 }
1024 }
1025 }
1026 while ((l = KdbpGetNextBreakPointNr(l+1)) >= 0);
1027
1028 return TRUE;
1029 }
1030
1031 /*!\brief Enables, disables or clears a breakpoint.
1032 */
1033 static BOOLEAN
1034 KdbpCmdEnableDisableClearBreakPoint(
1035 ULONG Argc,
1036 PCHAR Argv[])
1037 {
1038 PCHAR pend;
1039 ULONG BreakPointNr;
1040
1041 if (Argc < 2)
1042 {
1043 KdbpPrint("%s: argument required\n", Argv[0]);
1044 return TRUE;
1045 }
1046
1047 pend = Argv[1];
1048 BreakPointNr = strtoul(Argv[1], &pend, 0);
1049 if (pend == Argv[1] || *pend != '\0')
1050 {
1051 KdbpPrint("%s: integer argument required\n", Argv[0]);
1052 return TRUE;
1053 }
1054
1055 if (Argv[0][1] == 'e') /* enable */
1056 {
1057 KdbpEnableBreakPoint(BreakPointNr, NULL);
1058 }
1059 else if (Argv [0][1] == 'd') /* disable */
1060 {
1061 KdbpDisableBreakPoint(BreakPointNr, NULL);
1062 }
1063 else /* clear */
1064 {
1065 ASSERT(Argv[0][1] == 'c');
1066 KdbpDeleteBreakPoint(BreakPointNr, NULL);
1067 }
1068
1069 return TRUE;
1070 }
1071
1072 /*!\brief Sets a software or hardware (memory) breakpoint at the given address.
1073 */
1074 static BOOLEAN
1075 KdbpCmdBreakPoint(ULONG Argc, PCHAR Argv[])
1076 {
1077 ULONGLONG Result = 0;
1078 ULONG_PTR Address;
1079 KDB_BREAKPOINT_TYPE Type;
1080 UCHAR Size = 0;
1081 KDB_ACCESS_TYPE AccessType = 0;
1082 ULONG AddressArgIndex, i;
1083 LONG ConditionArgIndex;
1084 BOOLEAN Global = TRUE;
1085
1086 if (Argv[0][2] == 'x') /* software breakpoint */
1087 {
1088 if (Argc < 2)
1089 {
1090 KdbpPrint("bpx: Address argument required.\n");
1091 return TRUE;
1092 }
1093
1094 AddressArgIndex = 1;
1095 Type = KdbBreakPointSoftware;
1096 }
1097 else /* memory breakpoint */
1098 {
1099 ASSERT(Argv[0][2] == 'm');
1100
1101 if (Argc < 2)
1102 {
1103 KdbpPrint("bpm: Access type argument required (one of r, w, rw, x)\n");
1104 return TRUE;
1105 }
1106
1107 if (_stricmp(Argv[1], "x") == 0)
1108 AccessType = KdbAccessExec;
1109 else if (_stricmp(Argv[1], "r") == 0)
1110 AccessType = KdbAccessRead;
1111 else if (_stricmp(Argv[1], "w") == 0)
1112 AccessType = KdbAccessWrite;
1113 else if (_stricmp(Argv[1], "rw") == 0)
1114 AccessType = KdbAccessReadWrite;
1115 else
1116 {
1117 KdbpPrint("bpm: Unknown access type '%s'\n", Argv[1]);
1118 return TRUE;
1119 }
1120
1121 if (Argc < 3)
1122 {
1123 KdbpPrint("bpm: %s argument required.\n", AccessType == KdbAccessExec ? "Address" : "Memory size");
1124 return TRUE;
1125 }
1126
1127 AddressArgIndex = 3;
1128 if (_stricmp(Argv[2], "byte") == 0)
1129 Size = 1;
1130 else if (_stricmp(Argv[2], "word") == 0)
1131 Size = 2;
1132 else if (_stricmp(Argv[2], "dword") == 0)
1133 Size = 4;
1134 else if (AccessType == KdbAccessExec)
1135 {
1136 Size = 1;
1137 AddressArgIndex--;
1138 }
1139 else
1140 {
1141 KdbpPrint("bpm: Unknown memory size '%s'\n", Argv[2]);
1142 return TRUE;
1143 }
1144
1145 if (Argc <= AddressArgIndex)
1146 {
1147 KdbpPrint("bpm: Address argument required.\n");
1148 return TRUE;
1149 }
1150
1151 Type = KdbBreakPointHardware;
1152 }
1153
1154 /* Put the arguments back together */
1155 ConditionArgIndex = -1;
1156 for (i = AddressArgIndex; i < (Argc-1); i++)
1157 {
1158 if (strcmp(Argv[i+1], "IF") == 0) /* IF found */
1159 {
1160 ConditionArgIndex = i + 2;
1161 if (ConditionArgIndex >= Argc)
1162 {
1163 KdbpPrint("%s: IF requires condition expression.\n", Argv[0]);
1164 return TRUE;
1165 }
1166
1167 for (i = ConditionArgIndex; i < (Argc-1); i++)
1168 Argv[i][strlen(Argv[i])] = ' ';
1169
1170 break;
1171 }
1172
1173 Argv[i][strlen(Argv[i])] = ' ';
1174 }
1175
1176 /* Evaluate the address expression */
1177 if (!KdbpEvaluateExpression(Argv[AddressArgIndex],
1178 sizeof("kdb:> ")-1 + (Argv[AddressArgIndex]-Argv[0]),
1179 &Result))
1180 {
1181 return TRUE;
1182 }
1183
1184 if (Result > (ULONGLONG)(~((ULONG_PTR)0)))
1185 KdbpPrint("%s: Warning: Address %I64x is beeing truncated\n", Argv[0],Result);
1186
1187 Address = (ULONG_PTR)Result;
1188
1189 KdbpInsertBreakPoint(Address, Type, Size, AccessType,
1190 (ConditionArgIndex < 0) ? NULL : Argv[ConditionArgIndex],
1191 Global, NULL);
1192
1193 return TRUE;
1194 }
1195
1196 /*!\brief Lists threads or switches to another thread context.
1197 */
1198 static BOOLEAN
1199 KdbpCmdThread(
1200 ULONG Argc,
1201 PCHAR Argv[])
1202 {
1203 PLIST_ENTRY Entry;
1204 PETHREAD Thread = NULL;
1205 PEPROCESS Process = NULL;
1206 BOOLEAN ReferencedThread = FALSE, ReferencedProcess = FALSE;
1207 PULONG Esp;
1208 PULONG Ebp;
1209 ULONG Eip;
1210 ULONG ul = 0;
1211 PCHAR State, pend, str1, str2;
1212 static const PCHAR ThreadStateToString[DeferredReady+1] =
1213 {
1214 "Initialized", "Ready", "Running",
1215 "Standby", "Terminated", "Waiting",
1216 "Transition", "DeferredReady"
1217 };
1218
1219 ASSERT(KdbCurrentProcess);
1220
1221 if (Argc >= 2 && _stricmp(Argv[1], "list") == 0)
1222 {
1223 Process = KdbCurrentProcess;
1224
1225 if (Argc >= 3)
1226 {
1227 ul = strtoul(Argv[2], &pend, 0);
1228 if (Argv[2] == pend)
1229 {
1230 KdbpPrint("thread: '%s' is not a valid process id!\n", Argv[2]);
1231 return TRUE;
1232 }
1233
1234 if (!NT_SUCCESS(PsLookupProcessByProcessId((PVOID)ul, &Process)))
1235 {
1236 KdbpPrint("thread: Invalid process id!\n");
1237 return TRUE;
1238 }
1239
1240 /* Remember our reference */
1241 ReferencedProcess = TRUE;
1242 }
1243
1244 Entry = Process->ThreadListHead.Flink;
1245 if (Entry == &Process->ThreadListHead)
1246 {
1247 if (Argc >= 3)
1248 KdbpPrint("No threads in process 0x%08x!\n", ul);
1249 else
1250 KdbpPrint("No threads in current process!\n");
1251
1252 if (ReferencedProcess)
1253 ObDereferenceObject(Process);
1254
1255 return TRUE;
1256 }
1257
1258 KdbpPrint(" TID State Prior. Affinity EBP EIP\n");
1259 do
1260 {
1261 Thread = CONTAINING_RECORD(Entry, ETHREAD, ThreadListEntry);
1262
1263 if (Thread == KdbCurrentThread)
1264 {
1265 str1 = "\x1b[1m*";
1266 str2 = "\x1b[0m";
1267 }
1268 else
1269 {
1270 str1 = " ";
1271 str2 = "";
1272 }
1273
1274 if (!Thread->Tcb.InitialStack)
1275 {
1276 /* Thread has no kernel stack (probably terminated) */
1277 Esp = Ebp = NULL;
1278 Eip = 0;
1279 }
1280 else if (Thread->Tcb.TrapFrame)
1281 {
1282 if (Thread->Tcb.TrapFrame->PreviousPreviousMode == KernelMode)
1283 Esp = (PULONG)Thread->Tcb.TrapFrame->TempEsp;
1284 else
1285 Esp = (PULONG)Thread->Tcb.TrapFrame->HardwareEsp;
1286
1287 Ebp = (PULONG)Thread->Tcb.TrapFrame->Ebp;
1288 Eip = Thread->Tcb.TrapFrame->Eip;
1289 }
1290 else
1291 {
1292 Esp = (PULONG)Thread->Tcb.KernelStack;
1293 Ebp = (PULONG)Esp[4];
1294 Eip = 0;
1295
1296 if (Ebp) /* FIXME: Should we attach to the process to read Ebp[1]? */
1297 KdbpSafeReadMemory(&Eip, Ebp + 1, sizeof (Eip));
1298 }
1299
1300 if (Thread->Tcb.State < (DeferredReady + 1))
1301 State = ThreadStateToString[Thread->Tcb.State];
1302 else
1303 State = "Unknown";
1304
1305 KdbpPrint(" %s0x%08x %-11s %3d 0x%08x 0x%08x 0x%08x%s\n",
1306 str1,
1307 Thread->Cid.UniqueThread,
1308 State,
1309 Thread->Tcb.Priority,
1310 Thread->Tcb.Affinity,
1311 Ebp,
1312 Eip,
1313 str2);
1314
1315 Entry = Entry->Flink;
1316 }
1317 while (Entry != &Process->ThreadListHead);
1318
1319 /* Release our reference, if any */
1320 if (ReferencedProcess)
1321 ObDereferenceObject(Process);
1322 }
1323 else if (Argc >= 2 && _stricmp(Argv[1], "attach") == 0)
1324 {
1325 if (Argc < 3)
1326 {
1327 KdbpPrint("thread attach: thread id argument required!\n");
1328 return TRUE;
1329 }
1330
1331 ul = strtoul(Argv[2], &pend, 0);
1332 if (Argv[2] == pend)
1333 {
1334 KdbpPrint("thread attach: '%s' is not a valid thread id!\n", Argv[2]);
1335 return TRUE;
1336 }
1337
1338 if (!KdbpAttachToThread((PVOID)ul))
1339 {
1340 return TRUE;
1341 }
1342
1343 KdbpPrint("Attached to thread 0x%08x.\n", ul);
1344 }
1345 else
1346 {
1347 Thread = KdbCurrentThread;
1348
1349 if (Argc >= 2)
1350 {
1351 ul = strtoul(Argv[1], &pend, 0);
1352 if (Argv[1] == pend)
1353 {
1354 KdbpPrint("thread: '%s' is not a valid thread id!\n", Argv[1]);
1355 return TRUE;
1356 }
1357
1358 if (!NT_SUCCESS(PsLookupThreadByThreadId((PVOID)ul, &Thread)))
1359 {
1360 KdbpPrint("thread: Invalid thread id!\n");
1361 return TRUE;
1362 }
1363
1364 /* Remember our reference */
1365 ReferencedThread = TRUE;
1366 }
1367
1368 if (Thread->Tcb.State < (DeferredReady + 1))
1369 State = ThreadStateToString[Thread->Tcb.State];
1370 else
1371 State = "Unknown";
1372
1373 KdbpPrint("%s"
1374 " TID: 0x%08x\n"
1375 " State: %s (0x%x)\n"
1376 " Priority: %d\n"
1377 " Affinity: 0x%08x\n"
1378 " Initial Stack: 0x%08x\n"
1379 " Stack Limit: 0x%08x\n"
1380 " Stack Base: 0x%08x\n"
1381 " Kernel Stack: 0x%08x\n"
1382 " Trap Frame: 0x%08x\n"
1383 " NPX State: %s (0x%x)\n",
1384 (Argc < 2) ? "Current Thread:\n" : "",
1385 Thread->Cid.UniqueThread,
1386 State, Thread->Tcb.State,
1387 Thread->Tcb.Priority,
1388 Thread->Tcb.Affinity,
1389 Thread->Tcb.InitialStack,
1390 Thread->Tcb.StackLimit,
1391 Thread->Tcb.StackBase,
1392 Thread->Tcb.KernelStack,
1393 Thread->Tcb.TrapFrame,
1394 NPX_STATE_TO_STRING(Thread->Tcb.NpxState), Thread->Tcb.NpxState);
1395
1396 /* Release our reference if we had one */
1397 if (ReferencedThread)
1398 ObDereferenceObject(Thread);
1399 }
1400
1401 return TRUE;
1402 }
1403
1404 /*!\brief Lists processes or switches to another process context.
1405 */
1406 static BOOLEAN
1407 KdbpCmdProc(
1408 ULONG Argc,
1409 PCHAR Argv[])
1410 {
1411 PLIST_ENTRY Entry;
1412 PEPROCESS Process;
1413 BOOLEAN ReferencedProcess = FALSE;
1414 PCHAR State, pend, str1, str2;
1415 ULONG ul;
1416 extern LIST_ENTRY PsActiveProcessHead;
1417
1418 if (Argc >= 2 && _stricmp(Argv[1], "list") == 0)
1419 {
1420 Entry = PsActiveProcessHead.Flink;
1421 if (!Entry || Entry == &PsActiveProcessHead)
1422 {
1423 KdbpPrint("No processes in the system!\n");
1424 return TRUE;
1425 }
1426
1427 KdbpPrint(" PID State Filename\n");
1428 do
1429 {
1430 Process = CONTAINING_RECORD(Entry, EPROCESS, ActiveProcessLinks);
1431
1432 if (Process == KdbCurrentProcess)
1433 {
1434 str1 = "\x1b[1m*";
1435 str2 = "\x1b[0m";
1436 }
1437 else
1438 {
1439 str1 = " ";
1440 str2 = "";
1441 }
1442
1443 State = ((Process->Pcb.State == ProcessInMemory) ? "In Memory" :
1444 ((Process->Pcb.State == ProcessOutOfMemory) ? "Out of Memory" : "In Transition"));
1445
1446 KdbpPrint(" %s0x%08x %-10s %s%s\n",
1447 str1,
1448 Process->UniqueProcessId,
1449 State,
1450 Process->ImageFileName,
1451 str2);
1452
1453 Entry = Entry->Flink;
1454 }
1455 while(Entry != &PsActiveProcessHead);
1456 }
1457 else if (Argc >= 2 && _stricmp(Argv[1], "attach") == 0)
1458 {
1459 if (Argc < 3)
1460 {
1461 KdbpPrint("process attach: process id argument required!\n");
1462 return TRUE;
1463 }
1464
1465 ul = strtoul(Argv[2], &pend, 0);
1466 if (Argv[2] == pend)
1467 {
1468 KdbpPrint("process attach: '%s' is not a valid process id!\n", Argv[2]);
1469 return TRUE;
1470 }
1471
1472 if (!KdbpAttachToProcess((PVOID)ul))
1473 {
1474 return TRUE;
1475 }
1476
1477 KdbpPrint("Attached to process 0x%08x, thread 0x%08x.\n", (ULONG)ul,
1478 (ULONG)KdbCurrentThread->Cid.UniqueThread);
1479 }
1480 else
1481 {
1482 Process = KdbCurrentProcess;
1483
1484 if (Argc >= 2)
1485 {
1486 ul = strtoul(Argv[1], &pend, 0);
1487 if (Argv[1] == pend)
1488 {
1489 KdbpPrint("proc: '%s' is not a valid process id!\n", Argv[1]);
1490 return TRUE;
1491 }
1492
1493 if (!NT_SUCCESS(PsLookupProcessByProcessId((PVOID)ul, &Process)))
1494 {
1495 KdbpPrint("proc: Invalid process id!\n");
1496 return TRUE;
1497 }
1498
1499 /* Remember our reference */
1500 ReferencedProcess = TRUE;
1501 }
1502
1503 State = ((Process->Pcb.State == ProcessInMemory) ? "In Memory" :
1504 ((Process->Pcb.State == ProcessOutOfMemory) ? "Out of Memory" : "In Transition"));
1505 KdbpPrint("%s"
1506 " PID: 0x%08x\n"
1507 " State: %s (0x%x)\n"
1508 " Image Filename: %s\n",
1509 (Argc < 2) ? "Current process:\n" : "",
1510 Process->UniqueProcessId,
1511 State, Process->Pcb.State,
1512 Process->ImageFileName);
1513
1514 /* Release our reference, if any */
1515 if (ReferencedProcess)
1516 ObDereferenceObject(Process);
1517 }
1518
1519 return TRUE;
1520 }
1521
1522 /*!\brief Lists loaded modules or the one containing the specified address.
1523 */
1524 static BOOLEAN
1525 KdbpCmdMod(
1526 ULONG Argc,
1527 PCHAR Argv[])
1528 {
1529 ULONGLONG Result = 0;
1530 ULONG_PTR Address;
1531 PLDR_DATA_TABLE_ENTRY LdrEntry;
1532 BOOLEAN DisplayOnlyOneModule = FALSE;
1533 INT i = 0;
1534
1535 if (Argc >= 2)
1536 {
1537 /* Put the arguments back together */
1538 Argc--;
1539 while (--Argc >= 1)
1540 Argv[Argc][strlen(Argv[Argc])] = ' ';
1541
1542 /* Evaluate the expression */
1543 if (!KdbpEvaluateExpression(Argv[1], sizeof("kdb:> ")-1 + (Argv[1]-Argv[0]), &Result))
1544 {
1545 return TRUE;
1546 }
1547
1548 if (Result > (ULONGLONG)(~((ULONG_PTR)0)))
1549 KdbpPrint("%s: Warning: Address %I64x is beeing truncated\n", Argv[0],Result);
1550
1551 Address = (ULONG_PTR)Result;
1552
1553 if (!KdbpSymFindModule((PVOID)Address, NULL, -1, &LdrEntry))
1554 {
1555 KdbpPrint("No module containing address 0x%p found!\n", Address);
1556 return TRUE;
1557 }
1558
1559 DisplayOnlyOneModule = TRUE;
1560 }
1561 else
1562 {
1563 if (!KdbpSymFindModule(NULL, NULL, 0, &LdrEntry))
1564 {
1565 ULONG_PTR ntoskrnlBase = ((ULONG_PTR)KdbpCmdMod) & 0xfff00000;
1566 KdbpPrint(" Base Size Name\n");
1567 KdbpPrint(" %08x %08x %s\n", ntoskrnlBase, 0, "ntoskrnl.exe");
1568 return TRUE;
1569 }
1570
1571 i = 1;
1572 }
1573
1574 KdbpPrint(" Base Size Name\n");
1575 for (;;)
1576 {
1577 KdbpPrint(" %08x %08x %wZ\n", LdrEntry->DllBase, LdrEntry->SizeOfImage, &LdrEntry->BaseDllName);
1578
1579 if(DisplayOnlyOneModule || !KdbpSymFindModule(NULL, NULL, i++, &LdrEntry))
1580 break;
1581 }
1582
1583 return TRUE;
1584 }
1585
1586 /*!\brief Displays GDT, LDT or IDTd.
1587 */
1588 static BOOLEAN
1589 KdbpCmdGdtLdtIdt(
1590 ULONG Argc,
1591 PCHAR Argv[])
1592 {
1593 KDESCRIPTOR Reg;
1594 ULONG SegDesc[2];
1595 ULONG SegBase;
1596 ULONG SegLimit;
1597 PCHAR SegType;
1598 USHORT SegSel;
1599 UCHAR Type, Dpl;
1600 INT i;
1601 ULONG ul;
1602
1603 if (Argv[0][0] == 'i')
1604 {
1605 /* Read IDTR */
1606 __sidt(&Reg.Limit);
1607
1608 if (Reg.Limit < 7)
1609 {
1610 KdbpPrint("Interrupt descriptor table is empty.\n");
1611 return TRUE;
1612 }
1613
1614 KdbpPrint("IDT Base: 0x%08x Limit: 0x%04x\n", Reg.Base, Reg.Limit);
1615 KdbpPrint(" Idx Type Seg. Sel. Offset DPL\n");
1616
1617 for (i = 0; (i + sizeof(SegDesc) - 1) <= Reg.Limit; i += 8)
1618 {
1619 if (!NT_SUCCESS(KdbpSafeReadMemory(SegDesc, (PVOID)(Reg.Base + i), sizeof(SegDesc))))
1620 {
1621 KdbpPrint("Couldn't access memory at 0x%08x!\n", Reg.Base + i);
1622 return TRUE;
1623 }
1624
1625 Dpl = ((SegDesc[1] >> 13) & 3);
1626 if ((SegDesc[1] & 0x1f00) == 0x0500) /* Task gate */
1627 SegType = "TASKGATE";
1628 else if ((SegDesc[1] & 0x1fe0) == 0x0e00) /* 32 bit Interrupt gate */
1629 SegType = "INTGATE32";
1630 else if ((SegDesc[1] & 0x1fe0) == 0x0600) /* 16 bit Interrupt gate */
1631 SegType = "INTGATE16";
1632 else if ((SegDesc[1] & 0x1fe0) == 0x0f00) /* 32 bit Trap gate */
1633 SegType = "TRAPGATE32";
1634 else if ((SegDesc[1] & 0x1fe0) == 0x0700) /* 16 bit Trap gate */
1635 SegType = "TRAPGATE16";
1636 else
1637 SegType = "UNKNOWN";
1638
1639 if ((SegDesc[1] & (1 << 15)) == 0) /* not present */
1640 {
1641 KdbpPrint(" %03d %-10s [NP] [NP] %02d\n",
1642 i / 8, SegType, Dpl);
1643 }
1644 else if ((SegDesc[1] & 0x1f00) == 0x0500) /* Task gate */
1645 {
1646 SegSel = SegDesc[0] >> 16;
1647 KdbpPrint(" %03d %-10s 0x%04x %02d\n",
1648 i / 8, SegType, SegSel, Dpl);
1649 }
1650 else
1651 {
1652 SegSel = SegDesc[0] >> 16;
1653 SegBase = (SegDesc[1] & 0xffff0000) | (SegDesc[0] & 0x0000ffff);
1654 KdbpPrint(" %03d %-10s 0x%04x 0x%08x %02d\n",
1655 i / 8, SegType, SegSel, SegBase, Dpl);
1656 }
1657 }
1658 }
1659 else
1660 {
1661 ul = 0;
1662
1663 if (Argv[0][0] == 'g')
1664 {
1665 /* Read GDTR */
1666 Ke386GetGlobalDescriptorTable(&Reg.Limit);
1667 i = 8;
1668 }
1669 else
1670 {
1671 ASSERT(Argv[0][0] == 'l');
1672
1673 /* Read LDTR */
1674 Reg.Limit = Ke386GetLocalDescriptorTable();
1675 Reg.Base = 0;
1676 i = 0;
1677 ul = 1 << 2;
1678 }
1679
1680 if (Reg.Limit < 7)
1681 {
1682 KdbpPrint("%s descriptor table is empty.\n",
1683 Argv[0][0] == 'g' ? "Global" : "Local");
1684 return TRUE;
1685 }
1686
1687 KdbpPrint("%cDT Base: 0x%08x Limit: 0x%04x\n",
1688 Argv[0][0] == 'g' ? 'G' : 'L', Reg.Base, Reg.Limit);
1689 KdbpPrint(" Idx Sel. Type Base Limit DPL Attribs\n");
1690
1691 for (; (i + sizeof(SegDesc) - 1) <= Reg.Limit; i += 8)
1692 {
1693 if (!NT_SUCCESS(KdbpSafeReadMemory(SegDesc, (PVOID)(Reg.Base + i), sizeof(SegDesc))))
1694 {
1695 KdbpPrint("Couldn't access memory at 0x%08x!\n", Reg.Base + i);
1696 return TRUE;
1697 }
1698
1699 Dpl = ((SegDesc[1] >> 13) & 3);
1700 Type = ((SegDesc[1] >> 8) & 0xf);
1701
1702 SegBase = SegDesc[0] >> 16;
1703 SegBase |= (SegDesc[1] & 0xff) << 16;
1704 SegBase |= SegDesc[1] & 0xff000000;
1705 SegLimit = SegDesc[0] & 0x0000ffff;
1706 SegLimit |= (SegDesc[1] >> 16) & 0xf;
1707
1708 if ((SegDesc[1] & (1 << 23)) != 0)
1709 {
1710 SegLimit *= 4096;
1711 SegLimit += 4095;
1712 }
1713 else
1714 {
1715 SegLimit++;
1716 }
1717
1718 if ((SegDesc[1] & (1 << 12)) == 0) /* System segment */
1719 {
1720 switch (Type)
1721 {
1722 case 1: SegType = "TSS16(Avl)"; break;
1723 case 2: SegType = "LDT"; break;
1724 case 3: SegType = "TSS16(Busy)"; break;
1725 case 4: SegType = "CALLGATE16"; break;
1726 case 5: SegType = "TASKGATE"; break;
1727 case 6: SegType = "INTGATE16"; break;
1728 case 7: SegType = "TRAPGATE16"; break;
1729 case 9: SegType = "TSS32(Avl)"; break;
1730 case 11: SegType = "TSS32(Busy)"; break;
1731 case 12: SegType = "CALLGATE32"; break;
1732 case 14: SegType = "INTGATE32"; break;
1733 case 15: SegType = "INTGATE32"; break;
1734 default: SegType = "UNKNOWN"; break;
1735 }
1736
1737 if (!(Type >= 1 && Type <= 3) &&
1738 Type != 9 && Type != 11)
1739 {
1740 SegBase = 0;
1741 SegLimit = 0;
1742 }
1743 }
1744 else if ((SegDesc[1] & (1 << 11)) == 0) /* Data segment */
1745 {
1746 if ((SegDesc[1] & (1 << 22)) != 0)
1747 SegType = "DATA32";
1748 else
1749 SegType = "DATA16";
1750 }
1751 else /* Code segment */
1752 {
1753 if ((SegDesc[1] & (1 << 22)) != 0)
1754 SegType = "CODE32";
1755 else
1756 SegType = "CODE16";
1757 }
1758
1759 if ((SegDesc[1] & (1 << 15)) == 0) /* not present */
1760 {
1761 KdbpPrint(" %03d 0x%04x %-11s [NP] [NP] %02d NP\n",
1762 i / 8, i | Dpl | ul, SegType, Dpl);
1763 }
1764 else
1765 {
1766 KdbpPrint(" %03d 0x%04x %-11s 0x%08x 0x%08x %02d ",
1767 i / 8, i | Dpl | ul, SegType, SegBase, SegLimit, Dpl);
1768
1769 if ((SegDesc[1] & (1 << 12)) == 0) /* System segment */
1770 {
1771 /* FIXME: Display system segment */
1772 }
1773 else if ((SegDesc[1] & (1 << 11)) == 0) /* Data segment */
1774 {
1775 if ((SegDesc[1] & (1 << 10)) != 0) /* Expand-down */
1776 KdbpPrint(" E");
1777
1778 KdbpPrint((SegDesc[1] & (1 << 9)) ? " R/W" : " R");
1779
1780 if ((SegDesc[1] & (1 << 8)) != 0)
1781 KdbpPrint(" A");
1782 }
1783 else /* Code segment */
1784 {
1785 if ((SegDesc[1] & (1 << 10)) != 0) /* Conforming */
1786 KdbpPrint(" C");
1787
1788 KdbpPrint((SegDesc[1] & (1 << 9)) ? " R/X" : " X");
1789
1790 if ((SegDesc[1] & (1 << 8)) != 0)
1791 KdbpPrint(" A");
1792 }
1793
1794 if ((SegDesc[1] & (1 << 20)) != 0)
1795 KdbpPrint(" AVL");
1796
1797 KdbpPrint("\n");
1798 }
1799 }
1800 }
1801
1802 return TRUE;
1803 }
1804
1805 /*!\brief Displays the KPCR
1806 */
1807 static BOOLEAN
1808 KdbpCmdPcr(
1809 ULONG Argc,
1810 PCHAR Argv[])
1811 {
1812 PKIPCR Pcr = (PKIPCR)KeGetPcr();
1813
1814 KdbpPrint("Current PCR is at 0x%08x.\n", (INT)Pcr);
1815 KdbpPrint(" Tib.ExceptionList: 0x%08x\n"
1816 " Tib.StackBase: 0x%08x\n"
1817 " Tib.StackLimit: 0x%08x\n"
1818 " Tib.SubSystemTib: 0x%08x\n"
1819 " Tib.FiberData/Version: 0x%08x\n"
1820 " Tib.ArbitraryUserPointer: 0x%08x\n"
1821 " Tib.Self: 0x%08x\n"
1822 " Self: 0x%08x\n"
1823 " PCRCB: 0x%08x\n"
1824 " Irql: 0x%02x\n"
1825 " IRR: 0x%08x\n"
1826 " IrrActive: 0x%08x\n"
1827 " IDR: 0x%08x\n"
1828 " KdVersionBlock: 0x%08x\n"
1829 " IDT: 0x%08x\n"
1830 " GDT: 0x%08x\n"
1831 " TSS: 0x%08x\n"
1832 " MajorVersion: 0x%04x\n"
1833 " MinorVersion: 0x%04x\n"
1834 " SetMember: 0x%08x\n"
1835 " StallScaleFactor: 0x%08x\n"
1836 " Number: 0x%02x\n"
1837 " L2CacheAssociativity: 0x%02x\n"
1838 " VdmAlert: 0x%08x\n"
1839 " L2CacheSize: 0x%08x\n"
1840 " InterruptMode: 0x%08x\n",
1841 Pcr->NtTib.ExceptionList, Pcr->NtTib.StackBase, Pcr->NtTib.StackLimit,
1842 Pcr->NtTib.SubSystemTib, Pcr->NtTib.FiberData, Pcr->NtTib.ArbitraryUserPointer,
1843 Pcr->NtTib.Self, Pcr->Self, Pcr->Prcb, Pcr->Irql, Pcr->IRR, Pcr->IrrActive,
1844 Pcr->IDR, Pcr->KdVersionBlock, Pcr->IDT, Pcr->GDT, Pcr->TSS,
1845 Pcr->MajorVersion, Pcr->MinorVersion, Pcr->SetMember, Pcr->StallScaleFactor,
1846 Pcr->Number, Pcr->SecondLevelCacheAssociativity,
1847 Pcr->VdmAlert, Pcr->SecondLevelCacheSize, Pcr->InterruptMode);
1848
1849 return TRUE;
1850 }
1851
1852 /*!\brief Displays the TSS
1853 */
1854 static BOOLEAN
1855 KdbpCmdTss(
1856 ULONG Argc,
1857 PCHAR Argv[])
1858 {
1859 KTSS *Tss = KeGetPcr()->TSS;
1860
1861 KdbpPrint("Current TSS is at 0x%08x.\n", (INT)Tss);
1862 KdbpPrint(" Eip: 0x%08x\n"
1863 " Es: 0x%04x\n"
1864 " Cs: 0x%04x\n"
1865 " Ss: 0x%04x\n"
1866 " Ds: 0x%04x\n"
1867 " Fs: 0x%04x\n"
1868 " Gs: 0x%04x\n"
1869 " IoMapBase: 0x%04x\n",
1870 Tss->Eip, Tss->Es, Tss->Cs, Tss->Ds, Tss->Fs, Tss->Gs, Tss->IoMapBase);
1871
1872 return TRUE;
1873 }
1874
1875 /*!\brief Bugchecks the system.
1876 */
1877 static BOOLEAN
1878 KdbpCmdBugCheck(
1879 ULONG Argc,
1880 PCHAR Argv[])
1881 {
1882 /* Set the flag and quit looping */
1883 KdbpBugCheckRequested = TRUE;
1884
1885 return FALSE;
1886 }
1887
1888 /*!\brief Sets or displays a config variables value.
1889 */
1890 static BOOLEAN
1891 KdbpCmdSet(
1892 ULONG Argc,
1893 PCHAR Argv[])
1894 {
1895 LONG l;
1896 BOOLEAN First;
1897 PCHAR pend = 0;
1898 KDB_ENTER_CONDITION ConditionFirst = KdbDoNotEnter;
1899 KDB_ENTER_CONDITION ConditionLast = KdbDoNotEnter;
1900
1901 static const PCHAR ExceptionNames[21] =
1902 {
1903 "ZERODEVIDE", "DEBUGTRAP", "NMI", "INT3", "OVERFLOW", "BOUND", "INVALIDOP",
1904 "NOMATHCOP", "DOUBLEFAULT", "RESERVED(9)", "INVALIDTSS", "SEGMENTNOTPRESENT",
1905 "STACKFAULT", "GPF", "PAGEFAULT", "RESERVED(15)", "MATHFAULT", "ALIGNMENTCHECK",
1906 "MACHINECHECK", "SIMDFAULT", "OTHERS"
1907 };
1908
1909 if (Argc == 1)
1910 {
1911 KdbpPrint("Available settings:\n");
1912 KdbpPrint(" syntax [intel|at&t]\n");
1913 KdbpPrint(" condition [exception|*] [first|last] [never|always|kmode|umode]\n");
1914 KdbpPrint(" break_on_module_load [true|false]\n");
1915 }
1916 else if (strcmp(Argv[1], "syntax") == 0)
1917 {
1918 if (Argc == 2)
1919 {
1920 KdbpPrint("syntax = %s\n", KdbUseIntelSyntax ? "intel" : "at&t");
1921 }
1922 else if (Argc >= 3)
1923 {
1924 if (_stricmp(Argv[2], "intel") == 0)
1925 KdbUseIntelSyntax = TRUE;
1926 else if (_stricmp(Argv[2], "at&t") == 0)
1927 KdbUseIntelSyntax = FALSE;
1928 else
1929 KdbpPrint("Unknown syntax '%s'.\n", Argv[2]);
1930 }
1931 }
1932 else if (strcmp(Argv[1], "condition") == 0)
1933 {
1934 if (Argc == 2)
1935 {
1936 KdbpPrint("Conditions: (First) (Last)\n");
1937 for (l = 0; l < RTL_NUMBER_OF(ExceptionNames) - 1; l++)
1938 {
1939 if (!ExceptionNames[l])
1940 continue;
1941
1942 if (!KdbpGetEnterCondition(l, TRUE, &ConditionFirst))
1943 ASSERT(0);
1944
1945 if (!KdbpGetEnterCondition(l, FALSE, &ConditionLast))
1946 ASSERT(0);
1947
1948 KdbpPrint(" #%02d %-20s %-8s %-8s\n", l, ExceptionNames[l],
1949 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst),
1950 KDB_ENTER_CONDITION_TO_STRING(ConditionLast));
1951 }
1952
1953 ASSERT(l == (RTL_NUMBER_OF(ExceptionNames) - 1));
1954 KdbpPrint(" %-20s %-8s %-8s\n", ExceptionNames[l],
1955 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst),
1956 KDB_ENTER_CONDITION_TO_STRING(ConditionLast));
1957 }
1958 else
1959 {
1960 if (Argc >= 5 && strcmp(Argv[2], "*") == 0) /* Allow * only when setting condition */
1961 {
1962 l = -1;
1963 }
1964 else
1965 {
1966 l = strtoul(Argv[2], &pend, 0);
1967
1968 if (Argv[2] == pend)
1969 {
1970 for (l = 0; l < RTL_NUMBER_OF(ExceptionNames); l++)
1971 {
1972 if (!ExceptionNames[l])
1973 continue;
1974
1975 if (_stricmp(ExceptionNames[l], Argv[2]) == 0)
1976 break;
1977 }
1978 }
1979
1980 if (l >= RTL_NUMBER_OF(ExceptionNames))
1981 {
1982 KdbpPrint("Unknown exception '%s'.\n", Argv[2]);
1983 return TRUE;
1984 }
1985 }
1986
1987 if (Argc > 4)
1988 {
1989 if (_stricmp(Argv[3], "first") == 0)
1990 First = TRUE;
1991 else if (_stricmp(Argv[3], "last") == 0)
1992 First = FALSE;
1993 else
1994 {
1995 KdbpPrint("set condition: second argument must be 'first' or 'last'\n");
1996 return TRUE;
1997 }
1998
1999 if (_stricmp(Argv[4], "never") == 0)
2000 ConditionFirst = KdbDoNotEnter;
2001 else if (_stricmp(Argv[4], "always") == 0)
2002 ConditionFirst = KdbEnterAlways;
2003 else if (_stricmp(Argv[4], "umode") == 0)
2004 ConditionFirst = KdbEnterFromUmode;
2005 else if (_stricmp(Argv[4], "kmode") == 0)
2006 ConditionFirst = KdbEnterFromKmode;
2007 else
2008 {
2009 KdbpPrint("set condition: third argument must be 'never', 'always', 'umode' or 'kmode'\n");
2010 return TRUE;
2011 }
2012
2013 if (!KdbpSetEnterCondition(l, First, ConditionFirst))
2014 {
2015 if (l >= 0)
2016 KdbpPrint("Couldn't change condition for exception #%02d\n", l);
2017 else
2018 KdbpPrint("Couldn't change condition for all exceptions\n", l);
2019 }
2020 }
2021 else /* Argc >= 3 */
2022 {
2023 if (!KdbpGetEnterCondition(l, TRUE, &ConditionFirst))
2024 ASSERT(0);
2025
2026 if (!KdbpGetEnterCondition(l, FALSE, &ConditionLast))
2027 ASSERT(0);
2028
2029 if (l < (RTL_NUMBER_OF(ExceptionNames) - 1))
2030 {
2031 KdbpPrint("Condition for exception #%02d (%s): FirstChance %s LastChance %s\n",
2032 l, ExceptionNames[l],
2033 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst),
2034 KDB_ENTER_CONDITION_TO_STRING(ConditionLast));
2035 }
2036 else
2037 {
2038 KdbpPrint("Condition for all other exceptions: FirstChance %s LastChance %s\n",
2039 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst),
2040 KDB_ENTER_CONDITION_TO_STRING(ConditionLast));
2041 }
2042 }
2043 }
2044 }
2045 else if (strcmp(Argv[1], "break_on_module_load") == 0)
2046 {
2047 if (Argc == 2)
2048 KdbpPrint("break_on_module_load = %s\n", KdbBreakOnModuleLoad ? "enabled" : "disabled");
2049 else if (Argc >= 3)
2050 {
2051 if (_stricmp(Argv[2], "enable") == 0 || _stricmp(Argv[2], "enabled") == 0 || _stricmp(Argv[2], "true") == 0)
2052 KdbBreakOnModuleLoad = TRUE;
2053 else if (_stricmp(Argv[2], "disable") == 0 || _stricmp(Argv[2], "disabled") == 0 || _stricmp(Argv[2], "false") == 0)
2054 KdbBreakOnModuleLoad = FALSE;
2055 else
2056 KdbpPrint("Unknown setting '%s'.\n", Argv[2]);
2057 }
2058 }
2059 else
2060 {
2061 KdbpPrint("Unknown setting '%s'.\n", Argv[1]);
2062 }
2063
2064 return TRUE;
2065 }
2066
2067 /*!\brief Displays help screen.
2068 */
2069 static BOOLEAN
2070 KdbpCmdHelp(
2071 ULONG Argc,
2072 PCHAR Argv[])
2073 {
2074 ULONG i;
2075
2076 KdbpPrint("Kernel debugger commands:\n");
2077 for (i = 0; i < RTL_NUMBER_OF(KdbDebuggerCommands); i++)
2078 {
2079 if (!KdbDebuggerCommands[i].Syntax) /* Command group */
2080 {
2081 if (i > 0)
2082 KdbpPrint("\n");
2083
2084 KdbpPrint("\x1b[7m* %s:\x1b[0m\n", KdbDebuggerCommands[i].Help);
2085 continue;
2086 }
2087
2088 KdbpPrint(" %-20s - %s\n",
2089 KdbDebuggerCommands[i].Syntax,
2090 KdbDebuggerCommands[i].Help);
2091 }
2092
2093 return TRUE;
2094 }
2095
2096 /*!\brief Prints the given string with printf-like formatting.
2097 *
2098 * \param Format Format of the string/arguments.
2099 * \param ... Variable number of arguments matching the format specified in \a Format.
2100 *
2101 * \note Doesn't correctly handle \\t and terminal escape sequences when calculating the
2102 * number of lines required to print a single line from the Buffer in the terminal.
2103 */
2104 VOID
2105 KdbpPrint(
2106 IN PCHAR Format,
2107 IN ... OPTIONAL)
2108 {
2109 static CHAR Buffer[4096];
2110 static BOOLEAN TerminalInitialized = FALSE;
2111 static BOOLEAN TerminalConnected = FALSE;
2112 static BOOLEAN TerminalReportsSize = TRUE;
2113 CHAR c = '\0';
2114 PCHAR p, p2;
2115 ULONG Length;
2116 ULONG i, j;
2117 LONG RowsPrintedByTerminal;
2118 ULONG ScanCode;
2119 va_list ap;
2120
2121 /* Check if the user has aborted output of the current command */
2122 if (KdbOutputAborted)
2123 return;
2124
2125 /* Initialize the terminal */
2126 if (!TerminalInitialized)
2127 {
2128 DbgPrint("\x1b[7h"); /* Enable linewrap */
2129
2130 /* Query terminal type */
2131 /*DbgPrint("\x1b[Z");*/
2132 DbgPrint("\x05");
2133
2134 TerminalInitialized = TRUE;
2135 Length = 0;
2136 KeStallExecutionProcessor(100000);
2137
2138 for (;;)
2139 {
2140 c = KdbpTryGetCharSerial(5000);
2141 if (c == -1)
2142 break;
2143
2144 Buffer[Length++] = c;
2145 if (Length >= (sizeof (Buffer) - 1))
2146 break;
2147 }
2148
2149 Buffer[Length] = '\0';
2150 if (Length > 0)
2151 TerminalConnected = TRUE;
2152 }
2153
2154 /* Get number of rows and columns in terminal */
2155 if ((KdbNumberOfRowsTerminal < 0) || (KdbNumberOfColsTerminal < 0) ||
2156 (KdbNumberOfRowsPrinted) == 0) /* Refresh terminal size each time when number of rows printed is 0 */
2157 {
2158 if ((KdbDebugState & KD_DEBUG_KDSERIAL) && TerminalConnected && TerminalReportsSize)
2159 {
2160 /* Try to query number of rows from terminal. A reply looks like "\x1b[8;24;80t" */
2161 TerminalReportsSize = FALSE;
2162 KeStallExecutionProcessor(100000);
2163 DbgPrint("\x1b[18t");
2164 c = KdbpTryGetCharSerial(5000);
2165
2166 if (c == KEY_ESC)
2167 {
2168 c = KdbpTryGetCharSerial(5000);
2169 if (c == '[')
2170 {
2171 Length = 0;
2172
2173 for (;;)
2174 {
2175 c = KdbpTryGetCharSerial(5000);
2176 if (c == -1)
2177 break;
2178
2179 Buffer[Length++] = c;
2180 if (isalpha(c) || Length >= (sizeof (Buffer) - 1))
2181 break;
2182 }
2183
2184 Buffer[Length] = '\0';
2185 if (Buffer[0] == '8' && Buffer[1] == ';')
2186 {
2187 for (i = 2; (i < Length) && (Buffer[i] != ';'); i++);
2188
2189 if (Buffer[i] == ';')
2190 {
2191 Buffer[i++] = '\0';
2192
2193 /* Number of rows is now at Buffer + 2 and number of cols at Buffer + i */
2194 KdbNumberOfRowsTerminal = strtoul(Buffer + 2, NULL, 0);
2195 KdbNumberOfColsTerminal = strtoul(Buffer + i, NULL, 0);
2196 TerminalReportsSize = TRUE;
2197 }
2198 }
2199 }
2200 /* Clear further characters */
2201 while ((c = KdbpTryGetCharSerial(5000)) != -1);
2202 }
2203 }
2204
2205 if (KdbNumberOfRowsTerminal <= 0)
2206 {
2207 /* Set number of rows to the default. */
2208 KdbNumberOfRowsTerminal = 24;
2209 }
2210 else if (KdbNumberOfColsTerminal <= 0)
2211 {
2212 /* Set number of cols to the default. */
2213 KdbNumberOfColsTerminal = 80;
2214 }
2215 }
2216
2217 /* Get the string */
2218 va_start(ap, Format);
2219 Length = _vsnprintf(Buffer, sizeof (Buffer) - 1, Format, ap);
2220 Buffer[Length] = '\0';
2221 va_end(ap);
2222
2223 p = Buffer;
2224 while (p[0] != '\0')
2225 {
2226 i = strcspn(p, "\n");
2227
2228 /* Calculate the number of lines which will be printed in the terminal
2229 * when outputting the current line
2230 */
2231 if (i > 0)
2232 RowsPrintedByTerminal = (i + KdbNumberOfColsPrinted - 1) / KdbNumberOfColsTerminal;
2233 else
2234 RowsPrintedByTerminal = 0;
2235
2236 if (p[i] == '\n')
2237 RowsPrintedByTerminal++;
2238
2239 /*DbgPrint("!%d!%d!%d!%d!", KdbNumberOfRowsPrinted, KdbNumberOfColsPrinted, i, RowsPrintedByTerminal);*/
2240
2241 /* Display a prompt if we printed one screen full of text */
2242 if (KdbNumberOfRowsTerminal > 0 &&
2243 (LONG)(KdbNumberOfRowsPrinted + RowsPrintedByTerminal) >= KdbNumberOfRowsTerminal)
2244 {
2245 if (KdbNumberOfColsPrinted > 0)
2246 DbgPrint("\n");
2247
2248 DbgPrint("--- Press q to abort, any other key to continue ---");
2249
2250 if (KdbDebugState & KD_DEBUG_KDSERIAL)
2251 c = KdbpGetCharSerial();
2252 else
2253 c = KdbpGetCharKeyboard(&ScanCode);
2254
2255 if (c == '\r')
2256 {
2257 /* Try to read '\n' which might follow '\r' - if \n is not received here
2258 * it will be interpreted as "return" when the next command should be read.
2259 */
2260 if (KdbDebugState & KD_DEBUG_KDSERIAL)
2261 c = KdbpTryGetCharSerial(5);
2262 else
2263 c = KdbpTryGetCharKeyboard(&ScanCode, 5);
2264 }
2265
2266 DbgPrint("\n");
2267 if (c == 'q')
2268 {
2269 KdbOutputAborted = TRUE;
2270 return;
2271 }
2272
2273 KdbNumberOfRowsPrinted = 0;
2274 KdbNumberOfColsPrinted = 0;
2275 }
2276
2277 /* Insert a NUL after the line and print only the current line. */
2278 if (p[i] == '\n' && p[i + 1] != '\0')
2279 {
2280 c = p[i + 1];
2281 p[i + 1] = '\0';
2282 }
2283 else
2284 {
2285 c = '\0';
2286 }
2287
2288 /* Remove escape sequences from the line if there's no terminal connected */
2289 if (!TerminalConnected)
2290 {
2291 while ((p2 = strrchr(p, '\x1b'))) /* Look for escape character */
2292 {
2293 if (p2[1] == '[')
2294 {
2295 j = 2;
2296 while (!isalpha(p2[j++]));
2297 strcpy(p2, p2 + j);
2298 }
2299 else
2300 {
2301 strcpy(p2, p2 + 1);
2302 }
2303 }
2304 }
2305
2306 DbgPrint("%s", p);
2307
2308 if (c != '\0')
2309 p[i + 1] = c;
2310
2311 /* Set p to the start of the next line and
2312 * remember the number of rows/cols printed
2313 */
2314 p += i;
2315 if (p[0] == '\n')
2316 {
2317 p++;
2318 KdbNumberOfColsPrinted = 0;
2319 }
2320 else
2321 {
2322 ASSERT(p[0] == '\0');
2323 KdbNumberOfColsPrinted += i;
2324 }
2325
2326 KdbNumberOfRowsPrinted += RowsPrintedByTerminal;
2327 }
2328 }
2329
2330 /*!\brief Appends a command to the command history
2331 *
2332 * \param Command Pointer to the command to append to the history.
2333 */
2334 static VOID
2335 KdbpCommandHistoryAppend(
2336 IN PCHAR Command)
2337 {
2338 ULONG Length1 = strlen(Command) + 1;
2339 ULONG Length2 = 0;
2340 INT i;
2341 PCHAR Buffer;
2342
2343 ASSERT(Length1 <= RTL_NUMBER_OF(KdbCommandHistoryBuffer));
2344
2345 if (Length1 <= 1 ||
2346 (KdbCommandHistory[KdbCommandHistoryIndex] &&
2347 strcmp(KdbCommandHistory[KdbCommandHistoryIndex], Command) == 0))
2348 {
2349 return;
2350 }
2351
2352 /* Calculate Length1 and Length2 */
2353 Buffer = KdbCommandHistoryBuffer + KdbCommandHistoryBufferIndex;
2354 KdbCommandHistoryBufferIndex += Length1;
2355 if (KdbCommandHistoryBufferIndex >= (LONG)RTL_NUMBER_OF(KdbCommandHistoryBuffer))
2356 {
2357 KdbCommandHistoryBufferIndex -= RTL_NUMBER_OF(KdbCommandHistoryBuffer);
2358 Length2 = KdbCommandHistoryBufferIndex;
2359 Length1 -= Length2;
2360 }
2361
2362 /* Remove previous commands until there is enough space to append the new command */
2363 for (i = KdbCommandHistoryIndex; KdbCommandHistory[i];)
2364 {
2365 if ((Length2 > 0 &&
2366 (KdbCommandHistory[i] >= Buffer ||
2367 KdbCommandHistory[i] < (KdbCommandHistoryBuffer + KdbCommandHistoryBufferIndex))) ||
2368 (Length2 <= 0 &&
2369 (KdbCommandHistory[i] >= Buffer &&
2370 KdbCommandHistory[i] < (KdbCommandHistoryBuffer + KdbCommandHistoryBufferIndex))))
2371 {
2372 KdbCommandHistory[i] = NULL;
2373 }
2374
2375 i--;
2376 if (i < 0)
2377 i = RTL_NUMBER_OF(KdbCommandHistory) - 1;
2378
2379 if (i == KdbCommandHistoryIndex)
2380 break;
2381 }
2382
2383 /* Make sure the new command history entry is free */
2384 KdbCommandHistoryIndex++;
2385 KdbCommandHistoryIndex %= RTL_NUMBER_OF(KdbCommandHistory);
2386 if (KdbCommandHistory[KdbCommandHistoryIndex])
2387 {
2388 KdbCommandHistory[KdbCommandHistoryIndex] = NULL;
2389 }
2390
2391 /* Append command */
2392 KdbCommandHistory[KdbCommandHistoryIndex] = Buffer;
2393 ASSERT((KdbCommandHistory[KdbCommandHistoryIndex] + Length1) <= KdbCommandHistoryBuffer + RTL_NUMBER_OF(KdbCommandHistoryBuffer));
2394 memcpy(KdbCommandHistory[KdbCommandHistoryIndex], Command, Length1);
2395 if (Length2 > 0)
2396 {
2397 memcpy(KdbCommandHistoryBuffer, Command + Length1, Length2);
2398 }
2399 }
2400
2401 /*!\brief Reads a line of user-input.
2402 *
2403 * \param Buffer Buffer to store the input into. Trailing newlines are removed.
2404 * \param Size Size of \a Buffer.
2405 *
2406 * \note Accepts only \n newlines, \r is ignored.
2407 */
2408 static VOID
2409 KdbpReadCommand(
2410 OUT PCHAR Buffer,
2411 IN ULONG Size)
2412 {
2413 CHAR Key;
2414 PCHAR Orig = Buffer;
2415 ULONG ScanCode = 0;
2416 BOOLEAN EchoOn;
2417 static CHAR LastCommand[1024] = "";
2418 static CHAR NextKey = '\0';
2419 INT CmdHistIndex = -1;
2420 INT i;
2421
2422 EchoOn = !((KdbDebugState & KD_DEBUG_KDNOECHO) != 0);
2423
2424 for (;;)
2425 {
2426 if (KdbDebugState & KD_DEBUG_KDSERIAL)
2427 {
2428 Key = (NextKey == '\0') ? KdbpGetCharSerial() : NextKey;
2429 NextKey = '\0';
2430 ScanCode = 0;
2431 if (Key == KEY_ESC) /* ESC */
2432 {
2433 Key = KdbpGetCharSerial();
2434 if (Key == '[')
2435 {
2436 Key = KdbpGetCharSerial();
2437
2438 switch (Key)
2439 {
2440 case 'A':
2441 ScanCode = KEY_SCAN_UP;
2442 break;
2443 case 'B':
2444 ScanCode = KEY_SCAN_DOWN;
2445 break;
2446 case 'C':
2447 break;
2448 case 'D':
2449 break;
2450 }
2451 }
2452 }
2453 }
2454 else
2455 {
2456 ScanCode = 0;
2457 Key = (NextKey == '\0') ? KdbpGetCharKeyboard(&ScanCode) : NextKey;
2458 NextKey = '\0';
2459 }
2460
2461 if ((ULONG)(Buffer - Orig) >= (Size - 1))
2462 {
2463 /* Buffer is full, accept only newlines */
2464 if (Key != '\n')
2465 continue;
2466 }
2467
2468 if (Key == '\r')
2469 {
2470 /* Read the next char - this is to throw away a \n which most clients should
2471 * send after \r.
2472 */
2473 KeStallExecutionProcessor(100000);
2474
2475 if (KdbDebugState & KD_DEBUG_KDSERIAL)
2476 NextKey = KdbpTryGetCharSerial(5);
2477 else
2478 NextKey = KdbpTryGetCharKeyboard(&ScanCode, 5);
2479
2480 if (NextKey == '\n' || NextKey == -1) /* \n or no response at all */
2481 NextKey = '\0';
2482
2483 KdbpPrint("\n");
2484
2485 /*
2486 * Repeat the last command if the user presses enter. Reduces the
2487 * risk of RSI when single-stepping.
2488 */
2489 if (Buffer == Orig)
2490 {
2491 strncpy(Buffer, LastCommand, Size);
2492 Buffer[Size - 1] = '\0';
2493 }
2494 else
2495 {
2496 *Buffer = '\0';
2497 strncpy(LastCommand, Orig, sizeof (LastCommand));
2498 LastCommand[sizeof (LastCommand) - 1] = '\0';
2499 }
2500
2501 return;
2502 }
2503 else if (Key == KEY_BS || Key == KEY_DEL)
2504 {
2505 if (Buffer > Orig)
2506 {
2507 Buffer--;
2508 *Buffer = 0;
2509
2510 if (EchoOn)
2511 KdbpPrint("%c %c", KEY_BS, KEY_BS);
2512 else
2513 KdbpPrint(" %c", KEY_BS);
2514 }
2515 }
2516 else if (ScanCode == KEY_SCAN_UP)
2517 {
2518 BOOLEAN Print = TRUE;
2519
2520 if (CmdHistIndex < 0)
2521 {
2522 CmdHistIndex = KdbCommandHistoryIndex;
2523 }
2524 else
2525 {
2526 i = CmdHistIndex - 1;
2527
2528 if (i < 0)
2529 CmdHistIndex = RTL_NUMBER_OF(KdbCommandHistory) - 1;
2530
2531 if (KdbCommandHistory[i] && i != KdbCommandHistoryIndex)
2532 CmdHistIndex = i;
2533 else
2534 Print = FALSE;
2535 }
2536
2537 if (Print && KdbCommandHistory[CmdHistIndex])
2538 {
2539 while (Buffer > Orig)
2540 {
2541 Buffer--;
2542 *Buffer = 0;
2543
2544 if (EchoOn)
2545 KdbpPrint("%c %c", KEY_BS, KEY_BS);
2546 else
2547 KdbpPrint(" %c", KEY_BS);
2548 }
2549
2550 i = min(strlen(KdbCommandHistory[CmdHistIndex]), Size - 1);
2551 memcpy(Orig, KdbCommandHistory[CmdHistIndex], i);
2552 Orig[i] = '\0';
2553 Buffer = Orig + i;
2554 KdbpPrint("%s", Orig);
2555 }
2556 }
2557 else if (ScanCode == KEY_SCAN_DOWN)
2558 {
2559 if (CmdHistIndex > 0 && CmdHistIndex != KdbCommandHistoryIndex)
2560 {
2561 i = CmdHistIndex + 1;
2562 if (i >= (INT)RTL_NUMBER_OF(KdbCommandHistory))
2563 i = 0;
2564
2565 if (KdbCommandHistory[i])
2566 {
2567 CmdHistIndex = i;
2568 while (Buffer > Orig)
2569 {
2570 Buffer--;
2571 *Buffer = 0;
2572
2573 if (EchoOn)
2574 KdbpPrint("%c %c", KEY_BS, KEY_BS);
2575 else
2576 KdbpPrint(" %c", KEY_BS);
2577 }
2578
2579 i = min(strlen(KdbCommandHistory[CmdHistIndex]), Size - 1);
2580 memcpy(Orig, KdbCommandHistory[CmdHistIndex], i);
2581 Orig[i] = '\0';
2582 Buffer = Orig + i;
2583 KdbpPrint("%s", Orig);
2584 }
2585 }
2586 }
2587 else
2588 {
2589 if (EchoOn)
2590 KdbpPrint("%c", Key);
2591
2592 *Buffer = Key;
2593 Buffer++;
2594 }
2595 }
2596 }
2597
2598 /*!\brief Parses command line and executes command if found
2599 *
2600 * \param Command Command line to parse and execute if possible.
2601 *
2602 * \retval TRUE Don't continue execution.
2603 * \retval FALSE Continue execution (leave KDB)
2604 */
2605 static BOOLEAN
2606 KdbpDoCommand(
2607 IN PCHAR Command)
2608 {
2609 ULONG i;
2610 PCHAR p;
2611 ULONG Argc;
2612 static PCH Argv[256];
2613 static CHAR OrigCommand[1024];
2614
2615 strncpy(OrigCommand, Command, sizeof(OrigCommand) - 1);
2616 OrigCommand[sizeof(OrigCommand) - 1] = '\0';
2617
2618 Argc = 0;
2619 p = Command;
2620
2621 for (;;)
2622 {
2623 while (*p == '\t' || *p == ' ')
2624 p++;
2625
2626 if (*p == '\0')
2627 break;
2628
2629 i = strcspn(p, "\t ");
2630 Argv[Argc++] = p;
2631 p += i;
2632 if (*p == '\0')
2633 break;
2634
2635 *p = '\0';
2636 p++;
2637 }
2638
2639 if (Argc < 1)
2640 return TRUE;
2641
2642 for (i = 0; i < RTL_NUMBER_OF(KdbDebuggerCommands); i++)
2643 {
2644 if (!KdbDebuggerCommands[i].Name)
2645 continue;
2646
2647 if (strcmp(KdbDebuggerCommands[i].Name, Argv[0]) == 0)
2648 {
2649 return KdbDebuggerCommands[i].Fn(Argc, Argv);
2650 }
2651 }
2652
2653 KdbpPrint("Command '%s' is unknown.\n", OrigCommand);
2654 return TRUE;
2655 }
2656
2657 /*!\brief KDB Main Loop.
2658 *
2659 * \param EnteredOnSingleStep TRUE if KDB was entered on single step.
2660 */
2661 VOID
2662 KdbpCliMainLoop(
2663 IN BOOLEAN EnteredOnSingleStep)
2664 {
2665 static CHAR Command[1024];
2666 BOOLEAN Continue;
2667
2668 if (EnteredOnSingleStep)
2669 {
2670 if (!KdbSymPrintAddress((PVOID)KdbCurrentTrapFrame->Tf.Eip))
2671 {
2672 KdbpPrint("<%x>", KdbCurrentTrapFrame->Tf.Eip);
2673 }
2674
2675 KdbpPrint(": ");
2676 if (KdbpDisassemble(KdbCurrentTrapFrame->Tf.Eip, KdbUseIntelSyntax) < 0)
2677 {
2678 KdbpPrint("<INVALID>");
2679 }
2680 KdbpPrint("\n");
2681 }
2682
2683 /* Flush the input buffer */
2684 if (KdbDebugState & KD_DEBUG_KDSERIAL)
2685 {
2686 while (KdbpTryGetCharSerial(1) != -1);
2687 }
2688 else
2689 {
2690 ULONG ScanCode;
2691 while (KdbpTryGetCharKeyboard(&ScanCode, 1) != -1);
2692 }
2693
2694 /* Main loop */
2695 do
2696 {
2697 /* Print the prompt */
2698 KdbpPrint("kdb:> ");
2699
2700 /* Read a command and remember it */
2701 KdbpReadCommand(Command, sizeof (Command));
2702 KdbpCommandHistoryAppend(Command);
2703
2704 /* Reset the number of rows/cols printed and output aborted state */
2705 KdbNumberOfRowsPrinted = KdbNumberOfColsPrinted = 0;
2706 KdbOutputAborted = FALSE;
2707
2708 /* Call the command */
2709 Continue = KdbpDoCommand(Command);
2710 }
2711 while (Continue);
2712 }
2713
2714 /*!\brief Called when a module is loaded.
2715 *
2716 * \param Name Filename of the module which was loaded.
2717 */
2718 VOID
2719 KdbpCliModuleLoaded(
2720 IN PUNICODE_STRING Name)
2721 {
2722 if (!KdbBreakOnModuleLoad)
2723 return;
2724
2725 KdbpPrint("Module %wZ loaded.\n", Name);
2726 DbgBreakPointWithStatus(DBG_STATUS_CONTROL_C);
2727 }
2728
2729 /*!\brief This function is called by KdbEnterDebuggerException...
2730 *
2731 * Used to interpret the init file in a context with a trapframe setup
2732 * (KdbpCliInit call KdbEnter which will call KdbEnterDebuggerException which will
2733 * call this function if KdbInitFileBuffer is not NULL.
2734 */
2735 VOID
2736 KdbpCliInterpretInitFile()
2737 {
2738 PCHAR p1, p2;
2739 INT i;
2740 CHAR c;
2741
2742 /* Execute the commands in the init file */
2743 DPRINT("KDB: Executing KDBinit file...\n");
2744 p1 = KdbInitFileBuffer;
2745 while (p1[0] != '\0')
2746 {
2747 i = strcspn(p1, "\r\n");
2748 if (i > 0)
2749 {
2750 c = p1[i];
2751 p1[i] = '\0';
2752
2753 /* Look for "break" command and comments */
2754 p2 = p1;
2755
2756 while (isspace(p2[0]))
2757 p2++;
2758
2759 if (strncmp(p2, "break", sizeof("break")-1) == 0 &&
2760 (p2[sizeof("break")-1] == '\0' || isspace(p2[sizeof("break")-1])))
2761 {
2762 /* break into the debugger */
2763 KdbpCliMainLoop(FALSE);
2764 }
2765 else if (p2[0] != '#' && p2[0] != '\0') /* Ignore empty lines and comments */
2766 {
2767 KdbpDoCommand(p1);
2768 }
2769
2770 p1[i] = c;
2771 }
2772
2773 p1 += i;
2774 while (p1[0] == '\r' || p1[0] == '\n')
2775 p1++;
2776 }
2777 DPRINT("KDB: KDBinit executed\n");
2778 }
2779
2780 /*!\brief Called when KDB is initialized
2781 *
2782 * Reads the KDBinit file from the SystemRoot\system32\drivers\etc directory and executes it.
2783 */
2784 VOID
2785 KdbpCliInit()
2786 {
2787 NTSTATUS Status;
2788 OBJECT_ATTRIBUTES ObjectAttributes;
2789 UNICODE_STRING FileName;
2790 IO_STATUS_BLOCK Iosb;
2791 FILE_STANDARD_INFORMATION FileStdInfo;
2792 HANDLE hFile = NULL;
2793 INT FileSize;
2794 PCHAR FileBuffer;
2795 ULONG OldEflags;
2796
2797 /* Initialize the object attributes */
2798 RtlInitUnicodeString(&FileName, L"\\SystemRoot\\system32\\drivers\\etc\\KDBinit");
2799 InitializeObjectAttributes(&ObjectAttributes, &FileName, 0, NULL, NULL);
2800
2801 /* Open the file */
2802 Status = ZwOpenFile(&hFile, FILE_READ_DATA, &ObjectAttributes, &Iosb, 0,
2803 FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT |
2804 FILE_NO_INTERMEDIATE_BUFFERING);
2805 if (!NT_SUCCESS(Status))
2806 {
2807 DPRINT("Could not open \\SystemRoot\\system32\\drivers\\etc\\KDBinit (Status 0x%x)", Status);
2808 return;
2809 }
2810
2811 /* Get the size of the file */
2812 Status = ZwQueryInformationFile(hFile, &Iosb, &FileStdInfo, sizeof (FileStdInfo),
2813 FileStandardInformation);
2814 if (!NT_SUCCESS(Status))
2815 {
2816 ZwClose(hFile);
2817 DPRINT("Could not query size of \\SystemRoot\\system32\\drivers\\etc\\KDBinit (Status 0x%x)", Status);
2818 return;
2819 }
2820 FileSize = FileStdInfo.EndOfFile.u.LowPart;
2821
2822 /* Allocate memory for the file */
2823 FileBuffer = ExAllocatePool(PagedPool, FileSize + 1); /* add 1 byte for terminating '\0' */
2824 if (!FileBuffer)
2825 {
2826 ZwClose(hFile);
2827 DPRINT("Could not allocate %d bytes for KDBinit file\n", FileSize);
2828 return;
2829 }
2830
2831 /* Load file into memory */
2832 Status = ZwReadFile(hFile, 0, 0, 0, &Iosb, FileBuffer, FileSize, 0, 0);
2833 ZwClose(hFile);
2834
2835 if (!NT_SUCCESS(Status) && Status != STATUS_END_OF_FILE)
2836 {
2837 ExFreePool(FileBuffer);
2838 DPRINT("Could not read KDBinit file into memory (Status 0x%lx)\n", Status);
2839 return;
2840 }
2841
2842 FileSize = min(FileSize, (INT)Iosb.Information);
2843 FileBuffer[FileSize] = '\0';
2844
2845 /* Enter critical section */
2846 OldEflags = __readeflags();
2847 _disable();
2848
2849 /* Interpret the init file... */
2850 KdbInitFileBuffer = FileBuffer;
2851 KdbEnter();
2852 KdbInitFileBuffer = NULL;
2853
2854 /* Leave critical section */
2855 __writeeflags(OldEflags);
2856
2857 ExFreePool(FileBuffer);
2858 }
2859
2860 VOID
2861 NTAPI
2862 KdpSerialDebugPrint(
2863 LPSTR Message,
2864 ULONG Length
2865 );
2866
2867 STRING KdpPromptString = RTL_CONSTANT_STRING("kdb:> ");
2868 extern KSPIN_LOCK KdpSerialSpinLock;
2869
2870 ULONG
2871 NTAPI
2872 KdpPrompt(IN LPSTR InString,
2873 IN USHORT InStringLength,
2874 OUT LPSTR OutString,
2875 IN USHORT OutStringLength)
2876 {
2877 USHORT i;
2878 CHAR Response;
2879 ULONG DummyScanCode;
2880 KIRQL OldIrql;
2881
2882 /* Acquire the printing spinlock without waiting at raised IRQL */
2883 while (TRUE)
2884 {
2885 /* Wait when the spinlock becomes available */
2886 while (!KeTestSpinLock(&KdpSerialSpinLock));
2887
2888 /* Spinlock was free, raise IRQL */
2889 KeRaiseIrql(HIGH_LEVEL, &OldIrql);
2890
2891 /* Try to get the spinlock */
2892 if (KeTryToAcquireSpinLockAtDpcLevel(&KdpSerialSpinLock))
2893 break;
2894
2895 /* Someone else got the spinlock, lower IRQL back */
2896 KeLowerIrql(OldIrql);
2897 }
2898
2899 /* Loop the string to send */
2900 for (i = 0; i < InStringLength; i++)
2901 {
2902 /* Print it to serial */
2903 KdPortPutByteEx(&SerialPortInfo, *(PCHAR)(InString + i));
2904 }
2905
2906 /* Print a new line for log neatness */
2907 KdPortPutByteEx(&SerialPortInfo, '\r');
2908 KdPortPutByteEx(&SerialPortInfo, '\n');
2909
2910 /* Print the kdb prompt */
2911 for (i = 0; i < KdpPromptString.Length; i++)
2912 {
2913 /* Print it to serial */
2914 KdPortPutByteEx(&SerialPortInfo,
2915 *(KdpPromptString.Buffer + i));
2916 }
2917
2918 /* Loop the whole string */
2919 for (i = 0; i < OutStringLength; i++)
2920 {
2921 /* Check if this is serial debugging mode */
2922 if (KdbDebugState & KD_DEBUG_KDSERIAL)
2923 {
2924 /* Get the character from serial */
2925 do
2926 {
2927 Response = KdbpTryGetCharSerial(MAXULONG);
2928 } while (Response == -1);
2929 }
2930 else
2931 {
2932 /* Get the response from the keyboard */
2933 do
2934 {
2935 Response = KdbpTryGetCharKeyboard(&DummyScanCode, MAXULONG);
2936 } while (Response == -1);
2937 }
2938
2939 /* Check for return */
2940 if (Response == '\r')
2941 {
2942 /*
2943 * We might need to discard the next '\n'.
2944 * Wait a bit to make sure we receive it.
2945 */
2946 KeStallExecutionProcessor(100000);
2947
2948 /* Check the mode */
2949 if (KdbDebugState & KD_DEBUG_KDSERIAL)
2950 {
2951 /* Read and discard the next character, if any */
2952 KdbpTryGetCharSerial(5);
2953 }
2954 else
2955 {
2956 /* Read and discard the next character, if any */
2957 KdbpTryGetCharKeyboard(&DummyScanCode, 5);
2958 }
2959
2960 /*
2961 * Null terminate the output string -- documentation states that
2962 * DbgPrompt does not null terminate, but it does
2963 */
2964 *(PCHAR)(OutString + i) = 0;
2965
2966 /* Print a new line */
2967 KdPortPutByteEx(&SerialPortInfo, '\r');
2968 KdPortPutByteEx(&SerialPortInfo, '\n');
2969
2970 /* Release spinlock */
2971 KiReleaseSpinLock(&KdpSerialSpinLock);
2972
2973 /* Lower IRQL back */
2974 KeLowerIrql(OldIrql);
2975
2976 /* Return the length */
2977 return OutStringLength + 1;
2978 }
2979
2980 /* Write it back and print it to the log */
2981 *(PCHAR)(OutString + i) = Response;
2982 KdPortPutByteEx(&SerialPortInfo, Response);
2983 }
2984
2985 /* Print a new line */
2986 KdPortPutByteEx(&SerialPortInfo, '\r');
2987 KdPortPutByteEx(&SerialPortInfo, '\n');
2988
2989 /* Release spinlock */
2990 KiReleaseSpinLock(&KdpSerialSpinLock);
2991
2992 /* Lower IRQL back */
2993 KeLowerIrql(OldIrql);
2994
2995 /* Return the length */
2996 return OutStringLength;
2997 }