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