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 address.", KdbpCmdDisassembleX
},
148 { "regs", "regs", "Display general purpose registers.", KdbpCmdRegs
},
149 { "cregs", "cregs", "Display control, descriptor table and task segment 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 address.", KdbpCmdBackTrace
},
154 { "dt", "dt [mod] [type] [addr]", "Print a struct. The address 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 the global descriptor table.", KdbpCmdGdtLdtIdt
},
178 { "ldt", "ldt", "Display the local descriptor table.", KdbpCmdGdtLdtIdt
},
179 { "idt", "idt", "Display the interrupt descriptor table.", KdbpCmdGdtLdtIdt
},
180 { "pcr", "pcr", "Display the processor control region.", KdbpCmdPcr
},
181 { "tss", "tss [selector|*descaddr]", "Display the current task state segment, or the one specified by its selector number or descriptor address.", 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("<%08x>:", 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
,
877 /* Display the EFlags */
878 KdbpPrint("EFLAGS 0x%08x ", Tf
->EFlags
);
879 for (i
= 0; i
< 32; i
++)
883 if ((Tf
->EFlags
& (1 << 1)) == 0)
888 KdbpPrint(" IOPL%d", (Tf
->EFlags
>> 12) & 3);
893 else if ((Tf
->EFlags
& (1 << i
)) != 0)
895 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 /* Retrieve the control registers */
915 Cr0
= KdbCurrentTrapFrame
->Cr0
;
916 Cr2
= KdbCurrentTrapFrame
->Cr2
;
917 Cr3
= KdbCurrentTrapFrame
->Cr3
;
918 Cr4
= KdbCurrentTrapFrame
->Cr4
;
920 /* Retrieve the descriptor table and task segment registers */
921 Ke386GetGlobalDescriptorTable(&Gdtr
.Limit
);
922 Ldtr
= Ke386GetLocalDescriptorTable();
926 /* Display the control registers */
927 KdbpPrint("CR0 0x%08x ", Cr0
);
928 for (i
= 0; i
< 32; i
++)
933 if ((Cr0
& (1 << i
)) != 0)
934 KdbpPrint(Cr0Bits
[i
]);
938 KdbpPrint("CR2 0x%08x\n", Cr2
);
939 KdbpPrint("CR3 0x%08x Pagedir-Base 0x%08x %s%s\n", Cr3
, (Cr3
& 0xfffff000),
940 (Cr3
& (1 << 3)) ? " PWT" : "", (Cr3
& (1 << 4)) ? " PCD" : "" );
941 KdbpPrint("CR4 0x%08x ", Cr4
);
942 for (i
= 0; i
< 32; i
++)
947 if ((Cr4
& (1 << i
)) != 0)
948 KdbpPrint(Cr4Bits
[i
]);
952 /* Display the descriptor table and task segment registers */
953 KdbpPrint("GDTR Base 0x%08x Size 0x%04x\n", Gdtr
.Base
, Gdtr
.Limit
);
954 KdbpPrint("LDTR 0x%04x\n", Ldtr
);
955 KdbpPrint("IDTR Base 0x%08x Size 0x%04x\n", Idtr
.Base
, Idtr
.Limit
);
956 KdbpPrint("TR 0x%04x\n", Tr
);
958 else if (Argv
[0][0] == 's') /* sregs */
960 KdbpPrint("CS 0x%04x Index 0x%04x %cDT RPL%d\n",
961 Tf
->SegCs
& 0xffff, (Tf
->SegCs
& 0xffff) >> 3,
962 (Tf
->SegCs
& (1 << 2)) ? 'L' : 'G', Tf
->SegCs
& 3);
963 KdbpPrint("DS 0x%04x Index 0x%04x %cDT RPL%d\n",
964 Tf
->SegDs
, Tf
->SegDs
>> 3, (Tf
->SegDs
& (1 << 2)) ? 'L' : 'G', Tf
->SegDs
& 3);
965 KdbpPrint("ES 0x%04x Index 0x%04x %cDT RPL%d\n",
966 Tf
->SegEs
, Tf
->SegEs
>> 3, (Tf
->SegEs
& (1 << 2)) ? 'L' : 'G', Tf
->SegEs
& 3);
967 KdbpPrint("FS 0x%04x Index 0x%04x %cDT RPL%d\n",
968 Tf
->SegFs
, Tf
->SegFs
>> 3, (Tf
->SegFs
& (1 << 2)) ? 'L' : 'G', Tf
->SegFs
& 3);
969 KdbpPrint("GS 0x%04x Index 0x%04x %cDT RPL%d\n",
970 Tf
->SegGs
, Tf
->SegGs
>> 3, (Tf
->SegGs
& (1 << 2)) ? 'L' : 'G', Tf
->SegGs
& 3);
971 KdbpPrint("SS 0x%04x Index 0x%04x %cDT RPL%d\n",
972 Tf
->HardwareSegSs
, Tf
->HardwareSegSs
>> 3, (Tf
->HardwareSegSs
& (1 << 2)) ? 'L' : 'G', Tf
->HardwareSegSs
& 3);
976 ASSERT(Argv
[0][0] == 'd');
977 KdbpPrint("DR0 0x%08x\n"
983 Tf
->Dr0
, Tf
->Dr1
, Tf
->Dr2
, Tf
->Dr3
,
992 IN USHORT TssSelector
,
993 OUT PULONG pType OPTIONAL
,
994 IN PKDESCRIPTOR pGdtr OPTIONAL
)
1000 /* Retrieve the Global Descriptor Table (user-provided or system) */
1004 Ke386GetGlobalDescriptorTable(&Gdtr
.Limit
);
1007 if ((TssSelector
& (sizeof(KGDTENTRY
) - 1)) ||
1008 (TssSelector
< sizeof(KGDTENTRY
)) ||
1009 (TssSelector
+ sizeof(KGDTENTRY
) - 1 > Gdtr
.Limit
))
1014 /* Retrieve the descriptor */
1015 if (!NT_SUCCESS(KdbpSafeReadMemory(&Desc
,
1016 (PVOID
)(Gdtr
.Base
+ TssSelector
),
1017 sizeof(KGDTENTRY
))))
1022 /* Check for TSS32(Avl) or TSS32(Busy) */
1023 if (Desc
.HighWord
.Bits
.Type
!= 9 && Desc
.HighWord
.Bits
.Type
!= 11)
1027 if (pType
) *pType
= Desc
.HighWord
.Bits
.Type
;
1029 Tss
= (PKTSS
)(ULONG_PTR
)(Desc
.BaseLow
|
1030 Desc
.HighWord
.Bytes
.BaseMid
<< 16 |
1031 Desc
.HighWord
.Bytes
.BaseHi
<< 24);
1037 KdbpTrapFrameFromPrevTss(
1038 PKTRAP_FRAME TrapFrame
)
1046 Ke386GetGlobalDescriptorTable(&Gdtr
.Limit
);
1049 if ((Sel
& (sizeof(KGDTENTRY
) - 1)) ||
1050 (Sel
< sizeof(KGDTENTRY
)) ||
1051 (Sel
+ sizeof(KGDTENTRY
) - 1 > Gdtr
.Limit
))
1054 if (!NT_SUCCESS(KdbpSafeReadMemory(&Desc
,
1055 (PVOID
)(Gdtr
.Base
+ Sel
),
1056 sizeof(KGDTENTRY
))))
1059 if (Desc
.HighWord
.Bits
.Type
!= 0xB)
1062 Tss
= (PKTSS
)(ULONG_PTR
)(Desc
.BaseLow
|
1063 Desc
.HighWord
.Bytes
.BaseMid
<< 16 |
1064 Desc
.HighWord
.Bytes
.BaseHi
<< 24);
1066 if (!NT_SUCCESS(KdbpSafeReadMemory(&Sel
,
1067 (PVOID
)&Tss
->Backlink
,
1071 if ((Sel
& (sizeof(KGDTENTRY
) - 1)) ||
1072 (Sel
< sizeof(KGDTENTRY
)) ||
1073 (Sel
+ sizeof(KGDTENTRY
) - 1 > Gdtr
.Limit
))
1076 if (!NT_SUCCESS(KdbpSafeReadMemory(&Desc
,
1077 (PVOID
)(Gdtr
.Base
+ Sel
),
1078 sizeof(KGDTENTRY
))))
1081 if (Desc
.HighWord
.Bits
.Type
!= 0xB)
1084 Tss
= (PKTSS
)(ULONG_PTR
)(Desc
.BaseLow
|
1085 Desc
.HighWord
.Bytes
.BaseMid
<< 16 |
1086 Desc
.HighWord
.Bytes
.BaseHi
<< 24);
1088 if (!NT_SUCCESS(KdbpSafeReadMemory(&Eip
,
1090 sizeof(ULONG_PTR
))))
1093 if (!NT_SUCCESS(KdbpSafeReadMemory(&Ebp
,
1095 sizeof(ULONG_PTR
))))
1098 TrapFrame
->Eip
= Eip
;
1099 TrapFrame
->Ebp
= Ebp
;
1103 VOID __cdecl
KiTrap02(VOID
);
1104 VOID FASTCALL
KiTrap03Handler(IN PKTRAP_FRAME
);
1105 VOID __cdecl
KiTrap08(VOID
);
1106 VOID __cdecl
KiTrap09(VOID
);
1109 KdbpInNmiOrDoubleFaultHandler(
1112 return (Address
> (ULONG_PTR
)KiTrap02
&& Address
< (ULONG_PTR
)KiTrap03Handler
) ||
1113 (Address
> (ULONG_PTR
)KiTrap08
&& Address
< (ULONG_PTR
)KiTrap09
);
1116 /*!\brief Displays a backtrace.
1124 ULONGLONG Result
= 0;
1125 ULONG_PTR Frame
= KdbCurrentTrapFrame
->Tf
.Ebp
;
1127 KTRAP_FRAME TrapFrame
;
1131 /* Check for [L count] part */
1134 if (strcmp(Argv
[Argc
-2], "L") == 0)
1136 ul
= strtoul(Argv
[Argc
-1], NULL
, 0);
1142 else if (Argv
[Argc
-1][0] == 'L')
1144 ul
= strtoul(Argv
[Argc
-1] + 1, NULL
, 0);
1151 /* Put the remaining arguments back together */
1153 for (ul
= 1; ul
< Argc
; ul
++)
1155 Argv
[ul
][strlen(Argv
[ul
])] = ' ';
1160 /* Check if frame addr or thread id is given. */
1163 if (Argv
[1][0] == '*')
1167 /* Evaluate the expression */
1168 if (!KdbpEvaluateExpression(Argv
[1], sizeof("kdb:> ")-1 + (Argv
[1]-Argv
[0]), &Result
))
1171 if (Result
> (ULONGLONG
)(~((ULONG_PTR
)0)))
1172 KdbpPrint("Warning: Address %I64x is beeing truncated\n",Result
);
1174 Frame
= (ULONG_PTR
)Result
;
1178 KdbpPrint("Thread backtrace not supported yet!\n");
1184 KdbpPrint("Eip:\n");
1186 /* Try printing the function at EIP */
1187 if (!KdbSymPrintAddress((PVOID
)KdbCurrentTrapFrame
->Tf
.Eip
, &KdbCurrentTrapFrame
->Tf
))
1188 KdbpPrint("<%08x>\n", KdbCurrentTrapFrame
->Tf
.Eip
);
1193 TrapFrame
= KdbCurrentTrapFrame
->Tf
;
1194 KdbpPrint("Frames:\n");
1198 BOOLEAN GotNextFrame
;
1203 if (!NT_SUCCESS(KdbpSafeReadMemory(&Address
, (PVOID
)(Frame
+ sizeof(ULONG_PTR
)), sizeof (ULONG_PTR
))))
1205 KdbpPrint("Couldn't access memory at 0x%p!\n", Frame
+ sizeof(ULONG_PTR
));
1209 if ((GotNextFrame
= NT_SUCCESS(KdbpSafeReadMemory(&Frame
, (PVOID
)Frame
, sizeof (ULONG_PTR
)))))
1210 TrapFrame
.Ebp
= Frame
;
1212 /* Print the location of the call instruction */
1213 if (!KdbSymPrintAddress((PVOID
)(Address
- 5), &TrapFrame
))
1214 KdbpPrint("<%08x>\n", Address
);
1218 if (KdbOutputAborted
) break;
1223 if (KdbpInNmiOrDoubleFaultHandler(Address
))
1225 if ((GotNextFrame
= KdbpTrapFrameFromPrevTss(&TrapFrame
)))
1227 Address
= TrapFrame
.Eip
;
1228 Frame
= TrapFrame
.Ebp
;
1230 if (!KdbSymPrintAddress((PVOID
)Address
, &TrapFrame
))
1231 KdbpPrint("<%08x>\n", Address
);
1239 KdbpPrint("Couldn't access memory at 0x%p!\n", Frame
);
1247 /*!\brief Continues execution of the system/leaves KDB.
1254 /* Exit the main loop */
1258 /*!\brief Continues execution of the system/leaves KDB.
1269 Count
= strtoul(Argv
[1], NULL
, 0);
1272 KdbpPrint("%s: Integer argument required\n", Argv
[0]);
1277 if (Argv
[0][0] == 'n')
1278 KdbSingleStepOver
= TRUE
;
1280 KdbSingleStepOver
= FALSE
;
1282 /* Set the number of single steps and return to the interrupted code. */
1283 KdbNumSingleSteps
= Count
;
1288 /*!\brief Lists breakpoints.
1291 KdbpCmdBreakPointList(
1296 ULONG_PTR Address
= 0;
1297 KDB_BREAKPOINT_TYPE Type
= 0;
1298 KDB_ACCESS_TYPE AccessType
= 0;
1301 BOOLEAN Enabled
= FALSE
;
1302 BOOLEAN Global
= FALSE
;
1303 PEPROCESS Process
= NULL
;
1304 PCHAR str1
, str2
, ConditionExpr
, GlobalOrLocal
;
1307 l
= KdbpGetNextBreakPointNr(0);
1310 KdbpPrint("No breakpoints.\n");
1314 KdbpPrint("Breakpoints:\n");
1317 if (!KdbpGetBreakPointInfo(l
, &Address
, &Type
, &Size
, &AccessType
, &DebugReg
,
1318 &Enabled
, &Global
, &Process
, &ConditionExpr
))
1323 if (l
== KdbLastBreakPointNr
)
1336 GlobalOrLocal
= " global";
1340 GlobalOrLocal
= Buffer
;
1341 sprintf(Buffer
, " PID 0x%08lx",
1342 (ULONG
)(Process
? Process
->UniqueProcessId
: INVALID_HANDLE_VALUE
));
1345 if (Type
== KdbBreakPointSoftware
|| Type
== KdbBreakPointTemporary
)
1347 KdbpPrint(" %s%03d BPX 0x%08x%s%s%s%s%s\n",
1349 Enabled
? "" : " disabled",
1351 ConditionExpr
? " IF " : "",
1352 ConditionExpr
? ConditionExpr
: "",
1355 else if (Type
== KdbBreakPointHardware
)
1359 KdbpPrint(" %s%03d BPM 0x%08x %-5s %-5s disabled%s%s%s%s\n", str1
, l
, Address
,
1360 KDB_ACCESS_TYPE_TO_STRING(AccessType
),
1361 Size
== 1 ? "byte" : (Size
== 2 ? "word" : "dword"),
1363 ConditionExpr
? " IF " : "",
1364 ConditionExpr
? ConditionExpr
: "",
1369 KdbpPrint(" %s%03d BPM 0x%08x %-5s %-5s DR%d%s%s%s%s\n", str1
, l
, Address
,
1370 KDB_ACCESS_TYPE_TO_STRING(AccessType
),
1371 Size
== 1 ? "byte" : (Size
== 2 ? "word" : "dword"),
1374 ConditionExpr
? " IF " : "",
1375 ConditionExpr
? ConditionExpr
: "",
1380 while ((l
= KdbpGetNextBreakPointNr(l
+1)) >= 0);
1385 /*!\brief Enables, disables or clears a breakpoint.
1388 KdbpCmdEnableDisableClearBreakPoint(
1397 KdbpPrint("%s: argument required\n", Argv
[0]);
1402 BreakPointNr
= strtoul(Argv
[1], &pend
, 0);
1403 if (pend
== Argv
[1] || *pend
!= '\0')
1405 KdbpPrint("%s: integer argument required\n", Argv
[0]);
1409 if (Argv
[0][1] == 'e') /* enable */
1411 KdbpEnableBreakPoint(BreakPointNr
, NULL
);
1413 else if (Argv
[0][1] == 'd') /* disable */
1415 KdbpDisableBreakPoint(BreakPointNr
, NULL
);
1419 ASSERT(Argv
[0][1] == 'c');
1420 KdbpDeleteBreakPoint(BreakPointNr
, NULL
);
1426 /*!\brief Sets a software or hardware (memory) breakpoint at the given address.
1429 KdbpCmdBreakPoint(ULONG Argc
, PCHAR Argv
[])
1431 ULONGLONG Result
= 0;
1433 KDB_BREAKPOINT_TYPE Type
;
1435 KDB_ACCESS_TYPE AccessType
= 0;
1436 ULONG AddressArgIndex
, i
;
1437 LONG ConditionArgIndex
;
1438 BOOLEAN Global
= TRUE
;
1440 if (Argv
[0][2] == 'x') /* software breakpoint */
1444 KdbpPrint("bpx: Address argument required.\n");
1448 AddressArgIndex
= 1;
1449 Type
= KdbBreakPointSoftware
;
1451 else /* memory breakpoint */
1453 ASSERT(Argv
[0][2] == 'm');
1457 KdbpPrint("bpm: Access type argument required (one of r, w, rw, x)\n");
1461 if (_stricmp(Argv
[1], "x") == 0)
1462 AccessType
= KdbAccessExec
;
1463 else if (_stricmp(Argv
[1], "r") == 0)
1464 AccessType
= KdbAccessRead
;
1465 else if (_stricmp(Argv
[1], "w") == 0)
1466 AccessType
= KdbAccessWrite
;
1467 else if (_stricmp(Argv
[1], "rw") == 0)
1468 AccessType
= KdbAccessReadWrite
;
1471 KdbpPrint("bpm: Unknown access type '%s'\n", Argv
[1]);
1477 KdbpPrint("bpm: %s argument required.\n", AccessType
== KdbAccessExec
? "Address" : "Memory size");
1481 AddressArgIndex
= 3;
1482 if (_stricmp(Argv
[2], "byte") == 0)
1484 else if (_stricmp(Argv
[2], "word") == 0)
1486 else if (_stricmp(Argv
[2], "dword") == 0)
1488 else if (AccessType
== KdbAccessExec
)
1495 KdbpPrint("bpm: Unknown memory size '%s'\n", Argv
[2]);
1499 if (Argc
<= AddressArgIndex
)
1501 KdbpPrint("bpm: Address argument required.\n");
1505 Type
= KdbBreakPointHardware
;
1508 /* Put the arguments back together */
1509 ConditionArgIndex
= -1;
1510 for (i
= AddressArgIndex
; i
< (Argc
-1); i
++)
1512 if (strcmp(Argv
[i
+1], "IF") == 0) /* IF found */
1514 ConditionArgIndex
= i
+ 2;
1515 if ((ULONG
)ConditionArgIndex
>= Argc
)
1517 KdbpPrint("%s: IF requires condition expression.\n", Argv
[0]);
1521 for (i
= ConditionArgIndex
; i
< (Argc
-1); i
++)
1522 Argv
[i
][strlen(Argv
[i
])] = ' ';
1527 Argv
[i
][strlen(Argv
[i
])] = ' ';
1530 /* Evaluate the address expression */
1531 if (!KdbpEvaluateExpression(Argv
[AddressArgIndex
],
1532 sizeof("kdb:> ")-1 + (Argv
[AddressArgIndex
]-Argv
[0]),
1538 if (Result
> (ULONGLONG
)(~((ULONG_PTR
)0)))
1539 KdbpPrint("%s: Warning: Address %I64x is beeing truncated\n", Argv
[0],Result
);
1541 Address
= (ULONG_PTR
)Result
;
1543 KdbpInsertBreakPoint(Address
, Type
, Size
, AccessType
,
1544 (ConditionArgIndex
< 0) ? NULL
: Argv
[ConditionArgIndex
],
1550 /*!\brief Lists threads or switches to another thread context.
1558 PETHREAD Thread
= NULL
;
1559 PEPROCESS Process
= NULL
;
1560 BOOLEAN ReferencedThread
= FALSE
, ReferencedProcess
= FALSE
;
1565 PCHAR State
, pend
, str1
, str2
;
1566 static const PCHAR ThreadStateToString
[DeferredReady
+1] =
1568 "Initialized", "Ready", "Running",
1569 "Standby", "Terminated", "Waiting",
1570 "Transition", "DeferredReady"
1573 ASSERT(KdbCurrentProcess
);
1575 if (Argc
>= 2 && _stricmp(Argv
[1], "list") == 0)
1577 Process
= KdbCurrentProcess
;
1581 ul
= strtoul(Argv
[2], &pend
, 0);
1582 if (Argv
[2] == pend
)
1584 KdbpPrint("thread: '%s' is not a valid process id!\n", Argv
[2]);
1588 if (!NT_SUCCESS(PsLookupProcessByProcessId((PVOID
)ul
, &Process
)))
1590 KdbpPrint("thread: Invalid process id!\n");
1594 /* Remember our reference */
1595 ReferencedProcess
= TRUE
;
1598 Entry
= Process
->ThreadListHead
.Flink
;
1599 if (Entry
== &Process
->ThreadListHead
)
1602 KdbpPrint("No threads in process 0x%08x!\n", ul
);
1604 KdbpPrint("No threads in current process!\n");
1606 if (ReferencedProcess
)
1607 ObDereferenceObject(Process
);
1612 KdbpPrint(" TID State Prior. Affinity EBP EIP\n");
1615 Thread
= CONTAINING_RECORD(Entry
, ETHREAD
, ThreadListEntry
);
1617 if (Thread
== KdbCurrentThread
)
1628 if (!Thread
->Tcb
.InitialStack
)
1630 /* Thread has no kernel stack (probably terminated) */
1634 else if (Thread
->Tcb
.TrapFrame
)
1636 if (Thread
->Tcb
.TrapFrame
->PreviousPreviousMode
== KernelMode
)
1637 Esp
= (PULONG
)Thread
->Tcb
.TrapFrame
->TempEsp
;
1639 Esp
= (PULONG
)Thread
->Tcb
.TrapFrame
->HardwareEsp
;
1641 Ebp
= (PULONG
)Thread
->Tcb
.TrapFrame
->Ebp
;
1642 Eip
= Thread
->Tcb
.TrapFrame
->Eip
;
1646 Esp
= (PULONG
)Thread
->Tcb
.KernelStack
;
1647 Ebp
= (PULONG
)Esp
[4];
1650 if (Ebp
) /* FIXME: Should we attach to the process to read Ebp[1]? */
1651 KdbpSafeReadMemory(&Eip
, Ebp
+ 1, sizeof (Eip
));
1654 if (Thread
->Tcb
.State
< (DeferredReady
+ 1))
1655 State
= ThreadStateToString
[Thread
->Tcb
.State
];
1659 KdbpPrint(" %s0x%08x %-11s %3d 0x%08x 0x%08x 0x%08x%s\n",
1661 Thread
->Cid
.UniqueThread
,
1663 Thread
->Tcb
.Priority
,
1664 Thread
->Tcb
.Affinity
,
1669 Entry
= Entry
->Flink
;
1671 while (Entry
!= &Process
->ThreadListHead
);
1673 /* Release our reference, if any */
1674 if (ReferencedProcess
)
1675 ObDereferenceObject(Process
);
1677 else if (Argc
>= 2 && _stricmp(Argv
[1], "attach") == 0)
1681 KdbpPrint("thread attach: thread id argument required!\n");
1685 ul
= strtoul(Argv
[2], &pend
, 0);
1686 if (Argv
[2] == pend
)
1688 KdbpPrint("thread attach: '%s' is not a valid thread id!\n", Argv
[2]);
1692 if (!KdbpAttachToThread((PVOID
)ul
))
1697 KdbpPrint("Attached to thread 0x%08x.\n", ul
);
1701 Thread
= KdbCurrentThread
;
1705 ul
= strtoul(Argv
[1], &pend
, 0);
1706 if (Argv
[1] == pend
)
1708 KdbpPrint("thread: '%s' is not a valid thread id!\n", Argv
[1]);
1712 if (!NT_SUCCESS(PsLookupThreadByThreadId((PVOID
)ul
, &Thread
)))
1714 KdbpPrint("thread: Invalid thread id!\n");
1718 /* Remember our reference */
1719 ReferencedThread
= TRUE
;
1722 if (Thread
->Tcb
.State
< (DeferredReady
+ 1))
1723 State
= ThreadStateToString
[Thread
->Tcb
.State
];
1729 " State: %s (0x%x)\n"
1731 " Affinity: 0x%08x\n"
1732 " Initial Stack: 0x%08x\n"
1733 " Stack Limit: 0x%08x\n"
1734 " Stack Base: 0x%08x\n"
1735 " Kernel Stack: 0x%08x\n"
1736 " Trap Frame: 0x%08x\n"
1737 " NPX State: %s (0x%x)\n",
1738 (Argc
< 2) ? "Current Thread:\n" : "",
1739 Thread
->Cid
.UniqueThread
,
1740 State
, Thread
->Tcb
.State
,
1741 Thread
->Tcb
.Priority
,
1742 Thread
->Tcb
.Affinity
,
1743 Thread
->Tcb
.InitialStack
,
1744 Thread
->Tcb
.StackLimit
,
1745 Thread
->Tcb
.StackBase
,
1746 Thread
->Tcb
.KernelStack
,
1747 Thread
->Tcb
.TrapFrame
,
1748 NPX_STATE_TO_STRING(Thread
->Tcb
.NpxState
), Thread
->Tcb
.NpxState
);
1750 /* Release our reference if we had one */
1751 if (ReferencedThread
)
1752 ObDereferenceObject(Thread
);
1758 /*!\brief Lists processes or switches to another process context.
1767 BOOLEAN ReferencedProcess
= FALSE
;
1768 PCHAR State
, pend
, str1
, str2
;
1770 extern LIST_ENTRY PsActiveProcessHead
;
1772 if (Argc
>= 2 && _stricmp(Argv
[1], "list") == 0)
1774 Entry
= PsActiveProcessHead
.Flink
;
1775 if (!Entry
|| Entry
== &PsActiveProcessHead
)
1777 KdbpPrint("No processes in the system!\n");
1781 KdbpPrint(" PID State Filename\n");
1784 Process
= CONTAINING_RECORD(Entry
, EPROCESS
, ActiveProcessLinks
);
1786 if (Process
== KdbCurrentProcess
)
1797 State
= ((Process
->Pcb
.State
== ProcessInMemory
) ? "In Memory" :
1798 ((Process
->Pcb
.State
== ProcessOutOfMemory
) ? "Out of Memory" : "In Transition"));
1800 KdbpPrint(" %s0x%08x %-10s %s%s\n",
1802 Process
->UniqueProcessId
,
1804 Process
->ImageFileName
,
1807 Entry
= Entry
->Flink
;
1809 while(Entry
!= &PsActiveProcessHead
);
1811 else if (Argc
>= 2 && _stricmp(Argv
[1], "attach") == 0)
1815 KdbpPrint("process attach: process id argument required!\n");
1819 ul
= strtoul(Argv
[2], &pend
, 0);
1820 if (Argv
[2] == pend
)
1822 KdbpPrint("process attach: '%s' is not a valid process id!\n", Argv
[2]);
1826 if (!KdbpAttachToProcess((PVOID
)ul
))
1831 KdbpPrint("Attached to process 0x%08x, thread 0x%08x.\n", (ULONG
)ul
,
1832 (ULONG
)KdbCurrentThread
->Cid
.UniqueThread
);
1836 Process
= KdbCurrentProcess
;
1840 ul
= strtoul(Argv
[1], &pend
, 0);
1841 if (Argv
[1] == pend
)
1843 KdbpPrint("proc: '%s' is not a valid process id!\n", Argv
[1]);
1847 if (!NT_SUCCESS(PsLookupProcessByProcessId((PVOID
)ul
, &Process
)))
1849 KdbpPrint("proc: Invalid process id!\n");
1853 /* Remember our reference */
1854 ReferencedProcess
= TRUE
;
1857 State
= ((Process
->Pcb
.State
== ProcessInMemory
) ? "In Memory" :
1858 ((Process
->Pcb
.State
== ProcessOutOfMemory
) ? "Out of Memory" : "In Transition"));
1861 " State: %s (0x%x)\n"
1862 " Image Filename: %s\n",
1863 (Argc
< 2) ? "Current process:\n" : "",
1864 Process
->UniqueProcessId
,
1865 State
, Process
->Pcb
.State
,
1866 Process
->ImageFileName
);
1868 /* Release our reference, if any */
1869 if (ReferencedProcess
)
1870 ObDereferenceObject(Process
);
1876 /*!\brief Lists loaded modules or the one containing the specified address.
1883 ULONGLONG Result
= 0;
1885 PLDR_DATA_TABLE_ENTRY LdrEntry
;
1886 BOOLEAN DisplayOnlyOneModule
= FALSE
;
1891 /* Put the arguments back together */
1894 Argv
[Argc
][strlen(Argv
[Argc
])] = ' ';
1896 /* Evaluate the expression */
1897 if (!KdbpEvaluateExpression(Argv
[1], sizeof("kdb:> ")-1 + (Argv
[1]-Argv
[0]), &Result
))
1902 if (Result
> (ULONGLONG
)(~((ULONG_PTR
)0)))
1903 KdbpPrint("%s: Warning: Address %I64x is beeing truncated\n", Argv
[0],Result
);
1905 Address
= (ULONG_PTR
)Result
;
1907 if (!KdbpSymFindModule((PVOID
)Address
, NULL
, -1, &LdrEntry
))
1909 KdbpPrint("No module containing address 0x%p found!\n", Address
);
1913 DisplayOnlyOneModule
= TRUE
;
1917 if (!KdbpSymFindModule(NULL
, NULL
, 0, &LdrEntry
))
1919 ULONG_PTR ntoskrnlBase
= ((ULONG_PTR
)KdbpCmdMod
) & 0xfff00000;
1920 KdbpPrint(" Base Size Name\n");
1921 KdbpPrint(" %08x %08x %s\n", ntoskrnlBase
, 0, "ntoskrnl.exe");
1928 KdbpPrint(" Base Size Name\n");
1931 KdbpPrint(" %08x %08x %wZ\n", LdrEntry
->DllBase
, LdrEntry
->SizeOfImage
, &LdrEntry
->BaseDllName
);
1933 if(DisplayOnlyOneModule
|| !KdbpSymFindModule(NULL
, NULL
, i
++, &LdrEntry
))
1940 /*!\brief Displays GDT, LDT or IDT.
1957 if (Argv
[0][0] == 'i')
1964 KdbpPrint("Interrupt descriptor table is empty.\n");
1968 KdbpPrint("IDT Base: 0x%08x Limit: 0x%04x\n", Reg
.Base
, Reg
.Limit
);
1969 KdbpPrint(" Idx Type Seg. Sel. Offset DPL\n");
1971 for (i
= 0; (i
+ sizeof(SegDesc
) - 1) <= Reg
.Limit
; i
+= 8)
1973 if (!NT_SUCCESS(KdbpSafeReadMemory(SegDesc
, (PVOID
)(Reg
.Base
+ i
), sizeof(SegDesc
))))
1975 KdbpPrint("Couldn't access memory at 0x%08x!\n", Reg
.Base
+ i
);
1979 Dpl
= ((SegDesc
[1] >> 13) & 3);
1980 if ((SegDesc
[1] & 0x1f00) == 0x0500) /* Task gate */
1981 SegType
= "TASKGATE";
1982 else if ((SegDesc
[1] & 0x1fe0) == 0x0e00) /* 32 bit Interrupt gate */
1983 SegType
= "INTGATE32";
1984 else if ((SegDesc
[1] & 0x1fe0) == 0x0600) /* 16 bit Interrupt gate */
1985 SegType
= "INTGATE16";
1986 else if ((SegDesc
[1] & 0x1fe0) == 0x0f00) /* 32 bit Trap gate */
1987 SegType
= "TRAPGATE32";
1988 else if ((SegDesc
[1] & 0x1fe0) == 0x0700) /* 16 bit Trap gate */
1989 SegType
= "TRAPGATE16";
1991 SegType
= "UNKNOWN";
1993 if ((SegDesc
[1] & (1 << 15)) == 0) /* not present */
1995 KdbpPrint(" %03d %-10s [NP] [NP] %02d\n",
1996 i
/ 8, SegType
, Dpl
);
1998 else if ((SegDesc
[1] & 0x1f00) == 0x0500) /* Task gate */
2000 SegSel
= SegDesc
[0] >> 16;
2001 KdbpPrint(" %03d %-10s 0x%04x %02d\n",
2002 i
/ 8, SegType
, SegSel
, Dpl
);
2006 SegSel
= SegDesc
[0] >> 16;
2007 SegBase
= (SegDesc
[1] & 0xffff0000) | (SegDesc
[0] & 0x0000ffff);
2008 KdbpPrint(" %03d %-10s 0x%04x 0x%08x %02d\n",
2009 i
/ 8, SegType
, SegSel
, SegBase
, Dpl
);
2017 if (Argv
[0][0] == 'g')
2020 Ke386GetGlobalDescriptorTable(&Reg
.Limit
);
2025 ASSERT(Argv
[0][0] == 'l');
2028 Reg
.Limit
= Ke386GetLocalDescriptorTable();
2036 KdbpPrint("%s descriptor table is empty.\n",
2037 Argv
[0][0] == 'g' ? "Global" : "Local");
2041 KdbpPrint("%cDT Base: 0x%08x Limit: 0x%04x\n",
2042 Argv
[0][0] == 'g' ? 'G' : 'L', Reg
.Base
, Reg
.Limit
);
2043 KdbpPrint(" Idx Sel. Type Base Limit DPL Attribs\n");
2045 for (; (i
+ sizeof(SegDesc
) - 1) <= Reg
.Limit
; i
+= 8)
2047 if (!NT_SUCCESS(KdbpSafeReadMemory(SegDesc
, (PVOID
)(Reg
.Base
+ i
), sizeof(SegDesc
))))
2049 KdbpPrint("Couldn't access memory at 0x%08x!\n", Reg
.Base
+ i
);
2053 Dpl
= ((SegDesc
[1] >> 13) & 3);
2054 Type
= ((SegDesc
[1] >> 8) & 0xf);
2056 SegBase
= SegDesc
[0] >> 16;
2057 SegBase
|= (SegDesc
[1] & 0xff) << 16;
2058 SegBase
|= SegDesc
[1] & 0xff000000;
2059 SegLimit
= SegDesc
[0] & 0x0000ffff;
2060 SegLimit
|= (SegDesc
[1] >> 16) & 0xf;
2062 if ((SegDesc
[1] & (1 << 23)) != 0)
2072 if ((SegDesc
[1] & (1 << 12)) == 0) /* System segment */
2076 case 1: SegType
= "TSS16(Avl)"; break;
2077 case 2: SegType
= "LDT"; break;
2078 case 3: SegType
= "TSS16(Busy)"; break;
2079 case 4: SegType
= "CALLGATE16"; break;
2080 case 5: SegType
= "TASKGATE"; break;
2081 case 6: SegType
= "INTGATE16"; break;
2082 case 7: SegType
= "TRAPGATE16"; break;
2083 case 9: SegType
= "TSS32(Avl)"; break;
2084 case 11: SegType
= "TSS32(Busy)"; break;
2085 case 12: SegType
= "CALLGATE32"; break;
2086 case 14: SegType
= "INTGATE32"; break;
2087 case 15: SegType
= "TRAPGATE32"; break;
2088 default: SegType
= "UNKNOWN"; break;
2091 if (!(Type
>= 1 && Type
<= 3) &&
2092 Type
!= 9 && Type
!= 11)
2098 else if ((SegDesc
[1] & (1 << 11)) == 0) /* Data segment */
2100 if ((SegDesc
[1] & (1 << 22)) != 0)
2105 else /* Code segment */
2107 if ((SegDesc
[1] & (1 << 22)) != 0)
2113 if ((SegDesc
[1] & (1 << 15)) == 0) /* Not present */
2115 KdbpPrint(" %03d 0x%04x %-11s [NP] [NP] %02d NP\n",
2116 i
/ 8, i
| Dpl
| ul
, SegType
, Dpl
);
2120 KdbpPrint(" %03d 0x%04x %-11s 0x%08x 0x%08x %02d ",
2121 i
/ 8, i
| Dpl
| ul
, SegType
, SegBase
, SegLimit
, Dpl
);
2123 if ((SegDesc
[1] & (1 << 12)) == 0) /* System segment */
2125 /* FIXME: Display system segment */
2127 else if ((SegDesc
[1] & (1 << 11)) == 0) /* Data segment */
2129 if ((SegDesc
[1] & (1 << 10)) != 0) /* Expand-down */
2132 KdbpPrint((SegDesc
[1] & (1 << 9)) ? " R/W" : " R");
2134 if ((SegDesc
[1] & (1 << 8)) != 0)
2137 else /* Code segment */
2139 if ((SegDesc
[1] & (1 << 10)) != 0) /* Conforming */
2142 KdbpPrint((SegDesc
[1] & (1 << 9)) ? " R/X" : " X");
2144 if ((SegDesc
[1] & (1 << 8)) != 0)
2148 if ((SegDesc
[1] & (1 << 20)) != 0)
2159 /*!\brief Displays the KPCR
2166 PKIPCR Pcr
= (PKIPCR
)KeGetPcr();
2168 KdbpPrint("Current PCR is at 0x%p.\n", Pcr
);
2169 KdbpPrint(" Tib.ExceptionList: 0x%08x\n"
2170 " Tib.StackBase: 0x%08x\n"
2171 " Tib.StackLimit: 0x%08x\n"
2172 " Tib.SubSystemTib: 0x%08x\n"
2173 " Tib.FiberData/Version: 0x%08x\n"
2174 " Tib.ArbitraryUserPointer: 0x%08x\n"
2175 " Tib.Self: 0x%08x\n"
2176 " SelfPcr: 0x%08x\n"
2180 " IrrActive: 0x%08x\n"
2182 " KdVersionBlock: 0x%08x\n"
2186 " MajorVersion: 0x%04x\n"
2187 " MinorVersion: 0x%04x\n"
2188 " SetMember: 0x%08x\n"
2189 " StallScaleFactor: 0x%08x\n"
2191 " L2CacheAssociativity: 0x%02x\n"
2192 " VdmAlert: 0x%08x\n"
2193 " L2CacheSize: 0x%08x\n"
2194 " InterruptMode: 0x%08x\n",
2195 Pcr
->NtTib
.ExceptionList
, Pcr
->NtTib
.StackBase
, Pcr
->NtTib
.StackLimit
,
2196 Pcr
->NtTib
.SubSystemTib
, Pcr
->NtTib
.FiberData
, Pcr
->NtTib
.ArbitraryUserPointer
,
2197 Pcr
->NtTib
.Self
, Pcr
->SelfPcr
, Pcr
->Prcb
, Pcr
->Irql
, Pcr
->IRR
, Pcr
->IrrActive
,
2198 Pcr
->IDR
, Pcr
->KdVersionBlock
, Pcr
->IDT
, Pcr
->GDT
, Pcr
->TSS
,
2199 Pcr
->MajorVersion
, Pcr
->MinorVersion
, Pcr
->SetMember
, Pcr
->StallScaleFactor
,
2200 Pcr
->Number
, Pcr
->SecondLevelCacheAssociativity
,
2201 Pcr
->VdmAlert
, Pcr
->SecondLevelCacheSize
, Pcr
->InterruptMode
);
2206 /*!\brief Displays the TSS
2219 * Specified TSS via its selector [selector] or descriptor address [*descaddr].
2220 * Note that we ignore any other argument values.
2222 PCHAR Param
, pszNext
;
2226 if (Argv
[1][0] == '*')
2229 ulValue
= strtoul(Param
, &pszNext
, 0);
2230 if (pszNext
&& *pszNext
)
2232 KdbpPrint("Invalid TSS specification.\n");
2236 if (Argv
[1][0] == '*')
2238 /* Descriptor specified */
2239 TssSelector
= 0; // Unknown selector!
2240 // TODO: Room for improvement: Find the TSS descriptor
2241 // in the GDT so as to validate it.
2242 Tss
= (PKTSS
)(ULONG_PTR
)ulValue
;
2245 KdbpPrint("Invalid 32-bit TSS descriptor.\n");
2251 /* Selector specified, retrive the corresponding TSS */
2252 TssSelector
= (USHORT
)ulValue
;
2253 Tss
= KdbpRetrieveTss(TssSelector
, NULL
, NULL
);
2256 KdbpPrint("Invalid 32-bit TSS selector.\n");
2264 /* If no TSS was specified, use the current TSS descriptor */
2265 TssSelector
= Ke386GetTr();
2266 Tss
= KeGetPcr()->TSS
;
2267 // NOTE: If everything works OK, Tss is the current TSS corresponding to the TR selector.
2270 KdbpPrint("%s TSS 0x%04x is at 0x%p.\n",
2271 (Tss
== KeGetPcr()->TSS
) ? "Current" : "Specified", TssSelector
, Tss
);
2272 KdbpPrint(" Backlink: 0x%04x\n"
2273 " Ss0:Esp0: 0x%04x:0x%08x\n"
2274 // NOTE: Ss1:Esp1 and Ss2:Esp2: are in the NotUsed1 field.
2294 " IoMapBase: 0x%04x\n",
2295 Tss
->Backlink
, Tss
->Ss0
, Tss
->Esp0
, Tss
->CR3
, Tss
->EFlags
,
2296 Tss
->Eax
, Tss
->Ebx
, Tss
->Ecx
, Tss
->Edx
, Tss
->Esi
, Tss
->Edi
,
2297 Tss
->Eip
, Tss
->Esp
, Tss
->Ebp
,
2298 Tss
->Cs
, Tss
->Ss
, Tss
->Ds
, Tss
->Es
, Tss
->Fs
, Tss
->Gs
,
2299 Tss
->LDT
, Tss
->Flags
, Tss
->IoMapBase
);
2304 /*!\brief Bugchecks the system.
2311 /* Set the flag and quit looping */
2312 KdbpBugCheckRequested
= TRUE
;
2321 /* Reboot immediately (we do not return) */
2322 HalReturnToFirmware(HalRebootRoutine
);
2330 IN ULONG BufLength
);
2332 /*!\brief Display debug messages on screen, with paging.
2334 * Keys for per-page view: Home, End, PageUp, Arrow Up, PageDown,
2335 * all others are as PageDown.
2344 KdbpIsInDmesgMode
= TRUE
; /* Toggle logging flag */
2345 if (!KdpDmesgBuffer
)
2347 KdbpPrint("Dmesg: error, buffer is not allocated! /DEBUGPORT=SCREEN kernel param required for dmesg.\n");
2351 KdbpPrint("*** Dmesg *** TotalWritten=%lu, BufferSize=%lu, CurrentPosition=%lu\n",
2352 KdbDmesgTotalWritten
, KdpDmesgBufferSize
, KdpDmesgCurrentPosition
);
2354 /* Pass data to the pager */
2355 end
= KdpDmesgCurrentPosition
;
2356 beg
= (end
+ KdpDmesgFreeBytes
) % KdpDmesgBufferSize
;
2358 /* No roll-overs, and overwritten=lost bytes */
2359 if (KdbDmesgTotalWritten
<= KdpDmesgBufferSize
)
2361 /* Show buffer (KdpDmesgBuffer + beg, num) */
2362 KdbpPager(KdpDmesgBuffer
, KdpDmesgCurrentPosition
);
2366 /* Show 2 buffers: (KdpDmesgBuffer + beg, KdpDmesgBufferSize - beg)
2367 * and: (KdpDmesgBuffer, end) */
2368 KdbpPager(KdpDmesgBuffer
+ beg
, KdpDmesgBufferSize
- beg
);
2369 KdbpPrint("*** Dmesg: buffer rollup ***\n");
2370 KdbpPager(KdpDmesgBuffer
, end
);
2372 KdbpPrint("*** Dmesg: end of output ***\n");
2374 KdbpIsInDmesgMode
= FALSE
; /* Toggle logging flag */
2379 /*!\brief Sets or displays a config variables value.
2389 KDB_ENTER_CONDITION ConditionFirst
= KdbDoNotEnter
;
2390 KDB_ENTER_CONDITION ConditionLast
= KdbDoNotEnter
;
2392 static const PCHAR ExceptionNames
[21] =
2394 "ZERODEVIDE", "DEBUGTRAP", "NMI", "INT3", "OVERFLOW", "BOUND", "INVALIDOP",
2395 "NOMATHCOP", "DOUBLEFAULT", "RESERVED(9)", "INVALIDTSS", "SEGMENTNOTPRESENT",
2396 "STACKFAULT", "GPF", "PAGEFAULT", "RESERVED(15)", "MATHFAULT", "ALIGNMENTCHECK",
2397 "MACHINECHECK", "SIMDFAULT", "OTHERS"
2402 KdbpPrint("Available settings:\n");
2403 KdbpPrint(" syntax [intel|at&t]\n");
2404 KdbpPrint(" condition [exception|*] [first|last] [never|always|kmode|umode]\n");
2405 KdbpPrint(" break_on_module_load [true|false]\n");
2407 else if (strcmp(Argv
[1], "syntax") == 0)
2411 KdbpPrint("syntax = %s\n", KdbUseIntelSyntax
? "intel" : "at&t");
2415 if (_stricmp(Argv
[2], "intel") == 0)
2416 KdbUseIntelSyntax
= TRUE
;
2417 else if (_stricmp(Argv
[2], "at&t") == 0)
2418 KdbUseIntelSyntax
= FALSE
;
2420 KdbpPrint("Unknown syntax '%s'.\n", Argv
[2]);
2423 else if (strcmp(Argv
[1], "condition") == 0)
2427 KdbpPrint("Conditions: (First) (Last)\n");
2428 for (l
= 0; l
< RTL_NUMBER_OF(ExceptionNames
) - 1; l
++)
2430 if (!ExceptionNames
[l
])
2433 if (!KdbpGetEnterCondition(l
, TRUE
, &ConditionFirst
))
2436 if (!KdbpGetEnterCondition(l
, FALSE
, &ConditionLast
))
2439 KdbpPrint(" #%02d %-20s %-8s %-8s\n", l
, ExceptionNames
[l
],
2440 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst
),
2441 KDB_ENTER_CONDITION_TO_STRING(ConditionLast
));
2444 ASSERT(l
== (RTL_NUMBER_OF(ExceptionNames
) - 1));
2445 KdbpPrint(" %-20s %-8s %-8s\n", ExceptionNames
[l
],
2446 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst
),
2447 KDB_ENTER_CONDITION_TO_STRING(ConditionLast
));
2451 if (Argc
>= 5 && strcmp(Argv
[2], "*") == 0) /* Allow * only when setting condition */
2457 l
= strtoul(Argv
[2], &pend
, 0);
2459 if (Argv
[2] == pend
)
2461 for (l
= 0; l
< RTL_NUMBER_OF(ExceptionNames
); l
++)
2463 if (!ExceptionNames
[l
])
2466 if (_stricmp(ExceptionNames
[l
], Argv
[2]) == 0)
2471 if (l
>= RTL_NUMBER_OF(ExceptionNames
))
2473 KdbpPrint("Unknown exception '%s'.\n", Argv
[2]);
2480 if (_stricmp(Argv
[3], "first") == 0)
2482 else if (_stricmp(Argv
[3], "last") == 0)
2486 KdbpPrint("set condition: second argument must be 'first' or 'last'\n");
2490 if (_stricmp(Argv
[4], "never") == 0)
2491 ConditionFirst
= KdbDoNotEnter
;
2492 else if (_stricmp(Argv
[4], "always") == 0)
2493 ConditionFirst
= KdbEnterAlways
;
2494 else if (_stricmp(Argv
[4], "umode") == 0)
2495 ConditionFirst
= KdbEnterFromUmode
;
2496 else if (_stricmp(Argv
[4], "kmode") == 0)
2497 ConditionFirst
= KdbEnterFromKmode
;
2500 KdbpPrint("set condition: third argument must be 'never', 'always', 'umode' or 'kmode'\n");
2504 if (!KdbpSetEnterCondition(l
, First
, ConditionFirst
))
2507 KdbpPrint("Couldn't change condition for exception #%02d\n", l
);
2509 KdbpPrint("Couldn't change condition for all exceptions\n", l
);
2512 else /* Argc >= 3 */
2514 if (!KdbpGetEnterCondition(l
, TRUE
, &ConditionFirst
))
2517 if (!KdbpGetEnterCondition(l
, FALSE
, &ConditionLast
))
2520 if (l
< (RTL_NUMBER_OF(ExceptionNames
) - 1))
2522 KdbpPrint("Condition for exception #%02d (%s): FirstChance %s LastChance %s\n",
2523 l
, ExceptionNames
[l
],
2524 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst
),
2525 KDB_ENTER_CONDITION_TO_STRING(ConditionLast
));
2529 KdbpPrint("Condition for all other exceptions: FirstChance %s LastChance %s\n",
2530 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst
),
2531 KDB_ENTER_CONDITION_TO_STRING(ConditionLast
));
2536 else if (strcmp(Argv
[1], "break_on_module_load") == 0)
2539 KdbpPrint("break_on_module_load = %s\n", KdbBreakOnModuleLoad
? "enabled" : "disabled");
2542 if (_stricmp(Argv
[2], "enable") == 0 || _stricmp(Argv
[2], "enabled") == 0 || _stricmp(Argv
[2], "true") == 0)
2543 KdbBreakOnModuleLoad
= TRUE
;
2544 else if (_stricmp(Argv
[2], "disable") == 0 || _stricmp(Argv
[2], "disabled") == 0 || _stricmp(Argv
[2], "false") == 0)
2545 KdbBreakOnModuleLoad
= FALSE
;
2547 KdbpPrint("Unknown setting '%s'.\n", Argv
[2]);
2552 KdbpPrint("Unknown setting '%s'.\n", Argv
[1]);
2558 /*!\brief Displays help screen.
2567 KdbpPrint("Kernel debugger commands:\n");
2568 for (i
= 0; i
< RTL_NUMBER_OF(KdbDebuggerCommands
); i
++)
2570 if (!KdbDebuggerCommands
[i
].Syntax
) /* Command group */
2575 KdbpPrint("\x1b[7m* %s:\x1b[0m\n", KdbDebuggerCommands
[i
].Help
);
2579 KdbpPrint(" %-20s - %s\n",
2580 KdbDebuggerCommands
[i
].Syntax
,
2581 KdbDebuggerCommands
[i
].Help
);
2587 /*!\brief Prints the given string with printf-like formatting.
2589 * \param Format Format of the string/arguments.
2590 * \param ... Variable number of arguments matching the format specified in \a Format.
2592 * \note Doesn't correctly handle \\t and terminal escape sequences when calculating the
2593 * number of lines required to print a single line from the Buffer in the terminal.
2594 * Prints maximum 4096 chars, because of its buffer size.
2601 static CHAR Buffer
[4096];
2602 static BOOLEAN TerminalInitialized
= FALSE
;
2603 static BOOLEAN TerminalConnected
= FALSE
;
2604 static BOOLEAN TerminalReportsSize
= TRUE
;
2609 LONG RowsPrintedByTerminal
;
2613 /* Check if the user has aborted output of the current command */
2614 if (KdbOutputAborted
)
2617 /* Initialize the terminal */
2618 if (!TerminalInitialized
)
2620 DbgPrint("\x1b[7h"); /* Enable linewrap */
2622 /* Query terminal type */
2623 /*DbgPrint("\x1b[Z");*/
2626 TerminalInitialized
= TRUE
;
2628 KeStallExecutionProcessor(100000);
2632 c
= KdbpTryGetCharSerial(5000);
2636 Buffer
[Length
++] = c
;
2637 if (Length
>= (sizeof (Buffer
) - 1))
2641 Buffer
[Length
] = '\0';
2643 TerminalConnected
= TRUE
;
2646 /* Get number of rows and columns in terminal */
2647 if ((KdbNumberOfRowsTerminal
< 0) || (KdbNumberOfColsTerminal
< 0) ||
2648 (KdbNumberOfRowsPrinted
) == 0) /* Refresh terminal size each time when number of rows printed is 0 */
2650 if ((KdbDebugState
& KD_DEBUG_KDSERIAL
) && TerminalConnected
&& TerminalReportsSize
)
2652 /* Try to query number of rows from terminal. A reply looks like "\x1b[8;24;80t" */
2653 TerminalReportsSize
= FALSE
;
2654 KeStallExecutionProcessor(100000);
2655 DbgPrint("\x1b[18t");
2656 c
= KdbpTryGetCharSerial(5000);
2660 c
= KdbpTryGetCharSerial(5000);
2667 c
= KdbpTryGetCharSerial(5000);
2671 Buffer
[Length
++] = c
;
2672 if (isalpha(c
) || Length
>= (sizeof (Buffer
) - 1))
2676 Buffer
[Length
] = '\0';
2677 if (Buffer
[0] == '8' && Buffer
[1] == ';')
2679 for (i
= 2; (i
< Length
) && (Buffer
[i
] != ';'); i
++);
2681 if (Buffer
[i
] == ';')
2685 /* Number of rows is now at Buffer + 2 and number of cols at Buffer + i */
2686 KdbNumberOfRowsTerminal
= strtoul(Buffer
+ 2, NULL
, 0);
2687 KdbNumberOfColsTerminal
= strtoul(Buffer
+ i
, NULL
, 0);
2688 TerminalReportsSize
= TRUE
;
2692 /* Clear further characters */
2693 while ((c
= KdbpTryGetCharSerial(5000)) != -1);
2697 if (KdbNumberOfRowsTerminal
<= 0)
2699 /* Set number of rows to the default. */
2700 KdbNumberOfRowsTerminal
= 23; //24; //Mna.: 23 for SCREEN debugport
2702 else if (KdbNumberOfColsTerminal
<= 0)
2704 /* Set number of cols to the default. */
2705 KdbNumberOfColsTerminal
= 75; //80; //Mna.: 75 for SCREEN debugport
2709 /* Get the string */
2710 va_start(ap
, Format
);
2711 Length
= _vsnprintf(Buffer
, sizeof (Buffer
) - 1, Format
, ap
);
2712 Buffer
[Length
] = '\0';
2716 while (p
[0] != '\0')
2718 i
= strcspn(p
, "\n");
2720 /* Calculate the number of lines which will be printed in the terminal
2721 * when outputting the current line
2724 RowsPrintedByTerminal
= (i
+ KdbNumberOfColsPrinted
- 1) / KdbNumberOfColsTerminal
;
2726 RowsPrintedByTerminal
= 0;
2729 RowsPrintedByTerminal
++;
2731 /*DbgPrint("!%d!%d!%d!%d!", KdbNumberOfRowsPrinted, KdbNumberOfColsPrinted, i, RowsPrintedByTerminal);*/
2733 /* Display a prompt if we printed one screen full of text */
2734 if (KdbNumberOfRowsTerminal
> 0 &&
2735 (LONG
)(KdbNumberOfRowsPrinted
+ RowsPrintedByTerminal
) >= KdbNumberOfRowsTerminal
)
2737 KdbRepeatLastCommand
= FALSE
;
2739 if (KdbNumberOfColsPrinted
> 0)
2742 DbgPrint("--- Press q to abort, any other key to continue ---");
2743 RowsPrintedByTerminal
++; /* added by Mna. */
2745 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
2746 c
= KdbpGetCharSerial();
2748 c
= KdbpGetCharKeyboard(&ScanCode
);
2752 /* Try to read '\n' which might follow '\r' - if \n is not received here
2753 * it will be interpreted as "return" when the next command should be read.
2755 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
2756 c
= KdbpTryGetCharSerial(5);
2758 c
= KdbpTryGetCharKeyboard(&ScanCode
, 5);
2764 KdbOutputAborted
= TRUE
;
2768 KdbNumberOfRowsPrinted
= 0;
2769 KdbNumberOfColsPrinted
= 0;
2772 /* Insert a NUL after the line and print only the current line. */
2773 if (p
[i
] == '\n' && p
[i
+ 1] != '\0')
2783 /* Remove escape sequences from the line if there's no terminal connected */
2784 if (!TerminalConnected
)
2786 while ((p2
= strrchr(p
, '\x1b'))) /* Look for escape character */
2788 size_t len
= strlen(p2
);
2792 while (!isalpha(p2
[j
++]));
2793 memmove(p2
, p2
+ j
, len
+ 1 - j
);
2797 memmove(p2
, p2
+ 1, len
);
2807 /* Set p to the start of the next line and
2808 * remember the number of rows/cols printed
2814 KdbNumberOfColsPrinted
= 0;
2818 ASSERT(p
[0] == '\0');
2819 KdbNumberOfColsPrinted
+= i
;
2822 KdbNumberOfRowsPrinted
+= RowsPrintedByTerminal
;
2826 /** memrchr(), explicitly defined, since was absent in MinGW of RosBE. */
2829 * Find the last occurrence of 'c' in the buffer 's' of size 'n'.
2832 memrchr(const void *s
, int c
, size_t n
)
2834 const unsigned char *cp
;
2838 cp
= (unsigned char *)s
+ n
;
2841 if (*(--cp
) == (unsigned char)c
)
2848 /*!\brief Calculate pointer position for N lines upper of current position.
2850 * \param Buffer Characters buffer to operate on.
2851 * \param BufLength Buffer size.
2853 * \note Calculate pointer position for N lines upper of current displaying
2854 * position within the given buffer.
2856 * Used by KdbpPager().
2857 * Now N lines count is hardcoded to KdbNumberOfRowsTerminal.
2860 CountOnePageUp(PCHAR Buffer
, ULONG BufLength
, PCHAR pCurPos
)
2863 // p0 is initial guess of Page Start
2864 ULONG p0len
= KdbNumberOfRowsTerminal
* KdbNumberOfColsTerminal
;
2865 PCHAR p0
= pCurPos
- p0len
;
2866 PCHAR prev_p
= p0
, p1
;
2869 if (pCurPos
< Buffer
)
2871 ASSERT(pCurPos
<= Buffer
+ BufLength
);
2873 p
= memrchr(p0
, '\n', p0len
);
2876 for (j
= KdbNumberOfRowsTerminal
; j
--; )
2879 p1
= memrchr(p0
, '\n', p
-p0
);
2889 linesCnt
= (KdbNumberOfColsTerminal
+prev_p
-p
-2) / KdbNumberOfColsTerminal
;
2899 /*!\brief Prints the given string with, page by page.
2901 * \param Buffer Characters buffer to print.
2902 * \param BufferLen Buffer size.
2904 * \note Doesn't correctly handle \\t and terminal escape sequences when calculating the
2905 * number of lines required to print a single line from the Buffer in the terminal.
2906 * Maximum length of buffer is limited only by memory size.
2908 * Note: BufLength should be greater then (KdbNumberOfRowsTerminal * KdbNumberOfColsTerminal).
2916 static CHAR InBuffer
[4096];
2917 static BOOLEAN TerminalInitialized
= FALSE
;
2918 static BOOLEAN TerminalConnected
= FALSE
;
2919 static BOOLEAN TerminalReportsSize
= TRUE
;
2924 LONG RowsPrintedByTerminal
;
2930 /* Check if the user has aborted output of the current command */
2931 if (KdbOutputAborted
)
2934 /* Initialize the terminal */
2935 if (!TerminalInitialized
)
2937 DbgPrint("\x1b[7h"); /* Enable linewrap */
2939 /* Query terminal type */
2940 /*DbgPrint("\x1b[Z");*/
2943 TerminalInitialized
= TRUE
;
2945 KeStallExecutionProcessor(100000);
2949 c
= KdbpTryGetCharSerial(5000);
2953 InBuffer
[Length
++] = c
;
2954 if (Length
>= (sizeof (InBuffer
) - 1))
2958 InBuffer
[Length
] = '\0';
2960 TerminalConnected
= TRUE
;
2963 /* Get number of rows and columns in terminal */
2964 if ((KdbNumberOfRowsTerminal
< 0) || (KdbNumberOfColsTerminal
< 0) ||
2965 (KdbNumberOfRowsPrinted
) == 0) /* Refresh terminal size each time when number of rows printed is 0 */
2967 if ((KdbDebugState
& KD_DEBUG_KDSERIAL
) && TerminalConnected
&& TerminalReportsSize
)
2969 /* Try to query number of rows from terminal. A reply looks like "\x1b[8;24;80t" */
2970 TerminalReportsSize
= FALSE
;
2971 KeStallExecutionProcessor(100000);
2972 DbgPrint("\x1b[18t");
2973 c
= KdbpTryGetCharSerial(5000);
2977 c
= KdbpTryGetCharSerial(5000);
2984 c
= KdbpTryGetCharSerial(5000);
2988 InBuffer
[Length
++] = c
;
2989 if (isalpha(c
) || Length
>= (sizeof (InBuffer
) - 1))
2993 InBuffer
[Length
] = '\0';
2994 if (InBuffer
[0] == '8' && InBuffer
[1] == ';')
2996 for (i
= 2; (i
< Length
) && (InBuffer
[i
] != ';'); i
++);
2998 if (Buffer
[i
] == ';')
3002 /* Number of rows is now at Buffer + 2 and number of cols at Buffer + i */
3003 KdbNumberOfRowsTerminal
= strtoul(InBuffer
+ 2, NULL
, 0);
3004 KdbNumberOfColsTerminal
= strtoul(InBuffer
+ i
, NULL
, 0);
3005 TerminalReportsSize
= TRUE
;
3009 /* Clear further characters */
3010 while ((c
= KdbpTryGetCharSerial(5000)) != -1);
3014 if (KdbNumberOfRowsTerminal
<= 0)
3016 /* Set number of rows to the default. */
3017 KdbNumberOfRowsTerminal
= 24;
3019 else if (KdbNumberOfColsTerminal
<= 0)
3021 /* Set number of cols to the default. */
3022 KdbNumberOfColsTerminal
= 80;
3026 /* Get the string */
3029 while (p
[0] != '\0')
3031 if ( p
> Buffer
+BufLength
)
3033 DbgPrint("Dmesg: error, p > Buffer+BufLength,d=%d", p
- (Buffer
+BufLength
));
3036 i
= strcspn(p
, "\n");
3038 // Are we out of buffer?
3039 if (p
+ i
> Buffer
+ BufLength
)
3040 // Leaving pager function:
3043 /* Calculate the number of lines which will be printed in the terminal
3044 * when outputting the current line.
3047 RowsPrintedByTerminal
= (i
+ KdbNumberOfColsPrinted
- 1) / KdbNumberOfColsTerminal
;
3049 RowsPrintedByTerminal
= 0;
3052 RowsPrintedByTerminal
++;
3054 /*DbgPrint("!%d!%d!%d!%d!", KdbNumberOfRowsPrinted, KdbNumberOfColsPrinted, i, RowsPrintedByTerminal);*/
3056 /* Display a prompt if we printed one screen full of text */
3057 if (KdbNumberOfRowsTerminal
> 0 &&
3058 (LONG
)(KdbNumberOfRowsPrinted
+ RowsPrintedByTerminal
) >= KdbNumberOfRowsTerminal
)
3060 KdbRepeatLastCommand
= FALSE
;
3062 if (KdbNumberOfColsPrinted
> 0)
3065 DbgPrint("--- Press q to abort, e/End,h/Home,u/PgUp, other key/PgDn ---");
3066 RowsPrintedByTerminal
++;
3068 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
3069 c
= KdbpGetCharSerial();
3071 c
= KdbpGetCharKeyboard(&ScanCode
);
3075 /* Try to read '\n' which might follow '\r' - if \n is not received here
3076 * it will be interpreted as "return" when the next command should be read.
3078 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
3079 c
= KdbpTryGetCharSerial(5);
3081 c
= KdbpTryGetCharKeyboard(&ScanCode
, 5);
3084 //DbgPrint("\n"); //Consize version: don't show pressed key
3085 DbgPrint(" '%c'/scan=%04x\n", c
, ScanCode
); // Shows pressed key
3089 KdbOutputAborted
= TRUE
;
3092 if ( ScanCode
== KEYSC_END
|| c
=='e')
3094 PCHAR pBufEnd
= Buffer
+ BufLength
;
3095 p
= CountOnePageUp(Buffer
, BufLength
, pBufEnd
);
3096 i
= strcspn(p
, "\n");
3098 else if (ScanCode
== KEYSC_PAGEUP
|| c
=='u')
3100 p
= CountOnePageUp(Buffer
, BufLength
, p
);
3101 i
= strcspn(p
, "\n");
3103 else if (ScanCode
== KEYSC_HOME
|| c
=='h')
3106 i
= strcspn(p
, "\n");
3108 else if (ScanCode
== KEYSC_ARROWUP
)
3110 p
= CountOnePageUp(Buffer
, BufLength
, p
);
3111 i
= strcspn(p
, "\n");
3114 KdbNumberOfRowsPrinted
= 0;
3115 KdbNumberOfColsPrinted
= 0;
3118 /* Insert a NUL after the line and print only the current line. */
3119 if (p
[i
] == '\n' && p
[i
+ 1] != '\0')
3129 /* Remove escape sequences from the line if there's no terminal connected */
3130 if (!TerminalConnected
)
3132 while ((p2
= strrchr(p
, '\x1b'))) /* Look for escape character */
3134 size_t len
= strlen(p2
);
3138 while (!isalpha(p2
[j
++]));
3139 memmove(p2
, p2
+ j
, len
+ 1 - j
);
3143 memmove(p2
, p2
+ 1, len
);
3148 // The main printing of the current line:
3151 // restore not null char with saved:
3155 /* Set p to the start of the next line and
3156 * remember the number of rows/cols printed
3162 KdbNumberOfColsPrinted
= 0;
3166 ASSERT(p
[0] == '\0');
3167 KdbNumberOfColsPrinted
+= i
;
3170 KdbNumberOfRowsPrinted
+= RowsPrintedByTerminal
;
3174 /*!\brief Appends a command to the command history
3176 * \param Command Pointer to the command to append to the history.
3179 KdbpCommandHistoryAppend(
3182 ULONG Length1
= strlen(Command
) + 1;
3187 ASSERT(Length1
<= RTL_NUMBER_OF(KdbCommandHistoryBuffer
));
3190 (KdbCommandHistory
[KdbCommandHistoryIndex
] &&
3191 strcmp(KdbCommandHistory
[KdbCommandHistoryIndex
], Command
) == 0))
3196 /* Calculate Length1 and Length2 */
3197 Buffer
= KdbCommandHistoryBuffer
+ KdbCommandHistoryBufferIndex
;
3198 KdbCommandHistoryBufferIndex
+= Length1
;
3199 if (KdbCommandHistoryBufferIndex
>= (LONG
)RTL_NUMBER_OF(KdbCommandHistoryBuffer
))
3201 KdbCommandHistoryBufferIndex
-= RTL_NUMBER_OF(KdbCommandHistoryBuffer
);
3202 Length2
= KdbCommandHistoryBufferIndex
;
3206 /* Remove previous commands until there is enough space to append the new command */
3207 for (i
= KdbCommandHistoryIndex
; KdbCommandHistory
[i
];)
3210 (KdbCommandHistory
[i
] >= Buffer
||
3211 KdbCommandHistory
[i
] < (KdbCommandHistoryBuffer
+ KdbCommandHistoryBufferIndex
))) ||
3213 (KdbCommandHistory
[i
] >= Buffer
&&
3214 KdbCommandHistory
[i
] < (KdbCommandHistoryBuffer
+ KdbCommandHistoryBufferIndex
))))
3216 KdbCommandHistory
[i
] = NULL
;
3221 i
= RTL_NUMBER_OF(KdbCommandHistory
) - 1;
3223 if (i
== KdbCommandHistoryIndex
)
3227 /* Make sure the new command history entry is free */
3228 KdbCommandHistoryIndex
++;
3229 KdbCommandHistoryIndex
%= RTL_NUMBER_OF(KdbCommandHistory
);
3230 if (KdbCommandHistory
[KdbCommandHistoryIndex
])
3232 KdbCommandHistory
[KdbCommandHistoryIndex
] = NULL
;
3235 /* Append command */
3236 KdbCommandHistory
[KdbCommandHistoryIndex
] = Buffer
;
3237 ASSERT((KdbCommandHistory
[KdbCommandHistoryIndex
] + Length1
) <= KdbCommandHistoryBuffer
+ RTL_NUMBER_OF(KdbCommandHistoryBuffer
));
3238 memcpy(KdbCommandHistory
[KdbCommandHistoryIndex
], Command
, Length1
);
3241 memcpy(KdbCommandHistoryBuffer
, Command
+ Length1
, Length2
);
3245 /*!\brief Reads a line of user-input.
3247 * \param Buffer Buffer to store the input into. Trailing newlines are removed.
3248 * \param Size Size of \a Buffer.
3250 * \note Accepts only \n newlines, \r is ignored.
3258 PCHAR Orig
= Buffer
;
3261 static CHAR LastCommand
[1024];
3262 static CHAR NextKey
= '\0';
3263 INT CmdHistIndex
= -1;
3266 EchoOn
= !((KdbDebugState
& KD_DEBUG_KDNOECHO
) != 0);
3270 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
3272 Key
= (NextKey
== '\0') ? KdbpGetCharSerial() : NextKey
;
3275 if (Key
== KEY_ESC
) /* ESC */
3277 Key
= KdbpGetCharSerial();
3280 Key
= KdbpGetCharSerial();
3285 ScanCode
= KEY_SCAN_UP
;
3288 ScanCode
= KEY_SCAN_DOWN
;
3301 Key
= (NextKey
== '\0') ? KdbpGetCharKeyboard(&ScanCode
) : NextKey
;
3305 if ((ULONG
)(Buffer
- Orig
) >= (Size
- 1))
3307 /* Buffer is full, accept only newlines */
3314 /* Read the next char - this is to throw away a \n which most clients should
3317 KeStallExecutionProcessor(100000);
3319 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
3320 NextKey
= KdbpTryGetCharSerial(5);
3322 NextKey
= KdbpTryGetCharKeyboard(&ScanCode
, 5);
3324 if (NextKey
== '\n' || NextKey
== -1) /* \n or no response at all */
3330 * Repeat the last command if the user presses enter. Reduces the
3331 * risk of RSI when single-stepping.
3335 KdbRepeatLastCommand
= TRUE
;
3337 RtlStringCbCopyA(LastCommand
, sizeof(LastCommand
), Orig
);
3339 else if (KdbRepeatLastCommand
)
3340 RtlStringCbCopyA(Buffer
, Size
, LastCommand
);
3346 else if (Key
== KEY_BS
|| Key
== KEY_DEL
)
3354 KdbpPrint("%c %c", KEY_BS
, KEY_BS
);
3356 KdbpPrint(" %c", KEY_BS
);
3359 else if (ScanCode
== KEY_SCAN_UP
)
3361 BOOLEAN Print
= TRUE
;
3363 if (CmdHistIndex
< 0)
3365 CmdHistIndex
= KdbCommandHistoryIndex
;
3369 i
= CmdHistIndex
- 1;
3372 CmdHistIndex
= RTL_NUMBER_OF(KdbCommandHistory
) - 1;
3374 if (KdbCommandHistory
[i
] && i
!= KdbCommandHistoryIndex
)
3380 if (Print
&& KdbCommandHistory
[CmdHistIndex
])
3382 while (Buffer
> Orig
)
3388 KdbpPrint("%c %c", KEY_BS
, KEY_BS
);
3390 KdbpPrint(" %c", KEY_BS
);
3393 i
= min(strlen(KdbCommandHistory
[CmdHistIndex
]), Size
- 1);
3394 memcpy(Orig
, KdbCommandHistory
[CmdHistIndex
], i
);
3397 KdbpPrint("%s", Orig
);
3400 else if (ScanCode
== KEY_SCAN_DOWN
)
3402 if (CmdHistIndex
> 0 && CmdHistIndex
!= KdbCommandHistoryIndex
)
3404 i
= CmdHistIndex
+ 1;
3405 if (i
>= (INT
)RTL_NUMBER_OF(KdbCommandHistory
))
3408 if (KdbCommandHistory
[i
])
3411 while (Buffer
> Orig
)
3417 KdbpPrint("%c %c", KEY_BS
, KEY_BS
);
3419 KdbpPrint(" %c", KEY_BS
);
3422 i
= min(strlen(KdbCommandHistory
[CmdHistIndex
]), Size
- 1);
3423 memcpy(Orig
, KdbCommandHistory
[CmdHistIndex
], i
);
3426 KdbpPrint("%s", Orig
);
3433 KdbpPrint("%c", Key
);
3444 KdbRegisterCliCallback(
3450 /* Loop all entries */
3451 for (i
= 0; i
< _countof(KdbCliCallbacks
); i
++)
3453 /* Check if deregistering was requested */
3456 /* Check if this entry is the one that was registered */
3457 if (KdbCliCallbacks
[i
] == Callback
)
3459 /* Delete it and report success */
3460 KdbCliCallbacks
[i
] = NULL
;
3466 /* Check if this entry is free */
3467 if (KdbCliCallbacks
[i
] == NULL
)
3469 /* Set it and and report success */
3470 KdbCliCallbacks
[i
] = Callback
;
3480 /*! \brief Invokes registered CLI callbacks until one of them handled the
3483 * \param Command - Command line to parse and execute if possible.
3484 * \param Argc - Number of arguments in Argv
3485 * \param Argv - Array of strings, each of them containing one argument.
3487 * \return TRUE, if the command was handled, FALSE if it was not handled.
3491 KdbpInvokeCliCallbacks(
3498 /* Loop all entries */
3499 for (i
= 0; i
< _countof(KdbCliCallbacks
); i
++)
3501 /* Check if this entry is registered */
3502 if (KdbCliCallbacks
[i
])
3504 /* Invoke the callback and check if it handled the command */
3505 if (KdbCliCallbacks
[i
](Command
, Argc
, Argv
))
3512 /* None of the callbacks handled the command */
3517 /*!\brief Parses command line and executes command if found
3519 * \param Command Command line to parse and execute if possible.
3521 * \retval TRUE Don't continue execution.
3522 * \retval FALSE Continue execution (leave KDB)
3531 // FIXME: for what do we need a 1024 characters command line and 256 tokens?
3532 static PCH Argv
[256];
3533 static CHAR OrigCommand
[1024];
3535 RtlStringCbCopyA(OrigCommand
, sizeof(OrigCommand
), Command
);
3542 while (*p
== '\t' || *p
== ' ')
3548 i
= strcspn(p
, "\t ");
3561 for (i
= 0; i
< RTL_NUMBER_OF(KdbDebuggerCommands
); i
++)
3563 if (!KdbDebuggerCommands
[i
].Name
)
3566 if (strcmp(KdbDebuggerCommands
[i
].Name
, Argv
[0]) == 0)
3568 return KdbDebuggerCommands
[i
].Fn(Argc
, Argv
);
3572 /* Now invoke the registered callbacks */
3573 if (KdbpInvokeCliCallbacks(Command
, Argc
, Argv
))
3578 KdbpPrint("Command '%s' is unknown.\n", OrigCommand
);
3582 /*!\brief KDB Main Loop.
3584 * \param EnteredOnSingleStep TRUE if KDB was entered on single step.
3588 IN BOOLEAN EnteredOnSingleStep
)
3590 static CHAR Command
[1024];
3593 if (EnteredOnSingleStep
)
3595 if (!KdbSymPrintAddress((PVOID
)KdbCurrentTrapFrame
->Tf
.Eip
, &KdbCurrentTrapFrame
->Tf
))
3597 KdbpPrint("<%08x>", KdbCurrentTrapFrame
->Tf
.Eip
);
3601 if (KdbpDisassemble(KdbCurrentTrapFrame
->Tf
.Eip
, KdbUseIntelSyntax
) < 0)
3603 KdbpPrint("<INVALID>");
3608 /* Flush the input buffer */
3609 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
3611 while (KdbpTryGetCharSerial(1) != -1);
3616 while (KdbpTryGetCharKeyboard(&ScanCode
, 1) != -1);
3622 /* Reset the number of rows/cols printed */
3623 KdbNumberOfRowsPrinted
= KdbNumberOfColsPrinted
= 0;
3625 /* Print the prompt */
3626 KdbpPrint("kdb:> ");
3628 /* Read a command and remember it */
3629 KdbpReadCommand(Command
, sizeof (Command
));
3630 KdbpCommandHistoryAppend(Command
);
3632 /* Reset the number of rows/cols printed and output aborted state */
3633 KdbNumberOfRowsPrinted
= KdbNumberOfColsPrinted
= 0;
3634 KdbOutputAborted
= FALSE
;
3636 /* Call the command */
3637 Continue
= KdbpDoCommand(Command
);
3638 KdbOutputAborted
= FALSE
;
3643 /*!\brief Called when a module is loaded.
3645 * \param Name Filename of the module which was loaded.
3648 KdbpCliModuleLoaded(
3649 IN PUNICODE_STRING Name
)
3651 if (!KdbBreakOnModuleLoad
)
3654 KdbpPrint("Module %wZ loaded.\n", Name
);
3655 DbgBreakPointWithStatus(DBG_STATUS_CONTROL_C
);
3658 /*!\brief This function is called by KdbEnterDebuggerException...
3660 * Used to interpret the init file in a context with a trapframe setup
3661 * (KdbpCliInit call KdbEnter which will call KdbEnterDebuggerException which will
3662 * call this function if KdbInitFileBuffer is not NULL.
3665 KdbpCliInterpretInitFile(VOID
)
3671 /* Execute the commands in the init file */
3672 DPRINT("KDB: Executing KDBinit file...\n");
3673 p1
= KdbInitFileBuffer
;
3674 while (p1
[0] != '\0')
3676 i
= strcspn(p1
, "\r\n");
3682 /* Look for "break" command and comments */
3685 while (isspace(p2
[0]))
3688 if (strncmp(p2
, "break", sizeof("break")-1) == 0 &&
3689 (p2
[sizeof("break")-1] == '\0' || isspace(p2
[sizeof("break")-1])))
3691 /* break into the debugger */
3692 KdbpCliMainLoop(FALSE
);
3694 else if (p2
[0] != '#' && p2
[0] != '\0') /* Ignore empty lines and comments */
3703 while (p1
[0] == '\r' || p1
[0] == '\n')
3706 DPRINT("KDB: KDBinit executed\n");
3709 /*!\brief Called when KDB is initialized
3711 * Reads the KDBinit file from the SystemRoot\System32\drivers\etc directory and executes it.
3717 OBJECT_ATTRIBUTES ObjectAttributes
;
3718 UNICODE_STRING FileName
;
3719 IO_STATUS_BLOCK Iosb
;
3720 FILE_STANDARD_INFORMATION FileStdInfo
;
3721 HANDLE hFile
= NULL
;
3726 /* Initialize the object attributes */
3727 RtlInitUnicodeString(&FileName
, L
"\\SystemRoot\\System32\\drivers\\etc\\KDBinit");
3728 InitializeObjectAttributes(&ObjectAttributes
, &FileName
, 0, NULL
, NULL
);
3731 Status
= ZwOpenFile(&hFile
, FILE_READ_DATA
| SYNCHRONIZE
,
3732 &ObjectAttributes
, &Iosb
, 0,
3733 FILE_NON_DIRECTORY_FILE
| FILE_SYNCHRONOUS_IO_NONALERT
|
3734 FILE_NO_INTERMEDIATE_BUFFERING
);
3735 if (!NT_SUCCESS(Status
))
3737 DPRINT("Could not open \\SystemRoot\\System32\\drivers\\etc\\KDBinit (Status 0x%x)", Status
);
3741 /* Get the size of the file */
3742 Status
= ZwQueryInformationFile(hFile
, &Iosb
, &FileStdInfo
, sizeof (FileStdInfo
),
3743 FileStandardInformation
);
3744 if (!NT_SUCCESS(Status
))
3747 DPRINT("Could not query size of \\SystemRoot\\System32\\drivers\\etc\\KDBinit (Status 0x%x)", Status
);
3750 FileSize
= FileStdInfo
.EndOfFile
.u
.LowPart
;
3752 /* Allocate memory for the file */
3753 FileBuffer
= ExAllocatePool(PagedPool
, FileSize
+ 1); /* add 1 byte for terminating '\0' */
3757 DPRINT("Could not allocate %d bytes for KDBinit file\n", FileSize
);
3761 /* Load file into memory */
3762 Status
= ZwReadFile(hFile
, NULL
, NULL
, NULL
, &Iosb
, FileBuffer
, FileSize
, NULL
, NULL
);
3765 if (!NT_SUCCESS(Status
) && Status
!= STATUS_END_OF_FILE
)
3767 ExFreePool(FileBuffer
);
3768 DPRINT("Could not read KDBinit file into memory (Status 0x%lx)\n", Status
);
3772 FileSize
= min(FileSize
, (INT
)Iosb
.Information
);
3773 FileBuffer
[FileSize
] = '\0';
3775 /* Enter critical section */
3776 OldEflags
= __readeflags();
3779 /* Interpret the init file... */
3780 KdbInitFileBuffer
= FileBuffer
;
3782 KdbInitFileBuffer
= NULL
;
3784 /* Leave critical section */
3785 __writeeflags(OldEflags
);
3787 ExFreePool(FileBuffer
);
3792 KdpSerialDebugPrint(
3797 STRING KdpPromptString
= RTL_CONSTANT_STRING("kdb:> ");
3798 extern KSPIN_LOCK KdpSerialSpinLock
;
3803 _In_reads_bytes_(InStringLength
) PCHAR UnsafeInString
,
3804 _In_ USHORT InStringLength
,
3805 _Out_writes_bytes_(OutStringLength
) PCHAR UnsafeOutString
,
3806 _In_ USHORT OutStringLength
,
3807 _In_ KPROCESSOR_MODE PreviousMode
,
3808 _In_ PKTRAP_FRAME TrapFrame
,
3809 _In_ PKEXCEPTION_FRAME ExceptionFrame
)
3813 ULONG DummyScanCode
;
3817 CHAR InStringBuffer
[512];
3818 CHAR OutStringBuffer
[512];
3820 /* Normalize the lengths */
3821 InStringLength
= min(InStringLength
,
3822 sizeof(InStringBuffer
));
3823 OutStringLength
= min(OutStringLength
,
3824 sizeof(OutStringBuffer
));
3826 /* Check if we need to verify the string */
3827 if (PreviousMode
!= KernelMode
)
3829 /* Handle user-mode buffers safely */
3832 /* Probe the prompt */
3833 ProbeForRead(UnsafeInString
,
3837 /* Capture prompt */
3838 InString
= InStringBuffer
;
3839 RtlCopyMemory(InString
,
3843 /* Probe and make room for response */
3844 ProbeForWrite(UnsafeOutString
,
3847 OutString
= OutStringBuffer
;
3849 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
3851 /* Bad string pointer, bail out */
3852 _SEH2_YIELD(return 0);
3858 InString
= UnsafeInString
;
3859 OutString
= UnsafeOutString
;
3862 /* Acquire the printing spinlock without waiting at raised IRQL */
3865 /* Wait when the spinlock becomes available */
3866 while (!KeTestSpinLock(&KdpSerialSpinLock
));
3868 /* Spinlock was free, raise IRQL */
3869 KeRaiseIrql(HIGH_LEVEL
, &OldIrql
);
3871 /* Try to get the spinlock */
3872 if (KeTryToAcquireSpinLockAtDpcLevel(&KdpSerialSpinLock
))
3875 /* Someone else got the spinlock, lower IRQL back */
3876 KeLowerIrql(OldIrql
);
3879 /* Loop the string to send */
3880 for (i
= 0; i
< InStringLength
; i
++)
3882 /* Print it to serial */
3883 KdPortPutByteEx(&SerialPortInfo
, *(PCHAR
)(InString
+ i
));
3886 /* Print a new line for log neatness */
3887 KdPortPutByteEx(&SerialPortInfo
, '\r');
3888 KdPortPutByteEx(&SerialPortInfo
, '\n');
3890 /* Print the kdb prompt */
3891 for (i
= 0; i
< KdpPromptString
.Length
; i
++)
3893 /* Print it to serial */
3894 KdPortPutByteEx(&SerialPortInfo
,
3895 *(KdpPromptString
.Buffer
+ i
));
3898 if (!(KdbDebugState
& KD_DEBUG_KDSERIAL
))
3901 /* Loop the whole string */
3902 for (i
= 0; i
< OutStringLength
; i
++)
3904 /* Check if this is serial debugging mode */
3905 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
3907 /* Get the character from serial */
3910 Response
= KdbpTryGetCharSerial(MAXULONG
);
3911 } while (Response
== -1);
3915 /* Get the response from the keyboard */
3918 Response
= KdbpTryGetCharKeyboard(&DummyScanCode
, MAXULONG
);
3919 } while (Response
== -1);
3922 /* Check for return */
3923 if (Response
== '\r')
3926 * We might need to discard the next '\n'.
3927 * Wait a bit to make sure we receive it.
3929 KeStallExecutionProcessor(100000);
3931 /* Check the mode */
3932 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
3934 /* Read and discard the next character, if any */
3935 KdbpTryGetCharSerial(5);
3939 /* Read and discard the next character, if any */
3940 KdbpTryGetCharKeyboard(&DummyScanCode
, 5);
3944 * Null terminate the output string -- documentation states that
3945 * DbgPrompt does not null terminate, but it does
3947 *(PCHAR
)(OutString
+ i
) = 0;
3951 /* Write it back and print it to the log */
3952 *(PCHAR
)(OutString
+ i
) = Response
;
3953 KdPortPutByteEx(&SerialPortInfo
, Response
);
3956 if (!(KdbDebugState
& KD_DEBUG_KDSERIAL
))
3959 /* Print a new line */
3960 KdPortPutByteEx(&SerialPortInfo
, '\r');
3961 KdPortPutByteEx(&SerialPortInfo
, '\n');
3963 /* Release spinlock */
3964 KiReleaseSpinLock(&KdpSerialSpinLock
);
3966 /* Lower IRQL back */
3967 KeLowerIrql(OldIrql
);
3969 /* Copy back response if required */
3970 if (PreviousMode
!= KernelMode
)
3974 /* Safely copy back response to user mode */
3975 RtlCopyMemory(UnsafeOutString
,
3979 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
3981 /* String became invalid after we exited, fail */
3982 _SEH2_YIELD(return 0);
3987 /* Return the length */