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
ExpKdbgExtPoolFind(ULONG Argc
, PCHAR Argv
[]);
97 BOOLEAN
ExpKdbgExtFileCache(ULONG Argc
, PCHAR Argv
[]);
98 BOOLEAN
ExpKdbgExtDefWrites(ULONG Argc
, PCHAR Argv
[]);
99 BOOLEAN
ExpKdbgExtIrpFind(ULONG Argc
, PCHAR Argv
[]);
100 BOOLEAN
ExpKdbgExtHandle(ULONG Argc
, PCHAR Argv
[]);
103 static BOOLEAN
KdbpCmdPrintStruct(ULONG Argc
, PCHAR Argv
[]);
106 /* GLOBALS *******************************************************************/
108 static PKDBG_CLI_ROUTINE KdbCliCallbacks
[10];
109 static BOOLEAN KdbUseIntelSyntax
= FALSE
; /* Set to TRUE for intel syntax */
110 static BOOLEAN KdbBreakOnModuleLoad
= FALSE
; /* Set to TRUE to break into KDB when a module is loaded */
112 static CHAR KdbCommandHistoryBuffer
[2048]; /* Command history string ringbuffer */
113 static PCHAR KdbCommandHistory
[sizeof(KdbCommandHistoryBuffer
) / 8] = { NULL
}; /* Command history ringbuffer */
114 static LONG KdbCommandHistoryBufferIndex
= 0;
115 static LONG KdbCommandHistoryIndex
= 0;
117 static ULONG KdbNumberOfRowsPrinted
= 0;
118 static ULONG KdbNumberOfColsPrinted
= 0;
119 static BOOLEAN KdbOutputAborted
= FALSE
;
120 static BOOLEAN KdbRepeatLastCommand
= FALSE
;
121 static LONG KdbNumberOfRowsTerminal
= -1;
122 static LONG KdbNumberOfColsTerminal
= -1;
124 PCHAR KdbInitFileBuffer
= NULL
; /* Buffer where KDBinit file is loaded into during initialization */
125 BOOLEAN KdbpBugCheckRequested
= FALSE
;
128 /* defined in ../kd/kdio.c, declare here: */
129 extern volatile BOOLEAN KdbpIsInDmesgMode
;
130 extern const ULONG KdpDmesgBufferSize
;
131 extern PCHAR KdpDmesgBuffer
;
132 extern volatile ULONG KdpDmesgCurrentPosition
;
133 extern volatile ULONG KdpDmesgFreeBytes
;
134 extern volatile ULONG KdbDmesgTotalWritten
;
141 BOOLEAN (*Fn
)(ULONG Argc
, PCHAR Argv
[]);
142 } KdbDebuggerCommands
[] = {
144 { NULL
, NULL
, "Data", NULL
},
145 { "?", "? expression", "Evaluate expression.", KdbpCmdEvalExpression
},
146 { "disasm", "disasm [address] [L count]", "Disassemble count instructions at address.", KdbpCmdDisassembleX
},
147 { "x", "x [address] [L count]", "Display count dwords, starting at addr.", KdbpCmdDisassembleX
},
148 { "regs", "regs", "Display general purpose registers.", KdbpCmdRegs
},
149 { "cregs", "cregs", "Display control registers.", KdbpCmdRegs
},
150 { "sregs", "sregs", "Display status registers.", KdbpCmdRegs
},
151 { "dregs", "dregs", "Display debug registers.", KdbpCmdRegs
},
152 { "bt", "bt [*frameaddr|thread id]", "Prints current backtrace or from given frame addr", KdbpCmdBackTrace
},
154 { "dt", "dt [mod] [type] [addr]", "Print a struct. Addr is optional.", KdbpCmdPrintStruct
},
158 { NULL
, NULL
, "Flow control", NULL
},
159 { "cont", "cont", "Continue execution (leave debugger)", KdbpCmdContinue
},
160 { "step", "step [count]", "Execute single instructions, stepping into interrupts.", KdbpCmdStep
},
161 { "next", "next [count]", "Execute single instructions, skipping calls and reps.", KdbpCmdStep
},
162 { "bl", "bl", "List breakpoints.", KdbpCmdBreakPointList
},
163 { "be", "be [breakpoint]", "Enable breakpoint.", KdbpCmdEnableDisableClearBreakPoint
},
164 { "bd", "bd [breakpoint]", "Disable breakpoint.", KdbpCmdEnableDisableClearBreakPoint
},
165 { "bc", "bc [breakpoint]", "Clear breakpoint.", KdbpCmdEnableDisableClearBreakPoint
},
166 { "bpx", "bpx [address] [IF condition]", "Set software execution breakpoint at address.", KdbpCmdBreakPoint
},
167 { "bpm", "bpm [r|w|rw|x] [byte|word|dword] [address] [IF condition]", "Set memory breakpoint at address.", KdbpCmdBreakPoint
},
170 { NULL
, NULL
, "Process/Thread", NULL
},
171 { "thread", "thread [list[ pid]|[attach ]tid]", "List threads in current or specified process, display thread with given id or attach to thread.", KdbpCmdThread
},
172 { "proc", "proc [list|[attach ]pid]", "List processes, display process with given id or attach to process.", KdbpCmdProc
},
174 /* System information */
175 { NULL
, NULL
, "System info", NULL
},
176 { "mod", "mod [address]", "List all modules or the one containing address.", KdbpCmdMod
},
177 { "gdt", "gdt", "Display global descriptor table.", KdbpCmdGdtLdtIdt
},
178 { "ldt", "ldt", "Display local descriptor table.", KdbpCmdGdtLdtIdt
},
179 { "idt", "idt", "Display interrupt descriptor table.", KdbpCmdGdtLdtIdt
},
180 { "pcr", "pcr", "Display processor control region.", KdbpCmdPcr
},
181 { "tss", "tss", "Display task state segment.", KdbpCmdTss
},
184 { NULL
, NULL
, "Others", NULL
},
185 { "bugcheck", "bugcheck", "Bugchecks the system.", KdbpCmdBugCheck
},
186 { "reboot", "reboot", "Reboots the system.", KdbpCmdReboot
},
187 { "filter", "filter [error|warning|trace|info|level]+|-[componentname|default]", "Enable/disable debug channels", KdbpCmdFilter
},
188 { "set", "set [var] [value]", "Sets var to value or displays value of var.", KdbpCmdSet
},
189 { "dmesg", "dmesg", "Display debug messages on screen, with navigation on pages.", KdbpCmdDmesg
},
190 { "kmsg", "kmsg", "Kernel dmesg. Alias for dmesg.", KdbpCmdDmesg
},
191 { "help", "help", "Display help screen.", KdbpCmdHelp
},
192 { "!pool", "!pool [Address [Flags]]", "Display information about pool allocations.", ExpKdbgExtPool
},
193 { "!poolused", "!poolused [Flags [Tag]]", "Display pool usage.", ExpKdbgExtPoolUsed
},
194 { "!poolfind", "!poolfind Tag [Pool]", "Search for pool tag allocations.", ExpKdbgExtPoolFind
},
195 { "!filecache", "!filecache", "Display cache usage.", ExpKdbgExtFileCache
},
196 { "!defwrites", "!defwrites", "Display cache write values.", ExpKdbgExtDefWrites
},
197 { "!irpfind", "!irpfind [Pool [startaddress [criteria data]]]", "Lists IRPs potentially matching criteria", ExpKdbgExtIrpFind
},
198 { "!handle", "!handle [Handle]", "Displays info about handles", ExpKdbgExtHandle
},
201 /* FUNCTIONS *****************************************************************/
203 /*!\brief Transform a component name to an integer
205 * \param ComponentName The name of the component.
206 * \param ComponentId Receives the component id on success.
208 * \retval TRUE Success.
209 * \retval FALSE Failure.
213 IN PCCH ComponentName
,
214 OUT PULONG ComponentId
)
225 { "DEFAULT", MAXULONG
},
226 { "SYSTEM", DPFLTR_SYSTEM_ID
},
227 { "SMSS", DPFLTR_SMSS_ID
},
228 { "SETUP", DPFLTR_SETUP_ID
},
229 { "NTFS", DPFLTR_NTFS_ID
},
230 { "FSTUB", DPFLTR_FSTUB_ID
},
231 { "CRASHDUMP", DPFLTR_CRASHDUMP_ID
},
232 { "CDAUDIO", DPFLTR_CDAUDIO_ID
},
233 { "CDROM", DPFLTR_CDROM_ID
},
234 { "CLASSPNP", DPFLTR_CLASSPNP_ID
},
235 { "DISK", DPFLTR_DISK_ID
},
236 { "REDBOOK", DPFLTR_REDBOOK_ID
},
237 { "STORPROP", DPFLTR_STORPROP_ID
},
238 { "SCSIPORT", DPFLTR_SCSIPORT_ID
},
239 { "SCSIMINIPORT", DPFLTR_SCSIMINIPORT_ID
},
240 { "CONFIG", DPFLTR_CONFIG_ID
},
241 { "I8042PRT", DPFLTR_I8042PRT_ID
},
242 { "SERMOUSE", DPFLTR_SERMOUSE_ID
},
243 { "LSERMOUS", DPFLTR_LSERMOUS_ID
},
244 { "KBDHID", DPFLTR_KBDHID_ID
},
245 { "MOUHID", DPFLTR_MOUHID_ID
},
246 { "KBDCLASS", DPFLTR_KBDCLASS_ID
},
247 { "MOUCLASS", DPFLTR_MOUCLASS_ID
},
248 { "TWOTRACK", DPFLTR_TWOTRACK_ID
},
249 { "WMILIB", DPFLTR_WMILIB_ID
},
250 { "ACPI", DPFLTR_ACPI_ID
},
251 { "AMLI", DPFLTR_AMLI_ID
},
252 { "HALIA64", DPFLTR_HALIA64_ID
},
253 { "VIDEO", DPFLTR_VIDEO_ID
},
254 { "SVCHOST", DPFLTR_SVCHOST_ID
},
255 { "VIDEOPRT", DPFLTR_VIDEOPRT_ID
},
256 { "TCPIP", DPFLTR_TCPIP_ID
},
257 { "DMSYNTH", DPFLTR_DMSYNTH_ID
},
258 { "NTOSPNP", DPFLTR_NTOSPNP_ID
},
259 { "FASTFAT", DPFLTR_FASTFAT_ID
},
260 { "SAMSS", DPFLTR_SAMSS_ID
},
261 { "PNPMGR", DPFLTR_PNPMGR_ID
},
262 { "NETAPI", DPFLTR_NETAPI_ID
},
263 { "SCSERVER", DPFLTR_SCSERVER_ID
},
264 { "SCCLIENT", DPFLTR_SCCLIENT_ID
},
265 { "SERIAL", DPFLTR_SERIAL_ID
},
266 { "SERENUM", DPFLTR_SERENUM_ID
},
267 { "UHCD", DPFLTR_UHCD_ID
},
268 { "RPCPROXY", DPFLTR_RPCPROXY_ID
},
269 { "AUTOCHK", DPFLTR_AUTOCHK_ID
},
270 { "DCOMSS", DPFLTR_DCOMSS_ID
},
271 { "UNIMODEM", DPFLTR_UNIMODEM_ID
},
272 { "SIS", DPFLTR_SIS_ID
},
273 { "FLTMGR", DPFLTR_FLTMGR_ID
},
274 { "WMICORE", DPFLTR_WMICORE_ID
},
275 { "BURNENG", DPFLTR_BURNENG_ID
},
276 { "IMAPI", DPFLTR_IMAPI_ID
},
277 { "SXS", DPFLTR_SXS_ID
},
278 { "FUSION", DPFLTR_FUSION_ID
},
279 { "IDLETASK", DPFLTR_IDLETASK_ID
},
280 { "SOFTPCI", DPFLTR_SOFTPCI_ID
},
281 { "TAPE", DPFLTR_TAPE_ID
},
282 { "MCHGR", DPFLTR_MCHGR_ID
},
283 { "IDEP", DPFLTR_IDEP_ID
},
284 { "PCIIDE", DPFLTR_PCIIDE_ID
},
285 { "FLOPPY", DPFLTR_FLOPPY_ID
},
286 { "FDC", DPFLTR_FDC_ID
},
287 { "TERMSRV", DPFLTR_TERMSRV_ID
},
288 { "W32TIME", DPFLTR_W32TIME_ID
},
289 { "PREFETCHER", DPFLTR_PREFETCHER_ID
},
290 { "RSFILTER", DPFLTR_RSFILTER_ID
},
291 { "FCPORT", DPFLTR_FCPORT_ID
},
292 { "PCI", DPFLTR_PCI_ID
},
293 { "DMIO", DPFLTR_DMIO_ID
},
294 { "DMCONFIG", DPFLTR_DMCONFIG_ID
},
295 { "DMADMIN", DPFLTR_DMADMIN_ID
},
296 { "WSOCKTRANSPORT", DPFLTR_WSOCKTRANSPORT_ID
},
297 { "VSS", DPFLTR_VSS_ID
},
298 { "PNPMEM", DPFLTR_PNPMEM_ID
},
299 { "PROCESSOR", DPFLTR_PROCESSOR_ID
},
300 { "DMSERVER", DPFLTR_DMSERVER_ID
},
301 { "SR", DPFLTR_SR_ID
},
302 { "INFINIBAND", DPFLTR_INFINIBAND_ID
},
303 { "IHVDRIVER", DPFLTR_IHVDRIVER_ID
},
304 { "IHVVIDEO", DPFLTR_IHVVIDEO_ID
},
305 { "IHVAUDIO", DPFLTR_IHVAUDIO_ID
},
306 { "IHVNETWORK", DPFLTR_IHVNETWORK_ID
},
307 { "IHVSTREAMING", DPFLTR_IHVSTREAMING_ID
},
308 { "IHVBUS", DPFLTR_IHVBUS_ID
},
309 { "HPS", DPFLTR_HPS_ID
},
310 { "RTLTHREADPOOL", DPFLTR_RTLTHREADPOOL_ID
},
311 { "LDR", DPFLTR_LDR_ID
},
312 { "TCPIP6", DPFLTR_TCPIP6_ID
},
313 { "ISAPNP", DPFLTR_ISAPNP_ID
},
314 { "SHPC", DPFLTR_SHPC_ID
},
315 { "STORPORT", DPFLTR_STORPORT_ID
},
316 { "STORMINIPORT", DPFLTR_STORMINIPORT_ID
},
317 { "PRINTSPOOLER", DPFLTR_PRINTSPOOLER_ID
},
318 { "VSSDYNDISK", DPFLTR_VSSDYNDISK_ID
},
319 { "VERIFIER", DPFLTR_VERIFIER_ID
},
320 { "VDS", DPFLTR_VDS_ID
},
321 { "VDSBAS", DPFLTR_VDSBAS_ID
},
322 { "VDSDYN", DPFLTR_VDSDYN_ID
},
323 { "VDSDYNDR", DPFLTR_VDSDYNDR_ID
},
324 { "VDSLDR", DPFLTR_VDSLDR_ID
},
325 { "VDSUTIL", DPFLTR_VDSUTIL_ID
},
326 { "DFRGIFC", DPFLTR_DFRGIFC_ID
},
327 { "MM", DPFLTR_MM_ID
},
328 { "DFSC", DPFLTR_DFSC_ID
},
329 { "WOW64", DPFLTR_WOW64_ID
},
330 { "ALPC", DPFLTR_ALPC_ID
},
331 { "WDI", DPFLTR_WDI_ID
},
332 { "PERFLIB", DPFLTR_PERFLIB_ID
},
333 { "KTM", DPFLTR_KTM_ID
},
334 { "IOSTRESS", DPFLTR_IOSTRESS_ID
},
335 { "HEAP", DPFLTR_HEAP_ID
},
336 { "WHEA", DPFLTR_WHEA_ID
},
337 { "USERGDI", DPFLTR_USERGDI_ID
},
338 { "MMCSS", DPFLTR_MMCSS_ID
},
339 { "TPM", DPFLTR_TPM_ID
},
340 { "THREADORDER", DPFLTR_THREADORDER_ID
},
341 { "ENVIRON", DPFLTR_ENVIRON_ID
},
342 { "EMS", DPFLTR_EMS_ID
},
343 { "WDT", DPFLTR_WDT_ID
},
344 { "FVEVOL", DPFLTR_FVEVOL_ID
},
345 { "NDIS", DPFLTR_NDIS_ID
},
346 { "NVCTRACE", DPFLTR_NVCTRACE_ID
},
347 { "LUAFV", DPFLTR_LUAFV_ID
},
348 { "APPCOMPAT", DPFLTR_APPCOMPAT_ID
},
349 { "USBSTOR", DPFLTR_USBSTOR_ID
},
350 { "SBP2PORT", DPFLTR_SBP2PORT_ID
},
351 { "COVERAGE", DPFLTR_COVERAGE_ID
},
352 { "CACHEMGR", DPFLTR_CACHEMGR_ID
},
353 { "MOUNTMGR", DPFLTR_MOUNTMGR_ID
},
354 { "CFR", DPFLTR_CFR_ID
},
355 { "TXF", DPFLTR_TXF_ID
},
356 { "KSECDD", DPFLTR_KSECDD_ID
},
357 { "FLTREGRESS", DPFLTR_FLTREGRESS_ID
},
358 { "MPIO", DPFLTR_MPIO_ID
},
359 { "MSDSM", DPFLTR_MSDSM_ID
},
360 { "UDFS", DPFLTR_UDFS_ID
},
361 { "PSHED", DPFLTR_PSHED_ID
},
362 { "STORVSP", DPFLTR_STORVSP_ID
},
363 { "LSASS", DPFLTR_LSASS_ID
},
364 { "SSPICLI", DPFLTR_SSPICLI_ID
},
365 { "CNG", DPFLTR_CNG_ID
},
366 { "EXFAT", DPFLTR_EXFAT_ID
},
367 { "FILETRACE", DPFLTR_FILETRACE_ID
},
368 { "XSAVE", DPFLTR_XSAVE_ID
},
369 { "SE", DPFLTR_SE_ID
},
370 { "DRIVEEXTENDER", DPFLTR_DRIVEEXTENDER_ID
},
373 for (i
= 0; i
< sizeof(ComponentTable
) / sizeof(ComponentTable
[0]); i
++)
375 if (_stricmp(ComponentName
, ComponentTable
[i
].Name
) == 0)
377 *ComponentId
= ComponentTable
[i
].Id
;
385 /*!\brief Evaluates an expression...
387 * Much like KdbpRpnEvaluateExpression, but prints the error message (if any)
388 * at the given offset.
390 * \param Expression Expression to evaluate.
391 * \param ErrOffset Offset (in characters) to print the error message at.
392 * \param Result Receives the result on success.
394 * \retval TRUE Success.
395 * \retval FALSE Failure.
398 KdbpEvaluateExpression(
401 OUT PULONGLONG Result
)
403 static CHAR ErrMsgBuffer
[130] = "^ ";
404 LONG ExpressionErrOffset
= -1;
405 PCHAR ErrMsg
= ErrMsgBuffer
;
408 Ok
= KdbpRpnEvaluateExpression(Expression
, KdbCurrentTrapFrame
, Result
,
409 &ExpressionErrOffset
, ErrMsgBuffer
+ 2);
412 if (ExpressionErrOffset
>= 0)
413 ExpressionErrOffset
+= ErrOffset
;
417 KdbpPrint("%*s%s\n", ExpressionErrOffset
, "", ErrMsg
);
427 OUT ULONG_PTR
*pulValue
)
431 /* Skip optional '0x' prefix */
432 if ((pszNum
[0] == '0') && ((pszNum
[1] == 'x') || (pszNum
[1] == 'X')))
435 /* Make a number from the string (hex) */
436 *pulValue
= strtoul(pszNum
, &endptr
, 16);
438 return (*endptr
== '\0');
441 /*!\brief Evaluates an expression and displays the result.
444 KdbpCmdEvalExpression(
449 ULONGLONG Result
= 0;
456 KdbpPrint("?: Argument required\n");
460 /* Put the arguments back together */
462 for (i
= 1; i
< Argc
; i
++)
464 len
= strlen(Argv
[i
]);
468 /* Evaluate the expression */
469 Ok
= KdbpEvaluateExpression(Argv
[1], sizeof("kdb:> ")-1 + (Argv
[1]-Argv
[0]), &Result
);
472 if (Result
> 0x00000000ffffffffLL
)
474 if (Result
& 0x8000000000000000LL
)
475 KdbpPrint("0x%016I64x %20I64u %20I64d\n", Result
, Result
, Result
);
477 KdbpPrint("0x%016I64x %20I64u\n", Result
, Result
);
483 if (ul
<= 0xff && ul
>= 0x80)
484 l
= (LONG
)((CHAR
)ul
);
485 else if (ul
<= 0xffff && ul
>= 0x8000)
486 l
= (LONG
)((SHORT
)ul
);
491 KdbpPrint("0x%08lx %10lu %10ld\n", ul
, ul
, l
);
493 KdbpPrint("0x%08lx %10lu\n", ul
, ul
);
502 /*!\brief Print a struct
505 KdbpPrintStructInternal
510 PROSSYM_AGGREGATE Aggregate
)
514 PROSSYM_AGGREGATE_MEMBER Member
;
515 ULONG IndentLen
= strlen(Indent
);
516 ROSSYM_AGGREGATE MemberAggregate
= {0 };
518 for (i
= 0; i
< Aggregate
->NumElements
; i
++) {
519 Member
= &Aggregate
->Elements
[i
];
520 KdbpPrint("%s%p+%x: %s", Indent
, ((PCHAR
)BaseAddress
) + Member
->BaseOffset
, Member
->Size
, Member
->Name
? Member
->Name
: "<anoymous>");
522 if (!strcmp(Member
->Type
, "_UNICODE_STRING")) {
523 KdbpPrint("\"%wZ\"\n", ((PCHAR
)BaseAddress
) + Member
->BaseOffset
);
525 } else if (!strcmp(Member
->Type
, "PUNICODE_STRING")) {
526 KdbpPrint("\"%wZ\"\n", *(((PUNICODE_STRING
*)((PCHAR
)BaseAddress
) + Member
->BaseOffset
)));
529 switch (Member
->Size
) {
535 if (NT_SUCCESS(KdbpSafeReadMemory(&Result
, ((PCHAR
)BaseAddress
) + Member
->BaseOffset
, Member
->Size
))) {
537 Result
>>= Member
->FirstBit
;
538 Result
&= ((1 << Member
->Bits
) - 1);
540 KdbpPrint(" %lx\n", Result
);
546 if (Member
->Size
< 8) {
547 if (NT_SUCCESS(KdbpSafeReadMemory(&Result
, ((PCHAR
)BaseAddress
) + Member
->BaseOffset
, Member
->Size
))) {
549 for (j
= 0; j
< Member
->Size
; j
++) {
550 KdbpPrint(" %02x", (int)(Result
& 0xff));
553 } else goto readfail
;
555 KdbpPrint(" %s @ %p {\n", Member
->Type
, ((PCHAR
)BaseAddress
) + Member
->BaseOffset
);
556 Indent
[IndentLen
] = ' ';
557 if (RosSymAggregate(Info
, Member
->Type
, &MemberAggregate
)) {
558 KdbpPrintStructInternal(Info
, Indent
, DoRead
, ((PCHAR
)BaseAddress
) + Member
->BaseOffset
, &MemberAggregate
);
559 RosSymFreeAggregate(&MemberAggregate
);
561 Indent
[IndentLen
] = 0;
562 KdbpPrint("%s}\n", Indent
);
568 if (Member
->Size
<= 8) {
571 KdbpPrint(" %s @ %x {\n", Member
->Type
, Member
->BaseOffset
);
572 Indent
[IndentLen
] = ' ';
573 if (RosSymAggregate(Info
, Member
->Type
, &MemberAggregate
)) {
574 KdbpPrintStructInternal(Info
, Indent
, DoRead
, BaseAddress
, &MemberAggregate
);
575 RosSymFreeAggregate(&MemberAggregate
);
577 Indent
[IndentLen
] = 0;
578 KdbpPrint("%s}\n", Indent
);
584 PROSSYM_INFO
KdbpSymFindCachedFile(PUNICODE_STRING ModName
);
592 ULONGLONG Result
= 0;
593 PVOID BaseAddress
= 0;
594 ROSSYM_AGGREGATE Aggregate
= {0};
595 UNICODE_STRING ModName
= {0};
596 ANSI_STRING AnsiName
= {0};
597 CHAR Indent
[100] = {0};
600 if (Argc
< 3) goto end
;
601 AnsiName
.Length
= AnsiName
.MaximumLength
= strlen(Argv
[1]);
602 AnsiName
.Buffer
= Argv
[1];
603 RtlAnsiStringToUnicodeString(&ModName
, &AnsiName
, TRUE
);
604 Info
= KdbpSymFindCachedFile(&ModName
);
606 if (!Info
|| !RosSymAggregate(Info
, Argv
[2], &Aggregate
)) {
607 DPRINT1("Could not get aggregate\n");
611 // Get an argument for location if it was given
614 PCHAR ArgStart
= Argv
[3];
615 DPRINT1("Trying to get expression\n");
616 for (i
= 3; i
< Argc
- 1; i
++)
618 len
= strlen(Argv
[i
]);
622 /* Evaluate the expression */
623 DPRINT1("Arg: %s\n", ArgStart
);
624 if (KdbpEvaluateExpression(ArgStart
, strlen(ArgStart
), &Result
)) {
625 BaseAddress
= (PVOID
)(ULONG_PTR
)Result
;
626 DPRINT1("BaseAddress: %p\n", BaseAddress
);
629 DPRINT1("BaseAddress %p\n", BaseAddress
);
630 KdbpPrintStructInternal(Info
, Indent
, !!BaseAddress
, BaseAddress
, &Aggregate
);
632 RosSymFreeAggregate(&Aggregate
);
633 RtlFreeUnicodeString(&ModName
);
638 /*!\brief Display list of active debug channels
645 ULONG i
, j
, ComponentId
, Level
;
646 ULONG set
= DPFLTR_MASK
, clear
= DPFLTR_MASK
;
657 { "error", 1 << DPFLTR_ERROR_LEVEL
},
658 { "warning", 1 << DPFLTR_WARNING_LEVEL
},
659 { "trace", 1 << DPFLTR_TRACE_LEVEL
},
660 { "info", 1 << DPFLTR_INFO_LEVEL
},
663 for (i
= 1; i
< Argc
; i
++)
666 p
= opt
+ strcspn(opt
, "+-");
667 if (!p
[0]) p
= opt
; /* assume it's a debug channel name */
671 for (j
= 0; j
< sizeof(debug_classes
) / sizeof(debug_classes
[0]); j
++)
673 SIZE_T len
= strlen(debug_classes
[j
].Name
);
674 if (len
!= (p
- opt
))
676 if (_strnicmp(opt
, debug_classes
[j
].Name
, len
) == 0) /* found it */
679 set
|= debug_classes
[j
].Level
;
681 clear
|= debug_classes
[j
].Level
;
685 if (j
== sizeof(debug_classes
) / sizeof(debug_classes
[0]))
687 Level
= strtoul(opt
, &pend
, 0);
690 KdbpPrint("filter: bad class name '%.*s'\n", p
- opt
, opt
);
706 if (*p
== '+' || *p
== '-')
709 if (!KdbpGetComponentId(p
, &ComponentId
))
711 KdbpPrint("filter: '%s' is not a valid component name!\n", p
);
715 /* Get current mask value */
716 NtSetDebugFilterState(ComponentId
, set
, TRUE
);
717 NtSetDebugFilterState(ComponentId
, clear
, FALSE
);
723 /*!\brief Disassembles 10 instructions at eip or given address or
724 * displays 16 dwords from memory at given address.
734 ULONGLONG Result
= 0;
735 ULONG_PTR Address
= KdbCurrentTrapFrame
->Tf
.Eip
;
738 if (Argv
[0][0] == 'x') /* display memory */
740 else /* disassemble */
745 /* Check for [L count] part */
747 if (strcmp(Argv
[Argc
-2], "L") == 0)
749 ul
= strtoul(Argv
[Argc
-1], NULL
, 0);
756 else if (Argv
[Argc
-1][0] == 'L')
758 ul
= strtoul(Argv
[Argc
-1] + 1, NULL
, 0);
766 /* Put the remaining arguments back together */
768 for (ul
= 1; ul
< Argc
; ul
++)
770 Argv
[ul
][strlen(Argv
[ul
])] = ' ';
775 /* Evaluate the expression */
778 if (!KdbpEvaluateExpression(Argv
[1], sizeof("kdb:> ")-1 + (Argv
[1]-Argv
[0]), &Result
))
781 if (Result
> (ULONGLONG
)(~((ULONG_PTR
)0)))
782 KdbpPrint("Warning: Address %I64x is beeing truncated\n",Result
);
784 Address
= (ULONG_PTR
)Result
;
786 else if (Argv
[0][0] == 'x')
788 KdbpPrint("x: Address argument required.\n");
792 if (Argv
[0][0] == 'x')
799 if (!KdbSymPrintAddress((PVOID
)Address
, NULL
))
800 KdbpPrint("<%x>:", Address
);
809 if (!NT_SUCCESS(KdbpSafeReadMemory(&ul
, (PVOID
)Address
, sizeof(ul
))))
810 KdbpPrint(" ????????");
812 KdbpPrint(" %08x", ul
);
814 Address
+= sizeof(ul
);
825 if (!KdbSymPrintAddress((PVOID
)Address
, NULL
))
826 KdbpPrint("<%08x>: ", Address
);
830 InstLen
= KdbpDisassemble(Address
, KdbUseIntelSyntax
);
833 KdbpPrint("<INVALID>\n");
845 /*!\brief Displays CPU registers.
852 PKTRAP_FRAME Tf
= &KdbCurrentTrapFrame
->Tf
;
854 static const PCHAR EflagsBits
[32] = { " CF", NULL
, " PF", " BIT3", " AF", " BIT5",
855 " ZF", " SF", " TF", " IF", " DF", " OF",
856 NULL
, NULL
, " NT", " BIT15", " RF", " VF",
857 " AC", " VIF", " VIP", " ID", " BIT22",
858 " BIT23", " BIT24", " BIT25", " BIT26",
859 " BIT27", " BIT28", " BIT29", " BIT30",
862 if (Argv
[0][0] == 'r') /* regs */
864 KdbpPrint("CS:EIP 0x%04x:0x%08x\n"
865 "SS:ESP 0x%04x:0x%08x\n"
866 " EAX 0x%08x EBX 0x%08x\n"
867 " ECX 0x%08x EDX 0x%08x\n"
868 " ESI 0x%08x EDI 0x%08x\n"
870 Tf
->SegCs
& 0xFFFF, Tf
->Eip
,
871 Tf
->HardwareSegSs
, Tf
->HardwareEsp
,
876 KdbpPrint("EFLAGS 0x%08x ", Tf
->EFlags
);
878 for (i
= 0; i
< 32; i
++)
882 if ((Tf
->EFlags
& (1 << 1)) == 0)
887 KdbpPrint(" IOPL%d", (Tf
->EFlags
>> 12) & 3);
892 else if ((Tf
->EFlags
& (1 << i
)) != 0)
894 KdbpPrint(EflagsBits
[i
]);
900 else if (Argv
[0][0] == 'c') /* cregs */
902 ULONG Cr0
, Cr2
, Cr3
, Cr4
;
903 KDESCRIPTOR Gdtr
= {0, 0, 0}, Idtr
= {0, 0, 0};
905 static const PCHAR Cr0Bits
[32] = { " PE", " MP", " EM", " TS", " ET", " NE", NULL
, NULL
,
906 NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
,
907 " WP", NULL
, " AM", NULL
, NULL
, NULL
, NULL
, NULL
,
908 NULL
, NULL
, NULL
, NULL
, NULL
, " NW", " CD", " PG" };
909 static const PCHAR Cr4Bits
[32] = { " VME", " PVI", " TSD", " DE", " PSE", " PAE", " MCE", " PGE",
910 " PCE", " OSFXSR", " OSXMMEXCPT", NULL
, NULL
, NULL
, NULL
, NULL
,
911 NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
,
912 NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
};
914 Cr0
= KdbCurrentTrapFrame
->Cr0
;
915 Cr2
= KdbCurrentTrapFrame
->Cr2
;
916 Cr3
= KdbCurrentTrapFrame
->Cr3
;
917 Cr4
= KdbCurrentTrapFrame
->Cr4
;
919 /* Get descriptor table regs */
920 Ke386GetGlobalDescriptorTable(&Gdtr
.Limit
);
921 Ldtr
= Ke386GetLocalDescriptorTable();
924 /* Display the control registers */
925 KdbpPrint("CR0 0x%08x ", Cr0
);
927 for (i
= 0; i
< 32; i
++)
932 if ((Cr0
& (1 << i
)) != 0)
933 KdbpPrint(Cr0Bits
[i
]);
936 KdbpPrint("\nCR2 0x%08x\n", Cr2
);
937 KdbpPrint("CR3 0x%08x Pagedir-Base 0x%08x %s%s\n", Cr3
, (Cr3
& 0xfffff000),
938 (Cr3
& (1 << 3)) ? " PWT" : "", (Cr3
& (1 << 4)) ? " PCD" : "" );
939 KdbpPrint("CR4 0x%08x ", Cr4
);
941 for (i
= 0; i
< 32; i
++)
946 if ((Cr4
& (1 << i
)) != 0)
947 KdbpPrint(Cr4Bits
[i
]);
950 /* Display the descriptor table regs */
951 KdbpPrint("\nGDTR Base 0x%08x Size 0x%04x\n", Gdtr
.Base
, Gdtr
.Limit
);
952 KdbpPrint("LDTR 0x%04x\n", Ldtr
);
953 KdbpPrint("IDTR Base 0x%08x Size 0x%04x\n", Idtr
.Base
, Idtr
.Limit
);
955 else if (Argv
[0][0] == 's') /* sregs */
957 KdbpPrint("CS 0x%04x Index 0x%04x %cDT RPL%d\n",
958 Tf
->SegCs
& 0xffff, (Tf
->SegCs
& 0xffff) >> 3,
959 (Tf
->SegCs
& (1 << 2)) ? 'L' : 'G', Tf
->SegCs
& 3);
960 KdbpPrint("DS 0x%04x Index 0x%04x %cDT RPL%d\n",
961 Tf
->SegDs
, Tf
->SegDs
>> 3, (Tf
->SegDs
& (1 << 2)) ? 'L' : 'G', Tf
->SegDs
& 3);
962 KdbpPrint("ES 0x%04x Index 0x%04x %cDT RPL%d\n",
963 Tf
->SegEs
, Tf
->SegEs
>> 3, (Tf
->SegEs
& (1 << 2)) ? 'L' : 'G', Tf
->SegEs
& 3);
964 KdbpPrint("FS 0x%04x Index 0x%04x %cDT RPL%d\n",
965 Tf
->SegFs
, Tf
->SegFs
>> 3, (Tf
->SegFs
& (1 << 2)) ? 'L' : 'G', Tf
->SegFs
& 3);
966 KdbpPrint("GS 0x%04x Index 0x%04x %cDT RPL%d\n",
967 Tf
->SegGs
, Tf
->SegGs
>> 3, (Tf
->SegGs
& (1 << 2)) ? 'L' : 'G', Tf
->SegGs
& 3);
968 KdbpPrint("SS 0x%04x Index 0x%04x %cDT RPL%d\n",
969 Tf
->HardwareSegSs
, Tf
->HardwareSegSs
>> 3, (Tf
->HardwareSegSs
& (1 << 2)) ? 'L' : 'G', Tf
->HardwareSegSs
& 3);
973 ASSERT(Argv
[0][0] == 'd');
974 KdbpPrint("DR0 0x%08x\n"
980 Tf
->Dr0
, Tf
->Dr1
, Tf
->Dr2
, Tf
->Dr3
,
988 KdbpTrapFrameFromPrevTss(
989 PKTRAP_FRAME TrapFrame
)
997 Ke386GetGlobalDescriptorTable(&Gdtr
.Limit
);
1000 if ((Sel
& (sizeof(KGDTENTRY
) - 1)) ||
1001 (Sel
< sizeof(KGDTENTRY
)) ||
1002 (Sel
+ sizeof(KGDTENTRY
) - 1 > Gdtr
.Limit
))
1005 if (!NT_SUCCESS(KdbpSafeReadMemory(&Desc
,
1006 (PVOID
)(Gdtr
.Base
+ Sel
),
1007 sizeof(KGDTENTRY
))))
1010 if (Desc
.HighWord
.Bits
.Type
!= 0xB)
1013 Tss
= (PKTSS
)(ULONG_PTR
)(Desc
.BaseLow
|
1014 Desc
.HighWord
.Bytes
.BaseMid
<< 16 |
1015 Desc
.HighWord
.Bytes
.BaseHi
<< 24);
1017 if (!NT_SUCCESS(KdbpSafeReadMemory(&Sel
,
1018 (PVOID
)&Tss
->Backlink
,
1022 if ((Sel
& (sizeof(KGDTENTRY
) - 1)) ||
1023 (Sel
< sizeof(KGDTENTRY
)) ||
1024 (Sel
+ sizeof(KGDTENTRY
) - 1 > Gdtr
.Limit
))
1027 if (!NT_SUCCESS(KdbpSafeReadMemory(&Desc
,
1028 (PVOID
)(Gdtr
.Base
+ Sel
),
1029 sizeof(KGDTENTRY
))))
1032 if (Desc
.HighWord
.Bits
.Type
!= 0xB)
1035 Tss
= (PKTSS
)(ULONG_PTR
)(Desc
.BaseLow
|
1036 Desc
.HighWord
.Bytes
.BaseMid
<< 16 |
1037 Desc
.HighWord
.Bytes
.BaseHi
<< 24);
1039 if (!NT_SUCCESS(KdbpSafeReadMemory(&Eip
,
1041 sizeof(ULONG_PTR
))))
1044 if (!NT_SUCCESS(KdbpSafeReadMemory(&Ebp
,
1046 sizeof(ULONG_PTR
))))
1049 TrapFrame
->Eip
= Eip
;
1050 TrapFrame
->Ebp
= Ebp
;
1054 VOID __cdecl
KiTrap02(VOID
);
1055 VOID FASTCALL
KiTrap03Handler(IN PKTRAP_FRAME
);
1056 VOID __cdecl
KiTrap08(VOID
);
1057 VOID __cdecl
KiTrap09(VOID
);
1060 KdbpInNmiOrDoubleFaultHandler(
1063 return (Address
> (ULONG_PTR
)KiTrap02
&& Address
< (ULONG_PTR
)KiTrap03Handler
) ||
1064 (Address
> (ULONG_PTR
)KiTrap08
&& Address
< (ULONG_PTR
)KiTrap09
);
1067 /*!\brief Displays a backtrace.
1075 ULONGLONG Result
= 0;
1076 ULONG_PTR Frame
= KdbCurrentTrapFrame
->Tf
.Ebp
;
1078 KTRAP_FRAME TrapFrame
;
1082 /* Check for [L count] part */
1085 if (strcmp(Argv
[Argc
-2], "L") == 0)
1087 ul
= strtoul(Argv
[Argc
-1], NULL
, 0);
1093 else if (Argv
[Argc
-1][0] == 'L')
1095 ul
= strtoul(Argv
[Argc
-1] + 1, NULL
, 0);
1102 /* Put the remaining arguments back together */
1104 for (ul
= 1; ul
< Argc
; ul
++)
1106 Argv
[ul
][strlen(Argv
[ul
])] = ' ';
1111 /* Check if frame addr or thread id is given. */
1114 if (Argv
[1][0] == '*')
1118 /* Evaluate the expression */
1119 if (!KdbpEvaluateExpression(Argv
[1], sizeof("kdb:> ")-1 + (Argv
[1]-Argv
[0]), &Result
))
1122 if (Result
> (ULONGLONG
)(~((ULONG_PTR
)0)))
1123 KdbpPrint("Warning: Address %I64x is beeing truncated\n",Result
);
1125 Frame
= (ULONG_PTR
)Result
;
1129 KdbpPrint("Thread backtrace not supported yet!\n");
1135 KdbpPrint("Eip:\n");
1137 /* Try printing the function at EIP */
1138 if (!KdbSymPrintAddress((PVOID
)KdbCurrentTrapFrame
->Tf
.Eip
, &KdbCurrentTrapFrame
->Tf
))
1139 KdbpPrint("<%08x>\n", KdbCurrentTrapFrame
->Tf
.Eip
);
1144 TrapFrame
= KdbCurrentTrapFrame
->Tf
;
1145 KdbpPrint("Frames:\n");
1149 BOOLEAN GotNextFrame
;
1154 if (!NT_SUCCESS(KdbpSafeReadMemory(&Address
, (PVOID
)(Frame
+ sizeof(ULONG_PTR
)), sizeof (ULONG_PTR
))))
1156 KdbpPrint("Couldn't access memory at 0x%p!\n", Frame
+ sizeof(ULONG_PTR
));
1160 if ((GotNextFrame
= NT_SUCCESS(KdbpSafeReadMemory(&Frame
, (PVOID
)Frame
, sizeof (ULONG_PTR
)))))
1161 TrapFrame
.Ebp
= Frame
;
1163 /* Print the location of the call instruction */
1164 if (!KdbSymPrintAddress((PVOID
)(Address
- 5), &TrapFrame
))
1165 KdbpPrint("<%08x>\n", Address
);
1169 if (KdbOutputAborted
) break;
1174 if (KdbpInNmiOrDoubleFaultHandler(Address
))
1176 if ((GotNextFrame
= KdbpTrapFrameFromPrevTss(&TrapFrame
)))
1178 Address
= TrapFrame
.Eip
;
1179 Frame
= TrapFrame
.Ebp
;
1181 if (!KdbSymPrintAddress((PVOID
)Address
, &TrapFrame
))
1182 KdbpPrint("<%08x>\n", Address
);
1190 KdbpPrint("Couldn't access memory at 0x%p!\n", Frame
);
1198 /*!\brief Continues execution of the system/leaves KDB.
1205 /* Exit the main loop */
1209 /*!\brief Continues execution of the system/leaves KDB.
1220 Count
= strtoul(Argv
[1], NULL
, 0);
1223 KdbpPrint("%s: Integer argument required\n", Argv
[0]);
1228 if (Argv
[0][0] == 'n')
1229 KdbSingleStepOver
= TRUE
;
1231 KdbSingleStepOver
= FALSE
;
1233 /* Set the number of single steps and return to the interrupted code. */
1234 KdbNumSingleSteps
= Count
;
1239 /*!\brief Lists breakpoints.
1242 KdbpCmdBreakPointList(
1247 ULONG_PTR Address
= 0;
1248 KDB_BREAKPOINT_TYPE Type
= 0;
1249 KDB_ACCESS_TYPE AccessType
= 0;
1252 BOOLEAN Enabled
= FALSE
;
1253 BOOLEAN Global
= FALSE
;
1254 PEPROCESS Process
= NULL
;
1255 PCHAR str1
, str2
, ConditionExpr
, GlobalOrLocal
;
1258 l
= KdbpGetNextBreakPointNr(0);
1261 KdbpPrint("No breakpoints.\n");
1265 KdbpPrint("Breakpoints:\n");
1268 if (!KdbpGetBreakPointInfo(l
, &Address
, &Type
, &Size
, &AccessType
, &DebugReg
,
1269 &Enabled
, &Global
, &Process
, &ConditionExpr
))
1274 if (l
== KdbLastBreakPointNr
)
1287 GlobalOrLocal
= " global";
1291 GlobalOrLocal
= Buffer
;
1292 sprintf(Buffer
, " PID 0x%08lx",
1293 (ULONG
)(Process
? Process
->UniqueProcessId
: INVALID_HANDLE_VALUE
));
1296 if (Type
== KdbBreakPointSoftware
|| Type
== KdbBreakPointTemporary
)
1298 KdbpPrint(" %s%03d BPX 0x%08x%s%s%s%s%s\n",
1300 Enabled
? "" : " disabled",
1302 ConditionExpr
? " IF " : "",
1303 ConditionExpr
? ConditionExpr
: "",
1306 else if (Type
== KdbBreakPointHardware
)
1310 KdbpPrint(" %s%03d BPM 0x%08x %-5s %-5s disabled%s%s%s%s\n", str1
, l
, Address
,
1311 KDB_ACCESS_TYPE_TO_STRING(AccessType
),
1312 Size
== 1 ? "byte" : (Size
== 2 ? "word" : "dword"),
1314 ConditionExpr
? " IF " : "",
1315 ConditionExpr
? ConditionExpr
: "",
1320 KdbpPrint(" %s%03d BPM 0x%08x %-5s %-5s DR%d%s%s%s%s\n", str1
, l
, Address
,
1321 KDB_ACCESS_TYPE_TO_STRING(AccessType
),
1322 Size
== 1 ? "byte" : (Size
== 2 ? "word" : "dword"),
1325 ConditionExpr
? " IF " : "",
1326 ConditionExpr
? ConditionExpr
: "",
1331 while ((l
= KdbpGetNextBreakPointNr(l
+1)) >= 0);
1336 /*!\brief Enables, disables or clears a breakpoint.
1339 KdbpCmdEnableDisableClearBreakPoint(
1348 KdbpPrint("%s: argument required\n", Argv
[0]);
1353 BreakPointNr
= strtoul(Argv
[1], &pend
, 0);
1354 if (pend
== Argv
[1] || *pend
!= '\0')
1356 KdbpPrint("%s: integer argument required\n", Argv
[0]);
1360 if (Argv
[0][1] == 'e') /* enable */
1362 KdbpEnableBreakPoint(BreakPointNr
, NULL
);
1364 else if (Argv
[0][1] == 'd') /* disable */
1366 KdbpDisableBreakPoint(BreakPointNr
, NULL
);
1370 ASSERT(Argv
[0][1] == 'c');
1371 KdbpDeleteBreakPoint(BreakPointNr
, NULL
);
1377 /*!\brief Sets a software or hardware (memory) breakpoint at the given address.
1380 KdbpCmdBreakPoint(ULONG Argc
, PCHAR Argv
[])
1382 ULONGLONG Result
= 0;
1384 KDB_BREAKPOINT_TYPE Type
;
1386 KDB_ACCESS_TYPE AccessType
= 0;
1387 ULONG AddressArgIndex
, i
;
1388 LONG ConditionArgIndex
;
1389 BOOLEAN Global
= TRUE
;
1391 if (Argv
[0][2] == 'x') /* software breakpoint */
1395 KdbpPrint("bpx: Address argument required.\n");
1399 AddressArgIndex
= 1;
1400 Type
= KdbBreakPointSoftware
;
1402 else /* memory breakpoint */
1404 ASSERT(Argv
[0][2] == 'm');
1408 KdbpPrint("bpm: Access type argument required (one of r, w, rw, x)\n");
1412 if (_stricmp(Argv
[1], "x") == 0)
1413 AccessType
= KdbAccessExec
;
1414 else if (_stricmp(Argv
[1], "r") == 0)
1415 AccessType
= KdbAccessRead
;
1416 else if (_stricmp(Argv
[1], "w") == 0)
1417 AccessType
= KdbAccessWrite
;
1418 else if (_stricmp(Argv
[1], "rw") == 0)
1419 AccessType
= KdbAccessReadWrite
;
1422 KdbpPrint("bpm: Unknown access type '%s'\n", Argv
[1]);
1428 KdbpPrint("bpm: %s argument required.\n", AccessType
== KdbAccessExec
? "Address" : "Memory size");
1432 AddressArgIndex
= 3;
1433 if (_stricmp(Argv
[2], "byte") == 0)
1435 else if (_stricmp(Argv
[2], "word") == 0)
1437 else if (_stricmp(Argv
[2], "dword") == 0)
1439 else if (AccessType
== KdbAccessExec
)
1446 KdbpPrint("bpm: Unknown memory size '%s'\n", Argv
[2]);
1450 if (Argc
<= AddressArgIndex
)
1452 KdbpPrint("bpm: Address argument required.\n");
1456 Type
= KdbBreakPointHardware
;
1459 /* Put the arguments back together */
1460 ConditionArgIndex
= -1;
1461 for (i
= AddressArgIndex
; i
< (Argc
-1); i
++)
1463 if (strcmp(Argv
[i
+1], "IF") == 0) /* IF found */
1465 ConditionArgIndex
= i
+ 2;
1466 if ((ULONG
)ConditionArgIndex
>= Argc
)
1468 KdbpPrint("%s: IF requires condition expression.\n", Argv
[0]);
1472 for (i
= ConditionArgIndex
; i
< (Argc
-1); i
++)
1473 Argv
[i
][strlen(Argv
[i
])] = ' ';
1478 Argv
[i
][strlen(Argv
[i
])] = ' ';
1481 /* Evaluate the address expression */
1482 if (!KdbpEvaluateExpression(Argv
[AddressArgIndex
],
1483 sizeof("kdb:> ")-1 + (Argv
[AddressArgIndex
]-Argv
[0]),
1489 if (Result
> (ULONGLONG
)(~((ULONG_PTR
)0)))
1490 KdbpPrint("%s: Warning: Address %I64x is beeing truncated\n", Argv
[0],Result
);
1492 Address
= (ULONG_PTR
)Result
;
1494 KdbpInsertBreakPoint(Address
, Type
, Size
, AccessType
,
1495 (ConditionArgIndex
< 0) ? NULL
: Argv
[ConditionArgIndex
],
1501 /*!\brief Lists threads or switches to another thread context.
1509 PETHREAD Thread
= NULL
;
1510 PEPROCESS Process
= NULL
;
1511 BOOLEAN ReferencedThread
= FALSE
, ReferencedProcess
= FALSE
;
1516 PCHAR State
, pend
, str1
, str2
;
1517 static const PCHAR ThreadStateToString
[DeferredReady
+1] =
1519 "Initialized", "Ready", "Running",
1520 "Standby", "Terminated", "Waiting",
1521 "Transition", "DeferredReady"
1524 ASSERT(KdbCurrentProcess
);
1526 if (Argc
>= 2 && _stricmp(Argv
[1], "list") == 0)
1528 Process
= KdbCurrentProcess
;
1532 ul
= strtoul(Argv
[2], &pend
, 0);
1533 if (Argv
[2] == pend
)
1535 KdbpPrint("thread: '%s' is not a valid process id!\n", Argv
[2]);
1539 if (!NT_SUCCESS(PsLookupProcessByProcessId((PVOID
)ul
, &Process
)))
1541 KdbpPrint("thread: Invalid process id!\n");
1545 /* Remember our reference */
1546 ReferencedProcess
= TRUE
;
1549 Entry
= Process
->ThreadListHead
.Flink
;
1550 if (Entry
== &Process
->ThreadListHead
)
1553 KdbpPrint("No threads in process 0x%08x!\n", ul
);
1555 KdbpPrint("No threads in current process!\n");
1557 if (ReferencedProcess
)
1558 ObDereferenceObject(Process
);
1563 KdbpPrint(" TID State Prior. Affinity EBP EIP\n");
1566 Thread
= CONTAINING_RECORD(Entry
, ETHREAD
, ThreadListEntry
);
1568 if (Thread
== KdbCurrentThread
)
1579 if (!Thread
->Tcb
.InitialStack
)
1581 /* Thread has no kernel stack (probably terminated) */
1585 else if (Thread
->Tcb
.TrapFrame
)
1587 if (Thread
->Tcb
.TrapFrame
->PreviousPreviousMode
== KernelMode
)
1588 Esp
= (PULONG
)Thread
->Tcb
.TrapFrame
->TempEsp
;
1590 Esp
= (PULONG
)Thread
->Tcb
.TrapFrame
->HardwareEsp
;
1592 Ebp
= (PULONG
)Thread
->Tcb
.TrapFrame
->Ebp
;
1593 Eip
= Thread
->Tcb
.TrapFrame
->Eip
;
1597 Esp
= (PULONG
)Thread
->Tcb
.KernelStack
;
1598 Ebp
= (PULONG
)Esp
[4];
1601 if (Ebp
) /* FIXME: Should we attach to the process to read Ebp[1]? */
1602 KdbpSafeReadMemory(&Eip
, Ebp
+ 1, sizeof (Eip
));
1605 if (Thread
->Tcb
.State
< (DeferredReady
+ 1))
1606 State
= ThreadStateToString
[Thread
->Tcb
.State
];
1610 KdbpPrint(" %s0x%08x %-11s %3d 0x%08x 0x%08x 0x%08x%s\n",
1612 Thread
->Cid
.UniqueThread
,
1614 Thread
->Tcb
.Priority
,
1615 Thread
->Tcb
.Affinity
,
1620 Entry
= Entry
->Flink
;
1622 while (Entry
!= &Process
->ThreadListHead
);
1624 /* Release our reference, if any */
1625 if (ReferencedProcess
)
1626 ObDereferenceObject(Process
);
1628 else if (Argc
>= 2 && _stricmp(Argv
[1], "attach") == 0)
1632 KdbpPrint("thread attach: thread id argument required!\n");
1636 ul
= strtoul(Argv
[2], &pend
, 0);
1637 if (Argv
[2] == pend
)
1639 KdbpPrint("thread attach: '%s' is not a valid thread id!\n", Argv
[2]);
1643 if (!KdbpAttachToThread((PVOID
)ul
))
1648 KdbpPrint("Attached to thread 0x%08x.\n", ul
);
1652 Thread
= KdbCurrentThread
;
1656 ul
= strtoul(Argv
[1], &pend
, 0);
1657 if (Argv
[1] == pend
)
1659 KdbpPrint("thread: '%s' is not a valid thread id!\n", Argv
[1]);
1663 if (!NT_SUCCESS(PsLookupThreadByThreadId((PVOID
)ul
, &Thread
)))
1665 KdbpPrint("thread: Invalid thread id!\n");
1669 /* Remember our reference */
1670 ReferencedThread
= TRUE
;
1673 if (Thread
->Tcb
.State
< (DeferredReady
+ 1))
1674 State
= ThreadStateToString
[Thread
->Tcb
.State
];
1680 " State: %s (0x%x)\n"
1682 " Affinity: 0x%08x\n"
1683 " Initial Stack: 0x%08x\n"
1684 " Stack Limit: 0x%08x\n"
1685 " Stack Base: 0x%08x\n"
1686 " Kernel Stack: 0x%08x\n"
1687 " Trap Frame: 0x%08x\n"
1688 " NPX State: %s (0x%x)\n",
1689 (Argc
< 2) ? "Current Thread:\n" : "",
1690 Thread
->Cid
.UniqueThread
,
1691 State
, Thread
->Tcb
.State
,
1692 Thread
->Tcb
.Priority
,
1693 Thread
->Tcb
.Affinity
,
1694 Thread
->Tcb
.InitialStack
,
1695 Thread
->Tcb
.StackLimit
,
1696 Thread
->Tcb
.StackBase
,
1697 Thread
->Tcb
.KernelStack
,
1698 Thread
->Tcb
.TrapFrame
,
1699 NPX_STATE_TO_STRING(Thread
->Tcb
.NpxState
), Thread
->Tcb
.NpxState
);
1701 /* Release our reference if we had one */
1702 if (ReferencedThread
)
1703 ObDereferenceObject(Thread
);
1709 /*!\brief Lists processes or switches to another process context.
1718 BOOLEAN ReferencedProcess
= FALSE
;
1719 PCHAR State
, pend
, str1
, str2
;
1721 extern LIST_ENTRY PsActiveProcessHead
;
1723 if (Argc
>= 2 && _stricmp(Argv
[1], "list") == 0)
1725 Entry
= PsActiveProcessHead
.Flink
;
1726 if (!Entry
|| Entry
== &PsActiveProcessHead
)
1728 KdbpPrint("No processes in the system!\n");
1732 KdbpPrint(" PID State Filename\n");
1735 Process
= CONTAINING_RECORD(Entry
, EPROCESS
, ActiveProcessLinks
);
1737 if (Process
== KdbCurrentProcess
)
1748 State
= ((Process
->Pcb
.State
== ProcessInMemory
) ? "In Memory" :
1749 ((Process
->Pcb
.State
== ProcessOutOfMemory
) ? "Out of Memory" : "In Transition"));
1751 KdbpPrint(" %s0x%08x %-10s %s%s\n",
1753 Process
->UniqueProcessId
,
1755 Process
->ImageFileName
,
1758 Entry
= Entry
->Flink
;
1760 while(Entry
!= &PsActiveProcessHead
);
1762 else if (Argc
>= 2 && _stricmp(Argv
[1], "attach") == 0)
1766 KdbpPrint("process attach: process id argument required!\n");
1770 ul
= strtoul(Argv
[2], &pend
, 0);
1771 if (Argv
[2] == pend
)
1773 KdbpPrint("process attach: '%s' is not a valid process id!\n", Argv
[2]);
1777 if (!KdbpAttachToProcess((PVOID
)ul
))
1782 KdbpPrint("Attached to process 0x%08x, thread 0x%08x.\n", (ULONG
)ul
,
1783 (ULONG
)KdbCurrentThread
->Cid
.UniqueThread
);
1787 Process
= KdbCurrentProcess
;
1791 ul
= strtoul(Argv
[1], &pend
, 0);
1792 if (Argv
[1] == pend
)
1794 KdbpPrint("proc: '%s' is not a valid process id!\n", Argv
[1]);
1798 if (!NT_SUCCESS(PsLookupProcessByProcessId((PVOID
)ul
, &Process
)))
1800 KdbpPrint("proc: Invalid process id!\n");
1804 /* Remember our reference */
1805 ReferencedProcess
= TRUE
;
1808 State
= ((Process
->Pcb
.State
== ProcessInMemory
) ? "In Memory" :
1809 ((Process
->Pcb
.State
== ProcessOutOfMemory
) ? "Out of Memory" : "In Transition"));
1812 " State: %s (0x%x)\n"
1813 " Image Filename: %s\n",
1814 (Argc
< 2) ? "Current process:\n" : "",
1815 Process
->UniqueProcessId
,
1816 State
, Process
->Pcb
.State
,
1817 Process
->ImageFileName
);
1819 /* Release our reference, if any */
1820 if (ReferencedProcess
)
1821 ObDereferenceObject(Process
);
1827 /*!\brief Lists loaded modules or the one containing the specified address.
1834 ULONGLONG Result
= 0;
1836 PLDR_DATA_TABLE_ENTRY LdrEntry
;
1837 BOOLEAN DisplayOnlyOneModule
= FALSE
;
1842 /* Put the arguments back together */
1845 Argv
[Argc
][strlen(Argv
[Argc
])] = ' ';
1847 /* Evaluate the expression */
1848 if (!KdbpEvaluateExpression(Argv
[1], sizeof("kdb:> ")-1 + (Argv
[1]-Argv
[0]), &Result
))
1853 if (Result
> (ULONGLONG
)(~((ULONG_PTR
)0)))
1854 KdbpPrint("%s: Warning: Address %I64x is beeing truncated\n", Argv
[0],Result
);
1856 Address
= (ULONG_PTR
)Result
;
1858 if (!KdbpSymFindModule((PVOID
)Address
, NULL
, -1, &LdrEntry
))
1860 KdbpPrint("No module containing address 0x%p found!\n", Address
);
1864 DisplayOnlyOneModule
= TRUE
;
1868 if (!KdbpSymFindModule(NULL
, NULL
, 0, &LdrEntry
))
1870 ULONG_PTR ntoskrnlBase
= ((ULONG_PTR
)KdbpCmdMod
) & 0xfff00000;
1871 KdbpPrint(" Base Size Name\n");
1872 KdbpPrint(" %08x %08x %s\n", ntoskrnlBase
, 0, "ntoskrnl.exe");
1879 KdbpPrint(" Base Size Name\n");
1882 KdbpPrint(" %08x %08x %wZ\n", LdrEntry
->DllBase
, LdrEntry
->SizeOfImage
, &LdrEntry
->BaseDllName
);
1884 if(DisplayOnlyOneModule
|| !KdbpSymFindModule(NULL
, NULL
, i
++, &LdrEntry
))
1891 /*!\brief Displays GDT, LDT or IDTd.
1908 if (Argv
[0][0] == 'i')
1915 KdbpPrint("Interrupt descriptor table is empty.\n");
1919 KdbpPrint("IDT Base: 0x%08x Limit: 0x%04x\n", Reg
.Base
, Reg
.Limit
);
1920 KdbpPrint(" Idx Type Seg. Sel. Offset DPL\n");
1922 for (i
= 0; (i
+ sizeof(SegDesc
) - 1) <= Reg
.Limit
; i
+= 8)
1924 if (!NT_SUCCESS(KdbpSafeReadMemory(SegDesc
, (PVOID
)(Reg
.Base
+ i
), sizeof(SegDesc
))))
1926 KdbpPrint("Couldn't access memory at 0x%08x!\n", Reg
.Base
+ i
);
1930 Dpl
= ((SegDesc
[1] >> 13) & 3);
1931 if ((SegDesc
[1] & 0x1f00) == 0x0500) /* Task gate */
1932 SegType
= "TASKGATE";
1933 else if ((SegDesc
[1] & 0x1fe0) == 0x0e00) /* 32 bit Interrupt gate */
1934 SegType
= "INTGATE32";
1935 else if ((SegDesc
[1] & 0x1fe0) == 0x0600) /* 16 bit Interrupt gate */
1936 SegType
= "INTGATE16";
1937 else if ((SegDesc
[1] & 0x1fe0) == 0x0f00) /* 32 bit Trap gate */
1938 SegType
= "TRAPGATE32";
1939 else if ((SegDesc
[1] & 0x1fe0) == 0x0700) /* 16 bit Trap gate */
1940 SegType
= "TRAPGATE16";
1942 SegType
= "UNKNOWN";
1944 if ((SegDesc
[1] & (1 << 15)) == 0) /* not present */
1946 KdbpPrint(" %03d %-10s [NP] [NP] %02d\n",
1947 i
/ 8, SegType
, Dpl
);
1949 else if ((SegDesc
[1] & 0x1f00) == 0x0500) /* Task gate */
1951 SegSel
= SegDesc
[0] >> 16;
1952 KdbpPrint(" %03d %-10s 0x%04x %02d\n",
1953 i
/ 8, SegType
, SegSel
, Dpl
);
1957 SegSel
= SegDesc
[0] >> 16;
1958 SegBase
= (SegDesc
[1] & 0xffff0000) | (SegDesc
[0] & 0x0000ffff);
1959 KdbpPrint(" %03d %-10s 0x%04x 0x%08x %02d\n",
1960 i
/ 8, SegType
, SegSel
, SegBase
, Dpl
);
1968 if (Argv
[0][0] == 'g')
1971 Ke386GetGlobalDescriptorTable(&Reg
.Limit
);
1976 ASSERT(Argv
[0][0] == 'l');
1979 Reg
.Limit
= Ke386GetLocalDescriptorTable();
1987 KdbpPrint("%s descriptor table is empty.\n",
1988 Argv
[0][0] == 'g' ? "Global" : "Local");
1992 KdbpPrint("%cDT Base: 0x%08x Limit: 0x%04x\n",
1993 Argv
[0][0] == 'g' ? 'G' : 'L', Reg
.Base
, Reg
.Limit
);
1994 KdbpPrint(" Idx Sel. Type Base Limit DPL Attribs\n");
1996 for (; (i
+ sizeof(SegDesc
) - 1) <= Reg
.Limit
; i
+= 8)
1998 if (!NT_SUCCESS(KdbpSafeReadMemory(SegDesc
, (PVOID
)(Reg
.Base
+ i
), sizeof(SegDesc
))))
2000 KdbpPrint("Couldn't access memory at 0x%08x!\n", Reg
.Base
+ i
);
2004 Dpl
= ((SegDesc
[1] >> 13) & 3);
2005 Type
= ((SegDesc
[1] >> 8) & 0xf);
2007 SegBase
= SegDesc
[0] >> 16;
2008 SegBase
|= (SegDesc
[1] & 0xff) << 16;
2009 SegBase
|= SegDesc
[1] & 0xff000000;
2010 SegLimit
= SegDesc
[0] & 0x0000ffff;
2011 SegLimit
|= (SegDesc
[1] >> 16) & 0xf;
2013 if ((SegDesc
[1] & (1 << 23)) != 0)
2023 if ((SegDesc
[1] & (1 << 12)) == 0) /* System segment */
2027 case 1: SegType
= "TSS16(Avl)"; break;
2028 case 2: SegType
= "LDT"; break;
2029 case 3: SegType
= "TSS16(Busy)"; break;
2030 case 4: SegType
= "CALLGATE16"; break;
2031 case 5: SegType
= "TASKGATE"; break;
2032 case 6: SegType
= "INTGATE16"; break;
2033 case 7: SegType
= "TRAPGATE16"; break;
2034 case 9: SegType
= "TSS32(Avl)"; break;
2035 case 11: SegType
= "TSS32(Busy)"; break;
2036 case 12: SegType
= "CALLGATE32"; break;
2037 case 14: SegType
= "INTGATE32"; break;
2038 case 15: SegType
= "INTGATE32"; break;
2039 default: SegType
= "UNKNOWN"; break;
2042 if (!(Type
>= 1 && Type
<= 3) &&
2043 Type
!= 9 && Type
!= 11)
2049 else if ((SegDesc
[1] & (1 << 11)) == 0) /* Data segment */
2051 if ((SegDesc
[1] & (1 << 22)) != 0)
2056 else /* Code segment */
2058 if ((SegDesc
[1] & (1 << 22)) != 0)
2064 if ((SegDesc
[1] & (1 << 15)) == 0) /* not present */
2066 KdbpPrint(" %03d 0x%04x %-11s [NP] [NP] %02d NP\n",
2067 i
/ 8, i
| Dpl
| ul
, SegType
, Dpl
);
2071 KdbpPrint(" %03d 0x%04x %-11s 0x%08x 0x%08x %02d ",
2072 i
/ 8, i
| Dpl
| ul
, SegType
, SegBase
, SegLimit
, Dpl
);
2074 if ((SegDesc
[1] & (1 << 12)) == 0) /* System segment */
2076 /* FIXME: Display system segment */
2078 else if ((SegDesc
[1] & (1 << 11)) == 0) /* Data segment */
2080 if ((SegDesc
[1] & (1 << 10)) != 0) /* Expand-down */
2083 KdbpPrint((SegDesc
[1] & (1 << 9)) ? " R/W" : " R");
2085 if ((SegDesc
[1] & (1 << 8)) != 0)
2088 else /* Code segment */
2090 if ((SegDesc
[1] & (1 << 10)) != 0) /* Conforming */
2093 KdbpPrint((SegDesc
[1] & (1 << 9)) ? " R/X" : " X");
2095 if ((SegDesc
[1] & (1 << 8)) != 0)
2099 if ((SegDesc
[1] & (1 << 20)) != 0)
2110 /*!\brief Displays the KPCR
2117 PKIPCR Pcr
= (PKIPCR
)KeGetPcr();
2119 KdbpPrint("Current PCR is at 0x%08x.\n", (INT
)Pcr
);
2120 KdbpPrint(" Tib.ExceptionList: 0x%08x\n"
2121 " Tib.StackBase: 0x%08x\n"
2122 " Tib.StackLimit: 0x%08x\n"
2123 " Tib.SubSystemTib: 0x%08x\n"
2124 " Tib.FiberData/Version: 0x%08x\n"
2125 " Tib.ArbitraryUserPointer: 0x%08x\n"
2126 " Tib.Self: 0x%08x\n"
2127 " SelfPcr: 0x%08x\n"
2131 " IrrActive: 0x%08x\n"
2133 " KdVersionBlock: 0x%08x\n"
2137 " MajorVersion: 0x%04x\n"
2138 " MinorVersion: 0x%04x\n"
2139 " SetMember: 0x%08x\n"
2140 " StallScaleFactor: 0x%08x\n"
2142 " L2CacheAssociativity: 0x%02x\n"
2143 " VdmAlert: 0x%08x\n"
2144 " L2CacheSize: 0x%08x\n"
2145 " InterruptMode: 0x%08x\n",
2146 Pcr
->NtTib
.ExceptionList
, Pcr
->NtTib
.StackBase
, Pcr
->NtTib
.StackLimit
,
2147 Pcr
->NtTib
.SubSystemTib
, Pcr
->NtTib
.FiberData
, Pcr
->NtTib
.ArbitraryUserPointer
,
2148 Pcr
->NtTib
.Self
, Pcr
->SelfPcr
, Pcr
->Prcb
, Pcr
->Irql
, Pcr
->IRR
, Pcr
->IrrActive
,
2149 Pcr
->IDR
, Pcr
->KdVersionBlock
, Pcr
->IDT
, Pcr
->GDT
, Pcr
->TSS
,
2150 Pcr
->MajorVersion
, Pcr
->MinorVersion
, Pcr
->SetMember
, Pcr
->StallScaleFactor
,
2151 Pcr
->Number
, Pcr
->SecondLevelCacheAssociativity
,
2152 Pcr
->VdmAlert
, Pcr
->SecondLevelCacheSize
, Pcr
->InterruptMode
);
2157 /*!\brief Displays the TSS
2164 KTSS
*Tss
= KeGetPcr()->TSS
;
2166 KdbpPrint("Current TSS is at 0x%08x.\n", (INT
)Tss
);
2167 KdbpPrint(" Eip: 0x%08x\n"
2174 " IoMapBase: 0x%04x\n",
2175 Tss
->Eip
, Tss
->Es
, Tss
->Cs
, Tss
->Ds
, Tss
->Fs
, Tss
->Gs
, Tss
->IoMapBase
);
2180 /*!\brief Bugchecks the system.
2187 /* Set the flag and quit looping */
2188 KdbpBugCheckRequested
= TRUE
;
2198 /* Reboot immediately (we do not return) */
2199 HalReturnToFirmware(HalRebootRoutine
);
2207 IN ULONG BufLength
);
2209 /*!\brief Display debug messages on screen, with paging.
2211 * Keys for per-page view: Home, End, PageUp, Arrow Up, PageDown,
2212 * all others are as PageDown.
2221 KdbpIsInDmesgMode
= TRUE
; /* Toggle logging flag */
2222 if (!KdpDmesgBuffer
)
2224 KdbpPrint("Dmesg: error, buffer is not allocated! /DEBUGPORT=SCREEN kernel param required for dmesg.\n");
2228 KdbpPrint("*** Dmesg *** TotalWritten=%lu, BufferSize=%lu, CurrentPosition=%lu\n",
2229 KdbDmesgTotalWritten
, KdpDmesgBufferSize
, KdpDmesgCurrentPosition
);
2231 // Pass data to the pager:
2232 end
= KdpDmesgCurrentPosition
;
2233 beg
= (end
+ KdpDmesgFreeBytes
) % KdpDmesgBufferSize
;
2235 // no roll-overs, and overwritten=lost bytes
2236 if (KdbDmesgTotalWritten
<= KdpDmesgBufferSize
)
2238 // show buffer (KdpDmesgBuffer + beg, num)
2239 KdbpPager(KdpDmesgBuffer
, KdpDmesgCurrentPosition
);
2243 // show 2 buffers: (KdpDmesgBuffer + beg, KdpDmesgBufferSize - beg)
2244 // and: (KdpDmesgBuffer, end)
2245 KdbpPager(KdpDmesgBuffer
+ beg
, KdpDmesgBufferSize
- beg
);
2246 KdbpPrint("*** Dmesg: buffer rollup ***\n");
2247 KdbpPager(KdpDmesgBuffer
, end
);
2249 KdbpPrint("*** Dmesg: end of output ***\n");
2251 KdbpIsInDmesgMode
= FALSE
; /* Toggle logging flag */
2256 /*!\brief Sets or displays a config variables value.
2266 KDB_ENTER_CONDITION ConditionFirst
= KdbDoNotEnter
;
2267 KDB_ENTER_CONDITION ConditionLast
= KdbDoNotEnter
;
2269 static const PCHAR ExceptionNames
[21] =
2271 "ZERODEVIDE", "DEBUGTRAP", "NMI", "INT3", "OVERFLOW", "BOUND", "INVALIDOP",
2272 "NOMATHCOP", "DOUBLEFAULT", "RESERVED(9)", "INVALIDTSS", "SEGMENTNOTPRESENT",
2273 "STACKFAULT", "GPF", "PAGEFAULT", "RESERVED(15)", "MATHFAULT", "ALIGNMENTCHECK",
2274 "MACHINECHECK", "SIMDFAULT", "OTHERS"
2279 KdbpPrint("Available settings:\n");
2280 KdbpPrint(" syntax [intel|at&t]\n");
2281 KdbpPrint(" condition [exception|*] [first|last] [never|always|kmode|umode]\n");
2282 KdbpPrint(" break_on_module_load [true|false]\n");
2284 else if (strcmp(Argv
[1], "syntax") == 0)
2288 KdbpPrint("syntax = %s\n", KdbUseIntelSyntax
? "intel" : "at&t");
2292 if (_stricmp(Argv
[2], "intel") == 0)
2293 KdbUseIntelSyntax
= TRUE
;
2294 else if (_stricmp(Argv
[2], "at&t") == 0)
2295 KdbUseIntelSyntax
= FALSE
;
2297 KdbpPrint("Unknown syntax '%s'.\n", Argv
[2]);
2300 else if (strcmp(Argv
[1], "condition") == 0)
2304 KdbpPrint("Conditions: (First) (Last)\n");
2305 for (l
= 0; l
< RTL_NUMBER_OF(ExceptionNames
) - 1; l
++)
2307 if (!ExceptionNames
[l
])
2310 if (!KdbpGetEnterCondition(l
, TRUE
, &ConditionFirst
))
2313 if (!KdbpGetEnterCondition(l
, FALSE
, &ConditionLast
))
2316 KdbpPrint(" #%02d %-20s %-8s %-8s\n", l
, ExceptionNames
[l
],
2317 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst
),
2318 KDB_ENTER_CONDITION_TO_STRING(ConditionLast
));
2321 ASSERT(l
== (RTL_NUMBER_OF(ExceptionNames
) - 1));
2322 KdbpPrint(" %-20s %-8s %-8s\n", ExceptionNames
[l
],
2323 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst
),
2324 KDB_ENTER_CONDITION_TO_STRING(ConditionLast
));
2328 if (Argc
>= 5 && strcmp(Argv
[2], "*") == 0) /* Allow * only when setting condition */
2334 l
= strtoul(Argv
[2], &pend
, 0);
2336 if (Argv
[2] == pend
)
2338 for (l
= 0; l
< RTL_NUMBER_OF(ExceptionNames
); l
++)
2340 if (!ExceptionNames
[l
])
2343 if (_stricmp(ExceptionNames
[l
], Argv
[2]) == 0)
2348 if (l
>= RTL_NUMBER_OF(ExceptionNames
))
2350 KdbpPrint("Unknown exception '%s'.\n", Argv
[2]);
2357 if (_stricmp(Argv
[3], "first") == 0)
2359 else if (_stricmp(Argv
[3], "last") == 0)
2363 KdbpPrint("set condition: second argument must be 'first' or 'last'\n");
2367 if (_stricmp(Argv
[4], "never") == 0)
2368 ConditionFirst
= KdbDoNotEnter
;
2369 else if (_stricmp(Argv
[4], "always") == 0)
2370 ConditionFirst
= KdbEnterAlways
;
2371 else if (_stricmp(Argv
[4], "umode") == 0)
2372 ConditionFirst
= KdbEnterFromUmode
;
2373 else if (_stricmp(Argv
[4], "kmode") == 0)
2374 ConditionFirst
= KdbEnterFromKmode
;
2377 KdbpPrint("set condition: third argument must be 'never', 'always', 'umode' or 'kmode'\n");
2381 if (!KdbpSetEnterCondition(l
, First
, ConditionFirst
))
2384 KdbpPrint("Couldn't change condition for exception #%02d\n", l
);
2386 KdbpPrint("Couldn't change condition for all exceptions\n", l
);
2389 else /* Argc >= 3 */
2391 if (!KdbpGetEnterCondition(l
, TRUE
, &ConditionFirst
))
2394 if (!KdbpGetEnterCondition(l
, FALSE
, &ConditionLast
))
2397 if (l
< (RTL_NUMBER_OF(ExceptionNames
) - 1))
2399 KdbpPrint("Condition for exception #%02d (%s): FirstChance %s LastChance %s\n",
2400 l
, ExceptionNames
[l
],
2401 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst
),
2402 KDB_ENTER_CONDITION_TO_STRING(ConditionLast
));
2406 KdbpPrint("Condition for all other exceptions: FirstChance %s LastChance %s\n",
2407 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst
),
2408 KDB_ENTER_CONDITION_TO_STRING(ConditionLast
));
2413 else if (strcmp(Argv
[1], "break_on_module_load") == 0)
2416 KdbpPrint("break_on_module_load = %s\n", KdbBreakOnModuleLoad
? "enabled" : "disabled");
2419 if (_stricmp(Argv
[2], "enable") == 0 || _stricmp(Argv
[2], "enabled") == 0 || _stricmp(Argv
[2], "true") == 0)
2420 KdbBreakOnModuleLoad
= TRUE
;
2421 else if (_stricmp(Argv
[2], "disable") == 0 || _stricmp(Argv
[2], "disabled") == 0 || _stricmp(Argv
[2], "false") == 0)
2422 KdbBreakOnModuleLoad
= FALSE
;
2424 KdbpPrint("Unknown setting '%s'.\n", Argv
[2]);
2429 KdbpPrint("Unknown setting '%s'.\n", Argv
[1]);
2435 /*!\brief Displays help screen.
2444 KdbpPrint("Kernel debugger commands:\n");
2445 for (i
= 0; i
< RTL_NUMBER_OF(KdbDebuggerCommands
); i
++)
2447 if (!KdbDebuggerCommands
[i
].Syntax
) /* Command group */
2452 KdbpPrint("\x1b[7m* %s:\x1b[0m\n", KdbDebuggerCommands
[i
].Help
);
2456 KdbpPrint(" %-20s - %s\n",
2457 KdbDebuggerCommands
[i
].Syntax
,
2458 KdbDebuggerCommands
[i
].Help
);
2464 /*!\brief Prints the given string with printf-like formatting.
2466 * \param Format Format of the string/arguments.
2467 * \param ... Variable number of arguments matching the format specified in \a Format.
2469 * \note Doesn't correctly handle \\t and terminal escape sequences when calculating the
2470 * number of lines required to print a single line from the Buffer in the terminal.
2471 * Prints maximum 4096 chars, because of its buffer size.
2478 static CHAR Buffer
[4096];
2479 static BOOLEAN TerminalInitialized
= FALSE
;
2480 static BOOLEAN TerminalConnected
= FALSE
;
2481 static BOOLEAN TerminalReportsSize
= TRUE
;
2486 LONG RowsPrintedByTerminal
;
2490 /* Check if the user has aborted output of the current command */
2491 if (KdbOutputAborted
)
2494 /* Initialize the terminal */
2495 if (!TerminalInitialized
)
2497 DbgPrint("\x1b[7h"); /* Enable linewrap */
2499 /* Query terminal type */
2500 /*DbgPrint("\x1b[Z");*/
2503 TerminalInitialized
= TRUE
;
2505 KeStallExecutionProcessor(100000);
2509 c
= KdbpTryGetCharSerial(5000);
2513 Buffer
[Length
++] = c
;
2514 if (Length
>= (sizeof (Buffer
) - 1))
2518 Buffer
[Length
] = '\0';
2520 TerminalConnected
= TRUE
;
2523 /* Get number of rows and columns in terminal */
2524 if ((KdbNumberOfRowsTerminal
< 0) || (KdbNumberOfColsTerminal
< 0) ||
2525 (KdbNumberOfRowsPrinted
) == 0) /* Refresh terminal size each time when number of rows printed is 0 */
2527 if ((KdbDebugState
& KD_DEBUG_KDSERIAL
) && TerminalConnected
&& TerminalReportsSize
)
2529 /* Try to query number of rows from terminal. A reply looks like "\x1b[8;24;80t" */
2530 TerminalReportsSize
= FALSE
;
2531 KeStallExecutionProcessor(100000);
2532 DbgPrint("\x1b[18t");
2533 c
= KdbpTryGetCharSerial(5000);
2537 c
= KdbpTryGetCharSerial(5000);
2544 c
= KdbpTryGetCharSerial(5000);
2548 Buffer
[Length
++] = c
;
2549 if (isalpha(c
) || Length
>= (sizeof (Buffer
) - 1))
2553 Buffer
[Length
] = '\0';
2554 if (Buffer
[0] == '8' && Buffer
[1] == ';')
2556 for (i
= 2; (i
< Length
) && (Buffer
[i
] != ';'); i
++);
2558 if (Buffer
[i
] == ';')
2562 /* Number of rows is now at Buffer + 2 and number of cols at Buffer + i */
2563 KdbNumberOfRowsTerminal
= strtoul(Buffer
+ 2, NULL
, 0);
2564 KdbNumberOfColsTerminal
= strtoul(Buffer
+ i
, NULL
, 0);
2565 TerminalReportsSize
= TRUE
;
2569 /* Clear further characters */
2570 while ((c
= KdbpTryGetCharSerial(5000)) != -1);
2574 if (KdbNumberOfRowsTerminal
<= 0)
2576 /* Set number of rows to the default. */
2577 KdbNumberOfRowsTerminal
= 23; //24; //Mna.: 23 for SCREEN debugport
2579 else if (KdbNumberOfColsTerminal
<= 0)
2581 /* Set number of cols to the default. */
2582 KdbNumberOfColsTerminal
= 75; //80; //Mna.: 75 for SCREEN debugport
2586 /* Get the string */
2587 va_start(ap
, Format
);
2588 Length
= _vsnprintf(Buffer
, sizeof (Buffer
) - 1, Format
, ap
);
2589 Buffer
[Length
] = '\0';
2593 while (p
[0] != '\0')
2595 i
= strcspn(p
, "\n");
2597 /* Calculate the number of lines which will be printed in the terminal
2598 * when outputting the current line
2601 RowsPrintedByTerminal
= (i
+ KdbNumberOfColsPrinted
- 1) / KdbNumberOfColsTerminal
;
2603 RowsPrintedByTerminal
= 0;
2606 RowsPrintedByTerminal
++;
2608 /*DbgPrint("!%d!%d!%d!%d!", KdbNumberOfRowsPrinted, KdbNumberOfColsPrinted, i, RowsPrintedByTerminal);*/
2610 /* Display a prompt if we printed one screen full of text */
2611 if (KdbNumberOfRowsTerminal
> 0 &&
2612 (LONG
)(KdbNumberOfRowsPrinted
+ RowsPrintedByTerminal
) >= KdbNumberOfRowsTerminal
)
2614 KdbRepeatLastCommand
= FALSE
;
2616 if (KdbNumberOfColsPrinted
> 0)
2619 DbgPrint("--- Press q to abort, any other key to continue ---");
2620 RowsPrintedByTerminal
++; /* added by Mna. */
2622 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
2623 c
= KdbpGetCharSerial();
2625 c
= KdbpGetCharKeyboard(&ScanCode
);
2629 /* Try to read '\n' which might follow '\r' - if \n is not received here
2630 * it will be interpreted as "return" when the next command should be read.
2632 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
2633 c
= KdbpTryGetCharSerial(5);
2635 c
= KdbpTryGetCharKeyboard(&ScanCode
, 5);
2641 KdbOutputAborted
= TRUE
;
2645 KdbNumberOfRowsPrinted
= 0;
2646 KdbNumberOfColsPrinted
= 0;
2649 /* Insert a NUL after the line and print only the current line. */
2650 if (p
[i
] == '\n' && p
[i
+ 1] != '\0')
2660 /* Remove escape sequences from the line if there's no terminal connected */
2661 if (!TerminalConnected
)
2663 while ((p2
= strrchr(p
, '\x1b'))) /* Look for escape character */
2668 while (!isalpha(p2
[j
++]));
2683 /* Set p to the start of the next line and
2684 * remember the number of rows/cols printed
2690 KdbNumberOfColsPrinted
= 0;
2694 ASSERT(p
[0] == '\0');
2695 KdbNumberOfColsPrinted
+= i
;
2698 KdbNumberOfRowsPrinted
+= RowsPrintedByTerminal
;
2702 /** memrchr(), explicitly defined, since was absent in MinGW of RosBE. */
2705 * Find the last occurrence of 'c' in the buffer 's' of size 'n'.
2708 memrchr(const void *s
, int c
, size_t n
)
2710 const unsigned char *cp
;
2714 cp
= (unsigned char *)s
+ n
;
2717 if (*(--cp
) == (unsigned char)c
)
2724 /*!\brief Calculate pointer position for N lines upper of current position.
2726 * \param Buffer Characters buffer to operate on.
2727 * \param BufLength Buffer size.
2729 * \note Calculate pointer position for N lines upper of current displaying
2730 * position within the given buffer.
2732 * Used by KdbpPager().
2733 * Now N lines count is hardcoded to KdbNumberOfRowsTerminal.
2736 CountOnePageUp(PCHAR Buffer
, ULONG BufLength
, PCHAR pCurPos
)
2739 // p0 is initial guess of Page Start
2740 ULONG p0len
= KdbNumberOfRowsTerminal
* KdbNumberOfColsTerminal
;
2741 PCHAR p0
= pCurPos
- p0len
;
2742 PCHAR prev_p
= p0
, p1
;
2745 if (pCurPos
< Buffer
)
2747 ASSERT(pCurPos
<= Buffer
+ BufLength
);
2749 p
= memrchr(p0
, '\n', p0len
);
2752 for (j
= KdbNumberOfRowsTerminal
; j
--; )
2755 p1
= memrchr(p0
, '\n', p
-p0
);
2765 linesCnt
= (KdbNumberOfColsTerminal
+prev_p
-p
-2) / KdbNumberOfColsTerminal
;
2775 /*!\brief Prints the given string with, page by page.
2777 * \param Buffer Characters buffer to print.
2778 * \param BufferLen Buffer size.
2780 * \note Doesn't correctly handle \\t and terminal escape sequences when calculating the
2781 * number of lines required to print a single line from the Buffer in the terminal.
2782 * Maximum length of buffer is limited only by memory size.
2784 * Note: BufLength should be greater then (KdbNumberOfRowsTerminal * KdbNumberOfColsTerminal).
2792 static CHAR InBuffer
[4096];
2793 static BOOLEAN TerminalInitialized
= FALSE
;
2794 static BOOLEAN TerminalConnected
= FALSE
;
2795 static BOOLEAN TerminalReportsSize
= TRUE
;
2800 LONG RowsPrintedByTerminal
;
2806 /* Check if the user has aborted output of the current command */
2807 if (KdbOutputAborted
)
2810 /* Initialize the terminal */
2811 if (!TerminalInitialized
)
2813 DbgPrint("\x1b[7h"); /* Enable linewrap */
2815 /* Query terminal type */
2816 /*DbgPrint("\x1b[Z");*/
2819 TerminalInitialized
= TRUE
;
2821 KeStallExecutionProcessor(100000);
2825 c
= KdbpTryGetCharSerial(5000);
2829 InBuffer
[Length
++] = c
;
2830 if (Length
>= (sizeof (InBuffer
) - 1))
2834 InBuffer
[Length
] = '\0';
2836 TerminalConnected
= TRUE
;
2839 /* Get number of rows and columns in terminal */
2840 if ((KdbNumberOfRowsTerminal
< 0) || (KdbNumberOfColsTerminal
< 0) ||
2841 (KdbNumberOfRowsPrinted
) == 0) /* Refresh terminal size each time when number of rows printed is 0 */
2843 if ((KdbDebugState
& KD_DEBUG_KDSERIAL
) && TerminalConnected
&& TerminalReportsSize
)
2845 /* Try to query number of rows from terminal. A reply looks like "\x1b[8;24;80t" */
2846 TerminalReportsSize
= FALSE
;
2847 KeStallExecutionProcessor(100000);
2848 DbgPrint("\x1b[18t");
2849 c
= KdbpTryGetCharSerial(5000);
2853 c
= KdbpTryGetCharSerial(5000);
2860 c
= KdbpTryGetCharSerial(5000);
2864 InBuffer
[Length
++] = c
;
2865 if (isalpha(c
) || Length
>= (sizeof (InBuffer
) - 1))
2869 InBuffer
[Length
] = '\0';
2870 if (InBuffer
[0] == '8' && InBuffer
[1] == ';')
2872 for (i
= 2; (i
< Length
) && (InBuffer
[i
] != ';'); i
++);
2874 if (Buffer
[i
] == ';')
2878 /* Number of rows is now at Buffer + 2 and number of cols at Buffer + i */
2879 KdbNumberOfRowsTerminal
= strtoul(InBuffer
+ 2, NULL
, 0);
2880 KdbNumberOfColsTerminal
= strtoul(InBuffer
+ i
, NULL
, 0);
2881 TerminalReportsSize
= TRUE
;
2885 /* Clear further characters */
2886 while ((c
= KdbpTryGetCharSerial(5000)) != -1);
2890 if (KdbNumberOfRowsTerminal
<= 0)
2892 /* Set number of rows to the default. */
2893 KdbNumberOfRowsTerminal
= 24;
2895 else if (KdbNumberOfColsTerminal
<= 0)
2897 /* Set number of cols to the default. */
2898 KdbNumberOfColsTerminal
= 80;
2902 /* Get the string */
2905 while (p
[0] != '\0')
2907 if ( p
> Buffer
+BufLength
)
2909 DbgPrint("Dmesg: error, p > Buffer+BufLength,d=%d", p
- (Buffer
+BufLength
));
2912 i
= strcspn(p
, "\n");
2914 // Are we out of buffer?
2915 if (p
+ i
> Buffer
+ BufLength
)
2916 // Leaving pager function:
2919 /* Calculate the number of lines which will be printed in the terminal
2920 * when outputting the current line
2923 RowsPrintedByTerminal
= (i
+ KdbNumberOfColsPrinted
- 1) / KdbNumberOfColsTerminal
;
2925 RowsPrintedByTerminal
= 0;
2928 RowsPrintedByTerminal
++;
2930 /*DbgPrint("!%d!%d!%d!%d!", KdbNumberOfRowsPrinted, KdbNumberOfColsPrinted, i, RowsPrintedByTerminal);*/
2932 /* Display a prompt if we printed one screen full of text */
2933 if (KdbNumberOfRowsTerminal
> 0 &&
2934 (LONG
)(KdbNumberOfRowsPrinted
+ RowsPrintedByTerminal
) >= KdbNumberOfRowsTerminal
)
2936 KdbRepeatLastCommand
= FALSE
;
2938 if (KdbNumberOfColsPrinted
> 0)
2941 DbgPrint("--- Press q to abort, e/End,h/Home,u/PgUp, other key/PgDn ---");
2942 RowsPrintedByTerminal
++;
2944 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
2945 c
= KdbpGetCharSerial();
2947 c
= KdbpGetCharKeyboard(&ScanCode
);
2951 /* Try to read '\n' which might follow '\r' - if \n is not received here
2952 * it will be interpreted as "return" when the next command should be read.
2954 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
2955 c
= KdbpTryGetCharSerial(5);
2957 c
= KdbpTryGetCharKeyboard(&ScanCode
, 5);
2960 //DbgPrint("\n"); //Consize version: don't show pressed key
2961 DbgPrint(" '%c'/scan=%04x\n", c
, ScanCode
); // Shows pressed key
2965 KdbOutputAborted
= TRUE
;
2968 if ( ScanCode
== KEYSC_END
|| c
=='e')
2970 PCHAR pBufEnd
= Buffer
+ BufLength
;
2971 p
= CountOnePageUp(Buffer
, BufLength
, pBufEnd
);
2972 i
= strcspn(p
, "\n");
2974 else if (ScanCode
== KEYSC_PAGEUP
|| c
=='u')
2976 p
= CountOnePageUp(Buffer
, BufLength
, p
);
2977 i
= strcspn(p
, "\n");
2979 else if (ScanCode
== KEYSC_HOME
|| c
=='h')
2982 i
= strcspn(p
, "\n");
2984 else if (ScanCode
== KEYSC_ARROWUP
)
2986 p
= CountOnePageUp(Buffer
, BufLength
, p
);
2987 i
= strcspn(p
, "\n");
2990 KdbNumberOfRowsPrinted
= 0;
2991 KdbNumberOfColsPrinted
= 0;
2994 /* Insert a NUL after the line and print only the current line. */
2995 if (p
[i
] == '\n' && p
[i
+ 1] != '\0')
3005 /* Remove escape sequences from the line if there's no terminal connected */
3006 if (!TerminalConnected
)
3008 while ((p2
= strrchr(p
, '\x1b'))) /* Look for escape character */
3013 while (!isalpha(p2
[j
++]));
3023 // The main printing of the current line:
3026 // restore not null char with saved:
3030 /* Set p to the start of the next line and
3031 * remember the number of rows/cols printed
3037 KdbNumberOfColsPrinted
= 0;
3041 ASSERT(p
[0] == '\0');
3042 KdbNumberOfColsPrinted
+= i
;
3045 KdbNumberOfRowsPrinted
+= RowsPrintedByTerminal
;
3049 /*!\brief Appends a command to the command history
3051 * \param Command Pointer to the command to append to the history.
3054 KdbpCommandHistoryAppend(
3057 ULONG Length1
= strlen(Command
) + 1;
3062 ASSERT(Length1
<= RTL_NUMBER_OF(KdbCommandHistoryBuffer
));
3065 (KdbCommandHistory
[KdbCommandHistoryIndex
] &&
3066 strcmp(KdbCommandHistory
[KdbCommandHistoryIndex
], Command
) == 0))
3071 /* Calculate Length1 and Length2 */
3072 Buffer
= KdbCommandHistoryBuffer
+ KdbCommandHistoryBufferIndex
;
3073 KdbCommandHistoryBufferIndex
+= Length1
;
3074 if (KdbCommandHistoryBufferIndex
>= (LONG
)RTL_NUMBER_OF(KdbCommandHistoryBuffer
))
3076 KdbCommandHistoryBufferIndex
-= RTL_NUMBER_OF(KdbCommandHistoryBuffer
);
3077 Length2
= KdbCommandHistoryBufferIndex
;
3081 /* Remove previous commands until there is enough space to append the new command */
3082 for (i
= KdbCommandHistoryIndex
; KdbCommandHistory
[i
];)
3085 (KdbCommandHistory
[i
] >= Buffer
||
3086 KdbCommandHistory
[i
] < (KdbCommandHistoryBuffer
+ KdbCommandHistoryBufferIndex
))) ||
3088 (KdbCommandHistory
[i
] >= Buffer
&&
3089 KdbCommandHistory
[i
] < (KdbCommandHistoryBuffer
+ KdbCommandHistoryBufferIndex
))))
3091 KdbCommandHistory
[i
] = NULL
;
3096 i
= RTL_NUMBER_OF(KdbCommandHistory
) - 1;
3098 if (i
== KdbCommandHistoryIndex
)
3102 /* Make sure the new command history entry is free */
3103 KdbCommandHistoryIndex
++;
3104 KdbCommandHistoryIndex
%= RTL_NUMBER_OF(KdbCommandHistory
);
3105 if (KdbCommandHistory
[KdbCommandHistoryIndex
])
3107 KdbCommandHistory
[KdbCommandHistoryIndex
] = NULL
;
3110 /* Append command */
3111 KdbCommandHistory
[KdbCommandHistoryIndex
] = Buffer
;
3112 ASSERT((KdbCommandHistory
[KdbCommandHistoryIndex
] + Length1
) <= KdbCommandHistoryBuffer
+ RTL_NUMBER_OF(KdbCommandHistoryBuffer
));
3113 memcpy(KdbCommandHistory
[KdbCommandHistoryIndex
], Command
, Length1
);
3116 memcpy(KdbCommandHistoryBuffer
, Command
+ Length1
, Length2
);
3120 /*!\brief Reads a line of user-input.
3122 * \param Buffer Buffer to store the input into. Trailing newlines are removed.
3123 * \param Size Size of \a Buffer.
3125 * \note Accepts only \n newlines, \r is ignored.
3133 PCHAR Orig
= Buffer
;
3136 static CHAR LastCommand
[1024];
3137 static CHAR NextKey
= '\0';
3138 INT CmdHistIndex
= -1;
3141 EchoOn
= !((KdbDebugState
& KD_DEBUG_KDNOECHO
) != 0);
3145 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
3147 Key
= (NextKey
== '\0') ? KdbpGetCharSerial() : NextKey
;
3150 if (Key
== KEY_ESC
) /* ESC */
3152 Key
= KdbpGetCharSerial();
3155 Key
= KdbpGetCharSerial();
3160 ScanCode
= KEY_SCAN_UP
;
3163 ScanCode
= KEY_SCAN_DOWN
;
3176 Key
= (NextKey
== '\0') ? KdbpGetCharKeyboard(&ScanCode
) : NextKey
;
3180 if ((ULONG
)(Buffer
- Orig
) >= (Size
- 1))
3182 /* Buffer is full, accept only newlines */
3189 /* Read the next char - this is to throw away a \n which most clients should
3192 KeStallExecutionProcessor(100000);
3194 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
3195 NextKey
= KdbpTryGetCharSerial(5);
3197 NextKey
= KdbpTryGetCharKeyboard(&ScanCode
, 5);
3199 if (NextKey
== '\n' || NextKey
== -1) /* \n or no response at all */
3205 * Repeat the last command if the user presses enter. Reduces the
3206 * risk of RSI when single-stepping.
3210 KdbRepeatLastCommand
= TRUE
;
3212 RtlStringCbCopyA(LastCommand
, sizeof(LastCommand
), Orig
);
3214 else if (KdbRepeatLastCommand
)
3215 RtlStringCbCopyA(Buffer
, Size
, LastCommand
);
3221 else if (Key
== KEY_BS
|| Key
== KEY_DEL
)
3229 KdbpPrint("%c %c", KEY_BS
, KEY_BS
);
3231 KdbpPrint(" %c", KEY_BS
);
3234 else if (ScanCode
== KEY_SCAN_UP
)
3236 BOOLEAN Print
= TRUE
;
3238 if (CmdHistIndex
< 0)
3240 CmdHistIndex
= KdbCommandHistoryIndex
;
3244 i
= CmdHistIndex
- 1;
3247 CmdHistIndex
= RTL_NUMBER_OF(KdbCommandHistory
) - 1;
3249 if (KdbCommandHistory
[i
] && i
!= KdbCommandHistoryIndex
)
3255 if (Print
&& KdbCommandHistory
[CmdHistIndex
])
3257 while (Buffer
> Orig
)
3263 KdbpPrint("%c %c", KEY_BS
, KEY_BS
);
3265 KdbpPrint(" %c", KEY_BS
);
3268 i
= min(strlen(KdbCommandHistory
[CmdHistIndex
]), Size
- 1);
3269 memcpy(Orig
, KdbCommandHistory
[CmdHistIndex
], i
);
3272 KdbpPrint("%s", Orig
);
3275 else if (ScanCode
== KEY_SCAN_DOWN
)
3277 if (CmdHistIndex
> 0 && CmdHistIndex
!= KdbCommandHistoryIndex
)
3279 i
= CmdHistIndex
+ 1;
3280 if (i
>= (INT
)RTL_NUMBER_OF(KdbCommandHistory
))
3283 if (KdbCommandHistory
[i
])
3286 while (Buffer
> Orig
)
3292 KdbpPrint("%c %c", KEY_BS
, KEY_BS
);
3294 KdbpPrint(" %c", KEY_BS
);
3297 i
= min(strlen(KdbCommandHistory
[CmdHistIndex
]), Size
- 1);
3298 memcpy(Orig
, KdbCommandHistory
[CmdHistIndex
], i
);
3301 KdbpPrint("%s", Orig
);
3308 KdbpPrint("%c", Key
);
3319 KdbRegisterCliCallback(
3325 /* Loop all entries */
3326 for (i
= 0; i
< _countof(KdbCliCallbacks
); i
++)
3328 /* Check if deregistering was requested */
3331 /* Check if this entry is the one that was registered */
3332 if (KdbCliCallbacks
[i
] == Callback
)
3334 /* Delete it and report success */
3335 KdbCliCallbacks
[i
] = NULL
;
3341 /* Check if this entry is free */
3342 if (KdbCliCallbacks
[i
] == NULL
)
3344 /* Set it and and report success */
3345 KdbCliCallbacks
[i
] = Callback
;
3355 /*! \brief Invokes registered CLI callbacks until one of them handled the
3358 * \param Command - Command line to parse and execute if possible.
3359 * \param Argc - Number of arguments in Argv
3360 * \param Argv - Array of strings, each of them containing one argument.
3362 * \return TRUE, if the command was handled, FALSE if it was not handled.
3366 KdbpInvokeCliCallbacks(
3373 /* Loop all entries */
3374 for (i
= 0; i
< _countof(KdbCliCallbacks
); i
++)
3376 /* Check if this entry is registered */
3377 if (KdbCliCallbacks
[i
])
3379 /* Invoke the callback and check if it handled the command */
3380 if (KdbCliCallbacks
[i
](Command
, Argc
, Argv
))
3387 /* None of the callbacks handled the command */
3392 /*!\brief Parses command line and executes command if found
3394 * \param Command Command line to parse and execute if possible.
3396 * \retval TRUE Don't continue execution.
3397 * \retval FALSE Continue execution (leave KDB)
3406 // FIXME: for what do we need a 1024 characters command line and 256 tokens?
3407 static PCH Argv
[256];
3408 static CHAR OrigCommand
[1024];
3410 RtlStringCbCopyA(OrigCommand
, sizeof(OrigCommand
), Command
);
3417 while (*p
== '\t' || *p
== ' ')
3423 i
= strcspn(p
, "\t ");
3436 for (i
= 0; i
< RTL_NUMBER_OF(KdbDebuggerCommands
); i
++)
3438 if (!KdbDebuggerCommands
[i
].Name
)
3441 if (strcmp(KdbDebuggerCommands
[i
].Name
, Argv
[0]) == 0)
3443 return KdbDebuggerCommands
[i
].Fn(Argc
, Argv
);
3447 /* Now invoke the registered callbacks */
3448 if (KdbpInvokeCliCallbacks(Command
, Argc
, Argv
))
3453 KdbpPrint("Command '%s' is unknown.\n", OrigCommand
);
3457 /*!\brief KDB Main Loop.
3459 * \param EnteredOnSingleStep TRUE if KDB was entered on single step.
3463 IN BOOLEAN EnteredOnSingleStep
)
3465 static CHAR Command
[1024];
3468 if (EnteredOnSingleStep
)
3470 if (!KdbSymPrintAddress((PVOID
)KdbCurrentTrapFrame
->Tf
.Eip
, &KdbCurrentTrapFrame
->Tf
))
3472 KdbpPrint("<%x>", KdbCurrentTrapFrame
->Tf
.Eip
);
3476 if (KdbpDisassemble(KdbCurrentTrapFrame
->Tf
.Eip
, KdbUseIntelSyntax
) < 0)
3478 KdbpPrint("<INVALID>");
3483 /* Flush the input buffer */
3484 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
3486 while (KdbpTryGetCharSerial(1) != -1);
3491 while (KdbpTryGetCharKeyboard(&ScanCode
, 1) != -1);
3497 /* Reset the number of rows/cols printed */
3498 KdbNumberOfRowsPrinted
= KdbNumberOfColsPrinted
= 0;
3500 /* Print the prompt */
3501 KdbpPrint("kdb:> ");
3503 /* Read a command and remember it */
3504 KdbpReadCommand(Command
, sizeof (Command
));
3505 KdbpCommandHistoryAppend(Command
);
3507 /* Reset the number of rows/cols printed and output aborted state */
3508 KdbNumberOfRowsPrinted
= KdbNumberOfColsPrinted
= 0;
3509 KdbOutputAborted
= FALSE
;
3511 /* Call the command */
3512 Continue
= KdbpDoCommand(Command
);
3513 KdbOutputAborted
= FALSE
;
3518 /*!\brief Called when a module is loaded.
3520 * \param Name Filename of the module which was loaded.
3523 KdbpCliModuleLoaded(
3524 IN PUNICODE_STRING Name
)
3526 if (!KdbBreakOnModuleLoad
)
3529 KdbpPrint("Module %wZ loaded.\n", Name
);
3530 DbgBreakPointWithStatus(DBG_STATUS_CONTROL_C
);
3533 /*!\brief This function is called by KdbEnterDebuggerException...
3535 * Used to interpret the init file in a context with a trapframe setup
3536 * (KdbpCliInit call KdbEnter which will call KdbEnterDebuggerException which will
3537 * call this function if KdbInitFileBuffer is not NULL.
3540 KdbpCliInterpretInitFile(VOID
)
3546 /* Execute the commands in the init file */
3547 DPRINT("KDB: Executing KDBinit file...\n");
3548 p1
= KdbInitFileBuffer
;
3549 while (p1
[0] != '\0')
3551 i
= strcspn(p1
, "\r\n");
3557 /* Look for "break" command and comments */
3560 while (isspace(p2
[0]))
3563 if (strncmp(p2
, "break", sizeof("break")-1) == 0 &&
3564 (p2
[sizeof("break")-1] == '\0' || isspace(p2
[sizeof("break")-1])))
3566 /* break into the debugger */
3567 KdbpCliMainLoop(FALSE
);
3569 else if (p2
[0] != '#' && p2
[0] != '\0') /* Ignore empty lines and comments */
3578 while (p1
[0] == '\r' || p1
[0] == '\n')
3581 DPRINT("KDB: KDBinit executed\n");
3584 /*!\brief Called when KDB is initialized
3586 * Reads the KDBinit file from the SystemRoot\System32\drivers\etc directory and executes it.
3592 OBJECT_ATTRIBUTES ObjectAttributes
;
3593 UNICODE_STRING FileName
;
3594 IO_STATUS_BLOCK Iosb
;
3595 FILE_STANDARD_INFORMATION FileStdInfo
;
3596 HANDLE hFile
= NULL
;
3601 /* Initialize the object attributes */
3602 RtlInitUnicodeString(&FileName
, L
"\\SystemRoot\\System32\\drivers\\etc\\KDBinit");
3603 InitializeObjectAttributes(&ObjectAttributes
, &FileName
, 0, NULL
, NULL
);
3606 Status
= ZwOpenFile(&hFile
, FILE_READ_DATA
| SYNCHRONIZE
,
3607 &ObjectAttributes
, &Iosb
, 0,
3608 FILE_NON_DIRECTORY_FILE
| FILE_SYNCHRONOUS_IO_NONALERT
|
3609 FILE_NO_INTERMEDIATE_BUFFERING
);
3610 if (!NT_SUCCESS(Status
))
3612 DPRINT("Could not open \\SystemRoot\\System32\\drivers\\etc\\KDBinit (Status 0x%x)", Status
);
3616 /* Get the size of the file */
3617 Status
= ZwQueryInformationFile(hFile
, &Iosb
, &FileStdInfo
, sizeof (FileStdInfo
),
3618 FileStandardInformation
);
3619 if (!NT_SUCCESS(Status
))
3622 DPRINT("Could not query size of \\SystemRoot\\System32\\drivers\\etc\\KDBinit (Status 0x%x)", Status
);
3625 FileSize
= FileStdInfo
.EndOfFile
.u
.LowPart
;
3627 /* Allocate memory for the file */
3628 FileBuffer
= ExAllocatePool(PagedPool
, FileSize
+ 1); /* add 1 byte for terminating '\0' */
3632 DPRINT("Could not allocate %d bytes for KDBinit file\n", FileSize
);
3636 /* Load file into memory */
3637 Status
= ZwReadFile(hFile
, NULL
, NULL
, NULL
, &Iosb
, FileBuffer
, FileSize
, NULL
, NULL
);
3640 if (!NT_SUCCESS(Status
) && Status
!= STATUS_END_OF_FILE
)
3642 ExFreePool(FileBuffer
);
3643 DPRINT("Could not read KDBinit file into memory (Status 0x%lx)\n", Status
);
3647 FileSize
= min(FileSize
, (INT
)Iosb
.Information
);
3648 FileBuffer
[FileSize
] = '\0';
3650 /* Enter critical section */
3651 OldEflags
= __readeflags();
3654 /* Interpret the init file... */
3655 KdbInitFileBuffer
= FileBuffer
;
3657 KdbInitFileBuffer
= NULL
;
3659 /* Leave critical section */
3660 __writeeflags(OldEflags
);
3662 ExFreePool(FileBuffer
);
3667 KdpSerialDebugPrint(
3672 STRING KdpPromptString
= RTL_CONSTANT_STRING("kdb:> ");
3673 extern KSPIN_LOCK KdpSerialSpinLock
;
3678 _In_reads_bytes_(InStringLength
) PCHAR UnsafeInString
,
3679 _In_ USHORT InStringLength
,
3680 _Out_writes_bytes_(OutStringLength
) PCHAR UnsafeOutString
,
3681 _In_ USHORT OutStringLength
,
3682 _In_ KPROCESSOR_MODE PreviousMode
,
3683 _In_ PKTRAP_FRAME TrapFrame
,
3684 _In_ PKEXCEPTION_FRAME ExceptionFrame
)
3688 ULONG DummyScanCode
;
3692 CHAR InStringBuffer
[512];
3693 CHAR OutStringBuffer
[512];
3695 /* Normalize the lengths */
3696 InStringLength
= min(InStringLength
,
3697 sizeof(InStringBuffer
));
3698 OutStringLength
= min(OutStringLength
,
3699 sizeof(OutStringBuffer
));
3701 /* Check if we need to verify the string */
3702 if (PreviousMode
!= KernelMode
)
3704 /* Handle user-mode buffers safely */
3707 /* Probe the prompt */
3708 ProbeForRead(UnsafeInString
,
3712 /* Capture prompt */
3713 InString
= InStringBuffer
;
3714 RtlCopyMemory(InString
,
3718 /* Probe and make room for response */
3719 ProbeForWrite(UnsafeOutString
,
3722 OutString
= OutStringBuffer
;
3724 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
3726 /* Bad string pointer, bail out */
3727 _SEH2_YIELD(return 0);
3733 InString
= UnsafeInString
;
3734 OutString
= UnsafeOutString
;
3737 /* Acquire the printing spinlock without waiting at raised IRQL */
3740 /* Wait when the spinlock becomes available */
3741 while (!KeTestSpinLock(&KdpSerialSpinLock
));
3743 /* Spinlock was free, raise IRQL */
3744 KeRaiseIrql(HIGH_LEVEL
, &OldIrql
);
3746 /* Try to get the spinlock */
3747 if (KeTryToAcquireSpinLockAtDpcLevel(&KdpSerialSpinLock
))
3750 /* Someone else got the spinlock, lower IRQL back */
3751 KeLowerIrql(OldIrql
);
3754 /* Loop the string to send */
3755 for (i
= 0; i
< InStringLength
; i
++)
3757 /* Print it to serial */
3758 KdPortPutByteEx(&SerialPortInfo
, *(PCHAR
)(InString
+ i
));
3761 /* Print a new line for log neatness */
3762 KdPortPutByteEx(&SerialPortInfo
, '\r');
3763 KdPortPutByteEx(&SerialPortInfo
, '\n');
3765 /* Print the kdb prompt */
3766 for (i
= 0; i
< KdpPromptString
.Length
; i
++)
3768 /* Print it to serial */
3769 KdPortPutByteEx(&SerialPortInfo
,
3770 *(KdpPromptString
.Buffer
+ i
));
3773 if (!(KdbDebugState
& KD_DEBUG_KDSERIAL
))
3776 /* Loop the whole string */
3777 for (i
= 0; i
< OutStringLength
; i
++)
3779 /* Check if this is serial debugging mode */
3780 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
3782 /* Get the character from serial */
3785 Response
= KdbpTryGetCharSerial(MAXULONG
);
3786 } while (Response
== -1);
3790 /* Get the response from the keyboard */
3793 Response
= KdbpTryGetCharKeyboard(&DummyScanCode
, MAXULONG
);
3794 } while (Response
== -1);
3797 /* Check for return */
3798 if (Response
== '\r')
3801 * We might need to discard the next '\n'.
3802 * Wait a bit to make sure we receive it.
3804 KeStallExecutionProcessor(100000);
3806 /* Check the mode */
3807 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
3809 /* Read and discard the next character, if any */
3810 KdbpTryGetCharSerial(5);
3814 /* Read and discard the next character, if any */
3815 KdbpTryGetCharKeyboard(&DummyScanCode
, 5);
3819 * Null terminate the output string -- documentation states that
3820 * DbgPrompt does not null terminate, but it does
3822 *(PCHAR
)(OutString
+ i
) = 0;
3826 /* Write it back and print it to the log */
3827 *(PCHAR
)(OutString
+ i
) = Response
;
3828 KdPortPutByteEx(&SerialPortInfo
, Response
);
3831 if (!(KdbDebugState
& KD_DEBUG_KDSERIAL
))
3834 /* Print a new line */
3835 KdPortPutByteEx(&SerialPortInfo
, '\r');
3836 KdPortPutByteEx(&SerialPortInfo
, '\n');
3838 /* Release spinlock */
3839 KiReleaseSpinLock(&KdpSerialSpinLock
);
3841 /* Lower IRQL back */
3842 KeLowerIrql(OldIrql
);
3844 /* Copy back response if required */
3845 if (PreviousMode
!= KernelMode
)
3849 /* Safely copy back response to user mode */
3850 RtlCopyMemory(UnsafeOutString
,
3854 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
3856 /* String became invalid after we exited, fail */
3857 _SEH2_YIELD(return 0);
3862 /* Return the length */