3
votes

I want to create a python pretty printer within gdb. I have a hidden data-type xyzHandle in the program I'm trying to debug. I can pull out some information from that handle with a C function; which I can call within the gdb debugger. For example:

xyzHandle object1 = api_get_first_object();

(gdb) print (char *)xyz_get_string(1, object1)

I know I can create a gdb command like 'pn' and use that; but I want to use the build-in python of (gdb) to create a pretty-printer that if it sees 'xyzHandle' it will call 'xyz_get_string(1, object1)' and just print the returned string. That way in (gdb) I can simply type 'print object1' .

I've read about how to create a simple gdb-python pretty_printer , but I don't know how to call a function that resides in the program I'm debugging from python.

Here is my sample pretty printer for the xyzHandle object.

# To load this into your gdb session
#
# (gdb) python execfile ("script-name")
#

import gdb.printing

class xyzHandlePrinter:
    """Print an xyzHandle object"""

    def __init__(self, val):
        self.val = val

    def to_string(self):
        return ( str( ???how-do-I-call xyz_get_str???) )


def build_pretty_printer():
    pp = gdb.printing.RegexpCollectionPrettyPrinter("XYZ Library")
    pp.add_printer('xyzHandle Printer', '^xyzHandle', xyzHandlePrinter)
    return pp

gdb.printing.register_pretty_printer(
    gdb.current_objfile(),
    build_pretty_printer())
1

1 Answers

3
votes

create a pretty-printer that if it sees 'xyzHandle' it will call 'xyz_get_string(1, object1)' and just print the returned string

This is generally a bad idea: your pretty printer will work on "live" process, but will error out in post-mortem (core file) debugging. You will generally be better off if you replicate the functionality of xyz_get_string in pure Python.

I don't know how to call a function that resides in the program I'm debugging from python.

You can use gdb.parse_and_eval for that.