__init__.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """
  4. Machinery for generating tracing-related intermediate files.
  5. """
  6. __author__ = "Lluís Vilanova <vilanova@ac.upc.edu>"
  7. __copyright__ = "Copyright 2012-2014, Lluís Vilanova <vilanova@ac.upc.edu>"
  8. __license__ = "GPL version 2 or (at your option) any later version"
  9. __maintainer__ = "Stefan Hajnoczi"
  10. __email__ = "stefanha@linux.vnet.ibm.com"
  11. import re
  12. import sys
  13. import weakref
  14. import tracetool.format
  15. import tracetool.backend
  16. import tracetool.transform
  17. def error_write(*lines):
  18. """Write a set of error lines."""
  19. sys.stderr.writelines("\n".join(lines) + "\n")
  20. def error(*lines):
  21. """Write a set of error lines and exit."""
  22. error_write(*lines)
  23. sys.exit(1)
  24. def out(*lines, **kwargs):
  25. """Write a set of output lines.
  26. You can use kwargs as a shorthand for mapping variables when formating all
  27. the strings in lines.
  28. """
  29. lines = [ l % kwargs for l in lines ]
  30. sys.stdout.writelines("\n".join(lines) + "\n")
  31. class Arguments:
  32. """Event arguments description."""
  33. def __init__(self, args):
  34. """
  35. Parameters
  36. ----------
  37. args :
  38. List of (type, name) tuples.
  39. """
  40. self._args = args
  41. def copy(self):
  42. """Create a new copy."""
  43. return Arguments(list(self._args))
  44. @staticmethod
  45. def build(arg_str):
  46. """Build and Arguments instance from an argument string.
  47. Parameters
  48. ----------
  49. arg_str : str
  50. String describing the event arguments.
  51. """
  52. res = []
  53. for arg in arg_str.split(","):
  54. arg = arg.strip()
  55. if arg == 'void':
  56. continue
  57. if '*' in arg:
  58. arg_type, identifier = arg.rsplit('*', 1)
  59. arg_type += '*'
  60. identifier = identifier.strip()
  61. else:
  62. arg_type, identifier = arg.rsplit(None, 1)
  63. res.append((arg_type, identifier))
  64. return Arguments(res)
  65. def __iter__(self):
  66. """Iterate over the (type, name) pairs."""
  67. return iter(self._args)
  68. def __len__(self):
  69. """Number of arguments."""
  70. return len(self._args)
  71. def __str__(self):
  72. """String suitable for declaring function arguments."""
  73. if len(self._args) == 0:
  74. return "void"
  75. else:
  76. return ", ".join([ " ".join([t, n]) for t,n in self._args ])
  77. def __repr__(self):
  78. """Evaluable string representation for this object."""
  79. return "Arguments(\"%s\")" % str(self)
  80. def names(self):
  81. """List of argument names."""
  82. return [ name for _, name in self._args ]
  83. def types(self):
  84. """List of argument types."""
  85. return [ type_ for type_, _ in self._args ]
  86. def transform(self, *trans):
  87. """Return a new Arguments instance with transformed types.
  88. The types in the resulting Arguments instance are transformed according
  89. to tracetool.transform.transform_type.
  90. """
  91. res = []
  92. for type_, name in self._args:
  93. res.append((tracetool.transform.transform_type(type_, *trans),
  94. name))
  95. return Arguments(res)
  96. class Event(object):
  97. """Event description.
  98. Attributes
  99. ----------
  100. name : str
  101. The event name.
  102. fmt : str
  103. The event format string.
  104. properties : set(str)
  105. Properties of the event.
  106. args : Arguments
  107. The event arguments.
  108. """
  109. _CRE = re.compile("((?P<props>[\w\s]+)\s+)?"
  110. "(?P<name>\w+)"
  111. "\((?P<args>[^)]*)\)"
  112. "\s*"
  113. "(?:(?:(?P<fmt_trans>\".+),)?\s*(?P<fmt>\".+))?"
  114. "\s*")
  115. _VALID_PROPS = set(["disable", "tcg", "tcg-trans", "tcg-exec"])
  116. def __init__(self, name, props, fmt, args, orig=None):
  117. """
  118. Parameters
  119. ----------
  120. name : string
  121. Event name.
  122. props : list of str
  123. Property names.
  124. fmt : str, list of str
  125. Event printing format (or formats).
  126. args : Arguments
  127. Event arguments.
  128. orig : Event or None
  129. Original Event before transformation.
  130. """
  131. self.name = name
  132. self.properties = props
  133. self.fmt = fmt
  134. self.args = args
  135. if orig is None:
  136. self.original = weakref.ref(self)
  137. else:
  138. self.original = orig
  139. unknown_props = set(self.properties) - self._VALID_PROPS
  140. if len(unknown_props) > 0:
  141. raise ValueError("Unknown properties: %s"
  142. % ", ".join(unknown_props))
  143. assert isinstance(self.fmt, str) or len(self.fmt) == 2
  144. def copy(self):
  145. """Create a new copy."""
  146. return Event(self.name, list(self.properties), self.fmt,
  147. self.args.copy(), self)
  148. @staticmethod
  149. def build(line_str):
  150. """Build an Event instance from a string.
  151. Parameters
  152. ----------
  153. line_str : str
  154. Line describing the event.
  155. """
  156. m = Event._CRE.match(line_str)
  157. assert m is not None
  158. groups = m.groupdict('')
  159. name = groups["name"]
  160. props = groups["props"].split()
  161. fmt = groups["fmt"]
  162. fmt_trans = groups["fmt_trans"]
  163. if len(fmt_trans) > 0:
  164. fmt = [fmt_trans, fmt]
  165. args = Arguments.build(groups["args"])
  166. if "tcg-trans" in props:
  167. raise ValueError("Invalid property 'tcg-trans'")
  168. if "tcg-exec" in props:
  169. raise ValueError("Invalid property 'tcg-exec'")
  170. if "tcg" not in props and not isinstance(fmt, str):
  171. raise ValueError("Only events with 'tcg' property can have two formats")
  172. if "tcg" in props and isinstance(fmt, str):
  173. raise ValueError("Events with 'tcg' property must have two formats")
  174. return Event(name, props, fmt, args)
  175. def __repr__(self):
  176. """Evaluable string representation for this object."""
  177. if isinstance(self.fmt, str):
  178. fmt = self.fmt
  179. else:
  180. fmt = "%s, %s" % (self.fmt[0], self.fmt[1])
  181. return "Event('%s %s(%s) %s')" % (" ".join(self.properties),
  182. self.name,
  183. self.args,
  184. fmt)
  185. _FMT = re.compile("(%[\d\.]*\w+|%.*PRI\S+)")
  186. def formats(self):
  187. """List of argument print formats."""
  188. assert not isinstance(self.fmt, list)
  189. return self._FMT.findall(self.fmt)
  190. QEMU_TRACE = "trace_%(name)s"
  191. QEMU_TRACE_TCG = QEMU_TRACE + "_tcg"
  192. def api(self, fmt=None):
  193. if fmt is None:
  194. fmt = Event.QEMU_TRACE
  195. return fmt % {"name": self.name}
  196. def transform(self, *trans):
  197. """Return a new Event with transformed Arguments."""
  198. return Event(self.name,
  199. list(self.properties),
  200. self.fmt,
  201. self.args.transform(*trans),
  202. self)
  203. def _read_events(fobj):
  204. events = []
  205. for line in fobj:
  206. if not line.strip():
  207. continue
  208. if line.lstrip().startswith('#'):
  209. continue
  210. event = Event.build(line)
  211. # transform TCG-enabled events
  212. if "tcg" not in event.properties:
  213. events.append(event)
  214. else:
  215. event_trans = event.copy()
  216. event_trans.name += "_trans"
  217. event_trans.properties += ["tcg-trans"]
  218. event_trans.fmt = event.fmt[0]
  219. args_trans = []
  220. for atrans, aorig in zip(
  221. event_trans.transform(tracetool.transform.TCG_2_HOST).args,
  222. event.args):
  223. if atrans == aorig:
  224. args_trans.append(atrans)
  225. event_trans.args = Arguments(args_trans)
  226. event_trans = event_trans.copy()
  227. event_exec = event.copy()
  228. event_exec.name += "_exec"
  229. event_exec.properties += ["tcg-exec"]
  230. event_exec.fmt = event.fmt[1]
  231. event_exec = event_exec.transform(tracetool.transform.TCG_2_HOST)
  232. new_event = [event_trans, event_exec]
  233. event.event_trans, event.event_exec = new_event
  234. events.extend(new_event)
  235. return events
  236. class TracetoolError (Exception):
  237. """Exception for calls to generate."""
  238. pass
  239. def try_import(mod_name, attr_name=None, attr_default=None):
  240. """Try to import a module and get an attribute from it.
  241. Parameters
  242. ----------
  243. mod_name : str
  244. Module name.
  245. attr_name : str, optional
  246. Name of an attribute in the module.
  247. attr_default : optional
  248. Default value if the attribute does not exist in the module.
  249. Returns
  250. -------
  251. A pair indicating whether the module could be imported and the module or
  252. object or attribute value.
  253. """
  254. try:
  255. module = __import__(mod_name, globals(), locals(), ["__package__"])
  256. if attr_name is None:
  257. return True, module
  258. return True, getattr(module, str(attr_name), attr_default)
  259. except ImportError:
  260. return False, None
  261. def generate(fevents, format, backends,
  262. binary=None, probe_prefix=None):
  263. """Generate the output for the given (format, backends) pair.
  264. Parameters
  265. ----------
  266. fevents : file
  267. Event description file.
  268. format : str
  269. Output format name.
  270. backends : list
  271. Output backend names.
  272. binary : str or None
  273. See tracetool.backend.dtrace.BINARY.
  274. probe_prefix : str or None
  275. See tracetool.backend.dtrace.PROBEPREFIX.
  276. """
  277. # fix strange python error (UnboundLocalError tracetool)
  278. import tracetool
  279. format = str(format)
  280. if len(format) is 0:
  281. raise TracetoolError("format not set")
  282. if not tracetool.format.exists(format):
  283. raise TracetoolError("unknown format: %s" % format)
  284. if len(backends) is 0:
  285. raise TracetoolError("no backends specified")
  286. for backend in backends:
  287. if not tracetool.backend.exists(backend):
  288. raise TracetoolError("unknown backend: %s" % backend)
  289. backend = tracetool.backend.Wrapper(backends, format)
  290. import tracetool.backend.dtrace
  291. tracetool.backend.dtrace.BINARY = binary
  292. tracetool.backend.dtrace.PROBEPREFIX = probe_prefix
  293. events = _read_events(fevents)
  294. tracetool.format.generate(events, format, backend)