brintos

brintos / llvm-project-archived public Read only

0
0
Text · 5.7 KiB · f3146f7 Raw
169 lines · python
1#!/usr/bin/env python32"""3A gdb-compatible frontend for lldb that implements just enough4commands to run the tests in the debuginfo-tests repository with lldb.5"""6 7# ----------------------------------------------------------------------8# Auto-detect lldb python module.9import subprocess, platform, os, sys10 11# Set the path to look first for the built lldb (in case it exists).12lldb_python_path = os.environ["LLDB_PYTHON_PATH"]13if len(lldb_python_path) > 0:14    sys.path.insert(0, lldb_python_path)15 16try:17    # Just try for LLDB in case PYTHONPATH is already correctly setup.18    import lldb19except ImportError:20    # Ask the command line driver for the path to the lldb module. Copy over21    # the environment so that SDKROOT is propagated to xcrun.22    command = (23        ["xcrun", "lldb", "-P"] if platform.system() == "Darwin" else ["lldb", "-P"]24    )25    # Extend the PYTHONPATH if the path exists and isn't already there.26    lldb_python_path = subprocess.check_output(command).decode("utf-8").strip()27    if os.path.exists(lldb_python_path) and not sys.path.__contains__(lldb_python_path):28        sys.path.append(lldb_python_path)29    # Try importing LLDB again.30    try:31        import lldb32 33        print('imported lldb from: "%s"' % lldb_python_path)34    except ImportError:35        print(36            "error: couldn't locate the 'lldb' module, please set PYTHONPATH correctly"37        )38        sys.exit(1)39# ----------------------------------------------------------------------40 41# Command line option handling.42import argparse43 44parser = argparse.ArgumentParser(description=__doc__)45parser.add_argument("--quiet", "-q", action="store_true", help="ignored")46parser.add_argument(47    "-batch", action="store_true", help="exit after processing comand line"48)49parser.add_argument("-n", action="store_true", help="ignore .lldb file")50parser.add_argument(51    "-x", dest="script", type=argparse.FileType("r"), help="execute commands from file"52)53parser.add_argument("target", help="the program to debug")54args = parser.parse_args()55 56 57# Create a new debugger instance.58debugger = lldb.SBDebugger.Create()59debugger.SkipLLDBInitFiles(args.n)60 61# Make sure to clean up the debugger on exit.62import atexit63 64 65def on_exit():66    debugger.Terminate()67 68 69atexit.register(on_exit)70 71# Don't return from lldb function calls until the process stops.72debugger.SetAsync(False)73 74# Create a target from a file and arch.75arch = os.popen("file " + args.target).read().split()[-1]76target = debugger.CreateTargetWithFileAndArch(args.target, arch)77 78if not target:79    print("Could not create target %s" % args.target)80    sys.exit(1)81 82if not args.script:83    print("Interactive mode is not implemented.")84    sys.exit(1)85 86import re87 88for command in args.script:89    # Strip newline and whitespaces and split into words.90    cmd = command[:-1].strip().split()91    if not cmd:92        continue93 94    print("> %s" % command[:-1])95 96    try:97        if re.match("^r|(run)$", cmd[0]):98            error = lldb.SBError()99            launchinfo = lldb.SBLaunchInfo([])100            launchinfo.SetWorkingDirectory(os.getcwd())101            process = target.Launch(launchinfo, error)102            print(error)103            if not process or error.fail:104                state = process.GetState()105                print("State = %d" % state)106                print(107                    """108ERROR: Could not launch process.109NOTE: There are several reasons why this may happen:110  * Root needs to run "DevToolsSecurity --enable".111  * Older versions of lldb cannot launch more than one process simultaneously.112"""113                )114                sys.exit(1)115 116        elif re.match("^b|(break)$", cmd[0]) and len(cmd) == 2:117            if re.match("[0-9]+", cmd[1]):118                # b line119                mainfile = target.FindFunctions("main")[0].compile_unit.file120                print(target.BreakpointCreateByLocation(mainfile, int(cmd[1])))121            else:122                # b file:line123                file, line = cmd[1].split(":")124                print(target.BreakpointCreateByLocation(file, int(line)))125 126        elif re.match("^ptype$", cmd[0]) and len(cmd) == 2:127            # GDB's ptype has multiple incarnations depending on its128            # argument (global variable, function, type).  The definition129            # here is for looking up the signature of a function and only130            # if that fails it looks for a type with that name.131            # Type lookup in LLDB would be "image lookup --type".132            for elem in target.FindFunctions(cmd[1]):133                print(elem.function.type)134                continue135            print(target.FindFirstType(cmd[1]))136 137        elif re.match("^po$", cmd[0]) and len(cmd) > 1:138            try:139                opts = lldb.SBExpressionOptions()140                opts.SetFetchDynamicValue(True)141                opts.SetCoerceResultToId(True)142                print(target.EvaluateExpression(" ".join(cmd[1:]), opts))143            except:144                # FIXME: This is a fallback path for the lab.llvm.org145                # buildbot running OS X 10.7; it should be removed.146                thread = process.GetThreadAtIndex(0)147                frame = thread.GetFrameAtIndex(0)148                print(frame.EvaluateExpression(" ".join(cmd[1:])))149 150        elif re.match("^p|(print)$", cmd[0]) and len(cmd) > 1:151            thread = process.GetThreadAtIndex(0)152            frame = thread.GetFrameAtIndex(0)153            print(frame.EvaluateExpression(" ".join(cmd[1:])))154 155        elif re.match("^n|(next)$", cmd[0]):156            thread = process.GetThreadAtIndex(0)157            thread.StepOver()158 159        elif re.match("^q|(quit)$", cmd[0]):160            sys.exit(0)161 162        else:163            print(debugger.HandleCommand(" ".join(cmd)))164 165    except SystemExit:166        raise167    except:168        print('Could not handle the command "%s"' % " ".join(cmd))169