dumper.py 60 KB
Newer Older
1
from __future__ import with_statement
hjk's avatar
hjk committed
2 3

import sys
4
import base64
5
import __builtin__
6
import os
hjk's avatar
hjk committed
7
import tempfile
8

9 10 11 12
# Fails on Windows.
try:
    import curses.ascii
    def printableChar(ucs):
13 14 15
        if curses.ascii.isprint(ucs):
            return ucs
        return '?'
16
except:
17 18 19 20
    def printableChar(ucs):
        if ucs >= 32 and ucs <= 126:
            return ucs
        return '?'
hjk's avatar
hjk committed
21

22
# Fails on SimulatorQt.
23
tempFileCounter = 0
24
try:
25 26 27
    # Test if 2.6 is used (Windows), trigger exception and default
    # to 2nd version.
    tempfile.NamedTemporaryFile(prefix="py_",delete=True)
28
    def createTempFile():
29
        file = tempfile.NamedTemporaryFile(prefix="py_",delete=False)
30
        file.close()
31
        return file.name, file
32

33 34
except:
    def createTempFile():
35 36
        global tempFileCounter
        tempFileCounter += 1
37
        fileName = "%s/py_tmp_%d_%d" \
hjk's avatar
hjk committed
38
            % (tempfile.gettempdir(), os.getpid(), tempFileCounter)
39
        return fileName, None
40

41 42 43 44
def removeTempFile(name, file):
    try:
        os.remove(name)
    except:
45
        pass
46

47 48 49 50 51
try:
    import binascii
except:
    pass

hjk's avatar
hjk committed
52 53 54
verbosity = 0
verbosity = 1

55 56 57 58
# Some "Enums"

# Encodings
Unencoded8Bit, \
59 60 61 62 63 64 65 66 67 68
Base64Encoded8BitWithQuotes, \
Base64Encoded16BitWithQuotes, \
Base64Encoded32BitWithQuotes, \
Base64Encoded16Bit, \
Base64Encoded8Bit, \
Hex2EncodedLatin1, \
Hex4EncodedLittleEndian, \
Hex8EncodedLittleEndian, \
Hex2EncodedUtf8, \
Hex8EncodedBigEndian, \
Arvid Ephraim Picciani's avatar
Arvid Ephraim Picciani committed
69
Hex4EncodedBigEndian, \
70 71 72
Hex4EncodedLittleEndianWithoutQuotes, \
Hex2EncodedLocal8Bit \
    = range(14)
73 74

# Display modes
75 76 77 78 79 80
StopDisplay, \
DisplayImage1, \
DisplayString, \
DisplayImage, \
DisplayProcess \
    = range(5)
81 82


83
def hasInferiorThreadList():
hjk's avatar
hjk committed
84
    return False
85
    try:
86
        a = gdb.inferiors()[0].threads()
87 88 89 90
        return True
    except:
        return False

91 92 93 94 95 96 97
def upcast(value):
    try:
        type = value.dynamic_type
        return value.cast(type)
    except:
        return value

98 99
typeCache = {}

100 101 102 103 104 105 106
class TypeInfo:
    def __init__(self, type):
        self.size = type.sizeof
        self.reported = False

typeInfoCache = {}

107 108
def lookupType(typestring):
    type = typeCache.get(typestring)
hjk's avatar
hjk committed
109
    #warn("LOOKUP 1: %s -> %s" % (typestring, type))
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
    if not type is None:
        return type

    ts = typestring
    while True:
        #WARN("ts: '%s'" % ts)
        if ts.startswith("class "):
            ts = ts[6:]
        elif ts.startswith("struct "):
            ts = ts[7:]
        elif ts.startswith("const "):
            ts = ts[6:]
        elif ts.startswith("volatile "):
            ts = ts[9:]
        elif ts.startswith("enum "):
            ts = ts[5:]
        elif ts.endswith(" const"):
            ts = ts[:-6]
        elif ts.endswith(" volatile"):
            ts = ts[:-9]
        elif ts.endswith("*const"):
            ts = ts[:-5]
        elif ts.endswith("*volatile"):
            ts = ts[:-8]
        else:
            break

    if ts.endswith('*'):
        type = lookupType(ts[0:-1])
hjk's avatar
hjk committed
139 140 141
        if not type is None:
            type = type.pointer()
            typeCache[typestring] = type
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
            return type

    try:
        #warn("LOOKING UP '%s'" % ts)
        type = gdb.lookup_type(ts)
    except RuntimeError, error:
        #warn("LOOKING UP '%s': %s" % (ts, error))
        # See http://sourceware.org/bugzilla/show_bug.cgi?id=11912
        exp = "(class '%s'*)0" % ts
        try:
            type = parseAndEvaluate(exp).type.target()
        except:
            # Can throw "RuntimeError: No type named class Foo."
            pass
    except:
        #warn("LOOKING UP '%s' FAILED" % ts)
158
        pass
159 160 161

    # This could still be None as gdb.lookup_type("char[3]") generates
    # "RuntimeError: No type named char[3]"
