Skip to content

GDB pretty printing support #1952

Closed
@aaaaaaaaargh

Description

@aaaaaaaaargh

Debugging JSON objects with GDB is very tedious and in some cases (e.g. from within CLion) not even possible due to the complexity of the type. I've created a small pretty printer that takes care of this issue by utilising the libraries .dump() method.

I hope some of you may find that useful. Feel free to use this any way you like, including incorporation in the library codebase :)

# Pretty printing support for nlohmann::basic_json objects.

import gdb.printing

class NlohmannJsonPrinter(object):
    "Print a json"
    
    def __init__(self, val):
        self.val = val
        
    def to_string(self):
        eval_string = "(*("+str(self.val.type)+"*)("+str(self.val.address)+")).dump(2, ' ', false, nlohmann::detail::error_handler_t::strict).c_str()"
        result = gdb.parse_and_eval(eval_string)
        
        return result.string()
        
    def display_hint(self):
        return 'JSON'
        
def build_pretty_printer():
    pp = gdb.printing.RegexpCollectionPrettyPrinter(
        "nlohmann::basic_json")
    pp.add_printer('JSON', '^nlohmann::basic_json<.*>$', NlohmannJsonPrinter)
    return pp
 
def register_json_printer():
    gdb.printing.register_pretty_printer(
        gdb.current_objfile(),
        build_pretty_printer())

How to use:

  • Save the code in a file somewhere. The exact location isn't that important, I use ~/Dev/.gdb.
  • Add the path to your .gdbinit system paths, import and register the printer as usual:
sys.path.append('/home/your/path/to/the-file.gdb')

from nlohmannjson import register_json_printer
register_json_printer()

Have fun!

Metadata

Metadata

Assignees

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions