gdbbridge.py 52.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
############################################################################
#
# Copyright (C) 2016 The Qt Company Ltd.
# Contact: https://www.qt.io/licensing/
#
# This file is part of Qt Creator.
#
# Commercial License Usage
# Licensees holding valid commercial Qt licenses may use this file in
# accordance with the commercial license agreement provided with the
# Software or, alternatively, in accordance with the terms contained in
# a written agreement between you and The Qt Company. For licensing terms
# and conditions see https://www.qt.io/terms-conditions. For further
# information use the contact form at https://www.qt.io/contact-us.
#
# GNU General Public License Usage
# Alternatively, this file may be used under the terms of the GNU
# General Public License version 3 as published by the Free Software
# Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
# included in the packaging of this file. Please review the following
# information to ensure the GNU General Public License requirements will
# be met: https://www.gnu.org/licenses/gpl-3.0.html.
#
############################################################################
hjk's avatar
hjk committed
25

26 27 28 29 30
try:
    import __builtin__
except:
    import builtins

hjk's avatar
hjk committed
31
import gdb
hjk's avatar
hjk committed
32
import os
33
import os.path
34
import sys
35
import struct
hjk's avatar
hjk committed
36
import tempfile
37
import types
38 39

from dumper import *
40

41 42 43 44 45 46 47

#######################################################################
#
# Infrastructure
#
#######################################################################

48
def safePrint(output):
49 50 51
    try:
        print(output)
    except:
hjk's avatar
hjk committed
52
        out = ''
53 54 55
        for c in output:
            cc = ord(c)
            if cc > 127:
hjk's avatar
hjk committed
56
                out += '\\\\%d' % cc
57
            elif cc < 0:
hjk's avatar
hjk committed
58
                out += '\\\\%d' % (cc + 256)
59 60 61 62 63 64 65 66 67 68
            else:
                out += c
        print(out)

def registerCommand(name, func):

    class Command(gdb.Command):
        def __init__(self):
            super(Command, self).__init__(name, gdb.COMMAND_OBSCURE)
        def invoke(self, args, from_tty):
69
            safePrint(func(args))
70 71 72 73 74 75 76 77 78 79 80 81 82 83

    Command()



#######################################################################
#
# Convenience
#
#######################################################################

# Just convienience for 'python print ...'
class PPCommand(gdb.Command):
    def __init__(self):
hjk's avatar
hjk committed
84
        super(PPCommand, self).__init__('pp', gdb.COMMAND_OBSCURE)
85 86 87 88 89 90 91 92
    def invoke(self, args, from_tty):
        print(eval(args))

PPCommand()

# Just convienience for 'python print gdb.parse_and_eval(...)'
class PPPCommand(gdb.Command):
    def __init__(self):
hjk's avatar
hjk committed
93
        super(PPPCommand, self).__init__('ppp', gdb.COMMAND_OBSCURE)
94 95 96 97 98 99 100
    def invoke(self, args, from_tty):
        print(gdb.parse_and_eval(args))

PPPCommand()


def scanStack(p, n):
101
    p = int(p)
102 103
    r = []
    for i in xrange(n):
hjk's avatar
hjk committed
104 105 106
        f = gdb.parse_and_eval('{void*}%s' % p)
        m = gdb.execute('info symbol %s' % f, to_string=True)
        if not m.startswith('No symbol matches'):
107 108 109 110 111 112
            r.append(m)
        p += f.type.sizeof
    return r

class ScanStackCommand(gdb.Command):
    def __init__(self):
hjk's avatar
hjk committed
113
        super(ScanStackCommand, self).__init__('scanStack', gdb.COMMAND_OBSCURE)
114 115 116
    def invoke(self, args, from_tty):
        if len(args) == 0:
            args = 20
hjk's avatar
hjk committed
117
        safePrint(scanStack(gdb.parse_and_eval('$sp'), int(args)))
118 119 120

ScanStackCommand()

hjk's avatar
hjk committed
121

122 123 124 125 126 127 128 129 130
#######################################################################
#
# Import plain gdb pretty printers
#
#######################################################################

class PlainDumper:
    def __init__(self, printer):
        self.printer = printer
131
        self.typeCache = {}
132 133

    def __call__(self, d, value):
134 135 136 137
        try:
            printer = self.printer.gen_printer(value)
        except:
            printer = self.printer.invoke(value)
hjk's avatar
hjk committed
138
        lister = getattr(printer, 'children', None)
139 140
        children = [] if lister is None else list(lister())
        d.putType(self.printer.name)
141 142 143
        val = printer.to_string()
        if isinstance(val, str):
            d.putValue(val)
144 145
        elif sys.version_info[0] <= 2 and isinstance(val, unicode):
            d.putValue(val)
146
        else: # Assuming LazyString
147
            d.putCharArrayHelper(val.address, val.length, val.type)
148

149 150 151 152 153 154 155
        d.putNumChild(len(children))
        if d.isExpanded():
            with Children(d):
                for child in children:
                    d.putSubItem(child[0], child[1])