162 163
    return type

164
def cleanAddress(addr):
165 166
    if addr is None:
        return "<no address>"
167 168
    # We cannot use str(addr) as it yields rubbish for char pointers
    # that might trigger Unicode encoding errors.
169
    #return addr.cast(lookupType("void").pointer())
170 171
    # We do not use "hex(...)" as it (sometimes?) adds a "L" suffix.
    return "0x%x" % long(addr)
172

173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
def extractTemplateArgument(type, position):
    level = 0
    skipSpace = False
    inner = ""
    type = str(type)
    for c in type[type.find('<') + 1 : -1]:
        if c == '<':
            inner += c
            level += 1
        elif c == '>':
            level -= 1
            inner += c
        elif c == ',':
            if level == 0:
                if position == 0:
                    return inner
                position -= 1
                inner = ""
            else:
                inner += c
                skipSpace = True
        else:
            if skipSpace and c == ' ':
                pass
            else:
                inner += c
                skipSpace = False
    return inner

def templateArgument(type, position):
203 204 205 206 207 208
    try:
        # This fails on stock 7.2 with
        # "RuntimeError: No type named myns::QObject.\n"
        return type.template_argument(position)
    except:
        # That's something like "myns::QList<...>"
209
        return lookupType(extractTemplateArgument(type.strip_typedefs(), position))
210

211

hjk's avatar
hjk committed
212 213 214 215
# Workaround for gdb < 7.1
def numericTemplateArgument(type, position):
    try:
        return int(type.template_argument(position))
216
    except RuntimeError, error:
hjk's avatar
hjk committed
217 218 219 220
        # ": No type named 30."
        msg = str(error)
        return int(msg[14:-1])

221

222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
def showException(msg, exType, exValue, exTraceback):
    warn("**** CAUGHT EXCEPTION: %s ****" % msg)
    try:
        import traceback
        for line in traceback.format_exception(exType, exValue, exTraceback):
            warn("%s" % line)
    except:
        pass


class OutputSafer:
    def __init__(self, d, pre = "", post = ""):
        self.d = d
        self.pre = pre
        self.post = post

    def __enter__(self):
        self.d.put(self.pre)
        self.savedOutput = self.d.output
hjk's avatar
hjk committed
241
        self.d.output = []
242 243 244 245 246 247 248

    def __exit__(self, exType, exValue, exTraceBack):
        self.d.put(self.post)
        if self.d.passExceptions and not exType is None:
            showException("OUTPUTSAFER", exType, exValue, exTraceBack)
            self.d.output = self.savedOutput
        else:
hjk's avatar
hjk committed
249 250
            self.savedOutput.extend(self.d.output)
            self.d.output = self.savedOutput
251 252 253
        return False


254 255 256 257 258 259 260 261 262 263 264 265
class NoAddress:
    def __init__(self, d):
        self.d = d

    def __enter__(self):
        self.savedPrintsAddress = self.d.printsAddress
        self.d.printsAddress = False

    def __exit__(self, exType, exValue, exTraceBack):
        self.d.printsAddress = self.savedPrintsAddress


266 267 268 269 270 271 272 273 274 275 276
class SubItem:
    def __init__(self, d):
        self.d = d

    def __enter__(self):
        self.d.put('{')
        self.savedValue = self.d.currentValue
        self.savedValuePriority = self.d.currentValuePriority
        self.savedValueEncoding = self.d.currentValueEncoding
        self.savedType = self.d.currentType
        self.savedTypePriority = self.d.currentTypePriority
hjk's avatar
hjk committed
277
        self.d.currentValue = "<not accessible>"
278
        self.d.currentValuePriority = -100
279 280
        self.d.currentValueEncoding = None
        self.d.currentType = ""
281
        self.d.currentTypePriority = -100
282 283 284 285 286 287

    def __exit__(self, exType, exValue, exTraceBack):
        #warn(" CURRENT VALUE: %s %s %s" % (self.d.currentValue,
        #    self.d.currentValueEncoding, self.d.currentValuePriority))
        if self.d.passExceptions and not exType is None:
            showException("SUBITEM", exType, exValue, exTraceBack)
288
        try:
289
            #warn("TYPE VALUE: %s" % self.d.currentValue)
290 291
            type = stripClassTag(str(self.d.currentType))
            #warn("TYPE: '%s'  DEFAULT: '%s'" % (type, self.d.currentChildType))
292

293 294
            if len(type) > 0 and type != self.d.currentChildType:
                self.d.put('type="%s",' % type) # str(type.unqualified()) ?
295
                if not type in typeInfoCache and type != " ": # FIXME: Move to lookupType
296 297 298
                    typeObj = lookupType(type)
                    if not typeObj is None:
                        typeInfoCache[type] = TypeInfo(typeObj)
299
            if not self.d.currentValueEncoding is None:
300
                self.d.put('valueencoded="%d",' % self.d.currentValueEncoding)
301
            if not self.d.currentValue is None:
302
                self.d.put('value="%s",' % self.d.currentValue)
303 304
        except:
            pass
