Scripting WinDbg with PowerShell

A while back, Roberto Farah published a script library to help control WinDbg through PowerShell. I’ve been using WinDbg for more debugging lately, and decided (after following one to many object references by hand) that I needed to script my investigations.


PowerDbg is definitely helpful – Roberto has tons of great scripts published that help analyze all kinds of interesting data. It also made me think of an alternative approach that works around some of the problem areas – PowerDbg uses SendKeys, window focusing, and used WinDbg logging as the communication mechanism. After some investigation, I thought that automation of the command-line version (cdb.exe) through its input and output streams might be easier and more efficient – which indeed it was.


You set up a remote from the Windbg instance you want to control, and then the WinDbg module (below) connects to the remote session (by manipulating standard in / standard out of cdb.exe) to manage its output.



Windows PowerShell V2
Copyright (C) 2008 Microsoft Corporation. All rights reserved.
PS C:\Users\leeholm> Import-Module Windbg
PS C:\Users\leeholm> Connect-Windbg "tcp:Port=10456,Server=SERVER"
PS C:\Users\leeholm> Invoke-WindbgCommand .symfix
PS C:\Users\leeholm> Invoke-WindbgCommand .reload
0:009> Reloading current modules
................................................................
...........
PS C:\Users\leeholm> Invoke-WindbgCommand k
0:009> ChildEBP RetAddr
0460fbe8 76ebd0d0 ntdll!DbgBreakPoint [d:\foo.c @ 206]
0460fc18 76fc4911 ntdll!DbgUiRemoteBreakin+0x3c [d:\bar.c @ 298]
0460fc24 76e6e4b6 kernel32!BaseThreadInitThunk+0xe [d:\baz.c @ 66]
0460fc64 76e6e489 ntdll!__RtlUserThreadStart+0x23 [d:\bing.c @ 2740]
0460fc7c 00000000 ntdll!_RtlUserThreadStart+0x1b [d:\bing.c @ 2672]
PS C:\Users\leeholm>


Here’s an example function to demonstrate its use:









001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054

################################################################################
##
## Resolve-PsInvocationInfo.ps1
## Resolves the command and script information from an active PowerShell
## process
##
################################################################################
Import-Module windbg
Connect-Windbg "tcp:Port=10456,Server=SERVER"

function Resolve-Member($address, $member)
{
    $output = Invoke-WindbgCommand !dumpobj $address
   
    if(-not $member)
    {
        $output
    }
    else
    {
        $currentMember = ($member -split "\.")[0]
        $remaining = $member.Remove(0, $currentMember.Length).TrimStart('.')
       
        Write-Verbose "Looking for $currentMember on $address"
       
        $output = $output | 
            Select-String ("(instance|shared).*$currentMember" + '$') |
            Select-String -NotMatch 00000000

        if($output)
        {
            $columns = -split $output
            $address = $columns[6]
           
            Resolve-Member $address $remaining
        }
        else
        {
            Write-Error "Could not resolve $currentMember on $address"
        }
    }
}

$null = Invoke-WindbgCommand .loadby sos mscorwks
$output = Invoke-WindbgCommand ("!dumpheap -type " +
    "System.Management.Automation.InvocationInfo -short")
foreach($line in $output)
{
    Resolve-Member $line commandInfo.name
    Resolve-Member $line scriptToken._script
    Resolve-Member $line scriptToken._line
}

Disconnect-Windbg

And the module itself (WinDbg.psm1, place in a “WinDbg” folder in your modules folder):


(Edit: 05/13/09 - Updated to support local kernel debugging)









001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148

################################################################################
##
## WinDbg.psm1
## Automate WinDbg with PowerShell scripting
##
## To use:
## In WinDbg, set up a server: .server tcp:Port=10456
##
## In PowerShell
##
## Import-Module windbg
## Connect-Windbg -remote "tcp:Port=10456,Server=<server>"
## Other remote connection strings / protocols work, too.
##
## For local kernel debugging:
##
## Import-Module Windbg -ArgumentList 'C:\<path>\kd.exe'
## Connect-Windbg -ArgumentList "-kl"
## Invoke-WindbgCommand "!process"
##
## Cleaning up:
## Disconnect-Windbg
##
################################################################################

