__init__.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  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-2017, 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. # We only want to allow standard C types or fixed sized
  32. # integer types. We don't want QEMU specific types
  33. # as we can't assume trace backends can resolve all the
  34. # typedefs
  35. ALLOWED_TYPES = [
  36. "int",
  37. "long",
  38. "short",
  39. "char",
  40. "bool",
  41. "unsigned",
  42. "signed",
  43. "int8_t",
  44. "uint8_t",
  45. "int16_t",
  46. "uint16_t",
  47. "int32_t",
  48. "uint32_t",
  49. "int64_t",
  50. "uint64_t",
  51. "void",
  52. "size_t",
  53. "ssize_t",
  54. "uintptr_t",
  55. "ptrdiff_t",
  56. # Magic substitution is done by tracetool
  57. "TCGv",
  58. ]
  59. def validate_type(name):
  60. bits = name.split(" ")
  61. for bit in bits:
  62. bit = re.sub("\*", "", bit)
  63. if bit == "":
  64. continue
  65. if bit == "const":
  66. continue
  67. if bit not in ALLOWED_TYPES:
  68. raise ValueError("Argument type '%s' is not in whitelist. "
  69. "Only standard C types and fixed size integer "
  70. "types should be used. struct, union, and "
  71. "other complex pointer types should be "
  72. "declared as 'void *'" % name)
  73. class Arguments:
  74. """Event arguments description."""
  75. def __init__(self, args):
  76. """
  77. Parameters
  78. ----------
  79. args :
  80. List of (type, name) tuples or Arguments objects.
  81. """
  82. self._args = []
  83. for arg in args:
  84. if isinstance(arg, Arguments):
  85. self._args.extend(arg._args)
  86. else:
  87. self._args.append(arg)
  88. def copy(self):
  89. """Create a new copy."""
  90. return Arguments(list(self._args))
  91. @staticmethod
  92. def build(arg_str):
  93. """Build and Arguments instance from an argument string.
  94. Parameters
  95. ----------
  96. arg_str : str
  97. String describing the event arguments.
  98. """
  99. res = []
  100. for arg in arg_str.split(","):
  101. arg = arg.strip()
  102. if not arg:
  103. raise ValueError("Empty argument (did you forget to use 'void'?)")
  104. if arg == 'void':
  105. continue
  106. if '*' in arg:
  107. arg_type, identifier = arg.rsplit('*', 1)
  108. arg_type += '*'
  109. identifier = identifier.strip()
  110. else:
  111. arg_type, identifier = arg.rsplit(None, 1)
  112. validate_type(arg_type)
  113. res.append((arg_type, identifier))
  114. return Arguments(res)
  115. def __getitem__(self, index):
  116. if isinstance(index, slice):
  117. return Arguments(self._args[index])
  118. else:
  119. return self._args[index]
  120. def __iter__(self):
  121. """Iterate over the (type, name) pairs."""
  122. return iter(self._args)
  123. def __len__(self):
  124. """Number of arguments."""
  125. return len(self._args)
  126. def __str__(self):
  127. """String suitable for declaring function arguments."""
  128. if len(self._args) == 0:
  129. return "void"
  130. else:
  131. return ", ".join([ " ".join([t, n]) for t,n in self._args ])
  132. def __repr__(self):
  133. """Evaluable string representation for this object."""
  134. return "Arguments(\"%s\")" % str(self)
  135. def names(self):
  136. """List of argument names."""
  137. return [ name for _, name in self._args ]
  138. def types(self):
  139. """List of argument types."""
  140. return [ type_ for type_, _ in self._args ]
  141. def casted(self):
  142. """List of argument names casted to their type."""
  143. return ["(%s)%s" % (type_, name) for type_, name in self._args]
  144. def transform(self, *trans):
  145. """Return a new Arguments instance with transformed types.
  146. The types in the resulting Arguments instance are transformed according
  147. to tracetool.transform.transform_type.
  148. """
  149. res = []
  150. for type_, name in self._args:
  151. res.append((tracetool.transform.transform_type(type_, *trans),
  152. name))
  153. return Arguments(res)
  154. class Event(object):
  155. """Event description.
  156. Attributes
  157. ----------
  158. name : str
  159. The event name.
  160. fmt : str
  161. The event format string.
  162. properties : set(str)
  163. Properties of the event.
  164. args : Arguments
  165. The event arguments.
  166. """
  167. _CRE = re.compile("((?P<props>[\w\s]+)\s+)?"
  168. "(?P<name>\w+)"
  169. "\((?P<args>[^)]*)\)"
  170. "\s*"
  171. "(?:(?:(?P<fmt_trans>\".+),)?\s*(?P<fmt>\".+))?"
  172. "\s*")
  173. _VALID_PROPS = set(["disable", "tcg", "tcg-trans", "tcg-exec", "vcpu"])
  174. def __init__(self, name, props, fmt, args, orig=None,
  175. event_trans=None, event_exec=None):
  176. """
  177. Parameters
  178. ----------
  179. name : string
  180. Event name.
  181. props : list of str
  182. Property names.
  183. fmt : str, list of str
  184. Event printing format string(s).
  185. args : Arguments
  186. Event arguments.
  187. orig : Event or None
  188. Original Event before transformation/generation.
  189. event_trans : Event or None
  190. Generated translation-time event ("tcg" property).
  191. event_exec : Event or None
  192. Generated execution-time event ("tcg" property).
  193. """
  194. self.name = name
  195. self.properties = props
  196. self.fmt = fmt
  197. self.args = args
  198. self.event_trans = event_trans
  199. self.event_exec = event_exec
  200. if len(args) > 10:
  201. raise ValueError("Event '%s' has more than maximum permitted "
  202. "argument count" % name)
  203. if orig is None:
  204. self.original = weakref.ref(self)
  205. else:
  206. self.original = orig
  207. unknown_props = set(self.properties) - self._VALID_PROPS
  208. if len(unknown_props) > 0:
  209. raise ValueError("Unknown properties: %s"
  210. % ", ".join(unknown_props))
  211. assert isinstance(self.fmt, str) or len(self.fmt) == 2
  212. def copy(self):
  213. """Create a new copy."""
  214. return Event(self.name, list(self.properties), self.fmt,
  215. self.args.copy(), self, self.event_trans, self.event_exec)
  216. @staticmethod
  217. def build(line_str):
  218. """Build an Event instance from a string.
  219. Parameters
  220. ----------
  221. line_str : str
  222. Line describing the event.
  223. """
  224. m = Event._CRE.match(line_str)
  225. assert m is not None
  226. groups = m.groupdict('')
  227. name = groups["name"]
  228. props = groups["props"].split()
  229. fmt = groups["fmt"]
  230. fmt_trans = groups["fmt_trans"]
  231. if fmt.find("%m") != -1 or fmt_trans.find("%m") != -1:
  232. raise ValueError("Event format '%m' is forbidden, pass the error "
  233. "as an explicit trace argument")
  234. if fmt.endswith(r'\n"'):
  235. raise ValueError("Event format must not end with a newline "
  236. "character")
  237. if len(fmt_trans) > 0:
  238. fmt = [fmt_trans, fmt]
  239. args = Arguments.build(groups["args"])
  240. if "tcg-trans" in props:
  241. raise ValueError("Invalid property 'tcg-trans'")
  242. if "tcg-exec" in props:
  243. raise ValueError("Invalid property 'tcg-exec'")
  244. if "tcg" not in props and not isinstance(fmt, str):
  245. raise ValueError("Only events with 'tcg' property can have two format strings")
  246. if "tcg" in props and isinstance(fmt, str):
  247. raise ValueError("Events with 'tcg' property must have two format strings")
  248. event = Event(name, props, fmt, args)
  249. # add implicit arguments when using the 'vcpu' property
  250. import tracetool.vcpu
  251. event = tracetool.vcpu.transform_event(event)
  252. return event
  253. def __repr__(self):
  254. """Evaluable string representation for this object."""
  255. if isinstance(self.fmt, str):
  256. fmt = self.fmt
  257. else:
  258. fmt = "%s, %s" % (self.fmt[0], self.fmt[1])
  259. return "Event('%s %s(%s) %s')" % (" ".join(self.properties),
  260. self.name,
  261. self.args,
  262. fmt)
  263. # Star matching on PRI is dangerous as one might have multiple
  264. # arguments with that format, hence the non-greedy version of it.
  265. _FMT = re.compile("(%[\d\.]*\w+|%.*?PRI\S+)")
  266. def formats(self):
  267. """List conversion specifiers in the argument print format string."""
  268. assert not isinstance(self.fmt, list)
  269. return self._FMT.findall(self.fmt)
  270. QEMU_TRACE = "trace_%(name)s"
  271. QEMU_TRACE_NOCHECK = "_nocheck__" + QEMU_TRACE
  272. QEMU_TRACE_TCG = QEMU_TRACE + "_tcg"
  273. QEMU_DSTATE = "_TRACE_%(NAME)s_DSTATE"
  274. QEMU_BACKEND_DSTATE = "TRACE_%(NAME)s_BACKEND_DSTATE"
  275. QEMU_EVENT = "_TRACE_%(NAME)s_EVENT"
  276. def api(self, fmt=None):
  277. if fmt is None:
  278. fmt = Event.QEMU_TRACE
  279. return fmt % {"name": self.name, "NAME": self.name.upper()}
  280. def transform(self, *trans):
  281. """Return a new Event with transformed Arguments."""
  282. return Event(self.name,
  283. list(self.properties),
  284. self.fmt,
  285. self.args.transform(*trans),
  286. self)
  287. def read_events(fobj, fname):
  288. """Generate the output for the given (format, backends) pair.
  289. Parameters
  290. ----------
  291. fobj : file
  292. Event description file.
  293. fname : str
  294. Name of event file
  295. Returns a list of Event objects
  296. """
  297. events = []
  298. for lineno, line in enumerate(fobj, 1):
  299. if line[-1] != '\n':
  300. raise ValueError("%s does not end with a new line" % fname)
  301. if not line.strip():
  302. continue
  303. if line.lstrip().startswith('#'):
  304. continue
  305. try:
  306. event = Event.build(line)
  307. except ValueError as e:
  308. arg0 = 'Error at %s:%d: %s' % (fname, lineno, e.args[0])
  309. e.args = (arg0,) + e.args[1:]
  310. raise
  311. # transform TCG-enabled events
  312. if "tcg" not in event.properties:
  313. events.append(event)
  314. else:
  315. event_trans = event.copy()
  316. event_trans.name += "_trans"
  317. event_trans.properties += ["tcg-trans"]
  318. event_trans.fmt = event.fmt[0]
  319. # ignore TCG arguments
  320. args_trans = []
  321. for atrans, aorig in zip(
  322. event_trans.transform(tracetool.transform.TCG_2_HOST).args,
  323. event.args):
  324. if atrans == aorig:
  325. args_trans.append(atrans)
  326. event_trans.args = Arguments(args_trans)
  327. event_exec = event.copy()
  328. event_exec.name += "_exec"
  329. event_exec.properties += ["tcg-exec"]
  330. event_exec.fmt = event.fmt[1]
  331. event_exec.args = event_exec.args.transform(tracetool.transform.TCG_2_HOST)
  332. new_event = [event_trans, event_exec]
  333. event.event_trans, event.event_exec = new_event
  334. events.extend(new_event)
  335. return events
  336. class TracetoolError (Exception):
  337. """Exception for calls to generate."""
  338. pass
  339. def try_import(mod_name, attr_name=None, attr_default=None):
  340. """Try to import a module and get an attribute from it.
  341. Parameters
  342. ----------
  343. mod_name : str
  344. Module name.
  345. attr_name : str, optional
  346. Name of an attribute in the module.
  347. attr_default : optional
  348. Default value if the attribute does not exist in the module.
  349. Returns
  350. -------
  351. A pair indicating whether the module could be imported and the module or
  352. object or attribute value.
  353. """
  354. try:
  355. module = __import__(mod_name, globals(), locals(), ["__package__"])
  356. if attr_name is None:
  357. return True, module
  358. return True, getattr(module, str(attr_name), attr_default)
  359. except ImportError:
  360. return False, None
  361. def generate(events, group, format, backends,
  362. binary=None, probe_prefix=None):
  363. """Generate the output for the given (format, backends) pair.
  364. Parameters
  365. ----------
  366. events : list
  367. list of Event objects to generate for
  368. group: str
  369. Name of the tracing group
  370. format : str
  371. Output format name.
  372. backends : list
  373. Output backend names.
  374. binary : str or None
  375. See tracetool.backend.dtrace.BINARY.
  376. probe_prefix : str or None
  377. See tracetool.backend.dtrace.PROBEPREFIX.
  378. """
  379. # fix strange python error (UnboundLocalError tracetool)
  380. import tracetool
  381. format = str(format)
  382. if len(format) == 0:
  383. raise TracetoolError("format not set")
  384. if not tracetool.format.exists(format):
  385. raise TracetoolError("unknown format: %s" % format)
  386. if len(backends) == 0:
  387. raise TracetoolError("no backends specified")
  388. for backend in backends:
  389. if not tracetool.backend.exists(backend):
  390. raise TracetoolError("unknown backend: %s" % backend)
  391. backend = tracetool.backend.Wrapper(backends, format)
  392. import tracetool.backend.dtrace
  393. tracetool.backend.dtrace.BINARY = binary
  394. tracetool.backend.dtrace.PROBEPREFIX = probe_prefix
  395. tracetool.format.generate(events, format, backend, group)