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