lldbbridge.py 60.4 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 re
35
36
import select
import sys
37
import subprocess
38
import threading
39

40
41
42
43
44
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
45
46
47
from stdtypes import *
from misctypes import *
from boosttypes import *
48
from creatortypes import *
49

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

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

57
if error.startswith('lldb: invalid option -- P'):
58
    sys.stdout.write('msg=\'Could not run "%s -P". Trying to find lldb.so from Xcode.\'@\n' % lldbCmd)
59
60
61
62
63
    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/'
64
65
        sys.stdout.write('msg=\'Could not run "xcode-select --print-path"@\n')
        sys.stdout.write('msg=\'Using hardcoded fallback at %s\'@\n' % path)
66
67
    else:
        path = path.strip() + '/../SharedFrameworks/LLDB.framework/Versions/A/Resources/Python/'
68
        sys.stdout.write('msg=\'Using fallback at %s\'@\n' % path)
69

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

import lldb
73
74
75
76
77
78
79

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

80
qqWatchpointOffset = 10000
81

82
lldb.theDumper = None
83
84

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

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

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

96

97
98
99
100
101
102
103
104
105
106
# 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
107
108
109
110
111
BreakpointAtSysCall = 9
WatchpointAtAddress = 10
WatchpointAtExpression = 11
BreakpointOnQmlSignalEmit = 12
BreakpointAtJavaScriptThrow = 13
112

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

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

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

126
127
Value = lldb.SBValue

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

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

143
def impl_SBValue__sub__(self, other):
144
    if self.GetType().IsPointerType():
145
146
147
148
        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())
149
        if other.GetType().IsPointerType():
150
151
            itemsize = self.GetType().GetPointeeType().GetByteSize()
            return (self.GetValueAsUnsigned() - other.GetValueAsUnsigned()) / itemsize
152
    raise RuntimeError("SBValue.__sub__ not implemented: %s" % self.GetType())
153
154
    return NotImplemented

155
156
157
158
159
160
161
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):
162
    return self.GetValueAsSigned()
163
164
165
166
167
168
169
170
171
172

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
173

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

177
178
179
180
181
182
183
184
185
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)
186
    return value.GetChildMemberWithName(index)
187

188
189
190
191
def impl_SBValue__deref(value):
    result = value.Dereference()
    if result.IsValid():
        return result
192
193
194
    #warn("RESULT.LOADADDRESS A: 0x%x" % result.GetLoadAddress())
    result = value.CreateValueFromAddress(None, value.GetValueAsUnsigned(), value.GetType().GetPointerType())
    #warn("RESULT.LOADADDRESS B: 0x%x" % result.GetLoadAddress())
195
196
    return result

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

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

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

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


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

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

225
226
227
228
def simpleEncoding(typeobj):
    code = typeobj.GetTypeClass()
    size = typeobj.sizeof
    if code == lldb.eTypeClassBuiltin:
hjk's avatar
hjk committed
229
230
231
232
233
234
        name = str(typeobj)
        if name == "float":
            return Hex2EncodedFloat4
        if name == "double":
            return Hex2EncodedFloat8
        if name.find("unsigned") >= 0:
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
            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
hjk's avatar
hjk committed
253

254
class Dumper(DumperBase):
255
    def __init__(self):
256
257
        DumperBase.__init__(self)

258
259
        lldb.theDumper = self

260
        self.debugger = lldb.SBDebugger.Create()
261
        #self.debugger.SetLoggingCallback(loggingCallback)
262
263
264
265
266
267
        #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")
268
269
270
271
272
273
274
275
276
277

        # 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)

278
        self.isLldb = True
279
280
281
282
        self.process = None
        self.target = None
        self.eventState = lldb.eStateInvalid
        self.expandedINames = {}
283
        self.passExceptions = False
284
        self.useLldbDumpers = False
hjk's avatar
hjk committed
285
        self.autoDerefPointers = True
286
        self.useDynamicType = True
hjk's avatar
hjk committed
287
        self.useFancy = True
hjk's avatar
hjk committed
288
289
        self.formats = {}
        self.typeformats = {}
290
291
292
293
294
295

        self.currentIName = None
        self.currentValuePriority = -100
        self.currentValueEncoding = None
        self.currentType = ""
        self.currentTypePriority = -100
