8

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?

2 Answers 2

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?

Sign up to request clarification or add additional context in comments.

Comments

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.

3 Comments

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 Can you explain more what is the problem?
@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: cq674350529.github.io/2020/05/09/%E6%8A%80%E5%B7%A7misc (only Chinese version, google translation maybe helpful. )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.