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",Result
);
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
[32] = { " 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"
614 if (Argv
[0][0] == 'r') /* regs */
617 KdbpPrint("CS:EIP 0x%04x:0x%08x\n"
618 "SS:ESP 0x%04x:0x%08x\n"
619 " EAX 0x%08x EBX 0x%08x\n"
620 " ECX 0x%08x EDX 0x%08x\n"
621 " ESI 0x%08x EDI 0x%08x\n"
623 Tf
->SegCs
& 0xFFFF, Tf
->Eip
,
624 Tf
->HardwareSegSs
, Tf
->HardwareEsp
,
629 #elif defined(_M_AMD64)
630 KdbpPrint("CS:RIP 0x%04x:0x%p\n"
631 "SS:RSP 0x%04x:0x%p\n"
632 " RAX 0x%p RBX 0x%p\n"
633 " RCX 0x%p RDX 0x%p\n"
634 " RSI 0x%p RDI 0x%p\n"
635 " RBP 0x%p R8 0x%p\n"
636 " R9 0x%p R10 0x%p\n"
638 Tf
->SegCs
& 0xFFFF, Tf
->Rip
,
647 KdbpPrint("EFLAGS 0x%08x ", Tf
->EFlags
);
649 for (i
= 0; i
< 32; i
++)
653 if ((Tf
->EFlags
& (1 << 1)) == 0)
658 KdbpPrint(" IOPL%d", (Tf
->EFlags
>> 12) & 3);
663 else if ((Tf
->EFlags
& (1 << i
)) != 0)
665 KdbpPrint(EflagsBits
[i
]);
671 else if (Argv
[0][0] == 'c') /* cregs */
673 ULONG_PTR Cr0
, Cr2
, Cr3
, Cr4
;
674 KDESCRIPTOR Gdtr
, Idtr
;
677 Ke386GetGlobalDescriptorTable(&Gdtr
.Limit
);
678 Ldtr
= Ke386GetLocalDescriptorTable();
679 #elif defined(_M_AMD64)
682 static const PCHAR Cr0Bits
[32] = { " PE", " MP", " EM", " TS", " ET", " NE", NULL
, NULL
,
683 NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
,
684 " WP", NULL
, " AM", NULL
, NULL
, NULL
, NULL
, NULL
,
685 NULL
, NULL
, NULL
, NULL
, NULL
, " NW", " CD", " PG" };
686 static const PCHAR Cr4Bits
[32] = { " VME", " PVI", " TSD", " DE", " PSE", " PAE", " MCE", " PGE",
687 " PCE", " OSFXSR", " OSXMMEXCPT", NULL
, NULL
, NULL
, NULL
, NULL
,
688 NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
,
689 NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
};
691 Cr0
= KdbCurrentTrapFrame
->Cr0
;
692 Cr2
= KdbCurrentTrapFrame
->Cr2
;
693 Cr3
= KdbCurrentTrapFrame
->Cr3
;
694 Cr4
= KdbCurrentTrapFrame
->Cr4
;
696 /* Get interrupt descriptor table regs */
699 /* Display the control registers */
700 KdbpPrint("CR0 0x%p ", Cr0
);
702 for (i
= 0; i
< 32; i
++)
707 if ((Cr0
& (1 << i
)) != 0)
708 KdbpPrint(Cr0Bits
[i
]);
711 KdbpPrint("\nCR2 0x%p\n", Cr2
);
712 KdbpPrint("CR3 0x%p Pagedir-Base 0x%p %s%s\n", Cr3
, (Cr3
& 0xfffff000),
713 (Cr3
& (1 << 3)) ? " PWT" : "", (Cr3
& (1 << 4)) ? " PCD" : "" );
714 KdbpPrint("CR4 0x%p ", Cr4
);
716 for (i
= 0; i
< 32; i
++)
721 if ((Cr4
& (1 << i
)) != 0)
722 KdbpPrint(Cr4Bits
[i
]);
725 /* Display the descriptor table regs */
726 KdbpPrint("\nGDTR Base 0x%p Size 0x%04x\n", Gdtr
.Base
, Gdtr
.Limit
);
728 KdbpPrint("LDTR 0x%p\n", Ldtr
);
730 KdbpPrint("IDTR Base 0x%p Size 0x%04x\n", Idtr
.Base
, Idtr
.Limit
);
732 else if (Argv
[0][0] == 's') /* sregs */
734 KdbpPrint("CS 0x%04x Index 0x%04x %cDT RPL%d\n",
735 Tf
->SegCs
& 0xffff, (Tf
->SegCs
& 0xffff) >> 3,
736 (Tf
->SegCs
& (1 << 2)) ? 'L' : 'G', Tf
->SegCs
& 3);
737 KdbpPrint("DS 0x%04x Index 0x%04x %cDT RPL%d\n",
738 Tf
->SegDs
, Tf
->SegDs
>> 3, (Tf
->SegDs
& (1 << 2)) ? 'L' : 'G', Tf
->SegDs
& 3);
739 KdbpPrint("ES 0x%04x Index 0x%04x %cDT RPL%d\n",
740 Tf
->SegEs
, Tf
->SegEs
>> 3, (Tf
->SegEs
& (1 << 2)) ? 'L' : 'G', Tf
->SegEs
& 3);
741 KdbpPrint("FS 0x%04x Index 0x%04x %cDT RPL%d\n",
742 Tf
->SegFs
, Tf
->SegFs
>> 3, (Tf
->SegFs
& (1 << 2)) ? 'L' : 'G', Tf
->SegFs
& 3);
743 KdbpPrint("GS 0x%04x Index 0x%04x %cDT RPL%d\n",
744 Tf
->SegGs
, Tf
->SegGs
>> 3, (Tf
->SegGs
& (1 << 2)) ? 'L' : 'G', Tf
->SegGs
& 3);
746 KdbpPrint("SS 0x%04x Index 0x%04x %cDT RPL%d\n",
747 Tf
->HardwareSegSs
, Tf
->HardwareSegSs
>> 3, (Tf
->HardwareSegSs
& (1 << 2)) ? 'L' : 'G', Tf
->HardwareSegSs
& 3);
749 KdbpPrint("SS 0x%04x Index 0x%04x %cDT RPL%d\n",
750 Tf
->SegSs
, Tf
->SegSs
>> 3, (Tf
->SegSs
& (1 << 2)) ? 'L' : 'G', Tf
->SegSs
& 3);
756 ASSERT(Argv
[0][0] == 'd');
757 KdbpPrint("DR0 0x%p\n"
763 Tf
->Dr0
, Tf
->Dr1
, Tf
->Dr2
, Tf
->Dr3
,
770 /*!\brief Displays a backtrace.
779 ULONGLONG Result
= 0;
781 ULONG_PTR Frame
= KdbCurrentTrapFrame
->Tf
.Ebp
;
782 #elif defined(_M_AMD64)
783 ULONG_PTR Frame
= KdbCurrentTrapFrame
->Tf
.Rbp
;
789 /* Check for [L count] part */
792 if (strcmp(Argv
[Argc
-2], "L") == 0)
794 ul
= strtoul(Argv
[Argc
-1], NULL
, 0);
801 else if (Argv
[Argc
-1][0] == 'L')
803 ul
= strtoul(Argv
[Argc
-1] + 1, NULL
, 0);
811 /* Put the remaining arguments back together */
813 for (ul
= 1; ul
< Argc
; ul
++)
815 Argv
[ul
][strlen(Argv
[ul
])] = ' ';
820 /* Check if frame addr or thread id is given. */
823 if (Argv
[1][0] == '*')
827 /* Evaluate the expression */
828 if (!KdbpEvaluateExpression(Argv
[1], sizeof("kdb:> ")-1 + (Argv
[1]-Argv
[0]), &Result
))
831 if (Result
> (ULONGLONG
)(~((ULONG_PTR
)0)))
832 KdbpPrint("Warning: Address %I64x is beeing truncated\n",Result
);
834 Frame
= (ULONG_PTR
)Result
;
838 KdbpPrint("Thread backtrace not supported yet!\n");
846 /* Try printing the function at EIP */
847 if (!KdbSymPrintAddress((PVOID
)KdbCurrentTrapFrame
->Tf
.Eip
))
848 KdbpPrint("<%x>\n", KdbCurrentTrapFrame
->Tf
.Eip
);
853 KdbpPrint("Frames:\n");
859 if (!NT_SUCCESS(KdbpSafeReadMemory(&Address
, (PVOID
)(Frame
+ sizeof(ULONG_PTR
)), sizeof (ULONG_PTR
))))
861 KdbpPrint("Couldn't access memory at 0x%p!\n", Frame
+ sizeof(ULONG_PTR
));
865 if (!KdbSymPrintAddress((PVOID
)Address
))
866 KdbpPrint("<%x>\n", Address
);
873 if (!NT_SUCCESS(KdbpSafeReadMemory(&Frame
, (PVOID
)Frame
, sizeof (ULONG_PTR
))))
875 KdbpPrint("Couldn't access memory at 0x%p!\n", Frame
);
883 /*!\brief Continues execution of the system/leaves KDB.
890 /* Exit the main loop */
894 /*!\brief Continues execution of the system/leaves KDB.
905 Count
= strtoul(Argv
[1], NULL
, 0);
908 KdbpPrint("%s: Integer argument required\n", Argv
[0]);
913 if (Argv
[0][0] == 'n')
914 KdbSingleStepOver
= TRUE
;
916 KdbSingleStepOver
= FALSE
;
918 /* Set the number of single steps and return to the interrupted code. */
919 KdbNumSingleSteps
= Count
;
924 /*!\brief Lists breakpoints.
927 KdbpCmdBreakPointList(
932 ULONG_PTR Address
= 0;
933 KDB_BREAKPOINT_TYPE Type
= 0;
934 KDB_ACCESS_TYPE AccessType
= 0;
937 BOOLEAN Enabled
= FALSE
;
938 BOOLEAN Global
= FALSE
;
939 PEPROCESS Process
= NULL
;
940 PCHAR str1
, str2
, ConditionExpr
, GlobalOrLocal
;
943 l
= KdbpGetNextBreakPointNr(0);
946 KdbpPrint("No breakpoints.\n");
950 KdbpPrint("Breakpoints:\n");
953 if (!KdbpGetBreakPointInfo(l
, &Address
, &Type
, &Size
, &AccessType
, &DebugReg
,
954 &Enabled
, &Global
, &Process
, &ConditionExpr
))
959 if (l
== KdbLastBreakPointNr
)
972 GlobalOrLocal
= " global";
976 GlobalOrLocal
= Buffer
;
977 sprintf(Buffer
, " PID 0x%08lx",
978 (ULONG_PTR
)(Process
? Process
->UniqueProcessId
: INVALID_HANDLE_VALUE
));
981 if (Type
== KdbBreakPointSoftware
|| Type
== KdbBreakPointTemporary
)
983 KdbpPrint(" %s%03d BPX 0x%08x%s%s%s%s%s\n",
985 Enabled
? "" : " disabled",
987 ConditionExpr
? " IF " : "",
988 ConditionExpr
? ConditionExpr
: "",
991 else if (Type
== KdbBreakPointHardware
)
995 KdbpPrint(" %s%03d BPM 0x%08x %-5s %-5s disabled%s%s%s%s\n", str1
, l
, Address
,
996 KDB_ACCESS_TYPE_TO_STRING(AccessType
),
997 Size
== 1 ? "byte" : (Size
== 2 ? "word" : "dword"),
999 ConditionExpr
? " IF " : "",
1000 ConditionExpr
? ConditionExpr
: "",
1005 KdbpPrint(" %s%03d BPM 0x%08x %-5s %-5s DR%d%s%s%s%s\n", str1
, l
, Address
,
1006 KDB_ACCESS_TYPE_TO_STRING(AccessType
),
1007 Size
== 1 ? "byte" : (Size
== 2 ? "word" : "dword"),
1010 ConditionExpr
? " IF " : "",
1011 ConditionExpr
? ConditionExpr
: "",
1016 while ((l
= KdbpGetNextBreakPointNr(l
+1)) >= 0);
1021 /*!\brief Enables, disables or clears a breakpoint.
1024 KdbpCmdEnableDisableClearBreakPoint(
1033 KdbpPrint("%s: argument required\n", Argv
[0]);
1038 BreakPointNr
= strtoul(Argv
[1], &pend
, 0);
1039 if (pend
== Argv
[1] || *pend
!= '\0')
1041 KdbpPrint("%s: integer argument required\n", Argv
[0]);
1045 if (Argv
[0][1] == 'e') /* enable */
1047 KdbpEnableBreakPoint(BreakPointNr
, NULL
);
1049 else if (Argv
[0][1] == 'd') /* disable */
1051 KdbpDisableBreakPoint(BreakPointNr
, NULL
);
1055 ASSERT(Argv
[0][1] == 'c');
1056 KdbpDeleteBreakPoint(BreakPointNr
, NULL
);
1062 /*!\brief Sets a software or hardware (memory) breakpoint at the given address.
1065 KdbpCmdBreakPoint(ULONG Argc
, PCHAR Argv
[])
1067 ULONGLONG Result
= 0;
1069 KDB_BREAKPOINT_TYPE Type
;
1071 KDB_ACCESS_TYPE AccessType
= 0;
1072 ULONG AddressArgIndex
, i
;
1073 LONG ConditionArgIndex
;
1074 BOOLEAN Global
= TRUE
;
1076 if (Argv
[0][2] == 'x') /* software breakpoint */
1080 KdbpPrint("bpx: Address argument required.\n");
1084 AddressArgIndex
= 1;
1085 Type
= KdbBreakPointSoftware
;
1087 else /* memory breakpoint */
1089 ASSERT(Argv
[0][2] == 'm');
1093 KdbpPrint("bpm: Access type argument required (one of r, w, rw, x)\n");
1097 if (_stricmp(Argv
[1], "x") == 0)
1098 AccessType
= KdbAccessExec
;
1099 else if (_stricmp(Argv
[1], "r") == 0)
1100 AccessType
= KdbAccessRead
;
1101 else if (_stricmp(Argv
[1], "w") == 0)
1102 AccessType
= KdbAccessWrite
;
1103 else if (_stricmp(Argv
[1], "rw") == 0)
1104 AccessType
= KdbAccessReadWrite
;
1107 KdbpPrint("bpm: Unknown access type '%s'\n", Argv
[1]);
1113 KdbpPrint("bpm: %s argument required.\n", AccessType
== KdbAccessExec
? "Address" : "Memory size");
1117 AddressArgIndex
= 3;
1118 if (_stricmp(Argv
[2], "byte") == 0)
1120 else if (_stricmp(Argv
[2], "word") == 0)
1122 else if (_stricmp(Argv
[2], "dword") == 0)
1124 else if (_stricmp(Argv
[2], "qword") == 0)
1126 else if (AccessType
== KdbAccessExec
)
1133 KdbpPrint("bpm: Unknown memory size '%s'\n", Argv
[2]);
1137 if (Argc
<= AddressArgIndex
)
1139 KdbpPrint("bpm: Address argument required.\n");
1143 Type
= KdbBreakPointHardware
;
1146 /* Put the arguments back together */
1147 ConditionArgIndex
= -1;
1148 for (i
= AddressArgIndex
; i
< (Argc
-1); i
++)
1150 if (strcmp(Argv
[i
+1], "IF") == 0) /* IF found */
1152 ConditionArgIndex
= i
+ 2;
1153 if (ConditionArgIndex
>= Argc
)
1155 KdbpPrint("%s: IF requires condition expression.\n", Argv
[0]);
1159 for (i
= ConditionArgIndex
; i
< (Argc
-1); i
++)
1160 Argv
[i
][strlen(Argv
[i
])] = ' ';
1165 Argv
[i
][strlen(Argv
[i
])] = ' ';
1168 /* Evaluate the address expression */
1169 if (!KdbpEvaluateExpression(Argv
[AddressArgIndex
],
1170 sizeof("kdb:> ")-1 + (Argv
[AddressArgIndex
]-Argv
[0]),
1176 if (Result
> (ULONGLONG
)(~((ULONG_PTR
)0)))
1177 KdbpPrint("%s: Warning: Address %I64x is beeing truncated\n", Argv
[0],Result
);
1179 Address
= (ULONG_PTR
)Result
;
1181 KdbpInsertBreakPoint(Address
, Type
, Size
, AccessType
,
1182 (ConditionArgIndex
< 0) ? NULL
: Argv
[ConditionArgIndex
],
1188 /*!\brief Lists threads or switches to another thread context.
1196 PETHREAD Thread
= NULL
;
1197 PEPROCESS Process
= NULL
;
1198 BOOLEAN ReferencedThread
= FALSE
, ReferencedProcess
= FALSE
;
1203 PCHAR State
, pend
, str1
, str2
;
1204 static const PCHAR ThreadStateToString
[DeferredReady
+1] =
1206 "Initialized", "Ready", "Running",
1207 "Standby", "Terminated", "Waiting",
1208 "Transition", "DeferredReady"
1211 ASSERT(KdbCurrentProcess
);
1213 if (Argc
>= 2 && _stricmp(Argv
[1], "list") == 0)
1215 Process
= KdbCurrentProcess
;
1219 ul
= strtoul(Argv
[2], &pend
, 0);
1220 if (Argv
[2] == pend
)
1222 KdbpPrint("thread: '%s' is not a valid process id!\n", Argv
[2]);
1226 if (!NT_SUCCESS(PsLookupProcessByProcessId((PVOID
)ul
, &Process
)))
1228 KdbpPrint("thread: Invalid process id!\n");
1232 /* Remember our reference */
1233 ReferencedProcess
= TRUE
;
1236 Entry
= Process
->ThreadListHead
.Flink
;
1237 if (Entry
== &Process
->ThreadListHead
)
1240 KdbpPrint("No threads in process 0x%08x!\n", ul
);
1242 KdbpPrint("No threads in current process!\n");
1244 if (ReferencedProcess
)
1245 ObDereferenceObject(Process
);
1250 KdbpPrint(" TID State Prior. Affinity EBP EIP\n");
1253 Thread
= CONTAINING_RECORD(Entry
, ETHREAD
, ThreadListEntry
);
1255 if (Thread
== KdbCurrentThread
)
1266 if (Thread
->Tcb
.TrapFrame
)
1269 if (Thread
->Tcb
.TrapFrame
->PreviousPreviousMode
== KernelMode
)
1270 Esp
= (PULONG
)Thread
->Tcb
.TrapFrame
->TempEsp
;
1272 Esp
= (PULONG
)Thread
->Tcb
.TrapFrame
->HardwareEsp
;
1274 Ebp
= (PULONG
)Thread
->Tcb
.TrapFrame
->Ebp
;
1275 Eip
= Thread
->Tcb
.TrapFrame
->Eip
;
1277 #elif defined(_M_AMD64)
1278 Esp
= (PULONG_PTR
)Thread
->Tcb
.TrapFrame
->Rsp
;
1280 Ebp
= (PULONG_PTR
)Thread
->Tcb
.TrapFrame
->Rbp
;
1281 Eip
= Thread
->Tcb
.TrapFrame
->Eip
;
1286 Esp
= (PULONG_PTR
)Thread
->Tcb
.KernelStack
;
1287 Ebp
= (PULONG_PTR
)Esp
[4];
1290 if (Ebp
) /* FIXME: Should we attach to the process to read Ebp[1]? */
1291 KdbpSafeReadMemory(&Eip
, Ebp
+ 1, sizeof (Eip
));
1294 if (Thread
->Tcb
.State
< (DeferredReady
+ 1))
1295 State
= ThreadStateToString
[Thread
->Tcb
.State
];
1299 KdbpPrint(" %s0x%p %-11s %3d 0x%p 0x%p 0x%p%s\n",
1301 Thread
->Cid
.UniqueThread
,
1303 Thread
->Tcb
.Priority
,
1304 Thread
->Tcb
.Affinity
,
1309 Entry
= Entry
->Flink
;
1311 while (Entry
!= &Process
->ThreadListHead
);
1313 /* Release our reference, if any */
1314 if (ReferencedProcess
)
1315 ObDereferenceObject(Process
);
1317 else if (Argc
>= 2 && _stricmp(Argv
[1], "attach") == 0)
1321 KdbpPrint("thread attach: thread id argument required!\n");
1325 ul
= strtoul(Argv
[2], &pend
, 0);
1326 if (Argv
[2] == pend
)
1328 KdbpPrint("thread attach: '%s' is not a valid thread id!\n", Argv
[2]);
1332 if (!KdbpAttachToThread((PVOID
)ul
))
1337 KdbpPrint("Attached to thread 0x%08x.\n", ul
);
1341 Thread
= KdbCurrentThread
;
1345 ul
= strtoul(Argv
[1], &pend
, 0);
1346 if (Argv
[1] == pend
)
1348 KdbpPrint("thread: '%s' is not a valid thread id!\n", Argv
[1]);
1352 if (!NT_SUCCESS(PsLookupThreadByThreadId((PVOID
)ul
, &Thread
)))
1354 KdbpPrint("thread: Invalid thread id!\n");
1358 /* Remember our reference */
1359 ReferencedThread
= TRUE
;
1362 if (Thread
->Tcb
.State
< (DeferredReady
+ 1))
1363 State
= ThreadStateToString
[Thread
->Tcb
.State
];
1369 " State: %s (0x%x)\n"
1371 " Affinity: 0x%08x\n"
1372 " Initial Stack: 0x%p\n"
1373 " Stack Limit: 0x%p\n"
1374 " Stack Base: 0x%p\n"
1375 " Kernel Stack: 0x%p\n"
1376 " Trap Frame: 0x%p\n"
1377 " NPX State: %s (0x%x)\n",
1378 (Argc
< 2) ? "Current Thread:\n" : "",
1379 Thread
->Cid
.UniqueThread
,
1380 State
, Thread
->Tcb
.State
,
1381 Thread
->Tcb
.Priority
,
1382 Thread
->Tcb
.Affinity
,
1383 Thread
->Tcb
.InitialStack
,
1384 Thread
->Tcb
.StackLimit
,
1385 Thread
->Tcb
.StackBase
,
1386 Thread
->Tcb
.KernelStack
,
1387 Thread
->Tcb
.TrapFrame
,
1388 NPX_STATE_TO_STRING(Thread
->Tcb
.NpxState
), Thread
->Tcb
.NpxState
);
1390 /* Release our reference if we had one */
1391 if (ReferencedThread
)
1392 ObDereferenceObject(Thread
);
1398 /*!\brief Lists processes or switches to another process context.
1407 BOOLEAN ReferencedProcess
= FALSE
;
1408 PCHAR State
, pend
, str1
, str2
;
1410 extern LIST_ENTRY PsActiveProcessHead
;
1412 if (Argc
>= 2 && _stricmp(Argv
[1], "list") == 0)
1414 Entry
= PsActiveProcessHead
.Flink
;
1415 if (!Entry
|| Entry
== &PsActiveProcessHead
)
1417 KdbpPrint("No processes in the system!\n");
1421 KdbpPrint(" PID State Filename\n");
1424 Process
= CONTAINING_RECORD(Entry
, EPROCESS
, ActiveProcessLinks
);
1426 if (Process
== KdbCurrentProcess
)
1437 State
= ((Process
->Pcb
.State
== ProcessInMemory
) ? "In Memory" :
1438 ((Process
->Pcb
.State
== ProcessOutOfMemory
) ? "Out of Memory" : "In Transition"));
1440 KdbpPrint(" %s0x%08x %-10s %s%s\n",
1442 Process
->UniqueProcessId
,
1444 Process
->ImageFileName
,
1447 Entry
= Entry
->Flink
;
1449 while(Entry
!= &PsActiveProcessHead
);
1451 else if (Argc
>= 2 && _stricmp(Argv
[1], "attach") == 0)
1455 KdbpPrint("process attach: process id argument required!\n");
1459 ul
= strtoul(Argv
[2], &pend
, 0);
1460 if (Argv
[2] == pend
)
1462 KdbpPrint("process attach: '%s' is not a valid process id!\n", Argv
[2]);
1466 if (!KdbpAttachToProcess((PVOID
)ul
))
1471 KdbpPrint("Attached to process 0x%x, thread 0x%x.\n", ul
,
1472 (ULONG_PTR
)KdbCurrentThread
->Cid
.UniqueThread
);
1476 Process
= KdbCurrentProcess
;
1480 ul
= strtoul(Argv
[1], &pend
, 0);
1481 if (Argv
[1] == pend
)
1483 KdbpPrint("proc: '%s' is not a valid process id!\n", Argv
[1]);
1487 if (!NT_SUCCESS(PsLookupProcessByProcessId((PVOID
)ul
, &Process
)))
1489 KdbpPrint("proc: Invalid process id!\n");
1493 /* Remember our reference */
1494 ReferencedProcess
= TRUE
;
1497 State
= ((Process
->Pcb
.State
== ProcessInMemory
) ? "In Memory" :
1498 ((Process
->Pcb
.State
== ProcessOutOfMemory
) ? "Out of Memory" : "In Transition"));
1501 " State: %s (0x%x)\n"
1502 " Image Filename: %s\n",
1503 (Argc
< 2) ? "Current process:\n" : "",
1504 Process
->UniqueProcessId
,
1505 State
, Process
->Pcb
.State
,
1506 Process
->ImageFileName
);
1508 /* Release our reference, if any */
1509 if (ReferencedProcess
)
1510 ObDereferenceObject(Process
);
1516 /*!\brief Lists loaded modules or the one containing the specified address.
1523 ULONGLONG Result
= 0;
1525 PLDR_DATA_TABLE_ENTRY LdrEntry
;
1526 BOOLEAN DisplayOnlyOneModule
= FALSE
;
1531 /* Put the arguments back together */
1534 Argv
[Argc
][strlen(Argv
[Argc
])] = ' ';
1536 /* Evaluate the expression */
1537 if (!KdbpEvaluateExpression(Argv
[1], sizeof("kdb:> ")-1 + (Argv
[1]-Argv
[0]), &Result
))
1542 if (Result
> (ULONGLONG
)(~((ULONG_PTR
)0)))
1543 KdbpPrint("%s: Warning: Address %I64x is beeing truncated\n", Argv
[0],Result
);
1545 Address
= (ULONG_PTR
)Result
;
1547 if (!KdbpSymFindModule((PVOID
)Address
, NULL
, -1, &LdrEntry
))
1549 KdbpPrint("No module containing address 0x%p found!\n", Address
);
1553 DisplayOnlyOneModule
= TRUE
;
1557 if (!KdbpSymFindModule(NULL
, NULL
, 0, &LdrEntry
))
1559 ULONG_PTR ntoskrnlBase
= ((ULONG_PTR
)KdbpCmdMod
) & 0xfff00000;
1560 KdbpPrint(" Base Size Name\n");
1561 KdbpPrint(" %p %x %s\n", ntoskrnlBase
, 0, "ntoskrnl.exe");
1568 KdbpPrint(" Base Size Name\n");
1571 KdbpPrint(" %p %x %wZ\n", LdrEntry
->DllBase
, LdrEntry
->SizeOfImage
, &LdrEntry
->BaseDllName
);
1573 if(DisplayOnlyOneModule
|| !KdbpSymFindModule(NULL
, NULL
, i
++, &LdrEntry
))
1580 /*!\brief Displays GDT, LDT or IDTd.
1599 if (Argv
[0][0] == 'i')
1606 KdbpPrint("Interrupt descriptor table is empty.\n");
1610 KdbpPrint("IDT Base: 0x%p Limit: 0x%04x\n", Reg
.Base
, Reg
.Limit
);
1611 KdbpPrint(" Idx Type Seg. Sel. Offset DPL\n");
1613 while (i
< (Reg
.Limit
)/sizeof(IdtEntry
))
1615 if (!NT_SUCCESS(KdbpSafeReadMemory(&IdtEntry
, (PVOID
)((ULONG_PTR
)Reg
.Base
+(i
*sizeof(IdtEntry
))), sizeof(IdtEntry
))))
1617 KdbpPrint("Couldn't access memory at 0x%x!\n", (ULONG_PTR
)Reg
.Base
+ sizeof(IdtEntry
));
1622 if (IdtEntry
.Type
== 0x5) /* Task gate */
1623 SegType
= "TASKGATE";
1624 else if (IdtEntry
.Type
== 0xE) /* 32 bit Interrupt gate */
1625 SegType
= "INTGATE32";
1626 else if (IdtEntry
.Type
== 0x6) /* 16 bit Interrupt gate */
1627 SegType
= "INTGATE16";
1628 else if (IdtEntry
.Type
== 0xF) /* 32 bit Trap gate */
1629 SegType
= "TRAPGATE32";
1630 else if (IdtEntry
.Type
== 0x7) /* 16 bit Trap gate */
1631 SegType
= "TRAPGATE16";
1633 SegType
= "UNKNOWN";
1635 if (IdtEntry
.Present
== 0) /* not present */
1637 KdbpPrint(" %03d %-10s [NP] [NP] %02d\n",
1640 else if (IdtEntry
.Type
== 0x5) /* Task gate */
1642 SegSel
= IdtEntry
.Selector
;
1643 KdbpPrint(" %03d %-10s 0x%04x %02d\n",
1644 i
, SegType
, SegSel
, Dpl
);
1648 SegSel
= IdtEntry
.Selector
;
1649 SegBase
= (ULONG64
)IdtEntry
.OffsetLow
|
1650 (ULONG64
)IdtEntry
.OffsetMiddle
<< 16 |
1651 (ULONG64
)IdtEntry
.OffsetHigh
<< 32;
1653 KdbpPrint(" %03d %-10s 0x%04x 0x%p %02d\n",
1654 i
, SegType
, SegSel
, SegBase
, Dpl
);
1663 if (Argv
[0][0] == 'g')
1671 ASSERT(Argv
[0][0] == 'l');
1682 KdbpPrint("%s descriptor table is empty.\n",
1683 Argv
[0][0] == 'g' ? "Global" : "Local");
1687 KdbpPrint("%cDT Base: 0x%p Limit: 0x%04x\n",
1688 Argv
[0][0] == 'g' ? 'G' : 'L', Reg
.Base
, Reg
.Limit
);
1689 KdbpPrint(" Idx Sel. Type Base Limit DPL Attribs\n");
1691 while (i
< (Reg
.Limit
)/sizeof(GdtEntry
))
1693 if (!NT_SUCCESS(KdbpSafeReadMemory(&GdtEntry
, (PVOID
)((ULONG_PTR
)Reg
.Base
+(i
* 8)), sizeof(GdtEntry
))))
1695 KdbpPrint("Couldn't access memory at 0x%p!\n", (ULONG_PTR
)Reg
.Base
+ i
);
1699 Dpl
= GdtEntry
.Bits
.Dpl
;
1700 Type
= GdtEntry
.Bits
.Type
;
1702 SegBase
= (ULONG_PTR
)KiGetGdtDescriptorBase(&GdtEntry
);
1704 SegLimit
= GdtEntry
.LimitLow
;
1705 SegLimit
|= (ULONG64
)GdtEntry
.Bits
.LimitHigh
<< 32;
1707 if (GdtEntry
.Bits
.DefaultBig
!= 0)
1717 if (GdtEntry
.Bits
.System
== 1) /* System segment */
1721 case 1: SegType
= "TSS16(Avl)"; break;
1722 case 2: SegType
= "LDT"; break;
1723 case 3: SegType
= "TSS16(Busy)"; break;
1724 case 4: SegType
= "CALLGATE16"; break;
1725 case 5: SegType
= "TASKGATE"; break;
1726 case 6: SegType
= "INTGATE16"; break;
1727 case 7: SegType
= "TRAPGATE16"; break;
1728 case 9: SegType
= "TSS32(Avl)"; break;
1729 case 11: SegType
= "TSS32(Busy)"; break;
1730 case 12: SegType
= "CALLGATE32"; break;
1731 case 14: SegType
= "INTGATE32"; break;
1732 case 15: SegType
= "INTGATE32"; break;
1733 default: SegType
= "UNKNOWN"; break;
1736 if (!(Type
>= 1 && Type
<= 3) &&
1737 Type
!= 9 && Type
!= 11)
1743 else if ((Type
& (1 << 3)) == 0) /* Data segment */
1745 if (GdtEntry
.Bits
.LongMode
!= 0)
1750 else /* Code segment */
1752 if (GdtEntry
.Bits
.LongMode
!= 0)
1758 if (GdtEntry
.Bits
.Present
== 0) /* not present */
1760 KdbpPrint(" %03d 0x%04x %-11s [NP] [NP] %02d NP\n",
1761 i
, i
| Dpl
| ul
, SegType
, Dpl
);
1765 KdbpPrint(" %03d 0x%04x %-11s 0x%p 0x%08x %02d ",
1766 i
, i
| Dpl
| ul
, SegType
, SegBase
, SegLimit
, Dpl
);
1768 if (GdtEntry
.Bits
.System
== 1) /* System segment */
1770 /* FIXME: Display system segment */
1771 /* they are twice as big as regular segments */
1774 else if ((Type
& (1 << 3)) == 0) /* Data segment */
1776 if ((Type
& (1 << 2)) != 0) /* Expand-down */
1779 KdbpPrint((Type
& (1 << 1)) ? " R/W" : " R");
1781 if ((Type
& (1 >> 1)) != 0)
1784 else /* Code segment */
1786 if ((Type
& (1 << 2)) != 0) /* Conforming */
1789 KdbpPrint((Type
& (1 << 1)) ? " R/X" : " X");
1791 if ((Type
& (1 << 1)) != 0)
1795 if ((GdtEntry
.Bits
.LimitHigh
& (1 << 3)) != 0)
1808 /*!\brief Displays GDT, LDT or IDTd.
1826 if (Argv
[0][0] == 'i')
1833 KdbpPrint("Interrupt descriptor table is empty.\n");
1837 KdbpPrint("IDT Base: 0x%08x Limit: 0x%04x\n", Reg
.Base
, Reg
.Limit
);
1838 KdbpPrint(" Idx Type Seg. Sel. Offset DPL\n");
1840 for (i
= 0; (i
+ sizeof(SegDesc
) - 1) <= Reg
.Limit
; i
+= 8)
1842 if (!NT_SUCCESS(KdbpSafeReadMemory(SegDesc
, (PVOID
)((ULONG_PTR
)Reg
.Base
+ i
), sizeof(SegDesc
))))
1844 KdbpPrint("Couldn't access memory at 0x%08x!\n", (ULONG_PTR
)Reg
.Base
+ i
);
1848 Dpl
= ((SegDesc
[1] >> 13) & 3);
1849 if ((SegDesc
[1] & 0x1f00) == 0x0500) /* Task gate */
1850 SegType
= "TASKGATE";
1851 else if ((SegDesc
[1] & 0x1fe0) == 0x0e00) /* 32 bit Interrupt gate */
1852 SegType
= "INTGATE32";
1853 else if ((SegDesc
[1] & 0x1fe0) == 0x0600) /* 16 bit Interrupt gate */
1854 SegType
= "INTGATE16";
1855 else if ((SegDesc
[1] & 0x1fe0) == 0x0f00) /* 32 bit Trap gate */
1856 SegType
= "TRAPGATE32";
1857 else if ((SegDesc
[1] & 0x1fe0) == 0x0700) /* 16 bit Trap gate */
1858 SegType
= "TRAPGATE16";
1860 SegType
= "UNKNOWN";
1862 if ((SegDesc
[1] & (1 << 15)) == 0) /* not present */
1864 KdbpPrint(" %03d %-10s [NP] [NP] %02d\n",
1865 i
/ 8, SegType
, Dpl
);
1867 else if ((SegDesc
[1] & 0x1f00) == 0x0500) /* Task gate */
1869 SegSel
= SegDesc
[0] >> 16;
1870 KdbpPrint(" %03d %-10s 0x%04x %02d\n",
1871 i
/ 8, SegType
, SegSel
, Dpl
);
1875 SegSel
= SegDesc
[0] >> 16;
1876 SegBase
= (SegDesc
[1] & 0xffff0000) | (SegDesc
[0] & 0x0000ffff);
1877 KdbpPrint(" %03d %-10s 0x%04x 0x%08x %02d\n",
1878 i
/ 8, SegType
, SegSel
, SegBase
, Dpl
);
1886 if (Argv
[0][0] == 'g')
1889 Ke386GetGlobalDescriptorTable(&Reg
.Limit
);
1894 ASSERT(Argv
[0][0] == 'l');
1897 Reg
.Limit
= Ke386GetLocalDescriptorTable();
1905 KdbpPrint("%s descriptor table is empty.\n",
1906 Argv
[0][0] == 'g' ? "Global" : "Local");
1910 KdbpPrint("%cDT Base: 0x%08x Limit: 0x%04x\n",
1911 Argv
[0][0] == 'g' ? 'G' : 'L', Reg
.Base
, Reg
.Limit
);
1912 KdbpPrint(" Idx Sel. Type Base Limit DPL Attribs\n");
1914 for (; (i
+ sizeof(SegDesc
) - 1) <= Reg
.Limit
; i
+= 8)
1916 if (!NT_SUCCESS(KdbpSafeReadMemory(SegDesc
, (PVOID
)((ULONG_PTR
)Reg
.Base
+ i
), sizeof(SegDesc
))))
1918 KdbpPrint("Couldn't access memory at 0x%08x!\n", (ULONG_PTR
)Reg
.Base
+ i
);
1922 Dpl
= ((SegDesc
[1] >> 13) & 3);
1923 Type
= ((SegDesc
[1] >> 8) & 0xf);
1925 SegBase
= SegDesc
[0] >> 16;
1926 SegBase
|= (SegDesc
[1] & 0xff) << 16;
1927 SegBase
|= SegDesc
[1] & 0xff000000;
1928 SegLimit
= SegDesc
[0] & 0x0000ffff;
1929 SegLimit
|= (SegDesc
[1] >> 16) & 0xf;
1931 if ((SegDesc
[1] & (1 << 23)) != 0)
1941 if ((SegDesc
[1] & (1 << 12)) == 0) /* System segment */
1945 case 1: SegType
= "TSS16(Avl)"; break;
1946 case 2: SegType
= "LDT"; break;
1947 case 3: SegType
= "TSS16(Busy)"; break;
1948 case 4: SegType
= "CALLGATE16"; break;
1949 case 5: SegType
= "TASKGATE"; break;
1950 case 6: SegType
= "INTGATE16"; break;
1951 case 7: SegType
= "TRAPGATE16"; break;
1952 case 9: SegType
= "TSS32(Avl)"; break;
1953 case 11: SegType
= "TSS32(Busy)"; break;
1954 case 12: SegType
= "CALLGATE32"; break;
1955 case 14: SegType
= "INTGATE32"; break;
1956 case 15: SegType
= "INTGATE32"; break;
1957 default: SegType
= "UNKNOWN"; break;
1960 if (!(Type
>= 1 && Type
<= 3) &&
1961 Type
!= 9 && Type
!= 11)
1967 else if ((SegDesc
[1] & (1 << 11)) == 0) /* Data segment */
1969 if ((SegDesc
[1] & (1 << 22)) != 0)
1974 else /* Code segment */
1976 if ((SegDesc
[1] & (1 << 22)) != 0)
1982 if ((SegDesc
[1] & (1 << 15)) == 0) /* not present */
1984 KdbpPrint(" %03d 0x%04x %-11s [NP] [NP] %02d NP\n",
1985 i
/ 8, i
| Dpl
| ul
, SegType
, Dpl
);
1989 KdbpPrint(" %03d 0x%04x %-11s 0x%08x 0x%08x %02d ",
1990 i
/ 8, i
| Dpl
| ul
, SegType
, SegBase
, SegLimit
, Dpl
);
1992 if ((SegDesc
[1] & (1 << 12)) == 0) /* System segment */
1994 /* FIXME: Display system segment */
1996 else if ((SegDesc
[1] & (1 << 11)) == 0) /* Data segment */
1998 if ((SegDesc
[1] & (1 << 10)) != 0) /* Expand-down */
2001 KdbpPrint((SegDesc
[1] & (1 << 9)) ? " R/W" : " R");
2003 if ((SegDesc
[1] & (1 << 8)) != 0)
2006 else /* Code segment */
2008 if ((SegDesc
[1] & (1 << 10)) != 0) /* Conforming */
2011 KdbpPrint((SegDesc
[1] & (1 << 9)) ? " R/X" : " X");
2013 if ((SegDesc
[1] & (1 << 8)) != 0)
2017 if ((SegDesc
[1] & (1 << 20)) != 0)
2029 /*!\brief Displays the KPCR
2036 PKIPCR Pcr
= (PKIPCR
)KeGetPcr();
2039 KdbpPrint("Current PCR is at 0x%08x.\n", (INT
)Pcr
);
2040 KdbpPrint(" Tib.ExceptionList: 0x%08x\n"
2041 " Tib.StackBase: 0x%08x\n"
2042 " Tib.StackLimit: 0x%08x\n"
2043 " Tib.SubSystemTib: 0x%08x\n"
2044 " Tib.FiberData/Version: 0x%08x\n"
2045 " Tib.ArbitraryUserPointer: 0x%08x\n"
2046 " Tib.Self: 0x%08x\n"
2051 " IrrActive: 0x%08x\n"
2053 " KdVersionBlock: 0x%08x\n"
2057 " MajorVersion: 0x%04x\n"
2058 " MinorVersion: 0x%04x\n"
2059 " SetMember: 0x%08x\n"
2060 " StallScaleFactor: 0x%08x\n"
2062 " L2CacheAssociativity: 0x%02x\n"
2063 " VdmAlert: 0x%08x\n"
2064 " L2CacheSize: 0x%08x\n"
2065 " InterruptMode: 0x%08x\n",
2066 Pcr
->NtTib
.ExceptionList
, Pcr
->NtTib
.StackBase
, Pcr
->NtTib
.StackLimit
,
2067 Pcr
->NtTib
.SubSystemTib
, Pcr
->NtTib
.FiberData
, Pcr
->NtTib
.ArbitraryUserPointer
,
2068 Pcr
->NtTib
.Self
, Pcr
->Self
, Pcr
->Prcb
, Pcr
->Irql
, Pcr
->IRR
, Pcr
->IrrActive
,
2069 Pcr
->IDR
, Pcr
->KdVersionBlock
, Pcr
->IDT
, Pcr
->GDT
, Pcr
->TSS
,
2070 Pcr
->MajorVersion
, Pcr
->MinorVersion
, Pcr
->SetMember
, Pcr
->StallScaleFactor
,
2071 Pcr
->Number
, Pcr
->L2CacheAssociativity
,
2072 Pcr
->VdmAlert
, Pcr
->SecondLevelCacheSize
, Pcr
->InterruptMode
);
2073 #elif defined(_M_AMD64)
2074 KdbpPrint("Current PCR is at 0x%x.\n", (INT_PTR
)Pcr
);
2075 KdbpPrint(" Tib.ExceptionList: 0x%p\n"
2076 " Tib.StackBase: 0x%p\n"
2077 " Tib.StackLimit: 0x%x\n"
2078 " Tib.SubSystemTib: 0x%p\n"
2079 " Tib.FiberData/Version: 0x%x\n"
2080 " Tib.ArbitraryUserPointer: 0x%p\n"
2085 " KdVersionBlock: 0x%08x\n"
2090 " MajorVersion: 0x%04x\n"
2091 " MinorVersion: 0x%04x\n"
2092 " StallScaleFactor: 0x%08x\n"
2093 " L2CacheAssociativity: 0x%02x\n"
2094 " L2CacheSize: 0x%08x\n",
2095 Pcr
->NtTib
.ExceptionList
, Pcr
->NtTib
.StackBase
, Pcr
->NtTib
.StackLimit
,
2096 Pcr
->NtTib
.SubSystemTib
, Pcr
->NtTib
.FiberData
, Pcr
->NtTib
.ArbitraryUserPointer
,
2097 Pcr
->NtTib
.Self
, Pcr
->Self
, Pcr
->Prcb
, Pcr
->Irql
,
2098 Pcr
->KdVersionBlock
, Pcr
->IdtBase
, Pcr
->GdtBase
, Pcr
->TssBase
,Pcr
->UserRsp
,
2099 Pcr
->MajorVersion
, Pcr
->MinorVersion
, Pcr
->StallScaleFactor
,
2100 Pcr
->SecondLevelCacheAssociativity
, Pcr
->SecondLevelCacheSize
);
2105 /*!\brief Displays the TSS
2113 KTSS
*Tss
= KeGetPcr()->TSS
;
2115 KdbpPrint("Current TSS is at 0x%p.\n", (INT_PTR
)Tss
);
2116 KdbpPrint(" Eip: 0x%p\n"
2123 " IoMapBase: 0x%04x\n",
2124 Tss
->Eip
, Tss
->Es
, Tss
->Cs
, Tss
->Ds
, Tss
->Fs
, Tss
->Gs
, Tss
->IoMapBase
);
2125 #elif defined(_M_AMD64)
2126 KTSS
*Tss
= KeGetPcr()->TssBase
;
2128 KdbpPrint("Current TSS is at 0x%p.\n", (INT_PTR
)Tss
);
2129 KdbpPrint(" Rsp0: 0x%p\n"
2133 " IoMapBase: 0x%04x\n",
2134 Tss
->Rsp0
, Tss
->Rsp1
, Tss
->Rsp2
, Tss
->Ist
, Tss
->IoMapBase
);
2139 /*!\brief Bugchecks the system.
2146 /* Set the flag and quit looping */
2147 KdbpBugCheckRequested
= TRUE
;
2152 /*!\brief Sets or displays a config variables value.
2162 KDB_ENTER_CONDITION ConditionFirst
= KdbDoNotEnter
;
2163 KDB_ENTER_CONDITION ConditionLast
= KdbDoNotEnter
;
2165 static const PCHAR ExceptionNames
[21] =
2167 "ZERODEVIDE", "DEBUGTRAP", "NMI", "INT3", "OVERFLOW", "BOUND", "INVALIDOP",
2168 "NOMATHCOP", "DOUBLEFAULT", "RESERVED(9)", "INVALIDTSS", "SEGMENTNOTPRESENT",
2169 "STACKFAULT", "GPF", "PAGEFAULT", "RESERVED(15)", "MATHFAULT", "ALIGNMENTCHECK",
2170 "MACHINECHECK", "SIMDFAULT", "OTHERS"
2175 KdbpPrint("Available settings:\n");
2176 KdbpPrint(" syntax [intel|at&t]\n");
2177 KdbpPrint(" condition [exception|*] [first|last] [never|always|kmode|umode]\n");
2178 KdbpPrint(" break_on_module_load [true|false]\n");
2180 else if (strcmp(Argv
[1], "syntax") == 0)
2184 KdbpPrint("syntax = %s\n", KdbUseIntelSyntax
? "intel" : "at&t");
2188 if (_stricmp(Argv
[2], "intel") == 0)
2189 KdbUseIntelSyntax
= TRUE
;
2190 else if (_stricmp(Argv
[2], "at&t") == 0)
2191 KdbUseIntelSyntax
= FALSE
;
2193 KdbpPrint("Unknown syntax '%s'.\n", Argv
[2]);
2196 else if (strcmp(Argv
[1], "condition") == 0)
2200 KdbpPrint("Conditions: (First) (Last)\n");
2201 for (l
= 0; l
< RTL_NUMBER_OF(ExceptionNames
) - 1; l
++)
2203 if (!ExceptionNames
[l
])
2206 if (!KdbpGetEnterCondition(l
, TRUE
, &ConditionFirst
))
2209 if (!KdbpGetEnterCondition(l
, FALSE
, &ConditionLast
))
2212 KdbpPrint(" #%02d %-20s %-8s %-8s\n", l
, ExceptionNames
[l
],
2213 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst
),
2214 KDB_ENTER_CONDITION_TO_STRING(ConditionLast
));
2217 ASSERT(l
== (RTL_NUMBER_OF(ExceptionNames
) - 1));
2218 KdbpPrint(" %-20s %-8s %-8s\n", ExceptionNames
[l
],
2219 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst
),
2220 KDB_ENTER_CONDITION_TO_STRING(ConditionLast
));
2224 if (Argc
>= 5 && strcmp(Argv
[2], "*") == 0) /* Allow * only when setting condition */
2230 l
= strtoul(Argv
[2], &pend
, 0);
2232 if (Argv
[2] == pend
)
2234 for (l
= 0; l
< RTL_NUMBER_OF(ExceptionNames
); l
++)
2236 if (!ExceptionNames
[l
])
2239 if (_stricmp(ExceptionNames
[l
], Argv
[2]) == 0)
2244 if (l
>= RTL_NUMBER_OF(ExceptionNames
))
2246 KdbpPrint("Unknown exception '%s'.\n", Argv
[2]);
2253 if (_stricmp(Argv
[3], "first") == 0)
2255 else if (_stricmp(Argv
[3], "last") == 0)
2259 KdbpPrint("set condition: second argument must be 'first' or 'last'\n");
2263 if (_stricmp(Argv
[4], "never") == 0)
2264 ConditionFirst
= KdbDoNotEnter
;
2265 else if (_stricmp(Argv
[4], "always") == 0)
2266 ConditionFirst
= KdbEnterAlways
;
2267 else if (_stricmp(Argv
[4], "umode") == 0)
2268 ConditionFirst
= KdbEnterFromUmode
;
2269 else if (_stricmp(Argv
[4], "kmode") == 0)
2270 ConditionFirst
= KdbEnterFromKmode
;
2273 KdbpPrint("set condition: third argument must be 'never', 'always', 'umode' or 'kmode'\n");
2277 if (!KdbpSetEnterCondition(l
, First
, ConditionFirst
))
2280 KdbpPrint("Couldn't change condition for exception #%02d\n", l
);
2282 KdbpPrint("Couldn't change condition for all exceptions\n", l
);
2285 else /* Argc >= 3 */
2287 if (!KdbpGetEnterCondition(l
, TRUE
, &ConditionFirst
))
2290 if (!KdbpGetEnterCondition(l
, FALSE
, &ConditionLast
))
2293 if (l
< (RTL_NUMBER_OF(ExceptionNames
) - 1))
2295 KdbpPrint("Condition for exception #%02d (%s): FirstChance %s LastChance %s\n",
2296 l
, ExceptionNames
[l
],
2297 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst
),
2298 KDB_ENTER_CONDITION_TO_STRING(ConditionLast
));
2302 KdbpPrint("Condition for all other exceptions: FirstChance %s LastChance %s\n",
2303 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst
),
2304 KDB_ENTER_CONDITION_TO_STRING(ConditionLast
));
2309 else if (strcmp(Argv
[1], "break_on_module_load") == 0)
2312 KdbpPrint("break_on_module_load = %s\n", KdbBreakOnModuleLoad
? "enabled" : "disabled");
2315 if (_stricmp(Argv
[2], "enable") == 0 || _stricmp(Argv
[2], "enabled") == 0 || _stricmp(Argv
[2], "true") == 0)
2316 KdbBreakOnModuleLoad
= TRUE
;
2317 else if (_stricmp(Argv
[2], "disable") == 0 || _stricmp(Argv
[2], "disabled") == 0 || _stricmp(Argv
[2], "false") == 0)
2318 KdbBreakOnModuleLoad
= FALSE
;
2320 KdbpPrint("Unknown setting '%s'.\n", Argv
[2]);
2325 KdbpPrint("Unknown setting '%s'.\n", Argv
[1]);
2331 /*!\brief Displays help screen.
2340 KdbpPrint("Kernel debugger commands:\n");
2341 for (i
= 0; i
< RTL_NUMBER_OF(KdbDebuggerCommands
); i
++)
2343 if (!KdbDebuggerCommands
[i
].Syntax
) /* Command group */
2348 KdbpPrint("\x1b[7m* %s:\x1b[0m\n", KdbDebuggerCommands
[i
].Help
);
2352 KdbpPrint(" %-20s - %s\n",
2353 KdbDebuggerCommands
[i
].Syntax
,
2354 KdbDebuggerCommands
[i
].Help
);
2360 /*!\brief Prints the given string with printf-like formatting.
2362 * \param Format Format of the string/arguments.
2363 * \param ... Variable number of arguments matching the format specified in \a Format.
2365 * \note Doesn't correctly handle \\t and terminal escape sequences when calculating the
2366 * number of lines required to print a single line from the Buffer in the terminal.
2373 static CHAR Buffer
[4096];
2374 static BOOLEAN TerminalInitialized
= FALSE
;
2375 static BOOLEAN TerminalConnected
= FALSE
;
2376 static BOOLEAN TerminalReportsSize
= TRUE
;
2381 LONG RowsPrintedByTerminal
;
2385 /* Check if the user has aborted output of the current command */
2386 if (KdbOutputAborted
)
2389 /* Initialize the terminal */
2390 if (!TerminalInitialized
)
2392 DbgPrint("\x1b[7h"); /* Enable linewrap */
2394 /* Query terminal type */
2395 /*DbgPrint("\x1b[Z");*/
2398 TerminalInitialized
= TRUE
;
2400 KeStallExecutionProcessor(100000);
2404 c
= KdbpTryGetCharSerial(5000);
2408 Buffer
[Length
++] = c
;
2409 if (Length
>= (sizeof (Buffer
) - 1))
2413 Buffer
[Length
] = '\0';
2415 TerminalConnected
= TRUE
;
2418 /* Get number of rows and columns in terminal */
2419 if ((KdbNumberOfRowsTerminal
< 0) || (KdbNumberOfColsTerminal
< 0) ||
2420 (KdbNumberOfRowsPrinted
) == 0) /* Refresh terminal size each time when number of rows printed is 0 */
2422 if ((KdbDebugState
& KD_DEBUG_KDSERIAL
) && TerminalConnected
&& TerminalReportsSize
)
2424 /* Try to query number of rows from terminal. A reply looks like "\x1b[8;24;80t" */
2425 TerminalReportsSize
= FALSE
;
2426 KeStallExecutionProcessor(100000);
2427 DbgPrint("\x1b[18t");
2428 c
= KdbpTryGetCharSerial(5000);
2432 c
= KdbpTryGetCharSerial(5000);
2439 c
= KdbpTryGetCharSerial(5000);
2443 Buffer
[Length
++] = c
;
2444 if (isalpha(c
) || Length
>= (sizeof (Buffer
) - 1))
2448 Buffer
[Length
] = '\0';
2449 if (Buffer
[0] == '8' && Buffer
[1] == ';')
2451 for (i
= 2; (i
< Length
) && (Buffer
[i
] != ';'); i
++);
2453 if (Buffer
[i
] == ';')
2457 /* Number of rows is now at Buffer + 2 and number of cols at Buffer + i */
2458 KdbNumberOfRowsTerminal
= strtoul(Buffer
+ 2, NULL
, 0);
2459 KdbNumberOfColsTerminal
= strtoul(Buffer
+ i
, NULL
, 0);
2460 TerminalReportsSize
= TRUE
;
2464 /* Clear further characters */
2465 while ((c
= KdbpTryGetCharSerial(5000)) != -1);
2469 if (KdbNumberOfRowsTerminal
<= 0)
2471 /* Set number of rows to the default. */
2472 KdbNumberOfRowsTerminal
= 24;
2474 else if (KdbNumberOfColsTerminal
<= 0)
2476 /* Set number of cols to the default. */
2477 KdbNumberOfColsTerminal
= 80;
2481 /* Get the string */
2482 va_start(ap
, Format
);
2483 Length
= _vsnprintf(Buffer
, sizeof (Buffer
) - 1, Format
, ap
);
2484 Buffer
[Length
] = '\0';
2488 while (p
[0] != '\0')
2490 i
= strcspn(p
, "\n");
2492 /* Calculate the number of lines which will be printed in the terminal
2493 * when outputting the current line
2496 RowsPrintedByTerminal
= (i
+ KdbNumberOfColsPrinted
- 1) / KdbNumberOfColsTerminal
;
2498 RowsPrintedByTerminal
= 0;
2501 RowsPrintedByTerminal
++;
2503 /*DbgPrint("!%d!%d!%d!%d!", KdbNumberOfRowsPrinted, KdbNumberOfColsPrinted, i, RowsPrintedByTerminal);*/
2505 /* Display a prompt if we printed one screen full of text */
2506 if (KdbNumberOfRowsTerminal
> 0 &&
2507 (LONG
)(KdbNumberOfRowsPrinted
+ RowsPrintedByTerminal
) >= KdbNumberOfRowsTerminal
)
2509 if (KdbNumberOfColsPrinted
> 0)
2512 DbgPrint("--- Press q to abort, any other key to continue ---");
2514 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
2515 c
= KdbpGetCharSerial();
2517 c
= KdbpGetCharKeyboard(&ScanCode
);
2521 /* Try to read '\n' which might follow '\r' - if \n is not received here
2522 * it will be interpreted as "return" when the next command should be read.
2524 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
2525 c
= KdbpTryGetCharSerial(5);
2527 c
= KdbpTryGetCharKeyboard(&ScanCode
, 5);
2533 KdbOutputAborted
= TRUE
;
2537 KdbNumberOfRowsPrinted
= 0;
2538 KdbNumberOfColsPrinted
= 0;
2541 /* Insert a NUL after the line and print only the current line. */
2542 if (p
[i
] == '\n' && p
[i
+ 1] != '\0')
2552 /* Remove escape sequences from the line if there's no terminal connected */
2553 if (!TerminalConnected
)
2555 while ((p2
= strrchr(p
, '\x1b'))) /* Look for escape character */
2560 while (!isalpha(p2
[j
++]));
2575 /* Set p to the start of the next line and
2576 * remember the number of rows/cols printed
2582 KdbNumberOfColsPrinted
= 0;
2586 ASSERT(p
[0] == '\0');
2587 KdbNumberOfColsPrinted
+= i
;
2590 KdbNumberOfRowsPrinted
+= RowsPrintedByTerminal
;
2594 /*!\brief Appends a command to the command history
2596 * \param Command Pointer to the command to append to the history.
2599 KdbpCommandHistoryAppend(
2602 ULONG Length1
= strlen(Command
) + 1;
2607 ASSERT(Length1
<= RTL_NUMBER_OF(KdbCommandHistoryBuffer
));
2610 (KdbCommandHistory
[KdbCommandHistoryIndex
] &&
2611 strcmp(KdbCommandHistory
[KdbCommandHistoryIndex
], Command
) == 0))
2616 /* Calculate Length1 and Length2 */
2617 Buffer
= KdbCommandHistoryBuffer
+ KdbCommandHistoryBufferIndex
;
2618 KdbCommandHistoryBufferIndex
+= Length1
;
2619 if (KdbCommandHistoryBufferIndex
>= (LONG
)RTL_NUMBER_OF(KdbCommandHistoryBuffer
))
2621 KdbCommandHistoryBufferIndex
-= RTL_NUMBER_OF(KdbCommandHistoryBuffer
);
2622 Length2
= KdbCommandHistoryBufferIndex
;
2626 /* Remove previous commands until there is enough space to append the new command */
2627 for (i
= KdbCommandHistoryIndex
; KdbCommandHistory
[i
];)
2630 (KdbCommandHistory
[i
] >= Buffer
||
2631 KdbCommandHistory
[i
] < (KdbCommandHistoryBuffer
+ KdbCommandHistoryBufferIndex
))) ||
2633 (KdbCommandHistory
[i
] >= Buffer
&&
2634 KdbCommandHistory
[i
] < (KdbCommandHistoryBuffer
+ KdbCommandHistoryBufferIndex
))))
2636 KdbCommandHistory
[i
] = NULL
;
2641 i
= RTL_NUMBER_OF(KdbCommandHistory
) - 1;
2643 if (i
== KdbCommandHistoryIndex
)
2647 /* Make sure the new command history entry is free */
2648 KdbCommandHistoryIndex
++;
2649 KdbCommandHistoryIndex
%= RTL_NUMBER_OF(KdbCommandHistory
);
2650 if (KdbCommandHistory
[KdbCommandHistoryIndex
])
2652 KdbCommandHistory
[KdbCommandHistoryIndex
] = NULL
;
2655 /* Append command */
2656 KdbCommandHistory
[KdbCommandHistoryIndex
] = Buffer
;
2657 ASSERT((KdbCommandHistory
[KdbCommandHistoryIndex
] + Length1
) <= KdbCommandHistoryBuffer
+ RTL_NUMBER_OF(KdbCommandHistoryBuffer
));
2658 memcpy(KdbCommandHistory
[KdbCommandHistoryIndex
], Command
, Length1
);
2661 memcpy(KdbCommandHistoryBuffer
, Command
+ Length1
, Length2
);
2665 /*!\brief Reads a line of user-input.
2667 * \param Buffer Buffer to store the input into. Trailing newlines are removed.
2668 * \param Size Size of \a Buffer.
2670 * \note Accepts only \n newlines, \r is ignored.
2678 PCHAR Orig
= Buffer
;
2681 static CHAR LastCommand
[1024] = "";
2682 static CHAR NextKey
= '\0';
2683 INT CmdHistIndex
= -1;
2686 EchoOn
= !((KdbDebugState
& KD_DEBUG_KDNOECHO
) != 0);
2690 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
2692 Key
= (NextKey
== '\0') ? KdbpGetCharSerial() : NextKey
;
2695 if (Key
== KEY_ESC
) /* ESC */
2697 Key
= KdbpGetCharSerial();
2700 Key
= KdbpGetCharSerial();
2705 ScanCode
= KEY_SCAN_UP
;
2708 ScanCode
= KEY_SCAN_DOWN
;
2721 Key
= (NextKey
== '\0') ? KdbpGetCharKeyboard(&ScanCode
) : NextKey
;
2725 if ((ULONG
)(Buffer
- Orig
) >= (Size
- 1))
2727 /* Buffer is full, accept only newlines */
2734 /* Read the next char - this is to throw away a \n which most clients should
2737 KeStallExecutionProcessor(100000);
2739 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
2740 NextKey
= KdbpTryGetCharSerial(5);
2742 NextKey
= KdbpTryGetCharKeyboard(&ScanCode
, 5);
2744 if (NextKey
== '\n' || NextKey
== -1) /* \n or no response at all */
2750 * Repeat the last command if the user presses enter. Reduces the
2751 * risk of RSI when single-stepping.
2755 strncpy(Buffer
, LastCommand
, Size
);
2756 Buffer
[Size
- 1] = '\0';
2761 strncpy(LastCommand
, Orig
, sizeof (LastCommand
));
2762 LastCommand
[sizeof (LastCommand
) - 1] = '\0';
2767 else if (Key
== KEY_BS
|| Key
== KEY_DEL
)
2775 KdbpPrint("%c %c", KEY_BS
, KEY_BS
);
2777 KdbpPrint(" %c", KEY_BS
);
2780 else if (ScanCode
== KEY_SCAN_UP
)
2782 BOOLEAN Print
= TRUE
;
2784 if (CmdHistIndex
< 0)
2786 CmdHistIndex
= KdbCommandHistoryIndex
;
2790 i
= CmdHistIndex
- 1;
2793 CmdHistIndex
= RTL_NUMBER_OF(KdbCommandHistory
) - 1;
2795 if (KdbCommandHistory
[i
] && i
!= KdbCommandHistoryIndex
)
2801 if (Print
&& KdbCommandHistory
[CmdHistIndex
])
2803 while (Buffer
> Orig
)
2809 KdbpPrint("%c %c", KEY_BS
, KEY_BS
);
2811 KdbpPrint(" %c", KEY_BS
);
2814 i
= min(strlen(KdbCommandHistory
[CmdHistIndex
]), Size
- 1);
2815 memcpy(Orig
, KdbCommandHistory
[CmdHistIndex
], i
);
2818 KdbpPrint("%s", Orig
);
2821 else if (ScanCode
== KEY_SCAN_DOWN
)
2823 if (CmdHistIndex
> 0 && CmdHistIndex
!= KdbCommandHistoryIndex
)
2825 i
= CmdHistIndex
+ 1;
2826 if (i
>= (INT
)RTL_NUMBER_OF(KdbCommandHistory
))
2829 if (KdbCommandHistory
[i
])
2832 while (Buffer
> Orig
)
2838 KdbpPrint("%c %c", KEY_BS
, KEY_BS
);
2840 KdbpPrint(" %c", KEY_BS
);
2843 i
= min(strlen(KdbCommandHistory
[CmdHistIndex
]), Size
- 1);
2844 memcpy(Orig
, KdbCommandHistory
[CmdHistIndex
], i
);
2847 KdbpPrint("%s", Orig
);
2854 KdbpPrint("%c", Key
);
2862 /*!\brief Parses command line and executes command if found
2864 * \param Command Command line to parse and execute if possible.
2866 * \retval TRUE Don't continue execution.
2867 * \retval FALSE Continue execution (leave KDB)
2876 static PCH Argv
[256];
2877 static CHAR OrigCommand
[1024];
2879 strncpy(OrigCommand
, Command
, sizeof(OrigCommand
) - 1);
2880 OrigCommand
[sizeof(OrigCommand
) - 1] = '\0';
2887 while (*p
== '\t' || *p
== ' ')
2893 i
= strcspn(p
, "\t ");
2906 for (i
= 0; i
< RTL_NUMBER_OF(KdbDebuggerCommands
); i
++)
2908 if (!KdbDebuggerCommands
[i
].Name
)
2911 if (strcmp(KdbDebuggerCommands
[i
].Name
, Argv
[0]) == 0)
2913 return KdbDebuggerCommands
[i
].Fn(Argc
, Argv
);
2917 KdbpPrint("Command '%s' is unknown.\n", OrigCommand
);
2921 /*!\brief KDB Main Loop.
2923 * \param EnteredOnSingleStep TRUE if KDB was entered on single step.
2927 IN BOOLEAN EnteredOnSingleStep
)
2929 static CHAR Command
[1024];
2932 if (EnteredOnSingleStep
)
2934 if (!KdbSymPrintAddress((PVOID
)KdbCurrentTrapFrame
->Tf
.Eip
))
2936 KdbpPrint("<%x>", KdbCurrentTrapFrame
->Tf
.Eip
);
2940 if (KdbpDisassemble(KdbCurrentTrapFrame
->Tf
.Eip
, KdbUseIntelSyntax
) < 0)
2942 KdbpPrint("<INVALID>");
2947 /* Flush the input buffer */
2948 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
2950 while (KdbpTryGetCharSerial(1) != -1);
2955 while (KdbpTryGetCharKeyboard(&ScanCode
, 1) != -1);
2961 /* Print the prompt */
2962 KdbpPrint("kdb:> ");
2964 /* Read a command and remember it */
2965 KdbpReadCommand(Command
, sizeof (Command
));
2966 KdbpCommandHistoryAppend(Command
);
2968 /* Reset the number of rows/cols printed and output aborted state */
2969 KdbNumberOfRowsPrinted
= KdbNumberOfColsPrinted
= 0;
2970 KdbOutputAborted
= FALSE
;
2972 /* Call the command */
2973 Continue
= KdbpDoCommand(Command
);
2978 /*!\brief Called when a module is loaded.
2980 * \param Name Filename of the module which was loaded.
2983 KdbpCliModuleLoaded(
2984 IN PUNICODE_STRING Name
)
2986 if (!KdbBreakOnModuleLoad
)
2989 KdbpPrint("Module %wZ loaded.\n", Name
);
2990 DbgBreakPointWithStatus(DBG_STATUS_CONTROL_C
);
2993 /*!\brief This function is called by KdbEnterDebuggerException...
2995 * Used to interpret the init file in a context with a trapframe setup
2996 * (KdbpCliInit call KdbEnter which will call KdbEnterDebuggerException which will
2997 * call this function if KdbInitFileBuffer is not NULL.
3000 KdbpCliInterpretInitFile()
3006 /* Execute the commands in the init file */
3007 DPRINT("KDB: Executing KDBinit file...\n");
3008 p1
= KdbInitFileBuffer
;
3009 while (p1
[0] != '\0')
3011 i
= strcspn(p1
, "\r\n");
3017 /* Look for "break" command and comments */
3020 while (isspace(p2
[0]))
3023 if (strncmp(p2
, "break", sizeof("break")-1) == 0 &&
3024 (p2
[sizeof("break")-1] == '\0' || isspace(p2
[sizeof("break")-1])))
3026 /* break into the debugger */
3027 KdbpCliMainLoop(FALSE
);
3029 else if (p2
[0] != '#' && p2
[0] != '\0') /* Ignore empty lines and comments */
3038 while (p1
[0] == '\r' || p1
[0] == '\n')
3041 DPRINT("KDB: KDBinit executed\n");
3044 /*!\brief Called when KDB is initialized
3046 * Reads the KDBinit file from the SystemRoot\system32\drivers\etc directory and executes it.
3052 OBJECT_ATTRIBUTES ObjectAttributes
;
3053 UNICODE_STRING FileName
;
3054 IO_STATUS_BLOCK Iosb
;
3055 FILE_STANDARD_INFORMATION FileStdInfo
;
3056 HANDLE hFile
= NULL
;
3061 /* Initialize the object attributes */
3062 RtlInitUnicodeString(&FileName
, L
"\\SystemRoot\\system32\\drivers\\etc\\KDBinit");
3063 InitializeObjectAttributes(&ObjectAttributes
, &FileName
, 0, NULL
, NULL
);
3066 Status
= ZwOpenFile(&hFile
, FILE_READ_DATA
, &ObjectAttributes
, &Iosb
, 0,
3067 FILE_NON_DIRECTORY_FILE
| FILE_SYNCHRONOUS_IO_NONALERT
|
3068 FILE_NO_INTERMEDIATE_BUFFERING
);
3069 if (!NT_SUCCESS(Status
))
3071 DPRINT("Could not open \\SystemRoot\\system32\\drivers\\etc\\KDBinit (Status 0x%x)", Status
);
3075 /* Get the size of the file */
3076 Status
= ZwQueryInformationFile(hFile
, &Iosb
, &FileStdInfo
, sizeof (FileStdInfo
),
3077 FileStandardInformation
);
3078 if (!NT_SUCCESS(Status
))
3081 DPRINT("Could not query size of \\SystemRoot\\system32\\drivers\\etc\\KDBinit (Status 0x%x)", Status
);
3084 FileSize
= FileStdInfo
.EndOfFile
.u
.LowPart
;
3086 /* Allocate memory for the file */
3087 FileBuffer
= ExAllocatePool(PagedPool
, FileSize
+ 1); /* add 1 byte for terminating '\0' */
3091 DPRINT("Could not allocate %d bytes for KDBinit file\n", FileSize
);
3095 /* Load file into memory */
3096 Status
= ZwReadFile(hFile
, 0, 0, 0, &Iosb
, FileBuffer
, FileSize
, 0, 0);
3099 if (!NT_SUCCESS(Status
) && Status
!= STATUS_END_OF_FILE
)
3101 ExFreePool(FileBuffer
);
3102 DPRINT("Could not read KDBinit file into memory (Status 0x%lx)\n", Status
);
3106 FileSize
= min(FileSize
, (INT
)Iosb
.Information
);
3107 FileBuffer
[FileSize
] = '\0';
3109 /* Enter critical section */
3110 OldEflags
= __readeflags();
3113 /* Interpret the init file... */
3114 KdbInitFileBuffer
= FileBuffer
;
3116 KdbInitFileBuffer
= NULL
;
3118 /* Leave critical section */
3119 __writeeflags(OldEflags
);
3121 ExFreePool(FileBuffer
);
3126 KdpSerialDebugPrint(
3131 STRING KdpPromptString
= RTL_CONSTANT_STRING("kdb:> ");
3132 extern KSPIN_LOCK KdpSerialSpinLock
;
3136 KdpPrompt(IN LPSTR InString
,
3137 IN USHORT InStringLength
,
3138 OUT LPSTR OutString
,
3139 IN USHORT OutStringLength
)
3143 ULONG DummyScanCode
;
3146 /* Acquire the printing spinlock without waiting at raised IRQL */
3149 /* Wait when the spinlock becomes available */
3150 while (!KeTestSpinLock(&KdpSerialSpinLock
));
3152 /* Spinlock was free, raise IRQL */
3153 KeRaiseIrql(HIGH_LEVEL
, &OldIrql
);
3155 /* Try to get the spinlock */
3156 if (KeTryToAcquireSpinLockAtDpcLevel(&KdpSerialSpinLock
))
3159 /* Someone else got the spinlock, lower IRQL back */
3160 KeLowerIrql(OldIrql
);
3163 /* Loop the string to send */
3164 for (i
= 0; i
< InStringLength
; i
++)
3166 /* Print it to serial */
3167 KdPortPutByteEx(&SerialPortInfo
, *(PCHAR
)(InString
+ i
));
3170 /* Print a new line for log neatness */
3171 KdPortPutByteEx(&SerialPortInfo
, '\r');
3172 KdPortPutByteEx(&SerialPortInfo
, '\n');
3174 /* Print the kdb prompt */
3175 for (i
= 0; i
< KdpPromptString
.Length
; i
++)
3177 /* Print it to serial */
3178 KdPortPutByteEx(&SerialPortInfo
,
3179 *(KdpPromptString
.Buffer
+ i
));
3182 /* Loop the whole string */
3183 for (i
= 0; i
< OutStringLength
; i
++)
3185 /* Check if this is serial debugging mode */
3186 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
3188 /* Get the character from serial */
3191 Response
= KdbpTryGetCharSerial(MAXULONG
);
3192 } while (Response
== -1);
3196 /* Get the response from the keyboard */
3199 Response
= KdbpTryGetCharKeyboard(&DummyScanCode
, MAXULONG
);
3200 } while (Response
== -1);
3203 /* Check for return */
3204 if (Response
== '\r')
3207 * We might need to discard the next '\n'.
3208 * Wait a bit to make sure we receive it.
3210 KeStallExecutionProcessor(100000);
3212 /* Check the mode */
3213 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
3215 /* Read and discard the next character, if any */
3216 KdbpTryGetCharSerial(5);
3220 /* Read and discard the next character, if any */
3221 KdbpTryGetCharKeyboard(&DummyScanCode
, 5);
3225 * Null terminate the output string -- documentation states that
3226 * DbgPrompt does not null terminate, but it does
3228 *(PCHAR
)(OutString
+ i
) = 0;
3230 /* Print a new line */
3231 KdPortPutByteEx(&SerialPortInfo
, '\r');
3232 KdPortPutByteEx(&SerialPortInfo
, '\n');
3234 /* Release spinlock */
3235 KiReleaseSpinLock(&KdpSerialSpinLock
);
3237 /* Lower IRQL back */
3238 KeLowerIrql(OldIrql
);
3240 /* Return the length */
3241 return OutStringLength
+ 1;
3244 /* Write it back and print it to the log */
3245 *(PCHAR
)(OutString
+ i
) = Response
;
3246 KdPortPutByteEx(&SerialPortInfo
, Response
);
3249 /* Print a new line */
3250 KdPortPutByteEx(&SerialPortInfo
, '\r');
3251 KdPortPutByteEx(&SerialPortInfo
, '\n');
3253 /* Release spinlock */
3254 KiReleaseSpinLock(&KdpSerialSpinLock
);
3256 /* Lower IRQL back */
3257 KeLowerIrql(OldIrql
);
3259 /* Return the length */
3260 return OutStringLength
;