lbridge.py 48.2 KB
Newer Older
1

2
import atexit
3
import binascii
4 5
import inspect
import os
6 7 8
import threading
import select
import sys
9 10
import subprocess

11

12 13 14 15
proc = subprocess.Popen(args=[sys.argv[1], "-P"], stdout=subprocess.PIPE)
path = proc.stdout.read().strip()
#sys.path.append(path)
sys.path.insert(1, path)
16 17

import lldb
18 19 20

cdbLoaded = False
gdbLoaded = False
21
lldbLoaded = True
22

hjk's avatar
hjk committed
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
# Encodings. Keep that synchronized with DebuggerEncoding in watchutils.h
Unencoded8Bit, \
Base64Encoded8BitWithQuotes, \
Base64Encoded16BitWithQuotes, \
Base64Encoded32BitWithQuotes, \
Base64Encoded16Bit, \
Base64Encoded8Bit, \
Hex2EncodedLatin1, \
Hex4EncodedLittleEndian, \
Hex8EncodedLittleEndian, \
Hex2EncodedUtf8, \
Hex8EncodedBigEndian, \
Hex4EncodedBigEndian, \
Hex4EncodedLittleEndianWithoutQuotes, \
Hex2EncodedLocal8Bit, \
JulianDate, \
MillisecondsSinceMidnight, \
JulianDateAndMillisecondsSinceMidnight, \
Hex2EncodedInt1, \
Hex2EncodedInt2, \
Hex2EncodedInt4, \
Hex2EncodedInt8, \
Hex2EncodedUInt1, \
Hex2EncodedUInt2, \
Hex2EncodedUInt4, \
Hex2EncodedUInt8, \
Hex2EncodedFloat4, \
Hex2EncodedFloat8 \
    = range(27)

# Display modes. Keep that synchronized with DebuggerDisplay in watchutils.h
StopDisplay, \
DisplayImageData, \
DisplayUtf16String, \
DisplayImageFile, \
DisplayProcess, \
DisplayLatin1String, \
DisplayUtf8String \
    = range(7)

63
def lookupType(name):
64
    return None
65 66 67 68 69 70

def isSimpleType(typeobj):
    typeClass = typeobj.GetTypeClass()
    #warn("TYPECLASS: %s" % typeClass)
    return typeClass == lldb.eTypeClassBuiltin

71 72 73 74 75 76
#######################################################################
#
# Helpers
#
#######################################################################

77
qqStringCutOff = 10000
78

hjk's avatar
hjk committed
79 80 81 82 83 84 85 86 87 88 89 90
# This is a cache mapping from 'type name' to 'display alternatives'.
qqFormats = {}

# This is a cache of all known dumpers.
qqDumpers = {}

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

# This keeps canonical forms of the typenames, without array indices etc.
qqStripForFormat = {}

91 92
def directBaseClass(typeobj, index = 0):
    return typeobj.GetDirectBaseClassAtIndex(index)
93

hjk's avatar
hjk committed
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
def stripForFormat(typeName):
    global qqStripForFormat
    if typeName in qqStripForFormat:
        return qqStripForFormat[typeName]
    stripped = ""
    inArray = 0
    for c in stripClassTag(typeName):
        if c == '<':
            break
        if c == ' ':
            continue
        if c == '[':
            inArray += 1
        elif c == ']':
            inArray -= 1
        if inArray and ord(c) >= 48 and ord(c) <= 57:
            continue
        stripped +=  c
    qqStripForFormat[typeName] = stripped
    return stripped


def registerDumper(function):
117
    if hasattr(function, 'func_name'):
hjk's avatar
hjk committed
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
        funcname = function.func_name
        if funcname.startswith("qdump__"):
            type = funcname[7:]
            qqDumpers[type] = function
            qqFormats[type] = qqFormats.get(type, "")
        elif funcname.startswith("qform__"):
            type = funcname[7:]
            formats = ""
            try:
                formats = function()
            except:
                pass
            qqFormats[type] = formats
        elif funcname.startswith("qedit__"):
            type = funcname[7:]
            try:
                qqEditable[type] = function
            except:
                pass
137 138

def warn(message):
139
    print 'XXX="%s",' % message.encode("latin1").replace('"', "'")
140 141 142

def showException(msg, exType, exValue, exTraceback):
    warn("**** CAUGHT EXCEPTION: %s ****" % msg)
143 144 145
    import traceback
    lines = [line for line in traceback.format_exception(exType, exValue, exTraceback)]
    warn('\n'.join(lines))
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170

def registerCommand(name, func):
    pass

def currentFrame():
    currentThread = self.process.GetThreadAtIndex(0)
    return currentThread.GetFrameAtIndex(0)

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

def breakpoint_function_wrapper(baton, process, frame, bp_loc):
    result = '*stopped'
    result += ',line="%s"' % frame.line_entry.line
    result += ',file="%s"' % frame.line_entry.file
    warn("WRAPPER: %s " %result)
    return result


def onBreak():
    db.debugger.HandleCommand("settings set frame-format ''")
    db.debugger.HandleCommand("settings set thread-format ''")
    result = "*stopped,frame={....}"
    print result

171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196

PointerCode = None
ArrayCode = None
StructCode = None
UnionCode = None
EnumCode = None
FlagsCode = None
FunctionCode = None
IntCode = None
FloatCode = None
VoidCode = None
SetCode = None
RangeCode = None
StringCode = None
BitStringCode = None
ErrorTypeCode = None
MethodCode = None
MethodPointerCode = None
MemberPointerCode = None
ReferenceCode = None
CharCode = None
BoolCode = None
ComplexCode = None
TypedefCode = None
NamespaceCode = None
SimpleValueCode = None # LLDB only
197 198 199


