dumper.py 55.3 KB
Newer Older
hjk's avatar
hjk committed
1
import sys
2
import base64
3
import __builtin__
4
import os
hjk's avatar
hjk committed
5
import tempfile
6

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

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

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

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

45 46 47 48 49
try:
    import binascii
except:
    pass

hjk's avatar
hjk committed
50 51 52
verbosity = 0
verbosity = 1

53 54 55 56
# Some "Enums"

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

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


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

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

96 97
typeCache = {}

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

typeInfoCache = {}

105 106
def lookupType(typestring):
    type = typeCache.get(typestring)
hjk's avatar
hjk committed
107
    #warn("LOOKUP 1: %s -> %s" % (typestring, type))
108 109 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
    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
137 138 139
        if not type is None:
            type = type.pointer()
            typeCache[typestring] = type
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
            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)
156
        pass
157 158 159

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

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

171 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
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):
201 202 203 204 205 206
    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<...>"
207
        return lookupType(extractTemplateArgument(type.strip_typedefs(), position))
208

209

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

219

220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
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
239
        self.d.output = []
240 241 242 243 244 245 246

    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
247 248
            self.savedOutput.extend(self.d.output)
            self.d.output = self.savedOutput
249 250 251
        return False


252 253 254 255 256
class NoAddress:
    def __init__(self, d):
        self.d = d

    def __enter__(self):
hjk's avatar
hjk committed
257 258
        self.savedPrintsAddress = self.d.currentPrintsAddress
        self.d.currentPrintsAddress = False
259 260

    def __exit__(self, exType, exValue, exTraceBack):
hjk's avatar
hjk committed
261
        self.d.currentPrintsAddress = self.savedPrintsAddress
262 263


264
class SubItem:
hjk's avatar
hjk committed
265
    def __init__(self, d, component):
266
        self.d = d
hjk's avatar
hjk committed
267 268
        self.iname = "%s.%s" % (d.currentIName, component)
        self.name = component
269 270 271

    def __enter__(self):
        self.d.put('{')
hjk's avatar
hjk committed
272 273 274 275
        #if not self.name is None:
        if isinstance(self.name, str):
            self.d.put('name="%s",' % self.name)
        self.savedIName = self.d.currentIName
276 277 278 279 280
        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
281
        self.d.currentIName = self.iname
282
        self.d.currentValuePriority = -100
283 284
        self.d.currentValueEncoding = None
        self.d.currentType = ""
285
        self.d.currentTypePriority = -100
286 287 288 289 290 291

    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)
292
        try:
293
            #warn("TYPE VALUE: %s" % self.d.currentValue)
hjk's avatar
hjk committed
294 295 296 297 298 299 300 301
            typeName = stripClassTag(self.d.currentType)
            #warn("TYPE: '%s'  DEFAULT: '%s' % (typeName, self.d.currentChildType))

            if len(typeName) > 0 and typeName != self.d.currentChildType:
                self.d.put('type="%s",' % typeName) # str(type.unqualified()) ?
                if not typeName in typeInfoCache \
                        and typeName != " ": # FIXME: Move to lookupType
                    typeObj = lookupType(typeName)
302
                    if not typeObj is None:
hjk's avatar
hjk committed
303 304 305 306 307 308
                        typeInfoCache[typeName] = TypeInfo(typeObj)
            if  self.d.currentValue is None:
                self.d.put('value="<not accessible>",numchild="0",')
            else:
                if not self.d.currentValueEncoding is None:
                    self.d.put('valueencoded="%d",' % self.d.currentValueEncoding)
309
                self.d.put('value="%s",' % self.d.currentValue)
310 311
        except:
            pass
312
        self.d.put('},')
hjk's avatar
hjk committed
313
        self.d.currentIName = self.savedIName
314 315 316 317 318 319 320
        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

hjk's avatar
hjk committed
321 322 323 324 325 326 327 328 329 330 331
class TopLevelItem(SubItem):
    def __init__(self, d, iname):
        self.d = d
        self.iname = iname
        self.name = None

class UnnamedSubItem(SubItem):
    def __init__(self, d, component):
        self.d = d
        self.iname = "%s.%s" % (self.d.currentIName, component)
        self.name = None
332 333

class Children:
hjk's avatar
hjk committed
334 335
    def __init__(self, d, numChild = 1, childType = None, childNumChild = None,
            maxNumChild = None, addrBase = None, addrStep = None):
336 337 338
        self.d = d
        self.numChild = numChild
        self.childNumChild = childNumChild
