blob: b221d9a2415ac3b7b30541dffa1b2447df9be1af [file] [log] [blame]
Philippe Mathieu-Daudé3d004a32020-01-30 17:32:25 +01001#!/usr/bin/env python3
Stefan Hajnoczi26f72272010-05-22 19:24:51 +01002#
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#
Stefano Garzarellad0fb9652021-05-17 17:16:58 +020010# For help see docs/devel/tracing.rst
Stefan Hajnoczi26f72272010-05-22 19:24:51 +010011
Stefan Hajnoczi26f72272010-05-22 19:24:51 +010012import struct
Stefan Hajnoczi59da6682011-02-22 13:59:41 +000013import inspect
Daniel P. Berranged1b97bc2016-10-04 14:35:56 +010014from tracetool import read_events, Event
Harsh Prateek Bora90a147a2012-07-18 15:16:00 +053015from tracetool.backend.simple import is_string
Stefan Hajnoczi26f72272010-05-22 19:24:51 +010016
Mads Ynddal2c109f22023-09-26 12:34:23 +020017__all__ = ['Analyzer', 'process', 'run']
18
Stefan Hajnoczi26f72272010-05-22 19:24:51 +010019header_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
Volker Rümelinc6e93c92021-01-31 18:34:15 +0100179 frameinfo = inspect.getframeinfo(inspect.currentframe())
180 dropped_event = Event.build("Dropped_Event(uint64_t num_events_dropped)",
181 frameinfo.lineno + 1, frameinfo.filename)
Daniel P. Berrange7f1b5882016-10-04 14:35:50 +0100182 edict = {"dropped": dropped_event}
Stefan Hajnoczi840d8352017-08-15 09:44:30 +0100183 idtoname = {dropped_event_id: "dropped"}
Harsh Prateek Bora90a147a2012-07-18 15:16:00 +0530184
Daniel P. Berrange7f1b5882016-10-04 14:35:50 +0100185 for event in events:
186 edict[event.name] = event
Harsh Prateek Bora90a147a2012-07-18 15:16:00 +0530187
Stefan Hajnoczi840d8352017-08-15 09:44:30 +0100188 # If there is no header assume event ID mapping matches events list
189 if not read_header:
190 for event_id, event in enumerate(events):
191 idtoname[event_id] = event.name
192
Stefan Hajnoczi59da6682011-02-22 13:59:41 +0000193 def build_fn(analyzer, event):
Harsh Prateek Bora90a147a2012-07-18 15:16:00 +0530194 if isinstance(event, str):
195 return analyzer.catchall
196
197 fn = getattr(analyzer, event.name, None)
Stefan Hajnoczi59da6682011-02-22 13:59:41 +0000198 if fn is None:
199 return analyzer.catchall
200
Harsh Prateek Bora90a147a2012-07-18 15:16:00 +0530201 event_argcount = len(event.args)
Stefan Hajnoczi59da6682011-02-22 13:59:41 +0000202 fn_argcount = len(inspect.getargspec(fn)[0]) - 1
203 if fn_argcount == event_argcount + 1:
204 # Include timestamp as first argument
Stefan Hajnoczie42860a2018-02-22 16:39:01 +0000205 return lambda _, rec: fn(*(rec[1:2] + rec[3:3 + event_argcount]))
Stefan Hajnoczi80ff35c2014-05-07 19:24:11 +0200206 elif fn_argcount == event_argcount + 2:
207 # Include timestamp and pid
208 return lambda _, rec: fn(*rec[1:3 + event_argcount])
Stefan Hajnoczi59da6682011-02-22 13:59:41 +0000209 else:
Stefan Hajnoczi80ff35c2014-05-07 19:24:11 +0200210 # Just arguments, no timestamp or pid
211 return lambda _, rec: fn(*rec[3:3 + event_argcount])
Stefan Hajnoczi59da6682011-02-22 13:59:41 +0000212
213 analyzer.begin()
214 fn_cache = {}
Stefan Hajnoczi840d8352017-08-15 09:44:30 +0100215 for rec in read_trace_records(edict, idtoname, log):
Stefan Hajnoczi59da6682011-02-22 13:59:41 +0000216 event_num = rec[0]
Harsh Prateek Bora90a147a2012-07-18 15:16:00 +0530217 event = edict[event_num]
Stefan Hajnoczi59da6682011-02-22 13:59:41 +0000218 if event_num not in fn_cache:
219 fn_cache[event_num] = build_fn(analyzer, event)
220 fn_cache[event_num](event, rec)
221 analyzer.end()
222
223def run(analyzer):
224 """Execute an analyzer on a trace file given on the command-line.
225
226 This function is useful as a driver for simple analysis scripts. More
227 advanced scripts will want to call process() instead."""
228 import sys
229
Stefan Hajnoczi15327c32014-06-22 21:46:06 +0800230 read_header = True
231 if len(sys.argv) == 4 and sys.argv[1] == '--no-header':
232 read_header = False
233 del sys.argv[1]
234 elif len(sys.argv) != 3:
235 sys.stderr.write('usage: %s [--no-header] <trace-events> ' \
236 '<trace-file>\n' % sys.argv[0])
Stefan Hajnoczi59da6682011-02-22 13:59:41 +0000237 sys.exit(1)
238
Daniel P. Berrangé86b5aac2018-03-06 15:46:50 +0000239 events = read_events(open(sys.argv[1], 'r'), sys.argv[1])
Stefan Hajnoczi15327c32014-06-22 21:46:06 +0800240 process(events, sys.argv[2], analyzer, read_header=read_header)
Stefan Hajnoczi59da6682011-02-22 13:59:41 +0000241
242if __name__ == '__main__':
243 class Formatter(Analyzer):
244 def __init__(self):
245 self.last_timestamp = None
246
247 def catchall(self, event, rec):
248 timestamp = rec[1]
249 if self.last_timestamp is None:
250 self.last_timestamp = timestamp
251 delta_ns = timestamp - self.last_timestamp
252 self.last_timestamp = timestamp
253
Stefan Hajnoczi80ff35c2014-05-07 19:24:11 +0200254 fields = [event.name, '%0.3f' % (delta_ns / 1000.0),
255 'pid=%d' % rec[2]]
256 i = 3
Harsh Prateek Bora90a147a2012-07-18 15:16:00 +0530257 for type, name in event.args:
258 if is_string(type):
Stefan Hajnoczi80ff35c2014-05-07 19:24:11 +0200259 fields.append('%s=%s' % (name, rec[i]))
Harsh Prateek Bora90a147a2012-07-18 15:16:00 +0530260 else:
Stefan Hajnoczi80ff35c2014-05-07 19:24:11 +0200261 fields.append('%s=0x%x' % (name, rec[i]))
Harsh Prateek Bora90a147a2012-07-18 15:16:00 +0530262 i += 1
Eduardo Habkostf03868b2018-06-08 09:29:43 -0300263 print(' '.join(fields))
Stefan Hajnoczi59da6682011-02-22 13:59:41 +0000264
265 run(Formatter())