qapi-code-gen.txt 18 KB

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