hjk's avatar
hjk committed
339 340 341 342 343 344 345 346 347 348
        self.maxNumChild = maxNumChild
        self.addrBase = addrBase
        self.addrStep = addrStep
        self.printsAddress = True
        if not childType is None:
            self.childType = stripClassTag(str(childType))
            self.d.put('childtype="%s",' % self.childType)
            if isSimpleType(childType):
                self.d.put('childnumchild="0",')
                self.childNumChild = 0
349
            elif childType.code == PointerCode:
hjk's avatar
hjk committed
350 351 352 353 354 355 356 357 358 359 360
                self.d.put('childnumchild="1",')
                self.childNumChild = 1
        else:
            self.childType = None
        try:
            if not addrBase is None and not addrStep is None:
                self.d.put('addrbase="0x%x",' % long(addrBase))
                self.d.put('addrstep="0x%x",' % long(addrStep))
                self.printsAddress = False
        except:
            warn("ADDRBASE: %s" % addrBase)
361 362 363 364 365
        #warn("CHILDREN: %s %s %s" % (numChild, childType, childNumChild))

    def __enter__(self):
        self.savedChildType = self.d.currentChildType
        self.savedChildNumChild = self.d.currentChildNumChild
hjk's avatar
hjk committed
366 367 368 369 370 371 372 373
        self.savedNumChild = self.d.currentNumChild
        self.savedMaxNumChild = self.d.currentMaxNumChild
        self.savedPrintsAddress = self.d.currentPrintsAddress
        self.d.currentChildType = self.childType
        self.d.currentChildNumChild = self.childNumChild
        self.d.currentNumChild = self.numChild
        self.d.currentMaxNumChild = self.maxNumChild
        self.d.currentPrintsAddress = self.printsAddress
374 375 376 377 378
        self.d.put("children=[")

    def __exit__(self, exType, exValue, exTraceBack):
        if self.d.passExceptions and not exType is None:
            showException("CHILDREN", exType, exValue, exTraceBack)
hjk's avatar
hjk committed
379 380 381
        if not self.d.currentMaxNumChild is None:
            if self.d.currentMaxNumChild < self.d.currentNumChild:
                self.d.put('{name="<incomplete>",value="",type="",numchild="0"},')
382 383
        self.d.currentChildType = self.savedChildType
        self.d.currentChildNumChild = self.savedChildNumChild
hjk's avatar
hjk committed
384 385 386
        self.d.currentNumChild = self.savedNumChild
        self.d.currentMaxNumChild = self.savedMaxNumChild
        self.d.currentPrintsAddress = self.savedPrintsAddress
387 388 389 390
        self.d.put('],')
        return True


391
def value(expr):
392
    value = parseAndEvaluate(expr)
393 394 395 396 397
    try:
        return int(value)
    except:
        return str(value)

hjk's avatar
hjk committed
398
def isSimpleType(typeobj):
399
    code = typeobj.code
400 401 402 403 404
    return code == BoolCode \
        or code == CharCode \
        or code == IntCode \
        or code == FloatCode \
        or code == EnumCode
hjk's avatar
hjk committed
405 406

def warn(message):
407 408
    if True or verbosity > 0:
        print "XXX: %s\n" % message.encode("latin1")
hjk's avatar
hjk committed
409 410 411 412 413 414
    pass

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

415 416 417 418 419
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
420
#def couldBePointer(p, align):
421
#    type = lookupType("unsigned int")
hjk's avatar
hjk committed
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
#    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):
441 442 443 444
    # 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 ")
445 446 447 448 449 450
    #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
451 452

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

def stripClassTag(typeName):
    if typeName.startswith("class "):
        return typeName[6:]
    if typeName.startswith("struct "):
        return typeName[7:]
    if typeName.startswith("const "):
        return typeName[6:]
    if typeName.startswith("volatile "):
        return typeName[9:]
    return typeName
hjk's avatar
hjk committed
473 474

def checkPointerRange(p, n):
475
    for i in xrange(n):
hjk's avatar
hjk committed
476 477 478
        checkPointer(p)
        ++p

hjk's avatar
hjk committed
479 480 481 482 483 484 485 486 487 488 489 490 491
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
492
    type = stripClassTag(str(value.type))
493
    if type.find(":") >= 0:
hjk's avatar
hjk committed
494
        type = "'" + type + "'"
495
    # 'class' is needed, see http://sourceware.org/bugzilla/show_bug.cgi?id=11912
hjk's avatar
hjk committed
496
    exp = "((class %s*)%s)->%s(%s)" % (type, value.address, func, arg)
hjk's avatar
hjk committed
497
    #warn("CALL: %s" % exp)
498 499 500 501 502
    result = None
    try:
        result = parseAndEvaluate(exp)
    except:
        pass