305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
        self.d.put('},')
        self.d.currentValue = self.savedValue
        self.d.currentValuePriority = self.savedValuePriority
        self.d.currentValueEncoding = self.savedValueEncoding
        self.d.currentType = self.savedType
        self.d.currentTypePriority = self.savedTypePriority
        return True


class Children:
    def __init__(self, d, numChild = 1, childType = None, childNumChild = None):
        self.d = d
        self.numChild = numChild
        self.childType = childType
        self.childNumChild = childNumChild
        #warn("CHILDREN: %s %s %s" % (numChild, childType, childNumChild))

    def __enter__(self):
        childType = ""
        childNumChild = -1
        if type(self.numChild) is list:
            numChild = self.numChild[0]
            maxNumChild = self.numChild[1]
        else:
            numChild = self.numChild
            maxNumChild = self.numChild
        if numChild == 0:
            self.childType = None
        if not self.childType is None:
            childType = stripClassTag(str(self.childType))
            self.d.put('childtype="%s",' % childType)
336
            if isSimpleType(self.childType):
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
                self.d.put('childnumchild="0",')
                childNumChild = 0
            elif self.childType.code == gdb.TYPE_CODE_PTR:
                self.d.put('childnumchild="1",')
                childNumChild = 1
        if not self.childNumChild is None:
            self.d.put('childnumchild="%s",' % self.childNumChild)
            childNumChild = self.childNumChild
        self.savedChildType = self.d.currentChildType
        self.savedChildNumChild = self.d.currentChildNumChild
        self.savedNumChilds = self.d.currentNumChilds
        self.savedMaxNumChilds = self.d.currentNumChilds
        self.d.currentChildType = childType
        self.d.currentChildNumChild = childNumChild
        self.d.currentNumChilds = numChild
        self.d.currentMaxNumChilds = maxNumChild
        self.d.put("children=[")

    def __exit__(self, exType, exValue, exTraceBack):
        if self.d.passExceptions and not exType is None:
            showException("CHILDREN", exType, exValue, exTraceBack)
        if self.d.currentMaxNumChilds < self.d.currentNumChilds:
hjk's avatar
hjk committed
359
            self.d.putEllipsis()
360 361 362 363 364 365 366 367
        self.d.currentChildType = self.savedChildType
        self.d.currentChildNumChild = self.savedChildNumChild
        self.d.currentNumChilds = self.savedNumChilds
        self.d.currentMaxNumChilds = self.savedMaxNumChilds
        self.d.put('],')
        return True


368 369 370 371 372 373 374 375 376 377 378
# Creates a list of field names of an anon union or struct
def listOfFields(type):
    fields = []
    for field in type.fields():
        if len(field.name) > 0:
            fields += field.name
        else:
            fields += listOfFields(field.type)
    return fields


379
def value(expr):
380
    value = parseAndEvaluate(expr)
381 382 383 384 385
    try:
        return int(value)
    except:
        return str(value)

hjk's avatar
hjk committed
386
def isSimpleType(typeobj):
387 388 389 390 391
    code = typeobj.code
    return code == gdb.TYPE_CODE_BOOL \
        or code == gdb.TYPE_CODE_CHAR \
        or code == gdb.TYPE_CODE_INT \
        or code == gdb.TYPE_CODE_FLT \
392
        or code == gdb.TYPE_CODE_ENUM
393

hjk's avatar
hjk committed
394 395 396 397 398 399 400 401 402
def isStringType(d, typeobj):
    type = str(typeobj)
    return type == d.ns + "QString" \
        or type == d.ns + "QByteArray" \
        or type == "std::string" \
        or type == "std::wstring" \
        or type == "wstring"

def warn(message):
403 404
    if True or verbosity > 0:
        print "XXX: %s\n" % message.encode("latin1")
hjk's avatar
hjk committed
405 406 407 408 409 410
    pass

def check(exp):
    if not exp:
        raise RuntimeError("Check failed")

411 412 413 414 415
def checkRef(ref):
    count = ref["_q_value"]
    check(count > 0)
    check(count < 1000000) # assume there aren't a million references to any object

hjk's avatar
hjk committed
416
#def couldBePointer(p, align):
417
#    type = lookupType("unsigned int")
hjk's avatar
hjk committed
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
#    ptr = gdb.Value(p).cast(type)
#    d = int(str(ptr))
#    warn("CHECKING : %s %d " % (p, ((d & 3) == 0 and (d > 1000 or d == 0))))
#    return (d & (align - 1)) and (d > 1000 or d == 0)


def checkAccess(p, align = 1):
    return p.dereference()

def checkContents(p, expected, align = 1):
    if int(p.dereference()) != expected:
        raise RuntimeError("Contents check failed")

def checkPointer(p, align = 1):
    if not isNull(p):
        p.dereference()


def isNull(p):
437 438 439 440
    # The following can cause evaluation to abort with "UnicodeEncodeError"
    # for invalid char *, as their "contents" is being examined
    #s = str(p)
    #return s == "0x0" or s.startswith("0x0 ")