def importPlainDumpers(args):
hjk's avatar
hjk committed
156
    if args == 'off':
157
        try:
hjk's avatar
hjk committed
158
            gdb.execute('disable pretty-printer .* .*')
159 160
        except:
            # Might occur in non-ASCII directories
hjk's avatar
hjk committed
161
            warn('COULD NOT DISABLE PRETTY PRINTERS')
162 163
    else:
        theDumper.importPlainDumpers()
164

hjk's avatar
hjk committed
165
registerCommand('importPlainDumpers', importPlainDumpers)
166 167


168 169 170 171 172 173 174

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

    def __enter__(self):
        self.savedOutput = self.d.output
175
        self.d.output = ''
176 177 178

    def __exit__(self, exType, exValue, exTraceBack):
        if self.d.passExceptions and not exType is None:
hjk's avatar
hjk committed
179
            showException('OUTPUTSAFER', exType, exValue, exTraceBack)
180 181
            self.d.output = self.savedOutput
        else:
182
            self.savedOutput += self.d.output
183 184 185 186 187 188 189 190 191 192 193 194
            self.d.output = self.savedOutput
        return False



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


195 196
class Dumper(DumperBase):

197
    def __init__(self):
198 199
        DumperBase.__init__(self)

200
        # These values will be kept between calls to 'fetchVariables'.
201
        self.isGdb = True
202
        self.typeCache = {}
203
        self.interpreterBreakpointResolvers = []
204

205
    def prepare(self, args):
206
        self.output = ''
207
        self.setVariableFetchingOptions(args)
208

209
    def fromFrameValue(self, nativeValue):
hjk's avatar
hjk committed
210
        #warn('FROM FRAME VALUE: %s' % nativeValue.address)
211
        val = nativeValue
212 213 214 215
        try:
           val = nativeValue.cast(nativeValue.dynamic_type)
        except:
           pass
216
        return self.fromNativeValue(val)
217 218

    def fromNativeValue(self, nativeValue):
hjk's avatar
hjk committed
219
        #warn('FROM NATIVE VALUE: %s' % nativeValue)
220
        self.check(isinstance(nativeValue, gdb.Value))
221
        nativeType = nativeValue.type
222 223
        code = nativeType.code
        if code == gdb.TYPE_CODE_REF:
224
            targetType = self.fromNativeType(nativeType.target().unqualified())
225
            val = self.createReferenceValue(toInteger(nativeValue.address), targetType)
226
            val.nativeValue = nativeValue
hjk's avatar
hjk committed
227
            #warn('CREATED REF: %s' % val)
228 229
            return val
        if code == gdb.TYPE_CODE_PTR:
230 231 232 233
            try:
                nativeTargetValue = nativeValue.dereference()
            except:
                nativeTargetValue = None
234
            targetType = self.fromNativeType(nativeType.target().unqualified())
235
            val = self.createPointerValue(toInteger(nativeValue), targetType)
236
            val.nativeValue = nativeValue
hjk's avatar
hjk committed
237
            #warn('CREATED PTR 1: %s' % val)
238 239
            if not nativeValue.address is None:
                val.laddress = toInteger(nativeValue.address)
hjk's avatar
hjk committed
240
            #warn('CREATED PTR 2: %s' % val)
241 242 243
            return val
        if code == gdb.TYPE_CODE_TYPEDEF:
            targetType = nativeType.strip_typedefs().unqualified()
hjk's avatar
hjk committed
244
            #warn('TARGET TYPE: %s' % targetType)
245 246 247
            if targetType.code == gdb.TYPE_CODE_ARRAY:
                val = self.Value(self)
                val.laddress = toInteger(nativeValue.address)
248
                val.nativeValue = nativeValue
249 250 251
            else:
                # Cast may fail (e.g for arrays, see test for Bug5799)
                val = self.fromNativeValue(nativeValue.cast(targetType))
252 253
            val.type = self.fromNativeType(nativeType)
            val.nativeValue = nativeValue
hjk's avatar
hjk committed
254
            #warn('CREATED TYPEDEF: %s' % val)
255 256
            return val

257
        val = self.Value(self)
258
        val.nativeValue = nativeValue
259 260
        if not nativeValue.address is None:
            val.laddress = toInteger(nativeValue.address)
261 262
        else:
            size = nativeType.sizeof
hjk's avatar
hjk committed
263
            chars = self.lookupNativeType('unsigned char')
264 265 266
            y = nativeValue.cast(chars.array(0, int(nativeType.sizeof - 1)))
            buf = bytearray(struct.pack('x' * size))
            for i in range(size):
267 268 269 270
                try:
                    buf[i] = int(y[i])
                except:
                    pass
271 272
            val.ldata = bytes(buf)

273
        val.type = self.fromNativeType(nativeType)
274
        val.lIsInScope = not nativeValue.is_optimized_out