296
        self.currentValue = None
297
298
299
300
301
        self.currentNumChild = None
        self.currentMaxNumChild = None
        self.currentPrintsAddress = None
        self.currentChildType = None
        self.currentChildNumChild = None
302
        self.currentWatchers = {}
303

hjk's avatar
hjk committed
304
        self.executable_ = None
305
306
307
308
        self.startMode_ = None
        self.processArgs_ = None
        self.attachPid_ = None

309
310
        self.charType_ = None
        self.intType_ = None
311
        self.int64Type_ = None
312
313
        self.sizetType_ = None
        self.charPtrType_ = None
hjk's avatar
hjk committed
314
        self.voidPtrType_ = None
315
        self.isShuttingDown_ = False
316
        self.isInterrupting_ = False
317
        self.dummyValue = None
318
        self.types_ = {}
319

320
321
322
323
324
325
326
327
328
    def enterSubItem(self, item):
        if isinstance(item.name, lldb.SBValue):
            # Avoid $$__synth__ suffix on Mac.
            value = item.name
            value.SetPreferSyntheticValue(False)
            item.name = value.GetName()
            if item.name is None:
                self.anonNumber += 1
                item.name = "#%d" % self.anonNumber
329
330
        if not item.iname:
            item.iname = "%s.%s" % (self.currentIName, item.name)
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
356
357
358
359
360
361
362
        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:
363
                    self.put('valueencoded="%s",' % self.currentValueEncoding)
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
                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
380
381
382
    def childWithName(self, value, name):
        child = value.GetChildMemberWithName(name)
        return child if child.IsValid() else None
383

384
385
386
387
388
389
390
391
392
    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()

393
394
395
396
397
    def enumExpression(self, enumType, enumValue):
        ns = self.qtNamespace()
        return ns + "Qt::" + enumType + "(" \
            + ns + "Qt::" + enumType + "::" + enumValue + ")"

398
399
400
401
402
403
404
    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)
405
        result = value.CreateValueFromExpression('', exp)
406
407
408
        #warn("  -> %s" % result)
        return result

409
410
411
412
413
414
415
416
417
418
    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

419
420
421
422
423
    def parseAndEvaluate(self, expr):
        thread = self.currentThread()
        frame = thread.GetFrameAtIndex(0)
        return frame.EvaluateExpression(expr)

424
425
426
427
428
429
430
431
432
433
434
435
436
    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)

437
    def templateArgument(self, typeobj, index):
438
        type = typeobj.GetTemplateArgumentType(index)
hjk's avatar
hjk committed
439
        if type.IsValid():
440
441
442
443
444
445
446
            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)
447

hjk's avatar
hjk committed
448
449
450
451
452
453
    def isReferenceType(self, typeobj):
        return typeobj.IsReferenceType()

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

454
455
    def qtVersionAndNamespace(self):
        self.cachedQtNamespace = ""
456
        self.cachedQtVersion = 0x0
457

458
459
460
        coreExpression = re.compile(r"(lib)?Qt5?Core")
        for n in range(0, self.target.GetNumModules()):
            module = self.target.GetModuleAtIndex(n)
461
462
            fileName = module.GetFileSpec().GetFilename()
            if coreExpression.match(fileName):
463
                # Extract version.
464
                reverseVersion = module.GetVersion()
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
                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")

481
482
483
484
485
486
487
488
489
490

                # 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
491
                break
492
493

        # Memoize good results.
494
        self.qtNamespace = lambda: self.cachedQtNamespace
495
        self.qtVersion = lambda: self.cachedQtVersion
496
497
498
499
500
501

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

    def qtVersion(self):
502
        self.qtVersionAndNamespace()
503
        return self.cachedQtVersion
504

hjk's avatar
hjk committed
505
506
507
    def intSize(self):
        return 4

508
509
    def intType(self):
        if self.intType_ is None:
hjk's avatar
hjk committed
510
             self.intType_ = self.target.FindFirstType('int')
511
512
        return self.intType_

513
514
515
516
517
    def int64Type(self):
        if self.int64Type_ is None:
             self.int64Type_ = self.target.FindFirstType('long long int')
        return self.int64Type_

518
519
    def charType(self):
        if self.charType_ is None:
hjk's avatar
hjk committed
520
             self.charType_ = self.target.FindFirstType('char')
