1 = How to use the QAPI code generator =
3 QAPI is a native C API within QEMU which provides management-level
4 functionality to internal/external users. For external
5 users/processes, this interface is made available by a JSON-based
6 QEMU Monitor protocol that is provided by the QMP server.
8 To map QMP-defined interfaces to the native C QAPI implementations,
9 a JSON-based schema is used to define types and function
10 signatures, and a set of scripts is used to generate types/signatures,
11 and marshaling/dispatch code. The QEMU Guest Agent also uses these
12 scripts, paired with a separate schema, to generate
13 marshaling/dispatch code for the guest agent server running in the
16 This document will describe how the schemas, scripts, and resulting
20 == QMP/Guest agent schema ==
22 This file defines the types, commands, and events used by QMP. It should
23 fully describe the interface used by QMP.
25 This file is designed to be loosely based on JSON although it's technically
26 executable Python. While dictionaries are used, they are parsed as
27 OrderedDicts so that ordering is preserved.
29 There are two basic syntaxes used, type definitions and command definitions.
31 The first syntax defines a type and is represented by a dictionary. There are
32 three kinds of user-defined types that are supported: complex types,
33 enumeration types and union types.
35 Generally speaking, types definitions should always use CamelCase for the type
36 names. Command names should be all lower case with words separated by a hyphen.
41 The QAPI schema definitions can be modularized using the 'include' directive:
43 { 'include': 'path/to/file.json'}
45 The directive is evaluated recursively, and include paths are relative to the
46 file using the directive. Multiple includes of the same file are safe.
51 A complex type is a dictionary containing a single key whose value is a
52 dictionary. This corresponds to a struct in C or an Object in JSON. An
53 example of a complex type is:
56 'data': { 'member1': 'str', 'member2': 'int', '*member3': 'str' } }
58 The use of '*' as a prefix to the name means the member is optional.
60 The default initialization value of an optional argument should not be changed
61 between versions of QEMU unless the new default maintains backward
62 compatibility to the user-visible behavior of the old default.
64 With proper documentation, this policy still allows some flexibility; for
65 example, documenting that a default of 0 picks an optimal buffer size allows
66 one release to declare the optimal size at 512 while another release declares
67 the optimal size at 4096 - the user-visible behavior is not the bytes used by
68 the buffer, but the fact that the buffer was optimal size.
70 On input structures (only mentioned in the 'data' side of a command), changing
71 from mandatory to optional is safe (older clients will supply the option, and
72 newer clients can benefit from the default); changing from optional to
73 mandatory is backwards incompatible (older clients may be omitting the option,
74 and must continue to work).
76 On output structures (only mentioned in the 'returns' side of a command),
77 changing from mandatory to optional is in general unsafe (older clients may be
78 expecting the field, and could crash if it is missing), although it can be done
79 if the only way that the optional argument will be omitted is when it is
80 triggered by the presence of a new input flag to the command that older clients
81 don't know to send. Changing from optional to mandatory is safe.
83 A structure that is used in both input and output of various commands
84 must consider the backwards compatibility constraints of both directions
87 A complex type definition can specify another complex type as its base.
88 In this case, the fields of the base type are included as top-level fields
89 of the new complex type's dictionary in the QMP wire format. An example
92 { 'type': 'BlockdevOptionsGenericFormat', 'data': { 'file': 'str' } }
93 { 'type': 'BlockdevOptionsGenericCOWFormat',
94 'base': 'BlockdevOptionsGenericFormat',
95 'data': { '*backing': 'str' } }
97 An example BlockdevOptionsGenericCOWFormat object on the wire could use
98 both fields like this:
100 { "file": "/some/place/my-image",
101 "backing": "/some/place/my-backing-file" }
103 === Enumeration types ===
105 An enumeration type is a dictionary containing a single key whose value is a
106 list of strings. An example enumeration is:
108 { 'enum': 'MyEnum', 'data': [ 'value1', 'value2', 'value3' ] }
112 Union types are used to let the user choose between several different data
113 types. A union type is defined using a dictionary as explained in the
114 following paragraphs.
117 A simple union type defines a mapping from discriminator values to data types
118 like in this example:
120 { 'type': 'FileOptions', 'data': { 'filename': 'str' } }
121 { 'type': 'Qcow2Options',
122 'data': { 'backing-file': 'str', 'lazy-refcounts': 'bool' } }
124 { 'union': 'BlockdevOptions',
125 'data': { 'file': 'FileOptions',
126 'qcow2': 'Qcow2Options' } }
128 In the QMP wire format, a simple union is represented by a dictionary that
129 contains the 'type' field as a discriminator, and a 'data' field that is of the
130 specified data type corresponding to the discriminator value:
132 { "type": "qcow2", "data" : { "backing-file": "/some/place/my-image",
133 "lazy-refcounts": true } }
136 A union definition can specify a complex type as its base. In this case, the
137 fields of the complex type are included as top-level fields of the union
138 dictionary in the QMP wire format. An example definition is:
140 { 'type': 'BlockdevCommonOptions', 'data': { 'readonly': 'bool' } }
141 { 'union': 'BlockdevOptions',
142 'base': 'BlockdevCommonOptions',
143 'data': { 'raw': 'RawOptions',
144 'qcow2': 'Qcow2Options' } }
146 And it looks like this on the wire:
150 "data" : { "backing-file": "/some/place/my-image",
151 "lazy-refcounts": true } }
154 Flat union types avoid the nesting on the wire. They are used whenever a
155 specific field of the base type is declared as the discriminator ('type' is
156 then no longer generated). The discriminator must be of enumeration type.
157 The above example can then be modified as follows:
159 { 'enum': 'BlockdevDriver', 'data': [ 'raw', 'qcow2' ] }
160 { 'type': 'BlockdevCommonOptions',
161 'data': { 'driver': 'BlockdevDriver', 'readonly': 'bool' } }
162 { 'union': 'BlockdevOptions',
163 'base': 'BlockdevCommonOptions',
164 'discriminator': 'driver',
165 'data': { 'raw': 'RawOptions',
166 'qcow2': 'Qcow2Options' } }
168 Resulting in this JSON object:
172 "backing-file": "/some/place/my-image",
173 "lazy-refcounts": true }
176 A special type of unions are anonymous unions. They don't form a dictionary in
177 the wire format but allow the direct use of different types in their place. As
178 they aren't structured, they don't have any explicit discriminator but use
179 the (QObject) data type of their value as an implicit discriminator. This means
180 that they are restricted to using only one discriminator value per QObject
181 type. For example, you cannot have two different complex types in an anonymous
182 union, or two different integer types.
184 Anonymous unions are declared using an empty dictionary as their discriminator.
185 The discriminator values never appear on the wire, they are only used in the
186 generated C code. Anonymous unions cannot have a base type.
188 { 'union': 'BlockRef',
190 'data': { 'definition': 'BlockdevOptions',
191 'reference': 'str' } }
193 This example allows using both of the following example objects:
195 { "file": "my_existing_block_device_id" }
196 { "file": { "driver": "file",
198 "filename": "/tmp/mydisk.qcow2" } }
203 Commands are defined by using a list containing three members. The first
204 member is the command name, the second member is a dictionary containing
205 arguments, and the third member is the return type.
207 An example command is:
209 { 'command': 'my-command',
210 'data': { 'arg1': 'str', '*arg2': 'str' },
215 Events are defined with the keyword 'event'. When 'data' is also specified,
216 additional info will be included in the event. Finally there will be C API
217 generated in qapi-event.h; when called by QEMU code, a message with timestamp
218 will be emitted on the wire. If timestamp is -1, it means failure to retrieve
223 { 'event': 'EVENT_C',
224 'data': { '*a': 'int', 'b': 'str' } }
226 Resulting in this JSON object:
228 { "event": "EVENT_C",
229 "data": { "b": "test string" },
230 "timestamp": { "seconds": 1267020223, "microseconds": 435656 } }
233 == Code generation ==
235 Schemas are fed into 3 scripts to generate all the code/files that, paired
236 with the core QAPI libraries, comprise everything required to take JSON
237 commands read in by a QMP/guest agent server, unmarshal the arguments into
238 the underlying C types, call into the corresponding C function, and map the
239 response back to a QMP/guest agent response to be returned to the user.
241 As an example, we'll use the following schema, which describes a single
242 complex user-defined type (which will produce a C struct, along with a list
243 node structure that can be used to chain together a list of such types in
244 case we want to accept/return a list of this type with a command), and a
245 command which takes that type as a parameter and returns the same type:
247 $ cat example-schema.json
248 { 'type': 'UserDefOne',
249 'data': { 'integer': 'int', 'string': 'str' } }
251 { 'command': 'my-command',
252 'data': {'arg1': 'UserDefOne'},
253 'returns': 'UserDefOne' }
255 { 'event': 'MY_EVENT' }
257 === scripts/qapi-types.py ===
259 Used to generate the C types defined by a schema. The following files are
262 $(prefix)qapi-types.h - C types corresponding to types defined in
263 the schema you pass in
264 $(prefix)qapi-types.c - Cleanup functions for the above C types
266 The $(prefix) is an optional parameter used as a namespace to keep the
267 generated code from one schema/code-generation separated from others so code
268 can be generated/used from multiple schemas without clobbering previously
273 $ python scripts/qapi-types.py --output-dir="qapi-generated" \
274 --prefix="example-" --input-file=example-schema.json
275 $ cat qapi-generated/example-qapi-types.c
276 [Uninteresting stuff omitted...]
278 void qapi_free_UserDefOneList(UserDefOneList *obj)
280 QapiDeallocVisitor *md;
287 md = qapi_dealloc_visitor_new();
288 v = qapi_dealloc_get_visitor(md);
289 visit_type_UserDefOneList(v, &obj, NULL, NULL);
290 qapi_dealloc_visitor_cleanup(md);
293 void qapi_free_UserDefOne(UserDefOne *obj)
295 QapiDeallocVisitor *md;
302 md = qapi_dealloc_visitor_new();
303 v = qapi_dealloc_get_visitor(md);
304 visit_type_UserDefOne(v, &obj, NULL, NULL);
305 qapi_dealloc_visitor_cleanup(md);
308 $ cat qapi-generated/example-qapi-types.h
309 [Uninteresting stuff omitted...]
311 #ifndef EXAMPLE_QAPI_TYPES_H
312 #define EXAMPLE_QAPI_TYPES_H
314 [Builtin types omitted...]
316 typedef struct UserDefOne UserDefOne;
318 typedef struct UserDefOneList
324 struct UserDefOneList *next;
327 [Functions on builtin types omitted...]
335 void qapi_free_UserDefOneList(UserDefOneList *obj);
336 void qapi_free_UserDefOne(UserDefOne *obj);
340 === scripts/qapi-visit.py ===
342 Used to generate the visitor functions used to walk through and convert
343 a QObject (as provided by QMP) to a native C data structure and
344 vice-versa, as well as the visitor function used to dealloc a complex
345 schema-defined C type.
347 The following files are generated:
349 $(prefix)qapi-visit.c: visitor function for a particular C type, used
350 to automagically convert QObjects into the
351 corresponding C type and vice-versa, as well
352 as for deallocating memory for an existing C
355 $(prefix)qapi-visit.h: declarations for previously mentioned visitor
360 $ python scripts/qapi-visit.py --output-dir="qapi-generated"
361 --prefix="example-" --input-file=example-schema.json
362 $ cat qapi-generated/example-qapi-visit.c
363 [Uninteresting stuff omitted...]
365 static void visit_type_UserDefOne_fields(Visitor *m, UserDefOne **obj, Error **errp)
368 visit_type_int(m, &(*obj)->integer, "integer", &err);
372 visit_type_str(m, &(*obj)->string, "string", &err);
378 error_propagate(errp, err);
381 void visit_type_UserDefOne(Visitor *m, UserDefOne **obj, const char *name, Error **errp)
385 visit_start_struct(m, (void **)obj, "UserDefOne", name, sizeof(UserDefOne), &err);
388 visit_type_UserDefOne_fields(m, obj, errp);
390 visit_end_struct(m, &err);
392 error_propagate(errp, err);
395 void visit_type_UserDefOneList(Visitor *m, UserDefOneList **obj, const char *name, Error **errp)
398 GenericList *i, **prev;
400 visit_start_list(m, name, &err);
405 for (prev = (GenericList **)obj;
406 !err && (i = visit_next_list(m, prev, &err)) != NULL;
408 UserDefOneList *native_i = (UserDefOneList *)i;
409 visit_type_UserDefOne(m, &native_i->value, NULL, &err);
412 error_propagate(errp, err);
414 visit_end_list(m, &err);
416 error_propagate(errp, err);
418 $ python scripts/qapi-commands.py --output-dir="qapi-generated" \
419 --prefix="example-" --input-file=example-schema.json
420 $ cat qapi-generated/example-qapi-visit.h
421 [Uninteresting stuff omitted...]
423 #ifndef EXAMPLE_QAPI_VISIT_H
424 #define EXAMPLE_QAPI_VISIT_H
426 [Visitors for builtin types omitted...]
428 void visit_type_UserDefOne(Visitor *m, UserDefOne **obj, const char *name, Error **errp);
429 void visit_type_UserDefOneList(Visitor *m, UserDefOneList **obj, const char *name, Error **errp);
433 === scripts/qapi-commands.py ===
435 Used to generate the marshaling/dispatch functions for the commands defined
436 in the schema. The following files are generated:
438 $(prefix)qmp-marshal.c: command marshal/dispatch functions for each
439 QMP command defined in the schema. Functions
440 generated by qapi-visit.py are used to
441 convert QObjects received from the wire into
442 function parameters, and uses the same
443 visitor functions to convert native C return
444 values to QObjects from transmission back
447 $(prefix)qmp-commands.h: Function prototypes for the QMP commands
448 specified in the schema.
452 $ python scripts/qapi-commands.py --output-dir="qapi-generated"
453 --prefix="example-" --input-file=example-schema.json
454 $ cat qapi-generated/example-qmp-marshal.c
455 [Uninteresting stuff omitted...]
457 static void qmp_marshal_output_my_command(UserDefOne *ret_in, QObject **ret_out, Error **errp)
459 Error *local_err = NULL;
460 QmpOutputVisitor *mo = qmp_output_visitor_new();
461 QapiDeallocVisitor *md;
464 v = qmp_output_get_visitor(mo);
465 visit_type_UserDefOne(v, &ret_in, "unused", &local_err);
469 *ret_out = qmp_output_get_qobject(mo);
472 error_propagate(errp, local_err);
473 qmp_output_visitor_cleanup(mo);
474 md = qapi_dealloc_visitor_new();
475 v = qapi_dealloc_get_visitor(md);
476 visit_type_UserDefOne(v, &ret_in, "unused", NULL);
477 qapi_dealloc_visitor_cleanup(md);
480 static void qmp_marshal_input_my_command(QDict *args, QObject **ret, Error **errp)
482 Error *local_err = NULL;
483 UserDefOne *retval = NULL;
484 QmpInputVisitor *mi = qmp_input_visitor_new_strict(QOBJECT(args));
485 QapiDeallocVisitor *md;
487 UserDefOne *arg1 = NULL;
489 v = qmp_input_get_visitor(mi);
490 visit_type_UserDefOne(v, &arg1, "arg1", &local_err);
495 retval = qmp_my_command(arg1, &local_err);
500 qmp_marshal_output_my_command(retval, ret, &local_err);
503 error_propagate(errp, local_err);
504 qmp_input_visitor_cleanup(mi);
505 md = qapi_dealloc_visitor_new();
506 v = qapi_dealloc_get_visitor(md);
507 visit_type_UserDefOne(v, &arg1, "arg1", NULL);
508 qapi_dealloc_visitor_cleanup(md);
512 static void qmp_init_marshal(void)
514 qmp_register_command("my-command", qmp_marshal_input_my_command, QCO_NO_OPTIONS);
517 qapi_init(qmp_init_marshal);
518 $ cat qapi-generated/example-qmp-commands.h
519 [Uninteresting stuff omitted...]
521 #ifndef EXAMPLE_QMP_COMMANDS_H
522 #define EXAMPLE_QMP_COMMANDS_H
524 #include "example-qapi-types.h"
525 #include "qapi/qmp/qdict.h"
526 #include "qapi/error.h"
528 UserDefOne *qmp_my_command(UserDefOne *arg1, Error **errp);
532 === scripts/qapi-event.py ===
534 Used to generate the event-related C code defined by a schema. The
535 following files are created:
537 $(prefix)qapi-event.h - Function prototypes for each event type, plus an
538 enumeration of all event names
539 $(prefix)qapi-event.c - Implementation of functions to send an event
543 $ python scripts/qapi-event.py --output-dir="qapi-generated"
544 --prefix="example-" --input-file=example-schema.json
545 $ cat qapi-generated/example-qapi-event.c
546 [Uninteresting stuff omitted...]
548 void qapi_event_send_my_event(Error **errp)
551 Error *local_err = NULL;
552 QMPEventFuncEmit emit;
553 emit = qmp_event_get_func_emit();
558 qmp = qmp_event_build_dict("MY_EVENT");
560 emit(EXAMPLE_QAPI_EVENT_MY_EVENT, qmp, &local_err);
562 error_propagate(errp, local_err);
566 const char *EXAMPLE_QAPIEvent_lookup[] = {
570 $ cat qapi-generated/example-qapi-event.h
571 [Uninteresting stuff omitted...]
573 #ifndef EXAMPLE_QAPI_EVENT_H
574 #define EXAMPLE_QAPI_EVENT_H
576 #include "qapi/error.h"
577 #include "qapi/qmp/qdict.h"
578 #include "example-qapi-types.h"
581 void qapi_event_send_my_event(Error **errp);
583 extern const char *EXAMPLE_QAPIEvent_lookup[];
584 typedef enum EXAMPLE_QAPIEvent
586 EXAMPLE_QAPI_EVENT_MY_EVENT = 0,
587 EXAMPLE_QAPI_EVENT_MAX = 1,