441 442 443 444 445 446
    #try:
    #    # Can fail with: "RuntimeError: Cannot access memory at address 0x5"
    #    return p.cast(lookupType("void").pointer()) == 0
    #except:
    #    return False
    return long(p) == 0
hjk's avatar
hjk committed
447 448 449 450 451 452 453 454

movableTypes = set([
    "QBrush", "QBitArray", "QByteArray",
    "QCustomTypeInfo", "QChar",
    "QDate", "QDateTime",
    "QFileInfo", "QFixed", "QFixedPoint", "QFixedSize",
    "QHashDummyValue",
    "QIcon", "QImage",
hjk's avatar
hjk committed
455
    "QLine", "QLineF", "QLatin1Char", "QLocale",
hjk's avatar
hjk committed
456 457 458 459 460 461 462 463 464 465 466 467 468 469
    "QMatrix", "QModelIndex",
    "QPoint", "QPointF", "QPen", "QPersistentModelIndex",
    "QResourceRoot", "QRect", "QRectF", "QRegExp",
    "QSize", "QSizeF", "QString",
    "QTime", "QTextBlock",
    "QUrl",
    "QVariant",
    "QXmlStreamAttribute", "QXmlStreamNamespaceDeclaration",
    "QXmlStreamNotationDeclaration", "QXmlStreamEntityDeclaration"])


def stripClassTag(type):
    if type.startswith("class "):
        return type[6:]
hjk's avatar
hjk committed
470
    if type.startswith("struct "):
471
        return type[7:]
hjk's avatar
hjk committed
472
    if type.startswith("const "):
hjk's avatar
hjk committed
473
        return type[6:]
hjk's avatar
hjk committed
474
    if type.startswith("volatile "):
hjk's avatar
hjk committed
475
        return type[9:]
hjk's avatar
hjk committed
476 477 478
    return type

def checkPointerRange(p, n):
479
    for i in xrange(n):
hjk's avatar
hjk committed
480 481 482
        checkPointer(p)
        ++p

hjk's avatar
hjk committed
483 484 485 486 487 488 489 490 491 492 493 494 495
def call2(value, func, args):
    # args is a tuple.
    arg = ""
    for i in range(len(args)):
        if i:
            arg += ','
        a = args[i]
        if (':' in a) and not ("'" in a):
            arg = "'%s'" % a
        else:
            arg += a

    #warn("CALL: %s -> %s(%s)" % (value, func, arg))
hjk's avatar
hjk committed
496
    type = stripClassTag(str(value.type))
497
    if type.find(":") >= 0:
hjk's avatar
hjk committed
498
        type = "'" + type + "'"
499
    # 'class' is needed, see http://sourceware.org/bugzilla/show_bug.cgi?id=11912
hjk's avatar
hjk committed
500
    exp = "((class %s*)%s)->%s(%s)" % (type, value.address, func, arg)
hjk's avatar
hjk committed
501
    #warn("CALL: %s" % exp)
502 503 504 505 506
    result = None
    try:
        result = parseAndEvaluate(exp)
    except:
        pass
hjk's avatar
hjk committed
507 508 509
    #warn("  -> %s" % result)
    return result

hjk's avatar
hjk committed
510 511 512
def call(value, func, *args):
    return call2(value, func, args)

513 514 515 516
def makeValue(type, init):
    type = stripClassTag(type)
    if type.find(":") >= 0:
        type = "'" + type + "'"
517 518
    # Avoid malloc symbol clash with QVector
    gdb.execute("set $d = (%s*)calloc(sizeof(%s), 1)" % (type, type))
519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535
    gdb.execute("set *$d = {%s}" % init)
    value = parseAndEvaluate("$d").dereference()
    #warn("  TYPE: %s" % value.type)
    #warn("  ADDR: %s" % value.address)
    #warn("  VALUE: %s" % value)
    return value

def makeExpression(value):
    type = stripClassTag(str(value.type))
    if type.find(":") >= 0:
        type = "'" + type + "'"
    #warn("  TYPE: %s" % type)
    #exp = "(*(%s*)(&%s))" % (type, value.address)
    exp = "(*(%s*)(%s))" % (type, value.address)
    #warn("  EXP: %s" % exp)
    return exp

536 537
qqNs = None

538
def qtNamespace():
539
    # FIXME: This only works when call from inside a Qt function frame.
540
    global qqNs
541 542
    if not qqNs is None:
        return qqNs
543
    try:
544
        str = catchCliOutput("ptype QString::Null")[0]
hjk's avatar
hjk committed
545
        # The result looks like:
546 547 548 549 550
        # "type = const struct myns::QString::Null {"
        # "    <no data fields>"
        # "}"
        pos1 = str.find("struct") + 7
        pos2 = str.find("QString::Null")
551 552 553 554
        if pos1 > -1 and pos2 > -1:
            qqNs = str[pos1:pos2]
            return qqNs
        return ""
555
    except:
556
        return ""
hjk's avatar
hjk committed
557

558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586
# --  Determine size of qptrdiff (cached)

qqptrdiffSize = None

