qapi: Document 'struct' metatype
[qemu.git] / docs / qapi-code-gen.txt
bloba874a6d43658e6bf09ea3b8b2d148e15e7a6f6f6
1 = How to use the QAPI code generator =
3 Copyright IBM Corp. 2011
4 Copyright (C) 2012-2015 Red Hat, Inc.
6 This work is licensed under the terms of the GNU GPL, version 2 or
7 later. See the COPYING file in the top-level directory.
9 == Introduction ==
11 QAPI is a native C API within QEMU which provides management-level
12 functionality to internal and external users. For external
13 users/processes, this interface is made available by a JSON-based wire
14 format for the QEMU Monitor Protocol (QMP) for controlling qemu, as
15 well as the QEMU Guest Agent (QGA) for communicating with the guest.
17 To map QMP and QGA interfaces to the native C QAPI implementations, a
18 JSON-based schema is used to define types and function signatures, and
19 a set of scripts is used to generate types, signatures, and
20 marshaling/dispatch code. This document will describe how the schemas,
21 scripts, and resulting code are used.
24 == QMP/Guest agent schema ==
26 A QAPI schema file is designed to be loosely based on JSON
27 (http://www.ietf.org/rfc/rfc7159.txt) with changes for quoting style
28 and the use of comments; a QAPI schema file is then parsed by a python
29 code generation program.  A valid QAPI schema consists of a series of
30 top-level expressions, with no commas between them.  Where
31 dictionaries (JSON objects) are used, they are parsed as python
32 OrderedDicts so that ordering is preserved (for predictable layout of
33 generated C structs and parameter lists).  Ordering doesn't matter
34 between top-level expressions or the keys within an expression, but
35 does matter within dictionary values for 'data' and 'returns' members
36 of a single expression.  QAPI schema input is written using 'single
37 quotes' instead of JSON's "double quotes" (in contrast, QMP uses no
38 comments, and while input accepts 'single quotes' as an extension,
39 output is strict JSON using only "double quotes").  As in JSON,
40 trailing commas are not permitted in arrays or dictionaries.  Input
41 must be ASCII (although QMP supports full Unicode strings, the QAPI
42 parser does not).  At present, there is no place where a QAPI schema
43 requires the use of JSON numbers or null.
45 Comments are allowed; anything between an unquoted # and the following
46 newline is ignored.  Although there is not yet a documentation
47 generator, a form of stylized comments has developed for consistently
48 documenting details about an expression and when it was added to the
49 schema.  The documentation is delimited between two lines of ##, then
50 the first line names the expression, an optional overview is provided,
51 then individual documentation about each member of 'data' is provided,
52 and finally, a 'Since: x.y.z' tag lists the release that introduced
53 the expression.  Optional fields are tagged with the phrase
54 '#optional', often with their default value; and extensions added
55 after the expression was first released are also given a '(since
56 x.y.z)' comment.  For example:
58     ##
59     # @BlockStats:
60     #
61     # Statistics of a virtual block device or a block backing device.
62     #
63     # @device: #optional If the stats are for a virtual block device, the name
64     #          corresponding to the virtual block device.
65     #
66     # @stats:  A @BlockDeviceStats for the device.
67     #
68     # @parent: #optional This describes the file block device if it has one.
69     #
70     # @backing: #optional This describes the backing block device if it has one.
71     #           (Since 2.0)
72     #
73     # Since: 0.14.0
74     ##
75     { 'struct': 'BlockStats',
76       'data': {'*device': 'str', 'stats': 'BlockDeviceStats',
77                '*parent': 'BlockStats',
78                '*backing': 'BlockStats'} }
80 The schema sets up a series of types, as well as commands and events
81 that will use those types.  Forward references are allowed: the parser
82 scans in two passes, where the first pass learns all type names, and
83 the second validates the schema and generates the code.  This allows
84 the definition of complex structs that can have mutually recursive
85 types, and allows for indefinite nesting of QMP that satisfies the
86 schema.  A type name should not be defined more than once.
88 There are seven top-level expressions recognized by the parser:
89 'include', 'command', 'struct', 'enum', 'union', 'alternate', and
90 'event'.  There are several groups of types: simple types (a number of
91 built-in types, such as 'int' and 'str'; as well as enumerations),
92 complex types (structs and two flavors of unions), and alternate types
93 (a choice between other types).  The 'command' and 'event' expressions
94 can refer to existing types by name, or list an anonymous type as a
95 dictionary. Listing a type name inside an array refers to a
96 single-dimension array of that type; multi-dimension arrays are not
97 directly supported (although an array of a complex struct that
98 contains an array member is possible).
100 Types, commands, and events share a common namespace.  Therefore,
101 generally speaking, type definitions should always use CamelCase for
102 user-defined type names, while built-in types are lowercase. Type
103 definitions should not end in 'Kind', as this namespace is used for
104 creating implicit C enums for visiting union types.  Command names,
105 and field names within a type, should be all lower case with words
106 separated by a hyphen.  However, some existing older commands and
107 complex types use underscore; when extending such expressions,
108 consistency is preferred over blindly avoiding underscore.  Event
109 names should be ALL_CAPS with words separated by underscore.  The
110 special string '**' appears for some commands that manually perform
111 their own type checking rather than relying on the type-safe code
112 produced by the qapi code generators.
114 Any name (command, event, type, field, or enum value) beginning with
115 "x-" is marked experimental, and may be withdrawn or changed
116 incompatibly in a future release.  Downstream vendors may add
117 extensions; such extensions should begin with a prefix matching
118 "__RFQDN_" (for the reverse-fully-qualified-domain-name of the
119 vendor), even if the rest of the name uses dash (example:
120 __com.redhat_drive-mirror).  Other than downstream extensions (with
121 leading underscore and the use of dots), all names should begin with a
122 letter, and contain only ASCII letters, digits, dash, and underscore.
123 It is okay to reuse names that match C keywords; the generator will
124 rename a field named "default" in the QAPI to "q_default" in the
125 generated C code.
127 In the rest of this document, usage lines are given for each
128 expression type, with literal strings written in lower case and
129 placeholders written in capitals.  If a literal string includes a
130 prefix of '*', that key/value pair can be omitted from the expression.
131 For example, a usage statement that includes '*base':STRUCT-NAME
132 means that an expression has an optional key 'base', which if present
133 must have a value that forms a struct name.
136 === Built-in Types ===
138 The following types are built-in to the parser:
139   'str' - arbitrary UTF-8 string
140   'int' - 64-bit signed integer (although the C code may place further
141           restrictions on acceptable range)
142   'number' - floating point number
143   'bool' - JSON value of true or false
144   'int8', 'int16', 'int32', 'int64' - like 'int', but enforce maximum
145                                       bit size
146   'uint8', 'uint16', 'uint32', 'uint64' - unsigned counterparts
147   'size' - like 'uint64', but allows scaled suffix from command line
148            visitor
151 === Includes ===
153 Usage: { 'include': STRING }
155 The QAPI schema definitions can be modularized using the 'include' directive:
157  { 'include': 'path/to/file.json' }
159 The directive is evaluated recursively, and include paths are relative to the
160 file using the directive. Multiple includes of the same file are
161 safe.  No other keys should appear in the expression, and the include
162 value should be a string.
164 As a matter of style, it is a good idea to have all files be
165 self-contained, but at the moment, nothing prevents an included file
166 from making a forward reference to a type that is only introduced by
167 an outer file.  The parser may be made stricter in the future to
168 prevent incomplete include files.
171 === Struct types ===
173 Usage: { 'struct': STRING, 'data': DICT, '*base': STRUCT-NAME }
175 A struct is a dictionary containing a single 'data' key whose
176 value is a dictionary.  This corresponds to a struct in C or an Object
177 in JSON. Each value of the 'data' dictionary must be the name of a
178 type, or a one-element array containing a type name.  An example of a
179 struct is:
181  { 'struct': 'MyType',
182    'data': { 'member1': 'str', 'member2': 'int', '*member3': 'str' } }
184 The use of '*' as a prefix to the name means the member is optional in
185 the corresponding QMP usage.
187 The default initialization value of an optional argument should not be changed
188 between versions of QEMU unless the new default maintains backward
189 compatibility to the user-visible behavior of the old default.
191 With proper documentation, this policy still allows some flexibility; for
192 example, documenting that a default of 0 picks an optimal buffer size allows
193 one release to declare the optimal size at 512 while another release declares
194 the optimal size at 4096 - the user-visible behavior is not the bytes used by
195 the buffer, but the fact that the buffer was optimal size.
197 On input structures (only mentioned in the 'data' side of a command), changing
198 from mandatory to optional is safe (older clients will supply the option, and
199 newer clients can benefit from the default); changing from optional to
200 mandatory is backwards incompatible (older clients may be omitting the option,
201 and must continue to work).
203 On output structures (only mentioned in the 'returns' side of a command),
204 changing from mandatory to optional is in general unsafe (older clients may be
205 expecting the field, and could crash if it is missing), although it can be done
206 if the only way that the optional argument will be omitted is when it is
207 triggered by the presence of a new input flag to the command that older clients
208 don't know to send.  Changing from optional to mandatory is safe.
210 A structure that is used in both input and output of various commands
211 must consider the backwards compatibility constraints of both directions
212 of use.
214 A struct definition can specify another struct as its base.
215 In this case, the fields of the base type are included as top-level fields
216 of the new struct's dictionary in the QMP wire format. An example
217 definition is:
219  { 'struct': 'BlockdevOptionsGenericFormat', 'data': { 'file': 'str' } }
220  { 'struct': 'BlockdevOptionsGenericCOWFormat',
221    'base': 'BlockdevOptionsGenericFormat',
222    'data': { '*backing': 'str' } }
224 An example BlockdevOptionsGenericCOWFormat object on the wire could use
225 both fields like this:
227  { "file": "/some/place/my-image",
228    "backing": "/some/place/my-backing-file" }
231 === Enumeration types ===
233 Usage: { 'enum': STRING, 'data': ARRAY-OF-STRING }
235 An enumeration type is a dictionary containing a single 'data' key
236 whose value is a list of strings.  An example enumeration is:
238  { 'enum': 'MyEnum', 'data': [ 'value1', 'value2', 'value3' ] }
240 Nothing prevents an empty enumeration, although it is probably not
241 useful.  The list of strings should be lower case; if an enum name
242 represents multiple words, use '-' between words.  The string 'max' is
243 not allowed as an enum value, and values should not be repeated.
245 The enumeration values are passed as strings over the QMP protocol,
246 but are encoded as C enum integral values in generated code.  While
247 the C code starts numbering at 0, it is better to use explicit
248 comparisons to enum values than implicit comparisons to 0; the C code
249 will also include a generated enum member ending in _MAX for tracking
250 the size of the enum, useful when using common functions for
251 converting between strings and enum values.  Since the wire format
252 always passes by name, it is acceptable to reorder or add new
253 enumeration members in any location without breaking QMP clients;
254 however, removing enum values would break compatibility.  For any
255 struct that has a field that will only contain a finite set of
256 string values, using an enum type for that field is better than
257 open-coding the field to be type 'str'.
260 === Union types ===
262 Usage: { 'union': STRING, 'data': DICT }
263 or:    { 'union': STRING, 'data': DICT, 'base': STRUCT-NAME,
264          'discriminator': ENUM-MEMBER-OF-BASE }
266 Union types are used to let the user choose between several different
267 variants for an object.  There are two flavors: simple (no
268 discriminator or base), flat (both discriminator and base).  A union
269 type is defined using a data dictionary as explained in the following
270 paragraphs.
272 A simple union type defines a mapping from automatic discriminator
273 values to data types like in this example:
275  { 'struct': 'FileOptions', 'data': { 'filename': 'str' } }
276  { 'struct': 'Qcow2Options',
277    'data': { 'backing-file': 'str', 'lazy-refcounts': 'bool' } }
279  { 'union': 'BlockdevOptions',
280    'data': { 'file': 'FileOptions',
281              'qcow2': 'Qcow2Options' } }
283 In the QMP wire format, a simple union is represented by a dictionary
284 that contains the 'type' field as a discriminator, and a 'data' field
285 that is of the specified data type corresponding to the discriminator
286 value, as in these examples:
288  { "type": "file", "data" : { "filename": "/some/place/my-image" } }
289  { "type": "qcow2", "data" : { "backing-file": "/some/place/my-image",
290                                "lazy-refcounts": true } }
292 The generated C code uses a struct containing a union. Additionally,
293 an implicit C enum 'NameKind' is created, corresponding to the union
294 'Name', for accessing the various branches of the union.  No branch of
295 the union can be named 'max', as this would collide with the implicit
296 enum.  The value for each branch can be of any type.
299 A flat union definition specifies a struct as its base, and
300 avoids nesting on the wire.  All branches of the union must be
301 complex types, and the top-level fields of the union dictionary on
302 the wire will be combination of fields from both the base type and the
303 appropriate branch type (when merging two dictionaries, there must be
304 no keys in common).  The 'discriminator' field must be the name of an
305 enum-typed member of the base struct.
307 The following example enhances the above simple union example by
308 adding a common field 'readonly', renaming the discriminator to
309 something more applicable, and reducing the number of {} required on
310 the wire:
312  { 'enum': 'BlockdevDriver', 'data': [ 'raw', 'qcow2' ] }
313  { 'struct': 'BlockdevCommonOptions',
314    'data': { 'driver': 'BlockdevDriver', 'readonly': 'bool' } }
315  { 'union': 'BlockdevOptions',
316    'base': 'BlockdevCommonOptions',
317    'discriminator': 'driver',
318    'data': { 'file': 'FileOptions',
319              'qcow2': 'Qcow2Options' } }
321 Resulting in these JSON objects:
323  { "driver": "file", "readonly": true,
324    "filename": "/some/place/my-image" }
325  { "driver": "qcow2", "readonly": false,
326    "backing-file": "/some/place/my-image", "lazy-refcounts": true }
328 Notice that in a flat union, the discriminator name is controlled by
329 the user, but because it must map to a base member with enum type, the
330 code generator can ensure that branches exist for all values of the
331 enum (although the order of the keys need not match the declaration of
332 the enum).  In the resulting generated C data types, a flat union is
333 represented as a struct with the base member fields included directly,
334 and then a union of structures for each branch of the struct.
336 A simple union can always be re-written as a flat union where the base
337 class has a single member named 'type', and where each branch of the
338 union has a struct with a single member named 'data'.  That is,
340  { 'union': 'Simple', 'data': { 'one': 'str', 'two': 'int' } }
342 is identical on the wire to:
344  { 'enum': 'Enum', 'data': ['one', 'two'] }
345  { 'struct': 'Base', 'data': { 'type': 'Enum' } }
346  { 'struct': 'Branch1', 'data': { 'data': 'str' } }
347  { 'struct': 'Branch2', 'data': { 'data': 'int' } }
348  { 'union': 'Flat': 'base': 'Base', 'discriminator': 'type',
349    'data': { 'one': 'Branch1', 'two': 'Branch2' } }
352 === Alternate types ===
354 Usage: { 'alternate': STRING, 'data': DICT }
356 An alternate type is one that allows a choice between two or more JSON
357 data types (string, integer, number, or object, but currently not
358 array) on the wire.  The definition is similar to a simple union type,
359 where each branch of the union names a QAPI type.  For example:
361  { 'alternate': 'BlockRef',
362    'data': { 'definition': 'BlockdevOptions',
363              'reference': 'str' } }
365 Just like for a simple union, an implicit C enum 'NameKind' is created
366 to enumerate the branches for the alternate 'Name'.
368 Unlike a union, the discriminator string is never passed on the wire
369 for QMP.  Instead, the value's JSON type serves as an implicit
370 discriminator, which in turn means that an alternate can only express
371 a choice between types represented differently in JSON.  If a branch
372 is typed as the 'bool' built-in, the alternate accepts true and false;
373 if it is typed as any of the various numeric built-ins, it accepts a
374 JSON number; if it is typed as a 'str' built-in or named enum type, it
375 accepts a JSON string; and if it is typed as a complex type (struct or
376 union), it accepts a JSON object.  Two different complex types, for
377 instance, aren't permitted, because both are represented as a JSON
378 object.
380 The example alternate declaration above allows using both of the
381 following example objects:
383  { "file": "my_existing_block_device_id" }
384  { "file": { "driver": "file",
385              "readonly": false,
386              "filename": "/tmp/mydisk.qcow2" } }
389 === Commands ===
391 Usage: { 'command': STRING, '*data': COMPLEX-TYPE-NAME-OR-DICT,
392          '*returns': TYPE-NAME-OR-DICT,
393          '*gen': false, '*success-response': false }
395 Commands are defined by using a dictionary containing several members,
396 where three members are most common.  The 'command' member is a
397 mandatory string, and determines the "execute" value passed in a QMP
398 command exchange.
400 The 'data' argument maps to the "arguments" dictionary passed in as
401 part of a QMP command.  The 'data' member is optional and defaults to
402 {} (an empty dictionary).  If present, it must be the string name of a
403 complex type, a one-element array containing the name of a complex
404 type, or a dictionary that declares an anonymous type with the same
405 semantics as a 'struct' expression, with one exception noted below when
406 'gen' is used.
408 The 'returns' member describes what will appear in the "return" field
409 of a QMP reply on successful completion of a command.  The member is
410 optional from the command declaration; if absent, the "return" field
411 will be an empty dictionary.  If 'returns' is present, it must be the
412 string name of a complex or built-in type, a one-element array
413 containing the name of a complex or built-in type, or a dictionary
414 that declares an anonymous type with the same semantics as a 'struct'
415 expression, with one exception noted below when 'gen' is used.
416 Although it is permitted to have the 'returns' member name a built-in
417 type or an array of built-in types, any command that does this cannot
418 be extended to return additional information in the future; thus, new
419 commands should strongly consider returning a dictionary-based type or
420 an array of dictionaries, even if the dictionary only contains one
421 field at the present.
423 All commands use a dictionary to report failure, with no way to
424 specify that in QAPI.  Where the error return is different than the
425 usual GenericError class in order to help the client react differently
426 to certain error conditions, it is worth documenting this in the
427 comments before the command declaration.
429 Some example commands:
431  { 'command': 'my-first-command',
432    'data': { 'arg1': 'str', '*arg2': 'str' } }
433  { 'struct': 'MyType', 'data': { '*value': 'str' } }
434  { 'command': 'my-second-command',
435    'returns': [ 'MyType' ] }
437 which would validate this QMP transaction:
439  => { "execute": "my-first-command",
440       "arguments": { "arg1": "hello" } }
441  <= { "return": { } }
442  => { "execute": "my-second-command" }
443  <= { "return": [ { "value": "one" }, { } ] }
445 In rare cases, QAPI cannot express a type-safe representation of a
446 corresponding QMP command.  In these cases, if the command expression
447 includes the key 'gen' with boolean value false, then the 'data' or
448 'returns' member that intends to bypass generated type-safety and do
449 its own manual validation should use an inline dictionary definition,
450 with a value of '**' rather than a valid type name for the keys that
451 the generated code will not validate.  Please try to avoid adding new
452 commands that rely on this, and instead use type-safe unions.  For an
453 example of bypass usage:
455  { 'command': 'netdev_add',
456    'data': {'type': 'str', 'id': 'str', '*props': '**'},
457    'gen': false }
459 Normally, the QAPI schema is used to describe synchronous exchanges,
460 where a response is expected.  But in some cases, the action of a
461 command is expected to change state in a way that a successful
462 response is not possible (although the command will still return a
463 normal dictionary error on failure).  When a successful reply is not
464 possible, the command expression should include the optional key
465 'success-response' with boolean value false.  So far, only QGA makes
466 use of this field.
469 === Events ===
471 Usage: { 'event': STRING, '*data': COMPLEX-TYPE-NAME-OR-DICT }
473 Events are defined with the keyword 'event'.  It is not allowed to
474 name an event 'MAX', since the generator also produces a C enumeration
475 of all event names with a generated _MAX value at the end.  When
476 'data' is also specified, additional info will be included in the
477 event, with similar semantics to a 'struct' expression.  Finally there
478 will be C API generated in qapi-event.h; when called by QEMU code, a
479 message with timestamp will be emitted on the wire.
481 An example event is:
483 { 'event': 'EVENT_C',
484   'data': { '*a': 'int', 'b': 'str' } }
486 Resulting in this JSON object:
488 { "event": "EVENT_C",
489   "data": { "b": "test string" },
490   "timestamp": { "seconds": 1267020223, "microseconds": 435656 } }
493 == Code generation ==
495 Schemas are fed into 3 scripts to generate all the code/files that, paired
496 with the core QAPI libraries, comprise everything required to take JSON
497 commands read in by a QMP/guest agent server, unmarshal the arguments into
498 the underlying C types, call into the corresponding C function, and map the
499 response back to a QMP/guest agent response to be returned to the user.
501 As an example, we'll use the following schema, which describes a single
502 complex user-defined type (which will produce a C struct, along with a list
503 node structure that can be used to chain together a list of such types in
504 case we want to accept/return a list of this type with a command), and a
505 command which takes that type as a parameter and returns the same type:
507     $ cat example-schema.json
508     { 'struct': 'UserDefOne',
509       'data': { 'integer': 'int', 'string': 'str' } }
511     { 'command': 'my-command',
512       'data':    {'arg1': 'UserDefOne'},
513       'returns': 'UserDefOne' }
515     { 'event': 'MY_EVENT' }
517 === scripts/qapi-types.py ===
519 Used to generate the C types defined by a schema. The following files are
520 created:
522 $(prefix)qapi-types.h - C types corresponding to types defined in
523                         the schema you pass in
524 $(prefix)qapi-types.c - Cleanup functions for the above C types
526 The $(prefix) is an optional parameter used as a namespace to keep the
527 generated code from one schema/code-generation separated from others so code
528 can be generated/used from multiple schemas without clobbering previously
529 created code.
531 Example:
533     $ python scripts/qapi-types.py --output-dir="qapi-generated" \
534     --prefix="example-" --input-file=example-schema.json
535     $ cat qapi-generated/example-qapi-types.c
536 [Uninteresting stuff omitted...]
538     void qapi_free_UserDefOneList(UserDefOneList *obj)
539     {
540         QapiDeallocVisitor *md;
541         Visitor *v;
543         if (!obj) {
544             return;
545         }
547         md = qapi_dealloc_visitor_new();
548         v = qapi_dealloc_get_visitor(md);
549         visit_type_UserDefOneList(v, &obj, NULL, NULL);
550         qapi_dealloc_visitor_cleanup(md);
551     }
553     void qapi_free_UserDefOne(UserDefOne *obj)
554     {
555         QapiDeallocVisitor *md;
556         Visitor *v;
558         if (!obj) {
559             return;
560         }
562         md = qapi_dealloc_visitor_new();
563         v = qapi_dealloc_get_visitor(md);
564         visit_type_UserDefOne(v, &obj, NULL, NULL);
565         qapi_dealloc_visitor_cleanup(md);
566     }
568     $ cat qapi-generated/example-qapi-types.h
569 [Uninteresting stuff omitted...]
571     #ifndef EXAMPLE_QAPI_TYPES_H
572     #define EXAMPLE_QAPI_TYPES_H
574 [Built-in types omitted...]
576     typedef struct UserDefOne UserDefOne;
578     typedef struct UserDefOneList
579     {
580         union {
581             UserDefOne *value;
582             uint64_t padding;
583         };
584         struct UserDefOneList *next;
585     } UserDefOneList;
587 [Functions on built-in types omitted...]
589     struct UserDefOne
590     {
591         int64_t integer;
592         char *string;
593     };
595     void qapi_free_UserDefOneList(UserDefOneList *obj);
596     void qapi_free_UserDefOne(UserDefOne *obj);
598     #endif
600 === scripts/qapi-visit.py ===
602 Used to generate the visitor functions used to walk through and convert
603 a QObject (as provided by QMP) to a native C data structure and
604 vice-versa, as well as the visitor function used to dealloc a complex
605 schema-defined C type.
607 The following files are generated:
609 $(prefix)qapi-visit.c: visitor function for a particular C type, used
610                        to automagically convert QObjects into the
611                        corresponding C type and vice-versa, as well
612                        as for deallocating memory for an existing C
613                        type
615 $(prefix)qapi-visit.h: declarations for previously mentioned visitor
616                        functions
618 Example:
620     $ python scripts/qapi-visit.py --output-dir="qapi-generated"
621     --prefix="example-" --input-file=example-schema.json
622     $ cat qapi-generated/example-qapi-visit.c
623 [Uninteresting stuff omitted...]
625     static void visit_type_UserDefOne_fields(Visitor *m, UserDefOne **obj, Error **errp)
626     {
627         Error *err = NULL;
628         visit_type_int(m, &(*obj)->integer, "integer", &err);
629         if (err) {
630             goto out;
631         }
632         visit_type_str(m, &(*obj)->string, "string", &err);
633         if (err) {
634             goto out;
635         }
637     out:
638         error_propagate(errp, err);
639     }
641     void visit_type_UserDefOne(Visitor *m, UserDefOne **obj, const char *name, Error **errp)
642     {
643         Error *err = NULL;
645         visit_start_struct(m, (void **)obj, "UserDefOne", name, sizeof(UserDefOne), &err);
646         if (!err) {
647             if (*obj) {
648                 visit_type_UserDefOne_fields(m, obj, errp);
649             }
650             visit_end_struct(m, &err);
651         }
652         error_propagate(errp, err);
653     }
655     void visit_type_UserDefOneList(Visitor *m, UserDefOneList **obj, const char *name, Error **errp)
656     {
657         Error *err = NULL;
658         GenericList *i, **prev;
660         visit_start_list(m, name, &err);
661         if (err) {
662             goto out;
663         }
665         for (prev = (GenericList **)obj;
666              !err && (i = visit_next_list(m, prev, &err)) != NULL;
667              prev = &i) {
668             UserDefOneList *native_i = (UserDefOneList *)i;
669             visit_type_UserDefOne(m, &native_i->value, NULL, &err);
670         }
672         error_propagate(errp, err);
673         err = NULL;
674         visit_end_list(m, &err);
675     out:
676         error_propagate(errp, err);
677     }
678     $ python scripts/qapi-commands.py --output-dir="qapi-generated" \
679     --prefix="example-" --input-file=example-schema.json
680     $ cat qapi-generated/example-qapi-visit.h
681 [Uninteresting stuff omitted...]
683     #ifndef EXAMPLE_QAPI_VISIT_H
684     #define EXAMPLE_QAPI_VISIT_H
686 [Visitors for built-in types omitted...]
688     void visit_type_UserDefOne(Visitor *m, UserDefOne **obj, const char *name, Error **errp);
689     void visit_type_UserDefOneList(Visitor *m, UserDefOneList **obj, const char *name, Error **errp);
691     #endif
693 === scripts/qapi-commands.py ===
695 Used to generate the marshaling/dispatch functions for the commands defined
696 in the schema. The following files are generated:
698 $(prefix)qmp-marshal.c: command marshal/dispatch functions for each
699                         QMP command defined in the schema. Functions
700                         generated by qapi-visit.py are used to
701                         convert QObjects received from the wire into
702                         function parameters, and uses the same
703                         visitor functions to convert native C return
704                         values to QObjects from transmission back
705                         over the wire.
707 $(prefix)qmp-commands.h: Function prototypes for the QMP commands
708                          specified in the schema.
710 Example:
712     $ python scripts/qapi-commands.py --output-dir="qapi-generated"
713     --prefix="example-" --input-file=example-schema.json
714     $ cat qapi-generated/example-qmp-marshal.c
715 [Uninteresting stuff omitted...]
717     static void qmp_marshal_output_my_command(UserDefOne *ret_in, QObject **ret_out, Error **errp)
718     {
719         Error *local_err = NULL;
720         QmpOutputVisitor *mo = qmp_output_visitor_new();
721         QapiDeallocVisitor *md;
722         Visitor *v;
724         v = qmp_output_get_visitor(mo);
725         visit_type_UserDefOne(v, &ret_in, "unused", &local_err);
726         if (local_err) {
727             goto out;
728         }
729         *ret_out = qmp_output_get_qobject(mo);
731     out:
732         error_propagate(errp, local_err);
733         qmp_output_visitor_cleanup(mo);
734         md = qapi_dealloc_visitor_new();
735         v = qapi_dealloc_get_visitor(md);
736         visit_type_UserDefOne(v, &ret_in, "unused", NULL);
737         qapi_dealloc_visitor_cleanup(md);
738     }
740     static void qmp_marshal_input_my_command(QDict *args, QObject **ret, Error **errp)
741     {
742         Error *local_err = NULL;
743         UserDefOne *retval = NULL;
744         QmpInputVisitor *mi = qmp_input_visitor_new_strict(QOBJECT(args));
745         QapiDeallocVisitor *md;
746         Visitor *v;
747         UserDefOne *arg1 = NULL;
749         v = qmp_input_get_visitor(mi);
750         visit_type_UserDefOne(v, &arg1, "arg1", &local_err);
751         if (local_err) {
752             goto out;
753         }
755         retval = qmp_my_command(arg1, &local_err);
756         if (local_err) {
757             goto out;
758         }
760         qmp_marshal_output_my_command(retval, ret, &local_err);
762     out:
763         error_propagate(errp, local_err);
764         qmp_input_visitor_cleanup(mi);
765         md = qapi_dealloc_visitor_new();
766         v = qapi_dealloc_get_visitor(md);
767         visit_type_UserDefOne(v, &arg1, "arg1", NULL);
768         qapi_dealloc_visitor_cleanup(md);
769         return;
770     }
772     static void qmp_init_marshal(void)
773     {
774         qmp_register_command("my-command", qmp_marshal_input_my_command, QCO_NO_OPTIONS);
775     }
777     qapi_init(qmp_init_marshal);
778     $ cat qapi-generated/example-qmp-commands.h
779 [Uninteresting stuff omitted...]
781     #ifndef EXAMPLE_QMP_COMMANDS_H
782     #define EXAMPLE_QMP_COMMANDS_H
784     #include "example-qapi-types.h"
785     #include "qapi/qmp/qdict.h"
786     #include "qapi/error.h"
788     UserDefOne *qmp_my_command(UserDefOne *arg1, Error **errp);
790     #endif
792 === scripts/qapi-event.py ===
794 Used to generate the event-related C code defined by a schema. The
795 following files are created:
797 $(prefix)qapi-event.h - Function prototypes for each event type, plus an
798                         enumeration of all event names
799 $(prefix)qapi-event.c - Implementation of functions to send an event
801 Example:
803     $ python scripts/qapi-event.py --output-dir="qapi-generated"
804     --prefix="example-" --input-file=example-schema.json
805     $ cat qapi-generated/example-qapi-event.c
806 [Uninteresting stuff omitted...]
808     void qapi_event_send_my_event(Error **errp)
809     {
810         QDict *qmp;
811         Error *local_err = NULL;
812         QMPEventFuncEmit emit;
813         emit = qmp_event_get_func_emit();
814         if (!emit) {
815             return;
816         }
818         qmp = qmp_event_build_dict("MY_EVENT");
820         emit(EXAMPLE_QAPI_EVENT_MY_EVENT, qmp, &local_err);
822         error_propagate(errp, local_err);
823         QDECREF(qmp);
824     }
826     const char *EXAMPLE_QAPIEvent_lookup[] = {
827         "MY_EVENT",
828         NULL,
829     };
830     $ cat qapi-generated/example-qapi-event.h
831 [Uninteresting stuff omitted...]
833     #ifndef EXAMPLE_QAPI_EVENT_H
834     #define EXAMPLE_QAPI_EVENT_H
836     #include "qapi/error.h"
837     #include "qapi/qmp/qdict.h"
838     #include "example-qapi-types.h"
841     void qapi_event_send_my_event(Error **errp);
843     extern const char *EXAMPLE_QAPIEvent_lookup[];
844     typedef enum EXAMPLE_QAPIEvent
845     {
846         EXAMPLE_QAPI_EVENT_MY_EVENT = 0,
847         EXAMPLE_QAPI_EVENT_MAX = 1,
848     } EXAMPLE_QAPIEvent;
850     #endif