# Data members
200 201 202
SimpleValueCode = 100
StructCode = 101
PointerCode = 102
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219

# 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
BreakpointAtSysCall = 10
WatchpointAtAddress = 11
WatchpointAtExpression = 12
BreakpointOnQmlSignalEmit = 13
BreakpointAtJavaScriptThrow = 14

220 221 222
# See db.StateType
stateNames = ["invalid", "unloaded", "connected", "attaching", "launching", "stopped",
    "running", "stepping", "crashed", "detached", "exited", "suspended" ]
223

224 225 226 227 228
def loggingCallback(args):
    s = args.strip()
    s = s.replace('"', "'")
    sys.stdout.write('log="%s"@\n' % s)

hjk's avatar
hjk committed
229 230 231 232
def check(exp):
    if not exp:
        raise RuntimeError("Check failed")

233 234 235 236 237 238 239 240 241
def checkPointer(p, align = 1):
    if not isNull(p):
        p.Dereference()

def isNull(p):
    return long(p) == 0

Value = lldb.SBValue

hjk's avatar
hjk committed
242
def checkSimpleRef(ref):
243
    count = int(ref["_q_value"])
hjk's avatar
hjk committed
244 245 246 247 248
    check(count > 0)
    check(count < 1000000)

def checkRef(ref):
    try:
249
        count = int(ref["atomic"]["_q_value"]) # Qt 5.
hjk's avatar
hjk committed
250 251
        minimum = -1
    except:
252
        count = int(ref["_q_value"]) # Qt 4.
hjk's avatar
hjk committed
253 254 255 256 257
        minimum = 0
    # Assume there aren't a million references to any object.
    check(count >= minimum)
    check(count < 1000000)

258 259 260 261
def createPointerValue(context, address, pointeeType):
    addr = int(address) & 0xFFFFFFFFFFFFFFFF
    return context.CreateValueFromAddress(None, addr, pointeeType).AddressOf()

262 263
def impl_SBValue__add__(self, offset):
    if self.GetType().IsPointerType():
264 265 266 267
        if isinstance(offset, int) or isinstance(offset, long):
            pass
        else:
            offset = offset.GetValueAsSigned()
268
        itemsize = self.GetType().GetPointeeType().GetByteSize()
269
        address = self.GetValueAsUnsigned() + offset * itemsize
270
        address = address & 0xFFFFFFFFFFFFFFFF  # Force unsigned
271
        return createPointerValue(self, address, self.GetType().GetPointeeType())
272
    raise RuntimeError("SBValue.__add__ not implemented: %s" % self.GetType())
273 274
    return NotImplemented

275
def impl_SBValue__sub__(self, other):
276
    if self.GetType().IsPointerType():
277 278 279 280
        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())
281
        if other.GetType().IsPointerType():
282 283
            itemsize = self.GetType().GetPointeeType().GetByteSize()
            return (self.GetValueAsUnsigned() - other.GetValueAsUnsigned()) / itemsize
284
    raise RuntimeError("SBValue.__sub__ not implemented: %s" % self.GetType())
285 286
    return NotImplemented

287 288 289 290 291 292 293
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):
294 295
    return self.GetValueAsSigned()
    #return int(self.GetValue(), 0)
296

297 298 299
def impl_SBValue__long__(self):
    return int(self.GetValue(), 0)

300
def impl_SBValue__getitem__(self, name):
301 302 303
    if self.GetType().IsPointerType() and isinstance(name, int):
        innertype = self.Dereference().GetType()
        address = self.GetValueAsUnsigned() + name * innertype.GetByteSize()
304 305
        address = address & 0xFFFFFFFFFFFFFFFF  # Force unsigned
        return self.CreateValueFromAddress(None, address, innertype)
306 307 308 309 310
    return self.GetChildMemberWithName(name)

def childAt(value, index):
    return value.GetChildAtIndex(index)

311
lldb.SBValue.__add__ = impl_SBValue__add__
312
lldb.SBValue.__sub__ = impl_SBValue__sub__
313
lldb.SBValue.__le__ = impl_SBValue__le__
314

315 316
lldb.SBValue.__getitem__ = impl_SBValue__getitem__
lldb.SBValue.__int__ = impl_SBValue__int__
317 318
lldb.SBValue.__long__ = lambda self: long(self.GetValue(), 0)

319
lldb.SBValue.code = lambda self: self.GetTypeClass()
320 321
lldb.SBValue.cast = lambda self, typeObj: self.Cast(typeObj)
lldb.SBValue.dereference = lambda self: self.Dereference()
322
lldb.SBValue.address = property(lambda self: self.GetAddress())
323

324
lldb.SBType.unqualified = lambda self: self.GetUnqualifiedType()
325
lldb.SBType.pointer = lambda self: self.GetPointerType()
326
lldb.SBType.code = lambda self: self.GetTypeClass()
327
lldb.SBType.sizeof = property(lambda self: self.GetByteSize())
hjk's avatar
hjk committed
328
lldb.SBType.strip_typedefs = lambda self: self.GetCanonicalType()
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360

def simpleEncoding(typeobj):
    code = typeobj.GetTypeClass()
    size = typeobj.sizeof
    #if code == BoolCode or code == CharCode:
    #    return Hex2EncodedInt1
    #if code == IntCode:
    if code == lldb.eTypeClassBuiltin:
        if str(typeobj).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
    #if code == FloatCode:
    #    if size == 4:
    #        return Hex2EncodedFloat4
    #    if size == 8:
    #        return Hex2EncodedFloat8
    return None
hjk's avatar
hjk committed
361

362 363 364 365
class Children:
    def __init__(self, d, numChild = 1, childType = None, childNumChild = None,
            maxNumChild = None, addrBase = None, addrStep = None):
        self.d = d
366 367 368 369 370 371 372 373 374 375 376
        self.numChild = numChild
        self.childNumChild = childNumChild
        self.maxNumChild = maxNumChild
        self.addrBase = addrBase
        self.addrStep = addrStep
        self.printsAddress = True
        if childType is None:
            self.childType = None
        else:
            #self.childType = stripClassTag(str(childType))
            self.childType = childType
hjk's avatar
hjk committed
377
            self.d.put('childtype="%s",' % self.childType.GetName())
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
            if childNumChild is None:
                pass
                #if isSimpleType(childType):
                #    self.d.put('childnumchild="0",')
                #    self.childNumChild = 0
                #elif childType.code == PointerCode:
                #    self.d.put('childnumchild="1",')
                #    self.childNumChild = 1
            else:
                self.d.put('childnumchild="%s",' % childNumChild)
                self.childNumChild = childNumChild
        try:
            if not addrBase is None and not addrStep is None:
                self.d.put('addrbase="0x%x",' % long(addrBase))
                self.d.put('addrstep="0x%x",' % long(addrStep))
                self.printsAddress = False
        except:
            warn("ADDRBASE: %s" % addrBase)
        #warn("CHILDREN: %s %s %s" % (numChild, childType, childNumChild))
397 398

    def __enter__(self):
399 400 401 402 403 404 405 406 407 408 409
        self.savedChildType = self.d.currentChildType
        self.savedChildNumChild = self.d.currentChildNumChild
        self.savedNumChild = self.d.currentNumChild
        self.savedMaxNumChild = self.d.currentMaxNumChild
        self.savedPrintsAddress = self.d.currentPrintsAddress
        self.d.currentChildType = self.childType
        self.d.currentChildNumChild = self.childNumChild
        self.d.currentNumChild = self.numChild
        self.d.currentMaxNumChild = self.maxNumChild
        self.d.currentPrintsAddress = self.printsAddress
        self.d.put("children=[")
410 411 412 413 414

    def __exit__(self, exType, exValue, exTraceBack):
        if not exType is None:
            if self.d.passExceptions:
                showException("CHILDREN", exType, exValue, exTraceBack)
415 416 417 418 419 420 421 422 423 424 425
            self.d.putNumChild(0)
            self.d.putValue("<not accessible>")
        if not self.d.currentMaxNumChild is None:
            if self.d.currentMaxNumChild < self.d.currentNumChild:
                self.d.put('{name="<incomplete>",value="",type="",numchild="0"},')
        self.d.currentChildType = self.savedChildType
        self.d.currentChildNumChild = self.savedChildNumChild
        self.d.currentNumChild = self.savedNumChild
        self.d.currentMaxNumChild = self.savedMaxNumChild
        self.d.currentPrintsAddress = self.savedPrintsAddress
        self.d.put('],')
426 427
        return True

428 429


430 431 432
class SubItem:
    def __init__(self, d, component):
        self.d = d
433
        if isinstance(component, lldb.SBValue):
434 435 436 437
            # Avoid $$__synth__ suffix on Mac.
            value = component
            value.SetPreferSyntheticValue(False)
            self.name = value.GetName()
438 439 440
        else:
            self.name = component
        self.iname = "%s.%s" % (d.currentIName, self.name)
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485

    def __enter__(self):
        self.d.put('{')
        #if not self.name is None:
        if isinstance(self.name, str):
            self.d.put('name="%s",' % self.name)
        self.savedIName = self.d.currentIName
        self.savedValue = self.d.currentValue
        self.savedValuePriority = self.d.currentValuePriority
        self.savedValueEncoding = self.d.currentValueEncoding
        self.savedType = self.d.currentType
        self.savedTypePriority = self.d.currentTypePriority
        self.d.currentIName = self.iname
        self.d.currentValuePriority = -100
        self.d.currentValueEncoding = None
        self.d.currentType = ""
        self.d.currentTypePriority = -100

    def __exit__(self, exType, exValue, exTraceBack):
        if not exType is None:
            if self.d.passExceptions:
                showException("SUBITEM", exType, exValue, exTraceBack)
            self.d.putNumChild(0)
            self.d.putValue("<not accessible>")
        try:
            typeName = self.d.currentType
            if len(typeName) > 0 and typeName != self.d.currentChildType:
                self.d.put('type="%s",' % typeName) # str(type.unqualified()) ?
            if  self.d.currentValue is None:
                self.d.put('value="<not accessible>",numchild="0",')
            else:
                if not self.d.currentValueEncoding is None:
                    self.d.put('valueencoded="%d",' % self.d.currentValueEncoding)
                self.d.put('value="%s",' % self.d.currentValue)
        except:
            pass
        self.d.put('},')
        self.d.currentIName = self.savedIName
        self.d.currentValue = self.savedValue
        self.d.currentValuePriority = self.savedValuePriority
        self.d.currentValueEncoding = self.savedValueEncoding
        self.d.currentType = self.savedType
        self.d.currentTypePriority = self.savedTypePriority
        return True

