gdbgdb-python

Programatically detect what breakpoint was reached with GDB


I have a script which debugs my application and it does set 2 breakpoints. If I would be debugging it manually I would be able to see which one got triggered. But doing it in an automatic manner, I don't know which breakpoint was reached, is there a way to write if conditions or something to detect which one was reached?

If this feature is not possible with vanilla gdb but only with python gdb I would be happy to switch/upgrade the process.

Edit: With Tom's help I can have

break main
commands
  set $gdb_breakpoint=1
end

break main.cpp:4053
commands
  set $gdb_breakpoint=2
end

break fault_handler.cpp:55
commands
  set $gdb_breakpoint=3
end

break unit_tests_complete
commands
  set $gdb_breakpoint=4
end

And then when the breakpoints got triggered I can check the variable to know where I got halted. In a pure software context this could be easier and maybe multiple breakpoints wouldn't be needed to begin with. This is testing hardware where the fault could happen erratically then this approach should do the trick.


Solution

  • The gdb CLI provides a commands command which can be used to attach other gdb commands to a breakpoint. So for example:

    (gdb) break main
    Breakpoint 1 at 0x40ce90: file ../../binutils-gdb/gdb/gdb.c, line 25.
    (gdb) commands 1
    Type commands for breakpoint(s) 1, one per line.
    End with a line saying just "end".
    >print "hi"
    >end
    

    ... will arrange to print "hi" when the breakpoint is hit.

    If you prefer to use Python, then you can add a listener to the gdb.events.stop event, and look specifically for breakpoint stops.