521
522
523
524
525
526
527
528
        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
529
530
531
        if self.voidPtrType_ is None:
             self.voidPtrType_ = self.target.FindFirstType('void').GetPointerType()
        return self.voidPtrType_
532

hjk's avatar
hjk committed
533
    def ptrSize(self):
534
535
536
537
538
539
540
        return self.charPtrType().GetByteSize()

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

541
542
543
    def addressOf(self, value):
        return int(value.GetLoadAddress())

hjk's avatar
hjk committed
544
545
546
    def extractInt(self, address):
        return int(self.createValue(address, self.intType()))

547
548
549
    def extractInt64(self, address):
        return int(self.createValue(address, self.int64Type()))

550
551
552
    def extractByte(self, address):
        return int(self.createValue(address, self.charType())) & 0xFF

553
554
555
556
557
558
    def handleCommand(self, command):
        result = lldb.SBCommandReturnObject()
        self.debugger.GetCommandInterpreter().HandleCommand(command, result)
        success = result.Succeeded()
        if success:
            self.report('output="%s"' % result.GetOutput())
559
        else:
560
561
562
563
564
565
            self.report('error="%s"' % result.GetError())
        self.reportData()

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

566
    def isMovableType(self, type):
567
        if type.GetTypeClass() in (lldb.eTypeClassBuiltin, lldb.eTypeClassPointer):
568
            return True
569
        return self.isKnownMovableType(self.stripNamespaceFromType(type.GetName()))
570

571
572
    def putNumChild(self, numchild):
        #warn("NUM CHILD: '%s' '%s'" % (numchild, self.currentChildNumChild))
hjk's avatar
hjk committed
573
574
        #if numchild != self.currentChildNumChild:
        self.put('numchild="%s",' % numchild)
575

576
577
578
579
580
581
582
    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
583
584
585
    def putSimpleValue(self, value, encoding = None, priority = 0):
        self.putValue(value.GetValue(), encoding, priority)

586
    def tryPutArrayContents(self, typeobj, base, n):
587
        if not self.isSimpleType(typeobj):
588
589
590
            return False
        size = n * typeobj.sizeof
        self.put('childtype="%s",' % typeobj)
591
592
        self.put('addrbase="0x%x",' % int(base))
        self.put('addrstep="%d",' % typeobj.sizeof)
593
594
        self.put('arrayencoding="%s",' % simpleEncoding(typeobj))
        self.put('arraydata="')
595
        self.put(self.readMemory(base, size))
596
597
598
599
600
601
        self.put('",')
        return True

    def putArrayData(self, type, base, n,
            childNumChild = None, maxNumChild = 10000):
        if not self.tryPutArrayContents(type, base, n):
602
            base = self.createPointerValue(base, type)
603
604
605
606
607
            with Children(self, n, type, childNumChild, maxNumChild,
                    base, type.GetByteSize()):
                for i in self.childRange():
                    self.putSubItem(i, (base + i).dereference())

608
609
610
611
612
613
614
615
    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)

616
    def putCallItem(self, name, value, func, *args):
617
        result = self.call2(value, func, args)
618
619
620
        with SubItem(self, name):
            self.putItem(result)

621
622
623
624
625
    def childRange(self):
        if self.currentMaxNumChild is None:
            return xrange(0, self.currentNumChild)
        return xrange(min(self.currentMaxNumChild, self.currentNumChild))

626
627
628
    def canonicalTypeName(self, name):
        return re.sub('\\bconst\\b', '', name).replace(' ', '')

629
    def lookupType(self, name):
hjk's avatar
hjk committed
630
        #warn("LOOKUP TYPE NAME: %s" % name)
hjk's avatar
hjk committed
631
        if name.endswith('*'):
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
            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
652

653
    def setupInferior(self, args):
654
        error = lldb.SBError()
655
656

        self.executable_ = args['executable']
657
658
659
        self.startMode_ = args.get('startMode', 1)
        self.processArgs_ = args.get('processArgs', '')
        self.attachPid_ = args.get('attachPid', 0)
Fawzi Mohamed's avatar
Fawzi Mohamed committed
660
        self.sysRoot_ = args.get('sysRoot', '')
Fawzi Mohamed's avatar
Fawzi Mohamed committed
661
        self.remoteChannel_ = args.get('remoteChannel', '')
