3 * Copyright (C) 2005 ReactOS Team
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.
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.
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.
20 * PROJECT: ReactOS kernel
21 * FILE: ntoskrnl/kdbg/kdb_cli.c
22 * PURPOSE: Kernel debugger command line interface
23 * PROGRAMMER: Gregor Anich (blight@blight.eu.org)
29 /* INCLUDES ******************************************************************/
36 /* DEFINES *******************************************************************/
42 #define KEY_SCAN_UP 72
43 #define KEY_SCAN_DOWN 80
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
52 #define KDB_ENTER_CONDITION_TO_STRING(cond) \
53 ((cond) == KdbDoNotEnter ? "never" : \
54 ((cond) == KdbEnterAlways ? "always" : \
55 ((cond) == KdbEnterFromKmode ? "kmode" : "umode")))
57 #define KDB_ACCESS_TYPE_TO_STRING(type) \
58 ((type) == KdbAccessRead ? "read" : \
59 ((type) == KdbAccessWrite ? "write" : \
60 ((type) == KdbAccessReadWrite ? "rdwr" : "exec")))
62 #define NPX_STATE_TO_STRING(state) \
63 ((state) == NPX_STATE_LOADED ? "Loaded" : \
64 ((state) == NPX_STATE_NOT_LOADED ? "Not loaded" : "Unknown"))
66 /* PROTOTYPES ****************************************************************/
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
[]);
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
[]);
79 static BOOLEAN
KdbpCmdThread(ULONG Argc
, PCHAR Argv
[]);
80 static BOOLEAN
KdbpCmdProc(ULONG Argc
, PCHAR Argv
[]);
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
[]);
87 static BOOLEAN
KdbpCmdBugCheck(ULONG Argc
, PCHAR Argv
[]);
88 static BOOLEAN
KdbpCmdReboot(ULONG Argc
, PCHAR Argv
[]);
89 static BOOLEAN
KdbpCmdFilter(ULONG Argc
, PCHAR Argv
[]);
90 static BOOLEAN
KdbpCmdSet(ULONG Argc
, PCHAR Argv
[]);
91 static BOOLEAN
KdbpCmdHelp(ULONG Argc
, PCHAR Argv
[]);
92 static BOOLEAN
KdbpCmdDmesg(ULONG Argc
, PCHAR Argv
[]);
94 BOOLEAN
ExpKdbgExtPool(ULONG Argc
, PCHAR Argv
[]);
95 BOOLEAN
ExpKdbgExtPoolUsed(ULONG Argc
, PCHAR Argv
[]);
96 BOOLEAN
ExpKdbgExtFileCache(ULONG Argc
, PCHAR Argv
[]);
99 static BOOLEAN
KdbpCmdPrintStruct(ULONG Argc
, PCHAR Argv
[]);
102 /* GLOBALS *******************************************************************/
104 static PKDBG_CLI_ROUTINE KdbCliCallbacks
[10];
105 static BOOLEAN KdbUseIntelSyntax
= FALSE
; /* Set to TRUE for intel syntax */
106 static BOOLEAN KdbBreakOnModuleLoad
= FALSE
; /* Set to TRUE to break into KDB when a module is loaded */
108 static CHAR KdbCommandHistoryBuffer
[2048]; /* Command history string ringbuffer */
109 static PCHAR KdbCommandHistory
[sizeof(KdbCommandHistoryBuffer
) / 8] = { NULL
}; /* Command history ringbuffer */
110 static LONG KdbCommandHistoryBufferIndex
= 0;
111 static LONG KdbCommandHistoryIndex
= 0;
113 static ULONG KdbNumberOfRowsPrinted
= 0;
114 static ULONG KdbNumberOfColsPrinted
= 0;
115 static BOOLEAN KdbOutputAborted
= FALSE
;
116 static BOOLEAN KdbRepeatLastCommand
= FALSE
;
117 static LONG KdbNumberOfRowsTerminal
= -1;
118 static LONG KdbNumberOfColsTerminal
= -1;
120 PCHAR KdbInitFileBuffer
= NULL
; /* Buffer where KDBinit file is loaded into during initialization */
121 BOOLEAN KdbpBugCheckRequested
= FALSE
;
124 /* defined in ../kd/kdio.c, declare here: */
125 extern volatile BOOLEAN KdbpIsInDmesgMode
;
126 extern const ULONG KdpDmesgBufferSize
;
127 extern PCHAR KdpDmesgBuffer
;
128 extern volatile ULONG KdpDmesgCurrentPosition
;
129 extern volatile ULONG KdpDmesgFreeBytes
;
130 extern volatile ULONG KdbDmesgTotalWritten
;
137 BOOLEAN (*Fn
)(ULONG Argc
, PCHAR Argv
[]);
138 } KdbDebuggerCommands
[] = {
140 { NULL
, NULL
, "Data", NULL
},
141 { "?", "? expression", "Evaluate expression.", KdbpCmdEvalExpression
},
142 { "disasm", "disasm [address] [L count]", "Disassemble count instructions at address.", KdbpCmdDisassembleX
},
143 { "x", "x [address] [L count]", "Display count dwords, starting at addr.", KdbpCmdDisassembleX
},
144 { "regs", "regs", "Display general purpose registers.", KdbpCmdRegs
},
145 { "cregs", "cregs", "Display control registers.", KdbpCmdRegs
},
146 { "sregs", "sregs", "Display status registers.", KdbpCmdRegs
},
147 { "dregs", "dregs", "Display debug registers.", KdbpCmdRegs
},
148 { "bt", "bt [*frameaddr|thread id]", "Prints current backtrace or from given frame addr", KdbpCmdBackTrace
},
150 { "dt", "dt [mod] [type] [addr]", "Print a struct. Addr is optional.", KdbpCmdPrintStruct
},
154 { NULL
, NULL
, "Flow control", NULL
},
155 { "cont", "cont", "Continue execution (leave debugger)", KdbpCmdContinue
},
156 { "step", "step [count]", "Execute single instructions, stepping into interrupts.", KdbpCmdStep
},
157 { "next", "next [count]", "Execute single instructions, skipping calls and reps.", KdbpCmdStep
},
158 { "bl", "bl", "List breakpoints.", KdbpCmdBreakPointList
},
159 { "be", "be [breakpoint]", "Enable breakpoint.", KdbpCmdEnableDisableClearBreakPoint
},
160 { "bd", "bd [breakpoint]", "Disable breakpoint.", KdbpCmdEnableDisableClearBreakPoint
},
161 { "bc", "bc [breakpoint]", "Clear breakpoint.", KdbpCmdEnableDisableClearBreakPoint
},
162 { "bpx", "bpx [address] [IF condition]", "Set software execution breakpoint at address.", KdbpCmdBreakPoint
},
163 { "bpm", "bpm [r|w|rw|x] [byte|word|dword] [address] [IF condition]", "Set memory breakpoint at address.", KdbpCmdBreakPoint
},
166 { NULL
, NULL
, "Process/Thread", NULL
},
167 { "thread", "thread [list[ pid]|[attach ]tid]", "List threads in current or specified process, display thread with given id or attach to thread.", KdbpCmdThread
},
168 { "proc", "proc [list|[attach ]pid]", "List processes, display process with given id or attach to process.", KdbpCmdProc
},
170 /* System information */
171 { NULL
, NULL
, "System info", NULL
},
172 { "mod", "mod [address]", "List all modules or the one containing address.", KdbpCmdMod
},
173 { "gdt", "gdt", "Display global descriptor table.", KdbpCmdGdtLdtIdt
},
174 { "ldt", "ldt", "Display local descriptor table.", KdbpCmdGdtLdtIdt
},
175 { "idt", "idt", "Display interrupt descriptor table.", KdbpCmdGdtLdtIdt
},
176 { "pcr", "pcr", "Display processor control region.", KdbpCmdPcr
},
177 { "tss", "tss", "Display task state segment.", KdbpCmdTss
},
180 { NULL
, NULL
, "Others", NULL
},
181 { "bugcheck", "bugcheck", "Bugchecks the system.", KdbpCmdBugCheck
},
182 { "reboot", "reboot", "Reboots the system.", KdbpCmdReboot
},
183 { "filter", "filter [error|warning|trace|info|level]+|-[componentname|default]", "Enable/disable debug channels", KdbpCmdFilter
},
184 { "set", "set [var] [value]", "Sets var to value or displays value of var.", KdbpCmdSet
},
185 { "dmesg", "dmesg", "Display debug messages on screen, with navigation on pages.", KdbpCmdDmesg
},
186 { "kmsg", "kmsg", "Kernel dmesg. Alias for dmesg.", KdbpCmdDmesg
},
187 { "help", "help", "Display help screen.", KdbpCmdHelp
},
188 { "!pool", "!pool [Address [Flags]]", "Display information about pool allocations.", ExpKdbgExtPool
},
189 { "!poolused", "!poolused [Flags [Tag]]", "Display pool usage.", ExpKdbgExtPoolUsed
},
190 { "!filecache", "!filecache", "Display cache usage.", ExpKdbgExtFileCache
},
193 /* FUNCTIONS *****************************************************************/
195 /*!\brief Transform a component name to an integer
197 * \param ComponentName The name of the component.
198 * \param ComponentId Receives the component id on success.
200 * \retval TRUE Success.
201 * \retval FALSE Failure.
205 IN PCCH ComponentName
,
206 OUT PULONG ComponentId
)
217 { "DEFAULT", MAXULONG
},
218 { "SYSTEM", DPFLTR_SYSTEM_ID
},
219 { "SMSS", DPFLTR_SMSS_ID
},
220 { "SETUP", DPFLTR_SETUP_ID
},
221 { "NTFS", DPFLTR_NTFS_ID
},
222 { "FSTUB", DPFLTR_FSTUB_ID
},
223 { "CRASHDUMP", DPFLTR_CRASHDUMP_ID
},
224 { "CDAUDIO", DPFLTR_CDAUDIO_ID
},
225 { "CDROM", DPFLTR_CDROM_ID
},
226 { "CLASSPNP", DPFLTR_CLASSPNP_ID
},
227 { "DISK", DPFLTR_DISK_ID
},
228 { "REDBOOK", DPFLTR_REDBOOK_ID
},
229 { "STORPROP", DPFLTR_STORPROP_ID
},
230 { "SCSIPORT", DPFLTR_SCSIPORT_ID
},
231 { "SCSIMINIPORT", DPFLTR_SCSIMINIPORT_ID
},
232 { "CONFIG", DPFLTR_CONFIG_ID
},
233 { "I8042PRT", DPFLTR_I8042PRT_ID
},
234 { "SERMOUSE", DPFLTR_SERMOUSE_ID
},
235 { "LSERMOUS", DPFLTR_LSERMOUS_ID
},
236 { "KBDHID", DPFLTR_KBDHID_ID
},
237 { "MOUHID", DPFLTR_MOUHID_ID
},
238 { "KBDCLASS", DPFLTR_KBDCLASS_ID
},
239 { "MOUCLASS", DPFLTR_MOUCLASS_ID
},
240 { "TWOTRACK", DPFLTR_TWOTRACK_ID
},
241 { "WMILIB", DPFLTR_WMILIB_ID
},
242 { "ACPI", DPFLTR_ACPI_ID
},
243 { "AMLI", DPFLTR_AMLI_ID
},
244 { "HALIA64", DPFLTR_HALIA64_ID
},
245 { "VIDEO", DPFLTR_VIDEO_ID
},
246 { "SVCHOST", DPFLTR_SVCHOST_ID
},
247 { "VIDEOPRT", DPFLTR_VIDEOPRT_ID
},
248 { "TCPIP", DPFLTR_TCPIP_ID
},
249 { "DMSYNTH", DPFLTR_DMSYNTH_ID
},
250 { "NTOSPNP", DPFLTR_NTOSPNP_ID
},
251 { "FASTFAT", DPFLTR_FASTFAT_ID
},
252 { "SAMSS", DPFLTR_SAMSS_ID
},
253 { "PNPMGR", DPFLTR_PNPMGR_ID
},
254 { "NETAPI", DPFLTR_NETAPI_ID
},
255 { "SCSERVER", DPFLTR_SCSERVER_ID
},
256 { "SCCLIENT", DPFLTR_SCCLIENT_ID
},
257 { "SERIAL", DPFLTR_SERIAL_ID
},
258 { "SERENUM", DPFLTR_SERENUM_ID
},
259 { "UHCD", DPFLTR_UHCD_ID
},
260 { "RPCPROXY", DPFLTR_RPCPROXY_ID
},
261 { "AUTOCHK", DPFLTR_AUTOCHK_ID
},
262 { "DCOMSS", DPFLTR_DCOMSS_ID
},
263 { "UNIMODEM", DPFLTR_UNIMODEM_ID
},
264 { "SIS", DPFLTR_SIS_ID
},
265 { "FLTMGR", DPFLTR_FLTMGR_ID
},
266 { "WMICORE", DPFLTR_WMICORE_ID
},
267 { "BURNENG", DPFLTR_BURNENG_ID
},
268 { "IMAPI", DPFLTR_IMAPI_ID
},
269 { "SXS", DPFLTR_SXS_ID
},
270 { "FUSION", DPFLTR_FUSION_ID
},
271 { "IDLETASK", DPFLTR_IDLETASK_ID
},
272 { "SOFTPCI", DPFLTR_SOFTPCI_ID
},
273 { "TAPE", DPFLTR_TAPE_ID
},
274 { "MCHGR", DPFLTR_MCHGR_ID
},
275 { "IDEP", DPFLTR_IDEP_ID
},
276 { "PCIIDE", DPFLTR_PCIIDE_ID
},
277 { "FLOPPY", DPFLTR_FLOPPY_ID
},
278 { "FDC", DPFLTR_FDC_ID
},
279 { "TERMSRV", DPFLTR_TERMSRV_ID
},
280 { "W32TIME", DPFLTR_W32TIME_ID
},
281 { "PREFETCHER", DPFLTR_PREFETCHER_ID
},
282 { "RSFILTER", DPFLTR_RSFILTER_ID
},
283 { "FCPORT", DPFLTR_FCPORT_ID
},
284 { "PCI", DPFLTR_PCI_ID
},
285 { "DMIO", DPFLTR_DMIO_ID
},
286 { "DMCONFIG", DPFLTR_DMCONFIG_ID
},
287 { "DMADMIN", DPFLTR_DMADMIN_ID
},
288 { "WSOCKTRANSPORT", DPFLTR_WSOCKTRANSPORT_ID
},
289 { "VSS", DPFLTR_VSS_ID
},
290 { "PNPMEM", DPFLTR_PNPMEM_ID
},
291 { "PROCESSOR", DPFLTR_PROCESSOR_ID
},
292 { "DMSERVER", DPFLTR_DMSERVER_ID
},
293 { "SR", DPFLTR_SR_ID
},
294 { "INFINIBAND", DPFLTR_INFINIBAND_ID
},
295 { "IHVDRIVER", DPFLTR_IHVDRIVER_ID
},
296 { "IHVVIDEO", DPFLTR_IHVVIDEO_ID
},
297 { "IHVAUDIO", DPFLTR_IHVAUDIO_ID
},
298 { "IHVNETWORK", DPFLTR_IHVNETWORK_ID
},
299 { "IHVSTREAMING", DPFLTR_IHVSTREAMING_ID
},
300 { "IHVBUS", DPFLTR_IHVBUS_ID
},
301 { "HPS", DPFLTR_HPS_ID
},
302 { "RTLTHREADPOOL", DPFLTR_RTLTHREADPOOL_ID
},
303 { "LDR", DPFLTR_LDR_ID
},
304 { "TCPIP6", DPFLTR_TCPIP6_ID
},
305 { "ISAPNP", DPFLTR_ISAPNP_ID
},
306 { "SHPC", DPFLTR_SHPC_ID
},
307 { "STORPORT", DPFLTR_STORPORT_ID
},
308 { "STORMINIPORT", DPFLTR_STORMINIPORT_ID
},
309 { "PRINTSPOOLER", DPFLTR_PRINTSPOOLER_ID
},
310 { "VSSDYNDISK", DPFLTR_VSSDYNDISK_ID
},
311 { "VERIFIER", DPFLTR_VERIFIER_ID
},
312 { "VDS", DPFLTR_VDS_ID
},
313 { "VDSBAS", DPFLTR_VDSBAS_ID
},
314 { "VDSDYN", DPFLTR_VDSDYN_ID
},
315 { "VDSDYNDR", DPFLTR_VDSDYNDR_ID
},
316 { "VDSLDR", DPFLTR_VDSLDR_ID
},
317 { "VDSUTIL", DPFLTR_VDSUTIL_ID
},
318 { "DFRGIFC", DPFLTR_DFRGIFC_ID
},
319 { "MM", DPFLTR_MM_ID
},
320 { "DFSC", DPFLTR_DFSC_ID
},
321 { "WOW64", DPFLTR_WOW64_ID
},
322 { "ALPC", DPFLTR_ALPC_ID
},
323 { "WDI", DPFLTR_WDI_ID
},
324 { "PERFLIB", DPFLTR_PERFLIB_ID
},
325 { "KTM", DPFLTR_KTM_ID
},
326 { "IOSTRESS", DPFLTR_IOSTRESS_ID
},
327 { "HEAP", DPFLTR_HEAP_ID
},
328 { "WHEA", DPFLTR_WHEA_ID
},
329 { "USERGDI", DPFLTR_USERGDI_ID
},
330 { "MMCSS", DPFLTR_MMCSS_ID
},
331 { "TPM", DPFLTR_TPM_ID
},
332 { "THREADORDER", DPFLTR_THREADORDER_ID
},
333 { "ENVIRON", DPFLTR_ENVIRON_ID
},
334 { "EMS", DPFLTR_EMS_ID
},
335 { "WDT", DPFLTR_WDT_ID
},
336 { "FVEVOL", DPFLTR_FVEVOL_ID
},
337 { "NDIS", DPFLTR_NDIS_ID
},
338 { "NVCTRACE", DPFLTR_NVCTRACE_ID
},
339 { "LUAFV", DPFLTR_LUAFV_ID
},
340 { "APPCOMPAT", DPFLTR_APPCOMPAT_ID
},
341 { "USBSTOR", DPFLTR_USBSTOR_ID
},
342 { "SBP2PORT", DPFLTR_SBP2PORT_ID
},
343 { "COVERAGE", DPFLTR_COVERAGE_ID
},
344 { "CACHEMGR", DPFLTR_CACHEMGR_ID
},
345 { "MOUNTMGR", DPFLTR_MOUNTMGR_ID
},
346 { "CFR", DPFLTR_CFR_ID
},
347 { "TXF", DPFLTR_TXF_ID
},
348 { "KSECDD", DPFLTR_KSECDD_ID
},
349 { "FLTREGRESS", DPFLTR_FLTREGRESS_ID
},
350 { "MPIO", DPFLTR_MPIO_ID
},
351 { "MSDSM", DPFLTR_MSDSM_ID
},
352 { "UDFS", DPFLTR_UDFS_ID
},
353 { "PSHED", DPFLTR_PSHED_ID
},
354 { "STORVSP", DPFLTR_STORVSP_ID
},
355 { "LSASS", DPFLTR_LSASS_ID
},
356 { "SSPICLI", DPFLTR_SSPICLI_ID
},
357 { "CNG", DPFLTR_CNG_ID
},
358 { "EXFAT", DPFLTR_EXFAT_ID
},
359 { "FILETRACE", DPFLTR_FILETRACE_ID
},
360 { "XSAVE", DPFLTR_XSAVE_ID
},
361 { "SE", DPFLTR_SE_ID
},
362 { "DRIVEEXTENDER", DPFLTR_DRIVEEXTENDER_ID
},
365 for (i
= 0; i
< sizeof(ComponentTable
) / sizeof(ComponentTable
[0]); i
++)
367 if (_stricmp(ComponentName
, ComponentTable
[i
].Name
) == 0)
369 *ComponentId
= ComponentTable
[i
].Id
;
377 /*!\brief Evaluates an expression...
379 * Much like KdbpRpnEvaluateExpression, but prints the error message (if any)
380 * at the given offset.
382 * \param Expression Expression to evaluate.
383 * \param ErrOffset Offset (in characters) to print the error message at.
384 * \param Result Receives the result on success.
386 * \retval TRUE Success.
387 * \retval FALSE Failure.
390 KdbpEvaluateExpression(
393 OUT PULONGLONG Result
)
395 static CHAR ErrMsgBuffer
[130] = "^ ";
396 LONG ExpressionErrOffset
= -1;
397 PCHAR ErrMsg
= ErrMsgBuffer
;
400 Ok
= KdbpRpnEvaluateExpression(Expression
, KdbCurrentTrapFrame
, Result
,
401 &ExpressionErrOffset
, ErrMsgBuffer
+ 2);
404 if (ExpressionErrOffset
>= 0)
405 ExpressionErrOffset
+= ErrOffset
;
409 KdbpPrint("%*s%s\n", ExpressionErrOffset
, "", ErrMsg
);
419 OUT ULONG_PTR
*pulValue
)
423 /* Skip optional '0x' prefix */
424 if ((pszNum
[0] == '0') && ((pszNum
[1] == 'x') || (pszNum
[1] == 'X')))
427 /* Make a number from the string (hex) */
428 *pulValue
= strtoul(pszNum
, &endptr
, 16);
430 return (*endptr
== '\0');
433 /*!\brief Evaluates an expression and displays the result.
436 KdbpCmdEvalExpression(
441 ULONGLONG Result
= 0;
448 KdbpPrint("?: Argument required\n");
452 /* Put the arguments back together */
454 for (i
= 1; i
< Argc
; i
++)
456 len
= strlen(Argv
[i
]);
460 /* Evaluate the expression */
461 Ok
= KdbpEvaluateExpression(Argv
[1], sizeof("kdb:> ")-1 + (Argv
[1]-Argv
[0]), &Result
);
464 if (Result
> 0x00000000ffffffffLL
)
466 if (Result
& 0x8000000000000000LL
)
467 KdbpPrint("0x%016I64x %20I64u %20I64d\n", Result
, Result
, Result
);
469 KdbpPrint("0x%016I64x %20I64u\n", Result
, Result
);
475 if (ul
<= 0xff && ul
>= 0x80)
476 l
= (LONG
)((CHAR
)ul
);
477 else if (ul
<= 0xffff && ul
>= 0x8000)
478 l
= (LONG
)((SHORT
)ul
);
483 KdbpPrint("0x%08lx %10lu %10ld\n", ul
, ul
, l
);
485 KdbpPrint("0x%08lx %10lu\n", ul
, ul
);
494 /*!\brief Print a struct
497 KdbpPrintStructInternal
502 PROSSYM_AGGREGATE Aggregate
)
506 PROSSYM_AGGREGATE_MEMBER Member
;
507 ULONG IndentLen
= strlen(Indent
);
508 ROSSYM_AGGREGATE MemberAggregate
= {0 };
510 for (i
= 0; i
< Aggregate
->NumElements
; i
++) {
511 Member
= &Aggregate
->Elements
[i
];
512 KdbpPrint("%s%p+%x: %s", Indent
, ((PCHAR
)BaseAddress
) + Member
->BaseOffset
, Member
->Size
, Member
->Name
? Member
->Name
: "<anoymous>");
514 if (!strcmp(Member
->Type
, "_UNICODE_STRING")) {
515 KdbpPrint("\"%wZ\"\n", ((PCHAR
)BaseAddress
) + Member
->BaseOffset
);
517 } else if (!strcmp(Member
->Type
, "PUNICODE_STRING")) {
518 KdbpPrint("\"%wZ\"\n", *(((PUNICODE_STRING
*)((PCHAR
)BaseAddress
) + Member
->BaseOffset
)));
521 switch (Member
->Size
) {
527 if (NT_SUCCESS(KdbpSafeReadMemory(&Result
, ((PCHAR
)BaseAddress
) + Member
->BaseOffset
, Member
->Size
))) {
529 Result
>>= Member
->FirstBit
;
530 Result
&= ((1 << Member
->Bits
) - 1);
532 KdbpPrint(" %lx\n", Result
);
538 if (Member
->Size
< 8) {
539 if (NT_SUCCESS(KdbpSafeReadMemory(&Result
, ((PCHAR
)BaseAddress
) + Member
->BaseOffset
, Member
->Size
))) {
541 for (j
= 0; j
< Member
->Size
; j
++) {
542 KdbpPrint(" %02x", (int)(Result
& 0xff));
545 } else goto readfail
;
547 KdbpPrint(" %s @ %p {\n", Member
->Type
, ((PCHAR
)BaseAddress
) + Member
->BaseOffset
);
548 Indent
[IndentLen
] = ' ';
549 if (RosSymAggregate(Info
, Member
->Type
, &MemberAggregate
)) {
550 KdbpPrintStructInternal(Info
, Indent
, DoRead
, ((PCHAR
)BaseAddress
) + Member
->BaseOffset
, &MemberAggregate
);
551 RosSymFreeAggregate(&MemberAggregate
);
553 Indent
[IndentLen
] = 0;
554 KdbpPrint("%s}\n", Indent
);
560 if (Member
->Size
<= 8) {
563 KdbpPrint(" %s @ %x {\n", Member
->Type
, Member
->BaseOffset
);
564 Indent
[IndentLen
] = ' ';
565 if (RosSymAggregate(Info
, Member
->Type
, &MemberAggregate
)) {
566 KdbpPrintStructInternal(Info
, Indent
, DoRead
, BaseAddress
, &MemberAggregate
);
567 RosSymFreeAggregate(&MemberAggregate
);
569 Indent
[IndentLen
] = 0;
570 KdbpPrint("%s}\n", Indent
);
576 PROSSYM_INFO
KdbpSymFindCachedFile(PUNICODE_STRING ModName
);
584 ULONGLONG Result
= 0;
585 PVOID BaseAddress
= 0;
586 ROSSYM_AGGREGATE Aggregate
= {0};
587 UNICODE_STRING ModName
= {0};
588 ANSI_STRING AnsiName
= {0};
589 CHAR Indent
[100] = {0};
592 if (Argc
< 3) goto end
;
593 AnsiName
.Length
= AnsiName
.MaximumLength
= strlen(Argv
[1]);
594 AnsiName
.Buffer
= Argv
[1];
595 RtlAnsiStringToUnicodeString(&ModName
, &AnsiName
, TRUE
);
596 Info
= KdbpSymFindCachedFile(&ModName
);
598 if (!Info
|| !RosSymAggregate(Info
, Argv
[2], &Aggregate
)) {
599 DPRINT1("Could not get aggregate\n");
603 // Get an argument for location if it was given
606 PCHAR ArgStart
= Argv
[3];
607 DPRINT1("Trying to get expression\n");
608 for (i
= 3; i
< Argc
- 1; i
++)
610 len
= strlen(Argv
[i
]);
614 /* Evaluate the expression */
615 DPRINT1("Arg: %s\n", ArgStart
);
616 if (KdbpEvaluateExpression(ArgStart
, strlen(ArgStart
), &Result
)) {
617 BaseAddress
= (PVOID
)(ULONG_PTR
)Result
;
618 DPRINT1("BaseAddress: %p\n", BaseAddress
);
621 DPRINT1("BaseAddress %p\n", BaseAddress
);
622 KdbpPrintStructInternal(Info
, Indent
, !!BaseAddress
, BaseAddress
, &Aggregate
);
624 RosSymFreeAggregate(&Aggregate
);
625 RtlFreeUnicodeString(&ModName
);
630 /*!\brief Display list of active debug channels
637 ULONG i
, j
, ComponentId
, Level
;
638 ULONG set
= DPFLTR_MASK
, clear
= DPFLTR_MASK
;
649 { "error", 1 << DPFLTR_ERROR_LEVEL
},
650 { "warning", 1 << DPFLTR_WARNING_LEVEL
},
651 { "trace", 1 << DPFLTR_TRACE_LEVEL
},
652 { "info", 1 << DPFLTR_INFO_LEVEL
},
655 for (i
= 1; i
< Argc
; i
++)
658 p
= opt
+ strcspn(opt
, "+-");
659 if (!p
[0]) p
= opt
; /* assume it's a debug channel name */
663 for (j
= 0; j
< sizeof(debug_classes
) / sizeof(debug_classes
[0]); j
++)
665 SIZE_T len
= strlen(debug_classes
[j
].Name
);
666 if (len
!= (p
- opt
))
668 if (_strnicmp(opt
, debug_classes
[j
].Name
, len
) == 0) /* found it */
671 set
|= debug_classes
[j
].Level
;
673 clear
|= debug_classes
[j
].Level
;
677 if (j
== sizeof(debug_classes
) / sizeof(debug_classes
[0]))
679 Level
= strtoul(opt
, &pend
, 0);
682 KdbpPrint("filter: bad class name '%.*s'\n", p
- opt
, opt
);
698 if (*p
== '+' || *p
== '-')
701 if (!KdbpGetComponentId(p
, &ComponentId
))
703 KdbpPrint("filter: '%s' is not a valid component name!\n", p
);
707 /* Get current mask value */
708 NtSetDebugFilterState(ComponentId
, set
, TRUE
);
709 NtSetDebugFilterState(ComponentId
, clear
, FALSE
);
715 /*!\brief Disassembles 10 instructions at eip or given address or
716 * displays 16 dwords from memory at given address.
726 ULONGLONG Result
= 0;
727 ULONG_PTR Address
= KdbCurrentTrapFrame
->Tf
.Eip
;
730 if (Argv
[0][0] == 'x') /* display memory */
732 else /* disassemble */
737 /* Check for [L count] part */
739 if (strcmp(Argv
[Argc
-2], "L") == 0)
741 ul
= strtoul(Argv
[Argc
-1], NULL
, 0);
748 else if (Argv
[Argc
-1][0] == 'L')
750 ul
= strtoul(Argv
[Argc
-1] + 1, NULL
, 0);
758 /* Put the remaining arguments back together */
760 for (ul
= 1; ul
< Argc
; ul
++)
762 Argv
[ul
][strlen(Argv
[ul
])] = ' ';
767 /* Evaluate the expression */
770 if (!KdbpEvaluateExpression(Argv
[1], sizeof("kdb:> ")-1 + (Argv
[1]-Argv
[0]), &Result
))
773 if (Result
> (ULONGLONG
)(~((ULONG_PTR
)0)))
774 KdbpPrint("Warning: Address %I64x is beeing truncated\n",Result
);
776 Address
= (ULONG_PTR
)Result
;
778 else if (Argv
[0][0] == 'x')
780 KdbpPrint("x: Address argument required.\n");
784 if (Argv
[0][0] == 'x')
791 if (!KdbSymPrintAddress((PVOID
)Address
, NULL
))
792 KdbpPrint("<%x>:", Address
);
801 if (!NT_SUCCESS(KdbpSafeReadMemory(&ul
, (PVOID
)Address
, sizeof(ul
))))
802 KdbpPrint(" ????????");
804 KdbpPrint(" %08x", ul
);
806 Address
+= sizeof(ul
);
817 if (!KdbSymPrintAddress((PVOID
)Address
, NULL
))
818 KdbpPrint("<%08x>: ", Address
);
822 InstLen
= KdbpDisassemble(Address
, KdbUseIntelSyntax
);
825 KdbpPrint("<INVALID>\n");
837 /*!\brief Displays CPU registers.
844 PKTRAP_FRAME Tf
= &KdbCurrentTrapFrame
->Tf
;
846 static const PCHAR EflagsBits
[32] = { " CF", NULL
, " PF", " BIT3", " AF", " BIT5",
847 " ZF", " SF", " TF", " IF", " DF", " OF",
848 NULL
, NULL
, " NT", " BIT15", " RF", " VF",
849 " AC", " VIF", " VIP", " ID", " BIT22",
850 " BIT23", " BIT24", " BIT25", " BIT26",
851 " BIT27", " BIT28", " BIT29", " BIT30",
854 if (Argv
[0][0] == 'r') /* regs */
856 KdbpPrint("CS:EIP 0x%04x:0x%08x\n"
857 "SS:ESP 0x%04x:0x%08x\n"
858 " EAX 0x%08x EBX 0x%08x\n"
859 " ECX 0x%08x EDX 0x%08x\n"
860 " ESI 0x%08x EDI 0x%08x\n"
862 Tf
->SegCs
& 0xFFFF, Tf
->Eip
,
863 Tf
->HardwareSegSs
, Tf
->HardwareEsp
,
868 KdbpPrint("EFLAGS 0x%08x ", Tf
->EFlags
);
870 for (i
= 0; i
< 32; i
++)
874 if ((Tf
->EFlags
& (1 << 1)) == 0)
879 KdbpPrint(" IOPL%d", (Tf
->EFlags
>> 12) & 3);
884 else if ((Tf
->EFlags
& (1 << i
)) != 0)
886 KdbpPrint(EflagsBits
[i
]);
892 else if (Argv
[0][0] == 'c') /* cregs */
894 ULONG Cr0
, Cr2
, Cr3
, Cr4
;
895 KDESCRIPTOR Gdtr
= {0, 0, 0}, Idtr
= {0, 0, 0};
897 static const PCHAR Cr0Bits
[32] = { " PE", " MP", " EM", " TS", " ET", " NE", NULL
, NULL
,
898 NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
,
899 " WP", NULL
, " AM", NULL
, NULL
, NULL
, NULL
, NULL
,
900 NULL
, NULL
, NULL
, NULL
, NULL
, " NW", " CD", " PG" };
901 static const PCHAR Cr4Bits
[32] = { " VME", " PVI", " TSD", " DE", " PSE", " PAE", " MCE", " PGE",
902 " PCE", " OSFXSR", " OSXMMEXCPT", NULL
, NULL
, NULL
, NULL
, NULL
,
903 NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
,
904 NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
};
906 Cr0
= KdbCurrentTrapFrame
->Cr0
;
907 Cr2
= KdbCurrentTrapFrame
->Cr2
;
908 Cr3
= KdbCurrentTrapFrame
->Cr3
;
909 Cr4
= KdbCurrentTrapFrame
->Cr4
;
911 /* Get descriptor table regs */
912 Ke386GetGlobalDescriptorTable(&Gdtr
.Limit
);
913 Ldtr
= Ke386GetLocalDescriptorTable();
916 /* Display the control registers */
917 KdbpPrint("CR0 0x%08x ", Cr0
);
919 for (i
= 0; i
< 32; i
++)
924 if ((Cr0
& (1 << i
)) != 0)
925 KdbpPrint(Cr0Bits
[i
]);
928 KdbpPrint("\nCR2 0x%08x\n", Cr2
);
929 KdbpPrint("CR3 0x%08x Pagedir-Base 0x%08x %s%s\n", Cr3
, (Cr3
& 0xfffff000),
930 (Cr3
& (1 << 3)) ? " PWT" : "", (Cr3
& (1 << 4)) ? " PCD" : "" );
931 KdbpPrint("CR4 0x%08x ", Cr4
);
933 for (i
= 0; i
< 32; i
++)
938 if ((Cr4
& (1 << i
)) != 0)
939 KdbpPrint(Cr4Bits
[i
]);
942 /* Display the descriptor table regs */
943 KdbpPrint("\nGDTR Base 0x%08x Size 0x%04x\n", Gdtr
.Base
, Gdtr
.Limit
);
944 KdbpPrint("LDTR 0x%04x\n", Ldtr
);
945 KdbpPrint("IDTR Base 0x%08x Size 0x%04x\n", Idtr
.Base
, Idtr
.Limit
);
947 else if (Argv
[0][0] == 's') /* sregs */
949 KdbpPrint("CS 0x%04x Index 0x%04x %cDT RPL%d\n",
950 Tf
->SegCs
& 0xffff, (Tf
->SegCs
& 0xffff) >> 3,
951 (Tf
->SegCs
& (1 << 2)) ? 'L' : 'G', Tf
->SegCs
& 3);
952 KdbpPrint("DS 0x%04x Index 0x%04x %cDT RPL%d\n",
953 Tf
->SegDs
, Tf
->SegDs
>> 3, (Tf
->SegDs
& (1 << 2)) ? 'L' : 'G', Tf
->SegDs
& 3);
954 KdbpPrint("ES 0x%04x Index 0x%04x %cDT RPL%d\n",
955 Tf
->SegEs
, Tf
->SegEs
>> 3, (Tf
->SegEs
& (1 << 2)) ? 'L' : 'G', Tf
->SegEs
& 3);
956 KdbpPrint("FS 0x%04x Index 0x%04x %cDT RPL%d\n",
957 Tf
->SegFs
, Tf
->SegFs
>> 3, (Tf
->SegFs
& (1 << 2)) ? 'L' : 'G', Tf
->SegFs
& 3);
958 KdbpPrint("GS 0x%04x Index 0x%04x %cDT RPL%d\n",
959 Tf
->SegGs
, Tf
->SegGs
>> 3, (Tf
->SegGs
& (1 << 2)) ? 'L' : 'G', Tf
->SegGs
& 3);
960 KdbpPrint("SS 0x%04x Index 0x%04x %cDT RPL%d\n",
961 Tf
->HardwareSegSs
, Tf
->HardwareSegSs
>> 3, (Tf
->HardwareSegSs
& (1 << 2)) ? 'L' : 'G', Tf
->HardwareSegSs
& 3);
965 ASSERT(Argv
[0][0] == 'd');
966 KdbpPrint("DR0 0x%08x\n"
972 Tf
->Dr0
, Tf
->Dr1
, Tf
->Dr2
, Tf
->Dr3
,
980 KdbpTrapFrameFromPrevTss(
981 PKTRAP_FRAME TrapFrame
)
989 Ke386GetGlobalDescriptorTable(&Gdtr
.Limit
);
992 if ((Sel
& (sizeof(KGDTENTRY
) - 1)) ||
993 (Sel
< sizeof(KGDTENTRY
)) ||
994 (Sel
+ sizeof(KGDTENTRY
) - 1 > Gdtr
.Limit
))
997 if (!NT_SUCCESS(KdbpSafeReadMemory(&Desc
,
998 (PVOID
)(Gdtr
.Base
+ Sel
),
1002 if (Desc
.HighWord
.Bits
.Type
!= 0xB)
1005 Tss
= (PKTSS
)(ULONG_PTR
)(Desc
.BaseLow
|
1006 Desc
.HighWord
.Bytes
.BaseMid
<< 16 |
1007 Desc
.HighWord
.Bytes
.BaseHi
<< 24);
1009 if (!NT_SUCCESS(KdbpSafeReadMemory(&Sel
,
1010 (PVOID
)&Tss
->Backlink
,
1014 if ((Sel
& (sizeof(KGDTENTRY
) - 1)) ||
1015 (Sel
< sizeof(KGDTENTRY
)) ||
1016 (Sel
+ sizeof(KGDTENTRY
) - 1 > Gdtr
.Limit
))
1019 if (!NT_SUCCESS(KdbpSafeReadMemory(&Desc
,
1020 (PVOID
)(Gdtr
.Base
+ Sel
),
1021 sizeof(KGDTENTRY
))))
1024 if (Desc
.HighWord
.Bits
.Type
!= 0xB)
1027 Tss
= (PKTSS
)(ULONG_PTR
)(Desc
.BaseLow
|
1028 Desc
.HighWord
.Bytes
.BaseMid
<< 16 |
1029 Desc
.HighWord
.Bytes
.BaseHi
<< 24);
1031 if (!NT_SUCCESS(KdbpSafeReadMemory(&Eip
,
1033 sizeof(ULONG_PTR
))))
1036 if (!NT_SUCCESS(KdbpSafeReadMemory(&Ebp
,
1038 sizeof(ULONG_PTR
))))
1041 TrapFrame
->Eip
= Eip
;
1042 TrapFrame
->Ebp
= Ebp
;
1046 VOID __cdecl
KiTrap02(VOID
);
1047 VOID FASTCALL
KiTrap03Handler(IN PKTRAP_FRAME
);
1048 VOID __cdecl
KiTrap08(VOID
);
1049 VOID __cdecl
KiTrap09(VOID
);
1052 KdbpInNmiOrDoubleFaultHandler(
1055 return (Address
> (ULONG_PTR
)KiTrap02
&& Address
< (ULONG_PTR
)KiTrap03Handler
) ||
1056 (Address
> (ULONG_PTR
)KiTrap08
&& Address
< (ULONG_PTR
)KiTrap09
);
1059 /*!\brief Displays a backtrace.
1067 ULONGLONG Result
= 0;
1068 ULONG_PTR Frame
= KdbCurrentTrapFrame
->Tf
.Ebp
;
1070 KTRAP_FRAME TrapFrame
;
1074 /* Check for [L count] part */
1077 if (strcmp(Argv
[Argc
-2], "L") == 0)
1079 ul
= strtoul(Argv
[Argc
-1], NULL
, 0);
1085 else if (Argv
[Argc
-1][0] == 'L')
1087 ul
= strtoul(Argv
[Argc
-1] + 1, NULL
, 0);
1094 /* Put the remaining arguments back together */
1096 for (ul
= 1; ul
< Argc
; ul
++)
1098 Argv
[ul
][strlen(Argv
[ul
])] = ' ';
1103 /* Check if frame addr or thread id is given. */
1106 if (Argv
[1][0] == '*')
1110 /* Evaluate the expression */
1111 if (!KdbpEvaluateExpression(Argv
[1], sizeof("kdb:> ")-1 + (Argv
[1]-Argv
[0]), &Result
))
1114 if (Result
> (ULONGLONG
)(~((ULONG_PTR
)0)))
1115 KdbpPrint("Warning: Address %I64x is beeing truncated\n",Result
);
1117 Frame
= (ULONG_PTR
)Result
;
1121 KdbpPrint("Thread backtrace not supported yet!\n");
1127 KdbpPrint("Eip:\n");
1129 /* Try printing the function at EIP */
1130 if (!KdbSymPrintAddress((PVOID
)KdbCurrentTrapFrame
->Tf
.Eip
, &KdbCurrentTrapFrame
->Tf
))
1131 KdbpPrint("<%08x>\n", KdbCurrentTrapFrame
->Tf
.Eip
);
1136 TrapFrame
= KdbCurrentTrapFrame
->Tf
;
1137 KdbpPrint("Frames:\n");
1141 BOOLEAN GotNextFrame
;
1146 if (!NT_SUCCESS(KdbpSafeReadMemory(&Address
, (PVOID
)(Frame
+ sizeof(ULONG_PTR
)), sizeof (ULONG_PTR
))))
1148 KdbpPrint("Couldn't access memory at 0x%p!\n", Frame
+ sizeof(ULONG_PTR
));
1152 if ((GotNextFrame
= NT_SUCCESS(KdbpSafeReadMemory(&Frame
, (PVOID
)Frame
, sizeof (ULONG_PTR
)))))
1153 TrapFrame
.Ebp
= Frame
;
1155 /* Print the location of the call instruction */
1156 if (!KdbSymPrintAddress((PVOID
)(Address
- 5), &TrapFrame
))
1157 KdbpPrint("<%08x>\n", Address
);
1161 if (KdbOutputAborted
) break;
1166 if (KdbpInNmiOrDoubleFaultHandler(Address
))
1168 if ((GotNextFrame
= KdbpTrapFrameFromPrevTss(&TrapFrame
)))
1170 Address
= TrapFrame
.Eip
;
1171 Frame
= TrapFrame
.Ebp
;
1173 if (!KdbSymPrintAddress((PVOID
)Address
, &TrapFrame
))
1174 KdbpPrint("<%08x>\n", Address
);
1182 KdbpPrint("Couldn't access memory at 0x%p!\n", Frame
);
1190 /*!\brief Continues execution of the system/leaves KDB.
1197 /* Exit the main loop */
1201 /*!\brief Continues execution of the system/leaves KDB.
1212 Count
= strtoul(Argv
[1], NULL
, 0);
1215 KdbpPrint("%s: Integer argument required\n", Argv
[0]);
1220 if (Argv
[0][0] == 'n')
1221 KdbSingleStepOver
= TRUE
;
1223 KdbSingleStepOver
= FALSE
;
1225 /* Set the number of single steps and return to the interrupted code. */
1226 KdbNumSingleSteps
= Count
;
1231 /*!\brief Lists breakpoints.
1234 KdbpCmdBreakPointList(
1239 ULONG_PTR Address
= 0;
1240 KDB_BREAKPOINT_TYPE Type
= 0;
1241 KDB_ACCESS_TYPE AccessType
= 0;
1244 BOOLEAN Enabled
= FALSE
;
1245 BOOLEAN Global
= FALSE
;
1246 PEPROCESS Process
= NULL
;
1247 PCHAR str1
, str2
, ConditionExpr
, GlobalOrLocal
;
1250 l
= KdbpGetNextBreakPointNr(0);
1253 KdbpPrint("No breakpoints.\n");
1257 KdbpPrint("Breakpoints:\n");
1260 if (!KdbpGetBreakPointInfo(l
, &Address
, &Type
, &Size
, &AccessType
, &DebugReg
,
1261 &Enabled
, &Global
, &Process
, &ConditionExpr
))
1266 if (l
== KdbLastBreakPointNr
)
1279 GlobalOrLocal
= " global";
1283 GlobalOrLocal
= Buffer
;
1284 sprintf(Buffer
, " PID 0x%08lx",
1285 (ULONG
)(Process
? Process
->UniqueProcessId
: INVALID_HANDLE_VALUE
));
1288 if (Type
== KdbBreakPointSoftware
|| Type
== KdbBreakPointTemporary
)
1290 KdbpPrint(" %s%03d BPX 0x%08x%s%s%s%s%s\n",
1292 Enabled
? "" : " disabled",
1294 ConditionExpr
? " IF " : "",
1295 ConditionExpr
? ConditionExpr
: "",
1298 else if (Type
== KdbBreakPointHardware
)
1302 KdbpPrint(" %s%03d BPM 0x%08x %-5s %-5s disabled%s%s%s%s\n", str1
, l
, Address
,
1303 KDB_ACCESS_TYPE_TO_STRING(AccessType
),
1304 Size
== 1 ? "byte" : (Size
== 2 ? "word" : "dword"),
1306 ConditionExpr
? " IF " : "",
1307 ConditionExpr
? ConditionExpr
: "",
1312 KdbpPrint(" %s%03d BPM 0x%08x %-5s %-5s DR%d%s%s%s%s\n", str1
, l
, Address
,
1313 KDB_ACCESS_TYPE_TO_STRING(AccessType
),
1314 Size
== 1 ? "byte" : (Size
== 2 ? "word" : "dword"),
1317 ConditionExpr
? " IF " : "",
1318 ConditionExpr
? ConditionExpr
: "",
1323 while ((l
= KdbpGetNextBreakPointNr(l
+1)) >= 0);
1328 /*!\brief Enables, disables or clears a breakpoint.
1331 KdbpCmdEnableDisableClearBreakPoint(
1340 KdbpPrint("%s: argument required\n", Argv
[0]);
1345 BreakPointNr
= strtoul(Argv
[1], &pend
, 0);
1346 if (pend
== Argv
[1] || *pend
!= '\0')
1348 KdbpPrint("%s: integer argument required\n", Argv
[0]);
1352 if (Argv
[0][1] == 'e') /* enable */
1354 KdbpEnableBreakPoint(BreakPointNr
, NULL
);
1356 else if (Argv
[0][1] == 'd') /* disable */
1358 KdbpDisableBreakPoint(BreakPointNr
, NULL
);
1362 ASSERT(Argv
[0][1] == 'c');
1363 KdbpDeleteBreakPoint(BreakPointNr
, NULL
);
1369 /*!\brief Sets a software or hardware (memory) breakpoint at the given address.
1372 KdbpCmdBreakPoint(ULONG Argc
, PCHAR Argv
[])
1374 ULONGLONG Result
= 0;
1376 KDB_BREAKPOINT_TYPE Type
;
1378 KDB_ACCESS_TYPE AccessType
= 0;
1379 ULONG AddressArgIndex
, i
;
1380 LONG ConditionArgIndex
;
1381 BOOLEAN Global
= TRUE
;
1383 if (Argv
[0][2] == 'x') /* software breakpoint */
1387 KdbpPrint("bpx: Address argument required.\n");
1391 AddressArgIndex
= 1;
1392 Type
= KdbBreakPointSoftware
;
1394 else /* memory breakpoint */
1396 ASSERT(Argv
[0][2] == 'm');
1400 KdbpPrint("bpm: Access type argument required (one of r, w, rw, x)\n");
1404 if (_stricmp(Argv
[1], "x") == 0)
1405 AccessType
= KdbAccessExec
;
1406 else if (_stricmp(Argv
[1], "r") == 0)
1407 AccessType
= KdbAccessRead
;
1408 else if (_stricmp(Argv
[1], "w") == 0)
1409 AccessType
= KdbAccessWrite
;
1410 else if (_stricmp(Argv
[1], "rw") == 0)
1411 AccessType
= KdbAccessReadWrite
;
1414 KdbpPrint("bpm: Unknown access type '%s'\n", Argv
[1]);
1420 KdbpPrint("bpm: %s argument required.\n", AccessType
== KdbAccessExec
? "Address" : "Memory size");
1424 AddressArgIndex
= 3;
1425 if (_stricmp(Argv
[2], "byte") == 0)
1427 else if (_stricmp(Argv
[2], "word") == 0)
1429 else if (_stricmp(Argv
[2], "dword") == 0)
1431 else if (AccessType
== KdbAccessExec
)
1438 KdbpPrint("bpm: Unknown memory size '%s'\n", Argv
[2]);
1442 if (Argc
<= AddressArgIndex
)
1444 KdbpPrint("bpm: Address argument required.\n");
1448 Type
= KdbBreakPointHardware
;
1451 /* Put the arguments back together */
1452 ConditionArgIndex
= -1;
1453 for (i
= AddressArgIndex
; i
< (Argc
-1); i
++)
1455 if (strcmp(Argv
[i
+1], "IF") == 0) /* IF found */
1457 ConditionArgIndex
= i
+ 2;
1458 if ((ULONG
)ConditionArgIndex
>= Argc
)
1460 KdbpPrint("%s: IF requires condition expression.\n", Argv
[0]);
1464 for (i
= ConditionArgIndex
; i
< (Argc
-1); i
++)
1465 Argv
[i
][strlen(Argv
[i
])] = ' ';
1470 Argv
[i
][strlen(Argv
[i
])] = ' ';
1473 /* Evaluate the address expression */
1474 if (!KdbpEvaluateExpression(Argv
[AddressArgIndex
],
1475 sizeof("kdb:> ")-1 + (Argv
[AddressArgIndex
]-Argv
[0]),
1481 if (Result
> (ULONGLONG
)(~((ULONG_PTR
)0)))
1482 KdbpPrint("%s: Warning: Address %I64x is beeing truncated\n", Argv
[0],Result
);
1484 Address
= (ULONG_PTR
)Result
;
1486 KdbpInsertBreakPoint(Address
, Type
, Size
, AccessType
,
1487 (ConditionArgIndex
< 0) ? NULL
: Argv
[ConditionArgIndex
],
1493 /*!\brief Lists threads or switches to another thread context.
1501 PETHREAD Thread
= NULL
;
1502 PEPROCESS Process
= NULL
;
1503 BOOLEAN ReferencedThread
= FALSE
, ReferencedProcess
= FALSE
;
1508 PCHAR State
, pend
, str1
, str2
;
1509 static const PCHAR ThreadStateToString
[DeferredReady
+1] =
1511 "Initialized", "Ready", "Running",
1512 "Standby", "Terminated", "Waiting",
1513 "Transition", "DeferredReady"
1516 ASSERT(KdbCurrentProcess
);
1518 if (Argc
>= 2 && _stricmp(Argv
[1], "list") == 0)
1520 Process
= KdbCurrentProcess
;
1524 ul
= strtoul(Argv
[2], &pend
, 0);
1525 if (Argv
[2] == pend
)
1527 KdbpPrint("thread: '%s' is not a valid process id!\n", Argv
[2]);
1531 if (!NT_SUCCESS(PsLookupProcessByProcessId((PVOID
)ul
, &Process
)))
1533 KdbpPrint("thread: Invalid process id!\n");
1537 /* Remember our reference */
1538 ReferencedProcess
= TRUE
;
1541 Entry
= Process
->ThreadListHead
.Flink
;
1542 if (Entry
== &Process
->ThreadListHead
)
1545 KdbpPrint("No threads in process 0x%08x!\n", ul
);
1547 KdbpPrint("No threads in current process!\n");
1549 if (ReferencedProcess
)
1550 ObDereferenceObject(Process
);
1555 KdbpPrint(" TID State Prior. Affinity EBP EIP\n");
1558 Thread
= CONTAINING_RECORD(Entry
, ETHREAD
, ThreadListEntry
);
1560 if (Thread
== KdbCurrentThread
)
1571 if (!Thread
->Tcb
.InitialStack
)
1573 /* Thread has no kernel stack (probably terminated) */
1577 else if (Thread
->Tcb
.TrapFrame
)
1579 if (Thread
->Tcb
.TrapFrame
->PreviousPreviousMode
== KernelMode
)
1580 Esp
= (PULONG
)Thread
->Tcb
.TrapFrame
->TempEsp
;
1582 Esp
= (PULONG
)Thread
->Tcb
.TrapFrame
->HardwareEsp
;
1584 Ebp
= (PULONG
)Thread
->Tcb
.TrapFrame
->Ebp
;
1585 Eip
= Thread
->Tcb
.TrapFrame
->Eip
;
1589 Esp
= (PULONG
)Thread
->Tcb
.KernelStack
;
1590 Ebp
= (PULONG
)Esp
[4];
1593 if (Ebp
) /* FIXME: Should we attach to the process to read Ebp[1]? */
1594 KdbpSafeReadMemory(&Eip
, Ebp
+ 1, sizeof (Eip
));
1597 if (Thread
->Tcb
.State
< (DeferredReady
+ 1))
1598 State
= ThreadStateToString
[Thread
->Tcb
.State
];
1602 KdbpPrint(" %s0x%08x %-11s %3d 0x%08x 0x%08x 0x%08x%s\n",
1604 Thread
->Cid
.UniqueThread
,
1606 Thread
->Tcb
.Priority
,
1607 Thread
->Tcb
.Affinity
,
1612 Entry
= Entry
->Flink
;
1614 while (Entry
!= &Process
->ThreadListHead
);
1616 /* Release our reference, if any */
1617 if (ReferencedProcess
)
1618 ObDereferenceObject(Process
);
1620 else if (Argc
>= 2 && _stricmp(Argv
[1], "attach") == 0)
1624 KdbpPrint("thread attach: thread id argument required!\n");
1628 ul
= strtoul(Argv
[2], &pend
, 0);
1629 if (Argv
[2] == pend
)
1631 KdbpPrint("thread attach: '%s' is not a valid thread id!\n", Argv
[2]);
1635 if (!KdbpAttachToThread((PVOID
)ul
))
1640 KdbpPrint("Attached to thread 0x%08x.\n", ul
);
1644 Thread
= KdbCurrentThread
;
1648 ul
= strtoul(Argv
[1], &pend
, 0);
1649 if (Argv
[1] == pend
)
1651 KdbpPrint("thread: '%s' is not a valid thread id!\n", Argv
[1]);
1655 if (!NT_SUCCESS(PsLookupThreadByThreadId((PVOID
)ul
, &Thread
)))
1657 KdbpPrint("thread: Invalid thread id!\n");
1661 /* Remember our reference */
1662 ReferencedThread
= TRUE
;
1665 if (Thread
->Tcb
.State
< (DeferredReady
+ 1))
1666 State
= ThreadStateToString
[Thread
->Tcb
.State
];
1672 " State: %s (0x%x)\n"
1674 " Affinity: 0x%08x\n"
1675 " Initial Stack: 0x%08x\n"
1676 " Stack Limit: 0x%08x\n"
1677 " Stack Base: 0x%08x\n"
1678 " Kernel Stack: 0x%08x\n"
1679 " Trap Frame: 0x%08x\n"
1680 " NPX State: %s (0x%x)\n",
1681 (Argc
< 2) ? "Current Thread:\n" : "",
1682 Thread
->Cid
.UniqueThread
,
1683 State
, Thread
->Tcb
.State
,
1684 Thread
->Tcb
.Priority
,
1685 Thread
->Tcb
.Affinity
,
1686 Thread
->Tcb
.InitialStack
,
1687 Thread
->Tcb
.StackLimit
,
1688 Thread
->Tcb
.StackBase
,
1689 Thread
->Tcb
.KernelStack
,
1690 Thread
->Tcb
.TrapFrame
,
1691 NPX_STATE_TO_STRING(Thread
->Tcb
.NpxState
), Thread
->Tcb
.NpxState
);
1693 /* Release our reference if we had one */
1694 if (ReferencedThread
)
1695 ObDereferenceObject(Thread
);
1701 /*!\brief Lists processes or switches to another process context.
1710 BOOLEAN ReferencedProcess
= FALSE
;
1711 PCHAR State
, pend
, str1
, str2
;
1713 extern LIST_ENTRY PsActiveProcessHead
;
1715 if (Argc
>= 2 && _stricmp(Argv
[1], "list") == 0)
1717 Entry
= PsActiveProcessHead
.Flink
;
1718 if (!Entry
|| Entry
== &PsActiveProcessHead
)
1720 KdbpPrint("No processes in the system!\n");
1724 KdbpPrint(" PID State Filename\n");
1727 Process
= CONTAINING_RECORD(Entry
, EPROCESS
, ActiveProcessLinks
);
1729 if (Process
== KdbCurrentProcess
)
1740 State
= ((Process
->Pcb
.State
== ProcessInMemory
) ? "In Memory" :
1741 ((Process
->Pcb
.State
== ProcessOutOfMemory
) ? "Out of Memory" : "In Transition"));
1743 KdbpPrint(" %s0x%08x %-10s %s%s\n",
1745 Process
->UniqueProcessId
,
1747 Process
->ImageFileName
,
1750 Entry
= Entry
->Flink
;
1752 while(Entry
!= &PsActiveProcessHead
);
1754 else if (Argc
>= 2 && _stricmp(Argv
[1], "attach") == 0)
1758 KdbpPrint("process attach: process id argument required!\n");
1762 ul
= strtoul(Argv
[2], &pend
, 0);
1763 if (Argv
[2] == pend
)
1765 KdbpPrint("process attach: '%s' is not a valid process id!\n", Argv
[2]);
1769 if (!KdbpAttachToProcess((PVOID
)ul
))
1774 KdbpPrint("Attached to process 0x%08x, thread 0x%08x.\n", (ULONG
)ul
,
1775 (ULONG
)KdbCurrentThread
->Cid
.UniqueThread
);
1779 Process
= KdbCurrentProcess
;
1783 ul
= strtoul(Argv
[1], &pend
, 0);
1784 if (Argv
[1] == pend
)
1786 KdbpPrint("proc: '%s' is not a valid process id!\n", Argv
[1]);
1790 if (!NT_SUCCESS(PsLookupProcessByProcessId((PVOID
)ul
, &Process
)))
1792 KdbpPrint("proc: Invalid process id!\n");
1796 /* Remember our reference */
1797 ReferencedProcess
= TRUE
;
1800 State
= ((Process
->Pcb
.State
== ProcessInMemory
) ? "In Memory" :
1801 ((Process
->Pcb
.State
== ProcessOutOfMemory
) ? "Out of Memory" : "In Transition"));
1804 " State: %s (0x%x)\n"
1805 " Image Filename: %s\n",
1806 (Argc
< 2) ? "Current process:\n" : "",
1807 Process
->UniqueProcessId
,
1808 State
, Process
->Pcb
.State
,
1809 Process
->ImageFileName
);
1811 /* Release our reference, if any */
1812 if (ReferencedProcess
)
1813 ObDereferenceObject(Process
);
1819 /*!\brief Lists loaded modules or the one containing the specified address.
1826 ULONGLONG Result
= 0;
1828 PLDR_DATA_TABLE_ENTRY LdrEntry
;
1829 BOOLEAN DisplayOnlyOneModule
= FALSE
;
1834 /* Put the arguments back together */
1837 Argv
[Argc
][strlen(Argv
[Argc
])] = ' ';
1839 /* Evaluate the expression */
1840 if (!KdbpEvaluateExpression(Argv
[1], sizeof("kdb:> ")-1 + (Argv
[1]-Argv
[0]), &Result
))
1845 if (Result
> (ULONGLONG
)(~((ULONG_PTR
)0)))
1846 KdbpPrint("%s: Warning: Address %I64x is beeing truncated\n", Argv
[0],Result
);
1848 Address
= (ULONG_PTR
)Result
;
1850 if (!KdbpSymFindModule((PVOID
)Address
, NULL
, -1, &LdrEntry
))
1852 KdbpPrint("No module containing address 0x%p found!\n", Address
);
1856 DisplayOnlyOneModule
= TRUE
;
1860 if (!KdbpSymFindModule(NULL
, NULL
, 0, &LdrEntry
))
1862 ULONG_PTR ntoskrnlBase
= ((ULONG_PTR
)KdbpCmdMod
) & 0xfff00000;
1863 KdbpPrint(" Base Size Name\n");
1864 KdbpPrint(" %08x %08x %s\n", ntoskrnlBase
, 0, "ntoskrnl.exe");
1871 KdbpPrint(" Base Size Name\n");
1874 KdbpPrint(" %08x %08x %wZ\n", LdrEntry
->DllBase
, LdrEntry
->SizeOfImage
, &LdrEntry
->BaseDllName
);
1876 if(DisplayOnlyOneModule
|| !KdbpSymFindModule(NULL
, NULL
, i
++, &LdrEntry
))
1883 /*!\brief Displays GDT, LDT or IDTd.
1900 if (Argv
[0][0] == 'i')
1907 KdbpPrint("Interrupt descriptor table is empty.\n");
1911 KdbpPrint("IDT Base: 0x%08x Limit: 0x%04x\n", Reg
.Base
, Reg
.Limit
);
1912 KdbpPrint(" Idx Type Seg. Sel. Offset DPL\n");
1914 for (i
= 0; (i
+ sizeof(SegDesc
) - 1) <= Reg
.Limit
; i
+= 8)
1916 if (!NT_SUCCESS(KdbpSafeReadMemory(SegDesc
, (PVOID
)(Reg
.Base
+ i
), sizeof(SegDesc
))))
1918 KdbpPrint("Couldn't access memory at 0x%08x!\n", Reg
.Base
+ i
);
1922 Dpl
= ((SegDesc
[1] >> 13) & 3);
1923 if ((SegDesc
[1] & 0x1f00) == 0x0500) /* Task gate */
1924 SegType
= "TASKGATE";
1925 else if ((SegDesc
[1] & 0x1fe0) == 0x0e00) /* 32 bit Interrupt gate */
1926 SegType
= "INTGATE32";
1927 else if ((SegDesc
[1] & 0x1fe0) == 0x0600) /* 16 bit Interrupt gate */
1928 SegType
= "INTGATE16";
1929 else if ((SegDesc
[1] & 0x1fe0) == 0x0f00) /* 32 bit Trap gate */
1930 SegType
= "TRAPGATE32";
1931 else if ((SegDesc
[1] & 0x1fe0) == 0x0700) /* 16 bit Trap gate */
1932 SegType
= "TRAPGATE16";
1934 SegType
= "UNKNOWN";
1936 if ((SegDesc
[1] & (1 << 15)) == 0) /* not present */
1938 KdbpPrint(" %03d %-10s [NP] [NP] %02d\n",
1939 i
/ 8, SegType
, Dpl
);
1941 else if ((SegDesc
[1] & 0x1f00) == 0x0500) /* Task gate */
1943 SegSel
= SegDesc
[0] >> 16;
1944 KdbpPrint(" %03d %-10s 0x%04x %02d\n",
1945 i
/ 8, SegType
, SegSel
, Dpl
);
1949 SegSel
= SegDesc
[0] >> 16;
1950 SegBase
= (SegDesc
[1] & 0xffff0000) | (SegDesc
[0] & 0x0000ffff);
1951 KdbpPrint(" %03d %-10s 0x%04x 0x%08x %02d\n",
1952 i
/ 8, SegType
, SegSel
, SegBase
, Dpl
);
1960 if (Argv
[0][0] == 'g')
1963 Ke386GetGlobalDescriptorTable(&Reg
.Limit
);
1968 ASSERT(Argv
[0][0] == 'l');
1971 Reg
.Limit
= Ke386GetLocalDescriptorTable();
1979 KdbpPrint("%s descriptor table is empty.\n",
1980 Argv
[0][0] == 'g' ? "Global" : "Local");
1984 KdbpPrint("%cDT Base: 0x%08x Limit: 0x%04x\n",
1985 Argv
[0][0] == 'g' ? 'G' : 'L', Reg
.Base
, Reg
.Limit
);
1986 KdbpPrint(" Idx Sel. Type Base Limit DPL Attribs\n");
1988 for (; (i
+ sizeof(SegDesc
) - 1) <= Reg
.Limit
; i
+= 8)
1990 if (!NT_SUCCESS(KdbpSafeReadMemory(SegDesc
, (PVOID
)(Reg
.Base
+ i
), sizeof(SegDesc
))))
1992 KdbpPrint("Couldn't access memory at 0x%08x!\n", Reg
.Base
+ i
);
1996 Dpl
= ((SegDesc
[1] >> 13) & 3);
1997 Type
= ((SegDesc
[1] >> 8) & 0xf);
1999 SegBase
= SegDesc
[0] >> 16;
2000 SegBase
|= (SegDesc
[1] & 0xff) << 16;
2001 SegBase
|= SegDesc
[1] & 0xff000000;
2002 SegLimit
= SegDesc
[0] & 0x0000ffff;
2003 SegLimit
|= (SegDesc
[1] >> 16) & 0xf;
2005 if ((SegDesc
[1] & (1 << 23)) != 0)
2015 if ((SegDesc
[1] & (1 << 12)) == 0) /* System segment */
2019 case 1: SegType
= "TSS16(Avl)"; break;
2020 case 2: SegType
= "LDT"; break;
2021 case 3: SegType
= "TSS16(Busy)"; break;
2022 case 4: SegType
= "CALLGATE16"; break;
2023 case 5: SegType
= "TASKGATE"; break;
2024 case 6: SegType
= "INTGATE16"; break;
2025 case 7: SegType
= "TRAPGATE16"; break;
2026 case 9: SegType
= "TSS32(Avl)"; break;
2027 case 11: SegType
= "TSS32(Busy)"; break;
2028 case 12: SegType
= "CALLGATE32"; break;
2029 case 14: SegType
= "INTGATE32"; break;
2030 case 15: SegType
= "INTGATE32"; break;
2031 default: SegType
= "UNKNOWN"; break;
2034 if (!(Type
>= 1 && Type
<= 3) &&
2035 Type
!= 9 && Type
!= 11)
2041 else if ((SegDesc
[1] & (1 << 11)) == 0) /* Data segment */
2043 if ((SegDesc
[1] & (1 << 22)) != 0)
2048 else /* Code segment */
2050 if ((SegDesc
[1] & (1 << 22)) != 0)
2056 if ((SegDesc
[1] & (1 << 15)) == 0) /* not present */
2058 KdbpPrint(" %03d 0x%04x %-11s [NP] [NP] %02d NP\n",
2059 i
/ 8, i
| Dpl
| ul
, SegType
, Dpl
);
2063 KdbpPrint(" %03d 0x%04x %-11s 0x%08x 0x%08x %02d ",
2064 i
/ 8, i
| Dpl
| ul
, SegType
, SegBase
, SegLimit
, Dpl
);
2066 if ((SegDesc
[1] & (1 << 12)) == 0) /* System segment */
2068 /* FIXME: Display system segment */
2070 else if ((SegDesc
[1] & (1 << 11)) == 0) /* Data segment */
2072 if ((SegDesc
[1] & (1 << 10)) != 0) /* Expand-down */
2075 KdbpPrint((SegDesc
[1] & (1 << 9)) ? " R/W" : " R");
2077 if ((SegDesc
[1] & (1 << 8)) != 0)
2080 else /* Code segment */
2082 if ((SegDesc
[1] & (1 << 10)) != 0) /* Conforming */
2085 KdbpPrint((SegDesc
[1] & (1 << 9)) ? " R/X" : " X");
2087 if ((SegDesc
[1] & (1 << 8)) != 0)
2091 if ((SegDesc
[1] & (1 << 20)) != 0)
2102 /*!\brief Displays the KPCR
2109 PKIPCR Pcr
= (PKIPCR
)KeGetPcr();
2111 KdbpPrint("Current PCR is at 0x%08x.\n", (INT
)Pcr
);
2112 KdbpPrint(" Tib.ExceptionList: 0x%08x\n"
2113 " Tib.StackBase: 0x%08x\n"
2114 " Tib.StackLimit: 0x%08x\n"
2115 " Tib.SubSystemTib: 0x%08x\n"
2116 " Tib.FiberData/Version: 0x%08x\n"
2117 " Tib.ArbitraryUserPointer: 0x%08x\n"
2118 " Tib.Self: 0x%08x\n"
2119 " SelfPcr: 0x%08x\n"
2123 " IrrActive: 0x%08x\n"
2125 " KdVersionBlock: 0x%08x\n"
2129 " MajorVersion: 0x%04x\n"
2130 " MinorVersion: 0x%04x\n"
2131 " SetMember: 0x%08x\n"
2132 " StallScaleFactor: 0x%08x\n"
2134 " L2CacheAssociativity: 0x%02x\n"
2135 " VdmAlert: 0x%08x\n"
2136 " L2CacheSize: 0x%08x\n"
2137 " InterruptMode: 0x%08x\n",
2138 Pcr
->NtTib
.ExceptionList
, Pcr
->NtTib
.StackBase
, Pcr
->NtTib
.StackLimit
,
2139 Pcr
->NtTib
.SubSystemTib
, Pcr
->NtTib
.FiberData
, Pcr
->NtTib
.ArbitraryUserPointer
,
2140 Pcr
->NtTib
.Self
, Pcr
->SelfPcr
, Pcr
->Prcb
, Pcr
->Irql
, Pcr
->IRR
, Pcr
->IrrActive
,
2141 Pcr
->IDR
, Pcr
->KdVersionBlock
, Pcr
->IDT
, Pcr
->GDT
, Pcr
->TSS
,
2142 Pcr
->MajorVersion
, Pcr
->MinorVersion
, Pcr
->SetMember
, Pcr
->StallScaleFactor
,
2143 Pcr
->Number
, Pcr
->SecondLevelCacheAssociativity
,
2144 Pcr
->VdmAlert
, Pcr
->SecondLevelCacheSize
, Pcr
->InterruptMode
);
2149 /*!\brief Displays the TSS
2156 KTSS
*Tss
= KeGetPcr()->TSS
;
2158 KdbpPrint("Current TSS is at 0x%08x.\n", (INT
)Tss
);
2159 KdbpPrint(" Eip: 0x%08x\n"
2166 " IoMapBase: 0x%04x\n",
2167 Tss
->Eip
, Tss
->Es
, Tss
->Cs
, Tss
->Ds
, Tss
->Fs
, Tss
->Gs
, Tss
->IoMapBase
);
2172 /*!\brief Bugchecks the system.
2179 /* Set the flag and quit looping */
2180 KdbpBugCheckRequested
= TRUE
;
2190 /* Reboot immediately (we do not return) */
2191 HalReturnToFirmware(HalRebootRoutine
);
2199 IN ULONG BufLength
);
2201 /*!\brief Display debug messages on screen, with paging.
2203 * Keys for per-page view: Home, End, PageUp, Arrow Up, PageDown,
2204 * all others are as PageDown.
2213 KdbpIsInDmesgMode
= TRUE
; /* Toggle logging flag */
2214 if (!KdpDmesgBuffer
)
2216 KdbpPrint("Dmesg: error, buffer is not allocated! /DEBUGPORT=SCREEN kernel param required for dmesg.\n");
2220 KdbpPrint("*** Dmesg *** TotalWritten=%lu, BufferSize=%lu, CurrentPosition=%lu\n",
2221 KdbDmesgTotalWritten
, KdpDmesgBufferSize
, KdpDmesgCurrentPosition
);
2223 // Pass data to the pager:
2224 end
= KdpDmesgCurrentPosition
;
2225 beg
= (end
+ KdpDmesgFreeBytes
) % KdpDmesgBufferSize
;
2227 // no roll-overs, and overwritten=lost bytes
2228 if (KdbDmesgTotalWritten
<= KdpDmesgBufferSize
)
2230 // show buffer (KdpDmesgBuffer + beg, num)
2231 KdbpPager(KdpDmesgBuffer
, KdpDmesgCurrentPosition
);
2235 // show 2 buffers: (KdpDmesgBuffer + beg, KdpDmesgBufferSize - beg)
2236 // and: (KdpDmesgBuffer, end)
2237 KdbpPager(KdpDmesgBuffer
+ beg
, KdpDmesgBufferSize
- beg
);
2238 KdbpPrint("*** Dmesg: buffer rollup ***\n");
2239 KdbpPager(KdpDmesgBuffer
, end
);
2241 KdbpPrint("*** Dmesg: end of output ***\n");
2243 KdbpIsInDmesgMode
= FALSE
; /* Toggle logging flag */
2248 /*!\brief Sets or displays a config variables value.
2258 KDB_ENTER_CONDITION ConditionFirst
= KdbDoNotEnter
;
2259 KDB_ENTER_CONDITION ConditionLast
= KdbDoNotEnter
;
2261 static const PCHAR ExceptionNames
[21] =
2263 "ZERODEVIDE", "DEBUGTRAP", "NMI", "INT3", "OVERFLOW", "BOUND", "INVALIDOP",
2264 "NOMATHCOP", "DOUBLEFAULT", "RESERVED(9)", "INVALIDTSS", "SEGMENTNOTPRESENT",
2265 "STACKFAULT", "GPF", "PAGEFAULT", "RESERVED(15)", "MATHFAULT", "ALIGNMENTCHECK",
2266 "MACHINECHECK", "SIMDFAULT", "OTHERS"
2271 KdbpPrint("Available settings:\n");
2272 KdbpPrint(" syntax [intel|at&t]\n");
2273 KdbpPrint(" condition [exception|*] [first|last] [never|always|kmode|umode]\n");
2274 KdbpPrint(" break_on_module_load [true|false]\n");
2276 else if (strcmp(Argv
[1], "syntax") == 0)
2280 KdbpPrint("syntax = %s\n", KdbUseIntelSyntax
? "intel" : "at&t");
2284 if (_stricmp(Argv
[2], "intel") == 0)
2285 KdbUseIntelSyntax
= TRUE
;
2286 else if (_stricmp(Argv
[2], "at&t") == 0)
2287 KdbUseIntelSyntax
= FALSE
;
2289 KdbpPrint("Unknown syntax '%s'.\n", Argv
[2]);
2292 else if (strcmp(Argv
[1], "condition") == 0)
2296 KdbpPrint("Conditions: (First) (Last)\n");
2297 for (l
= 0; l
< RTL_NUMBER_OF(ExceptionNames
) - 1; l
++)
2299 if (!ExceptionNames
[l
])
2302 if (!KdbpGetEnterCondition(l
, TRUE
, &ConditionFirst
))
2305 if (!KdbpGetEnterCondition(l
, FALSE
, &ConditionLast
))
2308 KdbpPrint(" #%02d %-20s %-8s %-8s\n", l
, ExceptionNames
[l
],
2309 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst
),
2310 KDB_ENTER_CONDITION_TO_STRING(ConditionLast
));
2313 ASSERT(l
== (RTL_NUMBER_OF(ExceptionNames
) - 1));
2314 KdbpPrint(" %-20s %-8s %-8s\n", ExceptionNames
[l
],
2315 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst
),
2316 KDB_ENTER_CONDITION_TO_STRING(ConditionLast
));
2320 if (Argc
>= 5 && strcmp(Argv
[2], "*") == 0) /* Allow * only when setting condition */
2326 l
= strtoul(Argv
[2], &pend
, 0);
2328 if (Argv
[2] == pend
)
2330 for (l
= 0; l
< RTL_NUMBER_OF(ExceptionNames
); l
++)
2332 if (!ExceptionNames
[l
])
2335 if (_stricmp(ExceptionNames
[l
], Argv
[2]) == 0)
2340 if (l
>= RTL_NUMBER_OF(ExceptionNames
))
2342 KdbpPrint("Unknown exception '%s'.\n", Argv
[2]);
2349 if (_stricmp(Argv
[3], "first") == 0)
2351 else if (_stricmp(Argv
[3], "last") == 0)
2355 KdbpPrint("set condition: second argument must be 'first' or 'last'\n");
2359 if (_stricmp(Argv
[4], "never") == 0)
2360 ConditionFirst
= KdbDoNotEnter
;
2361 else if (_stricmp(Argv
[4], "always") == 0)
2362 ConditionFirst
= KdbEnterAlways
;
2363 else if (_stricmp(Argv
[4], "umode") == 0)
2364 ConditionFirst
= KdbEnterFromUmode
;
2365 else if (_stricmp(Argv
[4], "kmode") == 0)
2366 ConditionFirst
= KdbEnterFromKmode
;
2369 KdbpPrint("set condition: third argument must be 'never', 'always', 'umode' or 'kmode'\n");
2373 if (!KdbpSetEnterCondition(l
, First
, ConditionFirst
))
2376 KdbpPrint("Couldn't change condition for exception #%02d\n", l
);
2378 KdbpPrint("Couldn't change condition for all exceptions\n", l
);
2381 else /* Argc >= 3 */
2383 if (!KdbpGetEnterCondition(l
, TRUE
, &ConditionFirst
))
2386 if (!KdbpGetEnterCondition(l
, FALSE
, &ConditionLast
))
2389 if (l
< (RTL_NUMBER_OF(ExceptionNames
) - 1))
2391 KdbpPrint("Condition for exception #%02d (%s): FirstChance %s LastChance %s\n",
2392 l
, ExceptionNames
[l
],
2393 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst
),
2394 KDB_ENTER_CONDITION_TO_STRING(ConditionLast
));
2398 KdbpPrint("Condition for all other exceptions: FirstChance %s LastChance %s\n",
2399 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst
),
2400 KDB_ENTER_CONDITION_TO_STRING(ConditionLast
));
2405 else if (strcmp(Argv
[1], "break_on_module_load") == 0)
2408 KdbpPrint("break_on_module_load = %s\n", KdbBreakOnModuleLoad
? "enabled" : "disabled");
2411 if (_stricmp(Argv
[2], "enable") == 0 || _stricmp(Argv
[2], "enabled") == 0 || _stricmp(Argv
[2], "true") == 0)
2412 KdbBreakOnModuleLoad
= TRUE
;
2413 else if (_stricmp(Argv
[2], "disable") == 0 || _stricmp(Argv
[2], "disabled") == 0 || _stricmp(Argv
[2], "false") == 0)
2414 KdbBreakOnModuleLoad
= FALSE
;
2416 KdbpPrint("Unknown setting '%s'.\n", Argv
[2]);
2421 KdbpPrint("Unknown setting '%s'.\n", Argv
[1]);
2427 /*!\brief Displays help screen.
2436 KdbpPrint("Kernel debugger commands:\n");
2437 for (i
= 0; i
< RTL_NUMBER_OF(KdbDebuggerCommands
); i
++)
2439 if (!KdbDebuggerCommands
[i
].Syntax
) /* Command group */
2444 KdbpPrint("\x1b[7m* %s:\x1b[0m\n", KdbDebuggerCommands
[i
].Help
);
2448 KdbpPrint(" %-20s - %s\n",
2449 KdbDebuggerCommands
[i
].Syntax
,
2450 KdbDebuggerCommands
[i
].Help
);
2456 /*!\brief Prints the given string with printf-like formatting.
2458 * \param Format Format of the string/arguments.
2459 * \param ... Variable number of arguments matching the format specified in \a Format.
2461 * \note Doesn't correctly handle \\t and terminal escape sequences when calculating the
2462 * number of lines required to print a single line from the Buffer in the terminal.
2463 * Prints maximum 4096 chars, because of its buffer size.
2470 static CHAR Buffer
[4096];
2471 static BOOLEAN TerminalInitialized
= FALSE
;
2472 static BOOLEAN TerminalConnected
= FALSE
;
2473 static BOOLEAN TerminalReportsSize
= TRUE
;
2478 LONG RowsPrintedByTerminal
;
2482 /* Check if the user has aborted output of the current command */
2483 if (KdbOutputAborted
)
2486 /* Initialize the terminal */
2487 if (!TerminalInitialized
)
2489 DbgPrint("\x1b[7h"); /* Enable linewrap */
2491 /* Query terminal type */
2492 /*DbgPrint("\x1b[Z");*/
2495 TerminalInitialized
= TRUE
;
2497 KeStallExecutionProcessor(100000);
2501 c
= KdbpTryGetCharSerial(5000);
2505 Buffer
[Length
++] = c
;
2506 if (Length
>= (sizeof (Buffer
) - 1))
2510 Buffer
[Length
] = '\0';
2512 TerminalConnected
= TRUE
;
2515 /* Get number of rows and columns in terminal */
2516 if ((KdbNumberOfRowsTerminal
< 0) || (KdbNumberOfColsTerminal
< 0) ||
2517 (KdbNumberOfRowsPrinted
) == 0) /* Refresh terminal size each time when number of rows printed is 0 */
2519 if ((KdbDebugState
& KD_DEBUG_KDSERIAL
) && TerminalConnected
&& TerminalReportsSize
)
2521 /* Try to query number of rows from terminal. A reply looks like "\x1b[8;24;80t" */
2522 TerminalReportsSize
= FALSE
;
2523 KeStallExecutionProcessor(100000);
2524 DbgPrint("\x1b[18t");
2525 c
= KdbpTryGetCharSerial(5000);
2529 c
= KdbpTryGetCharSerial(5000);
2536 c
= KdbpTryGetCharSerial(5000);
2540 Buffer
[Length
++] = c
;
2541 if (isalpha(c
) || Length
>= (sizeof (Buffer
) - 1))
2545 Buffer
[Length
] = '\0';
2546 if (Buffer
[0] == '8' && Buffer
[1] == ';')
2548 for (i
= 2; (i
< Length
) && (Buffer
[i
] != ';'); i
++);
2550 if (Buffer
[i
] == ';')
2554 /* Number of rows is now at Buffer + 2 and number of cols at Buffer + i */
2555 KdbNumberOfRowsTerminal
= strtoul(Buffer
+ 2, NULL
, 0);
2556 KdbNumberOfColsTerminal
= strtoul(Buffer
+ i
, NULL
, 0);
2557 TerminalReportsSize
= TRUE
;
2561 /* Clear further characters */
2562 while ((c
= KdbpTryGetCharSerial(5000)) != -1);
2566 if (KdbNumberOfRowsTerminal
<= 0)
2568 /* Set number of rows to the default. */
2569 KdbNumberOfRowsTerminal
= 23; //24; //Mna.: 23 for SCREEN debugport
2571 else if (KdbNumberOfColsTerminal
<= 0)
2573 /* Set number of cols to the default. */
2574 KdbNumberOfColsTerminal
= 75; //80; //Mna.: 75 for SCREEN debugport
2578 /* Get the string */
2579 va_start(ap
, Format
);
2580 Length
= _vsnprintf(Buffer
, sizeof (Buffer
) - 1, Format
, ap
);
2581 Buffer
[Length
] = '\0';
2585 while (p
[0] != '\0')
2587 i
= strcspn(p
, "\n");
2589 /* Calculate the number of lines which will be printed in the terminal
2590 * when outputting the current line
2593 RowsPrintedByTerminal
= (i
+ KdbNumberOfColsPrinted
- 1) / KdbNumberOfColsTerminal
;
2595 RowsPrintedByTerminal
= 0;
2598 RowsPrintedByTerminal
++;
2600 /*DbgPrint("!%d!%d!%d!%d!", KdbNumberOfRowsPrinted, KdbNumberOfColsPrinted, i, RowsPrintedByTerminal);*/
2602 /* Display a prompt if we printed one screen full of text */
2603 if (KdbNumberOfRowsTerminal
> 0 &&
2604 (LONG
)(KdbNumberOfRowsPrinted
+ RowsPrintedByTerminal
) >= KdbNumberOfRowsTerminal
)
2606 KdbRepeatLastCommand
= FALSE
;
2608 if (KdbNumberOfColsPrinted
> 0)
2611 DbgPrint("--- Press q to abort, any other key to continue ---");
2612 RowsPrintedByTerminal
++; /* added by Mna. */
2614 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
2615 c
= KdbpGetCharSerial();
2617 c
= KdbpGetCharKeyboard(&ScanCode
);
2621 /* Try to read '\n' which might follow '\r' - if \n is not received here
2622 * it will be interpreted as "return" when the next command should be read.
2624 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
2625 c
= KdbpTryGetCharSerial(5);
2627 c
= KdbpTryGetCharKeyboard(&ScanCode
, 5);
2633 KdbOutputAborted
= TRUE
;
2637 KdbNumberOfRowsPrinted
= 0;
2638 KdbNumberOfColsPrinted
= 0;
2641 /* Insert a NUL after the line and print only the current line. */
2642 if (p
[i
] == '\n' && p
[i
+ 1] != '\0')
2652 /* Remove escape sequences from the line if there's no terminal connected */
2653 if (!TerminalConnected
)
2655 while ((p2
= strrchr(p
, '\x1b'))) /* Look for escape character */
2660 while (!isalpha(p2
[j
++]));
2675 /* Set p to the start of the next line and
2676 * remember the number of rows/cols printed
2682 KdbNumberOfColsPrinted
= 0;
2686 ASSERT(p
[0] == '\0');
2687 KdbNumberOfColsPrinted
+= i
;
2690 KdbNumberOfRowsPrinted
+= RowsPrintedByTerminal
;
2694 /** memrchr(), explicitly defined, since was absent in MinGW of RosBE. */
2697 * Find the last occurrence of 'c' in the buffer 's' of size 'n'.
2700 memrchr(const void *s
, int c
, size_t n
)
2702 const unsigned char *cp
;
2706 cp
= (unsigned char *)s
+ n
;
2709 if (*(--cp
) == (unsigned char)c
)
2716 /*!\brief Calculate pointer position for N lines upper of current position.
2718 * \param Buffer Characters buffer to operate on.
2719 * \param BufLength Buffer size.
2721 * \note Calculate pointer position for N lines upper of current displaying
2722 * position within the given buffer.
2724 * Used by KdbpPager().
2725 * Now N lines count is hardcoded to KdbNumberOfRowsTerminal.
2728 CountOnePageUp(PCHAR Buffer
, ULONG BufLength
, PCHAR pCurPos
)
2731 // p0 is initial guess of Page Start
2732 ULONG p0len
= KdbNumberOfRowsTerminal
* KdbNumberOfColsTerminal
;
2733 PCHAR p0
= pCurPos
- p0len
;
2734 PCHAR prev_p
= p0
, p1
;
2737 if (pCurPos
< Buffer
)
2739 ASSERT(pCurPos
<= Buffer
+ BufLength
);
2741 p
= memrchr(p0
, '\n', p0len
);
2744 for (j
= KdbNumberOfRowsTerminal
; j
--; )
2747 p1
= memrchr(p0
, '\n', p
-p0
);
2757 linesCnt
= (KdbNumberOfColsTerminal
+prev_p
-p
-2) / KdbNumberOfColsTerminal
;
2767 /*!\brief Prints the given string with, page by page.
2769 * \param Buffer Characters buffer to print.
2770 * \param BufferLen Buffer size.
2772 * \note Doesn't correctly handle \\t and terminal escape sequences when calculating the
2773 * number of lines required to print a single line from the Buffer in the terminal.
2774 * Maximum length of buffer is limited only by memory size.
2776 * Note: BufLength should be greater then (KdbNumberOfRowsTerminal * KdbNumberOfColsTerminal).
2784 static CHAR InBuffer
[4096];
2785 static BOOLEAN TerminalInitialized
= FALSE
;
2786 static BOOLEAN TerminalConnected
= FALSE
;
2787 static BOOLEAN TerminalReportsSize
= TRUE
;
2792 LONG RowsPrintedByTerminal
;
2798 /* Check if the user has aborted output of the current command */
2799 if (KdbOutputAborted
)
2802 /* Initialize the terminal */
2803 if (!TerminalInitialized
)
2805 DbgPrint("\x1b[7h"); /* Enable linewrap */
2807 /* Query terminal type */
2808 /*DbgPrint("\x1b[Z");*/
2811 TerminalInitialized
= TRUE
;
2813 KeStallExecutionProcessor(100000);
2817 c
= KdbpTryGetCharSerial(5000);
2821 InBuffer
[Length
++] = c
;
2822 if (Length
>= (sizeof (InBuffer
) - 1))
2826 InBuffer
[Length
] = '\0';
2828 TerminalConnected
= TRUE
;
2831 /* Get number of rows and columns in terminal */
2832 if ((KdbNumberOfRowsTerminal
< 0) || (KdbNumberOfColsTerminal
< 0) ||
2833 (KdbNumberOfRowsPrinted
) == 0) /* Refresh terminal size each time when number of rows printed is 0 */
2835 if ((KdbDebugState
& KD_DEBUG_KDSERIAL
) && TerminalConnected
&& TerminalReportsSize
)
2837 /* Try to query number of rows from terminal. A reply looks like "\x1b[8;24;80t" */
2838 TerminalReportsSize
= FALSE
;
2839 KeStallExecutionProcessor(100000);
2840 DbgPrint("\x1b[18t");
2841 c
= KdbpTryGetCharSerial(5000);
2845 c
= KdbpTryGetCharSerial(5000);
2852 c
= KdbpTryGetCharSerial(5000);
2856 InBuffer
[Length
++] = c
;
2857 if (isalpha(c
) || Length
>= (sizeof (InBuffer
) - 1))
2861 InBuffer
[Length
] = '\0';
2862 if (InBuffer
[0] == '8' && InBuffer
[1] == ';')
2864 for (i
= 2; (i
< Length
) && (InBuffer
[i
] != ';'); i
++);
2866 if (Buffer
[i
] == ';')
2870 /* Number of rows is now at Buffer + 2 and number of cols at Buffer + i */
2871 KdbNumberOfRowsTerminal
= strtoul(InBuffer
+ 2, NULL
, 0);
2872 KdbNumberOfColsTerminal
= strtoul(InBuffer
+ i
, NULL
, 0);
2873 TerminalReportsSize
= TRUE
;
2877 /* Clear further characters */
2878 while ((c
= KdbpTryGetCharSerial(5000)) != -1);
2882 if (KdbNumberOfRowsTerminal
<= 0)
2884 /* Set number of rows to the default. */
2885 KdbNumberOfRowsTerminal
= 24;
2887 else if (KdbNumberOfColsTerminal
<= 0)
2889 /* Set number of cols to the default. */
2890 KdbNumberOfColsTerminal
= 80;
2894 /* Get the string */
2897 while (p
[0] != '\0')
2899 if ( p
> Buffer
+BufLength
)
2901 DbgPrint("Dmesg: error, p > Buffer+BufLength,d=%d", p
- (Buffer
+BufLength
));
2904 i
= strcspn(p
, "\n");
2906 // Are we out of buffer?
2907 if (p
+ i
> Buffer
+ BufLength
)
2908 // Leaving pager function:
2911 /* Calculate the number of lines which will be printed in the terminal
2912 * when outputting the current line
2915 RowsPrintedByTerminal
= (i
+ KdbNumberOfColsPrinted
- 1) / KdbNumberOfColsTerminal
;
2917 RowsPrintedByTerminal
= 0;
2920 RowsPrintedByTerminal
++;
2922 /*DbgPrint("!%d!%d!%d!%d!", KdbNumberOfRowsPrinted, KdbNumberOfColsPrinted, i, RowsPrintedByTerminal);*/
2924 /* Display a prompt if we printed one screen full of text */
2925 if (KdbNumberOfRowsTerminal
> 0 &&
2926 (LONG
)(KdbNumberOfRowsPrinted
+ RowsPrintedByTerminal
) >= KdbNumberOfRowsTerminal
)
2928 KdbRepeatLastCommand
= FALSE
;
2930 if (KdbNumberOfColsPrinted
> 0)
2933 DbgPrint("--- Press q to abort, e/End,h/Home,u/PgUp, other key/PgDn ---");
2934 RowsPrintedByTerminal
++;
2936 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
2937 c
= KdbpGetCharSerial();
2939 c
= KdbpGetCharKeyboard(&ScanCode
);
2943 /* Try to read '\n' which might follow '\r' - if \n is not received here
2944 * it will be interpreted as "return" when the next command should be read.
2946 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
2947 c
= KdbpTryGetCharSerial(5);
2949 c
= KdbpTryGetCharKeyboard(&ScanCode
, 5);
2952 //DbgPrint("\n"); //Consize version: don't show pressed key
2953 DbgPrint(" '%c'/scan=%04x\n", c
, ScanCode
); // Shows pressed key
2957 KdbOutputAborted
= TRUE
;
2960 if ( ScanCode
== KEYSC_END
|| c
=='e')
2962 PCHAR pBufEnd
= Buffer
+ BufLength
;
2963 p
= CountOnePageUp(Buffer
, BufLength
, pBufEnd
);
2964 i
= strcspn(p
, "\n");
2966 else if (ScanCode
== KEYSC_PAGEUP
|| c
=='u')
2968 p
= CountOnePageUp(Buffer
, BufLength
, p
);
2969 i
= strcspn(p
, "\n");
2971 else if (ScanCode
== KEYSC_HOME
|| c
=='h')
2974 i
= strcspn(p
, "\n");
2976 else if (ScanCode
== KEYSC_ARROWUP
)
2978 p
= CountOnePageUp(Buffer
, BufLength
, p
);
2979 i
= strcspn(p
, "\n");
2982 KdbNumberOfRowsPrinted
= 0;
2983 KdbNumberOfColsPrinted
= 0;
2986 /* Insert a NUL after the line and print only the current line. */
2987 if (p
[i
] == '\n' && p
[i
+ 1] != '\0')
2997 /* Remove escape sequences from the line if there's no terminal connected */
2998 if (!TerminalConnected
)
3000 while ((p2
= strrchr(p
, '\x1b'))) /* Look for escape character */
3005 while (!isalpha(p2
[j
++]));
3015 // The main printing of the current line:
3018 // restore not null char with saved:
3022 /* Set p to the start of the next line and
3023 * remember the number of rows/cols printed
3029 KdbNumberOfColsPrinted
= 0;
3033 ASSERT(p
[0] == '\0');
3034 KdbNumberOfColsPrinted
+= i
;
3037 KdbNumberOfRowsPrinted
+= RowsPrintedByTerminal
;
3041 /*!\brief Appends a command to the command history
3043 * \param Command Pointer to the command to append to the history.
3046 KdbpCommandHistoryAppend(
3049 ULONG Length1
= strlen(Command
) + 1;
3054 ASSERT(Length1
<= RTL_NUMBER_OF(KdbCommandHistoryBuffer
));
3057 (KdbCommandHistory
[KdbCommandHistoryIndex
] &&
3058 strcmp(KdbCommandHistory
[KdbCommandHistoryIndex
], Command
) == 0))
3063 /* Calculate Length1 and Length2 */
3064 Buffer
= KdbCommandHistoryBuffer
+ KdbCommandHistoryBufferIndex
;
3065 KdbCommandHistoryBufferIndex
+= Length1
;
3066 if (KdbCommandHistoryBufferIndex
>= (LONG
)RTL_NUMBER_OF(KdbCommandHistoryBuffer
))
3068 KdbCommandHistoryBufferIndex
-= RTL_NUMBER_OF(KdbCommandHistoryBuffer
);
3069 Length2
= KdbCommandHistoryBufferIndex
;
3073 /* Remove previous commands until there is enough space to append the new command */
3074 for (i
= KdbCommandHistoryIndex
; KdbCommandHistory
[i
];)
3077 (KdbCommandHistory
[i
] >= Buffer
||
3078 KdbCommandHistory
[i
] < (KdbCommandHistoryBuffer
+ KdbCommandHistoryBufferIndex
))) ||
3080 (KdbCommandHistory
[i
] >= Buffer
&&
3081 KdbCommandHistory
[i
] < (KdbCommandHistoryBuffer
+ KdbCommandHistoryBufferIndex
))))
3083 KdbCommandHistory
[i
] = NULL
;
3088 i
= RTL_NUMBER_OF(KdbCommandHistory
) - 1;
3090 if (i
== KdbCommandHistoryIndex
)
3094 /* Make sure the new command history entry is free */
3095 KdbCommandHistoryIndex
++;
3096 KdbCommandHistoryIndex
%= RTL_NUMBER_OF(KdbCommandHistory
);
3097 if (KdbCommandHistory
[KdbCommandHistoryIndex
])
3099 KdbCommandHistory
[KdbCommandHistoryIndex
] = NULL
;
3102 /* Append command */
3103 KdbCommandHistory
[KdbCommandHistoryIndex
] = Buffer
;
3104 ASSERT((KdbCommandHistory
[KdbCommandHistoryIndex
] + Length1
) <= KdbCommandHistoryBuffer
+ RTL_NUMBER_OF(KdbCommandHistoryBuffer
));
3105 memcpy(KdbCommandHistory
[KdbCommandHistoryIndex
], Command
, Length1
);
3108 memcpy(KdbCommandHistoryBuffer
, Command
+ Length1
, Length2
);
3112 /*!\brief Reads a line of user-input.
3114 * \param Buffer Buffer to store the input into. Trailing newlines are removed.
3115 * \param Size Size of \a Buffer.
3117 * \note Accepts only \n newlines, \r is ignored.
3125 PCHAR Orig
= Buffer
;
3128 static CHAR LastCommand
[1024];
3129 static CHAR NextKey
= '\0';
3130 INT CmdHistIndex
= -1;
3133 EchoOn
= !((KdbDebugState
& KD_DEBUG_KDNOECHO
) != 0);
3137 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
3139 Key
= (NextKey
== '\0') ? KdbpGetCharSerial() : NextKey
;
3142 if (Key
== KEY_ESC
) /* ESC */
3144 Key
= KdbpGetCharSerial();
3147 Key
= KdbpGetCharSerial();
3152 ScanCode
= KEY_SCAN_UP
;
3155 ScanCode
= KEY_SCAN_DOWN
;
3168 Key
= (NextKey
== '\0') ? KdbpGetCharKeyboard(&ScanCode
) : NextKey
;
3172 if ((ULONG
)(Buffer
- Orig
) >= (Size
- 1))
3174 /* Buffer is full, accept only newlines */
3181 /* Read the next char - this is to throw away a \n which most clients should
3184 KeStallExecutionProcessor(100000);
3186 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
3187 NextKey
= KdbpTryGetCharSerial(5);
3189 NextKey
= KdbpTryGetCharKeyboard(&ScanCode
, 5);
3191 if (NextKey
== '\n' || NextKey
== -1) /* \n or no response at all */
3197 * Repeat the last command if the user presses enter. Reduces the
3198 * risk of RSI when single-stepping.
3202 KdbRepeatLastCommand
= TRUE
;
3204 RtlStringCbCopyA(LastCommand
, sizeof(LastCommand
), Orig
);
3206 else if (KdbRepeatLastCommand
)
3207 RtlStringCbCopyA(Buffer
, Size
, LastCommand
);
3213 else if (Key
== KEY_BS
|| Key
== KEY_DEL
)
3221 KdbpPrint("%c %c", KEY_BS
, KEY_BS
);
3223 KdbpPrint(" %c", KEY_BS
);
3226 else if (ScanCode
== KEY_SCAN_UP
)
3228 BOOLEAN Print
= TRUE
;
3230 if (CmdHistIndex
< 0)
3232 CmdHistIndex
= KdbCommandHistoryIndex
;
3236 i
= CmdHistIndex
- 1;
3239 CmdHistIndex
= RTL_NUMBER_OF(KdbCommandHistory
) - 1;
3241 if (KdbCommandHistory
[i
] && i
!= KdbCommandHistoryIndex
)
3247 if (Print
&& KdbCommandHistory
[CmdHistIndex
])
3249 while (Buffer
> Orig
)
3255 KdbpPrint("%c %c", KEY_BS
, KEY_BS
);
3257 KdbpPrint(" %c", KEY_BS
);
3260 i
= min(strlen(KdbCommandHistory
[CmdHistIndex
]), Size
- 1);
3261 memcpy(Orig
, KdbCommandHistory
[CmdHistIndex
], i
);
3264 KdbpPrint("%s", Orig
);
3267 else if (ScanCode
== KEY_SCAN_DOWN
)
3269 if (CmdHistIndex
> 0 && CmdHistIndex
!= KdbCommandHistoryIndex
)
3271 i
= CmdHistIndex
+ 1;
3272 if (i
>= (INT
)RTL_NUMBER_OF(KdbCommandHistory
))
3275 if (KdbCommandHistory
[i
])
3278 while (Buffer
> Orig
)
3284 KdbpPrint("%c %c", KEY_BS
, KEY_BS
);
3286 KdbpPrint(" %c", KEY_BS
);
3289 i
= min(strlen(KdbCommandHistory
[CmdHistIndex
]), Size
- 1);
3290 memcpy(Orig
, KdbCommandHistory
[CmdHistIndex
], i
);
3293 KdbpPrint("%s", Orig
);
3300 KdbpPrint("%c", Key
);
3311 KdbRegisterCliCallback(
3317 /* Loop all entries */
3318 for (i
= 0; i
< _countof(KdbCliCallbacks
); i
++)
3320 /* Check if deregistering was requested */
3323 /* Check if this entry is the one that was registered */
3324 if (KdbCliCallbacks
[i
] == Callback
)
3326 /* Delete it and report success */
3327 KdbCliCallbacks
[i
] = NULL
;
3333 /* Check if this entry is free */
3334 if (KdbCliCallbacks
[i
] == NULL
)
3336 /* Set it and and report success */
3337 KdbCliCallbacks
[i
] = Callback
;
3347 /*! \brief Invokes registered CLI callbacks until one of them handled the
3350 * \param Command - Command line to parse and execute if possible.
3351 * \param Argc - Number of arguments in Argv
3352 * \param Argv - Array of strings, each of them containing one argument.
3354 * \return TRUE, if the command was handled, FALSE if it was not handled.
3358 KdbpInvokeCliCallbacks(
3365 /* Loop all entries */
3366 for (i
= 0; i
< _countof(KdbCliCallbacks
); i
++)
3368 /* Check if this entry is registered */
3369 if (KdbCliCallbacks
[i
])
3371 /* Invoke the callback and check if it handled the command */
3372 if (KdbCliCallbacks
[i
](Command
, Argc
, Argv
))
3379 /* None of the callbacks handled the command */
3384 /*!\brief Parses command line and executes command if found
3386 * \param Command Command line to parse and execute if possible.
3388 * \retval TRUE Don't continue execution.
3389 * \retval FALSE Continue execution (leave KDB)
3398 // FIXME: for what do we need a 1024 characters command line and 256 tokens?
3399 static PCH Argv
[256];
3400 static CHAR OrigCommand
[1024];
3402 RtlStringCbCopyA(OrigCommand
, sizeof(OrigCommand
), Command
);
3409 while (*p
== '\t' || *p
== ' ')
3415 i
= strcspn(p
, "\t ");
3428 for (i
= 0; i
< RTL_NUMBER_OF(KdbDebuggerCommands
); i
++)
3430 if (!KdbDebuggerCommands
[i
].Name
)
3433 if (strcmp(KdbDebuggerCommands
[i
].Name
, Argv
[0]) == 0)
3435 return KdbDebuggerCommands
[i
].Fn(Argc
, Argv
);
3439 /* Now invoke the registered callbacks */
3440 if (KdbpInvokeCliCallbacks(Command
, Argc
, Argv
))
3445 KdbpPrint("Command '%s' is unknown.\n", OrigCommand
);
3449 /*!\brief KDB Main Loop.
3451 * \param EnteredOnSingleStep TRUE if KDB was entered on single step.
3455 IN BOOLEAN EnteredOnSingleStep
)
3457 static CHAR Command
[1024];
3460 if (EnteredOnSingleStep
)
3462 if (!KdbSymPrintAddress((PVOID
)KdbCurrentTrapFrame
->Tf
.Eip
, &KdbCurrentTrapFrame
->Tf
))
3464 KdbpPrint("<%x>", KdbCurrentTrapFrame
->Tf
.Eip
);
3468 if (KdbpDisassemble(KdbCurrentTrapFrame
->Tf
.Eip
, KdbUseIntelSyntax
) < 0)
3470 KdbpPrint("<INVALID>");
3475 /* Flush the input buffer */
3476 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
3478 while (KdbpTryGetCharSerial(1) != -1);
3483 while (KdbpTryGetCharKeyboard(&ScanCode
, 1) != -1);
3489 /* Reset the number of rows/cols printed */
3490 KdbNumberOfRowsPrinted
= KdbNumberOfColsPrinted
= 0;
3492 /* Print the prompt */
3493 KdbpPrint("kdb:> ");
3495 /* Read a command and remember it */
3496 KdbpReadCommand(Command
, sizeof (Command
));
3497 KdbpCommandHistoryAppend(Command
);
3499 /* Reset the number of rows/cols printed and output aborted state */
3500 KdbNumberOfRowsPrinted
= KdbNumberOfColsPrinted
= 0;
3501 KdbOutputAborted
= FALSE
;
3503 /* Call the command */
3504 Continue
= KdbpDoCommand(Command
);
3505 KdbOutputAborted
= FALSE
;
3510 /*!\brief Called when a module is loaded.
3512 * \param Name Filename of the module which was loaded.
3515 KdbpCliModuleLoaded(
3516 IN PUNICODE_STRING Name
)
3518 if (!KdbBreakOnModuleLoad
)
3521 KdbpPrint("Module %wZ loaded.\n", Name
);
3522 DbgBreakPointWithStatus(DBG_STATUS_CONTROL_C
);
3525 /*!\brief This function is called by KdbEnterDebuggerException...
3527 * Used to interpret the init file in a context with a trapframe setup
3528 * (KdbpCliInit call KdbEnter which will call KdbEnterDebuggerException which will
3529 * call this function if KdbInitFileBuffer is not NULL.
3532 KdbpCliInterpretInitFile(VOID
)
3538 /* Execute the commands in the init file */
3539 DPRINT("KDB: Executing KDBinit file...\n");
3540 p1
= KdbInitFileBuffer
;
3541 while (p1
[0] != '\0')
3543 i
= strcspn(p1
, "\r\n");
3549 /* Look for "break" command and comments */
3552 while (isspace(p2
[0]))
3555 if (strncmp(p2
, "break", sizeof("break")-1) == 0 &&
3556 (p2
[sizeof("break")-1] == '\0' || isspace(p2
[sizeof("break")-1])))
3558 /* break into the debugger */
3559 KdbpCliMainLoop(FALSE
);
3561 else if (p2
[0] != '#' && p2
[0] != '\0') /* Ignore empty lines and comments */
3570 while (p1
[0] == '\r' || p1
[0] == '\n')
3573 DPRINT("KDB: KDBinit executed\n");
3576 /*!\brief Called when KDB is initialized
3578 * Reads the KDBinit file from the SystemRoot\System32\drivers\etc directory and executes it.
3584 OBJECT_ATTRIBUTES ObjectAttributes
;
3585 UNICODE_STRING FileName
;
3586 IO_STATUS_BLOCK Iosb
;
3587 FILE_STANDARD_INFORMATION FileStdInfo
;
3588 HANDLE hFile
= NULL
;
3593 /* Initialize the object attributes */
3594 RtlInitUnicodeString(&FileName
, L
"\\SystemRoot\\System32\\drivers\\etc\\KDBinit");
3595 InitializeObjectAttributes(&ObjectAttributes
, &FileName
, 0, NULL
, NULL
);
3598 Status
= ZwOpenFile(&hFile
, FILE_READ_DATA
| SYNCHRONIZE
,
3599 &ObjectAttributes
, &Iosb
, 0,
3600 FILE_NON_DIRECTORY_FILE
| FILE_SYNCHRONOUS_IO_NONALERT
|
3601 FILE_NO_INTERMEDIATE_BUFFERING
);
3602 if (!NT_SUCCESS(Status
))
3604 DPRINT("Could not open \\SystemRoot\\System32\\drivers\\etc\\KDBinit (Status 0x%x)", Status
);
3608 /* Get the size of the file */
3609 Status
= ZwQueryInformationFile(hFile
, &Iosb
, &FileStdInfo
, sizeof (FileStdInfo
),
3610 FileStandardInformation
);
3611 if (!NT_SUCCESS(Status
))
3614 DPRINT("Could not query size of \\SystemRoot\\System32\\drivers\\etc\\KDBinit (Status 0x%x)", Status
);
3617 FileSize
= FileStdInfo
.EndOfFile
.u
.LowPart
;
3619 /* Allocate memory for the file */
3620 FileBuffer
= ExAllocatePool(PagedPool
, FileSize
+ 1); /* add 1 byte for terminating '\0' */
3624 DPRINT("Could not allocate %d bytes for KDBinit file\n", FileSize
);
3628 /* Load file into memory */
3629 Status
= ZwReadFile(hFile
, NULL
, NULL
, NULL
, &Iosb
, FileBuffer
, FileSize
, NULL
, NULL
);
3632 if (!NT_SUCCESS(Status
) && Status
!= STATUS_END_OF_FILE
)
3634 ExFreePool(FileBuffer
);
3635 DPRINT("Could not read KDBinit file into memory (Status 0x%lx)\n", Status
);
3639 FileSize
= min(FileSize
, (INT
)Iosb
.Information
);
3640 FileBuffer
[FileSize
] = '\0';
3642 /* Enter critical section */
3643 OldEflags
= __readeflags();
3646 /* Interpret the init file... */
3647 KdbInitFileBuffer
= FileBuffer
;
3649 KdbInitFileBuffer
= NULL
;
3651 /* Leave critical section */
3652 __writeeflags(OldEflags
);
3654 ExFreePool(FileBuffer
);
3659 KdpSerialDebugPrint(
3664 STRING KdpPromptString
= RTL_CONSTANT_STRING("kdb:> ");
3665 extern KSPIN_LOCK KdpSerialSpinLock
;
3670 _In_reads_bytes_(InStringLength
) PCHAR UnsafeInString
,
3671 _In_ USHORT InStringLength
,
3672 _Out_writes_bytes_(OutStringLength
) PCHAR UnsafeOutString
,
3673 _In_ USHORT OutStringLength
,
3674 _In_ KPROCESSOR_MODE PreviousMode
)
3678 ULONG DummyScanCode
;
3682 CHAR InStringBuffer
[512];
3683 CHAR OutStringBuffer
[512];
3685 /* Normalize the lengths */
3686 InStringLength
= min(InStringLength
,
3687 sizeof(InStringBuffer
));
3688 OutStringLength
= min(OutStringLength
,
3689 sizeof(OutStringBuffer
));
3691 /* Check if we need to verify the string */
3692 if (PreviousMode
!= KernelMode
)
3694 /* Handle user-mode buffers safely */
3697 /* Probe the prompt */
3698 ProbeForRead(UnsafeInString
,
3702 /* Capture prompt */
3703 InString
= InStringBuffer
;
3704 RtlCopyMemory(InString
,
3708 /* Probe and make room for response */
3709 ProbeForWrite(UnsafeOutString
,
3712 OutString
= OutStringBuffer
;
3714 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
3716 /* Bad string pointer, bail out */
3717 _SEH2_YIELD(return 0);
3723 InString
= UnsafeInString
;
3724 OutString
= UnsafeOutString
;
3727 /* Acquire the printing spinlock without waiting at raised IRQL */
3730 /* Wait when the spinlock becomes available */
3731 while (!KeTestSpinLock(&KdpSerialSpinLock
));
3733 /* Spinlock was free, raise IRQL */
3734 KeRaiseIrql(HIGH_LEVEL
, &OldIrql
);
3736 /* Try to get the spinlock */
3737 if (KeTryToAcquireSpinLockAtDpcLevel(&KdpSerialSpinLock
))
3740 /* Someone else got the spinlock, lower IRQL back */
3741 KeLowerIrql(OldIrql
);
3744 /* Loop the string to send */
3745 for (i
= 0; i
< InStringLength
; i
++)
3747 /* Print it to serial */
3748 KdPortPutByteEx(&SerialPortInfo
, *(PCHAR
)(InString
+ i
));
3751 /* Print a new line for log neatness */
3752 KdPortPutByteEx(&SerialPortInfo
, '\r');
3753 KdPortPutByteEx(&SerialPortInfo
, '\n');
3755 /* Print the kdb prompt */
3756 for (i
= 0; i
< KdpPromptString
.Length
; i
++)
3758 /* Print it to serial */
3759 KdPortPutByteEx(&SerialPortInfo
,
3760 *(KdpPromptString
.Buffer
+ i
));
3763 if (!(KdbDebugState
& KD_DEBUG_KDSERIAL
))
3766 /* Loop the whole string */
3767 for (i
= 0; i
< OutStringLength
; i
++)
3769 /* Check if this is serial debugging mode */
3770 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
3772 /* Get the character from serial */
3775 Response
= KdbpTryGetCharSerial(MAXULONG
);
3776 } while (Response
== -1);
3780 /* Get the response from the keyboard */
3783 Response
= KdbpTryGetCharKeyboard(&DummyScanCode
, MAXULONG
);
3784 } while (Response
== -1);
3787 /* Check for return */
3788 if (Response
== '\r')
3791 * We might need to discard the next '\n'.
3792 * Wait a bit to make sure we receive it.
3794 KeStallExecutionProcessor(100000);
3796 /* Check the mode */
3797 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
3799 /* Read and discard the next character, if any */
3800 KdbpTryGetCharSerial(5);
3804 /* Read and discard the next character, if any */
3805 KdbpTryGetCharKeyboard(&DummyScanCode
, 5);
3809 * Null terminate the output string -- documentation states that
3810 * DbgPrompt does not null terminate, but it does
3812 *(PCHAR
)(OutString
+ i
) = 0;
3816 /* Write it back and print it to the log */
3817 *(PCHAR
)(OutString
+ i
) = Response
;
3818 KdPortPutByteEx(&SerialPortInfo
, Response
);
3821 if (!(KdbDebugState
& KD_DEBUG_KDSERIAL
))
3824 /* Print a new line */
3825 KdPortPutByteEx(&SerialPortInfo
, '\r');
3826 KdPortPutByteEx(&SerialPortInfo
, '\n');
3828 /* Release spinlock */
3829 KiReleaseSpinLock(&KdpSerialSpinLock
);
3831 /* Lower IRQL back */
3832 KeLowerIrql(OldIrql
);
3834 /* Copy back response if required */
3835 if (PreviousMode
!= KernelMode
)
3839 /* Safely copy back response to user mode */
3840 RtlCopyMemory(UnsafeOutString
,
3844 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
3846 /* String became invalid after we exited, fail */
3847 _SEH2_YIELD(return 0);
3852 /* Return the length */