hjk's avatar
hjk committed
503 504 505
    #warn("  -> %s" % result)
    return result

hjk's avatar
hjk committed
506 507 508
def call(value, func, *args):
    return call2(value, func, args)

509 510 511 512
def makeValue(type, init):
    type = stripClassTag(type)
    if type.find(":") >= 0:
        type = "'" + type + "'"
513 514
    # Avoid malloc symbol clash with QVector
    gdb.execute("set $d = (%s*)calloc(sizeof(%s), 1)" % (type, type))
515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531
    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

532 533
qqNs = None

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

554 555 556 557 558 559 560 561 562 563 564 565 566 567 568
# --  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

569 570
def findFirstZero(p, maximum):
    for i in xrange(maximum):
571 572 573
        if p.dereference() == 0:
            return i
        p = p + 1
574
    return maximum + 1
575

576
def extractCharArray(p, maxsize):
577
    t = lookupType("unsigned char").pointer()
578
    p = p.cast(t)
579
    limit = findFirstZero(p, maxsize)
580 581 582 583
    s = ""
    for i in xrange(limit):
        s += "%c" % int(p.dereference())
        p += 1
584
    if i > maxsize:
585 586 587 588 589 590 591 592 593 594 595 596 597
        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
598
    return extractCharArray(data, min(100, size))
599

600
def encodeCharArray(p, maxsize, limit = -1):
601
    t = lookupType("unsigned char").pointer()
602
    p = p.cast(t)
603 604
    if limit == -1:
        limit = findFirstZero(p, maxsize)
605
    s = ""
606 607 608 609 610 611 612 613
    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
614
    if limit > maxsize:
615 616 617 618
        s += "2e2e2e"
    return s

def encodeChar2Array(p, maxsize):
619
    t = lookupType("unsigned short").pointer()
620
    p = p.cast(t)
621
    limit = findFirstZero(p, maxsize)
622 623 624 625 626 627 628 629 630
    s = ""
    for i in xrange(limit):
        s += "%04x" % int(p.dereference())
        p += 1
    if i == maxsize:
        s += "2e002e002e00"
    return s

def encodeChar4Array(p, maxsize):
631
    t = lookupType("unsigned int").pointer()
632
    p = p.cast(t)
633
    limit = findFirstZero(p, maxsize)
634 635 636 637
    s = ""
    for i in xrange(limit):
        s += "%08x" % int(p.dereference())
        p += 1
638
    if i > maxsize:
639
        s += "2e0000002e0000002e000000"
640 641
    return s

642 643 644 645 646 647 648 649 650 651 652 653
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']
654
        charPointerType = lookupType('char *')
hjk's avatar
hjk committed
655 656
        data = qByteArrayData['d'].cast(charPointerType) \
             + qByteArrayData['offset'] + charPointerType.sizeof
657 658
        return data, size, alloc

659
def encodeByteArray(value):
660
    data, size, alloc = qByteArrayData(value)
661 662 663 664
    check(0 <= size and size <= alloc and alloc <= 100*1000*1000)
    if size > 0:
        checkAccess(data, 4)
        checkAccess(data + size) == 0
665
    return encodeCharArray(data, 100, size)
666

667 668 669 670 671 672 673
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()
674 675
        ushortPointerType = lookupType('ushort *')
        data = qStringData['d'].cast(ushortPointerType) + ushortPointerType.sizeof / 2 + qStringData['offset']
676 677
        return data, qStringData['size'], qStringData['alloc']

678
def encodeString(value):
679 680
    data, size, alloc = qQStringData(value)

681 682 683
    check(0 <= size and size <= alloc and alloc <= 100*1000*1000)
    if size > 0:
        checkAccess(data, 4)
hjk's avatar
hjk committed
684
        checkAccess(data + size) == 0
685
    s = ""
686
    limit = min(size, 1000)
687 688 689
    try:
        # gdb.Inferior is new in gdb 7.2
        inferior = gdb.inferiors()[0]
690
        s = binascii.hexlify(inferior.read_memory(data, 2 * limit))
691
    except:
692
        p = data
693
        for i in xrange(limit):
694 695 696 697
            val = int(p.dereference())
            s += "%02x" % (val % 256)
            s += "%02x" % (val / 256)
            p += 1
698 699
    if limit < size:
        s += "2e002e002e00"
700 701
    return s

hjk's avatar
hjk committed
702 703
def stripTypedefs(type):
    type = type.unqualified()
hjk's avatar
hjk committed
704
    while type.code == TypedefCode:
705 706 707
        type = type.strip_typedefs().unqualified()
    return type