662
        self.platform_ = args.get('platform', '')
663

664
665
        if self.platform_:
            self.debugger.SetCurrentPlatform(self.platform_)
Fawzi Mohamed's avatar
Fawzi Mohamed committed
666
667
668
        # sysroot has to be set *after* the platform
        if self.sysRoot_:
            self.debugger.SetCurrentPlatformSDKRoot(self.sysRoot_)
669
        self.target = self.debugger.CreateTarget(self.executable_, None, None, True, error)
670
671
        self.importDumpers()

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

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

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

683
684
685
        if self.attachPid_ > 0:
            attachInfo = lldb.SBAttachInfo(self.attachPid_)
            self.process = self.target.Attach(attachInfo, error)
686
            if not error.Success():
Fawzi Mohamed's avatar
Fawzi Mohamed committed
687
688
689
                self.report('state="inferiorrunfailed"')
                return
            self.report('pid="%s"' % self.process.GetProcessID())
690
691
692
693
            # 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
694
695
696
697
        elif len(self.remoteChannel_) > 0:
            self.process = self.target.ConnectRemote(
            self.debugger.GetListener(),
            self.remoteChannel_, None, error)
698
699
700
            if not error.Success():
                self.report('state="inferiorrunfailed"')
                return
701
702
703
704
            # 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"')
705
        else:
706
            launchInfo = lldb.SBLaunchInfo(self.processArgs_.split())
707
            launchInfo.SetWorkingDirectory(os.getcwd())
708
709
            environmentList = [key + "=" + value for key,value in os.environ.items()]
            launchInfo.SetEnvironmentEntries(environmentList, False)
710
            self.process = self.target.Launch(launchInfo, error)
711
            if not error.Success():
712
713
                self.reportError(error)
                self.report('state="enginerunfailed"')
Fawzi Mohamed's avatar
Fawzi Mohamed committed
714
715
716
                return
            self.report('pid="%s"' % self.process.GetProcessID())
            self.report('state="enginerunandinferiorrunok"')
717

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

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

    def reportError(self, error):
        self.report(self.describeError(error))
736
737

    def currentThread(self):
738
        return None if self.process is None else self.process.GetSelectedThread()
739
740

    def currentFrame(self):
741
742
        thread = self.currentThread()
        return None if thread is None else thread.GetSelectedFrame()
743
744
745

    def reportLocation(self):
        thread = self.currentThread()
746
        frame = thread.GetSelectedFrame()
747
748
749
750
        file = fileName(frame.line_entry.file)
        line = frame.line_entry.line
        self.report('location={file="%s",line="%s",addr="%s"}' % (file, line, frame.pc))

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

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

791
    def firstUsableFrame(self, thread):
hjk's avatar
hjk committed
792
        for i in xrange(10):
hjk's avatar
hjk committed
793
794
795
796
797
798
799
            frame = thread.GetFrameAtIndex(i)
            lineEntry = frame.GetLineEntry()
            line = lineEntry.GetLine()
            if line != 0:
                return i
        return None

hjk's avatar
hjk committed
800
    def reportStack(self, _ = None):
801
        if not self.process:
802
            self.report('msg="No process"')
803
804
805
806
807
808
809
810
            return
        thread = self.currentThread()
        if not thread:
            self.report('msg="No thread"')
            return
        frame = thread.GetSelectedFrame()
        if frame:
            frameId = frame.GetFrameID()
811
        else:
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
            frameId = 0;
        result = 'stack={current-frame="%s"' % frameId
        result += ',current-thread="%s"' % thread.GetThreadID()
        result += ',frames=['
        n = thread.GetNumFrames()
        for i in xrange(n):
            frame = thread.GetFrameAtIndex(i)
            lineEntry = frame.GetLineEntry()
            line = lineEntry.GetLine()
            usable = line != 0
            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 += ',usable="%d"' % usable
            result += ',file="%s"},' % fileName(lineEntry.file)
        result += '],hasmore="0"},'
        self.report(result)
832

833
834
835
836
837
    def putBetterType(self, type):
        try:
            self.currentType = type.GetName()
        except:
            self.currentType = str(type)
838
        self.currentTypePriority = self.currentTypePriority + 1
