Can I define a gdb command that works with pointer or object?

175 views Asked by At

Suppose I create a gdb user-defined command like this:

define pfoo
call foo_printer($arg0)
end

where foo_printer takes a pointer argument. Then if I have a pointer variable pf I can do:

pfoo pf

But if I have a non-pointer variable f, I need to remember to provide &:

pfoo &f

Is there a way to define the command to work with either pointer or non-pointer argument? Ie, so both of these would work:

pfoo pf
pfoo f
1

There are 1 answers

0
John H. On

As a novice to the GDB Python API, this is what I came up with:

class FooPrinter (gdb.Command):
    """Print a FOO (pointer or not, may be nil)"""
    def __init__(self):
        super(FooPrinter, self).__init__("pfoo", gdb.COMMAND_USER)
    def invoke(self, foo, from_tty):
        gdb_foo = gdb.parse_and_eval(foo)
        if gdb_foo.type.code == gdb.TYPE_CODE_PTR:
            if not gdb_foo.address:
                gdb.write("<nil>\n")
            else:
                gdb.execute("call foo_printer(" + foo + ")")
        else:
            gdb.execute("call foo_printer(&" + foo + ")")

FooPrinter()

(And then source that file in .gdbinit.)

Please do let me know if this might be improved.