3 #----------------------------------------------------------------------
4 # Be sure to add the python path that points to the LLDB shared library.
6 # setenv PYTHONPATH /Applications/Xcode.app/Contents/SharedFrameworks/LLDB.framework/Resources/Python
8 # export PYTHONPATH=/Applications/Xcode.app/Contents/SharedFrameworks/LLDB.framework/Resources/Python
9 #----------------------------------------------------------------------
21 #----------------------------------------------------------------------
22 # Code that auto imports LLDB
23 #----------------------------------------------------------------------
25 # Just try for LLDB in case PYTHONPATH is already correctly setup
28 lldb_python_dirs = list()
29 # lldb is not in the PYTHONPATH, try some defaults for the current platform
30 platform_system = platform.system()
31 if platform_system == 'Darwin':
32 # On Darwin, try the currently selected Xcode directory
33 xcode_dir = commands.getoutput("xcode-select --print-path")
35 lldb_python_dirs.append(os.path.realpath(xcode_dir + '/../SharedFrameworks/LLDB.framework/Resources/Python'))
36 lldb_python_dirs.append(xcode_dir + '/Library/PrivateFrameworks/LLDB.framework/Resources/Python')
37 lldb_python_dirs.append('/System/Library/PrivateFrameworks/LLDB.framework/Resources/Python')
39 for lldb_python_dir in lldb_python_dirs:
40 if os.path.exists(lldb_python_dir):
41 if not (sys.path.__contains__(lldb_python_dir)):
42 sys.path.append(lldb_python_dir)
48 print 'imported lldb from: "%s"' % (lldb_python_dir)
52 print "error: couldn't locate the 'lldb' module, please set PYTHONPATH correctly"
58 self.start = time.clock()
61 def __exit__(self, *args):
62 self.end = time.clock()
63 self.interval = self.end - self.start
66 """Class that encapsulates actions to take when a thread stops for a reason."""
67 def __init__(self, callback = None, callback_owner = None):
68 self.callback = callback
69 self.callback_owner = callback_owner
70 def ThreadStopped (self, thread):
71 assert False, "performance.Action.ThreadStopped(self, thread) must be overridden in a subclass"
73 class PlanCompleteAction (Action):
74 def __init__(self, callback = None, callback_owner = None):
75 Action.__init__(self, callback, callback_owner)
76 def ThreadStopped (self, thread):
77 if thread.GetStopReason() == lldb.eStopReasonPlanComplete:
79 if self.callback_owner:
80 self.callback (self.callback_owner, thread)
82 self.callback (thread)
87 class BreakpointAction (Action):
88 def __init__(self, callback = None, callback_owner = None, name = None, module = None, file = None, line = None, breakpoint = None):
89 Action.__init__(self, callback, callback_owner)
90 self.modules = lldb.SBFileSpecList()
91 self.files = lldb.SBFileSpecList()
92 self.breakpoints = list()
93 # "module" can be a list or a string
95 self.breakpoints.append(breakpoint)
98 if isinstance(module, types.ListType):
99 for module_path in module:
100 self.modules.Append(lldb.SBFileSpec(module_path, False))
101 elif isinstance(module, types.StringTypes):
102 self.modules.Append(lldb.SBFileSpec(module, False))
104 # "file" can be a list or a string
106 if isinstance(file, types.ListType):
107 self.files = lldb.SBFileSpecList()
109 self.files.Append(lldb.SBFileSpec(f, False))
110 elif isinstance(file, types.StringTypes):
111 self.files.Append(lldb.SBFileSpec(file, False))
112 self.breakpoints.append (self.target.BreakpointCreateByName(name, self.modules, self.files))
114 self.breakpoints.append (self.target.BreakpointCreateByLocation(file, line))
115 def ThreadStopped (self, thread):
116 if thread.GetStopReason() == lldb.eStopReasonBreakpoint:
117 for bp in self.breakpoints:
118 if bp.GetID() == thread.GetStopReasonDataAtIndex(0):
120 if self.callback_owner:
121 self.callback (self.callback_owner, thread)
123 self.callback (thread)
127 """Class that aids in running performance tests."""
130 self.debugger = lldb.SBDebugger.Create()
134 self.launch_info = None
136 self.listener = self.debugger.GetListener()
137 self.user_actions = list()
138 self.builtin_actions = list()
139 self.bp_id_to_dict = dict()
141 def Setup(self, args):
142 self.launch_info = lldb.SBLaunchInfo(args)
144 def Run (self, args):
145 assert False, "performance.TestCase.Run(self, args) must be subclassed"
149 error = lldb.SBError()
150 self.process = self.target.Launch (self.launch_info, error)
151 if not error.Success():
152 print "error: %s" % error.GetCString()
154 self.process.GetBroadcaster().AddListener(self.listener, lldb.SBProcess.eBroadcastBitStateChanged | lldb.SBProcess.eBroadcastBitInterrupt)
158 def WaitForNextProcessEvent (self):
162 process_event = lldb.SBEvent()
163 if self.listener.WaitForEvent (lldb.UINT32_MAX, process_event):
164 state = lldb.SBProcess.GetStateFromEvent (process_event)
166 print "event = %s" % (lldb.SBDebugger.StateAsCString(state))
167 if lldb.SBProcess.GetRestartedFromEvent(process_event):
169 if state == lldb.eStateInvalid or state == lldb.eStateDetached or state == lldb.eStateCrashed or state == lldb.eStateUnloaded or state == lldb.eStateExited:
170 event = process_event
172 elif state == lldb.eStateConnected or state == lldb.eStateAttaching or state == lldb.eStateLaunching or state == lldb.eStateRunning or state == lldb.eStateStepping or state == lldb.eStateSuspended:
174 elif state == lldb.eStateStopped:
175 event = process_event
176 call_test_step = True
178 selected_thread = False
179 for thread in self.process:
180 frame = thread.GetFrameAtIndex(0)
181 select_thread = False
183 stop_reason = thread.GetStopReason()
185 print "tid = %#x pc = %#x " % (thread.GetThreadID(),frame.GetPC()),
186 if stop_reason == lldb.eStopReasonNone:
189 elif stop_reason == lldb.eStopReasonTrace:
193 elif stop_reason == lldb.eStopReasonPlanComplete:
196 print "plan complete"
197 elif stop_reason == lldb.eStopReasonThreadExiting:
199 print "thread exiting"
200 elif stop_reason == lldb.eStopReasonExec:
203 elif stop_reason == lldb.eStopReasonInvalid:
206 elif stop_reason == lldb.eStopReasonException:
211 elif stop_reason == lldb.eStopReasonBreakpoint:
213 bp_id = thread.GetStopReasonDataAtIndex(0)
214 bp_loc_id = thread.GetStopReasonDataAtIndex(1)
216 print "breakpoint id = %d.%d" % (bp_id, bp_loc_id)
217 elif stop_reason == lldb.eStopReasonWatchpoint:
220 print "watchpoint id = %d" % (thread.GetStopReasonDataAtIndex(0))
221 elif stop_reason == lldb.eStopReasonSignal:
224 print "signal %d" % (thread.GetStopReasonDataAtIndex(0))
226 if select_thread and not selected_thread:
228 selected_thread = self.process.SetSelectedThread(thread)
230 for action in self.user_actions:
231 action.ThreadStopped (thread)
236 # Xcode.RunCommand(self.debugger,"bt all",true)
241 '''A class that encapsulates a measurement'''
243 object.__init__(self)
245 assert False, "performance.Measurement.Measure() must be subclassed"
247 class MemoryMeasurement(Measurement):
248 '''A class that can measure memory statistics for a process.'''
249 def __init__(self, pid):
250 Measurement.__init__(self)
252 self.stats = ["rprvt","rshrd","rsize","vsize","vprvt","kprvt","kshrd","faults","cow","pageins"]
253 self.command = "top -l 1 -pid %u -stats %s" % (self.pid, ",".join(self.stats))
257 output = commands.getoutput(self.command).split("\n")[-1]
258 values = re.split('[-+\s]+', output)
259 for (idx, stat) in enumerate(values):
265 elif stat[-1] == 'M':
266 multiplier = 1024*1024
268 elif stat[-1] == 'G':
269 multiplier = 1024*1024*1024
270 elif stat[-1] == 'T':
271 multiplier = 1024*1024*1024*1024
273 self.value[self.stats[idx]] = int (stat) * multiplier
276 '''Dump the MemoryMeasurement current value'''
278 for key in self.value.keys():
281 s += "%8s = %s" % (key, self.value[key])
285 class TesterTestCase(TestCase):
287 TestCase.__init__(self)
291 def BreakpointHit (self, thread):
292 bp_id = thread.GetStopReasonDataAtIndex(0)
293 loc_id = thread.GetStopReasonDataAtIndex(1)
294 print "Breakpoint %i.%i hit: %s" % (bp_id, loc_id, thread.process.target.FindBreakpointByID(bp_id))
297 def PlanComplete (self, thread):
298 if self.num_steps > 0:
300 self.num_steps = self.num_steps - 1
302 thread.process.Kill()
304 def Run (self, args):
306 with Timer() as total_time:
307 self.target = self.debugger.CreateTarget(args[0])
309 with Timer() as breakpoint_timer:
310 bp = self.target.BreakpointCreateByName("main")
311 print('Breakpoint time = %.03f sec.' % breakpoint_timer.interval)
313 self.user_actions.append (BreakpointAction(breakpoint=bp, callback=TesterTestCase.BreakpointHit, callback_owner=self))
314 self.user_actions.append (PlanCompleteAction(callback=TesterTestCase.PlanComplete, callback_owner=self))
318 self.WaitForNextProcessEvent()
320 print "error: failed to launch process"
322 print "error: failed to create target with '%s'" % (args[0])
323 print('Total time = %.03f sec.' % total_time.interval)
326 if __name__ == '__main__':
327 lldb.SBDebugger.Initialize()
328 test = TesterTestCase()
329 test.Run (sys.argv[1:])
330 mem = MemoryMeasurement(os.getpid())
333 lldb.SBDebugger.Terminate()
334 # print "sleeeping for 100 seconds"