275 276 277 278 279 280 281 282
        code = nativeType.code
        if code == gdb.TYPE_CODE_ENUM:
            val.ldisplay = str(nativeValue)
            intval = int(nativeValue)
            if val.ldisplay != intval:
                val.ldisplay += ' (%s)' % intval
        elif code == gdb.TYPE_CODE_COMPLEX:
            val.ldisplay = str(nativeValue)
283 284
        #elif code == gdb.TYPE_CODE_ARRAY:
        #    val.type.ltarget = nativeValue[0].type.unqualified()
285 286
        return val

287 288 289 290 291
    def ptrSize(self):
        result = gdb.lookup_type('void').pointer().sizeof
        self.ptrSize = lambda: result
        return result

292
    def fromNativeType(self, nativeType):
293
        self.check(isinstance(nativeType, gdb.Type))
294 295
        code = nativeType.code
        #warn('FROM NATIVE TYPE: %s' % nativeType)
296
        nativeType = nativeType.unqualified()
297 298 299

        if code == gdb.TYPE_CODE_PTR:
            #warn('PTR')
300
            targetType = self.fromNativeType(nativeType.target().unqualified())
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
            return self.createPointerType(targetType)

        if code == gdb.TYPE_CODE_REF:
            #warn('REF')
            targetType = self.fromNativeType(nativeType.target().unqualified())
            return self.createReferenceType(targetType)

        if code == gdb.TYPE_CODE_ARRAY:
            #warn('ARRAY')
            nativeTargetType = nativeType.target().unqualified()
            targetType = self.fromNativeType(nativeTargetType)
            count = nativeType.sizeof // nativeTargetType.sizeof
            return self.createArrayType(targetType, count)

        if code == gdb.TYPE_CODE_TYPEDEF:
            #warn('TYPEDEF')
            nativeTargetType = nativeType.unqualified()
            while nativeTargetType.code == gdb.TYPE_CODE_TYPEDEF:
                nativeTargetType = nativeTargetType.strip_typedefs().unqualified()
            targetType = self.fromNativeType(nativeTargetType)
321 322
            return self.createTypedefedType(targetType, str(nativeType),
                                            self.nativeTypeId(nativeType))
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355

        if code == gdb.TYPE_CODE_ERROR:
            warn('Type error: %s' % nativeType)
            return self.Type(self, '')

        typeId = self.nativeTypeId(nativeType)
        res = self.typeData.get(typeId, None)
        if res is None:
            tdata = self.TypeData(self)
            tdata.name = str(nativeType)
            tdata.typeId = typeId
            tdata.lbitsize = nativeType.sizeof * 8
            tdata.code = {
                #gdb.TYPE_CODE_TYPEDEF : TypeCodeTypedef, # Handled above.
                gdb.TYPE_CODE_METHOD : TypeCodeFunction,
                gdb.TYPE_CODE_VOID : TypeCodeVoid,
                gdb.TYPE_CODE_FUNC : TypeCodeFunction,
                gdb.TYPE_CODE_METHODPTR : TypeCodeFunction,
                gdb.TYPE_CODE_MEMBERPTR : TypeCodeFunction,
                #gdb.TYPE_CODE_PTR : TypeCodePointer,  # Handled above.
                #gdb.TYPE_CODE_REF : TypeCodeReference,  # Handled above.
                gdb.TYPE_CODE_BOOL : TypeCodeIntegral,
                gdb.TYPE_CODE_CHAR : TypeCodeIntegral,
                gdb.TYPE_CODE_INT : TypeCodeIntegral,
                gdb.TYPE_CODE_FLT : TypeCodeFloat,
                gdb.TYPE_CODE_ENUM : TypeCodeEnum,
                #gdb.TYPE_CODE_ARRAY : TypeCodeArray,
                gdb.TYPE_CODE_STRUCT : TypeCodeStruct,
                gdb.TYPE_CODE_UNION : TypeCodeStruct,
                gdb.TYPE_CODE_COMPLEX : TypeCodeComplex,
                gdb.TYPE_CODE_STRING : TypeCodeFortranString,
            }[code]
            if tdata.code == TypeCodeEnum:
356
                tdata.enumDisplay = lambda intval, addr : \
357 358 359
                    self.nativeTypeEnumDisplay(nativeType, intval, 0)
                tdata.enumHexDisplay = lambda intval, addr : \
                    self.nativeTypeEnumDisplay(nativeType, intval, 1)
360 361 362
            if tdata.code == TypeCodeStruct:
                tdata.lalignment = lambda : \
                    self.nativeStructAlignment(nativeType)
363 364
                tdata.lfields = lambda value : \
                    self.listMembers(value, nativeType)
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
            tdata.templateArguments = self.listTemplateParameters(nativeType)
            self.registerType(typeId, tdata) # Fix up fields and template args
        #    warn('CREATE TYPE: %s' % typeId)
        #else:
        #    warn('REUSE TYPE: %s' % typeId)
        return self.Type(self, typeId)

    def listTemplateParameters(self, nativeType):
        targs = []
        pos = 0
        while True:
            try:
                targ = nativeType.template_argument(pos)
            except:
                break
            if isinstance(targ, gdb.Type):
                targs.append(self.fromNativeType(targ.unqualified()))
            elif isinstance(targ, gdb.Value):
                targs.append(self.fromNativeValue(targ).value())
            else:
