Common WinDbg Commands (Thematically Grouped)
Common WinDbg Commands (Thematically Grouped)
Common WinDbg Commands (Thematically Grouped)
9) Exceptions, events, and crash analysis 10) Loaded modules and image information
17) Information about variables 18) Memory 19) Manipulating memory ranges 20) Memory: Heap 21) Application Verifier 22) Logging extension (logexts.dll)
3) Debugging sessions (attach, detach, ..) 11) Process related information 4) Expressions and commands 5) Debugger markup language (DML) 6) Main extensions 7) Symbols 8) Sources 12) Thread related information 13) Breakpoints 14) Tracing and stepping (F10, F11) 15) Call stack 16) Registers
1) Built-in help commands Cmd ? Variants / Params ? ? /D .help .help /D .help /D a* .chain .chain /D .extmatch /e ExtDLL FunctionFilter .extmatch /D /e ExtDLL FunctionFilter Description Display regular commands Display regular commands as DML Display . commands Display . commands in DML format (top bar of links is given) Display . commands that start with a* (wildcard) as DML Lists all loaded debugger extensions Lists all loaded debugger extensions as DML (where extensions are linked to a .extmatch) Show all exported functions of an extension DLL. FunctionFilter = wildcard string Same in DML format (functions link to "!ExtName.help FuncName" commands) Example: .extmatch /D /e uext * (show all exported functions of uext.dll) .hh .hh Text Open WinDbg's help Text = text to look up in the help file index Example: .hh dt
.help
.chain
.extmatch
.hh
Go up 2) General WinDbg's commands (show version, clear screen, etc.) Cmd version vercommand vertarget Variants / Params Description Dump version info of debugger and loaded extension DLLs Dump command line that was used to start the debugger Version of target computer Toggle verbose mode ON/OFF In verbose mode some commands (such as register dumping) have more detailed output. n [8 | 10 | 16] .formats Expression .formats Set number base Show number formats = evaluates a numerical expression or symbol and displays it in multiple numerical formats (hex, decimal, octal, binary, time, ..) Example 1: .formats 5 Example 2: .formats poi(nLocal1) == .formats @@($!nLocal1) Clear screen Displays the most recent exception or event that occurred (why the debugger is waiting?) .effmach .effmach . .effmach # .effmach x86 | amd64 | ia64 | ebc Dump effective machine (x86, amd64, ..): Use target computer's native processor mode Use processor mode of the code that is executing for the most recent event Use x86, amd64, ia64, or ebc processor mode This setting influences many debugger features: - > which processor's unwinder is used for stack tracing - > which processor's register set is active .time display time (system- up, process- up, kernel time, user time)
CTRL+ALT+V
.cls .lastevent
.effmach
http://www.windbg.info/doc/1-common-cmds.html[08/15/2010 13:08:25]
.restart
Go up 4) Expressions and commands Cmd ; ? Expression ?? Expression Variants / Params Description Command separator (cm1; cm2; ..) Evaluate expression (use default evaluator) Evaluate c++ expression Choose default expression evaluator Show current evaluator Show available evaluators Set c++ as the default expression evaluator Set masm as the default expression evaluator Comment Line Specifier Terminated by: end of line Comment Specifier Terminated by: end of line OR semicolon Echo Comment - > comment text + echo it Terminated by: end of line OR semicolon With the $$ token or the * token the debugger will ignore the inputted text without echoing it.
.expr
$$
$$ [any text]
.echo
Go up 5) Debugger markup language (DML) Starting with the 6.6.07 version of the debugger a new mechanism for enhancing output from the debugger and extensions was included: DML. DML allows output to include directives and extra non -display information in the form of tags. Debugger user interfaces parse out the extra information to provide new behaviors. DML is primarily intended to address two issues: Linking of related information Discoverability of debugger and extension functionality Cmd .dml_start .prefer_dml [1 | 0] Variants / Params Description Kick of to other DML commands Global setting: should DML- enhanced commands default to DML? Note that many commands like k, lm, .. output DML content thereafter. .help has a new DML mode where a top bar of links is given .chain has a new DML mode where extensions are linked to a .extmatch .extmatch has a new DML format where exported functions link to "!ExtName.help FuncName" commands lm has a new DML mode where module names link to lmv commands k has a new DML mode where frame numbers link to a .frame/dv Allows for interactive exploration of code flow for a function. .dml_flow .dml_flow StartAddr TargetAddr 1. Builds a code flow graph for the function starting at the given start address (similar to uf) 2. Shows the basic block given the target address plus links to referring blocks and blocks referred to by the current block Example: .dml_flow CreateRemoteThread CreateRemoteThread+30
.prefer_dml
.help /D .chain /D
.extmatch /D
lmD kM
Go up 6) Main extensions
http://www.windbg.info/doc/1-common-cmds.html[08/15/2010 13:08:25]
!NAME.help
!NAME.help FUNCTION
Go up 7) Symbols Cmd ld Variants / Params ld ModuleName ld * !sym !sym noisy !sym quiet x x x x x x [Options] Module!Symbol /t .. /v .. /a .. /n .. /z .. Description Load symbols for Module Load symbols for all modules Get state of symbol loading Set noisy symbol loading (debugger displays info about its search for symbols) Set quiet symbol loading (=default) Examine symbols: displays symbols that match the specified pattern with data type verbose (symbol type and size) sort by address sort by name sort by size ("size" of a function symbol is the size of the function in memory) List nearest symbols = display the symbols at or near the given Addr. Useful to: ln ln Addr determine what a pointer is pointing to when looking at a corrupted stack to determine which procedure made a call Display or set symbol search path Append directories to previous symbol path displays current symbol options add option remove option Set symbol store path to automatically point to http://msdl.microsoft.com/download/symbols + = append it to the existing path DownstreamStore = directory to be used as a downstream store. Default is WinDbgInstallationDir\Sym. Reload symbol information for all modules** f = force immediate symbol load (overrides lazy loading); v = verbose mode Module = for Module only **Note: The .reload command does not actually cause symbol information to be read. It just lets the debugger know that the symbol files may have changed, or that a new module should be added to the module list. To force actual symbol loading to occur use the /f option, or the ld (Load Symbols) command.
!sym
.sympath
.sympath .sympath+ .symopt .symopt+ Flags .symopt- Flags .symfix .symfix+ DownstreamStore
.symopt
.symfix
Collapse x *! x ntdll!* x /t /v MyDll!* x kernel32!*LoadLib* list all modules list all symbols of ntdll list all symbol in MyDll with data type, symbol type and size list all symbols in kernel32 that contain the word LoadLib
http://www.windbg.info/doc/1-common-cmds.html[08/15/2010 13:08:25]
Immediately reload symbols for ntdll.dll. Reload symbols for verifier. Use the given path.
Go up 8) Sources Cmd .srcpath Variants / Params .srcpath .srcpath+ DIR {1|0} [ - e | - d | - t] l+l, l- l l+o, l- o l+s, l- s l+t, l- t Description Display or set source search path Append directory to the searched source path Controls noisy source loading Toggle source line support: enable; disable; toggle show line numbers suppress all but [s] source and line number source mode vs. assembly mode
.srcnoisy .lines
l (small letter L)
Go up 9) Exceptions, events, and crash analysis Cmd g Variants / Params g gH gN Description Go Go exception handled Go not handled What happened? Shows most recent event or exception !analyze - v !analyze - hang !analyze - f sx sxe sxd sxn sxi sxr .exr- 1 .exr Addr Display information about the current exception or bug check; verbose User mode: Analyzes the thread stack to determine whether any threads are blocking other threads. See an exception analysis even when the debugger does not detect an exception. Show all event filters with break status and handling break first- chance break second- chance notify; don't break ignore event reset filter settings to default values display most recent exception record display exception record at Addr displays exception context record (registers) associated with the current exception Addr Display content and type of C++ exception
.lastevent
!analyze
sx
.exr
.ecxr !cppexr Collapse exr - 1 .exr 7c901230 !cppexr 7c901230 display most recent exception display exception at address 7c901230 display c++ exception at address 7c901230
Go up 10) Loaded modules and image information Cmd lm Variants / Params lm[ v | l | k | u | f ] [m Pattern] lmD Description List modules; verbose | with loaded symbols | k- kernel or u- user only symbol info | image path; pattern that the module name must match DML mode of lm; lmv command links included in output all loaded modules with load count by initialization order by load order (default) by memory order with version info only module at ModuleAddr brief help
!dlls
-i -l -m -v - c ModuleAddr -?
http://www.windbg.info/doc/1-common-cmds.html[08/15/2010 13:08:25]
!dh
display information for kernel32.dll, including load-count display detailed information about kernel32, including symbol information display headers for kernel32
Go up 11) Process related information Cmd !dml_proc | (pipe) .tlist !peb Collapse !peb r $peb dt ntdll!_PEB dt ntdll!_PEB @$peb - r Dump formatted view of processes PEB (only some information) Dump address ob PEB. $peb == pseudo- register Dump PEB struct Recursively ( - r) dump PEB of our process Variants / Params Description (DML) displays current processes and allows drilling into processes for more information Print status of all processes being debugged lists all processes running on the system display formatted view of the process's environment block (PEB)
Go up 12) Thread related information Cmd Variants / Params ~ ~* [Command] ~. [Command] ~# [Command] ~Number [Command] ~~[TID] [Command] ~Ns Description list threads all threads current thread thread that caused the current event or exception thread whose ordinal is Number thread whose thread ID is TID (the brackets are required) switch to thread N (new current thread) [Command]: works for a few regular commands such as k, r Execute thread- specific commands (CommandString = one or more commands to be executed) for: all threads current thread thread which caused the current event thread with ordinal Freeze thread (see ~ for Thread syntax) Unfreeze thread (see ~ for Thread syntax) Suspend thread = increment thread's suspend count Resume thread = decrement thread's suspend count display formatted view of the thread's environment block (TEB)
~e
~f ~u ~n ~m !teb
http://www.windbg.info/doc/1-common-cmds.html[08/15/2010 13:08:25]
!tls
.ttime
!gle
call stack for all threads ~ !uniqstack Freeze Thread TID=2 Freeze the thread causing the current exception Unfreeze Thread TID=3 == ~2r; ~2k; ~2kd will repeat every the extension command !gle for every single thread being debugged
!tls - 1
!runaway 7
Dump formatted view of our threads TEB (only some information) Dump TEB of current thread
Go up 13) Breakpoints Cmd bl bc * bc # [#] [#] be * be # [#] [#] bd * bd # [#] [#] bp [Addr] bp [Addr] ["CmdString"] bp [~Thrd] bp[#] [Options] [Addr] [Passes] ["CmdString"] Variants / Params Description List breakpoints Clear all breakpoints Clear breakpoint # Enable all bps Enable bp # Disable all bps Disable bp # Set breakpoint at address CmdString = Cmd1; Cmd2; .. Executed every time the BP is hit. ~Thrd == thread that the bp applies too. # = Breakpoint ID Passes = Activate breakpoint after #Passes (it is ignored before) Set unresolved breakpoint. bp is set when the module gets loaded
bc
be
bd
bu [Addr] bu See bp .. bm SymPattern bm SymPattern ["CmdString"] bm [~Thrd] bm [Options] SymPattern [#Passes] ["CmdString"]
Set symbol breakpoint. SymPattern can contain wildcards CmdString = Cmd1; Cmd2; .. Executed every time the BP is hit. ~Thrd == thread that the bp applies too. Passes = Activate breakpoint after #Passes (it is ignored before)
http://www.windbg.info/doc/1-common-cmds.html[08/15/2010 13:08:25]
The syntax bm SymPattern is equivalent to using x SymPattern and then using bu on each of the results. ba [r|w|e] [Size] Addr ba [~Thrd] ba[#] [r|w|e] [Size] [Options] [Addr] [Passes] ["CmdString"] Break on Access: [r=read/write, w=write, e=execute], Size=[1|2|4 bytes] [~Thrd] == thread that the bp applies too. # = Breakpoint ID Passes = Activate breakpoint after #Passes (it is ignored before) renumbers one or more breakpoints
br Collapse
With bp, the breakpoint location is always converted to an address. In contrast, a bu or a bm breakpoint is always associated with the symbolic value. Simple Examples bp `mod!source.c:12` bm myprogram!mem* bu myModule!func ba w4 77a456a8 bp @@( MyClass::MyMethod ) set breakpoint at specified source code SymbolPattern is equivalent to using x SymbolPattern bp set as soon as myModule is loaded break on write access break on methods (useful if the same method is overloaded and thus present on several addresses)
Breakpoitns with options Breakpoint that is triggered only once bp mod!addr /1 Breakpoint that will start hitting after k -1 passes bp mod!addr k
Breakpoints with commands: The command will be executed when the breakpoint is hit. Produce a log every time the breakpoint is hit ba w4 81a578a8 "k;g" Create a dump every time BP is hit bu myModule!func ".dump c:\dump.dmp; g" DllMain called for MYDLL -> check reason bu MYDLL!DllMain "j (dwo(@esp+8) == 1) '.echo MYDLL!DllMain - > DLL_PROCESS_ATTACH; kn' ; 'g' " LoadLibraryExW( anyDLL ) called -> display name of anyDLL bu kernel32!LoadLibraryExW ".echo LoadLibraryExW for - >; du dwo(@esp+4); g" LoadLibraryExW( MYDLL ) called? -> Break only if LoadLibrary is called for MyDLL bu kernel32!LoadLibraryExW ";as /mu ${/v:MyAlias} poi(@esp+4); .if ( $spat( \"${MyAlias}\", \"*MYDLL*\" ) != 0 ) { kn; } .else { g }" The first parameter to LoadLibrary (at address ESP + 4) is a string pointer to the DLL name in question. The MASM $spat operator will compare this pointer to a predefined string- wildcard, this is *MYDLL* in our example. Unfortunately $spat can accept aliases or constants, but no memory pointers. This is why we store our string in question to an alias ( MyAlias) first. Our kernel32!LoadLibraryExW breakpoint will hit only if the pattern compared by $spat matches. Otherwise the application will continue executing. Skip execution of a function bu sioctl!DriverEntry "r eip = poi(@esp); r esp = @esp + 0xC; .echo sioctl!DriverEntry skipped; g" Right at a functions entry point the value found on the top of the stack contains the return address r eip = poi(@esp) - > Set EIP (instruction pointer) to the value found at offset 0x0 DriverEntry has 2x4 byte parameters = 8 bytes + 4 bytes for the return address = 0xC r esp = @esp + 0xC - > Add 0xC to Esp (the stack pointer), effectively unwinding the stack pointer bu MyApp!WinMain "r eip = poi(@esp); r esp = @esp + 0x14; .echo WinSpy!WinMain entered; g" WinMain has 4x4 byte parameters = 0x10 bytes + 4 bytes for the return address = 0x14
Howto set a brekpoint in your code programatically? kernel32!DebugBreak ntdll!DbgBreakPoint __asm int 3 (x86 only)
http://www.windbg.info/doc/1-common-cmds.html[08/15/2010 13:08:25]
Go up 14) Tracing and stepping (F10, F11) Each step executes either a single assembly instruction or a single source line, depending on whether the debugger is in assembly mode or source mode. Use the l+t and l -t commands or the buttons on the WinDbg toolbar to switch between these modes. Cmd Variants / Params g gu g (F5) Description Go (F5) Go up = execute until the current function is complete gu ~= g @$ra gu ~= bp /1 /c @$csp @$ra;g - > $csp = same as esp on x86 - > $ra = The return address currently on the stack Single step - executes a single instruction or source line. Subroutines are treated as a single step. Toggle display of registers and flags Count = count of instructions or source lines to step through before stopping Command = debugger command to be executed after the step is performed StartAddress = Causes execution to begin at the specified address. Default is the current EIP. ~Thread = The specified thread is thawed and all others frozen
p pr p Count p [Count] "Command" p =StartAddress [Count] ["Command"] [~Thread] p [=StartAddress] [Count] ["Command"] t .. pt ..
p (F10)
t (F11)
Single trace - executes a single instruction or source line. For subroutines each step is traced as well.
pt
Step to next return - similar to the GU (go up), but staying in context of the current function If EIP is already on a return instruction, the entire return is executed. After this return is returned, execution will continue until another return is reached. Trace to next return - similar to the GU (go up), but staying in context of the current function If EIP is already on a return instruction, the debugger traces into the return and continues executing until another return is reached. Step to next call - executes the program until a call instruction is reached If EIP is already on a call instruction, the entire call will be executed. After this call is returned execution will continue until another call is reached. Trace to next call - executes the program until a call instruction is reached If EIP is already on a call instruction, the debugger will trace into the call and continue executing until another call is reached. Step to address; StopAddr = address at which execution will stop Called functions are treated as a single unit Toggle display of registers and flags Command = debugger command to be executed after the step is performed StartAddress = Causes execution to begin at the specified address. Default is the current EIP. Trace to address; StopAddr = address at which execution will stop Called functions are traced as well Trace and watch data. Go to the beginning of a function and do a wt. It will run through the entire function and display statistics. [Options] [= StartAddr] [EndAddr] - l Depth .. - m Module [ - m Module2] .. - i Module [ - i Module2] .. - oa .. - or .. - oR .. - nc .. - ns .. - nw .. StartAddr = execution begin; EndAddr = address at which to end tracing (default = after RET of current function) l = maximum depth of traced calls m = restrict tracing to Module i = ignore code from Module oa = dump actual address of call sites or = dump return register values (EAX value) of sub- functions oR = dump return register values (EAX value) in the appropriate type nc = no info for individual calls ns = no summary info ns = no warnings Dump current filter list = functions that are skipped when tracing (t, ta, tc) FilterList = Filter 1; Filter 2; ... symbols associated with functions to be stepped over (skipped) clear the filter list .step_filter is not very useful in assembly mode, as each function call is on a different line.
tt
tt ..
pc
pc ..
tc
tc ..
pa StopAddr pa
ta
wt
.step_filter
Collapse g g `:123`; ? poi(counter); g go executes the current program to source line 123; print the value of counter; resume execution
http://www.windbg.info/doc/1-common-cmds.html[08/15/2010 13:08:25]
pc pa 7c801b0b
wt wt - l 4 - oR
trace and watch sub- functions trace sub- functions to depth 4, display their return values
Go up 15) Call stack Cmd Variants / Params k [n] [f] [L] [#Frames] kb ... kp ... kP ... kv ... Description dump stack; n = with frame #; f = distance between adjacent frames; L = omit source lines; number of stack frames to display first 3 params all params: param type + name + value all params formatted (new line) FPO info, calling convention display raw stack data + possible symbol info == dds esp DML variant with links to .frame #;dv Set stack length. The default is 20 (0x14). .frame .frame # .frame /r [#] show current frame specify frame # show register values The .frame command specifies which local context (scope) will be used to interpret local variables, or displays the current local context. When executing a near call, the processor pushes the value of the EIP register (which contains the offset of the instruction following the CALL instruction) onto the stack (for use later as a returninstruction pointer). This is the first step in building a frame. Each time a function call is made, another frame is created so that the called function can access arguments, create local variables, and provide a mechanism to return to calling function. The composition of the frame is dependant on the function calling convention. !uniqstack !uniqstack [b|v|p] [n] !uniqstack - ? show stacks for all threads [b = first 3 params, v = FPO + calling convention, p = all params: param type + name + value], [n = with frame #] brief help locate all stacks that contain Symbol or module [0 = show only TID, 1 = TID + frames, 2 = entire thread stack] brief help
kd kM .kframes
kd [WordCnt]
.frame
!uniqstack
!findstack
Collapse k kn kb kb 5 display call stack call stack with frame numbers display call stack with first 3 params display first 5 frames only
To get more than 3 Function Arguments from the stack dd ChildEBP+8 (Parameters start at ChildEBP+8) dd ChildEBP+8 (frame X) == dd ESP (frame X- 1)
get all stacks of our process (one for each thread) display all stacks that contain "kernel32"
show current frame set frame 2 for the local context display registers in frame 0
Go up
http://www.windbg.info/doc/1-common-cmds.html[08/15/2010 13:08:25]
r Reg:[Num]Type
rF
rX
Dump all SSE XMM registers == rM 0x40 Dump only specified SSE XMM registers Value to assign to the register
rm
Dump default register mask. This mask controls how registers are displayed by the "r". Dump a list of possible Mask bits Specify the mask to use when displaying the registers.
rm 0x20 r
rF rM 0x4 rm 0x4; r
dump all floating point register dump all floating point register dump all floating point registers
Go up 17) Information about variables Cmd Variants / Params dt dt dt dt -h [mod!]Name [mod!]Name Field [Field] [mod!]Name [Field] Addr Description Brief help Dump variable info Dump only 'field- name(s)' (struct or unions) Addr of struct to be dumped
http://www.windbg.info/doc/1-common-cmds.html[08/15/2010 13:08:25]
dt
dv
dv dv Pattern dv [ /i /t /V ] [Pattern] dv [/i /t /V /a /n /z] [Pattern] Collapse dt ntdll!_PEB* dt ntdll!_PEB* - v dt ntdll!_PEB* - v - s 9 list all variables that contain the word _PEB
list with verbose output (address and size included) list only symbols whose size is 9 bytes
dt ntdll!_PEB dt ntdll!_PEB @$peb dt ntdll!_PEB 7efde000 dt ntdll!_PEB Ldr SessionId dt ntdll!_PEB Ldr - y OS*
dump _PEB info dump _PEB for our process dump _PEB at Addr 7efde000 You can get our process's PEB address with "r @$peb" or with "!peb". dump only PEB's Ldr and SessionId fields dump Ldr field + all fields that start with OS*
dump m_cs and expand its subfields expand its subfields for 2 levels
dt ntdll!_PEB - r2
dv /t /i /V
dump local variables with type information (/t), addresses and EBP offsets (/V), classify them into categories (/i) Note: dv will also display the value of a THIS pointer for methods called with the "this calling- convention". BUG: You must first execute a few commands before dv displays the correct value. Right at a function's entry point the THIS pointer is present in ECX, so you can easily get it from there.
Go up 18) Memory Cmd Variants / Params d[a| u| b| w| W| d| c| q| f| D] [/c #] [Addr] Description Display memory [#columns to display] a = ascii chars u = Unicode chars b = byte + ascii w = word (2b) W = word (2b) + ascii d = dword (4b) c = dword (4b) + ascii q = qword (8b) f = floating point (single precision - 4b) D = floating point (double precision - 8b) dy[b | d] .. b = binary + byte d = binary + dword Edit memory b = byte w = word (2b) d = dword (4b) q = qword (8b) f = floating point (single precision - 4b) D = floating point (double precision - 8b)
d*
e[ b | w | d | q | f | D ] Addr Value
e*
http://www.windbg.info/doc/1-common-cmds.html[08/15/2010 13:08:25]
ds, dS
d*s
dl
!address
!vprot
display dwords at 0046c6b0 display 1 dword at 0046c6b0 display 3 dwords at 0046c6b0 display Unicode chars at 0046c6b0 display 5 Unicode chars at 0046c6b0
dds esp == kd
!mapped_file 00400000
show all memory regions of our process show all stack regions of our process show info for committed sub- region for our thread's stack. Note: For stack overflows SubRegionSize (size of committed memory) will be large, i.e.:
!address esp
--------------
http://www.windbg.info/doc/1-common-cmds.html[08/15/2010 13:08:25]
<- _TEB.StackLimit
<- _TEB.DeallocationStack
Go up 19) Manipulating memory ranges Cmd c m f Variants / Params c Range DestAddr m Range DestAddr f Range Pattern s Range Pattern s - [Flags]b Range Pattern Description Compare memory Move memory Fill memory. Pattern = a series of bytes (numeric or ASCII chars) Search memory b = byte (default value) Pattern = a series of bytes (numeric or ASCII chars) w = word (2b) d = dword (4b) q = qword (8b) Pattern = enclosed in single quotation marks (for example, 'Tag7') a = ascii string (must not be null- terminated) u = Unicode string (must not be null- terminated) Pattern = enclosed in double quotation marks (for example, "This string") Search for any memory containing printable ascii strings Search for any memory containing printable Unicode strings Length = minimum length of such strings; the default is 3 chars Search for objects of the same type. Object = Addr of a pointer to the Object or of the Object itself Flags ------w = search only writable memory 1 = output only addresses of search matches (useful if you are using the .foreach) Flags must be surrounded by a single set of brackets without spaces. Example: s -[swl 10]Type Range Pattern Hold and compare memory. The comparison is made byte- for- byte Memory range to safe Display all saved memory ranges Compares Range to all saved memory ranges Delete all saved memory ranges Delete specified memory ranges (any saved range containing Addr or overlapping with Range)
s - [Flags]a Range "Pattern" s - [Flags]u Range "Pattern" s s - [Flags,l length]sa Range s - [Flags,l length]su Range
.holdmem
Collapse c Addr (Addr+100) DestAddr c Addr L100 DestAddr compare 100 bytes at Addr with DestAddr - ||-
fill specified memory location with the pattern "ABC", repeated several times - ||-
s 0012ff40 L20 'H' 'e' 'l' 'l' 'o' s 0012ff40 L20 48 65 6c 6c 6f s - a 0012ff40 L20 "Hello"
search memory locations 0012FF40 through 0012FF5F for the pattern "Hello" - ||- ||-
http://www.windbg.info/doc/1-common-cmds.html[08/15/2010 13:08:25]
Go up 20) Memory: Heap Cmd Variants / Params !heap -? !heap !heap !heap !heap !heap !heap !heap !heap Description Brief help List heaps with index and HeapAddr List heaps with index and range (= startAddr(=HeapAddr), endAddr) Detailed heap info [Idx = heap Idx, 0 = all heaps] Validate heap [Idx = heap Idx, 0 = all heaps] Summary info, i.e. reserved and committed memory [Idx = heap Idx, 0 = all heaps] Detailed info for a block at given address Search heap block containing the address (v = search the whole process virtual space) Search for potentially leaked heap blocks Set conditional breakpoint in the heap manager [Heap = HeapAddr | Idx | 0] Remove a conditional breakpoint Dump info for allocations matching the specified size Filter by range Dump heap handle list Dump usage statistic for every AllocSize [HeapHandle = given heap | 0 = all heaps]. The statistic includes AllocSize, #blocks, TotalMem for each AllocSize. Extended page heap help Summary for NtGlobalFlag, HeapHandle + NormalHeap list ** Detailed info about a page heap with Handle Details of heap allocation containing UserAddr. Prints backtraces when available. Details of all allocations in all heaps in the process. The output includes UserAddr and AllocSize for every HeapAlloc call .
!heap
!heap - b, - B
!heap Heap - b [alloc | realloc | free] [Tag] !heap Heap - B [alloc | realloc | free] !heap - flt s Size !heap - flt r SizeMin SizeMax !heap -stat !heap -stat -h [HeapHandle | 0]
!heap - flt
!heap - stat
!heap - p
-p -p -p -p -p
It seems that the following applies for windows XP SP2: a) Normal heap 1. CreateHeap - > creates a _HEAP 2. AllocHeap - > creates a _HEAP_ENTRY b) Page heap enabled (gflags.exe /i +hpa) 1. CreateHeap - > creates a _DPH_HEAP_ROOT (+ _HEAP + 2x _HEAP_ENTRY)** 2. AllocHeap - > creates a _DPH_HEAP_BLOCK ** With page heap enabled there will still be a _HEAP with two constant _HEAP_ENTRY's for every CreateHeap call.
Description = value returned by HeapCreate or GetProcessHeap For normal heap: HeapHandle == HeapStartAddr = startAddr = NormalHeap = value in the range [ HeapAlloc...HeapAlloc+AllocSize] For normal heap this range is further within Heap[startAddr- endAddr] = AllocSize (value passed to HeapAlloc) = HeapHandle = HeapStartAddr For every HeapCreate a _HEAP struct is created. You can use "!heap - p - all" to get these addresses. For every HeapAlloc a _HEAP_ENTRY is created. You can use "!heap - p - all" to get these addresses. = usually HeapHandle + 0x1000 For every HeapCreate a _DPH_HEAP_ROOT is created. You can use "!heap - p - all" to get these addresses. For every HeapAlloc a _DPH_HEAP_BLOCK is created. You can use "!heap - p - all" to get these addresses.
Heap type Normal & page Normal & page Normal & page Normal & page Normal heap Normal heap
_DPH_HEAP_ROOT _DPH_HEAP_BLOCK
Collapse dt ntdll!_HEAP dt ntdll!_DPH_HEAP_ROOT dump _HEAP struct dump _DPH_HEAP_ROOT struct. Enable page heap. Then you can use "!heap - p - all" to get addresses of actual _DPH_HEAP_ROOT structs in your process. dump _DPH_HEAP_BLOCK struct. Enable page heap. Then you can use "!heap - p - all" to get addresses of actual _DPH_HEAP_BLOCK structs in your process.
dt ntdll!_DPH_HEAP_BLOCK
!heap
http://www.windbg.info/doc/1-common-cmds.html[08/15/2010 13:08:25]
!heap - flt s 20
Dump HeapHandle list. HeapHandle = value returned by HeapCreate or GetProcessHeap Dump usage statistic for HeapHandle = 00150000
Dump heap handle list Details of heap allocation containing address 014c6fb0 + call - stack if available Dump details of all allocations in all heaps in the process
Who allocated memory - who called HeapAlloc? 1. 2. 3. 4. 5. 6. Select "Create user mode stack trace database" for your image in GFlags (gflags.exe /i +ust) From WinDbg's command line do a !heap -p -a , where is the address of your allocation ***. While !heap - p - a will dump a call - stack, no source information will be included. To get source information you must additionally enable page heap in step 1 (gflags.exe /i +ust +hpa) Do a dt ntdll!_DPH_HEAP_BLOCK StackTrace , where is the DPH_HEAP_BLOCK address retrieved in step 3. Do a dds ", where is the value retrieved in step 5. Note that dds will dump the stack with source information included.
Who created a heap - who called HeapCreate? 1. Select "Create user mode stack trace database" and "Enable page heap" for your image in GFlags (gflags.exe /i +ust +hpa) 2. a) From WinDbg's command line do a !heap -p -h , where is the value returned by HeapCreate. You can do a !heap -stat or !heap -p to get all heap handles of your process. b) Alternatively you can use !heap -p -all to get addresses of all _DPH_HEAP_ROOT's of your process directly. 3. Do a dt ntdll!_DPH_HEAP_ROOT CreateStackTrace , where is the address of a _DPH_HEAP_ROOT retrieved in step 2 4. Do a dds , where is the value retrieved in step 3.
Finding memory leaks From WinDbg's command line do a !address summary . If RegionUsageHeap or RegionUsagePageHeap are growing, then you might have a memory leak on the heap. Proceed with the following steps. 1. Enable "Create user mode stack trace database" for your image in GFlags (gflags.exe /i +ust) 2. From WinDbg's command line do a !heap -stat, to get all active heap blocks and their handles. 3. Do a !heap -stat -h 0. This will list down handle specific allocation statistics for every AllocSize. For every AllocSize the following is listed: AllocSize, #blocks, and TotalMem. Take the AllocSize with maximum TotalMem. 4. Do a !heap -flt s . =AllocSize that we determined in the previous step. This command will list down all blocks with that particular size. 5. Do a !heap -p -a to get the stack trace from where you have allocated that much bytes. Use the that you got in step 4. 6. To get source information you must additionally enable page heap in step 1 (gflags.exe /i +ust +hpa) 7. Do a dt ntdll!_DPH_HEAP_BLOCK StackTrace , where is the DPH_HEAP_BLOCK address retrieved in step 5. 8. Do a dds ", where is the value retrieved in step 7. Note that dds will dump the stack with source information included.
int AllocSyze = 0x100000; // == 1 MB BYTE* pUserAddr = (BYTE*) HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, AllocSyze);
2. Often any address in the range [UserAddr....UserAddr+AlloSize] is also a valid parameter:
!heap -p -a [UserAddr....UserAddr+AlloSize]
Go up 21) Application Verifier Application Verifier profiles and tracks Microsoft Win32 APIs (heap, handles, locks, threads, DLL load/unload, and more), Exceptions, Kernel objects, Registry, File system. With the !avrf extension we get access to this tracking information! Cmd !avrf Variants / Params Description Displays Application Verifier options. If an Application Verifier Stop has occurred, reveal the nature of the stop and what caused it. -? - vs N - vs - a ADDR - hp N Brief help Dump last N entries from vspace log (MapViewOfFile, UnmapViewOfFile, ..). Searches ADDR in the vspace log. HeapAlloc, HeapFree, new, and delete log
http://www.windbg.info/doc/1-common-cmds.html[08/15/2010 13:08:25]
Go up 22) Logging extension (logexts.dll) You must enable the following options for you image in GFlags: -> "Create user mode stack trace database" -> "Stack Backtrace: (Megs)" -> 10 -> It seems that you sometimes also need to check and specify the "Debugger" field in GFlags Cmd !logexts.help !loge !logi !logd !logo !logo [e|d] [d|t|v] !loge [dir] Variants / Params Description displays all Logexts.dll extension commands Enable logging + possibly initialize it if not yet done. Output directory optional. Initialize (=inject Logger into the target application) but don't enable logging. Disable logging List output settings Enable/disable [d - Debugger, t - Text file, v - Verbose log] output. Use logviewer.exe to examine Verbose logs. List all categories List APIs in category # Enable/disable all categories Enable/disable category # Print buffer contents to debugger Flush buffer to log files Display module inclusion/exclusion list Specify module inclusion/exclusion list
!logo
!logc
!logc !logc p # !logc [e|d] * !logc [e|d] # [#] [#] !logb p !logb f !logm !logm [i|x] [DLL] [DLL]
!logb
!logm Collapse
Enable 19- ProcessesAndThreads and 22- StringManipulation logging: !loge !logc d * !logc p 19 logc e 19 22 !logo d v !logo d t !logo e d Enable logging Disable all categories Display APIs of category 19 Enable category 19 and 22 Disable verbose output Disable text output Enable debugger output
Between 1 November 2007 and 31 Januar 2009 this article was published on software.rkuster.com where it was viewed 28.705 times.
http://www.windbg.info/doc/1-common-cmds.html[08/15/2010 13:08:25]