simpletrace.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. #!/usr/bin/env python3
  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. #
  10. # For help see docs/devel/tracing.rst
  11. import sys
  12. import struct
  13. import inspect
  14. from tracetool import read_events, Event
  15. from tracetool.backend.simple import is_string
  16. __all__ = ['Analyzer', 'process', 'run']
  17. # This is the binary format that the QEMU "simple" trace backend
  18. # emits. There is no specification documentation because the format is
  19. # not guaranteed to be stable. Trace files must be parsed with the
  20. # same trace-events-all file and the same simpletrace.py file that
  21. # QEMU was built with.
  22. header_event_id = 0xffffffffffffffff
  23. header_magic = 0xf2b177cb0aa429b4
  24. dropped_event_id = 0xfffffffffffffffe
  25. record_type_mapping = 0
  26. record_type_event = 1
  27. log_header_fmt = '=QQQ'
  28. rec_header_fmt = '=QQII'
  29. rec_header_fmt_len = struct.calcsize(rec_header_fmt)
  30. class SimpleException(Exception):
  31. pass
  32. def read_header(fobj, hfmt):
  33. '''Read a trace record header'''
  34. hlen = struct.calcsize(hfmt)
  35. hdr = fobj.read(hlen)
  36. if len(hdr) != hlen:
  37. raise SimpleException('Error reading header. Wrong filetype provided?')
  38. return struct.unpack(hfmt, hdr)
  39. def get_mapping(fobj):
  40. (event_id, ) = struct.unpack('=Q', fobj.read(8))
  41. (len, ) = struct.unpack('=L', fobj.read(4))
  42. name = fobj.read(len).decode()
  43. return (event_id, name)
  44. def read_record(fobj):
  45. """Deserialize a trace record from a file into a tuple (event_num, timestamp, pid, args)."""
  46. event_id, timestamp_ns, record_length, record_pid = read_header(fobj, rec_header_fmt)
  47. args_payload = fobj.read(record_length - rec_header_fmt_len)
  48. return (event_id, timestamp_ns, record_pid, args_payload)
  49. def read_trace_header(fobj):
  50. """Read and verify trace file header"""
  51. _header_event_id, _header_magic, log_version = read_header(fobj, log_header_fmt)
  52. if _header_event_id != header_event_id:
  53. raise ValueError(f'Not a valid trace file, header id {_header_event_id} != {header_event_id}')
  54. if _header_magic != header_magic:
  55. raise ValueError(f'Not a valid trace file, header magic {_header_magic} != {header_magic}')
  56. if log_version not in [0, 2, 3, 4]:
  57. raise ValueError(f'Unknown version {log_version} of tracelog format!')
  58. if log_version != 4:
  59. raise ValueError(f'Log format {log_version} not supported with this QEMU release!')
  60. def read_trace_records(events, fobj, read_header):
  61. """Deserialize trace records from a file, yielding record tuples (event, event_num, timestamp, pid, arg1, ..., arg6).
  62. Args:
  63. event_mapping (str -> Event): events dict, indexed by name
  64. fobj (file): input file
  65. read_header (bool): whether headers were read from fobj
  66. """
  67. frameinfo = inspect.getframeinfo(inspect.currentframe())
  68. dropped_event = Event.build("Dropped_Event(uint64_t num_events_dropped)",
  69. frameinfo.lineno + 1, frameinfo.filename)
  70. event_mapping = {e.name: e for e in events}
  71. event_mapping["dropped"] = dropped_event
  72. event_id_to_name = {dropped_event_id: "dropped"}
  73. # If there is no header assume event ID mapping matches events list
  74. if not read_header:
  75. for event_id, event in enumerate(events):
  76. event_id_to_name[event_id] = event.name
  77. while True:
  78. t = fobj.read(8)
  79. if len(t) == 0:
  80. break
  81. (rectype, ) = struct.unpack('=Q', t)
  82. if rectype == record_type_mapping:
  83. event_id, event_name = get_mapping(fobj)
  84. event_id_to_name[event_id] = event_name
  85. else:
  86. event_id, timestamp_ns, pid, args_payload = read_record(fobj)
  87. event_name = event_id_to_name[event_id]
  88. try:
  89. event = event_mapping[event_name]
  90. except KeyError as e:
  91. raise SimpleException(
  92. f'{e} event is logged but is not declared in the trace events'
  93. 'file, try using trace-events-all instead.'
  94. )
  95. offset = 0
  96. args = []
  97. for type, _ in event.args:
  98. if is_string(type):
  99. (length,) = struct.unpack_from('=L', args_payload, offset=offset)
  100. offset += 4
  101. s = args_payload[offset:offset+length]
  102. offset += length
  103. args.append(s)
  104. else:
  105. (value,) = struct.unpack_from('=Q', args_payload, offset=offset)
  106. offset += 8
  107. args.append(value)
  108. yield (event_mapping[event_name], event_name, timestamp_ns, pid) + tuple(args)
  109. class Analyzer:
  110. """A trace file analyzer which processes trace records.
  111. An analyzer can be passed to run() or process(). The begin() method is
  112. invoked, then each trace record is processed, and finally the end() method
  113. is invoked. When Analyzer is used as a context-manager (using the `with`
  114. statement), begin() and end() are called automatically.
  115. If a method matching a trace event name exists, it is invoked to process
  116. that trace record. Otherwise the catchall() method is invoked.
  117. Example:
  118. The following method handles the runstate_set(int new_state) trace event::
  119. def runstate_set(self, new_state):
  120. ...
  121. The method can also take a timestamp argument before the trace event
  122. arguments::
  123. def runstate_set(self, timestamp, new_state):
  124. ...
  125. Timestamps have the uint64_t type and are in nanoseconds.
  126. The pid can be included in addition to the timestamp and is useful when
  127. dealing with traces from multiple processes::
  128. def runstate_set(self, timestamp, pid, new_state):
  129. ...
  130. """
  131. def begin(self):
  132. """Called at the start of the trace."""
  133. pass
  134. def catchall(self, event, rec):
  135. """Called if no specific method for processing a trace event has been found."""
  136. pass
  137. def end(self):
  138. """Called at the end of the trace."""
  139. pass
  140. def __enter__(self):
  141. self.begin()
  142. return self
  143. def __exit__(self, exc_type, exc_val, exc_tb):
  144. if exc_type is None:
  145. self.end()
  146. return False
  147. def process(events, log, analyzer, read_header=True):
  148. """Invoke an analyzer on each event in a log.
  149. Args:
  150. events (file-object or list or str): events list or file-like object or file path as str to read event data from
  151. log (file-object or str): file-like object or file path as str to read log data from
  152. analyzer (Analyzer): Instance of Analyzer to interpret the event data
  153. read_header (bool, optional): Whether to read header data from the log data. Defaults to True.
  154. """
  155. if isinstance(events, str):
  156. with open(events, 'r') as f:
  157. events_list = read_events(f, events)
  158. elif isinstance(events, list):
  159. # Treat as a list of events already produced by tracetool.read_events
  160. events_list = events
  161. else:
  162. # Treat as an already opened file-object
  163. events_list = read_events(events, events.name)
  164. close_log = False
  165. if isinstance(log, str):
  166. log = open(log, 'rb')
  167. close_log = True
  168. if read_header:
  169. read_trace_header(log)
  170. def build_fn(analyzer, event):
  171. if isinstance(event, str):
  172. return analyzer.catchall
  173. fn = getattr(analyzer, event.name, None)
  174. if fn is None:
  175. return analyzer.catchall
  176. event_argcount = len(event.args)
  177. fn_argcount = len(inspect.getfullargspec(fn)[0]) - 1
  178. if fn_argcount == event_argcount + 1:
  179. # Include timestamp as first argument
  180. return lambda _, rec: fn(*(rec[1:2] + rec[3:3 + event_argcount]))
  181. elif fn_argcount == event_argcount + 2:
  182. # Include timestamp and pid
  183. return lambda _, rec: fn(*rec[1:3 + event_argcount])
  184. else:
  185. # Just arguments, no timestamp or pid
  186. return lambda _, rec: fn(*rec[3:3 + event_argcount])
  187. with analyzer:
  188. fn_cache = {}
  189. for event, event_id, timestamp_ns, record_pid, *rec_args in read_trace_records(events, log, read_header):
  190. if event_id not in fn_cache:
  191. fn_cache[event_id] = build_fn(analyzer, event)
  192. fn_cache[event_id](event, (event_id, timestamp_ns, record_pid, *rec_args))
  193. if close_log:
  194. log.close()
  195. def run(analyzer):
  196. """Execute an analyzer on a trace file given on the command-line.
  197. This function is useful as a driver for simple analysis scripts. More
  198. advanced scripts will want to call process() instead."""
  199. try:
  200. # NOTE: See built-in `argparse` module for a more robust cli interface
  201. *no_header, trace_event_path, trace_file_path = sys.argv[1:]
  202. assert no_header == [] or no_header == ['--no-header'], 'Invalid no-header argument'
  203. except (AssertionError, ValueError):
  204. raise SimpleException(f'usage: {sys.argv[0]} [--no-header] <trace-events> <trace-file>\n')
  205. with open(trace_event_path, 'r') as events_fobj, open(trace_file_path, 'rb') as log_fobj:
  206. process(events_fobj, log_fobj, analyzer, read_header=not no_header)
  207. if __name__ == '__main__':
  208. class Formatter(Analyzer):
  209. def __init__(self):
  210. self.last_timestamp = None
  211. def catchall(self, event, rec):
  212. timestamp = rec[1]
  213. if self.last_timestamp is None:
  214. self.last_timestamp = timestamp
  215. delta_ns = timestamp - self.last_timestamp
  216. self.last_timestamp = timestamp
  217. fields = [event.name, '%0.3f' % (delta_ns / 1000.0),
  218. 'pid=%d' % rec[2]]
  219. i = 3
  220. for type, name in event.args:
  221. if is_string(type):
  222. fields.append('%s=%s' % (name, rec[i]))
  223. else:
  224. fields.append('%s=0x%x' % (name, rec[i]))
  225. i += 1
  226. print(' '.join(fields))
  227. try:
  228. run(Formatter())
  229. except SimpleException as e:
  230. sys.stderr.write(str(e) + "\n")
  231. sys.exit(1)