486
class Dumper:
487 488
    def __init__(self):
        self.debugger = lldb.SBDebugger.Create()
489
        #self.debugger.SetLoggingCallback(loggingCallback)
490 491 492 493 494 495 496 497 498 499 500 501 502 503
        #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")
        self.process = None
        self.target = None
        self.pid = None
        self.eventState = lldb.eStateInvalid
        self.listener = None
        self.options = {}
        self.expandedINames = {}
        self.passExceptions = True
504
        self.useLldbDumpers = False
505
        self.ns = ""
hjk's avatar
hjk committed
506
        self.autoDerefPointers = True
507
        self.useDynamicType = True
hjk's avatar
hjk committed
508
        self.useLoop = True
509 510 511 512 513 514

        self.currentIName = None
        self.currentValuePriority = -100
        self.currentValueEncoding = None
        self.currentType = ""
        self.currentTypePriority = -100
515
        self.currentValue = None
516 517 518 519 520
        self.currentNumChild = None
        self.currentMaxNumChild = None
        self.currentPrintsAddress = None
        self.currentChildType = None
        self.currentChildNumChild = None
521

hjk's avatar
hjk committed
522
        self.executable_ = None
523 524 525 526 527
        self.charType_ = None
        self.intType_ = None
        self.sizetType_ = None
        self.charPtrType_ = None
        self.voidType_ = None
528
        self.isShuttingDown_ = False
529

530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557
    def extractTemplateArgument(self, typename, index):
        level = 0
        skipSpace = False
        inner = ""
        for c in typename[typename.find('<') + 1 : -1]:
            if c == '<':
                inner += c
                level += 1
            elif c == '>':
                level -= 1
                inner += c
            elif c == ',':
                if level == 0:
                    if index == 0:
                        return inner
                    index -= 1
                    inner = ""
                else:
                    inner += c
                    skipSpace = True
            else:
                if skipSpace and c == ' ':
                    pass
                else:
                    inner += c
                    skipSpace = False
        return inner

558
    def templateArgument(self, typeobj, index):
559 560 561 562 563 564 565 566 567
        type = typeobj.GetTemplateArgumentType(index)
        if len(type.GetName()):
            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)
568

569 570
    def intType(self):
        if self.intType_ is None:
hjk's avatar
hjk committed
571
             self.intType_ = self.target.FindFirstType('int')
572 573 574 575
        return self.intType_

    def charType(self):
        if self.charType_ is None:
hjk's avatar
hjk committed
576
             self.charType_ = self.target.FindFirstType('char')
577 578 579 580 581 582 583 584
        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
585
        return None
586 587 588
        return self.charPtrType()  # FIXME

    def voidPtrSize(self):
hjk's avatar
hjk committed
589
        return None
590 591 592 593 594 595 596
        return self.charPtrType().GetByteSize()

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

597 598 599
    def addressOf(self, value):
        return int(value.GetLoadAddress())

600 601 602 603 604 605
    def handleCommand(self, command):
        result = lldb.SBCommandReturnObject()
        self.debugger.GetCommandInterpreter().HandleCommand(command, result)
        success = result.Succeeded()
        if success:
            self.report('output="%s"' % result.GetOutput())
606
        else:
607 608 609 610 611 612
            self.report('error="%s"' % result.GetError())
        self.reportData()

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

hjk's avatar
hjk committed
613 614 615 616 617 618 619
    def currentItemFormat(self):
        #format = self.formats.get(self.currentIName)
        #if format is None:
        #    format = self.typeformats.get(stripForFormat(str(self.currentType)))
        #return format
        return 0

620 621 622 623 624 625 626
    def isMovableType(self, type):
        if type.code == PointerCode:
            return True
        if isSimpleType(type):
            return True
        return self.stripNamespaceFromType(type.GetName()) in movableTypes

627 628
    def putNumChild(self, numchild):
        #warn("NUM CHILD: '%s' '%s'" % (numchild, self.currentChildNumChild))
hjk's avatar
hjk committed
629 630
        #if numchild != self.currentChildNumChild:
        self.put('numchild="%s",' % numchild)
631 632 633 634 635 636 637

    def putValue(self, value, encoding = None, priority = 0):
        # Higher priority values override lower ones.
        if priority >= self.currentValuePriority:
            self.currentValue = value
            self.currentValuePriority = priority
            self.currentValueEncoding = encoding
hjk's avatar
hjk committed
638
        #self.put('value="%s",' % value)
639

640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657
    # Convenience function.
    def putItemCount(self, count, maximum = 1000000000):
        # This needs to override the default value, so don't use 'put' directly.
        if count > maximum:
            self.putValue('<>%s items>' % maximum)
        else:
            self.putValue('<%s items>' % count)

    def isExpanded(self):
        #warn("IS EXPANDED: %s in %s: %s" % (self.currentIName,
        #    self.expandedINames, self.currentIName in self.expandedINames))
        return self.currentIName in self.expandedINames

    def tryPutArrayContents(self, typeobj, base, n):
        if not isSimpleType(typeobj):
            return False
        size = n * typeobj.sizeof
        self.put('childtype="%s",' % typeobj)
658 659
        self.put('addrbase="0x%x",' % int(base))
        self.put('addrstep="%d",' % typeobj.sizeof)
