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 #define KDB_ENTER_CONDITION_TO_STRING(cond) \
46 ((cond) == KdbDoNotEnter ? "never" : \
47 ((cond) == KdbEnterAlways ? "always" : \
48 ((cond) == KdbEnterFromKmode ? "kmode" : "umode")))
50 #define KDB_ACCESS_TYPE_TO_STRING(type) \
51 ((type) == KdbAccessRead ? "read" : \
52 ((type) == KdbAccessWrite ? "write" : \
53 ((type) == KdbAccessReadWrite ? "rdwr" : "exec")))
55 #define NPX_STATE_TO_STRING(state) \
56 ((state) == NPX_STATE_LOADED ? "Loaded" : \
57 ((state) == NPX_STATE_NOT_LOADED ? "Not loaded" : "Unknown"))
59 /* PROTOTYPES ****************************************************************/
61 static BOOLEAN
KdbpCmdEvalExpression(ULONG Argc
, PCHAR Argv
[]);
62 static BOOLEAN
KdbpCmdDisassembleX(ULONG Argc
, PCHAR Argv
[]);
63 static BOOLEAN
KdbpCmdRegs(ULONG Argc
, PCHAR Argv
[]);
64 static BOOLEAN
KdbpCmdBackTrace(ULONG Argc
, PCHAR Argv
[]);
66 static BOOLEAN
KdbpCmdContinue(ULONG Argc
, PCHAR Argv
[]);
67 static BOOLEAN
KdbpCmdStep(ULONG Argc
, PCHAR Argv
[]);
68 static BOOLEAN
KdbpCmdBreakPointList(ULONG Argc
, PCHAR Argv
[]);
69 static BOOLEAN
KdbpCmdEnableDisableClearBreakPoint(ULONG Argc
, PCHAR Argv
[]);
70 static BOOLEAN
KdbpCmdBreakPoint(ULONG Argc
, PCHAR Argv
[]);
72 static BOOLEAN
KdbpCmdThread(ULONG Argc
, PCHAR Argv
[]);
73 static BOOLEAN
KdbpCmdProc(ULONG Argc
, PCHAR Argv
[]);
75 static BOOLEAN
KdbpCmdMod(ULONG Argc
, PCHAR Argv
[]);
76 static BOOLEAN
KdbpCmdGdtLdtIdt(ULONG Argc
, PCHAR Argv
[]);
77 static BOOLEAN
KdbpCmdPcr(ULONG Argc
, PCHAR Argv
[]);
78 static BOOLEAN
KdbpCmdTss(ULONG Argc
, PCHAR Argv
[]);
80 static BOOLEAN
KdbpCmdBugCheck(ULONG Argc
, PCHAR Argv
[]);
81 static BOOLEAN
KdbpCmdFilter(ULONG Argc
, PCHAR Argv
[]);
82 static BOOLEAN
KdbpCmdSet(ULONG Argc
, PCHAR Argv
[]);
83 static BOOLEAN
KdbpCmdHelp(ULONG Argc
, PCHAR Argv
[]);
85 /* GLOBALS *******************************************************************/
87 static BOOLEAN KdbUseIntelSyntax
= FALSE
; /* Set to TRUE for intel syntax */
88 static BOOLEAN KdbBreakOnModuleLoad
= FALSE
; /* Set to TRUE to break into KDB when a module is loaded */
90 static CHAR KdbCommandHistoryBuffer
[2048]; /* Command history string ringbuffer */
91 static PCHAR KdbCommandHistory
[sizeof(KdbCommandHistoryBuffer
) / 8] = { NULL
}; /* Command history ringbuffer */
92 static LONG KdbCommandHistoryBufferIndex
= 0;
93 static LONG KdbCommandHistoryIndex
= 0;
95 static ULONG KdbNumberOfRowsPrinted
= 0;
96 static ULONG KdbNumberOfColsPrinted
= 0;
97 static BOOLEAN KdbOutputAborted
= FALSE
;
98 static LONG KdbNumberOfRowsTerminal
= -1;
99 static LONG KdbNumberOfColsTerminal
= -1;
101 PCHAR KdbInitFileBuffer
= NULL
; /* Buffer where KDBinit file is loaded into during initialization */
102 BOOLEAN KdbpBugCheckRequested
= FALSE
;
109 BOOLEAN (*Fn
)(ULONG Argc
, PCHAR Argv
[]);
110 } KdbDebuggerCommands
[] = {
112 { NULL
, NULL
, "Data", NULL
},
113 { "?", "? expression", "Evaluate expression.", KdbpCmdEvalExpression
},
114 { "disasm", "disasm [address] [L count]", "Disassemble count instructions at address.", KdbpCmdDisassembleX
},
115 { "x", "x [address] [L count]", "Display count dwords, starting at addr.", KdbpCmdDisassembleX
},
116 { "regs", "regs", "Display general purpose registers.", KdbpCmdRegs
},
117 { "cregs", "cregs", "Display control registers.", KdbpCmdRegs
},
118 { "sregs", "sregs", "Display status registers.", KdbpCmdRegs
},
119 { "dregs", "dregs", "Display debug registers.", KdbpCmdRegs
},
120 { "bt", "bt [*frameaddr|thread id]", "Prints current backtrace or from given frame addr", KdbpCmdBackTrace
},
123 { NULL
, NULL
, "Flow control", NULL
},
124 { "cont", "cont", "Continue execution (leave debugger)", KdbpCmdContinue
},
125 { "step", "step [count]", "Execute single instructions, stepping into interrupts.", KdbpCmdStep
},
126 { "next", "next [count]", "Execute single instructions, skipping calls and reps.", KdbpCmdStep
},
127 { "bl", "bl", "List breakpoints.", KdbpCmdBreakPointList
},
128 { "be", "be [breakpoint]", "Enable breakpoint.", KdbpCmdEnableDisableClearBreakPoint
},
129 { "bd", "bd [breakpoint]", "Disable breakpoint.", KdbpCmdEnableDisableClearBreakPoint
},
130 { "bc", "bc [breakpoint]", "Clear breakpoint.", KdbpCmdEnableDisableClearBreakPoint
},
131 { "bpx", "bpx [address] [IF condition]", "Set software execution breakpoint at address.", KdbpCmdBreakPoint
},
132 { "bpm", "bpm [r|w|rw|x] [byte|word|dword] [address] [IF condition]", "Set memory breakpoint at address.", KdbpCmdBreakPoint
},
135 { NULL
, NULL
, "Process/Thread", NULL
},
136 { "thread", "thread [list[ pid]|[attach ]tid]", "List threads in current or specified process, display thread with given id or attach to thread.", KdbpCmdThread
},
137 { "proc", "proc [list|[attach ]pid]", "List processes, display process with given id or attach to process.", KdbpCmdProc
},
139 /* System information */
140 { NULL
, NULL
, "System info", NULL
},
141 { "mod", "mod [address]", "List all modules or the one containing address.", KdbpCmdMod
},
142 { "gdt", "gdt", "Display global descriptor table.", KdbpCmdGdtLdtIdt
},
143 { "ldt", "ldt", "Display local descriptor table.", KdbpCmdGdtLdtIdt
},
144 { "idt", "idt", "Display interrupt descriptor table.", KdbpCmdGdtLdtIdt
},
145 { "pcr", "pcr", "Display processor control region.", KdbpCmdPcr
},
146 { "tss", "tss", "Display task state segment.", KdbpCmdTss
},
149 { NULL
, NULL
, "Others", NULL
},
150 { "bugcheck", "bugcheck", "Bugchecks the system.", KdbpCmdBugCheck
},
151 { "filter", "filter [error|warning|trace|info|level]+|-[componentname|default]", "Enable/disable debug channels", KdbpCmdFilter
},
152 { "set", "set [var] [value]", "Sets var to value or displays value of var.", KdbpCmdSet
},
153 { "help", "help", "Display help screen.", KdbpCmdHelp
}
156 /* FUNCTIONS *****************************************************************/
158 /*!\brief Transform a component name to an integer
160 * \param ComponentName The name of the component.
161 * \param ComponentId Receives the component id on success.
163 * \retval TRUE Success.
164 * \retval FALSE Failure.
168 IN PCCH ComponentName
,
169 OUT PULONG ComponentId
)
180 { "DEFAULT", DPFLTR_DEFAULT_ID
},
181 { "SYSTEM", DPFLTR_SYSTEM_ID
},
182 { "SMSS", DPFLTR_SMSS_ID
},
183 { "SETUP", DPFLTR_SETUP_ID
},
184 { "NTFS", DPFLTR_NTFS_ID
},
185 { "FSTUB", DPFLTR_FSTUB_ID
},
186 { "CRASHDUMP", DPFLTR_CRASHDUMP_ID
},
187 { "CDAUDIO", DPFLTR_CDAUDIO_ID
},
188 { "CDROM", DPFLTR_CDROM_ID
},
189 { "CLASSPNP", DPFLTR_CLASSPNP_ID
},
190 { "DISK", DPFLTR_DISK_ID
},
191 { "REDBOOK", DPFLTR_REDBOOK_ID
},
192 { "STORPROP", DPFLTR_STORPROP_ID
},
193 { "SCSIPORT", DPFLTR_SCSIPORT_ID
},
194 { "SCSIMINIPORT", DPFLTR_SCSIMINIPORT_ID
},
195 { "CONFIG", DPFLTR_CONFIG_ID
},
196 { "I8042PRT", DPFLTR_I8042PRT_ID
},
197 { "SERMOUSE", DPFLTR_SERMOUSE_ID
},
198 { "LSERMOUS", DPFLTR_LSERMOUS_ID
},
199 { "KBDHID", DPFLTR_KBDHID_ID
},
200 { "MOUHID", DPFLTR_MOUHID_ID
},
201 { "KBDCLASS", DPFLTR_KBDCLASS_ID
},
202 { "MOUCLASS", DPFLTR_MOUCLASS_ID
},
203 { "TWOTRACK", DPFLTR_TWOTRACK_ID
},
204 { "WMILIB", DPFLTR_WMILIB_ID
},
205 { "ACPI", DPFLTR_ACPI_ID
},
206 { "AMLI", DPFLTR_AMLI_ID
},
207 { "HALIA64", DPFLTR_HALIA64_ID
},
208 { "VIDEO", DPFLTR_VIDEO_ID
},
209 { "SVCHOST", DPFLTR_SVCHOST_ID
},
210 { "VIDEOPRT", DPFLTR_VIDEOPRT_ID
},
211 { "TCPIP", DPFLTR_TCPIP_ID
},
212 { "DMSYNTH", DPFLTR_DMSYNTH_ID
},
213 { "NTOSPNP", DPFLTR_NTOSPNP_ID
},
214 { "FASTFAT", DPFLTR_FASTFAT_ID
},
215 { "SAMSS", DPFLTR_SAMSS_ID
},
216 { "PNPMGR", DPFLTR_PNPMGR_ID
},
217 { "NETAPI", DPFLTR_NETAPI_ID
},
218 { "SCSERVER", DPFLTR_SCSERVER_ID
},
219 { "SCCLIENT", DPFLTR_SCCLIENT_ID
},
220 { "SERIAL", DPFLTR_SERIAL_ID
},
221 { "SERENUM", DPFLTR_SERENUM_ID
},
222 { "UHCD", DPFLTR_UHCD_ID
},
223 { "RPCPROXY", DPFLTR_RPCPROXY_ID
},
224 { "AUTOCHK", DPFLTR_AUTOCHK_ID
},
225 { "DCOMSS", DPFLTR_DCOMSS_ID
},
226 { "UNIMODEM", DPFLTR_UNIMODEM_ID
},
227 { "SIS", DPFLTR_SIS_ID
},
228 { "FLTMGR", DPFLTR_FLTMGR_ID
},
229 { "WMICORE", DPFLTR_WMICORE_ID
},
230 { "BURNENG", DPFLTR_BURNENG_ID
},
231 { "IMAPI", DPFLTR_IMAPI_ID
},
232 { "SXS", DPFLTR_SXS_ID
},
233 { "FUSION", DPFLTR_FUSION_ID
},
234 { "IDLETASK", DPFLTR_IDLETASK_ID
},
235 { "SOFTPCI", DPFLTR_SOFTPCI_ID
},
236 { "TAPE", DPFLTR_TAPE_ID
},
237 { "MCHGR", DPFLTR_MCHGR_ID
},
238 { "IDEP", DPFLTR_IDEP_ID
},
239 { "PCIIDE", DPFLTR_PCIIDE_ID
},
240 { "FLOPPY", DPFLTR_FLOPPY_ID
},
241 { "FDC", DPFLTR_FDC_ID
},
242 { "TERMSRV", DPFLTR_TERMSRV_ID
},
243 { "W32TIME", DPFLTR_W32TIME_ID
},
244 { "PREFETCHER", DPFLTR_PREFETCHER_ID
},
245 { "RSFILTER", DPFLTR_RSFILTER_ID
},
246 { "FCPORT", DPFLTR_FCPORT_ID
},
247 { "PCI", DPFLTR_PCI_ID
},
248 { "DMIO", DPFLTR_DMIO_ID
},
249 { "DMCONFIG", DPFLTR_DMCONFIG_ID
},
250 { "DMADMIN", DPFLTR_DMADMIN_ID
},
251 { "WSOCKTRANSPORT", DPFLTR_WSOCKTRANSPORT_ID
},
252 { "VSS", DPFLTR_VSS_ID
},
253 { "PNPMEM", DPFLTR_PNPMEM_ID
},
254 { "PROCESSOR", DPFLTR_PROCESSOR_ID
},
255 { "DMSERVER", DPFLTR_DMSERVER_ID
},
256 { "SR", DPFLTR_SR_ID
},
257 { "INFINIBAND", DPFLTR_INFINIBAND_ID
},
258 { "IHVDRIVER", DPFLTR_IHVDRIVER_ID
},
259 { "IHVVIDEO", DPFLTR_IHVVIDEO_ID
},
260 { "IHVAUDIO", DPFLTR_IHVAUDIO_ID
},
261 { "IHVNETWORK", DPFLTR_IHVNETWORK_ID
},
262 { "IHVSTREAMING", DPFLTR_IHVSTREAMING_ID
},
263 { "IHVBUS", DPFLTR_IHVBUS_ID
},
264 { "HPS", DPFLTR_HPS_ID
},
265 { "RTLTHREADPOOL", DPFLTR_RTLTHREADPOOL_ID
},
266 { "LDR", DPFLTR_LDR_ID
},
267 { "TCPIP6", DPFLTR_TCPIP6_ID
},
268 { "ISAPNP", DPFLTR_ISAPNP_ID
},
269 { "SHPC", DPFLTR_SHPC_ID
},
270 { "STORPORT", DPFLTR_STORPORT_ID
},
271 { "STORMINIPORT", DPFLTR_STORMINIPORT_ID
},
272 { "PRINTSPOOLER", DPFLTR_PRINTSPOOLER_ID
},
273 { "VSSDYNDISK", DPFLTR_VSSDYNDISK_ID
},
274 { "VERIFIER", DPFLTR_VERIFIER_ID
},
275 { "VDS", DPFLTR_VDS_ID
},
276 { "VDSBAS", DPFLTR_VDSBAS_ID
},
277 { "VDSDYN", DPFLTR_VDSDYN_ID
},
278 { "VDSDYNDR", DPFLTR_VDSDYNDR_ID
},
279 { "VDSLDR", DPFLTR_VDSLDR_ID
},
280 { "VDSUTIL", DPFLTR_VDSUTIL_ID
},
281 { "DFRGIFC", DPFLTR_DFRGIFC_ID
},
282 { "MM", DPFLTR_MM_ID
},
283 { "DFSC", DPFLTR_DFSC_ID
},
284 { "WOW64", DPFLTR_WOW64_ID
},
285 { "ALPC", DPFLTR_ALPC_ID
},
286 { "WDI", DPFLTR_WDI_ID
},
287 { "PERFLIB", DPFLTR_PERFLIB_ID
},
288 { "KTM", DPFLTR_KTM_ID
},
289 { "IOSTRESS", DPFLTR_IOSTRESS_ID
},
290 { "HEAP", DPFLTR_HEAP_ID
},
291 { "WHEA", DPFLTR_WHEA_ID
},
292 { "USERGDI", DPFLTR_USERGDI_ID
},
293 { "MMCSS", DPFLTR_MMCSS_ID
},
294 { "TPM", DPFLTR_TPM_ID
},
295 { "THREADORDER", DPFLTR_THREADORDER_ID
},
296 { "ENVIRON", DPFLTR_ENVIRON_ID
},
297 { "EMS", DPFLTR_EMS_ID
},
298 { "WDT", DPFLTR_WDT_ID
},
299 { "FVEVOL", DPFLTR_FVEVOL_ID
},
300 { "NDIS", DPFLTR_NDIS_ID
},
301 { "NVCTRACE", DPFLTR_NVCTRACE_ID
},
302 { "LUAFV", DPFLTR_LUAFV_ID
},
303 { "APPCOMPAT", DPFLTR_APPCOMPAT_ID
},
304 { "USBSTOR", DPFLTR_USBSTOR_ID
},
305 { "SBP2PORT", DPFLTR_SBP2PORT_ID
},
306 { "COVERAGE", DPFLTR_COVERAGE_ID
},
307 { "CACHEMGR", DPFLTR_CACHEMGR_ID
},
308 { "MOUNTMGR", DPFLTR_MOUNTMGR_ID
},
309 { "CFR", DPFLTR_CFR_ID
},
310 { "TXF", DPFLTR_TXF_ID
},
311 { "KSECDD", DPFLTR_KSECDD_ID
},
312 { "FLTREGRESS", DPFLTR_FLTREGRESS_ID
},
313 { "MPIO", DPFLTR_MPIO_ID
},
314 { "MSDSM", DPFLTR_MSDSM_ID
},
315 { "UDFS", DPFLTR_UDFS_ID
},
316 { "PSHED", DPFLTR_PSHED_ID
},
317 { "STORVSP", DPFLTR_STORVSP_ID
},
318 { "LSASS", DPFLTR_LSASS_ID
},
319 { "SSPICLI", DPFLTR_SSPICLI_ID
},
320 { "CNG", DPFLTR_CNG_ID
},
321 { "EXFAT", DPFLTR_EXFAT_ID
},
322 { "FILETRACE", DPFLTR_FILETRACE_ID
},
323 { "XSAVE", DPFLTR_XSAVE_ID
},
324 { "SE", DPFLTR_SE_ID
},
325 { "DRIVEEXTENDER", DPFLTR_DRIVEEXTENDER_ID
},
328 for (i
= 0; i
< sizeof(ComponentTable
) / sizeof(ComponentTable
[0]); i
++)
330 if (_stricmp(ComponentName
, ComponentTable
[i
].Name
) == 0)
332 *ComponentId
= ComponentTable
[i
].Id
;
340 /*!\brief Evaluates an expression...
342 * Much like KdbpRpnEvaluateExpression, but prints the error message (if any)
343 * at the given offset.
345 * \param Expression Expression to evaluate.
346 * \param ErrOffset Offset (in characters) to print the error message at.
347 * \param Result Receives the result on success.
349 * \retval TRUE Success.
350 * \retval FALSE Failure.
353 KdbpEvaluateExpression(
356 OUT PULONGLONG Result
)
358 static CHAR ErrMsgBuffer
[130] = "^ ";
359 LONG ExpressionErrOffset
= -1;
360 PCHAR ErrMsg
= ErrMsgBuffer
;
363 Ok
= KdbpRpnEvaluateExpression(Expression
, KdbCurrentTrapFrame
, Result
,
364 &ExpressionErrOffset
, ErrMsgBuffer
+ 2);
367 if (ExpressionErrOffset
>= 0)
368 ExpressionErrOffset
+= ErrOffset
;
372 KdbpPrint("%*s%s\n", ExpressionErrOffset
, "", ErrMsg
);
378 /*!\brief Evaluates an expression and displays the result.
381 KdbpCmdEvalExpression(
386 ULONGLONG Result
= 0;
393 KdbpPrint("?: Argument required\n");
397 /* Put the arguments back together */
399 for (i
= 1; i
< Argc
; i
++)
401 len
= strlen(Argv
[i
]);
405 /* Evaluate the expression */
406 Ok
= KdbpEvaluateExpression(Argv
[1], sizeof("kdb:> ")-1 + (Argv
[1]-Argv
[0]), &Result
);
409 if (Result
> 0x00000000ffffffffLL
)
411 if (Result
& 0x8000000000000000LL
)
412 KdbpPrint("0x%016I64x %20I64u %20I64d\n", Result
, Result
, Result
);
414 KdbpPrint("0x%016I64x %20I64u\n", Result
, Result
);
420 if (ul
<= 0xff && ul
>= 0x80)
421 l
= (LONG
)((CHAR
)ul
);
422 else if (ul
<= 0xffff && ul
>= 0x8000)
423 l
= (LONG
)((SHORT
)ul
);
428 KdbpPrint("0x%08lx %10lu %10ld\n", ul
, ul
, l
);
430 KdbpPrint("0x%08lx %10lu\n", ul
, ul
);
437 /*!\brief Display list of active debug channels
444 ULONG i
, j
, ComponentId
, Level
;
445 ULONG set
= DPFLTR_MASK
, clear
= DPFLTR_MASK
;
456 { "error", 1 << DPFLTR_ERROR_LEVEL
},
457 { "warning", 1 << DPFLTR_WARNING_LEVEL
},
458 { "trace", 1 << DPFLTR_TRACE_LEVEL
},
459 { "info", 1 << DPFLTR_INFO_LEVEL
},
462 for (i
= 1; i
< Argc
; i
++)
465 p
= opt
+ strcspn(opt
, "+-");
466 if (!p
[0]) p
= opt
; /* assume it's a debug channel name */
470 for (j
= 0; j
< sizeof(debug_classes
) / sizeof(debug_classes
[0]); j
++)
472 SIZE_T len
= strlen(debug_classes
[j
].Name
);
473 if (len
!= (p
- opt
))
475 if (_strnicmp(opt
, debug_classes
[j
].Name
, len
) == 0) /* found it */
478 set
|= debug_classes
[j
].Level
;
480 clear
|= debug_classes
[j
].Level
;
484 if (j
== sizeof(debug_classes
) / sizeof(debug_classes
[0]))
486 Level
= strtoul(opt
, &pend
, 0);
489 KdbpPrint("filter: bad class name '%.*s'\n", p
- opt
, opt
);
505 if (*p
== '+' || *p
== '-')
508 if (!KdbpGetComponentId(p
, &ComponentId
))
510 KdbpPrint("filter: '%s' is not a valid component name!\n", p
);
514 /* Get current mask value */
515 NtSetDebugFilterState(ComponentId
, set
, TRUE
);
516 NtSetDebugFilterState(ComponentId
, clear
, FALSE
);
522 /*!\brief Disassembles 10 instructions at eip or given address or
523 * displays 16 dwords from memory at given address.
533 ULONGLONG Result
= 0;
534 ULONG_PTR Address
= KdbCurrentTrapFrame
->Tf
.Eip
;
537 if (Argv
[0][0] == 'x') /* display memory */
539 else /* disassemble */
544 /* Check for [L count] part */
546 if (strcmp(Argv
[Argc
-2], "L") == 0)
548 ul
= strtoul(Argv
[Argc
-1], NULL
, 0);
555 else if (Argv
[Argc
-1][0] == 'L')
557 ul
= strtoul(Argv
[Argc
-1] + 1, NULL
, 0);
565 /* Put the remaining arguments back together */
567 for (ul
= 1; ul
< Argc
; ul
++)
569 Argv
[ul
][strlen(Argv
[ul
])] = ' ';
574 /* Evaluate the expression */
577 if (!KdbpEvaluateExpression(Argv
[1], sizeof("kdb:> ")-1 + (Argv
[1]-Argv
[0]), &Result
))
580 if (Result
> (ULONGLONG
)(~((ULONG_PTR
)0)))
581 KdbpPrint("Warning: Address %I64x is beeing truncated\n",Result
);
583 Address
= (ULONG_PTR
)Result
;
585 else if (Argv
[0][0] == 'x')
587 KdbpPrint("x: Address argument required.\n");
591 if (Argv
[0][0] == 'x')
598 if (!KdbSymPrintAddress((PVOID
)Address
))
599 KdbpPrint("<%x>:", Address
);
608 if (!NT_SUCCESS(KdbpSafeReadMemory(&ul
, (PVOID
)Address
, sizeof(ul
))))
609 KdbpPrint(" ????????");
611 KdbpPrint(" %08x", ul
);
613 Address
+= sizeof(ul
);
624 if (!KdbSymPrintAddress((PVOID
)Address
))
625 KdbpPrint("<%08x>: ", Address
);
629 InstLen
= KdbpDisassemble(Address
, KdbUseIntelSyntax
);
632 KdbpPrint("<INVALID>\n");
644 /*!\brief Displays CPU registers.
651 PKTRAP_FRAME Tf
= &KdbCurrentTrapFrame
->Tf
;
653 static const PCHAR EflagsBits
[32] = { " CF", NULL
, " PF", " BIT3", " AF", " BIT5",
654 " ZF", " SF", " TF", " IF", " DF", " OF",
655 NULL
, NULL
, " NT", " BIT15", " RF", " VF",
656 " AC", " VIF", " VIP", " ID", " BIT22",
657 " BIT23", " BIT24", " BIT25", " BIT26",
658 " BIT27", " BIT28", " BIT29", " BIT30",
661 if (Argv
[0][0] == 'r') /* regs */
663 KdbpPrint("CS:EIP 0x%04x:0x%08x\n"
664 "SS:ESP 0x%04x:0x%08x\n"
665 " EAX 0x%08x EBX 0x%08x\n"
666 " ECX 0x%08x EDX 0x%08x\n"
667 " ESI 0x%08x EDI 0x%08x\n"
669 Tf
->SegCs
& 0xFFFF, Tf
->Eip
,
670 Tf
->HardwareSegSs
, Tf
->HardwareEsp
,
675 KdbpPrint("EFLAGS 0x%08x ", Tf
->EFlags
);
677 for (i
= 0; i
< 32; i
++)
681 if ((Tf
->EFlags
& (1 << 1)) == 0)
686 KdbpPrint(" IOPL%d", (Tf
->EFlags
>> 12) & 3);
691 else if ((Tf
->EFlags
& (1 << i
)) != 0)
693 KdbpPrint(EflagsBits
[i
]);
699 else if (Argv
[0][0] == 'c') /* cregs */
701 ULONG Cr0
, Cr2
, Cr3
, Cr4
;
702 KDESCRIPTOR Gdtr
, Idtr
;
704 static const PCHAR Cr0Bits
[32] = { " PE", " MP", " EM", " TS", " ET", " NE", NULL
, NULL
,
705 NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
,
706 " WP", NULL
, " AM", NULL
, NULL
, NULL
, NULL
, NULL
,
707 NULL
, NULL
, NULL
, NULL
, NULL
, " NW", " CD", " PG" };
708 static const PCHAR Cr4Bits
[32] = { " VME", " PVI", " TSD", " DE", " PSE", " PAE", " MCE", " PGE",
709 " PCE", " OSFXSR", " OSXMMEXCPT", NULL
, NULL
, NULL
, NULL
, NULL
,
710 NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
,
711 NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
};
713 Cr0
= KdbCurrentTrapFrame
->Cr0
;
714 Cr2
= KdbCurrentTrapFrame
->Cr2
;
715 Cr3
= KdbCurrentTrapFrame
->Cr3
;
716 Cr4
= KdbCurrentTrapFrame
->Cr4
;
718 /* Get descriptor table regs */
719 Ke386GetGlobalDescriptorTable(&Gdtr
.Limit
);
720 Ldtr
= Ke386GetLocalDescriptorTable();
723 /* Display the control registers */
724 KdbpPrint("CR0 0x%08x ", Cr0
);
726 for (i
= 0; i
< 32; i
++)
731 if ((Cr0
& (1 << i
)) != 0)
732 KdbpPrint(Cr0Bits
[i
]);
735 KdbpPrint("\nCR2 0x%08x\n", Cr2
);
736 KdbpPrint("CR3 0x%08x Pagedir-Base 0x%08x %s%s\n", Cr3
, (Cr3
& 0xfffff000),
737 (Cr3
& (1 << 3)) ? " PWT" : "", (Cr3
& (1 << 4)) ? " PCD" : "" );
738 KdbpPrint("CR4 0x%08x ", Cr4
);
740 for (i
= 0; i
< 32; i
++)
745 if ((Cr4
& (1 << i
)) != 0)
746 KdbpPrint(Cr4Bits
[i
]);
749 /* Display the descriptor table regs */
750 KdbpPrint("\nGDTR Base 0x%08x Size 0x%04x\n", Gdtr
.Base
, Gdtr
.Limit
);
751 KdbpPrint("LDTR 0x%04x\n", Ldtr
);
752 KdbpPrint("IDTR Base 0x%08x Size 0x%04x\n", Idtr
.Base
, Idtr
.Limit
);
754 else if (Argv
[0][0] == 's') /* sregs */
756 KdbpPrint("CS 0x%04x Index 0x%04x %cDT RPL%d\n",
757 Tf
->SegCs
& 0xffff, (Tf
->SegCs
& 0xffff) >> 3,
758 (Tf
->SegCs
& (1 << 2)) ? 'L' : 'G', Tf
->SegCs
& 3);
759 KdbpPrint("DS 0x%04x Index 0x%04x %cDT RPL%d\n",
760 Tf
->SegDs
, Tf
->SegDs
>> 3, (Tf
->SegDs
& (1 << 2)) ? 'L' : 'G', Tf
->SegDs
& 3);
761 KdbpPrint("ES 0x%04x Index 0x%04x %cDT RPL%d\n",
762 Tf
->SegEs
, Tf
->SegEs
>> 3, (Tf
->SegEs
& (1 << 2)) ? 'L' : 'G', Tf
->SegEs
& 3);
763 KdbpPrint("FS 0x%04x Index 0x%04x %cDT RPL%d\n",
764 Tf
->SegFs
, Tf
->SegFs
>> 3, (Tf
->SegFs
& (1 << 2)) ? 'L' : 'G', Tf
->SegFs
& 3);
765 KdbpPrint("GS 0x%04x Index 0x%04x %cDT RPL%d\n",
766 Tf
->SegGs
, Tf
->SegGs
>> 3, (Tf
->SegGs
& (1 << 2)) ? 'L' : 'G', Tf
->SegGs
& 3);
767 KdbpPrint("SS 0x%04x Index 0x%04x %cDT RPL%d\n",
768 Tf
->HardwareSegSs
, Tf
->HardwareSegSs
>> 3, (Tf
->HardwareSegSs
& (1 << 2)) ? 'L' : 'G', Tf
->HardwareSegSs
& 3);
772 ASSERT(Argv
[0][0] == 'd');
773 KdbpPrint("DR0 0x%08x\n"
779 Tf
->Dr0
, Tf
->Dr1
, Tf
->Dr2
, Tf
->Dr3
,
786 /*!\brief Displays a backtrace.
794 ULONGLONG Result
= 0;
795 ULONG_PTR Frame
= KdbCurrentTrapFrame
->Tf
.Ebp
;
800 /* Check for [L count] part */
803 if (strcmp(Argv
[Argc
-2], "L") == 0)
805 ul
= strtoul(Argv
[Argc
-1], NULL
, 0);
811 else if (Argv
[Argc
-1][0] == 'L')
813 ul
= strtoul(Argv
[Argc
-1] + 1, NULL
, 0);
820 /* Put the remaining arguments back together */
822 for (ul
= 1; ul
< Argc
; ul
++)
824 Argv
[ul
][strlen(Argv
[ul
])] = ' ';
829 /* Check if frame addr or thread id is given. */
832 if (Argv
[1][0] == '*')
836 /* Evaluate the expression */
837 if (!KdbpEvaluateExpression(Argv
[1], sizeof("kdb:> ")-1 + (Argv
[1]-Argv
[0]), &Result
))
840 if (Result
> (ULONGLONG
)(~((ULONG_PTR
)0)))
841 KdbpPrint("Warning: Address %I64x is beeing truncated\n",Result
);
843 Frame
= (ULONG_PTR
)Result
;
847 KdbpPrint("Thread backtrace not supported yet!\n");
855 /* Try printing the function at EIP */
856 if (!KdbSymPrintAddress((PVOID
)KdbCurrentTrapFrame
->Tf
.Eip
))
857 KdbpPrint("<%08x>\n", KdbCurrentTrapFrame
->Tf
.Eip
);
862 KdbpPrint("Frames:\n");
868 if (!NT_SUCCESS(KdbpSafeReadMemory(&Address
, (PVOID
)(Frame
+ sizeof(ULONG_PTR
)), sizeof (ULONG_PTR
))))
870 KdbpPrint("Couldn't access memory at 0x%p!\n", Frame
+ sizeof(ULONG_PTR
));
874 /* Print the location of the call instruction */
875 if (!KdbSymPrintAddress((PVOID
)(Address
- 5)))
876 KdbpPrint("<%08x>\n", Address
);
880 if (KdbOutputAborted
) break;
885 if (!NT_SUCCESS(KdbpSafeReadMemory(&Frame
, (PVOID
)Frame
, sizeof (ULONG_PTR
))))
887 KdbpPrint("Couldn't access memory at 0x%p!\n", Frame
);
895 /*!\brief Continues execution of the system/leaves KDB.
902 /* Exit the main loop */
906 /*!\brief Continues execution of the system/leaves KDB.
917 Count
= strtoul(Argv
[1], NULL
, 0);
920 KdbpPrint("%s: Integer argument required\n", Argv
[0]);
925 if (Argv
[0][0] == 'n')
926 KdbSingleStepOver
= TRUE
;
928 KdbSingleStepOver
= FALSE
;
930 /* Set the number of single steps and return to the interrupted code. */
931 KdbNumSingleSteps
= Count
;
936 /*!\brief Lists breakpoints.
939 KdbpCmdBreakPointList(
944 ULONG_PTR Address
= 0;
945 KDB_BREAKPOINT_TYPE Type
= 0;
946 KDB_ACCESS_TYPE AccessType
= 0;
949 BOOLEAN Enabled
= FALSE
;
950 BOOLEAN Global
= FALSE
;
951 PEPROCESS Process
= NULL
;
952 PCHAR str1
, str2
, ConditionExpr
, GlobalOrLocal
;
955 l
= KdbpGetNextBreakPointNr(0);
958 KdbpPrint("No breakpoints.\n");
962 KdbpPrint("Breakpoints:\n");
965 if (!KdbpGetBreakPointInfo(l
, &Address
, &Type
, &Size
, &AccessType
, &DebugReg
,
966 &Enabled
, &Global
, &Process
, &ConditionExpr
))
971 if (l
== KdbLastBreakPointNr
)
984 GlobalOrLocal
= " global";
988 GlobalOrLocal
= Buffer
;
989 sprintf(Buffer
, " PID 0x%08lx",
990 (ULONG
)(Process
? Process
->UniqueProcessId
: INVALID_HANDLE_VALUE
));
993 if (Type
== KdbBreakPointSoftware
|| Type
== KdbBreakPointTemporary
)
995 KdbpPrint(" %s%03d BPX 0x%08x%s%s%s%s%s\n",
997 Enabled
? "" : " disabled",
999 ConditionExpr
? " IF " : "",
1000 ConditionExpr
? ConditionExpr
: "",
1003 else if (Type
== KdbBreakPointHardware
)
1007 KdbpPrint(" %s%03d BPM 0x%08x %-5s %-5s disabled%s%s%s%s\n", str1
, l
, Address
,
1008 KDB_ACCESS_TYPE_TO_STRING(AccessType
),
1009 Size
== 1 ? "byte" : (Size
== 2 ? "word" : "dword"),
1011 ConditionExpr
? " IF " : "",
1012 ConditionExpr
? ConditionExpr
: "",
1017 KdbpPrint(" %s%03d BPM 0x%08x %-5s %-5s DR%d%s%s%s%s\n", str1
, l
, Address
,
1018 KDB_ACCESS_TYPE_TO_STRING(AccessType
),
1019 Size
== 1 ? "byte" : (Size
== 2 ? "word" : "dword"),
1022 ConditionExpr
? " IF " : "",
1023 ConditionExpr
? ConditionExpr
: "",
1028 while ((l
= KdbpGetNextBreakPointNr(l
+1)) >= 0);
1033 /*!\brief Enables, disables or clears a breakpoint.
1036 KdbpCmdEnableDisableClearBreakPoint(
1045 KdbpPrint("%s: argument required\n", Argv
[0]);
1050 BreakPointNr
= strtoul(Argv
[1], &pend
, 0);
1051 if (pend
== Argv
[1] || *pend
!= '\0')
1053 KdbpPrint("%s: integer argument required\n", Argv
[0]);
1057 if (Argv
[0][1] == 'e') /* enable */
1059 KdbpEnableBreakPoint(BreakPointNr
, NULL
);
1061 else if (Argv
[0][1] == 'd') /* disable */
1063 KdbpDisableBreakPoint(BreakPointNr
, NULL
);
1067 ASSERT(Argv
[0][1] == 'c');
1068 KdbpDeleteBreakPoint(BreakPointNr
, NULL
);
1074 /*!\brief Sets a software or hardware (memory) breakpoint at the given address.
1077 KdbpCmdBreakPoint(ULONG Argc
, PCHAR Argv
[])
1079 ULONGLONG Result
= 0;
1081 KDB_BREAKPOINT_TYPE Type
;
1083 KDB_ACCESS_TYPE AccessType
= 0;
1084 ULONG AddressArgIndex
, i
;
1085 LONG ConditionArgIndex
;
1086 BOOLEAN Global
= TRUE
;
1088 if (Argv
[0][2] == 'x') /* software breakpoint */
1092 KdbpPrint("bpx: Address argument required.\n");
1096 AddressArgIndex
= 1;
1097 Type
= KdbBreakPointSoftware
;
1099 else /* memory breakpoint */
1101 ASSERT(Argv
[0][2] == 'm');
1105 KdbpPrint("bpm: Access type argument required (one of r, w, rw, x)\n");
1109 if (_stricmp(Argv
[1], "x") == 0)
1110 AccessType
= KdbAccessExec
;
1111 else if (_stricmp(Argv
[1], "r") == 0)
1112 AccessType
= KdbAccessRead
;
1113 else if (_stricmp(Argv
[1], "w") == 0)
1114 AccessType
= KdbAccessWrite
;
1115 else if (_stricmp(Argv
[1], "rw") == 0)
1116 AccessType
= KdbAccessReadWrite
;
1119 KdbpPrint("bpm: Unknown access type '%s'\n", Argv
[1]);
1125 KdbpPrint("bpm: %s argument required.\n", AccessType
== KdbAccessExec
? "Address" : "Memory size");
1129 AddressArgIndex
= 3;
1130 if (_stricmp(Argv
[2], "byte") == 0)
1132 else if (_stricmp(Argv
[2], "word") == 0)
1134 else if (_stricmp(Argv
[2], "dword") == 0)
1136 else if (AccessType
== KdbAccessExec
)
1143 KdbpPrint("bpm: Unknown memory size '%s'\n", Argv
[2]);
1147 if (Argc
<= AddressArgIndex
)
1149 KdbpPrint("bpm: Address argument required.\n");
1153 Type
= KdbBreakPointHardware
;
1156 /* Put the arguments back together */
1157 ConditionArgIndex
= -1;
1158 for (i
= AddressArgIndex
; i
< (Argc
-1); i
++)
1160 if (strcmp(Argv
[i
+1], "IF") == 0) /* IF found */
1162 ConditionArgIndex
= i
+ 2;
1163 if (ConditionArgIndex
>= Argc
)
1165 KdbpPrint("%s: IF requires condition expression.\n", Argv
[0]);
1169 for (i
= ConditionArgIndex
; i
< (Argc
-1); i
++)
1170 Argv
[i
][strlen(Argv
[i
])] = ' ';
1175 Argv
[i
][strlen(Argv
[i
])] = ' ';
1178 /* Evaluate the address expression */
1179 if (!KdbpEvaluateExpression(Argv
[AddressArgIndex
],
1180 sizeof("kdb:> ")-1 + (Argv
[AddressArgIndex
]-Argv
[0]),
1186 if (Result
> (ULONGLONG
)(~((ULONG_PTR
)0)))
1187 KdbpPrint("%s: Warning: Address %I64x is beeing truncated\n", Argv
[0],Result
);
1189 Address
= (ULONG_PTR
)Result
;
1191 KdbpInsertBreakPoint(Address
, Type
, Size
, AccessType
,
1192 (ConditionArgIndex
< 0) ? NULL
: Argv
[ConditionArgIndex
],
1198 /*!\brief Lists threads or switches to another thread context.
1206 PETHREAD Thread
= NULL
;
1207 PEPROCESS Process
= NULL
;
1208 BOOLEAN ReferencedThread
= FALSE
, ReferencedProcess
= FALSE
;
1213 PCHAR State
, pend
, str1
, str2
;
1214 static const PCHAR ThreadStateToString
[DeferredReady
+1] =
1216 "Initialized", "Ready", "Running",
1217 "Standby", "Terminated", "Waiting",
1218 "Transition", "DeferredReady"
1221 ASSERT(KdbCurrentProcess
);
1223 if (Argc
>= 2 && _stricmp(Argv
[1], "list") == 0)
1225 Process
= KdbCurrentProcess
;
1229 ul
= strtoul(Argv
[2], &pend
, 0);
1230 if (Argv
[2] == pend
)
1232 KdbpPrint("thread: '%s' is not a valid process id!\n", Argv
[2]);
1236 if (!NT_SUCCESS(PsLookupProcessByProcessId((PVOID
)ul
, &Process
)))
1238 KdbpPrint("thread: Invalid process id!\n");
1242 /* Remember our reference */
1243 ReferencedProcess
= TRUE
;
1246 Entry
= Process
->ThreadListHead
.Flink
;
1247 if (Entry
== &Process
->ThreadListHead
)
1250 KdbpPrint("No threads in process 0x%08x!\n", ul
);
1252 KdbpPrint("No threads in current process!\n");
1254 if (ReferencedProcess
)
1255 ObDereferenceObject(Process
);
1260 KdbpPrint(" TID State Prior. Affinity EBP EIP\n");
1263 Thread
= CONTAINING_RECORD(Entry
, ETHREAD
, ThreadListEntry
);
1265 if (Thread
== KdbCurrentThread
)
1276 if (!Thread
->Tcb
.InitialStack
)
1278 /* Thread has no kernel stack (probably terminated) */
1282 else if (Thread
->Tcb
.TrapFrame
)
1284 if (Thread
->Tcb
.TrapFrame
->PreviousPreviousMode
== KernelMode
)
1285 Esp
= (PULONG
)Thread
->Tcb
.TrapFrame
->TempEsp
;
1287 Esp
= (PULONG
)Thread
->Tcb
.TrapFrame
->HardwareEsp
;
1289 Ebp
= (PULONG
)Thread
->Tcb
.TrapFrame
->Ebp
;
1290 Eip
= Thread
->Tcb
.TrapFrame
->Eip
;
1294 Esp
= (PULONG
)Thread
->Tcb
.KernelStack
;
1295 Ebp
= (PULONG
)Esp
[4];
1298 if (Ebp
) /* FIXME: Should we attach to the process to read Ebp[1]? */
1299 KdbpSafeReadMemory(&Eip
, Ebp
+ 1, sizeof (Eip
));
1302 if (Thread
->Tcb
.State
< (DeferredReady
+ 1))
1303 State
= ThreadStateToString
[Thread
->Tcb
.State
];
1307 KdbpPrint(" %s0x%08x %-11s %3d 0x%08x 0x%08x 0x%08x%s\n",
1309 Thread
->Cid
.UniqueThread
,
1311 Thread
->Tcb
.Priority
,
1312 Thread
->Tcb
.Affinity
,
1317 Entry
= Entry
->Flink
;
1319 while (Entry
!= &Process
->ThreadListHead
);
1321 /* Release our reference, if any */
1322 if (ReferencedProcess
)
1323 ObDereferenceObject(Process
);
1325 else if (Argc
>= 2 && _stricmp(Argv
[1], "attach") == 0)
1329 KdbpPrint("thread attach: thread id argument required!\n");
1333 ul
= strtoul(Argv
[2], &pend
, 0);
1334 if (Argv
[2] == pend
)
1336 KdbpPrint("thread attach: '%s' is not a valid thread id!\n", Argv
[2]);
1340 if (!KdbpAttachToThread((PVOID
)ul
))
1345 KdbpPrint("Attached to thread 0x%08x.\n", ul
);
1349 Thread
= KdbCurrentThread
;
1353 ul
= strtoul(Argv
[1], &pend
, 0);
1354 if (Argv
[1] == pend
)
1356 KdbpPrint("thread: '%s' is not a valid thread id!\n", Argv
[1]);
1360 if (!NT_SUCCESS(PsLookupThreadByThreadId((PVOID
)ul
, &Thread
)))
1362 KdbpPrint("thread: Invalid thread id!\n");
1366 /* Remember our reference */
1367 ReferencedThread
= TRUE
;
1370 if (Thread
->Tcb
.State
< (DeferredReady
+ 1))
1371 State
= ThreadStateToString
[Thread
->Tcb
.State
];
1377 " State: %s (0x%x)\n"
1379 " Affinity: 0x%08x\n"
1380 " Initial Stack: 0x%08x\n"
1381 " Stack Limit: 0x%08x\n"
1382 " Stack Base: 0x%08x\n"
1383 " Kernel Stack: 0x%08x\n"
1384 " Trap Frame: 0x%08x\n"
1385 " NPX State: %s (0x%x)\n",
1386 (Argc
< 2) ? "Current Thread:\n" : "",
1387 Thread
->Cid
.UniqueThread
,
1388 State
, Thread
->Tcb
.State
,
1389 Thread
->Tcb
.Priority
,
1390 Thread
->Tcb
.Affinity
,
1391 Thread
->Tcb
.InitialStack
,
1392 Thread
->Tcb
.StackLimit
,
1393 Thread
->Tcb
.StackBase
,
1394 Thread
->Tcb
.KernelStack
,
1395 Thread
->Tcb
.TrapFrame
,
1396 NPX_STATE_TO_STRING(Thread
->Tcb
.NpxState
), Thread
->Tcb
.NpxState
);
1398 /* Release our reference if we had one */
1399 if (ReferencedThread
)
1400 ObDereferenceObject(Thread
);
1406 /*!\brief Lists processes or switches to another process context.
1415 BOOLEAN ReferencedProcess
= FALSE
;
1416 PCHAR State
, pend
, str1
, str2
;
1418 extern LIST_ENTRY PsActiveProcessHead
;
1420 if (Argc
>= 2 && _stricmp(Argv
[1], "list") == 0)
1422 Entry
= PsActiveProcessHead
.Flink
;
1423 if (!Entry
|| Entry
== &PsActiveProcessHead
)
1425 KdbpPrint("No processes in the system!\n");
1429 KdbpPrint(" PID State Filename\n");
1432 Process
= CONTAINING_RECORD(Entry
, EPROCESS
, ActiveProcessLinks
);
1434 if (Process
== KdbCurrentProcess
)
1445 State
= ((Process
->Pcb
.State
== ProcessInMemory
) ? "In Memory" :
1446 ((Process
->Pcb
.State
== ProcessOutOfMemory
) ? "Out of Memory" : "In Transition"));
1448 KdbpPrint(" %s0x%08x %-10s %s%s\n",
1450 Process
->UniqueProcessId
,
1452 Process
->ImageFileName
,
1455 Entry
= Entry
->Flink
;
1457 while(Entry
!= &PsActiveProcessHead
);
1459 else if (Argc
>= 2 && _stricmp(Argv
[1], "attach") == 0)
1463 KdbpPrint("process attach: process id argument required!\n");
1467 ul
= strtoul(Argv
[2], &pend
, 0);
1468 if (Argv
[2] == pend
)
1470 KdbpPrint("process attach: '%s' is not a valid process id!\n", Argv
[2]);
1474 if (!KdbpAttachToProcess((PVOID
)ul
))
1479 KdbpPrint("Attached to process 0x%08x, thread 0x%08x.\n", (ULONG
)ul
,
1480 (ULONG
)KdbCurrentThread
->Cid
.UniqueThread
);
1484 Process
= KdbCurrentProcess
;
1488 ul
= strtoul(Argv
[1], &pend
, 0);
1489 if (Argv
[1] == pend
)
1491 KdbpPrint("proc: '%s' is not a valid process id!\n", Argv
[1]);
1495 if (!NT_SUCCESS(PsLookupProcessByProcessId((PVOID
)ul
, &Process
)))
1497 KdbpPrint("proc: Invalid process id!\n");
1501 /* Remember our reference */
1502 ReferencedProcess
= TRUE
;
1505 State
= ((Process
->Pcb
.State
== ProcessInMemory
) ? "In Memory" :
1506 ((Process
->Pcb
.State
== ProcessOutOfMemory
) ? "Out of Memory" : "In Transition"));
1509 " State: %s (0x%x)\n"
1510 " Image Filename: %s\n",
1511 (Argc
< 2) ? "Current process:\n" : "",
1512 Process
->UniqueProcessId
,
1513 State
, Process
->Pcb
.State
,
1514 Process
->ImageFileName
);
1516 /* Release our reference, if any */
1517 if (ReferencedProcess
)
1518 ObDereferenceObject(Process
);
1524 /*!\brief Lists loaded modules or the one containing the specified address.
1531 ULONGLONG Result
= 0;
1533 PLDR_DATA_TABLE_ENTRY LdrEntry
;
1534 BOOLEAN DisplayOnlyOneModule
= FALSE
;
1539 /* Put the arguments back together */
1542 Argv
[Argc
][strlen(Argv
[Argc
])] = ' ';
1544 /* Evaluate the expression */
1545 if (!KdbpEvaluateExpression(Argv
[1], sizeof("kdb:> ")-1 + (Argv
[1]-Argv
[0]), &Result
))
1550 if (Result
> (ULONGLONG
)(~((ULONG_PTR
)0)))
1551 KdbpPrint("%s: Warning: Address %I64x is beeing truncated\n", Argv
[0],Result
);
1553 Address
= (ULONG_PTR
)Result
;
1555 if (!KdbpSymFindModule((PVOID
)Address
, NULL
, -1, &LdrEntry
))
1557 KdbpPrint("No module containing address 0x%p found!\n", Address
);
1561 DisplayOnlyOneModule
= TRUE
;
1565 if (!KdbpSymFindModule(NULL
, NULL
, 0, &LdrEntry
))
1567 ULONG_PTR ntoskrnlBase
= ((ULONG_PTR
)KdbpCmdMod
) & 0xfff00000;
1568 KdbpPrint(" Base Size Name\n");
1569 KdbpPrint(" %08x %08x %s\n", ntoskrnlBase
, 0, "ntoskrnl.exe");
1576 KdbpPrint(" Base Size Name\n");
1579 KdbpPrint(" %08x %08x %wZ\n", LdrEntry
->DllBase
, LdrEntry
->SizeOfImage
, &LdrEntry
->BaseDllName
);
1581 if(DisplayOnlyOneModule
|| !KdbpSymFindModule(NULL
, NULL
, i
++, &LdrEntry
))
1588 /*!\brief Displays GDT, LDT or IDTd.
1605 if (Argv
[0][0] == 'i')
1612 KdbpPrint("Interrupt descriptor table is empty.\n");
1616 KdbpPrint("IDT Base: 0x%08x Limit: 0x%04x\n", Reg
.Base
, Reg
.Limit
);
1617 KdbpPrint(" Idx Type Seg. Sel. Offset DPL\n");
1619 for (i
= 0; (i
+ sizeof(SegDesc
) - 1) <= Reg
.Limit
; i
+= 8)
1621 if (!NT_SUCCESS(KdbpSafeReadMemory(SegDesc
, (PVOID
)(Reg
.Base
+ i
), sizeof(SegDesc
))))
1623 KdbpPrint("Couldn't access memory at 0x%08x!\n", Reg
.Base
+ i
);
1627 Dpl
= ((SegDesc
[1] >> 13) & 3);
1628 if ((SegDesc
[1] & 0x1f00) == 0x0500) /* Task gate */
1629 SegType
= "TASKGATE";
1630 else if ((SegDesc
[1] & 0x1fe0) == 0x0e00) /* 32 bit Interrupt gate */
1631 SegType
= "INTGATE32";
1632 else if ((SegDesc
[1] & 0x1fe0) == 0x0600) /* 16 bit Interrupt gate */
1633 SegType
= "INTGATE16";
1634 else if ((SegDesc
[1] & 0x1fe0) == 0x0f00) /* 32 bit Trap gate */
1635 SegType
= "TRAPGATE32";
1636 else if ((SegDesc
[1] & 0x1fe0) == 0x0700) /* 16 bit Trap gate */
1637 SegType
= "TRAPGATE16";
1639 SegType
= "UNKNOWN";
1641 if ((SegDesc
[1] & (1 << 15)) == 0) /* not present */
1643 KdbpPrint(" %03d %-10s [NP] [NP] %02d\n",
1644 i
/ 8, SegType
, Dpl
);
1646 else if ((SegDesc
[1] & 0x1f00) == 0x0500) /* Task gate */
1648 SegSel
= SegDesc
[0] >> 16;
1649 KdbpPrint(" %03d %-10s 0x%04x %02d\n",
1650 i
/ 8, SegType
, SegSel
, Dpl
);
1654 SegSel
= SegDesc
[0] >> 16;
1655 SegBase
= (SegDesc
[1] & 0xffff0000) | (SegDesc
[0] & 0x0000ffff);
1656 KdbpPrint(" %03d %-10s 0x%04x 0x%08x %02d\n",
1657 i
/ 8, SegType
, SegSel
, SegBase
, Dpl
);
1665 if (Argv
[0][0] == 'g')
1668 Ke386GetGlobalDescriptorTable(&Reg
.Limit
);
1673 ASSERT(Argv
[0][0] == 'l');
1676 Reg
.Limit
= Ke386GetLocalDescriptorTable();
1684 KdbpPrint("%s descriptor table is empty.\n",
1685 Argv
[0][0] == 'g' ? "Global" : "Local");
1689 KdbpPrint("%cDT Base: 0x%08x Limit: 0x%04x\n",
1690 Argv
[0][0] == 'g' ? 'G' : 'L', Reg
.Base
, Reg
.Limit
);
1691 KdbpPrint(" Idx Sel. Type Base Limit DPL Attribs\n");
1693 for (; (i
+ sizeof(SegDesc
) - 1) <= Reg
.Limit
; i
+= 8)
1695 if (!NT_SUCCESS(KdbpSafeReadMemory(SegDesc
, (PVOID
)(Reg
.Base
+ i
), sizeof(SegDesc
))))
1697 KdbpPrint("Couldn't access memory at 0x%08x!\n", Reg
.Base
+ i
);
1701 Dpl
= ((SegDesc
[1] >> 13) & 3);
1702 Type
= ((SegDesc
[1] >> 8) & 0xf);
1704 SegBase
= SegDesc
[0] >> 16;
1705 SegBase
|= (SegDesc
[1] & 0xff) << 16;
1706 SegBase
|= SegDesc
[1] & 0xff000000;
1707 SegLimit
= SegDesc
[0] & 0x0000ffff;
1708 SegLimit
|= (SegDesc
[1] >> 16) & 0xf;
1710 if ((SegDesc
[1] & (1 << 23)) != 0)
1720 if ((SegDesc
[1] & (1 << 12)) == 0) /* System segment */
1724 case 1: SegType
= "TSS16(Avl)"; break;
1725 case 2: SegType
= "LDT"; break;
1726 case 3: SegType
= "TSS16(Busy)"; break;
1727 case 4: SegType
= "CALLGATE16"; break;
1728 case 5: SegType
= "TASKGATE"; break;
1729 case 6: SegType
= "INTGATE16"; break;
1730 case 7: SegType
= "TRAPGATE16"; break;
1731 case 9: SegType
= "TSS32(Avl)"; break;
1732 case 11: SegType
= "TSS32(Busy)"; break;
1733 case 12: SegType
= "CALLGATE32"; break;
1734 case 14: SegType
= "INTGATE32"; break;
1735 case 15: SegType
= "INTGATE32"; break;
1736 default: SegType
= "UNKNOWN"; break;
1739 if (!(Type
>= 1 && Type
<= 3) &&
1740 Type
!= 9 && Type
!= 11)
1746 else if ((SegDesc
[1] & (1 << 11)) == 0) /* Data segment */
1748 if ((SegDesc
[1] & (1 << 22)) != 0)
1753 else /* Code segment */
1755 if ((SegDesc
[1] & (1 << 22)) != 0)
1761 if ((SegDesc
[1] & (1 << 15)) == 0) /* not present */
1763 KdbpPrint(" %03d 0x%04x %-11s [NP] [NP] %02d NP\n",
1764 i
/ 8, i
| Dpl
| ul
, SegType
, Dpl
);
1768 KdbpPrint(" %03d 0x%04x %-11s 0x%08x 0x%08x %02d ",
1769 i
/ 8, i
| Dpl
| ul
, SegType
, SegBase
, SegLimit
, Dpl
);
1771 if ((SegDesc
[1] & (1 << 12)) == 0) /* System segment */
1773 /* FIXME: Display system segment */
1775 else if ((SegDesc
[1] & (1 << 11)) == 0) /* Data segment */
1777 if ((SegDesc
[1] & (1 << 10)) != 0) /* Expand-down */
1780 KdbpPrint((SegDesc
[1] & (1 << 9)) ? " R/W" : " R");
1782 if ((SegDesc
[1] & (1 << 8)) != 0)
1785 else /* Code segment */
1787 if ((SegDesc
[1] & (1 << 10)) != 0) /* Conforming */
1790 KdbpPrint((SegDesc
[1] & (1 << 9)) ? " R/X" : " X");
1792 if ((SegDesc
[1] & (1 << 8)) != 0)
1796 if ((SegDesc
[1] & (1 << 20)) != 0)
1807 /*!\brief Displays the KPCR
1814 PKIPCR Pcr
= (PKIPCR
)KeGetPcr();
1816 KdbpPrint("Current PCR is at 0x%08x.\n", (INT
)Pcr
);
1817 KdbpPrint(" Tib.ExceptionList: 0x%08x\n"
1818 " Tib.StackBase: 0x%08x\n"
1819 " Tib.StackLimit: 0x%08x\n"
1820 " Tib.SubSystemTib: 0x%08x\n"
1821 " Tib.FiberData/Version: 0x%08x\n"
1822 " Tib.ArbitraryUserPointer: 0x%08x\n"
1823 " Tib.Self: 0x%08x\n"
1828 " IrrActive: 0x%08x\n"
1830 " KdVersionBlock: 0x%08x\n"
1834 " MajorVersion: 0x%04x\n"
1835 " MinorVersion: 0x%04x\n"
1836 " SetMember: 0x%08x\n"
1837 " StallScaleFactor: 0x%08x\n"
1839 " L2CacheAssociativity: 0x%02x\n"
1840 " VdmAlert: 0x%08x\n"
1841 " L2CacheSize: 0x%08x\n"
1842 " InterruptMode: 0x%08x\n",
1843 Pcr
->NtTib
.ExceptionList
, Pcr
->NtTib
.StackBase
, Pcr
->NtTib
.StackLimit
,
1844 Pcr
->NtTib
.SubSystemTib
, Pcr
->NtTib
.FiberData
, Pcr
->NtTib
.ArbitraryUserPointer
,
1845 Pcr
->NtTib
.Self
, Pcr
->Self
, Pcr
->Prcb
, Pcr
->Irql
, Pcr
->IRR
, Pcr
->IrrActive
,
1846 Pcr
->IDR
, Pcr
->KdVersionBlock
, Pcr
->IDT
, Pcr
->GDT
, Pcr
->TSS
,
1847 Pcr
->MajorVersion
, Pcr
->MinorVersion
, Pcr
->SetMember
, Pcr
->StallScaleFactor
,
1848 Pcr
->Number
, Pcr
->SecondLevelCacheAssociativity
,
1849 Pcr
->VdmAlert
, Pcr
->SecondLevelCacheSize
, Pcr
->InterruptMode
);
1854 /*!\brief Displays the TSS
1861 KTSS
*Tss
= KeGetPcr()->TSS
;
1863 KdbpPrint("Current TSS is at 0x%08x.\n", (INT
)Tss
);
1864 KdbpPrint(" Eip: 0x%08x\n"
1871 " IoMapBase: 0x%04x\n",
1872 Tss
->Eip
, Tss
->Es
, Tss
->Cs
, Tss
->Ds
, Tss
->Fs
, Tss
->Gs
, Tss
->IoMapBase
);
1877 /*!\brief Bugchecks the system.
1884 /* Set the flag and quit looping */
1885 KdbpBugCheckRequested
= TRUE
;
1890 /*!\brief Sets or displays a config variables value.
1900 KDB_ENTER_CONDITION ConditionFirst
= KdbDoNotEnter
;
1901 KDB_ENTER_CONDITION ConditionLast
= KdbDoNotEnter
;
1903 static const PCHAR ExceptionNames
[21] =
1905 "ZERODEVIDE", "DEBUGTRAP", "NMI", "INT3", "OVERFLOW", "BOUND", "INVALIDOP",
1906 "NOMATHCOP", "DOUBLEFAULT", "RESERVED(9)", "INVALIDTSS", "SEGMENTNOTPRESENT",
1907 "STACKFAULT", "GPF", "PAGEFAULT", "RESERVED(15)", "MATHFAULT", "ALIGNMENTCHECK",
1908 "MACHINECHECK", "SIMDFAULT", "OTHERS"
1913 KdbpPrint("Available settings:\n");
1914 KdbpPrint(" syntax [intel|at&t]\n");
1915 KdbpPrint(" condition [exception|*] [first|last] [never|always|kmode|umode]\n");
1916 KdbpPrint(" break_on_module_load [true|false]\n");
1918 else if (strcmp(Argv
[1], "syntax") == 0)
1922 KdbpPrint("syntax = %s\n", KdbUseIntelSyntax
? "intel" : "at&t");
1926 if (_stricmp(Argv
[2], "intel") == 0)
1927 KdbUseIntelSyntax
= TRUE
;
1928 else if (_stricmp(Argv
[2], "at&t") == 0)
1929 KdbUseIntelSyntax
= FALSE
;
1931 KdbpPrint("Unknown syntax '%s'.\n", Argv
[2]);
1934 else if (strcmp(Argv
[1], "condition") == 0)
1938 KdbpPrint("Conditions: (First) (Last)\n");
1939 for (l
= 0; l
< RTL_NUMBER_OF(ExceptionNames
) - 1; l
++)
1941 if (!ExceptionNames
[l
])
1944 if (!KdbpGetEnterCondition(l
, TRUE
, &ConditionFirst
))
1947 if (!KdbpGetEnterCondition(l
, FALSE
, &ConditionLast
))
1950 KdbpPrint(" #%02d %-20s %-8s %-8s\n", l
, ExceptionNames
[l
],
1951 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst
),
1952 KDB_ENTER_CONDITION_TO_STRING(ConditionLast
));
1955 ASSERT(l
== (RTL_NUMBER_OF(ExceptionNames
) - 1));
1956 KdbpPrint(" %-20s %-8s %-8s\n", ExceptionNames
[l
],
1957 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst
),
1958 KDB_ENTER_CONDITION_TO_STRING(ConditionLast
));
1962 if (Argc
>= 5 && strcmp(Argv
[2], "*") == 0) /* Allow * only when setting condition */
1968 l
= strtoul(Argv
[2], &pend
, 0);
1970 if (Argv
[2] == pend
)
1972 for (l
= 0; l
< RTL_NUMBER_OF(ExceptionNames
); l
++)
1974 if (!ExceptionNames
[l
])
1977 if (_stricmp(ExceptionNames
[l
], Argv
[2]) == 0)
1982 if (l
>= RTL_NUMBER_OF(ExceptionNames
))
1984 KdbpPrint("Unknown exception '%s'.\n", Argv
[2]);
1991 if (_stricmp(Argv
[3], "first") == 0)
1993 else if (_stricmp(Argv
[3], "last") == 0)
1997 KdbpPrint("set condition: second argument must be 'first' or 'last'\n");
2001 if (_stricmp(Argv
[4], "never") == 0)
2002 ConditionFirst
= KdbDoNotEnter
;
2003 else if (_stricmp(Argv
[4], "always") == 0)
2004 ConditionFirst
= KdbEnterAlways
;
2005 else if (_stricmp(Argv
[4], "umode") == 0)
2006 ConditionFirst
= KdbEnterFromUmode
;
2007 else if (_stricmp(Argv
[4], "kmode") == 0)
2008 ConditionFirst
= KdbEnterFromKmode
;
2011 KdbpPrint("set condition: third argument must be 'never', 'always', 'umode' or 'kmode'\n");
2015 if (!KdbpSetEnterCondition(l
, First
, ConditionFirst
))
2018 KdbpPrint("Couldn't change condition for exception #%02d\n", l
);
2020 KdbpPrint("Couldn't change condition for all exceptions\n", l
);
2023 else /* Argc >= 3 */
2025 if (!KdbpGetEnterCondition(l
, TRUE
, &ConditionFirst
))
2028 if (!KdbpGetEnterCondition(l
, FALSE
, &ConditionLast
))
2031 if (l
< (RTL_NUMBER_OF(ExceptionNames
) - 1))
2033 KdbpPrint("Condition for exception #%02d (%s): FirstChance %s LastChance %s\n",
2034 l
, ExceptionNames
[l
],
2035 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst
),
2036 KDB_ENTER_CONDITION_TO_STRING(ConditionLast
));
2040 KdbpPrint("Condition for all other exceptions: FirstChance %s LastChance %s\n",
2041 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst
),
2042 KDB_ENTER_CONDITION_TO_STRING(ConditionLast
));
2047 else if (strcmp(Argv
[1], "break_on_module_load") == 0)
2050 KdbpPrint("break_on_module_load = %s\n", KdbBreakOnModuleLoad
? "enabled" : "disabled");
2053 if (_stricmp(Argv
[2], "enable") == 0 || _stricmp(Argv
[2], "enabled") == 0 || _stricmp(Argv
[2], "true") == 0)
2054 KdbBreakOnModuleLoad
= TRUE
;
2055 else if (_stricmp(Argv
[2], "disable") == 0 || _stricmp(Argv
[2], "disabled") == 0 || _stricmp(Argv
[2], "false") == 0)
2056 KdbBreakOnModuleLoad
= FALSE
;
2058 KdbpPrint("Unknown setting '%s'.\n", Argv
[2]);
2063 KdbpPrint("Unknown setting '%s'.\n", Argv
[1]);
2069 /*!\brief Displays help screen.
2078 KdbpPrint("Kernel debugger commands:\n");
2079 for (i
= 0; i
< RTL_NUMBER_OF(KdbDebuggerCommands
); i
++)
2081 if (!KdbDebuggerCommands
[i
].Syntax
) /* Command group */
2086 KdbpPrint("\x1b[7m* %s:\x1b[0m\n", KdbDebuggerCommands
[i
].Help
);
2090 KdbpPrint(" %-20s - %s\n",
2091 KdbDebuggerCommands
[i
].Syntax
,
2092 KdbDebuggerCommands
[i
].Help
);
2098 /*!\brief Prints the given string with printf-like formatting.
2100 * \param Format Format of the string/arguments.
2101 * \param ... Variable number of arguments matching the format specified in \a Format.
2103 * \note Doesn't correctly handle \\t and terminal escape sequences when calculating the
2104 * number of lines required to print a single line from the Buffer in the terminal.
2111 static CHAR Buffer
[4096];
2112 static BOOLEAN TerminalInitialized
= FALSE
;
2113 static BOOLEAN TerminalConnected
= FALSE
;
2114 static BOOLEAN TerminalReportsSize
= TRUE
;
2119 LONG RowsPrintedByTerminal
;
2123 /* Check if the user has aborted output of the current command */
2124 if (KdbOutputAborted
)
2127 /* Initialize the terminal */
2128 if (!TerminalInitialized
)
2130 DbgPrint("\x1b[7h"); /* Enable linewrap */
2132 /* Query terminal type */
2133 /*DbgPrint("\x1b[Z");*/
2136 TerminalInitialized
= TRUE
;
2138 KeStallExecutionProcessor(100000);
2142 c
= KdbpTryGetCharSerial(5000);
2146 Buffer
[Length
++] = c
;
2147 if (Length
>= (sizeof (Buffer
) - 1))
2151 Buffer
[Length
] = '\0';
2153 TerminalConnected
= TRUE
;
2156 /* Get number of rows and columns in terminal */
2157 if ((KdbNumberOfRowsTerminal
< 0) || (KdbNumberOfColsTerminal
< 0) ||
2158 (KdbNumberOfRowsPrinted
) == 0) /* Refresh terminal size each time when number of rows printed is 0 */
2160 if ((KdbDebugState
& KD_DEBUG_KDSERIAL
) && TerminalConnected
&& TerminalReportsSize
)
2162 /* Try to query number of rows from terminal. A reply looks like "\x1b[8;24;80t" */
2163 TerminalReportsSize
= FALSE
;
2164 KeStallExecutionProcessor(100000);
2165 DbgPrint("\x1b[18t");
2166 c
= KdbpTryGetCharSerial(5000);
2170 c
= KdbpTryGetCharSerial(5000);
2177 c
= KdbpTryGetCharSerial(5000);
2181 Buffer
[Length
++] = c
;
2182 if (isalpha(c
) || Length
>= (sizeof (Buffer
) - 1))
2186 Buffer
[Length
] = '\0';
2187 if (Buffer
[0] == '8' && Buffer
[1] == ';')
2189 for (i
= 2; (i
< Length
) && (Buffer
[i
] != ';'); i
++);
2191 if (Buffer
[i
] == ';')
2195 /* Number of rows is now at Buffer + 2 and number of cols at Buffer + i */
2196 KdbNumberOfRowsTerminal
= strtoul(Buffer
+ 2, NULL
, 0);
2197 KdbNumberOfColsTerminal
= strtoul(Buffer
+ i
, NULL
, 0);
2198 TerminalReportsSize
= TRUE
;
2202 /* Clear further characters */
2203 while ((c
= KdbpTryGetCharSerial(5000)) != -1);
2207 if (KdbNumberOfRowsTerminal
<= 0)
2209 /* Set number of rows to the default. */
2210 KdbNumberOfRowsTerminal
= 24;
2212 else if (KdbNumberOfColsTerminal
<= 0)
2214 /* Set number of cols to the default. */
2215 KdbNumberOfColsTerminal
= 80;
2219 /* Get the string */
2220 va_start(ap
, Format
);
2221 Length
= _vsnprintf(Buffer
, sizeof (Buffer
) - 1, Format
, ap
);
2222 Buffer
[Length
] = '\0';
2226 while (p
[0] != '\0')
2228 i
= strcspn(p
, "\n");
2230 /* Calculate the number of lines which will be printed in the terminal
2231 * when outputting the current line
2234 RowsPrintedByTerminal
= (i
+ KdbNumberOfColsPrinted
- 1) / KdbNumberOfColsTerminal
;
2236 RowsPrintedByTerminal
= 0;
2239 RowsPrintedByTerminal
++;
2241 /*DbgPrint("!%d!%d!%d!%d!", KdbNumberOfRowsPrinted, KdbNumberOfColsPrinted, i, RowsPrintedByTerminal);*/
2243 /* Display a prompt if we printed one screen full of text */
2244 if (KdbNumberOfRowsTerminal
> 0 &&
2245 (LONG
)(KdbNumberOfRowsPrinted
+ RowsPrintedByTerminal
) >= KdbNumberOfRowsTerminal
)
2247 if (KdbNumberOfColsPrinted
> 0)
2250 DbgPrint("--- Press q to abort, any other key to continue ---");
2252 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
2253 c
= KdbpGetCharSerial();
2255 c
= KdbpGetCharKeyboard(&ScanCode
);
2259 /* Try to read '\n' which might follow '\r' - if \n is not received here
2260 * it will be interpreted as "return" when the next command should be read.
2262 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
2263 c
= KdbpTryGetCharSerial(5);
2265 c
= KdbpTryGetCharKeyboard(&ScanCode
, 5);
2271 KdbOutputAborted
= TRUE
;
2275 KdbNumberOfRowsPrinted
= 0;
2276 KdbNumberOfColsPrinted
= 0;
2279 /* Insert a NUL after the line and print only the current line. */
2280 if (p
[i
] == '\n' && p
[i
+ 1] != '\0')
2290 /* Remove escape sequences from the line if there's no terminal connected */
2291 if (!TerminalConnected
)
2293 while ((p2
= strrchr(p
, '\x1b'))) /* Look for escape character */
2298 while (!isalpha(p2
[j
++]));
2313 /* Set p to the start of the next line and
2314 * remember the number of rows/cols printed
2320 KdbNumberOfColsPrinted
= 0;
2324 ASSERT(p
[0] == '\0');
2325 KdbNumberOfColsPrinted
+= i
;
2328 KdbNumberOfRowsPrinted
+= RowsPrintedByTerminal
;
2332 /*!\brief Appends a command to the command history
2334 * \param Command Pointer to the command to append to the history.
2337 KdbpCommandHistoryAppend(
2340 ULONG Length1
= strlen(Command
) + 1;
2345 ASSERT(Length1
<= RTL_NUMBER_OF(KdbCommandHistoryBuffer
));
2348 (KdbCommandHistory
[KdbCommandHistoryIndex
] &&
2349 strcmp(KdbCommandHistory
[KdbCommandHistoryIndex
], Command
) == 0))
2354 /* Calculate Length1 and Length2 */
2355 Buffer
= KdbCommandHistoryBuffer
+ KdbCommandHistoryBufferIndex
;
2356 KdbCommandHistoryBufferIndex
+= Length1
;
2357 if (KdbCommandHistoryBufferIndex
>= (LONG
)RTL_NUMBER_OF(KdbCommandHistoryBuffer
))
2359 KdbCommandHistoryBufferIndex
-= RTL_NUMBER_OF(KdbCommandHistoryBuffer
);
2360 Length2
= KdbCommandHistoryBufferIndex
;
2364 /* Remove previous commands until there is enough space to append the new command */
2365 for (i
= KdbCommandHistoryIndex
; KdbCommandHistory
[i
];)
2368 (KdbCommandHistory
[i
] >= Buffer
||
2369 KdbCommandHistory
[i
] < (KdbCommandHistoryBuffer
+ KdbCommandHistoryBufferIndex
))) ||
2371 (KdbCommandHistory
[i
] >= Buffer
&&
2372 KdbCommandHistory
[i
] < (KdbCommandHistoryBuffer
+ KdbCommandHistoryBufferIndex
))))
2374 KdbCommandHistory
[i
] = NULL
;
2379 i
= RTL_NUMBER_OF(KdbCommandHistory
) - 1;
2381 if (i
== KdbCommandHistoryIndex
)
2385 /* Make sure the new command history entry is free */
2386 KdbCommandHistoryIndex
++;
2387 KdbCommandHistoryIndex
%= RTL_NUMBER_OF(KdbCommandHistory
);
2388 if (KdbCommandHistory
[KdbCommandHistoryIndex
])
2390 KdbCommandHistory
[KdbCommandHistoryIndex
] = NULL
;
2393 /* Append command */
2394 KdbCommandHistory
[KdbCommandHistoryIndex
] = Buffer
;
2395 ASSERT((KdbCommandHistory
[KdbCommandHistoryIndex
] + Length1
) <= KdbCommandHistoryBuffer
+ RTL_NUMBER_OF(KdbCommandHistoryBuffer
));
2396 memcpy(KdbCommandHistory
[KdbCommandHistoryIndex
], Command
, Length1
);
2399 memcpy(KdbCommandHistoryBuffer
, Command
+ Length1
, Length2
);
2403 /*!\brief Reads a line of user-input.
2405 * \param Buffer Buffer to store the input into. Trailing newlines are removed.
2406 * \param Size Size of \a Buffer.
2408 * \note Accepts only \n newlines, \r is ignored.
2416 PCHAR Orig
= Buffer
;
2419 static CHAR LastCommand
[1024] = "";
2420 static CHAR NextKey
= '\0';
2421 INT CmdHistIndex
= -1;
2424 EchoOn
= !((KdbDebugState
& KD_DEBUG_KDNOECHO
) != 0);
2428 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
2430 Key
= (NextKey
== '\0') ? KdbpGetCharSerial() : NextKey
;
2433 if (Key
== KEY_ESC
) /* ESC */
2435 Key
= KdbpGetCharSerial();
2438 Key
= KdbpGetCharSerial();
2443 ScanCode
= KEY_SCAN_UP
;
2446 ScanCode
= KEY_SCAN_DOWN
;
2459 Key
= (NextKey
== '\0') ? KdbpGetCharKeyboard(&ScanCode
) : NextKey
;
2463 if ((ULONG
)(Buffer
- Orig
) >= (Size
- 1))
2465 /* Buffer is full, accept only newlines */
2472 /* Read the next char - this is to throw away a \n which most clients should
2475 KeStallExecutionProcessor(100000);
2477 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
2478 NextKey
= KdbpTryGetCharSerial(5);
2480 NextKey
= KdbpTryGetCharKeyboard(&ScanCode
, 5);
2482 if (NextKey
== '\n' || NextKey
== -1) /* \n or no response at all */
2488 * Repeat the last command if the user presses enter. Reduces the
2489 * risk of RSI when single-stepping.
2493 strncpy(Buffer
, LastCommand
, Size
);
2494 Buffer
[Size
- 1] = '\0';
2499 strncpy(LastCommand
, Orig
, sizeof (LastCommand
));
2500 LastCommand
[sizeof (LastCommand
) - 1] = '\0';
2505 else if (Key
== KEY_BS
|| Key
== KEY_DEL
)
2513 KdbpPrint("%c %c", KEY_BS
, KEY_BS
);
2515 KdbpPrint(" %c", KEY_BS
);
2518 else if (ScanCode
== KEY_SCAN_UP
)
2520 BOOLEAN Print
= TRUE
;
2522 if (CmdHistIndex
< 0)
2524 CmdHistIndex
= KdbCommandHistoryIndex
;
2528 i
= CmdHistIndex
- 1;
2531 CmdHistIndex
= RTL_NUMBER_OF(KdbCommandHistory
) - 1;
2533 if (KdbCommandHistory
[i
] && i
!= KdbCommandHistoryIndex
)
2539 if (Print
&& KdbCommandHistory
[CmdHistIndex
])
2541 while (Buffer
> Orig
)
2547 KdbpPrint("%c %c", KEY_BS
, KEY_BS
);
2549 KdbpPrint(" %c", KEY_BS
);
2552 i
= min(strlen(KdbCommandHistory
[CmdHistIndex
]), Size
- 1);
2553 memcpy(Orig
, KdbCommandHistory
[CmdHistIndex
], i
);
2556 KdbpPrint("%s", Orig
);
2559 else if (ScanCode
== KEY_SCAN_DOWN
)
2561 if (CmdHistIndex
> 0 && CmdHistIndex
!= KdbCommandHistoryIndex
)
2563 i
= CmdHistIndex
+ 1;
2564 if (i
>= (INT
)RTL_NUMBER_OF(KdbCommandHistory
))
2567 if (KdbCommandHistory
[i
])
2570 while (Buffer
> Orig
)
2576 KdbpPrint("%c %c", KEY_BS
, KEY_BS
);
2578 KdbpPrint(" %c", KEY_BS
);
2581 i
= min(strlen(KdbCommandHistory
[CmdHistIndex
]), Size
- 1);
2582 memcpy(Orig
, KdbCommandHistory
[CmdHistIndex
], i
);
2585 KdbpPrint("%s", Orig
);
2592 KdbpPrint("%c", Key
);
2600 /*!\brief Parses command line and executes command if found
2602 * \param Command Command line to parse and execute if possible.
2604 * \retval TRUE Don't continue execution.
2605 * \retval FALSE Continue execution (leave KDB)
2614 static PCH Argv
[256];
2615 static CHAR OrigCommand
[1024];
2617 strncpy(OrigCommand
, Command
, sizeof(OrigCommand
) - 1);
2618 OrigCommand
[sizeof(OrigCommand
) - 1] = '\0';
2625 while (*p
== '\t' || *p
== ' ')
2631 i
= strcspn(p
, "\t ");
2644 for (i
= 0; i
< RTL_NUMBER_OF(KdbDebuggerCommands
); i
++)
2646 if (!KdbDebuggerCommands
[i
].Name
)
2649 if (strcmp(KdbDebuggerCommands
[i
].Name
, Argv
[0]) == 0)
2651 return KdbDebuggerCommands
[i
].Fn(Argc
, Argv
);
2655 KdbpPrint("Command '%s' is unknown.\n", OrigCommand
);
2659 /*!\brief KDB Main Loop.
2661 * \param EnteredOnSingleStep TRUE if KDB was entered on single step.
2665 IN BOOLEAN EnteredOnSingleStep
)
2667 static CHAR Command
[1024];
2670 if (EnteredOnSingleStep
)
2672 if (!KdbSymPrintAddress((PVOID
)KdbCurrentTrapFrame
->Tf
.Eip
))
2674 KdbpPrint("<%x>", KdbCurrentTrapFrame
->Tf
.Eip
);
2678 if (KdbpDisassemble(KdbCurrentTrapFrame
->Tf
.Eip
, KdbUseIntelSyntax
) < 0)
2680 KdbpPrint("<INVALID>");
2685 /* Flush the input buffer */
2686 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
2688 while (KdbpTryGetCharSerial(1) != -1);
2693 while (KdbpTryGetCharKeyboard(&ScanCode
, 1) != -1);
2699 /* Print the prompt */
2700 KdbpPrint("kdb:> ");
2702 /* Read a command and remember it */
2703 KdbpReadCommand(Command
, sizeof (Command
));
2704 KdbpCommandHistoryAppend(Command
);
2706 /* Reset the number of rows/cols printed and output aborted state */
2707 KdbNumberOfRowsPrinted
= KdbNumberOfColsPrinted
= 0;
2708 KdbOutputAborted
= FALSE
;
2710 /* Call the command */
2711 Continue
= KdbpDoCommand(Command
);
2712 KdbOutputAborted
= FALSE
;
2717 /*!\brief Called when a module is loaded.
2719 * \param Name Filename of the module which was loaded.
2722 KdbpCliModuleLoaded(
2723 IN PUNICODE_STRING Name
)
2725 if (!KdbBreakOnModuleLoad
)
2728 KdbpPrint("Module %wZ loaded.\n", Name
);
2729 DbgBreakPointWithStatus(DBG_STATUS_CONTROL_C
);
2732 /*!\brief This function is called by KdbEnterDebuggerException...
2734 * Used to interpret the init file in a context with a trapframe setup
2735 * (KdbpCliInit call KdbEnter which will call KdbEnterDebuggerException which will
2736 * call this function if KdbInitFileBuffer is not NULL.
2739 KdbpCliInterpretInitFile()
2745 /* Execute the commands in the init file */
2746 DPRINT("KDB: Executing KDBinit file...\n");
2747 p1
= KdbInitFileBuffer
;
2748 while (p1
[0] != '\0')
2750 i
= strcspn(p1
, "\r\n");
2756 /* Look for "break" command and comments */
2759 while (isspace(p2
[0]))
2762 if (strncmp(p2
, "break", sizeof("break")-1) == 0 &&
2763 (p2
[sizeof("break")-1] == '\0' || isspace(p2
[sizeof("break")-1])))
2765 /* break into the debugger */
2766 KdbpCliMainLoop(FALSE
);
2768 else if (p2
[0] != '#' && p2
[0] != '\0') /* Ignore empty lines and comments */
2777 while (p1
[0] == '\r' || p1
[0] == '\n')
2780 DPRINT("KDB: KDBinit executed\n");
2783 /*!\brief Called when KDB is initialized
2785 * Reads the KDBinit file from the SystemRoot\system32\drivers\etc directory and executes it.
2791 OBJECT_ATTRIBUTES ObjectAttributes
;
2792 UNICODE_STRING FileName
;
2793 IO_STATUS_BLOCK Iosb
;
2794 FILE_STANDARD_INFORMATION FileStdInfo
;
2795 HANDLE hFile
= NULL
;
2800 /* Initialize the object attributes */
2801 RtlInitUnicodeString(&FileName
, L
"\\SystemRoot\\system32\\drivers\\etc\\KDBinit");
2802 InitializeObjectAttributes(&ObjectAttributes
, &FileName
, 0, NULL
, NULL
);
2805 Status
= ZwOpenFile(&hFile
, FILE_READ_DATA
, &ObjectAttributes
, &Iosb
, 0,
2806 FILE_NON_DIRECTORY_FILE
| FILE_SYNCHRONOUS_IO_NONALERT
|
2807 FILE_NO_INTERMEDIATE_BUFFERING
);
2808 if (!NT_SUCCESS(Status
))
2810 DPRINT("Could not open \\SystemRoot\\system32\\drivers\\etc\\KDBinit (Status 0x%x)", Status
);
2814 /* Get the size of the file */
2815 Status
= ZwQueryInformationFile(hFile
, &Iosb
, &FileStdInfo
, sizeof (FileStdInfo
),
2816 FileStandardInformation
);
2817 if (!NT_SUCCESS(Status
))
2820 DPRINT("Could not query size of \\SystemRoot\\system32\\drivers\\etc\\KDBinit (Status 0x%x)", Status
);
2823 FileSize
= FileStdInfo
.EndOfFile
.u
.LowPart
;
2825 /* Allocate memory for the file */
2826 FileBuffer
= ExAllocatePool(PagedPool
, FileSize
+ 1); /* add 1 byte for terminating '\0' */
2830 DPRINT("Could not allocate %d bytes for KDBinit file\n", FileSize
);
2834 /* Load file into memory */
2835 Status
= ZwReadFile(hFile
, 0, 0, 0, &Iosb
, FileBuffer
, FileSize
, 0, 0);
2838 if (!NT_SUCCESS(Status
) && Status
!= STATUS_END_OF_FILE
)
2840 ExFreePool(FileBuffer
);
2841 DPRINT("Could not read KDBinit file into memory (Status 0x%lx)\n", Status
);
2845 FileSize
= min(FileSize
, (INT
)Iosb
.Information
);
2846 FileBuffer
[FileSize
] = '\0';
2848 /* Enter critical section */
2849 OldEflags
= __readeflags();
2852 /* Interpret the init file... */
2853 KdbInitFileBuffer
= FileBuffer
;
2855 KdbInitFileBuffer
= NULL
;
2857 /* Leave critical section */
2858 __writeeflags(OldEflags
);
2860 ExFreePool(FileBuffer
);
2865 KdpSerialDebugPrint(
2870 STRING KdpPromptString
= RTL_CONSTANT_STRING("kdb:> ");
2871 extern KSPIN_LOCK KdpSerialSpinLock
;
2875 KdpPrompt(IN LPSTR InString
,
2876 IN USHORT InStringLength
,
2877 OUT LPSTR OutString
,
2878 IN USHORT OutStringLength
)
2882 ULONG DummyScanCode
;
2885 /* Acquire the printing spinlock without waiting at raised IRQL */
2888 /* Wait when the spinlock becomes available */
2889 while (!KeTestSpinLock(&KdpSerialSpinLock
));
2891 /* Spinlock was free, raise IRQL */
2892 KeRaiseIrql(HIGH_LEVEL
, &OldIrql
);
2894 /* Try to get the spinlock */
2895 if (KeTryToAcquireSpinLockAtDpcLevel(&KdpSerialSpinLock
))
2898 /* Someone else got the spinlock, lower IRQL back */
2899 KeLowerIrql(OldIrql
);
2902 /* Loop the string to send */
2903 for (i
= 0; i
< InStringLength
; i
++)
2905 /* Print it to serial */
2906 KdPortPutByteEx(&SerialPortInfo
, *(PCHAR
)(InString
+ i
));
2909 /* Print a new line for log neatness */
2910 KdPortPutByteEx(&SerialPortInfo
, '\r');
2911 KdPortPutByteEx(&SerialPortInfo
, '\n');
2913 /* Print the kdb prompt */
2914 for (i
= 0; i
< KdpPromptString
.Length
; i
++)
2916 /* Print it to serial */
2917 KdPortPutByteEx(&SerialPortInfo
,
2918 *(KdpPromptString
.Buffer
+ i
));
2921 /* Loop the whole string */
2922 for (i
= 0; i
< OutStringLength
; i
++)
2924 /* Check if this is serial debugging mode */
2925 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
2927 /* Get the character from serial */
2930 Response
= KdbpTryGetCharSerial(MAXULONG
);
2931 } while (Response
== -1);
2935 /* Get the response from the keyboard */
2938 Response
= KdbpTryGetCharKeyboard(&DummyScanCode
, MAXULONG
);
2939 } while (Response
== -1);
2942 /* Check for return */
2943 if (Response
== '\r')
2946 * We might need to discard the next '\n'.
2947 * Wait a bit to make sure we receive it.
2949 KeStallExecutionProcessor(100000);
2951 /* Check the mode */
2952 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
2954 /* Read and discard the next character, if any */
2955 KdbpTryGetCharSerial(5);
2959 /* Read and discard the next character, if any */
2960 KdbpTryGetCharKeyboard(&DummyScanCode
, 5);
2964 * Null terminate the output string -- documentation states that
2965 * DbgPrompt does not null terminate, but it does
2967 *(PCHAR
)(OutString
+ i
) = 0;
2969 /* Print a new line */
2970 KdPortPutByteEx(&SerialPortInfo
, '\r');
2971 KdPortPutByteEx(&SerialPortInfo
, '\n');
2973 /* Release spinlock */
2974 KiReleaseSpinLock(&KdpSerialSpinLock
);
2976 /* Lower IRQL back */
2977 KeLowerIrql(OldIrql
);
2979 /* Return the length */
2980 return OutStringLength
+ 1;
2983 /* Write it back and print it to the log */
2984 *(PCHAR
)(OutString
+ i
) = Response
;
2985 KdPortPutByteEx(&SerialPortInfo
, Response
);
2988 /* Print a new line */
2989 KdPortPutByteEx(&SerialPortInfo
, '\r');
2990 KdPortPutByteEx(&SerialPortInfo
, '\n');
2992 /* Release spinlock */
2993 KiReleaseSpinLock(&KdpSerialSpinLock
);
2995 /* Lower IRQL back */
2996 KeLowerIrql(OldIrql
);
2998 /* Return the length */
2999 return OutStringLength
;