blob: da98284abaf751d6f7a4124bfe5c1064ba4443b1 [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')
35
Jeff Brown595ae1e2012-05-22 14:52:13 -070036 parser.add_option('--link-assets', dest='link_assets', default=False,
37 action='store_true', help='link to original CSS or JS resources '
38 'instead of embedding them')
Glenn Kastena0cfa1d2012-10-08 15:40:30 -070039 parser.add_option('--from-file', dest='from_file', action='store',
Xia Wang340d7722013-02-15 12:38:09 -080040 help='read the trace from a file (compressed) rather than running a live trace')
Jamie Gennis2da489c2012-09-19 18:06:29 -070041 parser.add_option('--asset-dir', dest='asset_dir', default='trace-viewer',
42 type='string', help='')
Keun young Parkde427be2012-08-30 15:17:13 -070043 parser.add_option('-e', '--serial', dest='device_serial', type='string',
44 help='adb device serial number')
Jamie Gennisfe4c5942012-11-18 18:15:22 -080045
Jamie Gennis92791472012-03-05 17:33:58 -080046 options, args = parser.parse_args()
47
Jamie Gennisfe4c5942012-11-18 18:15:22 -080048 if options.list_categories:
49 atrace_args = ['adb', 'shell', 'atrace', '--list_categories']
50 expect_trace = False
51 elif options.from_file is not None:
Glenn Kastena0cfa1d2012-10-08 15:40:30 -070052 atrace_args = ['cat', options.from_file]
Jamie Gennisfe4c5942012-11-18 18:15:22 -080053 expect_trace = True
54 else:
55 atrace_args = ['adb', 'shell', 'atrace', '-z']
56 expect_trace = True
57
58 if options.trace_time is not None:
59 if options.trace_time > 0:
60 atrace_args.extend(['-t', str(options.trace_time)])
61 else:
62 parser.error('the trace time must be a positive number')
63 if options.trace_buf_size is not None:
64 if options.trace_buf_size > 0:
65 atrace_args.extend(['-b', str(options.trace_buf_size)])
66 else:
67 parser.error('the trace buffer size must be a positive number')
68
69 atrace_args.extend(args)
70
71 if atrace_args[0] == 'adb':
72 add_adb_serial(atrace_args, options.device_serial)
Glenn Kastena0cfa1d2012-10-08 15:40:30 -070073
Jamie Gennis4b56a2b2012-04-28 01:06:56 -070074 script_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
Jeff Brown595ae1e2012-05-22 14:52:13 -070075
76 if options.link_assets:
Jamie Gennis2da489c2012-09-19 18:06:29 -070077 src_dir = os.path.join(script_dir, options.asset_dir, 'src')
78 build_dir = os.path.join(script_dir, options.asset_dir, 'build')
79
80 js_files, js_flattenizer, css_files = get_assets(src_dir, build_dir)
81
82 css = '\n'.join(linked_css_tag % (os.path.join(src_dir, f)) for f in css_files)
83 js = '<script language="javascript">\n%s</script>\n' % js_flattenizer
84 js += '\n'.join(linked_js_tag % (os.path.join(src_dir, f)) for f in js_files)
Jeff Brown595ae1e2012-05-22 14:52:13 -070085 else:
Jamie Gennis2da489c2012-09-19 18:06:29 -070086 css_filename = os.path.join(script_dir, flattened_css_file)
87 js_filename = os.path.join(script_dir, flattened_js_file)
Jeff Brown595ae1e2012-05-22 14:52:13 -070088 css = compiled_css_tag % (open(css_filename).read())
89 js = compiled_js_tag % (open(js_filename).read())
Jamie Gennis4b56a2b2012-04-28 01:06:56 -070090
Jamie Gennis92791472012-03-05 17:33:58 -080091 html_filename = options.output_file
Jamie Gennis92791472012-03-05 17:33:58 -080092
Jamie Gennis1bf4a492012-03-13 18:07:36 -070093 adb = subprocess.Popen(atrace_args, stdout=subprocess.PIPE,
Jamie Gennis7e3783f2012-04-28 13:16:11 -070094 stderr=subprocess.PIPE)
Jamie Gennis9623f132013-03-08 14:50:37 -080095
96 result = None
97 data = []
98
99 # Read the text portion of the output and watch for the 'TRACE:' marker that
100 # indicates the start of the trace data.
101 while result is None:
Jamie Gennis1bf4a492012-03-13 18:07:36 -0700102 ready = select.select([adb.stdout, adb.stderr], [], [adb.stdout, adb.stderr])
103 if adb.stderr in ready[0]:
104 err = os.read(adb.stderr.fileno(), 4096)
105 sys.stderr.write(err)
106 sys.stderr.flush()
107 if adb.stdout in ready[0]:
Jamie Gennis9623f132013-03-08 14:50:37 -0800108 out = os.read(adb.stdout.fileno(), 4096)
109 parts = out.split('\nTRACE:', 1)
110
111 txt = parts[0].replace('\r', '')
112 if len(parts) == 2:
113 # The '\nTRACE:' match stole the last newline from the text, so add it
114 # back here.
115 txt += '\n'
116 sys.stdout.write(txt)
117 sys.stdout.flush()
118
119 if len(parts) == 2:
120 data.append(parts[1])
121 sys.stdout.write("downloading trace...")
122 sys.stdout.flush()
123 break
124
Jamie Gennis1bf4a492012-03-13 18:07:36 -0700125 result = adb.poll()
Jamie Gennis9623f132013-03-08 14:50:37 -0800126
127 # Read and buffer the data portion of the output.
128 while result is None:
129 ready = select.select([adb.stdout, adb.stderr], [], [adb.stdout, adb.stderr])
130 if adb.stderr in ready[0]:
131 err = os.read(adb.stderr.fileno(), 4096)
132 sys.stderr.write(err)
133 sys.stderr.flush()
134 if adb.stdout in ready[0]:
135 out = os.read(adb.stdout.fileno(), 4096)
136 data.append(out)
137
138 result = adb.poll()
139
140 if result == 0:
141 if expect_trace:
142 data = ''.join(data)
143
144 # Collapse CRLFs that are added by adb shell.
145 if data.startswith('\r\n'):
146 data = data.replace('\r\n', '\n')
147
148 # Skip the initial newline.
149 data = data[1:]
150
151 if not data:
152 print >> sys.stderr, ('No data was captured. Output file was not ' +
153 'written.')
154 sys.exit(1)
155 else:
156 # Indicate to the user that the data download is complete.
157 print " done\n"
158
159 html_file = open(html_filename, 'w')
160 html_file.write(html_prefix % (css, js))
161
162 size = 4096
163 dec = zlib.decompressobj()
164 for chunk in (data[i:i+size] for i in xrange(0, len(data), size)):
165 decoded_chunk = dec.decompress(chunk)
166 html_chunk = decoded_chunk.replace('\n', '\\n\\\n')
167 html_file.write(html_chunk)
168
169 html_out = dec.flush().replace('\n', '\\n\\\n')
Jamie Gennisbf3e6162012-04-28 19:16:49 -0700170 html_file.write(html_out)
Jamie Gennis9623f132013-03-08 14:50:37 -0800171 html_file.write(html_suffix)
172 html_file.close()
173 print "\n wrote file://%s/%s\n" % (os.getcwd(), options.output_file)
174
175 else: # i.e. result != 0
176 print >> sys.stderr, 'adb returned error code %d' % result
177 sys.exit(1)
Jamie Gennis92791472012-03-05 17:33:58 -0800178
Jamie Gennis2da489c2012-09-19 18:06:29 -0700179def get_assets(src_dir, build_dir):
180 sys.path.append(build_dir)
181 gen = __import__('generate_standalone_timeline_view', {}, {})
182 parse_deps = __import__('parse_deps', {}, {})
183 filenames = gen._get_input_filenames()
Jamie Gennis9623f132013-03-08 14:50:37 -0800184 load_sequence = parse_deps.calc_load_sequence(filenames, src_dir)
Jamie Gennis2da489c2012-09-19 18:06:29 -0700185
186 js_files = []
187 js_flattenizer = "window.FLATTENED = {};\n"
188 css_files = []
189
190 for module in load_sequence:
191 js_files.append(os.path.relpath(module.filename, src_dir))
192 js_flattenizer += "window.FLATTENED['%s'] = true;\n" % module.name
193 for style_sheet in module.style_sheets:
194 css_files.append(os.path.relpath(style_sheet.filename, src_dir))
195
196 sys.path.pop()
197
198 return (js_files, js_flattenizer, css_files)
199
Jamie Gennis92791472012-03-05 17:33:58 -0800200html_prefix = """<!DOCTYPE HTML>
201<html>
202<head i18n-values="dir:textdirection;">
203<title>Android System Trace</title>
Jeff Brown595ae1e2012-05-22 14:52:13 -0700204%s
205%s
Jamie Gennis2da489c2012-09-19 18:06:29 -0700206<script language="javascript">
207document.addEventListener('DOMContentLoaded', function() {
208 if (!linuxPerfData)
209 return;
210
Jeff Brown88448d92013-03-27 17:00:08 -0700211 var m = new tracing.Model(linuxPerfData);
Jamie Gennis2da489c2012-09-19 18:06:29 -0700212 var timelineViewEl = document.querySelector('.view');
Jeff Brown88448d92013-03-27 17:00:08 -0700213 tracing.ui.decorate(timelineViewEl, tracing.TimelineView);
Jamie Gennis2da489c2012-09-19 18:06:29 -0700214 timelineViewEl.model = m;
215 timelineViewEl.tabIndex = 1;
216 timelineViewEl.timeline.focusElement = timelineViewEl;
217});
218</script>
Jamie Gennis92791472012-03-05 17:33:58 -0800219<style>
220 .view {
221 overflow: hidden;
222 position: absolute;
223 top: 0;
224 bottom: 0;
225 left: 0;
226 right: 0;
227 }
228</style>
229</head>
230<body>
231 <div class="view">
232 </div>
Jamie Gennis2da489c2012-09-19 18:06:29 -0700233<!-- BEGIN TRACE -->
Jamie Gennis92791472012-03-05 17:33:58 -0800234 <script>
235 var linuxPerfData = "\\
236"""
237
Jamie Gennis2da489c2012-09-19 18:06:29 -0700238html_suffix = """\\n";
Jamie Gennis92791472012-03-05 17:33:58 -0800239 </script>
Jamie Gennis2da489c2012-09-19 18:06:29 -0700240<!-- END TRACE -->
Jamie Gennis92791472012-03-05 17:33:58 -0800241</body>
242</html>
243"""
244
Jeff Brown595ae1e2012-05-22 14:52:13 -0700245compiled_css_tag = """<style type="text/css">%s</style>"""
246compiled_js_tag = """<script language="javascript">%s</script>"""
247
248linked_css_tag = """<link rel="stylesheet" href="%s"></link>"""
249linked_js_tag = """<script language="javascript" src="%s"></script>"""
250
Jamie Gennis92791472012-03-05 17:33:58 -0800251if __name__ == '__main__':
252 main()