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