blob: 83033e0be71582f8078f07ef2fc7e7a361f22cb5 [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.
140 while result is None:
141 ready = select.select([adb.stdout, adb.stderr], [], [adb.stdout, adb.stderr])
142 if adb.stderr in ready[0]:
143 err = os.read(adb.stderr.fileno(), 4096)
144 sys.stderr.write(err)
145 sys.stderr.flush()
146 if adb.stdout in ready[0]:
147 out = os.read(adb.stdout.fileno(), 4096)
148 data.append(out)
149
150 result = adb.poll()
151
152 if result == 0:
153 if expect_trace:
154 data = ''.join(data)
155
156 # Collapse CRLFs that are added by adb shell.
157 if data.startswith('\r\n'):
158 data = data.replace('\r\n', '\n')
159
160 # Skip the initial newline.
161 data = data[1:]
162
163 if not data:
164 print >> sys.stderr, ('No data was captured. Output file was not ' +
165 'written.')
166 sys.exit(1)
167 else:
168 # Indicate to the user that the data download is complete.
169 print " done\n"
170
171 html_file = open(html_filename, 'w')
172 html_file.write(html_prefix % (css, js))
173
174 size = 4096
175 dec = zlib.decompressobj()
176 for chunk in (data[i:i+size] for i in xrange(0, len(data), size)):
177 decoded_chunk = dec.decompress(chunk)
178 html_chunk = decoded_chunk.replace('\n', '\\n\\\n')
179 html_file.write(html_chunk)
180
181 html_out = dec.flush().replace('\n', '\\n\\\n')
Jamie Gennisbf3e6162012-04-28 19:16:49 -0700182 html_file.write(html_out)
Jamie Gennis9623f132013-03-08 14:50:37 -0800183 html_file.write(html_suffix)
184 html_file.close()
185 print "\n wrote file://%s/%s\n" % (os.getcwd(), options.output_file)
186
187 else: # i.e. result != 0
188 print >> sys.stderr, 'adb returned error code %d' % result
189 sys.exit(1)
Jamie Gennis92791472012-03-05 17:33:58 -0800190
Jamie Gennis2da489c2012-09-19 18:06:29 -0700191def get_assets(src_dir, build_dir):
192 sys.path.append(build_dir)
193 gen = __import__('generate_standalone_timeline_view', {}, {})
194 parse_deps = __import__('parse_deps', {}, {})
195 filenames = gen._get_input_filenames()
Jamie Gennis9623f132013-03-08 14:50:37 -0800196 load_sequence = parse_deps.calc_load_sequence(filenames, src_dir)
Jamie Gennis2da489c2012-09-19 18:06:29 -0700197
198 js_files = []
199 js_flattenizer = "window.FLATTENED = {};\n"
200 css_files = []
201
202 for module in load_sequence:
203 js_files.append(os.path.relpath(module.filename, src_dir))
204 js_flattenizer += "window.FLATTENED['%s'] = true;\n" % module.name
205 for style_sheet in module.style_sheets:
206 css_files.append(os.path.relpath(style_sheet.filename, src_dir))
207
208 sys.path.pop()
209
210 return (js_files, js_flattenizer, css_files)
211
Jamie Gennis92791472012-03-05 17:33:58 -0800212html_prefix = """<!DOCTYPE HTML>
213<html>
214<head i18n-values="dir:textdirection;">
Jamie Gennisb9a5fc82013-03-27 19:55:09 -0700215<meta charset="utf-8"/>
Jamie Gennis92791472012-03-05 17:33:58 -0800216<title>Android System Trace</title>
Jeff Brown595ae1e2012-05-22 14:52:13 -0700217%s
218%s
Jamie Gennis2da489c2012-09-19 18:06:29 -0700219<script language="javascript">
220document.addEventListener('DOMContentLoaded', function() {
221 if (!linuxPerfData)
222 return;
223
Jeff Brown88448d92013-03-27 17:00:08 -0700224 var m = new tracing.Model(linuxPerfData);
Jamie Gennis2da489c2012-09-19 18:06:29 -0700225 var timelineViewEl = document.querySelector('.view');
Jeff Brown88448d92013-03-27 17:00:08 -0700226 tracing.ui.decorate(timelineViewEl, tracing.TimelineView);
Jamie Gennis2da489c2012-09-19 18:06:29 -0700227 timelineViewEl.model = m;
228 timelineViewEl.tabIndex = 1;
229 timelineViewEl.timeline.focusElement = timelineViewEl;
230});
231</script>
Jamie Gennis92791472012-03-05 17:33:58 -0800232<style>
233 .view {
234 overflow: hidden;
235 position: absolute;
236 top: 0;
237 bottom: 0;
238 left: 0;
239 right: 0;
240 }
241</style>
242</head>
243<body>
244 <div class="view">
245 </div>
Jamie Gennis2da489c2012-09-19 18:06:29 -0700246<!-- BEGIN TRACE -->
Jamie Gennis92791472012-03-05 17:33:58 -0800247 <script>
248 var linuxPerfData = "\\
249"""
250
Jamie Gennis2da489c2012-09-19 18:06:29 -0700251html_suffix = """\\n";
Jamie Gennis92791472012-03-05 17:33:58 -0800252 </script>
Jamie Gennis2da489c2012-09-19 18:06:29 -0700253<!-- END TRACE -->
Jamie Gennis92791472012-03-05 17:33:58 -0800254</body>
255</html>
256"""
257
Jeff Brown595ae1e2012-05-22 14:52:13 -0700258compiled_css_tag = """<style type="text/css">%s</style>"""
259compiled_js_tag = """<script language="javascript">%s</script>"""
260
261linked_css_tag = """<link rel="stylesheet" href="%s"></link>"""
262linked_js_tag = """<script language="javascript" src="%s"></script>"""
263
Jamie Gennis92791472012-03-05 17:33:58 -0800264if __name__ == '__main__':
265 main()