blob: 3e71bbeeb3f0d20046c5a215d475fbaf114bd08c [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
Jamie Gennis92791472012-03-05 17:33:58 -080029def main():
30 parser = optparse.OptionParser()
31 parser.add_option('-o', dest='output_file', help='write HTML to FILE',
32 default='trace.html', metavar='FILE')
33 parser.add_option('-t', '--time', dest='trace_time', type='int',
34 help='trace for N seconds', metavar='N')
Jamie Gennis98ef97d2012-03-07 16:06:53 -080035 parser.add_option('-b', '--buf-size', dest='trace_buf_size', type='int',
36 help='use a trace buffer size of N KB', metavar='N')
Jeff Browna4d8b282012-05-22 18:56:09 -070037 parser.add_option('-d', '--disk', dest='trace_disk', default=False,
Jamie Gennis1f5d4e92012-06-07 16:59:27 -070038 action='store_true', help='trace disk I/O (requires root)')
Jamie Gennis98ef97d2012-03-07 16:06:53 -080039 parser.add_option('-f', '--cpu-freq', dest='trace_cpu_freq', default=False,
40 action='store_true', help='trace CPU frequency changes')
Jamie Gennis415e5d82012-05-07 18:00:11 -070041 parser.add_option('-i', '--cpu-idle', dest='trace_cpu_idle', default=False,
42 action='store_true', help='trace CPU idle events')
Jamie Gennis98ef97d2012-03-07 16:06:53 -080043 parser.add_option('-l', '--cpu-load', dest='trace_cpu_load', default=False,
44 action='store_true', help='trace CPU load')
Andy Stadler5bd161f2012-05-03 15:31:03 -070045 parser.add_option('-s', '--no-cpu-sched', dest='trace_cpu_sched', default=True,
46 action='store_false', help='inhibit tracing CPU ' +
47 'scheduler (allows longer trace times by reducing data ' +
48 'rate into buffer)')
Jamie Gennis92791472012-03-05 17:33:58 -080049 parser.add_option('-w', '--workqueue', dest='trace_workqueue', default=False,
Jamie Gennis1f5d4e92012-06-07 16:59:27 -070050 action='store_true', help='trace the kernel workqueues ' +
51 '(requires root)')
Jamie Gennis7e3783f2012-04-28 13:16:11 -070052 parser.add_option('--set-tags', dest='set_tags', action='store',
53 help='set the enabled trace tags and exit; set to a ' +
54 'comma separated list of: ' +
55 ', '.join(trace_tag_bits.iterkeys()))
Jeff Brown595ae1e2012-05-22 14:52:13 -070056 parser.add_option('--link-assets', dest='link_assets', default=False,
57 action='store_true', help='link to original CSS or JS resources '
58 'instead of embedding them')
Jamie Gennis92791472012-03-05 17:33:58 -080059 options, args = parser.parse_args()
60
Jamie Gennis7e3783f2012-04-28 13:16:11 -070061 if options.set_tags:
62 flags = 0
63 tags = options.set_tags.split(',')
64 for tag in tags:
65 try:
66 flags |= trace_tag_bits[tag]
67 except KeyError:
68 parser.error('unrecognized tag: %s\nknown tags are: %s' %
69 (tag, ', '.join(trace_tag_bits.iterkeys())))
Jamie Gennis81e9aa72012-05-09 13:57:58 -070070 atrace_args = ['adb', 'shell', 'setprop', 'debug.atrace.tags.enableflags', hex(flags)]
Jamie Gennis7e3783f2012-04-28 13:16:11 -070071 try:
72 subprocess.check_call(atrace_args)
73 except subprocess.CalledProcessError, e:
Jamie Gennis1f5d4e92012-06-07 16:59:27 -070074 print >> sys.stderr, 'unable to set tags: %s' % e
Jamie Gennis7e3783f2012-04-28 13:16:11 -070075 print '\nSet enabled tags to: %s\n' % ', '.join(tags)
76 print ('You will likely need to restart the Android framework for this to ' +
77 'take effect:\n\n adb shell stop\n adb shell ' +
78 'start\n')
79 return
80
Andy Stadler5bd161f2012-05-03 15:31:03 -070081 atrace_args = ['adb', 'shell', 'atrace', '-z']
Jeff Browna4d8b282012-05-22 18:56:09 -070082 if options.trace_disk:
83 atrace_args.append('-d')
Jamie Gennis98ef97d2012-03-07 16:06:53 -080084 if options.trace_cpu_freq:
85 atrace_args.append('-f')
Jamie Gennis415e5d82012-05-07 18:00:11 -070086 if options.trace_cpu_idle:
87 atrace_args.append('-i')
Jamie Gennis98ef97d2012-03-07 16:06:53 -080088 if options.trace_cpu_load:
89 atrace_args.append('-l')
Andy Stadler5bd161f2012-05-03 15:31:03 -070090 if options.trace_cpu_sched:
91 atrace_args.append('-s')
Jamie Gennis92791472012-03-05 17:33:58 -080092 if options.trace_workqueue:
93 atrace_args.append('-w')
94 if options.trace_time is not None:
95 if options.trace_time > 0:
96 atrace_args.extend(['-t', str(options.trace_time)])
97 else:
98 parser.error('the trace time must be a positive number')
Jamie Gennis98ef97d2012-03-07 16:06:53 -080099 if options.trace_buf_size is not None:
100 if options.trace_buf_size > 0:
101 atrace_args.extend(['-b', str(options.trace_buf_size)])
102 else:
103 parser.error('the trace buffer size must be a positive number')
Jamie Gennis92791472012-03-05 17:33:58 -0800104
Jamie Gennis4b56a2b2012-04-28 01:06:56 -0700105 script_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
Jeff Brown595ae1e2012-05-22 14:52:13 -0700106
107 if options.link_assets:
108 css = '\n'.join(linked_css_tag % (os.path.join(script_dir, f)) for f in config.css_in_files)
109 js = '\n'.join(linked_js_tag % (os.path.join(script_dir, f)) for f in config.js_in_files)
110 else:
111 css_filename = os.path.join(script_dir, config.css_out_file)
112 js_filename = os.path.join(script_dir, config.js_out_file)
113 css = compiled_css_tag % (open(css_filename).read())
114 js = compiled_js_tag % (open(js_filename).read())
Jamie Gennis4b56a2b2012-04-28 01:06:56 -0700115
Jamie Gennis92791472012-03-05 17:33:58 -0800116 html_filename = options.output_file
Jamie Gennis92791472012-03-05 17:33:58 -0800117
118 trace_started = False
Jamie Gennis1bf4a492012-03-13 18:07:36 -0700119 leftovers = ''
120 adb = subprocess.Popen(atrace_args, stdout=subprocess.PIPE,
Jamie Gennis7e3783f2012-04-28 13:16:11 -0700121 stderr=subprocess.PIPE)
Jamie Gennisbf3e6162012-04-28 19:16:49 -0700122 dec = zlib.decompressobj()
Jamie Gennis92791472012-03-05 17:33:58 -0800123 while True:
Jamie Gennis1bf4a492012-03-13 18:07:36 -0700124 ready = select.select([adb.stdout, adb.stderr], [], [adb.stdout, adb.stderr])
125 if adb.stderr in ready[0]:
126 err = os.read(adb.stderr.fileno(), 4096)
127 sys.stderr.write(err)
128 sys.stderr.flush()
129 if adb.stdout in ready[0]:
Jamie Gennisbf3e6162012-04-28 19:16:49 -0700130 out = leftovers + os.read(adb.stdout.fileno(), 4096)
131 out = out.replace('\r\n', '\n')
132 if out.endswith('\r'):
133 out = out[:-1]
134 leftovers = '\r'
135 else:
136 leftovers = ''
Jamie Gennis92791472012-03-05 17:33:58 -0800137 if not trace_started:
Jamie Gennis1bf4a492012-03-13 18:07:36 -0700138 lines = out.splitlines(True)
Jamie Gennisbf3e6162012-04-28 19:16:49 -0700139 out = ''
Jamie Gennis92791472012-03-05 17:33:58 -0800140 for i, line in enumerate(lines):
Jamie Gennisbf3e6162012-04-28 19:16:49 -0700141 if line == 'TRACE:\n':
Jamie Gennis1bf4a492012-03-13 18:07:36 -0700142 sys.stdout.write("downloading trace...")
Jamie Gennis92791472012-03-05 17:33:58 -0800143 sys.stdout.flush()
Jamie Gennis1bf4a492012-03-13 18:07:36 -0700144 out = ''.join(lines[i+1:])
Jamie Gennis1f5d4e92012-06-07 16:59:27 -0700145 html_file = open(html_filename, 'w')
146 html_file.write(html_prefix % (css, js))
Jamie Gennis92791472012-03-05 17:33:58 -0800147 trace_started = True
148 break
Jamie Gennis1bf4a492012-03-13 18:07:36 -0700149 elif 'TRACE:'.startswith(line) and i == len(lines) - 1:
Jamie Gennisbf3e6162012-04-28 19:16:49 -0700150 leftovers = line + leftovers
Jamie Gennis92791472012-03-05 17:33:58 -0800151 else:
Jamie Gennis1bf4a492012-03-13 18:07:36 -0700152 sys.stdout.write(line)
Jamie Gennis92791472012-03-05 17:33:58 -0800153 sys.stdout.flush()
Jamie Gennisbf3e6162012-04-28 19:16:49 -0700154 if len(out) > 0:
155 out = dec.decompress(out)
156 html_out = out.replace('\n', '\\n\\\n')
Jamie Gennis1bf4a492012-03-13 18:07:36 -0700157 if len(html_out) > 0:
158 html_file.write(html_out)
159 result = adb.poll()
Jamie Gennis92791472012-03-05 17:33:58 -0800160 if result is not None:
161 break
162 if result != 0:
Jamie Gennis1f5d4e92012-06-07 16:59:27 -0700163 print >> sys.stderr, 'adb returned error code %d' % result
164 elif trace_started:
Jamie Gennisbf3e6162012-04-28 19:16:49 -0700165 html_out = dec.flush().replace('\n', '\\n\\\n').replace('\r', '')
166 if len(html_out) > 0:
167 html_file.write(html_out)
Jamie Gennis92791472012-03-05 17:33:58 -0800168 html_file.write(html_suffix)
169 html_file.close()
Jamie Gennis1bf4a492012-03-13 18:07:36 -0700170 print " done\n\n wrote file://%s/%s\n" % (os.getcwd(), options.output_file)
Jamie Gennis1f5d4e92012-06-07 16:59:27 -0700171 else:
172 print >> sys.stderr, ('An error occured while capturing the trace. Output ' +
173 'file was not written.')
Jamie Gennis92791472012-03-05 17:33:58 -0800174
175html_prefix = """<!DOCTYPE HTML>
176<html>
177<head i18n-values="dir:textdirection;">
178<title>Android System Trace</title>
Jeff Brown595ae1e2012-05-22 14:52:13 -0700179%s
180%s
Jamie Gennis92791472012-03-05 17:33:58 -0800181<style>
182 .view {
183 overflow: hidden;
184 position: absolute;
185 top: 0;
186 bottom: 0;
187 left: 0;
188 right: 0;
189 }
190</style>
191</head>
192<body>
193 <div class="view">
194 </div>
195 <script>
196 var linuxPerfData = "\\
197"""
198
Jamie Gennis1bf4a492012-03-13 18:07:36 -0700199html_suffix = """ dummy-0000 [000] 0.0: 0: trace_event_clock_sync: parent_ts=0.0\\n";
Jamie Gennis92791472012-03-05 17:33:58 -0800200 </script>
201</body>
202</html>
203"""
204
Jeff Brown595ae1e2012-05-22 14:52:13 -0700205compiled_css_tag = """<style type="text/css">%s</style>"""
206compiled_js_tag = """<script language="javascript">%s</script>"""
207
208linked_css_tag = """<link rel="stylesheet" href="%s"></link>"""
209linked_js_tag = """<script language="javascript" src="%s"></script>"""
210
Jamie Gennis92791472012-03-05 17:33:58 -0800211if __name__ == '__main__':
212 main()