385
                error('UNKNOWN TEMPLATE PARAMETER')
386
            pos += 1
hjk's avatar
hjk committed
387 388
        targs2 = self.listTemplateParametersManually(str(nativeType))
        return targs if len(targs) >= len(targs2) else targs2
389

390 391 392 393 394
    def nativeTypeEnumDisplay(self, nativeType, intval, useHex):
        if useHex:
            format = lambda text, intval: '%s (0x%04x)' % (text, intval)
        else:
            format = lambda text, intval: '%s (%d)' % (text, intval)
395
        try:
Orgad Shaneh's avatar
Orgad Shaneh committed
396
            enumerators = []
397
            for field in nativeType.fields():
Orgad Shaneh's avatar
Orgad Shaneh committed
398
                # If we found an exact match, return it immediately
399
                if field.enumval == intval:
400
                    return format(field.name, intval)
Orgad Shaneh's avatar
Orgad Shaneh committed
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
                enumerators.append((field.name, field.enumval))

            # No match was found, try to return as flags
            enumerators.sort(key = lambda x: x[1])
            flags = []
            v = intval
            found = False
            for (name, value) in enumerators:
                if v & value != 0:
                    flags.append(name)
                    v = v & ~value
                    found = True
            if not found or v != 0:
                # Leftover value
                flags.append('unknown:%d' % v)
416
            return format(" | ".join(flags), intval)
417
        except:
418
            pass
419 420
        if useHex:
            return '0x%04x' % intval;
421
        return '%d' % intval
422 423

    def nativeTypeId(self, nativeType):
424
        if nativeType and (nativeType.code == gdb.TYPE_CODE_TYPEDEF):
425
            return '%s{%s}' % (nativeType, nativeType.strip_typedefs())
426 427 428 429 430
        name = str(nativeType)
        if len(name) == 0:
            c = '0'
        elif name == 'union {...}':
            c = 'u'
431 432
        elif name.endswith('{...}'):
            c = 's'
433 434
        else:
            return name
435 436
        typeId = c + ''.join(['{%s:%s}' % (f.name, self.nativeTypeId(f.type))
                              for f in nativeType.fields()])
437
        return typeId
438

439
    def nativeStructAlignment(self, nativeType):
440
        self.preping('align ' + str(nativeType))
hjk's avatar
hjk committed
441
        #warn('NATIVE ALIGN FOR %s' % nativeType.name)
442 443 444 445 446 447
        def handleItem(nativeFieldType, align):
            a = self.fromNativeType(nativeFieldType).alignment()
            return a if a > align else align
        align = 1
        for f in nativeType.fields():
            align = handleItem(f.type, align)
448
        self.ping('align ' + str(nativeType))
449 450 451
        return align


452 453 454 455 456 457 458 459 460
        #except:
        #    # Happens in the BoostList dumper for a 'const bool'
        #    # item named 'constant_time_size'. There isn't anything we can do
        #    # in this case.
         #   pass

        #yield value.extractField(field)


461 462
    def memberFromNativeFieldAndValue(self, nativeField, nativeValue, fieldName, value):
        nativeMember = self.nativeMemberFromField(nativeValue, nativeField)
463 464 465 466 467 468
        if nativeMember is None:
            val = self.Value(self)
            val.name = fieldName
            val.type = self.fromNativeType(nativeField.type)
            val.lIsInScope = False
            return val
469 470 471
        val = self.fromNativeValue(nativeMember)
        nativeFieldType = nativeField.type.unqualified()
        if nativeField.bitsize:
472
            val.lvalue = int(nativeMember)
473
            val.laddress = None
474 475
            fieldType = self.fromNativeType(nativeFieldType)
            val.type = self.createBitfieldType(fieldType, nativeField.bitsize)
476 477 478
        val.isBaseClass = nativeField.is_base_class
        val.name = fieldName
        return val
479

480
    def nativeMemberFromField(self, nativeValue, nativeField):
481 482 483 484 485 486 487 488 489 490 491 492
        if nativeField.is_base_class:
            return nativeValue.cast(nativeField.type)
        try:
            return nativeValue[nativeField]
        except:
            pass
        try:
            return nativeValue[nativeField.name]
        except:
            pass
        return None

493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512
    def listMembers(self, value, nativeType):
        nativeValue = value.nativeValue

        anonNumber = 0

        #warn('LISTING FIELDS FOR %s' % nativeType)
        for nativeField in nativeType.fields():
            fieldName = nativeField.name
            # Something without a name.
            # Anonymous union? We need a dummy name to distinguish
            # multiple anonymous unions in the struct.
            # Since GDB commit b5b08fb4 anonymous structs get also reported
            # with a 'None' name.
            if fieldName is None or len(fieldName) == 0:
                # Something without a name.
                # Anonymous union? We need a dummy name to distinguish
                # multiple anonymous unions in the struct.
                anonNumber += 1
                fieldName = '#%s' % anonNumber
            #warn('FIELD: %s' % fieldName)
