2
0

__init__.py 13 KB

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