1 Chapter 8 - Advanced Native Code Techniques with WinDBGSpring Testing Seminar Debugging Applications for .Net and Microsoft Windows John Robbins Coordinator: Dr.James Fawcett Presented by Priyaa Nachimuthu
2 Agenda Overview Installation notes The Basics Debugging SituationsGeneral Debugging with Command Window The Magical Extensions Dealing with dump files Son of Strike (SOS) Summary
3 Overview Microsoft Visual Studio debugger vs. WinDBG.User-mode native applications. Gives real memory breakpoints and binary handling for minidumps. Allows to see complete OS heaps and all handle information of a process.
4 Overview Goal – starting out,power commands,bugs and strange problems with WinDBG. SOS ( Son of Strike) – managed applications and dump files. Version used : Recent : Beta Refer for the latest information on Debugging Tools for Windows.
5 Installation Notes Include SDK UI – a veneer over DBGENG.DLLMicrosoft NTSD - NT Symbolic Debugger (console application) Documentation – DEBUGGER.CHM
6 Installation Notes DescriptionAdditional Tools Installed with Debugging Tools for Windows Programs Description CDB.EXE The same debugger, as NTSD except it will use the existing command shell when started instead of creating a new one. LOGGER.EXE, LOGVIEWER.EXE A logging system to log all your API calls, record parameters, and return values so that you can track down operating system interaction issues. LIST.EXE A console based text file listing utility. UMDH.EXE The user mode heap dumping utility. TLIST.EXE Lists the currently running process to a console window. KILL.EXE An absolute process killer that will remove any user mode process from memory. BREAKIN.EXE Forces a Debug Break call in the process specified on the command line.
7 The Basics WinDBG – not so helpful as VS.Net in finding symbols and source code. VS.Net - .pdb gives the path to any source file. Symbol server setup. WinDBG chooses _NT_SYMBOL_PATH variable as the base symbol path.
8 The Basics Workspace – specific information about each process which includes breakpoints,window layout,and symbol paths. Base workspace settings – store common values needed across the processes. Source file paths – set _NT_SOURCE_PATH or use source path search dialog popup on WinDBG.
9 The Basics Default location – C run-time and MFC/ATL source code
10 The Basics Live debugging – loads binary files automatically.Debugging minidumps – gets binaries directly from your symbol server. WinDBG is vital for handling minidumps and for squashing bugs. Opening processes – workspace gets updated with specific symbol,source and binary paths. F5 – VS.Net vs. WinDBG
11 The Basics Debugger windows for registers,memory and locals.Scratch pad for taking debug notes.
12 The Basics How to change the command line argument to a process when it is opened in WinDBG?
13 Debugging Situations Command window To specify the address:module!format To specify an address based on a source and line: ‘[[module!]filename][:linenumber]’ Eg: ‘foo.cpp:23’
14 Debugging Situations WinDBG commands:Regular commands – control the debuggee. Meta commands – control the debugger and the act of debugging. Extension commands – digs into the debuggee and analyses states.
15 Debugging Situations Use command help - ? .help – meta commands..hh – HTML help file. Ensuring correct symbols are loaded. WinDBG – an excellent symbol handling. Force symbols to reload at any time. Check Reload option.
16 Debugging Situations 0:000> lm start end module namea AssertTest (deferred) MSVCR71D (deferred) c MSVCP71D (deferred) a BugslayerUtil (deferred) 6d d58d dbghelp (deferred) 70a ad SHLWAPI (deferred) a COMCTL32 (deferred) 77c c VERSION (deferred) 77c c msvcrt (deferred) 77c cb GDI (deferred) 77d dc USER (deferred) 77dd e5d ADVAPI32 (deferred) 77e f kernel32 (deferred) 77f ff ntdll (pdb symbols) \\zeno\WebSymbols\ntdll.pdb\3D6DE29B2\ntdll.pdb RPCRT (deferred)
17 Debugging Situations 0.000> ld assert test 0.000> lmLazy symbol loading ( Deferred ) – to save memory. To force a symbol load: 0.000> ld assert test **** Warning : Unable to verify checksum for AssertTest.exe Symbols loaded for AssertTest 0.000> ld * ( all symbol loading) 0.000> .RELOAD /f ( reports only the modules with symbol problems ) /Release switch – should be /CHECKSUM To verify proper symbol loading : 0.000> lm
18 Debugging Situations 0:000> lm start end module namea AssertTest C (pdb symbols) D:\Dev\BookTwo\Disk\Output\AssertTest.pdb MSVCR71D (pdb symbols) e:\winnt\system32\msvcr71d.pdb c MSVCP71D (pdb symbols) e:\winnt\system32\msvcp71d.pdb # (octothorpe) - COMCTL32.DLL. C – checksums are not set for symbols. To examine the address in memory : 0.000>x kernel32!LoadLibraryW 77e8a379 KERNEL32!LoadLibraryW
19 Debugging Situations 0:000> lm v m gdi32 start end module name77c cb GDI (pdb symbols) \\zeno\WebSymbols\ gdi32.pdb\3D6DE59F2\gdi32.pdb Loaded symbol image file: E:\WINNT\system32\GDI32.dll Image path: E:\WINNT\system32\GDI32.dll Timestamp: Thu Aug 29 06:40: (3D6DFA27) Checksum: C File version: Product version: File flags: (Mask 3F) File OS: NT Win32 File type: Dll File date: CompanyName: Microsoft Corporation ProductName: Microsoft® Windows® Operating System InternalName: gdi32 OriginalFilename: gdi32 ProductVersion: FileVersion: (xpsp ) FileDescription: GDI Client DLL LegalCopyright: © Microsoft Corporation. All rights reserved.
20 Debugging Situations Processes and threads Debugging child processes.CHILDDBG 1/0
21 Debugging Situations 1.001 > | ( for processes)0 id:9ac create name:cmd.exe 1 id:3d0 child notepad.exe 1.001>~ ( for threads) 1 Id: 3d0.39c Suspend:1 Teb: 7ffde000 Unfrozen 2 Id: 3d0.1a4 Suspend: 1 Teb: 7ffdd000 Unfrozen 3 Id: 3d0.8f0 Suspend: 1 Teb: 7ffdc000 Unfrozen 4 Id: 3d0.950 Suspend: 1 Teb: 7ffdb000 Unfrozen
22 Debugging Situations To create a process from the command window:.create “E:\winnt\system32\sol.exe To Attach to a process: .attach (process id) .tlist (lists process ids) 0n1544 e:\winnt\system32\sol.exe 0n1436 E:\Program Files\Windows NT\Pinball\pinball.exe 0n2120 E:\WINNT\system32\winmine.exe
23 Debugging Situations To Detach from a process: .DETACHNon-Invasive Attaching – dedicated instance of WinDBG. Warning – Process 1612 is not attached as a debuggee.The process can be examined but debug events will not be received.
24 General debugging with command windowLooking at and evaluating variables K – display stack backtrace N – to see the call stack with frame numbers on the left. .frame 1 dv cFuncFMT = CResString cIM = CImageHlp_Module szBaseName = Array [260] pMark = cccccccc dwBase = 0x400000 bEnumRet = 0xcccccccc argc = 2 argv = 00344e18 fileOutput = szOutputName = Array [260] iRetValue = 0 bRet = 1 hFile = c8 cRS = CResString
25 General debugging with command windowDT ( Display Type) dt pdb2map!IMAGE* ?? – Evaluate C++ expressions and check pointer arithmetic.
26 General debugging with command windowExecuting,Stepping and Tracing F5 - G (Go command) Shift +F11 – G followed by an address. $ra – use pseudo register as parameter to find the return address.
27 General debugging with command windowT – tracing (step into) P – stepping (step over) .LINES – Toggle source line support (step by assembly instructions). TC – Trace to Next Call PC – Step to Next Call
28 General debugging with command windowTrace and Watch Data Helps to track down performance issues. Eg: STL Code A hierarchical display of function calls A Summary of calls
29 General debugging with command windowSaving options .LOGOPEN – open log file .LOGAPPEND – append log file .LOGCLOSE – close log file Displays till it hits the return address.
30 General debugging with command window0:000> wt Tracing WTExample!wmain to return address c [ 0] WTExample!wmain [ 1] WTExample!Foo [ 2] WTExample!Bar [ 3] WTExample!Baz [ 4] WTExample!Do [ 5] WTExample!Re [ 6] WTExample!Mi [ 7] WTExample!Fa [ 8] WTExample!So [ 9] WTExample!La [10] WTExample!Ti [11] WTExample!Do2 [12] kernel32!Sleep [13] kernel32!SleepEx [14] kernel32!_SEH_prolog [13] kernel32!SleepEx [14] ntdll!
31 General debugging with command window240 instructions were executed in 239 events (0 from other threads) Function Name Invocations MinInst MaxInst AvgInst SharedUserData!SystemCallStub WTExample!Bar WTExample!Baz WTExample!Do WTExample!Do WTExample!Fa WTExample!Foo WTExample!La 1 system call was executed Calls System Call1 ntdll!ZwDelayExecution
32 General debugging with command windowWT -nc : supresses the hierarchy -ns : displays just the hierarchy -0a : displays address,source and line information - l : maximum depth of calls to display
33 General debugging with command windowBreakpoints BP – hard breakpoint that WinDBG associates with the process. BU – associated with the symbol.saved in the workspace. Limited breakpoints dialog box. BL – currently active breakpoint list.
34 General debugging with command windowBE – Breakpoint Enable BD – Breakpoint Disable [~Thread] bu[ID] [Address [Passes]] ["CommandString"] ~Thread- WinDBG thread no. Passes –how many times a breakpoint can be skipped before stopping. j expression 'if true command' ; 'if false command'
35 General debugging with command windowMemory Access Breakpoints [~Thread] ba[ID] Access Size [Address [Passes]] ["CommandString"] BA – Break on Access command Uses Intel debug registers KP:g – to see the stack at the time of access
36 General debugging with command windowExceptions and Events Events – standard events passed to debuggers by MS Win32 debugging API. SX,SXD,SXE,SXI,SXN – to manipulate exceptions and events. Use of dialog box is recommended.
37 General debugging with command windowException group box provides various options. Enabled Disabled Output Ignore
38 General debugging with command windowStatus Description Enabled When the exception occurs, execution occurs and the target will break into the debugger. The first time the exception occurs, the debugger will ignore it. The second time it occurs, execution will halt and the target will break into the debugger. Output When the exception occurs, it won't break into the debugger. However, a message informing the user of this exception will be displayed. Ignore When the exception occurs, the debugger will ignore it. No message will be displayed. Exception Break Status Disabled
39 General debugging with command windowFirst chance exception .LASTEVENT – Display Last Event
40 General debugging with command windowControlling WinDBG Meta commands .CLS .ENABLE_UNICODE .SHELL .SHELL_QUIT OutputDebugString calls
41 General debugging with command windowvoid Baz ( int ) { // To see the following convert into WinDBG commands, issue the // command ".ocommand WINDBGCMD:" inside WinDBG OutputDebugString ( _T ( "WINDBGCMD: .echo \"Hello from WinDBG\";g" )); OutputDebugString ( _T ( "WINDBGCMD: kp;g" ) ) ; OutputDebugString ( _T ("WINDBGCMD: .echo \"Stack walk is done\";g")) ; }
42 The Magical ExtensionsExtensions are DLL files that export specific function names to do the work. Debugging tools for Windows directory contains OS versions of the extension commands. (Win 2000 free build and Win XP) .CHAIN – List Debugger Extensions
43 The Magical Extensions.LOAD – to load an extension. .UNLOAD – to unload an extension DLL. Extension commands are lowercase and are case sensitive. Syntax to call a command: !dllname.command e.g.: !ntsdexts.help !analyze – v command : quick analysis of the current exception(exception record, and call stack) !locks – to see all the locked critical sections. !handle – shows the handle value,and how many of each type of object is in the process.
44 The Magical Extensions!imgreloc – runs through loaded modules and tells whether all modules are loaded at your preferred address. :003> !imgreloc tp4serv - at preferred address 00c50000 tp4uires - RELOCATED from 5ad70000 uxtheme - at preferred address 6b S3appdll - at preferred address WINSTA - at preferred address 76f50000 wtsapi32 - at preferred address !net_send – to send messages to other users !for_each_frame – undocumented and very useful !for_each_frame dv – each frame’s local variables up the stack.
45 Dealing with dump files.DUMP – to create adump file during live debugging. Options: /u – appends date,time and PID. /c – comment specification. /a – write out dump files for multiple processes.
46 Dealing with dump filesTwo types – full and mini dump files Full – includes everything about the process.specified with /f option. Mini – specify using /m option(default).loaded modules versions and sufficient stack information to produce call stacks for all active threads. /mh – writes active handle information. /b – save dump file as a .CAB file.
47 Dealing with dump filesOpen dump files from file menu – Open Crash Dump. WinDBG gets everything loaded automatically. Steps: LM command with v option – to determine missing symbols in some modules. Update the symbol file path for missing symbols. Set the image paths.Paste the symbol path string in the Executable Image Search Path dialog box. WinDBG automatically searches the symbol server for binaries.
48 Dealing with dump filesSet up the source path. Force a symbol reload .RELOAD /f LM – to check for symbol mismatches Symbols and binaries are vital for debugging dump files. .DUMPCAB –a : writes all symbols to a file
49 Son of Strike (SOS) Managed applications are hard to debug.Helpful when creating new .NET front-ends that leverage the existing COM components using COM interop. SOS – debugger extension to help watch .NET portions of dump or live application.
50 Son of Strike (SOS) .load sos - Get SOS.Dll loadedSOS.Dll is a part of .NET Framework The basic documentation for SOS – SOS.htm file in
51 Summary The intent was to show the power of WinDBG.The biggest trick with WinDBG is getting the symbols and source set up. WinDBG offers flexibility for controlling exactly where symbols are found and loaded. An outstanding breakpoint control and dump file handling.
52 References Minidumps MSDN – WinDBG trends
53 Thank you!