qapi-code-gen.txt 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  1. = How to use the QAPI code generator =
  2. QAPI is a native C API within QEMU which provides management-level
  3. functionality to internal/external users. For external
  4. users/processes, this interface is made available by a JSON-based
  5. QEMU Monitor protocol that is provided by the QMP server.
  6. To map QMP-defined interfaces to the native C QAPI implementations,
  7. a JSON-based schema is used to define types and function
  8. signatures, and a set of scripts is used to generate types/signatures,
  9. and marshaling/dispatch code. The QEMU Guest Agent also uses these
  10. scripts, paired with a separate schema, to generate
  11. marshaling/dispatch code for the guest agent server running in the
  12. guest.
  13. This document will describe how the schemas, scripts, and resulting
  14. code are used.
  15. == QMP/Guest agent schema ==
  16. This file defines the types, commands, and events used by QMP. It should
  17. fully describe the interface used by QMP.
  18. This file is designed to be loosely based on JSON although it's technically
  19. executable Python. While dictionaries are used, they are parsed as
  20. OrderedDicts so that ordering is preserved.
  21. There are two basic syntaxes used, type definitions and command definitions.
  22. The first syntax defines a type and is represented by a dictionary. There are
  23. three kinds of user-defined types that are supported: complex types,
  24. enumeration types and union types.
  25. Generally speaking, types definitions should always use CamelCase for the type
  26. names. Command names should be all lower case with words separated by a hyphen.
  27. === Includes ===
  28. The QAPI schema definitions can be modularized using the 'include' directive:
  29. { 'include': 'path/to/file.json'}
  30. The directive is evaluated recursively, and include paths are relative to the
  31. file using the directive. Multiple includes of the same file are safe.
  32. === Complex types ===
  33. A complex type is a dictionary containing a single key whose value is a
  34. dictionary. This corresponds to a struct in C or an Object in JSON. An
  35. example of a complex type is:
  36. { 'type': 'MyType',
  37. 'data': { 'member1': 'str', 'member2': 'int', '*member3': 'str' } }
  38. The use of '*' as a prefix to the name means the member is optional.
  39. The default initialization value of an optional argument should not be changed
  40. between versions of QEMU unless the new default maintains backward
  41. compatibility to the user-visible behavior of the old default.
  42. With proper documentation, this policy still allows some flexibility; for
  43. example, documenting that a default of 0 picks an optimal buffer size allows
  44. one release to declare the optimal size at 512 while another release declares
  45. the optimal size at 4096 - the user-visible behavior is not the bytes used by
  46. the buffer, but the fact that the buffer was optimal size.
  47. On input structures (only mentioned in the 'data' side of a command), changing
  48. from mandatory to optional is safe (older clients will supply the option, and
  49. newer clients can benefit from the default); changing from optional to
  50. mandatory is backwards incompatible (older clients may be omitting the option,
  51. and must continue to work).
  52. On output structures (only mentioned in the 'returns' side of a command),
  53. changing from mandatory to optional is in general unsafe (older clients may be
  54. expecting the field, and could crash if it is missing), although it can be done
  55. if the only way that the optional argument will be omitted is when it is
  56. triggered by the presence of a new input flag to the command that older clients
  57. don't know to send. Changing from optional to mandatory is safe.
  58. A structure that is used in both input and output of various commands
  59. must consider the backwards compatibility constraints of both directions
  60. of use.
  61. A complex type definition can specify another complex type as its base.
  62. In this case, the fields of the base type are included as top-level fields
  63. of the new complex type's dictionary in the QMP wire format. An example
  64. definition is:
  65. { 'type': 'BlockdevOptionsGenericFormat', 'data': { 'file': 'str' } }
  66. { 'type': 'BlockdevOptionsGenericCOWFormat',
  67. 'base': 'BlockdevOptionsGenericFormat',
  68. 'data': { '*backing': 'str' } }
  69. An example BlockdevOptionsGenericCOWFormat object on the wire could use
  70. both fields like this:
  71. { "file": "/some/place/my-image",
  72. "backing": "/some/place/my-backing-file" }
  73. === Enumeration types ===
  74. An enumeration type is a dictionary containing a single key whose value is a
  75. list of strings. An example enumeration is:
  76. { 'enum': 'MyEnum', 'data': [ 'value1', 'value2', 'value3' ] }
  77. === Union types ===
  78. Union types are used to let the user choose between several different data
  79. types. A union type is defined using a dictionary as explained in the
  80. following paragraphs.
  81. A simple union type defines a mapping from discriminator values to data types
  82. like in this example:
  83. { 'type': 'FileOptions', 'data': { 'filename': 'str' } }
  84. { 'type': 'Qcow2Options',
  85. 'data': { 'backing-file': 'str', 'lazy-refcounts': 'bool' } }
  86. { 'union': 'BlockdevOptions',
  87. 'data': { 'file': 'FileOptions',
  88. 'qcow2': 'Qcow2Options' } }
  89. In the QMP wire format, a simple union is represented by a dictionary that
  90. contains the 'type' field as a discriminator, and a 'data' field that is of the
  91. specified data type corresponding to the discriminator value:
  92. { "type": "qcow2", "data" : { "backing-file": "/some/place/my-image",
  93. "lazy-refcounts": true } }
  94. A union definition can specify a complex type as its base. In this case, the
  95. fields of the complex type are included as top-level fields of the union
  96. dictionary in the QMP wire format. An example definition is:
  97. { 'type': 'BlockdevCommonOptions', 'data': { 'readonly': 'bool' } }
  98. { 'union': 'BlockdevOptions',
  99. 'base': 'BlockdevCommonOptions',
  100. 'data': { 'raw': 'RawOptions',
  101. 'qcow2': 'Qcow2Options' } }
  102. And it looks like this on the wire:
  103. { "type": "qcow2",
  104. "readonly": false,
  105. "data" : { "backing-file": "/some/place/my-image",
  106. "lazy-refcounts": true } }
  107. Flat union types avoid the nesting on the wire. They are used whenever a
  108. specific field of the base type is declared as the discriminator ('type' is
  109. then no longer generated). The discriminator must be of enumeration type.
  110. The above example can then be modified as follows:
  111. { 'enum': 'BlockdevDriver', 'data': [ 'raw', 'qcow2' ] }
  112. { 'type': 'BlockdevCommonOptions',
  113. 'data': { 'driver': 'BlockdevDriver', 'readonly': 'bool' } }
  114. { 'union': 'BlockdevOptions',
  115. 'base': 'BlockdevCommonOptions',
  116. 'discriminator': 'driver',
  117. 'data': { 'raw': 'RawOptions',
  118. 'qcow2': 'Qcow2Options' } }
  119. Resulting in this JSON object:
  120. { "driver": "qcow2",
  121. "readonly": false,
  122. "backing-file": "/some/place/my-image",
  123. "lazy-refcounts": true }
  124. A special type of unions are anonymous unions. They don't form a dictionary in
  125. the wire format but allow the direct use of different types in their place. As
  126. they aren't structured, they don't have any explicit discriminator but use
  127. the (QObject) data type of their value as an implicit discriminator. This means
  128. that they are restricted to using only one discriminator value per QObject
  129. type. For example, you cannot have two different complex types in an anonymous
  130. union, or two different integer types.
  131. Anonymous unions are declared using an empty dictionary as their discriminator.
  132. The discriminator values never appear on the wire, they are only used in the
  133. generated C code. Anonymous unions cannot have a base type.
  134. { 'union': 'BlockRef',
  135. 'discriminator': {},
  136. 'data': { 'definition': 'BlockdevOptions',
  137. 'reference': 'str' } }
  138. This example allows using both of the following example objects:
  139. { "file": "my_existing_block_device_id" }
  140. { "file": { "driver": "file",
  141. "readonly": false,
  142. "filename": "/tmp/mydisk.qcow2" } }
  143. === Commands ===
  144. Commands are defined by using a list containing three members. The first
  145. member is the command name, the second member is a dictionary containing
  146. arguments, and the third member is the return type.
  147. An example command is:
  148. { 'command': 'my-command',
  149. 'data': { 'arg1': 'str', '*arg2': 'str' },
  150. 'returns': 'str' }
  151. === Events ===
  152. Events are defined with the keyword 'event'. When 'data' is also specified,
  153. additional info will be included in the event. Finally there will be C API
  154. generated in qapi-event.h; when called by QEMU code, a message with timestamp
  155. will be emitted on the wire. If timestamp is -1, it means failure to retrieve
  156. host time.
  157. An example event is:
  158. { 'event': 'EVENT_C',
  159. 'data': { '*a': 'int', 'b': 'str' } }
  160. Resulting in this JSON object:
  161. { "event": "EVENT_C",
  162. "data": { "b": "test string" },
  163. "timestamp": { "seconds": 1267020223, "microseconds": 435656 } }
  164. == Code generation ==
  165. Schemas are fed into 3 scripts to generate all the code/files that, paired
  166. with the core QAPI libraries, comprise everything required to take JSON
  167. commands read in by a QMP/guest agent server, unmarshal the arguments into
  168. the underlying C types, call into the corresponding C function, and map the
  169. response back to a QMP/guest agent response to be returned to the user.
  170. As an example, we'll use the following schema, which describes a single
  171. complex user-defined type (which will produce a C struct, along with a list
  172. node structure that can be used to chain together a list of such types in
  173. case we want to accept/return a list of this type with a command), and a
  174. command which takes that type as a parameter and returns the same type:
  175. $ cat example-schema.json
  176. { 'type': 'UserDefOne',
  177. 'data': { 'integer': 'int', 'string': 'str' } }
  178. { 'command': 'my-command',
  179. 'data': {'arg1': 'UserDefOne'},
  180. 'returns': 'UserDefOne' }
  181. { 'event': 'MY_EVENT' }
  182. === scripts/qapi-types.py ===
  183. Used to generate the C types defined by a schema. The following files are
  184. created:
  185. $(prefix)qapi-types.h - C types corresponding to types defined in
  186. the schema you pass in
  187. $(prefix)qapi-types.c - Cleanup functions for the above C types
  188. The $(prefix) is an optional parameter used as a namespace to keep the
  189. generated code from one schema/code-generation separated from others so code
  190. can be generated/used from multiple schemas without clobbering previously
  191. created code.
  192. Example:
  193. $ python scripts/qapi-types.py --output-dir="qapi-generated" \
  194. --prefix="example-" --input-file=example-schema.json
  195. $ cat qapi-generated/example-qapi-types.c
  196. [Uninteresting stuff omitted...]
  197. void qapi_free_UserDefOneList(UserDefOneList *obj)
  198. {
  199. QapiDeallocVisitor *md;
  200. Visitor *v;
  201. if (!obj) {
  202. return;
  203. }
  204. md = qapi_dealloc_visitor_new();
  205. v = qapi_dealloc_get_visitor(md);
  206. visit_type_UserDefOneList(v, &obj, NULL, NULL);
  207. qapi_dealloc_visitor_cleanup(md);
  208. }
  209. void qapi_free_UserDefOne(UserDefOne *obj)
  210. {
  211. QapiDeallocVisitor *md;
  212. Visitor *v;
  213. if (!obj) {
  214. return;
  215. }
  216. md = qapi_dealloc_visitor_new();
  217. v = qapi_dealloc_get_visitor(md);
  218. visit_type_UserDefOne(v, &obj, NULL, NULL);
  219. qapi_dealloc_visitor_cleanup(md);
  220. }
  221. $ cat qapi-generated/example-qapi-types.h
  222. [Uninteresting stuff omitted...]
  223. #ifndef EXAMPLE_QAPI_TYPES_H
  224. #define EXAMPLE_QAPI_TYPES_H
  225. [Builtin types omitted...]
  226. typedef struct UserDefOne UserDefOne;
  227. typedef struct UserDefOneList
  228. {
  229. union {
  230. UserDefOne *value;
  231. uint64_t padding;
  232. };
  233. struct UserDefOneList *next;
  234. } UserDefOneList;
  235. [Functions on builtin types omitted...]
  236. struct UserDefOne
  237. {
  238. int64_t integer;
  239. char *string;
  240. };
  241. void qapi_free_UserDefOneList(UserDefOneList *obj);
  242. void qapi_free_UserDefOne(UserDefOne *obj);
  243. #endif
  244. === scripts/qapi-visit.py ===
  245. Used to generate the visitor functions used to walk through and convert
  246. a QObject (as provided by QMP) to a native C data structure and
  247. vice-versa, as well as the visitor function used to dealloc a complex
  248. schema-defined C type.
  249. The following files are generated:
  250. $(prefix)qapi-visit.c: visitor function for a particular C type, used
  251. to automagically convert QObjects into the
  252. corresponding C type and vice-versa, as well
  253. as for deallocating memory for an existing C
  254. type
  255. $(prefix)qapi-visit.h: declarations for previously mentioned visitor
  256. functions
  257. Example:
  258. $ python scripts/qapi-visit.py --output-dir="qapi-generated"
  259. --prefix="example-" --input-file=example-schema.json
  260. $ cat qapi-generated/example-qapi-visit.c
  261. [Uninteresting stuff omitted...]
  262. static void visit_type_UserDefOne_fields(Visitor *m, UserDefOne **obj, Error **errp)
  263. {
  264. Error *err = NULL;
  265. visit_type_int(m, &(*obj)->integer, "integer", &err);
  266. if (err) {
  267. goto out;
  268. }
  269. visit_type_str(m, &(*obj)->string, "string", &err);
  270. if (err) {
  271. goto out;
  272. }
  273. out:
  274. error_propagate(errp, err);
  275. }
  276. void visit_type_UserDefOne(Visitor *m, UserDefOne **obj, const char *name, Error **errp)
  277. {
  278. Error *err = NULL;
  279. visit_start_struct(m, (void **)obj, "UserDefOne", name, sizeof(UserDefOne), &err);
  280. if (!err) {
  281. if (*obj) {
  282. visit_type_UserDefOne_fields(m, obj, errp);
  283. }
  284. visit_end_struct(m, &err);
  285. }
  286. error_propagate(errp, err);
  287. }
  288. void visit_type_UserDefOneList(Visitor *m, UserDefOneList **obj, const char *name, Error **errp)
  289. {
  290. Error *err = NULL;
  291. GenericList *i, **prev;
  292. visit_start_list(m, name, &err);
  293. if (err) {
  294. goto out;
  295. }
  296. for (prev = (GenericList **)obj;
  297. !err && (i = visit_next_list(m, prev, &err)) != NULL;
  298. prev = &i) {
  299. UserDefOneList *native_i = (UserDefOneList *)i;
  300. visit_type_UserDefOne(m, &native_i->value, NULL, &err);
  301. }
  302. error_propagate(errp, err);
  303. err = NULL;
  304. visit_end_list(m, &err);
  305. out:
  306. error_propagate(errp, err);
  307. }
  308. $ python scripts/qapi-commands.py --output-dir="qapi-generated" \
  309. --prefix="example-" --input-file=example-schema.json
  310. $ cat qapi-generated/example-qapi-visit.h
  311. [Uninteresting stuff omitted...]
  312. #ifndef EXAMPLE_QAPI_VISIT_H
  313. #define EXAMPLE_QAPI_VISIT_H
  314. [Visitors for builtin types omitted...]
  315. void visit_type_UserDefOne(Visitor *m, UserDefOne **obj, const char *name, Error **errp);
  316. void visit_type_UserDefOneList(Visitor *m, UserDefOneList **obj, const char *name, Error **errp);
  317. #endif
  318. === scripts/qapi-commands.py ===
  319. Used to generate the marshaling/dispatch functions for the commands defined
  320. in the schema. The following files are generated:
  321. $(prefix)qmp-marshal.c: command marshal/dispatch functions for each
  322. QMP command defined in the schema. Functions
  323. generated by qapi-visit.py are used to
  324. convert QObjects received from the wire into
  325. function parameters, and uses the same
  326. visitor functions to convert native C return
  327. values to QObjects from transmission back
  328. over the wire.
  329. $(prefix)qmp-commands.h: Function prototypes for the QMP commands
  330. specified in the schema.
  331. Example:
  332. $ python scripts/qapi-commands.py --output-dir="qapi-generated"
  333. --prefix="example-" --input-file=example-schema.json
  334. $ cat qapi-generated/example-qmp-marshal.c
  335. [Uninteresting stuff omitted...]
  336. static void qmp_marshal_output_my_command(UserDefOne *ret_in, QObject **ret_out, Error **errp)
  337. {
  338. Error *local_err = NULL;
  339. QmpOutputVisitor *mo = qmp_output_visitor_new();
  340. QapiDeallocVisitor *md;
  341. Visitor *v;
  342. v = qmp_output_get_visitor(mo);
  343. visit_type_UserDefOne(v, &ret_in, "unused", &local_err);
  344. if (local_err) {
  345. goto out;
  346. }
  347. *ret_out = qmp_output_get_qobject(mo);
  348. out:
  349. error_propagate(errp, local_err);
  350. qmp_output_visitor_cleanup(mo);
  351. md = qapi_dealloc_visitor_new();
  352. v = qapi_dealloc_get_visitor(md);
  353. visit_type_UserDefOne(v, &ret_in, "unused", NULL);
  354. qapi_dealloc_visitor_cleanup(md);
  355. }
  356. static void qmp_marshal_input_my_command(QDict *args, QObject **ret, Error **errp)
  357. {
  358. Error *local_err = NULL;
  359. UserDefOne *retval = NULL;
  360. QmpInputVisitor *mi = qmp_input_visitor_new_strict(QOBJECT(args));
  361. QapiDeallocVisitor *md;
  362. Visitor *v;
  363. UserDefOne *arg1 = NULL;
  364. v = qmp_input_get_visitor(mi);
  365. visit_type_UserDefOne(v, &arg1, "arg1", &local_err);
  366. if (local_err) {
  367. goto out;
  368. }
  369. retval = qmp_my_command(arg1, &local_err);
  370. if (local_err) {
  371. goto out;
  372. }
  373. qmp_marshal_output_my_command(retval, ret, &local_err);
  374. out:
  375. error_propagate(errp, local_err);
  376. qmp_input_visitor_cleanup(mi);
  377. md = qapi_dealloc_visitor_new();
  378. v = qapi_dealloc_get_visitor(md);
  379. visit_type_UserDefOne(v, &arg1, "arg1", NULL);
  380. qapi_dealloc_visitor_cleanup(md);
  381. return;
  382. }
  383. static void qmp_init_marshal(void)
  384. {
  385. qmp_register_command("my-command", qmp_marshal_input_my_command, QCO_NO_OPTIONS);
  386. }
  387. qapi_init(qmp_init_marshal);
  388. $ cat qapi-generated/example-qmp-commands.h
  389. [Uninteresting stuff omitted...]
  390. #ifndef EXAMPLE_QMP_COMMANDS_H
  391. #define EXAMPLE_QMP_COMMANDS_H
  392. #include "example-qapi-types.h"
  393. #include "qapi/qmp/qdict.h"
  394. #include "qapi/error.h"
  395. UserDefOne *qmp_my_command(UserDefOne *arg1, Error **errp);
  396. #endif
  397. === scripts/qapi-event.py ===
  398. Used to generate the event-related C code defined by a schema. The
  399. following files are created:
  400. $(prefix)qapi-event.h - Function prototypes for each event type, plus an
  401. enumeration of all event names
  402. $(prefix)qapi-event.c - Implementation of functions to send an event
  403. Example:
  404. $ python scripts/qapi-event.py --output-dir="qapi-generated"
  405. --prefix="example-" --input-file=example-schema.json
  406. $ cat qapi-generated/example-qapi-event.c
  407. [Uninteresting stuff omitted...]
  408. void qapi_event_send_my_event(Error **errp)
  409. {
  410. QDict *qmp;
  411. Error *local_err = NULL;
  412. QMPEventFuncEmit emit;
  413. emit = qmp_event_get_func_emit();
  414. if (!emit) {
  415. return;
  416. }
  417. qmp = qmp_event_build_dict("MY_EVENT");
  418. emit(EXAMPLE_QAPI_EVENT_MY_EVENT, qmp, &local_err);
  419. error_propagate(errp, local_err);
  420. QDECREF(qmp);
  421. }
  422. const char *EXAMPLE_QAPIEvent_lookup[] = {
  423. "MY_EVENT",
  424. NULL,
  425. };
  426. $ cat qapi-generated/example-qapi-event.h
  427. [Uninteresting stuff omitted...]
  428. #ifndef EXAMPLE_QAPI_EVENT_H
  429. #define EXAMPLE_QAPI_EVENT_H
  430. #include "qapi/error.h"
  431. #include "qapi/qmp/qdict.h"
  432. #include "example-qapi-types.h"
  433. void qapi_event_send_my_event(Error **errp);
  434. extern const char *EXAMPLE_QAPIEvent_lookup[];
  435. typedef enum EXAMPLE_QAPIEvent
  436. {
  437. EXAMPLE_QAPI_EVENT_MY_EVENT = 0,
  438. EXAMPLE_QAPI_EVENT_MAX = 1,
  439. } EXAMPLE_QAPIEvent;
  440. #endif