660 661
        self.put('arrayencoding="%s",' % simpleEncoding(typeobj))
        self.put('arraydata="')
662
        self.put(self.readRawMemory(base, size))
663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684
        self.put('",')
        return True

    def putPlotData(self, type, base, n, plotFormat):
        if self.isExpanded():
            self.putArrayData(type, base, n)

    def putArrayData(self, type, base, n,
            childNumChild = None, maxNumChild = 10000):
        if not self.tryPutArrayContents(type, base, n):
            base = base.cast(type.pointer())
            with Children(self, n, type, childNumChild, maxNumChild,
                    base, type.GetByteSize()):
                for i in self.childRange():
                    self.putSubItem(i, (base + i).dereference())

    def childRange(self):
        if self.currentMaxNumChild is None:
            return xrange(0, self.currentNumChild)
        return xrange(min(self.currentMaxNumChild, self.currentNumChild))

    def lookupType(self, name):
hjk's avatar
hjk committed
685 686
        #warn("LOOKUP: %s" % self.target.FindFirstType(name))
        return self.target.FindFirstType(name)
687

688
    def setupInferior(self, args):
hjk's avatar
hjk committed
689 690
        executable = args['executable']
        self.executable_ = executable
691
        error = lldb.SBError()
hjk's avatar
hjk committed
692
        self.target = self.debugger.CreateTarget(executable, None, None, True, error)
693 694 695 696 697 698 699 700 701 702 703
        self.listener = self.target.GetDebugger().GetListener()
        self.process = self.target.Launch(self.listener, None, None,
                                            None, None, None,
                                            None, 0, True, error)
        self.broadcaster = self.process.GetBroadcaster()
        rc = self.broadcaster.AddListener(self.listener, 15)
        if rc != 15:
            warn("ADDING LISTENER FAILED: %s" % rc)

        self.importDumpers()

704
        if self.target.IsValid():
hjk's avatar
hjk committed
705
            self.report('state="inferiorsetupok",msg="%s",exe="%s"' % (error, executable))
706
        else:
hjk's avatar
hjk committed
707
            self.report('state="inferiorsetupfailed",msg="%s",exe="%s"' % (error, executable))
708

hjk's avatar
hjk committed
709 710
        warn("STATE AFTER LAUNCH: %s" % stateNames[self.process.GetState()])

711
    def runEngine(self, _):
712 713 714
        error = lldb.SBError()
        self.pid = self.process.GetProcessID()
        self.report('pid="%s"' % self.pid)
715
        self.consumeEvents()
hjk's avatar
hjk committed
716
        error = self.process.Continue()
717 718 719 720
        self.consumeEvents()
        self.reportError(error)

        self.report('state="enginerunandinferiorrunok"')
721

hjk's avatar
hjk committed
722 723 724
        if self.useLoop:
            s = threading.Thread(target=self.loop, args=[])
            s.start()
725

726
    def describeError(self, error):
727 728 729 730 731 732
        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()
733 734 735 736
        return result

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

    def currentThread(self):
739
        return self.process.GetSelectedThread()
740 741 742 743 744 745

    def currentFrame(self):
        return self.currentThread().GetSelectedFrame()

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

    def reportThreads(self):
        result = 'threads={threads=['
753
        for i in xrange(0, self.process.GetNumThreads()):
754
            thread = self.process.GetThreadAtIndex(i)
755 756
            result += '{id="%d"' % thread.GetThreadID()
            result += ',index="%s"' % i
757 758
            result += ',stop-reason="%s"' % thread.GetStopReason()
            result += ',name="%s"' % thread.GetName()
759 760 761 762 763 764 765 766 767 768 769 770 771 772
            result += ',frame={'
            frame = thread.GetFrameAtIndex(0)
            result += 'pc="0x%x"' % frame.pc
            result += ',addr="0x%x"' % frame.pc
            result += ',fp="0x%x"' % frame.fp
            result += ',func="%s"' % frame.function.name
            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)

hjk's avatar
hjk committed
773
    def reportStack(self, _ = None):
774 775 776 777
        if self.process is None:
            self.report('msg="No process"')
        else:
            thread = self.currentThread()
778 779 780
            result = 'stack={current-frame="%s"' % thread.GetSelectedFrame().GetFrameID()
            result += ',current-thread="%s"' % thread.GetThreadID()
            result += ',frames=['
781 782 783 784
            n = thread.GetNumFrames()
            if n > 4:
                n = 4
            for i in xrange(n):
785 786 787
                frame = thread.GetFrameAtIndex(i)
                lineEntry = frame.GetLineEntry()
                result += '{pc="0x%x"' % frame.GetPC()
788
                result += ',level="%d"' % frame.idx
789
                result += ',addr="0x%x"' % frame.GetPCAddress().GetLoadAddress(self.target)
790
                result += ',func="%s"' % frame.GetFunctionName()
791 792
                result += ',line="%d"' % lineEntry.GetLine()
                result += ',fullname="%s"' % fileName(lineEntry.file)
793
                result += ',usable="1"'
794
                result += ',file="%s"},' % fileName(lineEntry.file)
795 796 797 798 799

            hasmore = '0'
            result += '],hasmore="%s"},' % hasmore
            self.report(result)

800 801 802 803 804 805 806 807
    # Convenience function.
    def putItemCount(self, count, maximum = 1000000000):
        # This needs to override the default value, so don't use 'put' directly.
        if count > maximum:
            self.putValue('<>%s items>' % maximum)
        else:
            self.putValue('<%s items>' % count)

