forked from llvm/llvm-project
- Notifications
You must be signed in to change notification settings - Fork 339
/
Copy pathperformance.py
executable file
·439 lines (394 loc) · 16.6 KB
/
performance.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
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
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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
#!/usr/bin/env python
# ----------------------------------------------------------------------
# Be sure to add the python path that points to the LLDB shared library.
# On MacOSX csh, tcsh:
# setenv PYTHONPATH /Applications/Xcode.app/Contents/SharedFrameworks/LLDB.framework/Resources/Python
# On MacOSX sh, bash:
# export PYTHONPATH=/Applications/Xcode.app/Contents/SharedFrameworks/LLDB.framework/Resources/Python
# ----------------------------------------------------------------------
importoptparse
importos
importplatform
importre
importresource
importsys
importsubprocess
importtime
importtypes
# ----------------------------------------------------------------------
# Code that auto imports LLDB
# ----------------------------------------------------------------------
try:
# Just try for LLDB in case PYTHONPATH is already correctly setup
importlldb
exceptImportError:
lldb_python_dirs=list()
# lldb is not in the PYTHONPATH, try some defaults for the current platform
platform_system=platform.system()
ifplatform_system=="Darwin":
# On Darwin, try the currently selected Xcode directory
xcode_dir=subprocess.check_output("xcode-select --print-path", shell=True)
ifxcode_dir:
lldb_python_dirs.append(
os.path.realpath(
xcode_dir+"/../SharedFrameworks/LLDB.framework/Resources/Python"
)
)
lldb_python_dirs.append(
xcode_dir+"/Library/PrivateFrameworks/LLDB.framework/Resources/Python"
)
lldb_python_dirs.append(
"/System/Library/PrivateFrameworks/LLDB.framework/Resources/Python"
)
success=False
forlldb_python_dirinlldb_python_dirs:
ifos.path.exists(lldb_python_dir):
ifnot (sys.path.__contains__(lldb_python_dir)):
sys.path.append(lldb_python_dir)
try:
importlldb
exceptImportError:
pass
else:
print('imported lldb from: "%s"'% (lldb_python_dir))
success=True
break
ifnotsuccess:
print(
"error: couldn't locate the 'lldb' module, please set PYTHONPATH correctly"
)
sys.exit(1)
classTimer:
def__enter__(self):
self.start=time.clock()
returnself
def__exit__(self, *args):
self.end=time.clock()
self.interval=self.end-self.start
classAction(object):
"""Class that encapsulates actions to take when a thread stops for a reason."""
def__init__(self, callback=None, callback_owner=None):
self.callback=callback
self.callback_owner=callback_owner
defThreadStopped(self, thread):
assert (
False
), "performance.Action.ThreadStopped(self, thread) must be overridden in a subclass"
classPlanCompleteAction(Action):
def__init__(self, callback=None, callback_owner=None):
Action.__init__(self, callback, callback_owner)
defThreadStopped(self, thread):
ifthread.GetStopReason() ==lldb.eStopReasonPlanComplete:
ifself.callback:
ifself.callback_owner:
self.callback(self.callback_owner, thread)
else:
self.callback(thread)
returnTrue
returnFalse
classBreakpointAction(Action):
def__init__(
self,
callback=None,
callback_owner=None,
name=None,
module=None,
file=None,
line=None,
breakpoint=None,
):
Action.__init__(self, callback, callback_owner)
self.modules=lldb.SBFileSpecList()
self.files=lldb.SBFileSpecList()
self.breakpoints=list()
# "module" can be a list or a string
ifbreakpoint:
self.breakpoints.append(breakpoint)
else:
ifmodule:
ifisinstance(module, types.ListType):
formodule_pathinmodule:
self.modules.Append(lldb.SBFileSpec(module_path, False))
elifisinstance(module, types.StringTypes):
self.modules.Append(lldb.SBFileSpec(module, False))
ifname:
# "file" can be a list or a string
iffile:
ifisinstance(file, types.ListType):
self.files=lldb.SBFileSpecList()
forfinfile:
self.files.Append(lldb.SBFileSpec(f, False))
elifisinstance(file, types.StringTypes):
self.files.Append(lldb.SBFileSpec(file, False))
self.breakpoints.append(
self.target.BreakpointCreateByName(name, self.modules, self.files)
)
eliffileandline:
self.breakpoints.append(
self.target.BreakpointCreateByLocation(file, line)
)
defThreadStopped(self, thread):
ifthread.GetStopReason() ==lldb.eStopReasonBreakpoint:
forbpinself.breakpoints:
ifbp.GetID() ==thread.GetStopReasonDataAtIndex(0):
ifself.callback:
ifself.callback_owner:
self.callback(self.callback_owner, thread)
else:
self.callback(thread)
returnTrue
returnFalse
classTestCase:
"""Class that aids in running performance tests."""
def__init__(self):
self.verbose=False
self.debugger=lldb.SBDebugger.Create()
self.target=None
self.process=None
self.thread=None
self.launch_info=None
self.done=False
self.listener=self.debugger.GetListener()
self.user_actions=list()
self.builtin_actions=list()
self.bp_id_to_dict=dict()
defSetup(self, args):
self.launch_info=lldb.SBLaunchInfo(args)
defRun(self, args):
assertFalse, "performance.TestCase.Run(self, args) must be subclassed"
defLaunch(self):
ifself.target:
error=lldb.SBError()
self.process=self.target.Launch(self.launch_info, error)
ifnoterror.Success():
print("error: %s"%error.GetCString())
ifself.process:
self.process.GetBroadcaster().AddListener(
self.listener,
lldb.SBProcess.eBroadcastBitStateChanged
|lldb.SBProcess.eBroadcastBitInterrupt,
)
returnTrue
returnFalse
defWaitForNextProcessEvent(self):
event=None
ifself.process:
whileeventisNone:
process_event=lldb.SBEvent()
ifself.listener.WaitForEvent(lldb.UINT32_MAX, process_event):
state=lldb.SBProcess.GetStateFromEvent(process_event)
ifself.verbose:
print("event = %s"% (lldb.SBDebugger.StateAsCString(state)))
iflldb.SBProcess.GetRestartedFromEvent(process_event):
continue
if (
state==lldb.eStateInvalid
orstate==lldb.eStateDetached
orstate==lldb.eStateCrashed
orstate==lldb.eStateUnloaded
orstate==lldb.eStateExited
):
event=process_event
self.done=True
elif (
state==lldb.eStateConnected
orstate==lldb.eStateAttaching
orstate==lldb.eStateLaunching
orstate==lldb.eStateRunning
orstate==lldb.eStateStepping
orstate==lldb.eStateSuspended
):
continue
elifstate==lldb.eStateStopped:
event=process_event
call_test_step=True
fatal=False
selected_thread=False
forthreadinself.process:
frame=thread.GetFrameAtIndex(0)
select_thread=False
stop_reason=thread.GetStopReason()
ifself.verbose:
print(
"tid = %#x pc = %#x "
% (thread.GetThreadID(), frame.GetPC()),
end=" ",
)
ifstop_reason==lldb.eStopReasonNone:
ifself.verbose:
print("none")
elifstop_reason==lldb.eStopReasonTrace:
select_thread=True
ifself.verbose:
print("trace")
elifstop_reason==lldb.eStopReasonPlanComplete:
select_thread=True
ifself.verbose:
print("plan complete")
elifstop_reason==lldb.eStopReasonThreadExiting:
ifself.verbose:
print("thread exiting")
elifstop_reason==lldb.eStopReasonExec:
ifself.verbose:
print("exec")
elifstop_reason==lldb.eStopReasonInvalid:
ifself.verbose:
print("invalid")
elifstop_reason==lldb.eStopReasonException:
select_thread=True
ifself.verbose:
print("exception")
fatal=True
elifstop_reason==lldb.eStopReasonBreakpoint:
select_thread=True
bp_id=thread.GetStopReasonDataAtIndex(0)
bp_loc_id=thread.GetStopReasonDataAtIndex(1)
ifself.verbose:
print("breakpoint id = %d.%d"% (bp_id, bp_loc_id))
elifstop_reason==lldb.eStopReasonWatchpoint:
select_thread=True
ifself.verbose:
print(
"watchpoint id = %d"
% (thread.GetStopReasonDataAtIndex(0))
)
elifstop_reason==lldb.eStopReasonSignal:
select_thread=True
ifself.verbose:
print(
"signal %d"
% (thread.GetStopReasonDataAtIndex(0))
)
elifstop_reason==lldb.eStopReasonFork:
ifself.verbose:
print(
"fork pid = %d"
% (thread.GetStopReasonDataAtIndex(0))
)
elifstop_reason==lldb.eStopReasonVFork:
ifself.verbose:
print(
"vfork pid = %d"
% (thread.GetStopReasonDataAtIndex(0))
)
elifstop_reason==lldb.eStopReasonVForkDone:
ifself.verbose:
print("vfork done")
ifselect_threadandnotselected_thread:
self.thread=thread
selected_thread=self.process.SetSelectedThread(thread)
foractioninself.user_actions:
action.ThreadStopped(thread)
iffatal:
# if self.verbose:
# Xcode.RunCommand(self.debugger,"bt all",true)
sys.exit(1)
returnevent
classMeasurement:
"""A class that encapsulates a measurement"""
def__init__(self):
object.__init__(self)
defMeasure(self):
assertFalse, "performance.Measurement.Measure() must be subclassed"
classMemoryMeasurement(Measurement):
"""A class that can measure memory statistics for a process."""
def__init__(self, pid):
Measurement.__init__(self)
self.pid=pid
self.stats= [
"rprvt",
"rshrd",
"rsize",
"vsize",
"vprvt",
"kprvt",
"kshrd",
"faults",
"cow",
"pageins",
]
self.command="top -l 1 -pid %u -stats %s"% (self.pid, ",".join(self.stats))
self.value=dict()
defMeasure(self):
output=subprocess.getoutput(self.command).split("\n")[-1]
values=re.split(r"[-+\s]+", output)
foridx, statinenumerate(values):
multiplier=1
ifstat:
ifstat[-1] =="K":
multiplier=1024
stat=stat[:-1]
elifstat[-1] =="M":
multiplier=1024*1024
stat=stat[:-1]
elifstat[-1] =="G":
multiplier=1024*1024*1024
elifstat[-1] =="T":
multiplier=1024*1024*1024*1024
stat=stat[:-1]
self.value[self.stats[idx]] =int(stat) *multiplier
def__str__(self):
"""Dump the MemoryMeasurement current value"""
s=""
forkeyinself.value.keys():
ifs:
s+="\n"
s+="%8s = %s"% (key, self.value[key])
returns
classTesterTestCase(TestCase):
def__init__(self):
TestCase.__init__(self)
self.verbose=True
self.num_steps=5
defBreakpointHit(self, thread):
bp_id=thread.GetStopReasonDataAtIndex(0)
loc_id=thread.GetStopReasonDataAtIndex(1)
print(
"Breakpoint %i.%i hit: %s"
% (bp_id, loc_id, thread.process.target.FindBreakpointByID(bp_id))
)
thread.StepOver()
defPlanComplete(self, thread):
ifself.num_steps>0:
thread.StepOver()
self.num_steps=self.num_steps-1
else:
thread.process.Kill()
defRun(self, args):
self.Setup(args)
withTimer() astotal_time:
self.target=self.debugger.CreateTarget(args[0])
ifself.target:
withTimer() asbreakpoint_timer:
bp=self.target.BreakpointCreateByName("main")
print("Breakpoint time = %.03f sec."%breakpoint_timer.interval)
self.user_actions.append(
BreakpointAction(
breakpoint=bp,
callback=TesterTestCase.BreakpointHit,
callback_owner=self,
)
)
self.user_actions.append(
PlanCompleteAction(
callback=TesterTestCase.PlanComplete, callback_owner=self
)
)
ifself.Launch():
whilenotself.done:
self.WaitForNextProcessEvent()
else:
print("error: failed to launch process")
else:
print("error: failed to create target with '%s'"% (args[0]))
print("Total time = %.03f sec."%total_time.interval)
if__name__=="__main__":
lldb.SBDebugger.Initialize()
test=TesterTestCase()
test.Run(sys.argv[1:])
mem=MemoryMeasurement(os.getpid())
mem.Measure()
print(str(mem))
lldb.SBDebugger.Terminate()
# print "sleeeping for 100 seconds"
# time.sleep(100)