Skip to content

Latest commit

 

History

History
1338 lines (994 loc) · 37.7 KB

File metadata and controls

1338 lines (994 loc) · 37.7 KB

WinDbg User Tutorial Manual

A Complete Entry-Level Guide to Windows Debugging


Table of Contents

  1. Introduction to WinDbg
  2. Installation and Setup
  3. Understanding the Interface
  4. Basic Concepts
  5. Getting Started with Live Debugging
  6. Working with Crash Dumps
  7. Essential Commands
  8. Practical Debugging Scenarios
  9. Advanced Features
  10. Troubleshooting Common Issues
  11. Resources and Next Steps

1. Introduction to WinDbg

What is WinDbg?

WinDbg (Windows Debugger) is a powerful debugging tool developed by Microsoft for analyzing Windows applications, drivers, and the Windows operating system itself. It's part of the Windows SDK and is widely used by developers, system administrators, and security researchers.

Key Features

Feature Description
Multi-target Debugging Debug user-mode applications, kernel-mode drivers, and system crashes
Live Debugging Attach to running processes for real-time analysis
Crash Dump Analysis Analyze memory dumps from crashed applications or systems
Scripting Support Automate debugging tasks with JavaScript and other scripting languages
Extension Support Use built-in and custom extensions for specialized debugging

When to Use WinDbg

graph TD
    A[Application Issues] --> B{Issue Type}
    B --> C[Crashes/Hangs]
    B --> D[Memory Leaks]
    B --> E[Performance Issues]
    B --> F[Driver Problems]
    C --> G[Use WinDbg]
    D --> G
    E --> G
    F --> G
Loading

WinDbg vs Other Debuggers

Tool Best For Complexity Cost
WinDbg System-level debugging, crash dumps High Free
Visual Studio Debugger Application development Medium Paid/Free
Process Monitor File/Registry monitoring Low Free
Application Verifier Finding application errors Medium Free

2. Installation and Setup

System Requirements

  • Operating System: Windows 7 or later (Windows 10/11 recommended)
  • Architecture: x86, x64, or ARM64
  • RAM: Minimum 4GB (8GB+ recommended for dump analysis)
  • Storage: 2GB free space for installation

Installation Methods

Method 1: Windows SDK (Recommended)

  1. Download the Windows SDK from Microsoft's official website
  2. Run the installer
  3. Select "Debugging Tools for Windows" component
  4. Complete the installation

Method 2: Microsoft Store

  1. Open Microsoft Store
  2. Search for "WinDbg Preview"
  3. Install the modern version with updated UI

Initial Configuration

Setting Up Symbol Paths

Symbols are crucial for meaningful debugging. Configure your symbol path:

_NT_SYMBOL_PATH=srv*c:\symbols*https://msdl.microsoft.com/download/symbols

Environment Variables Setup

Variable Purpose Example Value
_NT_SYMBOL_PATH Symbol file location srv*c:\symbols*https://msdl.microsoft.com/download/symbols
_NT_SOURCE_PATH Source code location c:\source;c:\projects
_NT_EXECUTABLE_IMAGE_PATH Binary file location c:\windows\system32

Verification

To verify your installation:

  1. Open Command Prompt as Administrator
  2. Type windbg and press Enter
  3. WinDbg should launch successfully

3. Understanding the Interface

WinDbg Classic Interface

┌─────────────────────────────────────────────────────────────────┐
│ File  Edit  View  Debug  Options  Window  Help                 │
├─────────────────────────────────────────────────────────────────┤
│ [Toolbar with common debugging buttons]                         │
├─────────────────────────────────────────────────────────────────┤
│                                                                 │
│  Command Window                     │  Watch Window             │
│  > !analyze -v                     │                           │
│  > k                              │  Variable1: 0x12345678    │
│  > lm                             │  Variable2: "Hello"       │
│                                    │                           │
├─────────────────────────────────────┼───────────────────────────┤
│                                    │                           │
│  Disassembly Window                │  Registers Window         │
│  ntdll!NtWaitForSingleObject:      │  eax=00000000            │
│  77f5d5a0 mov     edx,esp          │  ebx=00000001            │
│  77f5d5a2 sysenter                │  ecx=7ffdf000            │
│                                    │                           │
└─────────────────────────────────────┴───────────────────────────┘

