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