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