Key Interface Components

Component Purpose Keyboard Shortcut
Command Window Execute debugging commands Alt+1
Watch Window Monitor variables and expressions Alt+2
Locals Window View local variables Alt+3
Registers Window Display CPU registers Alt+4
Memory Window Examine memory contents Alt+5
Call Stack Window Show function call hierarchy Alt+6
Disassembly Window View assembly code Alt+7

WinDbg Preview Interface

WinDbg Preview offers a modernized interface with:

  • Tabbed Windows: Organize multiple debugging sessions
  • Enhanced Syntax Highlighting: Better code readability
  • Improved Search: Find text across all windows
  • Dark Theme Support: Reduce eye strain during long debugging sessions

4. Basic Concepts

Understanding Processes and Threads

Process Architecture

┌─────────────────────────────────────┐
│           Process Space             │
│  ┌─────────────────────────────────┐ │
│  │        Virtual Memory           │ │
│  │  ┌─────────┐  ┌─────────┐      │ │
│  │  │  Code   │  │  Data   │      │ │
│  │  │ Section │  │ Section │      │ │
│  │  └─────────┘  └─────────┘      │ │
│  │  ┌─────────┐  ┌─────────┐      │ │
│  │  │  Heap   │  │  Stack  │      │ │
│  │  │         │  │(Thread 1)│      │ │
│  │  └─────────┘  └─────────┘      │ │
│  └─────────────────────────────────┘ │
└─────────────────────────────────────┘

Thread States

State Description Common Causes
Running Currently executing Normal execution
Ready Waiting for CPU time Multitasking
Waiting Blocked on resource I/O operations, locks
Terminated Execution completed Normal or abnormal exit

Memory Management

Virtual Memory Layout (32-bit)

0xFFFFFFFF ┌─────────────────┐
           │   Kernel Space  │ (2GB)
           │                 │
0x80000000 ├─────────────────┤
           │   User Space    │ (2GB)
           │                 │
           │   Application   │
           │     Code        │
           │                 │
0x00000000 └─────────────────┘

Memory Types

Type Purpose Characteristics
Stack Function calls, local variables LIFO, automatic cleanup
Heap Dynamic memory allocation Manual management required
Code Executable instructions Read-only, shared
Data Global variables, constants Read/write, initialized

Debugging Modes

User-Mode Debugging

  • Target: Applications and services
  • Access Level: Limited to user permissions
  • Use Cases: Application crashes, hangs, logic errors

Kernel-Mode Debugging

  • Target: Device drivers, operating system
  • Access Level: Full system access
  • Use Cases: Blue screens, driver issues, system-level problems

Symbol Files

What are Symbols?

Symbols contain metadata about your program:

  • Function names
  • Variable names
  • Data type information
  • Source line numbers

Symbol File Types

Extension Type Contains
.pdb Program Database Full debugging information
.dbg Debug File Older format, basic info
.sym Symbol File Minimal symbol information

5. Getting Started with Live Debugging

Attaching to a Running Process

Step-by-Step Process Attachment

  1. Launch WinDbg as Administrator

    Right-click WinDbg → "Run as administrator"
    
  2. Attach to Process

    • Menu: File → Attach to a Process
    • Keyboard: F6
  3. Select Target Process

    Process Name Description Debug Difficulty
    notepad.exe Simple text editor Beginner
    calc.exe Calculator application Beginner
    explorer.exe Windows Explorer Intermediate
    chrome.exe Web browser Advanced

Example: Debugging Notepad

Microsoft (R) Windows Debugger Version 10.0.22621.2428 AMD64
Copyright (c) Microsoft Corporation. All rights reserved.

Executable search path is: 
ModLoad: 00007ff7`8b2d0000 00007ff7`8b310000   notepad.exe
ModLoad: 00007ffc`d5f10000 00007ffc`d6108000   ntdll.dll
ModLoad: 00007ffc`d4e60000 00007ffc`d4f1d000   C:\WINDOWS\System32\KERNEL32.DLL
ModLoad: 00007ffc`d3820000 00007ffc`d3b16000   C:\WINDOWS\System32\KERNELBASE.dll

0:000> 

Basic Navigation Commands

Essential Movement Commands

