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