pythonpython-2.7gdbgdb-python

gdb python : How to redirect the output of a gdb command to a variable?


I am using RHEL 5.3 OS, gdb 7.5 and python 2.7. I am writing a script in Python to automate some gdb debugging steps. Can we store the output of the following command ("name1") into a variable?

(gdb) p *(ptr->name)
$13 = "name1"

I want to do this because in my Python script I will compare this (name1) to a user input string, and if matches, will do some action otherwise ask user to input another string.

Please Suggest me alternative if it is not possible.


Solution

  • Getting the value of an expression in GDB is what gdb.parse_and_eval() is for. I think you want something like this:

    name1.c :

    #include <string.h>
    #include <stdio.h>
    
    /* https://github.com/scottt/debugbreak */
    #include <debugbreak/debugbreak.h>
    
    struct T {
        char *name;
    };
    
    int main()
    {
        struct T t, *p = &t;
        t.name = strdup("name1");
        debug_break();
        printf("%s\n", p->name);
        return 0;
    }
    

    input-name.py :

    import gdb
    
    gdb.execute('set python print-stack full')
    gdb.execute('set confirm off')
    gdb.execute('file name1')
    gdb.execute('run')
    
    name_in_program = gdb.parse_and_eval('p->name').string()
    gdb.write('Please input name: ')
    name = raw_input()
    while name != name_in_program:
        gdb.write('Please try another name: ')
        name = raw_input()
    
    gdb.execute('quit')
    

    Sample session:

    $ gdb -q -x input-name.py
    
    Program received signal SIGTRAP, Trace/breakpoint trap.
    main () at name1.c:16
    16      printf("%s\n", p->name);
    Please input name: nameX
    Please try another name: name1
    
    $
    

    Note that I took the shortcut of breaking into the debugger by inserting a trap instruction in my C code via debug_break(). You'd probably want to set a breakpoint instead.