hjk's avatar
hjk committed
839
        #warn("BETTER TYPE: %s PRIORITY: %s" % (type, self.currentTypePriority))
hjk's avatar
hjk committed
840

hjk's avatar
hjk committed
841
    def extractBlob(self, base, size):
hjk's avatar
hjk committed
842
        if size == 0:
hjk's avatar
hjk committed
843
            return Blob("")
844
845
        base = int(base) & 0xFFFFFFFFFFFFFFFF
        size = int(size) & 0xFFFFFFFF
hjk's avatar
hjk committed
846
        error = lldb.SBError()
hjk's avatar
hjk committed
847
        return Blob(self.process.ReadMemory(base, size, error))
hjk's avatar
hjk committed
848

849
850
851
852
853
854
855
856
857
858
    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))

859
860
861
862
863
864
865
866
867
868
869
    def extractStaticMetaObjectHelper(self, typeobj):
        if typeobj.GetTypeClass() in (lldb.eTypeClassStruct, lldb.eTypeClassClass):
            needle = typeobj.GetUnqualifiedType().GetName() + "::staticMetaObject"
            result = self.target.FindFirstGlobalVariable(needle)
            if result is None:
                result = 0
        else:
            result = 0
        self.knownStaticMetaObjects[typeobj.GetName()] = result
        return result

870
    def extractStaticMetaObject(self, typeobj):
871
872
873
874
875
        result = self.extractStaticMetaObjectHelper(typeobj)
        if result:
            return result
        base = typeobj.GetDirectBaseClassAtIndex(0).GetType()
        return self.extractStaticMetaObjectHelper(base)
hjk's avatar
hjk committed
876

877
878
879
    def stripNamespaceFromType(self, typeName):
        #type = stripClassTag(typeName)
        type = typeName
880
881
882
        ns = self.qtNamespace()
        if len(ns) > 0 and type.startswith(ns):
            type = type[len(ns):]
883
884
885
886
887
888
        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
889
890
891
892
        if type.startswith("const "):
            type = type[6:]
        if type.startswith("volatile "):
            type = type[9:]
893
894
895
        return type

    def putSubItem(self, component, value, tryDynamic=True):
896
        if not value.IsValid():
897
            warn("INVALID SUBITEM: %s" % value.GetName())
898
            return
899
900
901
        with SubItem(self, component):
            self.putItem(value, tryDynamic)

hjk's avatar
hjk committed
902
    def putAddress(self, addr):
903
904
905
906
        #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
907

hjk's avatar
hjk committed
908
909
910
    def isFunctionType(self, type):
        return type.IsFunctionType()

911
    def putItem(self, value, tryDynamic=True):
hjk's avatar
hjk committed
912
        #value = value.GetDynamicValue(lldb.eDynamicCanRunTarget)
913
        typeName = value.GetType().GetUnqualifiedType().GetName()
914
        value.SetPreferDynamicValue(tryDynamic)
hjk's avatar
hjk committed
915
        typeClass = value.GetType().GetTypeClass()
916

hjk's avatar
hjk committed
917
        if tryDynamic:
918
            self.putAddress(value.GetLoadAddress())
hjk's avatar
hjk committed
919

920
        # Handle build-in LLDB visualizers if wanted.
921
        if False and self.useLldbDumpers and value.GetTypeSynthetic().IsValid():
922
923
924
925
926
927
928
929
930
931
            # FIXME: print "official" summary?
            summary = value.GetTypeSummary()
            if summary.IsValid():
                warn("DATA: %s" % summary.GetData())
            value.SetPreferSyntheticValue(False)
            provider = value.GetTypeSynthetic()
            data = provider.GetData()
            formatter = eval(data)(value, {})
            formatter.update()
            numchild = formatter.num_children()
hjk's avatar
hjk committed
932
            self.put('iname="%s",' % self.currentIName)
hjk's avatar
hjk committed
933
            self.putType(typeName)
hjk's avatar
hjk committed
934
935
            self.put('numchild="%s",' % numchild)
            self.put('addr="0x%x",' % value.GetLoadAddress())
936
            self.putItemCount(numchild)
hjk's avatar
hjk committed
937
938
            if self.currentIName in self.expandedINames:
                with Children(self):
939
940
941
942
943
944
                    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
945
946
        # Typedefs
        if typeClass == lldb.eTypeClassTypedef:
