qapi: Flat unions with arbitrary discriminator
[qemu/kevin.git] / docs / qapi-code-gen.txt
blob11f19cfa5f263b48a64173c7dc3d217fab289254
1 = How to use the QAPI code generator =
3 * Note: as of this writing, QMP does not use QAPI. Eventually QMP
4 commands will be converted to use QAPI internally. The following
5 information describes QMP/QAPI as it will exist after the
6 conversion.
8 QAPI is a native C API within QEMU which provides management-level
9 functionality to internal/external users. For external
10 users/processes, this interface is made available by a JSON-based
11 QEMU Monitor protocol that is provided by the QMP server.
13 To map QMP-defined interfaces to the native C QAPI implementations,
14 a JSON-based schema is used to define types and function
15 signatures, and a set of scripts is used to generate types/signatures,
16 and marshaling/dispatch code. The QEMU Guest Agent also uses these
17 scripts, paired with a separate schema, to generate
18 marshaling/dispatch code for the guest agent server running in the
19 guest.
21 This document will describe how the schemas, scripts, and resulting
22 code is used.
25 == QMP/Guest agent schema ==
27 This file defines the types, commands, and events used by QMP.  It should
28 fully describe the interface used by QMP.
30 This file is designed to be loosely based on JSON although it's technically
31 executable Python.  While dictionaries are used, they are parsed as
32 OrderedDicts so that ordering is preserved.
34 There are two basic syntaxes used, type definitions and command definitions.
36 The first syntax defines a type and is represented by a dictionary.  There are
37 three kinds of user-defined types that are supported: complex types,
38 enumeration types and union types.
40 Generally speaking, types definitions should always use CamelCase for the type
41 names. Command names should be all lower case with words separated by a hyphen.
43 === Complex types ===
45 A complex type is a dictionary containing a single key whose value is a
46 dictionary.  This corresponds to a struct in C or an Object in JSON.  An
47 example of a complex type is:
49  { 'type': 'MyType',
50    'data': { 'member1': 'str', 'member2': 'int', '*member3': 'str' } }
52 The use of '*' as a prefix to the name means the member is optional.  Optional
53 members should always be added to the end of the dictionary to preserve
54 backwards compatibility.
56 === Enumeration types ===
58 An enumeration type is a dictionary containing a single key whose value is a
59 list of strings.  An example enumeration is:
61  { 'enum': 'MyEnum', 'data': [ 'value1', 'value2', 'value3' ] }
63 === Union types ===
65 Union types are used to let the user choose between several different data
66 types.  A union type is defined using a dictionary as explained in the
67 following paragraphs.
70 A simple union type defines a mapping from discriminator values to data types
71 like in this example:
73  { 'type': 'FileOptions', 'data': { 'filename': 'str' } }
74  { 'type': 'Qcow2Options',
75    'data': { 'backing-file': 'str', 'lazy-refcounts': 'bool' } }
77  { 'union': 'BlockdevOptions',
78    'data': { 'file': 'FileOptions',
79              'qcow2': 'Qcow2Options' } }
81 In the QMP wire format, a simple union is represented by a dictionary that
82 contains the 'type' field as a discriminator, and a 'data' field that is of the
83 specified data type corresponding to the discriminator value:
85  { "type": "qcow2", "data" : { "backing-file": "/some/place/my-image",
86                                "lazy-refcounts": true } }
89 A union definition can specify a complex type as its base. In this case, the
90 fields of the complex type are included as top-level fields of the union
91 dictionary in the QMP wire format. An example definition is:
93  { 'type': 'BlockdevCommonOptions', 'data': { 'readonly': 'bool' } }
94  { 'union': 'BlockdevOptions',
95    'base': 'BlockdevCommonOptions',
96    'data': { 'raw': 'RawOptions',
97              'qcow2': 'Qcow2Options' } }
99 And it looks like this on the wire:
101  { "type": "qcow2",
102    "readonly": false,
103    "data" : { "backing-file": "/some/place/my-image",
104               "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 always be a string field.
110 The above example can then be modified as follows:
112  { 'type': 'BlockdevCommonOptions',
113    'data': { 'driver': 'str', 'readonly': 'bool' } }
114  { 'union': 'BlockdevOptions',
115    'base': 'BlockdevCommonOptions',
116    'discriminator': 'driver',
117    'data': { 'raw': 'RawOptions',
118              'qcow2': 'Qcow2Options' } }
120 Resulting in this JSON object:
122  { "driver": "qcow2",
123    "readonly": false,
124    "backing-file": "/some/place/my-image",
125    "lazy-refcounts": true }
128 === Commands ===
130 Commands are defined by using a list containing three members.  The first
131 member is the command name, the second member is a dictionary containing
132 arguments, and the third member is the return type.
134 An example command is:
136  { 'command': 'my-command',
137    'data': { 'arg1': 'str', '*arg2': 'str' },
138    'returns': 'str' }
141 == Code generation ==
143 Schemas are fed into 3 scripts to generate all the code/files that, paired
144 with the core QAPI libraries, comprise everything required to take JSON
145 commands read in by a QMP/guest agent server, unmarshal the arguments into
146 the underlying C types, call into the corresponding C function, and map the
147 response back to a QMP/guest agent response to be returned to the user.
149 As an example, we'll use the following schema, which describes a single
150 complex user-defined type (which will produce a C struct, along with a list
151 node structure that can be used to chain together a list of such types in
152 case we want to accept/return a list of this type with a command), and a
153 command which takes that type as a parameter and returns the same type:
155     mdroth@illuin:~/w/qemu2.git$ cat example-schema.json
156     { 'type': 'UserDefOne',
157       'data': { 'integer': 'int', 'string': 'str' } }
159     { 'command': 'my-command',
160       'data':    {'arg1': 'UserDefOne'},
161       'returns': 'UserDefOne' }
162     mdroth@illuin:~/w/qemu2.git$
164 === scripts/qapi-types.py ===
166 Used to generate the C types defined by a schema. The following files are
167 created:
169 $(prefix)qapi-types.h - C types corresponding to types defined in
170                         the schema you pass in
171 $(prefix)qapi-types.c - Cleanup functions for the above C types
173 The $(prefix) is an optional parameter used as a namespace to keep the
174 generated code from one schema/code-generation separated from others so code
175 can be generated/used from multiple schemas without clobbering previously
176 created code.
178 Example:
180     mdroth@illuin:~/w/qemu2.git$ python scripts/qapi-types.py \
181       --output-dir="qapi-generated" --prefix="example-" < example-schema.json
182     mdroth@illuin:~/w/qemu2.git$ cat qapi-generated/example-qapi-types.c
183     /* AUTOMATICALLY GENERATED, DO NOT MODIFY */
185     #include "qapi/qapi-dealloc-visitor.h"
186     #include "example-qapi-types.h"
187     #include "example-qapi-visit.h"
189     void qapi_free_UserDefOne(UserDefOne * obj)
190     {
191         QapiDeallocVisitor *md;
192         Visitor *v;
194         if (!obj) {
195             return;
196         }
198         md = qapi_dealloc_visitor_new();
199         v = qapi_dealloc_get_visitor(md);
200         visit_type_UserDefOne(v, &obj, NULL, NULL);
201         qapi_dealloc_visitor_cleanup(md);
202     }
204     mdroth@illuin:~/w/qemu2.git$ cat qapi-generated/example-qapi-types.h
205     /* AUTOMATICALLY GENERATED, DO NOT MODIFY */
206     #ifndef QAPI_GENERATED_EXAMPLE_QAPI_TYPES
207     #define QAPI_GENERATED_EXAMPLE_QAPI_TYPES
209     #include "qapi/qapi-types-core.h"
211     typedef struct UserDefOne UserDefOne;
213     typedef struct UserDefOneList
214     {
215         UserDefOne *value;
216         struct UserDefOneList *next;
217     } UserDefOneList;
219     struct UserDefOne
220     {
221         int64_t integer;
222         char * string;
223     };
225     void qapi_free_UserDefOne(UserDefOne * obj);
227     #endif
230 === scripts/qapi-visit.py ===
232 Used to generate the visitor functions used to walk through and convert
233 a QObject (as provided by QMP) to a native C data structure and
234 vice-versa, as well as the visitor function used to dealloc a complex
235 schema-defined C type.
237 The following files are generated:
239 $(prefix)qapi-visit.c: visitor function for a particular C type, used
240                        to automagically convert QObjects into the
241                        corresponding C type and vice-versa, as well
242                        as for deallocating memory for an existing C
243                        type
245 $(prefix)qapi-visit.h: declarations for previously mentioned visitor
246                        functions
248 Example:
250     mdroth@illuin:~/w/qemu2.git$ python scripts/qapi-visit.py \
251         --output-dir="qapi-generated" --prefix="example-" < example-schema.json
252     mdroth@illuin:~/w/qemu2.git$ cat qapi-generated/example-qapi-visit.c
253     /* THIS FILE IS AUTOMATICALLY GENERATED, DO NOT MODIFY */
255     #include "example-qapi-visit.h"
257     void visit_type_UserDefOne(Visitor *m, UserDefOne ** obj, const char *name, Error **errp)
258     {
259         visit_start_struct(m, (void **)obj, "UserDefOne", name, sizeof(UserDefOne), errp);
260         visit_type_int(m, (obj && *obj) ? &(*obj)->integer : NULL, "integer", errp);
261         visit_type_str(m, (obj && *obj) ? &(*obj)->string : NULL, "string", errp);
262         visit_end_struct(m, errp);
263     }
265     void visit_type_UserDefOneList(Visitor *m, UserDefOneList ** obj, const char *name, Error **errp)
266     {
267         GenericList *i, **prev = (GenericList **)obj;
269         visit_start_list(m, name, errp);
271         for (; (i = visit_next_list(m, prev, errp)) != NULL; prev = &i) {
272             UserDefOneList *native_i = (UserDefOneList *)i;
273             visit_type_UserDefOne(m, &native_i->value, NULL, errp);
274         }
276         visit_end_list(m, errp);
277     }
278     mdroth@illuin:~/w/qemu2.git$ cat qapi-generated/example-qapi-visit.h
279     /* THIS FILE IS AUTOMATICALLY GENERATED, DO NOT MODIFY */
281     #ifndef QAPI_GENERATED_EXAMPLE_QAPI_VISIT
282     #define QAPI_GENERATED_EXAMPLE_QAPI_VISIT
284     #include "qapi/qapi-visit-core.h"
285     #include "example-qapi-types.h"
287     void visit_type_UserDefOne(Visitor *m, UserDefOne ** obj, const char *name, Error **errp);
288     void visit_type_UserDefOneList(Visitor *m, UserDefOneList ** obj, const char *name, Error **errp);
290     #endif
291     mdroth@illuin:~/w/qemu2.git$
293 (The actual structure of the visit_type_* functions is a bit more complex
294 in order to propagate errors correctly and avoid leaking memory).
296 === scripts/qapi-commands.py ===
298 Used to generate the marshaling/dispatch functions for the commands defined
299 in the schema. The following files are generated:
301 $(prefix)qmp-marshal.c: command marshal/dispatch functions for each
302                         QMP command defined in the schema. Functions
303                         generated by qapi-visit.py are used to
304                         convert QObjects received from the wire into
305                         function parameters, and uses the same
306                         visitor functions to convert native C return
307                         values to QObjects from transmission back
308                         over the wire.
310 $(prefix)qmp-commands.h: Function prototypes for the QMP commands
311                          specified in the schema.
313 Example:
315     mdroth@illuin:~/w/qemu2.git$ cat qapi-generated/example-qmp-marshal.c
316     /* THIS FILE IS AUTOMATICALLY GENERATED, DO NOT MODIFY */
318     #include "qemu-objects.h"
319     #include "qapi/qmp-core.h"
320     #include "qapi/qapi-visit-core.h"
321     #include "qapi/qmp-output-visitor.h"
322     #include "qapi/qmp-input-visitor.h"
323     #include "qapi/qapi-dealloc-visitor.h"
324     #include "example-qapi-types.h"
325     #include "example-qapi-visit.h"
327     #include "example-qmp-commands.h"
328     static void qmp_marshal_output_my_command(UserDefOne * ret_in, QObject **ret_out, Error **errp)
329     {
330         QapiDeallocVisitor *md = qapi_dealloc_visitor_new();
331         QmpOutputVisitor *mo = qmp_output_visitor_new();
332         Visitor *v;
334         v = qmp_output_get_visitor(mo);
335         visit_type_UserDefOne(v, &ret_in, "unused", errp);
336         v = qapi_dealloc_get_visitor(md);
337         visit_type_UserDefOne(v, &ret_in, "unused", errp);
338         qapi_dealloc_visitor_cleanup(md);
341         *ret_out = qmp_output_get_qobject(mo);
342     }
344     static void qmp_marshal_input_my_command(QmpState *qmp__sess, QDict *args, QObject **ret, Error **errp)
345     {
346         UserDefOne * retval = NULL;
347         QmpInputVisitor *mi;
348         QapiDeallocVisitor *md;
349         Visitor *v;
350         UserDefOne * arg1 = NULL;
352         mi = qmp_input_visitor_new(QOBJECT(args));
353         v = qmp_input_get_visitor(mi);
354         visit_type_UserDefOne(v, &arg1, "arg1", errp);
356         if (error_is_set(errp)) {
357             goto out;
358         }
359         retval = qmp_my_command(arg1, errp);
360         qmp_marshal_output_my_command(retval, ret, errp);
362     out:
363         md = qapi_dealloc_visitor_new();
364         v = qapi_dealloc_get_visitor(md);
365         visit_type_UserDefOne(v, &arg1, "arg1", errp);
366         qapi_dealloc_visitor_cleanup(md);
367         return;
368     }
370     static void qmp_init_marshal(void)
371     {
372         qmp_register_command("my-command", qmp_marshal_input_my_command);
373     }
375     qapi_init(qmp_init_marshal);
376     mdroth@illuin:~/w/qemu2.git$ cat qapi-generated/example-qmp-commands.h
377     /* THIS FILE IS AUTOMATICALLY GENERATED, DO NOT MODIFY */
379     #ifndef QAPI_GENERATED_EXAMPLE_QMP_COMMANDS
380     #define QAPI_GENERATED_EXAMPLE_QMP_COMMANDS
382     #include "example-qapi-types.h"
383     #include "error.h"
385     UserDefOne * qmp_my_command(UserDefOne * arg1, Error **errp);
387     #endif
388     mdroth@illuin:~/w/qemu2.git$