target-xtensa: don't generate dead code
[qemu.git] / docs / qapi-code-gen.txt
blob8313ba6af8b1ff72609b726ff5823478f846e165
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
14 guest.
16 This document will describe how the schemas, scripts, and resulting
17 code are used.
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.
39 === Includes ===
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.
49 === Complex types ===
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:
55  { 'type': 'MyType',
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
85 of use.
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
90 definition is:
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' ] }
110 === Union types ===
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:
148  { "type": "qcow2",
149    "readonly": false,
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:
170  { "driver": "qcow2",
171    "readonly": false,
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',
189    'discriminator': {},
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",
197              "readonly": false,
198              "filename": "/tmp/mydisk.qcow2" } }
201 === Commands ===
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' },
211    'returns': 'str' }
213 === Events ===
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
219 host time.
221 An example event is:
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
260 created:
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
269 created code.
271 Example:
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)
279     {
280         QapiDeallocVisitor *md;
281         Visitor *v;
283         if (!obj) {
284             return;
285         }
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);
291     }
293     void qapi_free_UserDefOne(UserDefOne *obj)
294     {
295         QapiDeallocVisitor *md;
296         Visitor *v;
298         if (!obj) {
299             return;
300         }
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);
306     }
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
319     {
320         union {
321             UserDefOne *value;
322             uint64_t padding;
323         };
324         struct UserDefOneList *next;
325     } UserDefOneList;
327 [Functions on builtin types omitted...]
329     struct UserDefOne
330     {
331         int64_t integer;
332         char *string;
333     };
335     void qapi_free_UserDefOneList(UserDefOneList *obj);
336     void qapi_free_UserDefOne(UserDefOne *obj);
338     #endif
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
353                        type
355 $(prefix)qapi-visit.h: declarations for previously mentioned visitor
356                        functions
358 Example:
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)
366     {
367         Error *err = NULL;
368         visit_type_int(m, &(*obj)->integer, "integer", &err);
369         if (err) {
370             goto out;
371         }
372         visit_type_str(m, &(*obj)->string, "string", &err);
373         if (err) {
374             goto out;
375         }
377     out:
378         error_propagate(errp, err);
379     }
381     void visit_type_UserDefOne(Visitor *m, UserDefOne **obj, const char *name, Error **errp)
382     {
383         Error *err = NULL;
385         visit_start_struct(m, (void **)obj, "UserDefOne", name, sizeof(UserDefOne), &err);
386         if (!err) {
387             if (*obj) {
388                 visit_type_UserDefOne_fields(m, obj, errp);
389             }
390             visit_end_struct(m, &err);
391         }
392         error_propagate(errp, err);
393     }
395     void visit_type_UserDefOneList(Visitor *m, UserDefOneList **obj, const char *name, Error **errp)
396     {
397         Error *err = NULL;
398         GenericList *i, **prev;
400         visit_start_list(m, name, &err);
401         if (err) {
402             goto out;
403         }
405         for (prev = (GenericList **)obj;
406              !err && (i = visit_next_list(m, prev, &err)) != NULL;
407              prev = &i) {
408             UserDefOneList *native_i = (UserDefOneList *)i;
409             visit_type_UserDefOne(m, &native_i->value, NULL, &err);
410         }
412         error_propagate(errp, err);
413         err = NULL;
414         visit_end_list(m, &err);
415     out:
416         error_propagate(errp, err);
417     }
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);
431     #endif
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
445                         over the wire.
447 $(prefix)qmp-commands.h: Function prototypes for the QMP commands
448                          specified in the schema.
450 Example:
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)
458     {
459         Error *local_err = NULL;
460         QmpOutputVisitor *mo = qmp_output_visitor_new();
461         QapiDeallocVisitor *md;
462         Visitor *v;
464         v = qmp_output_get_visitor(mo);
465         visit_type_UserDefOne(v, &ret_in, "unused", &local_err);
466         if (local_err) {
467             goto out;
468         }
469         *ret_out = qmp_output_get_qobject(mo);
471     out:
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);
478     }
480     static void qmp_marshal_input_my_command(QDict *args, QObject **ret, Error **errp)
481     {
482         Error *local_err = NULL;
483         UserDefOne *retval = NULL;
484         QmpInputVisitor *mi = qmp_input_visitor_new_strict(QOBJECT(args));
485         QapiDeallocVisitor *md;
486         Visitor *v;
487         UserDefOne *arg1 = NULL;
489         v = qmp_input_get_visitor(mi);
490         visit_type_UserDefOne(v, &arg1, "arg1", &local_err);
491         if (local_err) {
492             goto out;
493         }
495         retval = qmp_my_command(arg1, &local_err);
496         if (local_err) {
497             goto out;
498         }
500         qmp_marshal_output_my_command(retval, ret, &local_err);
502     out:
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);
509         return;
510     }
512     static void qmp_init_marshal(void)
513     {
514         qmp_register_command("my-command", qmp_marshal_input_my_command, QCO_NO_OPTIONS);
515     }
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);
530     #endif
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
541 Example:
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)
549     {
550         QDict *qmp;
551         Error *local_err = NULL;
552         QMPEventFuncEmit emit;
553         emit = qmp_event_get_func_emit();
554         if (!emit) {
555             return;
556         }
558         qmp = qmp_event_build_dict("MY_EVENT");
560         emit(EXAMPLE_QAPI_EVENT_MY_EVENT, qmp, &local_err);
562         error_propagate(errp, local_err);
563         QDECREF(qmp);
564     }
566     const char *EXAMPLE_QAPIEvent_lookup[] = {
567         "MY_EVENT",
568         NULL,
569     };
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
585     {
586         EXAMPLE_QAPI_EVENT_MY_EVENT = 0,
587         EXAMPLE_QAPI_EVENT_MAX = 1,
588     } EXAMPLE_QAPIEvent;
590     #endif