947
            if typeName in self.qqDumpers:
hjk's avatar
hjk committed
948
949
                self.putType(typeName)
                self.context = value
950
                self.qqDumpers[typeName](self, value)
hjk's avatar
hjk committed
951
                return
hjk's avatar
hjk committed
952
953
            realType = value.GetType()
            if hasattr(realType, 'GetCanonicalType'):
954
955
956
957
                baseType = realType.GetCanonicalType()
                baseValue = value.Cast(baseType.unqualified())
                self.putItem(baseValue)
                self.putBetterType(realType)
hjk's avatar
hjk committed
958
                return
hjk's avatar
hjk committed
959

960
        # Our turf now.
961
        value.SetPreferSyntheticValue(False)
962

963
        # Arrays
hjk's avatar
hjk committed
964
        if typeClass == lldb.eTypeClassArray:
965
            self.putCStyleArray(value)
966
967
            return

968
969
        # Vectors like char __attribute__ ((vector_size (8)))
        if typeClass == lldb.eTypeClassVector:
970
            self.putCStyleArray(value)
971
972
            return

973
974
        # References
        if value.GetType().IsReferenceType():
hjk's avatar
hjk committed
975
            origType = value.GetTypeName();
hjk's avatar
hjk committed
976
            type = value.GetType().GetDereferencedType().unqualified()
hjk's avatar
hjk committed
977
            addr = int(value) & 0xFFFFFFFFFFFFFFFF
hjk's avatar
hjk committed
978
            self.putItem(value.CreateValueFromAddress(None, addr, type))
hjk's avatar
hjk committed
979
            self.putBetterType(origType)
980
981
            return

hjk's avatar
hjk committed
982
        # Pointers
hjk's avatar
hjk committed
983
        if value.GetType().IsPointerType():
hjk's avatar
hjk committed
984
985
            self.putFormattedPointer(value)
            return
hjk's avatar
hjk committed
986

987
        #warn("VALUE: %s" % value)
hjk's avatar
hjk committed
988
989
990
991
        #warn("FANCY: %s" % self.useFancy)
        if self.useFancy:
            stripped = self.stripNamespaceFromType(typeName).replace("::", "__")
            #warn("STRIPPED: %s" % stripped)
992
993
            #warn("DUMPABLE: %s" % (stripped in self.qqDumpers))
            if stripped in self.qqDumpers:
hjk's avatar
hjk committed
994
                self.putType(typeName)
hjk's avatar
hjk committed
995
                self.context = value
996
                self.qqDumpers[stripped](self, value)
hjk's avatar
hjk committed
997
                return
998
999
1000
1001

        # Normal value
        #numchild = 1 if value.MightHaveChildren() else 0
        numchild = value.GetNumChildren()
hjk's avatar
hjk committed
1002
        self.putType(typeName)
1003
1004
1005
1006
1007
        self.putEmptyValue(-1)
        staticMetaObject = self.extractStaticMetaObject(value.GetType())
        if staticMetaObject:
            self.context = value
            self.putQObjectNameValue(value)
hjk's avatar
hjk committed
1008
1009
1010
1011
1012
        else:
            v = value.GetValue()
            if v:
                self.putValue(v)

1013
        self.put('numchild="%s",' % numchild)
1014

1015
1016
1017
        if self.currentIName in self.expandedINames:
            with Children(self):
                self.putFields(value)
1018
1019
                if staticMetaObject:
                    self.putQObjectGuts(value, staticMetaObject)
1020

1021
1022
1023
    def warn(self, msg):
        self.put('{name="%s",value="",type=""},' % msg)

1024
    def putFields(self, value):
1025
1026
1027
1028
        # Suppress printing of 'name' field for arrays.
        if value.GetType().GetTypeClass() == lldb.eTypeClassArray:
            for i in xrange(value.GetNumChildren()):
                child = value.GetChildAtIndex(i)
1029
                with UnnamedSubItem(self, str(i)):
1030
1031
1032
                    self.putItem(child)
            return

1033
        n = value.GetNumChildren()
1034
        m = value.GetType().GetNumberOfDirectBaseClasses()
1035
1036
        if n > 10000:
            n = 10000
1037
1038
1039
        # seems to happen in the 'inheritance' autotest
        if m > n:
            m = n
