blob: 3b2585eddd5f25fc9cf94cd392171a672548dbef [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
Jamie Gennis2da489c2012-09-19 18:06:29 -070013import errno, optparse, os, select, subprocess, sys, time, zlib
Jamie Gennis92791472012-03-05 17:33:58 -080014
Jamie Gennis2da489c2012-09-19 18:06:29 -070015flattened_css_file = 'style.css'
16flattened_js_file = 'script.js'
17
Keun young Parkde427be2012-08-30 15:17:13 -070018def add_adb_serial(command, serial):
19 if serial != None:
20 command.insert(1, serial)
21 command.insert(1, '-s')
22
Jamie Gennis92791472012-03-05 17:33:58 -080023def main():
Jamie Gennisfe4c5942012-11-18 18:15:22 -080024 usage = "Usage: %prog [options] [category1 [category2 ...]]"
25 desc = "Example: %prog -b 32768 -t 15 gfx input view sched freq"
26 parser = optparse.OptionParser(usage=usage, description=desc)
Jamie Gennis92791472012-03-05 17:33:58 -080027 parser.add_option('-o', dest='output_file', help='write HTML to FILE',
28 default='trace.html', metavar='FILE')
29 parser.add_option('-t', '--time', dest='trace_time', type='int',
30 help='trace for N seconds', metavar='N')
Jamie Gennis98ef97d2012-03-07 16:06:53 -080031 parser.add_option('-b', '--buf-size', dest='trace_buf_size', type='int',
32 help='use a trace buffer size of N KB', metavar='N')
Jamie Gennis553ec562012-11-20 17:45:49 -080033 parser.add_option('-k', '--ktrace', dest='kfuncs', action='store',
34 help='specify a comma-separated list of kernel functions to trace')
Jamie Gennisfe4c5942012-11-18 18:15:22 -080035 parser.add_option('-l', '--list-categories', dest='list_categories', default=False,
36 action='store_true', help='list the available categories and exit')
Jamie Gennisb9a5fc82013-03-27 19:55:09 -070037 parser.add_option('-a', '--app', dest='app_name', default=None, type='string',
38 action='store', help='enable application-level tracing for comma-separated ' +
39 'list of app cmdlines')
Jamie Gennisfe4c5942012-11-18 18:15:22 -080040
Jeff Brown595ae1e2012-05-22 14:52:13 -070041 parser.add_option('--link-assets', dest='link_assets', default=False,
42 action='store_true', help='link to original CSS or JS resources '
43 'instead of embedding them')
Glenn Kastena0cfa1d2012-10-08 15:40:30 -070044 parser.add_option('--from-file', dest='from_file', action='store',
Xia Wang340d7722013-02-15 12:38:09 -080045 help='read the trace from a file (compressed) rather than running a live trace')
Jamie Gennis2da489c2012-09-19 18:06:29 -070046 parser.add_option('--asset-dir', dest='asset_dir', default='trace-viewer',
47 type='string', help='')
Keun young Parkde427be2012-08-30 15:17:13 -070048 parser.add_option('-e', '--serial', dest='device_serial', type='string',
49 help='adb device serial number')
Jamie Gennisfe4c5942012-11-18 18:15:22 -080050
Jamie Gennis92791472012-03-05 17:33:58 -080051 options, args = parser.parse_args()
52
Jamie Gennisfe4c5942012-11-18 18:15:22 -080053 if options.list_categories:
54 atrace_args = ['adb', 'shell', 'atrace', '--list_categories']
55 expect_trace = False
56 elif options.from_file is not None:
Glenn Kastena0cfa1d2012-10-08 15:40:30 -070057 atrace_args = ['cat', options.from_file]
Jamie Gennisfe4c5942012-11-18 18:15:22 -080058 expect_trace = True
59 else:
60 atrace_args = ['adb', 'shell', 'atrace', '-z']
61 expect_trace = True
62
63 if options.trace_time is not None:
64 if options.trace_time > 0:
65 atrace_args.extend(['-t', str(options.trace_time)])
66 else:
67 parser.error('the trace time must be a positive number')
Jamie Gennisb9a5fc82013-03-27 19:55:09 -070068
Jamie Gennisfe4c5942012-11-18 18:15:22 -080069 if options.trace_buf_size is not None:
70 if options.trace_buf_size > 0:
71 atrace_args.extend(['-b', str(options.trace_buf_size)])
72 else:
73 parser.error('the trace buffer size must be a positive number')
74
Jamie Gennisb9a5fc82013-03-27 19:55:09 -070075 if options.app_name is not None:
76 atrace_args.extend(['-a', options.app_name])
77
Jamie Gennis553ec562012-11-20 17:45:49 -080078 if options.kfuncs is not None:
79 atrace_args.extend(['-k', options.kfuncs])
80
Jamie Gennisfe4c5942012-11-18 18:15:22 -080081 atrace_args.extend(args)
82
83 if atrace_args[0] == 'adb':
84 add_adb_serial(atrace_args, options.device_serial)
Glenn Kastena0cfa1d2012-10-08 15:40:30 -070085
Jamie Gennis4b56a2b2012-04-28 01:06:56 -070086 script_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
Jeff Brown595ae1e2012-05-22 14:52:13 -070087
88 if options.link_assets:
Jamie Gennis2da489c2012-09-19 18:06:29 -070089 src_dir = os.path.join(script_dir, options.asset_dir, 'src')
90 build_dir = os.path.join(script_dir, options.asset_dir, 'build')
91
92 js_files, js_flattenizer, css_files = get_assets(src_dir, build_dir)
93
94 css = '\n'.join(linked_css_tag % (os.path.join(src_dir, f)) for f in css_files)
95 js = '<script language="javascript">\n%s</script>\n' % js_flattenizer
96 js += '\n'.join(linked_js_tag % (os.path.join(src_dir, f)) for f in js_files)
Jeff Brown595ae1e2012-05-22 14:52:13 -070097 else:
Jamie Gennis2da489c2012-09-19 18:06:29 -070098 css_filename = os.path.join(script_dir, flattened_css_file)
99 js_filename = os.path.join(script_dir, flattened_js_file)
Jeff Brown595ae1e2012-05-22 14:52:13 -0700100 css = compiled_css_tag % (open(css_filename).read())
101 js = compiled_js_tag % (open(js_filename).read())
Jamie Gennis4b56a2b2012-04-28 01:06:56 -0700102
Jamie Gennis92791472012-03-05 17:33:58 -0800103 html_filename = options.output_file
Jamie Gennis92791472012-03-05 17:33:58 -0800104
Jamie Gennis1bf4a492012-03-13 18:07:36 -0700105 adb = subprocess.Popen(atrace_args, stdout=subprocess.PIPE,
Jamie Gennis7e3783f2012-04-28 13:16:11 -0700106 stderr=subprocess.PIPE)
Jamie Gennis9623f132013-03-08 14:50:37 -0800107
108 result = None
109 data = []
110
111 # Read the text portion of the output and watch for the 'TRACE:' marker that
112 # indicates the start of the trace data.
113 while result is None:
Jamie Gennis1bf4a492012-03-13 18:07:36 -0700114 ready = select.select([adb.stdout, adb.stderr], [], [adb.stdout, adb.stderr])
115 if adb.stderr in ready[0]:
116 err = os.read(adb.stderr.fileno(), 4096)
117 sys.stderr.write(err)
118 sys.stderr.flush()
119 if adb.stdout in ready[0]:
Jamie Gennis9623f132013-03-08 14:50:37 -0800120 out = os.read(adb.stdout.fileno(), 4096)
121 parts = out.split('\nTRACE:', 1)
122
123 txt = parts[0].replace('\r', '')
124 if len(parts) == 2:
125 # The '\nTRACE:' match stole the last newline from the text, so add it
126 # back here.
127 txt += '\n'
128 sys.stdout.write(txt)
129 sys.stdout.flush()
130
131 if len(parts) == 2:
132 data.append(parts[1])
133 sys.stdout.write("downloading trace...")
134 sys.stdout.flush()
135 break
136
Jamie Gennis1bf4a492012-03-13 18:07:36 -0700137 result = adb.poll()
Jamie Gennis9623f132013-03-08 14:50:37 -0800138
139 # Read and buffer the data portion of the output.
Jamie Gennis18bb5282013-05-13 15:39:58 -0700140 while True:
Jamie Gennis9623f132013-03-08 14:50:37 -0800141 ready = select.select([adb.stdout, adb.stderr], [], [adb.stdout, adb.stderr])
Jamie Gennis18bb5282013-05-13 15:39:58 -0700142 keepReading = False
Jamie Gennis9623f132013-03-08 14:50:37 -0800143 if adb.stderr in ready[0]:
144 err = os.read(adb.stderr.fileno(), 4096)
Jamie Gennis18bb5282013-05-13 15:39:58 -0700145 if len(err) > 0:
146 keepReading = True
147 sys.stderr.write(err)
148 sys.stderr.flush()
Jamie Gennis9623f132013-03-08 14:50:37 -0800149 if adb.stdout in ready[0]:
150 out = os.read(adb.stdout.fileno(), 4096)
Jamie Gennis18bb5282013-05-13 15:39:58 -0700151 if len(out) > 0:
152 keepReading = True
153 data.append(out)
154
155 if result is not None and not keepReading:
156 break
Jamie Gennis9623f132013-03-08 14:50:37 -0800157
158 result = adb.poll()
159
160 if result == 0:
161 if expect_trace:
162 data = ''.join(data)
163
164 # Collapse CRLFs that are added by adb shell.
165 if data.startswith('\r\n'):
166 data = data.replace('\r\n', '\n')
167
168 # Skip the initial newline.
169 data = data[1:]
170
171 if not data:
172 print >> sys.stderr, ('No data was captured. Output file was not ' +
173 'written.')
174 sys.exit(1)
175 else:
176 # Indicate to the user that the data download is complete.
177 print " done\n"
178
179 html_file = open(html_filename, 'w')
180 html_file.write(html_prefix % (css, js))
181
182 size = 4096
183 dec = zlib.decompressobj()
184 for chunk in (data[i:i+size] for i in xrange(0, len(data), size)):
185 decoded_chunk = dec.decompress(chunk)
186 html_chunk = decoded_chunk.replace('\n', '\\n\\\n')
187 html_file.write(html_chunk)
188
189 html_out = dec.flush().replace('\n', '\\n\\\n')
Jamie Gennisbf3e6162012-04-28 19:16:49 -0700190 html_file.write(html_out)
Jamie Gennis9623f132013-03-08 14:50:37 -0800191 html_file.write(html_suffix)
192 html_file.close()
193 print "\n wrote file://%s/%s\n" % (os.getcwd(), options.output_file)
194
195 else: # i.e. result != 0
196 print >> sys.stderr, 'adb returned error code %d' % result
197 sys.exit(1)
Jamie Gennis92791472012-03-05 17:33:58 -0800198
Jamie Gennis2da489c2012-09-19 18:06:29 -0700199def get_assets(src_dir, build_dir):
200 sys.path.append(build_dir)
201 gen = __import__('generate_standalone_timeline_view', {}, {})
202 parse_deps = __import__('parse_deps', {}, {})
203 filenames = gen._get_input_filenames()
Jamie Gennis9623f132013-03-08 14:50:37 -0800204 load_sequence = parse_deps.calc_load_sequence(filenames, src_dir)
Jamie Gennis2da489c2012-09-19 18:06:29 -0700205
206 js_files = []
207 js_flattenizer = "window.FLATTENED = {};\n"
208 css_files = []
209
210 for module in load_sequence:
211 js_files.append(os.path.relpath(module.filename, src_dir))
212 js_flattenizer += "window.FLATTENED['%s'] = true;\n" % module.name
213 for style_sheet in module.style_sheets:
214 css_files.append(os.path.relpath(style_sheet.filename, src_dir))
215
216 sys.path.pop()
217
218 return (js_files, js_flattenizer, css_files)
219
Jamie Gennis92791472012-03-05 17:33:58 -0800220html_prefix = """<!DOCTYPE HTML>
221<html>
222<head i18n-values="dir:textdirection;">
Jamie Gennisb9a5fc82013-03-27 19:55:09 -0700223<meta charset="utf-8"/>
Jamie Gennis92791472012-03-05 17:33:58 -0800224<title>Android System Trace</title>
Jeff Brown595ae1e2012-05-22 14:52:13 -0700225%s
226%s
Jamie Gennis2da489c2012-09-19 18:06:29 -0700227<script language="javascript">
228document.addEventListener('DOMContentLoaded', function() {
229 if (!linuxPerfData)
230 return;
231
Jeff Brown88448d92013-03-27 17:00:08 -0700232 var m = new tracing.Model(linuxPerfData);
Jamie Gennis2da489c2012-09-19 18:06:29 -0700233 var timelineViewEl = document.querySelector('.view');
Jeff Brown88448d92013-03-27 17:00:08 -0700234 tracing.ui.decorate(timelineViewEl, tracing.TimelineView);
Jamie Gennis2da489c2012-09-19 18:06:29 -0700235 timelineViewEl.model = m;
236 timelineViewEl.tabIndex = 1;
237 timelineViewEl.timeline.focusElement = timelineViewEl;
238});
239</script>
Jamie Gennis92791472012-03-05 17:33:58 -0800240<style>
241 .view {
242 overflow: hidden;
243 position: absolute;
244 top: 0;
245 bottom: 0;
246 left: 0;
247 right: 0;
248 }
249</style>
250</head>
251<body>
252 <div class="view">
253 </div>
Jamie Gennis2da489c2012-09-19 18:06:29 -0700254<!-- BEGIN TRACE -->
Jamie Gennis92791472012-03-05 17:33:58 -0800255 <script>
256 var linuxPerfData = "\\
257"""
258
Jamie Gennis2da489c2012-09-19 18:06:29 -0700259html_suffix = """\\n";
Jamie Gennis92791472012-03-05 17:33:58 -0800260 </script>
Jamie Gennis2da489c2012-09-19 18:06:29 -0700261<!-- END TRACE -->
Jamie Gennis92791472012-03-05 17:33:58 -0800262</body>
263</html>
264"""
265
Jeff Brown595ae1e2012-05-22 14:52:13 -0700266compiled_css_tag = """<style type="text/css">%s</style>"""
267compiled_js_tag = """<script language="javascript">%s</script>"""
268
269linked_css_tag = """<link rel="stylesheet" href="%s"></link>"""
270linked_js_tag = """<script language="javascript" src="%s"></script>"""
271
Jamie Gennis92791472012-03-05 17:33:58 -0800272if __name__ == '__main__':
273 main()