hjk's avatar
hjk committed
708 709
def extractFields(type):
    # Insufficient, see http://sourceware.org/bugzilla/show_bug.cgi?id=10953:
hjk's avatar
hjk committed
710
    #fields = type.fields()
hjk's avatar
hjk committed
711
    # Insufficient, see http://sourceware.org/bugzilla/show_bug.cgi?id=11777:
hjk's avatar
hjk committed
712
    #fields = defsype).fields()
hjk's avatar
hjk committed
713
    # This seems to work.
hjk's avatar
hjk committed
714
    #warn("TYPE 0: %s" % type)
hjk's avatar
hjk committed
715
    type = stripTypedefs(type)
716 717 718
    fields = type.fields()
    if len(fields):
        return fields
hjk's avatar
hjk committed
719
    #warn("TYPE 1: %s" % type)
720
    # This fails for arrays. See comment in lookupType.
721 722 723
    type0 = lookupType(str(type))
    if not type0 is None:
        type = type0
hjk's avatar
hjk committed
724
    if type.code == FunctionCode:
725
        return []
hjk's avatar
hjk committed
726 727
    #warn("TYPE 2: %s" % type)
    fields = type.fields()
hjk's avatar
hjk committed
728
    #warn("FIELDS: %s" % fields)
hjk's avatar
hjk committed
729 730
    return fields

hjk's avatar
hjk committed
731 732
#######################################################################
#
733
# LocalItem
hjk's avatar
hjk committed
734 735 736
#
#######################################################################

737
# Contains iname, name, and value.
hjk's avatar
hjk committed
738
class LocalItem:
739
    pass
hjk's avatar
hjk committed
740

741 742 743 744 745 746
#######################################################################
#
# SetupCommand
#
#######################################################################

747
# This is a cache mapping from 'type name' to 'display alternatives'.
748
qqFormats = {}
749 750

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

753 754 755
# This is a cache of all dumpers that support writing.
qqEditable = {}

756 757 758 759 760
# 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
761
qqQObjectCache = {}
762

763
def bbsetup(args):
764 765 766 767 768
    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
769
            qqFormats[name] = qqFormats.get(name, "")
770 771 772 773 774 775 776 777
        elif key.startswith("qform__"):
            name = key[7:]
            formats = ""
            try:
                formats = value()
            except:
                pass
            qqFormats[name] = formats
778 779 780 781 782 783
        elif key.startswith("qedit__"):
            name = key[7:]
            try:
                qqEditable[name] = value
            except:
                pass
784
    result = "dumpers=["
785
    #qqNs = qtNamespace() # This is too early
786
    for key, value in qqFormats.items():
787 788 789 790
        if qqEditable.has_key(key):
            result += '{type="%s",formats="%s",editable="true"},' % (key, value)
        else:
            result += '{type="%s",formats="%s"},' % (key, value)
791 792
    result += ']'
    #result += ',namespace="%s"' % qqNs
793
    result += ',hasInferiorThreadList="%s"' % int(hasInferiorThreadList())
794 795
    return result

796 797
registerCommand("bbsetup", bbsetup)

798

799 800 801 802 803 804 805
#######################################################################
#
# Edit Command
#
#######################################################################

def bbedit(args):
806 807
    (type, expr, value) = args.split(",")
    type = base64.b16decode(type, True)
808
    ns = qtNamespace()
809 810
    if type.startswith(ns):
        type = type[len(ns):]
811
    type = type.replace("::", "__")
812 813 814 815 816 817
    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))
818 819 820
    if qqEditable.has_key(type):
        qqEditable[type](expr, value)

821
registerCommand("bbedit", bbedit)
822 823


hjk's avatar
hjk committed
824 825
#######################################################################
#
826
# Frame Command
hjk's avatar
hjk committed
827 828 829
#
#######################################################################

830
def bb(args):
hjk's avatar
hjk committed
831
    output = 'data=[' + "".join(Dumper(args).output) + '],typeinfo=['
832 833 834 835 836 837 838
    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
839

840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857
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
858 859 860 861 862 863 864

#######################################################################
#
# The Dumper Class
#
#######################################################################

865

hjk's avatar
hjk committed
866
class Dumper:
867
    def __init__(self, args):
hjk's avatar
hjk committed
868
        self.output = []
hjk's avatar
hjk committed
869 870
        self.currentIName = ""
        self.currentPrintsAddress = True
871 872
        self.currentChildType = ""
        self.currentChildNumChild = -1
hjk's avatar
hjk committed
873 874
        self.currentMaxNumChild = -1
        self.currentNumChild = -1
875 876 877 878 879
        self.currentValue = None
        self.currentValuePriority = -100
        self.currentValueEncoding = None
        self.currentType = None
        self.currentTypePriority = -100