1040
1041
1042
        for i in xrange(m):
            child = value.GetChildAtIndex(i)
            with UnnamedSubItem(self, "@%d" % (i + 1)):
1043
                self.put('iname="%s",' % self.currentIName)
1044
1045
1046
                self.put('name="[%s]",' % child.name)
                self.putItem(child)
        for i in xrange(m, n):
1047
        #for i in range(n):
hjk's avatar
hjk committed
1048
            child = value.GetChildAtIndex(i)
1049
1050
1051
1052
1053
            if int(child.GetLoadAddress()) == 0xffffffffffffffff:
                typeClass = child.GetType().GetTypeClass()
                if typeClass != lldb.eTypeClassBuiltin:
                    field = value.GetType().GetFieldAtIndex(i)
                    addr = value.GetLoadAddress() + field.GetOffsetInBytes()
1054
                    child = value.CreateValueFromAddress(child.GetName(), addr, child.GetType())
hjk's avatar
hjk committed
1055
1056
1057
            if child.IsValid():  # FIXME: Anon members?
                with SubItem(self, child):
                    self.putItem(child)
1058

hjk's avatar
hjk committed
1059
    def reportVariables(self, _ = None):
1060
1061
1062
        frame = self.currentFrame()
        if frame is None:
            return
1063
        self.currentIName = 'local'
1064
        self.put('data=[')
1065
        self.anonNumber = 0
1066
        shadowed = {}
1067
        ids = {} # Filter out duplicates entries at the same address.
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
        values = list(frame.GetVariables(True, True, False, False))

        # We need to look at static variables to get access to
        # local constants. But not at all of them.
        for staticVar in frame.GetVariables(False, False, True, False):
            typename = staticVar.GetType().GetName()
            name = staticVar.GetName()
            if name.startswith("qt_meta_stringdata_"):
                continue
            if name.startswith("qt_meta_data_"):
                continue
            if name.endswith("::staticMetaObject") \
                    and typename.endswith("QMetaObject"):
                continue
            values.append(staticVar)

1084
1085
        values.reverse() # To get shadowed vars numbered backwards.
        for value in values:
1086
1087
1088
            if not value.IsValid():
                continue
            name = value.GetName()
1089
            id = "%s:0x%x" % (name, value.GetLoadAddress())
1090
1091
1092
            if id in ids:
                continue
            ids[id] = True
1093
1094
            #if self.dummyValue is None:
            #    self.dummyValue = value
1095
1096
1097
            if name is None:
                warn("NO NAME FOR VALUE: %s" % value)
                continue
1098
            if name in shadowed:
1099
1100
1101
1102
1103
1104
1105
1106
                level = shadowed[name]
                shadowed[name] = level + 1
                name += "@%s" % level
            else:
                shadowed[name] = 1
            with SubItem(self, name):
                self.put('iname="%s",' % self.currentIName)
                self.putItem(value)
1107
1108

        # 'watchers':[{'id':'watch.0','exp':'23'},...]
1109
1110
1111
1112
1113
        #if not self.dummyValue is None:
        for watcher in self.currentWatchers:
            iname = watcher['iname']
            # could be 'watch.0' or 'tooltip.deadbead'
            (base, component) = iname.split('.')
hjk's avatar
hjk committed
1114
            exp = self.hexdecode(watcher['exp'])
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
            if exp == "":
                self.put('type="",value="",exp=""')
                continue

            options = lldb.SBExpressionOptions()
            value = self.target.EvaluateExpression(exp, options)
            #value = self.target.EvaluateExpression(iname, exp)
            self.currentIName = base
            with SubItem(self, component):
                self.put('exp="%s",' % exp)
hjk's avatar
hjk committed
1125
                self.put('wname="%s",' % self.hexencode(exp))
1126
1127
                self.put('iname="%s",' % iname)
                self.putItem(value)
1128

1129
1130
1131
        self.put(']')
        self.report('')

hjk's avatar
hjk committed
1132
    def reportData(self, _ = None):
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
        if self.process is None:
            self.report('process="none"')
        else:
            state = self.process.GetState()
            if state == lldb.eStateStopped:
                self.reportStack()
                self.reportThreads()
                self.reportLocation()
                self.reportVariables()

1143
    def reportRegisters(self, _ = None):