Command Action Example
g Go/Continue execution g
p Step over p
t Step into t
gu Go up (step out) gu
bp Set breakpoint bp notepad!WinMain

Examining the Current State

0:000> r
rax=0000000000000000 rbx=0000000000000000 rcx=00007ff78b2df340
rdx=0000000000000000 rsi=0000000000000000 rdi=0000000000000000
rip=00007ffc0d5d7034 rsp=000000000018fe28 rbp=0000000000000000
 r8=0000000000000000  r9=0000000000000000 r10=0000000000000000
r11=0000000000000000 r12=0000000000000000 r13=0000000000000000
r14=0000000000000000 r15=0000000000000000
iopl=0         nv up ei pl zr na po nc
ntdll!DbgBreakPoint:
00007ffc`0d5d7034 cc              int     3

Setting Breakpoints

Types of Breakpoints

graph TD
    A[Breakpoints] --> B[Software Breakpoints]
    A --> C[Hardware Breakpoints]
    A --> D[Conditional Breakpoints]
    
    B --> E[bp - Function entry]
    B --> F[ba - Memory access]
    
    C --> G[Limited quantity - 4 max]
    C --> H[ba with /h flag]
    
    D --> I[Break only when condition true]
    D --> J[.if statements]
Loading

Breakpoint Examples

# Set breakpoint at function
bp notepad!WinMain

# Set breakpoint with condition
bp notepad!SaveFile "j (@rcx != 0) ''; 'gc'"

# Set hardware breakpoint on memory access
ba r4 0x00401000

# List all breakpoints
bl

# Clear breakpoint
bc 0

Practical Exercise: Debugging a Simple Application

Create Test Application

  1. Open Notepad
  2. Type some text
  3. Attach WinDbg to notepad process
  4. Set breakpoint: bp user32!MessageBoxW
  5. In Notepad: File → Exit (without saving)
  6. Observe breakpoint hit when save dialog appears

6. Working with Crash Dumps

Understanding Dump Files

Dump File Types

Type Size Contains Use Case
Mini Dump Small (KB-MB) Stack, basic info Initial triage
Heap Dump Medium (MB-GB) + Heap memory Memory leak analysis
Full Dump Large (GB) Complete memory Comprehensive analysis
Kernel Dump Variable Kernel memory System crash analysis

Generating Dump Files

Manual Methods
Method Tool Command
Task Manager Built-in Right-click process → Create dump file
Process Explorer Sysinternals Right-click process → Create Dump → Mini/Full
WinDbg Debugger .dump /ma c:\dumps\myapp.dmp
Automatic Methods
Windows Error Reporting (WER) Configuration:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\Windows Error Reporting\LocalDumps

Values:
- DumpFolder: REG_EXPAND_SZ (default: %LOCALAPPDATA%\CrashDumps)
- DumpCount: REG_DWORD (default: 10)
- DumpType: REG_DWORD (0=Custom, 1=Mini, 2=Full)

Opening and Analyzing Dumps

Loading a Dump File

  1. File Menu Method

    File → Open Crash Dump → Select .dmp file
    
  2. Command Line Method

    windbg -z c:\dumps\application.dmp
    

Initial Analysis Commands

# Analyze crash automatically
!analyze -v

# Show loaded modules
lm

# Display exception information
.exr -1

# Show call stack
k

# Show thread information
~*k

Example Dump Analysis

Sample Crash Analysis Output

0:000> !analyze -v
*******************************************************************************
*                                                                             *
*                        Exception Analysis                                   *
*                                                                             *
*******************************************************************************

APPLICATION_FAULT_c0000005_ACCESS_VIOLATION

FAULTING_IP: 
myapp!ProcessData+0x15
00401015 8b08            mov     ecx,dword ptr [eax]

EXCEPTION_RECORD:  ffffffff -- (.exr 0xffffffffffffffff)
ExceptionAddress: 00401015 (myapp!ProcessData+0x0000000000000015)
   ExceptionCode: c0000005 (Access violation)
  ExceptionFlags: 00000000
NumberParameters: 2
   Parameter[0]: 00000000
   Parameter[1]: 00000000

FAULTING_THREAD:  00000000

PROCESS_NAME:  myapp.exe

ERROR_CODE: (NTSTATUS) 0xc0000005 - The instruction at 0x%p referenced memory at 0x%p. The memory could not be %s.

EXCEPTION_CODE: (NTSTATUS) 0xc0000005 - The instruction at 0x%p referenced memory at 0x%p. The memory could not be %s.

Analyzing the Results

Field Meaning Action
FAULTING_IP Instruction that caused crash Examine source code at this location
ExceptionCode Type of exception c0000005 = Access Violation
FAULTING_THREAD Thread that crashed Focus debugging on this thread

Common Crash Patterns

Access Violations (0xc0000005)

graph TD
    A[Access Violation] --> B[Read from NULL pointer]
    A --> C[Write to NULL pointer]
    A --> D[Buffer overflow]
    A --> E[Use after free]
    A --> F[Stack corruption]
Loading

Debugging Approach for Each Pattern

Pattern Investigation Commands What to Look For
NULL Pointer r, u @rip, dv Register values, local variables
Buffer Overflow db @rsp, !heap -p -a Stack contents, heap metadata
Use After Free !heap -p -a @rax, !gflag Heap block status, page heap

7. Essential Commands

Basic Information Commands

System and Process Information

Command Purpose Example Output
vertarget Show target information Target machine: Local machine
version WinDbg version Version 10.0.22621.2428
!peb Process Environment Block PEB at 000000000038f000
!teb Thread Environment Block TEB at 00000000003a0000

Module and Symbol Commands

# List all modules
lm

# List modules with details
lmf

# Show module information
lmvm ntdll

# Reload symbols
.reload

# Check symbol status
!sym noisy

Memory Examination Commands

Memory Display Commands

Command Purpose Format
d Display memory Various formats
db Display bytes Hexadecimal bytes
dw Display words 16-bit words
dd Display dwords 32-bit dwords
dq Display qwords 64-bit qwords
da Display ASCII String format
du Display Unicode Wide string format

Memory Examples

# Display memory as bytes
0:000> db 0x401000 L20
00401000  4d 5a 90 00 03 00 00 00-04 00 00 00 ff ff 00 00  MZ..............
00401010  b8 00 00 00 00 00 00 00-40 00 00 00 00 00 00 00  ........@.......

# Display as ASCII string
0:000> da 0x402000
00402000  "Hello World!"

# Display as Unicode string
0:000> du 0x403000
00403000  "Hello World!"

Stack and Call Analysis

Call Stack Commands

Command Purpose Usage
k Show call stack k
kb Stack with parameters kb
kv Verbose stack kv
kp Stack with source kp

Example Call Stack

0:000> kb
 # ChildEBP RetAddr  Args to Child              
00 0018fe00 004010b2 00000001 00322a70 00323b88 myapp!CrashFunction+0x15
01 0018fe20 00401134 00000001 00322a70 00323b88 myapp!ProcessData+0x42
02 0018fe40 004011a8 00000001 00322a70 00323b88 myapp!MainLoop+0x24
03 0018ff80 0040128d 00400000 00000000 00322a48 myapp!WinMain+0x98
04 0018ffc0 7c817067 00000000 00000000 7ffdf000 myapp!__mainCRTStartup+0x12d
05 0018fff0 00000000 004011f6 00000000 78746341 kernel32!BaseProcessStart+0x23

Thread Analysis Commands

Multi-Threading Commands

Command Purpose Description
~ List threads Show all threads
~0s Switch to thread 0 Change current thread
~*k Stack for all threads Show all call stacks
~*r Registers for all threads Show all registers

Thread States

0:000> ~
   0  Id: 1234.5678 Suspend: 1 Teb: 7ffdf000 Unfrozen
.  1  Id: 1234.90ab Suspend: 1 Teb: 7ffde000 Unfrozen
   2  Id: 1234.cdef Suspend: 1 Teb: 7ffdd000 Unfrozen

Register and CPU Commands

Register Commands

Command Purpose Example
r Show registers Display all registers
r eax Show specific register Display EAX value
r eax=0 Set register value Set EAX to 0

Example Register Display

0:000> r
rax=0000000000000000 rbx=0000000000401000 rcx=0000000000000001
rdx=0000000000000000 rsi=0000000000000000 rdi=0000000000322a70
rip=0000000000401015 rsp=000000000018fe00 rbp=000000000018fe20
 r8=0000000000000000  r9=0000000000000000 r10=0000000000000000
r11=0000000000000246 r12=0000000000000000 r13=0000000000000000
r14=0000000000000000 r15=0000000000000000
iopl=0         nv up ei pl zr na pe nc
cs=0023  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00000246
myapp!CrashFunction+0x15:
00401015 8b08            mov     ecx,dword ptr [rax] ds:002b:00000000=????????

8. Practical Debugging Scenarios

Scenario 1: Application Crash Investigation

Problem Description

An application crashes intermittently with an access violation. We have a crash dump to analyze.

Investigation Steps

  1. Load the dump and perform initial analysis
windbg -z c:\dumps\myapp_crash.dmp

0:000> !analyze -v
  1. Examine the faulting instruction
0:000> u @rip
myapp!ProcessBuffer+0x15:
00401015 8b08            mov     ecx,dword ptr [rax]  ; <-- Crash here
00401017 83c008          add     eax,8
0040101a 3bc7            cmp     eax,edi
0040101c 7c f7           jl      myapp!ProcessBuffer+0x10 (00401015)
  1. Check register values
0:000> r
rax=0000000000000000  ; <-- NULL pointer!
rcx=0000000000000001
  1. Examine function parameters
0:000> dv
         buffer = 0x00000000  ; NULL buffer passed to function
          size = 0n100

Root Cause Analysis

Evidence Conclusion
RAX = 0 NULL pointer dereference
Faulting instruction reads from [rax] Attempt to read from address 0
Function parameter shows buffer = NULL Caller passed invalid parameter

Resolution Steps

  1. Trace back to caller
0:000> kb
00 myapp!ProcessBuffer+0x15
01 myapp!HandleRequest+0x42    ; <-- Check this function
02 myapp!MainLoop+0x24
  1. Examine caller function
0:000> u myapp!HandleRequest+0x30 L10
# Look for buffer allocation/validation

Scenario 2: Memory Leak Detection

Problem Description

Application memory usage grows continuously over time. Need to identify the leak source.

Detection Method

  1. Enable heap tracking
gflags -i myapp.exe +hpa
  1. Attach debugger and run application
windbg myapp.exe
0:000> g
  1. Take heap snapshots
# Initial snapshot
0:000> !heap -s

# After some operations
0:000> !heap -s

Heap Analysis Commands

Command Purpose Information Provided
!heap -s Heap summary Total heap usage per heap
!heap -stat -h 0 Heap statistics Allocation sizes and counts
!heap -flt s 1000 Filter by size Find allocations ≥ 1000 bytes
!heap -p -a <addr> Allocation details Stack trace of allocation

Example Output Analysis

0:000> !heap -stat -h 0
 heap @ 00150000
group-by: TOTSIZE max-display: 20
    size     #blocks     total     ( %) (percent of total busy bytes)
    1000 -      1       1000  (  1.00)
    800  -      2       1600  (  1.60)
    400  -     50      20000  ( 20.00)  <-- Suspicious!
    100  -    100      10000  ( 10.00)

The 400-byte allocations show 50 blocks, which might indicate a leak pattern.

Scenario 3: Deadlock Investigation

Problem Description

Multi-threaded application hangs periodically. Suspected deadlock between threads.

Investigation Approach

  1. Examine all threads
0:000> ~*k
   0  Id: 1234.5678 Suspend: 1 Teb: 7ffdf000 Unfrozen
      Child-SP          RetAddr           Call Site
      0018fe00          77f5d5a0          ntdll!NtWaitForSingleObject+0x15
      0018fe20          004010b2          kernel32!WaitForSingleObjectEx+0x43
      0018fe40          00401134          myapp!WaitForResource+0x22
      
   1  Id: 1234.90ab Suspend: 1 Teb: 7ffde000 Unfrozen
      Child-SP          RetAddr           Call Site
      0018ee00          77f5d5a0          ntdll!NtWaitForSingleObject+0x15
      0018ee20          004010b2          kernel32!WaitForSingleObjectEx+0x43
      0018ee40          00401134          myapp!WaitForResource+0x22
  1. Analyze synchronization objects
0:000> !locks
CritSec ntdll!LdrpLoaderLock+0 at 77f5f000
WaiterWoken        No
LockCount          2
RecursionCount     1
OwningThread       90ab    <-- Thread 1 owns
EntryCount         0
ContentionCount    1
*** Locked

Deadlock Detection Table

Thread Owns Wants Status
0 (5678) Lock B Lock A Waiting
1 (90ab) Lock A Lock B Waiting

This shows a classic deadlock: Thread 0 owns B and wants A, while Thread 1 owns A and wants B.

Scenario 4: Performance Bottleneck Analysis

Problem Description

Application runs slowly during certain operations. Need to identify performance bottlenecks.

Profiling Approach

  1. Use sampling profiler
# Take multiple samples during slow operation
0:000> ~*k
# Repeat several times to identify common patterns
  1. Analyze CPU usage patterns
# Look for functions appearing frequently in samples
Common functions in samples:
- myapp!SlowFunction+0x15    (40% of samples)
- ntdll!RtlAllocateHeap+0x23 (25% of samples)
- myapp!StringCompare+0x8    (20% of samples)

Performance Issues Identification

Issue Type Symptoms Investigation Commands
CPU Bound High CPU, slow response Sampling profiler, hot functions
I/O Bound Low CPU, waiting threads Thread states, wait analysis
Memory Bound High memory usage Heap analysis, allocation patterns
Lock Contention Multiple waiting threads Lock analysis, synchronization

9. Advanced Features

Extension Commands

Common Extensions

Extension Purpose Key Commands
!analyze Automated crash analysis !analyze -v
!heap Heap debugging !heap -s, !heap -stat
!locks Lock analysis !locks, !cs
!handle Handle debugging !handle, !htrace

Custom Extensions

WinDbg supports loading custom extensions:

# Load extension
.load c:\extensions\myext.dll

# Use extension command
!myext.analyze

# List available extensions
.chain

Scripting and Automation

JavaScript Scripting

WinDbg supports JavaScript for automation:

// Example: Find all modules with specific pattern
"use strict";

function findModulesWithPattern(pattern) {
    let modules = host.currentSession.Processes.First()
                      .Modules
                      .Where(m => m.Name.includes(pattern));
    
    for (let module of modules) {
        host.diagnostics.debugLog(
            `Found: ${module.Name} at ${module.BaseAddress.toString(16)}\n`
        );
    }
}

// Usage: dx @$scriptContents.findModulesWithPattern("kernel")

Batch Commands

Create command files for repetitive tasks:

$ Crash analysis script
!analyze -v
lm
~*k
!heap -s
.logclose

Save as analyze_crash.txt and run with:

$$><c:\scripts\analyze_crash.txt

Data Model Integration

Using dx Command

The dx command provides access to the debugger data model:

# Show process information
dx @$curprocess

# Show all threads
dx @$curprocess.Threads

# Show modules
dx @$curprocess.Modules

# Query specific data
dx @$curprocess.Threads.Where(t => t.Id == 0x1234)

Advanced Data Queries

Query Type Example Purpose
Filter threads dx @$curprocess.Threads.Where(t => t.State == "Waiting") Find waiting threads
Module analysis dx @$curprocess.Modules.OrderByDescending(m => m.Size) Largest modules first
Stack analysis dx @$curthread.Stack.Frames.Select(f => f.ToDisplayString()) Get stack as strings

Time Travel Debugging (TTD)

What is TTD?

Time Travel Debugging allows you to record execution and replay it backwards and forwards.

graph LR
    A[Program Start] --> B[Record Execution]
    B --> C[Crash/Issue]
    C --> D[Replay Backwards]
    D --> E[Find Root Cause]
    E --> F[Step Forward/Back]
Loading

TTD Commands

Command Purpose Example
!tt.start Start recording !tt.start c:\traces\myapp.run
!tt.stop Stop recording !tt.stop
!position Show current position !position
g- Go backwards g-
p- Step backwards p-

TTD Practical Example

# Start recording
0:000> !tt.start c:\traces\crash_analysis.run
Recording started

# Run until crash
0:000> g
(Application crashes)

# Go back in time
0:000> g- @$curthread.Stack.Frames[1].InstructionOffset

# Step through the problem area
0:000> p
0:000> p-

Advanced Memory Analysis

Page Heap Debugging

Enable advanced heap debugging:

# Enable page heap for application
gflags -i myapp.exe +hpa +htc +hfc

# Full page heap (slower but more thorough)
gflags -i myapp.exe +full

Memory Pool Analysis

For kernel debugging:

# Show pool usage
!poolused

# Find pool tag
!poolfind 'MyTg'

# Analyze pool corruption
!pool <address>

Virtual Memory Analysis

Command Purpose Usage
!vadump Virtual address dump Kernel mode only
!vm Virtual memory stats !vm
!vprot Memory protection !vprot <address>

10. Troubleshooting Common Issues

Symbol Loading Problems

Common Symbol Issues

Problem Symptoms Solution
No symbols loaded Function names show as addresses Configure symbol path
Wrong symbol version Mismatched function offsets Update symbols
Symbol path issues Cannot download symbols Check network/proxy
Private symbols missing Limited debugging info Use correct PDB files

Symbol Troubleshooting Steps

  1. Check symbol path
0:000> .sympath
Symbol search path is: srv*c:\symbols*https://msdl.microsoft.com/download/symbols
  1. Enable symbol loading diagnostics
0:000> !sym noisy
0:000> .reload /f
  1. Verify symbol loading
0:000> lmv m myapp
start    end        module name
00400000 0040f000   myapp    (pdb symbols)  c:\symbols\myapp.pdb\{GUID}\myapp.pdb
    Loaded symbol image file: myapp.exe
    Mapped memory image file: c:\symbols\myapp.exe\{GUID}\myapp.exe
    Image path: myapp.exe
    Image name: myapp.exe
    Timestamp:        Fri Oct 13 14:30:45 2023
    CheckSum:         0000A23B
    ImageSize:        0000F000
    Translations:     0000.04b0 0000.04e4 0409.04b0 0409.04e4

Debugger Connection Issues

Local Debugging Problems

Issue Cause Solution
Access denied Insufficient privileges Run as Administrator
Process not found Incorrect process name/ID Use Task Manager to verify
Debugger hangs Target process issues Use non-invasive attach

Remote Debugging Setup

# On target machine (run as Administrator)
dbgsrv -t tcp:port=1234

# On debugging machine
windbg -remote tcp:server=192.168.1.100,port=1234

Performance Issues

Slow Symbol Loading

# Use local symbol cache
_NT_SYMBOL_PATH=cache*c:\localsyms;srv*c:\symbols*https://msdl.microsoft.com/download/symbols

# Preload symbols
.reload /f

Large Dump File Analysis

Dump Size Recommended Actions
< 100MB Load normally
100MB - 1GB Use mini dump if possible
> 1GB Consider kernel dump analysis tools

Common Error Messages

Error Resolution Guide

Error Meaning Resolution
Symbol file could not be found Missing or wrong symbols Check symbol path and version
Unable to read memory Invalid memory address Verify address is accessible
Access violation reading location Reading protected memory Check memory permissions
Debuggee not connected Lost connection to target Reconnect or restart debugging

Advanced Error Diagnosis

# Check last error
0:000> !error

# Get detailed error information
0:000> .lastevent

# Check debugger internal state
0:000> .dbgdbg

11. Resources and Next Steps

Essential References

Microsoft Documentation

Resource URL Content
WinDbg Documentation docs.microsoft.com/en-us/windows-hardware/drivers/debugger/ Official reference
Debugging Tools docs.microsoft.com/en-us/windows-hardware/drivers/debugger/getting-started Getting started guide
Symbol Files docs.microsoft.com/en-us/windows/win32/debug/symbol-files Symbol file information

Community Resources

┌─────────────────────────────────────────┐
│            Learning Path                │
├─────────────────────────────────────────┤
│ 1. Master basic commands               │
│ 2. Practice with simple applications   │
│ 3. Analyze real crash dumps           │
│ 4. Learn extension commands           │
│ 5. Explore advanced features          │
│ 6. Contribute to community            │
└─────────────────────────────────────────┘

Recommended Learning Exercises

Beginner Exercises

  1. Basic Process Debugging

    • Attach to Notepad
    • Set breakpoints in user32.dll functions
    • Examine call stacks and memory
  2. Crash Dump Analysis

    • Create intentional crashes
    • Generate dumps
    • Analyze with !analyze -v
  3. Memory Investigation

    • Examine heap allocations
    • Track memory usage patterns
    • Practice memory display commands

Intermediate Exercises

  1. Multi-threaded Debugging

    • Debug applications with multiple threads
    • Investigate thread synchronization
    • Analyze deadlock scenarios
  2. Extension Usage

    • Master heap analysis commands
    • Use handle debugging extensions
    • Practice lock analysis
  3. Scripting

    • Write simple JavaScript automation
    • Create command batch files
    • Use data model queries

Advanced Exercises

  1. Kernel Debugging

    • Set up kernel debugging environment
    • Analyze driver issues
    • Investigate system crashes
  2. Time Travel Debugging

    • Record and replay execution
    • Navigate backwards through time
    • Find root causes of intermittent issues
  3. Custom Extensions

    • Write simple debugger extensions
    • Integrate with existing tools
    • Contribute to open source projects

Building Your Debugging Toolkit

Essential Tools Combination

Phase Primary Tool Supporting Tools
Initial Investigation WinDbg Process Explorer, Process Monitor
Memory Analysis WinDbg + !heap Application Verifier, VMMap
Performance WinDbg + Sampling Performance Toolkit, ETW
Automation WinDbg Scripts PowerShell, Batch files

Setting Up Your Environment

Recommended Directory Structure:
C:\Debugging\
├── Symbols\          (Symbol cache)
├── Dumps\            (Crash dumps)
├── Scripts\          (Automation scripts)
├── Extensions\       (Custom extensions)
├── Logs\            (Debug session logs)
└── Tools\           (Additional utilities)

Professional Development

Certification and Training

Level Focus Area Recommended Path
Beginner Application debugging Microsoft Learn modules
Intermediate System debugging Windows Internals training
Advanced Kernel/driver debugging WDF/WDM driver courses
Expert Tool development Debugger extension development

Community Involvement

  • Forums: Microsoft Developer Community, Stack Overflow
  • Blogs: Follow debugging experts and Microsoft teams
  • Conferences: WinHEC, Microsoft Build, local user groups
  • Open Source: Contribute to debugging tools and extensions

Quick Reference Card

Most Used Commands

Essential Commands Quick Reference:

Process Control:
g       - Go/Continue
p       - Step over  
t       - Step into
gu      - Step out
q       - Quit

Information:
k       - Call stack
r       - Registers
lm      - List modules
~       - List threads
!analyze -v - Analyze crash

Memory:
dd <addr>   - Display memory (dwords)
db <addr>   - Display memory (bytes) 
da <addr>   - Display ASCII string
s <range>   - Search memory

Breakpoints:
bp <addr>   - Set breakpoint
bl          - List breakpoints
bc <id>     - Clear breakpoint
ba <type>   - Hardware breakpoint

Advanced:
!heap -s    - Heap summary
!locks      - Lock analysis
.dump       - Create dump file
dx          - Data model queries

Troubleshooting Checklist

Pre-Debugging Checklist

  • WinDbg running as Administrator
  • Symbol path configured correctly
  • Network connectivity for symbol downloads
  • Sufficient disk space for symbols and dumps
  • Target application has debug information

During Debugging Checklist

  • Symbols loaded successfully
  • Initial analysis completed (!analyze -v)
  • Call stack examined (k command)
  • Register state checked (r command)
  • Memory around crash location examined

Post-Debugging Checklist

  • Root cause identified
  • Reproduction steps documented
  • Fix verified
  • Debug session logged for future reference
  • Knowledge shared with team

Conclusion

This tutorial has provided a comprehensive introduction to WinDbg for entry-level users. You've learned:

  • Fundamental concepts of debugging and WinDbg's capabilities
  • Practical skills for analyzing crashes, memory issues, and performance problems
  • Advanced techniques including scripting, extensions, and time travel debugging
  • Troubleshooting strategies for common debugging challenges

Next Steps

  1. Practice regularly with real applications and crash dumps
  2. Join the community and learn from experienced debuggers
  3. Expand your knowledge into specialized areas like kernel debugging
  4. Share your learning by helping others and contributing to the community

Remember: Debugging is both an art and a science. The more you practice with WinDbg, the more intuitive and powerful it becomes. Start with simple scenarios and gradually work your way up to more complex debugging challenges.