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.
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:
61 # Statistics of a virtual block device or a block backing device.
63 # @device: #optional If the stats are for a virtual block device, the name
64 # corresponding to the virtual block device.
66 # @stats: A @BlockDeviceStats for the device.
68 # @parent: #optional This describes the file block device if it has one.
70 # @backing: #optional This describes the backing block device if it has one.
75 { 'type': '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 six top-level expressions recognized by the parser:
89 'include', 'command', 'type', 'enum', 'union', and 'event'. There are
90 several built-in types, such as 'int' and 'str'; additionally, the
91 top-level expressions can define complex types, enumeration types, and
92 several flavors of union types. The 'command' and 'event' expressions
93 can refer to existing types by name, or list an anonymous type as a
94 dictionary. Listing a type name inside an array refers to a
95 single-dimension array of that type; multi-dimension arrays are not
96 directly supported (although an array of a complex struct that
97 contains an array member is possible).
99 Types, commands, and events share a common namespace. Therefore,
100 generally speaking, type definitions should always use CamelCase for
101 user-defined type names, while built-in types are lowercase. Type
102 definitions should not end in 'Kind', as this namespace is used for
103 creating implicit C enums for visiting union types. Command names,
104 and field names within a type, should be all lower case with words
105 separated by a hyphen. However, some existing older commands and
106 complex types use underscore; when extending such expressions,
107 consistency is preferred over blindly avoiding underscore. Event
108 names should be ALL_CAPS with words separated by underscore. The
109 special string '**' appears for some commands that manually perform
110 their own type checking rather than relying on the type-safe code
111 produced by the qapi code generators.
113 Any name (command, event, type, field, or enum value) beginning with
114 "x-" is marked experimental, and may be withdrawn or changed
115 incompatibly in a future release. Downstream vendors may add
116 extensions; such extensions should begin with a prefix matching
117 "__RFQDN_" (for the reverse-fully-qualified-domain-name of the
118 vendor), even if the rest of the name uses dash (example:
119 __com.redhat_drive-mirror). Other than downstream extensions (with
120 leading underscore and the use of dots), all names should begin with a
121 letter, and contain only ASCII letters, digits, dash, and underscore.
122 It is okay to reuse names that match C keywords; the generator will
123 rename a field named "default" in the QAPI to "q_default" in the
126 In the rest of this document, usage lines are given for each
127 expression type, with literal strings written in lower case and
128 placeholders written in capitals. If a literal string includes a
129 prefix of '*', that key/value pair can be omitted from the expression.
130 For example, a usage statement that includes '*base':COMPLEX-TYPE-NAME
131 means that an expression has an optional key 'base', which if present
132 must have a value that forms a complex type name.
135 === Built-in Types ===
137 The following types are built-in to the parser:
138 'str' - arbitrary UTF-8 string
139 'int' - 64-bit signed integer (although the C code may place further
140 restrictions on acceptable range)
141 'number' - floating point number
142 'bool' - JSON value of true or false
143 'int8', 'int16', 'int32', 'int64' - like 'int', but enforce maximum
145 'uint8', 'uint16', 'uint32', 'uint64' - unsigned counterparts
146 'size' - like 'uint64', but allows scaled suffix from command line
152 Usage: { 'include': STRING }
154 The QAPI schema definitions can be modularized using the 'include' directive:
156 { 'include': 'path/to/file.json' }
158 The directive is evaluated recursively, and include paths are relative to the
159 file using the directive. Multiple includes of the same file are
160 safe. No other keys should appear in the expression, and the include
161 value should be a string.
163 As a matter of style, it is a good idea to have all files be
164 self-contained, but at the moment, nothing prevents an included file
165 from making a forward reference to a type that is only introduced by
166 an outer file. The parser may be made stricter in the future to
167 prevent incomplete include files.
170 === Complex types ===
172 Usage: { 'type': STRING, 'data': DICT, '*base': COMPLEX-TYPE-NAME }
174 A complex type is a dictionary containing a single 'data' key whose
175 value is a dictionary. This corresponds to a struct in C or an Object
176 in JSON. Each value of the 'data' dictionary must be the name of a
177 type, or a one-element array containing a type name. An example of a
181 'data': { 'member1': 'str', 'member2': 'int', '*member3': 'str' } }
183 The use of '*' as a prefix to the name means the member is optional in
184 the corresponding QMP usage.
186 The default initialization value of an optional argument should not be changed
187 between versions of QEMU unless the new default maintains backward
188 compatibility to the user-visible behavior of the old default.
190 With proper documentation, this policy still allows some flexibility; for
191 example, documenting that a default of 0 picks an optimal buffer size allows
192 one release to declare the optimal size at 512 while another release declares
193 the optimal size at 4096 - the user-visible behavior is not the bytes used by
194 the buffer, but the fact that the buffer was optimal size.
196 On input structures (only mentioned in the 'data' side of a command), changing
197 from mandatory to optional is safe (older clients will supply the option, and
198 newer clients can benefit from the default); changing from optional to
199 mandatory is backwards incompatible (older clients may be omitting the option,
200 and must continue to work).
202 On output structures (only mentioned in the 'returns' side of a command),
203 changing from mandatory to optional is in general unsafe (older clients may be
204 expecting the field, and could crash if it is missing), although it can be done
205 if the only way that the optional argument will be omitted is when it is
206 triggered by the presence of a new input flag to the command that older clients
207 don't know to send. Changing from optional to mandatory is safe.
209 A structure that is used in both input and output of various commands
210 must consider the backwards compatibility constraints of both directions
213 A complex type definition can specify another complex type as its base.
214 In this case, the fields of the base type are included as top-level fields
215 of the new complex type's dictionary in the QMP wire format. An example
218 { 'type': 'BlockdevOptionsGenericFormat', 'data': { 'file': 'str' } }
219 { 'type': 'BlockdevOptionsGenericCOWFormat',
220 'base': 'BlockdevOptionsGenericFormat',
221 'data': { '*backing': 'str' } }
223 An example BlockdevOptionsGenericCOWFormat object on the wire could use
224 both fields like this:
226 { "file": "/some/place/my-image",
227 "backing": "/some/place/my-backing-file" }
230 === Enumeration types ===
232 Usage: { 'enum': STRING, 'data': ARRAY-OF-STRING }
234 An enumeration type is a dictionary containing a single 'data' key
235 whose value is a list of strings. An example enumeration is:
237 { 'enum': 'MyEnum', 'data': [ 'value1', 'value2', 'value3' ] }
239 Nothing prevents an empty enumeration, although it is probably not
240 useful. The list of strings should be lower case; if an enum name
241 represents multiple words, use '-' between words. The string 'max' is
242 not allowed as an enum value, and values should not be repeated.
244 The enumeration values are passed as strings over the QMP protocol,
245 but are encoded as C enum integral values in generated code. While
246 the C code starts numbering at 0, it is better to use explicit
247 comparisons to enum values than implicit comparisons to 0; the C code
248 will also include a generated enum member ending in _MAX for tracking
249 the size of the enum, useful when using common functions for
250 converting between strings and enum values. Since the wire format
251 always passes by name, it is acceptable to reorder or add new
252 enumeration members in any location without breaking QMP clients;
253 however, removing enum values would break compatibility. For any
254 complex type that has a field that will only contain a finite set of
255 string values, using an enum type for that field is better than
256 open-coding the field to be type 'str'.
261 Usage: { 'union': STRING, 'data': DICT }
262 or: { 'union': STRING, 'data': DICT, 'base': COMPLEX-TYPE-NAME,
263 'discriminator': ENUM-MEMBER-OF-BASE }
264 or: { 'union': STRING, 'data': DICT, 'discriminator': {} }
266 Union types are used to let the user choose between several different
267 variants for an object. There are three flavors: simple (no
268 discriminator or base), flat (both base and discriminator are
269 strings), and anonymous (discriminator is an empty dictionary). A
270 union type is defined using a data dictionary as explained in the
271 following paragraphs.
273 A simple union type defines a mapping from automatic discriminator
274 values to data types like in this example:
276 { 'type': 'FileOptions', 'data': { 'filename': 'str' } }
277 { 'type': 'Qcow2Options',
278 'data': { 'backing-file': 'str', 'lazy-refcounts': 'bool' } }
280 { 'union': 'BlockdevOptions',
281 'data': { 'file': 'FileOptions',
282 'qcow2': 'Qcow2Options' } }
284 In the QMP wire format, a simple union is represented by a dictionary
285 that contains the 'type' field as a discriminator, and a 'data' field
286 that is of the specified data type corresponding to the discriminator
287 value, as in these examples:
289 { "type": "file", "data" : { "filename": "/some/place/my-image" } }
290 { "type": "qcow2", "data" : { "backing-file": "/some/place/my-image",
291 "lazy-refcounts": true } }
293 The generated C code uses a struct containing a union. Additionally,
294 an implicit C enum 'NameKind' is created, corresponding to the union
295 'Name', for accessing the various branches of the union. No branch of
296 the union can be named 'max', as this would collide with the implicit
297 enum. The value for each branch can be of any type.
300 A flat union definition specifies a complex type as its base, and
301 avoids nesting on the wire. All branches of the union must be
302 complex types, and the top-level fields of the union dictionary on
303 the wire will be combination of fields from both the base type and the
304 appropriate branch type (when merging two dictionaries, there must be
305 no keys in common). The 'discriminator' field must be the name of an
306 enum-typed member of the base type.
308 The following example enhances the above simple union example by
309 adding a common field 'readonly', renaming the discriminator to
310 something more applicable, and reducing the number of {} required on
313 { 'enum': 'BlockdevDriver', 'data': [ 'raw', 'qcow2' ] }
314 { 'type': 'BlockdevCommonOptions',
315 'data': { 'driver': 'BlockdevDriver', 'readonly': 'bool' } }
316 { 'union': 'BlockdevOptions',
317 'base': 'BlockdevCommonOptions',
318 'discriminator': 'driver',
319 'data': { 'file': 'FileOptions',
320 'qcow2': 'Qcow2Options' } }
322 Resulting in these JSON objects:
324 { "driver": "file", "readonly": true,
325 "filename": "/some/place/my-image" }
326 { "driver": "qcow2", "readonly": false,
327 "backing-file": "/some/place/my-image", "lazy-refcounts": true }
329 Notice that in a flat union, the discriminator name is controlled by
330 the user, but because it must map to a base member with enum type, the
331 code generator can ensure that branches exist for all values of the
332 enum (although the order of the keys need not match the declaration of
333 the enum). In the resulting generated C data types, a flat union is
334 represented as a struct with the base member fields included directly,
335 and then a union of structures for each branch of the struct.
337 A simple union can always be re-written as a flat union where the base
338 class has a single member named 'type', and where each branch of the
339 union has a complex type with a single member named 'data'. That is,
341 { 'union': 'Simple', 'data': { 'one': 'str', 'two': 'int' } }
343 is identical on the wire to:
345 { 'enum': 'Enum', 'data': ['one', 'two'] }
346 { 'type': 'Base', 'data': { 'type': 'Enum' } }
347 { 'type': 'Branch1', 'data': { 'data': 'str' } }
348 { 'type': 'Branch2', 'data': { 'data': 'int' } }
349 { 'union': 'Flat': 'base': 'Base', 'discriminator': 'type',
350 'data': { 'one': 'Branch1', 'two': 'Branch2' } }
353 The final flavor of unions is an anonymous union. While the other two
354 union types are always passed as a JSON object in the wire format, an
355 anonymous union instead allows the direct use of different types in
356 its place. Anonymous unions are declared using an empty dictionary as
357 their discriminator. The discriminator values never appear on the
358 wire, they are only used in the generated C code. Anonymous unions
359 cannot have a base type.
361 { 'union': 'BlockRef',
363 'data': { 'definition': 'BlockdevOptions',
364 'reference': 'str' } }
366 This example allows using both of the following example objects:
368 { "file": "my_existing_block_device_id" }
369 { "file": { "driver": "file",
371 "filename": "/tmp/mydisk.qcow2" } }
376 Usage: { 'command': STRING, '*data': COMPLEX-TYPE-NAME-OR-DICT,
377 '*returns': TYPE-NAME-OR-DICT,
378 '*gen': false, '*success-response': false }
380 Commands are defined by using a dictionary containing several members,
381 where three members are most common. The 'command' member is a
382 mandatory string, and determines the "execute" value passed in a QMP
385 The 'data' argument maps to the "arguments" dictionary passed in as
386 part of a QMP command. The 'data' member is optional and defaults to
387 {} (an empty dictionary). If present, it must be the string name of a
388 complex type, a one-element array containing the name of a complex
389 type, or a dictionary that declares an anonymous type with the same
390 semantics as a 'type' expression, with one exception noted below when
393 The 'returns' member describes what will appear in the "return" field
394 of a QMP reply on successful completion of a command. The member is
395 optional from the command declaration; if absent, the "return" field
396 will be an empty dictionary. If 'returns' is present, it must be the
397 string name of a complex or built-in type, a one-element array
398 containing the name of a complex or built-in type, or a dictionary
399 that declares an anonymous type with the same semantics as a 'type'
400 expression, with one exception noted below when 'gen' is used.
401 Although it is permitted to have the 'returns' member name a built-in
402 type or an array of built-in types, any command that does this cannot
403 be extended to return additional information in the future; thus, new
404 commands should strongly consider returning a dictionary-based type or
405 an array of dictionaries, even if the dictionary only contains one
406 field at the present.
408 All commands use a dictionary to report failure, with no way to
409 specify that in QAPI. Where the error return is different than the
410 usual GenericError class in order to help the client react differently
411 to certain error conditions, it is worth documenting this in the
412 comments before the command declaration.
414 Some example commands:
416 { 'command': 'my-first-command',
417 'data': { 'arg1': 'str', '*arg2': 'str' } }
418 { 'type': 'MyType', 'data': { '*value': 'str' } }
419 { 'command': 'my-second-command',
420 'returns': [ 'MyType' ] }
422 which would validate this QMP transaction:
424 => { "execute": "my-first-command",
425 "arguments": { "arg1": "hello" } }
427 => { "execute": "my-second-command" }
428 <= { "return": [ { "value": "one" }, { } ] }
430 In rare cases, QAPI cannot express a type-safe representation of a
431 corresponding QMP command. In these cases, if the command expression
432 includes the key 'gen' with boolean value false, then the 'data' or
433 'returns' member that intends to bypass generated type-safety and do
434 its own manual validation should use an inline dictionary definition,
435 with a value of '**' rather than a valid type name for the keys that
436 the generated code will not validate. Please try to avoid adding new
437 commands that rely on this, and instead use type-safe unions. For an
438 example of bypass usage:
440 { 'command': 'netdev_add',
441 'data': {'type': 'str', 'id': 'str', '*props': '**'},
444 Normally, the QAPI schema is used to describe synchronous exchanges,
445 where a response is expected. But in some cases, the action of a
446 command is expected to change state in a way that a successful
447 response is not possible (although the command will still return a
448 normal dictionary error on failure). When a successful reply is not
449 possible, the command expression should include the optional key
450 'success-response' with boolean value false. So far, only QGA makes
456 Usage: { 'event': STRING, '*data': COMPLEX-TYPE-NAME-OR-DICT }
458 Events are defined with the keyword 'event'. It is not allowed to
459 name an event 'MAX', since the generator also produces a C enumeration
460 of all event names with a generated _MAX value at the end. When
461 'data' is also specified, additional info will be included in the
462 event, with similar semantics to a 'type' expression. Finally there
463 will be C API generated in qapi-event.h; when called by QEMU code, a
464 message with timestamp will be emitted on the wire.
468 { 'event': 'EVENT_C',
469 'data': { '*a': 'int', 'b': 'str' } }
471 Resulting in this JSON object:
473 { "event": "EVENT_C",
474 "data": { "b": "test string" },
475 "timestamp": { "seconds": 1267020223, "microseconds": 435656 } }
478 == Code generation ==
480 Schemas are fed into 3 scripts to generate all the code/files that, paired
481 with the core QAPI libraries, comprise everything required to take JSON
482 commands read in by a QMP/guest agent server, unmarshal the arguments into
483 the underlying C types, call into the corresponding C function, and map the
484 response back to a QMP/guest agent response to be returned to the user.
486 As an example, we'll use the following schema, which describes a single
487 complex user-defined type (which will produce a C struct, along with a list
488 node structure that can be used to chain together a list of such types in
489 case we want to accept/return a list of this type with a command), and a
490 command which takes that type as a parameter and returns the same type:
492 $ cat example-schema.json
493 { 'type': 'UserDefOne',
494 'data': { 'integer': 'int', 'string': 'str' } }
496 { 'command': 'my-command',
497 'data': {'arg1': 'UserDefOne'},
498 'returns': 'UserDefOne' }
500 { 'event': 'MY_EVENT' }
502 === scripts/qapi-types.py ===
504 Used to generate the C types defined by a schema. The following files are
507 $(prefix)qapi-types.h - C types corresponding to types defined in
508 the schema you pass in
509 $(prefix)qapi-types.c - Cleanup functions for the above C types
511 The $(prefix) is an optional parameter used as a namespace to keep the
512 generated code from one schema/code-generation separated from others so code
513 can be generated/used from multiple schemas without clobbering previously
518 $ python scripts/qapi-types.py --output-dir="qapi-generated" \
519 --prefix="example-" --input-file=example-schema.json
520 $ cat qapi-generated/example-qapi-types.c
521 [Uninteresting stuff omitted...]
523 void qapi_free_UserDefOneList(UserDefOneList *obj)
525 QapiDeallocVisitor *md;
532 md = qapi_dealloc_visitor_new();
533 v = qapi_dealloc_get_visitor(md);
534 visit_type_UserDefOneList(v, &obj, NULL, NULL);
535 qapi_dealloc_visitor_cleanup(md);
538 void qapi_free_UserDefOne(UserDefOne *obj)
540 QapiDeallocVisitor *md;
547 md = qapi_dealloc_visitor_new();
548 v = qapi_dealloc_get_visitor(md);
549 visit_type_UserDefOne(v, &obj, NULL, NULL);
550 qapi_dealloc_visitor_cleanup(md);
553 $ cat qapi-generated/example-qapi-types.h
554 [Uninteresting stuff omitted...]
556 #ifndef EXAMPLE_QAPI_TYPES_H
557 #define EXAMPLE_QAPI_TYPES_H
559 [Built-in types omitted...]
561 typedef struct UserDefOne UserDefOne;
563 typedef struct UserDefOneList
569 struct UserDefOneList *next;
572 [Functions on built-in types omitted...]
580 void qapi_free_UserDefOneList(UserDefOneList *obj);
581 void qapi_free_UserDefOne(UserDefOne *obj);
585 === scripts/qapi-visit.py ===
587 Used to generate the visitor functions used to walk through and convert
588 a QObject (as provided by QMP) to a native C data structure and
589 vice-versa, as well as the visitor function used to dealloc a complex
590 schema-defined C type.
592 The following files are generated:
594 $(prefix)qapi-visit.c: visitor function for a particular C type, used
595 to automagically convert QObjects into the
596 corresponding C type and vice-versa, as well
597 as for deallocating memory for an existing C
600 $(prefix)qapi-visit.h: declarations for previously mentioned visitor
605 $ python scripts/qapi-visit.py --output-dir="qapi-generated"
606 --prefix="example-" --input-file=example-schema.json
607 $ cat qapi-generated/example-qapi-visit.c
608 [Uninteresting stuff omitted...]
610 static void visit_type_UserDefOne_fields(Visitor *m, UserDefOne **obj, Error **errp)
613 visit_type_int(m, &(*obj)->integer, "integer", &err);
617 visit_type_str(m, &(*obj)->string, "string", &err);
623 error_propagate(errp, err);
626 void visit_type_UserDefOne(Visitor *m, UserDefOne **obj, const char *name, Error **errp)
630 visit_start_struct(m, (void **)obj, "UserDefOne", name, sizeof(UserDefOne), &err);
633 visit_type_UserDefOne_fields(m, obj, errp);
635 visit_end_struct(m, &err);
637 error_propagate(errp, err);
640 void visit_type_UserDefOneList(Visitor *m, UserDefOneList **obj, const char *name, Error **errp)
643 GenericList *i, **prev;
645 visit_start_list(m, name, &err);
650 for (prev = (GenericList **)obj;
651 !err && (i = visit_next_list(m, prev, &err)) != NULL;
653 UserDefOneList *native_i = (UserDefOneList *)i;
654 visit_type_UserDefOne(m, &native_i->value, NULL, &err);
657 error_propagate(errp, err);
659 visit_end_list(m, &err);
661 error_propagate(errp, err);
663 $ python scripts/qapi-commands.py --output-dir="qapi-generated" \
664 --prefix="example-" --input-file=example-schema.json
665 $ cat qapi-generated/example-qapi-visit.h
666 [Uninteresting stuff omitted...]
668 #ifndef EXAMPLE_QAPI_VISIT_H
669 #define EXAMPLE_QAPI_VISIT_H
671 [Visitors for built-in types omitted...]
673 void visit_type_UserDefOne(Visitor *m, UserDefOne **obj, const char *name, Error **errp);
674 void visit_type_UserDefOneList(Visitor *m, UserDefOneList **obj, const char *name, Error **errp);
678 === scripts/qapi-commands.py ===
680 Used to generate the marshaling/dispatch functions for the commands defined
681 in the schema. The following files are generated:
683 $(prefix)qmp-marshal.c: command marshal/dispatch functions for each
684 QMP command defined in the schema. Functions
685 generated by qapi-visit.py are used to
686 convert QObjects received from the wire into
687 function parameters, and uses the same
688 visitor functions to convert native C return
689 values to QObjects from transmission back
692 $(prefix)qmp-commands.h: Function prototypes for the QMP commands
693 specified in the schema.
697 $ python scripts/qapi-commands.py --output-dir="qapi-generated"
698 --prefix="example-" --input-file=example-schema.json
699 $ cat qapi-generated/example-qmp-marshal.c
700 [Uninteresting stuff omitted...]
702 static void qmp_marshal_output_my_command(UserDefOne *ret_in, QObject **ret_out, Error **errp)
704 Error *local_err = NULL;
705 QmpOutputVisitor *mo = qmp_output_visitor_new();
706 QapiDeallocVisitor *md;
709 v = qmp_output_get_visitor(mo);
710 visit_type_UserDefOne(v, &ret_in, "unused", &local_err);
714 *ret_out = qmp_output_get_qobject(mo);
717 error_propagate(errp, local_err);
718 qmp_output_visitor_cleanup(mo);
719 md = qapi_dealloc_visitor_new();
720 v = qapi_dealloc_get_visitor(md);
721 visit_type_UserDefOne(v, &ret_in, "unused", NULL);
722 qapi_dealloc_visitor_cleanup(md);
725 static void qmp_marshal_input_my_command(QDict *args, QObject **ret, Error **errp)
727 Error *local_err = NULL;
728 UserDefOne *retval = NULL;
729 QmpInputVisitor *mi = qmp_input_visitor_new_strict(QOBJECT(args));
730 QapiDeallocVisitor *md;
732 UserDefOne *arg1 = NULL;
734 v = qmp_input_get_visitor(mi);
735 visit_type_UserDefOne(v, &arg1, "arg1", &local_err);
740 retval = qmp_my_command(arg1, &local_err);
745 qmp_marshal_output_my_command(retval, ret, &local_err);
748 error_propagate(errp, local_err);
749 qmp_input_visitor_cleanup(mi);
750 md = qapi_dealloc_visitor_new();
751 v = qapi_dealloc_get_visitor(md);
752 visit_type_UserDefOne(v, &arg1, "arg1", NULL);
753 qapi_dealloc_visitor_cleanup(md);
757 static void qmp_init_marshal(void)
759 qmp_register_command("my-command", qmp_marshal_input_my_command, QCO_NO_OPTIONS);
762 qapi_init(qmp_init_marshal);
763 $ cat qapi-generated/example-qmp-commands.h
764 [Uninteresting stuff omitted...]
766 #ifndef EXAMPLE_QMP_COMMANDS_H
767 #define EXAMPLE_QMP_COMMANDS_H
769 #include "example-qapi-types.h"
770 #include "qapi/qmp/qdict.h"
771 #include "qapi/error.h"
773 UserDefOne *qmp_my_command(UserDefOne *arg1, Error **errp);
777 === scripts/qapi-event.py ===
779 Used to generate the event-related C code defined by a schema. The
780 following files are created:
782 $(prefix)qapi-event.h - Function prototypes for each event type, plus an
783 enumeration of all event names
784 $(prefix)qapi-event.c - Implementation of functions to send an event
788 $ python scripts/qapi-event.py --output-dir="qapi-generated"
789 --prefix="example-" --input-file=example-schema.json
790 $ cat qapi-generated/example-qapi-event.c
791 [Uninteresting stuff omitted...]
793 void qapi_event_send_my_event(Error **errp)
796 Error *local_err = NULL;
797 QMPEventFuncEmit emit;
798 emit = qmp_event_get_func_emit();
803 qmp = qmp_event_build_dict("MY_EVENT");
805 emit(EXAMPLE_QAPI_EVENT_MY_EVENT, qmp, &local_err);
807 error_propagate(errp, local_err);
811 const char *EXAMPLE_QAPIEvent_lookup[] = {
815 $ cat qapi-generated/example-qapi-event.h
816 [Uninteresting stuff omitted...]
818 #ifndef EXAMPLE_QAPI_EVENT_H
819 #define EXAMPLE_QAPI_EVENT_H
821 #include "qapi/error.h"
822 #include "qapi/qmp/qdict.h"
823 #include "example-qapi-types.h"
826 void qapi_event_send_my_event(Error **errp);
828 extern const char *EXAMPLE_QAPIEvent_lookup[];
829 typedef enum EXAMPLE_QAPIEvent
831 EXAMPLE_QAPI_EVENT_MY_EVENT = 0,
832 EXAMPLE_QAPI_EVENT_MAX = 1,