blob: e5da99d1b44e44d8fc00885e0484e809025c0097 [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 Gennisfe4c5942012-11-18 18:15:22 -080033 parser.add_option('-l', '--list-categories', dest='list_categories', default=False,
34 action='store_true', help='list the available categories and exit')
Jamie Gennisb9a5fc82013-03-27 19:55:09 -070035 parser.add_option('-a', '--app', dest='app_name', default=None, type='string',
36 action='store', help='enable application-level tracing for comma-separated ' +
37 'list of app cmdlines')
Jamie Gennisfe4c5942012-11-18 18:15:22 -080038
Jeff Brown595ae1e2012-05-22 14:52:13 -070039 parser.add_option('--link-assets', dest='link_assets', default=False,
40 action='store_true', help='link to original CSS or JS resources '
41 'instead of embedding them')
Glenn Kastena0cfa1d2012-10-08 15:40:30 -070042 parser.add_option('--from-file', dest='from_file', action='store',
Xia Wang340d7722013-02-15 12:38:09 -080043 help='read the trace from a file (compressed) rather than running a live trace')
Jamie Gennis2da489c2012-09-19 18:06:29 -070044 parser.add_option('--asset-dir', dest='asset_dir', default='trace-viewer',
45 type='string', help='')
Keun young Parkde427be2012-08-30 15:17:13 -070046 parser.add_option('-e', '--serial', dest='device_serial', type='string',
47 help='adb device serial number')
Jamie Gennisfe4c5942012-11-18 18:15:22 -080048
Jamie Gennis92791472012-03-05 17:33:58 -080049 options, args = parser.parse_args()
50
Jamie Gennisfe4c5942012-11-18 18:15:22 -080051 if options.list_categories:
52 atrace_args = ['adb', 'shell', 'atrace', '--list_categories']
53 expect_trace = False
54 elif options.from_file is not None:
Glenn Kastena0cfa1d2012-10-08 15:40:30 -070055 atrace_args = ['cat', options.from_file]
Jamie Gennisfe4c5942012-11-18 18:15:22 -080056 expect_trace = True
57 else:
58 atrace_args = ['adb', 'shell', 'atrace', '-z']
59 expect_trace = True
60
61 if options.trace_time is not None:
62 if options.trace_time > 0:
63 atrace_args.extend(['-t', str(options.trace_time)])
64 else:
65 parser.error('the trace time must be a positive number')
Jamie Gennisb9a5fc82013-03-27 19:55:09 -070066
Jamie Gennisfe4c5942012-11-18 18:15:22 -080067 if options.trace_buf_size is not None:
68 if options.trace_buf_size > 0:
69 atrace_args.extend(['-b', str(options.trace_buf_size)])
70 else:
71 parser.error('the trace buffer size must be a positive number')
72
Jamie Gennisb9a5fc82013-03-27 19:55:09 -070073 if options.app_name is not None:
74 atrace_args.extend(['-a', options.app_name])
75
Jamie Gennisfe4c5942012-11-18 18:15:22 -080076 atrace_args.extend(args)
77
78 if atrace_args[0] == 'adb':
79 add_adb_serial(atrace_args, options.device_serial)
Glenn Kastena0cfa1d2012-10-08 15:40:30 -070080
Jamie Gennis4b56a2b2012-04-28 01:06:56 -070081 script_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
Jeff Brown595ae1e2012-05-22 14:52:13 -070082
83 if options.link_assets:
Jamie Gennis2da489c2012-09-19 18:06:29 -070084 src_dir = os.path.join(script_dir, options.asset_dir, 'src')
85 build_dir = os.path.join(script_dir, options.asset_dir, 'build')
86
87 js_files, js_flattenizer, css_files = get_assets(src_dir, build_dir)
88
89 css = '\n'.join(linked_css_tag % (os.path.join(src_dir, f)) for f in css_files)
90 js = '<script language="javascript">\n%s</script>\n' % js_flattenizer
91 js += '\n'.join(linked_js_tag % (os.path.join(src_dir, f)) for f in js_files)
Jeff Brown595ae1e2012-05-22 14:52:13 -070092 else:
Jamie Gennis2da489c2012-09-19 18:06:29 -070093 css_filename = os.path.join(script_dir, flattened_css_file)
94 js_filename = os.path.join(script_dir, flattened_js_file)
Jeff Brown595ae1e2012-05-22 14:52:13 -070095 css = compiled_css_tag % (open(css_filename).read())
96 js = compiled_js_tag % (open(js_filename).read())
Jamie Gennis4b56a2b2012-04-28 01:06:56 -070097
Jamie Gennis92791472012-03-05 17:33:58 -080098 html_filename = options.output_file
Jamie Gennis92791472012-03-05 17:33:58 -080099
Jamie Gennis1bf4a492012-03-13 18:07:36 -0700100 adb = subprocess.Popen(atrace_args, stdout=subprocess.PIPE,
Jamie Gennis7e3783f2012-04-28 13:16:11 -0700101 stderr=subprocess.PIPE)
Jamie Gennis9623f132013-03-08 14:50:37 -0800102
103 result = None
104 data = []
105
106 # Read the text portion of the output and watch for the 'TRACE:' marker that
107 # indicates the start of the trace data.
108 while result is None:
Jamie Gennis1bf4a492012-03-13 18:07:36 -0700109 ready = select.select([adb.stdout, adb.stderr], [], [adb.stdout, adb.stderr])
110 if adb.stderr in ready[0]:
111 err = os.read(adb.stderr.fileno(), 4096)
112 sys.stderr.write(err)
113 sys.stderr.flush()
114 if adb.stdout in ready[0]:
Jamie Gennis9623f132013-03-08 14:50:37 -0800115 out = os.read(adb.stdout.fileno(), 4096)
116 parts = out.split('\nTRACE:', 1)
117
118 txt = parts[0].replace('\r', '')
119 if len(parts) == 2:
120 # The '\nTRACE:' match stole the last newline from the text, so add it
121 # back here.
122 txt += '\n'
123 sys.stdout.write(txt)
124 sys.stdout.flush()
125
126 if len(parts) == 2:
127 data.append(parts[1])
128 sys.stdout.write("downloading trace...")
129 sys.stdout.flush()
130 break
131
Jamie Gennis1bf4a492012-03-13 18:07:36 -0700132 result = adb.poll()
Jamie Gennis9623f132013-03-08 14:50:37 -0800133
134 # Read and buffer the data portion of the output.
135 while result is None:
136 ready = select.select([adb.stdout, adb.stderr], [], [adb.stdout, adb.stderr])
137 if adb.stderr in ready[0]:
138 err = os.read(adb.stderr.fileno(), 4096)
139 sys.stderr.write(err)
140 sys.stderr.flush()
141 if adb.stdout in ready[0]:
142 out = os.read(adb.stdout.fileno(), 4096)
143 data.append(out)
144
145 result = adb.poll()
146
147 if result == 0:
148 if expect_trace:
149 data = ''.join(data)
150
151 # Collapse CRLFs that are added by adb shell.
152 if data.startswith('\r\n'):
153 data = data.replace('\r\n', '\n')
154
155 # Skip the initial newline.
156 data = data[1:]
157
158 if not data:
159 print >> sys.stderr, ('No data was captured. Output file was not ' +
160 'written.')
161 sys.exit(1)
162 else:
163 # Indicate to the user that the data download is complete.
164 print " done\n"
165
166 html_file = open(html_filename, 'w')
167 html_file.write(html_prefix % (css, js))
168
169 size = 4096
170 dec = zlib.decompressobj()
171 for chunk in (data[i:i+size] for i in xrange(0, len(data), size)):
172 decoded_chunk = dec.decompress(chunk)
173 html_chunk = decoded_chunk.replace('\n', '\\n\\\n')
174 html_file.write(html_chunk)
175
176 html_out = dec.flush().replace('\n', '\\n\\\n')
Jamie Gennisbf3e6162012-04-28 19:16:49 -0700177 html_file.write(html_out)
Jamie Gennis9623f132013-03-08 14:50:37 -0800178 html_file.write(html_suffix)
179 html_file.close()
180 print "\n wrote file://%s/%s\n" % (os.getcwd(), options.output_file)
181
182 else: # i.e. result != 0
183 print >> sys.stderr, 'adb returned error code %d' % result
184 sys.exit(1)
Jamie Gennis92791472012-03-05 17:33:58 -0800185
Jamie Gennis2da489c2012-09-19 18:06:29 -0700186def get_assets(src_dir, build_dir):
187 sys.path.append(build_dir)
188 gen = __import__('generate_standalone_timeline_view', {}, {})
189 parse_deps = __import__('parse_deps', {}, {})
190 filenames = gen._get_input_filenames()
Jamie Gennis9623f132013-03-08 14:50:37 -0800191 load_sequence = parse_deps.calc_load_sequence(filenames, src_dir)
Jamie Gennis2da489c2012-09-19 18:06:29 -0700192
193 js_files = []
194 js_flattenizer = "window.FLATTENED = {};\n"
195 css_files = []
196
197 for module in load_sequence:
198 js_files.append(os.path.relpath(module.filename, src_dir))
199 js_flattenizer += "window.FLATTENED['%s'] = true;\n" % module.name
200 for style_sheet in module.style_sheets:
201 css_files.append(os.path.relpath(style_sheet.filename, src_dir))
202
203 sys.path.pop()
204
205 return (js_files, js_flattenizer, css_files)
206
Jamie Gennis92791472012-03-05 17:33:58 -0800207html_prefix = """<!DOCTYPE HTML>
208<html>
209<head i18n-values="dir:textdirection;">
Jamie Gennisb9a5fc82013-03-27 19:55:09 -0700210<meta charset="utf-8"/>
Jamie Gennis92791472012-03-05 17:33:58 -0800211<title>Android System Trace</title>
Jeff Brown595ae1e2012-05-22 14:52:13 -0700212%s
213%s
Jamie Gennis2da489c2012-09-19 18:06:29 -0700214<script language="javascript">
215document.addEventListener('DOMContentLoaded', function() {
216 if (!linuxPerfData)
217 return;
218
Jeff Brown88448d92013-03-27 17:00:08 -0700219 var m = new tracing.Model(linuxPerfData);
Jamie Gennis2da489c2012-09-19 18:06:29 -0700220 var timelineViewEl = document.querySelector('.view');
Jeff Brown88448d92013-03-27 17:00:08 -0700221 tracing.ui.decorate(timelineViewEl, tracing.TimelineView);
Jamie Gennis2da489c2012-09-19 18:06:29 -0700222 timelineViewEl.model = m;
223 timelineViewEl.tabIndex = 1;
224 timelineViewEl.timeline.focusElement = timelineViewEl;
225});
226</script>
Jamie Gennis92791472012-03-05 17:33:58 -0800227<style>
228 .view {
229 overflow: hidden;
230 position: absolute;
231 top: 0;
232 bottom: 0;
233 left: 0;
234 right: 0;
235 }
236</style>
237</head>
238<body>
239 <div class="view">
240 </div>
Jamie Gennis2da489c2012-09-19 18:06:29 -0700241<!-- BEGIN TRACE -->
Jamie Gennis92791472012-03-05 17:33:58 -0800242 <script>
243 var linuxPerfData = "\\
244"""
245
Jamie Gennis2da489c2012-09-19 18:06:29 -0700246html_suffix = """\\n";
Jamie Gennis92791472012-03-05 17:33:58 -0800247 </script>
Jamie Gennis2da489c2012-09-19 18:06:29 -0700248<!-- END TRACE -->
Jamie Gennis92791472012-03-05 17:33:58 -0800249</body>
250</html>
251"""
252
Jeff Brown595ae1e2012-05-22 14:52:13 -0700253compiled_css_tag = """<style type="text/css">%s</style>"""
254compiled_js_tag = """<script language="javascript">%s</script>"""
255
256linked_css_tag = """<link rel="stylesheet" href="%s"></link>"""
257linked_js_tag = """<script language="javascript" src="%s"></script>"""
258
Jamie Gennis92791472012-03-05 17:33:58 -0800259if __name__ == '__main__':
260 main()