blob: 1d4b30c02e93a68129a9cd5e638ae169b13948ec [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 Brown595ae1e2012-05-22 14:52:13 -070013import errno, optparse, os, select, subprocess, sys, time, zlib, config
Jamie Gennis92791472012-03-05 17:33:58 -080014
Jamie Gennis7e3783f2012-04-28 13:16:11 -070015# This list is based on the tags in frameworks/native/include/utils/Trace.h.
16trace_tag_bits = {
17 'gfx': 1<<1,
18 'input': 1<<2,
19 'view': 1<<3,
20 'webview': 1<<4,
21 'wm': 1<<5,
22 'am': 1<<6,
Andy Stadler5bd161f2012-05-03 15:31:03 -070023 'sync': 1<<7,
Glenn Kastenb4fa51e2012-05-07 09:19:32 -070024 'audio': 1<<8,
Jamie Gennisb7f480d2012-05-11 04:44:03 -070025 'video': 1<<9,
Eino-Ville Talvalada772982012-05-31 15:49:57 -070026 'camera': 1<<10,
Jamie Gennis7e3783f2012-04-28 13:16:11 -070027}
28
Keun young Parkde427be2012-08-30 15:17:13 -070029def add_adb_serial(command, serial):
30 if serial != None:
31 command.insert(1, serial)
32 command.insert(1, '-s')
33
Jamie Gennis92791472012-03-05 17:33:58 -080034def main():
35 parser = optparse.OptionParser()
36 parser.add_option('-o', dest='output_file', help='write HTML to FILE',
37 default='trace.html', metavar='FILE')
38 parser.add_option('-t', '--time', dest='trace_time', type='int',
39 help='trace for N seconds', metavar='N')
Jamie Gennis98ef97d2012-03-07 16:06:53 -080040 parser.add_option('-b', '--buf-size', dest='trace_buf_size', type='int',
41 help='use a trace buffer size of N KB', metavar='N')
Jeff Browna4d8b282012-05-22 18:56:09 -070042 parser.add_option('-d', '--disk', dest='trace_disk', default=False,
Jamie Gennis1f5d4e92012-06-07 16:59:27 -070043 action='store_true', help='trace disk I/O (requires root)')
Jamie Gennis98ef97d2012-03-07 16:06:53 -080044 parser.add_option('-f', '--cpu-freq', dest='trace_cpu_freq', default=False,
45 action='store_true', help='trace CPU frequency changes')
Jamie Gennis415e5d82012-05-07 18:00:11 -070046 parser.add_option('-i', '--cpu-idle', dest='trace_cpu_idle', default=False,
47 action='store_true', help='trace CPU idle events')
Jamie Gennis98ef97d2012-03-07 16:06:53 -080048 parser.add_option('-l', '--cpu-load', dest='trace_cpu_load', default=False,
49 action='store_true', help='trace CPU load')
Andy Stadler5bd161f2012-05-03 15:31:03 -070050 parser.add_option('-s', '--no-cpu-sched', dest='trace_cpu_sched', default=True,
51 action='store_false', help='inhibit tracing CPU ' +
52 'scheduler (allows longer trace times by reducing data ' +
53 'rate into buffer)')
Jamie Gennis92791472012-03-05 17:33:58 -080054 parser.add_option('-w', '--workqueue', dest='trace_workqueue', default=False,
Jamie Gennis1f5d4e92012-06-07 16:59:27 -070055 action='store_true', help='trace the kernel workqueues ' +
56 '(requires root)')
Jamie Gennis7e3783f2012-04-28 13:16:11 -070057 parser.add_option('--set-tags', dest='set_tags', action='store',
58 help='set the enabled trace tags and exit; set to a ' +
59 'comma separated list of: ' +
60 ', '.join(trace_tag_bits.iterkeys()))
Jeff Brown595ae1e2012-05-22 14:52:13 -070061 parser.add_option('--link-assets', dest='link_assets', default=False,
62 action='store_true', help='link to original CSS or JS resources '
63 'instead of embedding them')
Keun young Parkde427be2012-08-30 15:17:13 -070064 parser.add_option('-e', '--serial', dest='device_serial', type='string',
65 help='adb device serial number')
Jamie Gennis92791472012-03-05 17:33:58 -080066 options, args = parser.parse_args()
67
Jamie Gennis7e3783f2012-04-28 13:16:11 -070068 if options.set_tags:
69 flags = 0
70 tags = options.set_tags.split(',')
71 for tag in tags:
72 try:
73 flags |= trace_tag_bits[tag]
74 except KeyError:
75 parser.error('unrecognized tag: %s\nknown tags are: %s' %
76 (tag, ', '.join(trace_tag_bits.iterkeys())))
Jamie Gennis81e9aa72012-05-09 13:57:58 -070077 atrace_args = ['adb', 'shell', 'setprop', 'debug.atrace.tags.enableflags', hex(flags)]
Keun young Parkde427be2012-08-30 15:17:13 -070078 add_adb_serial(atrace_args, options.device_serial)
Jamie Gennis7e3783f2012-04-28 13:16:11 -070079 try:
80 subprocess.check_call(atrace_args)
81 except subprocess.CalledProcessError, e:
Jamie Gennis1f5d4e92012-06-07 16:59:27 -070082 print >> sys.stderr, 'unable to set tags: %s' % e
Jamie Gennis7e3783f2012-04-28 13:16:11 -070083 print '\nSet enabled tags to: %s\n' % ', '.join(tags)
84 print ('You will likely need to restart the Android framework for this to ' +
85 'take effect:\n\n adb shell stop\n adb shell ' +
86 'start\n')
87 return
88
Andy Stadler5bd161f2012-05-03 15:31:03 -070089 atrace_args = ['adb', 'shell', 'atrace', '-z']
Keun young Parkde427be2012-08-30 15:17:13 -070090 add_adb_serial(atrace_args, options.device_serial)
91
Jeff Browna4d8b282012-05-22 18:56:09 -070092 if options.trace_disk:
93 atrace_args.append('-d')
Jamie Gennis98ef97d2012-03-07 16:06:53 -080094 if options.trace_cpu_freq:
95 atrace_args.append('-f')
Jamie Gennis415e5d82012-05-07 18:00:11 -070096 if options.trace_cpu_idle:
97 atrace_args.append('-i')
Jamie Gennis98ef97d2012-03-07 16:06:53 -080098 if options.trace_cpu_load:
99 atrace_args.append('-l')
Andy Stadler5bd161f2012-05-03 15:31:03 -0700100 if options.trace_cpu_sched:
101 atrace_args.append('-s')
Jamie Gennis92791472012-03-05 17:33:58 -0800102 if options.trace_workqueue:
103 atrace_args.append('-w')
104 if options.trace_time is not None:
105 if options.trace_time > 0:
106 atrace_args.extend(['-t', str(options.trace_time)])
107 else:
108 parser.error('the trace time must be a positive number')
Jamie Gennis98ef97d2012-03-07 16:06:53 -0800109 if options.trace_buf_size is not None:
110 if options.trace_buf_size > 0:
111 atrace_args.extend(['-b', str(options.trace_buf_size)])
112 else:
113 parser.error('the trace buffer size must be a positive number')
Jamie Gennis92791472012-03-05 17:33:58 -0800114
Jamie Gennis4b56a2b2012-04-28 01:06:56 -0700115 script_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
Jeff Brown595ae1e2012-05-22 14:52:13 -0700116
117 if options.link_assets:
118 css = '\n'.join(linked_css_tag % (os.path.join(script_dir, f)) for f in config.css_in_files)
119 js = '\n'.join(linked_js_tag % (os.path.join(script_dir, f)) for f in config.js_in_files)
120 else:
121 css_filename = os.path.join(script_dir, config.css_out_file)
122 js_filename = os.path.join(script_dir, config.js_out_file)
123 css = compiled_css_tag % (open(css_filename).read())
124 js = compiled_js_tag % (open(js_filename).read())
Jamie Gennis4b56a2b2012-04-28 01:06:56 -0700125
Jamie Gennis92791472012-03-05 17:33:58 -0800126 html_filename = options.output_file
Jamie Gennis92791472012-03-05 17:33:58 -0800127
128 trace_started = False
Jamie Gennis1bf4a492012-03-13 18:07:36 -0700129 leftovers = ''
130 adb = subprocess.Popen(atrace_args, stdout=subprocess.PIPE,
Jamie Gennis7e3783f2012-04-28 13:16:11 -0700131 stderr=subprocess.PIPE)
Jamie Gennisbf3e6162012-04-28 19:16:49 -0700132 dec = zlib.decompressobj()
Jamie Gennis92791472012-03-05 17:33:58 -0800133 while True:
Jamie Gennis1bf4a492012-03-13 18:07:36 -0700134 ready = select.select([adb.stdout, adb.stderr], [], [adb.stdout, adb.stderr])
135 if adb.stderr in ready[0]:
136 err = os.read(adb.stderr.fileno(), 4096)
137 sys.stderr.write(err)
138 sys.stderr.flush()
139 if adb.stdout in ready[0]:
Jamie Gennisbf3e6162012-04-28 19:16:49 -0700140 out = leftovers + os.read(adb.stdout.fileno(), 4096)
141 out = out.replace('\r\n', '\n')
142 if out.endswith('\r'):
143 out = out[:-1]
144 leftovers = '\r'
145 else:
146 leftovers = ''
Jamie Gennis92791472012-03-05 17:33:58 -0800147 if not trace_started:
Jamie Gennis1bf4a492012-03-13 18:07:36 -0700148 lines = out.splitlines(True)
Jamie Gennisbf3e6162012-04-28 19:16:49 -0700149 out = ''
Jamie Gennis92791472012-03-05 17:33:58 -0800150 for i, line in enumerate(lines):
Jamie Gennisbf3e6162012-04-28 19:16:49 -0700151 if line == 'TRACE:\n':
Jamie Gennis1bf4a492012-03-13 18:07:36 -0700152 sys.stdout.write("downloading trace...")
Jamie Gennis92791472012-03-05 17:33:58 -0800153 sys.stdout.flush()
Jamie Gennis1bf4a492012-03-13 18:07:36 -0700154 out = ''.join(lines[i+1:])
Jamie Gennis1f5d4e92012-06-07 16:59:27 -0700155 html_file = open(html_filename, 'w')
156 html_file.write(html_prefix % (css, js))
Jamie Gennis92791472012-03-05 17:33:58 -0800157 trace_started = True
158 break
Jamie Gennis1bf4a492012-03-13 18:07:36 -0700159 elif 'TRACE:'.startswith(line) and i == len(lines) - 1:
Jamie Gennisbf3e6162012-04-28 19:16:49 -0700160 leftovers = line + leftovers
Jamie Gennis92791472012-03-05 17:33:58 -0800161 else:
Jamie Gennis1bf4a492012-03-13 18:07:36 -0700162 sys.stdout.write(line)
Jamie Gennis92791472012-03-05 17:33:58 -0800163 sys.stdout.flush()
Jamie Gennisbf3e6162012-04-28 19:16:49 -0700164 if len(out) > 0:
165 out = dec.decompress(out)
166 html_out = out.replace('\n', '\\n\\\n')
Jamie Gennis1bf4a492012-03-13 18:07:36 -0700167 if len(html_out) > 0:
168 html_file.write(html_out)
169 result = adb.poll()
Jamie Gennis92791472012-03-05 17:33:58 -0800170 if result is not None:
171 break
172 if result != 0:
Jamie Gennis1f5d4e92012-06-07 16:59:27 -0700173 print >> sys.stderr, 'adb returned error code %d' % result
174 elif trace_started:
Jamie Gennisbf3e6162012-04-28 19:16:49 -0700175 html_out = dec.flush().replace('\n', '\\n\\\n').replace('\r', '')
176 if len(html_out) > 0:
177 html_file.write(html_out)
Jamie Gennis92791472012-03-05 17:33:58 -0800178 html_file.write(html_suffix)
179 html_file.close()
Jamie Gennis1bf4a492012-03-13 18:07:36 -0700180 print " done\n\n wrote file://%s/%s\n" % (os.getcwd(), options.output_file)
Jamie Gennis1f5d4e92012-06-07 16:59:27 -0700181 else:
182 print >> sys.stderr, ('An error occured while capturing the trace. Output ' +
183 'file was not written.')
Jamie Gennis92791472012-03-05 17:33:58 -0800184
185html_prefix = """<!DOCTYPE HTML>
186<html>
187<head i18n-values="dir:textdirection;">
188<title>Android System Trace</title>
Jeff Brown595ae1e2012-05-22 14:52:13 -0700189%s
190%s
Jamie Gennis92791472012-03-05 17:33:58 -0800191<style>
192 .view {
193 overflow: hidden;
194 position: absolute;
195 top: 0;
196 bottom: 0;
197 left: 0;
198 right: 0;
199 }
200</style>
201</head>
202<body>
203 <div class="view">
204 </div>
205 <script>
206 var linuxPerfData = "\\
207"""
208
Jamie Gennis1bf4a492012-03-13 18:07:36 -0700209html_suffix = """ dummy-0000 [000] 0.0: 0: trace_event_clock_sync: parent_ts=0.0\\n";
Jamie Gennis92791472012-03-05 17:33:58 -0800210 </script>
211</body>
212</html>
213"""
214
Jeff Brown595ae1e2012-05-22 14:52:13 -0700215compiled_css_tag = """<style type="text/css">%s</style>"""
216compiled_js_tag = """<script language="javascript">%s</script>"""
217
218linked_css_tag = """<link rel="stylesheet" href="%s"></link>"""
219linked_js_tag = """<script language="javascript" src="%s"></script>"""
220
Jamie Gennis92791472012-03-05 17:33:58 -0800221if __name__ == '__main__':
222 main()