513 514 515 516 517 518
            # hasattr(nativeField, 'bitpos') == False indicates a static field,
            # but if we have access to a nativeValue .fromNativeField will
            # also succeed. We essentially skip only static members from
            # artificial values, like array members constructed from address.
            if hasattr(nativeField, 'bitpos') or nativeValue is not None:
                yield self.fromNativeField(nativeField, nativeValue, fieldName)
519 520 521 522 523 524 525 526 527

    def fromNativeField(self, nativeField, nativeValue, fieldName):
        nativeFieldType = nativeField.type.unqualified()
        #warn('  TYPE: %s' % nativeFieldType)
        #warn('  TYPEID: %s' % self.nativeTypeId(nativeFieldType))

        if hasattr(nativeField, 'bitpos'):
            bitpos = nativeField.bitpos
        else:
528
            bitpos = 0
529

530 531 532 533
        if hasattr(nativeField, 'bitsize') and nativeField.bitsize != 0:
            bitsize = nativeField.bitsize
        else:
            bitsize = 8 * nativeFieldType.sizeof
534

535
        fieldType = self.fromNativeType(nativeFieldType)
536
        if bitsize != nativeFieldType.sizeof * 8:
537
            fieldType = self.createBitfieldType(fieldType, bitsize)
538
        else:
539
            fieldType = fieldType
540

541 542 543 544 545 546 547 548 549 550 551
        if nativeValue is None:
            extractor = None
        else:
            extractor = lambda value, \
                               capturedNativeField = nativeField, \
                               capturedNativeValue = nativeValue, \
                               capturedFieldName = fieldName : \
                self.memberFromNativeFieldAndValue(capturedNativeField,
                                                   capturedNativeValue,
                                                   capturedFieldName,
                                                   value)
552

553 554 555 556
        #warn("FOUND NATIVE FIELD: %s bitpos: %s" % (fieldName, bitpos))
        return self.Field(dumper=self, name=fieldName, isBase=nativeField.is_base_class,
                           bitsize=bitsize, bitpos=bitpos, type=fieldType,
                           extractor=extractor)
557 558


559

560
    def listLocals(self, partialVar):
561 562 563 564
        frame = gdb.selected_frame()

        try:
            block = frame.block()
565
            #warn('BLOCK: %s ' % block)
566
        except RuntimeError as error:
567
            #warn('BLOCK IN FRAME NOT ACCESSIBLE: %s' % error)
568 569
            return []
        except:
570
            warn('BLOCK NOT ACCESSIBLE FOR UNKNOWN REASONS')
571 572 573 574 575 576 577 578 579
            return []

        items = []
        shadowed = {}
        while True:
            if block is None:
                warn("UNEXPECTED 'None' BLOCK")
                break
            for symbol in block:
580 581 582

              # Filter out labels etc.
              if symbol.is_variable or symbol.is_argument:
583 584
                name = symbol.print_name

hjk's avatar
hjk committed
585
                if name in ('__in_chrg', '__PRETTY_FUNCTION__'):
586 587
                    continue

588 589 590
                if not partialVar is None and partialVar != name:
                    continue

hjk's avatar
hjk committed
591 592 593
                # 'NotImplementedError: Symbol type not yet supported in
                # Python scripts.'
                #warn('SYMBOL %s  (%s, %s)): ' % (symbol, name, symbol.name))
594 595 596
                if self.passExceptions and not self.isTesting:
                    nativeValue = frame.read_var(name, block)
                    value = self.fromFrameValue(nativeValue)
597
                    value.name = name
hjk's avatar
hjk committed
598
                    #warn('READ 0: %s' % value.stringify())
599 600 601
                    items.append(value)
                    continue

602
                try:
603
                    # Same as above, but for production.
604 605
                    nativeValue = frame.read_var(name, block)
                    value = self.fromFrameValue(nativeValue)
606
                    value.name = name
hjk's avatar
hjk committed
607
                    #warn('READ 1: %s' % value.stringify())
608
                    items.append(value)
609 610 611 612 613
                    continue
                except:
                    pass

                try:
hjk's avatar
hjk committed
614
                    #warn('READ 2: %s' % item.value)
615
                    value = self.fromFrameValue(frame.read_var(name))
616
                    value.name = name
617
                    items.append(value)
618 619 620 621 622 623 624 625 626 627
                    continue
                except:
                    # RuntimeError: happens for
                    #     void foo() { std::string s; std::wstring w; }
                    # ValueError: happens for (as of 2010/11/4)
                    #     a local struct as found e.g. in
                    #     gcc sources in gcc.c, int execute()
                    pass

                try:
