blob: 516c0af44d023070b4605bc23c3f1d6f5266aa70 [file] [log] [blame]
Jamie Gennis92791472012-03-05 17:33:58 -08001#!/usr/bin/env python
2
Jamie Gennis4b56a2b2012-04-28 01:06:56 -07003# Copyright (c) 2011 The Chromium Authors. All rights reserved.
4# Use of this source code is governed by a BSD-style license that can be
5# found in the LICENSE file.
Jamie Gennis92791472012-03-05 17:33:58 -08006
7"""Android system-wide tracing utility.
8
9This is a tool for capturing a trace that includes data from both userland and
10the kernel. It creates an HTML file for visualizing the trace.
11"""
12
Jeff Brownc6e750f2014-08-15 16:27:54 -070013import errno, optparse, os, re, select, subprocess, sys, time, zlib
Jamie Gennis92791472012-03-05 17:33:58 -080014
Chris Craik5b5f1462015-04-07 16:41:13 -070015default_categories = 'sched gfx view dalvik webview input disk am wm'.split()
Jamie Gennis2da489c2012-09-19 18:06:29 -070016
Jamie Gennis664f21b2013-06-03 16:40:54 -070017class OptionParserIgnoreErrors(optparse.OptionParser):
18 def error(self, msg):
19 pass
20
21 def exit(self):
22 pass
23
24 def print_usage(self):
25 pass
26
27 def print_help(self):
28 pass
29
30 def print_version(self):
31 pass
32
33def get_device_sdk_version():
34 getprop_args = ['adb', 'shell', 'getprop', 'ro.build.version.sdk']
35
36 parser = OptionParserIgnoreErrors()
37 parser.add_option('-e', '--serial', dest='device_serial', type='string')
38 options, args = parser.parse_args()
39 if options.device_serial is not None:
40 getprop_args[1:1] = ['-s', options.device_serial]
41
Chris Craikb122baf2015-03-05 13:58:42 -080042 try:
43 adb = subprocess.Popen(getprop_args, stdout=subprocess.PIPE,
44 stderr=subprocess.PIPE)
45 except OSError:
46 print 'Missing adb?'
47 sys.exit(1)
Jamie Gennisc2a6cae2013-06-04 16:17:30 -070048 out, err = adb.communicate()
49 if adb.returncode != 0:
50 print >> sys.stderr, 'Error querying device SDK-version:'
51 print >> sys.stderr, err
52 sys.exit(1)
Jamie Gennis664f21b2013-06-03 16:40:54 -070053
Jamie Gennisc2a6cae2013-06-04 16:17:30 -070054 version = int(out)
55 return version
Jamie Gennis664f21b2013-06-03 16:40:54 -070056
Keun young Parkde427be2012-08-30 15:17:13 -070057def add_adb_serial(command, serial):
Jamie Gennis66a37682013-07-15 18:29:18 -070058 if serial is not None:
Keun young Parkde427be2012-08-30 15:17:13 -070059 command.insert(1, serial)
60 command.insert(1, '-s')
61
Chris Craik5b5f1462015-04-07 16:41:13 -070062def get_default_categories():
63 list_command = ['adb', 'shell', 'atrace', '--list_categories']
64 try:
65 categories_output = subprocess.check_output(list_command)
66 categories = [c.split('-')[0].strip() for c in categories_output.splitlines()]
67
68 return [c for c in categories if c in default_categories]
69 except:
70 return []
71
Jamie Gennis92791472012-03-05 17:33:58 -080072def main():
Jamie Gennis664f21b2013-06-03 16:40:54 -070073 device_sdk_version = get_device_sdk_version()
74 if device_sdk_version < 18:
75 legacy_script = os.path.join(os.path.dirname(sys.argv[0]), 'systrace-legacy.py')
76 os.execv(legacy_script, sys.argv)
77
Jamie Gennisfe4c5942012-11-18 18:15:22 -080078 usage = "Usage: %prog [options] [category1 [category2 ...]]"
79 desc = "Example: %prog -b 32768 -t 15 gfx input view sched freq"
80 parser = optparse.OptionParser(usage=usage, description=desc)
Jamie Gennis92791472012-03-05 17:33:58 -080081 parser.add_option('-o', dest='output_file', help='write HTML to FILE',
82 default='trace.html', metavar='FILE')
83 parser.add_option('-t', '--time', dest='trace_time', type='int',
84 help='trace for N seconds', metavar='N')
Jamie Gennis98ef97d2012-03-07 16:06:53 -080085 parser.add_option('-b', '--buf-size', dest='trace_buf_size', type='int',
86 help='use a trace buffer size of N KB', metavar='N')
Jamie Gennis553ec562012-11-20 17:45:49 -080087 parser.add_option('-k', '--ktrace', dest='kfuncs', action='store',
88 help='specify a comma-separated list of kernel functions to trace')
Jamie Gennisfe4c5942012-11-18 18:15:22 -080089 parser.add_option('-l', '--list-categories', dest='list_categories', default=False,
90 action='store_true', help='list the available categories and exit')
Jamie Gennisb9a5fc82013-03-27 19:55:09 -070091 parser.add_option('-a', '--app', dest='app_name', default=None, type='string',
92 action='store', help='enable application-level tracing for comma-separated ' +
93 'list of app cmdlines')
Jeff Brownc6e750f2014-08-15 16:27:54 -070094 parser.add_option('--no-fix-threads', dest='fix_threads', default=True,
95 action='store_false', help='don\'t fix missing or truncated thread names')
Adrian Roos61c9bc22015-05-06 19:06:01 -070096 parser.add_option('--no-fix-circular', dest='fix_circular', default=True,
97 action='store_false', help='don\'t fix truncated circular traces')
Jamie Gennisfe4c5942012-11-18 18:15:22 -080098
Jeff Brown595ae1e2012-05-22 14:52:13 -070099 parser.add_option('--link-assets', dest='link_assets', default=False,
100 action='store_true', help='link to original CSS or JS resources '
101 'instead of embedding them')
Glenn Kastena0cfa1d2012-10-08 15:40:30 -0700102 parser.add_option('--from-file', dest='from_file', action='store',
Xia Wang340d7722013-02-15 12:38:09 -0800103 help='read the trace from a file (compressed) rather than running a live trace')
Jamie Gennis2da489c2012-09-19 18:06:29 -0700104 parser.add_option('--asset-dir', dest='asset_dir', default='trace-viewer',
105 type='string', help='')
Keun young Parkde427be2012-08-30 15:17:13 -0700106 parser.add_option('-e', '--serial', dest='device_serial', type='string',
107 help='adb device serial number')
Jamie Gennisfe4c5942012-11-18 18:15:22 -0800108
Chris Craik5b5f1462015-04-07 16:41:13 -0700109 options, categories = parser.parse_args()
Jamie Gennis92791472012-03-05 17:33:58 -0800110
Chris Craikb122baf2015-03-05 13:58:42 -0800111 if options.link_assets or options.asset_dir != 'trace-viewer':
112 parser.error('--link-assets and --asset-dir is deprecated.')
113
Jamie Gennisfe4c5942012-11-18 18:15:22 -0800114 if options.list_categories:
Chris Craik631112b2015-04-28 17:00:17 -0700115 tracer_args = ['adb', 'shell', 'atrace --list_categories']
Jamie Gennisfe4c5942012-11-18 18:15:22 -0800116 expect_trace = False
117 elif options.from_file is not None:
Chris Craik631112b2015-04-28 17:00:17 -0700118 tracer_args = ['cat', options.from_file]
Jamie Gennisfe4c5942012-11-18 18:15:22 -0800119 expect_trace = True
120 else:
Chris Craik631112b2015-04-28 17:00:17 -0700121 atrace_args = ['atrace', '-z']
Jamie Gennisfe4c5942012-11-18 18:15:22 -0800122 expect_trace = True
123
124 if options.trace_time is not None:
125 if options.trace_time > 0:
126 atrace_args.extend(['-t', str(options.trace_time)])
127 else:
128 parser.error('the trace time must be a positive number')
Jamie Gennisb9a5fc82013-03-27 19:55:09 -0700129
Jamie Gennisfe4c5942012-11-18 18:15:22 -0800130 if options.trace_buf_size is not None:
131 if options.trace_buf_size > 0:
132 atrace_args.extend(['-b', str(options.trace_buf_size)])
133 else:
134 parser.error('the trace buffer size must be a positive number')
135
Jamie Gennisb9a5fc82013-03-27 19:55:09 -0700136 if options.app_name is not None:
137 atrace_args.extend(['-a', options.app_name])
138
Jamie Gennis553ec562012-11-20 17:45:49 -0800139 if options.kfuncs is not None:
140 atrace_args.extend(['-k', options.kfuncs])
141
Chris Craik5b5f1462015-04-07 16:41:13 -0700142 if not categories:
143 categories = get_default_categories()
144 atrace_args.extend(categories)
Jamie Gennisfe4c5942012-11-18 18:15:22 -0800145
Jeff Brownc6e750f2014-08-15 16:27:54 -0700146 if options.fix_threads:
147 atrace_args.extend([';', 'ps', '-t'])
Chris Craik631112b2015-04-28 17:00:17 -0700148 tracer_args = ['adb', 'shell', ' '.join(atrace_args)]
Jeff Brownc6e750f2014-08-15 16:27:54 -0700149
Chris Craik631112b2015-04-28 17:00:17 -0700150 if tracer_args[0] == 'adb':
151 add_adb_serial(tracer_args, options.device_serial)
Glenn Kastena0cfa1d2012-10-08 15:40:30 -0700152
Jamie Gennis4b56a2b2012-04-28 01:06:56 -0700153 script_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
Jeff Brown595ae1e2012-05-22 14:52:13 -0700154
Jamie Gennis92791472012-03-05 17:33:58 -0800155 html_filename = options.output_file
Jamie Gennis92791472012-03-05 17:33:58 -0800156
Chris Craik631112b2015-04-28 17:00:17 -0700157 adb = subprocess.Popen(tracer_args, stdout=subprocess.PIPE,
Jamie Gennis7e3783f2012-04-28 13:16:11 -0700158 stderr=subprocess.PIPE)
Jamie Gennis9623f132013-03-08 14:50:37 -0800159
160 result = None
161 data = []
162
163 # Read the text portion of the output and watch for the 'TRACE:' marker that
164 # indicates the start of the trace data.
165 while result is None:
Jamie Gennis1bf4a492012-03-13 18:07:36 -0700166 ready = select.select([adb.stdout, adb.stderr], [], [adb.stdout, adb.stderr])
167 if adb.stderr in ready[0]:
168 err = os.read(adb.stderr.fileno(), 4096)
169 sys.stderr.write(err)
170 sys.stderr.flush()
171 if adb.stdout in ready[0]:
Jamie Gennis9623f132013-03-08 14:50:37 -0800172 out = os.read(adb.stdout.fileno(), 4096)
173 parts = out.split('\nTRACE:', 1)
174
175 txt = parts[0].replace('\r', '')
176 if len(parts) == 2:
177 # The '\nTRACE:' match stole the last newline from the text, so add it
178 # back here.
179 txt += '\n'
180 sys.stdout.write(txt)
181 sys.stdout.flush()
182
183 if len(parts) == 2:
184 data.append(parts[1])
185 sys.stdout.write("downloading trace...")
186 sys.stdout.flush()
187 break
188
Jamie Gennis1bf4a492012-03-13 18:07:36 -0700189 result = adb.poll()
Jamie Gennis9623f132013-03-08 14:50:37 -0800190
191 # Read and buffer the data portion of the output.
Jamie Gennis18bb5282013-05-13 15:39:58 -0700192 while True:
Jamie Gennis9623f132013-03-08 14:50:37 -0800193 ready = select.select([adb.stdout, adb.stderr], [], [adb.stdout, adb.stderr])
Jamie Gennis18bb5282013-05-13 15:39:58 -0700194 keepReading = False
Jamie Gennis9623f132013-03-08 14:50:37 -0800195 if adb.stderr in ready[0]:
196 err = os.read(adb.stderr.fileno(), 4096)
Jamie Gennis18bb5282013-05-13 15:39:58 -0700197 if len(err) > 0:
198 keepReading = True
199 sys.stderr.write(err)
200 sys.stderr.flush()
Jamie Gennis9623f132013-03-08 14:50:37 -0800201 if adb.stdout in ready[0]:
202 out = os.read(adb.stdout.fileno(), 4096)
Jamie Gennis18bb5282013-05-13 15:39:58 -0700203 if len(out) > 0:
204 keepReading = True
205 data.append(out)
206
207 if result is not None and not keepReading:
208 break
Jamie Gennis9623f132013-03-08 14:50:37 -0800209
210 result = adb.poll()
211
212 if result == 0:
213 if expect_trace:
214 data = ''.join(data)
215
216 # Collapse CRLFs that are added by adb shell.
217 if data.startswith('\r\n'):
218 data = data.replace('\r\n', '\n')
219
220 # Skip the initial newline.
221 data = data[1:]
222
223 if not data:
224 print >> sys.stderr, ('No data was captured. Output file was not ' +
225 'written.')
226 sys.exit(1)
227 else:
228 # Indicate to the user that the data download is complete.
229 print " done\n"
230
Jeff Brownc6e750f2014-08-15 16:27:54 -0700231 # Extract the thread list dumped by ps.
232 threads = {}
233 if options.fix_threads:
Adrian Roos208a55a2015-05-07 15:54:32 -0700234 parts = re.split('USER +PID +PPID +VSIZE +RSS +WCHAN +PC +NAME', data, 1)
Jeff Brownc6e750f2014-08-15 16:27:54 -0700235 if len(parts) == 2:
236 data = parts[0]
237 for line in parts[1].splitlines():
238 cols = line.split(None, 8)
239 if len(cols) == 9:
240 tid = int(cols[1])
241 name = cols[8]
242 threads[tid] = name
243
244 # Decompress and preprocess the data.
245 out = zlib.decompress(data)
246 if options.fix_threads:
247 def repl(m):
248 tid = int(m.group(2))
249 if tid > 0:
250 name = threads.get(tid)
251 if name is None:
252 name = m.group(1)
253 if name == '<...>':
254 name = '<' + str(tid) + '>'
255 threads[tid] = name
256 return name + '-' + m.group(2)
257 else:
258 return m.group(0)
259 out = re.sub(r'^\s*(\S+)-(\d+)', repl, out, flags=re.MULTILINE)
260
Adrian Roos61c9bc22015-05-06 19:06:01 -0700261 if options.fix_circular:
262 out = fix_circular_traces(out)
263
Siva Velusamy48ea0762013-07-19 11:03:37 -0700264 html_prefix = read_asset(script_dir, 'prefix.html')
265 html_suffix = read_asset(script_dir, 'suffix.html')
Chris Craik5b5f1462015-04-07 16:41:13 -0700266 trace_viewer_html = read_asset(script_dir, 'systrace_trace_viewer.html')
Siva Velusamy48ea0762013-07-19 11:03:37 -0700267
Jamie Gennis9623f132013-03-08 14:50:37 -0800268 html_file = open(html_filename, 'w')
Chris Craikb122baf2015-03-05 13:58:42 -0800269 html_file.write(
270 html_prefix.replace("{{SYSTRACE_TRACE_VIEWER_HTML}}", trace_viewer_html))
Chris Craik92062442015-04-02 16:30:37 -0700271
Aaron Schulman64a222c2015-04-03 17:53:42 -0700272 html_file.write('<!-- BEGIN TRACE -->\n' +
273 ' <script class="trace-data" type="application/text">\n')
274 html_file.write(out)
275 html_file.write(' </script>\n<!-- END TRACE -->\n')
Chris Craik92062442015-04-02 16:30:37 -0700276
Jamie Gennis9623f132013-03-08 14:50:37 -0800277 html_file.write(html_suffix)
278 html_file.close()
Jamie Gennis66a37682013-07-15 18:29:18 -0700279 print "\n wrote file://%s\n" % os.path.abspath(options.output_file)
Jamie Gennis9623f132013-03-08 14:50:37 -0800280
281 else: # i.e. result != 0
282 print >> sys.stderr, 'adb returned error code %d' % result
283 sys.exit(1)
Jamie Gennis92791472012-03-05 17:33:58 -0800284
Siva Velusamy48ea0762013-07-19 11:03:37 -0700285def read_asset(src_dir, filename):
286 return open(os.path.join(src_dir, filename)).read()
287
Adrian Roos61c9bc22015-05-06 19:06:01 -0700288def fix_circular_traces(out):
289 """Fix inconsistentcies in traces due to circular buffering.
290
291 The circular buffers are kept per CPU, so it is not guaranteed that the
292 beginning of a slice is overwritten before the end. To work around this, we
293 throw away the prefix of the trace where not all CPUs have events yet."""
294
295 # If any of the CPU's buffers have filled up and
296 # older events have been dropped, the kernel
297 # emits markers of the form '##### CPU 2 buffer started ####' on
298 # the line before the first event in the trace on that CPU.
299 #
300 # No such headers are emitted if there were no overflows or the trace
301 # was captured with non-circular buffers.
302 buffer_start_re = re.compile(r'^#+ CPU \d+ buffer started', re.MULTILINE)
303
304 start_of_full_trace = 0
305
306 while True:
307 result = buffer_start_re.search(out, start_of_full_trace + 1)
308 if result:
309 start_of_full_trace = result.start()
310 else:
311 break
312
313 if start_of_full_trace > 0:
314 # Need to keep the header intact to make the importer happy.
315 end_of_header = re.search(r'^[^#]', out, re.MULTILINE).start()
316 out = out[:end_of_header] + out[start_of_full_trace:]
317 return out
Jeff Brown595ae1e2012-05-22 14:52:13 -0700318
Jamie Gennis92791472012-03-05 17:33:58 -0800319if __name__ == '__main__':
320 main()