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