Debian Codegraph @

cross-project-tests/debuginfo-tests/dexter/dex/debugger/lldb/LLDB.py

raw
1 # DExTer : Debugging Experience Tester
2 # ~~~~~~ ~ ~~ ~ ~~
3 #
4 # Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
5 # See https://llvm.org/LICENSE.txt for license information.
6 # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 """Interface for communicating with the LLDB debugger via its python interface.
8 """
9
10 import imp
11 import os
12 import shlex
13 from subprocess import CalledProcessError, check_output, STDOUT
14 import sys
15
16 from dex.debugger.DebuggerBase import DebuggerBase, watch_is_active
17 from dex.dextIR import FrameIR, LocIR, StepIR, StopReason, ValueIR
18 from dex.dextIR import StackFrame, SourceLocation, ProgramState
19 from dex.utils.Exceptions import DebuggerException, LoadDebuggerException
20 from dex.utils.ReturnCode import ReturnCode
21
22
23 class LLDB(DebuggerBase):
24 def __init__(self, context, *args):
25 self.lldb_executable = context.options.lldb_executable
26 self._debugger = None
27 self._target = None
28 self._process = None
29 self._thread = None
30 # Map {id (int): condition (str)} for breakpoints which have a
31 # condition. See get_triggered_breakpoint_ids usage for more info.
32 self._breakpoint_conditions = {}
33 super(LLDB, self).__init__(context, *args)
34
35 def _custom_init(self):
36 self._debugger = self._interface.SBDebugger.Create()
37 self._debugger.SetAsync(False)
38 self._target = self._debugger.CreateTargetWithFileAndArch(
39 self.context.options.executable, self.context.options.arch
40 )
41 if not self._target:
42 raise LoadDebuggerException(
43 'could not create target for executable "{}" with arch:{}'.format(
44 self.context.options.executable, self.context.options.arch
45 )
46 )
47
48 def _custom_exit(self):
49 if getattr(self, "_process", None):
50 self._process.Kill()
51 if getattr(self, "_debugger", None) and getattr(self, "_target", None):
52 self._debugger.DeleteTarget(self._target)
53
54 def _translate_stop_reason(self, reason):
55 if reason == self._interface.eStopReasonNone:
56 return None
57 if reason == self._interface.eStopReasonBreakpoint:
58 return StopReason.BREAKPOINT
59 if reason == self._interface.eStopReasonPlanComplete:
60 return StopReason.STEP
61 if reason == self._interface.eStopReasonThreadExiting:
62 return StopReason.PROGRAM_EXIT
63 if reason == self._interface.eStopReasonException:
64 return StopReason.ERROR
65 return StopReason.OTHER
66
67 def _load_interface(self):
68 try:
69 args = [self.lldb_executable, "-P"]
70 pythonpath = check_output(args, stderr=STDOUT).rstrip().decode("utf-8")
71 except CalledProcessError as e:
72 raise LoadDebuggerException(str(e), sys.exc_info())
73 except OSError as e:
74 raise LoadDebuggerException(
75 '{} ["{}"]'.format(e.strerror, self.lldb_executable), sys.exc_info()
76 )
77
78 if not os.path.isdir(pythonpath):
79 raise LoadDebuggerException(
80 'path "{}" does not exist [result of {}]'.format(pythonpath, args),
81 sys.exc_info(),
82 )
83
84 try:
85 module_info = imp.find_module("lldb", [pythonpath])
86 return imp.load_module("lldb", *module_info)
87 except ImportError as e:
88 msg = str(e)
89 if msg.endswith("not a valid Win32 application."):
90 msg = "{} [Are you mixing 32-bit and 64-bit binaries?]".format(msg)
91 raise LoadDebuggerException(msg, sys.exc_info())
92
93 @classmethod
94 def get_name(cls):
95 return "lldb"
96
97 @classmethod
98 def get_option_name(cls):
99 return "lldb"
100
101 @property
102 def version(self):
103 try:
104 return self._interface.SBDebugger_GetVersionString()
105 except AttributeError:
106 return None
107
108 def clear_breakpoints(self):
109 self._target.DeleteAllBreakpoints()
110
111 def _add_breakpoint(self, file_, line):
112 return self._add_conditional_breakpoint(file_, line, None)
113
114 def _add_conditional_breakpoint(self, file_, line, condition):
115 bp = self._target.BreakpointCreateByLocation(file_, line)
116 if not bp:
117 raise DebuggerException(
118 "could not add breakpoint [{}:{}]".format(file_, line)
119 )
120 id = bp.GetID()
121 if condition:
122 bp.SetCondition(condition)
123 assert id not in self._breakpoint_conditions
124 self._breakpoint_conditions[id] = condition
125 return id
126
127 def _evaulate_breakpoint_condition(self, id):
128 """Evaluate the breakpoint condition and return the result.
129
130 Returns True if a conditional breakpoint with the specified id cannot
131 be found (i.e. assume it is an unconditional breakpoint).
132 """
133 try:
134 condition = self._breakpoint_conditions[id]
135 except KeyError:
136 # This must be an unconditional breakpoint.
137 return True
138 valueIR = self.evaluate_expression(condition)
139 return valueIR.type_name == "bool" and valueIR.value == "true"
140
141 def get_triggered_breakpoint_ids(self):
142 # Breakpoints can only have been triggered if we've hit one.
143 stop_reason = self._translate_stop_reason(self._thread.GetStopReason())
144 if stop_reason != StopReason.BREAKPOINT:
145 return []
146 breakpoint_ids = set()
147 # When the stop reason is eStopReasonBreakpoint, GetStopReasonDataCount
148 # counts all breakpoints associated with the location that lldb has
149 # stopped at, regardless of their condition. I.e. Even if we have two
150 # breakpoints at the same source location that have mutually exclusive
151 # conditions, both will be counted by GetStopReasonDataCount when
152 # either condition is true. Check each breakpoint condition manually to
153 # filter the list down to breakpoints that have caused this stop.
154 #
155 # Breakpoints have two data parts: Breakpoint ID, Location ID. We're
156 # only interested in the Breakpoint ID so we skip every other item.
157 for i in range(0, self._thread.GetStopReasonDataCount(), 2):
158 id = self._thread.GetStopReasonDataAtIndex(i)
159 if self._evaulate_breakpoint_condition(id):
160 breakpoint_ids.add(id)
161 return breakpoint_ids
162
163 def delete_breakpoints(self, ids):
164 for id in ids:
165 bp = self._target.FindBreakpointByID(id)
166 if not bp:
167 # The ID is not valid.
168 raise KeyError
169 try:
170 del self._breakpoint_conditions[id]
171 except KeyError:
172 # This must be an unconditional breakpoint.
173 pass
174 self._target.BreakpointDelete(id)
175
176 def launch(self, cmdline):
177 num_resolved_breakpoints = 0
178 for b in self._target.breakpoint_iter():
179 num_resolved_breakpoints += b.GetNumLocations() > 0
180 assert num_resolved_breakpoints > 0
181
182 if self.context.options.target_run_args:
183 cmdline += shlex.split(self.context.options.target_run_args)
184 launch_info = self._target.GetLaunchInfo()
185 launch_info.SetWorkingDirectory(os.getcwd())
186 launch_info.SetArguments(cmdline, True)
187 error = self._interface.SBError()
188 self._process = self._target.Launch(launch_info, error)
189
190 if error.Fail():
191 raise DebuggerException(error.GetCString())
192 if not os.path.exists(self._target.executable.fullpath):
193 raise DebuggerException("exe does not exist")
194 if not self._process or self._process.GetNumThreads() == 0:
195 raise DebuggerException("could not launch process")
196 if self._process.GetNumThreads() != 1:
197 raise DebuggerException("multiple threads not supported")
198 self._thread = self._process.GetThreadAtIndex(0)
199
200 num_stopped_threads = 0
201 for thread in self._process:
202 if thread.GetStopReason() == self._interface.eStopReasonBreakpoint:
203 num_stopped_threads += 1
204 assert num_stopped_threads > 0
205 assert self._thread, (self._process, self._thread)
206
207 def step(self):
208 self._thread.StepInto()
209
210 def go(self) -> ReturnCode:
211 self._process.Continue()
212 return ReturnCode.OK
213
214 def _get_step_info(self, watches, step_index):
215 frames = []
216 state_frames = []
217
218 for i in range(0, self._thread.GetNumFrames()):
219 sb_frame = self._thread.GetFrameAtIndex(i)
220 sb_line = sb_frame.GetLineEntry()
221 sb_filespec = sb_line.GetFileSpec()
222
223 try:
224 path = os.path.join(
225 sb_filespec.GetDirectory(), sb_filespec.GetFilename()
226 )
227 except (AttributeError, TypeError):
228 path = None
229
230 function = self._sanitize_function_name(sb_frame.GetFunctionName())
231
232 loc_dict = {
233 "path": path,
234 "lineno": sb_line.GetLine(),
235 "column": sb_line.GetColumn(),
236 }
237 loc = LocIR(**loc_dict)
238 valid_loc_for_watch = loc.path and os.path.exists(loc.path)
239
240 frame = FrameIR(function=function, is_inlined=sb_frame.IsInlined(), loc=loc)
241
242 if any(
243 name in (frame.function or "") # pylint: disable=no-member
244 for name in self.frames_below_main
245 ):
246 break
247
248 frames.append(frame)
249
250 state_frame = StackFrame(
251 function=frame.function,
252 is_inlined=frame.is_inlined,
253 location=SourceLocation(**loc_dict),
254 watches={},
255 )
256 if valid_loc_for_watch:
257 for expr in map(
258 # Filter out watches that are not active in the current frame,
259 # and then evaluate all the active watches.
260 lambda watch_info, idx=i: self.evaluate_expression(
261 watch_info.expression, idx
262 ),
263 filter(
264 lambda watch_info, idx=i, line_no=loc.lineno, loc_path=loc.path: watch_is_active(
265 watch_info, loc_path, idx, line_no
266 ),
267 watches,
268 ),
269 ):
270 state_frame.watches[expr.expression] = expr
271 state_frames.append(state_frame)
272
273 if len(frames) == 1 and frames[0].function is None:
274 frames = []
275 state_frames = []
276
277 reason = self._translate_stop_reason(self._thread.GetStopReason())
278
279 return StepIR(
280 step_index=step_index,
281 frames=frames,
282 stop_reason=reason,
283 program_state=ProgramState(state_frames),
284 )
285
286 @property
287 def is_running(self):
288 # We're not running in async mode so this is always False.
289 return False
290
291 @property
292 def is_finished(self):
293 return not self._thread.GetFrameAtIndex(0)
294
295 @property
296 def frames_below_main(self):
297 return ["__scrt_common_main_seh", "__libc_start_main", "__libc_start_call_main"]
298
299 def evaluate_expression(self, expression, frame_idx=0) -> ValueIR:
300 result = self._thread.GetFrameAtIndex(frame_idx).EvaluateExpression(expression)
301 error_string = str(result.error)
302
303 value = result.value
304 could_evaluate = not any(
305 s in error_string
306 for s in [
307 "Can't run the expression locally",
308 "use of undeclared identifier",
309 "no member named",
310 "Couldn't lookup symbols",
311 "Couldn't look up symbols",
312 "reference to local variable",
313 "invalid use of 'this' outside of a non-static member function",
314 ]
315 )
316
317 is_optimized_away = any(
318 s in error_string
319 for s in [
320 "value may have been optimized out",
321 ]
322 )
323
324 is_irretrievable = any(
325 s in error_string
326 for s in [
327 "couldn't get the value of variable",
328 "couldn't read its memory",
329 "couldn't read from memory",
330 "Cannot access memory at address",
331 "invalid address (fault address:",
332 ]
333 )
334
335 if could_evaluate and not is_irretrievable and not is_optimized_away:
336 assert error_string == "success", (error_string, expression, value)
337 # assert result.value is not None, (result.value, expression)
338
339 if error_string == "success":
340 error_string = None
341
342 # attempt to find expression as a variable, if found, take the variable
343 # obj's type information as it's 'usually' more accurate.
344 var_result = self._thread.GetFrameAtIndex(frame_idx).FindVariable(expression)
345 if str(var_result.error) == "success":
346 type_name = var_result.type.GetDisplayTypeName()
347 else:
348 type_name = result.type.GetDisplayTypeName()
349
350 return ValueIR(
351 expression=expression,
352 value=value,
353 type_name=type_name,
354 error_string=error_string,
355 could_evaluate=could_evaluate,
356 is_optimized_away=is_optimized_away,
357 is_irretrievable=is_irretrievable,
358 )