7

I'm using Python to control GDB via batch commands. Here's how I'm calling GDB:

$ gdb --batch --command=cmd.gdb myprogram

The cmd.gdb listing just contains the line calling the Python script

source cmd.py

And the cmd.py script tries to create a breakpoint and attached command list

bp = gdb.Breakpoint("myFunc()") # break at function in myprogram
gdb.execute("commands " + str(bp.number))
# then what? I'd like to at least execute a "continue" on reaching breakpoint...  
gdb.execute("run")

The problem is I'm at a loss as to how to attach any GDB commands to the breakpoint from the Python script. Is there a way to do this, or am I missing some much easier and more obvious facility for automatically executing breakpoint-specific commands?

user2601195
  • 161
  • 2
  • 9

2 Answers2

5

def stop from GDB 7.7.1 can be used:

gdb.execute('file a.out', to_string=True)
class MyBreakpoint(gdb.Breakpoint):
    def stop (self):
        gdb.write('MyBreakpoint\n')
        # Continue automatically.
        return False
        # Actually stop.
        return True
MyBreakpoint('main')
gdb.execute('run')

Documented at: https://sourceware.org/gdb/onlinedocs/gdb/Breakpoints-In-Python.html#Breakpoints-In-Python

See also: How to script gdb (with python)? Example add breakpoints, run, what breakpoint did we hit?

Community
  • 1
  • 1
Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
1

I think this is probably a better way to do it rather than using GDB's "command list" facility.

bp1 = gdb.Breakpoint("myFunc()")

# Define handler routines
def stopHandler(stopEvent):
    for b in stopEvent.breakpoints:
        if b == bp1:
            print "myFunc() breakpoint"
        else:
            print "Unknown breakpoint"
    gdb.execute("continue")

# Register event handlers
gdb.events.stop.connect (stopHandler)

gdb.execute("run")

You could probably also subclass gdb.Breakpoint to add a "handle" routine instead of doing the equality check inside the loop.

user2601195
  • 161
  • 2
  • 9
  • Just a hint. The above method has a drawback: if call gdb.execute("continue") in stopHandler() directly, it will cause python.recursive error in some circumstance. – cq674350529 Jan 14 '20 at 08:35
  • @cq674350529 Can you explain more what is the problem? – MicrosoctCprog Jan 22 '21 at 07:22
  • @MicrosoctCprog The initial problem is that I can't execute multiple gdb cmds after running "commands xxx" in a raw shell way. But by inheriting `gdb.Breakpoint`, it's trivial to do that, and also solve another issues. Also, I concluded three common ways related to this: https://cq674350529.github.io/2020/05/09/%E6%8A%80%E5%B7%A7misc/ (only Chinese version, google translation maybe helpful. ) – cq674350529 Jan 25 '21 at 02:11