808 809 810 811 812 813
    def putType(self, type, priority = 0):
        # Higher priority values override lower ones.
        if priority >= self.currentTypePriority:
            self.currentType = str(type)
            self.currentTypePriority = priority

814 815 816 817 818
    def putBetterType(self, type):
        try:
            self.currentType = type.GetName()
        except:
            self.currentType = str(type)
819
        self.currentTypePriority = self.currentTypePriority + 1
hjk's avatar
hjk committed
820 821

    def readRawMemory(self, base, size):
hjk's avatar
hjk committed
822 823
        if size == 0:
            return ""
824 825 826 827 828 829
        #warn("BASE: %s " % base)
        #warn("SIZE: %s " % size)
        base = int(base) & 0xFFFFFFFFFFFFFFFF
        size = int(size) & 0xFFFFFFFF
        #warn("BASEX: %s " % base)
        #warn("SIZEX: %s " % size)
hjk's avatar
hjk committed
830
        error = lldb.SBError()
831
        contents = self.process.ReadMemory(base, size, error)
hjk's avatar
hjk committed
832 833 834 835 836 837 838 839 840 841 842 843
        return binascii.hexlify(contents)

    def computeLimit(self, size, limit):
        if limit is None:
            return size
        if limit == 0:
            #return min(size, qqStringCutOff)
            return min(size, 100)
        return min(size, limit)

    def putValue(self, value, encoding = None, priority = 0):
        # Higher priority values override lower ones.
844 845 846 847
        if priority >= self.currentValuePriority:
            self.currentValue = value
            self.currentValuePriority = priority
            self.currentValueEncoding = encoding
hjk's avatar
hjk committed
848

849 850 851 852 853 854 855 856 857 858 859 860 861 862
    def stripNamespaceFromType(self, typeName):
        #type = stripClassTag(typeName)
        type = typeName
        #if len(self.ns) > 0 and type.startswith(self.ns):
        #    type = type[len(self.ns):]
        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("<")
        return type

    def putSubItem(self, component, value, tryDynamic=True):
863 864 865
        if not value.IsValid():
            warn("INVALID")
            return
866 867 868
        with SubItem(self, component):
            self.putItem(value, tryDynamic)

869
    def putItem(self, value, tryDynamic=True):
hjk's avatar
hjk committed
870 871
        #value = value.GetDynamicValue(lldb.eDynamicCanRunTarget)
        typeName = value.GetTypeName()
872

873
        # Handle build-in LLDB visualizers if wanted.
874
        if self.useLldbDumpers and value.GetTypeSynthetic().IsValid():
875 876 877 878 879 880 881 882 883 884
            # 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
885 886 887 888
            self.put('iname="%s",' % self.currentIName)
            self.put('type="%s",' % typeName)
            self.put('numchild="%s",' % numchild)
            self.put('addr="0x%x",' % value.GetLoadAddress())
889
            self.putItemCount(numchild)
hjk's avatar
hjk committed
890 891
            if self.currentIName in self.expandedINames:
                with Children(self):
892 893 894 895 896 897
                    for i in xrange(numchild):
                        child = formatter.get_child_at_index(i)
                        with SubItem(self, i):
                            self.putItem(child)
            return

898
        # Our turf now.
899
        value.SetPreferSyntheticValue(False)
900 901 902 903 904 905 906 907 908 909 910 911

        # References
        if value.GetType().IsReferenceType():
            type = value.GetType().GetDereferencedType().GetPointerType()
            # FIXME: Find something more direct.
            value = value.CreateValueFromAddress(value.GetName(),
                value.AddressOf().GetValueAsUnsigned(), type).Dereference()
            #value = value.cast(value.dynamic_type)
            self.putItem(value)
            self.putBetterType("%s &" % value.GetTypeName())
            return

hjk's avatar
hjk committed
912 913 914 915 916
        # Pointers
        if value.GetType().IsPointerType() and self.autoDerefPointers:
            self.putItem(value.Dereference())
            return

917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935
        stripped = self.stripNamespaceFromType(typeName).replace("::", "__")
        #warn("VALUE: %s" % value)
        if stripped in qqDumpers:
            self.putType(typeName)
            qqDumpers[stripped](self, value)
            return

        # Normal value
        v = value.GetValue()
        #numchild = 1 if value.MightHaveChildren() else 0
        numchild = value.GetNumChildren()
        self.put('iname="%s",' % self.currentIName)
        self.put('type="%s",' % typeName)
        self.putValue("" if v is None else v)
        self.put('numchild="%s",' % numchild)
        self.put('addr="0x%x",' % value.GetLoadAddress())
        if self.currentIName in self.expandedINames:
            with Children(self):
                self.putFields(value)
936 937 938 939 940 941

    def putFields(self, value):
        n = value.GetNumChildren()
        if n > 10000:
            n = 10000
        for i in xrange(n):
hjk's avatar
hjk committed
942
            child = value.GetChildAtIndex(i)
943
            with SubItem(self, child):
hjk's avatar
hjk committed
944
                self.putItem(child)
945

hjk's avatar
hjk committed
946
    def reportVariables(self, _ = None):
947 948 949 950
        frame = self.currentThread().GetSelectedFrame()
        self.currentIName = "local"
        self.put('data=[')
        for value in frame.GetVariables(True, True, False, False):
951
            with SubItem(self, value):
952
                self.put('iname="%s",' % self.currentIName)
