Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a breakpoint on a python function in gdb

I sometime use gdb to debug python scripts (CPython of course). It is useful typically to debug core dumps (and when it involves c extension modules).

A basic question is how to set breakpoint on a python function in gdb. Say I've a python script with function foo and I want to break right after foo is called. I guess setting a conditional breakpoint on PyEval_EvalFrameEx might work, but not sure how to do it.

like image 803
amit Avatar asked Jan 09 '13 14:01

amit


People also ask

How do I set a breakpoint in gdb?

Setting breakpoints A breakpoint is like a stop sign in your code -- whenever gdb gets to a breakpoint it halts execution of your program and allows you to examine it. To set breakpoints, type "break [filename]:[linenumber]".

How do I debug a Python script in gdb?

Without an argument, the python-interactive command can be used to start an interactive Python prompt. To return to GDB, type the EOF character (e.g., Ctrl-D on an empty prompt). The python command can be used to evaluate Python code.

How do you set breakpoints in Python?

It's easy to set a breakpoint in Python code to i.e. inspect the contents of variables at a given line. Add import pdb; pdb. set_trace() at the corresponding line in the Python code and execute it. The execution will stop at the breakpoint.

What is breakpoint () in Python?

Python breakpoint() - Stop Debugging Python sys. breakpointhook() function uses environment variable PYTHONBREAKPOINT to configure the debugger. If unset, the default PDB debugger is used. If it's set to “0” then the function returns immediately and no code debugging is performed.


1 Answers

Using the technique you suggested, this works (though it's not pretty):

break PyEval_EvalFrameEx if (strcmp((((PyStringObject *)(f->f_code->co_name))->ob_sval), "foo") == 0)

Here, f is a PyFrameObject. You may also want to check f->f_code->co_filename to make sure you've got the right file. Note that this does slow down the program quite a bit, since you're breaking and comparing a lot.

GDB 7 has some nice helper macros for dealing with CPython, but I'm not familiar with them. There's probably a nicer way to accomplish what you're looking for with those.

like image 109
Brendan Dolan-Gavitt Avatar answered Oct 06 '22 00:10

Brendan Dolan-Gavitt