hjk's avatar
hjk committed
628 629
                    #warn('READ 3: %s %s' % (name, item.value))
                    #warn('ITEM 3: %s' % item.value)
630 631
                    value = self.fromFrameValue(gdb.parse_and_eval(name))
                    value.name = name
632
                    items.append(value)
633 634
                except:
                    # Can happen in inlined code (see last line of
hjk's avatar
hjk committed
635 636
                    # RowPainter::paintChars(): 'RuntimeError:
                    # No symbol '__val' in current context.\n'
637 638 639 640 641 642 643 644 645 646 647
                    pass

            # The outermost block in a function has the function member
            # FIXME: check whether this is guaranteed.
            if not block.function is None:
                break

            block = block.superblock

        return items

648 649 650
    def reportToken(self, args):
        pass

651 652 653 654
    # Hack to avoid QDate* dumper timeouts with GDB 7.4 on 32 bit
    # due to misaligned %ebx in SSE calls (qstring.cpp:findChar)
    # This seems to be fixed in 7.9 (or earlier)
    def canCallLocale(self):
655
        return self.ptrSize() == 8
656

657
    def fetchVariables(self, args):
658
        self.resetStats()
659
        self.prepare(args)
660

661 662 663 664 665
        self.preping('endian')
        self.isBigEndian = gdb.execute('show endian', to_string = True).find('big endian') > 0
        self.ping('endian')
        self.packCode = '>' if self.isBigEndian else '<'

666 667 668 669
        (ok, res) = self.tryFetchInterpreterVariables(args)
        if ok:
            safePrint(res)
            return
670

671
        self.output += 'data=['
672

hjk's avatar
hjk committed
673
        partialVar = args.get('partialvar', '')
674 675
        isPartial = len(partialVar) > 0
        partialName = partialVar.split('.')[1].split('@')[0] if isPartial else None
676

677
        variables = self.listLocals(partialName)
hjk's avatar
hjk committed
678
        #warn('VARIABLES: %s' % variables)
hjk's avatar
hjk committed
679

680
        # Take care of the return value of the last function call.
681
        if len(self.resultVarName) > 0:
682
            try:
683 684
                value = self.parseAndEvaluate(self.resultVarName)
                value.name = self.resultVarName
hjk's avatar
hjk committed
685
                value.iname = 'return.' + self.resultVarName
686
                variables.append(value)
687 688 689 690
            except:
                # Don't bother. It's only supplementary information anyway.
                pass

691 692
        self.handleLocals(variables)
        self.handleWatches(args)
693

694
        self.output += '],typeinfo=['
695
        for name in self.typesToReport.keys():
696
            typeobj = self.typesToReport[name]
697
            # Happens e.g. for '(anonymous namespace)::InsertDefOperation'
698 699 700
            #if not typeobj is None:
            #    self.output.append('{name="%s",size="%s"}'
            #        % (self.hexencode(name), typeobj.sizeof))
701
        self.output += ']'
702
        self.typesToReport = {}
703

704
        if self.forceQtNamespace:
705
            self.qtNamepaceToReport = self.qtNamespace()
706

707
        if self.qtNamespaceToReport:
708
            self.output += ',qtnamespace="%s"' % self.qtNamespaceToReport
709
            self.qtNamespaceToReport = None
710

711 712 713 714
        self.output += ',partial="%d"' % isPartial
        self.output += ',counts=%s' % self.counts
        self.output += ',timimgs=%s' % self.timings
        self.reportResult(self.output)
715

716
    def parseAndEvaluate(self, exp):
hjk's avatar
hjk committed
717
        #warn('EVALUATE "%s"' % exp)
718
        try:
719 720 721
            val = gdb.parse_and_eval(exp)
        except RuntimeError as error:
            if self.passExceptions:
722 723
                warn("Cannot evaluate '%s': %s" % (exp, error))
            return None
724
        return self.fromNativeValue(val)
725

726
    def callHelper(self, rettype, value, function, args):
727
        # args is a tuple.
hjk's avatar
hjk committed
728
        arg = ''
729 730 731 732 733 734 735 736 737
        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

hjk's avatar
hjk committed
738
        #warn('CALL: %s -> %s(%s)' % (value, function, arg))
hjk's avatar
hjk committed
739
        typeName = value.type.name
hjk's avatar
hjk committed
740
        if typeName.find(':') >= 0:
741
            typeName = "'" + typeName + "'"
742
        # 'class' is needed, see http://sourceware.org/bugzilla/show_bug.cgi?id=11912
hjk's avatar
hjk committed
743
        #exp = '((class %s*)%s)->%s(%s)' % (typeName, value.laddress, function, arg)
744
        addr = value.address()
745 746
        if addr is None:
           addr = self.pokeValue(value)
hjk's avatar
hjk committed
747 748
        #warn('PTR: %s -> %s(%s)' % (value, function, addr))
        exp = '((%s*)0x%x)->%s(%s)' % (typeName, addr, function, arg)