1144
1145
1146
1147
        if self.process is None:
            self.report('process="none"')
        else:
            frame = self.currentFrame()
1148
1149
1150
1151
1152
1153
1154
1155
1156
            if frame:
                result = 'registers=['
                for group in frame.GetRegisters():
                    for reg in group:
                        result += '{name="%s"' % reg.GetName()
                        result += ',value="%s"' % reg.GetValue()
                        result += ',type="%s"},' % reg.GetType()
                result += ']'
                self.report(result)
1157
1158

    def report(self, stuff):
1159
        sys.stdout.write(stuff + "@\n")
1160

hjk's avatar
hjk committed
1161
    def interruptInferior(self, _ = None):
1162
1163
        if self.process is None:
            self.report('msg="No process"')
1164
            return
1165
        self.isInterrupting_ = True
1166
1167
        error = self.process.Stop()
        self.reportError(error)
1168

hjk's avatar
hjk committed
1169
    def detachInferior(self, _ = None):
1170
1171
1172
1173
1174
1175
        if self.process is None:
            self.report('msg="No process"')
        else:
            error = self.process.Detach()
            self.reportError(error)
            self.reportData()
1176

hjk's avatar
hjk committed
1177
    def continueInferior(self, _ = None):
1178
1179
1180
1181
1182
1183
        if self.process is None:
            self.report('msg="No process"')
        else:
            error = self.process.Continue()
            self.reportError(error)

1184
1185
1186
1187
    def quitDebugger(self, _ = None):
        self.report('state="inferiorshutdownrequested"')
        self.process.Kill()

1188
1189
1190
    def handleEvent(self, event):
        out = lldb.SBStream()
        event.GetDescription(out)
1191
        #warn("EVENT: %s" % event)
1192
1193
1194
        type = event.GetType()
        msg = lldb.SBEvent.GetCStringFromEvent(event)
        flavor = event.GetDataFlavor()
1195
        state = lldb.SBProcess.GetStateFromEvent(event)
1196
        self.report('event={type="%s",data="%s",msg="%s",flavor="%s",state="%s"}'
1197
1198
1199
            % (type, out.GetData(), msg, flavor, state))
        if state != self.eventState:
            self.eventState = state
hjk's avatar
hjk committed
1200
            if state == lldb.eStateExited:
1201
1202
1203
1204
1205
                if self.isShuttingDown_:
                    self.report('state="inferiorshutdownok"')
                else:
                    self.report('state="inferiorexited"')
                self.report('exited={status="%s",desc="%s"}'
hjk's avatar
hjk committed
1206
                    % (self.process.GetExitStatus(), self.process.GetExitDescription()))
1207
1208
1209
1210
1211
1212
1213
1214
            elif state == lldb.eStateStopped:
                if self.isInterrupting_:
                    self.isInterrupting_ = False
                    self.report('state="inferiorstopok"')
                else:
                    self.report('state="stopped"')
            else:
                self.report('state="%s"' % stateNames[state])
1215
        if type == lldb.SBProcess.eBroadcastBitStateChanged:
hjk's avatar
hjk committed
1216
1217
            state = self.process.GetState()
            if state == lldb.eStateStopped:
1218
1219
1220
1221
1222
1223
                stoppedThread = self.firstStoppedThread()
                if stoppedThread:
                    self.process.SetSelectedThread(stoppedThread)
                    usableFrame = self.firstUsableFrame(stoppedThread)
                    if usableFrame:
                        stoppedThread.SetSelectedFrame(usableFrame)
hjk's avatar
hjk committed
1224
1225
1226
1227
                self.reportStack()
                self.reportThreads()
                self.reportLocation()
                self.reportVariables()
1228
                self.reportRegisters()
1229
1230
1231
        elif type == lldb.SBProcess.eBroadcastBitInterrupt:
            pass
        elif type == lldb.SBProcess.eBroadcastBitSTDOUT:
1232
1233
1234
            # FIXME: Size?
            msg = self.process.GetSTDOUT(1024)
            self.report('output={channel="stdout",data="%s"}'
hjk's avatar
hjk committed
1235
                % self.hexencode(msg))
1236
        elif type == lldb.SBProcess.eBroadcastBitSTDERR:
1237
            msg = self.process.GetSTDERR(1024)
hjk's avatar