def qtptrdiffSize():
    global qqptrdiffSize
    if not qqptrdiffSize is None:
        return qqptrdiffSize
    try:
        qqptrdiffSize = lookupType(qtNamespace() + 'qptrdiff').sizeof
        return qqptrdiffSize
    except:
        return 0

# --  Determine major Qt version by calling qVersion (cached)

qqMajorVersion = None

def qtMajorVersion():
    global qqMajorVersion
    if not qqMajorVersion is None:
        return qqMajorVersion
    try:
        # -- Result is returned as character, need to subtract '0'
        qqMajorVersion = int(parseAndEvaluate(qtNamespace() + "qVersion()[0]")) - 48
        return qqMajorVersion
    except:
        return 0

587 588
def findFirstZero(p, maximum):
    for i in xrange(maximum):
589 590 591
        if p.dereference() == 0:
            return i
        p = p + 1
592
    return maximum + 1
593

594
def extractCharArray(p, maxsize):
595
    t = lookupType("unsigned char").pointer()
596
    p = p.cast(t)
597
    limit = findFirstZero(p, maxsize)
598 599 600 601
    s = ""
    for i in xrange(limit):
        s += "%c" % int(p.dereference())
        p += 1
602
    if i > maxsize:
603 604 605 606 607 608 609 610 611 612 613 614 615
        s += "..."
    return s

def extractByteArray(value):
    d_ptr = value['d'].dereference()
    data = d_ptr['data']
    size = d_ptr['size']
    alloc = d_ptr['alloc']
    check(0 <= size and size <= alloc and alloc <= 100*1000*1000)
    checkRef(d_ptr["ref"])
    if size > 0:
        checkAccess(data, 4)
        checkAccess(data + size) == 0
616
    return extractCharArray(data, min(100, size))
617

618
def encodeCharArray(p, maxsize, limit = -1):
619
    t = lookupType("unsigned char").pointer()
620
    p = p.cast(t)
621 622
    if limit == -1:
        limit = findFirstZero(p, maxsize)
623
    s = ""
624 625 626 627 628 629 630 631
    try:
        # gdb.Inferior is new in gdb 7.2
        inferior = gdb.inferiors()[0]
        s = binascii.hexlify(inferior.read_memory(p, limit))
    except:
        for i in xrange(limit):
            s += "%02x" % int(p.dereference())
            p += 1
632
    if limit > maxsize:
633 634 635 636
        s += "2e2e2e"
    return s

def encodeChar2Array(p, maxsize):
637
    t = lookupType("unsigned short").pointer()
638
    p = p.cast(t)
639
    limit = findFirstZero(p, maxsize)
640 641 642 643 644 645 646 647 648
    s = ""
    for i in xrange(limit):
        s += "%04x" % int(p.dereference())
        p += 1
    if i == maxsize:
        s += "2e002e002e00"
    return s

def encodeChar4Array(p, maxsize):
649
    t = lookupType("unsigned int").pointer()
650
    p = p.cast(t)
651
    limit = findFirstZero(p, maxsize)
652 653 654 655
    s = ""
    for i in xrange(limit):
        s += "%08x" % int(p.dereference())
        p += 1
656
    if i > maxsize:
657
        s += "2e0000002e0000002e000000"
658 659
    return s

660 661 662 663 664 665 666 667 668 669 670 671 672 673 674
def qByteArrayData(value):
    if qtMajorVersion() < 5:
        d_ptr = value['d'].dereference()
        checkRef(d_ptr["ref"])
        data = d_ptr['data']
        size = d_ptr['size']
        alloc = d_ptr['alloc']
        return data, size, alloc
    else: # Qt5: Implement the QByteArrayData::data() accessor.
        qByteArrayData = value['d'].dereference()
        size = qByteArrayData['size']
        alloc = qByteArrayData['alloc']
        data = qByteArrayData['d'].cast(lookupType('char *')) + qByteArrayData['offset'] + qtptrdiffSize()
        return data, size, alloc

675
def encodeByteArray(value):
676
    data, size, alloc = qByteArrayData(value)
677 678 679 680
    check(0 <= size and size <= alloc and alloc <= 100*1000*1000)
    if size > 0:
        checkAccess(data, 4)
        checkAccess(data + size) == 0
681
    return encodeCharArray(data, 100, size)
682

683 684 685 686 687 688 689 690 691 692
def qQStringData(value):
    if qtMajorVersion() < 5:
        d_ptr = value['d'].dereference()
        checkRef(d_ptr['ref'])
        return d_ptr['data'], d_ptr['size'], d_ptr['alloc']
    else: # Qt5: Implement the QStringArrayData::data() accessor.
        qStringData = value['d'].dereference()
        data = qStringData['d'].cast(lookupType('ushort *')) + qtptrdiffSize() / 2 + qStringData['offset']
        return data, qStringData['size'], qStringData['alloc']

693
def encodeString(value):
694 695
    data, size, alloc = qQStringData(value)

696 697 698
    check(0 <= size and size <= alloc and alloc <= 100*1000*1000)
    if size > 0:
        checkAccess(data, 4)
