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