Debian Codegraph @

cross-project-tests/debuginfo-tests/llgdb-tests/llgdb.py

raw
1 #!/usr/bin/env python3
2 """
3 A gdb-compatible frontend for lldb that implements just enough
4 commands to run the tests in the debuginfo-tests repository with lldb.
5 """
6
7 # ----------------------------------------------------------------------
8 # Auto-detect lldb python module.
9 import subprocess, platform, os, sys
10
11 # Set the path to look first for the built lldb (in case it exists).
12 lldb_python_path = os.environ["LLDB_PYTHON_PATH"]
13 if len(lldb_python_path) > 0:
14 sys.path.insert(0, lldb_python_path)
15
16 try:
17 # Just try for LLDB in case PYTHONPATH is already correctly setup.
18 import lldb
19 except ImportError:
20 # Ask the command line driver for the path to the lldb module. Copy over
21 # 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 lldb
32
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.
42 import argparse
43
44 parser = argparse.ArgumentParser(description=__doc__)
45 parser.add_argument("--quiet", "-q", action="store_true", help="ignored")
46 parser.add_argument(
47 "-batch", action="store_true", help="exit after processing comand line"
48 )
49 parser.add_argument("-n", action="store_true", help="ignore .lldb file")
50 parser.add_argument(
51 "-x", dest="script", type=argparse.FileType("r"), help="execute commands from file"
52 )
53 parser.add_argument("target", help="the program to debug")
54 args = parser.parse_args()
55
56
57 # Create a new debugger instance.
58 debugger = lldb.SBDebugger.Create()
59 debugger.SkipLLDBInitFiles(args.n)
60
61 # Make sure to clean up the debugger on exit.
62 import atexit
63
64
65 def on_exit():
66 debugger.Terminate()
67
68
69 atexit.register(on_exit)
70
71 # Don't return from lldb function calls until the process stops.
72 debugger.SetAsync(False)
73
74 # Create a target from a file and arch.
75 arch = os.popen("file " + args.target).read().split()[-1]
76 target = debugger.CreateTargetWithFileAndArch(args.target, arch)
77
78 if not target:
79 print("Could not create target %s" % args.target)
80 sys.exit(1)
81
82 if not args.script:
83 print("Interactive mode is not implemented.")
84 sys.exit(1)
85
86 import re
87
88 for command in args.script:
89 # Strip newline and whitespaces and split into words.
90 cmd = command[:-1].strip().split()
91 if not cmd:
92 continue
93
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 """
108 ERROR: Could not launch process.
109 NOTE: 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 line
119 mainfile = target.FindFunctions("main")[0].compile_unit.file
120 print(target.BreakpointCreateByLocation(mainfile, int(cmd[1])))
121 else:
122 # b file:line
123 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 its
128 # argument (global variable, function, type). The definition
129 # here is for looking up the signature of a function and only
130 # 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 continue
135 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.org
145 # 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 raise
167 except:
168 print('Could not handle the command "%s"' % " ".join(cmd))