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/dbg/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
KdbpCmdFilter(ULONG Argc
, PCHAR Argv
[]);
89 static BOOLEAN
KdbpCmdSet(ULONG Argc
, PCHAR Argv
[]);
90 static BOOLEAN
KdbpCmdHelp(ULONG Argc
, PCHAR Argv
[]);
91 static BOOLEAN
KdbpCmdDmesg(ULONG Argc
, PCHAR Argv
[]);
94 static BOOLEAN
KdbpCmdPrintStruct(ULONG Argc
, PCHAR Argv
[]);
97 /* GLOBALS *******************************************************************/
99 static BOOLEAN KdbUseIntelSyntax
= FALSE
; /* Set to TRUE for intel syntax */
100 static BOOLEAN KdbBreakOnModuleLoad
= FALSE
; /* Set to TRUE to break into KDB when a module is loaded */
102 static CHAR KdbCommandHistoryBuffer
[2048]; /* Command history string ringbuffer */
103 static PCHAR KdbCommandHistory
[sizeof(KdbCommandHistoryBuffer
) / 8] = { NULL
}; /* Command history ringbuffer */
104 static LONG KdbCommandHistoryBufferIndex
= 0;
105 static LONG KdbCommandHistoryIndex
= 0;
107 static ULONG KdbNumberOfRowsPrinted
= 0;
108 static ULONG KdbNumberOfColsPrinted
= 0;
109 static BOOLEAN KdbOutputAborted
= FALSE
;
110 static BOOLEAN KdbRepeatLastCommand
= FALSE
;
111 static LONG KdbNumberOfRowsTerminal
= -1;
112 static LONG KdbNumberOfColsTerminal
= -1;
114 PCHAR KdbInitFileBuffer
= NULL
; /* Buffer where KDBinit file is loaded into during initialization */
115 BOOLEAN KdbpBugCheckRequested
= FALSE
;
118 /* defined in ../kd/kdio.c, declare here: */
119 extern volatile BOOLEAN KdbpIsInDmesgMode
;
120 extern const ULONG KdpDmesgBufferSize
;
121 extern PCHAR KdpDmesgBuffer
;
122 extern volatile ULONG KdpDmesgCurrentPosition
;
123 extern volatile ULONG KdpDmesgFreeBytes
;
124 extern volatile ULONG KdbDmesgTotalWritten
;
131 BOOLEAN (*Fn
)(ULONG Argc
, PCHAR Argv
[]);
132 } KdbDebuggerCommands
[] = {
134 { NULL
, NULL
, "Data", NULL
},
135 { "?", "? expression", "Evaluate expression.", KdbpCmdEvalExpression
},
136 { "disasm", "disasm [address] [L count]", "Disassemble count instructions at address.", KdbpCmdDisassembleX
},
137 { "x", "x [address] [L count]", "Display count dwords, starting at addr.", KdbpCmdDisassembleX
},
138 { "regs", "regs", "Display general purpose registers.", KdbpCmdRegs
},
139 { "cregs", "cregs", "Display control registers.", KdbpCmdRegs
},
140 { "sregs", "sregs", "Display status registers.", KdbpCmdRegs
},
141 { "dregs", "dregs", "Display debug registers.", KdbpCmdRegs
},
142 { "bt", "bt [*frameaddr|thread id]", "Prints current backtrace or from given frame addr", KdbpCmdBackTrace
},
144 { "dt", "dt [mod] [type] [addr]", "Print a struct. Addr is optional.", KdbpCmdPrintStruct
},
148 { NULL
, NULL
, "Flow control", NULL
},
149 { "cont", "cont", "Continue execution (leave debugger)", KdbpCmdContinue
},
150 { "step", "step [count]", "Execute single instructions, stepping into interrupts.", KdbpCmdStep
},
151 { "next", "next [count]", "Execute single instructions, skipping calls and reps.", KdbpCmdStep
},
152 { "bl", "bl", "List breakpoints.", KdbpCmdBreakPointList
},
153 { "be", "be [breakpoint]", "Enable breakpoint.", KdbpCmdEnableDisableClearBreakPoint
},
154 { "bd", "bd [breakpoint]", "Disable breakpoint.", KdbpCmdEnableDisableClearBreakPoint
},
155 { "bc", "bc [breakpoint]", "Clear breakpoint.", KdbpCmdEnableDisableClearBreakPoint
},
156 { "bpx", "bpx [address] [IF condition]", "Set software execution breakpoint at address.", KdbpCmdBreakPoint
},
157 { "bpm", "bpm [r|w|rw|x] [byte|word|dword] [address] [IF condition]", "Set memory breakpoint at address.", KdbpCmdBreakPoint
},
160 { NULL
, NULL
, "Process/Thread", NULL
},
161 { "thread", "thread [list[ pid]|[attach ]tid]", "List threads in current or specified process, display thread with given id or attach to thread.", KdbpCmdThread
},
162 { "proc", "proc [list|[attach ]pid]", "List processes, display process with given id or attach to process.", KdbpCmdProc
},
164 /* System information */
165 { NULL
, NULL
, "System info", NULL
},
166 { "mod", "mod [address]", "List all modules or the one containing address.", KdbpCmdMod
},
167 { "gdt", "gdt", "Display global descriptor table.", KdbpCmdGdtLdtIdt
},
168 { "ldt", "ldt", "Display local descriptor table.", KdbpCmdGdtLdtIdt
},
169 { "idt", "idt", "Display interrupt descriptor table.", KdbpCmdGdtLdtIdt
},
170 { "pcr", "pcr", "Display processor control region.", KdbpCmdPcr
},
171 { "tss", "tss", "Display task state segment.", KdbpCmdTss
},
174 { NULL
, NULL
, "Others", NULL
},
175 { "bugcheck", "bugcheck", "Bugchecks the system.", KdbpCmdBugCheck
},
176 { "filter", "filter [error|warning|trace|info|level]+|-[componentname|default]", "Enable/disable debug channels", KdbpCmdFilter
},
177 { "set", "set [var] [value]", "Sets var to value or displays value of var.", KdbpCmdSet
},
178 { "dmesg", "dmesg", "Display debug messages on screen, with navigation on pages.", KdbpCmdDmesg
},
179 { "kmsg", "kmsg", "Kernel dmesg. Alias for dmesg.", KdbpCmdDmesg
},
180 { "help", "help", "Display help screen.", KdbpCmdHelp
}
183 /* FUNCTIONS *****************************************************************/
185 /*!\brief Transform a component name to an integer
187 * \param ComponentName The name of the component.
188 * \param ComponentId Receives the component id on success.
190 * \retval TRUE Success.
191 * \retval FALSE Failure.
195 IN PCCH ComponentName
,
196 OUT PULONG ComponentId
)
207 { "DEFAULT", DPFLTR_DEFAULT_ID
},
208 { "SYSTEM", DPFLTR_SYSTEM_ID
},
209 { "SMSS", DPFLTR_SMSS_ID
},
210 { "SETUP", DPFLTR_SETUP_ID
},
211 { "NTFS", DPFLTR_NTFS_ID
},
212 { "FSTUB", DPFLTR_FSTUB_ID
},
213 { "CRASHDUMP", DPFLTR_CRASHDUMP_ID
},
214 { "CDAUDIO", DPFLTR_CDAUDIO_ID
},
215 { "CDROM", DPFLTR_CDROM_ID
},
216 { "CLASSPNP", DPFLTR_CLASSPNP_ID
},
217 { "DISK", DPFLTR_DISK_ID
},
218 { "REDBOOK", DPFLTR_REDBOOK_ID
},
219 { "STORPROP", DPFLTR_STORPROP_ID
},
220 { "SCSIPORT", DPFLTR_SCSIPORT_ID
},
221 { "SCSIMINIPORT", DPFLTR_SCSIMINIPORT_ID
},
222 { "CONFIG", DPFLTR_CONFIG_ID
},
223 { "I8042PRT", DPFLTR_I8042PRT_ID
},
224 { "SERMOUSE", DPFLTR_SERMOUSE_ID
},
225 { "LSERMOUS", DPFLTR_LSERMOUS_ID
},
226 { "KBDHID", DPFLTR_KBDHID_ID
},
227 { "MOUHID", DPFLTR_MOUHID_ID
},
228 { "KBDCLASS", DPFLTR_KBDCLASS_ID
},
229 { "MOUCLASS", DPFLTR_MOUCLASS_ID
},
230 { "TWOTRACK", DPFLTR_TWOTRACK_ID
},
231 { "WMILIB", DPFLTR_WMILIB_ID
},
232 { "ACPI", DPFLTR_ACPI_ID
},
233 { "AMLI", DPFLTR_AMLI_ID
},
234 { "HALIA64", DPFLTR_HALIA64_ID
},
235 { "VIDEO", DPFLTR_VIDEO_ID
},
236 { "SVCHOST", DPFLTR_SVCHOST_ID
},
237 { "VIDEOPRT", DPFLTR_VIDEOPRT_ID
},
238 { "TCPIP", DPFLTR_TCPIP_ID
},
239 { "DMSYNTH", DPFLTR_DMSYNTH_ID
},
240 { "NTOSPNP", DPFLTR_NTOSPNP_ID
},
241 { "FASTFAT", DPFLTR_FASTFAT_ID
},
242 { "SAMSS", DPFLTR_SAMSS_ID
},
243 { "PNPMGR", DPFLTR_PNPMGR_ID
},
244 { "NETAPI", DPFLTR_NETAPI_ID
},
245 { "SCSERVER", DPFLTR_SCSERVER_ID
},
246 { "SCCLIENT", DPFLTR_SCCLIENT_ID
},
247 { "SERIAL", DPFLTR_SERIAL_ID
},
248 { "SERENUM", DPFLTR_SERENUM_ID
},
249 { "UHCD", DPFLTR_UHCD_ID
},
250 { "RPCPROXY", DPFLTR_RPCPROXY_ID
},
251 { "AUTOCHK", DPFLTR_AUTOCHK_ID
},
252 { "DCOMSS", DPFLTR_DCOMSS_ID
},
253 { "UNIMODEM", DPFLTR_UNIMODEM_ID
},
254 { "SIS", DPFLTR_SIS_ID
},
255 { "FLTMGR", DPFLTR_FLTMGR_ID
},
256 { "WMICORE", DPFLTR_WMICORE_ID
},
257 { "BURNENG", DPFLTR_BURNENG_ID
},
258 { "IMAPI", DPFLTR_IMAPI_ID
},
259 { "SXS", DPFLTR_SXS_ID
},
260 { "FUSION", DPFLTR_FUSION_ID
},
261 { "IDLETASK", DPFLTR_IDLETASK_ID
},
262 { "SOFTPCI", DPFLTR_SOFTPCI_ID
},
263 { "TAPE", DPFLTR_TAPE_ID
},
264 { "MCHGR", DPFLTR_MCHGR_ID
},
265 { "IDEP", DPFLTR_IDEP_ID
},
266 { "PCIIDE", DPFLTR_PCIIDE_ID
},
267 { "FLOPPY", DPFLTR_FLOPPY_ID
},
268 { "FDC", DPFLTR_FDC_ID
},
269 { "TERMSRV", DPFLTR_TERMSRV_ID
},
270 { "W32TIME", DPFLTR_W32TIME_ID
},
271 { "PREFETCHER", DPFLTR_PREFETCHER_ID
},
272 { "RSFILTER", DPFLTR_RSFILTER_ID
},
273 { "FCPORT", DPFLTR_FCPORT_ID
},
274 { "PCI", DPFLTR_PCI_ID
},
275 { "DMIO", DPFLTR_DMIO_ID
},
276 { "DMCONFIG", DPFLTR_DMCONFIG_ID
},
277 { "DMADMIN", DPFLTR_DMADMIN_ID
},
278 { "WSOCKTRANSPORT", DPFLTR_WSOCKTRANSPORT_ID
},
279 { "VSS", DPFLTR_VSS_ID
},
280 { "PNPMEM", DPFLTR_PNPMEM_ID
},
281 { "PROCESSOR", DPFLTR_PROCESSOR_ID
},
282 { "DMSERVER", DPFLTR_DMSERVER_ID
},
283 { "SR", DPFLTR_SR_ID
},
284 { "INFINIBAND", DPFLTR_INFINIBAND_ID
},
285 { "IHVDRIVER", DPFLTR_IHVDRIVER_ID
},
286 { "IHVVIDEO", DPFLTR_IHVVIDEO_ID
},
287 { "IHVAUDIO", DPFLTR_IHVAUDIO_ID
},
288 { "IHVNETWORK", DPFLTR_IHVNETWORK_ID
},
289 { "IHVSTREAMING", DPFLTR_IHVSTREAMING_ID
},
290 { "IHVBUS", DPFLTR_IHVBUS_ID
},
291 { "HPS", DPFLTR_HPS_ID
},
292 { "RTLTHREADPOOL", DPFLTR_RTLTHREADPOOL_ID
},
293 { "LDR", DPFLTR_LDR_ID
},
294 { "TCPIP6", DPFLTR_TCPIP6_ID
},
295 { "ISAPNP", DPFLTR_ISAPNP_ID
},
296 { "SHPC", DPFLTR_SHPC_ID
},
297 { "STORPORT", DPFLTR_STORPORT_ID
},
298 { "STORMINIPORT", DPFLTR_STORMINIPORT_ID
},
299 { "PRINTSPOOLER", DPFLTR_PRINTSPOOLER_ID
},
300 { "VSSDYNDISK", DPFLTR_VSSDYNDISK_ID
},
301 { "VERIFIER", DPFLTR_VERIFIER_ID
},
302 { "VDS", DPFLTR_VDS_ID
},
303 { "VDSBAS", DPFLTR_VDSBAS_ID
},
304 { "VDSDYN", DPFLTR_VDSDYN_ID
},
305 { "VDSDYNDR", DPFLTR_VDSDYNDR_ID
},
306 { "VDSLDR", DPFLTR_VDSLDR_ID
},
307 { "VDSUTIL", DPFLTR_VDSUTIL_ID
},
308 { "DFRGIFC", DPFLTR_DFRGIFC_ID
},
309 { "MM", DPFLTR_MM_ID
},
310 { "DFSC", DPFLTR_DFSC_ID
},
311 { "WOW64", DPFLTR_WOW64_ID
},
312 { "ALPC", DPFLTR_ALPC_ID
},
313 { "WDI", DPFLTR_WDI_ID
},
314 { "PERFLIB", DPFLTR_PERFLIB_ID
},
315 { "KTM", DPFLTR_KTM_ID
},
316 { "IOSTRESS", DPFLTR_IOSTRESS_ID
},
317 { "HEAP", DPFLTR_HEAP_ID
},
318 { "WHEA", DPFLTR_WHEA_ID
},
319 { "USERGDI", DPFLTR_USERGDI_ID
},
320 { "MMCSS", DPFLTR_MMCSS_ID
},
321 { "TPM", DPFLTR_TPM_ID
},
322 { "THREADORDER", DPFLTR_THREADORDER_ID
},
323 { "ENVIRON", DPFLTR_ENVIRON_ID
},
324 { "EMS", DPFLTR_EMS_ID
},
325 { "WDT", DPFLTR_WDT_ID
},
326 { "FVEVOL", DPFLTR_FVEVOL_ID
},
327 { "NDIS", DPFLTR_NDIS_ID
},
328 { "NVCTRACE", DPFLTR_NVCTRACE_ID
},
329 { "LUAFV", DPFLTR_LUAFV_ID
},
330 { "APPCOMPAT", DPFLTR_APPCOMPAT_ID
},
331 { "USBSTOR", DPFLTR_USBSTOR_ID
},
332 { "SBP2PORT", DPFLTR_SBP2PORT_ID
},
333 { "COVERAGE", DPFLTR_COVERAGE_ID
},
334 { "CACHEMGR", DPFLTR_CACHEMGR_ID
},
335 { "MOUNTMGR", DPFLTR_MOUNTMGR_ID
},
336 { "CFR", DPFLTR_CFR_ID
},
337 { "TXF", DPFLTR_TXF_ID
},
338 { "KSECDD", DPFLTR_KSECDD_ID
},
339 { "FLTREGRESS", DPFLTR_FLTREGRESS_ID
},
340 { "MPIO", DPFLTR_MPIO_ID
},
341 { "MSDSM", DPFLTR_MSDSM_ID
},
342 { "UDFS", DPFLTR_UDFS_ID
},
343 { "PSHED", DPFLTR_PSHED_ID
},
344 { "STORVSP", DPFLTR_STORVSP_ID
},
345 { "LSASS", DPFLTR_LSASS_ID
},
346 { "SSPICLI", DPFLTR_SSPICLI_ID
},
347 { "CNG", DPFLTR_CNG_ID
},
348 { "EXFAT", DPFLTR_EXFAT_ID
},
349 { "FILETRACE", DPFLTR_FILETRACE_ID
},
350 { "XSAVE", DPFLTR_XSAVE_ID
},
351 { "SE", DPFLTR_SE_ID
},
352 { "DRIVEEXTENDER", DPFLTR_DRIVEEXTENDER_ID
},
355 for (i
= 0; i
< sizeof(ComponentTable
) / sizeof(ComponentTable
[0]); i
++)
357 if (_stricmp(ComponentName
, ComponentTable
[i
].Name
) == 0)
359 *ComponentId
= ComponentTable
[i
].Id
;
367 /*!\brief Evaluates an expression...
369 * Much like KdbpRpnEvaluateExpression, but prints the error message (if any)
370 * at the given offset.
372 * \param Expression Expression to evaluate.
373 * \param ErrOffset Offset (in characters) to print the error message at.
374 * \param Result Receives the result on success.
376 * \retval TRUE Success.
377 * \retval FALSE Failure.
380 KdbpEvaluateExpression(
383 OUT PULONGLONG Result
)
385 static CHAR ErrMsgBuffer
[130] = "^ ";
386 LONG ExpressionErrOffset
= -1;
387 PCHAR ErrMsg
= ErrMsgBuffer
;
390 Ok
= KdbpRpnEvaluateExpression(Expression
, KdbCurrentTrapFrame
, Result
,
391 &ExpressionErrOffset
, ErrMsgBuffer
+ 2);
394 if (ExpressionErrOffset
>= 0)
395 ExpressionErrOffset
+= ErrOffset
;
399 KdbpPrint("%*s%s\n", ExpressionErrOffset
, "", ErrMsg
);
405 /*!\brief Evaluates an expression and displays the result.
408 KdbpCmdEvalExpression(
413 ULONGLONG Result
= 0;
420 KdbpPrint("?: Argument required\n");
424 /* Put the arguments back together */
426 for (i
= 1; i
< Argc
; i
++)
428 len
= strlen(Argv
[i
]);
432 /* Evaluate the expression */
433 Ok
= KdbpEvaluateExpression(Argv
[1], sizeof("kdb:> ")-1 + (Argv
[1]-Argv
[0]), &Result
);
436 if (Result
> 0x00000000ffffffffLL
)
438 if (Result
& 0x8000000000000000LL
)
439 KdbpPrint("0x%016I64x %20I64u %20I64d\n", Result
, Result
, Result
);
441 KdbpPrint("0x%016I64x %20I64u\n", Result
, Result
);
447 if (ul
<= 0xff && ul
>= 0x80)
448 l
= (LONG
)((CHAR
)ul
);
449 else if (ul
<= 0xffff && ul
>= 0x8000)
450 l
= (LONG
)((SHORT
)ul
);
455 KdbpPrint("0x%08lx %10lu %10ld\n", ul
, ul
, l
);
457 KdbpPrint("0x%08lx %10lu\n", ul
, ul
);
466 /*!\brief Print a struct
469 KdbpPrintStructInternal
474 PROSSYM_AGGREGATE Aggregate
)
478 PROSSYM_AGGREGATE_MEMBER Member
;
479 ULONG IndentLen
= strlen(Indent
);
480 ROSSYM_AGGREGATE MemberAggregate
= {0 };
482 for (i
= 0; i
< Aggregate
->NumElements
; i
++) {
483 Member
= &Aggregate
->Elements
[i
];
484 KdbpPrint("%s%p+%x: %s", Indent
, ((PCHAR
)BaseAddress
) + Member
->BaseOffset
, Member
->Size
, Member
->Name
? Member
->Name
: "<anoymous>");
486 if (!strcmp(Member
->Type
, "_UNICODE_STRING")) {
487 KdbpPrint("\"%wZ\"\n", ((PCHAR
)BaseAddress
) + Member
->BaseOffset
);
489 } else if (!strcmp(Member
->Type
, "PUNICODE_STRING")) {
490 KdbpPrint("\"%wZ\"\n", *(((PUNICODE_STRING
*)((PCHAR
)BaseAddress
) + Member
->BaseOffset
)));
493 switch (Member
->Size
) {
499 if (NT_SUCCESS(KdbpSafeReadMemory(&Result
, ((PCHAR
)BaseAddress
) + Member
->BaseOffset
, Member
->Size
))) {
501 Result
>>= Member
->FirstBit
;
502 Result
&= ((1 << Member
->Bits
) - 1);
504 KdbpPrint(" %lx\n", Result
);
510 if (Member
->Size
< 8) {
511 if (NT_SUCCESS(KdbpSafeReadMemory(&Result
, ((PCHAR
)BaseAddress
) + Member
->BaseOffset
, Member
->Size
))) {
513 for (j
= 0; j
< Member
->Size
; j
++) {
514 KdbpPrint(" %02x", (int)(Result
& 0xff));
517 } else goto readfail
;
519 KdbpPrint(" %s @ %p {\n", Member
->Type
, ((PCHAR
)BaseAddress
) + Member
->BaseOffset
);
520 Indent
[IndentLen
] = ' ';
521 if (RosSymAggregate(Info
, Member
->Type
, &MemberAggregate
)) {
522 KdbpPrintStructInternal(Info
, Indent
, DoRead
, ((PCHAR
)BaseAddress
) + Member
->BaseOffset
, &MemberAggregate
);
523 RosSymFreeAggregate(&MemberAggregate
);
525 Indent
[IndentLen
] = 0;
526 KdbpPrint("%s}\n", Indent
);
532 if (Member
->Size
<= 8) {
535 KdbpPrint(" %s @ %x {\n", Member
->Type
, Member
->BaseOffset
);
536 Indent
[IndentLen
] = ' ';
537 if (RosSymAggregate(Info
, Member
->Type
, &MemberAggregate
)) {
538 KdbpPrintStructInternal(Info
, Indent
, DoRead
, BaseAddress
, &MemberAggregate
);
539 RosSymFreeAggregate(&MemberAggregate
);
541 Indent
[IndentLen
] = 0;
542 KdbpPrint("%s}\n", Indent
);
548 PROSSYM_INFO
KdbpSymFindCachedFile(PUNICODE_STRING ModName
);
556 ULONGLONG Result
= 0;
557 PVOID BaseAddress
= 0;
558 ROSSYM_AGGREGATE Aggregate
= {0};
559 UNICODE_STRING ModName
= {0};
560 ANSI_STRING AnsiName
= {0};
561 CHAR Indent
[100] = {0};
564 if (Argc
< 3) goto end
;
565 AnsiName
.Length
= AnsiName
.MaximumLength
= strlen(Argv
[1]);
566 AnsiName
.Buffer
= Argv
[1];
567 RtlAnsiStringToUnicodeString(&ModName
, &AnsiName
, TRUE
);
568 Info
= KdbpSymFindCachedFile(&ModName
);
570 if (!Info
|| !RosSymAggregate(Info
, Argv
[2], &Aggregate
)) {
571 DPRINT1("Could not get aggregate\n");
575 // Get an argument for location if it was given
578 PCHAR ArgStart
= Argv
[3];
579 DPRINT1("Trying to get expression\n");
580 for (i
= 3; i
< Argc
- 1; i
++)
582 len
= strlen(Argv
[i
]);
586 /* Evaluate the expression */
587 DPRINT1("Arg: %s\n", ArgStart
);
588 if (KdbpEvaluateExpression(ArgStart
, strlen(ArgStart
), &Result
)) {
589 BaseAddress
= (PVOID
)(ULONG_PTR
)Result
;
590 DPRINT1("BaseAddress: %p\n", BaseAddress
);
593 DPRINT1("BaseAddress %p\n", BaseAddress
);
594 KdbpPrintStructInternal(Info
, Indent
, !!BaseAddress
, BaseAddress
, &Aggregate
);
596 RosSymFreeAggregate(&Aggregate
);
597 RtlFreeUnicodeString(&ModName
);
602 /*!\brief Display list of active debug channels
609 ULONG i
, j
, ComponentId
, Level
;
610 ULONG set
= DPFLTR_MASK
, clear
= DPFLTR_MASK
;
621 { "error", 1 << DPFLTR_ERROR_LEVEL
},
622 { "warning", 1 << DPFLTR_WARNING_LEVEL
},
623 { "trace", 1 << DPFLTR_TRACE_LEVEL
},
624 { "info", 1 << DPFLTR_INFO_LEVEL
},
627 for (i
= 1; i
< Argc
; i
++)
630 p
= opt
+ strcspn(opt
, "+-");
631 if (!p
[0]) p
= opt
; /* assume it's a debug channel name */
635 for (j
= 0; j
< sizeof(debug_classes
) / sizeof(debug_classes
[0]); j
++)
637 SIZE_T len
= strlen(debug_classes
[j
].Name
);
638 if (len
!= (p
- opt
))
640 if (_strnicmp(opt
, debug_classes
[j
].Name
, len
) == 0) /* found it */
643 set
|= debug_classes
[j
].Level
;
645 clear
|= debug_classes
[j
].Level
;
649 if (j
== sizeof(debug_classes
) / sizeof(debug_classes
[0]))
651 Level
= strtoul(opt
, &pend
, 0);
654 KdbpPrint("filter: bad class name '%.*s'\n", p
- opt
, opt
);
670 if (*p
== '+' || *p
== '-')
673 if (!KdbpGetComponentId(p
, &ComponentId
))
675 KdbpPrint("filter: '%s' is not a valid component name!\n", p
);
679 /* Get current mask value */
680 NtSetDebugFilterState(ComponentId
, set
, TRUE
);
681 NtSetDebugFilterState(ComponentId
, clear
, FALSE
);
687 /*!\brief Disassembles 10 instructions at eip or given address or
688 * displays 16 dwords from memory at given address.
698 ULONGLONG Result
= 0;
699 ULONG_PTR Address
= KdbCurrentTrapFrame
->Tf
.Eip
;
702 if (Argv
[0][0] == 'x') /* display memory */
704 else /* disassemble */
709 /* Check for [L count] part */
711 if (strcmp(Argv
[Argc
-2], "L") == 0)
713 ul
= strtoul(Argv
[Argc
-1], NULL
, 0);
720 else if (Argv
[Argc
-1][0] == 'L')
722 ul
= strtoul(Argv
[Argc
-1] + 1, NULL
, 0);
730 /* Put the remaining arguments back together */
732 for (ul
= 1; ul
< Argc
; ul
++)
734 Argv
[ul
][strlen(Argv
[ul
])] = ' ';
739 /* Evaluate the expression */
742 if (!KdbpEvaluateExpression(Argv
[1], sizeof("kdb:> ")-1 + (Argv
[1]-Argv
[0]), &Result
))
745 if (Result
> (ULONGLONG
)(~((ULONG_PTR
)0)))
746 KdbpPrint("Warning: Address %I64x is beeing truncated\n",Result
);
748 Address
= (ULONG_PTR
)Result
;
750 else if (Argv
[0][0] == 'x')
752 KdbpPrint("x: Address argument required.\n");
756 if (Argv
[0][0] == 'x')
763 if (!KdbSymPrintAddress((PVOID
)Address
, NULL
))
764 KdbpPrint("<%x>:", Address
);
773 if (!NT_SUCCESS(KdbpSafeReadMemory(&ul
, (PVOID
)Address
, sizeof(ul
))))
774 KdbpPrint(" ????????");
776 KdbpPrint(" %08x", ul
);
778 Address
+= sizeof(ul
);
789 if (!KdbSymPrintAddress((PVOID
)Address
, NULL
))
790 KdbpPrint("<%08x>: ", Address
);
794 InstLen
= KdbpDisassemble(Address
, KdbUseIntelSyntax
);
797 KdbpPrint("<INVALID>\n");
809 /*!\brief Displays CPU registers.
816 PKTRAP_FRAME Tf
= &KdbCurrentTrapFrame
->Tf
;
818 static const PCHAR EflagsBits
[32] = { " CF", NULL
, " PF", " BIT3", " AF", " BIT5",
819 " ZF", " SF", " TF", " IF", " DF", " OF",
820 NULL
, NULL
, " NT", " BIT15", " RF", " VF",
821 " AC", " VIF", " VIP", " ID", " BIT22",
822 " BIT23", " BIT24", " BIT25", " BIT26",
823 " BIT27", " BIT28", " BIT29", " BIT30",
826 if (Argv
[0][0] == 'r') /* regs */
828 KdbpPrint("CS:EIP 0x%04x:0x%08x\n"
829 "SS:ESP 0x%04x:0x%08x\n"
830 " EAX 0x%08x EBX 0x%08x\n"
831 " ECX 0x%08x EDX 0x%08x\n"
832 " ESI 0x%08x EDI 0x%08x\n"
834 Tf
->SegCs
& 0xFFFF, Tf
->Eip
,
835 Tf
->HardwareSegSs
, Tf
->HardwareEsp
,
840 KdbpPrint("EFLAGS 0x%08x ", Tf
->EFlags
);
842 for (i
= 0; i
< 32; i
++)
846 if ((Tf
->EFlags
& (1 << 1)) == 0)
851 KdbpPrint(" IOPL%d", (Tf
->EFlags
>> 12) & 3);
856 else if ((Tf
->EFlags
& (1 << i
)) != 0)
858 KdbpPrint(EflagsBits
[i
]);
864 else if (Argv
[0][0] == 'c') /* cregs */
866 ULONG Cr0
, Cr2
, Cr3
, Cr4
;
867 KDESCRIPTOR Gdtr
, Idtr
;
869 static const PCHAR Cr0Bits
[32] = { " PE", " MP", " EM", " TS", " ET", " NE", NULL
, NULL
,
870 NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
,
871 " WP", NULL
, " AM", NULL
, NULL
, NULL
, NULL
, NULL
,
872 NULL
, NULL
, NULL
, NULL
, NULL
, " NW", " CD", " PG" };
873 static const PCHAR Cr4Bits
[32] = { " VME", " PVI", " TSD", " DE", " PSE", " PAE", " MCE", " PGE",
874 " PCE", " OSFXSR", " OSXMMEXCPT", NULL
, NULL
, NULL
, NULL
, NULL
,
875 NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
,
876 NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
};
878 Cr0
= KdbCurrentTrapFrame
->Cr0
;
879 Cr2
= KdbCurrentTrapFrame
->Cr2
;
880 Cr3
= KdbCurrentTrapFrame
->Cr3
;
881 Cr4
= KdbCurrentTrapFrame
->Cr4
;
883 /* Get descriptor table regs */
884 Ke386GetGlobalDescriptorTable(&Gdtr
.Limit
);
885 Ldtr
= Ke386GetLocalDescriptorTable();
888 /* Display the control registers */
889 KdbpPrint("CR0 0x%08x ", Cr0
);
891 for (i
= 0; i
< 32; i
++)
896 if ((Cr0
& (1 << i
)) != 0)
897 KdbpPrint(Cr0Bits
[i
]);
900 KdbpPrint("\nCR2 0x%08x\n", Cr2
);
901 KdbpPrint("CR3 0x%08x Pagedir-Base 0x%08x %s%s\n", Cr3
, (Cr3
& 0xfffff000),
902 (Cr3
& (1 << 3)) ? " PWT" : "", (Cr3
& (1 << 4)) ? " PCD" : "" );
903 KdbpPrint("CR4 0x%08x ", Cr4
);
905 for (i
= 0; i
< 32; i
++)
910 if ((Cr4
& (1 << i
)) != 0)
911 KdbpPrint(Cr4Bits
[i
]);
914 /* Display the descriptor table regs */
915 KdbpPrint("\nGDTR Base 0x%08x Size 0x%04x\n", Gdtr
.Base
, Gdtr
.Limit
);
916 KdbpPrint("LDTR 0x%04x\n", Ldtr
);
917 KdbpPrint("IDTR Base 0x%08x Size 0x%04x\n", Idtr
.Base
, Idtr
.Limit
);
919 else if (Argv
[0][0] == 's') /* sregs */
921 KdbpPrint("CS 0x%04x Index 0x%04x %cDT RPL%d\n",
922 Tf
->SegCs
& 0xffff, (Tf
->SegCs
& 0xffff) >> 3,
923 (Tf
->SegCs
& (1 << 2)) ? 'L' : 'G', Tf
->SegCs
& 3);
924 KdbpPrint("DS 0x%04x Index 0x%04x %cDT RPL%d\n",
925 Tf
->SegDs
, Tf
->SegDs
>> 3, (Tf
->SegDs
& (1 << 2)) ? 'L' : 'G', Tf
->SegDs
& 3);
926 KdbpPrint("ES 0x%04x Index 0x%04x %cDT RPL%d\n",
927 Tf
->SegEs
, Tf
->SegEs
>> 3, (Tf
->SegEs
& (1 << 2)) ? 'L' : 'G', Tf
->SegEs
& 3);
928 KdbpPrint("FS 0x%04x Index 0x%04x %cDT RPL%d\n",
929 Tf
->SegFs
, Tf
->SegFs
>> 3, (Tf
->SegFs
& (1 << 2)) ? 'L' : 'G', Tf
->SegFs
& 3);
930 KdbpPrint("GS 0x%04x Index 0x%04x %cDT RPL%d\n",
931 Tf
->SegGs
, Tf
->SegGs
>> 3, (Tf
->SegGs
& (1 << 2)) ? 'L' : 'G', Tf
->SegGs
& 3);
932 KdbpPrint("SS 0x%04x Index 0x%04x %cDT RPL%d\n",
933 Tf
->HardwareSegSs
, Tf
->HardwareSegSs
>> 3, (Tf
->HardwareSegSs
& (1 << 2)) ? 'L' : 'G', Tf
->HardwareSegSs
& 3);
937 ASSERT(Argv
[0][0] == 'd');
938 KdbpPrint("DR0 0x%08x\n"
944 Tf
->Dr0
, Tf
->Dr1
, Tf
->Dr2
, Tf
->Dr3
,
952 KdbpTrapFrameFromPrevTss(
953 PKTRAP_FRAME TrapFrame
)
961 Ke386GetGlobalDescriptorTable(&Gdtr
.Limit
);
964 if ((Sel
& (sizeof(KGDTENTRY
) - 1)) ||
965 (Sel
< sizeof(KGDTENTRY
)) ||
966 (Sel
+ sizeof(KGDTENTRY
) - 1 > Gdtr
.Limit
))
969 if (!NT_SUCCESS(KdbpSafeReadMemory(&Desc
,
970 (PVOID
)(Gdtr
.Base
+ Sel
),
974 if (Desc
.HighWord
.Bits
.Type
!= 0xB)
977 Tss
= (PKTSS
)(ULONG_PTR
)(Desc
.BaseLow
|
978 Desc
.HighWord
.Bytes
.BaseMid
<< 16 |
979 Desc
.HighWord
.Bytes
.BaseHi
<< 24);
981 if (!NT_SUCCESS(KdbpSafeReadMemory(&Sel
,
982 (PVOID
)&Tss
->Backlink
,
986 if ((Sel
& (sizeof(KGDTENTRY
) - 1)) ||
987 (Sel
< sizeof(KGDTENTRY
)) ||
988 (Sel
+ sizeof(KGDTENTRY
) - 1 > Gdtr
.Limit
))
991 if (!NT_SUCCESS(KdbpSafeReadMemory(&Desc
,
992 (PVOID
)(Gdtr
.Base
+ Sel
),
996 if (Desc
.HighWord
.Bits
.Type
!= 0xB)
999 Tss
= (PKTSS
)(ULONG_PTR
)(Desc
.BaseLow
|
1000 Desc
.HighWord
.Bytes
.BaseMid
<< 16 |
1001 Desc
.HighWord
.Bytes
.BaseHi
<< 24);
1003 if (!NT_SUCCESS(KdbpSafeReadMemory(&Eip
,
1005 sizeof(ULONG_PTR
))))
1008 if (!NT_SUCCESS(KdbpSafeReadMemory(&Ebp
,
1010 sizeof(ULONG_PTR
))))
1013 TrapFrame
->Eip
= Eip
;
1014 TrapFrame
->Ebp
= Ebp
;
1018 VOID __cdecl
KiTrap02(VOID
);
1019 VOID FASTCALL
KiTrap03Handler(IN PKTRAP_FRAME
);
1020 VOID __cdecl
KiTrap08(VOID
);
1021 VOID __cdecl
KiTrap09(VOID
);
1024 KdbpInNmiOrDoubleFaultHandler(
1027 return (Address
> (ULONG_PTR
)KiTrap02
&& Address
< (ULONG_PTR
)KiTrap03Handler
) ||
1028 (Address
> (ULONG_PTR
)KiTrap08
&& Address
< (ULONG_PTR
)KiTrap09
);
1031 /*!\brief Displays a backtrace.
1039 ULONGLONG Result
= 0;
1040 ULONG_PTR Frame
= KdbCurrentTrapFrame
->Tf
.Ebp
;
1042 KTRAP_FRAME TrapFrame
;
1046 /* Check for [L count] part */
1049 if (strcmp(Argv
[Argc
-2], "L") == 0)
1051 ul
= strtoul(Argv
[Argc
-1], NULL
, 0);
1057 else if (Argv
[Argc
-1][0] == 'L')
1059 ul
= strtoul(Argv
[Argc
-1] + 1, NULL
, 0);
1066 /* Put the remaining arguments back together */
1068 for (ul
= 1; ul
< Argc
; ul
++)
1070 Argv
[ul
][strlen(Argv
[ul
])] = ' ';
1075 /* Check if frame addr or thread id is given. */
1078 if (Argv
[1][0] == '*')
1082 /* Evaluate the expression */
1083 if (!KdbpEvaluateExpression(Argv
[1], sizeof("kdb:> ")-1 + (Argv
[1]-Argv
[0]), &Result
))
1086 if (Result
> (ULONGLONG
)(~((ULONG_PTR
)0)))
1087 KdbpPrint("Warning: Address %I64x is beeing truncated\n",Result
);
1089 Frame
= (ULONG_PTR
)Result
;
1093 KdbpPrint("Thread backtrace not supported yet!\n");
1099 KdbpPrint("Eip:\n");
1101 /* Try printing the function at EIP */
1102 if (!KdbSymPrintAddress((PVOID
)KdbCurrentTrapFrame
->Tf
.Eip
, &KdbCurrentTrapFrame
->Tf
))
1103 KdbpPrint("<%08x>\n", KdbCurrentTrapFrame
->Tf
.Eip
);
1108 TrapFrame
= KdbCurrentTrapFrame
->Tf
;
1109 KdbpPrint("Frames:\n");
1113 BOOLEAN GotNextFrame
;
1118 if (!NT_SUCCESS(KdbpSafeReadMemory(&Address
, (PVOID
)(Frame
+ sizeof(ULONG_PTR
)), sizeof (ULONG_PTR
))))
1120 KdbpPrint("Couldn't access memory at 0x%p!\n", Frame
+ sizeof(ULONG_PTR
));
1124 if ((GotNextFrame
= NT_SUCCESS(KdbpSafeReadMemory(&Frame
, (PVOID
)Frame
, sizeof (ULONG_PTR
)))))
1125 TrapFrame
.Ebp
= Frame
;
1127 /* Print the location of the call instruction */
1128 if (!KdbSymPrintAddress((PVOID
)(Address
- 5), &TrapFrame
))
1129 KdbpPrint("<%08x>\n", Address
);
1133 if (KdbOutputAborted
) break;
1138 if (KdbpInNmiOrDoubleFaultHandler(Address
))
1140 if ((GotNextFrame
= KdbpTrapFrameFromPrevTss(&TrapFrame
)))
1142 Address
= TrapFrame
.Eip
;
1143 Frame
= TrapFrame
.Ebp
;
1145 if (!KdbSymPrintAddress((PVOID
)Address
, &TrapFrame
))
1146 KdbpPrint("<%08x>\n", Address
);
1154 KdbpPrint("Couldn't access memory at 0x%p!\n", Frame
);
1162 /*!\brief Continues execution of the system/leaves KDB.
1169 /* Exit the main loop */
1173 /*!\brief Continues execution of the system/leaves KDB.
1184 Count
= strtoul(Argv
[1], NULL
, 0);
1187 KdbpPrint("%s: Integer argument required\n", Argv
[0]);
1192 if (Argv
[0][0] == 'n')
1193 KdbSingleStepOver
= TRUE
;
1195 KdbSingleStepOver
= FALSE
;
1197 /* Set the number of single steps and return to the interrupted code. */
1198 KdbNumSingleSteps
= Count
;
1203 /*!\brief Lists breakpoints.
1206 KdbpCmdBreakPointList(
1211 ULONG_PTR Address
= 0;
1212 KDB_BREAKPOINT_TYPE Type
= 0;
1213 KDB_ACCESS_TYPE AccessType
= 0;
1216 BOOLEAN Enabled
= FALSE
;
1217 BOOLEAN Global
= FALSE
;
1218 PEPROCESS Process
= NULL
;
1219 PCHAR str1
, str2
, ConditionExpr
, GlobalOrLocal
;
1222 l
= KdbpGetNextBreakPointNr(0);
1225 KdbpPrint("No breakpoints.\n");
1229 KdbpPrint("Breakpoints:\n");
1232 if (!KdbpGetBreakPointInfo(l
, &Address
, &Type
, &Size
, &AccessType
, &DebugReg
,
1233 &Enabled
, &Global
, &Process
, &ConditionExpr
))
1238 if (l
== KdbLastBreakPointNr
)
1251 GlobalOrLocal
= " global";
1255 GlobalOrLocal
= Buffer
;
1256 sprintf(Buffer
, " PID 0x%08lx",
1257 (ULONG
)(Process
? Process
->UniqueProcessId
: INVALID_HANDLE_VALUE
));
1260 if (Type
== KdbBreakPointSoftware
|| Type
== KdbBreakPointTemporary
)
1262 KdbpPrint(" %s%03d BPX 0x%08x%s%s%s%s%s\n",
1264 Enabled
? "" : " disabled",
1266 ConditionExpr
? " IF " : "",
1267 ConditionExpr
? ConditionExpr
: "",
1270 else if (Type
== KdbBreakPointHardware
)
1274 KdbpPrint(" %s%03d BPM 0x%08x %-5s %-5s disabled%s%s%s%s\n", str1
, l
, Address
,
1275 KDB_ACCESS_TYPE_TO_STRING(AccessType
),
1276 Size
== 1 ? "byte" : (Size
== 2 ? "word" : "dword"),
1278 ConditionExpr
? " IF " : "",
1279 ConditionExpr
? ConditionExpr
: "",
1284 KdbpPrint(" %s%03d BPM 0x%08x %-5s %-5s DR%d%s%s%s%s\n", str1
, l
, Address
,
1285 KDB_ACCESS_TYPE_TO_STRING(AccessType
),
1286 Size
== 1 ? "byte" : (Size
== 2 ? "word" : "dword"),
1289 ConditionExpr
? " IF " : "",
1290 ConditionExpr
? ConditionExpr
: "",
1295 while ((l
= KdbpGetNextBreakPointNr(l
+1)) >= 0);
1300 /*!\brief Enables, disables or clears a breakpoint.
1303 KdbpCmdEnableDisableClearBreakPoint(
1312 KdbpPrint("%s: argument required\n", Argv
[0]);
1317 BreakPointNr
= strtoul(Argv
[1], &pend
, 0);
1318 if (pend
== Argv
[1] || *pend
!= '\0')
1320 KdbpPrint("%s: integer argument required\n", Argv
[0]);
1324 if (Argv
[0][1] == 'e') /* enable */
1326 KdbpEnableBreakPoint(BreakPointNr
, NULL
);
1328 else if (Argv
[0][1] == 'd') /* disable */
1330 KdbpDisableBreakPoint(BreakPointNr
, NULL
);
1334 ASSERT(Argv
[0][1] == 'c');
1335 KdbpDeleteBreakPoint(BreakPointNr
, NULL
);
1341 /*!\brief Sets a software or hardware (memory) breakpoint at the given address.
1344 KdbpCmdBreakPoint(ULONG Argc
, PCHAR Argv
[])
1346 ULONGLONG Result
= 0;
1348 KDB_BREAKPOINT_TYPE Type
;
1350 KDB_ACCESS_TYPE AccessType
= 0;
1351 ULONG AddressArgIndex
, i
;
1352 LONG ConditionArgIndex
;
1353 BOOLEAN Global
= TRUE
;
1355 if (Argv
[0][2] == 'x') /* software breakpoint */
1359 KdbpPrint("bpx: Address argument required.\n");
1363 AddressArgIndex
= 1;
1364 Type
= KdbBreakPointSoftware
;
1366 else /* memory breakpoint */
1368 ASSERT(Argv
[0][2] == 'm');
1372 KdbpPrint("bpm: Access type argument required (one of r, w, rw, x)\n");
1376 if (_stricmp(Argv
[1], "x") == 0)
1377 AccessType
= KdbAccessExec
;
1378 else if (_stricmp(Argv
[1], "r") == 0)
1379 AccessType
= KdbAccessRead
;
1380 else if (_stricmp(Argv
[1], "w") == 0)
1381 AccessType
= KdbAccessWrite
;
1382 else if (_stricmp(Argv
[1], "rw") == 0)
1383 AccessType
= KdbAccessReadWrite
;
1386 KdbpPrint("bpm: Unknown access type '%s'\n", Argv
[1]);
1392 KdbpPrint("bpm: %s argument required.\n", AccessType
== KdbAccessExec
? "Address" : "Memory size");
1396 AddressArgIndex
= 3;
1397 if (_stricmp(Argv
[2], "byte") == 0)
1399 else if (_stricmp(Argv
[2], "word") == 0)
1401 else if (_stricmp(Argv
[2], "dword") == 0)
1403 else if (AccessType
== KdbAccessExec
)
1410 KdbpPrint("bpm: Unknown memory size '%s'\n", Argv
[2]);
1414 if (Argc
<= AddressArgIndex
)
1416 KdbpPrint("bpm: Address argument required.\n");
1420 Type
= KdbBreakPointHardware
;
1423 /* Put the arguments back together */
1424 ConditionArgIndex
= -1;
1425 for (i
= AddressArgIndex
; i
< (Argc
-1); i
++)
1427 if (strcmp(Argv
[i
+1], "IF") == 0) /* IF found */
1429 ConditionArgIndex
= i
+ 2;
1430 if ((ULONG
)ConditionArgIndex
>= Argc
)
1432 KdbpPrint("%s: IF requires condition expression.\n", Argv
[0]);
1436 for (i
= ConditionArgIndex
; i
< (Argc
-1); i
++)
1437 Argv
[i
][strlen(Argv
[i
])] = ' ';
1442 Argv
[i
][strlen(Argv
[i
])] = ' ';
1445 /* Evaluate the address expression */
1446 if (!KdbpEvaluateExpression(Argv
[AddressArgIndex
],
1447 sizeof("kdb:> ")-1 + (Argv
[AddressArgIndex
]-Argv
[0]),
1453 if (Result
> (ULONGLONG
)(~((ULONG_PTR
)0)))
1454 KdbpPrint("%s: Warning: Address %I64x is beeing truncated\n", Argv
[0],Result
);
1456 Address
= (ULONG_PTR
)Result
;
1458 KdbpInsertBreakPoint(Address
, Type
, Size
, AccessType
,
1459 (ConditionArgIndex
< 0) ? NULL
: Argv
[ConditionArgIndex
],
1465 /*!\brief Lists threads or switches to another thread context.
1473 PETHREAD Thread
= NULL
;
1474 PEPROCESS Process
= NULL
;
1475 BOOLEAN ReferencedThread
= FALSE
, ReferencedProcess
= FALSE
;
1480 PCHAR State
, pend
, str1
, str2
;
1481 static const PCHAR ThreadStateToString
[DeferredReady
+1] =
1483 "Initialized", "Ready", "Running",
1484 "Standby", "Terminated", "Waiting",
1485 "Transition", "DeferredReady"
1488 ASSERT(KdbCurrentProcess
);
1490 if (Argc
>= 2 && _stricmp(Argv
[1], "list") == 0)
1492 Process
= KdbCurrentProcess
;
1496 ul
= strtoul(Argv
[2], &pend
, 0);
1497 if (Argv
[2] == pend
)
1499 KdbpPrint("thread: '%s' is not a valid process id!\n", Argv
[2]);
1503 if (!NT_SUCCESS(PsLookupProcessByProcessId((PVOID
)ul
, &Process
)))
1505 KdbpPrint("thread: Invalid process id!\n");
1509 /* Remember our reference */
1510 ReferencedProcess
= TRUE
;
1513 Entry
= Process
->ThreadListHead
.Flink
;
1514 if (Entry
== &Process
->ThreadListHead
)
1517 KdbpPrint("No threads in process 0x%08x!\n", ul
);
1519 KdbpPrint("No threads in current process!\n");
1521 if (ReferencedProcess
)
1522 ObDereferenceObject(Process
);
1527 KdbpPrint(" TID State Prior. Affinity EBP EIP\n");
1530 Thread
= CONTAINING_RECORD(Entry
, ETHREAD
, ThreadListEntry
);
1532 if (Thread
== KdbCurrentThread
)
1543 if (!Thread
->Tcb
.InitialStack
)
1545 /* Thread has no kernel stack (probably terminated) */
1549 else if (Thread
->Tcb
.TrapFrame
)
1551 if (Thread
->Tcb
.TrapFrame
->PreviousPreviousMode
== KernelMode
)
1552 Esp
= (PULONG
)Thread
->Tcb
.TrapFrame
->TempEsp
;
1554 Esp
= (PULONG
)Thread
->Tcb
.TrapFrame
->HardwareEsp
;
1556 Ebp
= (PULONG
)Thread
->Tcb
.TrapFrame
->Ebp
;
1557 Eip
= Thread
->Tcb
.TrapFrame
->Eip
;
1561 Esp
= (PULONG
)Thread
->Tcb
.KernelStack
;
1562 Ebp
= (PULONG
)Esp
[4];
1565 if (Ebp
) /* FIXME: Should we attach to the process to read Ebp[1]? */
1566 KdbpSafeReadMemory(&Eip
, Ebp
+ 1, sizeof (Eip
));
1569 if (Thread
->Tcb
.State
< (DeferredReady
+ 1))
1570 State
= ThreadStateToString
[Thread
->Tcb
.State
];
1574 KdbpPrint(" %s0x%08x %-11s %3d 0x%08x 0x%08x 0x%08x%s\n",
1576 Thread
->Cid
.UniqueThread
,
1578 Thread
->Tcb
.Priority
,
1579 Thread
->Tcb
.Affinity
,
1584 Entry
= Entry
->Flink
;
1586 while (Entry
!= &Process
->ThreadListHead
);
1588 /* Release our reference, if any */
1589 if (ReferencedProcess
)
1590 ObDereferenceObject(Process
);
1592 else if (Argc
>= 2 && _stricmp(Argv
[1], "attach") == 0)
1596 KdbpPrint("thread attach: thread id argument required!\n");
1600 ul
= strtoul(Argv
[2], &pend
, 0);
1601 if (Argv
[2] == pend
)
1603 KdbpPrint("thread attach: '%s' is not a valid thread id!\n", Argv
[2]);
1607 if (!KdbpAttachToThread((PVOID
)ul
))
1612 KdbpPrint("Attached to thread 0x%08x.\n", ul
);
1616 Thread
= KdbCurrentThread
;
1620 ul
= strtoul(Argv
[1], &pend
, 0);
1621 if (Argv
[1] == pend
)
1623 KdbpPrint("thread: '%s' is not a valid thread id!\n", Argv
[1]);
1627 if (!NT_SUCCESS(PsLookupThreadByThreadId((PVOID
)ul
, &Thread
)))
1629 KdbpPrint("thread: Invalid thread id!\n");
1633 /* Remember our reference */
1634 ReferencedThread
= TRUE
;
1637 if (Thread
->Tcb
.State
< (DeferredReady
+ 1))
1638 State
= ThreadStateToString
[Thread
->Tcb
.State
];
1644 " State: %s (0x%x)\n"
1646 " Affinity: 0x%08x\n"
1647 " Initial Stack: 0x%08x\n"
1648 " Stack Limit: 0x%08x\n"
1649 " Stack Base: 0x%08x\n"
1650 " Kernel Stack: 0x%08x\n"
1651 " Trap Frame: 0x%08x\n"
1652 " NPX State: %s (0x%x)\n",
1653 (Argc
< 2) ? "Current Thread:\n" : "",
1654 Thread
->Cid
.UniqueThread
,
1655 State
, Thread
->Tcb
.State
,
1656 Thread
->Tcb
.Priority
,
1657 Thread
->Tcb
.Affinity
,
1658 Thread
->Tcb
.InitialStack
,
1659 Thread
->Tcb
.StackLimit
,
1660 Thread
->Tcb
.StackBase
,
1661 Thread
->Tcb
.KernelStack
,
1662 Thread
->Tcb
.TrapFrame
,
1663 NPX_STATE_TO_STRING(Thread
->Tcb
.NpxState
), Thread
->Tcb
.NpxState
);
1665 /* Release our reference if we had one */
1666 if (ReferencedThread
)
1667 ObDereferenceObject(Thread
);
1673 /*!\brief Lists processes or switches to another process context.
1682 BOOLEAN ReferencedProcess
= FALSE
;
1683 PCHAR State
, pend
, str1
, str2
;
1685 extern LIST_ENTRY PsActiveProcessHead
;
1687 if (Argc
>= 2 && _stricmp(Argv
[1], "list") == 0)
1689 Entry
= PsActiveProcessHead
.Flink
;
1690 if (!Entry
|| Entry
== &PsActiveProcessHead
)
1692 KdbpPrint("No processes in the system!\n");
1696 KdbpPrint(" PID State Filename\n");
1699 Process
= CONTAINING_RECORD(Entry
, EPROCESS
, ActiveProcessLinks
);
1701 if (Process
== KdbCurrentProcess
)
1712 State
= ((Process
->Pcb
.State
== ProcessInMemory
) ? "In Memory" :
1713 ((Process
->Pcb
.State
== ProcessOutOfMemory
) ? "Out of Memory" : "In Transition"));
1715 KdbpPrint(" %s0x%08x %-10s %s%s\n",
1717 Process
->UniqueProcessId
,
1719 Process
->ImageFileName
,
1722 Entry
= Entry
->Flink
;
1724 while(Entry
!= &PsActiveProcessHead
);
1726 else if (Argc
>= 2 && _stricmp(Argv
[1], "attach") == 0)
1730 KdbpPrint("process attach: process id argument required!\n");
1734 ul
= strtoul(Argv
[2], &pend
, 0);
1735 if (Argv
[2] == pend
)
1737 KdbpPrint("process attach: '%s' is not a valid process id!\n", Argv
[2]);
1741 if (!KdbpAttachToProcess((PVOID
)ul
))
1746 KdbpPrint("Attached to process 0x%08x, thread 0x%08x.\n", (ULONG
)ul
,
1747 (ULONG
)KdbCurrentThread
->Cid
.UniqueThread
);
1751 Process
= KdbCurrentProcess
;
1755 ul
= strtoul(Argv
[1], &pend
, 0);
1756 if (Argv
[1] == pend
)
1758 KdbpPrint("proc: '%s' is not a valid process id!\n", Argv
[1]);
1762 if (!NT_SUCCESS(PsLookupProcessByProcessId((PVOID
)ul
, &Process
)))
1764 KdbpPrint("proc: Invalid process id!\n");
1768 /* Remember our reference */
1769 ReferencedProcess
= TRUE
;
1772 State
= ((Process
->Pcb
.State
== ProcessInMemory
) ? "In Memory" :
1773 ((Process
->Pcb
.State
== ProcessOutOfMemory
) ? "Out of Memory" : "In Transition"));
1776 " State: %s (0x%x)\n"
1777 " Image Filename: %s\n",
1778 (Argc
< 2) ? "Current process:\n" : "",
1779 Process
->UniqueProcessId
,
1780 State
, Process
->Pcb
.State
,
1781 Process
->ImageFileName
);
1783 /* Release our reference, if any */
1784 if (ReferencedProcess
)
1785 ObDereferenceObject(Process
);
1791 /*!\brief Lists loaded modules or the one containing the specified address.
1798 ULONGLONG Result
= 0;
1800 PLDR_DATA_TABLE_ENTRY LdrEntry
;
1801 BOOLEAN DisplayOnlyOneModule
= FALSE
;
1806 /* Put the arguments back together */
1809 Argv
[Argc
][strlen(Argv
[Argc
])] = ' ';
1811 /* Evaluate the expression */
1812 if (!KdbpEvaluateExpression(Argv
[1], sizeof("kdb:> ")-1 + (Argv
[1]-Argv
[0]), &Result
))
1817 if (Result
> (ULONGLONG
)(~((ULONG_PTR
)0)))
1818 KdbpPrint("%s: Warning: Address %I64x is beeing truncated\n", Argv
[0],Result
);
1820 Address
= (ULONG_PTR
)Result
;
1822 if (!KdbpSymFindModule((PVOID
)Address
, NULL
, -1, &LdrEntry
))
1824 KdbpPrint("No module containing address 0x%p found!\n", Address
);
1828 DisplayOnlyOneModule
= TRUE
;
1832 if (!KdbpSymFindModule(NULL
, NULL
, 0, &LdrEntry
))
1834 ULONG_PTR ntoskrnlBase
= ((ULONG_PTR
)KdbpCmdMod
) & 0xfff00000;
1835 KdbpPrint(" Base Size Name\n");
1836 KdbpPrint(" %08x %08x %s\n", ntoskrnlBase
, 0, "ntoskrnl.exe");
1843 KdbpPrint(" Base Size Name\n");
1846 KdbpPrint(" %08x %08x %wZ\n", LdrEntry
->DllBase
, LdrEntry
->SizeOfImage
, &LdrEntry
->BaseDllName
);
1848 if(DisplayOnlyOneModule
|| !KdbpSymFindModule(NULL
, NULL
, i
++, &LdrEntry
))
1855 /*!\brief Displays GDT, LDT or IDTd.
1872 if (Argv
[0][0] == 'i')
1879 KdbpPrint("Interrupt descriptor table is empty.\n");
1883 KdbpPrint("IDT Base: 0x%08x Limit: 0x%04x\n", Reg
.Base
, Reg
.Limit
);
1884 KdbpPrint(" Idx Type Seg. Sel. Offset DPL\n");
1886 for (i
= 0; (i
+ sizeof(SegDesc
) - 1) <= Reg
.Limit
; i
+= 8)
1888 if (!NT_SUCCESS(KdbpSafeReadMemory(SegDesc
, (PVOID
)(Reg
.Base
+ i
), sizeof(SegDesc
))))
1890 KdbpPrint("Couldn't access memory at 0x%08x!\n", Reg
.Base
+ i
);
1894 Dpl
= ((SegDesc
[1] >> 13) & 3);
1895 if ((SegDesc
[1] & 0x1f00) == 0x0500) /* Task gate */
1896 SegType
= "TASKGATE";
1897 else if ((SegDesc
[1] & 0x1fe0) == 0x0e00) /* 32 bit Interrupt gate */
1898 SegType
= "INTGATE32";
1899 else if ((SegDesc
[1] & 0x1fe0) == 0x0600) /* 16 bit Interrupt gate */
1900 SegType
= "INTGATE16";
1901 else if ((SegDesc
[1] & 0x1fe0) == 0x0f00) /* 32 bit Trap gate */
1902 SegType
= "TRAPGATE32";
1903 else if ((SegDesc
[1] & 0x1fe0) == 0x0700) /* 16 bit Trap gate */
1904 SegType
= "TRAPGATE16";
1906 SegType
= "UNKNOWN";
1908 if ((SegDesc
[1] & (1 << 15)) == 0) /* not present */
1910 KdbpPrint(" %03d %-10s [NP] [NP] %02d\n",
1911 i
/ 8, SegType
, Dpl
);
1913 else if ((SegDesc
[1] & 0x1f00) == 0x0500) /* Task gate */
1915 SegSel
= SegDesc
[0] >> 16;
1916 KdbpPrint(" %03d %-10s 0x%04x %02d\n",
1917 i
/ 8, SegType
, SegSel
, Dpl
);
1921 SegSel
= SegDesc
[0] >> 16;
1922 SegBase
= (SegDesc
[1] & 0xffff0000) | (SegDesc
[0] & 0x0000ffff);
1923 KdbpPrint(" %03d %-10s 0x%04x 0x%08x %02d\n",
1924 i
/ 8, SegType
, SegSel
, SegBase
, Dpl
);
1932 if (Argv
[0][0] == 'g')
1935 Ke386GetGlobalDescriptorTable(&Reg
.Limit
);
1940 ASSERT(Argv
[0][0] == 'l');
1943 Reg
.Limit
= Ke386GetLocalDescriptorTable();
1951 KdbpPrint("%s descriptor table is empty.\n",
1952 Argv
[0][0] == 'g' ? "Global" : "Local");
1956 KdbpPrint("%cDT Base: 0x%08x Limit: 0x%04x\n",
1957 Argv
[0][0] == 'g' ? 'G' : 'L', Reg
.Base
, Reg
.Limit
);
1958 KdbpPrint(" Idx Sel. Type Base Limit DPL Attribs\n");
1960 for (; (i
+ sizeof(SegDesc
) - 1) <= Reg
.Limit
; i
+= 8)
1962 if (!NT_SUCCESS(KdbpSafeReadMemory(SegDesc
, (PVOID
)(Reg
.Base
+ i
), sizeof(SegDesc
))))
1964 KdbpPrint("Couldn't access memory at 0x%08x!\n", Reg
.Base
+ i
);
1968 Dpl
= ((SegDesc
[1] >> 13) & 3);
1969 Type
= ((SegDesc
[1] >> 8) & 0xf);
1971 SegBase
= SegDesc
[0] >> 16;
1972 SegBase
|= (SegDesc
[1] & 0xff) << 16;
1973 SegBase
|= SegDesc
[1] & 0xff000000;
1974 SegLimit
= SegDesc
[0] & 0x0000ffff;
1975 SegLimit
|= (SegDesc
[1] >> 16) & 0xf;
1977 if ((SegDesc
[1] & (1 << 23)) != 0)
1987 if ((SegDesc
[1] & (1 << 12)) == 0) /* System segment */
1991 case 1: SegType
= "TSS16(Avl)"; break;
1992 case 2: SegType
= "LDT"; break;
1993 case 3: SegType
= "TSS16(Busy)"; break;
1994 case 4: SegType
= "CALLGATE16"; break;
1995 case 5: SegType
= "TASKGATE"; break;
1996 case 6: SegType
= "INTGATE16"; break;
1997 case 7: SegType
= "TRAPGATE16"; break;
1998 case 9: SegType
= "TSS32(Avl)"; break;
1999 case 11: SegType
= "TSS32(Busy)"; break;
2000 case 12: SegType
= "CALLGATE32"; break;
2001 case 14: SegType
= "INTGATE32"; break;
2002 case 15: SegType
= "INTGATE32"; break;
2003 default: SegType
= "UNKNOWN"; break;
2006 if (!(Type
>= 1 && Type
<= 3) &&
2007 Type
!= 9 && Type
!= 11)
2013 else if ((SegDesc
[1] & (1 << 11)) == 0) /* Data segment */
2015 if ((SegDesc
[1] & (1 << 22)) != 0)
2020 else /* Code segment */
2022 if ((SegDesc
[1] & (1 << 22)) != 0)
2028 if ((SegDesc
[1] & (1 << 15)) == 0) /* not present */
2030 KdbpPrint(" %03d 0x%04x %-11s [NP] [NP] %02d NP\n",
2031 i
/ 8, i
| Dpl
| ul
, SegType
, Dpl
);
2035 KdbpPrint(" %03d 0x%04x %-11s 0x%08x 0x%08x %02d ",
2036 i
/ 8, i
| Dpl
| ul
, SegType
, SegBase
, SegLimit
, Dpl
);
2038 if ((SegDesc
[1] & (1 << 12)) == 0) /* System segment */
2040 /* FIXME: Display system segment */
2042 else if ((SegDesc
[1] & (1 << 11)) == 0) /* Data segment */
2044 if ((SegDesc
[1] & (1 << 10)) != 0) /* Expand-down */
2047 KdbpPrint((SegDesc
[1] & (1 << 9)) ? " R/W" : " R");
2049 if ((SegDesc
[1] & (1 << 8)) != 0)
2052 else /* Code segment */
2054 if ((SegDesc
[1] & (1 << 10)) != 0) /* Conforming */
2057 KdbpPrint((SegDesc
[1] & (1 << 9)) ? " R/X" : " X");
2059 if ((SegDesc
[1] & (1 << 8)) != 0)
2063 if ((SegDesc
[1] & (1 << 20)) != 0)
2074 /*!\brief Displays the KPCR
2081 PKIPCR Pcr
= (PKIPCR
)KeGetPcr();
2083 KdbpPrint("Current PCR is at 0x%08x.\n", (INT
)Pcr
);
2084 KdbpPrint(" Tib.ExceptionList: 0x%08x\n"
2085 " Tib.StackBase: 0x%08x\n"
2086 " Tib.StackLimit: 0x%08x\n"
2087 " Tib.SubSystemTib: 0x%08x\n"
2088 " Tib.FiberData/Version: 0x%08x\n"
2089 " Tib.ArbitraryUserPointer: 0x%08x\n"
2090 " Tib.Self: 0x%08x\n"
2095 " IrrActive: 0x%08x\n"
2097 " KdVersionBlock: 0x%08x\n"
2101 " MajorVersion: 0x%04x\n"
2102 " MinorVersion: 0x%04x\n"
2103 " SetMember: 0x%08x\n"
2104 " StallScaleFactor: 0x%08x\n"
2106 " L2CacheAssociativity: 0x%02x\n"
2107 " VdmAlert: 0x%08x\n"
2108 " L2CacheSize: 0x%08x\n"
2109 " InterruptMode: 0x%08x\n",
2110 Pcr
->NtTib
.ExceptionList
, Pcr
->NtTib
.StackBase
, Pcr
->NtTib
.StackLimit
,
2111 Pcr
->NtTib
.SubSystemTib
, Pcr
->NtTib
.FiberData
, Pcr
->NtTib
.ArbitraryUserPointer
,
2112 Pcr
->NtTib
.Self
, Pcr
->Self
, Pcr
->Prcb
, Pcr
->Irql
, Pcr
->IRR
, Pcr
->IrrActive
,
2113 Pcr
->IDR
, Pcr
->KdVersionBlock
, Pcr
->IDT
, Pcr
->GDT
, Pcr
->TSS
,
2114 Pcr
->MajorVersion
, Pcr
->MinorVersion
, Pcr
->SetMember
, Pcr
->StallScaleFactor
,
2115 Pcr
->Number
, Pcr
->SecondLevelCacheAssociativity
,
2116 Pcr
->VdmAlert
, Pcr
->SecondLevelCacheSize
, Pcr
->InterruptMode
);
2121 /*!\brief Displays the TSS
2128 KTSS
*Tss
= KeGetPcr()->TSS
;
2130 KdbpPrint("Current TSS is at 0x%08x.\n", (INT
)Tss
);
2131 KdbpPrint(" Eip: 0x%08x\n"
2138 " IoMapBase: 0x%04x\n",
2139 Tss
->Eip
, Tss
->Es
, Tss
->Cs
, Tss
->Ds
, Tss
->Fs
, Tss
->Gs
, Tss
->IoMapBase
);
2144 /*!\brief Bugchecks the system.
2151 /* Set the flag and quit looping */
2152 KdbpBugCheckRequested
= TRUE
;
2160 IN ULONG BufLength
);
2162 /*!\brief Display debug messages on screen, with paging.
2164 * Keys for per-page view: Home, End, PageUp, Arrow Up, PageDown,
2165 * all others are as PageDown.
2174 KdbpIsInDmesgMode
= TRUE
; /* Toggle logging flag */
2175 if (!KdpDmesgBuffer
)
2177 KdbpPrint("Dmesg: error, buffer is not allocated! /DEBUGPORT=SCREEN kernel param required for dmesg.\n");
2181 KdbpPrint("*** Dmesg *** TotalWritten=%lu, BufferSize=%lu, CurrentPosition=%lu\n",
2182 KdbDmesgTotalWritten
, KdpDmesgBufferSize
, KdpDmesgCurrentPosition
);
2184 // Pass data to the pager:
2185 end
= KdpDmesgCurrentPosition
;
2186 beg
= (end
+ KdpDmesgFreeBytes
) % KdpDmesgBufferSize
;
2188 // no roll-overs, and overwritten=lost bytes
2189 if (KdbDmesgTotalWritten
<= KdpDmesgBufferSize
)
2191 // show buffer (KdpDmesgBuffer + beg, num)
2192 KdbpPager(KdpDmesgBuffer
, KdpDmesgCurrentPosition
);
2196 // show 2 buffers: (KdpDmesgBuffer + beg, KdpDmesgBufferSize - beg)
2197 // and: (KdpDmesgBuffer, end)
2198 KdbpPager(KdpDmesgBuffer
+ beg
, KdpDmesgBufferSize
- beg
);
2199 KdbpPrint("*** Dmesg: buffer rollup ***\n");
2200 KdbpPager(KdpDmesgBuffer
, end
);
2202 KdbpPrint("*** Dmesg: end of output ***\n");
2204 KdbpIsInDmesgMode
= FALSE
; /* Toggle logging flag */
2209 /*!\brief Sets or displays a config variables value.
2219 KDB_ENTER_CONDITION ConditionFirst
= KdbDoNotEnter
;
2220 KDB_ENTER_CONDITION ConditionLast
= KdbDoNotEnter
;
2222 static const PCHAR ExceptionNames
[21] =
2224 "ZERODEVIDE", "DEBUGTRAP", "NMI", "INT3", "OVERFLOW", "BOUND", "INVALIDOP",
2225 "NOMATHCOP", "DOUBLEFAULT", "RESERVED(9)", "INVALIDTSS", "SEGMENTNOTPRESENT",
2226 "STACKFAULT", "GPF", "PAGEFAULT", "RESERVED(15)", "MATHFAULT", "ALIGNMENTCHECK",
2227 "MACHINECHECK", "SIMDFAULT", "OTHERS"
2232 KdbpPrint("Available settings:\n");
2233 KdbpPrint(" syntax [intel|at&t]\n");
2234 KdbpPrint(" condition [exception|*] [first|last] [never|always|kmode|umode]\n");
2235 KdbpPrint(" break_on_module_load [true|false]\n");
2237 else if (strcmp(Argv
[1], "syntax") == 0)
2241 KdbpPrint("syntax = %s\n", KdbUseIntelSyntax
? "intel" : "at&t");
2245 if (_stricmp(Argv
[2], "intel") == 0)
2246 KdbUseIntelSyntax
= TRUE
;
2247 else if (_stricmp(Argv
[2], "at&t") == 0)
2248 KdbUseIntelSyntax
= FALSE
;
2250 KdbpPrint("Unknown syntax '%s'.\n", Argv
[2]);
2253 else if (strcmp(Argv
[1], "condition") == 0)
2257 KdbpPrint("Conditions: (First) (Last)\n");
2258 for (l
= 0; l
< RTL_NUMBER_OF(ExceptionNames
) - 1; l
++)
2260 if (!ExceptionNames
[l
])
2263 if (!KdbpGetEnterCondition(l
, TRUE
, &ConditionFirst
))
2266 if (!KdbpGetEnterCondition(l
, FALSE
, &ConditionLast
))
2269 KdbpPrint(" #%02d %-20s %-8s %-8s\n", l
, ExceptionNames
[l
],
2270 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst
),
2271 KDB_ENTER_CONDITION_TO_STRING(ConditionLast
));
2274 ASSERT(l
== (RTL_NUMBER_OF(ExceptionNames
) - 1));
2275 KdbpPrint(" %-20s %-8s %-8s\n", ExceptionNames
[l
],
2276 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst
),
2277 KDB_ENTER_CONDITION_TO_STRING(ConditionLast
));
2281 if (Argc
>= 5 && strcmp(Argv
[2], "*") == 0) /* Allow * only when setting condition */
2287 l
= strtoul(Argv
[2], &pend
, 0);
2289 if (Argv
[2] == pend
)
2291 for (l
= 0; l
< RTL_NUMBER_OF(ExceptionNames
); l
++)
2293 if (!ExceptionNames
[l
])
2296 if (_stricmp(ExceptionNames
[l
], Argv
[2]) == 0)
2301 if (l
>= RTL_NUMBER_OF(ExceptionNames
))
2303 KdbpPrint("Unknown exception '%s'.\n", Argv
[2]);
2310 if (_stricmp(Argv
[3], "first") == 0)
2312 else if (_stricmp(Argv
[3], "last") == 0)
2316 KdbpPrint("set condition: second argument must be 'first' or 'last'\n");
2320 if (_stricmp(Argv
[4], "never") == 0)
2321 ConditionFirst
= KdbDoNotEnter
;
2322 else if (_stricmp(Argv
[4], "always") == 0)
2323 ConditionFirst
= KdbEnterAlways
;
2324 else if (_stricmp(Argv
[4], "umode") == 0)
2325 ConditionFirst
= KdbEnterFromUmode
;
2326 else if (_stricmp(Argv
[4], "kmode") == 0)
2327 ConditionFirst
= KdbEnterFromKmode
;
2330 KdbpPrint("set condition: third argument must be 'never', 'always', 'umode' or 'kmode'\n");
2334 if (!KdbpSetEnterCondition(l
, First
, ConditionFirst
))
2337 KdbpPrint("Couldn't change condition for exception #%02d\n", l
);
2339 KdbpPrint("Couldn't change condition for all exceptions\n", l
);
2342 else /* Argc >= 3 */
2344 if (!KdbpGetEnterCondition(l
, TRUE
, &ConditionFirst
))
2347 if (!KdbpGetEnterCondition(l
, FALSE
, &ConditionLast
))
2350 if (l
< (RTL_NUMBER_OF(ExceptionNames
) - 1))
2352 KdbpPrint("Condition for exception #%02d (%s): FirstChance %s LastChance %s\n",
2353 l
, ExceptionNames
[l
],
2354 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst
),
2355 KDB_ENTER_CONDITION_TO_STRING(ConditionLast
));
2359 KdbpPrint("Condition for all other exceptions: FirstChance %s LastChance %s\n",
2360 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst
),
2361 KDB_ENTER_CONDITION_TO_STRING(ConditionLast
));
2366 else if (strcmp(Argv
[1], "break_on_module_load") == 0)
2369 KdbpPrint("break_on_module_load = %s\n", KdbBreakOnModuleLoad
? "enabled" : "disabled");
2372 if (_stricmp(Argv
[2], "enable") == 0 || _stricmp(Argv
[2], "enabled") == 0 || _stricmp(Argv
[2], "true") == 0)
2373 KdbBreakOnModuleLoad
= TRUE
;
2374 else if (_stricmp(Argv
[2], "disable") == 0 || _stricmp(Argv
[2], "disabled") == 0 || _stricmp(Argv
[2], "false") == 0)
2375 KdbBreakOnModuleLoad
= FALSE
;
2377 KdbpPrint("Unknown setting '%s'.\n", Argv
[2]);
2382 KdbpPrint("Unknown setting '%s'.\n", Argv
[1]);
2388 /*!\brief Displays help screen.
2397 KdbpPrint("Kernel debugger commands:\n");
2398 for (i
= 0; i
< RTL_NUMBER_OF(KdbDebuggerCommands
); i
++)
2400 if (!KdbDebuggerCommands
[i
].Syntax
) /* Command group */
2405 KdbpPrint("\x1b[7m* %s:\x1b[0m\n", KdbDebuggerCommands
[i
].Help
);
2409 KdbpPrint(" %-20s - %s\n",
2410 KdbDebuggerCommands
[i
].Syntax
,
2411 KdbDebuggerCommands
[i
].Help
);
2417 /*!\brief Prints the given string with printf-like formatting.
2419 * \param Format Format of the string/arguments.
2420 * \param ... Variable number of arguments matching the format specified in \a Format.
2422 * \note Doesn't correctly handle \\t and terminal escape sequences when calculating the
2423 * number of lines required to print a single line from the Buffer in the terminal.
2424 * Prints maximum 4096 chars, because of its buffer size.
2431 static CHAR Buffer
[4096];
2432 static BOOLEAN TerminalInitialized
= FALSE
;
2433 static BOOLEAN TerminalConnected
= FALSE
;
2434 static BOOLEAN TerminalReportsSize
= TRUE
;
2439 LONG RowsPrintedByTerminal
;
2443 /* Check if the user has aborted output of the current command */
2444 if (KdbOutputAborted
)
2447 /* Initialize the terminal */
2448 if (!TerminalInitialized
)
2450 DbgPrint("\x1b[7h"); /* Enable linewrap */
2452 /* Query terminal type */
2453 /*DbgPrint("\x1b[Z");*/
2456 TerminalInitialized
= TRUE
;
2458 KeStallExecutionProcessor(100000);
2462 c
= KdbpTryGetCharSerial(5000);
2466 Buffer
[Length
++] = c
;
2467 if (Length
>= (sizeof (Buffer
) - 1))
2471 Buffer
[Length
] = '\0';
2473 TerminalConnected
= TRUE
;
2476 /* Get number of rows and columns in terminal */
2477 if ((KdbNumberOfRowsTerminal
< 0) || (KdbNumberOfColsTerminal
< 0) ||
2478 (KdbNumberOfRowsPrinted
) == 0) /* Refresh terminal size each time when number of rows printed is 0 */
2480 if ((KdbDebugState
& KD_DEBUG_KDSERIAL
) && TerminalConnected
&& TerminalReportsSize
)
2482 /* Try to query number of rows from terminal. A reply looks like "\x1b[8;24;80t" */
2483 TerminalReportsSize
= FALSE
;
2484 KeStallExecutionProcessor(100000);
2485 DbgPrint("\x1b[18t");
2486 c
= KdbpTryGetCharSerial(5000);
2490 c
= KdbpTryGetCharSerial(5000);
2497 c
= KdbpTryGetCharSerial(5000);
2501 Buffer
[Length
++] = c
;
2502 if (isalpha(c
) || Length
>= (sizeof (Buffer
) - 1))
2506 Buffer
[Length
] = '\0';
2507 if (Buffer
[0] == '8' && Buffer
[1] == ';')
2509 for (i
= 2; (i
< Length
) && (Buffer
[i
] != ';'); i
++);
2511 if (Buffer
[i
] == ';')
2515 /* Number of rows is now at Buffer + 2 and number of cols at Buffer + i */
2516 KdbNumberOfRowsTerminal
= strtoul(Buffer
+ 2, NULL
, 0);
2517 KdbNumberOfColsTerminal
= strtoul(Buffer
+ i
, NULL
, 0);
2518 TerminalReportsSize
= TRUE
;
2522 /* Clear further characters */
2523 while ((c
= KdbpTryGetCharSerial(5000)) != -1);
2527 if (KdbNumberOfRowsTerminal
<= 0)
2529 /* Set number of rows to the default. */
2530 KdbNumberOfRowsTerminal
= 23; //24; //Mna.: 23 for SCREEN debugport
2532 else if (KdbNumberOfColsTerminal
<= 0)
2534 /* Set number of cols to the default. */
2535 KdbNumberOfColsTerminal
= 75; //80; //Mna.: 75 for SCREEN debugport
2539 /* Get the string */
2540 va_start(ap
, Format
);
2541 Length
= _vsnprintf(Buffer
, sizeof (Buffer
) - 1, Format
, ap
);
2542 Buffer
[Length
] = '\0';
2546 while (p
[0] != '\0')
2548 i
= strcspn(p
, "\n");
2550 /* Calculate the number of lines which will be printed in the terminal
2551 * when outputting the current line
2554 RowsPrintedByTerminal
= (i
+ KdbNumberOfColsPrinted
- 1) / KdbNumberOfColsTerminal
;
2556 RowsPrintedByTerminal
= 0;
2559 RowsPrintedByTerminal
++;
2561 /*DbgPrint("!%d!%d!%d!%d!", KdbNumberOfRowsPrinted, KdbNumberOfColsPrinted, i, RowsPrintedByTerminal);*/
2563 /* Display a prompt if we printed one screen full of text */
2564 if (KdbNumberOfRowsTerminal
> 0 &&
2565 (LONG
)(KdbNumberOfRowsPrinted
+ RowsPrintedByTerminal
) >= KdbNumberOfRowsTerminal
)
2567 KdbRepeatLastCommand
= FALSE
;
2569 if (KdbNumberOfColsPrinted
> 0)
2572 DbgPrint("--- Press q to abort, any other key to continue ---");
2573 RowsPrintedByTerminal
++; /* added by Mna. */
2575 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
2576 c
= KdbpGetCharSerial();
2578 c
= KdbpGetCharKeyboard(&ScanCode
);
2582 /* Try to read '\n' which might follow '\r' - if \n is not received here
2583 * it will be interpreted as "return" when the next command should be read.
2585 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
2586 c
= KdbpTryGetCharSerial(5);
2588 c
= KdbpTryGetCharKeyboard(&ScanCode
, 5);
2594 KdbOutputAborted
= TRUE
;
2598 KdbNumberOfRowsPrinted
= 0;
2599 KdbNumberOfColsPrinted
= 0;
2602 /* Insert a NUL after the line and print only the current line. */
2603 if (p
[i
] == '\n' && p
[i
+ 1] != '\0')
2613 /* Remove escape sequences from the line if there's no terminal connected */
2614 if (!TerminalConnected
)
2616 while ((p2
= strrchr(p
, '\x1b'))) /* Look for escape character */
2621 while (!isalpha(p2
[j
++]));
2636 /* Set p to the start of the next line and
2637 * remember the number of rows/cols printed
2643 KdbNumberOfColsPrinted
= 0;
2647 ASSERT(p
[0] == '\0');
2648 KdbNumberOfColsPrinted
+= i
;
2651 KdbNumberOfRowsPrinted
+= RowsPrintedByTerminal
;
2655 /** memrchr(), explicitly defined, since was absent in MinGW of RosBE. */
2658 * Find the last occurrence of 'c' in the buffer 's' of size 'n'.
2661 memrchr(const void *s
, int c
, size_t n
)
2663 const unsigned char *cp
;
2667 cp
= (unsigned char *)s
+ n
;
2670 if (*(--cp
) == (unsigned char)c
)
2677 /*!\brief Calculate pointer position for N lines upper of current position.
2679 * \param Buffer Characters buffer to operate on.
2680 * \param BufLength Buffer size.
2682 * \note Calculate pointer position for N lines upper of current displaying
2683 * position within the given buffer.
2685 * Used by KdbpPager().
2686 * Now N lines count is hardcoded to KdbNumberOfRowsTerminal.
2689 CountOnePageUp(PCHAR Buffer
, ULONG BufLength
, PCHAR pCurPos
)
2692 // p0 is initial guess of Page Start
2693 ULONG p0len
= KdbNumberOfRowsTerminal
* KdbNumberOfColsTerminal
;
2694 PCHAR p0
= pCurPos
- p0len
;
2695 PCHAR prev_p
= p0
, p1
;
2698 if (pCurPos
< Buffer
)
2700 ASSERT(pCurPos
<= Buffer
+ BufLength
);
2702 p
= memrchr(p0
, '\n', p0len
);
2705 for (j
= KdbNumberOfRowsTerminal
; j
--; )
2708 p1
= memrchr(p0
, '\n', p
-p0
);
2718 linesCnt
= (KdbNumberOfColsTerminal
+prev_p
-p
-2) / KdbNumberOfColsTerminal
;
2728 /*!\brief Prints the given string with, page by page.
2730 * \param Buffer Characters buffer to print.
2731 * \param BufferLen Buffer size.
2733 * \note Doesn't correctly handle \\t and terminal escape sequences when calculating the
2734 * number of lines required to print a single line from the Buffer in the terminal.
2735 * Maximum length of buffer is limited only by memory size.
2737 * Note: BufLength should be greater then (KdbNumberOfRowsTerminal * KdbNumberOfColsTerminal).
2745 static CHAR InBuffer
[4096];
2746 static BOOLEAN TerminalInitialized
= FALSE
;
2747 static BOOLEAN TerminalConnected
= FALSE
;
2748 static BOOLEAN TerminalReportsSize
= TRUE
;
2753 LONG RowsPrintedByTerminal
;
2759 /* Check if the user has aborted output of the current command */
2760 if (KdbOutputAborted
)
2763 /* Initialize the terminal */
2764 if (!TerminalInitialized
)
2766 DbgPrint("\x1b[7h"); /* Enable linewrap */
2768 /* Query terminal type */
2769 /*DbgPrint("\x1b[Z");*/
2772 TerminalInitialized
= TRUE
;
2774 KeStallExecutionProcessor(100000);
2778 c
= KdbpTryGetCharSerial(5000);
2782 InBuffer
[Length
++] = c
;
2783 if (Length
>= (sizeof (InBuffer
) - 1))
2787 InBuffer
[Length
] = '\0';
2789 TerminalConnected
= TRUE
;
2792 /* Get number of rows and columns in terminal */
2793 if ((KdbNumberOfRowsTerminal
< 0) || (KdbNumberOfColsTerminal
< 0) ||
2794 (KdbNumberOfRowsPrinted
) == 0) /* Refresh terminal size each time when number of rows printed is 0 */
2796 if ((KdbDebugState
& KD_DEBUG_KDSERIAL
) && TerminalConnected
&& TerminalReportsSize
)
2798 /* Try to query number of rows from terminal. A reply looks like "\x1b[8;24;80t" */
2799 TerminalReportsSize
= FALSE
;
2800 KeStallExecutionProcessor(100000);
2801 DbgPrint("\x1b[18t");
2802 c
= KdbpTryGetCharSerial(5000);
2806 c
= KdbpTryGetCharSerial(5000);
2813 c
= KdbpTryGetCharSerial(5000);
2817 InBuffer
[Length
++] = c
;
2818 if (isalpha(c
) || Length
>= (sizeof (InBuffer
) - 1))
2822 InBuffer
[Length
] = '\0';
2823 if (InBuffer
[0] == '8' && InBuffer
[1] == ';')
2825 for (i
= 2; (i
< Length
) && (InBuffer
[i
] != ';'); i
++);
2827 if (Buffer
[i
] == ';')
2831 /* Number of rows is now at Buffer + 2 and number of cols at Buffer + i */
2832 KdbNumberOfRowsTerminal
= strtoul(InBuffer
+ 2, NULL
, 0);
2833 KdbNumberOfColsTerminal
= strtoul(InBuffer
+ i
, NULL
, 0);
2834 TerminalReportsSize
= TRUE
;
2838 /* Clear further characters */
2839 while ((c
= KdbpTryGetCharSerial(5000)) != -1);
2843 if (KdbNumberOfRowsTerminal
<= 0)
2845 /* Set number of rows to the default. */
2846 KdbNumberOfRowsTerminal
= 24;
2848 else if (KdbNumberOfColsTerminal
<= 0)
2850 /* Set number of cols to the default. */
2851 KdbNumberOfColsTerminal
= 80;
2855 /* Get the string */
2858 while (p
[0] != '\0')
2860 if ( p
> Buffer
+BufLength
)
2862 DbgPrint("Dmesg: error, p > Buffer+BufLength,d=%d", p
- (Buffer
+BufLength
));
2865 i
= strcspn(p
, "\n");
2867 // Are we out of buffer?
2868 if (p
+ i
> Buffer
+ BufLength
)
2869 // Leaving pager function:
2872 /* Calculate the number of lines which will be printed in the terminal
2873 * when outputting the current line
2876 RowsPrintedByTerminal
= (i
+ KdbNumberOfColsPrinted
- 1) / KdbNumberOfColsTerminal
;
2878 RowsPrintedByTerminal
= 0;
2881 RowsPrintedByTerminal
++;
2883 /*DbgPrint("!%d!%d!%d!%d!", KdbNumberOfRowsPrinted, KdbNumberOfColsPrinted, i, RowsPrintedByTerminal);*/
2885 /* Display a prompt if we printed one screen full of text */
2886 if (KdbNumberOfRowsTerminal
> 0 &&
2887 (LONG
)(KdbNumberOfRowsPrinted
+ RowsPrintedByTerminal
) >= KdbNumberOfRowsTerminal
)
2889 KdbRepeatLastCommand
= FALSE
;
2891 if (KdbNumberOfColsPrinted
> 0)
2894 DbgPrint("--- Press q to abort, e/End,h/Home,u/PgUp, other key/PgDn ---");
2895 RowsPrintedByTerminal
++;
2897 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
2898 c
= KdbpGetCharSerial();
2900 c
= KdbpGetCharKeyboard(&ScanCode
);
2904 /* Try to read '\n' which might follow '\r' - if \n is not received here
2905 * it will be interpreted as "return" when the next command should be read.
2907 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
2908 c
= KdbpTryGetCharSerial(5);
2910 c
= KdbpTryGetCharKeyboard(&ScanCode
, 5);
2913 //DbgPrint("\n"); //Consize version: don't show pressed key
2914 DbgPrint(" '%c'/scan=%04x\n", c
, ScanCode
); // Shows pressed key
2918 KdbOutputAborted
= TRUE
;
2921 if ( ScanCode
== KEYSC_END
|| c
=='e')
2923 PCHAR pBufEnd
= Buffer
+ BufLength
;
2924 p
= CountOnePageUp(Buffer
, BufLength
, pBufEnd
);
2925 i
= strcspn(p
, "\n");
2927 else if (ScanCode
== KEYSC_PAGEUP
|| c
=='u')
2929 p
= CountOnePageUp(Buffer
, BufLength
, p
);
2930 i
= strcspn(p
, "\n");
2932 else if (ScanCode
== KEYSC_HOME
|| c
=='h')
2935 i
= strcspn(p
, "\n");
2937 else if (ScanCode
== KEYSC_ARROWUP
)
2939 p
= CountOnePageUp(Buffer
, BufLength
, p
);
2940 i
= strcspn(p
, "\n");
2943 KdbNumberOfRowsPrinted
= 0;
2944 KdbNumberOfColsPrinted
= 0;
2947 /* Insert a NUL after the line and print only the current line. */
2948 if (p
[i
] == '\n' && p
[i
+ 1] != '\0')
2958 /* Remove escape sequences from the line if there's no terminal connected */
2959 if (!TerminalConnected
)
2961 while ((p2
= strrchr(p
, '\x1b'))) /* Look for escape character */
2966 while (!isalpha(p2
[j
++]));
2976 // The main printing of the current line:
2979 // restore not null char with saved:
2983 /* Set p to the start of the next line and
2984 * remember the number of rows/cols printed
2990 KdbNumberOfColsPrinted
= 0;
2994 ASSERT(p
[0] == '\0');
2995 KdbNumberOfColsPrinted
+= i
;
2998 KdbNumberOfRowsPrinted
+= RowsPrintedByTerminal
;
3002 /*!\brief Appends a command to the command history
3004 * \param Command Pointer to the command to append to the history.
3007 KdbpCommandHistoryAppend(
3010 ULONG Length1
= strlen(Command
) + 1;
3015 ASSERT(Length1
<= RTL_NUMBER_OF(KdbCommandHistoryBuffer
));
3018 (KdbCommandHistory
[KdbCommandHistoryIndex
] &&
3019 strcmp(KdbCommandHistory
[KdbCommandHistoryIndex
], Command
) == 0))
3024 /* Calculate Length1 and Length2 */
3025 Buffer
= KdbCommandHistoryBuffer
+ KdbCommandHistoryBufferIndex
;
3026 KdbCommandHistoryBufferIndex
+= Length1
;
3027 if (KdbCommandHistoryBufferIndex
>= (LONG
)RTL_NUMBER_OF(KdbCommandHistoryBuffer
))
3029 KdbCommandHistoryBufferIndex
-= RTL_NUMBER_OF(KdbCommandHistoryBuffer
);
3030 Length2
= KdbCommandHistoryBufferIndex
;
3034 /* Remove previous commands until there is enough space to append the new command */
3035 for (i
= KdbCommandHistoryIndex
; KdbCommandHistory
[i
];)
3038 (KdbCommandHistory
[i
] >= Buffer
||
3039 KdbCommandHistory
[i
] < (KdbCommandHistoryBuffer
+ KdbCommandHistoryBufferIndex
))) ||
3041 (KdbCommandHistory
[i
] >= Buffer
&&
3042 KdbCommandHistory
[i
] < (KdbCommandHistoryBuffer
+ KdbCommandHistoryBufferIndex
))))
3044 KdbCommandHistory
[i
] = NULL
;
3049 i
= RTL_NUMBER_OF(KdbCommandHistory
) - 1;
3051 if (i
== KdbCommandHistoryIndex
)
3055 /* Make sure the new command history entry is free */
3056 KdbCommandHistoryIndex
++;
3057 KdbCommandHistoryIndex
%= RTL_NUMBER_OF(KdbCommandHistory
);
3058 if (KdbCommandHistory
[KdbCommandHistoryIndex
])
3060 KdbCommandHistory
[KdbCommandHistoryIndex
] = NULL
;
3063 /* Append command */
3064 KdbCommandHistory
[KdbCommandHistoryIndex
] = Buffer
;
3065 ASSERT((KdbCommandHistory
[KdbCommandHistoryIndex
] + Length1
) <= KdbCommandHistoryBuffer
+ RTL_NUMBER_OF(KdbCommandHistoryBuffer
));
3066 memcpy(KdbCommandHistory
[KdbCommandHistoryIndex
], Command
, Length1
);
3069 memcpy(KdbCommandHistoryBuffer
, Command
+ Length1
, Length2
);
3073 /*!\brief Reads a line of user-input.
3075 * \param Buffer Buffer to store the input into. Trailing newlines are removed.
3076 * \param Size Size of \a Buffer.
3078 * \note Accepts only \n newlines, \r is ignored.
3086 PCHAR Orig
= Buffer
;
3089 static CHAR LastCommand
[1024];
3090 static CHAR NextKey
= '\0';
3091 INT CmdHistIndex
= -1;
3094 EchoOn
= !((KdbDebugState
& KD_DEBUG_KDNOECHO
) != 0);
3098 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
3100 Key
= (NextKey
== '\0') ? KdbpGetCharSerial() : NextKey
;
3103 if (Key
== KEY_ESC
) /* ESC */
3105 Key
= KdbpGetCharSerial();
3108 Key
= KdbpGetCharSerial();
3113 ScanCode
= KEY_SCAN_UP
;
3116 ScanCode
= KEY_SCAN_DOWN
;
3129 Key
= (NextKey
== '\0') ? KdbpGetCharKeyboard(&ScanCode
) : NextKey
;
3133 if ((ULONG
)(Buffer
- Orig
) >= (Size
- 1))
3135 /* Buffer is full, accept only newlines */
3142 /* Read the next char - this is to throw away a \n which most clients should
3145 KeStallExecutionProcessor(100000);
3147 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
3148 NextKey
= KdbpTryGetCharSerial(5);
3150 NextKey
= KdbpTryGetCharKeyboard(&ScanCode
, 5);
3152 if (NextKey
== '\n' || NextKey
== -1) /* \n or no response at all */
3158 * Repeat the last command if the user presses enter. Reduces the
3159 * risk of RSI when single-stepping.
3163 KdbRepeatLastCommand
= TRUE
;
3164 RtlStringCbCopyA(LastCommand
, sizeof(LastCommand
), Orig
);
3167 else if (KdbRepeatLastCommand
)
3168 RtlStringCbCopyA(Buffer
, Size
, LastCommand
);
3174 else if (Key
== KEY_BS
|| Key
== KEY_DEL
)
3182 KdbpPrint("%c %c", KEY_BS
, KEY_BS
);
3184 KdbpPrint(" %c", KEY_BS
);
3187 else if (ScanCode
== KEY_SCAN_UP
)
3189 BOOLEAN Print
= TRUE
;
3191 if (CmdHistIndex
< 0)
3193 CmdHistIndex
= KdbCommandHistoryIndex
;
3197 i
= CmdHistIndex
- 1;
3200 CmdHistIndex
= RTL_NUMBER_OF(KdbCommandHistory
) - 1;
3202 if (KdbCommandHistory
[i
] && i
!= KdbCommandHistoryIndex
)
3208 if (Print
&& KdbCommandHistory
[CmdHistIndex
])
3210 while (Buffer
> Orig
)
3216 KdbpPrint("%c %c", KEY_BS
, KEY_BS
);
3218 KdbpPrint(" %c", KEY_BS
);
3221 i
= min(strlen(KdbCommandHistory
[CmdHistIndex
]), Size
- 1);
3222 memcpy(Orig
, KdbCommandHistory
[CmdHistIndex
], i
);
3225 KdbpPrint("%s", Orig
);
3228 else if (ScanCode
== KEY_SCAN_DOWN
)
3230 if (CmdHistIndex
> 0 && CmdHistIndex
!= KdbCommandHistoryIndex
)
3232 i
= CmdHistIndex
+ 1;
3233 if (i
>= (INT
)RTL_NUMBER_OF(KdbCommandHistory
))
3236 if (KdbCommandHistory
[i
])
3239 while (Buffer
> Orig
)
3245 KdbpPrint("%c %c", KEY_BS
, KEY_BS
);
3247 KdbpPrint(" %c", KEY_BS
);
3250 i
= min(strlen(KdbCommandHistory
[CmdHistIndex
]), Size
- 1);
3251 memcpy(Orig
, KdbCommandHistory
[CmdHistIndex
], i
);
3254 KdbpPrint("%s", Orig
);
3261 KdbpPrint("%c", Key
);
3269 /*!\brief Parses command line and executes command if found
3271 * \param Command Command line to parse and execute if possible.
3273 * \retval TRUE Don't continue execution.
3274 * \retval FALSE Continue execution (leave KDB)
3283 static PCH Argv
[256];
3284 static CHAR OrigCommand
[1024];
3286 RtlStringCbCopyA(OrigCommand
, sizeof(OrigCommand
), Command
);
3293 while (*p
== '\t' || *p
== ' ')
3299 i
= strcspn(p
, "\t ");
3312 for (i
= 0; i
< RTL_NUMBER_OF(KdbDebuggerCommands
); i
++)
3314 if (!KdbDebuggerCommands
[i
].Name
)
3317 if (strcmp(KdbDebuggerCommands
[i
].Name
, Argv
[0]) == 0)
3319 return KdbDebuggerCommands
[i
].Fn(Argc
, Argv
);
3323 KdbpPrint("Command '%s' is unknown.\n", OrigCommand
);
3327 /*!\brief KDB Main Loop.
3329 * \param EnteredOnSingleStep TRUE if KDB was entered on single step.
3333 IN BOOLEAN EnteredOnSingleStep
)
3335 static CHAR Command
[1024];
3338 if (EnteredOnSingleStep
)
3340 if (!KdbSymPrintAddress((PVOID
)KdbCurrentTrapFrame
->Tf
.Eip
, &KdbCurrentTrapFrame
->Tf
))
3342 KdbpPrint("<%x>", KdbCurrentTrapFrame
->Tf
.Eip
);
3346 if (KdbpDisassemble(KdbCurrentTrapFrame
->Tf
.Eip
, KdbUseIntelSyntax
) < 0)
3348 KdbpPrint("<INVALID>");
3353 /* Flush the input buffer */
3354 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
3356 while (KdbpTryGetCharSerial(1) != -1);
3361 while (KdbpTryGetCharKeyboard(&ScanCode
, 1) != -1);
3367 /* Reset the number of rows/cols printed */
3368 KdbNumberOfRowsPrinted
= KdbNumberOfColsPrinted
= 0;
3370 /* Print the prompt */
3371 KdbpPrint("kdb:> ");
3373 /* Read a command and remember it */
3374 KdbpReadCommand(Command
, sizeof (Command
));
3375 KdbpCommandHistoryAppend(Command
);
3377 /* Reset the number of rows/cols printed and output aborted state */
3378 KdbNumberOfRowsPrinted
= KdbNumberOfColsPrinted
= 0;
3379 KdbOutputAborted
= FALSE
;
3381 /* Call the command */
3382 Continue
= KdbpDoCommand(Command
);
3383 KdbOutputAborted
= FALSE
;
3388 /*!\brief Called when a module is loaded.
3390 * \param Name Filename of the module which was loaded.
3393 KdbpCliModuleLoaded(
3394 IN PUNICODE_STRING Name
)
3396 if (!KdbBreakOnModuleLoad
)
3399 KdbpPrint("Module %wZ loaded.\n", Name
);
3400 DbgBreakPointWithStatus(DBG_STATUS_CONTROL_C
);
3403 /*!\brief This function is called by KdbEnterDebuggerException...
3405 * Used to interpret the init file in a context with a trapframe setup
3406 * (KdbpCliInit call KdbEnter which will call KdbEnterDebuggerException which will
3407 * call this function if KdbInitFileBuffer is not NULL.
3410 KdbpCliInterpretInitFile()
3416 /* Execute the commands in the init file */
3417 DPRINT("KDB: Executing KDBinit file...\n");
3418 p1
= KdbInitFileBuffer
;
3419 while (p1
[0] != '\0')
3421 i
= strcspn(p1
, "\r\n");
3427 /* Look for "break" command and comments */
3430 while (isspace(p2
[0]))
3433 if (strncmp(p2
, "break", sizeof("break")-1) == 0 &&
3434 (p2
[sizeof("break")-1] == '\0' || isspace(p2
[sizeof("break")-1])))
3436 /* break into the debugger */
3437 KdbpCliMainLoop(FALSE
);
3439 else if (p2
[0] != '#' && p2
[0] != '\0') /* Ignore empty lines and comments */
3448 while (p1
[0] == '\r' || p1
[0] == '\n')
3451 DPRINT("KDB: KDBinit executed\n");
3454 /*!\brief Called when KDB is initialized
3456 * Reads the KDBinit file from the SystemRoot\system32\drivers\etc directory and executes it.
3462 OBJECT_ATTRIBUTES ObjectAttributes
;
3463 UNICODE_STRING FileName
;
3464 IO_STATUS_BLOCK Iosb
;
3465 FILE_STANDARD_INFORMATION FileStdInfo
;
3466 HANDLE hFile
= NULL
;
3471 /* Initialize the object attributes */
3472 RtlInitUnicodeString(&FileName
, L
"\\SystemRoot\\system32\\drivers\\etc\\KDBinit");
3473 InitializeObjectAttributes(&ObjectAttributes
, &FileName
, 0, NULL
, NULL
);
3476 Status
= ZwOpenFile(&hFile
, FILE_READ_DATA
, &ObjectAttributes
, &Iosb
, 0,
3477 FILE_NON_DIRECTORY_FILE
| FILE_SYNCHRONOUS_IO_NONALERT
|
3478 FILE_NO_INTERMEDIATE_BUFFERING
);
3479 if (!NT_SUCCESS(Status
))
3481 DPRINT("Could not open \\SystemRoot\\system32\\drivers\\etc\\KDBinit (Status 0x%x)", Status
);
3485 /* Get the size of the file */
3486 Status
= ZwQueryInformationFile(hFile
, &Iosb
, &FileStdInfo
, sizeof (FileStdInfo
),
3487 FileStandardInformation
);
3488 if (!NT_SUCCESS(Status
))
3491 DPRINT("Could not query size of \\SystemRoot\\system32\\drivers\\etc\\KDBinit (Status 0x%x)", Status
);
3494 FileSize
= FileStdInfo
.EndOfFile
.u
.LowPart
;
3496 /* Allocate memory for the file */
3497 FileBuffer
= ExAllocatePool(PagedPool
, FileSize
+ 1); /* add 1 byte for terminating '\0' */
3501 DPRINT("Could not allocate %d bytes for KDBinit file\n", FileSize
);
3505 /* Load file into memory */
3506 Status
= ZwReadFile(hFile
, 0, 0, 0, &Iosb
, FileBuffer
, FileSize
, 0, 0);
3509 if (!NT_SUCCESS(Status
) && Status
!= STATUS_END_OF_FILE
)
3511 ExFreePool(FileBuffer
);
3512 DPRINT("Could not read KDBinit file into memory (Status 0x%lx)\n", Status
);
3516 FileSize
= min(FileSize
, (INT
)Iosb
.Information
);
3517 FileBuffer
[FileSize
] = '\0';
3519 /* Enter critical section */
3520 OldEflags
= __readeflags();
3523 /* Interpret the init file... */
3524 KdbInitFileBuffer
= FileBuffer
;
3526 KdbInitFileBuffer
= NULL
;
3528 /* Leave critical section */
3529 __writeeflags(OldEflags
);
3531 ExFreePool(FileBuffer
);
3536 KdpSerialDebugPrint(
3541 STRING KdpPromptString
= RTL_CONSTANT_STRING("kdb:> ");
3542 extern KSPIN_LOCK KdpSerialSpinLock
;
3546 KdpPrompt(IN LPSTR InString
,
3547 IN USHORT InStringLength
,
3548 OUT LPSTR OutString
,
3549 IN USHORT OutStringLength
)
3553 ULONG DummyScanCode
;
3556 /* Acquire the printing spinlock without waiting at raised IRQL */
3559 /* Wait when the spinlock becomes available */
3560 while (!KeTestSpinLock(&KdpSerialSpinLock
));
3562 /* Spinlock was free, raise IRQL */
3563 KeRaiseIrql(HIGH_LEVEL
, &OldIrql
);
3565 /* Try to get the spinlock */
3566 if (KeTryToAcquireSpinLockAtDpcLevel(&KdpSerialSpinLock
))
3569 /* Someone else got the spinlock, lower IRQL back */
3570 KeLowerIrql(OldIrql
);
3573 /* Loop the string to send */
3574 for (i
= 0; i
< InStringLength
; i
++)
3576 /* Print it to serial */
3577 KdPortPutByteEx(&SerialPortInfo
, *(PCHAR
)(InString
+ i
));
3580 /* Print a new line for log neatness */
3581 KdPortPutByteEx(&SerialPortInfo
, '\r');
3582 KdPortPutByteEx(&SerialPortInfo
, '\n');
3584 /* Print the kdb prompt */
3585 for (i
= 0; i
< KdpPromptString
.Length
; i
++)
3587 /* Print it to serial */
3588 KdPortPutByteEx(&SerialPortInfo
,
3589 *(KdpPromptString
.Buffer
+ i
));
3592 if (!(KdbDebugState
& KD_DEBUG_KDSERIAL
))
3595 /* Loop the whole string */
3596 for (i
= 0; i
< OutStringLength
; i
++)
3598 /* Check if this is serial debugging mode */
3599 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
3601 /* Get the character from serial */
3604 Response
= KdbpTryGetCharSerial(MAXULONG
);
3605 } while (Response
== -1);
3609 /* Get the response from the keyboard */
3612 Response
= KdbpTryGetCharKeyboard(&DummyScanCode
, MAXULONG
);
3613 } while (Response
== -1);
3616 /* Check for return */
3617 if (Response
== '\r')
3620 * We might need to discard the next '\n'.
3621 * Wait a bit to make sure we receive it.
3623 KeStallExecutionProcessor(100000);
3625 /* Check the mode */
3626 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
3628 /* Read and discard the next character, if any */
3629 KdbpTryGetCharSerial(5);
3633 /* Read and discard the next character, if any */
3634 KdbpTryGetCharKeyboard(&DummyScanCode
, 5);
3638 * Null terminate the output string -- documentation states that
3639 * DbgPrompt does not null terminate, but it does
3641 *(PCHAR
)(OutString
+ i
) = 0;
3643 /* Print a new line */
3644 KdPortPutByteEx(&SerialPortInfo
, '\r');
3645 KdPortPutByteEx(&SerialPortInfo
, '\n');
3647 /* Release spinlock */
3648 KiReleaseSpinLock(&KdpSerialSpinLock
);
3650 /* Lower IRQL back */
3651 KeLowerIrql(OldIrql
);
3653 /* Return the length */
3654 return OutStringLength
+ 1;
3657 /* Write it back and print it to the log */
3658 *(PCHAR
)(OutString
+ i
) = Response
;
3659 KdPortPutByteEx(&SerialPortInfo
, Response
);
3662 if (!(KdbDebugState
& KD_DEBUG_KDSERIAL
))
3665 /* Print a new line */
3666 KdPortPutByteEx(&SerialPortInfo
, '\r');
3667 KdPortPutByteEx(&SerialPortInfo
, '\n');
3669 /* Release spinlock */
3670 KiReleaseSpinLock(&KdpSerialSpinLock
);
3672 /* Lower IRQL back */
3673 KeLowerIrql(OldIrql
);
3675 /* Return the length */
3676 return OutStringLength
;