hjk's avatar
hjk committed
749
        #warn('CALL: %s' % exp)
750
        result = gdb.parse_and_eval(exp)
hjk's avatar
hjk committed
751
        #warn('  -> %s' % result)
752
        res = self.fromNativeValue(result)
753
        if value.address() is None:
754
            self.releaseValue(addr)
755
        return res
hjk's avatar
hjk committed
756 757

    def makeExpression(self, value):
hjk's avatar
hjk committed
758 759 760 761
        typename = '::' + value.type.name
        #warn('  TYPE: %s' % typename)
        exp = '(*(%s*)(0x%x))' % (typename, value.address())
        #warn('  EXP: %s' % exp)
hjk's avatar
hjk committed
762 763 764 765
        return exp

    def makeStdString(init):
        # Works only for small allocators, but they are usually empty.
hjk's avatar
hjk committed
766 767 768 769
        gdb.execute('set $d=(std::string*)calloc(sizeof(std::string), 2)');
        gdb.execute('call($d->basic_string("' + init +
            '",*(std::allocator<char>*)(1+$d)))')
        value = gdb.parse_and_eval('$d').dereference()
hjk's avatar
hjk committed
770 771
        return value

772
    def pokeValue(self, value):
773 774
        # Allocates inferior memory and copies the contents of value.
        # Returns a pointer to the copy.
775
        # Avoid malloc symbol clash with QVector
776 777 778
        size = value.type.size()
        data = value.data()
        h = self.hexencode(data)
hjk's avatar
hjk committed
779 780
        #warn('DATA: %s' % h)
        string = ''.join('\\x' + h[2*i:2*i+2] for i in range(size))
781 782
        exp = '(%s*)memcpy(calloc(%d, 1), "%s", %d)' \
            % (value.type.name, size, string, size)
hjk's avatar
hjk committed
783
        #warn('EXP: %s' % exp)
784
        res = gdb.parse_and_eval(exp)
hjk's avatar
hjk committed
785
        #warn('RES: %s' % res)
786
        return toInteger(res)
787

788 789 790
    def releaseValue(self, address):
        gdb.parse_and_eval('free(0x%x)' % address)

791
    def setValue(self, address, typename, value):
hjk's avatar
hjk committed
792
        cmd = 'set {%s}%s=%s' % (typename, address, value)
793 794
        gdb.execute(cmd)

795
    def setValues(self, address, typename, values):
hjk's avatar
hjk committed
796
        cmd = 'set {%s[%s]}%s={%s}' \
797
            % (typename, len(values), address, ','.join(map(str, values)))
798 799
        gdb.execute(cmd)

800 801
    def selectedInferior(self):
        try:
802
            # gdb.Inferior is new in gdb 7.2
803
            self.cachedInferior = gdb.selected_inferior()
804 805
        except:
            # Pre gdb 7.4. Right now we don't have more than one inferior anyway.
806 807 808 809 810
            self.cachedInferior = gdb.inferiors()[0]

        # Memoize result.
        self.selectedInferior = lambda: self.cachedInferior
        return self.cachedInferior
811

812
    def readRawMemory(self, address, size):
813 814 815 816 817 818 819
        #warn('READ: %s FROM 0x%x' % (size, address))
        if address == 0 or size == 0:
            return bytes()
        self.preping('readMem')
        res = self.selectedInferior().read_memory(address, size)
        self.ping('readMem')
        return res
820

821 822
    def findStaticMetaObject(self, type):
        symbolName = type.name + '::staticMetaObject'
823 824 825
        symbol = gdb.lookup_global_symbol(symbolName, gdb.SYMBOL_VAR_DOMAIN)
        if not symbol:
            return 0
826
        try:
827 828
            # Older GDB ~7.4 don't have gdb.Symbol.value()
            return toInteger(symbol.value().address)
829 830
        except:
            pass
831 832 833

        address = gdb.parse_and_eval("&'%s'" % symbolName)
        return toInteger(address)
834

835 836 837 838 839 840
    def isArmArchitecture(self):
        return 'arm' in gdb.TARGET_CONFIG.lower()

    def isQnxTarget(self):
        return 'qnx' in gdb.TARGET_CONFIG.lower()

841 842 843 844
    def isWindowsTarget(self):
        # We get i686-w64-mingw32
        return 'mingw' in gdb.TARGET_CONFIG.lower()

845 846 847
    def isMsvcTarget(self):
        return False

hjk's avatar
hjk committed
848 849 850 851 852 853
    def prettySymbolByAddress(self, address):
        try:
            return str(gdb.parse_and_eval('(void(*))0x%x' % address))
        except:
            return '0x%x' % address

hjk's avatar
hjk committed
854 855
    def qtVersionString(self):
        try:
hjk's avatar
hjk committed
856
            return str(gdb.lookup_symbol('qVersion')[0].value()())
hjk's avatar
hjk committed
857 858
        except:
            pass
859
        try:
860
            ns = self.qtNamespace()