hjk's avatar
hjk committed
699
        checkAccess(data + size) == 0
700
    s = ""
701
    limit = min(size, 1000)
702 703 704
    try:
        # gdb.Inferior is new in gdb 7.2
        inferior = gdb.inferiors()[0]
705
        s = binascii.hexlify(inferior.read_memory(data, 2 * limit))
706
    except:
707
        p = data
708
        for i in xrange(limit):
709 710 711 712
            val = int(p.dereference())
            s += "%02x" % (val % 256)
            s += "%02x" % (val / 256)
            p += 1
713 714
    if limit < size:
        s += "2e002e002e00"
715 716
    return s

hjk's avatar
hjk committed
717 718
def stripTypedefs(type):
    type = type.unqualified()
719 720 721 722
    while type.code == gdb.TYPE_CODE_TYPEDEF:
        type = type.strip_typedefs().unqualified()
    return type

hjk's avatar
hjk committed
723 724 725 726 727 728
def extractFields(type):
    # Insufficient, see http://sourceware.org/bugzilla/show_bug.cgi?id=10953:
    #fields = value.type.fields()
    # Insufficient, see http://sourceware.org/bugzilla/show_bug.cgi?id=11777:
    #fields = stripTypedefs(value.type).fields()
    # This seems to work.
hjk's avatar
hjk committed
729
    #warn("TYPE 0: %s" % type)
hjk's avatar
hjk committed
730
    type = stripTypedefs(type)
731 732 733
    fields = type.fields()
    if len(fields):
        return fields
hjk's avatar
hjk committed
734
    #warn("TYPE 1: %s" % type)
735
    # This fails for arrays. See comment in lookupType.
736 737 738
    type0 = lookupType(str(type))
    if not type0 is None:
        type = type0
739 740
    if type.code == gdb.TYPE_CODE_FUNC:
        return []
hjk's avatar
hjk committed
741 742
    #warn("TYPE 2: %s" % type)
    fields = type.fields()
hjk's avatar
hjk committed
743
    #warn("FIELDS: %s" % fields)
hjk's avatar
hjk committed
744 745
    return fields

hjk's avatar
hjk committed
746 747 748 749 750 751 752
#######################################################################
#
# Item
#
#######################################################################

class Item:
753
    def __init__(self, value, parentiname, iname = None, name = None):
hjk's avatar
hjk committed
754
        self.value = value
755 756 757 758
        if iname is None:
            self.iname = parentiname
        else:
            self.iname = "%s.%s" % (parentiname, iname)
hjk's avatar
hjk committed
759 760 761
        self.name = name


762 763 764 765 766 767
#######################################################################
#
# SetupCommand
#
#######################################################################

768
# This is a cache mapping from 'type name' to 'display alternatives'.
769
qqFormats = {}
770 771

# This is a cache of all known dumpers.
hjk's avatar
hjk committed
772
qqDumpers = {}
773

774 775 776
# This is a cache of all dumpers that support writing.
qqEditable = {}

777 778 779 780 781
# This is a cache of the namespace of the currently used Qt version.
# FIXME: This is not available on 'bbsetup' time, only at 'bb' time.

# This is a cache of typenames->bool saying whether we are QObject
# derived.
hjk's avatar
hjk committed
782
qqQObjectCache = {}
783

784
def bbsetup(args):
785 786 787 788 789
    module = sys.modules[__name__]
    for key, value in module.__dict__.items():
        if key.startswith("qdump__"):
            name = key[7:]
            qqDumpers[name] = value
hjk's avatar
hjk committed
790
            qqFormats[name] = qqFormats.get(name, "")
791 792 793 794 795 796 797 798
        elif key.startswith("qform__"):
            name = key[7:]
            formats = ""
            try:
                formats = value()
            except:
                pass
            qqFormats[name] = formats
799 800 801 802 803 804
        elif key.startswith("qedit__"):
            name = key[7:]
            try:
                qqEditable[name] = value
            except:
                pass
805
    result = "dumpers=["
806
    #qqNs = qtNamespace() # This is too early
807
    for key, value in qqFormats.items():
808 809 810 811
        if qqEditable.has_key(key):
            result += '{type="%s",formats="%s",editable="true"},' % (key, value)
        else:
            result += '{type="%s",formats="%s"},' % (key, value)
812 813
    result += ']'
    #result += ',namespace="%s"' % qqNs
814
    result += ',hasInferiorThreadList="%s"' % int(hasInferiorThreadList())
815 816
    return result

817 818
registerCommand("bbsetup", bbsetup)

819

820 821 822 823 824 825 826
#######################################################################
#
# Edit Command
#
#######################################################################

def bbedit(args):
827 828
    (type, expr, value) = args.split(",")
    type = base64.b16decode(type, True)
829
    ns = qtNamespace()
830 831
    if type.startswith(ns):
        type = type[len(ns):]
832
    type = type.replace("::", "__")
