Skip to content

Instantly share code, notes, and snippets.

@sffc
Last active December 22, 2023 09:57
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sffc/7b3826fd67cb78057a9e66f2b350a647 to your computer and use it in GitHub Desktop.
Save sffc/7b3826fd67cb78057a9e66f2b350a647 to your computer and use it in GitHub Desktop.
A GDB pretty-printer for ICU4C UnicodeStrings
# To autoload this file into GDB, put the following line in ~/.gdbinit:
#
# python execfile("/path/to/icu_unicodestring_prettyprinter.py")
#
# You can also run that line of code in the GDB console without adding it to ~/.gdbinit.
from __future__ import print_function
from array import array
import re
class UnicodeStringPrinter:
"""GDB pretty printer for ICU4C UnicodeString"""
def __init__(self, val):
self.val = val
def to_string(self):
fLengthAndFlags = self.val["fUnion"]["fFields"]["fLengthAndFlags"]
if fLengthAndFlags >= 0:
# Short length
length = fLengthAndFlags >> 5
else:
# Long length
length = self.val["fUnion"]["fFields"]["fLength"]
if (fLengthAndFlags & 2) != 0:
# Stack storage
if (fLengthAndFlags & 1) != 0:
return u"UnicodeString (BOGUS)"
stack = True
buffer = self.val["fUnion"]["fStackFields"]["fBuffer"]
else:
# Heap storage
stack = False
buffer = self.val["fUnion"]["fFields"]["fArray"]
content = array('B', [buffer[i] for i in range(length)]).tostring()
return u"UnicodeString (%d on %s): \"%s\"" % (
length,
u"stack" if stack else u"heap",
content)
unicode_string_re = re.compile("^icu_?\d*::UnicodeString$")
def lookup_type(val):
if unicode_string_re.match(str(val.type)):
return UnicodeStringPrinter(val)
return None
gdb.pretty_printers.append(lookup_type)
@Manishearth
Copy link

The tostring() needs to be tobytes() on Python 3 now

@brmarkus
Copy link

In GDB console (GNU gdb (Ubuntu 12.1-0ubuntu1~22.04) 12.1 in my case), need to call source /path/to/icu_unicodestring_prettyprinter.py.

In Visual Studio Code, in the "Debug Console" calling -exec source /path/to/icu_unicodestring_prettyprinter.py.

Adding to ~/.gdbinit didn't work for me.

Has anyone outthere got VisualStudio debugger (GDB, remote development) configured to call this Python script, e.g. in launch.json?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment