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
[]);
97 BOOLEAN
ExpKdbgExtDefWrites(ULONG Argc
, PCHAR Argv
[]);
99 BOOLEAN
PspKdbgIrpFind(ULONG Argc
, PCHAR Argv
[]);
102 static BOOLEAN
KdbpCmdPrintStruct(ULONG Argc
, PCHAR Argv
[]);
105 /* GLOBALS *******************************************************************/
107 static PKDBG_CLI_ROUTINE KdbCliCallbacks
[10];
108 static BOOLEAN KdbUseIntelSyntax
= FALSE
; /* Set to TRUE for intel syntax */
109 static BOOLEAN KdbBreakOnModuleLoad
= FALSE
; /* Set to TRUE to break into KDB when a module is loaded */
111 static CHAR KdbCommandHistoryBuffer
[2048]; /* Command history string ringbuffer */
112 static PCHAR KdbCommandHistory
[sizeof(KdbCommandHistoryBuffer
) / 8] = { NULL
}; /* Command history ringbuffer */
113 static LONG KdbCommandHistoryBufferIndex
= 0;
114 static LONG KdbCommandHistoryIndex
= 0;
116 static ULONG KdbNumberOfRowsPrinted
= 0;
117 static ULONG KdbNumberOfColsPrinted
= 0;
118 static BOOLEAN KdbOutputAborted
= FALSE
;
119 static BOOLEAN KdbRepeatLastCommand
= FALSE
;
120 static LONG KdbNumberOfRowsTerminal
= -1;
121 static LONG KdbNumberOfColsTerminal
= -1;
123 PCHAR KdbInitFileBuffer
= NULL
; /* Buffer where KDBinit file is loaded into during initialization */
124 BOOLEAN KdbpBugCheckRequested
= FALSE
;
127 /* defined in ../kd/kdio.c, declare here: */
128 extern volatile BOOLEAN KdbpIsInDmesgMode
;
129 extern const ULONG KdpDmesgBufferSize
;
130 extern PCHAR KdpDmesgBuffer
;
131 extern volatile ULONG KdpDmesgCurrentPosition
;
132 extern volatile ULONG KdpDmesgFreeBytes
;
133 extern volatile ULONG KdbDmesgTotalWritten
;
140 BOOLEAN (*Fn
)(ULONG Argc
, PCHAR Argv
[]);
141 } KdbDebuggerCommands
[] = {
143 { NULL
, NULL
, "Data", NULL
},
144 { "?", "? expression", "Evaluate expression.", KdbpCmdEvalExpression
},
145 { "disasm", "disasm [address] [L count]", "Disassemble count instructions at address.", KdbpCmdDisassembleX
},
146 { "x", "x [address] [L count]", "Display count dwords, starting at addr.", KdbpCmdDisassembleX
},
147 { "regs", "regs", "Display general purpose registers.", KdbpCmdRegs
},
148 { "cregs", "cregs", "Display control registers.", KdbpCmdRegs
},
149 { "sregs", "sregs", "Display status registers.", KdbpCmdRegs
},
150 { "dregs", "dregs", "Display debug registers.", KdbpCmdRegs
},
151 { "bt", "bt [*frameaddr|thread id]", "Prints current backtrace or from given frame addr", KdbpCmdBackTrace
},
153 { "dt", "dt [mod] [type] [addr]", "Print a struct. Addr is optional.", KdbpCmdPrintStruct
},
157 { NULL
, NULL
, "Flow control", NULL
},
158 { "cont", "cont", "Continue execution (leave debugger)", KdbpCmdContinue
},
159 { "step", "step [count]", "Execute single instructions, stepping into interrupts.", KdbpCmdStep
},
160 { "next", "next [count]", "Execute single instructions, skipping calls and reps.", KdbpCmdStep
},
161 { "bl", "bl", "List breakpoints.", KdbpCmdBreakPointList
},
162 { "be", "be [breakpoint]", "Enable breakpoint.", KdbpCmdEnableDisableClearBreakPoint
},
163 { "bd", "bd [breakpoint]", "Disable breakpoint.", KdbpCmdEnableDisableClearBreakPoint
},
164 { "bc", "bc [breakpoint]", "Clear breakpoint.", KdbpCmdEnableDisableClearBreakPoint
},
165 { "bpx", "bpx [address] [IF condition]", "Set software execution breakpoint at address.", KdbpCmdBreakPoint
},
166 { "bpm", "bpm [r|w|rw|x] [byte|word|dword] [address] [IF condition]", "Set memory breakpoint at address.", KdbpCmdBreakPoint
},
169 { NULL
, NULL
, "Process/Thread", NULL
},
170 { "thread", "thread [list[ pid]|[attach ]tid]", "List threads in current or specified process, display thread with given id or attach to thread.", KdbpCmdThread
},
171 { "proc", "proc [list|[attach ]pid]", "List processes, display process with given id or attach to process.", KdbpCmdProc
},
173 /* System information */
174 { NULL
, NULL
, "System info", NULL
},
175 { "mod", "mod [address]", "List all modules or the one containing address.", KdbpCmdMod
},
176 { "gdt", "gdt", "Display global descriptor table.", KdbpCmdGdtLdtIdt
},
177 { "ldt", "ldt", "Display local descriptor table.", KdbpCmdGdtLdtIdt
},
178 { "idt", "idt", "Display interrupt descriptor table.", KdbpCmdGdtLdtIdt
},
179 { "pcr", "pcr", "Display processor control region.", KdbpCmdPcr
},
180 { "tss", "tss", "Display task state segment.", KdbpCmdTss
},
183 { NULL
, NULL
, "Others", NULL
},
184 { "bugcheck", "bugcheck", "Bugchecks the system.", KdbpCmdBugCheck
},
185 { "reboot", "reboot", "Reboots the system.", KdbpCmdReboot
},
186 { "filter", "filter [error|warning|trace|info|level]+|-[componentname|default]", "Enable/disable debug channels", KdbpCmdFilter
},
187 { "set", "set [var] [value]", "Sets var to value or displays value of var.", KdbpCmdSet
},
188 { "dmesg", "dmesg", "Display debug messages on screen, with navigation on pages.", KdbpCmdDmesg
},
189 { "kmsg", "kmsg", "Kernel dmesg. Alias for dmesg.", KdbpCmdDmesg
},
190 { "help", "help", "Display help screen.", KdbpCmdHelp
},
191 { "!pool", "!pool [Address [Flags]]", "Display information about pool allocations.", ExpKdbgExtPool
},
192 { "!poolused", "!poolused [Flags [Tag]]", "Display pool usage.", ExpKdbgExtPoolUsed
},
193 { "!filecache", "!filecache", "Display cache usage.", ExpKdbgExtFileCache
},
194 { "!defwrites", "!defwrites", "Display cache write values.", ExpKdbgExtDefWrites
},
195 { "!irpfind", "!irpfind [criteria data]", "Lists IRPs potentially matching criteria", PspKdbgIrpFind
},
198 /* FUNCTIONS *****************************************************************/
200 /*!\brief Transform a component name to an integer
202 * \param ComponentName The name of the component.
203 * \param ComponentId Receives the component id on success.
205 * \retval TRUE Success.
206 * \retval FALSE Failure.
210 IN PCCH ComponentName
,
211 OUT PULONG ComponentId
)
222 { "DEFAULT", MAXULONG
},
223 { "SYSTEM", DPFLTR_SYSTEM_ID
},
224 { "SMSS", DPFLTR_SMSS_ID
},
225 { "SETUP", DPFLTR_SETUP_ID
},
226 { "NTFS", DPFLTR_NTFS_ID
},
227 { "FSTUB", DPFLTR_FSTUB_ID
},
228 { "CRASHDUMP", DPFLTR_CRASHDUMP_ID
},
229 { "CDAUDIO", DPFLTR_CDAUDIO_ID
},
230 { "CDROM", DPFLTR_CDROM_ID
},
231 { "CLASSPNP", DPFLTR_CLASSPNP_ID
},
232 { "DISK", DPFLTR_DISK_ID
},
233 { "REDBOOK", DPFLTR_REDBOOK_ID
},
234 { "STORPROP", DPFLTR_STORPROP_ID
},
235 { "SCSIPORT", DPFLTR_SCSIPORT_ID
},
236 { "SCSIMINIPORT", DPFLTR_SCSIMINIPORT_ID
},
237 { "CONFIG", DPFLTR_CONFIG_ID
},
238 { "I8042PRT", DPFLTR_I8042PRT_ID
},
239 { "SERMOUSE", DPFLTR_SERMOUSE_ID
},
240 { "LSERMOUS", DPFLTR_LSERMOUS_ID
},
241 { "KBDHID", DPFLTR_KBDHID_ID
},
242 { "MOUHID", DPFLTR_MOUHID_ID
},
243 { "KBDCLASS", DPFLTR_KBDCLASS_ID
},
244 { "MOUCLASS", DPFLTR_MOUCLASS_ID
},
245 { "TWOTRACK", DPFLTR_TWOTRACK_ID
},
246 { "WMILIB", DPFLTR_WMILIB_ID
},
247 { "ACPI", DPFLTR_ACPI_ID
},
248 { "AMLI", DPFLTR_AMLI_ID
},
249 { "HALIA64", DPFLTR_HALIA64_ID
},
250 { "VIDEO", DPFLTR_VIDEO_ID
},
251 { "SVCHOST", DPFLTR_SVCHOST_ID
},
252 { "VIDEOPRT", DPFLTR_VIDEOPRT_ID
},
253 { "TCPIP", DPFLTR_TCPIP_ID
},
254 { "DMSYNTH", DPFLTR_DMSYNTH_ID
},
255 { "NTOSPNP", DPFLTR_NTOSPNP_ID
},
256 { "FASTFAT", DPFLTR_FASTFAT_ID
},
257 { "SAMSS", DPFLTR_SAMSS_ID
},
258 { "PNPMGR", DPFLTR_PNPMGR_ID
},
259 { "NETAPI", DPFLTR_NETAPI_ID
},
260 { "SCSERVER", DPFLTR_SCSERVER_ID
},
261 { "SCCLIENT", DPFLTR_SCCLIENT_ID
},
262 { "SERIAL", DPFLTR_SERIAL_ID
},
263 { "SERENUM", DPFLTR_SERENUM_ID
},
264 { "UHCD", DPFLTR_UHCD_ID
},
265 { "RPCPROXY", DPFLTR_RPCPROXY_ID
},
266 { "AUTOCHK", DPFLTR_AUTOCHK_ID
},
267 { "DCOMSS", DPFLTR_DCOMSS_ID
},
268 { "UNIMODEM", DPFLTR_UNIMODEM_ID
},
269 { "SIS", DPFLTR_SIS_ID
},
270 { "FLTMGR", DPFLTR_FLTMGR_ID
},
271 { "WMICORE", DPFLTR_WMICORE_ID
},
272 { "BURNENG", DPFLTR_BURNENG_ID
},
273 { "IMAPI", DPFLTR_IMAPI_ID
},
274 { "SXS", DPFLTR_SXS_ID
},
275 { "FUSION", DPFLTR_FUSION_ID
},
276 { "IDLETASK", DPFLTR_IDLETASK_ID
},
277 { "SOFTPCI", DPFLTR_SOFTPCI_ID
},
278 { "TAPE", DPFLTR_TAPE_ID
},
279 { "MCHGR", DPFLTR_MCHGR_ID
},
280 { "IDEP", DPFLTR_IDEP_ID
},
281 { "PCIIDE", DPFLTR_PCIIDE_ID
},
282 { "FLOPPY", DPFLTR_FLOPPY_ID
},
283 { "FDC", DPFLTR_FDC_ID
},
284 { "TERMSRV", DPFLTR_TERMSRV_ID
},
285 { "W32TIME", DPFLTR_W32TIME_ID
},
286 { "PREFETCHER", DPFLTR_PREFETCHER_ID
},
287 { "RSFILTER", DPFLTR_RSFILTER_ID
},
288 { "FCPORT", DPFLTR_FCPORT_ID
},
289 { "PCI", DPFLTR_PCI_ID
},
290 { "DMIO", DPFLTR_DMIO_ID
},
291 { "DMCONFIG", DPFLTR_DMCONFIG_ID
},
292 { "DMADMIN", DPFLTR_DMADMIN_ID
},
293 { "WSOCKTRANSPORT", DPFLTR_WSOCKTRANSPORT_ID
},
294 { "VSS", DPFLTR_VSS_ID
},
295 { "PNPMEM", DPFLTR_PNPMEM_ID
},
296 { "PROCESSOR", DPFLTR_PROCESSOR_ID
},
297 { "DMSERVER", DPFLTR_DMSERVER_ID
},
298 { "SR", DPFLTR_SR_ID
},
299 { "INFINIBAND", DPFLTR_INFINIBAND_ID
},
300 { "IHVDRIVER", DPFLTR_IHVDRIVER_ID
},
301 { "IHVVIDEO", DPFLTR_IHVVIDEO_ID
},
302 { "IHVAUDIO", DPFLTR_IHVAUDIO_ID
},
303 { "IHVNETWORK", DPFLTR_IHVNETWORK_ID
},
304 { "IHVSTREAMING", DPFLTR_IHVSTREAMING_ID
},
305 { "IHVBUS", DPFLTR_IHVBUS_ID
},
306 { "HPS", DPFLTR_HPS_ID
},
307 { "RTLTHREADPOOL", DPFLTR_RTLTHREADPOOL_ID
},
308 { "LDR", DPFLTR_LDR_ID
},
309 { "TCPIP6", DPFLTR_TCPIP6_ID
},
310 { "ISAPNP", DPFLTR_ISAPNP_ID
},
311 { "SHPC", DPFLTR_SHPC_ID
},
312 { "STORPORT", DPFLTR_STORPORT_ID
},
313 { "STORMINIPORT", DPFLTR_STORMINIPORT_ID
},
314 { "PRINTSPOOLER", DPFLTR_PRINTSPOOLER_ID
},
315 { "VSSDYNDISK", DPFLTR_VSSDYNDISK_ID
},
316 { "VERIFIER", DPFLTR_VERIFIER_ID
},
317 { "VDS", DPFLTR_VDS_ID
},
318 { "VDSBAS", DPFLTR_VDSBAS_ID
},
319 { "VDSDYN", DPFLTR_VDSDYN_ID
},
320 { "VDSDYNDR", DPFLTR_VDSDYNDR_ID
},
321 { "VDSLDR", DPFLTR_VDSLDR_ID
},
322 { "VDSUTIL", DPFLTR_VDSUTIL_ID
},
323 { "DFRGIFC", DPFLTR_DFRGIFC_ID
},
324 { "MM", DPFLTR_MM_ID
},
325 { "DFSC", DPFLTR_DFSC_ID
},
326 { "WOW64", DPFLTR_WOW64_ID
},
327 { "ALPC", DPFLTR_ALPC_ID
},
328 { "WDI", DPFLTR_WDI_ID
},
329 { "PERFLIB", DPFLTR_PERFLIB_ID
},
330 { "KTM", DPFLTR_KTM_ID
},
331 { "IOSTRESS", DPFLTR_IOSTRESS_ID
},
332 { "HEAP", DPFLTR_HEAP_ID
},
333 { "WHEA", DPFLTR_WHEA_ID
},
334 { "USERGDI", DPFLTR_USERGDI_ID
},
335 { "MMCSS", DPFLTR_MMCSS_ID
},
336 { "TPM", DPFLTR_TPM_ID
},
337 { "THREADORDER", DPFLTR_THREADORDER_ID
},
338 { "ENVIRON", DPFLTR_ENVIRON_ID
},
339 { "EMS", DPFLTR_EMS_ID
},
340 { "WDT", DPFLTR_WDT_ID
},
341 { "FVEVOL", DPFLTR_FVEVOL_ID
},
342 { "NDIS", DPFLTR_NDIS_ID
},
343 { "NVCTRACE", DPFLTR_NVCTRACE_ID
},
344 { "LUAFV", DPFLTR_LUAFV_ID
},
345 { "APPCOMPAT", DPFLTR_APPCOMPAT_ID
},
346 { "USBSTOR", DPFLTR_USBSTOR_ID
},
347 { "SBP2PORT", DPFLTR_SBP2PORT_ID
},
348 { "COVERAGE", DPFLTR_COVERAGE_ID
},
349 { "CACHEMGR", DPFLTR_CACHEMGR_ID
},
350 { "MOUNTMGR", DPFLTR_MOUNTMGR_ID
},
351 { "CFR", DPFLTR_CFR_ID
},
352 { "TXF", DPFLTR_TXF_ID
},
353 { "KSECDD", DPFLTR_KSECDD_ID
},
354 { "FLTREGRESS", DPFLTR_FLTREGRESS_ID
},
355 { "MPIO", DPFLTR_MPIO_ID
},
356 { "MSDSM", DPFLTR_MSDSM_ID
},
357 { "UDFS", DPFLTR_UDFS_ID
},
358 { "PSHED", DPFLTR_PSHED_ID
},
359 { "STORVSP", DPFLTR_STORVSP_ID
},
360 { "LSASS", DPFLTR_LSASS_ID
},
361 { "SSPICLI", DPFLTR_SSPICLI_ID
},
362 { "CNG", DPFLTR_CNG_ID
},
363 { "EXFAT", DPFLTR_EXFAT_ID
},
364 { "FILETRACE", DPFLTR_FILETRACE_ID
},
365 { "XSAVE", DPFLTR_XSAVE_ID
},
366 { "SE", DPFLTR_SE_ID
},
367 { "DRIVEEXTENDER", DPFLTR_DRIVEEXTENDER_ID
},
370 for (i
= 0; i
< sizeof(ComponentTable
) / sizeof(ComponentTable
[0]); i
++)
372 if (_stricmp(ComponentName
, ComponentTable
[i
].Name
) == 0)
374 *ComponentId
= ComponentTable
[i
].Id
;
382 /*!\brief Evaluates an expression...
384 * Much like KdbpRpnEvaluateExpression, but prints the error message (if any)
385 * at the given offset.
387 * \param Expression Expression to evaluate.
388 * \param ErrOffset Offset (in characters) to print the error message at.
389 * \param Result Receives the result on success.
391 * \retval TRUE Success.
392 * \retval FALSE Failure.
395 KdbpEvaluateExpression(
398 OUT PULONGLONG Result
)
400 static CHAR ErrMsgBuffer
[130] = "^ ";
401 LONG ExpressionErrOffset
= -1;
402 PCHAR ErrMsg
= ErrMsgBuffer
;
405 Ok
= KdbpRpnEvaluateExpression(Expression
, KdbCurrentTrapFrame
, Result
,
406 &ExpressionErrOffset
, ErrMsgBuffer
+ 2);
409 if (ExpressionErrOffset
>= 0)
410 ExpressionErrOffset
+= ErrOffset
;
414 KdbpPrint("%*s%s\n", ExpressionErrOffset
, "", ErrMsg
);
424 OUT ULONG_PTR
*pulValue
)
428 /* Skip optional '0x' prefix */
429 if ((pszNum
[0] == '0') && ((pszNum
[1] == 'x') || (pszNum
[1] == 'X')))
432 /* Make a number from the string (hex) */
433 *pulValue
= strtoul(pszNum
, &endptr
, 16);
435 return (*endptr
== '\0');
438 /*!\brief Evaluates an expression and displays the result.
441 KdbpCmdEvalExpression(
446 ULONGLONG Result
= 0;
453 KdbpPrint("?: Argument required\n");
457 /* Put the arguments back together */
459 for (i
= 1; i
< Argc
; i
++)
461 len
= strlen(Argv
[i
]);
465 /* Evaluate the expression */
466 Ok
= KdbpEvaluateExpression(Argv
[1], sizeof("kdb:> ")-1 + (Argv
[1]-Argv
[0]), &Result
);
469 if (Result
> 0x00000000ffffffffLL
)
471 if (Result
& 0x8000000000000000LL
)
472 KdbpPrint("0x%016I64x %20I64u %20I64d\n", Result
, Result
, Result
);
474 KdbpPrint("0x%016I64x %20I64u\n", Result
, Result
);
480 if (ul
<= 0xff && ul
>= 0x80)
481 l
= (LONG
)((CHAR
)ul
);
482 else if (ul
<= 0xffff && ul
>= 0x8000)
483 l
= (LONG
)((SHORT
)ul
);
488 KdbpPrint("0x%08lx %10lu %10ld\n", ul
, ul
, l
);
490 KdbpPrint("0x%08lx %10lu\n", ul
, ul
);
499 /*!\brief Print a struct
502 KdbpPrintStructInternal
507 PROSSYM_AGGREGATE Aggregate
)
511 PROSSYM_AGGREGATE_MEMBER Member
;
512 ULONG IndentLen
= strlen(Indent
);
513 ROSSYM_AGGREGATE MemberAggregate
= {0 };
515 for (i
= 0; i
< Aggregate
->NumElements
; i
++) {
516 Member
= &Aggregate
->Elements
[i
];
517 KdbpPrint("%s%p+%x: %s", Indent
, ((PCHAR
)BaseAddress
) + Member
->BaseOffset
, Member
->Size
, Member
->Name
? Member
->Name
: "<anoymous>");
519 if (!strcmp(Member
->Type
, "_UNICODE_STRING")) {
520 KdbpPrint("\"%wZ\"\n", ((PCHAR
)BaseAddress
) + Member
->BaseOffset
);
522 } else if (!strcmp(Member
->Type
, "PUNICODE_STRING")) {
523 KdbpPrint("\"%wZ\"\n", *(((PUNICODE_STRING
*)((PCHAR
)BaseAddress
) + Member
->BaseOffset
)));
526 switch (Member
->Size
) {
532 if (NT_SUCCESS(KdbpSafeReadMemory(&Result
, ((PCHAR
)BaseAddress
) + Member
->BaseOffset
, Member
->Size
))) {
534 Result
>>= Member
->FirstBit
;
535 Result
&= ((1 << Member
->Bits
) - 1);
537 KdbpPrint(" %lx\n", Result
);
543 if (Member
->Size
< 8) {
544 if (NT_SUCCESS(KdbpSafeReadMemory(&Result
, ((PCHAR
)BaseAddress
) + Member
->BaseOffset
, Member
->Size
))) {
546 for (j
= 0; j
< Member
->Size
; j
++) {
547 KdbpPrint(" %02x", (int)(Result
& 0xff));
550 } else goto readfail
;
552 KdbpPrint(" %s @ %p {\n", Member
->Type
, ((PCHAR
)BaseAddress
) + Member
->BaseOffset
);
553 Indent
[IndentLen
] = ' ';
554 if (RosSymAggregate(Info
, Member
->Type
, &MemberAggregate
)) {
555 KdbpPrintStructInternal(Info
, Indent
, DoRead
, ((PCHAR
)BaseAddress
) + Member
->BaseOffset
, &MemberAggregate
);
556 RosSymFreeAggregate(&MemberAggregate
);
558 Indent
[IndentLen
] = 0;
559 KdbpPrint("%s}\n", Indent
);
565 if (Member
->Size
<= 8) {
568 KdbpPrint(" %s @ %x {\n", Member
->Type
, Member
->BaseOffset
);
569 Indent
[IndentLen
] = ' ';
570 if (RosSymAggregate(Info
, Member
->Type
, &MemberAggregate
)) {
571 KdbpPrintStructInternal(Info
, Indent
, DoRead
, BaseAddress
, &MemberAggregate
);
572 RosSymFreeAggregate(&MemberAggregate
);
574 Indent
[IndentLen
] = 0;
575 KdbpPrint("%s}\n", Indent
);
581 PROSSYM_INFO
KdbpSymFindCachedFile(PUNICODE_STRING ModName
);
589 ULONGLONG Result
= 0;
590 PVOID BaseAddress
= 0;
591 ROSSYM_AGGREGATE Aggregate
= {0};
592 UNICODE_STRING ModName
= {0};
593 ANSI_STRING AnsiName
= {0};
594 CHAR Indent
[100] = {0};
597 if (Argc
< 3) goto end
;
598 AnsiName
.Length
= AnsiName
.MaximumLength
= strlen(Argv
[1]);
599 AnsiName
.Buffer
= Argv
[1];
600 RtlAnsiStringToUnicodeString(&ModName
, &AnsiName
, TRUE
);
601 Info
= KdbpSymFindCachedFile(&ModName
);
603 if (!Info
|| !RosSymAggregate(Info
, Argv
[2], &Aggregate
)) {
604 DPRINT1("Could not get aggregate\n");
608 // Get an argument for location if it was given
611 PCHAR ArgStart
= Argv
[3];
612 DPRINT1("Trying to get expression\n");
613 for (i
= 3; i
< Argc
- 1; i
++)
615 len
= strlen(Argv
[i
]);
619 /* Evaluate the expression */
620 DPRINT1("Arg: %s\n", ArgStart
);
621 if (KdbpEvaluateExpression(ArgStart
, strlen(ArgStart
), &Result
)) {
622 BaseAddress
= (PVOID
)(ULONG_PTR
)Result
;
623 DPRINT1("BaseAddress: %p\n", BaseAddress
);
626 DPRINT1("BaseAddress %p\n", BaseAddress
);
627 KdbpPrintStructInternal(Info
, Indent
, !!BaseAddress
, BaseAddress
, &Aggregate
);
629 RosSymFreeAggregate(&Aggregate
);
630 RtlFreeUnicodeString(&ModName
);
635 /*!\brief Display list of active debug channels
642 ULONG i
, j
, ComponentId
, Level
;
643 ULONG set
= DPFLTR_MASK
, clear
= DPFLTR_MASK
;
654 { "error", 1 << DPFLTR_ERROR_LEVEL
},
655 { "warning", 1 << DPFLTR_WARNING_LEVEL
},
656 { "trace", 1 << DPFLTR_TRACE_LEVEL
},
657 { "info", 1 << DPFLTR_INFO_LEVEL
},
660 for (i
= 1; i
< Argc
; i
++)
663 p
= opt
+ strcspn(opt
, "+-");
664 if (!p
[0]) p
= opt
; /* assume it's a debug channel name */
668 for (j
= 0; j
< sizeof(debug_classes
) / sizeof(debug_classes
[0]); j
++)
670 SIZE_T len
= strlen(debug_classes
[j
].Name
);
671 if (len
!= (p
- opt
))
673 if (_strnicmp(opt
, debug_classes
[j
].Name
, len
) == 0) /* found it */
676 set
|= debug_classes
[j
].Level
;
678 clear
|= debug_classes
[j
].Level
;
682 if (j
== sizeof(debug_classes
) / sizeof(debug_classes
[0]))
684 Level
= strtoul(opt
, &pend
, 0);
687 KdbpPrint("filter: bad class name '%.*s'\n", p
- opt
, opt
);
703 if (*p
== '+' || *p
== '-')
706 if (!KdbpGetComponentId(p
, &ComponentId
))
708 KdbpPrint("filter: '%s' is not a valid component name!\n", p
);
712 /* Get current mask value */
713 NtSetDebugFilterState(ComponentId
, set
, TRUE
);
714 NtSetDebugFilterState(ComponentId
, clear
, FALSE
);
720 /*!\brief Disassembles 10 instructions at eip or given address or
721 * displays 16 dwords from memory at given address.
731 ULONGLONG Result
= 0;
732 ULONG_PTR Address
= KdbCurrentTrapFrame
->Tf
.Eip
;
735 if (Argv
[0][0] == 'x') /* display memory */
737 else /* disassemble */
742 /* Check for [L count] part */
744 if (strcmp(Argv
[Argc
-2], "L") == 0)
746 ul
= strtoul(Argv
[Argc
-1], NULL
, 0);
753 else if (Argv
[Argc
-1][0] == 'L')
755 ul
= strtoul(Argv
[Argc
-1] + 1, NULL
, 0);
763 /* Put the remaining arguments back together */
765 for (ul
= 1; ul
< Argc
; ul
++)
767 Argv
[ul
][strlen(Argv
[ul
])] = ' ';
772 /* Evaluate the expression */
775 if (!KdbpEvaluateExpression(Argv
[1], sizeof("kdb:> ")-1 + (Argv
[1]-Argv
[0]), &Result
))
778 if (Result
> (ULONGLONG
)(~((ULONG_PTR
)0)))
779 KdbpPrint("Warning: Address %I64x is beeing truncated\n",Result
);
781 Address
= (ULONG_PTR
)Result
;
783 else if (Argv
[0][0] == 'x')
785 KdbpPrint("x: Address argument required.\n");
789 if (Argv
[0][0] == 'x')
796 if (!KdbSymPrintAddress((PVOID
)Address
, NULL
))
797 KdbpPrint("<%x>:", Address
);
806 if (!NT_SUCCESS(KdbpSafeReadMemory(&ul
, (PVOID
)Address
, sizeof(ul
))))
807 KdbpPrint(" ????????");
809 KdbpPrint(" %08x", ul
);
811 Address
+= sizeof(ul
);
822 if (!KdbSymPrintAddress((PVOID
)Address
, NULL
))
823 KdbpPrint("<%08x>: ", Address
);
827 InstLen
= KdbpDisassemble(Address
, KdbUseIntelSyntax
);
830 KdbpPrint("<INVALID>\n");
842 /*!\brief Displays CPU registers.
849 PKTRAP_FRAME Tf
= &KdbCurrentTrapFrame
->Tf
;
851 static const PCHAR EflagsBits
[32] = { " CF", NULL
, " PF", " BIT3", " AF", " BIT5",
852 " ZF", " SF", " TF", " IF", " DF", " OF",
853 NULL
, NULL
, " NT", " BIT15", " RF", " VF",
854 " AC", " VIF", " VIP", " ID", " BIT22",
855 " BIT23", " BIT24", " BIT25", " BIT26",
856 " BIT27", " BIT28", " BIT29", " BIT30",
859 if (Argv
[0][0] == 'r') /* regs */
861 KdbpPrint("CS:EIP 0x%04x:0x%08x\n"
862 "SS:ESP 0x%04x:0x%08x\n"
863 " EAX 0x%08x EBX 0x%08x\n"
864 " ECX 0x%08x EDX 0x%08x\n"
865 " ESI 0x%08x EDI 0x%08x\n"
867 Tf
->SegCs
& 0xFFFF, Tf
->Eip
,
868 Tf
->HardwareSegSs
, Tf
->HardwareEsp
,
873 KdbpPrint("EFLAGS 0x%08x ", Tf
->EFlags
);
875 for (i
= 0; i
< 32; i
++)
879 if ((Tf
->EFlags
& (1 << 1)) == 0)
884 KdbpPrint(" IOPL%d", (Tf
->EFlags
>> 12) & 3);
889 else if ((Tf
->EFlags
& (1 << i
)) != 0)
891 KdbpPrint(EflagsBits
[i
]);
897 else if (Argv
[0][0] == 'c') /* cregs */
899 ULONG Cr0
, Cr2
, Cr3
, Cr4
;
900 KDESCRIPTOR Gdtr
= {0, 0, 0}, Idtr
= {0, 0, 0};
902 static const PCHAR Cr0Bits
[32] = { " PE", " MP", " EM", " TS", " ET", " NE", NULL
, NULL
,
903 NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
,
904 " WP", NULL
, " AM", NULL
, NULL
, NULL
, NULL
, NULL
,
905 NULL
, NULL
, NULL
, NULL
, NULL
, " NW", " CD", " PG" };
906 static const PCHAR Cr4Bits
[32] = { " VME", " PVI", " TSD", " DE", " PSE", " PAE", " MCE", " PGE",
907 " PCE", " OSFXSR", " OSXMMEXCPT", NULL
, NULL
, NULL
, NULL
, NULL
,
908 NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
,
909 NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
};
911 Cr0
= KdbCurrentTrapFrame
->Cr0
;
912 Cr2
= KdbCurrentTrapFrame
->Cr2
;
913 Cr3
= KdbCurrentTrapFrame
->Cr3
;
914 Cr4
= KdbCurrentTrapFrame
->Cr4
;
916 /* Get descriptor table regs */
917 Ke386GetGlobalDescriptorTable(&Gdtr
.Limit
);
918 Ldtr
= Ke386GetLocalDescriptorTable();
921 /* Display the control registers */
922 KdbpPrint("CR0 0x%08x ", Cr0
);
924 for (i
= 0; i
< 32; i
++)
929 if ((Cr0
& (1 << i
)) != 0)
930 KdbpPrint(Cr0Bits
[i
]);
933 KdbpPrint("\nCR2 0x%08x\n", Cr2
);
934 KdbpPrint("CR3 0x%08x Pagedir-Base 0x%08x %s%s\n", Cr3
, (Cr3
& 0xfffff000),
935 (Cr3
& (1 << 3)) ? " PWT" : "", (Cr3
& (1 << 4)) ? " PCD" : "" );
936 KdbpPrint("CR4 0x%08x ", Cr4
);
938 for (i
= 0; i
< 32; i
++)
943 if ((Cr4
& (1 << i
)) != 0)
944 KdbpPrint(Cr4Bits
[i
]);
947 /* Display the descriptor table regs */
948 KdbpPrint("\nGDTR Base 0x%08x Size 0x%04x\n", Gdtr
.Base
, Gdtr
.Limit
);
949 KdbpPrint("LDTR 0x%04x\n", Ldtr
);
950 KdbpPrint("IDTR Base 0x%08x Size 0x%04x\n", Idtr
.Base
, Idtr
.Limit
);
952 else if (Argv
[0][0] == 's') /* sregs */
954 KdbpPrint("CS 0x%04x Index 0x%04x %cDT RPL%d\n",
955 Tf
->SegCs
& 0xffff, (Tf
->SegCs
& 0xffff) >> 3,
956 (Tf
->SegCs
& (1 << 2)) ? 'L' : 'G', Tf
->SegCs
& 3);
957 KdbpPrint("DS 0x%04x Index 0x%04x %cDT RPL%d\n",
958 Tf
->SegDs
, Tf
->SegDs
>> 3, (Tf
->SegDs
& (1 << 2)) ? 'L' : 'G', Tf
->SegDs
& 3);
959 KdbpPrint("ES 0x%04x Index 0x%04x %cDT RPL%d\n",
960 Tf
->SegEs
, Tf
->SegEs
>> 3, (Tf
->SegEs
& (1 << 2)) ? 'L' : 'G', Tf
->SegEs
& 3);
961 KdbpPrint("FS 0x%04x Index 0x%04x %cDT RPL%d\n",
962 Tf
->SegFs
, Tf
->SegFs
>> 3, (Tf
->SegFs
& (1 << 2)) ? 'L' : 'G', Tf
->SegFs
& 3);
963 KdbpPrint("GS 0x%04x Index 0x%04x %cDT RPL%d\n",
964 Tf
->SegGs
, Tf
->SegGs
>> 3, (Tf
->SegGs
& (1 << 2)) ? 'L' : 'G', Tf
->SegGs
& 3);
965 KdbpPrint("SS 0x%04x Index 0x%04x %cDT RPL%d\n",
966 Tf
->HardwareSegSs
, Tf
->HardwareSegSs
>> 3, (Tf
->HardwareSegSs
& (1 << 2)) ? 'L' : 'G', Tf
->HardwareSegSs
& 3);
970 ASSERT(Argv
[0][0] == 'd');
971 KdbpPrint("DR0 0x%08x\n"
977 Tf
->Dr0
, Tf
->Dr1
, Tf
->Dr2
, Tf
->Dr3
,
985 KdbpTrapFrameFromPrevTss(
986 PKTRAP_FRAME TrapFrame
)
994 Ke386GetGlobalDescriptorTable(&Gdtr
.Limit
);
997 if ((Sel
& (sizeof(KGDTENTRY
) - 1)) ||
998 (Sel
< sizeof(KGDTENTRY
)) ||
999 (Sel
+ sizeof(KGDTENTRY
) - 1 > Gdtr
.Limit
))
1002 if (!NT_SUCCESS(KdbpSafeReadMemory(&Desc
,
1003 (PVOID
)(Gdtr
.Base
+ Sel
),
1004 sizeof(KGDTENTRY
))))
1007 if (Desc
.HighWord
.Bits
.Type
!= 0xB)
1010 Tss
= (PKTSS
)(ULONG_PTR
)(Desc
.BaseLow
|
1011 Desc
.HighWord
.Bytes
.BaseMid
<< 16 |
1012 Desc
.HighWord
.Bytes
.BaseHi
<< 24);
1014 if (!NT_SUCCESS(KdbpSafeReadMemory(&Sel
,
1015 (PVOID
)&Tss
->Backlink
,
1019 if ((Sel
& (sizeof(KGDTENTRY
) - 1)) ||
1020 (Sel
< sizeof(KGDTENTRY
)) ||
1021 (Sel
+ sizeof(KGDTENTRY
) - 1 > Gdtr
.Limit
))
1024 if (!NT_SUCCESS(KdbpSafeReadMemory(&Desc
,
1025 (PVOID
)(Gdtr
.Base
+ Sel
),
1026 sizeof(KGDTENTRY
))))
1029 if (Desc
.HighWord
.Bits
.Type
!= 0xB)
1032 Tss
= (PKTSS
)(ULONG_PTR
)(Desc
.BaseLow
|
1033 Desc
.HighWord
.Bytes
.BaseMid
<< 16 |
1034 Desc
.HighWord
.Bytes
.BaseHi
<< 24);
1036 if (!NT_SUCCESS(KdbpSafeReadMemory(&Eip
,
1038 sizeof(ULONG_PTR
))))
1041 if (!NT_SUCCESS(KdbpSafeReadMemory(&Ebp
,
1043 sizeof(ULONG_PTR
))))
1046 TrapFrame
->Eip
= Eip
;
1047 TrapFrame
->Ebp
= Ebp
;
1051 VOID __cdecl
KiTrap02(VOID
);
1052 VOID FASTCALL
KiTrap03Handler(IN PKTRAP_FRAME
);
1053 VOID __cdecl
KiTrap08(VOID
);
1054 VOID __cdecl
KiTrap09(VOID
);
1057 KdbpInNmiOrDoubleFaultHandler(
1060 return (Address
> (ULONG_PTR
)KiTrap02
&& Address
< (ULONG_PTR
)KiTrap03Handler
) ||
1061 (Address
> (ULONG_PTR
)KiTrap08
&& Address
< (ULONG_PTR
)KiTrap09
);
1064 /*!\brief Displays a backtrace.
1072 ULONGLONG Result
= 0;
1073 ULONG_PTR Frame
= KdbCurrentTrapFrame
->Tf
.Ebp
;
1075 KTRAP_FRAME TrapFrame
;
1079 /* Check for [L count] part */
1082 if (strcmp(Argv
[Argc
-2], "L") == 0)
1084 ul
= strtoul(Argv
[Argc
-1], NULL
, 0);
1090 else if (Argv
[Argc
-1][0] == 'L')
1092 ul
= strtoul(Argv
[Argc
-1] + 1, NULL
, 0);
1099 /* Put the remaining arguments back together */
1101 for (ul
= 1; ul
< Argc
; ul
++)
1103 Argv
[ul
][strlen(Argv
[ul
])] = ' ';
1108 /* Check if frame addr or thread id is given. */
1111 if (Argv
[1][0] == '*')
1115 /* Evaluate the expression */
1116 if (!KdbpEvaluateExpression(Argv
[1], sizeof("kdb:> ")-1 + (Argv
[1]-Argv
[0]), &Result
))
1119 if (Result
> (ULONGLONG
)(~((ULONG_PTR
)0)))
1120 KdbpPrint("Warning: Address %I64x is beeing truncated\n",Result
);
1122 Frame
= (ULONG_PTR
)Result
;
1126 KdbpPrint("Thread backtrace not supported yet!\n");
1132 KdbpPrint("Eip:\n");
1134 /* Try printing the function at EIP */
1135 if (!KdbSymPrintAddress((PVOID
)KdbCurrentTrapFrame
->Tf
.Eip
, &KdbCurrentTrapFrame
->Tf
))
1136 KdbpPrint("<%08x>\n", KdbCurrentTrapFrame
->Tf
.Eip
);
1141 TrapFrame
= KdbCurrentTrapFrame
->Tf
;
1142 KdbpPrint("Frames:\n");
1146 BOOLEAN GotNextFrame
;
1151 if (!NT_SUCCESS(KdbpSafeReadMemory(&Address
, (PVOID
)(Frame
+ sizeof(ULONG_PTR
)), sizeof (ULONG_PTR
))))
1153 KdbpPrint("Couldn't access memory at 0x%p!\n", Frame
+ sizeof(ULONG_PTR
));
1157 if ((GotNextFrame
= NT_SUCCESS(KdbpSafeReadMemory(&Frame
, (PVOID
)Frame
, sizeof (ULONG_PTR
)))))
1158 TrapFrame
.Ebp
= Frame
;
1160 /* Print the location of the call instruction */
1161 if (!KdbSymPrintAddress((PVOID
)(Address
- 5), &TrapFrame
))
1162 KdbpPrint("<%08x>\n", Address
);
1166 if (KdbOutputAborted
) break;
1171 if (KdbpInNmiOrDoubleFaultHandler(Address
))
1173 if ((GotNextFrame
= KdbpTrapFrameFromPrevTss(&TrapFrame
)))
1175 Address
= TrapFrame
.Eip
;
1176 Frame
= TrapFrame
.Ebp
;
1178 if (!KdbSymPrintAddress((PVOID
)Address
, &TrapFrame
))
1179 KdbpPrint("<%08x>\n", Address
);
1187 KdbpPrint("Couldn't access memory at 0x%p!\n", Frame
);
1195 /*!\brief Continues execution of the system/leaves KDB.
1202 /* Exit the main loop */
1206 /*!\brief Continues execution of the system/leaves KDB.
1217 Count
= strtoul(Argv
[1], NULL
, 0);
1220 KdbpPrint("%s: Integer argument required\n", Argv
[0]);
1225 if (Argv
[0][0] == 'n')
1226 KdbSingleStepOver
= TRUE
;
1228 KdbSingleStepOver
= FALSE
;
1230 /* Set the number of single steps and return to the interrupted code. */
1231 KdbNumSingleSteps
= Count
;
1236 /*!\brief Lists breakpoints.
1239 KdbpCmdBreakPointList(
1244 ULONG_PTR Address
= 0;
1245 KDB_BREAKPOINT_TYPE Type
= 0;
1246 KDB_ACCESS_TYPE AccessType
= 0;
1249 BOOLEAN Enabled
= FALSE
;
1250 BOOLEAN Global
= FALSE
;
1251 PEPROCESS Process
= NULL
;
1252 PCHAR str1
, str2
, ConditionExpr
, GlobalOrLocal
;
1255 l
= KdbpGetNextBreakPointNr(0);
1258 KdbpPrint("No breakpoints.\n");
1262 KdbpPrint("Breakpoints:\n");
1265 if (!KdbpGetBreakPointInfo(l
, &Address
, &Type
, &Size
, &AccessType
, &DebugReg
,
1266 &Enabled
, &Global
, &Process
, &ConditionExpr
))
1271 if (l
== KdbLastBreakPointNr
)
1284 GlobalOrLocal
= " global";
1288 GlobalOrLocal
= Buffer
;
1289 sprintf(Buffer
, " PID 0x%08lx",
1290 (ULONG
)(Process
? Process
->UniqueProcessId
: INVALID_HANDLE_VALUE
));
1293 if (Type
== KdbBreakPointSoftware
|| Type
== KdbBreakPointTemporary
)
1295 KdbpPrint(" %s%03d BPX 0x%08x%s%s%s%s%s\n",
1297 Enabled
? "" : " disabled",
1299 ConditionExpr
? " IF " : "",
1300 ConditionExpr
? ConditionExpr
: "",
1303 else if (Type
== KdbBreakPointHardware
)
1307 KdbpPrint(" %s%03d BPM 0x%08x %-5s %-5s disabled%s%s%s%s\n", str1
, l
, Address
,
1308 KDB_ACCESS_TYPE_TO_STRING(AccessType
),
1309 Size
== 1 ? "byte" : (Size
== 2 ? "word" : "dword"),
1311 ConditionExpr
? " IF " : "",
1312 ConditionExpr
? ConditionExpr
: "",
1317 KdbpPrint(" %s%03d BPM 0x%08x %-5s %-5s DR%d%s%s%s%s\n", str1
, l
, Address
,
1318 KDB_ACCESS_TYPE_TO_STRING(AccessType
),
1319 Size
== 1 ? "byte" : (Size
== 2 ? "word" : "dword"),
1322 ConditionExpr
? " IF " : "",
1323 ConditionExpr
? ConditionExpr
: "",
1328 while ((l
= KdbpGetNextBreakPointNr(l
+1)) >= 0);
1333 /*!\brief Enables, disables or clears a breakpoint.
1336 KdbpCmdEnableDisableClearBreakPoint(
1345 KdbpPrint("%s: argument required\n", Argv
[0]);
1350 BreakPointNr
= strtoul(Argv
[1], &pend
, 0);
1351 if (pend
== Argv
[1] || *pend
!= '\0')
1353 KdbpPrint("%s: integer argument required\n", Argv
[0]);
1357 if (Argv
[0][1] == 'e') /* enable */
1359 KdbpEnableBreakPoint(BreakPointNr
, NULL
);
1361 else if (Argv
[0][1] == 'd') /* disable */
1363 KdbpDisableBreakPoint(BreakPointNr
, NULL
);
1367 ASSERT(Argv
[0][1] == 'c');
1368 KdbpDeleteBreakPoint(BreakPointNr
, NULL
);
1374 /*!\brief Sets a software or hardware (memory) breakpoint at the given address.
1377 KdbpCmdBreakPoint(ULONG Argc
, PCHAR Argv
[])
1379 ULONGLONG Result
= 0;
1381 KDB_BREAKPOINT_TYPE Type
;
1383 KDB_ACCESS_TYPE AccessType
= 0;
1384 ULONG AddressArgIndex
, i
;
1385 LONG ConditionArgIndex
;
1386 BOOLEAN Global
= TRUE
;
1388 if (Argv
[0][2] == 'x') /* software breakpoint */
1392 KdbpPrint("bpx: Address argument required.\n");
1396 AddressArgIndex
= 1;
1397 Type
= KdbBreakPointSoftware
;
1399 else /* memory breakpoint */
1401 ASSERT(Argv
[0][2] == 'm');
1405 KdbpPrint("bpm: Access type argument required (one of r, w, rw, x)\n");
1409 if (_stricmp(Argv
[1], "x") == 0)
1410 AccessType
= KdbAccessExec
;
1411 else if (_stricmp(Argv
[1], "r") == 0)
1412 AccessType
= KdbAccessRead
;
1413 else if (_stricmp(Argv
[1], "w") == 0)
1414 AccessType
= KdbAccessWrite
;
1415 else if (_stricmp(Argv
[1], "rw") == 0)
1416 AccessType
= KdbAccessReadWrite
;
1419 KdbpPrint("bpm: Unknown access type '%s'\n", Argv
[1]);
1425 KdbpPrint("bpm: %s argument required.\n", AccessType
== KdbAccessExec
? "Address" : "Memory size");
1429 AddressArgIndex
= 3;
1430 if (_stricmp(Argv
[2], "byte") == 0)
1432 else if (_stricmp(Argv
[2], "word") == 0)
1434 else if (_stricmp(Argv
[2], "dword") == 0)
1436 else if (AccessType
== KdbAccessExec
)
1443 KdbpPrint("bpm: Unknown memory size '%s'\n", Argv
[2]);
1447 if (Argc
<= AddressArgIndex
)
1449 KdbpPrint("bpm: Address argument required.\n");
1453 Type
= KdbBreakPointHardware
;
1456 /* Put the arguments back together */
1457 ConditionArgIndex
= -1;
1458 for (i
= AddressArgIndex
; i
< (Argc
-1); i
++)
1460 if (strcmp(Argv
[i
+1], "IF") == 0) /* IF found */
1462 ConditionArgIndex
= i
+ 2;
1463 if ((ULONG
)ConditionArgIndex
>= Argc
)
1465 KdbpPrint("%s: IF requires condition expression.\n", Argv
[0]);
1469 for (i
= ConditionArgIndex
; i
< (Argc
-1); i
++)
1470 Argv
[i
][strlen(Argv
[i
])] = ' ';
1475 Argv
[i
][strlen(Argv
[i
])] = ' ';
1478 /* Evaluate the address expression */
1479 if (!KdbpEvaluateExpression(Argv
[AddressArgIndex
],
1480 sizeof("kdb:> ")-1 + (Argv
[AddressArgIndex
]-Argv
[0]),
1486 if (Result
> (ULONGLONG
)(~((ULONG_PTR
)0)))
1487 KdbpPrint("%s: Warning: Address %I64x is beeing truncated\n", Argv
[0],Result
);
1489 Address
= (ULONG_PTR
)Result
;
1491 KdbpInsertBreakPoint(Address
, Type
, Size
, AccessType
,
1492 (ConditionArgIndex
< 0) ? NULL
: Argv
[ConditionArgIndex
],
1498 /*!\brief Lists threads or switches to another thread context.
1506 PETHREAD Thread
= NULL
;
1507 PEPROCESS Process
= NULL
;
1508 BOOLEAN ReferencedThread
= FALSE
, ReferencedProcess
= FALSE
;
1513 PCHAR State
, pend
, str1
, str2
;
1514 static const PCHAR ThreadStateToString
[DeferredReady
+1] =
1516 "Initialized", "Ready", "Running",
1517 "Standby", "Terminated", "Waiting",
1518 "Transition", "DeferredReady"
1521 ASSERT(KdbCurrentProcess
);
1523 if (Argc
>= 2 && _stricmp(Argv
[1], "list") == 0)
1525 Process
= KdbCurrentProcess
;
1529 ul
= strtoul(Argv
[2], &pend
, 0);
1530 if (Argv
[2] == pend
)
1532 KdbpPrint("thread: '%s' is not a valid process id!\n", Argv
[2]);
1536 if (!NT_SUCCESS(PsLookupProcessByProcessId((PVOID
)ul
, &Process
)))
1538 KdbpPrint("thread: Invalid process id!\n");
1542 /* Remember our reference */
1543 ReferencedProcess
= TRUE
;
1546 Entry
= Process
->ThreadListHead
.Flink
;
1547 if (Entry
== &Process
->ThreadListHead
)
1550 KdbpPrint("No threads in process 0x%08x!\n", ul
);
1552 KdbpPrint("No threads in current process!\n");
1554 if (ReferencedProcess
)
1555 ObDereferenceObject(Process
);
1560 KdbpPrint(" TID State Prior. Affinity EBP EIP\n");
1563 Thread
= CONTAINING_RECORD(Entry
, ETHREAD
, ThreadListEntry
);
1565 if (Thread
== KdbCurrentThread
)
1576 if (!Thread
->Tcb
.InitialStack
)
1578 /* Thread has no kernel stack (probably terminated) */
1582 else if (Thread
->Tcb
.TrapFrame
)
1584 if (Thread
->Tcb
.TrapFrame
->PreviousPreviousMode
== KernelMode
)
1585 Esp
= (PULONG
)Thread
->Tcb
.TrapFrame
->TempEsp
;
1587 Esp
= (PULONG
)Thread
->Tcb
.TrapFrame
->HardwareEsp
;
1589 Ebp
= (PULONG
)Thread
->Tcb
.TrapFrame
->Ebp
;
1590 Eip
= Thread
->Tcb
.TrapFrame
->Eip
;
1594 Esp
= (PULONG
)Thread
->Tcb
.KernelStack
;
1595 Ebp
= (PULONG
)Esp
[4];
1598 if (Ebp
) /* FIXME: Should we attach to the process to read Ebp[1]? */
1599 KdbpSafeReadMemory(&Eip
, Ebp
+ 1, sizeof (Eip
));
1602 if (Thread
->Tcb
.State
< (DeferredReady
+ 1))
1603 State
= ThreadStateToString
[Thread
->Tcb
.State
];
1607 KdbpPrint(" %s0x%08x %-11s %3d 0x%08x 0x%08x 0x%08x%s\n",
1609 Thread
->Cid
.UniqueThread
,
1611 Thread
->Tcb
.Priority
,
1612 Thread
->Tcb
.Affinity
,
1617 Entry
= Entry
->Flink
;
1619 while (Entry
!= &Process
->ThreadListHead
);
1621 /* Release our reference, if any */
1622 if (ReferencedProcess
)
1623 ObDereferenceObject(Process
);
1625 else if (Argc
>= 2 && _stricmp(Argv
[1], "attach") == 0)
1629 KdbpPrint("thread attach: thread id argument required!\n");
1633 ul
= strtoul(Argv
[2], &pend
, 0);
1634 if (Argv
[2] == pend
)
1636 KdbpPrint("thread attach: '%s' is not a valid thread id!\n", Argv
[2]);
1640 if (!KdbpAttachToThread((PVOID
)ul
))
1645 KdbpPrint("Attached to thread 0x%08x.\n", ul
);
1649 Thread
= KdbCurrentThread
;
1653 ul
= strtoul(Argv
[1], &pend
, 0);
1654 if (Argv
[1] == pend
)
1656 KdbpPrint("thread: '%s' is not a valid thread id!\n", Argv
[1]);
1660 if (!NT_SUCCESS(PsLookupThreadByThreadId((PVOID
)ul
, &Thread
)))
1662 KdbpPrint("thread: Invalid thread id!\n");
1666 /* Remember our reference */
1667 ReferencedThread
= TRUE
;
1670 if (Thread
->Tcb
.State
< (DeferredReady
+ 1))
1671 State
= ThreadStateToString
[Thread
->Tcb
.State
];
1677 " State: %s (0x%x)\n"
1679 " Affinity: 0x%08x\n"
1680 " Initial Stack: 0x%08x\n"
1681 " Stack Limit: 0x%08x\n"
1682 " Stack Base: 0x%08x\n"
1683 " Kernel Stack: 0x%08x\n"
1684 " Trap Frame: 0x%08x\n"
1685 " NPX State: %s (0x%x)\n",
1686 (Argc
< 2) ? "Current Thread:\n" : "",
1687 Thread
->Cid
.UniqueThread
,
1688 State
, Thread
->Tcb
.State
,
1689 Thread
->Tcb
.Priority
,
1690 Thread
->Tcb
.Affinity
,
1691 Thread
->Tcb
.InitialStack
,
1692 Thread
->Tcb
.StackLimit
,
1693 Thread
->Tcb
.StackBase
,
1694 Thread
->Tcb
.KernelStack
,
1695 Thread
->Tcb
.TrapFrame
,
1696 NPX_STATE_TO_STRING(Thread
->Tcb
.NpxState
), Thread
->Tcb
.NpxState
);
1698 /* Release our reference if we had one */
1699 if (ReferencedThread
)
1700 ObDereferenceObject(Thread
);
1706 /*!\brief Lists processes or switches to another process context.
1715 BOOLEAN ReferencedProcess
= FALSE
;
1716 PCHAR State
, pend
, str1
, str2
;
1718 extern LIST_ENTRY PsActiveProcessHead
;
1720 if (Argc
>= 2 && _stricmp(Argv
[1], "list") == 0)
1722 Entry
= PsActiveProcessHead
.Flink
;
1723 if (!Entry
|| Entry
== &PsActiveProcessHead
)
1725 KdbpPrint("No processes in the system!\n");
1729 KdbpPrint(" PID State Filename\n");
1732 Process
= CONTAINING_RECORD(Entry
, EPROCESS
, ActiveProcessLinks
);
1734 if (Process
== KdbCurrentProcess
)
1745 State
= ((Process
->Pcb
.State
== ProcessInMemory
) ? "In Memory" :
1746 ((Process
->Pcb
.State
== ProcessOutOfMemory
) ? "Out of Memory" : "In Transition"));
1748 KdbpPrint(" %s0x%08x %-10s %s%s\n",
1750 Process
->UniqueProcessId
,
1752 Process
->ImageFileName
,
1755 Entry
= Entry
->Flink
;
1757 while(Entry
!= &PsActiveProcessHead
);
1759 else if (Argc
>= 2 && _stricmp(Argv
[1], "attach") == 0)
1763 KdbpPrint("process attach: process id argument required!\n");
1767 ul
= strtoul(Argv
[2], &pend
, 0);
1768 if (Argv
[2] == pend
)
1770 KdbpPrint("process attach: '%s' is not a valid process id!\n", Argv
[2]);
1774 if (!KdbpAttachToProcess((PVOID
)ul
))
1779 KdbpPrint("Attached to process 0x%08x, thread 0x%08x.\n", (ULONG
)ul
,
1780 (ULONG
)KdbCurrentThread
->Cid
.UniqueThread
);
1784 Process
= KdbCurrentProcess
;
1788 ul
= strtoul(Argv
[1], &pend
, 0);
1789 if (Argv
[1] == pend
)
1791 KdbpPrint("proc: '%s' is not a valid process id!\n", Argv
[1]);
1795 if (!NT_SUCCESS(PsLookupProcessByProcessId((PVOID
)ul
, &Process
)))
1797 KdbpPrint("proc: Invalid process id!\n");
1801 /* Remember our reference */
1802 ReferencedProcess
= TRUE
;
1805 State
= ((Process
->Pcb
.State
== ProcessInMemory
) ? "In Memory" :
1806 ((Process
->Pcb
.State
== ProcessOutOfMemory
) ? "Out of Memory" : "In Transition"));
1809 " State: %s (0x%x)\n"
1810 " Image Filename: %s\n",
1811 (Argc
< 2) ? "Current process:\n" : "",
1812 Process
->UniqueProcessId
,
1813 State
, Process
->Pcb
.State
,
1814 Process
->ImageFileName
);
1816 /* Release our reference, if any */
1817 if (ReferencedProcess
)
1818 ObDereferenceObject(Process
);
1824 /*!\brief Lists loaded modules or the one containing the specified address.
1831 ULONGLONG Result
= 0;
1833 PLDR_DATA_TABLE_ENTRY LdrEntry
;
1834 BOOLEAN DisplayOnlyOneModule
= FALSE
;
1839 /* Put the arguments back together */
1842 Argv
[Argc
][strlen(Argv
[Argc
])] = ' ';
1844 /* Evaluate the expression */
1845 if (!KdbpEvaluateExpression(Argv
[1], sizeof("kdb:> ")-1 + (Argv
[1]-Argv
[0]), &Result
))
1850 if (Result
> (ULONGLONG
)(~((ULONG_PTR
)0)))
1851 KdbpPrint("%s: Warning: Address %I64x is beeing truncated\n", Argv
[0],Result
);
1853 Address
= (ULONG_PTR
)Result
;
1855 if (!KdbpSymFindModule((PVOID
)Address
, NULL
, -1, &LdrEntry
))
1857 KdbpPrint("No module containing address 0x%p found!\n", Address
);
1861 DisplayOnlyOneModule
= TRUE
;
1865 if (!KdbpSymFindModule(NULL
, NULL
, 0, &LdrEntry
))
1867 ULONG_PTR ntoskrnlBase
= ((ULONG_PTR
)KdbpCmdMod
) & 0xfff00000;
1868 KdbpPrint(" Base Size Name\n");
1869 KdbpPrint(" %08x %08x %s\n", ntoskrnlBase
, 0, "ntoskrnl.exe");
1876 KdbpPrint(" Base Size Name\n");
1879 KdbpPrint(" %08x %08x %wZ\n", LdrEntry
->DllBase
, LdrEntry
->SizeOfImage
, &LdrEntry
->BaseDllName
);
1881 if(DisplayOnlyOneModule
|| !KdbpSymFindModule(NULL
, NULL
, i
++, &LdrEntry
))
1888 /*!\brief Displays GDT, LDT or IDTd.
1905 if (Argv
[0][0] == 'i')
1912 KdbpPrint("Interrupt descriptor table is empty.\n");
1916 KdbpPrint("IDT Base: 0x%08x Limit: 0x%04x\n", Reg
.Base
, Reg
.Limit
);
1917 KdbpPrint(" Idx Type Seg. Sel. Offset DPL\n");
1919 for (i
= 0; (i
+ sizeof(SegDesc
) - 1) <= Reg
.Limit
; i
+= 8)
1921 if (!NT_SUCCESS(KdbpSafeReadMemory(SegDesc
, (PVOID
)(Reg
.Base
+ i
), sizeof(SegDesc
))))
1923 KdbpPrint("Couldn't access memory at 0x%08x!\n", Reg
.Base
+ i
);
1927 Dpl
= ((SegDesc
[1] >> 13) & 3);
1928 if ((SegDesc
[1] & 0x1f00) == 0x0500) /* Task gate */
1929 SegType
= "TASKGATE";
1930 else if ((SegDesc
[1] & 0x1fe0) == 0x0e00) /* 32 bit Interrupt gate */
1931 SegType
= "INTGATE32";
1932 else if ((SegDesc
[1] & 0x1fe0) == 0x0600) /* 16 bit Interrupt gate */
1933 SegType
= "INTGATE16";
1934 else if ((SegDesc
[1] & 0x1fe0) == 0x0f00) /* 32 bit Trap gate */
1935 SegType
= "TRAPGATE32";
1936 else if ((SegDesc
[1] & 0x1fe0) == 0x0700) /* 16 bit Trap gate */
1937 SegType
= "TRAPGATE16";
1939 SegType
= "UNKNOWN";
1941 if ((SegDesc
[1] & (1 << 15)) == 0) /* not present */
1943 KdbpPrint(" %03d %-10s [NP] [NP] %02d\n",
1944 i
/ 8, SegType
, Dpl
);
1946 else if ((SegDesc
[1] & 0x1f00) == 0x0500) /* Task gate */
1948 SegSel
= SegDesc
[0] >> 16;
1949 KdbpPrint(" %03d %-10s 0x%04x %02d\n",
1950 i
/ 8, SegType
, SegSel
, Dpl
);
1954 SegSel
= SegDesc
[0] >> 16;
1955 SegBase
= (SegDesc
[1] & 0xffff0000) | (SegDesc
[0] & 0x0000ffff);
1956 KdbpPrint(" %03d %-10s 0x%04x 0x%08x %02d\n",
1957 i
/ 8, SegType
, SegSel
, SegBase
, Dpl
);
1965 if (Argv
[0][0] == 'g')
1968 Ke386GetGlobalDescriptorTable(&Reg
.Limit
);
1973 ASSERT(Argv
[0][0] == 'l');
1976 Reg
.Limit
= Ke386GetLocalDescriptorTable();
1984 KdbpPrint("%s descriptor table is empty.\n",
1985 Argv
[0][0] == 'g' ? "Global" : "Local");
1989 KdbpPrint("%cDT Base: 0x%08x Limit: 0x%04x\n",
1990 Argv
[0][0] == 'g' ? 'G' : 'L', Reg
.Base
, Reg
.Limit
);
1991 KdbpPrint(" Idx Sel. Type Base Limit DPL Attribs\n");
1993 for (; (i
+ sizeof(SegDesc
) - 1) <= Reg
.Limit
; i
+= 8)
1995 if (!NT_SUCCESS(KdbpSafeReadMemory(SegDesc
, (PVOID
)(Reg
.Base
+ i
), sizeof(SegDesc
))))
1997 KdbpPrint("Couldn't access memory at 0x%08x!\n", Reg
.Base
+ i
);
2001 Dpl
= ((SegDesc
[1] >> 13) & 3);
2002 Type
= ((SegDesc
[1] >> 8) & 0xf);
2004 SegBase
= SegDesc
[0] >> 16;
2005 SegBase
|= (SegDesc
[1] & 0xff) << 16;
2006 SegBase
|= SegDesc
[1] & 0xff000000;
2007 SegLimit
= SegDesc
[0] & 0x0000ffff;
2008 SegLimit
|= (SegDesc
[1] >> 16) & 0xf;
2010 if ((SegDesc
[1] & (1 << 23)) != 0)
2020 if ((SegDesc
[1] & (1 << 12)) == 0) /* System segment */
2024 case 1: SegType
= "TSS16(Avl)"; break;
2025 case 2: SegType
= "LDT"; break;
2026 case 3: SegType
= "TSS16(Busy)"; break;
2027 case 4: SegType
= "CALLGATE16"; break;
2028 case 5: SegType
= "TASKGATE"; break;
2029 case 6: SegType
= "INTGATE16"; break;
2030 case 7: SegType
= "TRAPGATE16"; break;
2031 case 9: SegType
= "TSS32(Avl)"; break;
2032 case 11: SegType
= "TSS32(Busy)"; break;
2033 case 12: SegType
= "CALLGATE32"; break;
2034 case 14: SegType
= "INTGATE32"; break;
2035 case 15: SegType
= "INTGATE32"; break;
2036 default: SegType
= "UNKNOWN"; break;
2039 if (!(Type
>= 1 && Type
<= 3) &&
2040 Type
!= 9 && Type
!= 11)
2046 else if ((SegDesc
[1] & (1 << 11)) == 0) /* Data segment */
2048 if ((SegDesc
[1] & (1 << 22)) != 0)
2053 else /* Code segment */
2055 if ((SegDesc
[1] & (1 << 22)) != 0)
2061 if ((SegDesc
[1] & (1 << 15)) == 0) /* not present */
2063 KdbpPrint(" %03d 0x%04x %-11s [NP] [NP] %02d NP\n",
2064 i
/ 8, i
| Dpl
| ul
, SegType
, Dpl
);
2068 KdbpPrint(" %03d 0x%04x %-11s 0x%08x 0x%08x %02d ",
2069 i
/ 8, i
| Dpl
| ul
, SegType
, SegBase
, SegLimit
, Dpl
);
2071 if ((SegDesc
[1] & (1 << 12)) == 0) /* System segment */
2073 /* FIXME: Display system segment */
2075 else if ((SegDesc
[1] & (1 << 11)) == 0) /* Data segment */
2077 if ((SegDesc
[1] & (1 << 10)) != 0) /* Expand-down */
2080 KdbpPrint((SegDesc
[1] & (1 << 9)) ? " R/W" : " R");
2082 if ((SegDesc
[1] & (1 << 8)) != 0)
2085 else /* Code segment */
2087 if ((SegDesc
[1] & (1 << 10)) != 0) /* Conforming */
2090 KdbpPrint((SegDesc
[1] & (1 << 9)) ? " R/X" : " X");
2092 if ((SegDesc
[1] & (1 << 8)) != 0)
2096 if ((SegDesc
[1] & (1 << 20)) != 0)
2107 /*!\brief Displays the KPCR
2114 PKIPCR Pcr
= (PKIPCR
)KeGetPcr();
2116 KdbpPrint("Current PCR is at 0x%08x.\n", (INT
)Pcr
);
2117 KdbpPrint(" Tib.ExceptionList: 0x%08x\n"
2118 " Tib.StackBase: 0x%08x\n"
2119 " Tib.StackLimit: 0x%08x\n"
2120 " Tib.SubSystemTib: 0x%08x\n"
2121 " Tib.FiberData/Version: 0x%08x\n"
2122 " Tib.ArbitraryUserPointer: 0x%08x\n"
2123 " Tib.Self: 0x%08x\n"
2124 " SelfPcr: 0x%08x\n"
2128 " IrrActive: 0x%08x\n"
2130 " KdVersionBlock: 0x%08x\n"
2134 " MajorVersion: 0x%04x\n"
2135 " MinorVersion: 0x%04x\n"
2136 " SetMember: 0x%08x\n"
2137 " StallScaleFactor: 0x%08x\n"
2139 " L2CacheAssociativity: 0x%02x\n"
2140 " VdmAlert: 0x%08x\n"
2141 " L2CacheSize: 0x%08x\n"
2142 " InterruptMode: 0x%08x\n",
2143 Pcr
->NtTib
.ExceptionList
, Pcr
->NtTib
.StackBase
, Pcr
->NtTib
.StackLimit
,
2144 Pcr
->NtTib
.SubSystemTib
, Pcr
->NtTib
.FiberData
, Pcr
->NtTib
.ArbitraryUserPointer
,
2145 Pcr
->NtTib
.Self
, Pcr
->SelfPcr
, Pcr
->Prcb
, Pcr
->Irql
, Pcr
->IRR
, Pcr
->IrrActive
,
2146 Pcr
->IDR
, Pcr
->KdVersionBlock
, Pcr
->IDT
, Pcr
->GDT
, Pcr
->TSS
,
2147 Pcr
->MajorVersion
, Pcr
->MinorVersion
, Pcr
->SetMember
, Pcr
->StallScaleFactor
,
2148 Pcr
->Number
, Pcr
->SecondLevelCacheAssociativity
,
2149 Pcr
->VdmAlert
, Pcr
->SecondLevelCacheSize
, Pcr
->InterruptMode
);
2154 /*!\brief Displays the TSS
2161 KTSS
*Tss
= KeGetPcr()->TSS
;
2163 KdbpPrint("Current TSS is at 0x%08x.\n", (INT
)Tss
);
2164 KdbpPrint(" Eip: 0x%08x\n"
2171 " IoMapBase: 0x%04x\n",
2172 Tss
->Eip
, Tss
->Es
, Tss
->Cs
, Tss
->Ds
, Tss
->Fs
, Tss
->Gs
, Tss
->IoMapBase
);
2177 /*!\brief Bugchecks the system.
2184 /* Set the flag and quit looping */
2185 KdbpBugCheckRequested
= TRUE
;
2195 /* Reboot immediately (we do not return) */
2196 HalReturnToFirmware(HalRebootRoutine
);
2204 IN ULONG BufLength
);
2206 /*!\brief Display debug messages on screen, with paging.
2208 * Keys for per-page view: Home, End, PageUp, Arrow Up, PageDown,
2209 * all others are as PageDown.
2218 KdbpIsInDmesgMode
= TRUE
; /* Toggle logging flag */
2219 if (!KdpDmesgBuffer
)
2221 KdbpPrint("Dmesg: error, buffer is not allocated! /DEBUGPORT=SCREEN kernel param required for dmesg.\n");
2225 KdbpPrint("*** Dmesg *** TotalWritten=%lu, BufferSize=%lu, CurrentPosition=%lu\n",
2226 KdbDmesgTotalWritten
, KdpDmesgBufferSize
, KdpDmesgCurrentPosition
);
2228 // Pass data to the pager:
2229 end
= KdpDmesgCurrentPosition
;
2230 beg
= (end
+ KdpDmesgFreeBytes
) % KdpDmesgBufferSize
;
2232 // no roll-overs, and overwritten=lost bytes
2233 if (KdbDmesgTotalWritten
<= KdpDmesgBufferSize
)
2235 // show buffer (KdpDmesgBuffer + beg, num)
2236 KdbpPager(KdpDmesgBuffer
, KdpDmesgCurrentPosition
);
2240 // show 2 buffers: (KdpDmesgBuffer + beg, KdpDmesgBufferSize - beg)
2241 // and: (KdpDmesgBuffer, end)
2242 KdbpPager(KdpDmesgBuffer
+ beg
, KdpDmesgBufferSize
- beg
);
2243 KdbpPrint("*** Dmesg: buffer rollup ***\n");
2244 KdbpPager(KdpDmesgBuffer
, end
);
2246 KdbpPrint("*** Dmesg: end of output ***\n");
2248 KdbpIsInDmesgMode
= FALSE
; /* Toggle logging flag */
2253 /*!\brief Sets or displays a config variables value.
2263 KDB_ENTER_CONDITION ConditionFirst
= KdbDoNotEnter
;
2264 KDB_ENTER_CONDITION ConditionLast
= KdbDoNotEnter
;
2266 static const PCHAR ExceptionNames
[21] =
2268 "ZERODEVIDE", "DEBUGTRAP", "NMI", "INT3", "OVERFLOW", "BOUND", "INVALIDOP",
2269 "NOMATHCOP", "DOUBLEFAULT", "RESERVED(9)", "INVALIDTSS", "SEGMENTNOTPRESENT",
2270 "STACKFAULT", "GPF", "PAGEFAULT", "RESERVED(15)", "MATHFAULT", "ALIGNMENTCHECK",
2271 "MACHINECHECK", "SIMDFAULT", "OTHERS"
2276 KdbpPrint("Available settings:\n");
2277 KdbpPrint(" syntax [intel|at&t]\n");
2278 KdbpPrint(" condition [exception|*] [first|last] [never|always|kmode|umode]\n");
2279 KdbpPrint(" break_on_module_load [true|false]\n");
2281 else if (strcmp(Argv
[1], "syntax") == 0)
2285 KdbpPrint("syntax = %s\n", KdbUseIntelSyntax
? "intel" : "at&t");
2289 if (_stricmp(Argv
[2], "intel") == 0)
2290 KdbUseIntelSyntax
= TRUE
;
2291 else if (_stricmp(Argv
[2], "at&t") == 0)
2292 KdbUseIntelSyntax
= FALSE
;
2294 KdbpPrint("Unknown syntax '%s'.\n", Argv
[2]);
2297 else if (strcmp(Argv
[1], "condition") == 0)
2301 KdbpPrint("Conditions: (First) (Last)\n");
2302 for (l
= 0; l
< RTL_NUMBER_OF(ExceptionNames
) - 1; l
++)
2304 if (!ExceptionNames
[l
])
2307 if (!KdbpGetEnterCondition(l
, TRUE
, &ConditionFirst
))
2310 if (!KdbpGetEnterCondition(l
, FALSE
, &ConditionLast
))
2313 KdbpPrint(" #%02d %-20s %-8s %-8s\n", l
, ExceptionNames
[l
],
2314 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst
),
2315 KDB_ENTER_CONDITION_TO_STRING(ConditionLast
));
2318 ASSERT(l
== (RTL_NUMBER_OF(ExceptionNames
) - 1));
2319 KdbpPrint(" %-20s %-8s %-8s\n", ExceptionNames
[l
],
2320 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst
),
2321 KDB_ENTER_CONDITION_TO_STRING(ConditionLast
));
2325 if (Argc
>= 5 && strcmp(Argv
[2], "*") == 0) /* Allow * only when setting condition */
2331 l
= strtoul(Argv
[2], &pend
, 0);
2333 if (Argv
[2] == pend
)
2335 for (l
= 0; l
< RTL_NUMBER_OF(ExceptionNames
); l
++)
2337 if (!ExceptionNames
[l
])
2340 if (_stricmp(ExceptionNames
[l
], Argv
[2]) == 0)
2345 if (l
>= RTL_NUMBER_OF(ExceptionNames
))
2347 KdbpPrint("Unknown exception '%s'.\n", Argv
[2]);
2354 if (_stricmp(Argv
[3], "first") == 0)
2356 else if (_stricmp(Argv
[3], "last") == 0)
2360 KdbpPrint("set condition: second argument must be 'first' or 'last'\n");
2364 if (_stricmp(Argv
[4], "never") == 0)
2365 ConditionFirst
= KdbDoNotEnter
;
2366 else if (_stricmp(Argv
[4], "always") == 0)
2367 ConditionFirst
= KdbEnterAlways
;
2368 else if (_stricmp(Argv
[4], "umode") == 0)
2369 ConditionFirst
= KdbEnterFromUmode
;
2370 else if (_stricmp(Argv
[4], "kmode") == 0)
2371 ConditionFirst
= KdbEnterFromKmode
;
2374 KdbpPrint("set condition: third argument must be 'never', 'always', 'umode' or 'kmode'\n");
2378 if (!KdbpSetEnterCondition(l
, First
, ConditionFirst
))
2381 KdbpPrint("Couldn't change condition for exception #%02d\n", l
);
2383 KdbpPrint("Couldn't change condition for all exceptions\n", l
);
2386 else /* Argc >= 3 */
2388 if (!KdbpGetEnterCondition(l
, TRUE
, &ConditionFirst
))
2391 if (!KdbpGetEnterCondition(l
, FALSE
, &ConditionLast
))
2394 if (l
< (RTL_NUMBER_OF(ExceptionNames
) - 1))
2396 KdbpPrint("Condition for exception #%02d (%s): FirstChance %s LastChance %s\n",
2397 l
, ExceptionNames
[l
],
2398 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst
),
2399 KDB_ENTER_CONDITION_TO_STRING(ConditionLast
));
2403 KdbpPrint("Condition for all other exceptions: FirstChance %s LastChance %s\n",
2404 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst
),
2405 KDB_ENTER_CONDITION_TO_STRING(ConditionLast
));
2410 else if (strcmp(Argv
[1], "break_on_module_load") == 0)
2413 KdbpPrint("break_on_module_load = %s\n", KdbBreakOnModuleLoad
? "enabled" : "disabled");
2416 if (_stricmp(Argv
[2], "enable") == 0 || _stricmp(Argv
[2], "enabled") == 0 || _stricmp(Argv
[2], "true") == 0)
2417 KdbBreakOnModuleLoad
= TRUE
;
2418 else if (_stricmp(Argv
[2], "disable") == 0 || _stricmp(Argv
[2], "disabled") == 0 || _stricmp(Argv
[2], "false") == 0)
2419 KdbBreakOnModuleLoad
= FALSE
;
2421 KdbpPrint("Unknown setting '%s'.\n", Argv
[2]);
2426 KdbpPrint("Unknown setting '%s'.\n", Argv
[1]);
2432 /*!\brief Displays help screen.
2441 KdbpPrint("Kernel debugger commands:\n");
2442 for (i
= 0; i
< RTL_NUMBER_OF(KdbDebuggerCommands
); i
++)
2444 if (!KdbDebuggerCommands
[i
].Syntax
) /* Command group */
2449 KdbpPrint("\x1b[7m* %s:\x1b[0m\n", KdbDebuggerCommands
[i
].Help
);
2453 KdbpPrint(" %-20s - %s\n",
2454 KdbDebuggerCommands
[i
].Syntax
,
2455 KdbDebuggerCommands
[i
].Help
);
2461 /*!\brief Prints the given string with printf-like formatting.
2463 * \param Format Format of the string/arguments.
2464 * \param ... Variable number of arguments matching the format specified in \a Format.
2466 * \note Doesn't correctly handle \\t and terminal escape sequences when calculating the
2467 * number of lines required to print a single line from the Buffer in the terminal.
2468 * Prints maximum 4096 chars, because of its buffer size.
2475 static CHAR Buffer
[4096];
2476 static BOOLEAN TerminalInitialized
= FALSE
;
2477 static BOOLEAN TerminalConnected
= FALSE
;
2478 static BOOLEAN TerminalReportsSize
= TRUE
;
2483 LONG RowsPrintedByTerminal
;
2487 /* Check if the user has aborted output of the current command */
2488 if (KdbOutputAborted
)
2491 /* Initialize the terminal */
2492 if (!TerminalInitialized
)
2494 DbgPrint("\x1b[7h"); /* Enable linewrap */
2496 /* Query terminal type */
2497 /*DbgPrint("\x1b[Z");*/
2500 TerminalInitialized
= TRUE
;
2502 KeStallExecutionProcessor(100000);
2506 c
= KdbpTryGetCharSerial(5000);
2510 Buffer
[Length
++] = c
;
2511 if (Length
>= (sizeof (Buffer
) - 1))
2515 Buffer
[Length
] = '\0';
2517 TerminalConnected
= TRUE
;
2520 /* Get number of rows and columns in terminal */
2521 if ((KdbNumberOfRowsTerminal
< 0) || (KdbNumberOfColsTerminal
< 0) ||
2522 (KdbNumberOfRowsPrinted
) == 0) /* Refresh terminal size each time when number of rows printed is 0 */
2524 if ((KdbDebugState
& KD_DEBUG_KDSERIAL
) && TerminalConnected
&& TerminalReportsSize
)
2526 /* Try to query number of rows from terminal. A reply looks like "\x1b[8;24;80t" */
2527 TerminalReportsSize
= FALSE
;
2528 KeStallExecutionProcessor(100000);
2529 DbgPrint("\x1b[18t");
2530 c
= KdbpTryGetCharSerial(5000);
2534 c
= KdbpTryGetCharSerial(5000);
2541 c
= KdbpTryGetCharSerial(5000);
2545 Buffer
[Length
++] = c
;
2546 if (isalpha(c
) || Length
>= (sizeof (Buffer
) - 1))
2550 Buffer
[Length
] = '\0';
2551 if (Buffer
[0] == '8' && Buffer
[1] == ';')
2553 for (i
= 2; (i
< Length
) && (Buffer
[i
] != ';'); i
++);
2555 if (Buffer
[i
] == ';')
2559 /* Number of rows is now at Buffer + 2 and number of cols at Buffer + i */
2560 KdbNumberOfRowsTerminal
= strtoul(Buffer
+ 2, NULL
, 0);
2561 KdbNumberOfColsTerminal
= strtoul(Buffer
+ i
, NULL
, 0);
2562 TerminalReportsSize
= TRUE
;
2566 /* Clear further characters */
2567 while ((c
= KdbpTryGetCharSerial(5000)) != -1);
2571 if (KdbNumberOfRowsTerminal
<= 0)
2573 /* Set number of rows to the default. */
2574 KdbNumberOfRowsTerminal
= 23; //24; //Mna.: 23 for SCREEN debugport
2576 else if (KdbNumberOfColsTerminal
<= 0)
2578 /* Set number of cols to the default. */
2579 KdbNumberOfColsTerminal
= 75; //80; //Mna.: 75 for SCREEN debugport
2583 /* Get the string */
2584 va_start(ap
, Format
);
2585 Length
= _vsnprintf(Buffer
, sizeof (Buffer
) - 1, Format
, ap
);
2586 Buffer
[Length
] = '\0';
2590 while (p
[0] != '\0')
2592 i
= strcspn(p
, "\n");
2594 /* Calculate the number of lines which will be printed in the terminal
2595 * when outputting the current line
2598 RowsPrintedByTerminal
= (i
+ KdbNumberOfColsPrinted
- 1) / KdbNumberOfColsTerminal
;
2600 RowsPrintedByTerminal
= 0;
2603 RowsPrintedByTerminal
++;
2605 /*DbgPrint("!%d!%d!%d!%d!", KdbNumberOfRowsPrinted, KdbNumberOfColsPrinted, i, RowsPrintedByTerminal);*/
2607 /* Display a prompt if we printed one screen full of text */
2608 if (KdbNumberOfRowsTerminal
> 0 &&
2609 (LONG
)(KdbNumberOfRowsPrinted
+ RowsPrintedByTerminal
) >= KdbNumberOfRowsTerminal
)
2611 KdbRepeatLastCommand
= FALSE
;
2613 if (KdbNumberOfColsPrinted
> 0)
2616 DbgPrint("--- Press q to abort, any other key to continue ---");
2617 RowsPrintedByTerminal
++; /* added by Mna. */
2619 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
2620 c
= KdbpGetCharSerial();
2622 c
= KdbpGetCharKeyboard(&ScanCode
);
2626 /* Try to read '\n' which might follow '\r' - if \n is not received here
2627 * it will be interpreted as "return" when the next command should be read.
2629 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
2630 c
= KdbpTryGetCharSerial(5);
2632 c
= KdbpTryGetCharKeyboard(&ScanCode
, 5);
2638 KdbOutputAborted
= TRUE
;
2642 KdbNumberOfRowsPrinted
= 0;
2643 KdbNumberOfColsPrinted
= 0;
2646 /* Insert a NUL after the line and print only the current line. */
2647 if (p
[i
] == '\n' && p
[i
+ 1] != '\0')
2657 /* Remove escape sequences from the line if there's no terminal connected */
2658 if (!TerminalConnected
)
2660 while ((p2
= strrchr(p
, '\x1b'))) /* Look for escape character */
2665 while (!isalpha(p2
[j
++]));
2680 /* Set p to the start of the next line and
2681 * remember the number of rows/cols printed
2687 KdbNumberOfColsPrinted
= 0;
2691 ASSERT(p
[0] == '\0');
2692 KdbNumberOfColsPrinted
+= i
;
2695 KdbNumberOfRowsPrinted
+= RowsPrintedByTerminal
;
2699 /** memrchr(), explicitly defined, since was absent in MinGW of RosBE. */
2702 * Find the last occurrence of 'c' in the buffer 's' of size 'n'.
2705 memrchr(const void *s
, int c
, size_t n
)
2707 const unsigned char *cp
;
2711 cp
= (unsigned char *)s
+ n
;
2714 if (*(--cp
) == (unsigned char)c
)
2721 /*!\brief Calculate pointer position for N lines upper of current position.
2723 * \param Buffer Characters buffer to operate on.
2724 * \param BufLength Buffer size.
2726 * \note Calculate pointer position for N lines upper of current displaying
2727 * position within the given buffer.
2729 * Used by KdbpPager().
2730 * Now N lines count is hardcoded to KdbNumberOfRowsTerminal.
2733 CountOnePageUp(PCHAR Buffer
, ULONG BufLength
, PCHAR pCurPos
)
2736 // p0 is initial guess of Page Start
2737 ULONG p0len
= KdbNumberOfRowsTerminal
* KdbNumberOfColsTerminal
;
2738 PCHAR p0
= pCurPos
- p0len
;
2739 PCHAR prev_p
= p0
, p1
;
2742 if (pCurPos
< Buffer
)
2744 ASSERT(pCurPos
<= Buffer
+ BufLength
);
2746 p
= memrchr(p0
, '\n', p0len
);
2749 for (j
= KdbNumberOfRowsTerminal
; j
--; )
2752 p1
= memrchr(p0
, '\n', p
-p0
);
2762 linesCnt
= (KdbNumberOfColsTerminal
+prev_p
-p
-2) / KdbNumberOfColsTerminal
;
2772 /*!\brief Prints the given string with, page by page.
2774 * \param Buffer Characters buffer to print.
2775 * \param BufferLen Buffer size.
2777 * \note Doesn't correctly handle \\t and terminal escape sequences when calculating the
2778 * number of lines required to print a single line from the Buffer in the terminal.
2779 * Maximum length of buffer is limited only by memory size.
2781 * Note: BufLength should be greater then (KdbNumberOfRowsTerminal * KdbNumberOfColsTerminal).
2789 static CHAR InBuffer
[4096];
2790 static BOOLEAN TerminalInitialized
= FALSE
;
2791 static BOOLEAN TerminalConnected
= FALSE
;
2792 static BOOLEAN TerminalReportsSize
= TRUE
;
2797 LONG RowsPrintedByTerminal
;
2803 /* Check if the user has aborted output of the current command */
2804 if (KdbOutputAborted
)
2807 /* Initialize the terminal */
2808 if (!TerminalInitialized
)
2810 DbgPrint("\x1b[7h"); /* Enable linewrap */
2812 /* Query terminal type */
2813 /*DbgPrint("\x1b[Z");*/
2816 TerminalInitialized
= TRUE
;
2818 KeStallExecutionProcessor(100000);
2822 c
= KdbpTryGetCharSerial(5000);
2826 InBuffer
[Length
++] = c
;
2827 if (Length
>= (sizeof (InBuffer
) - 1))
2831 InBuffer
[Length
] = '\0';
2833 TerminalConnected
= TRUE
;
2836 /* Get number of rows and columns in terminal */
2837 if ((KdbNumberOfRowsTerminal
< 0) || (KdbNumberOfColsTerminal
< 0) ||
2838 (KdbNumberOfRowsPrinted
) == 0) /* Refresh terminal size each time when number of rows printed is 0 */
2840 if ((KdbDebugState
& KD_DEBUG_KDSERIAL
) && TerminalConnected
&& TerminalReportsSize
)
2842 /* Try to query number of rows from terminal. A reply looks like "\x1b[8;24;80t" */
2843 TerminalReportsSize
= FALSE
;
2844 KeStallExecutionProcessor(100000);
2845 DbgPrint("\x1b[18t");
2846 c
= KdbpTryGetCharSerial(5000);
2850 c
= KdbpTryGetCharSerial(5000);
2857 c
= KdbpTryGetCharSerial(5000);
2861 InBuffer
[Length
++] = c
;
2862 if (isalpha(c
) || Length
>= (sizeof (InBuffer
) - 1))
2866 InBuffer
[Length
] = '\0';
2867 if (InBuffer
[0] == '8' && InBuffer
[1] == ';')
2869 for (i
= 2; (i
< Length
) && (InBuffer
[i
] != ';'); i
++);
2871 if (Buffer
[i
] == ';')
2875 /* Number of rows is now at Buffer + 2 and number of cols at Buffer + i */
2876 KdbNumberOfRowsTerminal
= strtoul(InBuffer
+ 2, NULL
, 0);
2877 KdbNumberOfColsTerminal
= strtoul(InBuffer
+ i
, NULL
, 0);
2878 TerminalReportsSize
= TRUE
;
2882 /* Clear further characters */
2883 while ((c
= KdbpTryGetCharSerial(5000)) != -1);
2887 if (KdbNumberOfRowsTerminal
<= 0)
2889 /* Set number of rows to the default. */
2890 KdbNumberOfRowsTerminal
= 24;
2892 else if (KdbNumberOfColsTerminal
<= 0)
2894 /* Set number of cols to the default. */
2895 KdbNumberOfColsTerminal
= 80;
2899 /* Get the string */
2902 while (p
[0] != '\0')
2904 if ( p
> Buffer
+BufLength
)
2906 DbgPrint("Dmesg: error, p > Buffer+BufLength,d=%d", p
- (Buffer
+BufLength
));
2909 i
= strcspn(p
, "\n");
2911 // Are we out of buffer?
2912 if (p
+ i
> Buffer
+ BufLength
)
2913 // Leaving pager function:
2916 /* Calculate the number of lines which will be printed in the terminal
2917 * when outputting the current line
2920 RowsPrintedByTerminal
= (i
+ KdbNumberOfColsPrinted
- 1) / KdbNumberOfColsTerminal
;
2922 RowsPrintedByTerminal
= 0;
2925 RowsPrintedByTerminal
++;
2927 /*DbgPrint("!%d!%d!%d!%d!", KdbNumberOfRowsPrinted, KdbNumberOfColsPrinted, i, RowsPrintedByTerminal);*/
2929 /* Display a prompt if we printed one screen full of text */
2930 if (KdbNumberOfRowsTerminal
> 0 &&
2931 (LONG
)(KdbNumberOfRowsPrinted
+ RowsPrintedByTerminal
) >= KdbNumberOfRowsTerminal
)
2933 KdbRepeatLastCommand
= FALSE
;
2935 if (KdbNumberOfColsPrinted
> 0)
2938 DbgPrint("--- Press q to abort, e/End,h/Home,u/PgUp, other key/PgDn ---");
2939 RowsPrintedByTerminal
++;
2941 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
2942 c
= KdbpGetCharSerial();
2944 c
= KdbpGetCharKeyboard(&ScanCode
);
2948 /* Try to read '\n' which might follow '\r' - if \n is not received here
2949 * it will be interpreted as "return" when the next command should be read.
2951 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
2952 c
= KdbpTryGetCharSerial(5);
2954 c
= KdbpTryGetCharKeyboard(&ScanCode
, 5);
2957 //DbgPrint("\n"); //Consize version: don't show pressed key
2958 DbgPrint(" '%c'/scan=%04x\n", c
, ScanCode
); // Shows pressed key
2962 KdbOutputAborted
= TRUE
;
2965 if ( ScanCode
== KEYSC_END
|| c
=='e')
2967 PCHAR pBufEnd
= Buffer
+ BufLength
;
2968 p
= CountOnePageUp(Buffer
, BufLength
, pBufEnd
);
2969 i
= strcspn(p
, "\n");
2971 else if (ScanCode
== KEYSC_PAGEUP
|| c
=='u')
2973 p
= CountOnePageUp(Buffer
, BufLength
, p
);
2974 i
= strcspn(p
, "\n");
2976 else if (ScanCode
== KEYSC_HOME
|| c
=='h')
2979 i
= strcspn(p
, "\n");
2981 else if (ScanCode
== KEYSC_ARROWUP
)
2983 p
= CountOnePageUp(Buffer
, BufLength
, p
);
2984 i
= strcspn(p
, "\n");
2987 KdbNumberOfRowsPrinted
= 0;
2988 KdbNumberOfColsPrinted
= 0;
2991 /* Insert a NUL after the line and print only the current line. */
2992 if (p
[i
] == '\n' && p
[i
+ 1] != '\0')
3002 /* Remove escape sequences from the line if there's no terminal connected */
3003 if (!TerminalConnected
)
3005 while ((p2
= strrchr(p
, '\x1b'))) /* Look for escape character */
3010 while (!isalpha(p2
[j
++]));
3020 // The main printing of the current line:
3023 // restore not null char with saved:
3027 /* Set p to the start of the next line and
3028 * remember the number of rows/cols printed
3034 KdbNumberOfColsPrinted
= 0;
3038 ASSERT(p
[0] == '\0');
3039 KdbNumberOfColsPrinted
+= i
;
3042 KdbNumberOfRowsPrinted
+= RowsPrintedByTerminal
;
3046 /*!\brief Appends a command to the command history
3048 * \param Command Pointer to the command to append to the history.
3051 KdbpCommandHistoryAppend(
3054 ULONG Length1
= strlen(Command
) + 1;
3059 ASSERT(Length1
<= RTL_NUMBER_OF(KdbCommandHistoryBuffer
));
3062 (KdbCommandHistory
[KdbCommandHistoryIndex
] &&
3063 strcmp(KdbCommandHistory
[KdbCommandHistoryIndex
], Command
) == 0))
3068 /* Calculate Length1 and Length2 */
3069 Buffer
= KdbCommandHistoryBuffer
+ KdbCommandHistoryBufferIndex
;
3070 KdbCommandHistoryBufferIndex
+= Length1
;
3071 if (KdbCommandHistoryBufferIndex
>= (LONG
)RTL_NUMBER_OF(KdbCommandHistoryBuffer
))
3073 KdbCommandHistoryBufferIndex
-= RTL_NUMBER_OF(KdbCommandHistoryBuffer
);
3074 Length2
= KdbCommandHistoryBufferIndex
;
3078 /* Remove previous commands until there is enough space to append the new command */
3079 for (i
= KdbCommandHistoryIndex
; KdbCommandHistory
[i
];)
3082 (KdbCommandHistory
[i
] >= Buffer
||
3083 KdbCommandHistory
[i
] < (KdbCommandHistoryBuffer
+ KdbCommandHistoryBufferIndex
))) ||
3085 (KdbCommandHistory
[i
] >= Buffer
&&
3086 KdbCommandHistory
[i
] < (KdbCommandHistoryBuffer
+ KdbCommandHistoryBufferIndex
))))
3088 KdbCommandHistory
[i
] = NULL
;
3093 i
= RTL_NUMBER_OF(KdbCommandHistory
) - 1;
3095 if (i
== KdbCommandHistoryIndex
)
3099 /* Make sure the new command history entry is free */
3100 KdbCommandHistoryIndex
++;
3101 KdbCommandHistoryIndex
%= RTL_NUMBER_OF(KdbCommandHistory
);
3102 if (KdbCommandHistory
[KdbCommandHistoryIndex
])
3104 KdbCommandHistory
[KdbCommandHistoryIndex
] = NULL
;
3107 /* Append command */
3108 KdbCommandHistory
[KdbCommandHistoryIndex
] = Buffer
;
3109 ASSERT((KdbCommandHistory
[KdbCommandHistoryIndex
] + Length1
) <= KdbCommandHistoryBuffer
+ RTL_NUMBER_OF(KdbCommandHistoryBuffer
));
3110 memcpy(KdbCommandHistory
[KdbCommandHistoryIndex
], Command
, Length1
);
3113 memcpy(KdbCommandHistoryBuffer
, Command
+ Length1
, Length2
);
3117 /*!\brief Reads a line of user-input.
3119 * \param Buffer Buffer to store the input into. Trailing newlines are removed.
3120 * \param Size Size of \a Buffer.
3122 * \note Accepts only \n newlines, \r is ignored.
3130 PCHAR Orig
= Buffer
;
3133 static CHAR LastCommand
[1024];
3134 static CHAR NextKey
= '\0';
3135 INT CmdHistIndex
= -1;
3138 EchoOn
= !((KdbDebugState
& KD_DEBUG_KDNOECHO
) != 0);
3142 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
3144 Key
= (NextKey
== '\0') ? KdbpGetCharSerial() : NextKey
;
3147 if (Key
== KEY_ESC
) /* ESC */
3149 Key
= KdbpGetCharSerial();
3152 Key
= KdbpGetCharSerial();
3157 ScanCode
= KEY_SCAN_UP
;
3160 ScanCode
= KEY_SCAN_DOWN
;
3173 Key
= (NextKey
== '\0') ? KdbpGetCharKeyboard(&ScanCode
) : NextKey
;
3177 if ((ULONG
)(Buffer
- Orig
) >= (Size
- 1))
3179 /* Buffer is full, accept only newlines */
3186 /* Read the next char - this is to throw away a \n which most clients should
3189 KeStallExecutionProcessor(100000);
3191 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
3192 NextKey
= KdbpTryGetCharSerial(5);
3194 NextKey
= KdbpTryGetCharKeyboard(&ScanCode
, 5);
3196 if (NextKey
== '\n' || NextKey
== -1) /* \n or no response at all */
3202 * Repeat the last command if the user presses enter. Reduces the
3203 * risk of RSI when single-stepping.
3207 KdbRepeatLastCommand
= TRUE
;
3209 RtlStringCbCopyA(LastCommand
, sizeof(LastCommand
), Orig
);
3211 else if (KdbRepeatLastCommand
)
3212 RtlStringCbCopyA(Buffer
, Size
, LastCommand
);
3218 else if (Key
== KEY_BS
|| Key
== KEY_DEL
)
3226 KdbpPrint("%c %c", KEY_BS
, KEY_BS
);
3228 KdbpPrint(" %c", KEY_BS
);
3231 else if (ScanCode
== KEY_SCAN_UP
)
3233 BOOLEAN Print
= TRUE
;
3235 if (CmdHistIndex
< 0)
3237 CmdHistIndex
= KdbCommandHistoryIndex
;
3241 i
= CmdHistIndex
- 1;
3244 CmdHistIndex
= RTL_NUMBER_OF(KdbCommandHistory
) - 1;
3246 if (KdbCommandHistory
[i
] && i
!= KdbCommandHistoryIndex
)
3252 if (Print
&& KdbCommandHistory
[CmdHistIndex
])
3254 while (Buffer
> Orig
)
3260 KdbpPrint("%c %c", KEY_BS
, KEY_BS
);
3262 KdbpPrint(" %c", KEY_BS
);
3265 i
= min(strlen(KdbCommandHistory
[CmdHistIndex
]), Size
- 1);
3266 memcpy(Orig
, KdbCommandHistory
[CmdHistIndex
], i
);
3269 KdbpPrint("%s", Orig
);
3272 else if (ScanCode
== KEY_SCAN_DOWN
)
3274 if (CmdHistIndex
> 0 && CmdHistIndex
!= KdbCommandHistoryIndex
)
3276 i
= CmdHistIndex
+ 1;
3277 if (i
>= (INT
)RTL_NUMBER_OF(KdbCommandHistory
))
3280 if (KdbCommandHistory
[i
])
3283 while (Buffer
> Orig
)
3289 KdbpPrint("%c %c", KEY_BS
, KEY_BS
);
3291 KdbpPrint(" %c", KEY_BS
);
3294 i
= min(strlen(KdbCommandHistory
[CmdHistIndex
]), Size
- 1);
3295 memcpy(Orig
, KdbCommandHistory
[CmdHistIndex
], i
);
3298 KdbpPrint("%s", Orig
);
3305 KdbpPrint("%c", Key
);
3316 KdbRegisterCliCallback(
3322 /* Loop all entries */
3323 for (i
= 0; i
< _countof(KdbCliCallbacks
); i
++)
3325 /* Check if deregistering was requested */
3328 /* Check if this entry is the one that was registered */
3329 if (KdbCliCallbacks
[i
] == Callback
)
3331 /* Delete it and report success */
3332 KdbCliCallbacks
[i
] = NULL
;
3338 /* Check if this entry is free */
3339 if (KdbCliCallbacks
[i
] == NULL
)
3341 /* Set it and and report success */
3342 KdbCliCallbacks
[i
] = Callback
;
3352 /*! \brief Invokes registered CLI callbacks until one of them handled the
3355 * \param Command - Command line to parse and execute if possible.
3356 * \param Argc - Number of arguments in Argv
3357 * \param Argv - Array of strings, each of them containing one argument.
3359 * \return TRUE, if the command was handled, FALSE if it was not handled.
3363 KdbpInvokeCliCallbacks(
3370 /* Loop all entries */
3371 for (i
= 0; i
< _countof(KdbCliCallbacks
); i
++)
3373 /* Check if this entry is registered */
3374 if (KdbCliCallbacks
[i
])
3376 /* Invoke the callback and check if it handled the command */
3377 if (KdbCliCallbacks
[i
](Command
, Argc
, Argv
))
3384 /* None of the callbacks handled the command */
3389 /*!\brief Parses command line and executes command if found
3391 * \param Command Command line to parse and execute if possible.
3393 * \retval TRUE Don't continue execution.
3394 * \retval FALSE Continue execution (leave KDB)
3403 // FIXME: for what do we need a 1024 characters command line and 256 tokens?
3404 static PCH Argv
[256];
3405 static CHAR OrigCommand
[1024];
3407 RtlStringCbCopyA(OrigCommand
, sizeof(OrigCommand
), Command
);
3414 while (*p
== '\t' || *p
== ' ')
3420 i
= strcspn(p
, "\t ");
3433 for (i
= 0; i
< RTL_NUMBER_OF(KdbDebuggerCommands
); i
++)
3435 if (!KdbDebuggerCommands
[i
].Name
)
3438 if (strcmp(KdbDebuggerCommands
[i
].Name
, Argv
[0]) == 0)
3440 return KdbDebuggerCommands
[i
].Fn(Argc
, Argv
);
3444 /* Now invoke the registered callbacks */
3445 if (KdbpInvokeCliCallbacks(Command
, Argc
, Argv
))
3450 KdbpPrint("Command '%s' is unknown.\n", OrigCommand
);
3454 /*!\brief KDB Main Loop.
3456 * \param EnteredOnSingleStep TRUE if KDB was entered on single step.
3460 IN BOOLEAN EnteredOnSingleStep
)
3462 static CHAR Command
[1024];
3465 if (EnteredOnSingleStep
)
3467 if (!KdbSymPrintAddress((PVOID
)KdbCurrentTrapFrame
->Tf
.Eip
, &KdbCurrentTrapFrame
->Tf
))
3469 KdbpPrint("<%x>", KdbCurrentTrapFrame
->Tf
.Eip
);
3473 if (KdbpDisassemble(KdbCurrentTrapFrame
->Tf
.Eip
, KdbUseIntelSyntax
) < 0)
3475 KdbpPrint("<INVALID>");
3480 /* Flush the input buffer */
3481 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
3483 while (KdbpTryGetCharSerial(1) != -1);
3488 while (KdbpTryGetCharKeyboard(&ScanCode
, 1) != -1);
3494 /* Reset the number of rows/cols printed */
3495 KdbNumberOfRowsPrinted
= KdbNumberOfColsPrinted
= 0;
3497 /* Print the prompt */
3498 KdbpPrint("kdb:> ");
3500 /* Read a command and remember it */
3501 KdbpReadCommand(Command
, sizeof (Command
));
3502 KdbpCommandHistoryAppend(Command
);
3504 /* Reset the number of rows/cols printed and output aborted state */
3505 KdbNumberOfRowsPrinted
= KdbNumberOfColsPrinted
= 0;
3506 KdbOutputAborted
= FALSE
;
3508 /* Call the command */
3509 Continue
= KdbpDoCommand(Command
);
3510 KdbOutputAborted
= FALSE
;
3515 /*!\brief Called when a module is loaded.
3517 * \param Name Filename of the module which was loaded.
3520 KdbpCliModuleLoaded(
3521 IN PUNICODE_STRING Name
)
3523 if (!KdbBreakOnModuleLoad
)
3526 KdbpPrint("Module %wZ loaded.\n", Name
);
3527 DbgBreakPointWithStatus(DBG_STATUS_CONTROL_C
);
3530 /*!\brief This function is called by KdbEnterDebuggerException...
3532 * Used to interpret the init file in a context with a trapframe setup
3533 * (KdbpCliInit call KdbEnter which will call KdbEnterDebuggerException which will
3534 * call this function if KdbInitFileBuffer is not NULL.
3537 KdbpCliInterpretInitFile(VOID
)
3543 /* Execute the commands in the init file */
3544 DPRINT("KDB: Executing KDBinit file...\n");
3545 p1
= KdbInitFileBuffer
;
3546 while (p1
[0] != '\0')
3548 i
= strcspn(p1
, "\r\n");
3554 /* Look for "break" command and comments */
3557 while (isspace(p2
[0]))
3560 if (strncmp(p2
, "break", sizeof("break")-1) == 0 &&
3561 (p2
[sizeof("break")-1] == '\0' || isspace(p2
[sizeof("break")-1])))
3563 /* break into the debugger */
3564 KdbpCliMainLoop(FALSE
);
3566 else if (p2
[0] != '#' && p2
[0] != '\0') /* Ignore empty lines and comments */
3575 while (p1
[0] == '\r' || p1
[0] == '\n')
3578 DPRINT("KDB: KDBinit executed\n");
3581 /*!\brief Called when KDB is initialized
3583 * Reads the KDBinit file from the SystemRoot\System32\drivers\etc directory and executes it.
3589 OBJECT_ATTRIBUTES ObjectAttributes
;
3590 UNICODE_STRING FileName
;
3591 IO_STATUS_BLOCK Iosb
;
3592 FILE_STANDARD_INFORMATION FileStdInfo
;
3593 HANDLE hFile
= NULL
;
3598 /* Initialize the object attributes */
3599 RtlInitUnicodeString(&FileName
, L
"\\SystemRoot\\System32\\drivers\\etc\\KDBinit");
3600 InitializeObjectAttributes(&ObjectAttributes
, &FileName
, 0, NULL
, NULL
);
3603 Status
= ZwOpenFile(&hFile
, FILE_READ_DATA
| SYNCHRONIZE
,
3604 &ObjectAttributes
, &Iosb
, 0,
3605 FILE_NON_DIRECTORY_FILE
| FILE_SYNCHRONOUS_IO_NONALERT
|
3606 FILE_NO_INTERMEDIATE_BUFFERING
);
3607 if (!NT_SUCCESS(Status
))
3609 DPRINT("Could not open \\SystemRoot\\System32\\drivers\\etc\\KDBinit (Status 0x%x)", Status
);
3613 /* Get the size of the file */
3614 Status
= ZwQueryInformationFile(hFile
, &Iosb
, &FileStdInfo
, sizeof (FileStdInfo
),
3615 FileStandardInformation
);
3616 if (!NT_SUCCESS(Status
))
3619 DPRINT("Could not query size of \\SystemRoot\\System32\\drivers\\etc\\KDBinit (Status 0x%x)", Status
);
3622 FileSize
= FileStdInfo
.EndOfFile
.u
.LowPart
;
3624 /* Allocate memory for the file */
3625 FileBuffer
= ExAllocatePool(PagedPool
, FileSize
+ 1); /* add 1 byte for terminating '\0' */
3629 DPRINT("Could not allocate %d bytes for KDBinit file\n", FileSize
);
3633 /* Load file into memory */
3634 Status
= ZwReadFile(hFile
, NULL
, NULL
, NULL
, &Iosb
, FileBuffer
, FileSize
, NULL
, NULL
);
3637 if (!NT_SUCCESS(Status
) && Status
!= STATUS_END_OF_FILE
)
3639 ExFreePool(FileBuffer
);
3640 DPRINT("Could not read KDBinit file into memory (Status 0x%lx)\n", Status
);
3644 FileSize
= min(FileSize
, (INT
)Iosb
.Information
);
3645 FileBuffer
[FileSize
] = '\0';
3647 /* Enter critical section */
3648 OldEflags
= __readeflags();
3651 /* Interpret the init file... */
3652 KdbInitFileBuffer
= FileBuffer
;
3654 KdbInitFileBuffer
= NULL
;
3656 /* Leave critical section */
3657 __writeeflags(OldEflags
);
3659 ExFreePool(FileBuffer
);
3664 KdpSerialDebugPrint(
3669 STRING KdpPromptString
= RTL_CONSTANT_STRING("kdb:> ");
3670 extern KSPIN_LOCK KdpSerialSpinLock
;
3675 _In_reads_bytes_(InStringLength
) PCHAR UnsafeInString
,
3676 _In_ USHORT InStringLength
,
3677 _Out_writes_bytes_(OutStringLength
) PCHAR UnsafeOutString
,
3678 _In_ USHORT OutStringLength
,
3679 _In_ KPROCESSOR_MODE PreviousMode
)
3683 ULONG DummyScanCode
;
3687 CHAR InStringBuffer
[512];
3688 CHAR OutStringBuffer
[512];
3690 /* Normalize the lengths */
3691 InStringLength
= min(InStringLength
,
3692 sizeof(InStringBuffer
));
3693 OutStringLength
= min(OutStringLength
,
3694 sizeof(OutStringBuffer
));
3696 /* Check if we need to verify the string */
3697 if (PreviousMode
!= KernelMode
)
3699 /* Handle user-mode buffers safely */
3702 /* Probe the prompt */
3703 ProbeForRead(UnsafeInString
,
3707 /* Capture prompt */
3708 InString
= InStringBuffer
;
3709 RtlCopyMemory(InString
,
3713 /* Probe and make room for response */
3714 ProbeForWrite(UnsafeOutString
,
3717 OutString
= OutStringBuffer
;
3719 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
3721 /* Bad string pointer, bail out */
3722 _SEH2_YIELD(return 0);
3728 InString
= UnsafeInString
;
3729 OutString
= UnsafeOutString
;
3732 /* Acquire the printing spinlock without waiting at raised IRQL */
3735 /* Wait when the spinlock becomes available */
3736 while (!KeTestSpinLock(&KdpSerialSpinLock
));
3738 /* Spinlock was free, raise IRQL */
3739 KeRaiseIrql(HIGH_LEVEL
, &OldIrql
);
3741 /* Try to get the spinlock */
3742 if (KeTryToAcquireSpinLockAtDpcLevel(&KdpSerialSpinLock
))
3745 /* Someone else got the spinlock, lower IRQL back */
3746 KeLowerIrql(OldIrql
);
3749 /* Loop the string to send */
3750 for (i
= 0; i
< InStringLength
; i
++)
3752 /* Print it to serial */
3753 KdPortPutByteEx(&SerialPortInfo
, *(PCHAR
)(InString
+ i
));
3756 /* Print a new line for log neatness */
3757 KdPortPutByteEx(&SerialPortInfo
, '\r');
3758 KdPortPutByteEx(&SerialPortInfo
, '\n');
3760 /* Print the kdb prompt */
3761 for (i
= 0; i
< KdpPromptString
.Length
; i
++)
3763 /* Print it to serial */
3764 KdPortPutByteEx(&SerialPortInfo
,
3765 *(KdpPromptString
.Buffer
+ i
));
3768 if (!(KdbDebugState
& KD_DEBUG_KDSERIAL
))
3771 /* Loop the whole string */
3772 for (i
= 0; i
< OutStringLength
; i
++)
3774 /* Check if this is serial debugging mode */
3775 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
3777 /* Get the character from serial */
3780 Response
= KdbpTryGetCharSerial(MAXULONG
);
3781 } while (Response
== -1);
3785 /* Get the response from the keyboard */
3788 Response
= KdbpTryGetCharKeyboard(&DummyScanCode
, MAXULONG
);
3789 } while (Response
== -1);
3792 /* Check for return */
3793 if (Response
== '\r')
3796 * We might need to discard the next '\n'.
3797 * Wait a bit to make sure we receive it.
3799 KeStallExecutionProcessor(100000);
3801 /* Check the mode */
3802 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
3804 /* Read and discard the next character, if any */
3805 KdbpTryGetCharSerial(5);
3809 /* Read and discard the next character, if any */
3810 KdbpTryGetCharKeyboard(&DummyScanCode
, 5);
3814 * Null terminate the output string -- documentation states that
3815 * DbgPrompt does not null terminate, but it does
3817 *(PCHAR
)(OutString
+ i
) = 0;
3821 /* Write it back and print it to the log */
3822 *(PCHAR
)(OutString
+ i
) = Response
;
3823 KdPortPutByteEx(&SerialPortInfo
, Response
);
3826 if (!(KdbDebugState
& KD_DEBUG_KDSERIAL
))
3829 /* Print a new line */
3830 KdPortPutByteEx(&SerialPortInfo
, '\r');
3831 KdPortPutByteEx(&SerialPortInfo
, '\n');
3833 /* Release spinlock */
3834 KiReleaseSpinLock(&KdpSerialSpinLock
);
3836 /* Lower IRQL back */
3837 KeLowerIrql(OldIrql
);
3839 /* Copy back response if required */
3840 if (PreviousMode
!= KernelMode
)
3844 /* Safely copy back response to user mode */
3845 RtlCopyMemory(UnsafeOutString
,
3849 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
3851 /* String became invalid after we exited, fail */
3852 _SEH2_YIELD(return 0);
3857 /* Return the length */