2
0

commands.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. """
  2. QAPI command marshaller generator
  3. Copyright IBM, Corp. 2011
  4. Copyright (C) 2014-2018 Red Hat, Inc.
  5. Authors:
  6. Anthony Liguori <aliguori@us.ibm.com>
  7. Michael Roth <mdroth@linux.vnet.ibm.com>
  8. Markus Armbruster <armbru@redhat.com>
  9. This work is licensed under the terms of the GNU GPL, version 2.
  10. See the COPYING file in the top-level directory.
  11. """
  12. from typing import (
  13. Dict,
  14. List,
  15. Optional,
  16. Set,
  17. )
  18. from .common import c_name, mcgen
  19. from .gen import (
  20. QAPIGenC,
  21. QAPISchemaModularCVisitor,
  22. build_params,
  23. gen_special_features,
  24. ifcontext,
  25. )
  26. from .schema import (
  27. QAPISchema,
  28. QAPISchemaFeature,
  29. QAPISchemaIfCond,
  30. QAPISchemaObjectType,
  31. QAPISchemaType,
  32. )
  33. from .source import QAPISourceInfo
  34. def gen_command_decl(name: str,
  35. arg_type: Optional[QAPISchemaObjectType],
  36. boxed: bool,
  37. ret_type: Optional[QAPISchemaType],
  38. coroutine: bool) -> str:
  39. return mcgen('''
  40. %(c_type)s %(coroutine_fn)sqmp_%(c_name)s(%(params)s);
  41. ''',
  42. c_type=(ret_type and ret_type.c_type()) or 'void',
  43. coroutine_fn='coroutine_fn ' if coroutine else '',
  44. c_name=c_name(name),
  45. params=build_params(arg_type, boxed, 'Error **errp'))
  46. def gen_call(name: str,
  47. arg_type: Optional[QAPISchemaObjectType],
  48. boxed: bool,
  49. ret_type: Optional[QAPISchemaType],
  50. gen_tracing: bool) -> str:
  51. ret = ''
  52. argstr = ''
  53. if boxed:
  54. assert arg_type
  55. argstr = '&arg, '
  56. elif arg_type:
  57. assert not arg_type.variants
  58. for memb in arg_type.members:
  59. if memb.need_has():
  60. argstr += 'arg.has_%s, ' % c_name(memb.name)
  61. argstr += 'arg.%s, ' % c_name(memb.name)
  62. lhs = ''
  63. if ret_type:
  64. lhs = 'retval = '
  65. name = c_name(name)
  66. upper = name.upper()
  67. if gen_tracing:
  68. ret += mcgen('''
  69. if (trace_event_get_state_backends(TRACE_QMP_ENTER_%(upper)s)) {
  70. g_autoptr(GString) req_json = qobject_to_json(QOBJECT(args));
  71. trace_qmp_enter_%(name)s(req_json->str);
  72. }
  73. ''',
  74. upper=upper, name=name)
  75. ret += mcgen('''
  76. %(lhs)sqmp_%(name)s(%(args)s&err);
  77. ''',
  78. name=name, args=argstr, lhs=lhs)
  79. ret += mcgen('''
  80. if (err) {
  81. ''')
  82. if gen_tracing:
  83. ret += mcgen('''
  84. trace_qmp_exit_%(name)s(error_get_pretty(err), false);
  85. ''',
  86. name=name)
  87. ret += mcgen('''
  88. error_propagate(errp, err);
  89. goto out;
  90. }
  91. ''')
  92. if ret_type:
  93. ret += mcgen('''
  94. qmp_marshal_output_%(c_name)s(retval, ret, errp);
  95. ''',
  96. c_name=ret_type.c_name())
  97. if gen_tracing:
  98. if ret_type:
  99. ret += mcgen('''
  100. if (trace_event_get_state_backends(TRACE_QMP_EXIT_%(upper)s)) {
  101. g_autoptr(GString) ret_json = qobject_to_json(*ret);
  102. trace_qmp_exit_%(name)s(ret_json->str, true);
  103. }
  104. ''',
  105. upper=upper, name=name)
  106. else:
  107. ret += mcgen('''
  108. trace_qmp_exit_%(name)s("{}", true);
  109. ''',
  110. name=name)
  111. return ret
  112. def gen_marshal_output(ret_type: QAPISchemaType) -> str:
  113. return mcgen('''
  114. static void qmp_marshal_output_%(c_name)s(%(c_type)s ret_in,
  115. QObject **ret_out, Error **errp)
  116. {
  117. Visitor *v;
  118. v = qobject_output_visitor_new_qmp(ret_out);
  119. if (visit_type_%(c_name)s(v, "unused", &ret_in, errp)) {
  120. visit_complete(v, ret_out);
  121. }
  122. visit_free(v);
  123. v = qapi_dealloc_visitor_new();
  124. visit_type_%(c_name)s(v, "unused", &ret_in, NULL);
  125. visit_free(v);
  126. }
  127. ''',
  128. c_type=ret_type.c_type(), c_name=ret_type.c_name())
  129. def build_marshal_proto(name: str,
  130. coroutine: bool) -> str:
  131. return ('void %(coroutine_fn)sqmp_marshal_%(c_name)s(%(params)s)' % {
  132. 'coroutine_fn': 'coroutine_fn ' if coroutine else '',
  133. 'c_name': c_name(name),
  134. 'params': 'QDict *args, QObject **ret, Error **errp',
  135. })
  136. def gen_marshal_decl(name: str,
  137. coroutine: bool) -> str:
  138. return mcgen('''
  139. %(proto)s;
  140. ''',
  141. proto=build_marshal_proto(name, coroutine))
  142. def gen_trace(name: str) -> str:
  143. return mcgen('''
  144. qmp_enter_%(name)s(const char *json) "%%s"
  145. qmp_exit_%(name)s(const char *result, bool succeeded) "%%s %%d"
  146. ''',
  147. name=c_name(name))
  148. def gen_marshal(name: str,
  149. arg_type: Optional[QAPISchemaObjectType],
  150. boxed: bool,
  151. ret_type: Optional[QAPISchemaType],
  152. gen_tracing: bool,
  153. coroutine: bool) -> str:
  154. have_args = boxed or (arg_type and not arg_type.is_empty())
  155. if have_args:
  156. assert arg_type is not None
  157. arg_type_c_name = arg_type.c_name()
  158. ret = mcgen('''
  159. %(proto)s
  160. {
  161. Error *err = NULL;
  162. bool ok = false;
  163. Visitor *v;
  164. ''',
  165. proto=build_marshal_proto(name, coroutine))
  166. if ret_type:
  167. ret += mcgen('''
  168. %(c_type)s retval;
  169. ''',
  170. c_type=ret_type.c_type())
  171. if have_args:
  172. ret += mcgen('''
  173. %(c_name)s arg = {0};
  174. ''',
  175. c_name=arg_type_c_name)
  176. ret += mcgen('''
  177. v = qobject_input_visitor_new_qmp(QOBJECT(args));
  178. if (!visit_start_struct(v, NULL, NULL, 0, errp)) {
  179. goto out;
  180. }
  181. ''')
  182. if have_args:
  183. ret += mcgen('''
  184. if (visit_type_%(c_arg_type)s_members(v, &arg, errp)) {
  185. ok = visit_check_struct(v, errp);
  186. }
  187. ''',
  188. c_arg_type=arg_type_c_name)
  189. else:
  190. ret += mcgen('''
  191. ok = visit_check_struct(v, errp);
  192. ''')
  193. ret += mcgen('''
  194. visit_end_struct(v, NULL);
  195. if (!ok) {
  196. goto out;
  197. }
  198. ''')
  199. ret += gen_call(name, arg_type, boxed, ret_type, gen_tracing)
  200. ret += mcgen('''
  201. out:
  202. visit_free(v);
  203. ''')
  204. ret += mcgen('''
  205. v = qapi_dealloc_visitor_new();
  206. visit_start_struct(v, NULL, NULL, 0, NULL);
  207. ''')
  208. if have_args:
  209. ret += mcgen('''
  210. visit_type_%(c_arg_type)s_members(v, &arg, NULL);
  211. ''',
  212. c_arg_type=arg_type_c_name)
  213. ret += mcgen('''
  214. visit_end_struct(v, NULL);
  215. visit_free(v);
  216. ''')
  217. ret += mcgen('''
  218. }
  219. ''')
  220. return ret
  221. def gen_register_command(name: str,
  222. features: List[QAPISchemaFeature],
  223. success_response: bool,
  224. allow_oob: bool,
  225. allow_preconfig: bool,
  226. coroutine: bool) -> str:
  227. options = []
  228. if not success_response:
  229. options += ['QCO_NO_SUCCESS_RESP']
  230. if allow_oob:
  231. options += ['QCO_ALLOW_OOB']
  232. if allow_preconfig:
  233. options += ['QCO_ALLOW_PRECONFIG']
  234. if coroutine:
  235. options += ['QCO_COROUTINE']
  236. ret = mcgen('''
  237. qmp_register_command(cmds, "%(name)s",
  238. qmp_marshal_%(c_name)s, %(opts)s, %(feats)s);
  239. ''',
  240. name=name, c_name=c_name(name),
  241. opts=' | '.join(options) or 0,
  242. feats=gen_special_features(features))
  243. return ret
  244. class QAPISchemaGenCommandVisitor(QAPISchemaModularCVisitor):
  245. def __init__(self, prefix: str, gen_tracing: bool):
  246. super().__init__(
  247. prefix, 'qapi-commands',
  248. ' * Schema-defined QAPI/QMP commands', None, __doc__,
  249. gen_tracing=gen_tracing)
  250. self._visited_ret_types: Dict[QAPIGenC, Set[QAPISchemaType]] = {}
  251. self._gen_tracing = gen_tracing
  252. def _begin_user_module(self, name: str) -> None:
  253. self._visited_ret_types[self._genc] = set()
  254. commands = self._module_basename('qapi-commands', name)
  255. types = self._module_basename('qapi-types', name)
  256. visit = self._module_basename('qapi-visit', name)
  257. self._genc.add(mcgen('''
  258. #include "qemu/osdep.h"
  259. #include "qapi/compat-policy.h"
  260. #include "qapi/visitor.h"
  261. #include "qapi/qmp/qdict.h"
  262. #include "qapi/dealloc-visitor.h"
  263. #include "qapi/error.h"
  264. #include "%(visit)s.h"
  265. #include "%(commands)s.h"
  266. ''',
  267. commands=commands, visit=visit))
  268. if self._gen_tracing and commands != 'qapi-commands':
  269. self._genc.add(mcgen('''
  270. #include "qapi/qmp/qjson.h"
  271. #include "trace/trace-%(nm)s_trace_events.h"
  272. ''',
  273. nm=c_name(commands, protect=False)))
  274. # We use c_name(commands, protect=False) to turn '-' into '_', to
  275. # match .underscorify() in trace/meson.build
  276. self._genh.add(mcgen('''
  277. #include "%(types)s.h"
  278. ''',
  279. types=types))
  280. def visit_begin(self, schema: QAPISchema) -> None:
  281. self._add_module('./init', ' * QAPI Commands initialization')
  282. self._genh.add(mcgen('''
  283. #include "qapi/qmp/dispatch.h"
  284. void %(c_prefix)sqmp_init_marshal(QmpCommandList *cmds);
  285. ''',
  286. c_prefix=c_name(self._prefix, protect=False)))
  287. self._genc.add(mcgen('''
  288. #include "qemu/osdep.h"
  289. #include "%(prefix)sqapi-commands.h"
  290. #include "%(prefix)sqapi-init-commands.h"
  291. void %(c_prefix)sqmp_init_marshal(QmpCommandList *cmds)
  292. {
  293. QTAILQ_INIT(cmds);
  294. ''',
  295. prefix=self._prefix,
  296. c_prefix=c_name(self._prefix, protect=False)))
  297. def visit_end(self) -> None:
  298. with self._temp_module('./init'):
  299. self._genc.add(mcgen('''
  300. }
  301. '''))
  302. def visit_command(self,
  303. name: str,
  304. info: Optional[QAPISourceInfo],
  305. ifcond: QAPISchemaIfCond,
  306. features: List[QAPISchemaFeature],
  307. arg_type: Optional[QAPISchemaObjectType],
  308. ret_type: Optional[QAPISchemaType],
  309. gen: bool,
  310. success_response: bool,
  311. boxed: bool,
  312. allow_oob: bool,
  313. allow_preconfig: bool,
  314. coroutine: bool) -> None:
  315. if not gen:
  316. return
  317. # FIXME: If T is a user-defined type, the user is responsible
  318. # for making this work, i.e. to make T's condition the
  319. # conjunction of the T-returning commands' conditions. If T
  320. # is a built-in type, this isn't possible: the
  321. # qmp_marshal_output_T() will be generated unconditionally.
  322. if ret_type and ret_type not in self._visited_ret_types[self._genc]:
  323. self._visited_ret_types[self._genc].add(ret_type)
  324. with ifcontext(ret_type.ifcond,
  325. self._genh, self._genc):
  326. self._genc.add(gen_marshal_output(ret_type))
  327. with ifcontext(ifcond, self._genh, self._genc):
  328. self._genh.add(gen_command_decl(name, arg_type, boxed,
  329. ret_type, coroutine))
  330. self._genh.add(gen_marshal_decl(name, coroutine))
  331. self._genc.add(gen_marshal(name, arg_type, boxed, ret_type,
  332. self._gen_tracing, coroutine))
  333. if self._gen_tracing:
  334. self._gen_trace_events.add(gen_trace(name))
  335. with self._temp_module('./init'):
  336. with ifcontext(ifcond, self._genh, self._genc):
  337. self._genc.add(gen_register_command(
  338. name, features, success_response, allow_oob,
  339. allow_preconfig, coroutine))
  340. def gen_commands(schema: QAPISchema,
  341. output_dir: str,
  342. prefix: str,
  343. gen_tracing: bool) -> None:
  344. vis = QAPISchemaGenCommandVisitor(prefix, gen_tracing)
  345. schema.visit(vis)
  346. vis.write(output_dir)