Search code examples
c++visual-studiodebuggingconditional-breakpoint

Visual studio breakpoint conditional on the stack state


Visual studio can print call stack when breakpoint hit, and can stop when conditions are met, is there any way to combine that and stop when function is called from another selected one, and ignore all other calls?


Solution

  • I believe the only way to do this is with a macro. Right click your breakpoint, choose "When Hit..", select "Run a macro", and point it to a macro that goes something like:

     Sub ContinueUnlessCalledFromRightContext()
        For Each frame As EnvDTE.StackFrame In DTE.Debugger.CurrentThread.StackFrames
            If (frame.FunctionName.Contains("SomeOtherMethodsName") Then Exit Function
        Next
    
        DTE.Debugger.Go() ` we weren't called from the right context so continue execution.
    End Sub
    

    The above is half psuedo code; I didn't actually test it, but should work with some minor edits.

    Note that this will be slow as hell if the breakpoint is hit a lot of times, because running macros from breakpoints is inherently very slow.

    BTW, If you were asking about .NET / C# it would've been a lot simpler, you could've just made a conditional breakpoint on

    new System.Diagnostics.StackTrace().ToString().Contains("SomeOtherMethodsName")
    

    ...and be done with it.