lldbbridge.py 65.6 KB
Newer Older
1
2
############################################################################
#
3
# Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# Contact: http://www.qt-project.org/legal
#
# 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 Digia.  For licensing terms and
# conditions see http://qt.digia.com/licensing.  For further information
# use the contact form at http://qt.digia.com/contact-us.
#
# GNU Lesser General Public License Usage
# Alternatively, this file may be used under the terms of the GNU Lesser
# General Public License version 2.1 as published by the Free Software
# Foundation and appearing in the file LICENSE.LGPL included in the
# packaging of this file.  Please review the following information to
# ensure the GNU Lesser General Public License version 2.1 requirements
# will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
#
# In addition, as a special exception, Digia gives you certain additional
# rights.  These rights are described in the Digia Qt LGPL Exception
# version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
#
#############################################################################
29

30
import atexit
31
import inspect
32
import json
33
import os
34
import platform
35
import re
36
37
import select
import sys
38
import subprocess
39
import threading
40

41
42
43
44
45
currentDir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
sys.path.insert(1, currentDir)

from dumper import *
from qttypes import *
hjk's avatar
hjk committed
46
47
48
from stdtypes import *
from misctypes import *
from boosttypes import *
49
from creatortypes import *
50

51
52
53
lldbCmd = 'lldb'
if len(sys.argv) > 1:
    lldbCmd = sys.argv[1]
54