param($cdbPath = "C:\Program Files\Debugging Tools for Windows\cdb.exe")

$SCRIPT:windbgProcess = $null
$SCRIPT:currentConnection = $null

## Connect to a windbg remote session
function Connect-Windbg
{
    param(
        [Parameter(ParameterSetName = "Remote", Mandatory = $true)]
        $remote,

        [Parameter(ParameterSetName = "ArgumentList", Mandatory = $true)]
        $argumentList
        
        )
        
    if($SCRIPT:currentConnection -and ($SCRIPT:currentConnection -ne $remote))
    {
        throw "Already connected to $remote. Use Disconnect-Windbg, " + 
            "then connect to another instance."
    }
    
    ## Launch cdb.exe, the command-line version of WinDbg.
    ## Take control of its input and output streams, which we'll use
    ## to capture commands and their output.
    if(-not $SCRIPT:currentConnection)
    {
        $processStartInfo = New-Object System.Diagnostics.ProcessStartInfo
        $processStartInfo.FileName = $cdbPath
        $processStartInfo.WorkingDirectory = (Get-Location).Path

        if($remote)
        {
                $processStartInfo.Arguments = "-remote $remote"
        }
        else
        {
                $processStartInfo.Arguments = $argumentList
        }
        
        $processStartInfo.UseShellExecute = $false
        $processStartInfo.RedirectStandardInput = $true
        $processStartInfo.RedirectStandardOutput = $true 

        $SCRIPT:windbgProcess = 
            [System.Diagnostics.Process]::Start($processStartInfo)
        $SCRIPT:currentConnection = $remote

        if(-not $SCRIPT:windbgProcess)
        {
            return
        }
        
        ## Ignore the stuff that was in the session before we
        ## connected
        $null = Receive-WindbgOutput
    }
}

## Disconnect from the session
function Disconnect-Windbg
{
    if($SCRIPT:windbgProcess -and (-not $SCRIPT:windbgProcess.HasExited))
    {
        $SCRIPT:windbgProcess.StandardOutput.Close()
        $SCRIPT:windbgProcess.StandardInput.Close()
        $SCRIPT:windbgProcess.Kill()
    }
    
    $SCRIPT:currentConnection = $null
    $SCRIPT:windbgProcess = $null
}

## Invoke a command in the connected WinDbg session, and return
## its output
function Invoke-WindbgCommand
{
    if(-not $SCRIPT:windbgProcess)
    {
        throw "Not connected. Use Connect-Windbg to connect to an " +
            "instance of WinDbg."
    }
    
    $SCRIPT:windbgProcess.StandardInput.WriteLine("$args")
    Receive-WindbgOutput
}

## Retrieve pending output from the connected WinDbg session
function Receive-WindbgOutput
{
    ## Add a special tag so that we know the end of the command
    ## response
    $sent = "PSWINDBG_COMPLETE_{0:o}" -f [DateTime]::Now        
    $SCRIPT:windbgProcess.StandardInput.WriteLine(".echo $sent")
    
    $received = New-Object System.Text.StringBuilder

    ## Wait for the response to end
    while($received.ToString().IndexOf($sent) -lt 0)
    {
        $null = $SCRIPT:windbgProcess.StandardOutput.EndOfStream
        while($SCRIPT:windbgProcess.StandardOutput.Peek() -ge 0)
        {
            $null = $received.Append(
                $SCRIPT:windbgProcess.StandardOutput.Read(), 1)
        }
    }
    
    ## Split it into lines, and return everything but the new
    ## prompt, and the "end response" tag
    $output = $received.ToString().Split("`r`n")
    if($output.Length -gt 2)
    {
        $output[0..($output.Length - 3)]
    }
}

Export-ModuleMember -Function Connect-Windbg
Export-ModuleMember -Function Disconnect-Windbg
Export-ModuleMember -Function Invoke-WindbgCommand

$MyInvocation.MyCommand.ScriptBlock.Module.OnRemove = { Disconnect-Windbg }

Printed from: http://www.leeholmes.com/blog/2009/01/21/scripting-windbg-with-powershell/ .
© Lee Holmes 2010.

5 Comments   »

RSS feed for comments on this post , TrackBack URI

Leave a Reply