Run Python script in GDB

Recent GDB (at least afeter version 7) can run Python script. To run it, we use source command as same as the GDB macro.

Let's try it. We prepare the following Python script.
$ cat hello.py
#!/usr/bin/env python
import sys
sys.stdout.write('Hello, my first script.\n')
Launch GDB and run the script
(gdb) source hello.py
Hello, my first script.

Use of GDB functions from a Python script

The following is the example to use GDB functions from a Python script. gdb.execute() can run operations used in the GDB command line.

The following example uses target.cc as a debug target.
[target.cc]
#include <cstdio>
#include <cstdlib>
#include <time.h>

int getval(int div)
{
        return time(NULL) / div;
}

int main(void)
{
        printf("val: %d\n", getval(5));
        return EXIT_SUCCESS;
}
show-bt.py will perform the following 4 operations.
  • Set a break point at the head of getval() function
  • Run the program
  • Show the bracktrace at the break point
  • Show rax register at the break point
[show-bt.py] 
gdb.execute('b getval')
gdb.execute('run')
gdb.execute('bt')
gdb.execute('p/x $rax')
The following is an example to run a script in the command line. The command line argument '-q' disables to show startup messages of GDB such as copyright. '-x' specifies the script to be executed.
$ gdb -q -x show-bt.py  target
Reading symbols from /home/foo/target...done.
Breakpoint 1 at 0x400627: file target.cc, line 7.

Breakpoint 1, getval (div=5) at target.cc:7
7               return time(NULL) / div;
#0  getval (div=5) at target.cc:7
#1  0x0000000000400656 in main () at target.cc:12
#2  0x00007ffff72d2ead in __libc_start_main (main=, argc=, ubp_av=, init=, fini=, rtld_fini=, stack_end=0x7fffffffe128) at libc-start.c:228
#3  0x0000000000400539 in _start ()
$1 = 0x7ffff763aee8

Get output of a command as a Python string

The above example only executes normal GDB commands. Let's get the output as a Python string. It can be achived by passing True to to_string parameter of get.execute() function. Python is also good at string processing, so you can easily extract and display specific strings in a formatted format.

The following exmaple shows the frame number and the last word from the stacktrace.
$ cat show-bt-and-format.py 
gdb.execute('b getval')
gdb.execute('run')
bt = gdb.execute('bt', to_string=True)
for line in bt.split('\n'):
  words = line.split(' ')
  print '%s %s' % (words[0], words[-1])
$ gdb -q -x show-bt-and-format.py  target
Reading symbols from /home/foo/target...done.
Breakpoint 1 at 0x400627: file target.cc, line 7.

Breakpoint 1, getval (div=5) at target.cc:7
7               return time(NULL) / div;
#0 target.cc:7
#1 target.cc:12
#2 libc-start.c:228
#3 ()

No comments:

Post a Comment