2
0

__init__.py 14 KB

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