880 881 882 883 884 885 886 887
        self.typeformats = {}
        self.formats = {}
        self.expandedINames = ""

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

888
        resultVarName = ""
889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916
        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
917
        self.partialUpdate = "partial" in options
918 919
        self.tooltipOnly = "tooltiponly" in options
        self.noLocals = "nolocals" in options
920
        self.ns = qtNamespace()
921 922 923 924

        #warn("NAMESPACE: '%s'" % self.ns)
        #warn("VARIABLES: %s" % varList)
        #warn("EXPANDED INAMES: %s" % self.expandedINames)
925
        #warn("WATCHERS: %s" % watchers)
926 927
        #warn("PARTIAL: %s" % self.partialUpdate)
        #warn("NO LOCALS: %s" % self.noLocals)
928 929 930 931 932
        module = sys.modules[__name__]

        #
        # Locals
        #
933
        locals = []
934
        fullUpdateNeeded = True
935
        if self.partialUpdate and len(varList) == 1 and not self.tooltipOnly:
936 937 938 939 940 941 942 943
            #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()
hjk's avatar
hjk committed
944 945 946
                item = LocalItem()
                item.iname = "local." + name
                item.name = name
947 948 949 950 951 952 953 954
                item.value = frame.read_var(name)
                locals = [item]
                #warn("PARTIAL LOCALS: %s" % locals)
                fullUpdateNeeded = False
            except:
                pass
            varList = []

955
        if fullUpdateNeeded and not self.tooltipOnly and not self.noLocals:
956
            locals = listOfLocals(varList)
957 958 959 960

        # Take care of the return value of the last function call.
        if len(resultVarName) > 0:
            try:
hjk's avatar
hjk committed
961 962 963 964 965
                item = LocalItem()
                item.name = resultVarName
                item.iname = "return." + resultVarName
                item.value = parseAndEvaluate(resultVarName)
                locals.append(item)
966 967 968 969 970
            except:
                # Don't bother. It's only supplementary information anyway.
                pass

        for item in locals:
hjk's avatar
hjk committed
971 972 973 974 975 976 977
            value = upcast(item.value)
            with OutputSafer(self, "", ""):
                self.anonNumber = -1

                type = value.type.unqualified()
                typeName = str(type)

978
                # Special handling for char** argv.
979
                if type.code == PointerCode \
hjk's avatar
hjk committed
980 981 982 983 984 985 986 987
                        and item.iname == "local.argv" \
                        and typeName == "char **":
                    n = 0
                    p = value
                    # p is 0 for "optimized out" cases. Or contains rubbish.
                    try:
                        if not isNull(p):
                            while not isNull(p.dereference()) and n <= 100:
988
                                p += 1
hjk's avatar
hjk committed
989 990 991
                                n += 1
                    except:
                        pass
992

hjk's avatar
hjk committed
993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008
                    with TopLevelItem(self, item.iname):
                        self.put('iname="local.argv",name="argv",')
                        self.putItemCount(n, 100)
                        self.putType(typeName)
                        self.putNumChild(n)
                        if self.currentIName in self.expandedINames:
                            p = value
                            with Children(self, n):
                                for i in xrange(n):
                                    self.putSubItem(i, p.dereference())
                                    p += 1
                    continue

                else:
                    # A "normal" local variable or parameter.
                    with TopLevelItem(self, item.iname):
1009 1010
                        self.put('iname="%s",' % item.iname)
                        self.put('name="%s",' % item.name)
hjk's avatar
hjk committed
1011
                        self.putItem(value)
1012 1013 1014 1015 1016 1017 1018 1019

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

1022
        #print('data=[' + locals + sep + watchers + ']\n')
1023

hjk's avatar
hjk committed
1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035
    def checkForQObjectBase(self, type):
        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
hjk committed
1036 1037
        if base.code != StructCode:
            return False
1038 1039 1040
        # Prevent infinite recursion in Qt 3.3.8
        if str(base) == name:
            return False
hjk's avatar
hjk committed
1041 1042 1043 1044
        result = self.checkForQObjectBase(base)
        qqQObjectCache[name] = result
        return result

1045 1046 1047

    def handleWatch(self, exp, iname):
        exp = str(exp)
1048
        escapedExp = base64.b64encode(exp);
1049 1050 1051
        #warn("HANDLING WATCH %s, INAME: '%s'" % (exp, iname))
        if exp.startswith("[") and exp.endswith("]"):
            #warn("EVAL: EXP: %s" % exp)
hjk's avatar
hjk committed
1052
            with TopLevelItem(self, iname):