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 *******************************************************************/
38 #define NPX_STATE_NOT_LOADED 0xA
39 #define NPX_STATE_LOADED 0x0
45 #define KEY_SCAN_UP 72
46 #define KEY_SCAN_DOWN 80
48 #define KDB_ENTER_CONDITION_TO_STRING(cond) \
49 ((cond) == KdbDoNotEnter ? "never" : \
50 ((cond) == KdbEnterAlways ? "always" : \
51 ((cond) == KdbEnterFromKmode ? "kmode" : "umode")))
53 #define KDB_ACCESS_TYPE_TO_STRING(type) \
54 ((type) == KdbAccessRead ? "read" : \
55 ((type) == KdbAccessWrite ? "write" : \
56 ((type) == KdbAccessReadWrite ? "rdwr" : "exec")))
58 #define NPX_STATE_TO_STRING(state) \
59 ((state) == NPX_STATE_LOADED ? "Loaded" : \
60 ((state) == NPX_STATE_NOT_LOADED ? "Not loaded" : "Unknown"))
62 /* PROTOTYPES ****************************************************************/
64 static BOOLEAN
KdbpCmdEvalExpression(ULONG Argc
, PCHAR Argv
[]);
65 static BOOLEAN
KdbpCmdDisassembleX(ULONG Argc
, PCHAR Argv
[]);
66 static BOOLEAN
KdbpCmdRegs(ULONG Argc
, PCHAR Argv
[]);
67 static BOOLEAN
KdbpCmdBackTrace(ULONG Argc
, PCHAR Argv
[]);
69 static BOOLEAN
KdbpCmdContinue(ULONG Argc
, PCHAR Argv
[]);
70 static BOOLEAN
KdbpCmdStep(ULONG Argc
, PCHAR Argv
[]);
71 static BOOLEAN
KdbpCmdBreakPointList(ULONG Argc
, PCHAR Argv
[]);
72 static BOOLEAN
KdbpCmdEnableDisableClearBreakPoint(ULONG Argc
, PCHAR Argv
[]);
73 static BOOLEAN
KdbpCmdBreakPoint(ULONG Argc
, PCHAR Argv
[]);
75 static BOOLEAN
KdbpCmdThread(ULONG Argc
, PCHAR Argv
[]);
76 static BOOLEAN
KdbpCmdProc(ULONG Argc
, PCHAR Argv
[]);
78 static BOOLEAN
KdbpCmdMod(ULONG Argc
, PCHAR Argv
[]);
79 static BOOLEAN
KdbpCmdGdtLdtIdt(ULONG Argc
, PCHAR Argv
[]);
80 static BOOLEAN
KdbpCmdPcr(ULONG Argc
, PCHAR Argv
[]);
81 static BOOLEAN
KdbpCmdTss(ULONG Argc
, PCHAR Argv
[]);
83 static BOOLEAN
KdbpCmdBugCheck(ULONG Argc
, PCHAR Argv
[]);
84 static BOOLEAN
KdbpCmdFilter(ULONG Argc
, PCHAR Argv
[]);
85 static BOOLEAN
KdbpCmdSet(ULONG Argc
, PCHAR Argv
[]);
86 static BOOLEAN
KdbpCmdHelp(ULONG Argc
, PCHAR Argv
[]);
88 /* GLOBALS *******************************************************************/
90 static BOOLEAN KdbUseIntelSyntax
= FALSE
; /* Set to TRUE for intel syntax */
91 static BOOLEAN KdbBreakOnModuleLoad
= FALSE
; /* Set to TRUE to break into KDB when a module is loaded */
93 static CHAR KdbCommandHistoryBuffer
[2048]; /* Command history string ringbuffer */
94 static PCHAR KdbCommandHistory
[sizeof(KdbCommandHistoryBuffer
) / 8] = { NULL
}; /* Command history ringbuffer */
95 static LONG KdbCommandHistoryBufferIndex
= 0;
96 static LONG KdbCommandHistoryIndex
= 0;
98 static ULONG KdbNumberOfRowsPrinted
= 0;
99 static ULONG KdbNumberOfColsPrinted
= 0;
100 static BOOLEAN KdbOutputAborted
= FALSE
;
101 static LONG KdbNumberOfRowsTerminal
= -1;
102 static LONG KdbNumberOfColsTerminal
= -1;
104 PCHAR KdbInitFileBuffer
= NULL
; /* Buffer where KDBinit file is loaded into during initialization */
105 BOOLEAN KdbpBugCheckRequested
= FALSE
;
112 BOOLEAN (*Fn
)(ULONG Argc
, PCHAR Argv
[]);
113 } KdbDebuggerCommands
[] = {
115 { NULL
, NULL
, "Data", NULL
},
116 { "?", "? expression", "Evaluate expression.", KdbpCmdEvalExpression
},
117 { "disasm", "disasm [address] [L count]", "Disassemble count instructions at address.", KdbpCmdDisassembleX
},
118 { "x", "x [address] [L count]", "Display count dwords, starting at addr.", KdbpCmdDisassembleX
},
119 { "regs", "regs", "Display general purpose registers.", KdbpCmdRegs
},
120 { "cregs", "cregs", "Display control registers.", KdbpCmdRegs
},
121 { "sregs", "sregs", "Display status registers.", KdbpCmdRegs
},
122 { "dregs", "dregs", "Display debug registers.", KdbpCmdRegs
},
123 { "bt", "bt [*frameaddr|thread id]", "Prints current backtrace or from given frame addr", KdbpCmdBackTrace
},
126 { NULL
, NULL
, "Flow control", NULL
},
127 { "cont", "cont", "Continue execution (leave debugger)", KdbpCmdContinue
},
128 { "step", "step [count]", "Execute single instructions, stepping into interrupts.", KdbpCmdStep
},
129 { "next", "next [count]", "Execute single instructions, skipping calls and reps.", KdbpCmdStep
},
130 { "bl", "bl", "List breakpoints.", KdbpCmdBreakPointList
},
131 { "be", "be [breakpoint]", "Enable breakpoint.", KdbpCmdEnableDisableClearBreakPoint
},
132 { "bd", "bd [breakpoint]", "Disable breakpoint.", KdbpCmdEnableDisableClearBreakPoint
},
133 { "bc", "bc [breakpoint]", "Clear breakpoint.", KdbpCmdEnableDisableClearBreakPoint
},
134 { "bpx", "bpx [address] [IF condition]", "Set software execution breakpoint at address.", KdbpCmdBreakPoint
},
135 { "bpm", "bpm [r|w|rw|x] [byte|word|dword] [address] [IF condition]", "Set memory breakpoint at address.", KdbpCmdBreakPoint
},
138 { NULL
, NULL
, "Process/Thread", NULL
},
139 { "thread", "thread [list[ pid]|[attach ]tid]", "List threads in current or specified process, display thread with given id or attach to thread.", KdbpCmdThread
},
140 { "proc", "proc [list|[attach ]pid]", "List processes, display process with given id or attach to process.", KdbpCmdProc
},
142 /* System information */
143 { NULL
, NULL
, "System info", NULL
},
144 { "mod", "mod [address]", "List all modules or the one containing address.", KdbpCmdMod
},
145 { "gdt", "gdt", "Display global descriptor table.", KdbpCmdGdtLdtIdt
},
146 { "ldt", "ldt", "Display local descriptor table.", KdbpCmdGdtLdtIdt
},
147 { "idt", "idt", "Display interrupt descriptor table.", KdbpCmdGdtLdtIdt
},
148 { "pcr", "pcr", "Display processor control region.", KdbpCmdPcr
},
149 { "tss", "tss", "Display task state segment.", KdbpCmdTss
},
152 { NULL
, NULL
, "Others", NULL
},
153 { "bugcheck", "bugcheck", "Bugchecks the system.", KdbpCmdBugCheck
},
154 { "filter", "filter [error|warning|trace|info|level]+|-[componentname|default]", "Enable/disable debug channels", KdbpCmdFilter
},
155 { "set", "set [var] [value]", "Sets var to value or displays value of var.", KdbpCmdSet
},
156 { "help", "help", "Display help screen.", KdbpCmdHelp
}
159 /* FUNCTIONS *****************************************************************/
161 /*!\brief Transform a component name to an integer
163 * \param ComponentName The name of the component.
164 * \param ComponentId Receives the component id on success.
166 * \retval TRUE Success.
167 * \retval FALSE Failure.
171 IN PCCH ComponentName
,
172 OUT PULONG ComponentId
)
183 { "DEFAULT", DPFLTR_DEFAULT_ID
},
184 { "SYSTEM", DPFLTR_SYSTEM_ID
},
185 { "SMSS", DPFLTR_SMSS_ID
},
186 { "SETUP", DPFLTR_SETUP_ID
},
187 { "NTFS", DPFLTR_NTFS_ID
},
188 { "FSTUB", DPFLTR_FSTUB_ID
},
189 { "CRASHDUMP", DPFLTR_CRASHDUMP_ID
},
190 { "CDAUDIO", DPFLTR_CDAUDIO_ID
},
191 { "CDROM", DPFLTR_CDROM_ID
},
192 { "CLASSPNP", DPFLTR_CLASSPNP_ID
},
193 { "DISK", DPFLTR_DISK_ID
},
194 { "REDBOOK", DPFLTR_REDBOOK_ID
},
195 { "STORPROP", DPFLTR_STORPROP_ID
},
196 { "SCSIPORT", DPFLTR_SCSIPORT_ID
},
197 { "SCSIMINIPORT", DPFLTR_SCSIMINIPORT_ID
},
198 { "CONFIG", DPFLTR_CONFIG_ID
},
199 { "I8042PRT", DPFLTR_I8042PRT_ID
},
200 { "SERMOUSE", DPFLTR_SERMOUSE_ID
},
201 { "LSERMOUS", DPFLTR_LSERMOUS_ID
},
202 { "KBDHID", DPFLTR_KBDHID_ID
},
203 { "MOUHID", DPFLTR_MOUHID_ID
},
204 { "KBDCLASS", DPFLTR_KBDCLASS_ID
},
205 { "MOUCLASS", DPFLTR_MOUCLASS_ID
},
206 { "TWOTRACK", DPFLTR_TWOTRACK_ID
},
207 { "WMILIB", DPFLTR_WMILIB_ID
},
208 { "ACPI", DPFLTR_ACPI_ID
},
209 { "AMLI", DPFLTR_AMLI_ID
},
210 { "HALIA64", DPFLTR_HALIA64_ID
},
211 { "VIDEO", DPFLTR_VIDEO_ID
},
212 { "SVCHOST", DPFLTR_SVCHOST_ID
},
213 { "VIDEOPRT", DPFLTR_VIDEOPRT_ID
},
214 { "TCPIP", DPFLTR_TCPIP_ID
},
215 { "DMSYNTH", DPFLTR_DMSYNTH_ID
},
216 { "NTOSPNP", DPFLTR_NTOSPNP_ID
},
217 { "FASTFAT", DPFLTR_FASTFAT_ID
},
218 { "SAMSS", DPFLTR_SAMSS_ID
},
219 { "PNPMGR", DPFLTR_PNPMGR_ID
},
220 { "NETAPI", DPFLTR_NETAPI_ID
},
221 { "SCSERVER", DPFLTR_SCSERVER_ID
},
222 { "SCCLIENT", DPFLTR_SCCLIENT_ID
},
223 { "SERIAL", DPFLTR_SERIAL_ID
},
224 { "SERENUM", DPFLTR_SERENUM_ID
},
225 { "UHCD", DPFLTR_UHCD_ID
},
226 { "BOOTOK", DPFLTR_BOOTOK_ID
},
227 { "BOOTVRFY", DPFLTR_BOOTVRFY_ID
},
228 { "RPCPROXY", DPFLTR_RPCPROXY_ID
},
229 { "AUTOCHK", DPFLTR_AUTOCHK_ID
},
230 { "DCOMSS", DPFLTR_DCOMSS_ID
},
231 { "UNIMODEM", DPFLTR_UNIMODEM_ID
},
232 { "SIS", DPFLTR_SIS_ID
},
233 { "FLTMGR", DPFLTR_FLTMGR_ID
},
234 { "WMICORE", DPFLTR_WMICORE_ID
},
235 { "BURNENG", DPFLTR_BURNENG_ID
},
236 { "IMAPI", DPFLTR_IMAPI_ID
},
237 { "SXS", DPFLTR_SXS_ID
},
238 { "FUSION", DPFLTR_FUSION_ID
},
239 { "IDLETASK", DPFLTR_IDLETASK_ID
},
240 { "SOFTPCI", DPFLTR_SOFTPCI_ID
},
241 { "TAPE", DPFLTR_TAPE_ID
},
242 { "MCHGR", DPFLTR_MCHGR_ID
},
243 { "IDEP", DPFLTR_IDEP_ID
},
244 { "PCIIDE", DPFLTR_PCIIDE_ID
},
245 { "FLOPPY", DPFLTR_FLOPPY_ID
},
246 { "FDC", DPFLTR_FDC_ID
},
247 { "TERMSRV", DPFLTR_TERMSRV_ID
},
248 { "W32TIME", DPFLTR_W32TIME_ID
},
249 { "PREFETCHER", DPFLTR_PREFETCHER_ID
},
250 { "RSFILTER", DPFLTR_RSFILTER_ID
},
251 { "FCPORT", DPFLTR_FCPORT_ID
},
252 { "PCI", DPFLTR_PCI_ID
},
253 { "DMIO", DPFLTR_DMIO_ID
},
254 { "DMCONFIG", DPFLTR_DMCONFIG_ID
},
255 { "DMADMIN", DPFLTR_DMADMIN_ID
},
256 { "WSOCKTRANSPORT", DPFLTR_WSOCKTRANSPORT_ID
},
257 { "VSS", DPFLTR_VSS_ID
},
258 { "PNPMEM", DPFLTR_PNPMEM_ID
},
259 { "PROCESSOR", DPFLTR_PROCESSOR_ID
},
260 { "DMSERVER", DPFLTR_DMSERVER_ID
},
261 { "SR", DPFLTR_SR_ID
},
262 { "INFINIBAND", DPFLTR_INFINIBAND_ID
},
263 { "IHVDRIVER", DPFLTR_IHVDRIVER_ID
},
264 { "IHVVIDEO", DPFLTR_IHVVIDEO_ID
},
265 { "IHVAUDIO", DPFLTR_IHVAUDIO_ID
},
266 { "IHVNETWORK", DPFLTR_IHVNETWORK_ID
},
267 { "IHVSTREAMING", DPFLTR_IHVSTREAMING_ID
},
268 { "IHVBUS", DPFLTR_IHVBUS_ID
},
269 { "HPS", DPFLTR_HPS_ID
},
270 { "RTLTHREADPOOL", DPFLTR_RTLTHREADPOOL_ID
},
271 { "LDR", DPFLTR_LDR_ID
},
272 { "TCPIP6", DPFLTR_TCPIP6_ID
},
273 { "ISAPNP", DPFLTR_ISAPNP_ID
},
274 { "SHPC", DPFLTR_SHPC_ID
},
275 { "STORPORT", DPFLTR_STORPORT_ID
},
276 { "STORMINIPORT", DPFLTR_STORMINIPORT_ID
},
277 { "PRINTSPOOLER", DPFLTR_PRINTSPOOLER_ID
},
280 for (i
= 0; i
< sizeof(ComponentTable
) / sizeof(ComponentTable
[0]); i
++)
282 if (_stricmp(ComponentName
, ComponentTable
[i
].Name
) == 0)
284 *ComponentId
= ComponentTable
[i
].Id
;
292 /*!\brief Evaluates an expression...
294 * Much like KdbpRpnEvaluateExpression, but prints the error message (if any)
295 * at the given offset.
297 * \param Expression Expression to evaluate.
298 * \param ErrOffset Offset (in characters) to print the error message at.
299 * \param Result Receives the result on success.
301 * \retval TRUE Success.
302 * \retval FALSE Failure.
305 KdbpEvaluateExpression(
308 OUT PULONGLONG Result
)
310 static CHAR ErrMsgBuffer
[130] = "^ ";
311 LONG ExpressionErrOffset
= -1;
312 PCHAR ErrMsg
= ErrMsgBuffer
;
315 Ok
= KdbpRpnEvaluateExpression(Expression
, KdbCurrentTrapFrame
, Result
,
316 &ExpressionErrOffset
, ErrMsgBuffer
+ 2);
319 if (ExpressionErrOffset
>= 0)
320 ExpressionErrOffset
+= ErrOffset
;
324 KdbpPrint("%*s%s\n", ExpressionErrOffset
, "", ErrMsg
);
330 /*!\brief Evaluates an expression and displays the result.
333 KdbpCmdEvalExpression(
338 ULONGLONG Result
= 0;
345 KdbpPrint("?: Argument required\n");
349 /* Put the arguments back together */
351 for (i
= 1; i
< Argc
; i
++)
353 len
= strlen(Argv
[i
]);
357 /* Evaluate the expression */
358 Ok
= KdbpEvaluateExpression(Argv
[1], sizeof("kdb:> ")-1 + (Argv
[1]-Argv
[0]), &Result
);
361 if (Result
> 0x00000000ffffffffLL
)
363 if (Result
& 0x8000000000000000LL
)
364 KdbpPrint("0x%016I64x %20I64u %20I64d\n", Result
, Result
, Result
);
366 KdbpPrint("0x%016I64x %20I64u\n", Result
, Result
);
372 if (ul
<= 0xff && ul
>= 0x80)
373 l
= (LONG
)((CHAR
)ul
);
374 else if (ul
<= 0xffff && ul
>= 0x8000)
375 l
= (LONG
)((SHORT
)ul
);
380 KdbpPrint("0x%08lx %10lu %10ld\n", ul
, ul
, l
);
382 KdbpPrint("0x%08lx %10lu\n", ul
, ul
);
389 /*!\brief Display list of active debug channels
396 ULONG i
, j
, ComponentId
, Level
;
397 ULONG set
= DPFLTR_MASK
, clear
= DPFLTR_MASK
;
408 { "error", 1 << DPFLTR_ERROR_LEVEL
},
409 { "warning", 1 << DPFLTR_WARNING_LEVEL
},
410 { "trace", 1 << DPFLTR_TRACE_LEVEL
},
411 { "info", 1 << DPFLTR_INFO_LEVEL
},
414 for (i
= 1; i
< Argc
; i
++)
417 p
= opt
+ strcspn(opt
, "+-");
418 if (!p
[0]) p
= opt
; /* assume it's a debug channel name */
422 for (j
= 0; j
< sizeof(debug_classes
) / sizeof(debug_classes
[0]); j
++)
424 SIZE_T len
= strlen(debug_classes
[j
].Name
);
425 if (len
!= (p
- opt
))
427 if (_strnicmp(opt
, debug_classes
[j
].Name
, len
) == 0) /* found it */
430 set
|= debug_classes
[j
].Level
;
432 clear
|= debug_classes
[j
].Level
;
436 if (j
== sizeof(debug_classes
) / sizeof(debug_classes
[0]))
438 Level
= strtoul(opt
, &pend
, 0);
441 KdbpPrint("filter: bad class name '%.*s'\n", p
- opt
, opt
);
457 if (*p
== '+' || *p
== '-')
460 if (!KdbpGetComponentId(p
, &ComponentId
))
462 KdbpPrint("filter: '%s' is not a valid component name!\n", p
);
466 /* Get current mask value */
467 NtSetDebugFilterState(ComponentId
, set
, TRUE
);
468 NtSetDebugFilterState(ComponentId
, clear
, FALSE
);
474 /*!\brief Disassembles 10 instructions at eip or given address or
475 * displays 16 dwords from memory at given address.
485 ULONGLONG Result
= 0;
486 ULONG_PTR Address
= KdbCurrentTrapFrame
->Tf
.Eip
;
489 if (Argv
[0][0] == 'x') /* display memory */
491 else /* disassemble */
496 /* Check for [L count] part */
498 if (strcmp(Argv
[Argc
-2], "L") == 0)
500 ul
= strtoul(Argv
[Argc
-1], NULL
, 0);
507 else if (Argv
[Argc
-1][0] == 'L')
509 ul
= strtoul(Argv
[Argc
-1] + 1, NULL
, 0);
517 /* Put the remaining arguments back together */
519 for (ul
= 1; ul
< Argc
; ul
++)
521 Argv
[ul
][strlen(Argv
[ul
])] = ' ';
526 /* Evaluate the expression */
529 if (!KdbpEvaluateExpression(Argv
[1], sizeof("kdb:> ")-1 + (Argv
[1]-Argv
[0]), &Result
))
532 if (Result
> (ULONGLONG
)(~((ULONG_PTR
)0)))
533 KdbpPrint("Warning: Address %I64x is beeing truncated\n");
535 Address
= (ULONG_PTR
)Result
;
537 else if (Argv
[0][0] == 'x')
539 KdbpPrint("x: Address argument required.\n");
543 if (Argv
[0][0] == 'x')
550 if (!KdbSymPrintAddress((PVOID
)Address
))
551 KdbpPrint("<%x>:", Address
);
560 if (!NT_SUCCESS(KdbpSafeReadMemory(&ul
, (PVOID
)Address
, sizeof(ul
))))
561 KdbpPrint(" ????????");
563 KdbpPrint(" %x", ul
);
565 Address
+= sizeof(ul
);
576 if (!KdbSymPrintAddress((PVOID
)Address
))
577 KdbpPrint("<%x>: ", Address
);
581 InstLen
= KdbpDisassemble(Address
, KdbUseIntelSyntax
);
584 KdbpPrint("<INVALID>\n");
596 /*!\brief Displays CPU registers.
603 PKTRAP_FRAME Tf
= &KdbCurrentTrapFrame
->Tf
;
605 const PCHAR EflagsBits
[64] = { " CF", NULL
, " PF", " BIT3", " AF", " BIT5",
606 " ZF", " SF", " TF", " IF", " DF", " OF",
607 NULL
, NULL
, " NT", " BIT15", " RF", " VF",
608 " AC", " VIF", " VIP", " ID", " BIT22",
609 " BIT23", " BIT24", " BIT25", " BIT26",
610 " BIT27", " BIT28", " BIT29", " BIT30",
611 " BIT31", " BIT32", " BIT33", " BIT34",
612 " BIT35", " BIT36", " BIT37", " BIT38",
613 " BIT39", " BIT40", " BIT41", " BIT42",
614 " BIT43", " BIT44", " BIT45", " BIT46",
615 " BIT47", " BIT48", " BIT49", " BIT50",
616 " BIT51", " BIT52", " BIT53", " BIT54",
617 " BIT55", " BIT56", " BIT57", " BIT58",
618 " BIT59", " BIT60", " BIT61", " BIT62",
622 if (Argv
[0][0] == 'r') /* regs */
625 KdbpPrint("CS:EIP 0x%04x:0x%08x\n"
626 "SS:ESP 0x%04x:0x%08x\n"
627 " EAX 0x%08x EBX 0x%08x\n"
628 " ECX 0x%08x EDX 0x%08x\n"
629 " ESI 0x%08x EDI 0x%08x\n"
631 Tf
->SegCs
& 0xFFFF, Tf
->Eip
,
632 Tf
->HardwareSegSs
, Tf
->HardwareEsp
,
637 #elif defined(_M_AMD64)
638 KdbpPrint("CS:RIP 0x%04x:0x%p\n"
639 "SS:RSP 0x%04x:0x%p\n"
640 " RAX 0x%p RBX 0x%p\n"
641 " RCX 0x%p RDX 0x%p\n"
642 " RSI 0x%p RDI 0x%p\n"
643 " RBP 0x%p R8 0x%p\n"
644 " R9 0x%p R10 0x%p\n"
646 Tf
->SegCs
& 0xFFFF, Tf
->Rip
,
655 KdbpPrint("EFLAGS 0x%08x ", Tf
->EFlags
);
658 for (i
= 0; i
< 32; i
++)
659 #elif defined(_M_AMD64)
660 for (i
= 0; i
< 64; i
++)
665 if ((Tf
->EFlags
& (1 << 1)) == 0)
670 KdbpPrint(" IOPL%d", (Tf
->EFlags
>> 12) & 3);
675 else if ((Tf
->EFlags
& (1 << i
)) != 0)
677 KdbpPrint(EflagsBits
[i
]);
683 else if (Argv
[0][0] == 'c') /* cregs */
685 ULONG_PTR Cr0
, Cr2
, Cr3
, Cr4
;
686 KDESCRIPTOR Gdtr
, Idtr
;
689 Ke386GetGlobalDescriptorTable(&Gdtr
.Limit
);
690 Ldtr
= Ke386GetLocalDescriptorTable();
691 #elif defined(_M_AMD64)
694 static const PCHAR Cr0Bits
[32] = { " PE", " MP", " EM", " TS", " ET", " NE", NULL
, NULL
,
695 NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
,
696 " WP", NULL
, " AM", NULL
, NULL
, NULL
, NULL
, NULL
,
697 NULL
, NULL
, NULL
, NULL
, NULL
, " NW", " CD", " PG" };
698 static const PCHAR Cr4Bits
[32] = { " VME", " PVI", " TSD", " DE", " PSE", " PAE", " MCE", " PGE",
699 " PCE", " OSFXSR", " OSXMMEXCPT", NULL
, NULL
, NULL
, NULL
, NULL
,
700 NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
,
701 NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
};
703 Cr0
= KdbCurrentTrapFrame
->Cr0
;
704 Cr2
= KdbCurrentTrapFrame
->Cr2
;
705 Cr3
= KdbCurrentTrapFrame
->Cr3
;
706 Cr4
= KdbCurrentTrapFrame
->Cr4
;
708 /* Get interrupt descriptor table regs */
711 /* Display the control registers */
712 KdbpPrint("CR0 0x%p ", Cr0
);
714 for (i
= 0; i
< 32; i
++)
719 if ((Cr0
& (1 << i
)) != 0)
720 KdbpPrint(Cr0Bits
[i
]);
723 KdbpPrint("\nCR2 0x%p\n", Cr2
);
724 KdbpPrint("CR3 0x%p Pagedir-Base 0x%p %s%s\n", Cr3
, (Cr3
& 0xfffff000),
725 (Cr3
& (1 << 3)) ? " PWT" : "", (Cr3
& (1 << 4)) ? " PCD" : "" );
726 KdbpPrint("CR4 0x%p ", Cr4
);
728 for (i
= 0; i
< 32; i
++)
733 if ((Cr4
& (1 << i
)) != 0)
734 KdbpPrint(Cr4Bits
[i
]);
737 /* Display the descriptor table regs */
738 KdbpPrint("\nGDTR Base 0x%p Size 0x%04x\n", Gdtr
.Base
, Gdtr
.Limit
);
740 KdbpPrint("LDTR 0x%p\n", Ldtr
);
742 KdbpPrint("IDTR Base 0x%p Size 0x%04x\n", Idtr
.Base
, Idtr
.Limit
);
744 else if (Argv
[0][0] == 's') /* sregs */
746 KdbpPrint("CS 0x%04x Index 0x%04x %cDT RPL%d\n",
747 Tf
->SegCs
& 0xffff, (Tf
->SegCs
& 0xffff) >> 3,
748 (Tf
->SegCs
& (1 << 2)) ? 'L' : 'G', Tf
->SegCs
& 3);
749 KdbpPrint("DS 0x%04x Index 0x%04x %cDT RPL%d\n",
750 Tf
->SegDs
, Tf
->SegDs
>> 3, (Tf
->SegDs
& (1 << 2)) ? 'L' : 'G', Tf
->SegDs
& 3);
751 KdbpPrint("ES 0x%04x Index 0x%04x %cDT RPL%d\n",
752 Tf
->SegEs
, Tf
->SegEs
>> 3, (Tf
->SegEs
& (1 << 2)) ? 'L' : 'G', Tf
->SegEs
& 3);
753 KdbpPrint("FS 0x%04x Index 0x%04x %cDT RPL%d\n",
754 Tf
->SegFs
, Tf
->SegFs
>> 3, (Tf
->SegFs
& (1 << 2)) ? 'L' : 'G', Tf
->SegFs
& 3);
755 KdbpPrint("GS 0x%04x Index 0x%04x %cDT RPL%d\n",
756 Tf
->SegGs
, Tf
->SegGs
>> 3, (Tf
->SegGs
& (1 << 2)) ? 'L' : 'G', Tf
->SegGs
& 3);
758 KdbpPrint("SS 0x%04x Index 0x%04x %cDT RPL%d\n",
759 Tf
->HardwareSegSs
, Tf
->HardwareSegSs
>> 3, (Tf
->HardwareSegSs
& (1 << 2)) ? 'L' : 'G', Tf
->HardwareSegSs
& 3);
761 KdbpPrint("SS 0x%04x Index 0x%04x %cDT RPL%d\n",
762 Tf
->SegSs
, Tf
->SegSs
>> 3, (Tf
->SegSs
& (1 << 2)) ? 'L' : 'G', Tf
->SegSs
& 3);
768 ASSERT(Argv
[0][0] == 'd');
769 KdbpPrint("DR0 0x%p\n"
775 Tf
->Dr0
, Tf
->Dr1
, Tf
->Dr2
, Tf
->Dr3
,
782 /*!\brief Displays a backtrace.
791 ULONGLONG Result
= 0;
793 ULONG_PTR Frame
= KdbCurrentTrapFrame
->Tf
.Ebp
;
794 #elif defined(_M_AMD64)
795 ULONG_PTR Frame
= KdbCurrentTrapFrame
->Tf
.Rbp
;
801 /* Check for [L count] part */
804 if (strcmp(Argv
[Argc
-2], "L") == 0)
806 ul
= strtoul(Argv
[Argc
-1], NULL
, 0);
813 else if (Argv
[Argc
-1][0] == 'L')
815 ul
= strtoul(Argv
[Argc
-1] + 1, NULL
, 0);
823 /* Put the remaining arguments back together */
825 for (ul
= 1; ul
< Argc
; ul
++)
827 Argv
[ul
][strlen(Argv
[ul
])] = ' ';
832 /* Check if frame addr or thread id is given. */
835 if (Argv
[1][0] == '*')
839 /* Evaluate the expression */
840 if (!KdbpEvaluateExpression(Argv
[1], sizeof("kdb:> ")-1 + (Argv
[1]-Argv
[0]), &Result
))
843 if (Result
> (ULONGLONG
)(~((ULONG_PTR
)0)))
844 KdbpPrint("Warning: Address %I64x is beeing truncated\n");
846 Frame
= (ULONG_PTR
)Result
;
850 KdbpPrint("Thread backtrace not supported yet!\n");
858 /* Try printing the function at EIP */
859 if (!KdbSymPrintAddress((PVOID
)KdbCurrentTrapFrame
->Tf
.Eip
))
860 KdbpPrint("<%x>\n", KdbCurrentTrapFrame
->Tf
.Eip
);
865 KdbpPrint("Frames:\n");
871 if (!NT_SUCCESS(KdbpSafeReadMemory(&Address
, (PVOID
)(Frame
+ sizeof(ULONG_PTR
)), sizeof (ULONG_PTR
))))
873 KdbpPrint("Couldn't access memory at 0x%p!\n", Frame
+ sizeof(ULONG_PTR
));
877 if (!KdbSymPrintAddress((PVOID
)Address
))
878 KdbpPrint("<%x>\n", Address
);
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_PTR
)(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 (_stricmp(Argv
[2], "qword") == 0)
1138 else if (AccessType
== KdbAccessExec
)
1145 KdbpPrint("bpm: Unknown memory size '%s'\n", Argv
[2]);
1149 if (Argc
<= AddressArgIndex
)
1151 KdbpPrint("bpm: Address argument required.\n");
1155 Type
= KdbBreakPointHardware
;
1158 /* Put the arguments back together */
1159 ConditionArgIndex
= -1;
1160 for (i
= AddressArgIndex
; i
< (Argc
-1); i
++)
1162 if (strcmp(Argv
[i
+1], "IF") == 0) /* IF found */
1164 ConditionArgIndex
= i
+ 2;
1165 if (ConditionArgIndex
>= Argc
)
1167 KdbpPrint("%s: IF requires condition expression.\n", Argv
[0]);
1171 for (i
= ConditionArgIndex
; i
< (Argc
-1); i
++)
1172 Argv
[i
][strlen(Argv
[i
])] = ' ';
1177 Argv
[i
][strlen(Argv
[i
])] = ' ';
1180 /* Evaluate the address expression */
1181 if (!KdbpEvaluateExpression(Argv
[AddressArgIndex
],
1182 sizeof("kdb:> ")-1 + (Argv
[AddressArgIndex
]-Argv
[0]),
1188 if (Result
> (ULONGLONG
)(~((ULONG_PTR
)0)))
1189 KdbpPrint("%s: Warning: Address %I64x is beeing truncated\n", Argv
[0]);
1191 Address
= (ULONG_PTR
)Result
;
1193 KdbpInsertBreakPoint(Address
, Type
, Size
, AccessType
,
1194 (ConditionArgIndex
< 0) ? NULL
: Argv
[ConditionArgIndex
],
1200 /*!\brief Lists threads or switches to another thread context.
1208 PETHREAD Thread
= NULL
;
1209 PEPROCESS Process
= NULL
;
1210 BOOLEAN ReferencedThread
= FALSE
, ReferencedProcess
= FALSE
;
1215 PCHAR State
, pend
, str1
, str2
;
1216 static const PCHAR ThreadStateToString
[DeferredReady
+1] =
1218 "Initialized", "Ready", "Running",
1219 "Standby", "Terminated", "Waiting",
1220 "Transition", "DeferredReady"
1223 ASSERT(KdbCurrentProcess
);
1225 if (Argc
>= 2 && _stricmp(Argv
[1], "list") == 0)
1227 Process
= KdbCurrentProcess
;
1231 ul
= strtoul(Argv
[2], &pend
, 0);
1232 if (Argv
[2] == pend
)
1234 KdbpPrint("thread: '%s' is not a valid process id!\n", Argv
[2]);
1238 if (!NT_SUCCESS(PsLookupProcessByProcessId((PVOID
)ul
, &Process
)))
1240 KdbpPrint("thread: Invalid process id!\n");
1244 /* Remember our reference */
1245 ReferencedProcess
= TRUE
;
1248 Entry
= Process
->ThreadListHead
.Flink
;
1249 if (Entry
== &Process
->ThreadListHead
)
1252 KdbpPrint("No threads in process 0x%08x!\n", ul
);
1254 KdbpPrint("No threads in current process!\n");
1256 if (ReferencedProcess
)
1257 ObDereferenceObject(Process
);
1262 KdbpPrint(" TID State Prior. Affinity EBP EIP\n");
1265 Thread
= CONTAINING_RECORD(Entry
, ETHREAD
, ThreadListEntry
);
1267 if (Thread
== KdbCurrentThread
)
1278 if (Thread
->Tcb
.TrapFrame
)
1281 if (Thread
->Tcb
.TrapFrame
->PreviousPreviousMode
== KernelMode
)
1282 Esp
= (PULONG
)Thread
->Tcb
.TrapFrame
->TempEsp
;
1284 Esp
= (PULONG
)Thread
->Tcb
.TrapFrame
->HardwareEsp
;
1286 Ebp
= (PULONG
)Thread
->Tcb
.TrapFrame
->Ebp
;
1287 Eip
= Thread
->Tcb
.TrapFrame
->Eip
;
1289 #elif defined(_M_AMD64)
1290 Esp
= (PULONG_PTR
)Thread
->Tcb
.TrapFrame
->Rsp
;
1292 Ebp
= (PULONG_PTR
)Thread
->Tcb
.TrapFrame
->Rbp
;
1293 Eip
= Thread
->Tcb
.TrapFrame
->Eip
;
1298 Esp
= (PULONG_PTR
)Thread
->Tcb
.KernelStack
;
1299 Ebp
= (PULONG_PTR
)Esp
[4];
1302 if (Ebp
) /* FIXME: Should we attach to the process to read Ebp[1]? */
1303 KdbpSafeReadMemory(&Eip
, Ebp
+ 1, sizeof (Eip
));
1306 if (Thread
->Tcb
.State
< (DeferredReady
+ 1))
1307 State
= ThreadStateToString
[Thread
->Tcb
.State
];
1311 KdbpPrint(" %s0x%p %-11s %3d 0x%p 0x%p 0x%p%s\n",
1313 Thread
->Cid
.UniqueThread
,
1315 Thread
->Tcb
.Priority
,
1316 Thread
->Tcb
.Affinity
,
1321 Entry
= Entry
->Flink
;
1323 while (Entry
!= &Process
->ThreadListHead
);
1325 /* Release our reference, if any */
1326 if (ReferencedProcess
)
1327 ObDereferenceObject(Process
);
1329 else if (Argc
>= 2 && _stricmp(Argv
[1], "attach") == 0)
1333 KdbpPrint("thread attach: thread id argument required!\n");
1337 ul
= strtoul(Argv
[2], &pend
, 0);
1338 if (Argv
[2] == pend
)
1340 KdbpPrint("thread attach: '%s' is not a valid thread id!\n", Argv
[2]);
1344 if (!KdbpAttachToThread((PVOID
)ul
))
1349 KdbpPrint("Attached to thread 0x%08x.\n", ul
);
1353 Thread
= KdbCurrentThread
;
1357 ul
= strtoul(Argv
[1], &pend
, 0);
1358 if (Argv
[1] == pend
)
1360 KdbpPrint("thread: '%s' is not a valid thread id!\n", Argv
[1]);
1364 if (!NT_SUCCESS(PsLookupThreadByThreadId((PVOID
)ul
, &Thread
)))
1366 KdbpPrint("thread: Invalid thread id!\n");
1370 /* Remember our reference */
1371 ReferencedThread
= TRUE
;
1374 if (Thread
->Tcb
.State
< (DeferredReady
+ 1))
1375 State
= ThreadStateToString
[Thread
->Tcb
.State
];
1381 " State: %s (0x%x)\n"
1383 " Affinity: 0x%08x\n"
1384 " Initial Stack: 0x%p\n"
1385 " Stack Limit: 0x%p\n"
1386 " Stack Base: 0x%p\n"
1387 " Kernel Stack: 0x%p\n"
1388 " Trap Frame: 0x%p\n"
1389 " NPX State: %s (0x%x)\n",
1390 (Argc
< 2) ? "Current Thread:\n" : "",
1391 Thread
->Cid
.UniqueThread
,
1392 State
, Thread
->Tcb
.State
,
1393 Thread
->Tcb
.Priority
,
1394 Thread
->Tcb
.Affinity
,
1395 Thread
->Tcb
.InitialStack
,
1396 Thread
->Tcb
.StackLimit
,
1397 Thread
->Tcb
.StackBase
,
1398 Thread
->Tcb
.KernelStack
,
1399 Thread
->Tcb
.TrapFrame
,
1400 NPX_STATE_TO_STRING(Thread
->Tcb
.NpxState
), Thread
->Tcb
.NpxState
);
1402 /* Release our reference if we had one */
1403 if (ReferencedThread
)
1404 ObDereferenceObject(Thread
);
1410 /*!\brief Lists processes or switches to another process context.
1419 BOOLEAN ReferencedProcess
= FALSE
;
1420 PCHAR State
, pend
, str1
, str2
;
1422 extern LIST_ENTRY PsActiveProcessHead
;
1424 if (Argc
>= 2 && _stricmp(Argv
[1], "list") == 0)
1426 Entry
= PsActiveProcessHead
.Flink
;
1427 if (!Entry
|| Entry
== &PsActiveProcessHead
)
1429 KdbpPrint("No processes in the system!\n");
1433 KdbpPrint(" PID State Filename\n");
1436 Process
= CONTAINING_RECORD(Entry
, EPROCESS
, ActiveProcessLinks
);
1438 if (Process
== KdbCurrentProcess
)
1449 State
= ((Process
->Pcb
.State
== ProcessInMemory
) ? "In Memory" :
1450 ((Process
->Pcb
.State
== ProcessOutOfMemory
) ? "Out of Memory" : "In Transition"));
1452 KdbpPrint(" %s0x%08x %-10s %s%s\n",
1454 Process
->UniqueProcessId
,
1456 Process
->ImageFileName
,
1459 Entry
= Entry
->Flink
;
1461 while(Entry
!= &PsActiveProcessHead
);
1463 else if (Argc
>= 2 && _stricmp(Argv
[1], "attach") == 0)
1467 KdbpPrint("process attach: process id argument required!\n");
1471 ul
= strtoul(Argv
[2], &pend
, 0);
1472 if (Argv
[2] == pend
)
1474 KdbpPrint("process attach: '%s' is not a valid process id!\n", Argv
[2]);
1478 if (!KdbpAttachToProcess((PVOID
)ul
))
1483 KdbpPrint("Attached to process 0x%x, thread 0x%x.\n", ul
,
1484 (ULONG_PTR
)KdbCurrentThread
->Cid
.UniqueThread
);
1488 Process
= KdbCurrentProcess
;
1492 ul
= strtoul(Argv
[1], &pend
, 0);
1493 if (Argv
[1] == pend
)
1495 KdbpPrint("proc: '%s' is not a valid process id!\n", Argv
[1]);
1499 if (!NT_SUCCESS(PsLookupProcessByProcessId((PVOID
)ul
, &Process
)))
1501 KdbpPrint("proc: Invalid process id!\n");
1505 /* Remember our reference */
1506 ReferencedProcess
= TRUE
;
1509 State
= ((Process
->Pcb
.State
== ProcessInMemory
) ? "In Memory" :
1510 ((Process
->Pcb
.State
== ProcessOutOfMemory
) ? "Out of Memory" : "In Transition"));
1513 " State: %s (0x%x)\n"
1514 " Image Filename: %s\n",
1515 (Argc
< 2) ? "Current process:\n" : "",
1516 Process
->UniqueProcessId
,
1517 State
, Process
->Pcb
.State
,
1518 Process
->ImageFileName
);
1520 /* Release our reference, if any */
1521 if (ReferencedProcess
)
1522 ObDereferenceObject(Process
);
1528 /*!\brief Lists loaded modules or the one containing the specified address.
1535 ULONGLONG Result
= 0;
1537 PLDR_DATA_TABLE_ENTRY LdrEntry
;
1538 BOOLEAN DisplayOnlyOneModule
= FALSE
;
1543 /* Put the arguments back together */
1546 Argv
[Argc
][strlen(Argv
[Argc
])] = ' ';
1548 /* Evaluate the expression */
1549 if (!KdbpEvaluateExpression(Argv
[1], sizeof("kdb:> ")-1 + (Argv
[1]-Argv
[0]), &Result
))
1554 if (Result
> (ULONGLONG
)(~((ULONG_PTR
)0)))
1555 KdbpPrint("%s: Warning: Address %I64x is beeing truncated\n", Argv
[0]);
1557 Address
= (ULONG_PTR
)Result
;
1559 if (!KdbpSymFindModule((PVOID
)Address
, NULL
, -1, &LdrEntry
))
1561 KdbpPrint("No module containing address 0x%p found!\n", Address
);
1565 DisplayOnlyOneModule
= TRUE
;
1569 if (!KdbpSymFindModule(NULL
, NULL
, 0, &LdrEntry
))
1571 ULONG_PTR ntoskrnlBase
= ((ULONG_PTR
)KdbpCmdMod
) & 0xfff00000;
1572 KdbpPrint(" Base Size Name\n");
1573 KdbpPrint(" %p %x %s\n", ntoskrnlBase
, 0, "ntoskrnl.exe");
1580 KdbpPrint(" Base Size Name\n");
1583 KdbpPrint(" %p %x %wZ\n", LdrEntry
->DllBase
, LdrEntry
->SizeOfImage
, &LdrEntry
->BaseDllName
);
1585 if(DisplayOnlyOneModule
|| !KdbpSymFindModule(NULL
, NULL
, i
++, &LdrEntry
))
1592 /*!\brief Displays GDT, LDT or IDTd.
1609 if (Argv
[0][0] == 'i')
1616 KdbpPrint("Interrupt descriptor table is empty.\n");
1620 KdbpPrint("IDT Base: 0x%08x Limit: 0x%04x\n", Reg
.Base
, Reg
.Limit
);
1621 KdbpPrint(" Idx Type Seg. Sel. Offset DPL\n");
1623 for (i
= 0; (i
+ sizeof(SegDesc
) - 1) <= Reg
.Limit
; i
+= 8)
1625 if (!NT_SUCCESS(KdbpSafeReadMemory(SegDesc
, (PVOID
)((ULONG_PTR
)Reg
.Base
+ i
), sizeof(SegDesc
))))
1627 KdbpPrint("Couldn't access memory at 0x%08x!\n", (ULONG_PTR
)Reg
.Base
+ i
);
1631 Dpl
= ((SegDesc
[1] >> 13) & 3);
1632 if ((SegDesc
[1] & 0x1f00) == 0x0500) /* Task gate */
1633 SegType
= "TASKGATE";
1634 else if ((SegDesc
[1] & 0x1fe0) == 0x0e00) /* 32 bit Interrupt gate */
1635 SegType
= "INTGATE32";
1636 else if ((SegDesc
[1] & 0x1fe0) == 0x0600) /* 16 bit Interrupt gate */
1637 SegType
= "INTGATE16";
1638 else if ((SegDesc
[1] & 0x1fe0) == 0x0f00) /* 32 bit Trap gate */
1639 SegType
= "TRAPGATE32";
1640 else if ((SegDesc
[1] & 0x1fe0) == 0x0700) /* 16 bit Trap gate */
1641 SegType
= "TRAPGATE16";
1643 SegType
= "UNKNOWN";
1645 if ((SegDesc
[1] & (1 << 15)) == 0) /* not present */
1647 KdbpPrint(" %03d %-10s [NP] [NP] %02d\n",
1648 i
/ 8, SegType
, Dpl
);
1650 else if ((SegDesc
[1] & 0x1f00) == 0x0500) /* Task gate */
1652 SegSel
= SegDesc
[0] >> 16;
1653 KdbpPrint(" %03d %-10s 0x%04x %02d\n",
1654 i
/ 8, SegType
, SegSel
, Dpl
);
1658 SegSel
= SegDesc
[0] >> 16;
1659 SegBase
= (SegDesc
[1] & 0xffff0000) | (SegDesc
[0] & 0x0000ffff);
1660 KdbpPrint(" %03d %-10s 0x%04x 0x%08x %02d\n",
1661 i
/ 8, SegType
, SegSel
, SegBase
, Dpl
);
1669 if (Argv
[0][0] == 'g')
1673 Ke386GetGlobalDescriptorTable(&Reg
.Limit
);
1674 #elif defined(_M_AMD64)
1681 ASSERT(Argv
[0][0] == 'l');
1685 Reg
.Limit
= Ke386GetLocalDescriptorTable();
1686 #elif defined(_M_AMD64)
1696 KdbpPrint("%s descriptor table is empty.\n",
1697 Argv
[0][0] == 'g' ? "Global" : "Local");
1701 KdbpPrint("%cDT Base: 0x%08x Limit: 0x%04x\n",
1702 Argv
[0][0] == 'g' ? 'G' : 'L', Reg
.Base
, Reg
.Limit
);
1703 KdbpPrint(" Idx Sel. Type Base Limit DPL Attribs\n");
1705 for (; (i
+ sizeof(SegDesc
) - 1) <= Reg
.Limit
; i
+= 8)
1707 if (!NT_SUCCESS(KdbpSafeReadMemory(SegDesc
, (PVOID
)((ULONG_PTR
)Reg
.Base
+ i
), sizeof(SegDesc
))))
1709 KdbpPrint("Couldn't access memory at 0x%08x!\n", (ULONG_PTR
)Reg
.Base
+ i
);
1713 Dpl
= ((SegDesc
[1] >> 13) & 3);
1714 Type
= ((SegDesc
[1] >> 8) & 0xf);
1716 SegBase
= SegDesc
[0] >> 16;
1717 SegBase
|= (SegDesc
[1] & 0xff) << 16;
1718 SegBase
|= SegDesc
[1] & 0xff000000;
1719 SegLimit
= SegDesc
[0] & 0x0000ffff;
1720 SegLimit
|= (SegDesc
[1] >> 16) & 0xf;
1722 if ((SegDesc
[1] & (1 << 23)) != 0)
1732 if ((SegDesc
[1] & (1 << 12)) == 0) /* System segment */
1736 case 1: SegType
= "TSS16(Avl)"; break;
1737 case 2: SegType
= "LDT"; break;
1738 case 3: SegType
= "TSS16(Busy)"; break;
1739 case 4: SegType
= "CALLGATE16"; break;
1740 case 5: SegType
= "TASKGATE"; break;
1741 case 6: SegType
= "INTGATE16"; break;
1742 case 7: SegType
= "TRAPGATE16"; break;
1743 case 9: SegType
= "TSS32(Avl)"; break;
1744 case 11: SegType
= "TSS32(Busy)"; break;
1745 case 12: SegType
= "CALLGATE32"; break;
1746 case 14: SegType
= "INTGATE32"; break;
1747 case 15: SegType
= "INTGATE32"; break;
1748 default: SegType
= "UNKNOWN"; break;
1751 if (!(Type
>= 1 && Type
<= 3) &&
1752 Type
!= 9 && Type
!= 11)
1758 else if ((SegDesc
[1] & (1 << 11)) == 0) /* Data segment */
1760 if ((SegDesc
[1] & (1 << 22)) != 0)
1765 else /* Code segment */
1767 if ((SegDesc
[1] & (1 << 22)) != 0)
1773 if ((SegDesc
[1] & (1 << 15)) == 0) /* not present */
1775 KdbpPrint(" %03d 0x%04x %-11s [NP] [NP] %02d NP\n",
1776 i
/ 8, i
| Dpl
| ul
, SegType
, Dpl
);
1780 KdbpPrint(" %03d 0x%04x %-11s 0x%08x 0x%08x %02d ",
1781 i
/ 8, i
| Dpl
| ul
, SegType
, SegBase
, SegLimit
, Dpl
);
1783 if ((SegDesc
[1] & (1 << 12)) == 0) /* System segment */
1785 /* FIXME: Display system segment */
1787 else if ((SegDesc
[1] & (1 << 11)) == 0) /* Data segment */
1789 if ((SegDesc
[1] & (1 << 10)) != 0) /* Expand-down */
1792 KdbpPrint((SegDesc
[1] & (1 << 9)) ? " R/W" : " R");
1794 if ((SegDesc
[1] & (1 << 8)) != 0)
1797 else /* Code segment */
1799 if ((SegDesc
[1] & (1 << 10)) != 0) /* Conforming */
1802 KdbpPrint((SegDesc
[1] & (1 << 9)) ? " R/X" : " X");
1804 if ((SegDesc
[1] & (1 << 8)) != 0)
1808 if ((SegDesc
[1] & (1 << 20)) != 0)
1819 /*!\brief Displays the KPCR
1826 PKIPCR Pcr
= (PKIPCR
)KeGetPcr();
1829 KdbpPrint("Current PCR is at 0x%08x.\n", (INT
)Pcr
);
1830 KdbpPrint(" Tib.ExceptionList: 0x%08x\n"
1831 " Tib.StackBase: 0x%08x\n"
1832 " Tib.StackLimit: 0x%08x\n"
1833 " Tib.SubSystemTib: 0x%08x\n"
1834 " Tib.FiberData/Version: 0x%08x\n"
1835 " Tib.ArbitraryUserPointer: 0x%08x\n"
1836 " Tib.Self: 0x%08x\n"
1841 " IrrActive: 0x%08x\n"
1843 " KdVersionBlock: 0x%08x\n"
1847 " MajorVersion: 0x%04x\n"
1848 " MinorVersion: 0x%04x\n"
1849 " SetMember: 0x%08x\n"
1850 " StallScaleFactor: 0x%08x\n"
1852 " L2CacheAssociativity: 0x%02x\n"
1853 " VdmAlert: 0x%08x\n"
1854 " L2CacheSize: 0x%08x\n"
1855 " InterruptMode: 0x%08x\n",
1856 Pcr
->NtTib
.ExceptionList
, Pcr
->NtTib
.StackBase
, Pcr
->NtTib
.StackLimit
,
1857 Pcr
->NtTib
.SubSystemTib
, Pcr
->NtTib
.FiberData
, Pcr
->NtTib
.ArbitraryUserPointer
,
1858 Pcr
->NtTib
.Self
, Pcr
->Self
, Pcr
->Prcb
, Pcr
->Irql
, Pcr
->IRR
, Pcr
->IrrActive
,
1859 Pcr
->IDR
, Pcr
->KdVersionBlock
, Pcr
->IDT
, Pcr
->GDT
, Pcr
->TSS
,
1860 Pcr
->MajorVersion
, Pcr
->MinorVersion
, Pcr
->SetMember
, Pcr
->StallScaleFactor
,
1861 Pcr
->Number
, Pcr
->L2CacheAssociativity
,
1862 Pcr
->VdmAlert
, Pcr
->SecondLevelCacheSize
, Pcr
->InterruptMode
);
1863 #elif defined(_M_AMD64)
1864 KdbpPrint("Current PCR is at 0x%x.\n", (INT_PTR
)Pcr
);
1865 KdbpPrint(" Tib.ExceptionList: 0x%x\n"
1866 " Tib.StackBase: 0x%x\n"
1867 " Tib.StackLimit: 0x%x\n"
1868 " Tib.SubSystemTib: 0x%x\n"
1869 " Tib.FiberData/Version: 0x%x\n"
1870 " Tib.ArbitraryUserPointer: 0x%x\n"
1875 " KdVersionBlock: 0x%08x\n"
1879 " UserRsp: 0x%08x\n"
1880 " MajorVersion: 0x%04x\n"
1881 " MinorVersion: 0x%04x\n"
1882 " StallScaleFactor: 0x%08x\n"
1883 " L2CacheAssociativity: 0x%02x\n"
1884 " L2CacheSize: 0x%08x\n",
1885 Pcr
->NtTib
.ExceptionList
, Pcr
->NtTib
.StackBase
, Pcr
->NtTib
.StackLimit
,
1886 Pcr
->NtTib
.SubSystemTib
, Pcr
->NtTib
.FiberData
, Pcr
->NtTib
.ArbitraryUserPointer
,
1887 Pcr
->NtTib
.Self
, Pcr
->Self
, Pcr
->Prcb
, Pcr
->Irql
,
1888 Pcr
->KdVersionBlock
, Pcr
->IdtBase
, Pcr
->GdtBase
, Pcr
->TssBase
,Pcr
->UserRsp
,
1889 Pcr
->MajorVersion
, Pcr
->MinorVersion
, Pcr
->StallScaleFactor
,
1890 Pcr
->SecondLevelCacheAssociativity
, Pcr
->SecondLevelCacheSize
);
1895 /*!\brief Displays the TSS
1903 KTSS
*Tss
= KeGetPcr()->TSS
;
1905 KdbpPrint("Current TSS is at 0x%08x.\n", (INT
)Tss
);
1906 KdbpPrint(" Eip: 0x%08x\n"
1913 " IoMapBase: 0x%04x\n",
1914 Tss
->Eip
, Tss
->Es
, Tss
->Cs
, Tss
->Ds
, Tss
->Fs
, Tss
->Gs
, Tss
->IoMapBase
);
1921 /*!\brief Bugchecks the system.
1928 /* Set the flag and quit looping */
1929 KdbpBugCheckRequested
= TRUE
;
1934 /*!\brief Sets or displays a config variables value.
1944 KDB_ENTER_CONDITION ConditionFirst
= KdbDoNotEnter
;
1945 KDB_ENTER_CONDITION ConditionLast
= KdbDoNotEnter
;
1947 static const PCHAR ExceptionNames
[21] =
1949 "ZERODEVIDE", "DEBUGTRAP", "NMI", "INT3", "OVERFLOW", "BOUND", "INVALIDOP",
1950 "NOMATHCOP", "DOUBLEFAULT", "RESERVED(9)", "INVALIDTSS", "SEGMENTNOTPRESENT",
1951 "STACKFAULT", "GPF", "PAGEFAULT", "RESERVED(15)", "MATHFAULT", "ALIGNMENTCHECK",
1952 "MACHINECHECK", "SIMDFAULT", "OTHERS"
1957 KdbpPrint("Available settings:\n");
1958 KdbpPrint(" syntax [intel|at&t]\n");
1959 KdbpPrint(" condition [exception|*] [first|last] [never|always|kmode|umode]\n");
1960 KdbpPrint(" break_on_module_load [true|false]\n");
1962 else if (strcmp(Argv
[1], "syntax") == 0)
1966 KdbpPrint("syntax = %s\n", KdbUseIntelSyntax
? "intel" : "at&t");
1970 if (_stricmp(Argv
[2], "intel") == 0)
1971 KdbUseIntelSyntax
= TRUE
;
1972 else if (_stricmp(Argv
[2], "at&t") == 0)
1973 KdbUseIntelSyntax
= FALSE
;
1975 KdbpPrint("Unknown syntax '%s'.\n", Argv
[2]);
1978 else if (strcmp(Argv
[1], "condition") == 0)
1982 KdbpPrint("Conditions: (First) (Last)\n");
1983 for (l
= 0; l
< RTL_NUMBER_OF(ExceptionNames
) - 1; l
++)
1985 if (!ExceptionNames
[l
])
1988 if (!KdbpGetEnterCondition(l
, TRUE
, &ConditionFirst
))
1991 if (!KdbpGetEnterCondition(l
, FALSE
, &ConditionLast
))
1994 KdbpPrint(" #%02d %-20s %-8s %-8s\n", l
, ExceptionNames
[l
],
1995 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst
),
1996 KDB_ENTER_CONDITION_TO_STRING(ConditionLast
));
1999 ASSERT(l
== (RTL_NUMBER_OF(ExceptionNames
) - 1));
2000 KdbpPrint(" %-20s %-8s %-8s\n", ExceptionNames
[l
],
2001 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst
),
2002 KDB_ENTER_CONDITION_TO_STRING(ConditionLast
));
2006 if (Argc
>= 5 && strcmp(Argv
[2], "*") == 0) /* Allow * only when setting condition */
2012 l
= strtoul(Argv
[2], &pend
, 0);
2014 if (Argv
[2] == pend
)
2016 for (l
= 0; l
< RTL_NUMBER_OF(ExceptionNames
); l
++)
2018 if (!ExceptionNames
[l
])
2021 if (_stricmp(ExceptionNames
[l
], Argv
[2]) == 0)
2026 if (l
>= RTL_NUMBER_OF(ExceptionNames
))
2028 KdbpPrint("Unknown exception '%s'.\n", Argv
[2]);
2035 if (_stricmp(Argv
[3], "first") == 0)
2037 else if (_stricmp(Argv
[3], "last") == 0)
2041 KdbpPrint("set condition: second argument must be 'first' or 'last'\n");
2045 if (_stricmp(Argv
[4], "never") == 0)
2046 ConditionFirst
= KdbDoNotEnter
;
2047 else if (_stricmp(Argv
[4], "always") == 0)
2048 ConditionFirst
= KdbEnterAlways
;
2049 else if (_stricmp(Argv
[4], "umode") == 0)
2050 ConditionFirst
= KdbEnterFromUmode
;
2051 else if (_stricmp(Argv
[4], "kmode") == 0)
2052 ConditionFirst
= KdbEnterFromKmode
;
2055 KdbpPrint("set condition: third argument must be 'never', 'always', 'umode' or 'kmode'\n");
2059 if (!KdbpSetEnterCondition(l
, First
, ConditionFirst
))
2062 KdbpPrint("Couldn't change condition for exception #%02d\n", l
);
2064 KdbpPrint("Couldn't change condition for all exceptions\n", l
);
2067 else /* Argc >= 3 */
2069 if (!KdbpGetEnterCondition(l
, TRUE
, &ConditionFirst
))
2072 if (!KdbpGetEnterCondition(l
, FALSE
, &ConditionLast
))
2075 if (l
< (RTL_NUMBER_OF(ExceptionNames
) - 1))
2077 KdbpPrint("Condition for exception #%02d (%s): FirstChance %s LastChance %s\n",
2078 l
, ExceptionNames
[l
],
2079 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst
),
2080 KDB_ENTER_CONDITION_TO_STRING(ConditionLast
));
2084 KdbpPrint("Condition for all other exceptions: FirstChance %s LastChance %s\n",
2085 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst
),
2086 KDB_ENTER_CONDITION_TO_STRING(ConditionLast
));
2091 else if (strcmp(Argv
[1], "break_on_module_load") == 0)
2094 KdbpPrint("break_on_module_load = %s\n", KdbBreakOnModuleLoad
? "enabled" : "disabled");
2097 if (_stricmp(Argv
[2], "enable") == 0 || _stricmp(Argv
[2], "enabled") == 0 || _stricmp(Argv
[2], "true") == 0)
2098 KdbBreakOnModuleLoad
= TRUE
;
2099 else if (_stricmp(Argv
[2], "disable") == 0 || _stricmp(Argv
[2], "disabled") == 0 || _stricmp(Argv
[2], "false") == 0)
2100 KdbBreakOnModuleLoad
= FALSE
;
2102 KdbpPrint("Unknown setting '%s'.\n", Argv
[2]);
2107 KdbpPrint("Unknown setting '%s'.\n", Argv
[1]);
2113 /*!\brief Displays help screen.
2122 KdbpPrint("Kernel debugger commands:\n");
2123 for (i
= 0; i
< RTL_NUMBER_OF(KdbDebuggerCommands
); i
++)
2125 if (!KdbDebuggerCommands
[i
].Syntax
) /* Command group */
2130 KdbpPrint("\x1b[7m* %s:\x1b[0m\n", KdbDebuggerCommands
[i
].Help
);
2134 KdbpPrint(" %-20s - %s\n",
2135 KdbDebuggerCommands
[i
].Syntax
,
2136 KdbDebuggerCommands
[i
].Help
);
2142 /*!\brief Prints the given string with printf-like formatting.
2144 * \param Format Format of the string/arguments.
2145 * \param ... Variable number of arguments matching the format specified in \a Format.
2147 * \note Doesn't correctly handle \\t and terminal escape sequences when calculating the
2148 * number of lines required to print a single line from the Buffer in the terminal.
2155 static CHAR Buffer
[4096];
2156 static BOOLEAN TerminalInitialized
= FALSE
;
2157 static BOOLEAN TerminalConnected
= FALSE
;
2158 static BOOLEAN TerminalReportsSize
= TRUE
;
2163 LONG RowsPrintedByTerminal
;
2167 /* Check if the user has aborted output of the current command */
2168 if (KdbOutputAborted
)
2171 /* Initialize the terminal */
2172 if (!TerminalInitialized
)
2174 DbgPrint("\x1b[7h"); /* Enable linewrap */
2176 /* Query terminal type */
2177 /*DbgPrint("\x1b[Z");*/
2180 TerminalInitialized
= TRUE
;
2182 KeStallExecutionProcessor(100000);
2186 c
= KdbpTryGetCharSerial(5000);
2190 Buffer
[Length
++] = c
;
2191 if (Length
>= (sizeof (Buffer
) - 1))
2195 Buffer
[Length
] = '\0';
2197 TerminalConnected
= TRUE
;
2200 /* Get number of rows and columns in terminal */
2201 if ((KdbNumberOfRowsTerminal
< 0) || (KdbNumberOfColsTerminal
< 0) ||
2202 (KdbNumberOfRowsPrinted
) == 0) /* Refresh terminal size each time when number of rows printed is 0 */
2204 if ((KdbDebugState
& KD_DEBUG_KDSERIAL
) && TerminalConnected
&& TerminalReportsSize
)
2206 /* Try to query number of rows from terminal. A reply looks like "\x1b[8;24;80t" */
2207 TerminalReportsSize
= FALSE
;
2208 KeStallExecutionProcessor(100000);
2209 DbgPrint("\x1b[18t");
2210 c
= KdbpTryGetCharSerial(5000);
2214 c
= KdbpTryGetCharSerial(5000);
2221 c
= KdbpTryGetCharSerial(5000);
2225 Buffer
[Length
++] = c
;
2226 if (isalpha(c
) || Length
>= (sizeof (Buffer
) - 1))
2230 Buffer
[Length
] = '\0';
2231 if (Buffer
[0] == '8' && Buffer
[1] == ';')
2233 for (i
= 2; (i
< Length
) && (Buffer
[i
] != ';'); i
++);
2235 if (Buffer
[i
] == ';')
2239 /* Number of rows is now at Buffer + 2 and number of cols at Buffer + i */
2240 KdbNumberOfRowsTerminal
= strtoul(Buffer
+ 2, NULL
, 0);
2241 KdbNumberOfColsTerminal
= strtoul(Buffer
+ i
, NULL
, 0);
2242 TerminalReportsSize
= TRUE
;
2246 /* Clear further characters */
2247 while ((c
= KdbpTryGetCharSerial(5000)) != -1);
2251 if (KdbNumberOfRowsTerminal
<= 0)
2253 /* Set number of rows to the default. */
2254 KdbNumberOfRowsTerminal
= 24;
2256 else if (KdbNumberOfColsTerminal
<= 0)
2258 /* Set number of cols to the default. */
2259 KdbNumberOfColsTerminal
= 80;
2263 /* Get the string */
2264 va_start(ap
, Format
);
2265 Length
= _vsnprintf(Buffer
, sizeof (Buffer
) - 1, Format
, ap
);
2266 Buffer
[Length
] = '\0';
2270 while (p
[0] != '\0')
2272 i
= strcspn(p
, "\n");
2274 /* Calculate the number of lines which will be printed in the terminal
2275 * when outputting the current line
2278 RowsPrintedByTerminal
= (i
+ KdbNumberOfColsPrinted
- 1) / KdbNumberOfColsTerminal
;
2280 RowsPrintedByTerminal
= 0;
2283 RowsPrintedByTerminal
++;
2285 /*DbgPrint("!%d!%d!%d!%d!", KdbNumberOfRowsPrinted, KdbNumberOfColsPrinted, i, RowsPrintedByTerminal);*/
2287 /* Display a prompt if we printed one screen full of text */
2288 if (KdbNumberOfRowsTerminal
> 0 &&
2289 (LONG
)(KdbNumberOfRowsPrinted
+ RowsPrintedByTerminal
) >= KdbNumberOfRowsTerminal
)
2291 if (KdbNumberOfColsPrinted
> 0)
2294 DbgPrint("--- Press q to abort, any other key to continue ---");
2296 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
2297 c
= KdbpGetCharSerial();
2299 c
= KdbpGetCharKeyboard(&ScanCode
);
2303 /* Try to read '\n' which might follow '\r' - if \n is not received here
2304 * it will be interpreted as "return" when the next command should be read.
2306 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
2307 c
= KdbpTryGetCharSerial(5);
2309 c
= KdbpTryGetCharKeyboard(&ScanCode
, 5);
2315 KdbOutputAborted
= TRUE
;
2319 KdbNumberOfRowsPrinted
= 0;
2320 KdbNumberOfColsPrinted
= 0;
2323 /* Insert a NUL after the line and print only the current line. */
2324 if (p
[i
] == '\n' && p
[i
+ 1] != '\0')
2334 /* Remove escape sequences from the line if there's no terminal connected */
2335 if (!TerminalConnected
)
2337 while ((p2
= strrchr(p
, '\x1b'))) /* Look for escape character */
2342 while (!isalpha(p2
[j
++]));
2357 /* Set p to the start of the next line and
2358 * remember the number of rows/cols printed
2364 KdbNumberOfColsPrinted
= 0;
2368 ASSERT(p
[0] == '\0');
2369 KdbNumberOfColsPrinted
+= i
;
2372 KdbNumberOfRowsPrinted
+= RowsPrintedByTerminal
;
2376 /*!\brief Appends a command to the command history
2378 * \param Command Pointer to the command to append to the history.
2381 KdbpCommandHistoryAppend(
2384 ULONG Length1
= strlen(Command
) + 1;
2389 ASSERT(Length1
<= RTL_NUMBER_OF(KdbCommandHistoryBuffer
));
2392 (KdbCommandHistory
[KdbCommandHistoryIndex
] &&
2393 strcmp(KdbCommandHistory
[KdbCommandHistoryIndex
], Command
) == 0))
2398 /* Calculate Length1 and Length2 */
2399 Buffer
= KdbCommandHistoryBuffer
+ KdbCommandHistoryBufferIndex
;
2400 KdbCommandHistoryBufferIndex
+= Length1
;
2401 if (KdbCommandHistoryBufferIndex
>= (LONG
)RTL_NUMBER_OF(KdbCommandHistoryBuffer
))
2403 KdbCommandHistoryBufferIndex
-= RTL_NUMBER_OF(KdbCommandHistoryBuffer
);
2404 Length2
= KdbCommandHistoryBufferIndex
;
2408 /* Remove previous commands until there is enough space to append the new command */
2409 for (i
= KdbCommandHistoryIndex
; KdbCommandHistory
[i
];)
2412 (KdbCommandHistory
[i
] >= Buffer
||
2413 KdbCommandHistory
[i
] < (KdbCommandHistoryBuffer
+ KdbCommandHistoryBufferIndex
))) ||
2415 (KdbCommandHistory
[i
] >= Buffer
&&
2416 KdbCommandHistory
[i
] < (KdbCommandHistoryBuffer
+ KdbCommandHistoryBufferIndex
))))
2418 KdbCommandHistory
[i
] = NULL
;
2423 i
= RTL_NUMBER_OF(KdbCommandHistory
) - 1;
2425 if (i
== KdbCommandHistoryIndex
)
2429 /* Make sure the new command history entry is free */
2430 KdbCommandHistoryIndex
++;
2431 KdbCommandHistoryIndex
%= RTL_NUMBER_OF(KdbCommandHistory
);
2432 if (KdbCommandHistory
[KdbCommandHistoryIndex
])
2434 KdbCommandHistory
[KdbCommandHistoryIndex
] = NULL
;
2437 /* Append command */
2438 KdbCommandHistory
[KdbCommandHistoryIndex
] = Buffer
;
2439 ASSERT((KdbCommandHistory
[KdbCommandHistoryIndex
] + Length1
) <= KdbCommandHistoryBuffer
+ RTL_NUMBER_OF(KdbCommandHistoryBuffer
));
2440 memcpy(KdbCommandHistory
[KdbCommandHistoryIndex
], Command
, Length1
);
2443 memcpy(KdbCommandHistoryBuffer
, Command
+ Length1
, Length2
);
2447 /*!\brief Reads a line of user-input.
2449 * \param Buffer Buffer to store the input into. Trailing newlines are removed.
2450 * \param Size Size of \a Buffer.
2452 * \note Accepts only \n newlines, \r is ignored.
2460 PCHAR Orig
= Buffer
;
2463 static CHAR LastCommand
[1024] = "";
2464 static CHAR NextKey
= '\0';
2465 INT CmdHistIndex
= -1;
2468 EchoOn
= !((KdbDebugState
& KD_DEBUG_KDNOECHO
) != 0);
2472 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
2474 Key
= (NextKey
== '\0') ? KdbpGetCharSerial() : NextKey
;
2477 if (Key
== KEY_ESC
) /* ESC */
2479 Key
= KdbpGetCharSerial();
2482 Key
= KdbpGetCharSerial();
2487 ScanCode
= KEY_SCAN_UP
;
2490 ScanCode
= KEY_SCAN_DOWN
;
2503 Key
= (NextKey
== '\0') ? KdbpGetCharKeyboard(&ScanCode
) : NextKey
;
2507 if ((ULONG
)(Buffer
- Orig
) >= (Size
- 1))
2509 /* Buffer is full, accept only newlines */
2516 /* Read the next char - this is to throw away a \n which most clients should
2519 KeStallExecutionProcessor(100000);
2521 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
2522 NextKey
= KdbpTryGetCharSerial(5);
2524 NextKey
= KdbpTryGetCharKeyboard(&ScanCode
, 5);
2526 if (NextKey
== '\n' || NextKey
== -1) /* \n or no response at all */
2532 * Repeat the last command if the user presses enter. Reduces the
2533 * risk of RSI when single-stepping.
2537 strncpy(Buffer
, LastCommand
, Size
);
2538 Buffer
[Size
- 1] = '\0';
2543 strncpy(LastCommand
, Orig
, sizeof (LastCommand
));
2544 LastCommand
[sizeof (LastCommand
) - 1] = '\0';
2549 else if (Key
== KEY_BS
|| Key
== KEY_DEL
)
2557 KdbpPrint("%c %c", KEY_BS
, KEY_BS
);
2559 KdbpPrint(" %c", KEY_BS
);
2562 else if (ScanCode
== KEY_SCAN_UP
)
2564 BOOLEAN Print
= TRUE
;
2566 if (CmdHistIndex
< 0)
2568 CmdHistIndex
= KdbCommandHistoryIndex
;
2572 i
= CmdHistIndex
- 1;
2575 CmdHistIndex
= RTL_NUMBER_OF(KdbCommandHistory
) - 1;
2577 if (KdbCommandHistory
[i
] && i
!= KdbCommandHistoryIndex
)
2583 if (Print
&& KdbCommandHistory
[CmdHistIndex
])
2585 while (Buffer
> Orig
)
2591 KdbpPrint("%c %c", KEY_BS
, KEY_BS
);
2593 KdbpPrint(" %c", KEY_BS
);
2596 i
= min(strlen(KdbCommandHistory
[CmdHistIndex
]), Size
- 1);
2597 memcpy(Orig
, KdbCommandHistory
[CmdHistIndex
], i
);
2600 KdbpPrint("%s", Orig
);
2603 else if (ScanCode
== KEY_SCAN_DOWN
)
2605 if (CmdHistIndex
> 0 && CmdHistIndex
!= KdbCommandHistoryIndex
)
2607 i
= CmdHistIndex
+ 1;
2608 if (i
>= (INT
)RTL_NUMBER_OF(KdbCommandHistory
))
2611 if (KdbCommandHistory
[i
])
2614 while (Buffer
> Orig
)
2620 KdbpPrint("%c %c", KEY_BS
, KEY_BS
);
2622 KdbpPrint(" %c", KEY_BS
);
2625 i
= min(strlen(KdbCommandHistory
[CmdHistIndex
]), Size
- 1);
2626 memcpy(Orig
, KdbCommandHistory
[CmdHistIndex
], i
);
2629 KdbpPrint("%s", Orig
);
2636 KdbpPrint("%c", Key
);
2644 /*!\brief Parses command line and executes command if found
2646 * \param Command Command line to parse and execute if possible.
2648 * \retval TRUE Don't continue execution.
2649 * \retval FALSE Continue execution (leave KDB)
2658 static PCH Argv
[256];
2659 static CHAR OrigCommand
[1024];
2661 strncpy(OrigCommand
, Command
, sizeof(OrigCommand
) - 1);
2662 OrigCommand
[sizeof(OrigCommand
) - 1] = '\0';
2669 while (*p
== '\t' || *p
== ' ')
2675 i
= strcspn(p
, "\t ");
2688 for (i
= 0; i
< RTL_NUMBER_OF(KdbDebuggerCommands
); i
++)
2690 if (!KdbDebuggerCommands
[i
].Name
)
2693 if (strcmp(KdbDebuggerCommands
[i
].Name
, Argv
[0]) == 0)
2695 return KdbDebuggerCommands
[i
].Fn(Argc
, Argv
);
2699 KdbpPrint("Command '%s' is unknown.\n", OrigCommand
);
2703 /*!\brief KDB Main Loop.
2705 * \param EnteredOnSingleStep TRUE if KDB was entered on single step.
2709 IN BOOLEAN EnteredOnSingleStep
)
2711 static CHAR Command
[1024];
2714 if (EnteredOnSingleStep
)
2716 if (!KdbSymPrintAddress((PVOID
)KdbCurrentTrapFrame
->Tf
.Eip
))
2718 KdbpPrint("<%x>", KdbCurrentTrapFrame
->Tf
.Eip
);
2722 if (KdbpDisassemble(KdbCurrentTrapFrame
->Tf
.Eip
, KdbUseIntelSyntax
) < 0)
2724 KdbpPrint("<INVALID>");
2729 /* Flush the input buffer */
2730 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
2732 while (KdbpTryGetCharSerial(1) != -1);
2737 while (KdbpTryGetCharKeyboard(&ScanCode
, 1) != -1);
2743 /* Print the prompt */
2744 KdbpPrint("kdb:> ");
2746 /* Read a command and remember it */
2747 KdbpReadCommand(Command
, sizeof (Command
));
2748 KdbpCommandHistoryAppend(Command
);
2750 /* Reset the number of rows/cols printed and output aborted state */
2751 KdbNumberOfRowsPrinted
= KdbNumberOfColsPrinted
= 0;
2752 KdbOutputAborted
= FALSE
;
2754 /* Call the command */
2755 Continue
= KdbpDoCommand(Command
);
2760 /*!\brief Called when a module is loaded.
2762 * \param Name Filename of the module which was loaded.
2765 KdbpCliModuleLoaded(
2766 IN PUNICODE_STRING Name
)
2768 if (!KdbBreakOnModuleLoad
)
2771 KdbpPrint("Module %wZ loaded.\n", Name
);
2772 DbgBreakPointWithStatus(DBG_STATUS_CONTROL_C
);
2775 /*!\brief This function is called by KdbEnterDebuggerException...
2777 * Used to interpret the init file in a context with a trapframe setup
2778 * (KdbpCliInit call KdbEnter which will call KdbEnterDebuggerException which will
2779 * call this function if KdbInitFileBuffer is not NULL.
2782 KdbpCliInterpretInitFile()
2788 /* Execute the commands in the init file */
2789 DPRINT("KDB: Executing KDBinit file...\n");
2790 p1
= KdbInitFileBuffer
;
2791 while (p1
[0] != '\0')
2793 i
= strcspn(p1
, "\r\n");
2799 /* Look for "break" command and comments */
2802 while (isspace(p2
[0]))
2805 if (strncmp(p2
, "break", sizeof("break")-1) == 0 &&
2806 (p2
[sizeof("break")-1] == '\0' || isspace(p2
[sizeof("break")-1])))
2808 /* break into the debugger */
2809 KdbpCliMainLoop(FALSE
);
2811 else if (p2
[0] != '#' && p2
[0] != '\0') /* Ignore empty lines and comments */
2820 while (p1
[0] == '\r' || p1
[0] == '\n')
2823 DPRINT("KDB: KDBinit executed\n");
2826 /*!\brief Called when KDB is initialized
2828 * Reads the KDBinit file from the SystemRoot\system32\drivers\etc directory and executes it.
2834 OBJECT_ATTRIBUTES ObjectAttributes
;
2835 UNICODE_STRING FileName
;
2836 IO_STATUS_BLOCK Iosb
;
2837 FILE_STANDARD_INFORMATION FileStdInfo
;
2838 HANDLE hFile
= NULL
;
2843 /* Initialize the object attributes */
2844 RtlInitUnicodeString(&FileName
, L
"\\SystemRoot\\system32\\drivers\\etc\\KDBinit");
2845 InitializeObjectAttributes(&ObjectAttributes
, &FileName
, 0, NULL
, NULL
);
2848 Status
= ZwOpenFile(&hFile
, FILE_READ_DATA
, &ObjectAttributes
, &Iosb
, 0,
2849 FILE_NON_DIRECTORY_FILE
| FILE_SYNCHRONOUS_IO_NONALERT
|
2850 FILE_NO_INTERMEDIATE_BUFFERING
);
2851 if (!NT_SUCCESS(Status
))
2853 DPRINT("Could not open \\SystemRoot\\system32\\drivers\\etc\\KDBinit (Status 0x%x)", Status
);
2857 /* Get the size of the file */
2858 Status
= ZwQueryInformationFile(hFile
, &Iosb
, &FileStdInfo
, sizeof (FileStdInfo
),
2859 FileStandardInformation
);
2860 if (!NT_SUCCESS(Status
))
2863 DPRINT("Could not query size of \\SystemRoot\\system32\\drivers\\etc\\KDBinit (Status 0x%x)", Status
);
2866 FileSize
= FileStdInfo
.EndOfFile
.u
.LowPart
;
2868 /* Allocate memory for the file */
2869 FileBuffer
= ExAllocatePool(PagedPool
, FileSize
+ 1); /* add 1 byte for terminating '\0' */
2873 DPRINT("Could not allocate %d bytes for KDBinit file\n", FileSize
);
2877 /* Load file into memory */
2878 Status
= ZwReadFile(hFile
, 0, 0, 0, &Iosb
, FileBuffer
, FileSize
, 0, 0);
2881 if (!NT_SUCCESS(Status
) && Status
!= STATUS_END_OF_FILE
)
2883 ExFreePool(FileBuffer
);
2884 DPRINT("Could not read KDBinit file into memory (Status 0x%lx)\n", Status
);
2888 FileSize
= min(FileSize
, (INT
)Iosb
.Information
);
2889 FileBuffer
[FileSize
] = '\0';
2891 /* Enter critical section */
2892 OldEflags
= __readeflags();
2895 /* Interpret the init file... */
2896 KdbInitFileBuffer
= FileBuffer
;
2898 KdbInitFileBuffer
= NULL
;
2900 /* Leave critical section */
2901 __writeeflags(OldEflags
);
2903 ExFreePool(FileBuffer
);
2908 KdpSerialDebugPrint(
2913 STRING KdpPromptString
= RTL_CONSTANT_STRING("kdb:> ");
2914 extern KSPIN_LOCK KdpSerialSpinLock
;
2918 KdpPrompt(IN LPSTR InString
,
2919 IN USHORT InStringLength
,
2920 OUT LPSTR OutString
,
2921 IN USHORT OutStringLength
)
2925 ULONG DummyScanCode
;
2928 /* Acquire the printing spinlock without waiting at raised IRQL */
2931 /* Wait when the spinlock becomes available */
2932 while (!KeTestSpinLock(&KdpSerialSpinLock
));
2934 /* Spinlock was free, raise IRQL */
2935 KeRaiseIrql(HIGH_LEVEL
, &OldIrql
);
2937 /* Try to get the spinlock */
2938 if (KeTryToAcquireSpinLockAtDpcLevel(&KdpSerialSpinLock
))
2941 /* Someone else got the spinlock, lower IRQL back */
2942 KeLowerIrql(OldIrql
);
2945 /* Loop the string to send */
2946 for (i
= 0; i
< InStringLength
; i
++)
2948 /* Print it to serial */
2949 KdPortPutByteEx(&SerialPortInfo
, *(PCHAR
)(InString
+ i
));
2952 /* Print a new line for log neatness */
2953 KdPortPutByteEx(&SerialPortInfo
, '\r');
2954 KdPortPutByteEx(&SerialPortInfo
, '\n');
2956 /* Print the kdb prompt */
2957 for (i
= 0; i
< KdpPromptString
.Length
; i
++)
2959 /* Print it to serial */
2960 KdPortPutByteEx(&SerialPortInfo
,
2961 *(KdpPromptString
.Buffer
+ i
));
2964 /* Loop the whole string */
2965 for (i
= 0; i
< OutStringLength
; i
++)
2967 /* Check if this is serial debugging mode */
2968 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
2970 /* Get the character from serial */
2973 Response
= KdbpTryGetCharSerial(MAXULONG
);
2974 } while (Response
== -1);
2978 /* Get the response from the keyboard */
2981 Response
= KdbpTryGetCharKeyboard(&DummyScanCode
, MAXULONG
);
2982 } while (Response
== -1);
2985 /* Check for return */
2986 if (Response
== '\r')
2989 * We might need to discard the next '\n'.
2990 * Wait a bit to make sure we receive it.
2992 KeStallExecutionProcessor(100000);
2994 /* Check the mode */
2995 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
2997 /* Read and discard the next character, if any */
2998 KdbpTryGetCharSerial(5);
3002 /* Read and discard the next character, if any */
3003 KdbpTryGetCharKeyboard(&DummyScanCode
, 5);
3007 * Null terminate the output string -- documentation states that
3008 * DbgPrompt does not null terminate, but it does
3010 *(PCHAR
)(OutString
+ i
) = 0;
3012 /* Print a new line */
3013 KdPortPutByteEx(&SerialPortInfo
, '\r');
3014 KdPortPutByteEx(&SerialPortInfo
, '\n');
3016 /* Release spinlock */
3017 KiReleaseSpinLock(&KdpSerialSpinLock
);
3019 /* Lower IRQL back */
3020 KeLowerIrql(OldIrql
);
3022 /* Return the length */
3023 return OutStringLength
+ 1;
3026 /* Write it back and print it to the log */
3027 *(PCHAR
)(OutString
+ i
) = Response
;
3028 KdPortPutByteEx(&SerialPortInfo
, Response
);
3031 /* Print a new line */
3032 KdPortPutByteEx(&SerialPortInfo
, '\r');
3033 KdPortPutByteEx(&SerialPortInfo
, '\n');
3035 /* Release spinlock */
3036 KiReleaseSpinLock(&KdpSerialSpinLock
);
3038 /* Lower IRQL back */
3039 KeLowerIrql(OldIrql
);
3041 /* Return the length */
3042 return OutStringLength
;