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
;
136 STRING KdbPromptString
= RTL_CONSTANT_STRING("kdb:> ");
139 // Debug Filter Component Table
149 // Default components
151 { "WIN2000", MAXULONG
},
152 { "DEFAULT", DPFLTR_DEFAULT_ID
},
154 // Standard components
156 { "SYSTEM", DPFLTR_SYSTEM_ID
},
157 { "SMSS", DPFLTR_SMSS_ID
},
158 { "SETUP", DPFLTR_SETUP_ID
},
159 { "NTFS", DPFLTR_NTFS_ID
},
160 { "FSTUB", DPFLTR_FSTUB_ID
},
161 { "CRASHDUMP", DPFLTR_CRASHDUMP_ID
},
162 { "CDAUDIO", DPFLTR_CDAUDIO_ID
},
163 { "CDROM", DPFLTR_CDROM_ID
},
164 { "CLASSPNP", DPFLTR_CLASSPNP_ID
},
165 { "DISK", DPFLTR_DISK_ID
},
166 { "REDBOOK", DPFLTR_REDBOOK_ID
},
167 { "STORPROP", DPFLTR_STORPROP_ID
},
168 { "SCSIPORT", DPFLTR_SCSIPORT_ID
},
169 { "SCSIMINIPORT", DPFLTR_SCSIMINIPORT_ID
},
170 { "CONFIG", DPFLTR_CONFIG_ID
},
171 { "I8042PRT", DPFLTR_I8042PRT_ID
},
172 { "SERMOUSE", DPFLTR_SERMOUSE_ID
},
173 { "LSERMOUS", DPFLTR_LSERMOUS_ID
},
174 { "KBDHID", DPFLTR_KBDHID_ID
},
175 { "MOUHID", DPFLTR_MOUHID_ID
},
176 { "KBDCLASS", DPFLTR_KBDCLASS_ID
},
177 { "MOUCLASS", DPFLTR_MOUCLASS_ID
},
178 { "TWOTRACK", DPFLTR_TWOTRACK_ID
},
179 { "WMILIB", DPFLTR_WMILIB_ID
},
180 { "ACPI", DPFLTR_ACPI_ID
},
181 { "AMLI", DPFLTR_AMLI_ID
},
182 { "HALIA64", DPFLTR_HALIA64_ID
},
183 { "VIDEO", DPFLTR_VIDEO_ID
},
184 { "SVCHOST", DPFLTR_SVCHOST_ID
},
185 { "VIDEOPRT", DPFLTR_VIDEOPRT_ID
},
186 { "TCPIP", DPFLTR_TCPIP_ID
},
187 { "DMSYNTH", DPFLTR_DMSYNTH_ID
},
188 { "NTOSPNP", DPFLTR_NTOSPNP_ID
},
189 { "FASTFAT", DPFLTR_FASTFAT_ID
},
190 { "SAMSS", DPFLTR_SAMSS_ID
},
191 { "PNPMGR", DPFLTR_PNPMGR_ID
},
192 { "NETAPI", DPFLTR_NETAPI_ID
},
193 { "SCSERVER", DPFLTR_SCSERVER_ID
},
194 { "SCCLIENT", DPFLTR_SCCLIENT_ID
},
195 { "SERIAL", DPFLTR_SERIAL_ID
},
196 { "SERENUM", DPFLTR_SERENUM_ID
},
197 { "UHCD", DPFLTR_UHCD_ID
},
198 { "RPCPROXY", DPFLTR_RPCPROXY_ID
},
199 { "AUTOCHK", DPFLTR_AUTOCHK_ID
},
200 { "DCOMSS", DPFLTR_DCOMSS_ID
},
201 { "UNIMODEM", DPFLTR_UNIMODEM_ID
},
202 { "SIS", DPFLTR_SIS_ID
},
203 { "FLTMGR", DPFLTR_FLTMGR_ID
},
204 { "WMICORE", DPFLTR_WMICORE_ID
},
205 { "BURNENG", DPFLTR_BURNENG_ID
},
206 { "IMAPI", DPFLTR_IMAPI_ID
},
207 { "SXS", DPFLTR_SXS_ID
},
208 { "FUSION", DPFLTR_FUSION_ID
},
209 { "IDLETASK", DPFLTR_IDLETASK_ID
},
210 { "SOFTPCI", DPFLTR_SOFTPCI_ID
},
211 { "TAPE", DPFLTR_TAPE_ID
},
212 { "MCHGR", DPFLTR_MCHGR_ID
},
213 { "IDEP", DPFLTR_IDEP_ID
},
214 { "PCIIDE", DPFLTR_PCIIDE_ID
},
215 { "FLOPPY", DPFLTR_FLOPPY_ID
},
216 { "FDC", DPFLTR_FDC_ID
},
217 { "TERMSRV", DPFLTR_TERMSRV_ID
},
218 { "W32TIME", DPFLTR_W32TIME_ID
},
219 { "PREFETCHER", DPFLTR_PREFETCHER_ID
},
220 { "RSFILTER", DPFLTR_RSFILTER_ID
},
221 { "FCPORT", DPFLTR_FCPORT_ID
},
222 { "PCI", DPFLTR_PCI_ID
},
223 { "DMIO", DPFLTR_DMIO_ID
},
224 { "DMCONFIG", DPFLTR_DMCONFIG_ID
},
225 { "DMADMIN", DPFLTR_DMADMIN_ID
},
226 { "WSOCKTRANSPORT", DPFLTR_WSOCKTRANSPORT_ID
},
227 { "VSS", DPFLTR_VSS_ID
},
228 { "PNPMEM", DPFLTR_PNPMEM_ID
},
229 { "PROCESSOR", DPFLTR_PROCESSOR_ID
},
230 { "DMSERVER", DPFLTR_DMSERVER_ID
},
231 { "SR", DPFLTR_SR_ID
},
232 { "INFINIBAND", DPFLTR_INFINIBAND_ID
},
233 { "IHVDRIVER", DPFLTR_IHVDRIVER_ID
},
234 { "IHVVIDEO", DPFLTR_IHVVIDEO_ID
},
235 { "IHVAUDIO", DPFLTR_IHVAUDIO_ID
},
236 { "IHVNETWORK", DPFLTR_IHVNETWORK_ID
},
237 { "IHVSTREAMING", DPFLTR_IHVSTREAMING_ID
},
238 { "IHVBUS", DPFLTR_IHVBUS_ID
},
239 { "HPS", DPFLTR_HPS_ID
},
240 { "RTLTHREADPOOL", DPFLTR_RTLTHREADPOOL_ID
},
241 { "LDR", DPFLTR_LDR_ID
},
242 { "TCPIP6", DPFLTR_TCPIP6_ID
},
243 { "ISAPNP", DPFLTR_ISAPNP_ID
},
244 { "SHPC", DPFLTR_SHPC_ID
},
245 { "STORPORT", DPFLTR_STORPORT_ID
},
246 { "STORMINIPORT", DPFLTR_STORMINIPORT_ID
},
247 { "PRINTSPOOLER", DPFLTR_PRINTSPOOLER_ID
},
248 { "VSSDYNDISK", DPFLTR_VSSDYNDISK_ID
},
249 { "VERIFIER", DPFLTR_VERIFIER_ID
},
250 { "VDS", DPFLTR_VDS_ID
},
251 { "VDSBAS", DPFLTR_VDSBAS_ID
},
252 { "VDSDYN", DPFLTR_VDSDYN_ID
}, // Specified in Vista+
253 { "VDSDYNDR", DPFLTR_VDSDYNDR_ID
},
254 { "VDSLDR", DPFLTR_VDSLDR_ID
}, // Specified in Vista+
255 { "VDSUTIL", DPFLTR_VDSUTIL_ID
},
256 { "DFRGIFC", DPFLTR_DFRGIFC_ID
},
257 { "MM", DPFLTR_MM_ID
},
258 { "DFSC", DPFLTR_DFSC_ID
},
259 { "WOW64", DPFLTR_WOW64_ID
},
261 // Components specified in Vista+, some of which we also use in ReactOS
263 { "ALPC", DPFLTR_ALPC_ID
},
264 { "WDI", DPFLTR_WDI_ID
},
265 { "PERFLIB", DPFLTR_PERFLIB_ID
},
266 { "KTM", DPFLTR_KTM_ID
},
267 { "IOSTRESS", DPFLTR_IOSTRESS_ID
},
268 { "HEAP", DPFLTR_HEAP_ID
},
269 { "WHEA", DPFLTR_WHEA_ID
},
270 { "USERGDI", DPFLTR_USERGDI_ID
},
271 { "MMCSS", DPFLTR_MMCSS_ID
},
272 { "TPM", DPFLTR_TPM_ID
},
273 { "THREADORDER", DPFLTR_THREADORDER_ID
},
274 { "ENVIRON", DPFLTR_ENVIRON_ID
},
275 { "EMS", DPFLTR_EMS_ID
},
276 { "WDT", DPFLTR_WDT_ID
},
277 { "FVEVOL", DPFLTR_FVEVOL_ID
},
278 { "NDIS", DPFLTR_NDIS_ID
},
279 { "NVCTRACE", DPFLTR_NVCTRACE_ID
},
280 { "LUAFV", DPFLTR_LUAFV_ID
},
281 { "APPCOMPAT", DPFLTR_APPCOMPAT_ID
},
282 { "USBSTOR", DPFLTR_USBSTOR_ID
},
283 { "SBP2PORT", DPFLTR_SBP2PORT_ID
},
284 { "COVERAGE", DPFLTR_COVERAGE_ID
},
285 { "CACHEMGR", DPFLTR_CACHEMGR_ID
},
286 { "MOUNTMGR", DPFLTR_MOUNTMGR_ID
},
287 { "CFR", DPFLTR_CFR_ID
},
288 { "TXF", DPFLTR_TXF_ID
},
289 { "KSECDD", DPFLTR_KSECDD_ID
},
290 { "FLTREGRESS", DPFLTR_FLTREGRESS_ID
},
291 { "MPIO", DPFLTR_MPIO_ID
},
292 { "MSDSM", DPFLTR_MSDSM_ID
},
293 { "UDFS", DPFLTR_UDFS_ID
},
294 { "PSHED", DPFLTR_PSHED_ID
},
295 { "STORVSP", DPFLTR_STORVSP_ID
},
296 { "LSASS", DPFLTR_LSASS_ID
},
297 { "SSPICLI", DPFLTR_SSPICLI_ID
},
298 { "CNG", DPFLTR_CNG_ID
},
299 { "EXFAT", DPFLTR_EXFAT_ID
},
300 { "FILETRACE", DPFLTR_FILETRACE_ID
},
301 { "XSAVE", DPFLTR_XSAVE_ID
},
302 { "SE", DPFLTR_SE_ID
},
303 { "DRIVEEXTENDER", DPFLTR_DRIVEEXTENDER_ID
},
314 BOOLEAN (*Fn
)(ULONG Argc
, PCHAR Argv
[]);
315 } KdbDebuggerCommands
[] = {
317 { NULL
, NULL
, "Data", NULL
},
318 { "?", "? expression", "Evaluate expression.", KdbpCmdEvalExpression
},
319 { "disasm", "disasm [address] [L count]", "Disassemble count instructions at address.", KdbpCmdDisassembleX
},
320 { "x", "x [address] [L count]", "Display count dwords, starting at address.", KdbpCmdDisassembleX
},
321 { "regs", "regs", "Display general purpose registers.", KdbpCmdRegs
},
322 { "cregs", "cregs", "Display control, descriptor table and task segment registers.", KdbpCmdRegs
},
323 { "sregs", "sregs", "Display status registers.", KdbpCmdRegs
},
324 { "dregs", "dregs", "Display debug registers.", KdbpCmdRegs
},
325 { "bt", "bt [*frameaddr|thread id]", "Prints current backtrace or from given frame address.", KdbpCmdBackTrace
},
327 { "dt", "dt [mod] [type] [addr]", "Print a struct. The address is optional.", KdbpCmdPrintStruct
},
331 { NULL
, NULL
, "Flow control", NULL
},
332 { "cont", "cont", "Continue execution (leave debugger).", KdbpCmdContinue
},
333 { "step", "step [count]", "Execute single instructions, stepping into interrupts.", KdbpCmdStep
},
334 { "next", "next [count]", "Execute single instructions, skipping calls and reps.", KdbpCmdStep
},
335 { "bl", "bl", "List breakpoints.", KdbpCmdBreakPointList
},
336 { "be", "be [breakpoint]", "Enable breakpoint.", KdbpCmdEnableDisableClearBreakPoint
},
337 { "bd", "bd [breakpoint]", "Disable breakpoint.", KdbpCmdEnableDisableClearBreakPoint
},
338 { "bc", "bc [breakpoint]", "Clear breakpoint.", KdbpCmdEnableDisableClearBreakPoint
},
339 { "bpx", "bpx [address] [IF condition]", "Set software execution breakpoint at address.", KdbpCmdBreakPoint
},
340 { "bpm", "bpm [r|w|rw|x] [byte|word|dword] [address] [IF condition]", "Set memory breakpoint at address.", KdbpCmdBreakPoint
},
343 { NULL
, NULL
, "Process/Thread", NULL
},
344 { "thread", "thread [list[ pid]|[attach ]tid]", "List threads in current or specified process, display thread with given id or attach to thread.", KdbpCmdThread
},
345 { "proc", "proc [list|[attach ]pid]", "List processes, display process with given id or attach to process.", KdbpCmdProc
},
347 /* System information */
348 { NULL
, NULL
, "System info", NULL
},
349 { "mod", "mod [address]", "List all modules or the one containing address.", KdbpCmdMod
},
350 { "gdt", "gdt", "Display the global descriptor table.", KdbpCmdGdtLdtIdt
},
351 { "ldt", "ldt", "Display the local descriptor table.", KdbpCmdGdtLdtIdt
},
352 { "idt", "idt", "Display the interrupt descriptor table.", KdbpCmdGdtLdtIdt
},
353 { "pcr", "pcr", "Display the processor control region.", KdbpCmdPcr
},
354 { "tss", "tss [selector|*descaddr]", "Display the current task state segment, or the one specified by its selector number or descriptor address.", KdbpCmdTss
},
357 { NULL
, NULL
, "Others", NULL
},
358 { "bugcheck", "bugcheck", "Bugchecks the system.", KdbpCmdBugCheck
},
359 { "reboot", "reboot", "Reboots the system.", KdbpCmdReboot
},
360 { "filter", "filter [error|warning|trace|info|level]+|-[componentname|default]", "Enable/disable debug channels.", KdbpCmdFilter
},
361 { "set", "set [var] [value]", "Sets var to value or displays value of var.", KdbpCmdSet
},
362 { "dmesg", "dmesg", "Display debug messages on screen, with navigation on pages.", KdbpCmdDmesg
},
363 { "kmsg", "kmsg", "Kernel dmesg. Alias for dmesg.", KdbpCmdDmesg
},
364 { "help", "help", "Display help screen.", KdbpCmdHelp
},
365 { "!pool", "!pool [Address [Flags]]", "Display information about pool allocations.", ExpKdbgExtPool
},
366 { "!poolused", "!poolused [Flags [Tag]]", "Display pool usage.", ExpKdbgExtPoolUsed
},
367 { "!poolfind", "!poolfind Tag [Pool]", "Search for pool tag allocations.", ExpKdbgExtPoolFind
},
368 { "!filecache", "!filecache", "Display cache usage.", ExpKdbgExtFileCache
},
369 { "!defwrites", "!defwrites", "Display cache write values.", ExpKdbgExtDefWrites
},
370 { "!irpfind", "!irpfind [Pool [startaddress [criteria data]]]", "Lists IRPs potentially matching criteria.", ExpKdbgExtIrpFind
},
371 { "!handle", "!handle [Handle]", "Displays info about handles.", ExpKdbgExtHandle
},
374 /* FUNCTIONS *****************************************************************/
376 /*!\brief Evaluates an expression...
378 * Much like KdbpRpnEvaluateExpression, but prints the error message (if any)
379 * at the given offset.
381 * \param Expression Expression to evaluate.
382 * \param ErrOffset Offset (in characters) to print the error message at.
383 * \param Result Receives the result on success.
385 * \retval TRUE Success.
386 * \retval FALSE Failure.
389 KdbpEvaluateExpression(
392 OUT PULONGLONG Result
)
394 static CHAR ErrMsgBuffer
[130] = "^ ";
395 LONG ExpressionErrOffset
= -1;
396 PCHAR ErrMsg
= ErrMsgBuffer
;
399 Ok
= KdbpRpnEvaluateExpression(Expression
, KdbCurrentTrapFrame
, Result
,
400 &ExpressionErrOffset
, ErrMsgBuffer
+ 2);
403 if (ExpressionErrOffset
>= 0)
404 ExpressionErrOffset
+= ErrOffset
;
408 KdbpPrint("%*s%s\n", ExpressionErrOffset
, "", ErrMsg
);
418 OUT ULONG_PTR
*pulValue
)
422 /* Skip optional '0x' prefix */
423 if ((pszNum
[0] == '0') && ((pszNum
[1] == 'x') || (pszNum
[1] == 'X')))
426 /* Make a number from the string (hex) */
427 *pulValue
= strtoul(pszNum
, &endptr
, 16);
429 return (*endptr
== '\0');
432 /*!\brief Evaluates an expression and displays the result.
435 KdbpCmdEvalExpression(
440 ULONGLONG Result
= 0;
447 KdbpPrint("?: Argument required\n");
451 /* Put the arguments back together */
453 for (i
= 1; i
< Argc
; i
++)
455 len
= strlen(Argv
[i
]);
459 /* Evaluate the expression */
460 Ok
= KdbpEvaluateExpression(Argv
[1], KdbPromptString
.Length
+ (Argv
[1]-Argv
[0]), &Result
);
463 if (Result
> 0x00000000ffffffffLL
)
465 if (Result
& 0x8000000000000000LL
)
466 KdbpPrint("0x%016I64x %20I64u %20I64d\n", Result
, Result
, Result
);
468 KdbpPrint("0x%016I64x %20I64u\n", Result
, Result
);
474 if (ul
<= 0xff && ul
>= 0x80)
475 l
= (LONG
)((CHAR
)ul
);
476 else if (ul
<= 0xffff && ul
>= 0x8000)
477 l
= (LONG
)((SHORT
)ul
);
482 KdbpPrint("0x%08lx %10lu %10ld\n", ul
, ul
, l
);
484 KdbpPrint("0x%08lx %10lu\n", ul
, ul
);
493 /*!\brief Print a struct
496 KdbpPrintStructInternal
501 PROSSYM_AGGREGATE Aggregate
)
505 PROSSYM_AGGREGATE_MEMBER Member
;
506 ULONG IndentLen
= strlen(Indent
);
507 ROSSYM_AGGREGATE MemberAggregate
= {0 };
509 for (i
= 0; i
< Aggregate
->NumElements
; i
++) {
510 Member
= &Aggregate
->Elements
[i
];
511 KdbpPrint("%s%p+%x: %s", Indent
, ((PCHAR
)BaseAddress
) + Member
->BaseOffset
, Member
->Size
, Member
->Name
? Member
->Name
: "<anoymous>");
513 if (!strcmp(Member
->Type
, "_UNICODE_STRING")) {
514 KdbpPrint("\"%wZ\"\n", ((PCHAR
)BaseAddress
) + Member
->BaseOffset
);
516 } else if (!strcmp(Member
->Type
, "PUNICODE_STRING")) {
517 KdbpPrint("\"%wZ\"\n", *(((PUNICODE_STRING
*)((PCHAR
)BaseAddress
) + Member
->BaseOffset
)));
520 switch (Member
->Size
) {
526 if (NT_SUCCESS(KdbpSafeReadMemory(&Result
, ((PCHAR
)BaseAddress
) + Member
->BaseOffset
, Member
->Size
))) {
528 Result
>>= Member
->FirstBit
;
529 Result
&= ((1 << Member
->Bits
) - 1);
531 KdbpPrint(" %lx\n", Result
);
537 if (Member
->Size
< 8) {
538 if (NT_SUCCESS(KdbpSafeReadMemory(&Result
, ((PCHAR
)BaseAddress
) + Member
->BaseOffset
, Member
->Size
))) {
540 for (j
= 0; j
< Member
->Size
; j
++) {
541 KdbpPrint(" %02x", (int)(Result
& 0xff));
544 } else goto readfail
;
546 KdbpPrint(" %s @ %p {\n", Member
->Type
, ((PCHAR
)BaseAddress
) + Member
->BaseOffset
);
547 Indent
[IndentLen
] = ' ';
548 if (RosSymAggregate(Info
, Member
->Type
, &MemberAggregate
)) {
549 KdbpPrintStructInternal(Info
, Indent
, DoRead
, ((PCHAR
)BaseAddress
) + Member
->BaseOffset
, &MemberAggregate
);
550 RosSymFreeAggregate(&MemberAggregate
);
552 Indent
[IndentLen
] = 0;
553 KdbpPrint("%s}\n", Indent
);
559 if (Member
->Size
<= 8) {
562 KdbpPrint(" %s @ %x {\n", Member
->Type
, Member
->BaseOffset
);
563 Indent
[IndentLen
] = ' ';
564 if (RosSymAggregate(Info
, Member
->Type
, &MemberAggregate
)) {
565 KdbpPrintStructInternal(Info
, Indent
, DoRead
, BaseAddress
, &MemberAggregate
);
566 RosSymFreeAggregate(&MemberAggregate
);
568 Indent
[IndentLen
] = 0;
569 KdbpPrint("%s}\n", Indent
);
575 PROSSYM_INFO
KdbpSymFindCachedFile(PUNICODE_STRING ModName
);
583 ULONGLONG Result
= 0;
584 PVOID BaseAddress
= 0;
585 ROSSYM_AGGREGATE Aggregate
= {0};
586 UNICODE_STRING ModName
= {0};
587 ANSI_STRING AnsiName
= {0};
588 CHAR Indent
[100] = {0};
591 if (Argc
< 3) goto end
;
592 AnsiName
.Length
= AnsiName
.MaximumLength
= strlen(Argv
[1]);
593 AnsiName
.Buffer
= Argv
[1];
594 RtlAnsiStringToUnicodeString(&ModName
, &AnsiName
, TRUE
);
595 Info
= KdbpSymFindCachedFile(&ModName
);
597 if (!Info
|| !RosSymAggregate(Info
, Argv
[2], &Aggregate
)) {
598 DPRINT1("Could not get aggregate\n");
602 // Get an argument for location if it was given
605 PCHAR ArgStart
= Argv
[3];
606 DPRINT1("Trying to get expression\n");
607 for (i
= 3; i
< Argc
- 1; i
++)
609 len
= strlen(Argv
[i
]);
613 /* Evaluate the expression */
614 DPRINT1("Arg: %s\n", ArgStart
);
615 if (KdbpEvaluateExpression(ArgStart
, strlen(ArgStart
), &Result
)) {
616 BaseAddress
= (PVOID
)(ULONG_PTR
)Result
;
617 DPRINT1("BaseAddress: %p\n", BaseAddress
);
620 DPRINT1("BaseAddress %p\n", BaseAddress
);
621 KdbpPrintStructInternal(Info
, Indent
, !!BaseAddress
, BaseAddress
, &Aggregate
);
623 RosSymFreeAggregate(&Aggregate
);
624 RtlFreeUnicodeString(&ModName
);
629 /*!\brief Retrieves the component ID corresponding to a given component name.
631 * \param ComponentName The name of the component.
632 * \param ComponentId Receives the component id on success.
634 * \retval TRUE Success.
635 * \retval FALSE Failure.
639 IN PCSTR ComponentName
,
640 OUT PULONG ComponentId
)
644 for (i
= 0; i
< sizeof(ComponentTable
) / sizeof(ComponentTable
[0]); i
++)
646 if (_stricmp(ComponentName
, ComponentTable
[i
].Name
) == 0)
648 *ComponentId
= ComponentTable
[i
].Id
;
656 /*!\brief Displays the list of active debug channels, or enable/disable debug channels.
663 ULONG i
, j
, ComponentId
, Level
;
664 ULONG set
= DPFLTR_MASK
, clear
= DPFLTR_MASK
;
675 { "error", 1 << DPFLTR_ERROR_LEVEL
},
676 { "warning", 1 << DPFLTR_WARNING_LEVEL
},
677 { "trace", 1 << DPFLTR_TRACE_LEVEL
},
678 { "info", 1 << DPFLTR_INFO_LEVEL
},
683 /* Display the list of available debug filter components */
684 KdbpPrint("REMARKS:\n"
685 "- The 'WIN2000' system-wide debug filter component is used for DbgPrint()\n"
686 " messages without Component ID and Level.\n"
687 "- The 'DEFAULT' debug filter component is used for DbgPrint() messages with\n"
688 " an unknown Component ID.\n\n");
689 KdbpPrint("The list of debug filter components currently available on your system is:\n\n");
690 KdbpPrint(" Component Name Component ID\n"
691 "================ ==============\n");
692 for (i
= 0; i
< sizeof(ComponentTable
) / sizeof(ComponentTable
[0]); i
++)
694 KdbpPrint("%16s 0x%08lx\n", ComponentTable
[i
].Name
, ComponentTable
[i
].Id
);
699 for (i
= 1; i
< Argc
; i
++)
702 p
= opt
+ strcspn(opt
, "+-");
703 if (!p
[0]) p
= opt
; /* Assume it's a debug channel name */
707 for (j
= 0; j
< sizeof(debug_classes
) / sizeof(debug_classes
[0]); j
++)
709 SIZE_T len
= strlen(debug_classes
[j
].Name
);
710 if (len
!= (p
- opt
))
712 if (_strnicmp(opt
, debug_classes
[j
].Name
, len
) == 0) /* Found it */
715 set
|= debug_classes
[j
].Level
;
717 clear
|= debug_classes
[j
].Level
;
721 if (j
== sizeof(debug_classes
) / sizeof(debug_classes
[0]))
723 Level
= strtoul(opt
, &pend
, 0);
726 KdbpPrint("filter: bad class name '%.*s'\n", p
- opt
, opt
);
742 if (*p
== '+' || *p
== '-')
745 if (!KdbpGetComponentId(p
, &ComponentId
))
747 KdbpPrint("filter: '%s' is not a valid component name!\n", p
);
751 /* Get current mask value */
752 NtSetDebugFilterState(ComponentId
, set
, TRUE
);
753 NtSetDebugFilterState(ComponentId
, clear
, FALSE
);
759 /*!\brief Disassembles 10 instructions at eip or given address or
760 * displays 16 dwords from memory at given address.
770 ULONGLONG Result
= 0;
771 ULONG_PTR Address
= KdbCurrentTrapFrame
->Tf
.Eip
;
774 if (Argv
[0][0] == 'x') /* display memory */
776 else /* disassemble */
781 /* Check for [L count] part */
783 if (strcmp(Argv
[Argc
-2], "L") == 0)
785 ul
= strtoul(Argv
[Argc
-1], NULL
, 0);
792 else if (Argv
[Argc
-1][0] == 'L')
794 ul
= strtoul(Argv
[Argc
-1] + 1, NULL
, 0);
802 /* Put the remaining arguments back together */
804 for (ul
= 1; ul
< Argc
; ul
++)
806 Argv
[ul
][strlen(Argv
[ul
])] = ' ';
811 /* Evaluate the expression */
814 if (!KdbpEvaluateExpression(Argv
[1], KdbPromptString
.Length
+ (Argv
[1]-Argv
[0]), &Result
))
817 if (Result
> (ULONGLONG
)(~((ULONG_PTR
)0)))
818 KdbpPrint("Warning: Address %I64x is beeing truncated\n",Result
);
820 Address
= (ULONG_PTR
)Result
;
822 else if (Argv
[0][0] == 'x')
824 KdbpPrint("x: Address argument required.\n");
828 if (Argv
[0][0] == 'x')
835 if (!KdbSymPrintAddress((PVOID
)Address
, NULL
))
836 KdbpPrint("<%08x>:", Address
);
845 if (!NT_SUCCESS(KdbpSafeReadMemory(&ul
, (PVOID
)Address
, sizeof(ul
))))
846 KdbpPrint(" ????????");
848 KdbpPrint(" %08x", ul
);
850 Address
+= sizeof(ul
);
861 if (!KdbSymPrintAddress((PVOID
)Address
, NULL
))
862 KdbpPrint("<%08x>: ", Address
);
866 InstLen
= KdbpDisassemble(Address
, KdbUseIntelSyntax
);
869 KdbpPrint("<INVALID>\n");
881 /*!\brief Displays CPU registers.
888 PKTRAP_FRAME Tf
= &KdbCurrentTrapFrame
->Tf
;
890 static const PCHAR EflagsBits
[32] = { " CF", NULL
, " PF", " BIT3", " AF", " BIT5",
891 " ZF", " SF", " TF", " IF", " DF", " OF",
892 NULL
, NULL
, " NT", " BIT15", " RF", " VF",
893 " AC", " VIF", " VIP", " ID", " BIT22",
894 " BIT23", " BIT24", " BIT25", " BIT26",
895 " BIT27", " BIT28", " BIT29", " BIT30",
898 if (Argv
[0][0] == 'r') /* regs */
900 KdbpPrint("CS:EIP 0x%04x:0x%08x\n"
901 "SS:ESP 0x%04x:0x%08x\n"
902 " EAX 0x%08x EBX 0x%08x\n"
903 " ECX 0x%08x EDX 0x%08x\n"
904 " ESI 0x%08x EDI 0x%08x\n"
906 Tf
->SegCs
& 0xFFFF, Tf
->Eip
,
907 Tf
->HardwareSegSs
, Tf
->HardwareEsp
,
913 /* Display the EFlags */
914 KdbpPrint("EFLAGS 0x%08x ", Tf
->EFlags
);
915 for (i
= 0; i
< 32; i
++)
919 if ((Tf
->EFlags
& (1 << 1)) == 0)
924 KdbpPrint(" IOPL%d", (Tf
->EFlags
>> 12) & 3);
929 else if ((Tf
->EFlags
& (1 << i
)) != 0)
931 KdbpPrint(EflagsBits
[i
]);
936 else if (Argv
[0][0] == 'c') /* cregs */
938 ULONG Cr0
, Cr2
, Cr3
, Cr4
;
939 KDESCRIPTOR Gdtr
= {0, 0, 0}, Idtr
= {0, 0, 0};
941 static const PCHAR Cr0Bits
[32] = { " PE", " MP", " EM", " TS", " ET", " NE", NULL
, NULL
,
942 NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
,
943 " WP", NULL
, " AM", NULL
, NULL
, NULL
, NULL
, NULL
,
944 NULL
, NULL
, NULL
, NULL
, NULL
, " NW", " CD", " PG" };
945 static const PCHAR Cr4Bits
[32] = { " VME", " PVI", " TSD", " DE", " PSE", " PAE", " MCE", " PGE",
946 " PCE", " OSFXSR", " OSXMMEXCPT", NULL
, NULL
, NULL
, NULL
, NULL
,
947 NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
,
948 NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
};
950 /* Retrieve the control registers */
951 Cr0
= KdbCurrentTrapFrame
->Cr0
;
952 Cr2
= KdbCurrentTrapFrame
->Cr2
;
953 Cr3
= KdbCurrentTrapFrame
->Cr3
;
954 Cr4
= KdbCurrentTrapFrame
->Cr4
;
956 /* Retrieve the descriptor table and task segment registers */
957 Ke386GetGlobalDescriptorTable(&Gdtr
.Limit
);
958 Ldtr
= Ke386GetLocalDescriptorTable();
962 /* Display the control registers */
963 KdbpPrint("CR0 0x%08x ", Cr0
);
964 for (i
= 0; i
< 32; i
++)
969 if ((Cr0
& (1 << i
)) != 0)
970 KdbpPrint(Cr0Bits
[i
]);
974 KdbpPrint("CR2 0x%08x\n", Cr2
);
975 KdbpPrint("CR3 0x%08x Pagedir-Base 0x%08x %s%s\n", Cr3
, (Cr3
& 0xfffff000),
976 (Cr3
& (1 << 3)) ? " PWT" : "", (Cr3
& (1 << 4)) ? " PCD" : "" );
977 KdbpPrint("CR4 0x%08x ", Cr4
);
978 for (i
= 0; i
< 32; i
++)
983 if ((Cr4
& (1 << i
)) != 0)
984 KdbpPrint(Cr4Bits
[i
]);
988 /* Display the descriptor table and task segment registers */
989 KdbpPrint("GDTR Base 0x%08x Size 0x%04x\n", Gdtr
.Base
, Gdtr
.Limit
);
990 KdbpPrint("LDTR 0x%04x\n", Ldtr
);
991 KdbpPrint("IDTR Base 0x%08x Size 0x%04x\n", Idtr
.Base
, Idtr
.Limit
);
992 KdbpPrint("TR 0x%04x\n", Tr
);
994 else if (Argv
[0][0] == 's') /* sregs */
996 KdbpPrint("CS 0x%04x Index 0x%04x %cDT RPL%d\n",
997 Tf
->SegCs
& 0xffff, (Tf
->SegCs
& 0xffff) >> 3,
998 (Tf
->SegCs
& (1 << 2)) ? 'L' : 'G', Tf
->SegCs
& 3);
999 KdbpPrint("DS 0x%04x Index 0x%04x %cDT RPL%d\n",
1000 Tf
->SegDs
, Tf
->SegDs
>> 3, (Tf
->SegDs
& (1 << 2)) ? 'L' : 'G', Tf
->SegDs
& 3);
1001 KdbpPrint("ES 0x%04x Index 0x%04x %cDT RPL%d\n",
1002 Tf
->SegEs
, Tf
->SegEs
>> 3, (Tf
->SegEs
& (1 << 2)) ? 'L' : 'G', Tf
->SegEs
& 3);
1003 KdbpPrint("FS 0x%04x Index 0x%04x %cDT RPL%d\n",
1004 Tf
->SegFs
, Tf
->SegFs
>> 3, (Tf
->SegFs
& (1 << 2)) ? 'L' : 'G', Tf
->SegFs
& 3);
1005 KdbpPrint("GS 0x%04x Index 0x%04x %cDT RPL%d\n",
1006 Tf
->SegGs
, Tf
->SegGs
>> 3, (Tf
->SegGs
& (1 << 2)) ? 'L' : 'G', Tf
->SegGs
& 3);
1007 KdbpPrint("SS 0x%04x Index 0x%04x %cDT RPL%d\n",
1008 Tf
->HardwareSegSs
, Tf
->HardwareSegSs
>> 3, (Tf
->HardwareSegSs
& (1 << 2)) ? 'L' : 'G', Tf
->HardwareSegSs
& 3);
1012 ASSERT(Argv
[0][0] == 'd');
1013 KdbpPrint("DR0 0x%08x\n"
1019 Tf
->Dr0
, Tf
->Dr1
, Tf
->Dr2
, Tf
->Dr3
,
1028 IN USHORT TssSelector
,
1029 OUT PULONG pType OPTIONAL
,
1030 IN PKDESCRIPTOR pGdtr OPTIONAL
)
1036 /* Retrieve the Global Descriptor Table (user-provided or system) */
1040 Ke386GetGlobalDescriptorTable(&Gdtr
.Limit
);
1043 if ((TssSelector
& (sizeof(KGDTENTRY
) - 1)) ||
1044 (TssSelector
< sizeof(KGDTENTRY
)) ||
1045 (TssSelector
+ sizeof(KGDTENTRY
) - 1 > Gdtr
.Limit
))
1050 /* Retrieve the descriptor */
1051 if (!NT_SUCCESS(KdbpSafeReadMemory(&Desc
,
1052 (PVOID
)(Gdtr
.Base
+ TssSelector
),
1053 sizeof(KGDTENTRY
))))
1058 /* Check for TSS32(Avl) or TSS32(Busy) */
1059 if (Desc
.HighWord
.Bits
.Type
!= 9 && Desc
.HighWord
.Bits
.Type
!= 11)
1063 if (pType
) *pType
= Desc
.HighWord
.Bits
.Type
;
1065 Tss
= (PKTSS
)(ULONG_PTR
)(Desc
.BaseLow
|
1066 Desc
.HighWord
.Bytes
.BaseMid
<< 16 |
1067 Desc
.HighWord
.Bytes
.BaseHi
<< 24);
1074 IN USHORT TssSelector
,
1082 /* Retrieve the TSS Backlink */
1083 if (!NT_SUCCESS(KdbpSafeReadMemory(&Backlink
,
1084 (PVOID
)&Tss
->Backlink
,
1090 return (Backlink
!= 0 && Backlink
!= TssSelector
);
1094 KdbpTrapFrameFromPrevTss(
1095 IN OUT PKTRAP_FRAME TrapFrame
,
1096 OUT PUSHORT TssSelector
,
1098 IN PKDESCRIPTOR pGdtr
)
1104 /* Retrieve the TSS Backlink */
1105 if (!NT_SUCCESS(KdbpSafeReadMemory(&Backlink
,
1106 (PVOID
)&Tss
->Backlink
,
1112 /* Retrieve the parent TSS */
1113 Tss
= KdbpRetrieveTss(Backlink
, NULL
, pGdtr
);
1117 if (!NT_SUCCESS(KdbpSafeReadMemory(&Eip
,
1119 sizeof(ULONG_PTR
))))
1124 if (!NT_SUCCESS(KdbpSafeReadMemory(&Ebp
,
1126 sizeof(ULONG_PTR
))))
1131 /* Return the parent TSS and its trap frame */
1132 *TssSelector
= Backlink
;
1134 TrapFrame
->Eip
= Eip
;
1135 TrapFrame
->Ebp
= Ebp
;
1139 /*!\brief Displays a backtrace.
1147 ULONGLONG Result
= 0;
1148 KTRAP_FRAME TrapFrame
= KdbCurrentTrapFrame
->Tf
;
1149 ULONG_PTR Frame
= TrapFrame
.Ebp
;
1157 /* Check for [L count] part */
1159 if (strcmp(Argv
[Argc
-2], "L") == 0)
1161 ul
= strtoul(Argv
[Argc
-1], NULL
, 0);
1167 else if (Argv
[Argc
-1][0] == 'L')
1169 ul
= strtoul(Argv
[Argc
-1] + 1, NULL
, 0);
1176 /* Put the remaining arguments back together */
1178 for (ul
= 1; ul
< Argc
; ul
++)
1180 Argv
[ul
][strlen(Argv
[ul
])] = ' ';
1185 /* Check if a Frame Address or Thread ID is given */
1188 if (Argv
[1][0] == '*')
1192 /* Evaluate the expression */
1193 if (!KdbpEvaluateExpression(Argv
[1], KdbPromptString
.Length
+ (Argv
[1]-Argv
[0]), &Result
))
1196 if (Result
> (ULONGLONG
)(~((ULONG_PTR
)0)))
1197 KdbpPrint("Warning: Address %I64x is beeing truncated\n", Result
);
1199 Frame
= (ULONG_PTR
)Result
;
1203 KdbpPrint("Thread backtrace not supported yet!\n");
1208 /* Retrieve the Global Descriptor Table */
1209 Ke386GetGlobalDescriptorTable(&Gdtr
.Limit
);
1211 /* Retrieve the current (active) TSS */
1212 TssSelector
= Ke386GetTr();
1213 Tss
= KdbpRetrieveTss(TssSelector
, NULL
, &Gdtr
);
1214 if (KdbpIsNestedTss(TssSelector
, Tss
))
1216 /* Display the active TSS if it is nested */
1217 KdbpPrint("[Active TSS 0x%04x @ 0x%p]\n", TssSelector
, Tss
);
1220 /* If no Frame Address or Thread ID was given, try printing the function at EIP */
1223 KdbpPrint("Eip:\n");
1224 if (!KdbSymPrintAddress((PVOID
)TrapFrame
.Eip
, &TrapFrame
))
1225 KdbpPrint("<%08x>\n", TrapFrame
.Eip
);
1230 /* Walk through the frames */
1231 KdbpPrint("Frames:\n");
1234 BOOLEAN GotNextFrame
;
1237 goto CheckForParentTSS
;
1240 if (!NT_SUCCESS(KdbpSafeReadMemory(&Address
, (PVOID
)(Frame
+ sizeof(ULONG_PTR
)), sizeof(ULONG_PTR
))))
1242 KdbpPrint("Couldn't access memory at 0x%p!\n", Frame
+ sizeof(ULONG_PTR
));
1243 goto CheckForParentTSS
;
1247 goto CheckForParentTSS
;
1249 GotNextFrame
= NT_SUCCESS(KdbpSafeReadMemory(&Frame
, (PVOID
)Frame
, sizeof(ULONG_PTR
)));
1251 TrapFrame
.Ebp
= Frame
;
1255 /* Print the location of the call instruction (assumed 5 bytes length) */
1256 if (!KdbSymPrintAddress((PVOID
)(Address
- 5), &TrapFrame
))
1257 KdbpPrint("<%08x>\n", Address
);
1261 if (KdbOutputAborted
)
1266 KdbpPrint("Couldn't access memory at 0x%p!\n", Frame
);
1267 goto CheckForParentTSS
; // break;
1274 * We have ended the stack walking for the current (active) TSS.
1275 * Check whether this TSS was nested, and if so switch to its parent
1276 * and walk its stack.
1278 if (!KdbpIsNestedTss(TssSelector
, Tss
))
1279 break; // The TSS is not nested, we stop there.
1281 GotNextFrame
= KdbpTrapFrameFromPrevTss(&TrapFrame
, &TssSelector
, &Tss
, &Gdtr
);
1284 KdbpPrint("Couldn't access parent TSS 0x%04x\n", Tss
->Backlink
);
1285 break; // Cannot retrieve the parent TSS, we stop there.
1287 Address
= TrapFrame
.Eip
;
1288 Frame
= TrapFrame
.Ebp
;
1290 KdbpPrint("[Parent TSS 0x%04x @ 0x%p]\n", TssSelector
, Tss
);
1292 if (!KdbSymPrintAddress((PVOID
)Address
, &TrapFrame
))
1293 KdbpPrint("<%08x>\n", Address
);
1301 /*!\brief Continues execution of the system/leaves KDB.
1308 /* Exit the main loop */
1312 /*!\brief Continues execution of the system/leaves KDB.
1323 Count
= strtoul(Argv
[1], NULL
, 0);
1326 KdbpPrint("%s: Integer argument required\n", Argv
[0]);
1331 if (Argv
[0][0] == 'n')
1332 KdbSingleStepOver
= TRUE
;
1334 KdbSingleStepOver
= FALSE
;
1336 /* Set the number of single steps and return to the interrupted code. */
1337 KdbNumSingleSteps
= Count
;
1342 /*!\brief Lists breakpoints.
1345 KdbpCmdBreakPointList(
1350 ULONG_PTR Address
= 0;
1351 KDB_BREAKPOINT_TYPE Type
= 0;
1352 KDB_ACCESS_TYPE AccessType
= 0;
1355 BOOLEAN Enabled
= FALSE
;
1356 BOOLEAN Global
= FALSE
;
1357 PEPROCESS Process
= NULL
;
1358 PCHAR str1
, str2
, ConditionExpr
, GlobalOrLocal
;
1361 l
= KdbpGetNextBreakPointNr(0);
1364 KdbpPrint("No breakpoints.\n");
1368 KdbpPrint("Breakpoints:\n");
1371 if (!KdbpGetBreakPointInfo(l
, &Address
, &Type
, &Size
, &AccessType
, &DebugReg
,
1372 &Enabled
, &Global
, &Process
, &ConditionExpr
))
1377 if (l
== KdbLastBreakPointNr
)
1390 GlobalOrLocal
= " global";
1394 GlobalOrLocal
= Buffer
;
1395 sprintf(Buffer
, " PID 0x%08lx",
1396 (ULONG
)(Process
? Process
->UniqueProcessId
: INVALID_HANDLE_VALUE
));
1399 if (Type
== KdbBreakPointSoftware
|| Type
== KdbBreakPointTemporary
)
1401 KdbpPrint(" %s%03d BPX 0x%08x%s%s%s%s%s\n",
1403 Enabled
? "" : " disabled",
1405 ConditionExpr
? " IF " : "",
1406 ConditionExpr
? ConditionExpr
: "",
1409 else if (Type
== KdbBreakPointHardware
)
1413 KdbpPrint(" %s%03d BPM 0x%08x %-5s %-5s disabled%s%s%s%s\n", str1
, l
, Address
,
1414 KDB_ACCESS_TYPE_TO_STRING(AccessType
),
1415 Size
== 1 ? "byte" : (Size
== 2 ? "word" : "dword"),
1417 ConditionExpr
? " IF " : "",
1418 ConditionExpr
? ConditionExpr
: "",
1423 KdbpPrint(" %s%03d BPM 0x%08x %-5s %-5s DR%d%s%s%s%s\n", str1
, l
, Address
,
1424 KDB_ACCESS_TYPE_TO_STRING(AccessType
),
1425 Size
== 1 ? "byte" : (Size
== 2 ? "word" : "dword"),
1428 ConditionExpr
? " IF " : "",
1429 ConditionExpr
? ConditionExpr
: "",
1434 while ((l
= KdbpGetNextBreakPointNr(l
+1)) >= 0);
1439 /*!\brief Enables, disables or clears a breakpoint.
1442 KdbpCmdEnableDisableClearBreakPoint(
1451 KdbpPrint("%s: argument required\n", Argv
[0]);
1456 BreakPointNr
= strtoul(Argv
[1], &pend
, 0);
1457 if (pend
== Argv
[1] || *pend
!= '\0')
1459 KdbpPrint("%s: integer argument required\n", Argv
[0]);
1463 if (Argv
[0][1] == 'e') /* enable */
1465 KdbpEnableBreakPoint(BreakPointNr
, NULL
);
1467 else if (Argv
[0][1] == 'd') /* disable */
1469 KdbpDisableBreakPoint(BreakPointNr
, NULL
);
1473 ASSERT(Argv
[0][1] == 'c');
1474 KdbpDeleteBreakPoint(BreakPointNr
, NULL
);
1480 /*!\brief Sets a software or hardware (memory) breakpoint at the given address.
1483 KdbpCmdBreakPoint(ULONG Argc
, PCHAR Argv
[])
1485 ULONGLONG Result
= 0;
1487 KDB_BREAKPOINT_TYPE Type
;
1489 KDB_ACCESS_TYPE AccessType
= 0;
1490 ULONG AddressArgIndex
, i
;
1491 LONG ConditionArgIndex
;
1492 BOOLEAN Global
= TRUE
;
1494 if (Argv
[0][2] == 'x') /* software breakpoint */
1498 KdbpPrint("bpx: Address argument required.\n");
1502 AddressArgIndex
= 1;
1503 Type
= KdbBreakPointSoftware
;
1505 else /* memory breakpoint */
1507 ASSERT(Argv
[0][2] == 'm');
1511 KdbpPrint("bpm: Access type argument required (one of r, w, rw, x)\n");
1515 if (_stricmp(Argv
[1], "x") == 0)
1516 AccessType
= KdbAccessExec
;
1517 else if (_stricmp(Argv
[1], "r") == 0)
1518 AccessType
= KdbAccessRead
;
1519 else if (_stricmp(Argv
[1], "w") == 0)
1520 AccessType
= KdbAccessWrite
;
1521 else if (_stricmp(Argv
[1], "rw") == 0)
1522 AccessType
= KdbAccessReadWrite
;
1525 KdbpPrint("bpm: Unknown access type '%s'\n", Argv
[1]);
1531 KdbpPrint("bpm: %s argument required.\n", AccessType
== KdbAccessExec
? "Address" : "Memory size");
1535 AddressArgIndex
= 3;
1536 if (_stricmp(Argv
[2], "byte") == 0)
1538 else if (_stricmp(Argv
[2], "word") == 0)
1540 else if (_stricmp(Argv
[2], "dword") == 0)
1542 else if (AccessType
== KdbAccessExec
)
1549 KdbpPrint("bpm: Unknown memory size '%s'\n", Argv
[2]);
1553 if (Argc
<= AddressArgIndex
)
1555 KdbpPrint("bpm: Address argument required.\n");
1559 Type
= KdbBreakPointHardware
;
1562 /* Put the arguments back together */
1563 ConditionArgIndex
= -1;
1564 for (i
= AddressArgIndex
; i
< (Argc
-1); i
++)
1566 if (strcmp(Argv
[i
+1], "IF") == 0) /* IF found */
1568 ConditionArgIndex
= i
+ 2;
1569 if ((ULONG
)ConditionArgIndex
>= Argc
)
1571 KdbpPrint("%s: IF requires condition expression.\n", Argv
[0]);
1575 for (i
= ConditionArgIndex
; i
< (Argc
-1); i
++)
1576 Argv
[i
][strlen(Argv
[i
])] = ' ';
1581 Argv
[i
][strlen(Argv
[i
])] = ' ';
1584 /* Evaluate the address expression */
1585 if (!KdbpEvaluateExpression(Argv
[AddressArgIndex
],
1586 KdbPromptString
.Length
+ (Argv
[AddressArgIndex
]-Argv
[0]),
1592 if (Result
> (ULONGLONG
)(~((ULONG_PTR
)0)))
1593 KdbpPrint("%s: Warning: Address %I64x is beeing truncated\n", Argv
[0],Result
);
1595 Address
= (ULONG_PTR
)Result
;
1597 KdbpInsertBreakPoint(Address
, Type
, Size
, AccessType
,
1598 (ConditionArgIndex
< 0) ? NULL
: Argv
[ConditionArgIndex
],
1604 /*!\brief Lists threads or switches to another thread context.
1612 PETHREAD Thread
= NULL
;
1613 PEPROCESS Process
= NULL
;
1614 BOOLEAN ReferencedThread
= FALSE
, ReferencedProcess
= FALSE
;
1619 PCHAR State
, pend
, str1
, str2
;
1620 static const PCHAR ThreadStateToString
[DeferredReady
+1] =
1622 "Initialized", "Ready", "Running",
1623 "Standby", "Terminated", "Waiting",
1624 "Transition", "DeferredReady"
1627 ASSERT(KdbCurrentProcess
);
1629 if (Argc
>= 2 && _stricmp(Argv
[1], "list") == 0)
1631 Process
= KdbCurrentProcess
;
1635 ul
= strtoul(Argv
[2], &pend
, 0);
1636 if (Argv
[2] == pend
)
1638 KdbpPrint("thread: '%s' is not a valid process id!\n", Argv
[2]);
1642 if (!NT_SUCCESS(PsLookupProcessByProcessId((PVOID
)ul
, &Process
)))
1644 KdbpPrint("thread: Invalid process id!\n");
1648 /* Remember our reference */
1649 ReferencedProcess
= TRUE
;
1652 Entry
= Process
->ThreadListHead
.Flink
;
1653 if (Entry
== &Process
->ThreadListHead
)
1656 KdbpPrint("No threads in process 0x%08x!\n", ul
);
1658 KdbpPrint("No threads in current process!\n");
1660 if (ReferencedProcess
)
1661 ObDereferenceObject(Process
);
1666 KdbpPrint(" TID State Prior. Affinity EBP EIP\n");
1669 Thread
= CONTAINING_RECORD(Entry
, ETHREAD
, ThreadListEntry
);
1671 if (Thread
== KdbCurrentThread
)
1682 if (!Thread
->Tcb
.InitialStack
)
1684 /* Thread has no kernel stack (probably terminated) */
1688 else if (Thread
->Tcb
.TrapFrame
)
1690 if (Thread
->Tcb
.TrapFrame
->PreviousPreviousMode
== KernelMode
)
1691 Esp
= (PULONG
)Thread
->Tcb
.TrapFrame
->TempEsp
;
1693 Esp
= (PULONG
)Thread
->Tcb
.TrapFrame
->HardwareEsp
;
1695 Ebp
= (PULONG
)Thread
->Tcb
.TrapFrame
->Ebp
;
1696 Eip
= Thread
->Tcb
.TrapFrame
->Eip
;
1700 Esp
= (PULONG
)Thread
->Tcb
.KernelStack
;
1701 Ebp
= (PULONG
)Esp
[4];
1704 if (Ebp
) /* FIXME: Should we attach to the process to read Ebp[1]? */
1705 KdbpSafeReadMemory(&Eip
, Ebp
+ 1, sizeof (Eip
));
1708 if (Thread
->Tcb
.State
< (DeferredReady
+ 1))
1709 State
= ThreadStateToString
[Thread
->Tcb
.State
];
1713 KdbpPrint(" %s0x%08x %-11s %3d 0x%08x 0x%08x 0x%08x%s\n",
1715 Thread
->Cid
.UniqueThread
,
1717 Thread
->Tcb
.Priority
,
1718 Thread
->Tcb
.Affinity
,
1723 Entry
= Entry
->Flink
;
1725 while (Entry
!= &Process
->ThreadListHead
);
1727 /* Release our reference, if any */
1728 if (ReferencedProcess
)
1729 ObDereferenceObject(Process
);
1731 else if (Argc
>= 2 && _stricmp(Argv
[1], "attach") == 0)
1735 KdbpPrint("thread attach: thread id argument required!\n");
1739 ul
= strtoul(Argv
[2], &pend
, 0);
1740 if (Argv
[2] == pend
)
1742 KdbpPrint("thread attach: '%s' is not a valid thread id!\n", Argv
[2]);
1746 if (!KdbpAttachToThread((PVOID
)ul
))
1751 KdbpPrint("Attached to thread 0x%08x.\n", ul
);
1755 Thread
= KdbCurrentThread
;
1759 ul
= strtoul(Argv
[1], &pend
, 0);
1760 if (Argv
[1] == pend
)
1762 KdbpPrint("thread: '%s' is not a valid thread id!\n", Argv
[1]);
1766 if (!NT_SUCCESS(PsLookupThreadByThreadId((PVOID
)ul
, &Thread
)))
1768 KdbpPrint("thread: Invalid thread id!\n");
1772 /* Remember our reference */
1773 ReferencedThread
= TRUE
;
1776 if (Thread
->Tcb
.State
< (DeferredReady
+ 1))
1777 State
= ThreadStateToString
[Thread
->Tcb
.State
];
1783 " State: %s (0x%x)\n"
1785 " Affinity: 0x%08x\n"
1786 " Initial Stack: 0x%08x\n"
1787 " Stack Limit: 0x%08x\n"
1788 " Stack Base: 0x%08x\n"
1789 " Kernel Stack: 0x%08x\n"
1790 " Trap Frame: 0x%08x\n"
1791 " NPX State: %s (0x%x)\n",
1792 (Argc
< 2) ? "Current Thread:\n" : "",
1793 Thread
->Cid
.UniqueThread
,
1794 State
, Thread
->Tcb
.State
,
1795 Thread
->Tcb
.Priority
,
1796 Thread
->Tcb
.Affinity
,
1797 Thread
->Tcb
.InitialStack
,
1798 Thread
->Tcb
.StackLimit
,
1799 Thread
->Tcb
.StackBase
,
1800 Thread
->Tcb
.KernelStack
,
1801 Thread
->Tcb
.TrapFrame
,
1802 NPX_STATE_TO_STRING(Thread
->Tcb
.NpxState
), Thread
->Tcb
.NpxState
);
1804 /* Release our reference if we had one */
1805 if (ReferencedThread
)
1806 ObDereferenceObject(Thread
);
1812 /*!\brief Lists processes or switches to another process context.
1821 BOOLEAN ReferencedProcess
= FALSE
;
1822 PCHAR State
, pend
, str1
, str2
;
1824 extern LIST_ENTRY PsActiveProcessHead
;
1826 if (Argc
>= 2 && _stricmp(Argv
[1], "list") == 0)
1828 Entry
= PsActiveProcessHead
.Flink
;
1829 if (!Entry
|| Entry
== &PsActiveProcessHead
)
1831 KdbpPrint("No processes in the system!\n");
1835 KdbpPrint(" PID State Filename\n");
1838 Process
= CONTAINING_RECORD(Entry
, EPROCESS
, ActiveProcessLinks
);
1840 if (Process
== KdbCurrentProcess
)
1851 State
= ((Process
->Pcb
.State
== ProcessInMemory
) ? "In Memory" :
1852 ((Process
->Pcb
.State
== ProcessOutOfMemory
) ? "Out of Memory" : "In Transition"));
1854 KdbpPrint(" %s0x%08x %-10s %s%s\n",
1856 Process
->UniqueProcessId
,
1858 Process
->ImageFileName
,
1861 Entry
= Entry
->Flink
;
1863 while(Entry
!= &PsActiveProcessHead
);
1865 else if (Argc
>= 2 && _stricmp(Argv
[1], "attach") == 0)
1869 KdbpPrint("process attach: process id argument required!\n");
1873 ul
= strtoul(Argv
[2], &pend
, 0);
1874 if (Argv
[2] == pend
)
1876 KdbpPrint("process attach: '%s' is not a valid process id!\n", Argv
[2]);
1880 if (!KdbpAttachToProcess((PVOID
)ul
))
1885 KdbpPrint("Attached to process 0x%08x, thread 0x%08x.\n", (ULONG
)ul
,
1886 (ULONG
)KdbCurrentThread
->Cid
.UniqueThread
);
1890 Process
= KdbCurrentProcess
;
1894 ul
= strtoul(Argv
[1], &pend
, 0);
1895 if (Argv
[1] == pend
)
1897 KdbpPrint("proc: '%s' is not a valid process id!\n", Argv
[1]);
1901 if (!NT_SUCCESS(PsLookupProcessByProcessId((PVOID
)ul
, &Process
)))
1903 KdbpPrint("proc: Invalid process id!\n");
1907 /* Remember our reference */
1908 ReferencedProcess
= TRUE
;
1911 State
= ((Process
->Pcb
.State
== ProcessInMemory
) ? "In Memory" :
1912 ((Process
->Pcb
.State
== ProcessOutOfMemory
) ? "Out of Memory" : "In Transition"));
1915 " State: %s (0x%x)\n"
1916 " Image Filename: %s\n",
1917 (Argc
< 2) ? "Current process:\n" : "",
1918 Process
->UniqueProcessId
,
1919 State
, Process
->Pcb
.State
,
1920 Process
->ImageFileName
);
1922 /* Release our reference, if any */
1923 if (ReferencedProcess
)
1924 ObDereferenceObject(Process
);
1930 /*!\brief Lists loaded modules or the one containing the specified address.
1937 ULONGLONG Result
= 0;
1939 PLDR_DATA_TABLE_ENTRY LdrEntry
;
1940 BOOLEAN DisplayOnlyOneModule
= FALSE
;
1945 /* Put the arguments back together */
1948 Argv
[Argc
][strlen(Argv
[Argc
])] = ' ';
1950 /* Evaluate the expression */
1951 if (!KdbpEvaluateExpression(Argv
[1], KdbPromptString
.Length
+ (Argv
[1]-Argv
[0]), &Result
))
1956 if (Result
> (ULONGLONG
)(~((ULONG_PTR
)0)))
1957 KdbpPrint("%s: Warning: Address %I64x is beeing truncated\n", Argv
[0],Result
);
1959 Address
= (ULONG_PTR
)Result
;
1961 if (!KdbpSymFindModule((PVOID
)Address
, NULL
, -1, &LdrEntry
))
1963 KdbpPrint("No module containing address 0x%p found!\n", Address
);
1967 DisplayOnlyOneModule
= TRUE
;
1971 if (!KdbpSymFindModule(NULL
, NULL
, 0, &LdrEntry
))
1973 ULONG_PTR ntoskrnlBase
= ((ULONG_PTR
)KdbpCmdMod
) & 0xfff00000;
1974 KdbpPrint(" Base Size Name\n");
1975 KdbpPrint(" %08x %08x %s\n", ntoskrnlBase
, 0, "ntoskrnl.exe");
1982 KdbpPrint(" Base Size Name\n");
1985 KdbpPrint(" %08x %08x %wZ\n", LdrEntry
->DllBase
, LdrEntry
->SizeOfImage
, &LdrEntry
->BaseDllName
);
1987 if(DisplayOnlyOneModule
|| !KdbpSymFindModule(NULL
, NULL
, i
++, &LdrEntry
))
1994 /*!\brief Displays GDT, LDT or IDT.
2011 if (Argv
[0][0] == 'i')
2018 KdbpPrint("Interrupt descriptor table is empty.\n");
2022 KdbpPrint("IDT Base: 0x%08x Limit: 0x%04x\n", Reg
.Base
, Reg
.Limit
);
2023 KdbpPrint(" Idx Type Seg. Sel. Offset DPL\n");
2025 for (i
= 0; (i
+ sizeof(SegDesc
) - 1) <= Reg
.Limit
; i
+= 8)
2027 if (!NT_SUCCESS(KdbpSafeReadMemory(SegDesc
, (PVOID
)(Reg
.Base
+ i
), sizeof(SegDesc
))))
2029 KdbpPrint("Couldn't access memory at 0x%08x!\n", Reg
.Base
+ i
);
2033 Dpl
= ((SegDesc
[1] >> 13) & 3);
2034 if ((SegDesc
[1] & 0x1f00) == 0x0500) /* Task gate */
2035 SegType
= "TASKGATE";
2036 else if ((SegDesc
[1] & 0x1fe0) == 0x0e00) /* 32 bit Interrupt gate */
2037 SegType
= "INTGATE32";
2038 else if ((SegDesc
[1] & 0x1fe0) == 0x0600) /* 16 bit Interrupt gate */
2039 SegType
= "INTGATE16";
2040 else if ((SegDesc
[1] & 0x1fe0) == 0x0f00) /* 32 bit Trap gate */
2041 SegType
= "TRAPGATE32";
2042 else if ((SegDesc
[1] & 0x1fe0) == 0x0700) /* 16 bit Trap gate */
2043 SegType
= "TRAPGATE16";
2045 SegType
= "UNKNOWN";
2047 if ((SegDesc
[1] & (1 << 15)) == 0) /* not present */
2049 KdbpPrint(" %03d %-10s [NP] [NP] %02d\n",
2050 i
/ 8, SegType
, Dpl
);
2052 else if ((SegDesc
[1] & 0x1f00) == 0x0500) /* Task gate */
2054 SegSel
= SegDesc
[0] >> 16;
2055 KdbpPrint(" %03d %-10s 0x%04x %02d\n",
2056 i
/ 8, SegType
, SegSel
, Dpl
);
2060 SegSel
= SegDesc
[0] >> 16;
2061 SegBase
= (SegDesc
[1] & 0xffff0000) | (SegDesc
[0] & 0x0000ffff);
2062 KdbpPrint(" %03d %-10s 0x%04x 0x%08x %02d\n",
2063 i
/ 8, SegType
, SegSel
, SegBase
, Dpl
);
2071 if (Argv
[0][0] == 'g')
2074 Ke386GetGlobalDescriptorTable(&Reg
.Limit
);
2079 ASSERT(Argv
[0][0] == 'l');
2082 Reg
.Limit
= Ke386GetLocalDescriptorTable();
2090 KdbpPrint("%s descriptor table is empty.\n",
2091 Argv
[0][0] == 'g' ? "Global" : "Local");
2095 KdbpPrint("%cDT Base: 0x%08x Limit: 0x%04x\n",
2096 Argv
[0][0] == 'g' ? 'G' : 'L', Reg
.Base
, Reg
.Limit
);
2097 KdbpPrint(" Idx Sel. Type Base Limit DPL Attribs\n");
2099 for (; (i
+ sizeof(SegDesc
) - 1) <= Reg
.Limit
; i
+= 8)
2101 if (!NT_SUCCESS(KdbpSafeReadMemory(SegDesc
, (PVOID
)(Reg
.Base
+ i
), sizeof(SegDesc
))))
2103 KdbpPrint("Couldn't access memory at 0x%08x!\n", Reg
.Base
+ i
);
2107 Dpl
= ((SegDesc
[1] >> 13) & 3);
2108 Type
= ((SegDesc
[1] >> 8) & 0xf);
2110 SegBase
= SegDesc
[0] >> 16;
2111 SegBase
|= (SegDesc
[1] & 0xff) << 16;
2112 SegBase
|= SegDesc
[1] & 0xff000000;
2113 SegLimit
= SegDesc
[0] & 0x0000ffff;
2114 SegLimit
|= (SegDesc
[1] >> 16) & 0xf;
2116 if ((SegDesc
[1] & (1 << 23)) != 0)
2126 if ((SegDesc
[1] & (1 << 12)) == 0) /* System segment */
2130 case 1: SegType
= "TSS16(Avl)"; break;
2131 case 2: SegType
= "LDT"; break;
2132 case 3: SegType
= "TSS16(Busy)"; break;
2133 case 4: SegType
= "CALLGATE16"; break;
2134 case 5: SegType
= "TASKGATE"; break;
2135 case 6: SegType
= "INTGATE16"; break;
2136 case 7: SegType
= "TRAPGATE16"; break;
2137 case 9: SegType
= "TSS32(Avl)"; break;
2138 case 11: SegType
= "TSS32(Busy)"; break;
2139 case 12: SegType
= "CALLGATE32"; break;
2140 case 14: SegType
= "INTGATE32"; break;
2141 case 15: SegType
= "TRAPGATE32"; break;
2142 default: SegType
= "UNKNOWN"; break;
2145 if (!(Type
>= 1 && Type
<= 3) &&
2146 Type
!= 9 && Type
!= 11)
2152 else if ((SegDesc
[1] & (1 << 11)) == 0) /* Data segment */
2154 if ((SegDesc
[1] & (1 << 22)) != 0)
2159 else /* Code segment */
2161 if ((SegDesc
[1] & (1 << 22)) != 0)
2167 if ((SegDesc
[1] & (1 << 15)) == 0) /* Not present */
2169 KdbpPrint(" %03d 0x%04x %-11s [NP] [NP] %02d NP\n",
2170 i
/ 8, i
| Dpl
| ul
, SegType
, Dpl
);
2174 KdbpPrint(" %03d 0x%04x %-11s 0x%08x 0x%08x %02d ",
2175 i
/ 8, i
| Dpl
| ul
, SegType
, SegBase
, SegLimit
, Dpl
);
2177 if ((SegDesc
[1] & (1 << 12)) == 0) /* System segment */
2179 /* FIXME: Display system segment */
2181 else if ((SegDesc
[1] & (1 << 11)) == 0) /* Data segment */
2183 if ((SegDesc
[1] & (1 << 10)) != 0) /* Expand-down */
2186 KdbpPrint((SegDesc
[1] & (1 << 9)) ? " R/W" : " R");
2188 if ((SegDesc
[1] & (1 << 8)) != 0)
2191 else /* Code segment */
2193 if ((SegDesc
[1] & (1 << 10)) != 0) /* Conforming */
2196 KdbpPrint((SegDesc
[1] & (1 << 9)) ? " R/X" : " X");
2198 if ((SegDesc
[1] & (1 << 8)) != 0)
2202 if ((SegDesc
[1] & (1 << 20)) != 0)
2213 /*!\brief Displays the KPCR
2220 PKIPCR Pcr
= (PKIPCR
)KeGetPcr();
2222 KdbpPrint("Current PCR is at 0x%p.\n", Pcr
);
2223 KdbpPrint(" Tib.ExceptionList: 0x%08x\n"
2224 " Tib.StackBase: 0x%08x\n"
2225 " Tib.StackLimit: 0x%08x\n"
2226 " Tib.SubSystemTib: 0x%08x\n"
2227 " Tib.FiberData/Version: 0x%08x\n"
2228 " Tib.ArbitraryUserPointer: 0x%08x\n"
2229 " Tib.Self: 0x%08x\n"
2230 " SelfPcr: 0x%08x\n"
2234 " IrrActive: 0x%08x\n"
2236 " KdVersionBlock: 0x%08x\n"
2240 " MajorVersion: 0x%04x\n"
2241 " MinorVersion: 0x%04x\n"
2242 " SetMember: 0x%08x\n"
2243 " StallScaleFactor: 0x%08x\n"
2245 " L2CacheAssociativity: 0x%02x\n"
2246 " VdmAlert: 0x%08x\n"
2247 " L2CacheSize: 0x%08x\n"
2248 " InterruptMode: 0x%08x\n",
2249 Pcr
->NtTib
.ExceptionList
, Pcr
->NtTib
.StackBase
, Pcr
->NtTib
.StackLimit
,
2250 Pcr
->NtTib
.SubSystemTib
, Pcr
->NtTib
.FiberData
, Pcr
->NtTib
.ArbitraryUserPointer
,
2251 Pcr
->NtTib
.Self
, Pcr
->SelfPcr
, Pcr
->Prcb
, Pcr
->Irql
, Pcr
->IRR
, Pcr
->IrrActive
,
2252 Pcr
->IDR
, Pcr
->KdVersionBlock
, Pcr
->IDT
, Pcr
->GDT
, Pcr
->TSS
,
2253 Pcr
->MajorVersion
, Pcr
->MinorVersion
, Pcr
->SetMember
, Pcr
->StallScaleFactor
,
2254 Pcr
->Number
, Pcr
->SecondLevelCacheAssociativity
,
2255 Pcr
->VdmAlert
, Pcr
->SecondLevelCacheSize
, Pcr
->InterruptMode
);
2260 /*!\brief Displays the TSS
2273 * Specified TSS via its selector [selector] or descriptor address [*descaddr].
2274 * Note that we ignore any other argument values.
2276 PCHAR Param
, pszNext
;
2280 if (Argv
[1][0] == '*')
2283 ulValue
= strtoul(Param
, &pszNext
, 0);
2284 if (pszNext
&& *pszNext
)
2286 KdbpPrint("Invalid TSS specification.\n");
2290 if (Argv
[1][0] == '*')
2292 /* Descriptor specified */
2293 TssSelector
= 0; // Unknown selector!
2294 // TODO: Room for improvement: Find the TSS descriptor
2295 // in the GDT so as to validate it.
2296 Tss
= (PKTSS
)(ULONG_PTR
)ulValue
;
2299 KdbpPrint("Invalid 32-bit TSS descriptor.\n");
2305 /* Selector specified, retrive the corresponding TSS */
2306 TssSelector
= (USHORT
)ulValue
;
2307 Tss
= KdbpRetrieveTss(TssSelector
, NULL
, NULL
);
2310 KdbpPrint("Invalid 32-bit TSS selector.\n");
2318 /* If no TSS was specified, use the current TSS descriptor */
2319 TssSelector
= Ke386GetTr();
2320 Tss
= KeGetPcr()->TSS
;
2321 // NOTE: If everything works OK, Tss is the current TSS corresponding to the TR selector.
2324 KdbpPrint("%s TSS 0x%04x is at 0x%p.\n",
2325 (Tss
== KeGetPcr()->TSS
) ? "Current" : "Specified", TssSelector
, Tss
);
2326 KdbpPrint(" Backlink: 0x%04x\n"
2327 " Ss0:Esp0: 0x%04x:0x%08x\n"
2328 // NOTE: Ss1:Esp1 and Ss2:Esp2: are in the NotUsed1 field.
2348 " IoMapBase: 0x%04x\n",
2349 Tss
->Backlink
, Tss
->Ss0
, Tss
->Esp0
, Tss
->CR3
, Tss
->EFlags
,
2350 Tss
->Eax
, Tss
->Ebx
, Tss
->Ecx
, Tss
->Edx
, Tss
->Esi
, Tss
->Edi
,
2351 Tss
->Eip
, Tss
->Esp
, Tss
->Ebp
,
2352 Tss
->Cs
, Tss
->Ss
, Tss
->Ds
, Tss
->Es
, Tss
->Fs
, Tss
->Gs
,
2353 Tss
->LDT
, Tss
->Flags
, Tss
->IoMapBase
);
2358 /*!\brief Bugchecks the system.
2365 /* Set the flag and quit looping */
2366 KdbpBugCheckRequested
= TRUE
;
2375 /* Reboot immediately (we do not return) */
2376 HalReturnToFirmware(HalRebootRoutine
);
2384 IN ULONG BufLength
);
2386 /*!\brief Display debug messages on screen, with paging.
2388 * Keys for per-page view: Home, End, PageUp, Arrow Up, PageDown,
2389 * all others are as PageDown.
2398 KdbpIsInDmesgMode
= TRUE
; /* Toggle logging flag */
2399 if (!KdpDmesgBuffer
)
2401 KdbpPrint("Dmesg: error, buffer is not allocated! /DEBUGPORT=SCREEN kernel param required for dmesg.\n");
2405 KdbpPrint("*** Dmesg *** TotalWritten=%lu, BufferSize=%lu, CurrentPosition=%lu\n",
2406 KdbDmesgTotalWritten
, KdpDmesgBufferSize
, KdpDmesgCurrentPosition
);
2408 /* Pass data to the pager */
2409 end
= KdpDmesgCurrentPosition
;
2410 beg
= (end
+ KdpDmesgFreeBytes
) % KdpDmesgBufferSize
;
2412 /* No roll-overs, and overwritten=lost bytes */
2413 if (KdbDmesgTotalWritten
<= KdpDmesgBufferSize
)
2415 /* Show buffer (KdpDmesgBuffer + beg, num) */
2416 KdbpPager(KdpDmesgBuffer
, KdpDmesgCurrentPosition
);
2420 /* Show 2 buffers: (KdpDmesgBuffer + beg, KdpDmesgBufferSize - beg)
2421 * and: (KdpDmesgBuffer, end) */
2422 KdbpPager(KdpDmesgBuffer
+ beg
, KdpDmesgBufferSize
- beg
);
2423 KdbpPrint("*** Dmesg: buffer rollup ***\n");
2424 KdbpPager(KdpDmesgBuffer
, end
);
2426 KdbpPrint("*** Dmesg: end of output ***\n");
2428 KdbpIsInDmesgMode
= FALSE
; /* Toggle logging flag */
2433 /*!\brief Sets or displays a config variables value.
2443 KDB_ENTER_CONDITION ConditionFirst
= KdbDoNotEnter
;
2444 KDB_ENTER_CONDITION ConditionLast
= KdbDoNotEnter
;
2446 static const PCHAR ExceptionNames
[21] =
2448 "ZERODEVIDE", "DEBUGTRAP", "NMI", "INT3", "OVERFLOW", "BOUND", "INVALIDOP",
2449 "NOMATHCOP", "DOUBLEFAULT", "RESERVED(9)", "INVALIDTSS", "SEGMENTNOTPRESENT",
2450 "STACKFAULT", "GPF", "PAGEFAULT", "RESERVED(15)", "MATHFAULT", "ALIGNMENTCHECK",
2451 "MACHINECHECK", "SIMDFAULT", "OTHERS"
2456 KdbpPrint("Available settings:\n");
2457 KdbpPrint(" syntax [intel|at&t]\n");
2458 KdbpPrint(" condition [exception|*] [first|last] [never|always|kmode|umode]\n");
2459 KdbpPrint(" break_on_module_load [true|false]\n");
2461 else if (strcmp(Argv
[1], "syntax") == 0)
2465 KdbpPrint("syntax = %s\n", KdbUseIntelSyntax
? "intel" : "at&t");
2469 if (_stricmp(Argv
[2], "intel") == 0)
2470 KdbUseIntelSyntax
= TRUE
;
2471 else if (_stricmp(Argv
[2], "at&t") == 0)
2472 KdbUseIntelSyntax
= FALSE
;
2474 KdbpPrint("Unknown syntax '%s'.\n", Argv
[2]);
2477 else if (strcmp(Argv
[1], "condition") == 0)
2481 KdbpPrint("Conditions: (First) (Last)\n");
2482 for (l
= 0; l
< RTL_NUMBER_OF(ExceptionNames
) - 1; l
++)
2484 if (!ExceptionNames
[l
])
2487 if (!KdbpGetEnterCondition(l
, TRUE
, &ConditionFirst
))
2490 if (!KdbpGetEnterCondition(l
, FALSE
, &ConditionLast
))
2493 KdbpPrint(" #%02d %-20s %-8s %-8s\n", l
, ExceptionNames
[l
],
2494 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst
),
2495 KDB_ENTER_CONDITION_TO_STRING(ConditionLast
));
2498 ASSERT(l
== (RTL_NUMBER_OF(ExceptionNames
) - 1));
2499 KdbpPrint(" %-20s %-8s %-8s\n", ExceptionNames
[l
],
2500 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst
),
2501 KDB_ENTER_CONDITION_TO_STRING(ConditionLast
));
2505 if (Argc
>= 5 && strcmp(Argv
[2], "*") == 0) /* Allow * only when setting condition */
2511 l
= strtoul(Argv
[2], &pend
, 0);
2513 if (Argv
[2] == pend
)
2515 for (l
= 0; l
< RTL_NUMBER_OF(ExceptionNames
); l
++)
2517 if (!ExceptionNames
[l
])
2520 if (_stricmp(ExceptionNames
[l
], Argv
[2]) == 0)
2525 if (l
>= RTL_NUMBER_OF(ExceptionNames
))
2527 KdbpPrint("Unknown exception '%s'.\n", Argv
[2]);
2534 if (_stricmp(Argv
[3], "first") == 0)
2536 else if (_stricmp(Argv
[3], "last") == 0)
2540 KdbpPrint("set condition: second argument must be 'first' or 'last'\n");
2544 if (_stricmp(Argv
[4], "never") == 0)
2545 ConditionFirst
= KdbDoNotEnter
;
2546 else if (_stricmp(Argv
[4], "always") == 0)
2547 ConditionFirst
= KdbEnterAlways
;
2548 else if (_stricmp(Argv
[4], "umode") == 0)
2549 ConditionFirst
= KdbEnterFromUmode
;
2550 else if (_stricmp(Argv
[4], "kmode") == 0)
2551 ConditionFirst
= KdbEnterFromKmode
;
2554 KdbpPrint("set condition: third argument must be 'never', 'always', 'umode' or 'kmode'\n");
2558 if (!KdbpSetEnterCondition(l
, First
, ConditionFirst
))
2561 KdbpPrint("Couldn't change condition for exception #%02d\n", l
);
2563 KdbpPrint("Couldn't change condition for all exceptions\n", l
);
2566 else /* Argc >= 3 */
2568 if (!KdbpGetEnterCondition(l
, TRUE
, &ConditionFirst
))
2571 if (!KdbpGetEnterCondition(l
, FALSE
, &ConditionLast
))
2574 if (l
< (RTL_NUMBER_OF(ExceptionNames
) - 1))
2576 KdbpPrint("Condition for exception #%02d (%s): FirstChance %s LastChance %s\n",
2577 l
, ExceptionNames
[l
],
2578 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst
),
2579 KDB_ENTER_CONDITION_TO_STRING(ConditionLast
));
2583 KdbpPrint("Condition for all other exceptions: FirstChance %s LastChance %s\n",
2584 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst
),
2585 KDB_ENTER_CONDITION_TO_STRING(ConditionLast
));
2590 else if (strcmp(Argv
[1], "break_on_module_load") == 0)
2593 KdbpPrint("break_on_module_load = %s\n", KdbBreakOnModuleLoad
? "enabled" : "disabled");
2596 if (_stricmp(Argv
[2], "enable") == 0 || _stricmp(Argv
[2], "enabled") == 0 || _stricmp(Argv
[2], "true") == 0)
2597 KdbBreakOnModuleLoad
= TRUE
;
2598 else if (_stricmp(Argv
[2], "disable") == 0 || _stricmp(Argv
[2], "disabled") == 0 || _stricmp(Argv
[2], "false") == 0)
2599 KdbBreakOnModuleLoad
= FALSE
;
2601 KdbpPrint("Unknown setting '%s'.\n", Argv
[2]);
2606 KdbpPrint("Unknown setting '%s'.\n", Argv
[1]);
2612 /*!\brief Displays help screen.
2621 KdbpPrint("Kernel debugger commands:\n");
2622 for (i
= 0; i
< RTL_NUMBER_OF(KdbDebuggerCommands
); i
++)
2624 if (!KdbDebuggerCommands
[i
].Syntax
) /* Command group */
2629 KdbpPrint("\x1b[7m* %s:\x1b[0m\n", KdbDebuggerCommands
[i
].Help
);
2633 KdbpPrint(" %-20s - %s\n",
2634 KdbDebuggerCommands
[i
].Syntax
,
2635 KdbDebuggerCommands
[i
].Help
);
2641 /*!\brief Prints the given string with printf-like formatting.
2643 * \param Format Format of the string/arguments.
2644 * \param ... Variable number of arguments matching the format specified in \a Format.
2646 * \note Doesn't correctly handle \\t and terminal escape sequences when calculating the
2647 * number of lines required to print a single line from the Buffer in the terminal.
2648 * Prints maximum 4096 chars, because of its buffer size.
2655 static CHAR Buffer
[4096];
2656 static BOOLEAN TerminalInitialized
= FALSE
;
2657 static BOOLEAN TerminalConnected
= FALSE
;
2658 static BOOLEAN TerminalReportsSize
= TRUE
;
2663 LONG RowsPrintedByTerminal
;
2667 /* Check if the user has aborted output of the current command */
2668 if (KdbOutputAborted
)
2671 /* Initialize the terminal */
2672 if (!TerminalInitialized
)
2674 DbgPrint("\x1b[7h"); /* Enable linewrap */
2676 /* Query terminal type */
2677 /*DbgPrint("\x1b[Z");*/
2680 TerminalInitialized
= TRUE
;
2682 KeStallExecutionProcessor(100000);
2686 c
= KdbpTryGetCharSerial(5000);
2690 Buffer
[Length
++] = c
;
2691 if (Length
>= (sizeof (Buffer
) - 1))
2695 Buffer
[Length
] = '\0';
2697 TerminalConnected
= TRUE
;
2700 /* Get number of rows and columns in terminal */
2701 if ((KdbNumberOfRowsTerminal
< 0) || (KdbNumberOfColsTerminal
< 0) ||
2702 (KdbNumberOfRowsPrinted
) == 0) /* Refresh terminal size each time when number of rows printed is 0 */
2704 if ((KdbDebugState
& KD_DEBUG_KDSERIAL
) && TerminalConnected
&& TerminalReportsSize
)
2706 /* Try to query number of rows from terminal. A reply looks like "\x1b[8;24;80t" */
2707 TerminalReportsSize
= FALSE
;
2708 KeStallExecutionProcessor(100000);
2709 DbgPrint("\x1b[18t");
2710 c
= KdbpTryGetCharSerial(5000);
2714 c
= KdbpTryGetCharSerial(5000);
2721 c
= KdbpTryGetCharSerial(5000);
2725 Buffer
[Length
++] = c
;
2726 if (isalpha(c
) || Length
>= (sizeof (Buffer
) - 1))
2730 Buffer
[Length
] = '\0';
2731 if (Buffer
[0] == '8' && Buffer
[1] == ';')
2733 for (i
= 2; (i
< Length
) && (Buffer
[i
] != ';'); i
++);
2735 if (Buffer
[i
] == ';')
2739 /* Number of rows is now at Buffer + 2 and number of cols at Buffer + i */
2740 KdbNumberOfRowsTerminal
= strtoul(Buffer
+ 2, NULL
, 0);
2741 KdbNumberOfColsTerminal
= strtoul(Buffer
+ i
, NULL
, 0);
2742 TerminalReportsSize
= TRUE
;
2746 /* Clear further characters */
2747 while ((c
= KdbpTryGetCharSerial(5000)) != -1);
2751 if (KdbNumberOfRowsTerminal
<= 0)
2753 /* Set number of rows to the default. */
2754 KdbNumberOfRowsTerminal
= 23; //24; //Mna.: 23 for SCREEN debugport
2756 else if (KdbNumberOfColsTerminal
<= 0)
2758 /* Set number of cols to the default. */
2759 KdbNumberOfColsTerminal
= 75; //80; //Mna.: 75 for SCREEN debugport
2763 /* Get the string */
2764 va_start(ap
, Format
);
2765 Length
= _vsnprintf(Buffer
, sizeof (Buffer
) - 1, Format
, ap
);
2766 Buffer
[Length
] = '\0';
2770 while (p
[0] != '\0')
2772 i
= strcspn(p
, "\n");
2774 /* Calculate the number of lines which will be printed in the terminal
2775 * when outputting the current line
2778 RowsPrintedByTerminal
= (i
+ KdbNumberOfColsPrinted
- 1) / KdbNumberOfColsTerminal
;
2780 RowsPrintedByTerminal
= 0;
2783 RowsPrintedByTerminal
++;
2785 /*DbgPrint("!%d!%d!%d!%d!", KdbNumberOfRowsPrinted, KdbNumberOfColsPrinted, i, RowsPrintedByTerminal);*/
2787 /* Display a prompt if we printed one screen full of text */
2788 if (KdbNumberOfRowsTerminal
> 0 &&
2789 (LONG
)(KdbNumberOfRowsPrinted
+ RowsPrintedByTerminal
) >= KdbNumberOfRowsTerminal
)
2791 KdbRepeatLastCommand
= FALSE
;
2793 if (KdbNumberOfColsPrinted
> 0)
2796 DbgPrint("--- Press q to abort, any other key to continue ---");
2797 RowsPrintedByTerminal
++; /* added by Mna. */
2799 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
2800 c
= KdbpGetCharSerial();
2802 c
= KdbpGetCharKeyboard(&ScanCode
);
2806 /* Try to read '\n' which might follow '\r' - if \n is not received here
2807 * it will be interpreted as "return" when the next command should be read.
2809 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
2810 c
= KdbpTryGetCharSerial(5);
2812 c
= KdbpTryGetCharKeyboard(&ScanCode
, 5);
2818 KdbOutputAborted
= TRUE
;
2822 KdbNumberOfRowsPrinted
= 0;
2823 KdbNumberOfColsPrinted
= 0;
2826 /* Insert a NUL after the line and print only the current line. */
2827 if (p
[i
] == '\n' && p
[i
+ 1] != '\0')
2837 /* Remove escape sequences from the line if there's no terminal connected */
2838 if (!TerminalConnected
)
2840 while ((p2
= strrchr(p
, '\x1b'))) /* Look for escape character */
2842 size_t len
= strlen(p2
);
2846 while (!isalpha(p2
[j
++]));
2847 memmove(p2
, p2
+ j
, len
+ 1 - j
);
2851 memmove(p2
, p2
+ 1, len
);
2861 /* Set p to the start of the next line and
2862 * remember the number of rows/cols printed
2868 KdbNumberOfColsPrinted
= 0;
2872 ASSERT(p
[0] == '\0');
2873 KdbNumberOfColsPrinted
+= i
;
2876 KdbNumberOfRowsPrinted
+= RowsPrintedByTerminal
;
2880 /** memrchr(), explicitly defined, since was absent in MinGW of RosBE. */
2883 * Find the last occurrence of 'c' in the buffer 's' of size 'n'.
2886 memrchr(const void *s
, int c
, size_t n
)
2888 const unsigned char *cp
;
2892 cp
= (unsigned char *)s
+ n
;
2895 if (*(--cp
) == (unsigned char)c
)
2902 /*!\brief Calculate pointer position for N lines upper of current position.
2904 * \param Buffer Characters buffer to operate on.
2905 * \param BufLength Buffer size.
2907 * \note Calculate pointer position for N lines upper of current displaying
2908 * position within the given buffer.
2910 * Used by KdbpPager().
2911 * Now N lines count is hardcoded to KdbNumberOfRowsTerminal.
2914 CountOnePageUp(PCHAR Buffer
, ULONG BufLength
, PCHAR pCurPos
)
2917 // p0 is initial guess of Page Start
2918 ULONG p0len
= KdbNumberOfRowsTerminal
* KdbNumberOfColsTerminal
;
2919 PCHAR p0
= pCurPos
- p0len
;
2920 PCHAR prev_p
= p0
, p1
;
2923 if (pCurPos
< Buffer
)
2925 ASSERT(pCurPos
<= Buffer
+ BufLength
);
2927 p
= memrchr(p0
, '\n', p0len
);
2930 for (j
= KdbNumberOfRowsTerminal
; j
--; )
2933 p1
= memrchr(p0
, '\n', p
-p0
);
2943 linesCnt
= (KdbNumberOfColsTerminal
+prev_p
-p
-2) / KdbNumberOfColsTerminal
;
2953 /*!\brief Prints the given string with, page by page.
2955 * \param Buffer Characters buffer to print.
2956 * \param BufferLen Buffer size.
2958 * \note Doesn't correctly handle \\t and terminal escape sequences when calculating the
2959 * number of lines required to print a single line from the Buffer in the terminal.
2960 * Maximum length of buffer is limited only by memory size.
2962 * Note: BufLength should be greater then (KdbNumberOfRowsTerminal * KdbNumberOfColsTerminal).
2970 static CHAR InBuffer
[4096];
2971 static BOOLEAN TerminalInitialized
= FALSE
;
2972 static BOOLEAN TerminalConnected
= FALSE
;
2973 static BOOLEAN TerminalReportsSize
= TRUE
;
2978 LONG RowsPrintedByTerminal
;
2984 /* Check if the user has aborted output of the current command */
2985 if (KdbOutputAborted
)
2988 /* Initialize the terminal */
2989 if (!TerminalInitialized
)
2991 DbgPrint("\x1b[7h"); /* Enable linewrap */
2993 /* Query terminal type */
2994 /*DbgPrint("\x1b[Z");*/
2997 TerminalInitialized
= TRUE
;
2999 KeStallExecutionProcessor(100000);
3003 c
= KdbpTryGetCharSerial(5000);
3007 InBuffer
[Length
++] = c
;
3008 if (Length
>= (sizeof (InBuffer
) - 1))
3012 InBuffer
[Length
] = '\0';
3014 TerminalConnected
= TRUE
;
3017 /* Get number of rows and columns in terminal */
3018 if ((KdbNumberOfRowsTerminal
< 0) || (KdbNumberOfColsTerminal
< 0) ||
3019 (KdbNumberOfRowsPrinted
) == 0) /* Refresh terminal size each time when number of rows printed is 0 */
3021 if ((KdbDebugState
& KD_DEBUG_KDSERIAL
) && TerminalConnected
&& TerminalReportsSize
)
3023 /* Try to query number of rows from terminal. A reply looks like "\x1b[8;24;80t" */
3024 TerminalReportsSize
= FALSE
;
3025 KeStallExecutionProcessor(100000);
3026 DbgPrint("\x1b[18t");
3027 c
= KdbpTryGetCharSerial(5000);
3031 c
= KdbpTryGetCharSerial(5000);
3038 c
= KdbpTryGetCharSerial(5000);
3042 InBuffer
[Length
++] = c
;
3043 if (isalpha(c
) || Length
>= (sizeof (InBuffer
) - 1))
3047 InBuffer
[Length
] = '\0';
3048 if (InBuffer
[0] == '8' && InBuffer
[1] == ';')
3050 for (i
= 2; (i
< Length
) && (InBuffer
[i
] != ';'); i
++);
3052 if (Buffer
[i
] == ';')
3056 /* Number of rows is now at Buffer + 2 and number of cols at Buffer + i */
3057 KdbNumberOfRowsTerminal
= strtoul(InBuffer
+ 2, NULL
, 0);
3058 KdbNumberOfColsTerminal
= strtoul(InBuffer
+ i
, NULL
, 0);
3059 TerminalReportsSize
= TRUE
;
3063 /* Clear further characters */
3064 while ((c
= KdbpTryGetCharSerial(5000)) != -1);
3068 if (KdbNumberOfRowsTerminal
<= 0)
3070 /* Set number of rows to the default. */
3071 KdbNumberOfRowsTerminal
= 24;
3073 else if (KdbNumberOfColsTerminal
<= 0)
3075 /* Set number of cols to the default. */
3076 KdbNumberOfColsTerminal
= 80;
3080 /* Get the string */
3083 while (p
[0] != '\0')
3085 if ( p
> Buffer
+BufLength
)
3087 DbgPrint("Dmesg: error, p > Buffer+BufLength,d=%d", p
- (Buffer
+BufLength
));
3090 i
= strcspn(p
, "\n");
3092 // Are we out of buffer?
3093 if (p
+ i
> Buffer
+ BufLength
)
3094 // Leaving pager function:
3097 /* Calculate the number of lines which will be printed in the terminal
3098 * when outputting the current line.
3101 RowsPrintedByTerminal
= (i
+ KdbNumberOfColsPrinted
- 1) / KdbNumberOfColsTerminal
;
3103 RowsPrintedByTerminal
= 0;
3106 RowsPrintedByTerminal
++;
3108 /*DbgPrint("!%d!%d!%d!%d!", KdbNumberOfRowsPrinted, KdbNumberOfColsPrinted, i, RowsPrintedByTerminal);*/
3110 /* Display a prompt if we printed one screen full of text */
3111 if (KdbNumberOfRowsTerminal
> 0 &&
3112 (LONG
)(KdbNumberOfRowsPrinted
+ RowsPrintedByTerminal
) >= KdbNumberOfRowsTerminal
)
3114 KdbRepeatLastCommand
= FALSE
;
3116 if (KdbNumberOfColsPrinted
> 0)
3119 DbgPrint("--- Press q to abort, e/End,h/Home,u/PgUp, other key/PgDn ---");
3120 RowsPrintedByTerminal
++;
3122 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
3123 c
= KdbpGetCharSerial();
3125 c
= KdbpGetCharKeyboard(&ScanCode
);
3129 /* Try to read '\n' which might follow '\r' - if \n is not received here
3130 * it will be interpreted as "return" when the next command should be read.
3132 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
3133 c
= KdbpTryGetCharSerial(5);
3135 c
= KdbpTryGetCharKeyboard(&ScanCode
, 5);
3138 //DbgPrint("\n"); //Consize version: don't show pressed key
3139 DbgPrint(" '%c'/scan=%04x\n", c
, ScanCode
); // Shows pressed key
3143 KdbOutputAborted
= TRUE
;
3146 if ( ScanCode
== KEYSC_END
|| c
=='e')
3148 PCHAR pBufEnd
= Buffer
+ BufLength
;
3149 p
= CountOnePageUp(Buffer
, BufLength
, pBufEnd
);
3150 i
= strcspn(p
, "\n");
3152 else if (ScanCode
== KEYSC_PAGEUP
|| c
=='u')
3154 p
= CountOnePageUp(Buffer
, BufLength
, p
);
3155 i
= strcspn(p
, "\n");
3157 else if (ScanCode
== KEYSC_HOME
|| c
=='h')
3160 i
= strcspn(p
, "\n");
3162 else if (ScanCode
== KEYSC_ARROWUP
)
3164 p
= CountOnePageUp(Buffer
, BufLength
, p
);
3165 i
= strcspn(p
, "\n");
3168 KdbNumberOfRowsPrinted
= 0;
3169 KdbNumberOfColsPrinted
= 0;
3172 /* Insert a NUL after the line and print only the current line. */
3173 if (p
[i
] == '\n' && p
[i
+ 1] != '\0')
3183 /* Remove escape sequences from the line if there's no terminal connected */
3184 if (!TerminalConnected
)
3186 while ((p2
= strrchr(p
, '\x1b'))) /* Look for escape character */
3188 size_t len
= strlen(p2
);
3192 while (!isalpha(p2
[j
++]));
3193 memmove(p2
, p2
+ j
, len
+ 1 - j
);
3197 memmove(p2
, p2
+ 1, len
);
3202 // The main printing of the current line:
3205 // restore not null char with saved:
3209 /* Set p to the start of the next line and
3210 * remember the number of rows/cols printed
3216 KdbNumberOfColsPrinted
= 0;
3220 ASSERT(p
[0] == '\0');
3221 KdbNumberOfColsPrinted
+= i
;
3224 KdbNumberOfRowsPrinted
+= RowsPrintedByTerminal
;
3228 /*!\brief Appends a command to the command history
3230 * \param Command Pointer to the command to append to the history.
3233 KdbpCommandHistoryAppend(
3236 ULONG Length1
= strlen(Command
) + 1;
3241 ASSERT(Length1
<= RTL_NUMBER_OF(KdbCommandHistoryBuffer
));
3244 (KdbCommandHistory
[KdbCommandHistoryIndex
] &&
3245 strcmp(KdbCommandHistory
[KdbCommandHistoryIndex
], Command
) == 0))
3250 /* Calculate Length1 and Length2 */
3251 Buffer
= KdbCommandHistoryBuffer
+ KdbCommandHistoryBufferIndex
;
3252 KdbCommandHistoryBufferIndex
+= Length1
;
3253 if (KdbCommandHistoryBufferIndex
>= (LONG
)RTL_NUMBER_OF(KdbCommandHistoryBuffer
))
3255 KdbCommandHistoryBufferIndex
-= RTL_NUMBER_OF(KdbCommandHistoryBuffer
);
3256 Length2
= KdbCommandHistoryBufferIndex
;
3260 /* Remove previous commands until there is enough space to append the new command */
3261 for (i
= KdbCommandHistoryIndex
; KdbCommandHistory
[i
];)
3264 (KdbCommandHistory
[i
] >= Buffer
||
3265 KdbCommandHistory
[i
] < (KdbCommandHistoryBuffer
+ KdbCommandHistoryBufferIndex
))) ||
3267 (KdbCommandHistory
[i
] >= Buffer
&&
3268 KdbCommandHistory
[i
] < (KdbCommandHistoryBuffer
+ KdbCommandHistoryBufferIndex
))))
3270 KdbCommandHistory
[i
] = NULL
;
3275 i
= RTL_NUMBER_OF(KdbCommandHistory
) - 1;
3277 if (i
== KdbCommandHistoryIndex
)
3281 /* Make sure the new command history entry is free */
3282 KdbCommandHistoryIndex
++;
3283 KdbCommandHistoryIndex
%= RTL_NUMBER_OF(KdbCommandHistory
);
3284 if (KdbCommandHistory
[KdbCommandHistoryIndex
])
3286 KdbCommandHistory
[KdbCommandHistoryIndex
] = NULL
;
3289 /* Append command */
3290 KdbCommandHistory
[KdbCommandHistoryIndex
] = Buffer
;
3291 ASSERT((KdbCommandHistory
[KdbCommandHistoryIndex
] + Length1
) <= KdbCommandHistoryBuffer
+ RTL_NUMBER_OF(KdbCommandHistoryBuffer
));
3292 memcpy(KdbCommandHistory
[KdbCommandHistoryIndex
], Command
, Length1
);
3295 memcpy(KdbCommandHistoryBuffer
, Command
+ Length1
, Length2
);
3299 /*!\brief Reads a line of user-input.
3301 * \param Buffer Buffer to store the input into. Trailing newlines are removed.
3302 * \param Size Size of \a Buffer.
3304 * \note Accepts only \n newlines, \r is ignored.
3312 PCHAR Orig
= Buffer
;
3315 static CHAR LastCommand
[1024];
3316 static CHAR NextKey
= '\0';
3317 INT CmdHistIndex
= -1;
3320 EchoOn
= !((KdbDebugState
& KD_DEBUG_KDNOECHO
) != 0);
3324 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
3326 Key
= (NextKey
== '\0') ? KdbpGetCharSerial() : NextKey
;
3329 if (Key
== KEY_ESC
) /* ESC */
3331 Key
= KdbpGetCharSerial();
3334 Key
= KdbpGetCharSerial();
3339 ScanCode
= KEY_SCAN_UP
;
3342 ScanCode
= KEY_SCAN_DOWN
;
3355 Key
= (NextKey
== '\0') ? KdbpGetCharKeyboard(&ScanCode
) : NextKey
;
3359 if ((ULONG
)(Buffer
- Orig
) >= (Size
- 1))
3361 /* Buffer is full, accept only newlines */
3368 /* Read the next char - this is to throw away a \n which most clients should
3371 KeStallExecutionProcessor(100000);
3373 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
3374 NextKey
= KdbpTryGetCharSerial(5);
3376 NextKey
= KdbpTryGetCharKeyboard(&ScanCode
, 5);
3378 if (NextKey
== '\n' || NextKey
== -1) /* \n or no response at all */
3384 * Repeat the last command if the user presses enter. Reduces the
3385 * risk of RSI when single-stepping.
3389 KdbRepeatLastCommand
= TRUE
;
3391 RtlStringCbCopyA(LastCommand
, sizeof(LastCommand
), Orig
);
3393 else if (KdbRepeatLastCommand
)
3394 RtlStringCbCopyA(Buffer
, Size
, LastCommand
);
3400 else if (Key
== KEY_BS
|| Key
== KEY_DEL
)
3408 KdbpPrint("%c %c", KEY_BS
, KEY_BS
);
3410 KdbpPrint(" %c", KEY_BS
);
3413 else if (ScanCode
== KEY_SCAN_UP
)
3415 BOOLEAN Print
= TRUE
;
3417 if (CmdHistIndex
< 0)
3419 CmdHistIndex
= KdbCommandHistoryIndex
;
3423 i
= CmdHistIndex
- 1;
3426 CmdHistIndex
= RTL_NUMBER_OF(KdbCommandHistory
) - 1;
3428 if (KdbCommandHistory
[i
] && i
!= KdbCommandHistoryIndex
)
3434 if (Print
&& KdbCommandHistory
[CmdHistIndex
])
3436 while (Buffer
> Orig
)
3442 KdbpPrint("%c %c", KEY_BS
, KEY_BS
);
3444 KdbpPrint(" %c", KEY_BS
);
3447 i
= min(strlen(KdbCommandHistory
[CmdHistIndex
]), Size
- 1);
3448 memcpy(Orig
, KdbCommandHistory
[CmdHistIndex
], i
);
3451 KdbpPrint("%s", Orig
);
3454 else if (ScanCode
== KEY_SCAN_DOWN
)
3456 if (CmdHistIndex
> 0 && CmdHistIndex
!= KdbCommandHistoryIndex
)
3458 i
= CmdHistIndex
+ 1;
3459 if (i
>= (INT
)RTL_NUMBER_OF(KdbCommandHistory
))
3462 if (KdbCommandHistory
[i
])
3465 while (Buffer
> Orig
)
3471 KdbpPrint("%c %c", KEY_BS
, KEY_BS
);
3473 KdbpPrint(" %c", KEY_BS
);
3476 i
= min(strlen(KdbCommandHistory
[CmdHistIndex
]), Size
- 1);
3477 memcpy(Orig
, KdbCommandHistory
[CmdHistIndex
], i
);
3480 KdbpPrint("%s", Orig
);
3487 KdbpPrint("%c", Key
);
3498 KdbRegisterCliCallback(
3504 /* Loop all entries */
3505 for (i
= 0; i
< _countof(KdbCliCallbacks
); i
++)
3507 /* Check if deregistering was requested */
3510 /* Check if this entry is the one that was registered */
3511 if (KdbCliCallbacks
[i
] == Callback
)
3513 /* Delete it and report success */
3514 KdbCliCallbacks
[i
] = NULL
;
3520 /* Check if this entry is free */
3521 if (KdbCliCallbacks
[i
] == NULL
)
3523 /* Set it and and report success */
3524 KdbCliCallbacks
[i
] = Callback
;
3534 /*! \brief Invokes registered CLI callbacks until one of them handled the
3537 * \param Command - Command line to parse and execute if possible.
3538 * \param Argc - Number of arguments in Argv
3539 * \param Argv - Array of strings, each of them containing one argument.
3541 * \return TRUE, if the command was handled, FALSE if it was not handled.
3545 KdbpInvokeCliCallbacks(
3552 /* Loop all entries */
3553 for (i
= 0; i
< _countof(KdbCliCallbacks
); i
++)
3555 /* Check if this entry is registered */
3556 if (KdbCliCallbacks
[i
])
3558 /* Invoke the callback and check if it handled the command */
3559 if (KdbCliCallbacks
[i
](Command
, Argc
, Argv
))
3566 /* None of the callbacks handled the command */
3571 /*!\brief Parses command line and executes command if found
3573 * \param Command Command line to parse and execute if possible.
3575 * \retval TRUE Don't continue execution.
3576 * \retval FALSE Continue execution (leave KDB)
3585 // FIXME: for what do we need a 1024 characters command line and 256 tokens?
3586 static PCHAR Argv
[256];
3587 static CHAR OrigCommand
[1024];
3589 RtlStringCbCopyA(OrigCommand
, sizeof(OrigCommand
), Command
);
3596 while (*p
== '\t' || *p
== ' ')
3602 i
= strcspn(p
, "\t ");
3615 for (i
= 0; i
< RTL_NUMBER_OF(KdbDebuggerCommands
); i
++)
3617 if (!KdbDebuggerCommands
[i
].Name
)
3620 if (strcmp(KdbDebuggerCommands
[i
].Name
, Argv
[0]) == 0)
3622 return KdbDebuggerCommands
[i
].Fn(Argc
, Argv
);
3626 /* Now invoke the registered callbacks */
3627 if (KdbpInvokeCliCallbacks(Command
, Argc
, Argv
))
3632 KdbpPrint("Command '%s' is unknown.\n", OrigCommand
);
3636 /*!\brief KDB Main Loop.
3638 * \param EnteredOnSingleStep TRUE if KDB was entered on single step.
3642 IN BOOLEAN EnteredOnSingleStep
)
3644 static CHAR Command
[1024];
3647 if (EnteredOnSingleStep
)
3649 if (!KdbSymPrintAddress((PVOID
)KdbCurrentTrapFrame
->Tf
.Eip
, &KdbCurrentTrapFrame
->Tf
))
3651 KdbpPrint("<%08x>", KdbCurrentTrapFrame
->Tf
.Eip
);
3655 if (KdbpDisassemble(KdbCurrentTrapFrame
->Tf
.Eip
, KdbUseIntelSyntax
) < 0)
3657 KdbpPrint("<INVALID>");
3662 /* Flush the input buffer */
3663 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
3665 while (KdbpTryGetCharSerial(1) != -1);
3670 while (KdbpTryGetCharKeyboard(&ScanCode
, 1) != -1);
3676 /* Reset the number of rows/cols printed */
3677 KdbNumberOfRowsPrinted
= KdbNumberOfColsPrinted
= 0;
3679 /* Print the prompt */
3680 KdbpPrint(KdbPromptString
.Buffer
);
3682 /* Read a command and remember it */
3683 KdbpReadCommand(Command
, sizeof (Command
));
3684 KdbpCommandHistoryAppend(Command
);
3686 /* Reset the number of rows/cols printed and output aborted state */
3687 KdbNumberOfRowsPrinted
= KdbNumberOfColsPrinted
= 0;
3688 KdbOutputAborted
= FALSE
;
3690 /* Call the command */
3691 Continue
= KdbpDoCommand(Command
);
3692 KdbOutputAborted
= FALSE
;
3697 /*!\brief Called when a module is loaded.
3699 * \param Name Filename of the module which was loaded.
3702 KdbpCliModuleLoaded(
3703 IN PUNICODE_STRING Name
)
3705 if (!KdbBreakOnModuleLoad
)
3708 KdbpPrint("Module %wZ loaded.\n", Name
);
3709 DbgBreakPointWithStatus(DBG_STATUS_CONTROL_C
);
3712 /*!\brief This function is called by KdbEnterDebuggerException...
3714 * Used to interpret the init file in a context with a trapframe setup
3715 * (KdbpCliInit call KdbEnter which will call KdbEnterDebuggerException which will
3716 * call this function if KdbInitFileBuffer is not NULL.
3719 KdbpCliInterpretInitFile(VOID
)
3725 /* Execute the commands in the init file */
3726 DPRINT("KDB: Executing KDBinit file...\n");
3727 p1
= KdbInitFileBuffer
;
3728 while (p1
[0] != '\0')
3730 i
= strcspn(p1
, "\r\n");
3736 /* Look for "break" command and comments */
3739 while (isspace(p2
[0]))
3742 if (strncmp(p2
, "break", sizeof("break")-1) == 0 &&
3743 (p2
[sizeof("break")-1] == '\0' || isspace(p2
[sizeof("break")-1])))
3745 /* break into the debugger */
3746 KdbpCliMainLoop(FALSE
);
3748 else if (p2
[0] != '#' && p2
[0] != '\0') /* Ignore empty lines and comments */
3757 while (p1
[0] == '\r' || p1
[0] == '\n')
3760 DPRINT("KDB: KDBinit executed\n");
3763 /*!\brief Called when KDB is initialized
3765 * Reads the KDBinit file from the SystemRoot\System32\drivers\etc directory and executes it.
3771 OBJECT_ATTRIBUTES ObjectAttributes
;
3772 UNICODE_STRING FileName
;
3773 IO_STATUS_BLOCK Iosb
;
3774 FILE_STANDARD_INFORMATION FileStdInfo
;
3775 HANDLE hFile
= NULL
;
3780 /* Initialize the object attributes */
3781 RtlInitUnicodeString(&FileName
, L
"\\SystemRoot\\System32\\drivers\\etc\\KDBinit");
3782 InitializeObjectAttributes(&ObjectAttributes
, &FileName
, 0, NULL
, NULL
);
3785 Status
= ZwOpenFile(&hFile
, FILE_READ_DATA
| SYNCHRONIZE
,
3786 &ObjectAttributes
, &Iosb
, 0,
3787 FILE_NON_DIRECTORY_FILE
| FILE_SYNCHRONOUS_IO_NONALERT
|
3788 FILE_NO_INTERMEDIATE_BUFFERING
);
3789 if (!NT_SUCCESS(Status
))
3791 DPRINT("Could not open \\SystemRoot\\System32\\drivers\\etc\\KDBinit (Status 0x%x)", Status
);
3795 /* Get the size of the file */
3796 Status
= ZwQueryInformationFile(hFile
, &Iosb
, &FileStdInfo
, sizeof (FileStdInfo
),
3797 FileStandardInformation
);
3798 if (!NT_SUCCESS(Status
))
3801 DPRINT("Could not query size of \\SystemRoot\\System32\\drivers\\etc\\KDBinit (Status 0x%x)", Status
);
3804 FileSize
= FileStdInfo
.EndOfFile
.u
.LowPart
;
3806 /* Allocate memory for the file */
3807 FileBuffer
= ExAllocatePool(PagedPool
, FileSize
+ 1); /* add 1 byte for terminating '\0' */
3811 DPRINT("Could not allocate %d bytes for KDBinit file\n", FileSize
);
3815 /* Load file into memory */
3816 Status
= ZwReadFile(hFile
, NULL
, NULL
, NULL
, &Iosb
, FileBuffer
, FileSize
, NULL
, NULL
);
3819 if (!NT_SUCCESS(Status
) && Status
!= STATUS_END_OF_FILE
)
3821 ExFreePool(FileBuffer
);
3822 DPRINT("Could not read KDBinit file into memory (Status 0x%lx)\n", Status
);
3826 FileSize
= min(FileSize
, (INT
)Iosb
.Information
);
3827 FileBuffer
[FileSize
] = '\0';
3829 /* Enter critical section */
3830 OldEflags
= __readeflags();
3833 /* Interpret the init file... */
3834 KdbInitFileBuffer
= FileBuffer
;
3836 KdbInitFileBuffer
= NULL
;
3838 /* Leave critical section */
3839 __writeeflags(OldEflags
);
3841 ExFreePool(FileBuffer
);