Search code examples
visual-studiovsixenvdtevs-extensibility

How can I programmatically examine the stack in my Visual Studio extension?


In a VS extension, assume that the code has just hit a breakpoint, and is in break mode. How can I programmatically examine the stack? Also, is there a way to figure out what the last executed statement was?

I haven't been able to find an advanced sample. There are hello-world type samples but they are mostly focused on adding/modifying UI elements in Visual Studio IDE.


Solution

  • You'll need to hook into the EnvDTE.Events.DebuggerEvents.OnEnterBreakMode event or equivalent to know when the process stops (and thus has a callstack). Be careful to keep a reference to EnvDTE.Events.DebuggerEvents otherwise it can be garbage collected and the connection to your event handler lost (normally this can't happen in C# but because of the way the EnvDTE event COM wrappers are implemented this is a known issue).

    Once the debugger is in break mode, you can iterate EnvDte.Debugger.CurrentThread.StackFrames like so:

    foreach (var frame in dte.Debugger.CurrentThread.StackFrames.Cast<EnvDTE.StackFrame>())
        ...
    

    If you wish to modify the current thread/stack or get more details than EnvDTE exposes, this is also possible but non-trivial. There is a COM interface called IDebuggerInternal that exposes these things directly, but it's not exported from the public MS DLLs. However, since it's a COM interface, you can re-declare it in C# and cast the SVsShellDebugger instance to it. If you want to go down this route I suggest disassembling Microsoft.VisualStudio.Debugger.Interop.Internal, Version=11.0.0.0 (e.g. with dotPeek) to get the interface definition and GUID.