953 954 955 956
                self.putItem(value)
        self.put(']')
        self.report('')

hjk's avatar
hjk committed
957
    def reportData(self, _ = None):
958 959 960 961 962 963 964 965 966 967 968
        self.reportRegisters()
        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()

969
    def reportRegisters(self, _ = None):
970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986
        if self.process is None:
            self.report('process="none"')
        else:
            frame = self.currentFrame()
            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)

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

hjk's avatar
hjk committed
987
    def interruptInferior(self, _ = None):
988 989 990 991 992 993 994
        if self.process is None:
            self.report('msg="No process"')
        else:
            #self.debugger.DispatchInputInterrupt()
            error = self.process.Stop()
            self.reportError(error)

hjk's avatar
hjk committed
995
    def detachInferior(self, _ = None):
996 997 998 999 1000 1001
        if self.process is None:
            self.report('msg="No process"')
        else:
            error = self.process.Detach()
            self.reportError(error)
            self.reportData()
1002

hjk's avatar
hjk committed
1003
    def continueInferior(self, _ = None):
1004 1005 1006 1007 1008 1009 1010 1011 1012
        if self.process is None:
            self.report('msg="No process"')
        else:
            error = self.process.Continue()
            self.reportError(error)

    def handleEvent(self, event):
        out = lldb.SBStream()
        event.GetDescription(out)
1013
        #warn("EVENT: %s" % event)
1014 1015 1016
        type = event.GetType()
        msg = lldb.SBEvent.GetCStringFromEvent(event)
        flavor = event.GetDataFlavor()
1017
        state = lldb.SBProcess.GetStateFromEvent(event)
1018
        self.report('event={type="%s",data="%s",msg="%s",flavor="%s",state="%s"}'
1019 1020 1021 1022
            % (type, out.GetData(), msg, flavor, state))
        if state != self.eventState:
            self.report('state="%s"' % stateNames[state])
            self.eventState = state
hjk's avatar
hjk committed
1023
            if state == lldb.eStateExited:
1024 1025 1026 1027 1028
                if self.isShuttingDown_:
                    self.report('state="inferiorshutdownok"')
                else:
                    self.report('state="inferiorexited"')
                self.report('exited={status="%s",desc="%s"}'
hjk's avatar
hjk committed
1029
                    % (self.process.GetExitStatus(), self.process.GetExitDescription()))
1030 1031 1032 1033 1034
        if type == lldb.SBProcess.eBroadcastBitStateChanged:
            self.reportData()
        elif type == lldb.SBProcess.eBroadcastBitInterrupt:
            pass
        elif type == lldb.SBProcess.eBroadcastBitSTDOUT:
1035 1036 1037 1038
            # FIXME: Size?
            msg = self.process.GetSTDOUT(1024)
            self.report('output={channel="stdout",data="%s"}'
                % binascii.hexlify(msg))
1039
        elif type == lldb.SBProcess.eBroadcastBitSTDERR:
1040 1041 1042
            msg = self.process.GetSTDERR(1024)
            self.report('output={channel="stdout",data="%s"}'
                % binascii.hexlify(msg))
1043 1044 1045
        elif type == lldb.SBProcess.eBroadcastBitProfileData:
            pass

1046 1047 1048 1049
    def processEvents(self):
        if self.listener is None:
            warn("NO LISTENER YET")
            return
1050 1051 1052 1053 1054 1055 1056
        event = lldb.SBEvent()
        while self.listener.PeekAtNextEvent(event):
            self.listener.GetNextEvent(event)
            self.handleEvent(event)

    def describeBreakpoint(self, bp, modelId):
        cond = bp.GetCondition()
hjk's avatar
hjk committed
1057
        result  = 'lldbid="%s"' % bp.GetID()
1058 1059 1060
        result += ',modelid="%s"' % modelId
        result += ',hitcount="%s"' % bp.GetHitCount()
        result += ',threadid="%s"' % bp.GetThreadID()
1061 1062 1063 1064
        try:
            result += ',oneshot="%s"' % (1 if bp.IsOneShot() else 0)
        except:
            pass
1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079
        result += ',enabled="%s"' % (1 if bp.IsEnabled() else 0)
        result += ',valid="%s"' % (1 if bp.IsValid() else 0)
        result += ',condition="%s"' % ("" if cond is None else cond)
        result += ',ignorecount="%s"' % bp.GetIgnoreCount()
        result += ',locations=['
        for i in xrange(bp.GetNumLocations()):
            loc = bp.GetLocationAtIndex(i)
            addr = loc.GetAddress()
            result += '{locid="%s"' % loc.GetID()
            result += ',func="%s"' % addr.GetFunction().GetName()
            result += ',enabled="%s"' % (1 if loc.IsEnabled() else 0)
            result += ',resolved="%s"' % (1 if loc.IsResolved() else 0)
            result += ',valid="%s"' % (1 if loc.IsValid() else 0)
            result += ',ignorecount="%s"' % loc.GetIgnoreCount()
            result += ',addr="%s"},' % loc.GetLoadAddress()
hjk's avatar
hjk committed
1080
        result += '],'
1081 1082
        return result