hjk's avatar
hjk committed
861 862 863 864 865 866
            return str(gdb.parse_and_eval("((const char*(*)())'%sqVersion')()" % ns))
        except:
            pass
        return None

    def qtVersion(self):
867 868
        try:
            # Only available with Qt 5.3+
hjk's avatar
hjk committed
869
            qtversion = int(str(gdb.parse_and_eval('((void**)&qtHookData)[2]')), 16)
870 871 872 873 874
            self.qtVersion = lambda: qtversion
            return qtversion
        except:
            pass

hjk's avatar
hjk committed
875 876
        try:
            version = self.qtVersionString()
877
            (major, minor, patch) = version[version.find('"')+1:version.rfind('"')].split('.')
hjk's avatar
hjk committed
878 879 880
            qtversion = 0x10000 * int(major) + 0x100 * int(minor) + int(patch)
            self.qtVersion = lambda: qtversion
            return qtversion
881
        except:
882 883
            # Use fallback until we have a better answer.
            return self.fallbackQtVersion
884

885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900
    def createSpecialBreakpoints(self, args):
        self.specialBreakpoints = []
        def newSpecial(spec):
            class SpecialBreakpoint(gdb.Breakpoint):
                def __init__(self, spec):
                    super(SpecialBreakpoint, self).\
                        __init__(spec, gdb.BP_BREAKPOINT, internal=True)
                    self.spec = spec

                def stop(self):
                    print("Breakpoint on '%s' hit." % self.spec)
                    return True
            return SpecialBreakpoint(spec)

        # FIXME: ns is accessed too early. gdb.Breakpoint() has no
        # 'rbreak' replacement, and breakpoints created with
hjk's avatar
hjk committed
901
        # 'gdb.execute('rbreak...') cannot be made invisible.
902 903 904 905
        # So let's ignore the existing of namespaced builds for this
        # fringe feature here for now.
        ns = self.qtNamespace()
        if args.get('breakonabort', 0):
hjk's avatar
hjk committed
906
            self.specialBreakpoints.append(newSpecial('abort'))
907 908

        if args.get('breakonwarning', 0):
hjk's avatar
hjk committed
909 910
            self.specialBreakpoints.append(newSpecial(ns + 'qWarning'))
            self.specialBreakpoints.append(newSpecial(ns + 'QMessageLogger::warning'))
911 912

        if args.get('breakonfatal', 0):
hjk's avatar
hjk committed
913 914
            self.specialBreakpoints.append(newSpecial(ns + 'qFatal'))
            self.specialBreakpoints.append(newSpecial(ns + 'QMessageLogger::fatal'))
915

916 917
    #def threadname(self, maximalStackDepth, objectPrivateType):
    #    e = gdb.selected_frame()
hjk's avatar
hjk committed
918
    #    out = ''
919 920 921 922 923 924 925 926
    #    ns = self.qtNamespace()
    #    while True:
    #        maximalStackDepth -= 1
    #        if maximalStackDepth < 0:
    #            break
    #        e = e.older()
    #        if e == None or e.name() == None:
    #            break
hjk's avatar
hjk committed
927
    #        if e.name() in (ns + 'QThreadPrivate::start', '_ZN14QThreadPrivate5startEPv@4'):
928
    #            try:
hjk's avatar
hjk committed
929 930
    #                thrptr = e.read_var('thr').dereference()
    #                d_ptr = thrptr['d_ptr']['d'].cast(objectPrivateType).dereference()
931
    #                try:
hjk's avatar
hjk committed
932
    #                    objectName = d_ptr['objectName']
933
    #                except: # Qt 5
hjk's avatar
hjk committed
934
    #                    p = d_ptr['extraData']
935
    #                    if not self.isNull(p):
hjk's avatar
hjk committed
936
    #                        objectName = p.dereference()['objectName']
937
    #                if not objectName is None:
938
    #                    (data, size, alloc) = self.stringData(objectName)
939 940 941 942
    #                    if size > 0:
    #                         s = self.readMemory(data, 2 * size)
    #
    #                thread = gdb.selected_thread()
hjk's avatar
hjk committed
943
    #                inner = '{valueencoded="uf16:2:0",id="'
944 945 946 947 948 949 950 951 952
    #                inner += str(thread.num) + '",value="'
    #                inner += s
    #                #inner += self.encodeString(objectName)
    #                inner += '"},'
    #
    #                out += inner
    #            except:
    #                pass
    #    return out
953 954

    def threadnames(self, maximalStackDepth):
955
        # FIXME: This needs a proper implementation for MinGW, and only there.
956
        # Linux, Mac and QNX mirror the objectName() to the underlying threads,
957 958
        # so we get the names already as part of the -thread-info output.
        return '[]'
959 960 961 962
        #out = '['
        #oldthread = gdb.selected_thread()
        #if oldthread:
        #    try:
hjk's avatar
hjk committed
963
        #        objectPrivateType = gdb.lookup_type(ns + 'QObjectPrivate').pointer()
964 965 966 967