I am about to develop a custom GDB pretty printer. Trying to follow simple guide from the GDB documentation I made the following:
printer.py:
import gdb.printing
class element_printer:
"""Print element object"""
def __init__(self, val) -> None:
self.val = val
def to_string(self):
return ("Sample element: value=<" + str(self.val["m_value"]))
return ("value=<" + str(self.val["m_value"]))
def build_pretty_printer():
pp = gdb.printing.RegexpCollectionPrettyPrinter("ReVolta")
pp.add_printer('ReVolta::element', '^ReVolta::element%', element_printer)
return pp
gdb.printing.register_pretty_printer(gdb.current_objfile(), build_pretty_printer())
which is intended to pretty print the objects of the following class:
element.cpp:
namespace ReVolta {
struct element {
size_t m_value;
};
...
element elm { 42 };
...
}
Unless loaded into GDB once in debug session, the object is shown as:
GDB:
print elm
$1 = {m_value = 42}
which is as expected, a generic way to show the content. Just to verify which pretty printers are loaded, here is the check I made:
GDB:
info pretty-printer
global pretty-printers:
builtin
mpx_bound128
objfile /lib/aarch64-linux-gnu/libstdc++.so.6 pretty-printers:
libstdc++-v6
__gnu_cxx::_Slist_iterator
__gnu_cxx::__8::_Slist_iterator
__gnu_cxx::__8::__normal_iterator
....
Notice just the printers from libstdc++-v6 are loaded (not a complete list above). Notice no custom printers are loaded. Now I load my printer modules:
GDB:
source /home/martin/git/revolta/test/librevolta/element.py
and try to verify the successful load:
GDB:
info pretty-printer
global pretty-printers:
ReVolta
ReVolta::element <----- MY CUSTOM PRETTY PRINTER HERE
builtin
mpx_bound128
objfile /lib/aarch64-linux-gnu/libstdc++.so.6 pretty-printers:
libstdc++-v6
__gnu_cxx::_Slist_iterator
__gnu_cxx::__8::_Slist_iterator
__gnu_cxx::__8::__normal_iterator
__gnu_cxx::__8::slist
....
Notice my custom pretty printer is loaded successfully (seems so).
PROBLEM: The problem is, it seems my pretty printer is not used. When I try to print the elm
instance of ReVolta::element
class, it gets the same result:
GDB:
print elm
$1 = {m_value = 42}
May I kindly ask you for help to make the pretty printer running? Many thanks to anyone willing to help! Martin
The issue was resolved by fixing the bug in regular expression. The correct regex to use in adding the printer is:
pp.add_printer('ReVolta::element', '^ReVolta::element$', element_printer)
Notice the $ used instead of % at the end of the regex.
Thanks @ssbssa for kicking me the right direction (as in question comments)