1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123
    def addBreakpoint(self, args):
        bpType = args["type"]
        if bpType == BreakpointByFileAndLine:
            bpNew = self.target.BreakpointCreateByLocation(
                str(args["file"]), int(args["line"]))
        elif bpType == BreakpointByFunction:
            bpNew = self.target.BreakpointCreateByName(args["function"])
        elif bpType == BreakpointAtMain:
            bpNew = self.target.BreakpointCreateByName(
                "main", self.target.GetExecutable().GetFilename())
        else:
            warn("UNKNOWN TYPE")
        bpNew.SetIgnoreCount(int(args["ignorecount"]))
        bpNew.SetCondition(str(args["condition"]))
        bpNew.SetEnabled(int(args["enabled"]))
        try:
            bpNew.SetOneShot(int(args["oneshot"]))
        except:
            pass
        #bpNew.SetCallback(breakpoint_function_wrapper, None)
        #bpNew.SetCallback(breakpoint_function_wrapper, None)
        #"breakpoint command add 1 -o \"import time; print time.asctime()\"
        #cmd = "script print(11111111)"
        #cmd = "continue"
        #self.debugger.HandleCommand(
        #    "breakpoint command add -o 'script onBreak()' %s" % bpNew.GetID())
        return bpNew

    def changeBreakpoint(self, args):
        bpChange = self.target.FindBreakpointByID(int(args["lldbid"]))
        bpChange.SetIgnoreCount(int(args["ignorecount"]))
        bpChange.SetCondition(str(args["condition"]))
        bpChange.SetEnabled(int(args["enabled"]))
        try:
            bpChange.SetOneShot(int(args["oneshot"]))
        except:
            pass

    def removeBreakpoint(self, args):
        return self.target.BreakpointDelete(int(args["lldbid"]))

1124
    def handleBreakpoints(self, args):
hjk's avatar
hjk committed
1125
        result = 'bkpts=['
1126
        for bp in args['bkpts']:
hjk's avatar
hjk committed
1127 1128 1129
            operation = bp['operation']

            if operation == 'add':
1130 1131 1132
                bpNew = self.addBreakpoint(bp)
                result += '{operation="added",%s}' \
                    % self.describeBreakpoint(bpNew, bp["modelid"])
hjk's avatar
hjk committed
1133 1134

            elif operation == 'change':
1135 1136 1137
                bpNew = self.changeBreakpoint(bp)
                result += '{operation="changed",%s' \
                    % self.describeBreakpoint(bpNew, bp["modelid"])
hjk's avatar
hjk committed
1138 1139

            elif operation == 'remove':
1140
                bpDead = self.removeBreakpoint(bp)
hjk's avatar
hjk committed
1141 1142 1143
                result += '{operation="removed",modelid="%s"}' % bp["modelid"]

        result += "]"
1144 1145
        self.report(result)

hjk's avatar
hjk committed
1146
    def listModules(self, args):
1147
        result = 'modules=['
hjk's avatar
hjk committed
1148 1149 1150
        for i in xrange(self.target.GetNumModules()):
            module = self.target.GetModuleAtIndex(i)
            result += '{file="%s"' % module.file.GetFullPath()
1151
            result += ',name="%s"' % module.file.basename
1152 1153 1154
            result += ',addrsize="%s"' % module.addr_size
            result += ',triple="%s"' % module.triple
            #result += ',sections={'
1155 1156 1157
            #for section in module.sections:
            #    result += '[name="%s"' % section.name
            #    result += ',addr="%s"' % section.addr
1158
            #    result += ',size="%s"],' % section.size
1159 1160 1161 1162 1163
            #result += '}'
            result += '},'
        result += ']'
        self.report(result)

1164 1165
    def listSymbols(self, args):
        moduleName = args['module']
1166 1167
        #file = lldb.SBFileSpec(moduleName)
        #module = self.target.FindModule(file)
hjk's avatar
hjk committed
1168 1169 1170
        for i in xrange(self.target.GetNumModules()):
            module = self.target.GetModuleAtIndex(i)
            if module.file.GetFullPath() == moduleName:
1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187
                break
        result = 'symbols={module="%s"' % moduleName
        result += ',valid="%s"' % module.IsValid()
        result += ',sections="%s"' % module.GetNumSections()
        result += ',symbols=['
        for symbol in module.symbols:
            startAddress = symbol.GetStartAddress().GetLoadAddress(self.target)
            endAddress = symbol.GetEndAddress().GetLoadAddress(self.target)
            result += '{type="%s"' % symbol.GetType()
            result += ',name="%s"' % symbol.GetName()
            result += ',address="0x%x"' % startAddress
            result += ',demangled="%s"' % symbol.GetMangledName()
            result += ',size="%s"' % (endAddress - startAddress)
            result += '},'
        result += ']}'
        self.report(result)

1188
    def executeNext(self, _ = None):
1189 1190
        self.currentThread().StepOver()

1191
    def executeNextI(self, _ = None):
1192
        self.currentThread().StepInstruction(lldb.eOnlyThisThread)
1193

1194
    def executeStep(self, _ = None):
1195 1196
        self.currentThread().StepInto()

1197 1198 1199 1200
    def shutdownInferior(self, _ = None):
        self.isShuttingDown_ = True
        self.process.Kill()

1201
    def quit(self, _ = None):
1202 1203
        self.report('state="engineshutdownok"')
        self.process.Kill()
1204

1205
    def executeStepI(self, _ = None):
1206
        self.currentThread().StepInstruction(lldb.eOnlyThisThread)
1207

1208
    def executeStepOut(self, _ = None):
1209
        self.currentThread().StepOut()
1210

1211 1212 1213
    def executeRunToLine(self, args):
        file = args['file']
        line = int(args['line'])