3 * Copyright (C) 2005 ReactOS Team
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 * PROJECT: ReactOS kernel
21 * FILE: ntoskrnl/dbg/kdb_cli.c
22 * PURPOSE: Kernel debugger command line interface
23 * PROGRAMMER: Gregor Anich (blight@blight.eu.org)
29 /* INCLUDES ******************************************************************/
36 /* DEFINES *******************************************************************/
42 #define KEY_SCAN_UP 72
43 #define KEY_SCAN_DOWN 80
45 #define KDB_ENTER_CONDITION_TO_STRING(cond) \
46 ((cond) == KdbDoNotEnter ? "never" : \
47 ((cond) == KdbEnterAlways ? "always" : \
48 ((cond) == KdbEnterFromKmode ? "kmode" : "umode")))
50 #define KDB_ACCESS_TYPE_TO_STRING(type) \
51 ((type) == KdbAccessRead ? "read" : \
52 ((type) == KdbAccessWrite ? "write" : \
53 ((type) == KdbAccessReadWrite ? "rdwr" : "exec")))
55 #define NPX_STATE_TO_STRING(state) \
56 ((state) == NPX_STATE_LOADED ? "Loaded" : \
57 ((state) == NPX_STATE_NOT_LOADED ? "Not loaded" : "Unknown"))
59 /* PROTOTYPES ****************************************************************/
61 static BOOLEAN
KdbpCmdEvalExpression(ULONG Argc
, PCHAR Argv
[]);
62 static BOOLEAN
KdbpCmdDisassembleX(ULONG Argc
, PCHAR Argv
[]);
63 static BOOLEAN
KdbpCmdRegs(ULONG Argc
, PCHAR Argv
[]);
64 static BOOLEAN
KdbpCmdBackTrace(ULONG Argc
, PCHAR Argv
[]);
66 static BOOLEAN
KdbpCmdContinue(ULONG Argc
, PCHAR Argv
[]);
67 static BOOLEAN
KdbpCmdStep(ULONG Argc
, PCHAR Argv
[]);
68 static BOOLEAN
KdbpCmdBreakPointList(ULONG Argc
, PCHAR Argv
[]);
69 static BOOLEAN
KdbpCmdEnableDisableClearBreakPoint(ULONG Argc
, PCHAR Argv
[]);
70 static BOOLEAN
KdbpCmdBreakPoint(ULONG Argc
, PCHAR Argv
[]);
72 static BOOLEAN
KdbpCmdThread(ULONG Argc
, PCHAR Argv
[]);
73 static BOOLEAN
KdbpCmdProc(ULONG Argc
, PCHAR Argv
[]);
75 static BOOLEAN
KdbpCmdMod(ULONG Argc
, PCHAR Argv
[]);
76 static BOOLEAN
KdbpCmdGdtLdtIdt(ULONG Argc
, PCHAR Argv
[]);
77 static BOOLEAN
KdbpCmdPcr(ULONG Argc
, PCHAR Argv
[]);
78 static BOOLEAN
KdbpCmdTss(ULONG Argc
, PCHAR Argv
[]);
80 static BOOLEAN
KdbpCmdBugCheck(ULONG Argc
, PCHAR Argv
[]);
81 static BOOLEAN
KdbpCmdFilter(ULONG Argc
, PCHAR Argv
[]);
82 static BOOLEAN
KdbpCmdSet(ULONG Argc
, PCHAR Argv
[]);
83 static BOOLEAN
KdbpCmdHelp(ULONG Argc
, PCHAR Argv
[]);
85 /* GLOBALS *******************************************************************/
87 static BOOLEAN KdbUseIntelSyntax
= FALSE
; /* Set to TRUE for intel syntax */
88 static BOOLEAN KdbBreakOnModuleLoad
= FALSE
; /* Set to TRUE to break into KDB when a module is loaded */
90 static CHAR KdbCommandHistoryBuffer
[2048]; /* Command history string ringbuffer */
91 static PCHAR KdbCommandHistory
[sizeof(KdbCommandHistoryBuffer
) / 8] = { NULL
}; /* Command history ringbuffer */
92 static LONG KdbCommandHistoryBufferIndex
= 0;
93 static LONG KdbCommandHistoryIndex
= 0;
95 static ULONG KdbNumberOfRowsPrinted
= 0;
96 static ULONG KdbNumberOfColsPrinted
= 0;
97 static BOOLEAN KdbOutputAborted
= FALSE
;
98 static LONG KdbNumberOfRowsTerminal
= -1;
99 static LONG KdbNumberOfColsTerminal
= -1;
101 PCHAR KdbInitFileBuffer
= NULL
; /* Buffer where KDBinit file is loaded into during initialization */
102 BOOLEAN KdbpBugCheckRequested
= FALSE
;
109 BOOLEAN (*Fn
)(ULONG Argc
, PCHAR Argv
[]);
110 } KdbDebuggerCommands
[] = {
112 { NULL
, NULL
, "Data", NULL
},
113 { "?", "? expression", "Evaluate expression.", KdbpCmdEvalExpression
},
114 { "disasm", "disasm [address] [L count]", "Disassemble count instructions at address.", KdbpCmdDisassembleX
},
115 { "x", "x [address] [L count]", "Display count dwords, starting at addr.", KdbpCmdDisassembleX
},
116 { "regs", "regs", "Display general purpose registers.", KdbpCmdRegs
},
117 { "cregs", "cregs", "Display control registers.", KdbpCmdRegs
},
118 { "sregs", "sregs", "Display status registers.", KdbpCmdRegs
},
119 { "dregs", "dregs", "Display debug registers.", KdbpCmdRegs
},
120 { "bt", "bt [*frameaddr|thread id]", "Prints current backtrace or from given frame addr", KdbpCmdBackTrace
},
123 { NULL
, NULL
, "Flow control", NULL
},
124 { "cont", "cont", "Continue execution (leave debugger)", KdbpCmdContinue
},
125 { "step", "step [count]", "Execute single instructions, stepping into interrupts.", KdbpCmdStep
},
126 { "next", "next [count]", "Execute single instructions, skipping calls and reps.", KdbpCmdStep
},
127 { "bl", "bl", "List breakpoints.", KdbpCmdBreakPointList
},
128 { "be", "be [breakpoint]", "Enable breakpoint.", KdbpCmdEnableDisableClearBreakPoint
},
129 { "bd", "bd [breakpoint]", "Disable breakpoint.", KdbpCmdEnableDisableClearBreakPoint
},
130 { "bc", "bc [breakpoint]", "Clear breakpoint.", KdbpCmdEnableDisableClearBreakPoint
},
131 { "bpx", "bpx [address] [IF condition]", "Set software execution breakpoint at address.", KdbpCmdBreakPoint
},
132 { "bpm", "bpm [r|w|rw|x] [byte|word|dword] [address] [IF condition]", "Set memory breakpoint at address.", KdbpCmdBreakPoint
},
135 { NULL
, NULL
, "Process/Thread", NULL
},
136 { "thread", "thread [list[ pid]|[attach ]tid]", "List threads in current or specified process, display thread with given id or attach to thread.", KdbpCmdThread
},
137 { "proc", "proc [list|[attach ]pid]", "List processes, display process with given id or attach to process.", KdbpCmdProc
},
139 /* System information */
140 { NULL
, NULL
, "System info", NULL
},
141 { "mod", "mod [address]", "List all modules or the one containing address.", KdbpCmdMod
},
142 { "gdt", "gdt", "Display global descriptor table.", KdbpCmdGdtLdtIdt
},
143 { "ldt", "ldt", "Display local descriptor table.", KdbpCmdGdtLdtIdt
},
144 { "idt", "idt", "Display interrupt descriptor table.", KdbpCmdGdtLdtIdt
},
145 { "pcr", "pcr", "Display processor control region.", KdbpCmdPcr
},
146 { "tss", "tss", "Display task state segment.", KdbpCmdTss
},
149 { NULL
, NULL
, "Others", NULL
},
150 { "bugcheck", "bugcheck", "Bugchecks the system.", KdbpCmdBugCheck
},
151 { "filter", "filter [error|warning|trace|info|level]+|-[componentname|default]", "Enable/disable debug channels", KdbpCmdFilter
},
152 { "set", "set [var] [value]", "Sets var to value or displays value of var.", KdbpCmdSet
},
153 { "help", "help", "Display help screen.", KdbpCmdHelp
}
156 /* FUNCTIONS *****************************************************************/
158 /*!\brief Transform a component name to an integer
160 * \param ComponentName The name of the component.
161 * \param ComponentId Receives the component id on success.
163 * \retval TRUE Success.
164 * \retval FALSE Failure.
168 IN PCCH ComponentName
,
169 OUT PULONG ComponentId
)
180 { "DEFAULT", DPFLTR_DEFAULT_ID
},
181 { "SYSTEM", DPFLTR_SYSTEM_ID
},
182 { "SMSS", DPFLTR_SMSS_ID
},
183 { "SETUP", DPFLTR_SETUP_ID
},
184 { "NTFS", DPFLTR_NTFS_ID
},
185 { "FSTUB", DPFLTR_FSTUB_ID
},
186 { "CRASHDUMP", DPFLTR_CRASHDUMP_ID
},
187 { "CDAUDIO", DPFLTR_CDAUDIO_ID
},
188 { "CDROM", DPFLTR_CDROM_ID
},
189 { "CLASSPNP", DPFLTR_CLASSPNP_ID
},
190 { "DISK", DPFLTR_DISK_ID
},
191 { "REDBOOK", DPFLTR_REDBOOK_ID
},
192 { "STORPROP", DPFLTR_STORPROP_ID
},
193 { "SCSIPORT", DPFLTR_SCSIPORT_ID
},
194 { "SCSIMINIPORT", DPFLTR_SCSIMINIPORT_ID
},
195 { "CONFIG", DPFLTR_CONFIG_ID
},
196 { "I8042PRT", DPFLTR_I8042PRT_ID
},
197 { "SERMOUSE", DPFLTR_SERMOUSE_ID
},
198 { "LSERMOUS", DPFLTR_LSERMOUS_ID
},
199 { "KBDHID", DPFLTR_KBDHID_ID
},
200 { "MOUHID", DPFLTR_MOUHID_ID
},
201 { "KBDCLASS", DPFLTR_KBDCLASS_ID
},
202 { "MOUCLASS", DPFLTR_MOUCLASS_ID
},
203 { "TWOTRACK", DPFLTR_TWOTRACK_ID
},
204 { "WMILIB", DPFLTR_WMILIB_ID
},
205 { "ACPI", DPFLTR_ACPI_ID
},
206 { "AMLI", DPFLTR_AMLI_ID
},
207 { "HALIA64", DPFLTR_HALIA64_ID
},
208 { "VIDEO", DPFLTR_VIDEO_ID
},
209 { "SVCHOST", DPFLTR_SVCHOST_ID
},
210 { "VIDEOPRT", DPFLTR_VIDEOPRT_ID
},
211 { "TCPIP", DPFLTR_TCPIP_ID
},
212 { "DMSYNTH", DPFLTR_DMSYNTH_ID
},
213 { "NTOSPNP", DPFLTR_NTOSPNP_ID
},
214 { "FASTFAT", DPFLTR_FASTFAT_ID
},
215 { "SAMSS", DPFLTR_SAMSS_ID
},
216 { "PNPMGR", DPFLTR_PNPMGR_ID
},
217 { "NETAPI", DPFLTR_NETAPI_ID
},
218 { "SCSERVER", DPFLTR_SCSERVER_ID
},
219 { "SCCLIENT", DPFLTR_SCCLIENT_ID
},
220 { "SERIAL", DPFLTR_SERIAL_ID
},
221 { "SERENUM", DPFLTR_SERENUM_ID
},
222 { "UHCD", DPFLTR_UHCD_ID
},
223 { "BOOTOK", DPFLTR_BOOTOK_ID
},
224 { "BOOTVRFY", DPFLTR_BOOTVRFY_ID
},
225 { "RPCPROXY", DPFLTR_RPCPROXY_ID
},
226 { "AUTOCHK", DPFLTR_AUTOCHK_ID
},
227 { "DCOMSS", DPFLTR_DCOMSS_ID
},
228 { "UNIMODEM", DPFLTR_UNIMODEM_ID
},
229 { "SIS", DPFLTR_SIS_ID
},
230 { "FLTMGR", DPFLTR_FLTMGR_ID
},
231 { "WMICORE", DPFLTR_WMICORE_ID
},
232 { "BURNENG", DPFLTR_BURNENG_ID
},
233 { "IMAPI", DPFLTR_IMAPI_ID
},
234 { "SXS", DPFLTR_SXS_ID
},
235 { "FUSION", DPFLTR_FUSION_ID
},
236 { "IDLETASK", DPFLTR_IDLETASK_ID
},
237 { "SOFTPCI", DPFLTR_SOFTPCI_ID
},
238 { "TAPE", DPFLTR_TAPE_ID
},
239 { "MCHGR", DPFLTR_MCHGR_ID
},
240 { "IDEP", DPFLTR_IDEP_ID
},
241 { "PCIIDE", DPFLTR_PCIIDE_ID
},
242 { "FLOPPY", DPFLTR_FLOPPY_ID
},
243 { "FDC", DPFLTR_FDC_ID
},
244 { "TERMSRV", DPFLTR_TERMSRV_ID
},
245 { "W32TIME", DPFLTR_W32TIME_ID
},
246 { "PREFETCHER", DPFLTR_PREFETCHER_ID
},
247 { "RSFILTER", DPFLTR_RSFILTER_ID
},
248 { "FCPORT", DPFLTR_FCPORT_ID
},
249 { "PCI", DPFLTR_PCI_ID
},
250 { "DMIO", DPFLTR_DMIO_ID
},
251 { "DMCONFIG", DPFLTR_DMCONFIG_ID
},
252 { "DMADMIN", DPFLTR_DMADMIN_ID
},
253 { "WSOCKTRANSPORT", DPFLTR_WSOCKTRANSPORT_ID
},
254 { "VSS", DPFLTR_VSS_ID
},
255 { "PNPMEM", DPFLTR_PNPMEM_ID
},
256 { "PROCESSOR", DPFLTR_PROCESSOR_ID
},
257 { "DMSERVER", DPFLTR_DMSERVER_ID
},
258 { "SR", DPFLTR_SR_ID
},
259 { "INFINIBAND", DPFLTR_INFINIBAND_ID
},
260 { "IHVDRIVER", DPFLTR_IHVDRIVER_ID
},
261 { "IHVVIDEO", DPFLTR_IHVVIDEO_ID
},
262 { "IHVAUDIO", DPFLTR_IHVAUDIO_ID
},
263 { "IHVNETWORK", DPFLTR_IHVNETWORK_ID
},
264 { "IHVSTREAMING", DPFLTR_IHVSTREAMING_ID
},
265 { "IHVBUS", DPFLTR_IHVBUS_ID
},
266 { "HPS", DPFLTR_HPS_ID
},
267 { "RTLTHREADPOOL", DPFLTR_RTLTHREADPOOL_ID
},
268 { "LDR", DPFLTR_LDR_ID
},
269 { "TCPIP6", DPFLTR_TCPIP6_ID
},
270 { "ISAPNP", DPFLTR_ISAPNP_ID
},
271 { "SHPC", DPFLTR_SHPC_ID
},
272 { "STORPORT", DPFLTR_STORPORT_ID
},
273 { "STORMINIPORT", DPFLTR_STORMINIPORT_ID
},
274 { "PRINTSPOOLER", DPFLTR_PRINTSPOOLER_ID
},
277 for (i
= 0; i
< sizeof(ComponentTable
) / sizeof(ComponentTable
[0]); i
++)
279 if (_stricmp(ComponentName
, ComponentTable
[i
].Name
) == 0)
281 *ComponentId
= ComponentTable
[i
].Id
;
289 /*!\brief Evaluates an expression...
291 * Much like KdbpRpnEvaluateExpression, but prints the error message (if any)
292 * at the given offset.
294 * \param Expression Expression to evaluate.
295 * \param ErrOffset Offset (in characters) to print the error message at.
296 * \param Result Receives the result on success.
298 * \retval TRUE Success.
299 * \retval FALSE Failure.
302 KdbpEvaluateExpression(
305 OUT PULONGLONG Result
)
307 static CHAR ErrMsgBuffer
[130] = "^ ";
308 LONG ExpressionErrOffset
= -1;
309 PCHAR ErrMsg
= ErrMsgBuffer
;
312 Ok
= KdbpRpnEvaluateExpression(Expression
, KdbCurrentTrapFrame
, Result
,
313 &ExpressionErrOffset
, ErrMsgBuffer
+ 2);
316 if (ExpressionErrOffset
>= 0)
317 ExpressionErrOffset
+= ErrOffset
;
321 KdbpPrint("%*s%s\n", ExpressionErrOffset
, "", ErrMsg
);
327 /*!\brief Evaluates an expression and displays the result.
330 KdbpCmdEvalExpression(
335 ULONGLONG Result
= 0;
342 KdbpPrint("?: Argument required\n");
346 /* Put the arguments back together */
348 for (i
= 1; i
< Argc
; i
++)
350 len
= strlen(Argv
[i
]);
354 /* Evaluate the expression */
355 Ok
= KdbpEvaluateExpression(Argv
[1], sizeof("kdb:> ")-1 + (Argv
[1]-Argv
[0]), &Result
);
358 if (Result
> 0x00000000ffffffffLL
)
360 if (Result
& 0x8000000000000000LL
)
361 KdbpPrint("0x%016I64x %20I64u %20I64d\n", Result
, Result
, Result
);
363 KdbpPrint("0x%016I64x %20I64u\n", Result
, Result
);
369 if (ul
<= 0xff && ul
>= 0x80)
370 l
= (LONG
)((CHAR
)ul
);
371 else if (ul
<= 0xffff && ul
>= 0x8000)
372 l
= (LONG
)((SHORT
)ul
);
377 KdbpPrint("0x%08lx %10lu %10ld\n", ul
, ul
, l
);
379 KdbpPrint("0x%08lx %10lu\n", ul
, ul
);
386 /*!\brief Display list of active debug channels
393 ULONG i
, j
, ComponentId
, Level
;
394 ULONG set
= DPFLTR_MASK
, clear
= DPFLTR_MASK
;
405 { "error", 1 << DPFLTR_ERROR_LEVEL
},
406 { "warning", 1 << DPFLTR_WARNING_LEVEL
},
407 { "trace", 1 << DPFLTR_TRACE_LEVEL
},
408 { "info", 1 << DPFLTR_INFO_LEVEL
},
411 for (i
= 1; i
< Argc
; i
++)
414 p
= opt
+ strcspn(opt
, "+-");
415 if (!p
[0]) p
= opt
; /* assume it's a debug channel name */
419 for (j
= 0; j
< sizeof(debug_classes
) / sizeof(debug_classes
[0]); j
++)
421 SIZE_T len
= strlen(debug_classes
[j
].Name
);
422 if (len
!= (p
- opt
))
424 if (_strnicmp(opt
, debug_classes
[j
].Name
, len
) == 0) /* found it */
427 set
|= debug_classes
[j
].Level
;
429 clear
|= debug_classes
[j
].Level
;
433 if (j
== sizeof(debug_classes
) / sizeof(debug_classes
[0]))
435 Level
= strtoul(opt
, &pend
, 0);
438 KdbpPrint("filter: bad class name '%.*s'\n", p
- opt
, opt
);
454 if (*p
== '+' || *p
== '-')
457 if (!KdbpGetComponentId(p
, &ComponentId
))
459 KdbpPrint("filter: '%s' is not a valid component name!\n", p
);
463 /* Get current mask value */
464 NtSetDebugFilterState(ComponentId
, set
, TRUE
);
465 NtSetDebugFilterState(ComponentId
, clear
, FALSE
);
471 /*!\brief Disassembles 10 instructions at eip or given address or
472 * displays 16 dwords from memory at given address.
482 ULONGLONG Result
= 0;
483 ULONG_PTR Address
= KdbCurrentTrapFrame
->Tf
.Eip
;
486 if (Argv
[0][0] == 'x') /* display memory */
488 else /* disassemble */
493 /* Check for [L count] part */
495 if (strcmp(Argv
[Argc
-2], "L") == 0)
497 ul
= strtoul(Argv
[Argc
-1], NULL
, 0);
504 else if (Argv
[Argc
-1][0] == 'L')
506 ul
= strtoul(Argv
[Argc
-1] + 1, NULL
, 0);
514 /* Put the remaining arguments back together */
516 for (ul
= 1; ul
< Argc
; ul
++)
518 Argv
[ul
][strlen(Argv
[ul
])] = ' ';
523 /* Evaluate the expression */
526 if (!KdbpEvaluateExpression(Argv
[1], sizeof("kdb:> ")-1 + (Argv
[1]-Argv
[0]), &Result
))
529 if (Result
> (ULONGLONG
)(~((ULONG_PTR
)0)))
530 KdbpPrint("Warning: Address %I64x is beeing truncated\n",Result
);
532 Address
= (ULONG_PTR
)Result
;
534 else if (Argv
[0][0] == 'x')
536 KdbpPrint("x: Address argument required.\n");
540 if (Argv
[0][0] == 'x')
547 if (!KdbSymPrintAddress((PVOID
)Address
))
548 KdbpPrint("<%x>:", Address
);
557 if (!NT_SUCCESS(KdbpSafeReadMemory(&ul
, (PVOID
)Address
, sizeof(ul
))))
558 KdbpPrint(" ????????");
560 KdbpPrint(" %08x", ul
);
562 Address
+= sizeof(ul
);
573 if (!KdbSymPrintAddress((PVOID
)Address
))
574 KdbpPrint("<%08x>: ", Address
);
578 InstLen
= KdbpDisassemble(Address
, KdbUseIntelSyntax
);
581 KdbpPrint("<INVALID>\n");
593 /*!\brief Displays CPU registers.
600 PKTRAP_FRAME Tf
= &KdbCurrentTrapFrame
->Tf
;
602 static const PCHAR EflagsBits
[32] = { " CF", NULL
, " PF", " BIT3", " AF", " BIT5",
603 " ZF", " SF", " TF", " IF", " DF", " OF",
604 NULL
, NULL
, " NT", " BIT15", " RF", " VF",
605 " AC", " VIF", " VIP", " ID", " BIT22",
606 " BIT23", " BIT24", " BIT25", " BIT26",
607 " BIT27", " BIT28", " BIT29", " BIT30",
610 if (Argv
[0][0] == 'r') /* regs */
612 KdbpPrint("CS:EIP 0x%04x:0x%08x\n"
613 "SS:ESP 0x%04x:0x%08x\n"
614 " EAX 0x%08x EBX 0x%08x\n"
615 " ECX 0x%08x EDX 0x%08x\n"
616 " ESI 0x%08x EDI 0x%08x\n"
618 Tf
->SegCs
& 0xFFFF, Tf
->Eip
,
619 Tf
->HardwareSegSs
, Tf
->HardwareEsp
,
624 KdbpPrint("EFLAGS 0x%08x ", Tf
->EFlags
);
626 for (i
= 0; i
< 32; i
++)
630 if ((Tf
->EFlags
& (1 << 1)) == 0)
635 KdbpPrint(" IOPL%d", (Tf
->EFlags
>> 12) & 3);
640 else if ((Tf
->EFlags
& (1 << i
)) != 0)
642 KdbpPrint(EflagsBits
[i
]);
648 else if (Argv
[0][0] == 'c') /* cregs */
650 ULONG Cr0
, Cr2
, Cr3
, Cr4
;
651 KDESCRIPTOR Gdtr
, Idtr
;
653 static const PCHAR Cr0Bits
[32] = { " PE", " MP", " EM", " TS", " ET", " NE", NULL
, NULL
,
654 NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
,
655 " WP", NULL
, " AM", NULL
, NULL
, NULL
, NULL
, NULL
,
656 NULL
, NULL
, NULL
, NULL
, NULL
, " NW", " CD", " PG" };
657 static const PCHAR Cr4Bits
[32] = { " VME", " PVI", " TSD", " DE", " PSE", " PAE", " MCE", " PGE",
658 " PCE", " OSFXSR", " OSXMMEXCPT", NULL
, NULL
, NULL
, NULL
, NULL
,
659 NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
,
660 NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
};
662 Cr0
= KdbCurrentTrapFrame
->Cr0
;
663 Cr2
= KdbCurrentTrapFrame
->Cr2
;
664 Cr3
= KdbCurrentTrapFrame
->Cr3
;
665 Cr4
= KdbCurrentTrapFrame
->Cr4
;
667 /* Get descriptor table regs */
668 Ke386GetGlobalDescriptorTable(&Gdtr
.Limit
);
669 Ldtr
= Ke386GetLocalDescriptorTable();
672 /* Display the control registers */
673 KdbpPrint("CR0 0x%08x ", Cr0
);
675 for (i
= 0; i
< 32; i
++)
680 if ((Cr0
& (1 << i
)) != 0)
681 KdbpPrint(Cr0Bits
[i
]);
684 KdbpPrint("\nCR2 0x%08x\n", Cr2
);
685 KdbpPrint("CR3 0x%08x Pagedir-Base 0x%08x %s%s\n", Cr3
, (Cr3
& 0xfffff000),
686 (Cr3
& (1 << 3)) ? " PWT" : "", (Cr3
& (1 << 4)) ? " PCD" : "" );
687 KdbpPrint("CR4 0x%08x ", Cr4
);
689 for (i
= 0; i
< 32; i
++)
694 if ((Cr4
& (1 << i
)) != 0)
695 KdbpPrint(Cr4Bits
[i
]);
698 /* Display the descriptor table regs */
699 KdbpPrint("\nGDTR Base 0x%08x Size 0x%04x\n", Gdtr
.Base
, Gdtr
.Limit
);
700 KdbpPrint("LDTR 0x%04x\n", Ldtr
);
701 KdbpPrint("IDTR Base 0x%08x Size 0x%04x\n", Idtr
.Base
, Idtr
.Limit
);
703 else if (Argv
[0][0] == 's') /* sregs */
705 KdbpPrint("CS 0x%04x Index 0x%04x %cDT RPL%d\n",
706 Tf
->SegCs
& 0xffff, (Tf
->SegCs
& 0xffff) >> 3,
707 (Tf
->SegCs
& (1 << 2)) ? 'L' : 'G', Tf
->SegCs
& 3);
708 KdbpPrint("DS 0x%04x Index 0x%04x %cDT RPL%d\n",
709 Tf
->SegDs
, Tf
->SegDs
>> 3, (Tf
->SegDs
& (1 << 2)) ? 'L' : 'G', Tf
->SegDs
& 3);
710 KdbpPrint("ES 0x%04x Index 0x%04x %cDT RPL%d\n",
711 Tf
->SegEs
, Tf
->SegEs
>> 3, (Tf
->SegEs
& (1 << 2)) ? 'L' : 'G', Tf
->SegEs
& 3);
712 KdbpPrint("FS 0x%04x Index 0x%04x %cDT RPL%d\n",
713 Tf
->SegFs
, Tf
->SegFs
>> 3, (Tf
->SegFs
& (1 << 2)) ? 'L' : 'G', Tf
->SegFs
& 3);
714 KdbpPrint("GS 0x%04x Index 0x%04x %cDT RPL%d\n",
715 Tf
->SegGs
, Tf
->SegGs
>> 3, (Tf
->SegGs
& (1 << 2)) ? 'L' : 'G', Tf
->SegGs
& 3);
716 KdbpPrint("SS 0x%04x Index 0x%04x %cDT RPL%d\n",
717 Tf
->HardwareSegSs
, Tf
->HardwareSegSs
>> 3, (Tf
->HardwareSegSs
& (1 << 2)) ? 'L' : 'G', Tf
->HardwareSegSs
& 3);
721 ASSERT(Argv
[0][0] == 'd');
722 KdbpPrint("DR0 0x%08x\n"
728 Tf
->Dr0
, Tf
->Dr1
, Tf
->Dr2
, Tf
->Dr3
,
735 /*!\brief Displays a backtrace.
744 ULONGLONG Result
= 0;
745 ULONG_PTR Frame
= KdbCurrentTrapFrame
->Tf
.Ebp
;
750 /* Check for [L count] part */
753 if (strcmp(Argv
[Argc
-2], "L") == 0)
755 ul
= strtoul(Argv
[Argc
-1], NULL
, 0);
762 else if (Argv
[Argc
-1][0] == 'L')
764 ul
= strtoul(Argv
[Argc
-1] + 1, NULL
, 0);
772 /* Put the remaining arguments back together */
774 for (ul
= 1; ul
< Argc
; ul
++)
776 Argv
[ul
][strlen(Argv
[ul
])] = ' ';
781 /* Check if frame addr or thread id is given. */
784 if (Argv
[1][0] == '*')
788 /* Evaluate the expression */
789 if (!KdbpEvaluateExpression(Argv
[1], sizeof("kdb:> ")-1 + (Argv
[1]-Argv
[0]), &Result
))
792 if (Result
> (ULONGLONG
)(~((ULONG_PTR
)0)))
793 KdbpPrint("Warning: Address %I64x is beeing truncated\n",Result
);
795 Frame
= (ULONG_PTR
)Result
;
799 KdbpPrint("Thread backtrace not supported yet!\n");
807 /* Try printing the function at EIP */
808 if (!KdbSymPrintAddress((PVOID
)KdbCurrentTrapFrame
->Tf
.Eip
))
809 KdbpPrint("<%08x>\n", KdbCurrentTrapFrame
->Tf
.Eip
);
814 KdbpPrint("Frames:\n");
820 if (!NT_SUCCESS(KdbpSafeReadMemory(&Address
, (PVOID
)(Frame
+ sizeof(ULONG_PTR
)), sizeof (ULONG_PTR
))))
822 KdbpPrint("Couldn't access memory at 0x%p!\n", Frame
+ sizeof(ULONG_PTR
));
826 if (!KdbSymPrintAddress((PVOID
)Address
))
827 KdbpPrint("<%08x>\n", Address
);
834 if (!NT_SUCCESS(KdbpSafeReadMemory(&Frame
, (PVOID
)Frame
, sizeof (ULONG_PTR
))))
836 KdbpPrint("Couldn't access memory at 0x%p!\n", Frame
);
844 /*!\brief Continues execution of the system/leaves KDB.
851 /* Exit the main loop */
855 /*!\brief Continues execution of the system/leaves KDB.
866 Count
= strtoul(Argv
[1], NULL
, 0);
869 KdbpPrint("%s: Integer argument required\n", Argv
[0]);
874 if (Argv
[0][0] == 'n')
875 KdbSingleStepOver
= TRUE
;
877 KdbSingleStepOver
= FALSE
;
879 /* Set the number of single steps and return to the interrupted code. */
880 KdbNumSingleSteps
= Count
;
885 /*!\brief Lists breakpoints.
888 KdbpCmdBreakPointList(
893 ULONG_PTR Address
= 0;
894 KDB_BREAKPOINT_TYPE Type
= 0;
895 KDB_ACCESS_TYPE AccessType
= 0;
898 BOOLEAN Enabled
= FALSE
;
899 BOOLEAN Global
= FALSE
;
900 PEPROCESS Process
= NULL
;
901 PCHAR str1
, str2
, ConditionExpr
, GlobalOrLocal
;
904 l
= KdbpGetNextBreakPointNr(0);
907 KdbpPrint("No breakpoints.\n");
911 KdbpPrint("Breakpoints:\n");
914 if (!KdbpGetBreakPointInfo(l
, &Address
, &Type
, &Size
, &AccessType
, &DebugReg
,
915 &Enabled
, &Global
, &Process
, &ConditionExpr
))
920 if (l
== KdbLastBreakPointNr
)
933 GlobalOrLocal
= " global";
937 GlobalOrLocal
= Buffer
;
938 sprintf(Buffer
, " PID 0x%08lx",
939 (ULONG
)(Process
? Process
->UniqueProcessId
: INVALID_HANDLE_VALUE
));
942 if (Type
== KdbBreakPointSoftware
|| Type
== KdbBreakPointTemporary
)
944 KdbpPrint(" %s%03d BPX 0x%08x%s%s%s%s%s\n",
946 Enabled
? "" : " disabled",
948 ConditionExpr
? " IF " : "",
949 ConditionExpr
? ConditionExpr
: "",
952 else if (Type
== KdbBreakPointHardware
)
956 KdbpPrint(" %s%03d BPM 0x%08x %-5s %-5s disabled%s%s%s%s\n", str1
, l
, Address
,
957 KDB_ACCESS_TYPE_TO_STRING(AccessType
),
958 Size
== 1 ? "byte" : (Size
== 2 ? "word" : "dword"),
960 ConditionExpr
? " IF " : "",
961 ConditionExpr
? ConditionExpr
: "",
966 KdbpPrint(" %s%03d BPM 0x%08x %-5s %-5s DR%d%s%s%s%s\n", str1
, l
, Address
,
967 KDB_ACCESS_TYPE_TO_STRING(AccessType
),
968 Size
== 1 ? "byte" : (Size
== 2 ? "word" : "dword"),
971 ConditionExpr
? " IF " : "",
972 ConditionExpr
? ConditionExpr
: "",
977 while ((l
= KdbpGetNextBreakPointNr(l
+1)) >= 0);
982 /*!\brief Enables, disables or clears a breakpoint.
985 KdbpCmdEnableDisableClearBreakPoint(
994 KdbpPrint("%s: argument required\n", Argv
[0]);
999 BreakPointNr
= strtoul(Argv
[1], &pend
, 0);
1000 if (pend
== Argv
[1] || *pend
!= '\0')
1002 KdbpPrint("%s: integer argument required\n", Argv
[0]);
1006 if (Argv
[0][1] == 'e') /* enable */
1008 KdbpEnableBreakPoint(BreakPointNr
, NULL
);
1010 else if (Argv
[0][1] == 'd') /* disable */
1012 KdbpDisableBreakPoint(BreakPointNr
, NULL
);
1016 ASSERT(Argv
[0][1] == 'c');
1017 KdbpDeleteBreakPoint(BreakPointNr
, NULL
);
1023 /*!\brief Sets a software or hardware (memory) breakpoint at the given address.
1026 KdbpCmdBreakPoint(ULONG Argc
, PCHAR Argv
[])
1028 ULONGLONG Result
= 0;
1030 KDB_BREAKPOINT_TYPE Type
;
1032 KDB_ACCESS_TYPE AccessType
= 0;
1033 ULONG AddressArgIndex
, i
;
1034 LONG ConditionArgIndex
;
1035 BOOLEAN Global
= TRUE
;
1037 if (Argv
[0][2] == 'x') /* software breakpoint */
1041 KdbpPrint("bpx: Address argument required.\n");
1045 AddressArgIndex
= 1;
1046 Type
= KdbBreakPointSoftware
;
1048 else /* memory breakpoint */
1050 ASSERT(Argv
[0][2] == 'm');
1054 KdbpPrint("bpm: Access type argument required (one of r, w, rw, x)\n");
1058 if (_stricmp(Argv
[1], "x") == 0)
1059 AccessType
= KdbAccessExec
;
1060 else if (_stricmp(Argv
[1], "r") == 0)
1061 AccessType
= KdbAccessRead
;
1062 else if (_stricmp(Argv
[1], "w") == 0)
1063 AccessType
= KdbAccessWrite
;
1064 else if (_stricmp(Argv
[1], "rw") == 0)
1065 AccessType
= KdbAccessReadWrite
;
1068 KdbpPrint("bpm: Unknown access type '%s'\n", Argv
[1]);
1074 KdbpPrint("bpm: %s argument required.\n", AccessType
== KdbAccessExec
? "Address" : "Memory size");
1078 AddressArgIndex
= 3;
1079 if (_stricmp(Argv
[2], "byte") == 0)
1081 else if (_stricmp(Argv
[2], "word") == 0)
1083 else if (_stricmp(Argv
[2], "dword") == 0)
1085 else if (AccessType
== KdbAccessExec
)
1092 KdbpPrint("bpm: Unknown memory size '%s'\n", Argv
[2]);
1096 if (Argc
<= AddressArgIndex
)
1098 KdbpPrint("bpm: Address argument required.\n");
1102 Type
= KdbBreakPointHardware
;
1105 /* Put the arguments back together */
1106 ConditionArgIndex
= -1;
1107 for (i
= AddressArgIndex
; i
< (Argc
-1); i
++)
1109 if (strcmp(Argv
[i
+1], "IF") == 0) /* IF found */
1111 ConditionArgIndex
= i
+ 2;
1112 if (ConditionArgIndex
>= Argc
)
1114 KdbpPrint("%s: IF requires condition expression.\n", Argv
[0]);
1118 for (i
= ConditionArgIndex
; i
< (Argc
-1); i
++)
1119 Argv
[i
][strlen(Argv
[i
])] = ' ';
1124 Argv
[i
][strlen(Argv
[i
])] = ' ';
1127 /* Evaluate the address expression */
1128 if (!KdbpEvaluateExpression(Argv
[AddressArgIndex
],
1129 sizeof("kdb:> ")-1 + (Argv
[AddressArgIndex
]-Argv
[0]),
1135 if (Result
> (ULONGLONG
)(~((ULONG_PTR
)0)))
1136 KdbpPrint("%s: Warning: Address %I64x is beeing truncated\n", Argv
[0],Result
);
1138 Address
= (ULONG_PTR
)Result
;
1140 KdbpInsertBreakPoint(Address
, Type
, Size
, AccessType
,
1141 (ConditionArgIndex
< 0) ? NULL
: Argv
[ConditionArgIndex
],
1147 /*!\brief Lists threads or switches to another thread context.
1155 PETHREAD Thread
= NULL
;
1156 PEPROCESS Process
= NULL
;
1157 BOOLEAN ReferencedThread
= FALSE
, ReferencedProcess
= FALSE
;
1162 PCHAR State
, pend
, str1
, str2
;
1163 static const PCHAR ThreadStateToString
[DeferredReady
+1] =
1165 "Initialized", "Ready", "Running",
1166 "Standby", "Terminated", "Waiting",
1167 "Transition", "DeferredReady"
1170 ASSERT(KdbCurrentProcess
);
1172 if (Argc
>= 2 && _stricmp(Argv
[1], "list") == 0)
1174 Process
= KdbCurrentProcess
;
1178 ul
= strtoul(Argv
[2], &pend
, 0);
1179 if (Argv
[2] == pend
)
1181 KdbpPrint("thread: '%s' is not a valid process id!\n", Argv
[2]);
1185 if (!NT_SUCCESS(PsLookupProcessByProcessId((PVOID
)ul
, &Process
)))
1187 KdbpPrint("thread: Invalid process id!\n");
1191 /* Remember our reference */
1192 ReferencedProcess
= TRUE
;
1195 Entry
= Process
->ThreadListHead
.Flink
;
1196 if (Entry
== &Process
->ThreadListHead
)
1199 KdbpPrint("No threads in process 0x%08x!\n", ul
);
1201 KdbpPrint("No threads in current process!\n");
1203 if (ReferencedProcess
)
1204 ObDereferenceObject(Process
);
1209 KdbpPrint(" TID State Prior. Affinity EBP EIP\n");
1212 Thread
= CONTAINING_RECORD(Entry
, ETHREAD
, ThreadListEntry
);
1214 if (Thread
== KdbCurrentThread
)
1225 if (Thread
->Tcb
.TrapFrame
)
1227 if (Thread
->Tcb
.TrapFrame
->PreviousPreviousMode
== KernelMode
)
1228 Esp
= (PULONG
)Thread
->Tcb
.TrapFrame
->TempEsp
;
1230 Esp
= (PULONG
)Thread
->Tcb
.TrapFrame
->HardwareEsp
;
1232 Ebp
= (PULONG
)Thread
->Tcb
.TrapFrame
->Ebp
;
1233 Eip
= Thread
->Tcb
.TrapFrame
->Eip
;
1237 Esp
= (PULONG
)Thread
->Tcb
.KernelStack
;
1238 Ebp
= (PULONG
)Esp
[4];
1241 if (Ebp
) /* FIXME: Should we attach to the process to read Ebp[1]? */
1242 KdbpSafeReadMemory(&Eip
, Ebp
+ 1, sizeof (Eip
));
1245 if (Thread
->Tcb
.State
< (DeferredReady
+ 1))
1246 State
= ThreadStateToString
[Thread
->Tcb
.State
];
1250 KdbpPrint(" %s0x%08x %-11s %3d 0x%08x 0x%08x 0x%08x%s\n",
1252 Thread
->Cid
.UniqueThread
,
1254 Thread
->Tcb
.Priority
,
1255 Thread
->Tcb
.Affinity
,
1260 Entry
= Entry
->Flink
;
1262 while (Entry
!= &Process
->ThreadListHead
);
1264 /* Release our reference, if any */
1265 if (ReferencedProcess
)
1266 ObDereferenceObject(Process
);
1268 else if (Argc
>= 2 && _stricmp(Argv
[1], "attach") == 0)
1272 KdbpPrint("thread attach: thread id argument required!\n");
1276 ul
= strtoul(Argv
[2], &pend
, 0);
1277 if (Argv
[2] == pend
)
1279 KdbpPrint("thread attach: '%s' is not a valid thread id!\n", Argv
[2]);
1283 if (!KdbpAttachToThread((PVOID
)ul
))
1288 KdbpPrint("Attached to thread 0x%08x.\n", ul
);
1292 Thread
= KdbCurrentThread
;
1296 ul
= strtoul(Argv
[1], &pend
, 0);
1297 if (Argv
[1] == pend
)
1299 KdbpPrint("thread: '%s' is not a valid thread id!\n", Argv
[1]);
1303 if (!NT_SUCCESS(PsLookupThreadByThreadId((PVOID
)ul
, &Thread
)))
1305 KdbpPrint("thread: Invalid thread id!\n");
1309 /* Remember our reference */
1310 ReferencedThread
= TRUE
;
1313 if (Thread
->Tcb
.State
< (DeferredReady
+ 1))
1314 State
= ThreadStateToString
[Thread
->Tcb
.State
];
1320 " State: %s (0x%x)\n"
1322 " Affinity: 0x%08x\n"
1323 " Initial Stack: 0x%08x\n"
1324 " Stack Limit: 0x%08x\n"
1325 " Stack Base: 0x%08x\n"
1326 " Kernel Stack: 0x%08x\n"
1327 " Trap Frame: 0x%08x\n"
1328 " NPX State: %s (0x%x)\n",
1329 (Argc
< 2) ? "Current Thread:\n" : "",
1330 Thread
->Cid
.UniqueThread
,
1331 State
, Thread
->Tcb
.State
,
1332 Thread
->Tcb
.Priority
,
1333 Thread
->Tcb
.Affinity
,
1334 Thread
->Tcb
.InitialStack
,
1335 Thread
->Tcb
.StackLimit
,
1336 Thread
->Tcb
.StackBase
,
1337 Thread
->Tcb
.KernelStack
,
1338 Thread
->Tcb
.TrapFrame
,
1339 NPX_STATE_TO_STRING(Thread
->Tcb
.NpxState
), Thread
->Tcb
.NpxState
);
1341 /* Release our reference if we had one */
1342 if (ReferencedThread
)
1343 ObDereferenceObject(Thread
);
1349 /*!\brief Lists processes or switches to another process context.
1358 BOOLEAN ReferencedProcess
= FALSE
;
1359 PCHAR State
, pend
, str1
, str2
;
1361 extern LIST_ENTRY PsActiveProcessHead
;
1363 if (Argc
>= 2 && _stricmp(Argv
[1], "list") == 0)
1365 Entry
= PsActiveProcessHead
.Flink
;
1366 if (!Entry
|| Entry
== &PsActiveProcessHead
)
1368 KdbpPrint("No processes in the system!\n");
1372 KdbpPrint(" PID State Filename\n");
1375 Process
= CONTAINING_RECORD(Entry
, EPROCESS
, ActiveProcessLinks
);
1377 if (Process
== KdbCurrentProcess
)
1388 State
= ((Process
->Pcb
.State
== ProcessInMemory
) ? "In Memory" :
1389 ((Process
->Pcb
.State
== ProcessOutOfMemory
) ? "Out of Memory" : "In Transition"));
1391 KdbpPrint(" %s0x%08x %-10s %s%s\n",
1393 Process
->UniqueProcessId
,
1395 Process
->ImageFileName
,
1398 Entry
= Entry
->Flink
;
1400 while(Entry
!= &PsActiveProcessHead
);
1402 else if (Argc
>= 2 && _stricmp(Argv
[1], "attach") == 0)
1406 KdbpPrint("process attach: process id argument required!\n");
1410 ul
= strtoul(Argv
[2], &pend
, 0);
1411 if (Argv
[2] == pend
)
1413 KdbpPrint("process attach: '%s' is not a valid process id!\n", Argv
[2]);
1417 if (!KdbpAttachToProcess((PVOID
)ul
))
1422 KdbpPrint("Attached to process 0x%08x, thread 0x%08x.\n", (ULONG
)ul
,
1423 (ULONG
)KdbCurrentThread
->Cid
.UniqueThread
);
1427 Process
= KdbCurrentProcess
;
1431 ul
= strtoul(Argv
[1], &pend
, 0);
1432 if (Argv
[1] == pend
)
1434 KdbpPrint("proc: '%s' is not a valid process id!\n", Argv
[1]);
1438 if (!NT_SUCCESS(PsLookupProcessByProcessId((PVOID
)ul
, &Process
)))
1440 KdbpPrint("proc: Invalid process id!\n");
1444 /* Remember our reference */
1445 ReferencedProcess
= TRUE
;
1448 State
= ((Process
->Pcb
.State
== ProcessInMemory
) ? "In Memory" :
1449 ((Process
->Pcb
.State
== ProcessOutOfMemory
) ? "Out of Memory" : "In Transition"));
1452 " State: %s (0x%x)\n"
1453 " Image Filename: %s\n",
1454 (Argc
< 2) ? "Current process:\n" : "",
1455 Process
->UniqueProcessId
,
1456 State
, Process
->Pcb
.State
,
1457 Process
->ImageFileName
);
1459 /* Release our reference, if any */
1460 if (ReferencedProcess
)
1461 ObDereferenceObject(Process
);
1467 /*!\brief Lists loaded modules or the one containing the specified address.
1474 ULONGLONG Result
= 0;
1476 PLDR_DATA_TABLE_ENTRY LdrEntry
;
1477 BOOLEAN DisplayOnlyOneModule
= FALSE
;
1482 /* Put the arguments back together */
1485 Argv
[Argc
][strlen(Argv
[Argc
])] = ' ';
1487 /* Evaluate the expression */
1488 if (!KdbpEvaluateExpression(Argv
[1], sizeof("kdb:> ")-1 + (Argv
[1]-Argv
[0]), &Result
))
1493 if (Result
> (ULONGLONG
)(~((ULONG_PTR
)0)))
1494 KdbpPrint("%s: Warning: Address %I64x is beeing truncated\n", Argv
[0],Result
);
1496 Address
= (ULONG_PTR
)Result
;
1498 if (!KdbpSymFindModule((PVOID
)Address
, NULL
, -1, &LdrEntry
))
1500 KdbpPrint("No module containing address 0x%p found!\n", Address
);
1504 DisplayOnlyOneModule
= TRUE
;
1508 if (!KdbpSymFindModule(NULL
, NULL
, 0, &LdrEntry
))
1510 ULONG_PTR ntoskrnlBase
= ((ULONG_PTR
)KdbpCmdMod
) & 0xfff00000;
1511 KdbpPrint(" Base Size Name\n");
1512 KdbpPrint(" %08x %08x %s\n", ntoskrnlBase
, 0, "ntoskrnl.exe");
1519 KdbpPrint(" Base Size Name\n");
1522 KdbpPrint(" %08x %08x %wZ\n", LdrEntry
->DllBase
, LdrEntry
->SizeOfImage
, &LdrEntry
->BaseDllName
);
1524 if(DisplayOnlyOneModule
|| !KdbpSymFindModule(NULL
, NULL
, i
++, &LdrEntry
))
1531 /*!\brief Displays GDT, LDT or IDTd.
1548 if (Argv
[0][0] == 'i')
1555 KdbpPrint("Interrupt descriptor table is empty.\n");
1559 KdbpPrint("IDT Base: 0x%08x Limit: 0x%04x\n", Reg
.Base
, Reg
.Limit
);
1560 KdbpPrint(" Idx Type Seg. Sel. Offset DPL\n");
1562 for (i
= 0; (i
+ sizeof(SegDesc
) - 1) <= Reg
.Limit
; i
+= 8)
1564 if (!NT_SUCCESS(KdbpSafeReadMemory(SegDesc
, (PVOID
)(Reg
.Base
+ i
), sizeof(SegDesc
))))
1566 KdbpPrint("Couldn't access memory at 0x%08x!\n", Reg
.Base
+ i
);
1570 Dpl
= ((SegDesc
[1] >> 13) & 3);
1571 if ((SegDesc
[1] & 0x1f00) == 0x0500) /* Task gate */
1572 SegType
= "TASKGATE";
1573 else if ((SegDesc
[1] & 0x1fe0) == 0x0e00) /* 32 bit Interrupt gate */
1574 SegType
= "INTGATE32";
1575 else if ((SegDesc
[1] & 0x1fe0) == 0x0600) /* 16 bit Interrupt gate */
1576 SegType
= "INTGATE16";
1577 else if ((SegDesc
[1] & 0x1fe0) == 0x0f00) /* 32 bit Trap gate */
1578 SegType
= "TRAPGATE32";
1579 else if ((SegDesc
[1] & 0x1fe0) == 0x0700) /* 16 bit Trap gate */
1580 SegType
= "TRAPGATE16";
1582 SegType
= "UNKNOWN";
1584 if ((SegDesc
[1] & (1 << 15)) == 0) /* not present */
1586 KdbpPrint(" %03d %-10s [NP] [NP] %02d\n",
1587 i
/ 8, SegType
, Dpl
);
1589 else if ((SegDesc
[1] & 0x1f00) == 0x0500) /* Task gate */
1591 SegSel
= SegDesc
[0] >> 16;
1592 KdbpPrint(" %03d %-10s 0x%04x %02d\n",
1593 i
/ 8, SegType
, SegSel
, Dpl
);
1597 SegSel
= SegDesc
[0] >> 16;
1598 SegBase
= (SegDesc
[1] & 0xffff0000) | (SegDesc
[0] & 0x0000ffff);
1599 KdbpPrint(" %03d %-10s 0x%04x 0x%08x %02d\n",
1600 i
/ 8, SegType
, SegSel
, SegBase
, Dpl
);
1608 if (Argv
[0][0] == 'g')
1611 Ke386GetGlobalDescriptorTable(&Reg
.Limit
);
1616 ASSERT(Argv
[0][0] == 'l');
1619 Reg
.Limit
= Ke386GetLocalDescriptorTable();
1627 KdbpPrint("%s descriptor table is empty.\n",
1628 Argv
[0][0] == 'g' ? "Global" : "Local");
1632 KdbpPrint("%cDT Base: 0x%08x Limit: 0x%04x\n",
1633 Argv
[0][0] == 'g' ? 'G' : 'L', Reg
.Base
, Reg
.Limit
);
1634 KdbpPrint(" Idx Sel. Type Base Limit DPL Attribs\n");
1636 for (; (i
+ sizeof(SegDesc
) - 1) <= Reg
.Limit
; i
+= 8)
1638 if (!NT_SUCCESS(KdbpSafeReadMemory(SegDesc
, (PVOID
)(Reg
.Base
+ i
), sizeof(SegDesc
))))
1640 KdbpPrint("Couldn't access memory at 0x%08x!\n", Reg
.Base
+ i
);
1644 Dpl
= ((SegDesc
[1] >> 13) & 3);
1645 Type
= ((SegDesc
[1] >> 8) & 0xf);
1647 SegBase
= SegDesc
[0] >> 16;
1648 SegBase
|= (SegDesc
[1] & 0xff) << 16;
1649 SegBase
|= SegDesc
[1] & 0xff000000;
1650 SegLimit
= SegDesc
[0] & 0x0000ffff;
1651 SegLimit
|= (SegDesc
[1] >> 16) & 0xf;
1653 if ((SegDesc
[1] & (1 << 23)) != 0)
1663 if ((SegDesc
[1] & (1 << 12)) == 0) /* System segment */
1667 case 1: SegType
= "TSS16(Avl)"; break;
1668 case 2: SegType
= "LDT"; break;
1669 case 3: SegType
= "TSS16(Busy)"; break;
1670 case 4: SegType
= "CALLGATE16"; break;
1671 case 5: SegType
= "TASKGATE"; break;
1672 case 6: SegType
= "INTGATE16"; break;
1673 case 7: SegType
= "TRAPGATE16"; break;
1674 case 9: SegType
= "TSS32(Avl)"; break;
1675 case 11: SegType
= "TSS32(Busy)"; break;
1676 case 12: SegType
= "CALLGATE32"; break;
1677 case 14: SegType
= "INTGATE32"; break;
1678 case 15: SegType
= "INTGATE32"; break;
1679 default: SegType
= "UNKNOWN"; break;
1682 if (!(Type
>= 1 && Type
<= 3) &&
1683 Type
!= 9 && Type
!= 11)
1689 else if ((SegDesc
[1] & (1 << 11)) == 0) /* Data segment */
1691 if ((SegDesc
[1] & (1 << 22)) != 0)
1696 else /* Code segment */
1698 if ((SegDesc
[1] & (1 << 22)) != 0)
1704 if ((SegDesc
[1] & (1 << 15)) == 0) /* not present */
1706 KdbpPrint(" %03d 0x%04x %-11s [NP] [NP] %02d NP\n",
1707 i
/ 8, i
| Dpl
| ul
, SegType
, Dpl
);
1711 KdbpPrint(" %03d 0x%04x %-11s 0x%08x 0x%08x %02d ",
1712 i
/ 8, i
| Dpl
| ul
, SegType
, SegBase
, SegLimit
, Dpl
);
1714 if ((SegDesc
[1] & (1 << 12)) == 0) /* System segment */
1716 /* FIXME: Display system segment */
1718 else if ((SegDesc
[1] & (1 << 11)) == 0) /* Data segment */
1720 if ((SegDesc
[1] & (1 << 10)) != 0) /* Expand-down */
1723 KdbpPrint((SegDesc
[1] & (1 << 9)) ? " R/W" : " R");
1725 if ((SegDesc
[1] & (1 << 8)) != 0)
1728 else /* Code segment */
1730 if ((SegDesc
[1] & (1 << 10)) != 0) /* Conforming */
1733 KdbpPrint((SegDesc
[1] & (1 << 9)) ? " R/X" : " X");
1735 if ((SegDesc
[1] & (1 << 8)) != 0)
1739 if ((SegDesc
[1] & (1 << 20)) != 0)
1750 /*!\brief Displays the KPCR
1757 PKIPCR Pcr
= (PKIPCR
)KeGetPcr();
1759 KdbpPrint("Current PCR is at 0x%08x.\n", (INT
)Pcr
);
1760 KdbpPrint(" Tib.ExceptionList: 0x%08x\n"
1761 " Tib.StackBase: 0x%08x\n"
1762 " Tib.StackLimit: 0x%08x\n"
1763 " Tib.SubSystemTib: 0x%08x\n"
1764 " Tib.FiberData/Version: 0x%08x\n"
1765 " Tib.ArbitraryUserPointer: 0x%08x\n"
1766 " Tib.Self: 0x%08x\n"
1771 " IrrActive: 0x%08x\n"
1773 " KdVersionBlock: 0x%08x\n"
1777 " MajorVersion: 0x%04x\n"
1778 " MinorVersion: 0x%04x\n"
1779 " SetMember: 0x%08x\n"
1780 " StallScaleFactor: 0x%08x\n"
1782 " L2CacheAssociativity: 0x%02x\n"
1783 " VdmAlert: 0x%08x\n"
1784 " L2CacheSize: 0x%08x\n"
1785 " InterruptMode: 0x%08x\n",
1786 Pcr
->NtTib
.ExceptionList
, Pcr
->NtTib
.StackBase
, Pcr
->NtTib
.StackLimit
,
1787 Pcr
->NtTib
.SubSystemTib
, Pcr
->NtTib
.FiberData
, Pcr
->NtTib
.ArbitraryUserPointer
,
1788 Pcr
->NtTib
.Self
, Pcr
->Self
, Pcr
->Prcb
, Pcr
->Irql
, Pcr
->IRR
, Pcr
->IrrActive
,
1789 Pcr
->IDR
, Pcr
->KdVersionBlock
, Pcr
->IDT
, Pcr
->GDT
, Pcr
->TSS
,
1790 Pcr
->MajorVersion
, Pcr
->MinorVersion
, Pcr
->SetMember
, Pcr
->StallScaleFactor
,
1791 Pcr
->Number
, Pcr
->SecondLevelCacheAssociativity
,
1792 Pcr
->VdmAlert
, Pcr
->SecondLevelCacheSize
, Pcr
->InterruptMode
);
1797 /*!\brief Displays the TSS
1804 KTSS
*Tss
= KeGetPcr()->TSS
;
1806 KdbpPrint("Current TSS is at 0x%08x.\n", (INT
)Tss
);
1807 KdbpPrint(" Eip: 0x%08x\n"
1814 " IoMapBase: 0x%04x\n",
1815 Tss
->Eip
, Tss
->Es
, Tss
->Cs
, Tss
->Ds
, Tss
->Fs
, Tss
->Gs
, Tss
->IoMapBase
);
1820 /*!\brief Bugchecks the system.
1827 /* Set the flag and quit looping */
1828 KdbpBugCheckRequested
= TRUE
;
1833 /*!\brief Sets or displays a config variables value.
1843 KDB_ENTER_CONDITION ConditionFirst
= KdbDoNotEnter
;
1844 KDB_ENTER_CONDITION ConditionLast
= KdbDoNotEnter
;
1846 static const PCHAR ExceptionNames
[21] =
1848 "ZERODEVIDE", "DEBUGTRAP", "NMI", "INT3", "OVERFLOW", "BOUND", "INVALIDOP",
1849 "NOMATHCOP", "DOUBLEFAULT", "RESERVED(9)", "INVALIDTSS", "SEGMENTNOTPRESENT",
1850 "STACKFAULT", "GPF", "PAGEFAULT", "RESERVED(15)", "MATHFAULT", "ALIGNMENTCHECK",
1851 "MACHINECHECK", "SIMDFAULT", "OTHERS"
1856 KdbpPrint("Available settings:\n");
1857 KdbpPrint(" syntax [intel|at&t]\n");
1858 KdbpPrint(" condition [exception|*] [first|last] [never|always|kmode|umode]\n");
1859 KdbpPrint(" break_on_module_load [true|false]\n");
1861 else if (strcmp(Argv
[1], "syntax") == 0)
1865 KdbpPrint("syntax = %s\n", KdbUseIntelSyntax
? "intel" : "at&t");
1869 if (_stricmp(Argv
[2], "intel") == 0)
1870 KdbUseIntelSyntax
= TRUE
;
1871 else if (_stricmp(Argv
[2], "at&t") == 0)
1872 KdbUseIntelSyntax
= FALSE
;
1874 KdbpPrint("Unknown syntax '%s'.\n", Argv
[2]);
1877 else if (strcmp(Argv
[1], "condition") == 0)
1881 KdbpPrint("Conditions: (First) (Last)\n");
1882 for (l
= 0; l
< RTL_NUMBER_OF(ExceptionNames
) - 1; l
++)
1884 if (!ExceptionNames
[l
])
1887 if (!KdbpGetEnterCondition(l
, TRUE
, &ConditionFirst
))
1890 if (!KdbpGetEnterCondition(l
, FALSE
, &ConditionLast
))
1893 KdbpPrint(" #%02d %-20s %-8s %-8s\n", l
, ExceptionNames
[l
],
1894 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst
),
1895 KDB_ENTER_CONDITION_TO_STRING(ConditionLast
));
1898 ASSERT(l
== (RTL_NUMBER_OF(ExceptionNames
) - 1));
1899 KdbpPrint(" %-20s %-8s %-8s\n", ExceptionNames
[l
],
1900 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst
),
1901 KDB_ENTER_CONDITION_TO_STRING(ConditionLast
));
1905 if (Argc
>= 5 && strcmp(Argv
[2], "*") == 0) /* Allow * only when setting condition */
1911 l
= strtoul(Argv
[2], &pend
, 0);
1913 if (Argv
[2] == pend
)
1915 for (l
= 0; l
< RTL_NUMBER_OF(ExceptionNames
); l
++)
1917 if (!ExceptionNames
[l
])
1920 if (_stricmp(ExceptionNames
[l
], Argv
[2]) == 0)
1925 if (l
>= RTL_NUMBER_OF(ExceptionNames
))
1927 KdbpPrint("Unknown exception '%s'.\n", Argv
[2]);
1934 if (_stricmp(Argv
[3], "first") == 0)
1936 else if (_stricmp(Argv
[3], "last") == 0)
1940 KdbpPrint("set condition: second argument must be 'first' or 'last'\n");
1944 if (_stricmp(Argv
[4], "never") == 0)
1945 ConditionFirst
= KdbDoNotEnter
;
1946 else if (_stricmp(Argv
[4], "always") == 0)
1947 ConditionFirst
= KdbEnterAlways
;
1948 else if (_stricmp(Argv
[4], "umode") == 0)
1949 ConditionFirst
= KdbEnterFromUmode
;
1950 else if (_stricmp(Argv
[4], "kmode") == 0)
1951 ConditionFirst
= KdbEnterFromKmode
;
1954 KdbpPrint("set condition: third argument must be 'never', 'always', 'umode' or 'kmode'\n");
1958 if (!KdbpSetEnterCondition(l
, First
, ConditionFirst
))
1961 KdbpPrint("Couldn't change condition for exception #%02d\n", l
);
1963 KdbpPrint("Couldn't change condition for all exceptions\n", l
);
1966 else /* Argc >= 3 */
1968 if (!KdbpGetEnterCondition(l
, TRUE
, &ConditionFirst
))
1971 if (!KdbpGetEnterCondition(l
, FALSE
, &ConditionLast
))
1974 if (l
< (RTL_NUMBER_OF(ExceptionNames
) - 1))
1976 KdbpPrint("Condition for exception #%02d (%s): FirstChance %s LastChance %s\n",
1977 l
, ExceptionNames
[l
],
1978 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst
),
1979 KDB_ENTER_CONDITION_TO_STRING(ConditionLast
));
1983 KdbpPrint("Condition for all other exceptions: FirstChance %s LastChance %s\n",
1984 KDB_ENTER_CONDITION_TO_STRING(ConditionFirst
),
1985 KDB_ENTER_CONDITION_TO_STRING(ConditionLast
));
1990 else if (strcmp(Argv
[1], "break_on_module_load") == 0)
1993 KdbpPrint("break_on_module_load = %s\n", KdbBreakOnModuleLoad
? "enabled" : "disabled");
1996 if (_stricmp(Argv
[2], "enable") == 0 || _stricmp(Argv
[2], "enabled") == 0 || _stricmp(Argv
[2], "true") == 0)
1997 KdbBreakOnModuleLoad
= TRUE
;
1998 else if (_stricmp(Argv
[2], "disable") == 0 || _stricmp(Argv
[2], "disabled") == 0 || _stricmp(Argv
[2], "false") == 0)
1999 KdbBreakOnModuleLoad
= FALSE
;
2001 KdbpPrint("Unknown setting '%s'.\n", Argv
[2]);
2006 KdbpPrint("Unknown setting '%s'.\n", Argv
[1]);
2012 /*!\brief Displays help screen.
2021 KdbpPrint("Kernel debugger commands:\n");
2022 for (i
= 0; i
< RTL_NUMBER_OF(KdbDebuggerCommands
); i
++)
2024 if (!KdbDebuggerCommands
[i
].Syntax
) /* Command group */
2029 KdbpPrint("\x1b[7m* %s:\x1b[0m\n", KdbDebuggerCommands
[i
].Help
);
2033 KdbpPrint(" %-20s - %s\n",
2034 KdbDebuggerCommands
[i
].Syntax
,
2035 KdbDebuggerCommands
[i
].Help
);
2041 /*!\brief Prints the given string with printf-like formatting.
2043 * \param Format Format of the string/arguments.
2044 * \param ... Variable number of arguments matching the format specified in \a Format.
2046 * \note Doesn't correctly handle \\t and terminal escape sequences when calculating the
2047 * number of lines required to print a single line from the Buffer in the terminal.
2054 static CHAR Buffer
[4096];
2055 static BOOLEAN TerminalInitialized
= FALSE
;
2056 static BOOLEAN TerminalConnected
= FALSE
;
2057 static BOOLEAN TerminalReportsSize
= TRUE
;
2062 LONG RowsPrintedByTerminal
;
2066 /* Check if the user has aborted output of the current command */
2067 if (KdbOutputAborted
)
2070 /* Initialize the terminal */
2071 if (!TerminalInitialized
)
2073 DbgPrint("\x1b[7h"); /* Enable linewrap */
2075 /* Query terminal type */
2076 /*DbgPrint("\x1b[Z");*/
2079 TerminalInitialized
= TRUE
;
2081 KeStallExecutionProcessor(100000);
2085 c
= KdbpTryGetCharSerial(5000);
2089 Buffer
[Length
++] = c
;
2090 if (Length
>= (sizeof (Buffer
) - 1))
2094 Buffer
[Length
] = '\0';
2096 TerminalConnected
= TRUE
;
2099 /* Get number of rows and columns in terminal */
2100 if ((KdbNumberOfRowsTerminal
< 0) || (KdbNumberOfColsTerminal
< 0) ||
2101 (KdbNumberOfRowsPrinted
) == 0) /* Refresh terminal size each time when number of rows printed is 0 */
2103 if ((KdbDebugState
& KD_DEBUG_KDSERIAL
) && TerminalConnected
&& TerminalReportsSize
)
2105 /* Try to query number of rows from terminal. A reply looks like "\x1b[8;24;80t" */
2106 TerminalReportsSize
= FALSE
;
2107 KeStallExecutionProcessor(100000);
2108 DbgPrint("\x1b[18t");
2109 c
= KdbpTryGetCharSerial(5000);
2113 c
= KdbpTryGetCharSerial(5000);
2120 c
= KdbpTryGetCharSerial(5000);
2124 Buffer
[Length
++] = c
;
2125 if (isalpha(c
) || Length
>= (sizeof (Buffer
) - 1))
2129 Buffer
[Length
] = '\0';
2130 if (Buffer
[0] == '8' && Buffer
[1] == ';')
2132 for (i
= 2; (i
< Length
) && (Buffer
[i
] != ';'); i
++);
2134 if (Buffer
[i
] == ';')
2138 /* Number of rows is now at Buffer + 2 and number of cols at Buffer + i */
2139 KdbNumberOfRowsTerminal
= strtoul(Buffer
+ 2, NULL
, 0);
2140 KdbNumberOfColsTerminal
= strtoul(Buffer
+ i
, NULL
, 0);
2141 TerminalReportsSize
= TRUE
;
2145 /* Clear further characters */
2146 while ((c
= KdbpTryGetCharSerial(5000)) != -1);
2150 if (KdbNumberOfRowsTerminal
<= 0)
2152 /* Set number of rows to the default. */
2153 KdbNumberOfRowsTerminal
= 24;
2155 else if (KdbNumberOfColsTerminal
<= 0)
2157 /* Set number of cols to the default. */
2158 KdbNumberOfColsTerminal
= 80;
2162 /* Get the string */
2163 va_start(ap
, Format
);
2164 Length
= _vsnprintf(Buffer
, sizeof (Buffer
) - 1, Format
, ap
);
2165 Buffer
[Length
] = '\0';
2169 while (p
[0] != '\0')
2171 i
= strcspn(p
, "\n");
2173 /* Calculate the number of lines which will be printed in the terminal
2174 * when outputting the current line
2177 RowsPrintedByTerminal
= (i
+ KdbNumberOfColsPrinted
- 1) / KdbNumberOfColsTerminal
;
2179 RowsPrintedByTerminal
= 0;
2182 RowsPrintedByTerminal
++;
2184 /*DbgPrint("!%d!%d!%d!%d!", KdbNumberOfRowsPrinted, KdbNumberOfColsPrinted, i, RowsPrintedByTerminal);*/
2186 /* Display a prompt if we printed one screen full of text */
2187 if (KdbNumberOfRowsTerminal
> 0 &&
2188 (LONG
)(KdbNumberOfRowsPrinted
+ RowsPrintedByTerminal
) >= KdbNumberOfRowsTerminal
)
2190 if (KdbNumberOfColsPrinted
> 0)
2193 DbgPrint("--- Press q to abort, any other key to continue ---");
2195 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
2196 c
= KdbpGetCharSerial();
2198 c
= KdbpGetCharKeyboard(&ScanCode
);
2202 /* Try to read '\n' which might follow '\r' - if \n is not received here
2203 * it will be interpreted as "return" when the next command should be read.
2205 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
2206 c
= KdbpTryGetCharSerial(5);
2208 c
= KdbpTryGetCharKeyboard(&ScanCode
, 5);
2214 KdbOutputAborted
= TRUE
;
2218 KdbNumberOfRowsPrinted
= 0;
2219 KdbNumberOfColsPrinted
= 0;
2222 /* Insert a NUL after the line and print only the current line. */
2223 if (p
[i
] == '\n' && p
[i
+ 1] != '\0')
2233 /* Remove escape sequences from the line if there's no terminal connected */
2234 if (!TerminalConnected
)
2236 while ((p2
= strrchr(p
, '\x1b'))) /* Look for escape character */
2241 while (!isalpha(p2
[j
++]));
2256 /* Set p to the start of the next line and
2257 * remember the number of rows/cols printed
2263 KdbNumberOfColsPrinted
= 0;
2267 ASSERT(p
[0] == '\0');
2268 KdbNumberOfColsPrinted
+= i
;
2271 KdbNumberOfRowsPrinted
+= RowsPrintedByTerminal
;
2275 /*!\brief Appends a command to the command history
2277 * \param Command Pointer to the command to append to the history.
2280 KdbpCommandHistoryAppend(
2283 ULONG Length1
= strlen(Command
) + 1;
2288 ASSERT(Length1
<= RTL_NUMBER_OF(KdbCommandHistoryBuffer
));
2291 (KdbCommandHistory
[KdbCommandHistoryIndex
] &&
2292 strcmp(KdbCommandHistory
[KdbCommandHistoryIndex
], Command
) == 0))
2297 /* Calculate Length1 and Length2 */
2298 Buffer
= KdbCommandHistoryBuffer
+ KdbCommandHistoryBufferIndex
;
2299 KdbCommandHistoryBufferIndex
+= Length1
;
2300 if (KdbCommandHistoryBufferIndex
>= (LONG
)RTL_NUMBER_OF(KdbCommandHistoryBuffer
))
2302 KdbCommandHistoryBufferIndex
-= RTL_NUMBER_OF(KdbCommandHistoryBuffer
);
2303 Length2
= KdbCommandHistoryBufferIndex
;
2307 /* Remove previous commands until there is enough space to append the new command */
2308 for (i
= KdbCommandHistoryIndex
; KdbCommandHistory
[i
];)
2311 (KdbCommandHistory
[i
] >= Buffer
||
2312 KdbCommandHistory
[i
] < (KdbCommandHistoryBuffer
+ KdbCommandHistoryBufferIndex
))) ||
2314 (KdbCommandHistory
[i
] >= Buffer
&&
2315 KdbCommandHistory
[i
] < (KdbCommandHistoryBuffer
+ KdbCommandHistoryBufferIndex
))))
2317 KdbCommandHistory
[i
] = NULL
;
2322 i
= RTL_NUMBER_OF(KdbCommandHistory
) - 1;
2324 if (i
== KdbCommandHistoryIndex
)
2328 /* Make sure the new command history entry is free */
2329 KdbCommandHistoryIndex
++;
2330 KdbCommandHistoryIndex
%= RTL_NUMBER_OF(KdbCommandHistory
);
2331 if (KdbCommandHistory
[KdbCommandHistoryIndex
])
2333 KdbCommandHistory
[KdbCommandHistoryIndex
] = NULL
;
2336 /* Append command */
2337 KdbCommandHistory
[KdbCommandHistoryIndex
] = Buffer
;
2338 ASSERT((KdbCommandHistory
[KdbCommandHistoryIndex
] + Length1
) <= KdbCommandHistoryBuffer
+ RTL_NUMBER_OF(KdbCommandHistoryBuffer
));
2339 memcpy(KdbCommandHistory
[KdbCommandHistoryIndex
], Command
, Length1
);
2342 memcpy(KdbCommandHistoryBuffer
, Command
+ Length1
, Length2
);
2346 /*!\brief Reads a line of user-input.
2348 * \param Buffer Buffer to store the input into. Trailing newlines are removed.
2349 * \param Size Size of \a Buffer.
2351 * \note Accepts only \n newlines, \r is ignored.
2359 PCHAR Orig
= Buffer
;
2362 static CHAR LastCommand
[1024] = "";
2363 static CHAR NextKey
= '\0';
2364 INT CmdHistIndex
= -1;
2367 EchoOn
= !((KdbDebugState
& KD_DEBUG_KDNOECHO
) != 0);
2371 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
2373 Key
= (NextKey
== '\0') ? KdbpGetCharSerial() : NextKey
;
2376 if (Key
== KEY_ESC
) /* ESC */
2378 Key
= KdbpGetCharSerial();
2381 Key
= KdbpGetCharSerial();
2386 ScanCode
= KEY_SCAN_UP
;
2389 ScanCode
= KEY_SCAN_DOWN
;
2402 Key
= (NextKey
== '\0') ? KdbpGetCharKeyboard(&ScanCode
) : NextKey
;
2406 if ((ULONG
)(Buffer
- Orig
) >= (Size
- 1))
2408 /* Buffer is full, accept only newlines */
2415 /* Read the next char - this is to throw away a \n which most clients should
2418 KeStallExecutionProcessor(100000);
2420 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
2421 NextKey
= KdbpTryGetCharSerial(5);
2423 NextKey
= KdbpTryGetCharKeyboard(&ScanCode
, 5);
2425 if (NextKey
== '\n' || NextKey
== -1) /* \n or no response at all */
2431 * Repeat the last command if the user presses enter. Reduces the
2432 * risk of RSI when single-stepping.
2436 strncpy(Buffer
, LastCommand
, Size
);
2437 Buffer
[Size
- 1] = '\0';
2442 strncpy(LastCommand
, Orig
, sizeof (LastCommand
));
2443 LastCommand
[sizeof (LastCommand
) - 1] = '\0';
2448 else if (Key
== KEY_BS
|| Key
== KEY_DEL
)
2456 KdbpPrint("%c %c", KEY_BS
, KEY_BS
);
2458 KdbpPrint(" %c", KEY_BS
);
2461 else if (ScanCode
== KEY_SCAN_UP
)
2463 BOOLEAN Print
= TRUE
;
2465 if (CmdHistIndex
< 0)
2467 CmdHistIndex
= KdbCommandHistoryIndex
;
2471 i
= CmdHistIndex
- 1;
2474 CmdHistIndex
= RTL_NUMBER_OF(KdbCommandHistory
) - 1;
2476 if (KdbCommandHistory
[i
] && i
!= KdbCommandHistoryIndex
)
2482 if (Print
&& KdbCommandHistory
[CmdHistIndex
])
2484 while (Buffer
> Orig
)
2490 KdbpPrint("%c %c", KEY_BS
, KEY_BS
);
2492 KdbpPrint(" %c", KEY_BS
);
2495 i
= min(strlen(KdbCommandHistory
[CmdHistIndex
]), Size
- 1);
2496 memcpy(Orig
, KdbCommandHistory
[CmdHistIndex
], i
);
2499 KdbpPrint("%s", Orig
);
2502 else if (ScanCode
== KEY_SCAN_DOWN
)
2504 if (CmdHistIndex
> 0 && CmdHistIndex
!= KdbCommandHistoryIndex
)
2506 i
= CmdHistIndex
+ 1;
2507 if (i
>= (INT
)RTL_NUMBER_OF(KdbCommandHistory
))
2510 if (KdbCommandHistory
[i
])
2513 while (Buffer
> Orig
)
2519 KdbpPrint("%c %c", KEY_BS
, KEY_BS
);
2521 KdbpPrint(" %c", KEY_BS
);
2524 i
= min(strlen(KdbCommandHistory
[CmdHistIndex
]), Size
- 1);
2525 memcpy(Orig
, KdbCommandHistory
[CmdHistIndex
], i
);
2528 KdbpPrint("%s", Orig
);
2535 KdbpPrint("%c", Key
);
2543 /*!\brief Parses command line and executes command if found
2545 * \param Command Command line to parse and execute if possible.
2547 * \retval TRUE Don't continue execution.
2548 * \retval FALSE Continue execution (leave KDB)
2557 static PCH Argv
[256];
2558 static CHAR OrigCommand
[1024];
2560 strncpy(OrigCommand
, Command
, sizeof(OrigCommand
) - 1);
2561 OrigCommand
[sizeof(OrigCommand
) - 1] = '\0';
2568 while (*p
== '\t' || *p
== ' ')
2574 i
= strcspn(p
, "\t ");
2587 for (i
= 0; i
< RTL_NUMBER_OF(KdbDebuggerCommands
); i
++)
2589 if (!KdbDebuggerCommands
[i
].Name
)
2592 if (strcmp(KdbDebuggerCommands
[i
].Name
, Argv
[0]) == 0)
2594 return KdbDebuggerCommands
[i
].Fn(Argc
, Argv
);
2598 KdbpPrint("Command '%s' is unknown.\n", OrigCommand
);
2602 /*!\brief KDB Main Loop.
2604 * \param EnteredOnSingleStep TRUE if KDB was entered on single step.
2608 IN BOOLEAN EnteredOnSingleStep
)
2610 static CHAR Command
[1024];
2613 if (EnteredOnSingleStep
)
2615 if (!KdbSymPrintAddress((PVOID
)KdbCurrentTrapFrame
->Tf
.Eip
))
2617 KdbpPrint("<%x>", KdbCurrentTrapFrame
->Tf
.Eip
);
2621 if (KdbpDisassemble(KdbCurrentTrapFrame
->Tf
.Eip
, KdbUseIntelSyntax
) < 0)
2623 KdbpPrint("<INVALID>");
2628 /* Flush the input buffer */
2629 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
2631 while (KdbpTryGetCharSerial(1) != -1);
2636 while (KdbpTryGetCharKeyboard(&ScanCode
, 1) != -1);
2642 /* Print the prompt */
2643 KdbpPrint("kdb:> ");
2645 /* Read a command and remember it */
2646 KdbpReadCommand(Command
, sizeof (Command
));
2647 KdbpCommandHistoryAppend(Command
);
2649 /* Reset the number of rows/cols printed and output aborted state */
2650 KdbNumberOfRowsPrinted
= KdbNumberOfColsPrinted
= 0;
2651 KdbOutputAborted
= FALSE
;
2653 /* Call the command */
2654 Continue
= KdbpDoCommand(Command
);
2659 /*!\brief Called when a module is loaded.
2661 * \param Name Filename of the module which was loaded.
2664 KdbpCliModuleLoaded(
2665 IN PUNICODE_STRING Name
)
2667 if (!KdbBreakOnModuleLoad
)
2670 KdbpPrint("Module %wZ loaded.\n", Name
);
2671 DbgBreakPointWithStatus(DBG_STATUS_CONTROL_C
);
2674 /*!\brief This function is called by KdbEnterDebuggerException...
2676 * Used to interpret the init file in a context with a trapframe setup
2677 * (KdbpCliInit call KdbEnter which will call KdbEnterDebuggerException which will
2678 * call this function if KdbInitFileBuffer is not NULL.
2681 KdbpCliInterpretInitFile()
2687 /* Execute the commands in the init file */
2688 DPRINT("KDB: Executing KDBinit file...\n");
2689 p1
= KdbInitFileBuffer
;
2690 while (p1
[0] != '\0')
2692 i
= strcspn(p1
, "\r\n");
2698 /* Look for "break" command and comments */
2701 while (isspace(p2
[0]))
2704 if (strncmp(p2
, "break", sizeof("break")-1) == 0 &&
2705 (p2
[sizeof("break")-1] == '\0' || isspace(p2
[sizeof("break")-1])))
2707 /* break into the debugger */
2708 KdbpCliMainLoop(FALSE
);
2710 else if (p2
[0] != '#' && p2
[0] != '\0') /* Ignore empty lines and comments */
2719 while (p1
[0] == '\r' || p1
[0] == '\n')
2722 DPRINT("KDB: KDBinit executed\n");
2725 /*!\brief Called when KDB is initialized
2727 * Reads the KDBinit file from the SystemRoot\system32\drivers\etc directory and executes it.
2733 OBJECT_ATTRIBUTES ObjectAttributes
;
2734 UNICODE_STRING FileName
;
2735 IO_STATUS_BLOCK Iosb
;
2736 FILE_STANDARD_INFORMATION FileStdInfo
;
2737 HANDLE hFile
= NULL
;
2742 /* Initialize the object attributes */
2743 RtlInitUnicodeString(&FileName
, L
"\\SystemRoot\\system32\\drivers\\etc\\KDBinit");
2744 InitializeObjectAttributes(&ObjectAttributes
, &FileName
, 0, NULL
, NULL
);
2747 Status
= ZwOpenFile(&hFile
, FILE_READ_DATA
, &ObjectAttributes
, &Iosb
, 0,
2748 FILE_NON_DIRECTORY_FILE
| FILE_SYNCHRONOUS_IO_NONALERT
|
2749 FILE_NO_INTERMEDIATE_BUFFERING
);
2750 if (!NT_SUCCESS(Status
))
2752 DPRINT("Could not open \\SystemRoot\\system32\\drivers\\etc\\KDBinit (Status 0x%x)", Status
);
2756 /* Get the size of the file */
2757 Status
= ZwQueryInformationFile(hFile
, &Iosb
, &FileStdInfo
, sizeof (FileStdInfo
),
2758 FileStandardInformation
);
2759 if (!NT_SUCCESS(Status
))
2762 DPRINT("Could not query size of \\SystemRoot\\system32\\drivers\\etc\\KDBinit (Status 0x%x)", Status
);
2765 FileSize
= FileStdInfo
.EndOfFile
.u
.LowPart
;
2767 /* Allocate memory for the file */
2768 FileBuffer
= ExAllocatePool(PagedPool
, FileSize
+ 1); /* add 1 byte for terminating '\0' */
2772 DPRINT("Could not allocate %d bytes for KDBinit file\n", FileSize
);
2776 /* Load file into memory */
2777 Status
= ZwReadFile(hFile
, 0, 0, 0, &Iosb
, FileBuffer
, FileSize
, 0, 0);
2780 if (!NT_SUCCESS(Status
) && Status
!= STATUS_END_OF_FILE
)
2782 ExFreePool(FileBuffer
);
2783 DPRINT("Could not read KDBinit file into memory (Status 0x%lx)\n", Status
);
2787 FileSize
= min(FileSize
, (INT
)Iosb
.Information
);
2788 FileBuffer
[FileSize
] = '\0';
2790 /* Enter critical section */
2791 OldEflags
= __readeflags();
2794 /* Interpret the init file... */
2795 KdbInitFileBuffer
= FileBuffer
;
2797 KdbInitFileBuffer
= NULL
;
2799 /* Leave critical section */
2800 __writeeflags(OldEflags
);
2802 ExFreePool(FileBuffer
);
2807 KdpSerialDebugPrint(
2812 STRING KdpPromptString
= RTL_CONSTANT_STRING("kdb:> ");
2813 extern KSPIN_LOCK KdpSerialSpinLock
;
2817 KdpPrompt(IN LPSTR InString
,
2818 IN USHORT InStringLength
,
2819 OUT LPSTR OutString
,
2820 IN USHORT OutStringLength
)
2824 ULONG DummyScanCode
;
2827 /* Acquire the printing spinlock without waiting at raised IRQL */
2830 /* Wait when the spinlock becomes available */
2831 while (!KeTestSpinLock(&KdpSerialSpinLock
));
2833 /* Spinlock was free, raise IRQL */
2834 KeRaiseIrql(HIGH_LEVEL
, &OldIrql
);
2836 /* Try to get the spinlock */
2837 if (KeTryToAcquireSpinLockAtDpcLevel(&KdpSerialSpinLock
))
2840 /* Someone else got the spinlock, lower IRQL back */
2841 KeLowerIrql(OldIrql
);
2844 /* Loop the string to send */
2845 for (i
= 0; i
< InStringLength
; i
++)
2847 /* Print it to serial */
2848 KdPortPutByteEx(&SerialPortInfo
, *(PCHAR
)(InString
+ i
));
2851 /* Print a new line for log neatness */
2852 KdPortPutByteEx(&SerialPortInfo
, '\r');
2853 KdPortPutByteEx(&SerialPortInfo
, '\n');
2855 /* Print the kdb prompt */
2856 for (i
= 0; i
< KdpPromptString
.Length
; i
++)
2858 /* Print it to serial */
2859 KdPortPutByteEx(&SerialPortInfo
,
2860 *(KdpPromptString
.Buffer
+ i
));
2863 /* Loop the whole string */
2864 for (i
= 0; i
< OutStringLength
; i
++)
2866 /* Check if this is serial debugging mode */
2867 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
2869 /* Get the character from serial */
2872 Response
= KdbpTryGetCharSerial(MAXULONG
);
2873 } while (Response
== -1);
2877 /* Get the response from the keyboard */
2880 Response
= KdbpTryGetCharKeyboard(&DummyScanCode
, MAXULONG
);
2881 } while (Response
== -1);
2884 /* Check for return */
2885 if (Response
== '\r')
2888 * We might need to discard the next '\n'.
2889 * Wait a bit to make sure we receive it.
2891 KeStallExecutionProcessor(100000);
2893 /* Check the mode */
2894 if (KdbDebugState
& KD_DEBUG_KDSERIAL
)
2896 /* Read and discard the next character, if any */
2897 KdbpTryGetCharSerial(5);
2901 /* Read and discard the next character, if any */
2902 KdbpTryGetCharKeyboard(&DummyScanCode
, 5);
2906 * Null terminate the output string -- documentation states that
2907 * DbgPrompt does not null terminate, but it does
2909 *(PCHAR
)(OutString
+ i
) = 0;
2911 /* Print a new line */
2912 KdPortPutByteEx(&SerialPortInfo
, '\r');
2913 KdPortPutByteEx(&SerialPortInfo
, '\n');
2915 /* Release spinlock */
2916 KiReleaseSpinLock(&KdpSerialSpinLock
);
2918 /* Lower IRQL back */
2919 KeLowerIrql(OldIrql
);
2921 /* Return the length */
2922 return OutStringLength
+ 1;
2925 /* Write it back and print it to the log */
2926 *(PCHAR
)(OutString
+ i
) = Response
;
2927 KdPortPutByteEx(&SerialPortInfo
, Response
);
2930 /* Print a new line */
2931 KdPortPutByteEx(&SerialPortInfo
, '\r');
2932 KdPortPutByteEx(&SerialPortInfo
, '\n');
2934 /* Release spinlock */
2935 KiReleaseSpinLock(&KdpSerialSpinLock
);
2937 /* Lower IRQL back */
2938 KeLowerIrql(OldIrql
);
2940 /* Return the length */
2941 return OutStringLength
;