833 834 835 836 837 838
    pos = type.find('<')
    if pos != -1:
        type = type[0:pos]
    expr = base64.b16decode(expr, True)
    value = base64.b16decode(value, True)
    #warn("EDIT: %s %s %s %s: " % (pos, type, expr, value))
839 840 841
    if qqEditable.has_key(type):
        qqEditable[type](expr, value)

842
registerCommand("bbedit", bbedit)
843 844


hjk's avatar
hjk committed
845 846
#######################################################################
#
847
# Frame Command
hjk's avatar
hjk committed
848 849 850
#
#######################################################################

851
def bb(args):
hjk's avatar
hjk committed
852
    output = 'data=[' + "".join(Dumper(args).output) + '],typeinfo=['
853 854 855 856 857 858 859
    for typeName, typeInfo in typeInfoCache.iteritems():
        if not typeInfo.reported:
            output += '{name="' + base64.b64encode(typeName)
            output += '",size="' + str(typeInfo.size) + '"},'
            typeInfo.reported = True
    output += ']';
    return output
hjk's avatar
hjk committed
860

861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878
registerCommand("bb", bb)

def p1(args):
    import cProfile
    cProfile.run('bb("%s")' % args, "/tmp/bbprof")
    import pstats
    pstats.Stats('/tmp/bbprof').sort_stats('time').print_stats()
    return ""

registerCommand("p1", p1)

def p2(args):
    import timeit
    return timeit.repeat('bb("%s")' % args,
        'from __main__ import bb', number=10)

registerCommand("p2", p2)

hjk's avatar
hjk committed
879

880 881 882 883 884 885
#######################################################################
#
# Step Command
#
#######################################################################

886 887 888 889 890 891 892 893 894 895 896 897 898 899
def sal(args):
    (cmd, addr) = arg.split(",")
    lines = catchCliOutput("info line *" + addr)
    fromAddr = "0x0"
    toAddr = "0x0"
    for line in lines:
        pos0from = line.find(" starts at address") + 19
        pos1from = line.find(" ", pos0from)
        pos0to = line.find(" ends at", pos1from) + 9
        pos1to = line.find(" ", pos0to)
        if pos1to > 0:
            fromAddr = line[pos0from : pos1from]
            toAddr = line[pos0to : pos1to]
    gdb.execute("maint packet sal%s,%s,%s" % (cmd,fromAddr, toAddr))
900

901
registerCommand("sal", sal)
hjk's avatar
hjk committed
902

903

hjk's avatar
hjk committed
904 905 906 907 908 909
#######################################################################
#
# The Dumper Class
#
#######################################################################

910

hjk's avatar
hjk committed
911
class Dumper:
912
    def __init__(self, args):
hjk's avatar
hjk committed
913
        self.output = []
914
        self.printsAddress = True
915 916 917 918 919 920 921 922 923
        self.currentChildType = ""
        self.currentChildNumChild = -1
        self.currentMaxNumChilds = -1
        self.currentNumChilds = -1
        self.currentValue = None
        self.currentValuePriority = -100
        self.currentValueEncoding = None
        self.currentType = None
        self.currentTypePriority = -100
924 925 926 927 928 929 930 931
        self.typeformats = {}
        self.formats = {}
        self.expandedINames = ""

        options = []
        varList = []
        watchers = ""

932
        resultVarName = ""
933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960
        for arg in args.split(' '):
            pos = arg.find(":") + 1
            if arg.startswith("options:"):
                options = arg[pos:].split(",")
            elif arg.startswith("vars:"):
                if len(arg[pos:]) > 0:
                    varList = arg[pos:].split(",")
            elif arg.startswith("resultvarname:"):
                resultVarName = arg[pos:]
            elif arg.startswith("expanded:"):
                self.expandedINames = set(arg[pos:].split(","))
            elif arg.startswith("typeformats:"):
                for f in arg[pos:].split(","):
                    pos = f.find("=")
                    if pos != -1:
                        type = base64.b16decode(f[0:pos], True)
                        self.typeformats[type] = int(f[pos+1:])
            elif arg.startswith("formats:"):
                for f in arg[pos:].split(","):
                    pos = f.find("=")
                    if pos != -1:
                        self.formats[f[0:pos]] = int(f[pos+1:])
            elif arg.startswith("watchers:"):
                watchers = base64.b16decode(arg[pos:], True)

        self.useFancy = "fancy" in options
        self.passExceptions = "pe" in options
        self.autoDerefPointers = "autoderef" in options
961
        self.partialUpdate = "partial" in options
962 963
        self.tooltipOnly = "tooltiponly" in options
        self.noLocals = "nolocals" in options
964
        self.ns = qtNamespace()
965 966 967 968 969
        self.alienSource = False
        #try:
        #    self.alienSource = catchCliOutput("info source")[0][-3:-1]==".d"
        #except:
        #    self.alienSource = False
970 971 972 973

        #warn("NAMESPACE: '%s'" % self.ns)
        #warn("VARIABLES: %s" % varList)
        #warn("EXPANDED INAMES: %s" % self.expandedINames)
974
        #warn("WATCHERS: %s" % watchers)
