blob: 4ad34f90cd55a78b2a9c802161b390fdcd31ad95 [file] [log] [blame]
Stefan Hajnoczi26f72272010-05-22 19:24:51 +01001#!/usr/bin/env python
2#
3# Pretty-printer for simple trace backend binary trace files
4#
5# Copyright IBM, Corp. 2010
6#
7# This work is licensed under the terms of the GNU GPL, version 2. See
8# the COPYING file in the top-level directory.
9#
Philippe Mathieu-Daudé87e03312017-07-28 19:46:05 -030010# For help see docs/devel/tracing.txt
Stefan Hajnoczi26f72272010-05-22 19:24:51 +010011
Eduardo Habkostf03868b2018-06-08 09:29:43 -030012from __future__ import print_function
Stefan Hajnoczi26f72272010-05-22 19:24:51 +010013import struct
14import re
Stefan Hajnoczi59da6682011-02-22 13:59:41 +000015import inspect
Daniel P. Berranged1b97bc2016-10-04 14:35:56 +010016from tracetool import read_events, Event
Harsh Prateek Bora90a147a2012-07-18 15:16:00 +053017from tracetool.backend.simple import is_string
Stefan Hajnoczi26f72272010-05-22 19:24:51 +010018
19header_event_id = 0xffffffffffffffff
20header_magic = 0xf2b177cb0aa429b4
Stefan Hajnoczi0b5538c2011-02-26 18:38:39 +000021dropped_event_id = 0xfffffffffffffffe
Stefan Hajnoczi26f72272010-05-22 19:24:51 +010022
Daniel P. Berrange7f1b5882016-10-04 14:35:50 +010023record_type_mapping = 0
24record_type_event = 1
25
Harsh Prateek Bora90a147a2012-07-18 15:16:00 +053026log_header_fmt = '=QQQ'
27rec_header_fmt = '=QQII'
Stefan Hajnoczi26f72272010-05-22 19:24:51 +010028
Harsh Prateek Bora90a147a2012-07-18 15:16:00 +053029def read_header(fobj, hfmt):
30 '''Read a trace record header'''
31 hlen = struct.calcsize(hfmt)
32 hdr = fobj.read(hlen)
33 if len(hdr) != hlen:
Stefan Hajnoczi26f72272010-05-22 19:24:51 +010034 return None
Harsh Prateek Bora90a147a2012-07-18 15:16:00 +053035 return struct.unpack(hfmt, hdr)
Stefan Hajnoczi26f72272010-05-22 19:24:51 +010036
Daniel P. Berrange7f1b5882016-10-04 14:35:50 +010037def get_record(edict, idtoname, rechdr, fobj):
38 """Deserialize a trace record from a file into a tuple
39 (name, timestamp, pid, arg1, ..., arg6)."""
Harsh Prateek Bora90a147a2012-07-18 15:16:00 +053040 if rechdr is None:
41 return None
Harsh Prateek Bora90a147a2012-07-18 15:16:00 +053042 if rechdr[0] != dropped_event_id:
43 event_id = rechdr[0]
Daniel P. Berrange7f1b5882016-10-04 14:35:50 +010044 name = idtoname[event_id]
45 rec = (name, rechdr[1], rechdr[3])
Jose Ricardo Ziviani249e9f72017-05-29 13:30:04 -030046 try:
47 event = edict[name]
Eduardo Habkostbd228082018-06-08 09:29:51 -030048 except KeyError as e:
Jose Ricardo Ziviani249e9f72017-05-29 13:30:04 -030049 import sys
50 sys.stderr.write('%s event is logged but is not declared ' \
51 'in the trace events file, try using ' \
52 'trace-events-all instead.\n' % str(e))
53 sys.exit(1)
54
Harsh Prateek Bora90a147a2012-07-18 15:16:00 +053055 for type, name in event.args:
56 if is_string(type):
57 l = fobj.read(4)
58 (len,) = struct.unpack('=L', l)
59 s = fobj.read(len)
60 rec = rec + (s,)
61 else:
62 (value,) = struct.unpack('=Q', fobj.read(8))
63 rec = rec + (value,)
64 else:
Daniel P. Berrange7f1b5882016-10-04 14:35:50 +010065 rec = ("dropped", rechdr[1], rechdr[3])
Harsh Prateek Bora90a147a2012-07-18 15:16:00 +053066 (value,) = struct.unpack('=Q', fobj.read(8))
67 rec = rec + (value,)
68 return rec
69
Daniel P. Berrange7f1b5882016-10-04 14:35:50 +010070def get_mapping(fobj):
71 (event_id, ) = struct.unpack('=Q', fobj.read(8))
72 (len, ) = struct.unpack('=L', fobj.read(4))
Eduardo Habkost749c1d82018-06-19 16:45:49 -030073 name = fobj.read(len).decode()
Harsh Prateek Bora90a147a2012-07-18 15:16:00 +053074
Daniel P. Berrange7f1b5882016-10-04 14:35:50 +010075 return (event_id, name)
76
77def read_record(edict, idtoname, fobj):
Stefan Hajnoczi80ff35c2014-05-07 19:24:11 +020078 """Deserialize a trace record from a file into a tuple (event_num, timestamp, pid, arg1, ..., arg6)."""
Harsh Prateek Bora90a147a2012-07-18 15:16:00 +053079 rechdr = read_header(fobj, rec_header_fmt)
Daniel P. Berrange7f1b5882016-10-04 14:35:50 +010080 return get_record(edict, idtoname, rechdr, fobj)
Harsh Prateek Bora90a147a2012-07-18 15:16:00 +053081
Stefan Hajnoczi15327c32014-06-22 21:46:06 +080082def read_trace_header(fobj):
83 """Read and verify trace file header"""
Harsh Prateek Bora90a147a2012-07-18 15:16:00 +053084 header = read_header(fobj, log_header_fmt)
Daniel P. Berrange25d54652017-01-25 16:14:17 +000085 if header is None:
Harsh Prateek Bora90a147a2012-07-18 15:16:00 +053086 raise ValueError('Not a valid trace file!')
Daniel P. Berrange25d54652017-01-25 16:14:17 +000087 if header[0] != header_event_id:
88 raise ValueError('Not a valid trace file, header id %d != %d' %
89 (header[0], header_event_id))
90 if header[1] != header_magic:
91 raise ValueError('Not a valid trace file, header magic %d != %d' %
92 (header[1], header_magic))
Harsh Prateek Bora90a147a2012-07-18 15:16:00 +053093
94 log_version = header[2]
Daniel P. Berrange7f1b5882016-10-04 14:35:50 +010095 if log_version not in [0, 2, 3, 4]:
Lluís Vilanovaef0bd3b2014-02-23 20:37:35 +010096 raise ValueError('Unknown version of tracelog format!')
Daniel P. Berrange7f1b5882016-10-04 14:35:50 +010097 if log_version != 4:
Lluís Vilanovaef0bd3b2014-02-23 20:37:35 +010098 raise ValueError('Log format %d not supported with this QEMU release!'
99 % log_version)
Stefan Hajnoczi26f72272010-05-22 19:24:51 +0100100
Stefan Hajnoczi840d8352017-08-15 09:44:30 +0100101def read_trace_records(edict, idtoname, fobj):
102 """Deserialize trace records from a file, yielding record tuples (event_num, timestamp, pid, arg1, ..., arg6).
103
104 Note that `idtoname` is modified if the file contains mapping records.
105
106 Args:
107 edict (str -> Event): events dict, indexed by name
108 idtoname (int -> str): event names dict, indexed by event ID
109 fobj (file): input file
110
111 """
Stefan Hajnoczi26f72272010-05-22 19:24:51 +0100112 while True:
Daniel P. Berrange7f1b5882016-10-04 14:35:50 +0100113 t = fobj.read(8)
114 if len(t) == 0:
Stefan Hajnoczi26f72272010-05-22 19:24:51 +0100115 break
116
Daniel P. Berrange7f1b5882016-10-04 14:35:50 +0100117 (rectype, ) = struct.unpack('=Q', t)
118 if rectype == record_type_mapping:
119 event_id, name = get_mapping(fobj)
120 idtoname[event_id] = name
121 else:
122 rec = read_record(edict, idtoname, fobj)
123
124 yield rec
Stefan Hajnoczi26f72272010-05-22 19:24:51 +0100125
Stefan Hajnoczi59da6682011-02-22 13:59:41 +0000126class Analyzer(object):
127 """A trace file analyzer which processes trace records.
Stefan Hajnoczi26f72272010-05-22 19:24:51 +0100128
Stefan Hajnoczi59da6682011-02-22 13:59:41 +0000129 An analyzer can be passed to run() or process(). The begin() method is
130 invoked, then each trace record is processed, and finally the end() method
131 is invoked.
Stefan Hajnoczi26f72272010-05-22 19:24:51 +0100132
Stefan Hajnoczi59da6682011-02-22 13:59:41 +0000133 If a method matching a trace event name exists, it is invoked to process
Stefan Hajnoczi659370f2017-04-11 10:56:54 +0100134 that trace record. Otherwise the catchall() method is invoked.
135
136 Example:
137 The following method handles the runstate_set(int new_state) trace event::
138
139 def runstate_set(self, new_state):
140 ...
141
142 The method can also take a timestamp argument before the trace event
143 arguments::
144
145 def runstate_set(self, timestamp, new_state):
146 ...
147
148 Timestamps have the uint64_t type and are in nanoseconds.
149
150 The pid can be included in addition to the timestamp and is useful when
151 dealing with traces from multiple processes::
152
153 def runstate_set(self, timestamp, pid, new_state):
154 ...
155 """
Stefan Hajnoczi26f72272010-05-22 19:24:51 +0100156
Stefan Hajnoczi59da6682011-02-22 13:59:41 +0000157 def begin(self):
158 """Called at the start of the trace."""
159 pass
Stefan Hajnoczi26f72272010-05-22 19:24:51 +0100160
Stefan Hajnoczi59da6682011-02-22 13:59:41 +0000161 def catchall(self, event, rec):
162 """Called if no specific method for processing a trace event has been found."""
163 pass
164
165 def end(self):
166 """Called at the end of the trace."""
167 pass
168
Stefan Hajnoczi15327c32014-06-22 21:46:06 +0800169def process(events, log, analyzer, read_header=True):
Stefan Hajnoczi59da6682011-02-22 13:59:41 +0000170 """Invoke an analyzer on each event in a log."""
171 if isinstance(events, str):
Daniel P. Berrangé86b5aac2018-03-06 15:46:50 +0000172 events = read_events(open(events, 'r'), events)
Stefan Hajnoczi59da6682011-02-22 13:59:41 +0000173 if isinstance(log, str):
174 log = open(log, 'rb')
175
Stefan Hajnoczi15327c32014-06-22 21:46:06 +0800176 if read_header:
177 read_trace_header(log)
178
Harsh Prateek Bora90a147a2012-07-18 15:16:00 +0530179 dropped_event = Event.build("Dropped_Event(uint64_t num_events_dropped)")
Daniel P. Berrange7f1b5882016-10-04 14:35:50 +0100180 edict = {"dropped": dropped_event}
Stefan Hajnoczi840d8352017-08-15 09:44:30 +0100181 idtoname = {dropped_event_id: "dropped"}
Harsh Prateek Bora90a147a2012-07-18 15:16:00 +0530182
Daniel P. Berrange7f1b5882016-10-04 14:35:50 +0100183 for event in events:
184 edict[event.name] = event
Harsh Prateek Bora90a147a2012-07-18 15:16:00 +0530185
Stefan Hajnoczi840d8352017-08-15 09:44:30 +0100186 # If there is no header assume event ID mapping matches events list
187 if not read_header:
188 for event_id, event in enumerate(events):
189 idtoname[event_id] = event.name
190
Stefan Hajnoczi59da6682011-02-22 13:59:41 +0000191 def build_fn(analyzer, event):
Harsh Prateek Bora90a147a2012-07-18 15:16:00 +0530192 if isinstance(event, str):
193 return analyzer.catchall
194
195 fn = getattr(analyzer, event.name, None)
Stefan Hajnoczi59da6682011-02-22 13:59:41 +0000196 if fn is None:
197 return analyzer.catchall
198
Harsh Prateek Bora90a147a2012-07-18 15:16:00 +0530199 event_argcount = len(event.args)
Stefan Hajnoczi59da6682011-02-22 13:59:41 +0000200 fn_argcount = len(inspect.getargspec(fn)[0]) - 1
201 if fn_argcount == event_argcount + 1:
202 # Include timestamp as first argument
Stefan Hajnoczie42860a2018-02-22 16:39:01 +0000203 return lambda _, rec: fn(*(rec[1:2] + rec[3:3 + event_argcount]))
Stefan Hajnoczi80ff35c2014-05-07 19:24:11 +0200204 elif fn_argcount == event_argcount + 2:
205 # Include timestamp and pid
206 return lambda _, rec: fn(*rec[1:3 + event_argcount])
Stefan Hajnoczi59da6682011-02-22 13:59:41 +0000207 else:
Stefan Hajnoczi80ff35c2014-05-07 19:24:11 +0200208 # Just arguments, no timestamp or pid
209 return lambda _, rec: fn(*rec[3:3 + event_argcount])
Stefan Hajnoczi59da6682011-02-22 13:59:41 +0000210
211 analyzer.begin()
212 fn_cache = {}
Stefan Hajnoczi840d8352017-08-15 09:44:30 +0100213 for rec in read_trace_records(edict, idtoname, log):
Stefan Hajnoczi59da6682011-02-22 13:59:41 +0000214 event_num = rec[0]
Harsh Prateek Bora90a147a2012-07-18 15:16:00 +0530215 event = edict[event_num]
Stefan Hajnoczi59da6682011-02-22 13:59:41 +0000216 if event_num not in fn_cache:
217 fn_cache[event_num] = build_fn(analyzer, event)
218 fn_cache[event_num](event, rec)
219 analyzer.end()
220
221def run(analyzer):
222 """Execute an analyzer on a trace file given on the command-line.
223
224 This function is useful as a driver for simple analysis scripts. More
225 advanced scripts will want to call process() instead."""
226 import sys
227
Stefan Hajnoczi15327c32014-06-22 21:46:06 +0800228 read_header = True
229 if len(sys.argv) == 4 and sys.argv[1] == '--no-header':
230 read_header = False
231 del sys.argv[1]
232 elif len(sys.argv) != 3:
233 sys.stderr.write('usage: %s [--no-header] <trace-events> ' \
234 '<trace-file>\n' % sys.argv[0])
Stefan Hajnoczi59da6682011-02-22 13:59:41 +0000235 sys.exit(1)
236
Daniel P. Berrangé86b5aac2018-03-06 15:46:50 +0000237 events = read_events(open(sys.argv[1], 'r'), sys.argv[1])
Stefan Hajnoczi15327c32014-06-22 21:46:06 +0800238 process(events, sys.argv[2], analyzer, read_header=read_header)
Stefan Hajnoczi59da6682011-02-22 13:59:41 +0000239
240if __name__ == '__main__':
241 class Formatter(Analyzer):
242 def __init__(self):
243 self.last_timestamp = None
244
245 def catchall(self, event, rec):
246 timestamp = rec[1]
247 if self.last_timestamp is None:
248 self.last_timestamp = timestamp
249 delta_ns = timestamp - self.last_timestamp
250 self.last_timestamp = timestamp
251
Stefan Hajnoczi80ff35c2014-05-07 19:24:11 +0200252 fields = [event.name, '%0.3f' % (delta_ns / 1000.0),
253 'pid=%d' % rec[2]]
254 i = 3
Harsh Prateek Bora90a147a2012-07-18 15:16:00 +0530255 for type, name in event.args:
256 if is_string(type):
Stefan Hajnoczi80ff35c2014-05-07 19:24:11 +0200257 fields.append('%s=%s' % (name, rec[i]))
Harsh Prateek Bora90a147a2012-07-18 15:16:00 +0530258 else:
Stefan Hajnoczi80ff35c2014-05-07 19:24:11 +0200259 fields.append('%s=0x%x' % (name, rec[i]))
Harsh Prateek Bora90a147a2012-07-18 15:16:00 +0530260 i += 1
Eduardo Habkostf03868b2018-06-08 09:29:43 -0300261 print(' '.join(fields))
Stefan Hajnoczi59da6682011-02-22 13:59:41 +0000262
263 run(Formatter())