Search code examples
gdb

How can the result of print-like formatting be used in a gdb printf expression?


In GDB I can get nice formatting of a POD struct when I use a plain print command:

(gdb) print l[0] 
$9 = {rq = 10, eq = 0 }

I would like to use a printf expression in a gdb user-defined function that formats this variable in the same way.

What is the correct syntax to do this? The "natural" way to do this fails

(gdb) printf "%s", l[0]
Value can't be converted to integer.

Solution

  • There have been a few questions where the answer involves putting the output of a GDB command into a convenience variable. Rather than writing Python every time, as in my first answer, here's a convenience function named $execute that does this. You can put it in the file ~/execute.py, and load it into GDB using the source command.

    import gdb
    
    class Execute(gdb.Function):
      """Execute the first argument as a command.
    Returns a string (C array of char).
    Optional second argument chomp=True will remove trailing newlines.
    In general, the first argument should be a C string,
    and the second argument a C bool."""
    
      def __init__(self):
        super(Execute, self).__init__("execute")
    
      def invoke(self, arg, chomp=True):
        ret = gdb.execute(arg.string(), to_string=True)
        if chomp:
           ret = ret.rstrip('\n')
        return ret
    
    Execute()
    

    And here's how to use it in your case:

    (gdb) source ~/execute.py
    (gdb) set $firstelt = $execute("output l[0]")
    (gdb) printf "In thread %d, first element is %s.\n", $_thread, $firstelt
    In thread 1, first element is {rq = 10, eq = 0}.
    

    The GDB output command does the same thing as print, but it omits the $n = at the beginning.