Print QStrings in GDB

If you will ever have to go through the hell of debugging Qt-applications, you might face the problem of printing the contents of QString objects. If you call print on a QString object in gdb, the output will most probably look like the following:

{static null = {}, static shared_null = {ref = {_q_value = 1}, 
alloc = 0, size = 0, data = 0x80e6d0a, clean = 0, simpletext = 0, righttoleft = 0, 
asciiCache = 0, capacity = 0, reserved = 0, array = {0}}, 
static shared_empty = {ref = {_q_value = 2}, alloc = 0, size = 0, data = 0xb734deb2, 
clean = 0, simpletext = 0, righttoleft = 0, asciiCache = 0, capacity = 0, 
reserved = 0, array = {0}}, d = 0x8105138, static codecForCStrings = 0x0}

This is (in most cases) not quite what we want to know about our QString object. Fortunately, GDB can interpret certain routines, so that we can implement a function that prints QStrings. These routines are stored in GDB’s init-file ~/.gdbinit. Unfortunately, the internal data representation of a string has changed in Qt4, such that we most certainly need two versions of the desired function. I will call the functions qprint3 and qprint4, respectively.

Qt3 Version

The Qt3 version was originally posted by David Faure to the KDE maillist in 2001:

define qprint3
    set $i=0
    while $i < $arg0.d->len
	print $arg0.d->unicode[$i++].cl
    end
end

Qt4 Version

define qprint4
    printf "(QString)0x%x (length=%i): \"",&$arg0,$arg0.d->size
    set $i=0
    while $i < $arg0.d->size
        set $c=$arg0.d->data[$i++]
        if $c < 32 || $c > 127
                printf "\\u0x%04x", $c
        else
                printf "%c", (char)$c
        end
    end
    printf "\"\n"
end

Further reading

The KDE source repository has some further pretty neat GDB macros.


Posted

in

by

Tags: