Your New Jekyll Site

home

Self debugging code with the .ocommand

30 Nov 2011

Have you ever found yourself debugging the same piece of code over and over again, repeating the same commands, and sometimes wishing there was a way to guide the debugger.

In the debugger you are able to set advanced breakpoints based on some condition or state. Often, you have to inspect the callstack or memory in order to find the right spot to put a break point in. This can be quite time consuming and hard. It is probably easier to create those conditional breakpoints in the code itself.

What you can do is insert code that tells the debugger what to do from inside your application. These are sent with debug traces, or OutputDebug as it is called in win32.

The following piece of .Net code tells the debugger to load the SOS extension, open a log file, and save the callstack, when the program exits the logfile is closed.

static void Main(string[] args)
{
    Action DebugCommand = 
        (s) => System.Diagnostics.Debug.WriteLine("DbgCmd " + s);
    DebugCommand(".loadby sos clr;g");
    DebugCommand(".logopen /t "c:\temp\log.txt";g");
    for(int i=0;i<1000;i++)
    {
        System.Console.WriteLine(i);
        if (i % 100 == 0)
        {
            DebugCommand("!ClrStack;g");
        }
    }
    DebugCommand("!threads;");
    DebugCommand(".logclose;");
}

The code uses a DebugCommand delegate, that prefixes the strings with “DbgCmd “, so that the prefix doesn’t need to be added everywhere you use it.

But in order for this to work, we will also have to tell the debugger to expect commands from the target. We do that with the .ocommand. That command take a string as parameter. The string serves as a prefix marker, so that the debugger can identify commands that are coming.

Image of windbg Then after starting the application with “g”, it just works.

Image of windbg