blob: 09511f624d1779413b7946d28bbe466ced356e06 [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
Mads Ynddalf7bd4f02023-09-26 12:34:25 +020012import sys
Stefan Hajnoczi26f72272010-05-22 19:24:51 +010013import struct
Stefan Hajnoczi59da6682011-02-22 13:59:41 +000014import inspect
Daniel P. Berranged1b97bc2016-10-04 14:35:56 +010015from tracetool import read_events, Event
Harsh Prateek Bora90a147a2012-07-18 15:16:00 +053016from tracetool.backend.simple import is_string
Stefan Hajnoczi26f72272010-05-22 19:24:51 +010017
Mads Ynddal2c109f22023-09-26 12:34:23 +020018__all__ = ['Analyzer', 'process', 'run']
19
Mads Ynddal8405ec62023-09-26 12:34:24 +020020# This is the binary format that the QEMU "simple" trace backend
21# emits. There is no specification documentation because the format is
22# not guaranteed to be stable. Trace files must be parsed with the
23# same trace-events-all file and the same simpletrace.py file that
24# QEMU was built with.
Stefan Hajnoczi26f72272010-05-22 19:24:51 +010025header_event_id = 0xffffffffffffffff
26header_magic = 0xf2b177cb0aa429b4
Stefan Hajnoczi0b5538c2011-02-26 18:38:39 +000027dropped_event_id = 0xfffffffffffffffe
Stefan Hajnoczi26f72272010-05-22 19:24:51 +010028
Daniel P. Berrange7f1b5882016-10-04 14:35:50 +010029record_type_mapping = 0
30record_type_event = 1
31
Harsh Prateek Bora90a147a2012-07-18 15:16:00 +053032log_header_fmt = '=QQQ'
33rec_header_fmt = '=QQII'
Stefan Hajnoczi26f72272010-05-22 19:24:51 +010034
Harsh Prateek Bora90a147a2012-07-18 15:16:00 +053035def read_header(fobj, hfmt):
36 '''Read a trace record header'''
37 hlen = struct.calcsize(hfmt)
38 hdr = fobj.read(hlen)
39 if len(hdr) != hlen:
Stefan Hajnoczi26f72272010-05-22 19:24:51 +010040 return None
Harsh Prateek Bora90a147a2012-07-18 15:16:00 +053041 return struct.unpack(hfmt, hdr)
Stefan Hajnoczi26f72272010-05-22 19:24:51 +010042
Mads Ynddal3b71b612023-09-26 12:34:26 +020043def get_record(event_mapping, event_id_to_name, rechdr, fobj):
Daniel P. Berrange7f1b5882016-10-04 14:35:50 +010044 """Deserialize a trace record from a file into a tuple
45 (name, timestamp, pid, arg1, ..., arg6)."""
Harsh Prateek Bora90a147a2012-07-18 15:16:00 +053046 if rechdr is None:
47 return None
Harsh Prateek Bora90a147a2012-07-18 15:16:00 +053048 if rechdr[0] != dropped_event_id:
49 event_id = rechdr[0]
Mads Ynddal3b71b612023-09-26 12:34:26 +020050 name = event_id_to_name[event_id]
Daniel P. Berrange7f1b5882016-10-04 14:35:50 +010051 rec = (name, rechdr[1], rechdr[3])
Jose Ricardo Ziviani249e9f72017-05-29 13:30:04 -030052 try:
Mads Ynddal3b71b612023-09-26 12:34:26 +020053 event = event_mapping[name]
Eduardo Habkostbd228082018-06-08 09:29:51 -030054 except KeyError as e:
Jose Ricardo Ziviani249e9f72017-05-29 13:30:04 -030055 sys.stderr.write('%s event is logged but is not declared ' \
56 'in the trace events file, try using ' \
57 'trace-events-all instead.\n' % str(e))
58 sys.exit(1)
59
Harsh Prateek Bora90a147a2012-07-18 15:16:00 +053060 for type, name in event.args:
61 if is_string(type):
62 l = fobj.read(4)
63 (len,) = struct.unpack('=L', l)
64 s = fobj.read(len)
65 rec = rec + (s,)
66 else:
67 (value,) = struct.unpack('=Q', fobj.read(8))
68 rec = rec + (value,)
69 else:
Daniel P. Berrange7f1b5882016-10-04 14:35:50 +010070 rec = ("dropped", rechdr[1], rechdr[3])
Harsh Prateek Bora90a147a2012-07-18 15:16:00 +053071 (value,) = struct.unpack('=Q', fobj.read(8))
72 rec = rec + (value,)
73 return rec
74
Daniel P. Berrange7f1b5882016-10-04 14:35:50 +010075def get_mapping(fobj):
76 (event_id, ) = struct.unpack('=Q', fobj.read(8))
77 (len, ) = struct.unpack('=L', fobj.read(4))
Eduardo Habkost749c1d82018-06-19 16:45:49 -030078 name = fobj.read(len).decode()
Harsh Prateek Bora90a147a2012-07-18 15:16:00 +053079
Daniel P. Berrange7f1b5882016-10-04 14:35:50 +010080 return (event_id, name)
81
Mads Ynddal3b71b612023-09-26 12:34:26 +020082def read_record(event_mapping, event_id_to_name, fobj):
Stefan Hajnoczi80ff35c2014-05-07 19:24:11 +020083 """Deserialize a trace record from a file into a tuple (event_num, timestamp, pid, arg1, ..., arg6)."""
Harsh Prateek Bora90a147a2012-07-18 15:16:00 +053084 rechdr = read_header(fobj, rec_header_fmt)
Mads Ynddal3b71b612023-09-26 12:34:26 +020085 return get_record(event_mapping, event_id_to_name, rechdr, fobj)
Harsh Prateek Bora90a147a2012-07-18 15:16:00 +053086
Stefan Hajnoczi15327c32014-06-22 21:46:06 +080087def read_trace_header(fobj):
88 """Read and verify trace file header"""
Harsh Prateek Bora90a147a2012-07-18 15:16:00 +053089 header = read_header(fobj, log_header_fmt)
Daniel P. Berrange25d54652017-01-25 16:14:17 +000090 if header is None:
Harsh Prateek Bora90a147a2012-07-18 15:16:00 +053091 raise ValueError('Not a valid trace file!')
Daniel P. Berrange25d54652017-01-25 16:14:17 +000092 if header[0] != header_event_id:
93 raise ValueError('Not a valid trace file, header id %d != %d' %
94 (header[0], header_event_id))
95 if header[1] != header_magic:
96 raise ValueError('Not a valid trace file, header magic %d != %d' %
97 (header[1], header_magic))
Harsh Prateek Bora90a147a2012-07-18 15:16:00 +053098
99 log_version = header[2]
Daniel P. Berrange7f1b5882016-10-04 14:35:50 +0100100 if log_version not in [0, 2, 3, 4]:
Lluís Vilanovaef0bd3b2014-02-23 20:37:35 +0100101 raise ValueError('Unknown version of tracelog format!')
Daniel P. Berrange7f1b5882016-10-04 14:35:50 +0100102 if log_version != 4:
Lluís Vilanovaef0bd3b2014-02-23 20:37:35 +0100103 raise ValueError('Log format %d not supported with this QEMU release!'
104 % log_version)
Stefan Hajnoczi26f72272010-05-22 19:24:51 +0100105
Mads Ynddal3b71b612023-09-26 12:34:26 +0200106def read_trace_records(event_mapping, event_id_to_name, fobj):
Stefan Hajnoczi840d8352017-08-15 09:44:30 +0100107 """Deserialize trace records from a file, yielding record tuples (event_num, timestamp, pid, arg1, ..., arg6).
108
Mads Ynddal3b71b612023-09-26 12:34:26 +0200109 Note that `event_id_to_name` is modified if the file contains mapping records.
Stefan Hajnoczi840d8352017-08-15 09:44:30 +0100110
111 Args:
Mads Ynddal3b71b612023-09-26 12:34:26 +0200112 event_mapping (str -> Event): events dict, indexed by name
113 event_id_to_name (int -> str): event names dict, indexed by event ID
Stefan Hajnoczi840d8352017-08-15 09:44:30 +0100114 fobj (file): input file
115
116 """
Stefan Hajnoczi26f72272010-05-22 19:24:51 +0100117 while True:
Daniel P. Berrange7f1b5882016-10-04 14:35:50 +0100118 t = fobj.read(8)
119 if len(t) == 0:
Stefan Hajnoczi26f72272010-05-22 19:24:51 +0100120 break
121
Daniel P. Berrange7f1b5882016-10-04 14:35:50 +0100122 (rectype, ) = struct.unpack('=Q', t)
123 if rectype == record_type_mapping:
124 event_id, name = get_mapping(fobj)
Mads Ynddal3b71b612023-09-26 12:34:26 +0200125 event_id_to_name[event_id] = name
Daniel P. Berrange7f1b5882016-10-04 14:35:50 +0100126 else:
Mads Ynddal3b71b612023-09-26 12:34:26 +0200127 rec = read_record(event_mapping, event_id_to_name, fobj)
Daniel P. Berrange7f1b5882016-10-04 14:35:50 +0100128
129 yield rec
Stefan Hajnoczi26f72272010-05-22 19:24:51 +0100130
Stefan Hajnoczi59da6682011-02-22 13:59:41 +0000131class Analyzer(object):
132 """A trace file analyzer which processes trace records.
Stefan Hajnoczi26f72272010-05-22 19:24:51 +0100133
Stefan Hajnoczi59da6682011-02-22 13:59:41 +0000134 An analyzer can be passed to run() or process(). The begin() method is
135 invoked, then each trace record is processed, and finally the end() method
136 is invoked.
Stefan Hajnoczi26f72272010-05-22 19:24:51 +0100137
Stefan Hajnoczi59da6682011-02-22 13:59:41 +0000138 If a method matching a trace event name exists, it is invoked to process
Stefan Hajnoczi659370f2017-04-11 10:56:54 +0100139 that trace record. Otherwise the catchall() method is invoked.
140
141 Example:
142 The following method handles the runstate_set(int new_state) trace event::
143
144 def runstate_set(self, new_state):
145 ...
146
147 The method can also take a timestamp argument before the trace event
148 arguments::
149
150 def runstate_set(self, timestamp, new_state):
151 ...
152
153 Timestamps have the uint64_t type and are in nanoseconds.
154
155 The pid can be included in addition to the timestamp and is useful when
156 dealing with traces from multiple processes::
157
158 def runstate_set(self, timestamp, pid, new_state):
159 ...
160 """
Stefan Hajnoczi26f72272010-05-22 19:24:51 +0100161
Stefan Hajnoczi59da6682011-02-22 13:59:41 +0000162 def begin(self):
163 """Called at the start of the trace."""
164 pass
Stefan Hajnoczi26f72272010-05-22 19:24:51 +0100165
Stefan Hajnoczi59da6682011-02-22 13:59:41 +0000166 def catchall(self, event, rec):
167 """Called if no specific method for processing a trace event has been found."""
168 pass
169
170 def end(self):
171 """Called at the end of the trace."""
172 pass
173
Stefan Hajnoczi15327c32014-06-22 21:46:06 +0800174def process(events, log, analyzer, read_header=True):
Mads Ynddalf7bd4f02023-09-26 12:34:25 +0200175 """Invoke an analyzer on each event in a log.
176 Args:
177 events (file-object or list or str): events list or file-like object or file path as str to read event data from
178 log (file-object or str): file-like object or file path as str to read log data from
179 analyzer (Analyzer): Instance of Analyzer to interpret the event data
180 read_header (bool, optional): Whether to read header data from the log data. Defaults to True.
181 """
182
Stefan Hajnoczi59da6682011-02-22 13:59:41 +0000183 if isinstance(events, str):
Mads Ynddalf7bd4f02023-09-26 12:34:25 +0200184 with open(events, 'r') as f:
185 events_list = read_events(f, events)
186 elif isinstance(events, list):
187 # Treat as a list of events already produced by tracetool.read_events
188 events_list = events
189 else:
190 # Treat as an already opened file-object
191 events_list = read_events(events, events.name)
192
193 close_log = False
Stefan Hajnoczi59da6682011-02-22 13:59:41 +0000194 if isinstance(log, str):
195 log = open(log, 'rb')
Mads Ynddalf7bd4f02023-09-26 12:34:25 +0200196 close_log = True
Stefan Hajnoczi59da6682011-02-22 13:59:41 +0000197
Stefan Hajnoczi15327c32014-06-22 21:46:06 +0800198 if read_header:
199 read_trace_header(log)
200
Volker Rümelinc6e93c92021-01-31 18:34:15 +0100201 frameinfo = inspect.getframeinfo(inspect.currentframe())
202 dropped_event = Event.build("Dropped_Event(uint64_t num_events_dropped)",
203 frameinfo.lineno + 1, frameinfo.filename)
Mads Ynddal3b71b612023-09-26 12:34:26 +0200204 event_mapping = {"dropped": dropped_event}
205 event_id_to_name = {dropped_event_id: "dropped"}
Harsh Prateek Bora90a147a2012-07-18 15:16:00 +0530206
Mads Ynddalf7bd4f02023-09-26 12:34:25 +0200207 for event in events_list:
Mads Ynddal3b71b612023-09-26 12:34:26 +0200208 event_mapping[event.name] = event
Harsh Prateek Bora90a147a2012-07-18 15:16:00 +0530209
Stefan Hajnoczi840d8352017-08-15 09:44:30 +0100210 # If there is no header assume event ID mapping matches events list
211 if not read_header:
Mads Ynddalf7bd4f02023-09-26 12:34:25 +0200212 for event_id, event in enumerate(events_list):
Mads Ynddal3b71b612023-09-26 12:34:26 +0200213 event_id_to_name[event_id] = event.name
Stefan Hajnoczi840d8352017-08-15 09:44:30 +0100214
Stefan Hajnoczi59da6682011-02-22 13:59:41 +0000215 def build_fn(analyzer, event):
Harsh Prateek Bora90a147a2012-07-18 15:16:00 +0530216 if isinstance(event, str):
217 return analyzer.catchall
218
219 fn = getattr(analyzer, event.name, None)
Stefan Hajnoczi59da6682011-02-22 13:59:41 +0000220 if fn is None:
221 return analyzer.catchall
222
Harsh Prateek Bora90a147a2012-07-18 15:16:00 +0530223 event_argcount = len(event.args)
Stefan Hajnoczi59da6682011-02-22 13:59:41 +0000224 fn_argcount = len(inspect.getargspec(fn)[0]) - 1
225 if fn_argcount == event_argcount + 1:
226 # Include timestamp as first argument
Stefan Hajnoczie42860a2018-02-22 16:39:01 +0000227 return lambda _, rec: fn(*(rec[1:2] + rec[3:3 + event_argcount]))
Stefan Hajnoczi80ff35c2014-05-07 19:24:11 +0200228 elif fn_argcount == event_argcount + 2:
229 # Include timestamp and pid
230 return lambda _, rec: fn(*rec[1:3 + event_argcount])
Stefan Hajnoczi59da6682011-02-22 13:59:41 +0000231 else:
Stefan Hajnoczi80ff35c2014-05-07 19:24:11 +0200232 # Just arguments, no timestamp or pid
233 return lambda _, rec: fn(*rec[3:3 + event_argcount])
Stefan Hajnoczi59da6682011-02-22 13:59:41 +0000234
235 analyzer.begin()
236 fn_cache = {}
Mads Ynddal3b71b612023-09-26 12:34:26 +0200237 for rec in read_trace_records(event_mapping, event_id_to_name, log):
Stefan Hajnoczi59da6682011-02-22 13:59:41 +0000238 event_num = rec[0]
Mads Ynddal3b71b612023-09-26 12:34:26 +0200239 event = event_mapping[event_num]
Stefan Hajnoczi59da6682011-02-22 13:59:41 +0000240 if event_num not in fn_cache:
241 fn_cache[event_num] = build_fn(analyzer, event)
242 fn_cache[event_num](event, rec)
243 analyzer.end()
244
Mads Ynddalf7bd4f02023-09-26 12:34:25 +0200245 if close_log:
246 log.close()
247
Stefan Hajnoczi59da6682011-02-22 13:59:41 +0000248def run(analyzer):
249 """Execute an analyzer on a trace file given on the command-line.
250
251 This function is useful as a driver for simple analysis scripts. More
252 advanced scripts will want to call process() instead."""
Stefan Hajnoczi59da6682011-02-22 13:59:41 +0000253
Mads Ynddalf7bd4f02023-09-26 12:34:25 +0200254 try:
255 # NOTE: See built-in `argparse` module for a more robust cli interface
256 *no_header, trace_event_path, trace_file_path = sys.argv[1:]
257 assert no_header == [] or no_header == ['--no-header'], 'Invalid no-header argument'
258 except (AssertionError, ValueError):
259 sys.stderr.write(f'usage: {sys.argv[0]} [--no-header] <trace-events> <trace-file>\n')
Stefan Hajnoczi59da6682011-02-22 13:59:41 +0000260 sys.exit(1)
261
Mads Ynddalf7bd4f02023-09-26 12:34:25 +0200262 with open(trace_event_path, 'r') as events_fobj, open(trace_file_path, 'rb') as log_fobj:
263 process(events_fobj, log_fobj, analyzer, read_header=not no_header)
Stefan Hajnoczi59da6682011-02-22 13:59:41 +0000264
265if __name__ == '__main__':
266 class Formatter(Analyzer):
267 def __init__(self):
268 self.last_timestamp = None
269
270 def catchall(self, event, rec):
271 timestamp = rec[1]
272 if self.last_timestamp is None:
273 self.last_timestamp = timestamp
274 delta_ns = timestamp - self.last_timestamp
275 self.last_timestamp = timestamp
276
Stefan Hajnoczi80ff35c2014-05-07 19:24:11 +0200277 fields = [event.name, '%0.3f' % (delta_ns / 1000.0),
278 'pid=%d' % rec[2]]
279 i = 3
Harsh Prateek Bora90a147a2012-07-18 15:16:00 +0530280 for type, name in event.args:
281 if is_string(type):
Stefan Hajnoczi80ff35c2014-05-07 19:24:11 +0200282 fields.append('%s=%s' % (name, rec[i]))
Harsh Prateek Bora90a147a2012-07-18 15:16:00 +0530283 else:
Stefan Hajnoczi80ff35c2014-05-07 19:24:11 +0200284 fields.append('%s=0x%x' % (name, rec[i]))
Harsh Prateek Bora90a147a2012-07-18 15:16:00 +0530285 i += 1
Eduardo Habkostf03868b2018-06-08 09:29:43 -0300286 print(' '.join(fields))
Stefan Hajnoczi59da6682011-02-22 13:59:41 +0000287
288 run(Formatter())