GDB: Pretty Printers

1. STDC++ Printer

The pretty printer for C++ STL containers is usually installed into system together with g++ and can be found at the below path.

(gdb) info pretty-printer 
  builtin
  libstdc++-v6

If the stdc++ printer is not installed yet, you can manually install it.

wget https://github.com/gcc-mirror/gcc/archive/refs/heads/master.zip \
    -O gcc.zip

unzip gcc.zip
python
  import sys
  from libstdcxx.v6.printers import register_libstdcxx_printers
  
  sys.path.insert(0, '/root/gcc-master/libstdc++-v3/python')
  register_libstdcxx_printers (None)
end

2. Manage Printers

Enable, disable and show pretty printers info.

  enable pretty-printer [object-regexp [name-regexp]]
  disable pretty-printer [object-regexp [name-regexp]]
  info pretty-printer [object-regexp [name-regexp]]

3. Writing a Printer

A pretty-printer consists of 3 steps:

typedef uint32_t in_addr_t;
struct in_addr
{
    in_addr_t s_addr;
};

3.1 Printer for in_addr.

1: Printer.

import gdb

class InAddrPrinter:
  def __init__(self, val):
    self.val = val
  def to_string(self):
    octets = self.val.bytes
    s = ""
    for x in octets:
      s += str(x) + "."
    return s

2: Lookup function.

import gdb

def in_addr_lookup(val):
  typename = val.type.name
  if typename == "in_addr":
    return InAddrPrinter(val)
  return None

3: Register lookup function (file: in_addr_printer.py).

from gdb.printing import register_pretty_printer

register_pretty_printer(
  obj=None, printer=in_addr_lookup, replace=True)

4: Test.

#include <arpa/inet.h>

int main()
{
  struct in_addr addr;

  inet_pton(AF_INET, 
    "192.168.1.1", 
    &addr);
}
(gdb) source in_addr_printer.py

(gdb) info pretty-printer 
  builtin
  in_addr_lookup
  libstdc++-v6

(gdb) print addr
$1 = 192.168.1.1.

References