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
[]);
93 /* GLOBALS *******************************************************************/
95 static BOOLEAN KdbUseIntelSyntax
= FALSE
; /* Set to TRUE for intel syntax */
96 static BOOLEAN KdbBreakOnModuleLoad
= FALSE
; /* Set to TRUE to break into KDB when a module is loaded */
98 static CHAR KdbCommandHistoryBuffer
[2048]; /* Command history string ringbuffer */
99 static PCHAR KdbCommandHistory
[sizeof(KdbCommandHistoryBuffer
) / 8] = { NULL
}; /* Command history ringbuffer */
100 static LONG KdbCommandHistoryBufferIndex
= 0;
101 static LONG KdbCommandHistoryIndex
= 0;
103 static ULONG KdbNumberOfRowsPrinted
= 0;
104 static ULONG KdbNumberOfColsPrinted
= 0;
105 static BOOLEAN KdbOutputAborted
= FALSE
;
106 static LONG KdbNumberOfRowsTerminal
= -1;
107 static LONG KdbNumberOfColsTerminal
= -1;
109 PCHAR KdbInitFileBuffer
= NULL
; /* Buffer where KDBinit file is loaded into during initialization */
110 BOOLEAN KdbpBugCheckRequested
= FALSE
;
113 /* defined in ../kd/kdio.c, declare here: */
114 extern volatile BOOLEAN KdbpIsInDmesgMode
;
115 extern const ULONG KdpDmesgBufferSize
;
116 extern PCHAR KdpDmesgBuffer
;
117 extern volatile ULONG KdpDmesgCurrentPosition
;
118 extern volatile ULONG KdpDmesgFreeBytes
;
119 extern volatile ULONG KdbDmesgTotalWritten
;
126 BOOLEAN (*Fn
)(ULONG Argc
, PCHAR Argv
[]);
127 } KdbDebuggerCommands
[] = {
129 { NULL
, NULL
, "Data", NULL
},
130 { "?", "? expression", "Evaluate expression.", KdbpCmdEvalExpression
},
131 { "disasm", "disasm [address] [L count]", "Disassemble count instructions at address.", KdbpCmdDisassembleX
},
132 { "x", "x [address] [L count]", "Display count dwords, starting at addr.", KdbpCmdDisassembleX
},
133 { "regs", "regs", "Display general purpose registers.", KdbpCmdRegs
},
134 { "cregs", "cregs", "Display control registers.", KdbpCmdRegs
},
135 { "sregs", "sregs", "Display status registers.", KdbpCmdRegs
},
136 { "dregs", "dregs", "Display debug registers.", KdbpCmdRegs
},
137 { "bt", "bt [*frameaddr|thread id]", "Prints current backtrace or from given frame addr", KdbpCmdBackTrace
},
140 { NULL
, NULL
, "Flow control", NULL
},
141 { "cont", "cont", "Continue execution (leave debugger)", KdbpCmdContinue
},
142 { "step", "step [count]", "Execute single instructions, stepping into interrupts.", KdbpCmdStep
},
143 { "next", "next [count]", "Execute single instructions, skipping calls and reps.", KdbpCmdStep
},
144 { "bl", "bl", "List breakpoints.", KdbpCmdBreakPointList
},
145 { "be", "be [breakpoint]", "Enable breakpoint.", KdbpCmdEnableDisableClearBreakPoint
},
146 { "bd", "bd [breakpoint]", "Disable breakpoint.", KdbpCmdEnableDisableClearBreakPoint
},
147 { "bc", "bc [breakpoint]", "Clear breakpoint.", KdbpCmdEnableDisableClearBreakPoint
},
148 { "bpx", "bpx [address] [IF condition]", "Set software execution breakpoint at address.", KdbpCmdBreakPoint
},
149 { "bpm", "bpm [r|w|rw|x] [byte|word|dword] [address] [IF condition]", "Set memory breakpoint at address.", KdbpCmdBreakPoint
},
152 { NULL
, NULL
, "Process/Thread", NULL
},
153 { "thread", "thread [list[ pid]|[attach ]tid]", "List threads in current or specified process, display thread with given id or attach to thread.", KdbpCmdThread
},
154 { "proc", "proc [list|[attach ]pid]", "List processes, display process with given id or attach to process.", KdbpCmdProc
},
156 /* System information */
157 { NULL
, NULL
, "System info", NULL
},
158 { "mod", "mod [address]", "List all modules or the one containing address.", KdbpCmdMod
},
159 { "gdt", "gdt", "Display global descriptor table.", KdbpCmdGdtLdtIdt
},
160 { "ldt", "ldt", "Display local descriptor table.", KdbpCmdGdtLdtIdt
},
161 { "idt", "idt", "Display interrupt descriptor table.", KdbpCmdGdtLdtIdt
},
162 { "pcr", "pcr", "Display processor control region.", KdbpCmdPcr
},
163 { "tss", "tss", "Display task state segment.", KdbpCmdTss
},
166 { NULL
, NULL
, "Others", NULL
},
167 { "bugcheck", "bugcheck", "Bugchecks the system.", KdbpCmdBugCheck
},
168 { "filter", "filter [error|warning|trace|info|level]+|-[componentname|default]", "Enable/disable debug channels", KdbpCmdFilter
},
169 { "set", "set [var] [value]", "Sets var to value or displays value of var.", KdbpCmdSet
},
170 { "dmesg", "dmesg", "Display debug messages on screen, with navigation on pages.", KdbpCmdDmesg
},
171 { "kmsg", "kmsg", "Kernel dmesg. Alias for dmesg.", KdbpCmdDmesg
},
172 { "help", "help", "Display help screen.", KdbpCmdHelp
}
175 /* FUNCTIONS *****************************************************************/
177 /*!\brief Transform a component name to an integer
179 * \param ComponentName The name of the component.
180 * \param ComponentId Receives the component id on success.
182 * \retval TRUE Success.
183 * \retval FALSE Failure.
187 IN PCCH ComponentName
,
188 OUT PULONG ComponentId
)
199 { "DEFAULT", DPFLTR_DEFAULT_ID
},
200 { "SYSTEM", DPFLTR_SYSTEM_ID
},
201 { "SMSS", DPFLTR_SMSS_ID
},
202 { "SETUP", DPFLTR_SETUP_ID
},
203 { "NTFS", DPFLTR_NTFS_ID
},
204 { "FSTUB", DPFLTR_FSTUB_ID
},
205 { "CRASHDUMP", DPFLTR_CRASHDUMP_ID
},
206 { "CDAUDIO", DPFLTR_CDAUDIO_ID
},
207 { "CDROM", DPFLTR_CDROM_ID
},
208 { "CLASSPNP", DPFLTR_CLASSPNP_ID
},
209 { "DISK", DPFLTR_DISK_ID
},
210 { "REDBOOK", DPFLTR_REDBOOK_ID
},
211 { "STORPROP", DPFLTR_STORPROP_ID
},
212 { "SCSIPORT", DPFLTR_SCSIPORT_ID
},
213 { "SCSIMINIPORT", DPFLTR_SCSIMINIPORT_ID
},
214 { "CONFIG", DPFLTR_CONFIG_ID
},
215 { "I8042PRT", DPFLTR_I8042PRT_ID
},
216 { "SERMOUSE", DPFLTR_SERMOUSE_ID
},
217 { "LSERMOUS", DPFLTR_LSERMOUS_ID
},
218 { "KBDHID", DPFLTR_KBDHID_ID
},
219 { "MOUHID", DPFLTR_MOUHID_ID
},
220 { "KBDCLASS", DPFLTR_KBDCLASS_ID
},
221 { "MOUCLASS", DPFLTR_MOUCLASS_ID
},
222 { "TWOTRACK", DPFLTR_TWOTRACK_ID
},
223 { "WMILIB", DPFLTR_WMILIB_ID
},
224 { "ACPI", DPFLTR_ACPI_ID
},
225 { "AMLI", DPFLTR_AMLI_ID
},
226 { "HALIA64", DPFLTR_HALIA64_ID
},
227 { "VIDEO", DPFLTR_VIDEO_ID
},
228 { "SVCHOST", DPFLTR_SVCHOST_ID
},
229 { "VIDEOPRT", DPFLTR_VIDEOPRT_ID
},
230 { "TCPIP", DPFLTR_TCPIP_ID
},
231 { "DMSYNTH", DPFLTR_DMSYNTH_ID
},
232 { "NTOSPNP", DPFLTR_NTOSPNP_ID
},
233 { "FASTFAT", DPFLTR_FASTFAT_ID
},
234 { "SAMSS", DPFLTR_SAMSS_ID
},
235 { "PNPMGR", DPFLTR_PNPMGR_ID
},
236 { "NETAPI", DPFLTR_NETAPI_ID
},
237 { "SCSERVER", DPFLTR_SCSERVER_ID
},
238 { "SCCLIENT", DPFLTR_SCCLIENT_ID
},
239 { "SERIAL", DPFLTR_SERIAL_ID
},
240 { "SERENUM", DPFLTR_SERENUM_ID
},
241 { "UHCD", DPFLTR_UHCD_ID
},
242 { "RPCPROXY", DPFLTR_RPCPROXY_ID
},
243 { "AUTOCHK", DPFLTR_AUTOCHK_ID
},
244 { "DCOMSS", DPFLTR_DCOMSS_ID
},
245 { "UNIMODEM", DPFLTR_UNIMODEM_ID
},
246 { "SIS", DPFLTR_SIS_ID
},
247 { "FLTMGR", DPFLTR_FLTMGR_ID
},
248 { "WMICORE", DPFLTR_WMICORE_ID
},
249 { "BURNENG", DPFLTR_BURNENG_ID
},
250 { "IMAPI", DPFLTR_IMAPI_ID
},
251 { "SXS", DPFLTR_SXS_ID
},
252 { "FUSION", DPFLTR_FUSION_ID
},
253 { "IDLETASK", DPFLTR_IDLETASK_ID
},
254 { "SOFTPCI", DPFLTR_SOFTPCI_ID
},
255 { "TAPE", DPFLTR_TAPE_ID
},
256 { "MCHGR", DPFLTR_MCHGR_ID
},
257 { "IDEP", DPFLTR_IDEP_ID
},
258 { "PCIIDE", DPFLTR_PCIIDE_ID
},
259 { "FLOPPY", DPFLTR_FLOPPY_ID
},
260 { "FDC", DPFLTR_FDC_ID
},
261 { "TERMSRV", DPFLTR_TERMSRV_ID
},
262 { "W32TIME", DPFLTR_W32TIME_ID
},
263 { "PREFETCHER", DPFLTR_PREFETCHER_ID
},
264 { "RSFILTER", DPFLTR_RSFILTER_ID
},
265 { "FCPORT", DPFLTR_FCPORT_ID
},
266 { "PCI", DPFLTR_PCI_ID
},
267 { "DMIO", DPFLTR_DMIO_ID
},
268 { "DMCONFIG", DPFLTR_DMCONFIG_ID
},
269 { "DMADMIN", DPFLTR_DMADMIN_ID
},
270 { "WSOCKTRANSPORT", DPFLTR_WSOCKTRANSPORT_ID
},
271 { "VSS", DPFLTR_VSS_ID
},
272 { "PNPMEM", DPFLTR_PNPMEM_ID
},
273 { "PROCESSOR", DPFLTR_PROCESSOR_ID
},
274 { "DMSERVER", DPFLTR_DMSERVER_ID
},
275 { "SR", DPFLTR_SR_ID
},
276 { "INFINIBAND", DPFLTR_INFINIBAND_ID
},
277 { "IHVDRIVER", DPFLTR_IHVDRIVER_ID
},
278 { "IHVVIDEO", DPFLTR_IHVVIDEO_ID
},
279 { "IHVAUDIO", DPFLTR_IHVAUDIO_ID
},
280 { "IHVNETWORK", DPFLTR_IHVNETWORK_ID
},
281 { "IHVSTREAMING", DPFLTR_IHVSTREAMING_ID
},
282 { "IHVBUS", DPFLTR_IHVBUS_ID
},
283 { "HPS", DPFLTR_HPS_ID
},
284 { "RTLTHREADPOOL", DPFLTR_RTLTHREADPOOL_ID
},
285 { "LDR", DPFLTR_LDR_ID
},
286 { "TCPIP6", DPFLTR_TCPIP6_ID
},
287 { "ISAPNP", DPFLTR_ISAPNP_ID
},
288 { "SHPC", DPFLTR_SHPC_ID
},
289 { "STORPORT", DPFLTR_STORPORT_ID
},
290 { "STORMINIPORT", DPFLTR_STORMINIPORT_ID
},
291 { "PRINTSPOOLER", DPFLTR_PRINTSPOOLER_ID
},
292 { "VSSDYNDISK", DPFLTR_VSSDYNDISK_ID
},
293 { "VERIFIER", DPFLTR_VERIFIER_ID
},
294 { "VDS", DPFLTR_VDS_ID
},
295 { "VDSBAS", DPFLTR_VDSBAS_ID
},
296 { "VDSDYN", DPFLTR_VDSDYN_ID
},
297 { "VDSDYNDR", DPFLTR_VDSDYNDR_ID
},
298 { "VDSLDR", DPFLTR_VDSLDR_ID
},
299 { "VDSUTIL", DPFLTR_VDSUTIL_ID
},
300 { "DFRGIFC", DPFLTR_DFRGIFC_ID
},
301 { "MM", DPFLTR_MM_ID
},
302 { "DFSC", DPFLTR_DFSC_ID
},
303 { "WOW64", DPFLTR_WOW64_ID
},
304 { "ALPC", DPFLTR_ALPC_ID
},
305 { "WDI", DPFLTR_WDI_ID
},
306 { "PERFLIB", DPFLTR_PERFLIB_ID
},
307 { "KTM", DPFLTR_KTM_ID
},
308 { "IOSTRESS", DPFLTR_IOSTRESS_ID
},
309 { "HEAP", DPFLTR_HEAP_ID
},
310 { "WHEA", DPFLTR_WHEA_ID
},
311 { "USERGDI", DPFLTR_USERGDI_ID
},
312 { "MMCSS", DPFLTR_MMCSS_ID
},
313 { "TPM", DPFLTR_TPM_ID
},
314 { "THREADORDER", DPFLTR_THREADORDER_ID
},
315 { "ENVIRON", DPFLTR_ENVIRON_ID
},
316 { "EMS", DPFLTR_EMS_ID
},
317 { "WDT", DPFLTR_WDT_ID
},
318 { "FVEVOL", DPFLTR_FVEVOL_ID
},
319 { "NDIS", DPFLTR_NDIS_ID
},
320 { "NVCTRACE", DPFLTR_NVCTRACE_ID
},
321 { "LUAFV", DPFLTR_LUAFV_ID
},
322 { "APPCOMPAT", DPFLTR_APPCOMPAT_ID
},
323 { "USBSTOR", DPFLTR_USBSTOR_ID
},
324 { "SBP2PORT", DPFLTR_SBP2PORT_ID
},
325 { "COVERAGE", DPFLTR_COVERAGE_ID
},
326 { "CACHEMGR", DPFLTR_CACHEMGR_ID
},
327 { "MOUNTMGR", DPFLTR_MOUNTMGR_ID
},
328 { "CFR", DPFLTR_CFR_ID
},
329 { "TXF", DPFLTR_TXF_ID
},
330 { "KSECDD", DPFLTR_KSECDD_ID
},
331 { "FLTREGRESS", DPFLTR_FLTREGRESS_ID
},
332 { "MPIO", DPFLTR_MPIO_ID
},
333 { "MSDSM", DPFLTR_MSDSM_ID
},
334 { "UDFS", DPFLTR_UDFS_ID
},
335 { "PSHED", DPFLTR_PSHED_ID
},
336 { "STORVSP", DPFLTR_STORVSP_ID
},
337 { "LSASS", DPFLTR_LSASS_ID
},
338 { "SSPICLI", DPFLTR_SSPICLI_ID
},
339 { "CNG", DPFLTR_CNG_ID
},
340 { "EXFAT", DPFLTR_EXFAT_ID
},
341 { "FILETRACE", DPFLTR_FILETRACE_ID
},
342 { "XSAVE", DPFLTR_XSAVE_ID
},
343 { "SE", DPFLTR_SE_ID
},
344 { "DRIVEEXTENDER", DPFLTR_DRIVEEXTENDER_ID
},
347 for (i
= 0; i
< sizeof(ComponentTable
) / sizeof(ComponentTable
[0]); i
++)
349 if (_stricmp(ComponentName
, ComponentTable
[i
].Name
) == 0)
351 *ComponentId
= ComponentTable
[i
].Id
;
359 /*!\brief Evaluates an expression...
361 * Much like KdbpRpnEvaluateExpression, but prints the error message (if any)
362 * at the given offset.
364 * \param Expression Expression to evaluate.
365 * \param ErrOffset Offset (in characters) to print the error message at.
366 * \param Result Receives the result on success.
368 * \retval TRUE Success.
369 * \retval FALSE Failure.
372 KdbpEvaluateExpression(
375 OUT PULONGLONG Result
)
377 static CHAR ErrMsgBuffer
[130] = "^ ";
378 LONG ExpressionErrOffset
= -1;
379 PCHAR ErrMsg
= ErrMsgBuffer
;
382 Ok
= KdbpRpnEvaluateExpression(Expression
, KdbCurrentTrapFrame
, Result
,
383 &ExpressionErrOffset
, ErrMsgBuffer
+ 2);
386 if (ExpressionErrOffset
>= 0)
387 ExpressionErrOffset
+= ErrOffset
;
391 KdbpPrint("%*s%s\n", ExpressionErrOffset
, "", ErrMsg
);
397 /*!\brief Evaluates an expression and displays the result.
400 KdbpCmdEvalExpression(
405 ULONGLONG Result
= 0;
412 KdbpPrint("?: Argument required\n");
416 /* Put the arguments back together */
418 for (i
= 1; i
< Argc
; i
++)
420 len
= strlen(Argv
[i
]);
424 /* Evaluate the expression */
425 Ok
= KdbpEvaluateExpression(Argv
[1], sizeof("kdb:> ")-1 + (Argv
[1]-Argv
[0]), &Result
);
428 if (Result
> 0x00000000ffffffffLL
)
430 if (Result
& 0x8000000000000000LL
)
431 KdbpPrint("0x%016I64x %20I64u %20I64d\n", Result
, Result
, Result
);
433 KdbpPrint("0x%016I64x %20I64u\n", Result
, Result
);
439 if (ul
<= 0xff && ul
>= 0x80)
440 l
= (LONG
)((CHAR
)ul
);
441 else if (ul
<= 0xffff && ul
>= 0x8000)
442 l
= (LONG
)((SHORT
)ul
);
447 KdbpPrint("0x%08lx %10lu %10ld\n", ul
, ul
, l
);
449 KdbpPrint("0x%08lx %10lu\n", ul
, ul
);
456 /*!\brief Display list of active debug channels
463 ULONG i
, j
, ComponentId
, Level
;
464 ULONG set
= DPFLTR_MASK
, clear
= DPFLTR_MASK
;
475 { "error", 1 << DPFLTR_ERROR_LEVEL
},
476 { "warning", 1 << DPFLTR_WARNING_LEVEL
},
477 { "trace", 1 << DPFLTR_TRACE_LEVEL
},
478 { "info", 1 << DPFLTR_INFO_LEVEL
},
481 for (i
= 1; i
< Argc
; i
++)
484 p
= opt
+ strcspn(opt
, "+-");
485 if (!p
[0]) p
= opt
; /* assume it's a debug channel name */
489 for (j
= 0; j
< sizeof(debug_classes
) / sizeof(debug_classes
[0]); j
++)
491 SIZE_T len
= strlen(debug_classes
[j
].Name
);
492 if (len
!= (p
- opt
))
494 if (_strnicmp(opt
, debug_classes
[j
].Name
, len
) == 0) /* found it */
497 set
|= debug_classes
[j
].Level
;
499 clear
|= debug_classes
[j
].Level
;
503 if (j
== sizeof(debug_classes
) / sizeof(debug_classes
[0]))
505 Level
= strtoul(opt
, &pend
, 0);
508 KdbpPrint("filter: bad class name '%.*s'\n", p
- opt
, opt
);
524 if (*p
== '+' || *p
== '-')
527 if (!KdbpGetComponentId(p
, &ComponentId
))
529 KdbpPrint("filter: '%s' is not a valid component name!\n", p
);
533 /* Get current mask value */
534 NtSetDebugFilterState(ComponentId
, set
, TRUE
);
535 NtSetDebugFilterState(ComponentId
, clear
, FALSE
);
541 /*!\brief Disassembles 10 instructions at eip or given address or
542 * displays 16 dwords from memory at given address.
552 ULONGLONG Result
= 0;
553 ULONG_PTR Address
= KdbCurrentTrapFrame
->Tf
.Eip
;
556 if (Argv
[0][0] == 'x') /* display memory */
558 else /* disassemble */
563 /* Check for [L count] part */
565 if (strcmp(Argv
[Argc
-2], "L") == 0)
567 ul
= strtoul(Argv
[Argc
-1], NULL
, 0);
574 else if (Argv
[Argc
-1][0] == 'L')
576 ul
= strtoul(Argv
[Argc
-1] + 1, NULL
, 0);
584 /* Put the remaining arguments back together */
586 for (ul
= 1; ul
< Argc
; ul
++)
588 Argv
[ul
][strlen(Argv
[ul
])] = ' ';
593 /* Evaluate the expression */
596 if (!KdbpEvaluateExpression(Argv
[1], sizeof("kdb:> ")-1 + (Argv
[1]-Argv
[0]), &Result
))
599 if (Result
> (ULONGLONG
)(~((ULONG_PTR
)0)))
600 KdbpPrint("Warning: Address %I64x is beeing truncated\n",Result
);
602 Address
= (ULONG_PTR
)Result
;
604 else if (Argv
[0][0] == 'x')
606 KdbpPrint("x: Address argument required.\n");
610 if (Argv
[0][0] == 'x')
617 if (!KdbSymPrintAddress((PVOID
)Address
, NULL
))
618 KdbpPrint("<%x>:", Address
);
627 if (!NT_SUCCESS(KdbpSafeReadMemory(&ul
, (PVOID
)Address
, sizeof(ul
))))
628 KdbpPrint(" ????????");
630 KdbpPrint(" %08x", ul
);
632 Address
+= sizeof(ul
);
643 if (!KdbSymPrintAddress((PVOID
)Address
, NULL
))
644 KdbpPrint("<%08x>: ", Address
);
648 InstLen
= KdbpDisassemble(Address
, KdbUseIntelSyntax
);
651 KdbpPrint("<INVALID>\n");
663 /*!\brief Displays CPU registers.
670 PKTRAP_FRAME Tf
= &KdbCurrentTrapFrame
->Tf
;
672 static const PCHAR EflagsBits
[32] = { " CF", NULL
, " PF", " BIT3", " AF", " BIT5",
673 " ZF", " SF", " TF", " IF", " DF", " OF",
674 NULL
, NULL
, " NT", " BIT15", " RF", " VF",
675 " AC", " VIF", " VIP", " ID", " BIT22",
676 " BIT23", " BIT24", " BIT25", " BIT26",
677 " BIT27", " BIT28", " BIT29", " BIT30",
680 if (Argv
[0][0] == 'r') /* regs */
682 KdbpPrint("CS:EIP 0x%04x:0x%08x\n"
683 "SS:ESP 0x%04x:0x%08x\n"
684 " EAX 0x%08x EBX 0x%08x\n"
685 " ECX 0x%08x EDX 0x%08x\n"
686 " ESI 0x%08x EDI 0x%08x\n"
688 Tf
->SegCs
& 0xFFFF, Tf
->Eip
,
689 Tf
->HardwareSegSs
, Tf
->HardwareEsp
,
694 KdbpPrint("EFLAGS 0x%08x ", Tf
->EFlags
);
696 for (i
= 0; i
< 32; i
++)
700 if ((Tf
->EFlags
& (1 << 1)) == 0)
705 KdbpPrint(" IOPL%d", (Tf
->EFlags
>> 12) & 3);
710 else if ((Tf
->EFlags
& (1 << i
)) != 0)
712 KdbpPrint(EflagsBits
[i
]);
718 else if (Argv
[0][0] == 'c') /* cregs */
720 ULONG Cr0
, Cr2
, Cr3
, Cr4
;
721 KDESCRIPTOR Gdtr
, Idtr
;
723 static const PCHAR Cr0Bits
[32] = { " PE", " MP", " EM", " TS", " ET", " NE", NULL
, NULL
,
724 NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
,
725 " WP", NULL
, " AM", NULL
, NULL
, NULL
, NULL
, NULL
,
726 NULL
, NULL
, NULL
, NULL
, NULL
, " NW", " CD", " PG" };
727 static const PCHAR Cr4Bits
[32] = { " VME", " PVI", " TSD", " DE", " PSE", " PAE", " MCE", " PGE",
728 " PCE", " OSFXSR", " OSXMMEXCPT", NULL
, NULL
, NULL
, NULL
, NULL
,
729 NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
,
730 NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
};
732 Cr0
= KdbCurrentTrapFrame
->Cr0
;
733 Cr2
= KdbCurrentTrapFrame
->Cr2
;
734 Cr3
= KdbCurrentTrapFrame
->Cr3
;
735 Cr4
= KdbCurrentTrapFrame
->Cr4
;
737 /* Get descriptor table regs */
738 Ke386GetGlobalDescriptorTable(&Gdtr
.Limit
);
739 Ldtr
= Ke386GetLocalDescriptorTable();
742 /* Display the control registers */
743 KdbpPrint("CR0 0x%08x ", Cr0
);
745 for (i
= 0; i
< 32; i
++)
750 if ((Cr0
& (1 << i
)) != 0)
751 KdbpPrint(Cr0Bits
[i
]);
754 KdbpPrint("\nCR2 0x%08x\n", Cr2
);
755 KdbpPrint("CR3 0x%08x Pagedir-Base 0x%08x %s%s\n", Cr3
, (Cr3
& 0xfffff000),
756 (Cr3
& (1 << 3)) ? " PWT" : "", (Cr3
& (1 << 4)) ? " PCD" : "" );
757 KdbpPrint("CR4 0x%08x ", Cr4
);
759 for (i
= 0; i
< 32; i
++)
764 if ((Cr4
& (1 << i
)) != 0)
765 KdbpPrint(Cr4Bits
[i
]);
768 /* Display the descriptor table regs */
769 KdbpPrint("\nGDTR Base 0x%08x Size 0x%04x\n", Gdtr
.Base
, Gdtr
.Limit
);
770 KdbpPrint("LDTR 0x%04x\n", Ldtr
);
771 KdbpPrint("IDTR Base 0x%08x Size 0x%04x\n", Idtr
.Base
, Idtr
.Limit
);
773 else if (Argv
[0][0] == 's') /* sregs */
775 KdbpPrint("CS 0x%04x Index 0x%04x %cDT RPL%d\n",
776 Tf
->SegCs
& 0xffff, (Tf
->SegCs
& 0xffff) >> 3,
777 (Tf
->SegCs
& (1 << 2)) ? 'L' : 'G', Tf
->SegCs
& 3);
778 KdbpPrint("DS 0x%04x Index 0x%04x %cDT RPL%d\n",
779 Tf
->SegDs
, Tf
->SegDs
>> 3, (Tf
->SegDs
& (1 << 2)) ? 'L' : 'G', Tf
->SegDs
& 3);
780 KdbpPrint("ES 0x%04x Index 0x%04x %cDT RPL%d\n",
781 Tf
->SegEs
, Tf
->SegEs
>> 3, (Tf
->SegEs
& (1 << 2)) ? 'L' : 'G', Tf
->SegEs
& 3);
782 KdbpPrint("FS 0x%04x Index 0x%04x %cDT RPL%d\n",
783 Tf
->SegFs
, Tf
->SegFs
>> 3, (Tf
->SegFs
& (1 << 2)) ? 'L' : 'G', Tf
->SegFs
& 3);
784 KdbpPrint("GS 0x%04x Index 0x%04x %cDT RPL%d\n",
785 Tf
->SegGs
, Tf
->SegGs
>> 3, (Tf
->SegGs
& (1 << 2)) ? 'L' : 'G', Tf
->SegGs
& 3);
786 KdbpPrint("SS 0x%04x Index 0x%04x %cDT RPL%d\n",
787 Tf
->HardwareSegSs
, Tf
->HardwareSegSs
>> 3, (Tf
->HardwareSegSs
& (1 << 2)) ? 'L' : 'G', Tf
->HardwareSegSs
& 3);
791 ASSERT(Argv
[0][0] == 'd');
792 KdbpPrint("DR0 0x%08x\n"
798 Tf
->Dr0
, Tf
->Dr1
, Tf
->Dr2
, Tf
->Dr3
,
805 /*!\brief Displays a backtrace.
813 ULONGLONG Result
= 0;
814 ULONG_PTR Frame
= KdbCurrentTrapFrame
->Tf
.Ebp
;
816 KTRAP_FRAME TrapFrame
;
820 /* Check for [L count] part */
823 if (strcmp(Argv
[Argc
-2], "L") == 0)
825 ul
= strtoul(Argv
[Argc
-1], NULL
, 0);
831 else if (Argv
[Argc
-1][0] == 'L')
833 ul
= strtoul(Argv
[Argc
-1] + 1, NULL
, 0);
840 /* Put the remaining arguments back together */
842 for (ul
= 1; ul
< Argc
; ul
++)
844 Argv
[ul
][strlen(Argv
[ul
])] = ' ';
849 /* Check if frame addr or thread id is given. */
852 if (Argv
[1][0] == '*')
856 /* Evaluate the expression */
857 if (!KdbpEvaluateExpression(Argv
[1], sizeof("kdb:> ")-1 + (Argv
[1]-Argv
[0]), &Result
))
860 if (Result
> (ULONGLONG
)(~((ULONG_PTR
)0)))
861 KdbpPrint("Warning: Address %I64x is beeing truncated\n",Result
);
863 Frame
= (ULONG_PTR
)Result
;
867 KdbpPrint("Thread backtrace not supported yet!\n");
875 /* Try printing the function at EIP */
876 if (!KdbSymPrintAddress((PVOID
)KdbCurrentTrapFrame
->Tf
.Eip
, &KdbCurrentTrapFrame
->Tf
))
877 KdbpPrint("<%08x>\n", KdbCurrentTrapFrame
->Tf
.Eip
);
882 TrapFrame
= KdbCurrentTrapFrame
->Tf
;
883 KdbpPrint("Frames:\n");
887 BOOLEAN GotNextFrame
;
892 if (!NT_SUCCESS(KdbpSafeReadMemory(&Address
, (PVOID
)(Frame
+ sizeof(ULONG_PTR
)), sizeof (ULONG_PTR
))))
894 KdbpPrint("Couldn't access memory at 0x%p!\n", Frame
+ sizeof(ULONG_PTR
));
898 if ((GotNextFrame
= NT_SUCCESS(KdbpSafeReadMemory(&Frame
, (PVOID
)Frame
, sizeof (ULONG_PTR
)))))
899 TrapFrame
.Ebp
= Frame
;
901 /* Print the location of the call instruction */
902 if (!KdbSymPrintAddress((PVOID
)(Address
- 5), &TrapFrame
))
903 KdbpPrint("<%08x>\n", Address
);
907 if (KdbOutputAborted
) break;
914 KdbpPrint("Couldn't access memory at 0x%p!\n", Frame
);
922 /*!\brief Continues execution of the system/leaves KDB.
929 /* Exit the main loop */
933 /*!\brief Continues execution of the system/leaves KDB.
944 Count
= strtoul(Argv
[1], NULL
, 0);
947 KdbpPrint("%s: Integer argument required\n", Argv
[0]);
952 if (Argv
[0][0] == 'n')
953 KdbSingleStepOver
= TRUE
;
955 KdbSingleStepOver
= FALSE
;
957 /* Set the number of single steps and return to the interrupted code. */
958 KdbNumSingleSteps
= Count
;
963 /*!\brief Lists breakpoints.
966 KdbpCmdBreakPointList(
971 ULONG_PTR Address
= 0;
972 KDB_BREAKPOINT_TYPE Type
= 0;
973 KDB_ACCESS_TYPE AccessType
= 0;
976 BOOLEAN Enabled
= FALSE
;
977 BOOLEAN Global
= FALSE
;
978 PEPROCESS Process
= NULL
;
979 PCHAR str1
, str2
, ConditionExpr
, GlobalOrLocal
;
982 l
= KdbpGetNextBreakPointNr(0);
985 KdbpPrint("No breakpoints.\n");
989 KdbpPrint("Breakpoints:\n");
992 if (!KdbpGetBreakPointInfo(l
, &Address
, &Type
, &Size
, &AccessType
, &DebugReg
,
993 &Enabled
, &Global
, &Process
, &ConditionExpr
))
998 if (l
== KdbLastBreakPointNr
)
1011 GlobalOrLocal
= " global";
1015 GlobalOrLocal
= Buffer
;
1016 sprintf(Buffer
, " PID 0x%08lx",
1017 (ULONG
)(Process
? Process
->UniqueProcessId
: INVALID_HANDLE_VALUE
));
1020 if (Type
== KdbBreakPointSoftware
|| Type
== KdbBreakPointTemporary
)
1022 KdbpPrint(" %s%03d BPX 0x%08x%s%s%s%s%s\n",
1024 Enabled
? "" : " disabled",
1026 ConditionExpr
? " IF " : "",
1027 ConditionExpr
? ConditionExpr
: "",
1030 else if (Type
== KdbBreakPointHardware
)
1034 KdbpPrint(" %s%03d BPM 0x%08x %-5s %-5s disabled%s%s%s%s\n", str1
, l
, Address
,
1035 KDB_ACCESS_TYPE_TO_STRING(AccessType
),
1036 Size
== 1 ? "byte" : (Size
== 2 ? "word" : "dword"),
1038 ConditionExpr
? " IF " : "",
1039 ConditionExpr
? ConditionExpr
: "",
1044 KdbpPrint(" %s%03d BPM 0x%08x %-5s %-5s DR%d%s%s%s%s\n", str1
, l
, Address
,
1045 KDB_ACCESS_TYPE_TO_STRING(AccessType
),
1046 Size
== 1 ? "byte" : (Size
== 2 ? "word" : "dword"),
1049 ConditionExpr
? " IF " : "",
1050 ConditionExpr
? ConditionExpr
: "",
1055 while ((l
= KdbpGetNextBreakPointNr(l
+1)) >= 0);
1060 /*!\brief Enables, disables or clears a breakpoint.
1063 KdbpCmdEnableDisableClearBreakPoint(
1072 KdbpPrint("%s: argument required\n", Argv
[0]);
1077 BreakPointNr
= strtoul(Argv
[1], &pend
, 0);
1078 if (pend
== Argv
[1] || *pend
!= '\0')
1080 KdbpPrint("%s: integer argument required\n", Argv
[0]);
1084 if (Argv
[0][1] == 'e') /* enable */
1086 KdbpEnableBreakPoint(BreakPointNr
, NULL
);
1088 else if (Argv
[0][1] == 'd') /* disable */
1090 KdbpDisableBreakPoint(BreakPointNr
, NULL
);
1094 ASSERT(Argv
[0][1] == 'c');
1095 KdbpDeleteBreakPoint(BreakPointNr
, NULL
);
1101 /*!\brief Sets a software or hardware (memory) breakpoint at the given address.
1104 KdbpCmdBreakPoint(ULONG Argc
, PCHAR Argv
[])
1106 ULONGLONG Result
= 0;
1108 KDB_BREAKPOINT_TYPE Type
;
1110 KDB_ACCESS_TYPE AccessType
= 0;
1111 ULONG AddressArgIndex
, i
;
1112 LONG ConditionArgIndex
;
1113 BOOLEAN Global
= TRUE
;
1115 if (Argv
[0][2] == 'x') /* software breakpoint */
1119 KdbpPrint("bpx: Address argument required.\n");
1123 AddressArgIndex
= 1;
1124 Type
= KdbBreakPointSoftware
;
1126 else /* memory breakpoint */
1128 ASSERT(Argv
[0][2] == 'm');
1132 KdbpPrint("bpm: Access type argument required (one of r, w, rw, x)\n");
1136 if (_stricmp(Argv
[1], "x") == 0)
1137 AccessType
= KdbAccessExec
;
1138 else if (_stricmp(Argv
[1], "r") == 0)
1139 AccessType
= KdbAccessRead
;
1140 else if (_stricmp(Argv
[1], "w") == 0)
1141 AccessType
= KdbAccessWrite
;
1142 else if (_stricmp(Argv
[1], "rw") == 0)
1143 AccessType
= KdbAccessReadWrite
;
1146 KdbpPrint("bpm: Unknown access type '%s'\n", Argv
[1]);
1152 KdbpPrint("bpm: %s argument required.\n", AccessType
== KdbAccessExec
? "Address" : "Memory size");
1156 AddressArgIndex
= 3;
1157 if (_stricmp(Argv
[2], "byte") == 0)
1159 else if (_stricmp(Argv
[2], "word") == 0)
1161 else if (_stricmp(Argv
[2], "dword") == 0)
1163 else if (AccessType
== KdbAccessExec
)
1170 KdbpPrint("bpm: Unknown memory size '%s'\n", Argv
[2]);
1174 if (Argc
<= AddressArgIndex
)
1176 KdbpPrint("bpm: Address argument required.\n");
1180 Type
= KdbBreakPointHardware
;
1183 /* Put the arguments back together */
1184 ConditionArgIndex
= -1;
1185 for (i
= AddressArgIndex
; i
< (Argc
-1); i
++)
1187 if (strcmp(Argv
[i
+1], "IF") == 0) /* IF found */
1189 ConditionArgIndex
= i
+ 2;
1190 if (ConditionArgIndex
>= Argc
)
1192 KdbpPrint("%s: IF requires condition expression.\n", Argv
[0]);
1196 for (i
= ConditionArgIndex
; i
< (Argc
-1); i
++)
1197 Argv
[i
][strlen(Argv
[i
])] = ' ';
1202 Argv
[i
][strlen(Argv
[i
])] = ' ';
1205 /* Evaluate the address expression */
1206 if (!KdbpEvaluateExpression(Argv
[AddressArgIndex
],
1207 sizeof("kdb:> ")-1 + (Argv
[AddressArgIndex
]-Argv
[0]),
1213 if (Result
> (ULONGLONG
)(~((ULONG_PTR
)0)))
1214 KdbpPrint("%s: Warning: Address %I64x is beeing truncated\n", Argv
[0],Result
);
1216 Address
= (ULONG_PTR
)Result
;
1218 KdbpInsertBreakPoint(Address
, Type
, Size
, AccessType
,
1219 (ConditionArgIndex
< 0) ? NULL
: Argv
[ConditionArgIndex
],
1225 /*!\brief Lists threads or switches to another thread context.
1233 PETHREAD Thread
= NULL
;
1234 PEPROCESS Process
= NULL
;
1235 BOOLEAN ReferencedThread
= FALSE
, ReferencedProcess
= FALSE
;
1240 PCHAR State
, pend
, str1
, str2
;
1241 static const PCHAR ThreadStateToString
[DeferredReady
+1] =
1243 "Initialized", "Ready", "Running",
1244 "Standby", "Terminated", "Waiting",
1245 "Transition", "DeferredReady"
1248 ASSERT(KdbCurrentProcess
);
1250 if (Argc
>= 2 && _stricmp(Argv
[1], "list") == 0)
1252 Process
= KdbCurrentProcess
;
1256 ul
= strtoul(Argv
[2], &pend
, 0);
1257 if (Argv
[2] == pend
)
1259 KdbpPrint("thread: '%s' is not a valid process id!\n", Argv
[2]);
1263 if (!NT_SUCCESS(PsLookupProcessByProcessId((PVOID
)ul
, &Process
)))
1265 KdbpPrint("thread: Invalid process id!\n");
1269 /* Remember our reference */
1270 ReferencedProcess
= TRUE
;
1273 Entry
= Process
->ThreadListHead
.Flink
;
1274 if (Entry
== &Process
->ThreadListHead
)
1277 KdbpPrint("No threads in process 0x%08x!\n", ul
);
1279 KdbpPrint("No threads in current process!\n");
1281 if (ReferencedProcess
)
1282 ObDereferenceObject(Process
);
1287 KdbpPrint(" TID State Prior. Affinity EBP EIP\n");
1290 Thread
= CONTAINING_RECORD(Entry
, ETHREAD
, ThreadListEntry
);
1292 if (Thread
== KdbCurrentThread
)
1303 if (!Thread
->Tcb
.InitialStack
)
1305 /* Thread has no kernel stack (probably terminated) */
1309 else if (Thread
->Tcb
.TrapFrame
)
1311 if (Thread
->Tcb
.TrapFrame
->PreviousPreviousMode
== KernelMode
)
1312 Esp
= (PULONG
)Thread
->Tcb
.TrapFrame
->TempEsp
;
1314 Esp
= (PULONG
)Thread
->Tcb
.TrapFrame
->HardwareEsp
;
1316 Ebp
= (PULONG
)Thread
->Tcb
.TrapFrame
->Ebp
;
1317 Eip
= Thread
->Tcb
.TrapFrame
->Eip
;
1321 Esp
= (PULONG
)Thread
->Tcb
.KernelStack
;
1322 Ebp
= (PULONG
)Esp
[4];
1325 if (Ebp
) /* FIXME: Should we attach to the process to read Ebp[1]? */
1326 KdbpSafeReadMemory(&Eip
, Ebp
+ 1, sizeof (Eip
));
1329 if (Thread
->Tcb
.State
< (DeferredReady
+ 1))
1330 State
= ThreadStateToString
[Thread
->Tcb
.State
];
1334 KdbpPrint(" %s0x%08x %-11s %3d 0x%08x 0x%08x 0x%08x%s\n",
1336 Thread
->Cid
.UniqueThread
,
1338 Thread
->Tcb
.Priority
,
1339 Thread
->Tcb
.Affinity
,
1344 Entry
= Entry
->Flink
;
1346 while (Entry
!= &Process
->ThreadListHead
);
1348 /* Release our reference, if any */
1349 if (ReferencedProcess
)
1350 ObDereferenceObject(Process
);
1352 else if (Argc
>= 2 && _stricmp(Argv
[1], "attach") == 0)
1356 KdbpPrint("thread attach: thread id argument required!\n");
1360 ul
= strtoul(Argv
[2], &pend
, 0);
1361 if (Argv
[2] == pend
)
1363 KdbpPrint("thread attach: '%s' is not a valid thread id!\n", Argv
[2]);
1367 if (!KdbpAttachToThread((PVOID
)ul
))
1372 KdbpPrint("Attached to thread 0x%08x.\n", ul
);
1376 Thread
= KdbCurrentThread
;
1380 ul
= strtoul(Argv
[1], &pend
, 0);
1381 if (Argv
[1] == pend
)
1383 KdbpPrint("thread: '%s' is not a valid thread id!\n", Argv
[1]);
1387 if (!NT_SUCCESS(PsLookupThreadByThreadId((PVOID
)ul
, &Thread
)))
1389 KdbpPrint("thread: Invalid thread id!\n");
1393 /* Remember our reference */
1394 ReferencedThread
= TRUE
;
1397 if (Thread
->Tcb
.State
< (DeferredReady
+ 1))
1398 State
= ThreadStateToString
[Thread
->Tcb
.State
];
1404 " State: %s (0x%x)\n"
1406 " Affinity: 0x%08x\n"
1407 " Initial Stack: 0x%08x\n"
1408 " Stack Limit: 0x%08x\n"
1409 " Stack Base: 0x%08x\n"
1410 " Kernel Stack: 0x%08x\n"
1411 " Trap Frame: 0x%08x\n"
1412 " NPX State: %s (0x%x)\n",
1413 (Argc
< 2) ? "Current Thread:\n" : "",
1414 Thread
->Cid
.UniqueThread
,
1415 State
, Thread
->Tcb
.State
,
1416 Thread
->Tcb
.Priority
,
1417 Thread
->Tcb
.Affinity
,
1418 Thread
->Tcb
.InitialStack
,
1419 Thread
->Tcb
.StackLimit
,
1420 Thread
->Tcb
.StackBase
,
1421 Thread
->Tcb
.KernelStack
,
1422 Thread
->Tcb
.TrapFrame
,
1423 NPX_STATE_TO_STRING(Thread
->Tcb
.NpxState
), Thread
->Tcb
.NpxState
);
1425 /* Release our reference if we had one */
1426 if (ReferencedThread
)
1427 ObDereferenceObject(Thread
);
1433 /*!\brief Lists processes or switches to another process context.
1442 BOOLEAN ReferencedProcess
= FALSE
;
1443 PCHAR State
, pend
, str1
, str2
;
1445 extern LIST_ENTRY PsActiveProcessHead
;
1447 if (Argc
>= 2 && _stricmp(Argv
[1], "list") == 0)
1449 Entry
= PsActiveProcessHead
.Flink
;
1450 if (!Entry
|| Entry
== &PsActiveProcessHead
)
1452 KdbpPrint("No processes in the system!\n");
1456 KdbpPrint(" PID State Filename\n");
1459 Process
= CONTAINING_RECORD(Entry
, EPROCESS
, ActiveProcessLinks
);
1461 if (Process
== KdbCurrentProcess
)
1472 State
= ((Process
->Pcb
.State
== ProcessInMemory
) ? "In Memory" :
1473 ((Process
->Pcb
.State
== ProcessOutOfMemory
) ? "Out of Memory" : "In Transition"));
1475 KdbpPrint(" %s0x%08x %-10s %s%s\n",
1477 Process
->UniqueProcessId
,
1479 Process
->ImageFileName
,
1482 Entry
= Entry
->Flink
;
1484 while(Entry
!= &PsActiveProcessHead
);
1486 else if (Argc
>= 2 && _stricmp(Argv
[1], "attach") == 0)
1490 KdbpPrint("process attach: process id argument required!\n");
1494 ul
= strtoul(Argv
[2], &pend
, 0);
1495 if (Argv
[2] == pend
)
1497 KdbpPrint("process attach: '%s' is not a valid process id!\n", Argv
[2]);
1501 if (!KdbpAttachToProcess((PVOID
)ul
))
1506 KdbpPrint("Attached to process 0x%08x, thread 0x%08x.\n", (ULONG
)ul
,
1507 (ULONG
)KdbCurrentThread
->Cid
.UniqueThread
);
1511 Process
= KdbCurrentProcess
;
1515 ul
= strtoul(Argv
[1], &pend
, 0);
1516 if (Argv
[1] == pend
)
1518 KdbpPrint("proc: '%s' is not a valid process id!\n", Argv
[1]);
1522 if (!NT_SUCCESS(PsLookupProcessByProcessId((PVOID
)ul
, &Process
)))
1524 KdbpPrint("proc: Invalid process id!\n");
1528 /* Remember our reference */
1529 ReferencedProcess
= TRUE
;
1532 State
= ((Process
->Pcb
.State
== ProcessInMemory
) ? "In Memory" :
1533 ((Process
->Pcb
.State
== ProcessOutOfMemory
) ? "Out of Memory" : "In Transition"));
1536 " State: %s (0x%x)\n"
1537 " Image Filename: %s\n",
1538 (Argc
< 2) ? "Current process:\n" : "",
1539 Process
->UniqueProcessId
,
1540 State
, Process
->Pcb
.State
,
1541 Process
->ImageFileName
);
1543 /* Release our reference, if any */
1544 if (ReferencedProcess
)
1545 ObDereferenceObject(Process
);
1551 /*!\brief Lists loaded modules or the one containing the specified address.
1558 ULONGLONG Result
= 0;
1560 PLDR_DATA_TABLE_ENTRY LdrEntry
;
1561 BOOLEAN DisplayOnlyOneModule
= FALSE
;
1566 /* Put the arguments back together */
1569 Argv
[Argc
][strlen(Argv
[Argc
])] = ' ';
1571 /* Evaluate the expression */
1572 if (!KdbpEvaluateExpression(Argv
[1], sizeof("kdb:> ")-1 + (Argv
[1]-Argv
[0]), &Result
))
1577 if (Result
> (ULONGLONG
)(~((ULONG_PTR
)0)))
1578 KdbpPrint("%s: Warning: Address %I64x is beeing truncated\n", Argv
[0],Result
);
1580 Address
= (ULONG_PTR
)Result
;
1582 if (!KdbpSymFindModule((PVOID
)Address
, NULL
, -1, &LdrEntry
))
1584 KdbpPrint("No module containing address 0x%p found!\n", Address
);
1588 DisplayOnlyOneModule
= TRUE
;
1592 if (!KdbpSymFindModule(NULL
, NULL
, 0, &LdrEntry
))
1594 ULONG_PTR ntoskrnlBase
= ((ULONG_PTR
)KdbpCmdMod
) & 0xfff00000;
1595 KdbpPrint(" Base Size Name\n");
1596 KdbpPrint(" %08x %08x %s\n", ntoskrnlBase
, 0, "ntoskrnl.exe");
1603 KdbpPrint(" Base Size Name\n");
1606 KdbpPrint(" %08x %08x %wZ\n", LdrEntry
->DllBase
, LdrEntry
->SizeOfImage
, &LdrEntry
->BaseDllName
);
1608 if(DisplayOnlyOneModule
|| !KdbpSymFindModule(NULL
, NULL
, i
++, &LdrEntry
))
1615 /*!\brief Displays GDT, LDT or IDTd.
1632 if (Argv
[0][0] == 'i')
1639 KdbpPrint("Interrupt descriptor table is empty.\n");
1643 KdbpPrint("IDT Base: 0x%08x Limit: 0x%04x\n", Reg
.Base
, Reg
.Limit
);
1644 KdbpPrint(" Idx Type Seg. Sel. Offset DPL\n");
1646 for (i
= 0; (i
+ sizeof(SegDesc
) - 1) <= Reg
.Limit
; i
+= 8)
1648 if (!NT_SUCCESS(KdbpSafeReadMemory(SegDesc
, (PVOID
)(Reg
.Base
+ i
), sizeof(SegDesc
))))
1650 KdbpPrint("Couldn't access memory at 0x%08x!\n", Reg
.Base
+ i
);
1654 Dpl
= ((SegDesc
[1] >> 13) & 3);
1655 if ((SegDesc
[1] & 0x1f00) == 0x0500) /* Task gate */
1656 SegType
= "TASKGATE";
1657 else if ((SegDesc
[1] & 0x1fe0) == 0x0e00) /* 32 bit Interrupt gate */
1658 SegType
= "INTGATE32";
1659 else if ((SegDesc
[1] & 0x1fe0) == 0x0600) /* 16 bit Interrupt gate */
1660 SegType
= "INTGATE16";
1661 else if ((SegDesc
[1] & 0x1fe0) == 0x0f00) /* 32 bit Trap gate */
1662 SegType
= "TRAPGATE32";
1663 else if ((SegDesc
[1] & 0x1fe0) == 0x0700) /* 16 bit Trap gate */
1664 SegType
= "TRAPGATE16";
1666 SegType
= "UNKNOWN";
1668 if ((SegDesc
[1] & (1 << 15)) == 0) /* not present */
1670 KdbpPrint(" %03d %-10s [NP] [NP] %02d\n",
1671 i
/ 8, SegType
, Dpl
);
1673 else if ((SegDesc
[1] & 0x1f00) == 0x0500) /* Task gate */
1675 SegSel
= SegDesc
[0] >> 16;
1676 KdbpPrint(" %03d %-10s 0x%04x %02d\n",
1677 i
/ 8, SegType
, SegSel
, Dpl
);
1681 SegSel
= SegDesc
[0] >> 16;
1682 SegBase
= (SegDesc
[1] & 0xffff0000) | (SegDesc
[0] & 0x0000ffff);
1683 KdbpPrint(" %03d %-10s 0x%04x 0x%08x %02d\n",
1684 i
/ 8, SegType
, SegSel
, SegBase
, Dpl
);
1692 if (Argv
[0][0] == 'g')
1695 Ke386GetGlobalDescriptorTable(&Reg
.Limit
);
1700 ASSERT(Argv
[0][0] == 'l');
1703 Reg
.Limit
= Ke386GetLocalDescriptorTable();
1711 KdbpPrint("%s descriptor table is empty.\n",
1712 Argv
[0][0] == 'g' ? "Global" : "Local");
1716 KdbpPrint("%cDT Base: 0x%08x Limit: 0x%04x\n",
1717 Argv
[0][0] == 'g' ? 'G' : 'L', Reg
.Base
, Reg
.Limit
);
1718 KdbpPrint(" Idx Sel. Type Base Limit DPL Attribs\n");
1720 for (; (i
+ sizeof(SegDesc
) - 1) <= Reg
.Limit
; i
+= 8)
1722 if (!NT_SUCCESS(KdbpSafeReadMemory(SegDesc
, (PVOID
)(Reg
.Base
+ i
), sizeof(SegDesc
))))
1724 KdbpPrint("Couldn't access memory at 0x%08x!\n", Reg
.Base
+ i
);
1728 Dpl
= ((SegDesc
[1] >> 13) & 3);
1729 Type
= ((SegDesc
[1] >> 8) & 0xf);
1731 SegBase
= SegDesc
[0] >> 16;
1732 SegBase
|= (SegDesc
[1] & 0xff) << 16;
1733 SegBase
|= SegDesc
[1] & 0xff000000;
1734 SegLimit
= SegDesc
[0] & 0x0000ffff;
1735 SegLimit
|= (SegDesc
[1] >> 16) & 0xf;
1737 if ((SegDesc
[1] & (1 << 23)) != 0)
1747 if ((SegDesc
[1] & (1 << 12)) == 0) /* System segment */
1751 case 1: SegType
= "TSS16(Avl)"; break;
1752 case 2: SegType
= "LDT"; break;
1753 case 3: SegType
= "TSS16(Busy)"; break;
1754 case 4: SegType
= "CALLGATE16"; break;
1755 case 5: SegType
= "TASKGATE"; break;
1756 case 6: SegType
= "INTGATE16"; break;
1757 case 7: SegType
= "TRAPGATE16"; break;
1758 case 9: SegType
= "TSS32(Avl)"; break;
1759 case 11: SegType
= "TSS32(Busy)"; break;
1760 case 12: SegType
= "CALLGATE32"; break;
1761 case 14: SegType
= "INTGATE32"; break;
1762 case 15: SegType
= "INTGATE32"; break;
1763 default: SegType
= "UNKNOWN"; break;
1766 if (!(Type
>= 1 && Type
<= 3) &&
1767 Type
!= 9 && Type
!= 11)
1773 else if ((SegDesc
[1] & (1 << 11)) == 0) /* Data segment */
1775 if ((SegDesc
[1] & (1 << 22)) != 0)
1780 else /* Code segment */
1782 if ((SegDesc
[1] & (1 << 22)) != 0)
1788 if ((SegDesc
[1] & (1 << 15)) == 0) /* not present */
1790 KdbpPrint(" %03d 0x%04x %-11s [NP] [NP] %02d NP\n",
1791 i
/ 8, i
| Dpl
| ul
, SegType
, Dpl
);
1795 KdbpPrint(" %03d 0x%04x %-11s 0x%08x 0x%08x %02d ",
1796 i
/ 8, i
| Dpl
| ul
, SegType
, SegBase
, SegLimit
, Dpl
);
1798 if ((SegDesc
[1] & (1 << 12)) == 0) /* System segment */
1800 /* FIXME: Display system segment */
1802 else if ((SegDesc
[1] & (1 << 11)) == 0) /* Data segment */
1804 if ((SegDesc
[1] & (1 << 10)) != 0) /* Expand-down */
1807 KdbpPrint((SegDesc
[1] & (1 << 9)) ? " R/W" : " R");
1809 if ((SegDesc
[1] & (1 << 8)) != 0)
1812 else /* Code segment */
1814 if ((SegDesc
[1] & (1 << 10)) != 0) /* Conforming */
1817 KdbpPrint((SegDesc
[1] & (1 << 9)) ? " R/X" : " X");
1819 if ((SegDesc
[1] & (1 << 8)) != 0)
1823 if ((SegDesc
[1] & (1 << 20)) != 0)
1834 /*!\brief Displays the KPCR
1841 PKIPCR Pcr
= (PKIPCR
)KeGetPcr();
1843 KdbpPrint("Current PCR is at 0x%08x.\n", (INT
)Pcr
);
1844 KdbpPrint(" Tib.ExceptionList: 0x%08x\n"
1845 " Tib.StackBase: 0x%08x\n"
1846 " Tib.StackLimit: 0x%08x\n"
1847 " Tib.SubSystemTib: 0x%08x\n"
1848 " Tib.FiberData/Version: 0x%08x\n"
1849 " Tib.ArbitraryUserPointer: 0x%08x\n"
1850 " Tib.Self: 0x%08x\n"
1855 " IrrActive: 0x%08x\n"
1857 " KdVersionBlock: 0x%08x\n"
1861 " MajorVersion: 0x%04x\n"
1862 " MinorVersion: 0x%04x\n"
1863 " SetMember: 0x%08x\n"
1864 " StallScaleFactor: 0x%08x\n"
1866 " L2CacheAssociativity: 0x%02x\n"
1867 " VdmAlert: 0x%08x\n"
1868 " L2CacheSize: 0x%08x\n"
1869 " InterruptMode: 0x%08x\n",
1870 Pcr
->NtTib
.ExceptionList
, Pcr
->NtTib
.StackBase
, Pcr
->NtTib
.StackLimit
,
1871 Pcr
->NtTib
.SubSystemTib
, Pcr
->NtTib
.FiberData
, Pcr
->NtTib
.ArbitraryUserPointer
,
1872 Pcr
->NtTib
.Self
, Pcr
->Self
, Pcr
->Prcb
, Pcr
->Irql
, Pcr
->IRR
, Pcr
->IrrActive
,
1873 Pcr
->IDR
, Pcr
->KdVersionBlock
, Pcr
->IDT
, Pcr
->GDT
, Pcr
->TSS
,
1874 Pcr
->MajorVersion
, Pcr
->MinorVersion
, Pcr
->SetMember
, Pcr
->StallScaleFactor
,
1875 Pcr
->Number
, Pcr
->SecondLevelCacheAssociativity
,
1876 Pcr
->VdmAlert
, Pcr
->SecondLevelCacheSize
, Pcr
->InterruptMode
);
1881 /*!\brief Displays the TSS
1888 KTSS
*Tss
= KeGetPcr()->TSS
;
1890 KdbpPrint("Current TSS is at 0x%08x.\n", (INT
)Tss
);
1891 KdbpPrint(" Eip: 0x%08x\n"
1898 " IoMapBase: 0x%04x\n",
1899 Tss
->Eip
, Tss
->Es
, Tss
->Cs
, Tss
->Ds
, Tss
->Fs
, Tss
->Gs
, Tss
->IoMapBase
);
1904 /*!\brief Bugchecks the system.
1911 /* Set the flag and quit looping */
1912 KdbpBugCheckRequested
= TRUE
;
1920 IN ULONG BufLength
);
1922 /*!\brief Display debug messages on screen, with paging.
1924 * Keys for per-page view: Home, End, PageUp, Arrow Up, PageDown,
1925 * all others are as PageDown.
1934 KdbpIsInDmesgMode
= TRUE
; /* Toggle logging flag */
1935 if (!KdpDmesgBuffer
)
1937 KdbpPrint("Dmesg: error, buffer is not allocated! /DEBUGPORT=SCREEN kernel param required for dmesg.\n");
1941 KdbpPrint("*** Dmesg *** TotalWritten=%lu, BufferSize=%lu, CurrentPosition=%lu\n",
1942 KdbDmesgTotalWritten
, KdpDmesgBufferSize
, KdpDmesgCurrentPosition
);
1944 // Pass data to the pager:
1945 end
= KdpDmesgCurrentPosition
;
1946 beg
= (end
+ KdpDmesgFreeBytes
) % KdpDmesgBufferSize
;
1948 // no roll-overs, and overwritten=lost bytes
1949 if (KdbDmesgTotalWritten
<= KdpDmesgBufferSize
)
1951 // show buffer (KdpDmesgBuffer + beg, num)
1952 KdbpPager(KdpDmesgBuffer
, KdpDmesgCurrentPosition
);
1956 // show 2 buffers: (KdpDmesgBuffer + beg, KdpDmesgBufferSize - beg)
1957 // and: (KdpDmesgBuffer, end)
1958 KdbpPager(KdpDmesgBuffer
+ beg
, KdpDmesgBufferSize
- beg
);
1959 KdbpPrint("*** Dmesg: buffer rollup ***\n");
1960 KdbpPager(KdpDmesgBuffer
, end
);
1962 KdbpPrint("*** Dmesg: end of output ***\n");
1964 KdbpIsInDmesgMode
= FALSE
; /* Toggle logging flag */
1969 /*!\brief Sets or displays a config variables value.
1979 KDB_ENTER_CONDITION ConditionFirst
= KdbDoNotEnter
;
1980 KDB_ENTER_CONDITION ConditionLast
= KdbDoNotEnter
;
1982 static const PCHAR ExceptionNames
[21] =
1984 "ZERODEVIDE", "DEBUGTRAP", "NMI", "INT3", "OVERFLOW", "BOUND", "INVALIDOP",
1985 "NOMATHCOP", "DOUBLEFAULT", "RESERVED(9)", "INVALIDTSS", "SEGMENTNOTPRESENT",
1986 "STACKFAULT", "GPF", "PAGEFAULT", "RESERVED(15)", "MATHFAULT", "ALIGNMENTCHECK",
1987 "MACHINECHECK", "SIMDFAULT", "OTHERS"
1992 KdbpPrint("Available settings:\n");
1993 KdbpPrint(" syntax [intel|at&t]\n");
1994 KdbpPrint(" condition [exception|*] [first|last] [never|always|kmode|umode]\n");
1995 KdbpPrint(" break_on_module_load [true|false]\n");
1997 else if (strcmp(Argv
[1], "syntax") == 0)
2001 KdbpPrint("syntax = %s\n", KdbUseIntelSyntax
? "intel" : "at&t");
2005 if (_stricmp(Argv
[2], "intel") == 0)
2006 KdbUseIntelSyntax
= TRUE
;
2007 else if (_stricmp(Argv
[2], "at&t") == 0)
2008 KdbUseIntelSyntax
= FALSE
;
2010 KdbpPrint("Unknown syntax '%s'.\n", Argv
[2]);
2013 else if (strcmp(Argv
[1], "condition") == 0)
2017 KdbpPrint("Conditions: (First) (Last)\n");
2018 for (l
= 0; l
< RTL_NUMBER_OF(ExceptionNames
) - 1; l
++)
2020 if (!ExceptionNames
[l
])
2023 if (!KdbpGetEnterCondition(l
, TRUE
, &ConditionFirst
))
2026 if (!KdbpGetEnterCondition(l
, FALSE
, &ConditionLast
))
2029 KdbpPrint(" #%02d %-20s %-8s %-8s\n", l
, ExceptionNames
[l
],
2030 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst
),
2031 KDB_ENTER_CONDITION_TO_STRING(ConditionLast
));
2034 ASSERT(l
== (RTL_NUMBER_OF(ExceptionNames
) - 1));
2035 KdbpPrint(" %-20s %-8s %-8s\n", ExceptionNames
[l
],
2036 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst
),
2037 KDB_ENTER_CONDITION_TO_STRING(ConditionLast
));
2041 if (Argc
>= 5 && strcmp(Argv
[2], "*") == 0) /* Allow * only when setting condition */
2047 l
= strtoul(Argv
[2], &pend
, 0);
2049 if (Argv
[2] == pend
)
2051 for (l
= 0; l
< RTL_NUMBER_OF(ExceptionNames
); l
++)
2053 if (!ExceptionNames
[l
])
2056 if (_stricmp(ExceptionNames
[l
], Argv
[2]) == 0)
2061 if (l
>= RTL_NUMBER_OF(ExceptionNames
))
2063 KdbpPrint("Unknown exception '%s'.\n", Argv
[2]);
2070 if (_stricmp(Argv
[3], "first") == 0)
2072 else if (_stricmp(Argv
[3], "last") == 0)
2076 KdbpPrint("set condition: second argument must be 'first' or 'last'\n");
2080 if (_stricmp(Argv
[4], "never") == 0)
2081 ConditionFirst
= KdbDoNotEnter
;
2082 else if (_stricmp(Argv
[4], "always") == 0)
2083 ConditionFirst
= KdbEnterAlways
;
2084 else if (_stricmp(Argv
[4], "umode") == 0)
2085 ConditionFirst
= KdbEnterFromUmode
;
2086 else if (_stricmp(Argv
[4], "kmode") == 0)
2087 ConditionFirst
= KdbEnterFromKmode
;
2090 KdbpPrint("set condition: third argument must be 'never', 'always', 'umode' or 'kmode'\n");
2094 if (!KdbpSetEnterCondition(l
, First
, ConditionFirst
))
2097 KdbpPrint("Couldn't change condition for exception #%02d\n", l
);
2099 KdbpPrint("Couldn't change condition for all exceptions\n", l
);
2102 else /* Argc >= 3 */
2104 if (!KdbpGetEnterCondition(l
, TRUE
, &ConditionFirst
))
2107 if (!KdbpGetEnterCondition(l
, FALSE
, &ConditionLast
))
2110 if (l
< (RTL_NUMBER_OF(ExceptionNames
) - 1))
2112 KdbpPrint("Condition for exception #%02d (%s): FirstChance %s LastChance %s\n",
2113 l
, ExceptionNames
[l
],
2114 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst
),
2115 KDB_ENTER_CONDITION_TO_STRING(ConditionLast
));
2119 KdbpPrint("Condition for all other exceptions: FirstChance %s LastChance %s\n",
2120 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst
),
2121 KDB_ENTER_CONDITION_TO_STRING(ConditionLast
));
2126 else if (strcmp(Argv
[1], "break_on_module_load") == 0)
2129 KdbpPrint("break_on_module_load = %s\n", KdbBreakOnModuleLoad
? "enabled" : "disabled");
2132 if (_stricmp(Argv
[2], "enable") == 0 || _stricmp(Argv
[2], "enabled") == 0 || _stricmp(Argv
[2], "true") == 0)
2133 KdbBreakOnModuleLoad
= TRUE
;
2134 else if (_stricmp(Argv
[2], "disable") == 0 || _stricmp(Argv
[2], "disabled") == 0 || _stricmp(Argv
[2], "false") == 0)
2135 KdbBreakOnModuleLoad
= FALSE
;
2137 KdbpPrint("Unknown setting '%s'.\n", Argv
[2]);
2142 KdbpPrint("Unknown setting '%s'.\n", Argv
[1]);
2148 /*!\brief Displays help screen.
2157 KdbpPrint("Kernel debugger commands:\n");
2158 for (i
= 0; i
< RTL_NUMBER_OF(KdbDebuggerCommands
); i
++)
2160 if (!KdbDebuggerCommands
[i
].Syntax
) /* Command group */
2165 KdbpPrint("\x1b[7m* %s:\x1b[0m\n", KdbDebuggerCommands
[i
].Help
);
2169 KdbpPrint(" %-20s - %s\n",
2170 KdbDebuggerCommands
[i
].Syntax
,
2171 KdbDebuggerCommands
[i
].Help
);
2177 /*!\brief Prints the given string with printf-like formatting.
2179 * \param Format Format of the string/arguments.
2180 * \param ... Variable number of arguments matching the format specified in \a Format.
2182 * \note Doesn't correctly handle \\t and terminal escape sequences when calculating the
2183 * number of lines required to print a single line from the Buffer in the terminal.
2184 * Prints maximum 4096 chars, because of its buffer size.
2191 static CHAR Buffer
[4096];
2192 static BOOLEAN TerminalInitialized
= FALSE
;
2193 static BOOLEAN TerminalConnected
= FALSE
;
2194 static BOOLEAN TerminalReportsSize
= TRUE
;
2199 LONG RowsPrintedByTerminal
;
2203 /* Check if the user has aborted output of the current command */
2204 if (KdbOutputAborted
)
2207 /* Initialize the terminal */
2208 if (!TerminalInitialized
)
2210 DbgPrint("\x1b[7h"); /* Enable linewrap */
2212 /* Query terminal type */
2213 /*DbgPrint("\x1b[Z");*/
2216 TerminalInitialized
= TRUE
;
2218 KeStallExecutionProcessor(100000);
2222 c
= KdbpTryGetCharSerial(5000);
2226 Buffer
[Length
++] = c
;
2227 if (Length
>= (sizeof (Buffer
) - 1))
2231 Buffer
[Length
] = '\0';
2233 TerminalConnected
= TRUE
;
2236 /* Get number of rows and columns in terminal */
2237 if ((KdbNumberOfRowsTerminal
< 0) || (KdbNumberOfColsTerminal
< 0) ||
2238 (KdbNumberOfRowsPrinted
) == 0) /* Refresh terminal size each time when number of rows printed is 0 */
2240 if ((KdbDebugState
& KD_DEBUG_KDSERIAL
) && TerminalConnected
&& TerminalReportsSize
)
2242 /* Try to query number of rows from terminal. A reply looks like "\x1b[8;24;80t" */
2243 TerminalReportsSize
= FALSE
;
2244 KeStallExecutionProcessor(100000);
2245 DbgPrint("\x1b[18t");
2246 c
= KdbpTryGetCharSerial(5000);
2250 c
= KdbpTryGetCharSerial(5000);
2257 c
= KdbpTryGetCharSerial(5000);
2261 Buffer
[Length
++] = c
;
2262 if (isalpha(c
) || Length
>= (sizeof (Buffer
) - 1))
2266 Buffer
[Length
] = '\0';
2267 if (Buffer
[0] == '8' && Buffer
[1] == ';')
2269 for (i
= 2; (i
< Length
) && (Buffer
[i
] != ';'); i
++);
2271 if (Buffer
[i
] == ';')
2275 /* Number of rows is now at Buffer + 2 and number of cols at Buffer + i */
2276 KdbNumberOfRowsTerminal
= strtoul(Buffer
+ 2, NULL
, 0);
2277 KdbNumberOfColsTerminal
= strtoul(Buffer
+ i
, NULL
, 0);
2278 TerminalReportsSize
= TRUE
;
2282 /* Clear further characters */
2283 while ((c
= KdbpTryGetCharSerial(5000)) != -1);
2287 if (KdbNumberOfRowsTerminal
<= 0)
2289 /* Set number of rows to the default. */
2290 KdbNumberOfRowsTerminal
= 23; //24; //Mna.: 23 for SCREEN debugport
2292 else if (KdbNumberOfColsTerminal
<= 0)
2294 /* Set number of cols to the default. */
2295 KdbNumberOfColsTerminal
= 75; //80; //Mna.: 75 for SCREEN debugport
2299 /* Get the string */
2300 va_start(ap
, Format
);
2301 Length
= _vsnprintf(Buffer
, sizeof (Buffer
) - 1, Format
, ap
);
2302 Buffer
[Length
] = '\0';
2306 while (p
[0] != '\0')
2308 i
= strcspn(p
, "\n");
2310 /* Calculate the number of lines which will be printed in the terminal
2311 * when outputting the current line
2314 RowsPrintedByTerminal
= (i
+ KdbNumberOfColsPrinted
- 1) / KdbNumberOfColsTerminal
;
2316 RowsPrintedByTerminal
= 0;
2319 RowsPrintedByTerminal
++;
2321 /*DbgPrint("!%d!%d!%d!%d!", KdbNumberOfRowsPrinted, KdbNumberOfColsPrinted, i, RowsPrintedByTerminal);*/
2323 /* Display a prompt if we printed one screen full of text */
2324 if (KdbNumberOfRowsTerminal
> 0 &&
2325 (LONG
)(KdbNumberOfRowsPrinted
+ RowsPrintedByTerminal
) >= KdbNumberOfRowsTerminal
)
2327 if (KdbNumberOfColsPrinted
> 0)
2330 DbgPrint("--- Press q to abort, any other key to continue ---");
2331 RowsPrintedByTerminal
++; /* added by Mna. */
2333 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
2334 c
= KdbpGetCharSerial();
2336 c
= KdbpGetCharKeyboard(&ScanCode
);
2340 /* Try to read '\n' which might follow '\r' - if \n is not received here
2341 * it will be interpreted as "return" when the next command should be read.
2343 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
2344 c
= KdbpTryGetCharSerial(5);
2346 c
= KdbpTryGetCharKeyboard(&ScanCode
, 5);
2352 KdbOutputAborted
= TRUE
;
2356 KdbNumberOfRowsPrinted
= 0;
2357 KdbNumberOfColsPrinted
= 0;
2360 /* Insert a NUL after the line and print only the current line. */
2361 if (p
[i
] == '\n' && p
[i
+ 1] != '\0')
2371 /* Remove escape sequences from the line if there's no terminal connected */
2372 if (!TerminalConnected
)
2374 while ((p2
= strrchr(p
, '\x1b'))) /* Look for escape character */
2379 while (!isalpha(p2
[j
++]));
2394 /* Set p to the start of the next line and
2395 * remember the number of rows/cols printed
2401 KdbNumberOfColsPrinted
= 0;
2405 ASSERT(p
[0] == '\0');
2406 KdbNumberOfColsPrinted
+= i
;
2409 KdbNumberOfRowsPrinted
+= RowsPrintedByTerminal
;
2413 /** memrchr(), explicitly defined, since was absent in MinGW of RosBE. */
2416 * Find the last occurrence of 'c' in the buffer 's' of size 'n'.
2419 memrchr(const void *s
, int c
, size_t n
)
2421 const unsigned char *cp
;
2425 cp
= (unsigned char *)s
+ n
;
2428 if (*(--cp
) == (unsigned char)c
)
2435 /*!\brief Calculate pointer position for N lines upper of current position.
2437 * \param Buffer Characters buffer to operate on.
2438 * \param BufLength Buffer size.
2440 * \note Calculate pointer position for N lines upper of current displaying
2441 * position within the given buffer.
2443 * Used by KdbpPager().
2444 * Now N lines count is hardcoded to KdbNumberOfRowsTerminal.
2447 CountOnePageUp(PCHAR Buffer
, ULONG BufLength
, PCHAR pCurPos
)
2450 // p0 is initial guess of Page Start
2451 ULONG p0len
= KdbNumberOfRowsTerminal
* KdbNumberOfColsTerminal
;
2452 PCHAR p0
= pCurPos
- p0len
;
2453 PCHAR prev_p
= p0
, p1
;
2456 if (pCurPos
< Buffer
)
2458 ASSERT(pCurPos
<= Buffer
+ BufLength
);
2460 p
= memrchr(p0
, '\n', p0len
);
2463 for (j
= KdbNumberOfRowsTerminal
; j
--; )
2465 p1
= memrchr(p0
, '\n', p
-p0
);
2475 int linesCnt
= (KdbNumberOfColsTerminal
+prev_p
-p
-2) / KdbNumberOfColsTerminal
;
2485 /*!\brief Prints the given string with, page by page.
2487 * \param Buffer Characters buffer to print.
2488 * \param BufferLen Buffer size.
2490 * \note Doesn't correctly handle \\t and terminal escape sequences when calculating the
2491 * number of lines required to print a single line from the Buffer in the terminal.
2492 * Maximum length of buffer is limited only by memory size.
2494 * Note: BufLength should be greater then (KdbNumberOfRowsTerminal * KdbNumberOfColsTerminal).
2502 static CHAR InBuffer
[4096];
2503 static BOOLEAN TerminalInitialized
= FALSE
;
2504 static BOOLEAN TerminalConnected
= FALSE
;
2505 static BOOLEAN TerminalReportsSize
= TRUE
;
2510 LONG RowsPrintedByTerminal
;
2516 /* Check if the user has aborted output of the current command */
2517 if (KdbOutputAborted
)
2520 /* Initialize the terminal */
2521 if (!TerminalInitialized
)
2523 DbgPrint("\x1b[7h"); /* Enable linewrap */
2525 /* Query terminal type */
2526 /*DbgPrint("\x1b[Z");*/
2529 TerminalInitialized
= TRUE
;
2531 KeStallExecutionProcessor(100000);
2535 c
= KdbpTryGetCharSerial(5000);
2539 InBuffer
[Length
++] = c
;
2540 if (Length
>= (sizeof (InBuffer
) - 1))
2544 InBuffer
[Length
] = '\0';
2546 TerminalConnected
= TRUE
;
2549 /* Get number of rows and columns in terminal */
2550 if ((KdbNumberOfRowsTerminal
< 0) || (KdbNumberOfColsTerminal
< 0) ||
2551 (KdbNumberOfRowsPrinted
) == 0) /* Refresh terminal size each time when number of rows printed is 0 */
2553 if ((KdbDebugState
& KD_DEBUG_KDSERIAL
) && TerminalConnected
&& TerminalReportsSize
)
2555 /* Try to query number of rows from terminal. A reply looks like "\x1b[8;24;80t" */
2556 TerminalReportsSize
= FALSE
;
2557 KeStallExecutionProcessor(100000);
2558 DbgPrint("\x1b[18t");
2559 c
= KdbpTryGetCharSerial(5000);
2563 c
= KdbpTryGetCharSerial(5000);
2570 c
= KdbpTryGetCharSerial(5000);
2574 InBuffer
[Length
++] = c
;
2575 if (isalpha(c
) || Length
>= (sizeof (InBuffer
) - 1))
2579 InBuffer
[Length
] = '\0';
2580 if (InBuffer
[0] == '8' && InBuffer
[1] == ';')
2582 for (i
= 2; (i
< Length
) && (InBuffer
[i
] != ';'); i
++);
2584 if (Buffer
[i
] == ';')
2588 /* Number of rows is now at Buffer + 2 and number of cols at Buffer + i */
2589 KdbNumberOfRowsTerminal
= strtoul(InBuffer
+ 2, NULL
, 0);
2590 KdbNumberOfColsTerminal
= strtoul(InBuffer
+ i
, NULL
, 0);
2591 TerminalReportsSize
= TRUE
;
2595 /* Clear further characters */
2596 while ((c
= KdbpTryGetCharSerial(5000)) != -1);
2600 if (KdbNumberOfRowsTerminal
<= 0)
2602 /* Set number of rows to the default. */
2603 KdbNumberOfRowsTerminal
= 24;
2605 else if (KdbNumberOfColsTerminal
<= 0)
2607 /* Set number of cols to the default. */
2608 KdbNumberOfColsTerminal
= 80;
2612 /* Get the string */
2615 while (p
[0] != '\0')
2617 if ( p
> Buffer
+BufLength
)
2619 DbgPrint("Dmesg: error, p > Buffer+BufLength,d=%d", p
- (Buffer
+BufLength
));
2622 i
= strcspn(p
, "\n");
2624 // Are we out of buffer?
2625 if (p
+ i
> Buffer
+ BufLength
)
2626 // Leaving pager function:
2629 /* Calculate the number of lines which will be printed in the terminal
2630 * when outputting the current line
2633 RowsPrintedByTerminal
= (i
+ KdbNumberOfColsPrinted
- 1) / KdbNumberOfColsTerminal
;
2635 RowsPrintedByTerminal
= 0;
2638 RowsPrintedByTerminal
++;
2640 /*DbgPrint("!%d!%d!%d!%d!", KdbNumberOfRowsPrinted, KdbNumberOfColsPrinted, i, RowsPrintedByTerminal);*/
2642 /* Display a prompt if we printed one screen full of text */
2643 if (KdbNumberOfRowsTerminal
> 0 &&
2644 (LONG
)(KdbNumberOfRowsPrinted
+ RowsPrintedByTerminal
) >= KdbNumberOfRowsTerminal
)
2646 if (KdbNumberOfColsPrinted
> 0)
2649 DbgPrint("--- Press q to abort, e/End,h/Home,u/PgUp, other key/PgDn ---");
2650 RowsPrintedByTerminal
++;
2652 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
2653 c
= KdbpGetCharSerial();
2655 c
= KdbpGetCharKeyboard(&ScanCode
);
2659 /* Try to read '\n' which might follow '\r' - if \n is not received here
2660 * it will be interpreted as "return" when the next command should be read.
2662 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
2663 c
= KdbpTryGetCharSerial(5);
2665 c
= KdbpTryGetCharKeyboard(&ScanCode
, 5);
2668 //DbgPrint("\n"); //Consize version: don't show pressed key
2669 DbgPrint(" '%c'/scan=%04x\n", c
, ScanCode
); // Shows pressed key
2673 KdbOutputAborted
= TRUE
;
2676 if ( ScanCode
== KEYSC_END
|| c
=='e')
2678 PCHAR pBufEnd
= Buffer
+ BufLength
;
2679 p
= CountOnePageUp(Buffer
, BufLength
, pBufEnd
);
2680 i
= strcspn(p
, "\n");
2682 else if (ScanCode
== KEYSC_PAGEUP
|| c
=='u')
2684 p
= CountOnePageUp(Buffer
, BufLength
, p
);
2685 i
= strcspn(p
, "\n");
2687 else if (ScanCode
== KEYSC_HOME
|| c
=='h')
2690 i
= strcspn(p
, "\n");
2692 else if (ScanCode
== KEYSC_ARROWUP
)
2694 p
= CountOnePageUp(Buffer
, BufLength
, p
);
2695 i
= strcspn(p
, "\n");
2698 KdbNumberOfRowsPrinted
= 0;
2699 KdbNumberOfColsPrinted
= 0;
2702 /* Insert a NUL after the line and print only the current line. */
2703 if (p
[i
] == '\n' && p
[i
+ 1] != '\0')
2713 /* Remove escape sequences from the line if there's no terminal connected */
2714 if (!TerminalConnected
)
2716 while ((p2
= strrchr(p
, '\x1b'))) /* Look for escape character */
2721 while (!isalpha(p2
[j
++]));
2731 // The main printing of the current line:
2734 // restore not null char with saved:
2738 /* Set p to the start of the next line and
2739 * remember the number of rows/cols printed
2745 KdbNumberOfColsPrinted
= 0;
2749 ASSERT(p
[0] == '\0');
2750 KdbNumberOfColsPrinted
+= i
;
2753 KdbNumberOfRowsPrinted
+= RowsPrintedByTerminal
;
2757 /*!\brief Appends a command to the command history
2759 * \param Command Pointer to the command to append to the history.
2762 KdbpCommandHistoryAppend(
2765 ULONG Length1
= strlen(Command
) + 1;
2770 ASSERT(Length1
<= RTL_NUMBER_OF(KdbCommandHistoryBuffer
));
2773 (KdbCommandHistory
[KdbCommandHistoryIndex
] &&
2774 strcmp(KdbCommandHistory
[KdbCommandHistoryIndex
], Command
) == 0))
2779 /* Calculate Length1 and Length2 */
2780 Buffer
= KdbCommandHistoryBuffer
+ KdbCommandHistoryBufferIndex
;
2781 KdbCommandHistoryBufferIndex
+= Length1
;
2782 if (KdbCommandHistoryBufferIndex
>= (LONG
)RTL_NUMBER_OF(KdbCommandHistoryBuffer
))
2784 KdbCommandHistoryBufferIndex
-= RTL_NUMBER_OF(KdbCommandHistoryBuffer
);
2785 Length2
= KdbCommandHistoryBufferIndex
;
2789 /* Remove previous commands until there is enough space to append the new command */
2790 for (i
= KdbCommandHistoryIndex
; KdbCommandHistory
[i
];)
2793 (KdbCommandHistory
[i
] >= Buffer
||
2794 KdbCommandHistory
[i
] < (KdbCommandHistoryBuffer
+ KdbCommandHistoryBufferIndex
))) ||
2796 (KdbCommandHistory
[i
] >= Buffer
&&
2797 KdbCommandHistory
[i
] < (KdbCommandHistoryBuffer
+ KdbCommandHistoryBufferIndex
))))
2799 KdbCommandHistory
[i
] = NULL
;
2804 i
= RTL_NUMBER_OF(KdbCommandHistory
) - 1;
2806 if (i
== KdbCommandHistoryIndex
)
2810 /* Make sure the new command history entry is free */
2811 KdbCommandHistoryIndex
++;
2812 KdbCommandHistoryIndex
%= RTL_NUMBER_OF(KdbCommandHistory
);
2813 if (KdbCommandHistory
[KdbCommandHistoryIndex
])
2815 KdbCommandHistory
[KdbCommandHistoryIndex
] = NULL
;
2818 /* Append command */
2819 KdbCommandHistory
[KdbCommandHistoryIndex
] = Buffer
;
2820 ASSERT((KdbCommandHistory
[KdbCommandHistoryIndex
] + Length1
) <= KdbCommandHistoryBuffer
+ RTL_NUMBER_OF(KdbCommandHistoryBuffer
));
2821 memcpy(KdbCommandHistory
[KdbCommandHistoryIndex
], Command
, Length1
);
2824 memcpy(KdbCommandHistoryBuffer
, Command
+ Length1
, Length2
);
2828 /*!\brief Reads a line of user-input.
2830 * \param Buffer Buffer to store the input into. Trailing newlines are removed.
2831 * \param Size Size of \a Buffer.
2833 * \note Accepts only \n newlines, \r is ignored.
2841 PCHAR Orig
= Buffer
;
2844 static CHAR LastCommand
[1024] = "";
2845 static CHAR NextKey
= '\0';
2846 INT CmdHistIndex
= -1;
2849 EchoOn
= !((KdbDebugState
& KD_DEBUG_KDNOECHO
) != 0);
2853 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
2855 Key
= (NextKey
== '\0') ? KdbpGetCharSerial() : NextKey
;
2858 if (Key
== KEY_ESC
) /* ESC */
2860 Key
= KdbpGetCharSerial();
2863 Key
= KdbpGetCharSerial();
2868 ScanCode
= KEY_SCAN_UP
;
2871 ScanCode
= KEY_SCAN_DOWN
;
2884 Key
= (NextKey
== '\0') ? KdbpGetCharKeyboard(&ScanCode
) : NextKey
;
2888 if ((ULONG
)(Buffer
- Orig
) >= (Size
- 1))
2890 /* Buffer is full, accept only newlines */
2897 /* Read the next char - this is to throw away a \n which most clients should
2900 KeStallExecutionProcessor(100000);
2902 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
2903 NextKey
= KdbpTryGetCharSerial(5);
2905 NextKey
= KdbpTryGetCharKeyboard(&ScanCode
, 5);
2907 if (NextKey
== '\n' || NextKey
== -1) /* \n or no response at all */
2913 * Repeat the last command if the user presses enter. Reduces the
2914 * risk of RSI when single-stepping.
2918 RtlStringCbCopyA(Buffer
, Size
, LastCommand
);
2923 RtlStringCbCopyA(LastCommand
, sizeof(LastCommand
), Orig
);
2928 else if (Key
== KEY_BS
|| Key
== KEY_DEL
)
2936 KdbpPrint("%c %c", KEY_BS
, KEY_BS
);
2938 KdbpPrint(" %c", KEY_BS
);
2941 else if (ScanCode
== KEY_SCAN_UP
)
2943 BOOLEAN Print
= TRUE
;
2945 if (CmdHistIndex
< 0)
2947 CmdHistIndex
= KdbCommandHistoryIndex
;
2951 i
= CmdHistIndex
- 1;
2954 CmdHistIndex
= RTL_NUMBER_OF(KdbCommandHistory
) - 1;
2956 if (KdbCommandHistory
[i
] && i
!= KdbCommandHistoryIndex
)
2962 if (Print
&& KdbCommandHistory
[CmdHistIndex
])
2964 while (Buffer
> Orig
)
2970 KdbpPrint("%c %c", KEY_BS
, KEY_BS
);
2972 KdbpPrint(" %c", KEY_BS
);
2975 i
= min(strlen(KdbCommandHistory
[CmdHistIndex
]), Size
- 1);
2976 memcpy(Orig
, KdbCommandHistory
[CmdHistIndex
], i
);
2979 KdbpPrint("%s", Orig
);
2982 else if (ScanCode
== KEY_SCAN_DOWN
)
2984 if (CmdHistIndex
> 0 && CmdHistIndex
!= KdbCommandHistoryIndex
)
2986 i
= CmdHistIndex
+ 1;
2987 if (i
>= (INT
)RTL_NUMBER_OF(KdbCommandHistory
))
2990 if (KdbCommandHistory
[i
])
2993 while (Buffer
> Orig
)
2999 KdbpPrint("%c %c", KEY_BS
, KEY_BS
);
3001 KdbpPrint(" %c", KEY_BS
);
3004 i
= min(strlen(KdbCommandHistory
[CmdHistIndex
]), Size
- 1);
3005 memcpy(Orig
, KdbCommandHistory
[CmdHistIndex
], i
);
3008 KdbpPrint("%s", Orig
);
3015 KdbpPrint("%c", Key
);
3023 /*!\brief Parses command line and executes command if found
3025 * \param Command Command line to parse and execute if possible.
3027 * \retval TRUE Don't continue execution.
3028 * \retval FALSE Continue execution (leave KDB)
3037 static PCH Argv
[256];
3038 static CHAR OrigCommand
[1024];
3040 RtlStringCbCopyA(OrigCommand
, sizeof(OrigCommand
), Command
);
3047 while (*p
== '\t' || *p
== ' ')
3053 i
= strcspn(p
, "\t ");
3066 for (i
= 0; i
< RTL_NUMBER_OF(KdbDebuggerCommands
); i
++)
3068 if (!KdbDebuggerCommands
[i
].Name
)
3071 if (strcmp(KdbDebuggerCommands
[i
].Name
, Argv
[0]) == 0)
3073 return KdbDebuggerCommands
[i
].Fn(Argc
, Argv
);
3077 KdbpPrint("Command '%s' is unknown.\n", OrigCommand
);
3081 /*!\brief KDB Main Loop.
3083 * \param EnteredOnSingleStep TRUE if KDB was entered on single step.
3087 IN BOOLEAN EnteredOnSingleStep
)
3089 static CHAR Command
[1024];
3092 if (EnteredOnSingleStep
)
3094 if (!KdbSymPrintAddress((PVOID
)KdbCurrentTrapFrame
->Tf
.Eip
, &KdbCurrentTrapFrame
->Tf
))
3096 KdbpPrint("<%x>", KdbCurrentTrapFrame
->Tf
.Eip
);
3100 if (KdbpDisassemble(KdbCurrentTrapFrame
->Tf
.Eip
, KdbUseIntelSyntax
) < 0)
3102 KdbpPrint("<INVALID>");
3107 /* Flush the input buffer */
3108 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
3110 while (KdbpTryGetCharSerial(1) != -1);
3115 while (KdbpTryGetCharKeyboard(&ScanCode
, 1) != -1);
3121 /* Reset the number of rows/cols printed */
3122 KdbNumberOfRowsPrinted
= KdbNumberOfColsPrinted
= 0;
3124 /* Print the prompt */
3125 KdbpPrint("kdb:> ");
3127 /* Read a command and remember it */
3128 KdbpReadCommand(Command
, sizeof (Command
));
3129 KdbpCommandHistoryAppend(Command
);
3131 /* Reset the number of rows/cols printed and output aborted state */
3132 KdbNumberOfRowsPrinted
= KdbNumberOfColsPrinted
= 0;
3133 KdbOutputAborted
= FALSE
;
3135 /* Call the command */
3136 Continue
= KdbpDoCommand(Command
);
3137 KdbOutputAborted
= FALSE
;
3142 /*!\brief Called when a module is loaded.
3144 * \param Name Filename of the module which was loaded.
3147 KdbpCliModuleLoaded(
3148 IN PUNICODE_STRING Name
)
3150 if (!KdbBreakOnModuleLoad
)
3153 KdbpPrint("Module %wZ loaded.\n", Name
);
3154 DbgBreakPointWithStatus(DBG_STATUS_CONTROL_C
);
3157 /*!\brief This function is called by KdbEnterDebuggerException...
3159 * Used to interpret the init file in a context with a trapframe setup
3160 * (KdbpCliInit call KdbEnter which will call KdbEnterDebuggerException which will
3161 * call this function if KdbInitFileBuffer is not NULL.
3164 KdbpCliInterpretInitFile()
3170 /* Execute the commands in the init file */
3171 DPRINT("KDB: Executing KDBinit file...\n");
3172 p1
= KdbInitFileBuffer
;
3173 while (p1
[0] != '\0')
3175 i
= strcspn(p1
, "\r\n");
3181 /* Look for "break" command and comments */
3184 while (isspace(p2
[0]))
3187 if (strncmp(p2
, "break", sizeof("break")-1) == 0 &&
3188 (p2
[sizeof("break")-1] == '\0' || isspace(p2
[sizeof("break")-1])))
3190 /* break into the debugger */
3191 KdbpCliMainLoop(FALSE
);
3193 else if (p2
[0] != '#' && p2
[0] != '\0') /* Ignore empty lines and comments */
3202 while (p1
[0] == '\r' || p1
[0] == '\n')
3205 DPRINT("KDB: KDBinit executed\n");
3208 /*!\brief Called when KDB is initialized
3210 * Reads the KDBinit file from the SystemRoot\system32\drivers\etc directory and executes it.
3216 OBJECT_ATTRIBUTES ObjectAttributes
;
3217 UNICODE_STRING FileName
;
3218 IO_STATUS_BLOCK Iosb
;
3219 FILE_STANDARD_INFORMATION FileStdInfo
;
3220 HANDLE hFile
= NULL
;
3225 /* Initialize the object attributes */
3226 RtlInitUnicodeString(&FileName
, L
"\\SystemRoot\\system32\\drivers\\etc\\KDBinit");
3227 InitializeObjectAttributes(&ObjectAttributes
, &FileName
, 0, NULL
, NULL
);
3230 Status
= ZwOpenFile(&hFile
, FILE_READ_DATA
, &ObjectAttributes
, &Iosb
, 0,
3231 FILE_NON_DIRECTORY_FILE
| FILE_SYNCHRONOUS_IO_NONALERT
|
3232 FILE_NO_INTERMEDIATE_BUFFERING
);
3233 if (!NT_SUCCESS(Status
))
3235 DPRINT("Could not open \\SystemRoot\\system32\\drivers\\etc\\KDBinit (Status 0x%x)", Status
);
3239 /* Get the size of the file */
3240 Status
= ZwQueryInformationFile(hFile
, &Iosb
, &FileStdInfo
, sizeof (FileStdInfo
),
3241 FileStandardInformation
);
3242 if (!NT_SUCCESS(Status
))
3245 DPRINT("Could not query size of \\SystemRoot\\system32\\drivers\\etc\\KDBinit (Status 0x%x)", Status
);
3248 FileSize
= FileStdInfo
.EndOfFile
.u
.LowPart
;
3250 /* Allocate memory for the file */
3251 FileBuffer
= ExAllocatePool(PagedPool
, FileSize
+ 1); /* add 1 byte for terminating '\0' */
3255 DPRINT("Could not allocate %d bytes for KDBinit file\n", FileSize
);
3259 /* Load file into memory */
3260 Status
= ZwReadFile(hFile
, 0, 0, 0, &Iosb
, FileBuffer
, FileSize
, 0, 0);
3263 if (!NT_SUCCESS(Status
) && Status
!= STATUS_END_OF_FILE
)
3265 ExFreePool(FileBuffer
);
3266 DPRINT("Could not read KDBinit file into memory (Status 0x%lx)\n", Status
);
3270 FileSize
= min(FileSize
, (INT
)Iosb
.Information
);
3271 FileBuffer
[FileSize
] = '\0';
3273 /* Enter critical section */
3274 OldEflags
= __readeflags();
3277 /* Interpret the init file... */
3278 KdbInitFileBuffer
= FileBuffer
;
3280 KdbInitFileBuffer
= NULL
;
3282 /* Leave critical section */
3283 __writeeflags(OldEflags
);
3285 ExFreePool(FileBuffer
);
3290 KdpSerialDebugPrint(
3295 STRING KdpPromptString
= RTL_CONSTANT_STRING("kdb:> ");
3296 extern KSPIN_LOCK KdpSerialSpinLock
;
3300 KdpPrompt(IN LPSTR InString
,
3301 IN USHORT InStringLength
,
3302 OUT LPSTR OutString
,
3303 IN USHORT OutStringLength
)
3307 ULONG DummyScanCode
;
3310 /* Acquire the printing spinlock without waiting at raised IRQL */
3313 /* Wait when the spinlock becomes available */
3314 while (!KeTestSpinLock(&KdpSerialSpinLock
));
3316 /* Spinlock was free, raise IRQL */
3317 KeRaiseIrql(HIGH_LEVEL
, &OldIrql
);
3319 /* Try to get the spinlock */
3320 if (KeTryToAcquireSpinLockAtDpcLevel(&KdpSerialSpinLock
))
3323 /* Someone else got the spinlock, lower IRQL back */
3324 KeLowerIrql(OldIrql
);
3327 /* Loop the string to send */
3328 for (i
= 0; i
< InStringLength
; i
++)
3330 /* Print it to serial */
3331 KdPortPutByteEx(&SerialPortInfo
, *(PCHAR
)(InString
+ i
));
3334 /* Print a new line for log neatness */
3335 KdPortPutByteEx(&SerialPortInfo
, '\r');
3336 KdPortPutByteEx(&SerialPortInfo
, '\n');
3338 /* Print the kdb prompt */
3339 for (i
= 0; i
< KdpPromptString
.Length
; i
++)
3341 /* Print it to serial */
3342 KdPortPutByteEx(&SerialPortInfo
,
3343 *(KdpPromptString
.Buffer
+ i
));
3346 /* Loop the whole string */
3347 for (i
= 0; i
< OutStringLength
; i
++)
3349 /* Check if this is serial debugging mode */
3350 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
3352 /* Get the character from serial */
3355 Response
= KdbpTryGetCharSerial(MAXULONG
);
3356 } while (Response
== -1);
3360 /* Get the response from the keyboard */
3363 Response
= KdbpTryGetCharKeyboard(&DummyScanCode
, MAXULONG
);
3364 } while (Response
== -1);
3367 /* Check for return */
3368 if (Response
== '\r')
3371 * We might need to discard the next '\n'.
3372 * Wait a bit to make sure we receive it.
3374 KeStallExecutionProcessor(100000);
3376 /* Check the mode */
3377 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
3379 /* Read and discard the next character, if any */
3380 KdbpTryGetCharSerial(5);
3384 /* Read and discard the next character, if any */
3385 KdbpTryGetCharKeyboard(&DummyScanCode
, 5);
3389 * Null terminate the output string -- documentation states that
3390 * DbgPrompt does not null terminate, but it does
3392 *(PCHAR
)(OutString
+ i
) = 0;
3394 /* Print a new line */
3395 KdPortPutByteEx(&SerialPortInfo
, '\r');
3396 KdPortPutByteEx(&SerialPortInfo
, '\n');
3398 /* Release spinlock */
3399 KiReleaseSpinLock(&KdpSerialSpinLock
);
3401 /* Lower IRQL back */
3402 KeLowerIrql(OldIrql
);
3404 /* Return the length */
3405 return OutStringLength
+ 1;
3408 /* Write it back and print it to the log */
3409 *(PCHAR
)(OutString
+ i
) = Response
;
3410 KdPortPutByteEx(&SerialPortInfo
, Response
);
3413 /* Print a new line */
3414 KdPortPutByteEx(&SerialPortInfo
, '\r');
3415 KdPortPutByteEx(&SerialPortInfo
, '\n');
3417 /* Release spinlock */
3418 KiReleaseSpinLock(&KdpSerialSpinLock
);
3420 /* Lower IRQL back */
3421 KeLowerIrql(OldIrql
);
3423 /* Return the length */
3424 return OutStringLength
;