55
proc = subprocess.Popen(args=[lldbCmd, '-P'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
56
(path, error) = proc.communicate()
57

58
if error.startswith('lldb: invalid option -- P'):
59
    sys.stdout.write('msg=\'Could not run "%s -P". Trying to find lldb.so from Xcode.\'@\n' % lldbCmd)
60
61
62
63
64
    proc = subprocess.Popen(args=['xcode-select', '--print-path'],
        stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    (path, error) = proc.communicate()
    if len(error):
        path = '/Applications/Xcode.app/Contents/SharedFrameworks/LLDB.framework/Versions/A/Resources/Python/'
65
66
        sys.stdout.write('msg=\'Could not run "xcode-select --print-path"@\n')
        sys.stdout.write('msg=\'Using hardcoded fallback at %s\'@\n' % path)
67
68
    else:
        path = path.strip() + '/../SharedFrameworks/LLDB.framework/Versions/A/Resources/Python/'
69
        sys.stdout.write('msg=\'Using fallback at %s\'@\n' % path)
70

71
sys.path.insert(1, path.strip())
72
73

import lldb
74
75
76
77
78
79
80

#######################################################################
#
# Helpers
#
#######################################################################

81
qqWatchpointOffset = 10000
82

83
lldb.theDumper = None
84
85

def warn(message):
86
    print('\n\nWARNING="%s",\n' % message.encode("latin1").replace('"', "'"))
87
88
89

def showException(msg, exType, exValue, exTraceback):
    warn("**** CAUGHT EXCEPTION: %s ****" % msg)
90
91
92
    import traceback
    lines = [line for line in traceback.format_exception(exType, exValue, exTraceback)]
    warn('\n'.join(lines))
93
94
95
96

def fileName(file):
    return str(file) if file.IsValid() else ''

97

98
99
100
101
102
103
104
105
106
107
# Breakpoints. Keep synchronized with BreakpointType in breakpoint.h
UnknownType = 0
BreakpointByFileAndLine = 1
BreakpointByFunction = 2
BreakpointByAddress = 3
BreakpointAtThrow = 4
BreakpointAtCatch = 5
BreakpointAtMain = 6
BreakpointAtFork = 7
BreakpointAtExec = 8
108
109
110
111
112
BreakpointAtSysCall = 9
WatchpointAtAddress = 10
WatchpointAtExpression = 11
BreakpointOnQmlSignalEmit = 12
BreakpointAtJavaScriptThrow = 13
113

114
115
116
# See db.StateType
stateNames = ["invalid", "unloaded", "connected", "attaching", "launching", "stopped",
    "running", "stepping", "crashed", "detached", "exited", "suspended" ]
117

118
119
120
def loggingCallback(args):
    s = args.strip()
    s = s.replace('"', "'")
121
    sys.stdout.write('log="%s"@\n' % s)
122

hjk's avatar
hjk committed
123
124
125
126
def check(exp):
    if not exp:
        raise RuntimeError("Check failed")

127
128
Value = lldb.SBValue

129
130
def impl_SBValue__add__(self, offset):
    if self.GetType().IsPointerType():
131
132
133
134
        if isinstance(offset, int) or isinstance(offset, long):
            pass
        else:
            offset = offset.GetValueAsSigned()
135
        itemsize = self.GetType().GetPointeeType().GetByteSize()
136
        address = self.GetValueAsUnsigned() + offset * itemsize
137
        address = address & 0xFFFFFFFFFFFFFFFF  # Force unsigned
138
139
        return self.CreateValueFromAddress(None, address,
                self.GetType().GetPointeeType()).AddressOf()
hjk's avatar
hjk committed
140

141
    raise RuntimeError("SBValue.__add__ not implemented: %s" % self.GetType())
142
143
    return NotImplemented

144
def impl_SBValue__sub__(self, other):
145
    if self.GetType().IsPointerType():
146
147
148
149
        if isinstance(other, int) or isinstance(other, long):
            address = self.GetValueAsUnsigned() - offset.GetValueAsSigned()
            address = address & 0xFFFFFFFFFFFFFFFF  # Force unsigned
            return self.CreateValueFromAddress(None, address, self.GetType())
150
        if other.GetType().IsPointerType():
151
152
            itemsize = self.GetType().GetPointeeType().GetByteSize()
            return (self.GetValueAsUnsigned() - other.GetValueAsUnsigned()) / itemsize
153
    raise RuntimeError("SBValue.__sub__ not implemented: %s" % self.GetType())
154
155
    return NotImplemented

156
157
158
159
160
161
162
def impl_SBValue__le__(self, other):
    if self.GetType().IsPointerType() and other.GetType().IsPointerType():
        return int(self) <= int(other)
    raise RuntimeError("SBValue.__le__ not implemented")
    return NotImplemented

def impl_SBValue__int__(self):
163
    return self.GetValueAsSigned()
164
165
166
167
168
169
170
171
172
173

def impl_SBValue__float__(self):
    error = lldb.SBError()
    if self.GetType().GetByteSize() == 4:
        result = self.GetData().GetFloat(error, 0)
    else:
        result = self.GetData().GetDouble(error, 0)
    if error.Success():
        return result
    return NotImplemented
174

175
176
177
def impl_SBValue__long__(self):
    return int(self.GetValue(), 0)

178
179
180
181
182
183
184
185
186
def impl_SBValue__getitem__(value, index):
    if isinstance(index, int):
        type = value.GetType()
        if type.IsPointerType():
            innertype = value.Dereference().GetType()
            address = value.GetValueAsUnsigned() + index * innertype.GetByteSize()
            address = address & 0xFFFFFFFFFFFFFFFF  # Force unsigned
            return value.CreateValueFromAddress(None, address, innertype)
        return value.GetChildAtIndex(index)
187
    return value.GetChildMemberWithName(index)
188

189
190
191
192
def impl_SBValue__deref(value):
    result = value.Dereference()
    if result.IsValid():
        return result
193
194
    exp = "*(class %s*)0x%x" % (value.GetType().GetPointeeType(), value.GetValueAsUnsigned())
    return value.CreateValueFromExpression(None, exp)
195

196
lldb.SBValue.__add__ = impl_SBValue__add__
197
lldb.SBValue.__sub__ = impl_SBValue__sub__
198
lldb.SBValue.__le__ = impl_SBValue__le__
199

200
201
lldb.SBValue.__getitem__ = impl_SBValue__getitem__
lldb.SBValue.__int__ = impl_SBValue__int__
202
lldb.SBValue.__float__ = impl_SBValue__float__
203
204
lldb.SBValue.__long__ = lambda self: long(self.GetValue(), 0)

205
lldb.SBValue.code = lambda self: self.GetTypeClass()
206
lldb.SBValue.cast = lambda self, typeObj: self.Cast(typeObj)
207
lldb.SBValue.dereference = impl_SBValue__deref
208
lldb.SBValue.address = property(lambda self: self.GetLoadAddress())
209
210

lldb.SBType.pointer = lambda self: self.GetPointerType()
hjk's avatar
hjk committed
211
lldb.SBType.target = lambda self: self.GetPointeeType()
212
lldb.SBType.code = lambda self: self.GetTypeClass()
213
lldb.SBType.sizeof = property(lambda self: self.GetByteSize())
214
215


hjk's avatar
hjk committed
216
217
lldb.SBType.unqualified = \
    lambda self: self.GetUnqualifiedType() if hasattr(self, 'GetUnqualifiedType') else self
218
219
lldb.SBType.strip_typedefs = \
    lambda self: self.GetCanonicalType() if hasattr(self, 'GetCanonicalType') else self
220

hjk's avatar
hjk committed
221
222
223
lldb.SBType.__orig__str__ = lldb.SBType.__str__
lldb.SBType.__str__ = lldb.SBType.GetName

224
class Dumper(DumperBase):
225
    def __init__(self):
226
227
        DumperBase.__init__(self)

228
229
        lldb.theDumper = self

230
        self.debugger = lldb.SBDebugger.Create()
231
        #self.debugger.SetLoggingCallback(loggingCallback)
232
233
234
235
236
237
        #Same as: self.debugger.HandleCommand("log enable lldb dyld step")
        #self.debugger.EnableLog("lldb", ["dyld", "step", "process", "state", "thread", "events",
        #    "communication", "unwind", "commands"])
        #self.debugger.EnableLog("lldb", ["all"])
        self.debugger.Initialize()
        self.debugger.HandleCommand("settings set auto-confirm on")
238
239
240
241
242
243
244
245
246
247

        # FIXME: warn("DISABLING DEFAULT FORMATTERS")
        # It doesn't work at all with 179.5 and we have some bad
        # interactonn in 3000
        # if not hasattr(lldb.SBType, 'GetCanonicalType'): # "Test" for 179.5
        self.debugger.HandleCommand('type category delete gnu-libstdc++')
        self.debugger.HandleCommand('type category delete libcxx')
        #for i in range(self.debugger.GetNumCategories()):
        #    self.debugger.GetCategoryAtIndex(i).SetEnabled(False)

248
        self.isLldb = True
hjk's avatar
hjk committed
249
        self.isGoodLldb = hasattr(lldb.SBValue, "SetPreferDynamicValue")
250
251
252
253
        self.process = None
        self.target = None
        self.eventState = lldb.eStateInvalid
        self.expandedINames = {}
254
        self.passExceptions = False
255
        self.useLldbDumpers = False
hjk's avatar
hjk committed
256
        self.autoDerefPointers = True
257
        self.useDynamicType = True
hjk's avatar
hjk committed
258
        self.useFancy = True
hjk's avatar
hjk committed
259
260
        self.formats = {}
        self.typeformats = {}
261
262
263
264
265
266

        self.currentIName = None
        self.currentValuePriority = -100
        self.currentValueEncoding = None
        self.currentType = ""
        self.currentTypePriority = -100
267
        self.currentValue = None
268
269
270
271
272
        self.currentNumChild = None
        self.currentMaxNumChild = None
        self.currentPrintsAddress = None
        self.currentChildType = None
        self.currentChildNumChild = None
273
        self.currentWatchers = {}
274

hjk's avatar
hjk committed
275
        self.executable_ = None
276
277
278
279
        self.startMode_ = None
        self.processArgs_ = None
        self.attachPid_ = None

280
281
        self.charType_ = None
        self.intType_ = None
282
        self.int64Type_ = None
283
284
        self.sizetType_ = None
        self.charPtrType_ = None
hjk's avatar
hjk committed
285
        self.voidPtrType_ = None
286
        self.isShuttingDown_ = False
287
        self.isInterrupting_ = False
288
        self.dummyValue = None
289
        self.types_ = {}
290
        self.breakpointsToCheck = set([])
291

292
293
294
295
    def enterSubItem(self, item):
        if isinstance(item.name, lldb.SBValue):
            # Avoid $$__synth__ suffix on Mac.
            value = item.name
hjk's avatar
hjk committed
296
297
            if self.isGoodLldb:
                value.SetPreferSyntheticValue(False)
298
299
300
301
            item.name = value.GetName()
            if item.name is None:
                self.anonNumber += 1
                item.name = "#%d" % self.anonNumber
302
303
        if not item.iname:
            item.iname = "%s.%s" % (self.currentIName, item.name)
304
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.put('{')
        #if not item.name is None:
        if isinstance(item.name, str):
            if item.name == '**&':
                item.name = '*'
            self.put('name="%s",' % item.name)
        item.savedIName = self.currentIName
        item.savedValue = self.currentValue
        item.savedValuePriority = self.currentValuePriority
        item.savedValueEncoding = self.currentValueEncoding
        item.savedType = self.currentType
        item.savedTypePriority = self.currentTypePriority
        self.currentIName = item.iname
        self.currentValuePriority = -100
        self.currentValueEncoding = None
        self.currentType = ""
        self.currentTypePriority = -100

    def exitSubItem(self, item, exType, exValue, exTraceBack):
        if not exType is None:
            if self.passExceptions:
                showException("SUBITEM", exType, exValue, exTraceBack)
            self.putNumChild(0)
            self.putValue("<not accessible>")
        try:
            typeName = self.currentType
            if len(typeName) > 0 and typeName != self.currentChildType:
                self.put('type="%s",' % typeName) # str(type.unqualified()) ?
            if  self.currentValue is None:
                self.put('value="<not accessible>",numchild="0",')
            else:
                if not self.currentValueEncoding is None:
336
                    self.put('valueencoded="%s",' % self.currentValueEncoding)
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
                self.put('value="%s",' % self.currentValue)
        except:
            pass
        self.put('},')
        self.currentIName = item.savedIName
        self.currentValue = item.savedValue
        self.currentValuePriority = item.savedValuePriority
        self.currentValueEncoding = item.savedValueEncoding
        self.currentType = item.savedType
        self.currentTypePriority = item.savedTypePriority
        return True

    def isSimpleType(self, typeobj):
        typeClass = typeobj.GetTypeClass()
        return typeClass == lldb.eTypeClassBuiltin

hjk's avatar
hjk committed
353
354
355
    def childWithName(self, value, name):
        child = value.GetChildMemberWithName(name)
        return child if child.IsValid() else None
356

357
358
359
    def simpleValue(self, value):
        return str(value.value)

360
361
362
363
364
365
366
367
368
    def childAt(self, value, index):
        return value.GetChildAtIndex(index)

    def fieldAt(self, type, index):
        return type.GetFieldAtIndex(index)

    def pointerValue(self, value):
        return value.GetValueAsUnsigned()

369
370
371
372
373
    def enumExpression(self, enumType, enumValue):
        ns = self.qtNamespace()
        return ns + "Qt::" + enumType + "(" \
            + ns + "Qt::" + enumType + "::" + enumValue + ")"

374
375
376
377
378
379
380
    def call2(self, value, func, args):
        # args is a tuple.
        arg = ','.join(args)
        #warn("CALL: %s -> %s(%s)" % (value, func, arg))
        type = value.type.name
        exp = "((%s*)%s)->%s(%s)" % (type, value.address, func, arg)
        #warn("CALL: %s" % exp)
381
        result = value.CreateValueFromExpression('', exp)
382
383
384
        #warn("  -> %s" % result)
        return result

385
386
387
388
389
390
391
392
393
394
    def makeValue(self, type, *args):
        thread = self.currentThread()
        frame = thread.GetFrameAtIndex(0)
        inner = ','.join(args)
        value = frame.EvaluateExpression(type + '{' + inner + '}')
        #warn("  TYPE: %s" % value.type)
        #warn("  ADDR: 0x%x" % value.address)
        #warn("  VALUE: %s" % value)
        return value

395
396
397
398
399
    def parseAndEvaluate(self, expr):
        thread = self.currentThread()
        frame = thread.GetFrameAtIndex(0)
        return frame.EvaluateExpression(expr)

400
401
402
403
404
405
406
407
408
409
410
411
412
    def call(self, value, func, *args):
        return self.call2(value, func, args)

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

    def isNull(self, p):
        return p.GetValueAsUnsigned() == 0

    def directBaseClass(self, typeobj, index = 0):
        return typeobj.GetDirectBaseClassAtIndex(index)

413
    def templateArgument(self, typeobj, index):
414
        type = typeobj.GetTemplateArgumentType(index)
hjk's avatar
hjk committed
415
        if type.IsValid():
416
417
418
419
420
421
422
            return type
        inner = self.extractTemplateArgument(typeobj.GetName(), index)
        return self.lookupType(inner)

    def numericTemplateArgument(self, typeobj, index):
        inner = self.extractTemplateArgument(typeobj.GetName(), index)
        return int(inner)
423

hjk's avatar
hjk committed
424
425
426
427
428
429
    def isReferenceType(self, typeobj):
        return typeobj.IsReferenceType()

    def isStructType(self, typeobj):
        return typeobj.GetTypeClass() in (lldb.eTypeClassStruct, lldb.eTypeClassClass)

430
431
    def qtVersionAndNamespace(self):
        self.cachedQtNamespace = ""
432
        self.cachedQtVersion = 0x0
433

434
435
436
        coreExpression = re.compile(r"(lib)?Qt5?Core")
        for n in range(0, self.target.GetNumModules()):
            module = self.target.GetModuleAtIndex(n)
437
438
            fileName = module.GetFileSpec().GetFilename()
            if coreExpression.match(fileName):
439
                # Extract version.
440
                reverseVersion = module.GetVersion()
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
                if len(reverseVersion):
                    # Mac, Clang?
                    reverseVersion.reverse()
                    shift = 0
                    for v in reverseVersion:
                        self.cachedQtVersion += v << shift
                        shift += 8
                else:
                    # Linux, gcc?
                    if fileName.endswith(".5"):
                        self.cachedQtVersion = 0x50000
                    elif fileName.endswith(".4"):
                        self.cachedQtVersion = 0x40800
                    else:
                        warn("CANNOT GUESS QT VERSION")

457
458
459
460
461
462
463
464
465
466

                # Look for some Qt symbol to extract namespace.
                for symbol in module.symbols:
                    name = symbol.GetName()
                    pos = name.find("QString")
                    if pos >= 0:
                        name = name[:pos]
                        if name.endswith("::"):
                            self.cachedQtNamespace = re.sub('^.*[^\w]([\w]+)::$', '\\1', name) + '::'
                        break
467
                break
468
469

        # Memoize good results.
470
        self.qtNamespace = lambda: self.cachedQtNamespace
471
        self.qtVersion = lambda: self.cachedQtVersion
472
473
474
475
476
477

    def qtNamespace(self):
        self.qtVersionAndNamespace()
        return self.cachedQtNamespace

    def qtVersion(self):
478
        self.qtVersionAndNamespace()
479
        return self.cachedQtVersion
480

hjk's avatar
hjk committed
481
482
483
    def intSize(self):
        return 4

484
485
    def intType(self):
        if self.intType_ is None:
hjk's avatar
hjk committed
486
             self.intType_ = self.target.FindFirstType('int')
487
488
        return self.intType_

489
490
491
492
493
    def int64Type(self):
        if self.int64Type_ is None:
             self.int64Type_ = self.target.FindFirstType('long long int')
        return self.int64Type_

494
495
    def charType(self):
        if self.charType_ is None:
hjk's avatar
hjk committed
496
             self.charType_ = self.target.FindFirstType('char')
497
498
499
500
501
502
503
504
        return self.charType_

    def charPtrType(self):
        if self.charPtrType_ is None:
             self.charPtrType_ = self.charType().GetPointerType()
        return self.charPtrType_

    def voidPtrType(self):
hjk's avatar
hjk committed
505
506
507
        if self.voidPtrType_ is None:
             self.voidPtrType_ = self.target.FindFirstType('void').GetPointerType()
        return self.voidPtrType_
508

hjk's avatar
hjk committed
509
    def ptrSize(self):
510
511
512
513
514
515
516
        return self.charPtrType().GetByteSize()

    def sizetType(self):
        if self.sizetType_ is None:
             self.sizetType_ = self.lookupType('size_t')
        return self.sizetType_

517
518
519
    def addressOf(self, value):
        return int(value.GetLoadAddress())

hjk's avatar
hjk committed
520
521
522
    def extractInt(self, address):
        return int(self.createValue(address, self.intType()))

523
524
525
    def extractInt64(self, address):
        return int(self.createValue(address, self.int64Type()))

526
527
528
    def extractByte(self, address):
        return int(self.createValue(address, self.charType())) & 0xFF

529
530
531
532
533
534
    def handleCommand(self, command):
        result = lldb.SBCommandReturnObject()
        self.debugger.GetCommandInterpreter().HandleCommand(command, result)
        success = result.Succeeded()
        if success:
            self.report('output="%s"' % result.GetOutput())
535
        else:
536
537
538
539
540
541
            self.report('error="%s"' % result.GetError())
        self.reportData()

    def put(self, stuff):
        sys.stdout.write(stuff)

542
    def isMovableType(self, type):
543
        if type.GetTypeClass() in (lldb.eTypeClassBuiltin, lldb.eTypeClassPointer):
544
            return True
545
        return self.isKnownMovableType(self.stripNamespaceFromType(type.GetName()))
546

547
548
    def putNumChild(self, numchild):
        #warn("NUM CHILD: '%s' '%s'" % (numchild, self.currentChildNumChild))
hjk's avatar
hjk committed
549
550
        #if numchild != self.currentChildNumChild:
        self.put('numchild="%s",' % numchild)
551

552
553
554
555
556
557
558
    def putPointerValue(self, value):
        # Use a lower priority
        if value is None:
            self.putEmptyValue(-1)
        else:
            self.putValue("0x%x" % value.Dereference())

hjk's avatar
hjk committed
559
560
561
    def putSimpleValue(self, value, encoding = None, priority = 0):
        self.putValue(value.GetValue(), encoding, priority)

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
587
588
589
    def simpleEncoding(self, typeobj):
        code = typeobj.GetTypeClass()
        size = typeobj.sizeof
        if code == lldb.eTypeClassBuiltin:
            name = str(typeobj)
            if name == "float":
                return Hex2EncodedFloat4
            if name == "double":
                return Hex2EncodedFloat8
            if name.find("unsigned") >= 0:
                if size == 1:
                    return Hex2EncodedUInt1
                if size == 2:
                    return Hex2EncodedUInt2
                if size == 4:
                    return Hex2EncodedUInt4
                if size == 8:
                    return Hex2EncodedUInt8
            else:
                if size == 1:
                    return Hex2EncodedInt1
                if size == 2:
                    return Hex2EncodedInt2
                if size == 4:
                    return Hex2EncodedInt4
                if size == 8:
                    return Hex2EncodedInt8
        return None
590
591
592
593

    def putArrayData(self, type, base, n,
            childNumChild = None, maxNumChild = 10000):
        if not self.tryPutArrayContents(type, base, n):
594
            base = self.createPointerValue(base, type)
595
596
597
598
599
            with Children(self, n, type, childNumChild, maxNumChild,
                    base, type.GetByteSize()):
                for i in self.childRange():
                    self.putSubItem(i, (base + i).dereference())

600
601
602
603
604
605
606
607
    def createPointerValue(self, address, pointeeType):
        addr = int(address) & 0xFFFFFFFFFFFFFFFF
        return self.context.CreateValueFromAddress(None, addr, pointeeType).AddressOf()

    def createValue(self, address, referencedType):
        addr = int(address) & 0xFFFFFFFFFFFFFFFF
        return self.context.CreateValueFromAddress(None, addr, referencedType)

608
    def putCallItem(self, name, value, func, *args):
609
        result = self.call2(value, func, args)
610
611
612
        with SubItem(self, name):
            self.putItem(result)

613
614
615
616
617
    def childRange(self):
        if self.currentMaxNumChild is None:
            return xrange(0, self.currentNumChild)
        return xrange(min(self.currentMaxNumChild, self.currentNumChild))

618
619
620
    def canonicalTypeName(self, name):
        return re.sub('\\bconst\\b', '', name).replace(' ', '')

621
    def lookupType(self, name):
hjk's avatar
hjk committed
622
        #warn("LOOKUP TYPE NAME: %s" % name)
hjk's avatar
hjk committed
623
        if name.endswith('*'):
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
            typeobj = self.lookupType(name[:-1].strip())
            return typeobj.GetPointerType() if type.IsValid() else None
        typeobj = self.target.FindFirstType(name)
        #warn("LOOKUP RESULT: %s" % typeobj.name)
        #warn("LOOKUP VALID: %s" % typeobj.IsValid())
        if typeobj.IsValid():
            return typeobj
        try:
            if len(self.types_) == 0:
                for i in xrange(self.target.GetNumModules()):
                    module = self.target.GetModuleAtIndex(i)
                    # SBModule.GetType is new somewhere after early 300.x
                    # So this may fail.
                    for t in module.GetTypes():
                        n = self.canonicalTypeName(t.GetName())
                        self.types_[n] = t
            return self.types_.get(self.canonicalTypeName(name))
        except:
            pass
        return None
644

645
    def setupInferior(self, args):
646
        error = lldb.SBError()
647
648

        self.executable_ = args['executable']
649
        self.startMode_ = args.get('startMode', 1)
650
        self.breakOnMain_ = args.get('breakOnMain', 0)
hjk's avatar
hjk committed
651
        self.useTerminal_ = args.get('useTerminal', 0)
652
653
        self.processArgs_ = args.get('processArgs', [])
        self.processArgs_ = map(lambda x: self.hexdecode(x), self.processArgs_)
654
        self.attachPid_ = args.get('attachPid', 0)
Fawzi Mohamed's avatar
Fawzi Mohamed committed
655
        self.sysRoot_ = args.get('sysRoot', '')
Fawzi Mohamed's avatar
Fawzi Mohamed committed
656
        self.remoteChannel_ = args.get('remoteChannel', '')
657
        self.platform_ = args.get('platform', '')
658

hjk's avatar
hjk committed
659
660
        self.ignoreStops = 1 if self.useTerminal_ else 0

661
662
        if self.platform_:
            self.debugger.SetCurrentPlatform(self.platform_)
Fawzi Mohamed's avatar
Fawzi Mohamed committed
663
664
665
        # sysroot has to be set *after* the platform
        if self.sysRoot_:
            self.debugger.SetCurrentPlatformSDKRoot(self.sysRoot_)
666
667
668
669
670

        if os.path.isfile(self.executable_):
            self.target = self.debugger.CreateTarget(self.executable_, None, None, True, error)
        else:
            self.target = self.debugger.CreateTarget(None, None, None, True, error)
671
672
        self.importDumpers()

673
674
        state = "inferiorsetupok" if self.target.IsValid() else "inferiorsetupfailed"
        self.report('state="%s",msg="%s",exe="%s"' % (state, error, self.executable_))
675

676
    def runEngine(self, _):
hjk's avatar
hjk committed
677
678
679
680
        s = threading.Thread(target=self.loop, args=[])
        s.start()

    def loop(self):
681
        error = lldb.SBError()
hjk's avatar
hjk committed
682
683
        listener = self.debugger.GetListener()

684
685
686
        if self.attachPid_ > 0:
            attachInfo = lldb.SBAttachInfo(self.attachPid_)
            self.process = self.target.Attach(attachInfo, error)
687
            if not error.Success():
Fawzi Mohamed's avatar
Fawzi Mohamed committed
688
689
690
                self.report('state="inferiorrunfailed"')
                return
            self.report('pid="%s"' % self.process.GetProcessID())
691
692
693
694
            # even if it stops it seems that lldb assumes it is running and later detects that
            # it did stop after all, so it is be better to mirror that and wait for the spontaneous
            # stop
            self.report('state="enginerunandinferiorrunok"')
Fawzi Mohamed's avatar
Fawzi Mohamed committed
695
696
697
698
        elif len(self.remoteChannel_) > 0:
            self.process = self.target.ConnectRemote(
            self.debugger.GetListener(),
            self.remoteChannel_, None, error)
699
700
701
            if not error.Success():
                self.report('state="inferiorrunfailed"')
                return
702
703
704
705
            # even if it stops it seems that lldb assumes it is running and later detects that
            # it did stop after all, so it is be better to mirror that and wait for the spontaneous
            # stop
            self.report('state="enginerunandinferiorrunok"')
706
        else:
707
            launchInfo = lldb.SBLaunchInfo(self.processArgs_)
708
            launchInfo.SetWorkingDirectory(os.getcwd())
709
710
            environmentList = [key + "=" + value for key,value in os.environ.items()]
            launchInfo.SetEnvironmentEntries(environmentList, False)
711
712
            if self.breakOnMain_:
                self.createBreakpointAtMain()
713
            self.process = self.target.Launch(launchInfo, error)
714
            if not error.Success():
715
716
                self.reportError(error)
                self.report('state="enginerunfailed"')
Fawzi Mohamed's avatar
Fawzi Mohamed committed
717
718
719
                return
            self.report('pid="%s"' % self.process.GetProcessID())
            self.report('state="enginerunandinferiorrunok"')
720

hjk's avatar
hjk committed
721
722
723
724
725
726
        event = lldb.SBEvent()
        while True:
            if listener.WaitForEvent(10000000, event):
                self.handleEvent(event)
            else:
                warn('TIMEOUT')
727

728
    def describeError(self, error):
729
730
731
732
733
        desc = lldb.SBStream()
        error.GetDescription(desc)
        result = 'error={type="%s"' % error.GetType()
        result += ',code="%s"' % error.GetError()
        result += ',desc="%s"}' % desc.GetData()
734
735
736
737
        return result

    def reportError(self, error):
        self.report(self.describeError(error))
hjk's avatar
hjk committed
738
739
        if error.GetType():
            self.reportStatus(error.GetCString())
740
741

    def currentThread(self):
742
        return None if self.process is None else self.process.GetSelectedThread()
743
744

    def currentFrame(self):
745
746
        thread = self.currentThread()
        return None if thread is None else thread.GetSelectedFrame()
747
748
749

    def reportLocation(self):
        thread = self.currentThread()
750
        frame = thread.GetSelectedFrame()
751
752
753
754
        file = fileName(frame.line_entry.file)
        line = frame.line_entry.line
        self.report('location={file="%s",line="%s",addr="%s"}' % (file, line, frame.pc))

755
756
757
    def firstStoppedThread(self):
        for i in xrange(0, self.process.GetNumThreads()):
            thread = self.process.GetThreadAtIndex(i)
758
759
760
761
762
763
            reason = thread.GetStopReason()
            if (reason == lldb.eStopReasonBreakpoint or
                    reason == lldb.eStopReasonException or
                    reason == lldb.eStopReasonPlanComplete or
                    reason == lldb.eStopReasonSignal or
                    reason == lldb.eStopReasonWatchpoint):
764
765
766
                return thread
        return None

767
    def reportThreads(self):
768
769
        reasons = ['None', 'Trace', 'Breakpoint', 'Watchpoint', 'Signal', 'Exception',
            'Exec', 'PlanComplete']
770
        result = 'threads={threads=['
771
        for i in xrange(0, self.process.GetNumThreads()):
772
            thread = self.process.GetThreadAtIndex(i)
773
            stopReason = thread.GetStopReason()
774
775
            result += '{id="%d"' % thread.GetThreadID()
            result += ',index="%s"' % i
776
            result += ',details="%s"' % thread.GetQueueName()
777
778
779
            result += ',stop-reason="%s"' % stopReason
            if stopReason >= 0 and stopReason < len(reasons):
                result += ',state="%s"' % reasons[stopReason]
780
            result += ',name="%s"' % thread.GetName()
781
782
783
784
785
            result += ',frame={'
            frame = thread.GetFrameAtIndex(0)
            result += 'pc="0x%x"' % frame.pc
            result += ',addr="0x%x"' % frame.pc
            result += ',fp="0x%x"' % frame.fp
786
            result += ',func="%s"' % frame.GetFunctionName()
787
788
789
790
791
792
793
794
            result += ',line="%s"' % frame.line_entry.line
            result += ',fullname="%s"' % fileName(frame.line_entry.file)
            result += ',file="%s"' % fileName(frame.line_entry.file)
            result += '}},'

        result += '],current-thread-id="%s"},' % self.currentThread().id
        self.report(result)

795
796
797
798
799
800
801
802
    def reportChangedBreakpoints(self):
        for i in xrange(0, self.target.GetNumBreakpoints()):
            bp = self.target.GetBreakpointAtIndex(i)
            if bp.GetID() in self.breakpointsToCheck:
                if bp.GetNumLocations():
                    self.breakpointsToCheck.remove(bp.GetID())
                    self.report('breakpoint-changed={%s}' % self.describeBreakpoint(bp))

803
    def firstUsableFrame(self, thread):
hjk's avatar
hjk committed
804
        for i in xrange(10):
hjk's avatar
hjk committed
805
806
807
808
809
810
811
            frame = thread.GetFrameAtIndex(i)
            lineEntry = frame.GetLineEntry()
            line = lineEntry.GetLine()
            if line != 0:
                return i
        return None

812
    def reportStack(self, args = {}):
813
        if not self.process:
814
            self.report('msg="No process"')
815
816
            return
        thread = self.currentThread()
817
        limit = args.get('stacklimit', -1)
818
819
820
        if not thread:
            self.report('msg="No thread"')
            return
821
822
823

        (n, isLimited) = (limit, True) if limit > 0 else (thread.GetNumFrames(), False)

824
        result = 'stack={current-thread="%s"' % thread.GetThreadID()
825
826
827
        result += ',frames=['
        for i in xrange(n):
            frame = thread.GetFrameAtIndex(i)
828
829
830
            if not frame.IsValid():
                isLimited = False
                break
831
832
833
834
835
836
837
838
839
            lineEntry = frame.GetLineEntry()
            line = lineEntry.GetLine()
            result += '{pc="0x%x"' % frame.GetPC()
            result += ',level="%d"' % frame.idx
            result += ',addr="0x%x"' % frame.GetPCAddress().GetLoadAddress(self.target)
            result += ',func="%s"' % frame.GetFunctionName()
            result += ',line="%d"' % line
            result += ',fullname="%s"' % fileName(lineEntry.file)
            result += ',file="%s"},' % fileName(lineEntry.file)
840
841
842
843
        result += ']'
        result += ',hasmore="%d"' % isLimited
        result += ',limit="%d"' % limit
        result += '}'
844
        self.report(result)
845

846
847
848
849
850
851
852
853
854
855
856
857
858
859
    def reportStackPosition(self):
        thread = self.currentThread()
        if not thread:
            self.report('msg="No thread"')
            return
        frame = thread.GetSelectedFrame()
        if frame:
            self.report('stack-position={id="%s"}' % frame.GetFrameID())
        else:
            self.report('stack-position={id="-1"}')

    def reportStackTop(self):
        self.report('stack-top={}')

860
861
862
863
864
    def putBetterType(self, type):
        try:
            self.currentType = type.GetName()
        except:
            self.currentType = str(type)
865
        self.currentTypePriority = self.currentTypePriority + 1
hjk's avatar
hjk committed
866
        #warn("BETTER TYPE: %s PRIORITY: %s" % (type, self.currentTypePriority))
hjk's avatar
hjk committed
867

hjk's avatar
hjk committed
868
    def extractBlob(self, base, size):
hjk's avatar
hjk committed
869
        if size == 0:
hjk's avatar
hjk committed
870
            return Blob("")
871
872
        base = int(base) & 0xFFFFFFFFFFFFFFFF
        size = int(size) & 0xFFFFFFFF
hjk's avatar
hjk committed
873
        error = lldb.SBError()
hjk's avatar
hjk committed
874
        return Blob(self.process.ReadMemory(base, size, error))
hjk's avatar
hjk committed
875

876
877
878
879
880
881
882
883
884
885
    def toBlob(self, value):
        data = value.GetData()
        size = int(data.GetByteSize())
        buf = bytearray(struct.pack('x' * size))
        error = lldb.SBError()
        #data.ReadRawData(error, 0, buf)
        for i in range(size):
            buf[i] = data.GetUnsignedInt8(error, i)
        return Blob(bytes(buf))

886
887
888
    def extractStaticMetaObjectHelper(self, typeobj):
        if typeobj.GetTypeClass() in (lldb.eTypeClassStruct, lldb.eTypeClassClass):
            needle = typeobj.GetUnqualifiedType().GetName() + "::staticMetaObject"
889
890
891
892
893
894
895
896
            options = lldb.SBExpressionOptions()
            result = self.target.EvaluateExpression(needle, options)
            # Surprising results include:
            # (lldb) script print lldb.target.FindFirstGlobalVariable(
            # '::QSharedDataPointer<QDirPrivate>::staticMetaObject')
            # (const QMetaObject) QAbstractAnimation::staticMetaObject = { d = { ... } }
            #if result.GetName() != needle:
            if result is None or not result.IsValid():
897
898
899
900
901
902
                result = 0
        else:
            result = 0
        self.knownStaticMetaObjects[typeobj.GetName()] = result
        return result

903
    def extractStaticMetaObject(self, typeobj):
hjk's avatar
hjk committed
904
905
        if not self.isGoodLldb:
            return 0
906
907
908
909
910
        result = self.extractStaticMetaObjectHelper(typeobj)
        if result:
            return result
        base = typeobj.GetDirectBaseClassAtIndex(0).GetType()
        return self.extractStaticMetaObjectHelper(base)
hjk's avatar
hjk committed
911

912
913
914
    def stripNamespaceFromType(self, typeName):
        #type = stripClassTag(typeName)
        type = typeName
915
916
917
        ns = self.qtNamespace()
        if len(ns) > 0 and type.startswith(ns):
            type = type[len(ns):]
918
919
920
921
922
923
        pos = type.find("<")
        # FIXME: make it recognize  foo<A>::bar<B>::iterator?
        while pos != -1:
            pos1 = type.rfind(">", pos)
            type = type[0:pos] + type[pos1+1:]
            pos = type.find("<")
hjk's avatar
hjk committed
924
925
926
927
        if type.startswith("const "):
            type = type[6:]
        if type.startswith("volatile "):
            type = type[9:]
928
929
930
        return type

    def putSubItem(self, component, value, tryDynamic=True):
931
        if not value.IsValid():
932
            warn("INVALID SUBITEM: %s" % value.GetName())
933
            return
934
935
936
        with SubItem(self, component):
            self.putItem(value, tryDynamic)

hjk's avatar
hjk committed
937
    def putAddress(self, addr):
938
939
940
941
        #if int(addr) == 0xffffffffffffffff:
        #    raise RuntimeError("Illegal address")
        if self.currentPrintsAddress and not addr is None:
            self.put('addr="0x%x",' % int(addr))
hjk's avatar
hjk committed
942

hjk's avatar
hjk committed
943
944
945
946
947
    def isFunctionType(self, typeobj):
        if self.isGoodLldb:
            return typeobj.IsFunctionType()
        #warn("TYPE: %s" % typeobj)
        return False
hjk's avatar
hjk committed
948

949
    def putItem(self, value, tryDynamic=True):
hjk's avatar
hjk committed
950
        #value = value.GetDynamicValue(lldb.eDynamicCanRunTarget)
951
        typeName = value.GetType().GetUnqualifiedType().GetName()
hjk's avatar
hjk committed
952
953
        if self.isGoodLldb:
            value.SetPreferDynamicValue(tryDynamic)
hjk's avatar
hjk committed
954
        typeClass = value.GetType().GetTypeClass()
955

hjk's avatar
hjk committed
956
        if tryDynamic:
957
            self.putAddress(value.GetLoadAddress())
hjk's avatar
hjk committed
958

959
        # Handle build-in LLDB visualizers if wanted.
960
        if False and self.useLldbDumpers and value.GetTypeSynthetic().IsValid():
961
962
963
964
            # FIXME: print "official" summary?
            summary = value.GetTypeSummary()
            if summary.IsValid():
                warn("DATA: %s" % summary.GetData())
hjk's avatar
hjk committed
965
966
            if self.isGoodLldb:
                value.SetPreferSyntheticValue(False)
967
968
969
970
971
            provider = value.GetTypeSynthetic()
            data = provider.GetData()
            formatter = eval(data)(value, {})
            formatter.update()
            numchild = formatter.num_children()
hjk's avatar
hjk committed
972
            self.put('iname="%s",' % self.currentIName)
hjk's avatar
hjk committed
973
            self.putType(typeName)
hjk's avatar
hjk committed
974
975
            self.put('numchild="%s",' % numchild)
            self.put('addr="0x%x",' % value.GetLoadAddress())
976
            self.putItemCount(numchild)
hjk's avatar
hjk committed
977
978
            if self.currentIName in self.expandedINames:
                with Children(self):
979
980
981
982
983
984
                    for i in xrange(numchild):
                        child = formatter.get_child_at_index(i)
                        with SubItem(self, i):
                            self.putItem(child)
            return

hjk's avatar
hjk committed
985
986
        # Typedefs
        if typeClass == lldb.eTypeClassTypedef:
987
            if typeName in self.qqDumpers:
hjk's avatar
hjk committed
988
989
                self.putType(typeName)
                self.context = value
990
                self.qqDumpers[typeName](self, value)
hjk's avatar
hjk committed
991
                return
hjk's avatar
hjk committed
992
993
            realType = value.GetType()
            if hasattr(realType, 'GetCanonicalType'):
994
995
996
997
                baseType = realType.GetCanonicalType()
                baseValue = value.Cast(baseType.unqualified())
                self.putItem(baseValue)
                self.putBetterType(realType)
hjk's avatar
hjk committed
998
                return
hjk's avatar
hjk committed
999

1000
        # Our turf now.
hjk's avatar
hjk committed
1001
1002
        if self.isGoodLldb:
            value.SetPreferSyntheticValue(False)
hjk's avatar