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