975 976
        #warn("PARTIAL: %s" % self.partialUpdate)
        #warn("NO LOCALS: %s" % self.noLocals)
977 978 979 980 981
        module = sys.modules[__name__]

        #
        # Locals
        #
982
        locals = []
983
        fullUpdateNeeded = True
984
        if self.partialUpdate and len(varList) == 1 and not self.tooltipOnly:
985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001
            #warn("PARTIAL: %s" % varList)
            parts = varList[0].split('.')
            #warn("PARTIAL PARTS: %s" % parts)
            name = parts[1]
            #warn("PARTIAL VAR: %s" % name)
            #fullUpdateNeeded = False
            try:
                frame = gdb.selected_frame()
                item = Item(0, "local", name, name)
                item.value = frame.read_var(name)
                locals = [item]
                #warn("PARTIAL LOCALS: %s" % locals)
                fullUpdateNeeded = False
            except:
                pass
            varList = []

1002
        if fullUpdateNeeded and not self.tooltipOnly and not self.noLocals:
1003
            locals = listOfLocals(varList)
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014

        # Take care of the return value of the last function call.
        if len(resultVarName) > 0:
            try:
                value = parseAndEvaluate(resultVarName)
                locals.append(Item(value, "return", resultVarName, "return"))
            except:
                # Don't bother. It's only supplementary information anyway.
                pass

        for item in locals:
1015
          item.value = upcast(item.value)
1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
          with OutputSafer(self, "", ""):
            self.anonNumber = -1
            #warn("ITEM NAME %s: " % item.name)
            try:
                #warn("ITEM VALUE %s: " % item.value)
                # Throw on funny stuff, catch below.
                # Unfortunately, this fails also with a "Unicode encoding error"
                # in testArray().
                #dummy = str(item.value)
                pass
            except:
                # Locals with failing memory access.
1028
                # FIXME: Isn't this taken care off by the SubItem destructor?
1029
                with SubItem(self):
1030 1031 1032
                    self.put('iname="%s",' % item.iname)
                    self.put('name="%s",' % item.name)
                    self.put('addr="<not accessible>",')
hjk's avatar
hjk committed
1033
                    self.put('numchild="0"')
1034 1035
                    self.putValue("<not accessible>")
                    self.putType(item.value.type)
1036 1037 1038 1039 1040 1041 1042 1043
                continue

            type = item.value.type
            if type.code == gdb.TYPE_CODE_PTR \
                    and item.name == "argv" and str(type) == "char **":
                # Special handling for char** argv.
                n = 0
                p = item.value
1044 1045 1046 1047 1048 1049 1050 1051
                # p is 0 for "optimized out" cases. Or contains rubbish.
                try:
                    if not isNull(p):
                        while not isNull(p.dereference()) and n <= 100:
                            p += 1
                            n += 1
                except:
                    pass
1052

1053
                with SubItem(self):
1054 1055
                    self.put('iname="%s",' % item.iname)
                    self.putName(item.name)
1056
                    self.putItemCount(n, 100)
1057 1058 1059 1060 1061 1062 1063
                    self.putType(type)
                    self.putNumChild(n)
                    if self.isExpanded(item):
                        p = item.value
                        with Children(self, n):
                            for i in xrange(n):
                                value = p.dereference()
1064
                                self.putSubItem(Item(value, item.iname, i, None))
1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075
                                p += 1
                            if n > 100:
                                self.putEllipsis()

            else:
                # A "normal" local variable or parameter.
                try:
                   addr = cleanAddress(item.value.address)
                   with SubItem(self):
                       self.put('iname="%s",' % item.iname)
                       self.put('addr="%s",' % addr)
1076
                       self.putItem(item)
1077 1078 1079
                except AttributeError:
                    # Thrown by cleanAddress with message "'NoneType' object
                    # has no attribute 'cast'" for optimized-out values.
1080
                    with SubItem(self):
1081 1082 1083
                        self.put('iname="%s",' % item.iname)
                        self.put('name="%s",' % item.name)
                        self.put('addr="<optimized out>",')
1084 1085
                        self.putValue("<optimized out>")
                        self.putType(item.value.type)
1086 1087 1088 1089 1090 1091 1092 1093

        #
        # Watchers
        #
        with OutputSafer(self, ",", ""):
            if len(watchers) > 0:
                for watcher in watchers.split("##"):
                    (exp, iname) = watcher.split("#")
1094
                    self.handleWatch(exp, iname)
1095

1096
        #print('data=[' + locals + sep + watchers + ']\n')
1097

hjk's avatar
hjk committed
1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111
    def checkForQObjectBase(self, type):
        if type.code != gdb.TYPE_CODE_STRUCT:
            return False
        name = str(type)
        if name in qqQObjectCache:
            return qqQObjectCache[name]
        if name == self.ns + "QObject":
            qqQObjectCache[name] = True
            return True
        fields = type.strip_typedefs().fields()
        if len(fields) == 0:
            qqQObjectCache[name] = False
            return False
        base = fields[0].type.strip_typedefs()
hjk's avatar