hw/sh4: Use MemoryRegion typedef
[qemu/ar7.git] / docs / devel / qapi-code-gen.txt
bloba7794ef658c613e6c69b0deb7c7ea5874e765c7a
1 = How to use the QAPI code generator =
3 Copyright IBM Corp. 2011
4 Copyright (C) 2012-2016 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.
16 The remainder of this document uses "Client JSON Protocol" when
17 referring to the wire contents of a QMP or QGA connection.
19 To map between Client JSON Protocol interfaces and the native C API,
20 we generate C code from a QAPI schema.  This document describes the
21 QAPI schema language, and how it gets mapped to the Client JSON
22 Protocol and to C.  It additionally provides guidance on maintaining
23 Client JSON Protocol compatibility.
26 == The QAPI schema language ==
28 The QAPI schema defines the Client JSON Protocol's commands and
29 events, as well as types used by them.  Forward references are
30 allowed.
32 It is permissible for the schema to contain additional types not used
33 by any commands or events, for the side effect of generated C code
34 used internally.
36 There are several kinds of types: simple types (a number of built-in
37 types, such as 'int' and 'str'; as well as enumerations), arrays,
38 complex types (structs and two flavors of unions), and alternate types
39 (a choice between other types).
42 === Schema syntax ===
44 Syntax is loosely based on JSON (http://www.ietf.org/rfc/rfc8259.txt).
45 Differences:
47 * Comments: start with a hash character (#) that is not part of a
48   string, and extend to the end of the line.
50 * Strings are enclosed in 'single quotes', not "double quotes".
52 * Strings are restricted to printable ASCII, and escape sequences to
53   just '\\'.
55 * Numbers and null are not supported.
57 A second layer of syntax defines the sequences of JSON texts that are
58 a correctly structured QAPI schema.  We provide a grammar for this
59 syntax in an EBNF-like notation:
61 * Production rules look like non-terminal = expression
62 * Concatenation: expression A B matches expression A, then B
63 * Alternation: expression A | B matches expression A or B
64 * Repetition: expression A... matches zero or more occurrences of
65   expression A
66 * Repetition: expression A, ... matches zero or more occurrences of
67   expression A separated by ,
68 * Grouping: expression ( A ) matches expression A
69 * JSON's structural characters are terminals: { } [ ] : ,
70 * JSON's literal names are terminals: false true
71 * String literals enclosed in 'single quotes' are terminal, and match
72   this JSON string, with a leading '*' stripped off
73 * When JSON object member's name starts with '*', the member is
74   optional.
75 * The symbol STRING is a terminal, and matches any JSON string
76 * The symbol BOOL is a terminal, and matches JSON false or true
77 * ALL-CAPS words other than STRING are non-terminals
79 The order of members within JSON objects does not matter unless
80 explicitly noted.
82 A QAPI schema consists of a series of top-level expressions:
84     SCHEMA = TOP-LEVEL-EXPR...
86 The top-level expressions are all JSON objects.  Code and
87 documentation is generated in schema definition order.  Code order
88 should not matter.
90 A top-level expressions is either a directive or a definition:
92     TOP-LEVEL-EXPR = DIRECTIVE | DEFINITION
94 There are two kinds of directives and six kinds of definitions:
96     DIRECTIVE = INCLUDE | PRAGMA
97     DEFINITION = ENUM | STRUCT | UNION | ALTERNATE | COMMAND | EVENT
99 These are discussed in detail below.
102 === Built-in Types ===
104 The following types are predefined, and map to C as follows:
106   Schema    C          JSON
107   str       char *     any JSON string, UTF-8
108   number    double     any JSON number
109   int       int64_t    a JSON number without fractional part
110                        that fits into the C integer type
111   int8      int8_t     likewise
112   int16     int16_t    likewise
113   int32     int32_t    likewise
114   int64     int64_t    likewise
115   uint8     uint8_t    likewise
116   uint16    uint16_t   likewise
117   uint32    uint32_t   likewise
118   uint64    uint64_t   likewise
119   size      uint64_t   like uint64_t, except StringInputVisitor
120                        accepts size suffixes
121   bool      bool       JSON true or false
122   null      QNull *    JSON null
123   any       QObject *  any JSON value
124   QType     QType      JSON string matching enum QType values
127 === Include directives ===
129 Syntax:
130     INCLUDE = { 'include': STRING }
132 The QAPI schema definitions can be modularized using the 'include' directive:
134  { 'include': 'path/to/file.json' }
136 The directive is evaluated recursively, and include paths are relative
137 to the file using the directive.  Multiple includes of the same file
138 are idempotent.
140 As a matter of style, it is a good idea to have all files be
141 self-contained, but at the moment, nothing prevents an included file
142 from making a forward reference to a type that is only introduced by
143 an outer file.  The parser may be made stricter in the future to
144 prevent incomplete include files.
147 === Pragma directives ===
149 Syntax:
150     PRAGMA = { 'pragma': { '*doc-required': BOOL,
151                            '*returns-whitelist': [ STRING, ... ],
152                            '*name-case-whitelist': [ STRING, ... ] } }
154 The pragma directive lets you control optional generator behavior.
156 Pragma's scope is currently the complete schema.  Setting the same
157 pragma to different values in parts of the schema doesn't work.
159 Pragma 'doc-required' takes a boolean value.  If true, documentation
160 is required.  Default is false.
162 Pragma 'returns-whitelist' takes a list of command names that may
163 violate the rules on permitted return types.  Default is none.
165 Pragma 'name-case-whitelist' takes a list of names that may violate
166 rules on use of upper- vs. lower-case letters.  Default is none.
169 === Enumeration types ===
171 Syntax:
172     ENUM = { 'enum': STRING,
173              'data': [ ENUM-VALUE, ... ],
174              '*prefix': STRING,
175              '*if': COND,
176              '*features': FEATURES }
177     ENUM-VALUE = STRING
178                | { 'name': STRING, '*if': COND }
180 Member 'enum' names the enum type.
182 Each member of the 'data' array defines a value of the enumeration
183 type.  The form STRING is shorthand for { 'name': STRING }.  The
184 'name' values must be be distinct.
186 Example:
188  { 'enum': 'MyEnum', 'data': [ 'value1', 'value2', 'value3' ] }
190 Nothing prevents an empty enumeration, although it is probably not
191 useful.
193 On the wire, an enumeration type's value is represented by its
194 (string) name.  In C, it's represented by an enumeration constant.
195 These are of the form PREFIX_NAME, where PREFIX is derived from the
196 enumeration type's name, and NAME from the value's name.  For the
197 example above, the generator maps 'MyEnum' to MY_ENUM and 'value1' to
198 VALUE1, resulting in the enumeration constant MY_ENUM_VALUE1.  The
199 optional 'prefix' member overrides PREFIX.
201 The generated C enumeration constants have values 0, 1, ..., N-1 (in
202 QAPI schema order), where N is the number of values.  There is an
203 additional enumeration constant PREFIX__MAX with value N.
205 Do not use string or an integer type when an enumeration type can do
206 the job satisfactorily.
208 The optional 'if' member specifies a conditional.  See "Configuring
209 the schema" below for more on this.
211 The optional 'features' member specifies features.  See "Features"
212 below for more on this.
215 === Type references and array types ===
217 Syntax:
218     TYPE-REF = STRING | ARRAY-TYPE
219     ARRAY-TYPE = [ STRING ]
221 A string denotes the type named by the string.
223 A one-element array containing a string denotes an array of the type
224 named by the string.  Example: ['int'] denotes an array of 'int'.
227 === Struct types ===
229 Syntax:
230     STRUCT = { 'struct': STRING,
231                'data': MEMBERS,
232                '*base': STRING,
233                '*if': COND,
234                '*features': FEATURES }
235     MEMBERS = { MEMBER, ... }
236     MEMBER = STRING : TYPE-REF
237            | STRING : { 'type': TYPE-REF,
238                         '*if': COND,
239                         '*features': FEATURES }
241 Member 'struct' names the struct type.
243 Each MEMBER of the 'data' object defines a member of the struct type.
245 The MEMBER's STRING name consists of an optional '*' prefix and the
246 struct member name.  If '*' is present, the member is optional.
248 The MEMBER's value defines its properties, in particular its type.
249 The form TYPE-REF is shorthand for { 'type': TYPE-REF }.
251 Example:
253  { 'struct': 'MyType',
254    'data': { 'member1': 'str', 'member2': ['int'], '*member3': 'str' } }
256 A struct type corresponds to a struct in C, and an object in JSON.
257 The C struct's members are generated in QAPI schema order.
259 The optional 'base' member names a struct type whose members are to be
260 included in this type.  They go first in the C struct.
262 Example:
264  { 'struct': 'BlockdevOptionsGenericFormat',
265    'data': { 'file': 'str' } }
266  { 'struct': 'BlockdevOptionsGenericCOWFormat',
267    'base': 'BlockdevOptionsGenericFormat',
268    'data': { '*backing': 'str' } }
270 An example BlockdevOptionsGenericCOWFormat object on the wire could use
271 both members like this:
273  { "file": "/some/place/my-image",
274    "backing": "/some/place/my-backing-file" }
276 The optional 'if' member specifies a conditional.  See "Configuring
277 the schema" below for more on this.
279 The optional 'features' member specifies features.  See "Features"
280 below for more on this.
283 === Union types ===
285 Syntax:
286     UNION = { 'union': STRING,
287               'data': BRANCHES,
288               '*if': COND,
289               '*features': FEATURES }
290           | { 'union': STRING,
291               'data': BRANCHES,
292               'base': ( MEMBERS | STRING ),
293               'discriminator': STRING,
294               '*if': COND,
295               '*features': FEATURES }
296     BRANCHES = { BRANCH, ... }
297     BRANCH = STRING : TYPE-REF
298            | STRING : { 'type': TYPE-REF, '*if': COND }
300 Member 'union' names the union type.
302 There are two flavors of union types: simple (no discriminator or
303 base), and flat (both discriminator and base).
305 Each BRANCH of the 'data' object defines a branch of the union.  A
306 union must have at least one branch.
308 The BRANCH's STRING name is the branch name.
310 The BRANCH's value defines the branch's properties, in particular its
311 type.  The form TYPE-REF is shorthand for { 'type': TYPE-REF }.
313 A simple union type defines a mapping from automatic discriminator
314 values to data types like in this example:
316  { 'struct': 'BlockdevOptionsFile', 'data': { 'filename': 'str' } }
317  { 'struct': 'BlockdevOptionsQcow2',
318    'data': { 'backing': 'str', '*lazy-refcounts': 'bool' } }
320  { 'union': 'BlockdevOptionsSimple',
321    'data': { 'file': 'BlockdevOptionsFile',
322              'qcow2': 'BlockdevOptionsQcow2' } }
324 In the Client JSON Protocol, a simple union is represented by an
325 object that contains the 'type' member as a discriminator, and a
326 'data' member that is of the specified data type corresponding to the
327 discriminator value, as in these examples:
329  { "type": "file", "data": { "filename": "/some/place/my-image" } }
330  { "type": "qcow2", "data": { "backing": "/some/place/my-image",
331                               "lazy-refcounts": true } }
333 The generated C code uses a struct containing a union.  Additionally,
334 an implicit C enum 'NameKind' is created, corresponding to the union
335 'Name', for accessing the various branches of the union.  The value
336 for each branch can be of any type.
338 Flat unions permit arbitrary common members that occur in all variants
339 of the union, not just a discriminator.  Their discriminators need not
340 be named 'type'.  They also avoid nesting on the wire.
342 The 'base' member defines the common members.  If it is a MEMBERS
343 object, it defines common members just like a struct type's 'data'
344 member defines struct type members.  If it is a STRING, it names a
345 struct type whose members are the common members.
347 All flat union branches must be of struct type.
349 In the Client JSON Protocol, a flat union is represented by an object
350 with the common members (from the base type) and the selected branch's
351 members.  The two sets of member names must be disjoint.  Member
352 'discriminator' must name a non-optional enum-typed member of the base
353 struct.
355 The following example enhances the above simple union example by
356 adding an optional common member 'read-only', renaming the
357 discriminator to something more applicable than the simple union's
358 default of 'type', and reducing the number of {} required on the wire:
360  { 'enum': 'BlockdevDriver', 'data': [ 'file', 'qcow2' ] }
361  { 'union': 'BlockdevOptions',
362    'base': { 'driver': 'BlockdevDriver', '*read-only': 'bool' },
363    'discriminator': 'driver',
364    'data': { 'file': 'BlockdevOptionsFile',
365              'qcow2': 'BlockdevOptionsQcow2' } }
367 Resulting in these JSON objects:
369  { "driver": "file", "read-only": true,
370    "filename": "/some/place/my-image" }
371  { "driver": "qcow2", "read-only": false,
372    "backing": "/some/place/my-image", "lazy-refcounts": true }
374 Notice that in a flat union, the discriminator name is controlled by
375 the user, but because it must map to a base member with enum type, the
376 code generator ensures that branches match the existing values of the
377 enum.  The order of branches need not match the order of the enum
378 values.  The branches need not cover all possible enum values.
379 Omitted enum values are still valid branches that add no additional
380 members to the data type.  In the resulting generated C data types, a
381 flat union is represented as a struct with the base members in QAPI
382 schema order, and then a union of structures for each branch of the
383 struct.
385 A simple union can always be re-written as a flat union where the base
386 class has a single member named 'type', and where each branch of the
387 union has a struct with a single member named 'data'.  That is,
389  { 'union': 'Simple', 'data': { 'one': 'str', 'two': 'int' } }
391 is identical on the wire to:
393  { 'enum': 'Enum', 'data': ['one', 'two'] }
394  { 'struct': 'Branch1', 'data': { 'data': 'str' } }
395  { 'struct': 'Branch2', 'data': { 'data': 'int' } }
396  { 'union': 'Flat': 'base': { 'type': 'Enum' }, 'discriminator': 'type',
397    'data': { 'one': 'Branch1', 'two': 'Branch2' } }
399 The optional 'if' member specifies a conditional.  See "Configuring
400 the schema" below for more on this.
402 The optional 'features' member specifies features.  See "Features"
403 below for more on this.
406 === Alternate types ===
408 Syntax:
409     ALTERNATE = { 'alternate': STRING,
410                   'data': ALTERNATIVES,
411                   '*if': COND,
412                   '*features': FEATURES }
413     ALTERNATIVES = { ALTERNATIVE, ... }
414     ALTERNATIVE = STRING : STRING
415                 | STRING : { 'type': STRING, '*if': COND }
417 Member 'alternate' names the alternate type.
419 Each ALTERNATIVE of the 'data' object defines a branch of the
420 alternate.  An alternate must have at least one branch.
422 The ALTERNATIVE's STRING name is the branch name.
424 The ALTERNATIVE's value defines the branch's properties, in particular
425 its type.  The form STRING is shorthand for { 'type': STRING }.
427 Example:
429  { 'alternate': 'BlockdevRef',
430    'data': { 'definition': 'BlockdevOptions',
431              'reference': 'str' } }
433 An alternate type is like a union type, except there is no
434 discriminator on the wire.  Instead, the branch to use is inferred
435 from the value.  An alternate can only express a choice between types
436 represented differently on the wire.
438 If a branch is typed as the 'bool' built-in, the alternate accepts
439 true and false; if it is typed as any of the various numeric
440 built-ins, it accepts a JSON number; if it is typed as a 'str'
441 built-in or named enum type, it accepts a JSON string; if it is typed
442 as the 'null' built-in, it accepts JSON null; and if it is typed as a
443 complex type (struct or union), it accepts a JSON object.
445 The example alternate declaration above allows using both of the
446 following example objects:
448  { "file": "my_existing_block_device_id" }
449  { "file": { "driver": "file",
450              "read-only": false,
451              "filename": "/tmp/mydisk.qcow2" } }
453 The optional 'if' member specifies a conditional.  See "Configuring
454 the schema" below for more on this.
456 The optional 'features' member specifies features.  See "Features"
457 below for more on this.
460 === Commands ===
462 Syntax:
463     COMMAND = { 'command': STRING,
464                 (
465                 '*data': ( MEMBERS | STRING ),
466                 |
467                 'data': STRING,
468                 'boxed': true,
469                 )
470                 '*returns': TYPE-REF,
471                 '*success-response': false,
472                 '*gen': false,
473                 '*allow-oob': true,
474                 '*allow-preconfig': true,
475                 '*if': COND,
476                 '*features': FEATURES }
478 Member 'command' names the command.
480 Member 'data' defines the arguments.  It defaults to an empty MEMBERS
481 object.
483 If 'data' is a MEMBERS object, then MEMBERS defines arguments just
484 like a struct type's 'data' defines struct type members.
486 If 'data' is a STRING, then STRING names a complex type whose members
487 are the arguments.  A union type requires 'boxed': true.
489 Member 'returns' defines the command's return type.  It defaults to an
490 empty struct type.  It must normally be a complex type or an array of
491 a complex type.  To return anything else, the command must be listed
492 in pragma 'returns-whitelist'.  If you do this, extending the command
493 to return additional information will be harder.  Use of
494 'returns-whitelist' for new commands is strongly discouraged.
496 A command's error responses are not specified in the QAPI schema.
497 Error conditions should be documented in comments.
499 In the Client JSON Protocol, the value of the "execute" or "exec-oob"
500 member is the command name.  The value of the "arguments" member then
501 has to conform to the arguments, and the value of the success
502 response's "return" member will conform to the return type.
504 Some example commands:
506  { 'command': 'my-first-command',
507    'data': { 'arg1': 'str', '*arg2': 'str' } }
508  { 'struct': 'MyType', 'data': { '*value': 'str' } }
509  { 'command': 'my-second-command',
510    'returns': [ 'MyType' ] }
512 which would validate this Client JSON Protocol transaction:
514  => { "execute": "my-first-command",
515       "arguments": { "arg1": "hello" } }
516  <= { "return": { } }
517  => { "execute": "my-second-command" }
518  <= { "return": [ { "value": "one" }, { } ] }
520 The generator emits a prototype for the C function implementing the
521 command.  The function itself needs to be written by hand.  See
522 section "Code generated for commands" for examples.
524 The function returns the return type.  When member 'boxed' is absent,
525 it takes the command arguments as arguments one by one, in QAPI schema
526 order.  Else it takes them wrapped in the C struct generated for the
527 complex argument type.  It takes an additional Error ** argument in
528 either case.
530 The generator also emits a marshalling function that extracts
531 arguments for the user's function out of an input QDict, calls the
532 user's function, and if it succeeded, builds an output QObject from
533 its return value.  This is for use by the QMP monitor core.
535 In rare cases, QAPI cannot express a type-safe representation of a
536 corresponding Client JSON Protocol command.  You then have to suppress
537 generation of a marshalling function by including a member 'gen' with
538 boolean value false, and instead write your own function.  For
539 example:
541  { 'command': 'netdev_add',
542    'data': {'type': 'str', 'id': 'str'},
543    'gen': false }
545 Please try to avoid adding new commands that rely on this, and instead
546 use type-safe unions.
548 Normally, the QAPI schema is used to describe synchronous exchanges,
549 where a response is expected.  But in some cases, the action of a
550 command is expected to change state in a way that a successful
551 response is not possible (although the command will still return an
552 error object on failure).  When a successful reply is not possible,
553 the command definition includes the optional member 'success-response'
554 with boolean value false.  So far, only QGA makes use of this member.
556 Member 'allow-oob' declares whether the command supports out-of-band
557 (OOB) execution.  It defaults to false.  For example:
559  { 'command': 'migrate_recover',
560    'data': { 'uri': 'str' }, 'allow-oob': true }
562 See qmp-spec.txt for out-of-band execution syntax and semantics.
564 Commands supporting out-of-band execution can still be executed
565 in-band.
567 When a command is executed in-band, its handler runs in the main
568 thread with the BQL held.
570 When a command is executed out-of-band, its handler runs in a
571 dedicated monitor I/O thread with the BQL *not* held.
573 An OOB-capable command handler must satisfy the following conditions:
575 - It terminates quickly.
576 - It does not invoke system calls that may block.
577 - It does not access guest RAM that may block when userfaultfd is
578   enabled for postcopy live migration.
579 - It takes only "fast" locks, i.e. all critical sections protected by
580   any lock it takes also satisfy the conditions for OOB command
581   handler code.
583 The restrictions on locking limit access to shared state.  Such access
584 requires synchronization, but OOB commands can't take the BQL or any
585 other "slow" lock.
587 When in doubt, do not implement OOB execution support.
589 Member 'allow-preconfig' declares whether the command is available
590 before the machine is built.  It defaults to false.  For example:
592  { 'command': 'qmp_capabilities',
593    'data': { '*enable': [ 'QMPCapability' ] },
594    'allow-preconfig': true }
596 QMP is available before the machine is built only when QEMU was
597 started with --preconfig.
599 The optional 'if' member specifies a conditional.  See "Configuring
600 the schema" below for more on this.
602 The optional 'features' member specifies features.  See "Features"
603 below for more on this.
606 === Events ===
608 Syntax:
609     EVENT = { 'event': STRING,
610               (
611               '*data': ( MEMBERS | STRING ),
612               |
613               'data': STRING,
614               'boxed': true,
615               )
616               '*if': COND,
617               '*features': FEATURES }
619 Member 'event' names the event.  This is the event name used in the
620 Client JSON Protocol.
622 Member 'data' defines the event-specific data.  It defaults to an
623 empty MEMBERS object.
625 If 'data' is a MEMBERS object, then MEMBERS defines event-specific
626 data just like a struct type's 'data' defines struct type members.
628 If 'data' is a STRING, then STRING names a complex type whose members
629 are the event-specific data.  A union type requires 'boxed': true.
631 An example event is:
633 { 'event': 'EVENT_C',
634   'data': { '*a': 'int', 'b': 'str' } }
636 Resulting in this JSON object:
638 { "event": "EVENT_C",
639   "data": { "b": "test string" },
640   "timestamp": { "seconds": 1267020223, "microseconds": 435656 } }
642 The generator emits a function to send the event.  When member 'boxed'
643 is absent, it takes event-specific data one by one, in QAPI schema
644 order.  Else it takes them wrapped in the C struct generated for the
645 complex type.  See section "Code generated for events" for examples.
647 The optional 'if' member specifies a conditional.  See "Configuring
648 the schema" below for more on this.
650 The optional 'features' member specifies features.  See "Features"
651 below for more on this.
654 === Features ===
656 Syntax:
657     FEATURES = [ FEATURE, ... ]
658     FEATURE = STRING
659             | { 'name': STRING, '*if': COND }
661 Sometimes, the behaviour of QEMU changes compatibly, but without a
662 change in the QMP syntax (usually by allowing values or operations
663 that previously resulted in an error).  QMP clients may still need to
664 know whether the extension is available.
666 For this purpose, a list of features can be specified for a command or
667 struct type.  Each list member can either be { 'name': STRING, '*if':
668 COND }, or STRING, which is shorthand for { 'name': STRING }.
670 The optional 'if' member specifies a conditional.  See "Configuring
671 the schema" below for more on this.
673 Example:
675 { 'struct': 'TestType',
676   'data': { 'number': 'int' },
677   'features': [ 'allow-negative-numbers' ] }
679 The feature strings are exposed to clients in introspection, as
680 explained in section "Client JSON Protocol introspection".
682 Intended use is to have each feature string signal that this build of
683 QEMU shows a certain behaviour.
686 ==== Special features ====
688 Feature "deprecated" marks a command, event, or struct member as
689 deprecated.  It is not supported elsewhere so far.
692 === Naming rules and reserved names ===
694 All names must begin with a letter, and contain only ASCII letters,
695 digits, hyphen, and underscore.  There are two exceptions: enum values
696 may start with a digit, and names that are downstream extensions (see
697 section Downstream extensions) start with underscore.
699 Names beginning with 'q_' are reserved for the generator, which uses
700 them for munging QMP names that resemble C keywords or other
701 problematic strings.  For example, a member named "default" in qapi
702 becomes "q_default" in the generated C code.
704 Types, commands, and events share a common namespace.  Therefore,
705 generally speaking, type definitions should always use CamelCase for
706 user-defined type names, while built-in types are lowercase.
708 Type names ending with 'Kind' or 'List' are reserved for the
709 generator, which uses them for implicit union enums and array types,
710 respectively.
712 Command names, and member names within a type, should be all lower
713 case with words separated by a hyphen.  However, some existing older
714 commands and complex types use underscore; when extending them,
715 consistency is preferred over blindly avoiding underscore.
717 Event names should be ALL_CAPS with words separated by underscore.
719 Member name 'u' and names starting with 'has-' or 'has_' are reserved
720 for the generator, which uses them for unions and for tracking
721 optional members.
723 Any name (command, event, type, member, or enum value) beginning with
724 "x-" is marked experimental, and may be withdrawn or changed
725 incompatibly in a future release.
727 Pragma 'name-case-whitelist' lets you violate the rules on use of
728 upper and lower case.  Use for new code is strongly discouraged.
731 === Downstream extensions ===
733 QAPI schema names that are externally visible, say in the Client JSON
734 Protocol, need to be managed with care.  Names starting with a
735 downstream prefix of the form __RFQDN_ are reserved for the downstream
736 who controls the valid, reverse fully qualified domain name RFQDN.
737 RFQDN may only contain ASCII letters, digits, hyphen and period.
739 Example: Red Hat, Inc. controls redhat.com, and may therefore add a
740 downstream command __com.redhat_drive-mirror.
743 === Configuring the schema ===
745 Syntax:
746     COND = STRING
747          | [ STRING, ... ]
749 All definitions take an optional 'if' member.  Its value must be a
750 string or a list of strings.  A string is shorthand for a list
751 containing just that string.  The code generated for the definition
752 will then be guarded by #if STRING for each STRING in the COND list.
754 Example: a conditional struct
756  { 'struct': 'IfStruct', 'data': { 'foo': 'int' },
757    'if': ['defined(CONFIG_FOO)', 'defined(HAVE_BAR)'] }
759 gets its generated code guarded like this:
761  #if defined(CONFIG_FOO)
762  #if defined(HAVE_BAR)
763  ... generated code ...
764  #endif /* defined(HAVE_BAR) */
765  #endif /* defined(CONFIG_FOO) */
767 Individual members of complex types, commands arguments, and
768 event-specific data can also be made conditional.  This requires the
769 longhand form of MEMBER.
771 Example: a struct type with unconditional member 'foo' and conditional
772 member 'bar'
774 { 'struct': 'IfStruct', 'data':
775   { 'foo': 'int',
776     'bar': { 'type': 'int', 'if': 'defined(IFCOND)'} } }
778 A union's discriminator may not be conditional.
780 Likewise, individual enumeration values be conditional.  This requires
781 the longhand form of ENUM-VALUE.
783 Example: an enum type with unconditional value 'foo' and conditional
784 value 'bar'
786 { 'enum': 'IfEnum', 'data':
787   [ 'foo',
788     { 'name' : 'bar', 'if': 'defined(IFCOND)' } ] }
790 Likewise, features can be conditional.  This requires the longhand
791 form of FEATURE.
793 Example: a struct with conditional feature 'allow-negative-numbers'
795 { 'struct': 'TestType',
796   'data': { 'number': 'int' },
797   'features': [ { 'name': 'allow-negative-numbers',
798                   'if' 'defined(IFCOND)' } ] }
800 Please note that you are responsible to ensure that the C code will
801 compile with an arbitrary combination of conditions, since the
802 generator is unable to check it at this point.
804 The conditions apply to introspection as well, i.e. introspection
805 shows a conditional entity only when the condition is satisfied in
806 this particular build.
809 === Documentation comments ===
811 A multi-line comment that starts and ends with a '##' line is a
812 documentation comment.
814 If the documentation comment starts like
816     ##
817     # @SYMBOL:
819 it documents the definition if SYMBOL, else it's free-form
820 documentation.
822 See below for more on definition documentation.
824 Free-form documentation may be used to provide additional text and
825 structuring content.
828 ==== Documentation markup ====
830 Comment text starting with '=' is a section title:
832     # = Section title
834 Double the '=' for a subsection title:
836     # == Subsection title
838 '|' denotes examples:
840     # | Text of the example, may span
841     # | multiple lines
843 '*' starts an itemized list:
845     # * First item, may span
846     #   multiple lines
847     # * Second item
849 You can also use '-' instead of '*'.
851 A decimal number followed by '.' starts a numbered list:
853     # 1. First item, may span
854     #    multiple lines
855     # 2. Second item
857 The actual number doesn't matter.  You could even use '*' instead of
858 '2.' for the second item.
860 Lists can't be nested.  Blank lines are currently not supported within
861 lists.
863 Additional whitespace between the initial '#' and the comment text is
864 permitted.
866 *foo* and _foo_ are for strong and emphasis styles respectively (they
867 do not work over multiple lines).  @foo is used to reference a name in
868 the schema.
870 Example:
873 # = Section
874 # == Subsection
876 # Some text foo with *strong* and _emphasis_
877 # 1. with a list
878 # 2. like that
880 # And some code:
881 # | $ echo foo
882 # | -> do this
883 # | <- get that
888 ==== Definition documentation ====
890 Definition documentation, if present, must immediately precede the
891 definition it documents.
893 When documentation is required (see pragma 'doc-required'), every
894 definition must have documentation.
896 Definition documentation starts with a line naming the definition,
897 followed by an optional overview, a description of each argument (for
898 commands and events), member (for structs and unions), branch (for
899 alternates), or value (for enums), and finally optional tagged
900 sections.
902 FIXME: the parser accepts these things in almost any order.
903 FIXME: union branches should be described, too.
905 Extensions added after the definition was first released carry a
906 '(since x.y.z)' comment.
908 A tagged section starts with one of the following words:
909 "Note:"/"Notes:", "Since:", "Example"/"Examples", "Returns:", "TODO:".
910 The section ends with the start of a new section.
912 A 'Since: x.y.z' tagged section lists the release that introduced the
913 definition.
915 For example:
918 # @BlockStats:
920 # Statistics of a virtual block device or a block backing device.
922 # @device: If the stats are for a virtual block device, the name
923 #          corresponding to the virtual block device.
925 # @node-name: The node name of the device. (since 2.3)
927 # ... more members ...
929 # Since: 0.14.0
931 { 'struct': 'BlockStats',
932   'data': {'*device': 'str', '*node-name': 'str',
933            ... more members ... } }
936 # @query-blockstats:
938 # Query the @BlockStats for all virtual block devices.
940 # @query-nodes: If true, the command will query all the
941 #               block nodes ... explain, explain ...  (since 2.3)
943 # Returns: A list of @BlockStats for each virtual block devices.
945 # Since: 0.14.0
947 # Example:
949 # -> { "execute": "query-blockstats" }
950 # <- {
951 #      ... lots of output ...
952 #    }
955 { 'command': 'query-blockstats',
956   'data': { '*query-nodes': 'bool' },
957   'returns': ['BlockStats'] }
960 == Client JSON Protocol introspection ==
962 Clients of a Client JSON Protocol commonly need to figure out what
963 exactly the server (QEMU) supports.
965 For this purpose, QMP provides introspection via command
966 query-qmp-schema.  QGA currently doesn't support introspection.
968 While Client JSON Protocol wire compatibility should be maintained
969 between qemu versions, we cannot make the same guarantees for
970 introspection stability.  For example, one version of qemu may provide
971 a non-variant optional member of a struct, and a later version rework
972 the member to instead be non-optional and associated with a variant.
973 Likewise, one version of qemu may list a member with open-ended type
974 'str', and a later version could convert it to a finite set of strings
975 via an enum type; or a member may be converted from a specific type to
976 an alternate that represents a choice between the original type and
977 something else.
979 query-qmp-schema returns a JSON array of SchemaInfo objects.  These
980 objects together describe the wire ABI, as defined in the QAPI schema.
981 There is no specified order to the SchemaInfo objects returned; a
982 client must search for a particular name throughout the entire array
983 to learn more about that name, but is at least guaranteed that there
984 will be no collisions between type, command, and event names.
986 However, the SchemaInfo can't reflect all the rules and restrictions
987 that apply to QMP.  It's interface introspection (figuring out what's
988 there), not interface specification.  The specification is in the QAPI
989 schema.  To understand how QMP is to be used, you need to study the
990 QAPI schema.
992 Like any other command, query-qmp-schema is itself defined in the QAPI
993 schema, along with the SchemaInfo type.  This text attempts to give an
994 overview how things work.  For details you need to consult the QAPI
995 schema.
997 SchemaInfo objects have common members "name", "meta-type",
998 "features", and additional variant members depending on the value of
999 meta-type.
1001 Each SchemaInfo object describes a wire ABI entity of a certain
1002 meta-type: a command, event or one of several kinds of type.
1004 SchemaInfo for commands and events have the same name as in the QAPI
1005 schema.
1007 Command and event names are part of the wire ABI, but type names are
1008 not.  Therefore, the SchemaInfo for types have auto-generated
1009 meaningless names.  For readability, the examples in this section use
1010 meaningful type names instead.
1012 Optional member "features" exposes the entity's feature strings as a
1013 JSON array of strings.
1015 To examine a type, start with a command or event using it, then follow
1016 references by name.
1018 QAPI schema definitions not reachable that way are omitted.
1020 The SchemaInfo for a command has meta-type "command", and variant
1021 members "arg-type", "ret-type" and "allow-oob".  On the wire, the
1022 "arguments" member of a client's "execute" command must conform to the
1023 object type named by "arg-type".  The "return" member that the server
1024 passes in a success response conforms to the type named by "ret-type".
1025 When "allow-oob" is true, it means the command supports out-of-band
1026 execution.  It defaults to false.
1028 If the command takes no arguments, "arg-type" names an object type
1029 without members.  Likewise, if the command returns nothing, "ret-type"
1030 names an object type without members.
1032 Example: the SchemaInfo for command query-qmp-schema
1034     { "name": "query-qmp-schema", "meta-type": "command",
1035       "arg-type": "q_empty", "ret-type": "SchemaInfoList" }
1037     Type "q_empty" is an automatic object type without members, and type
1038     "SchemaInfoList" is the array of SchemaInfo type.
1040 The SchemaInfo for an event has meta-type "event", and variant member
1041 "arg-type".  On the wire, a "data" member that the server passes in an
1042 event conforms to the object type named by "arg-type".
1044 If the event carries no additional information, "arg-type" names an
1045 object type without members.  The event may not have a data member on
1046 the wire then.
1048 Each command or event defined with 'data' as MEMBERS object in the
1049 QAPI schema implicitly defines an object type.
1051 Example: the SchemaInfo for EVENT_C from section Events
1053     { "name": "EVENT_C", "meta-type": "event",
1054       "arg-type": "q_obj-EVENT_C-arg" }
1056     Type "q_obj-EVENT_C-arg" is an implicitly defined object type with
1057     the two members from the event's definition.
1059 The SchemaInfo for struct and union types has meta-type "object".
1061 The SchemaInfo for a struct type has variant member "members".
1063 The SchemaInfo for a union type additionally has variant members "tag"
1064 and "variants".
1066 "members" is a JSON array describing the object's common members, if
1067 any.  Each element is a JSON object with members "name" (the member's
1068 name), "type" (the name of its type), and optionally "default".  The
1069 member is optional if "default" is present.  Currently, "default" can
1070 only have value null.  Other values are reserved for future
1071 extensions.  The "members" array is in no particular order; clients
1072 must search the entire object when learning whether a particular
1073 member is supported.
1075 Example: the SchemaInfo for MyType from section Struct types
1077     { "name": "MyType", "meta-type": "object",
1078       "members": [
1079           { "name": "member1", "type": "str" },
1080           { "name": "member2", "type": "int" },
1081           { "name": "member3", "type": "str", "default": null } ] }
1083 "features" exposes the command's feature strings as a JSON array of
1084 strings.
1086 Example: the SchemaInfo for TestType from section Features:
1088     { "name": "TestType", "meta-type": "object",
1089       "members": [
1090           { "name": "number", "type": "int" } ],
1091       "features": ["allow-negative-numbers"] }
1093 "tag" is the name of the common member serving as type tag.
1094 "variants" is a JSON array describing the object's variant members.
1095 Each element is a JSON object with members "case" (the value of type
1096 tag this element applies to) and "type" (the name of an object type
1097 that provides the variant members for this type tag value).  The
1098 "variants" array is in no particular order, and is not guaranteed to
1099 list cases in the same order as the corresponding "tag" enum type.
1101 Example: the SchemaInfo for flat union BlockdevOptions from section
1102 Union types
1104     { "name": "BlockdevOptions", "meta-type": "object",
1105       "members": [
1106           { "name": "driver", "type": "BlockdevDriver" },
1107           { "name": "read-only", "type": "bool", "default": null } ],
1108       "tag": "driver",
1109       "variants": [
1110           { "case": "file", "type": "BlockdevOptionsFile" },
1111           { "case": "qcow2", "type": "BlockdevOptionsQcow2" } ] }
1113 Note that base types are "flattened": its members are included in the
1114 "members" array.
1116 A simple union implicitly defines an enumeration type for its implicit
1117 discriminator (called "type" on the wire, see section Union types).
1119 A simple union implicitly defines an object type for each of its
1120 variants.
1122 Example: the SchemaInfo for simple union BlockdevOptionsSimple from section
1123 Union types
1125     { "name": "BlockdevOptionsSimple", "meta-type": "object",
1126       "members": [
1127           { "name": "type", "type": "BlockdevOptionsSimpleKind" } ],
1128       "tag": "type",
1129       "variants": [
1130           { "case": "file", "type": "q_obj-BlockdevOptionsFile-wrapper" },
1131           { "case": "qcow2", "type": "q_obj-BlockdevOptionsQcow2-wrapper" } ] }
1133     Enumeration type "BlockdevOptionsSimpleKind" and the object types
1134     "q_obj-BlockdevOptionsFile-wrapper", "q_obj-BlockdevOptionsQcow2-wrapper"
1135     are implicitly defined.
1137 The SchemaInfo for an alternate type has meta-type "alternate", and
1138 variant member "members".  "members" is a JSON array.  Each element is
1139 a JSON object with member "type", which names a type.  Values of the
1140 alternate type conform to exactly one of its member types.  There is
1141 no guarantee on the order in which "members" will be listed.
1143 Example: the SchemaInfo for BlockdevRef from section Alternate types
1145     { "name": "BlockdevRef", "meta-type": "alternate",
1146       "members": [
1147           { "type": "BlockdevOptions" },
1148           { "type": "str" } ] }
1150 The SchemaInfo for an array type has meta-type "array", and variant
1151 member "element-type", which names the array's element type.  Array
1152 types are implicitly defined.  For convenience, the array's name may
1153 resemble the element type; however, clients should examine member
1154 "element-type" instead of making assumptions based on parsing member
1155 "name".
1157 Example: the SchemaInfo for ['str']
1159     { "name": "[str]", "meta-type": "array",
1160       "element-type": "str" }
1162 The SchemaInfo for an enumeration type has meta-type "enum" and
1163 variant member "values".  The values are listed in no particular
1164 order; clients must search the entire enum when learning whether a
1165 particular value is supported.
1167 Example: the SchemaInfo for MyEnum from section Enumeration types
1169     { "name": "MyEnum", "meta-type": "enum",
1170       "values": [ "value1", "value2", "value3" ] }
1172 The SchemaInfo for a built-in type has the same name as the type in
1173 the QAPI schema (see section Built-in Types), with one exception
1174 detailed below.  It has variant member "json-type" that shows how
1175 values of this type are encoded on the wire.
1177 Example: the SchemaInfo for str
1179     { "name": "str", "meta-type": "builtin", "json-type": "string" }
1181 The QAPI schema supports a number of integer types that only differ in
1182 how they map to C.  They are identical as far as SchemaInfo is
1183 concerned.  Therefore, they get all mapped to a single type "int" in
1184 SchemaInfo.
1186 As explained above, type names are not part of the wire ABI.  Not even
1187 the names of built-in types.  Clients should examine member
1188 "json-type" instead of hard-coding names of built-in types.
1191 == Compatibility considerations ==
1193 Maintaining backward compatibility at the Client JSON Protocol level
1194 while evolving the schema requires some care.  This section is about
1195 syntactic compatibility, which is necessary, but not sufficient, for
1196 actual compatibility.
1198 Clients send commands with argument data, and receive command
1199 responses with return data and events with event data.
1201 Adding opt-in functionality to the send direction is backwards
1202 compatible: adding commands, optional arguments, enumeration values,
1203 union and alternate branches; turning an argument type into an
1204 alternate of that type; making mandatory arguments optional.  Clients
1205 oblivious of the new functionality continue to work.
1207 Incompatible changes include removing commands, command arguments,
1208 enumeration values, union and alternate branches, adding mandatory
1209 command arguments, and making optional arguments mandatory.
1211 The specified behavior of an absent optional argument should remain
1212 the same.  With proper documentation, this policy still allows some
1213 flexibility; for example, when an optional 'buffer-size' argument is
1214 specified to default to a sensible buffer size, the actual default
1215 value can still be changed.  The specified default behavior is not the
1216 exact size of the buffer, only that the default size is sensible.
1218 Adding functionality to the receive direction is generally backwards
1219 compatible: adding events, adding return and event data members.
1220 Clients are expected to ignore the ones they don't know.
1222 Removing "unreachable" stuff like events that can't be triggered
1223 anymore, optional return or event data members that can't be sent
1224 anymore, and return or event data member (enumeration) values that
1225 can't be sent anymore makes no difference to clients, except for
1226 introspection.  The latter can conceivably confuse clients, so tread
1227 carefully.
1229 Incompatible changes include removing return and event data members.
1231 Any change to a command definition's 'data' or one of the types used
1232 there (recursively) needs to consider send direction compatibility.
1234 Any change to a command definition's 'return', an event definition's
1235 'data', or one of the types used there (recursively) needs to consider
1236 receive direction compatibility.
1238 Any change to types used in both contexts need to consider both.
1240 Enumeration type values and complex and alternate type members may be
1241 reordered freely.  For enumerations and alternate types, this doesn't
1242 affect the wire encoding.  For complex types, this might make the
1243 implementation emit JSON object members in a different order, which
1244 the Client JSON Protocol permits.
1246 Since type names are not visible in the Client JSON Protocol, types
1247 may be freely renamed.  Even certain refactorings are invisible, such
1248 as splitting members from one type into a common base type.
1251 == Code generation ==
1253 The QAPI code generator qapi-gen.py generates code and documentation
1254 from the schema.  Together with the core QAPI libraries, this code
1255 provides everything required to take JSON commands read in by a Client
1256 JSON Protocol server, unmarshal the arguments into the underlying C
1257 types, call into the corresponding C function, map the response back
1258 to a Client JSON Protocol response to be returned to the user, and
1259 introspect the commands.
1261 As an example, we'll use the following schema, which describes a
1262 single complex user-defined type, along with command which takes a
1263 list of that type as a parameter, and returns a single element of that
1264 type.  The user is responsible for writing the implementation of
1265 qmp_my_command(); everything else is produced by the generator.
1267     $ cat example-schema.json
1268     { 'struct': 'UserDefOne',
1269       'data': { 'integer': 'int', '*string': 'str' } }
1271     { 'command': 'my-command',
1272       'data': { 'arg1': ['UserDefOne'] },
1273       'returns': 'UserDefOne' }
1275     { 'event': 'MY_EVENT' }
1277 We run qapi-gen.py like this:
1279     $ python scripts/qapi-gen.py --output-dir="qapi-generated" \
1280     --prefix="example-" example-schema.json
1282 For a more thorough look at generated code, the testsuite includes
1283 tests/qapi-schema/qapi-schema-tests.json that covers more examples of
1284 what the generator will accept, and compiles the resulting C code as
1285 part of 'make check-unit'.
1287 === Code generated for QAPI types ===
1289 The following files are created:
1291 $(prefix)qapi-types.h - C types corresponding to types defined in
1292                         the schema
1294 $(prefix)qapi-types.c - Cleanup functions for the above C types
1296 The $(prefix) is an optional parameter used as a namespace to keep the
1297 generated code from one schema/code-generation separated from others so code
1298 can be generated/used from multiple schemas without clobbering previously
1299 created code.
1301 Example:
1303     $ cat qapi-generated/example-qapi-types.h
1304 [Uninteresting stuff omitted...]
1306     #ifndef EXAMPLE_QAPI_TYPES_H
1307     #define EXAMPLE_QAPI_TYPES_H
1309     #include "qapi/qapi-builtin-types.h"
1311     typedef struct UserDefOne UserDefOne;
1313     typedef struct UserDefOneList UserDefOneList;
1315     typedef struct q_obj_my_command_arg q_obj_my_command_arg;
1317     struct UserDefOne {
1318         int64_t integer;
1319         bool has_string;
1320         char *string;
1321     };
1323     void qapi_free_UserDefOne(UserDefOne *obj);
1325     struct UserDefOneList {
1326         UserDefOneList *next;
1327         UserDefOne *value;
1328     };
1330     void qapi_free_UserDefOneList(UserDefOneList *obj);
1332     struct q_obj_my_command_arg {
1333         UserDefOneList *arg1;
1334     };
1336     #endif /* EXAMPLE_QAPI_TYPES_H */
1337     $ cat qapi-generated/example-qapi-types.c
1338 [Uninteresting stuff omitted...]
1340     void qapi_free_UserDefOne(UserDefOne *obj)
1341     {
1342         Visitor *v;
1344         if (!obj) {
1345             return;
1346         }
1348         v = qapi_dealloc_visitor_new();
1349         visit_type_UserDefOne(v, NULL, &obj, NULL);
1350         visit_free(v);
1351     }
1353     void qapi_free_UserDefOneList(UserDefOneList *obj)
1354     {
1355         Visitor *v;
1357         if (!obj) {
1358             return;
1359         }
1361         v = qapi_dealloc_visitor_new();
1362         visit_type_UserDefOneList(v, NULL, &obj, NULL);
1363         visit_free(v);
1364     }
1366 [Uninteresting stuff omitted...]
1368 For a modular QAPI schema (see section Include directives), code for
1369 each sub-module SUBDIR/SUBMODULE.json is actually generated into
1371 SUBDIR/$(prefix)qapi-types-SUBMODULE.h
1372 SUBDIR/$(prefix)qapi-types-SUBMODULE.c
1374 If qapi-gen.py is run with option --builtins, additional files are
1375 created:
1377 qapi-builtin-types.h - C types corresponding to built-in types
1379 qapi-builtin-types.c - Cleanup functions for the above C types
1381 === Code generated for visiting QAPI types ===
1383 These are the visitor functions used to walk through and convert
1384 between a native QAPI C data structure and some other format (such as
1385 QObject); the generated functions are named visit_type_FOO() and
1386 visit_type_FOO_members().
1388 The following files are generated:
1390 $(prefix)qapi-visit.c: Visitor function for a particular C type, used
1391                        to automagically convert QObjects into the
1392                        corresponding C type and vice-versa, as well
1393                        as for deallocating memory for an existing C
1394                        type
1396 $(prefix)qapi-visit.h: Declarations for previously mentioned visitor
1397                        functions
1399 Example:
1401     $ cat qapi-generated/example-qapi-visit.h
1402 [Uninteresting stuff omitted...]
1404     #ifndef EXAMPLE_QAPI_VISIT_H
1405     #define EXAMPLE_QAPI_VISIT_H
1407     #include "qapi/qapi-builtin-visit.h"
1408     #include "example-qapi-types.h"
1411     void visit_type_UserDefOne_members(Visitor *v, UserDefOne *obj, Error **errp);
1412     void visit_type_UserDefOne(Visitor *v, const char *name, UserDefOne **obj, Error **errp);
1413     void visit_type_UserDefOneList(Visitor *v, const char *name, UserDefOneList **obj, Error **errp);
1415     void visit_type_q_obj_my_command_arg_members(Visitor *v, q_obj_my_command_arg *obj, Error **errp);
1417     #endif /* EXAMPLE_QAPI_VISIT_H */
1418     $ cat qapi-generated/example-qapi-visit.c
1419 [Uninteresting stuff omitted...]
1421     void visit_type_UserDefOne_members(Visitor *v, UserDefOne *obj, Error **errp)
1422     {
1423         Error *err = NULL;
1425         visit_type_int(v, "integer", &obj->integer, &err);
1426         if (err) {
1427             goto out;
1428         }
1429         if (visit_optional(v, "string", &obj->has_string)) {
1430             visit_type_str(v, "string", &obj->string, &err);
1431             if (err) {
1432                 goto out;
1433             }
1434         }
1436     out:
1437         error_propagate(errp, err);
1438     }
1440     void visit_type_UserDefOne(Visitor *v, const char *name, UserDefOne **obj, Error **errp)
1441     {
1442         Error *err = NULL;
1444         visit_start_struct(v, name, (void **)obj, sizeof(UserDefOne), &err);
1445         if (err) {
1446             goto out;
1447         }
1448         if (!*obj) {
1449             /* incomplete */
1450             assert(visit_is_dealloc(v));
1451             goto out_obj;
1452         }
1453         visit_type_UserDefOne_members(v, *obj, &err);
1454         if (err) {
1455             goto out_obj;
1456         }
1457         visit_check_struct(v, &err);
1458     out_obj:
1459         visit_end_struct(v, (void **)obj);
1460         if (err && visit_is_input(v)) {
1461             qapi_free_UserDefOne(*obj);
1462             *obj = NULL;
1463         }
1464     out:
1465         error_propagate(errp, err);
1466     }
1468     void visit_type_UserDefOneList(Visitor *v, const char *name, UserDefOneList **obj, Error **errp)
1469     {
1470         Error *err = NULL;
1471         UserDefOneList *tail;
1472         size_t size = sizeof(**obj);
1474         visit_start_list(v, name, (GenericList **)obj, size, &err);
1475         if (err) {
1476             goto out;
1477         }
1479         for (tail = *obj; tail;
1480              tail = (UserDefOneList *)visit_next_list(v, (GenericList *)tail, size)) {
1481             visit_type_UserDefOne(v, NULL, &tail->value, &err);
1482             if (err) {
1483                 break;
1484             }
1485         }
1487         if (!err) {
1488             visit_check_list(v, &err);
1489         }
1490         visit_end_list(v, (void **)obj);
1491         if (err && visit_is_input(v)) {
1492             qapi_free_UserDefOneList(*obj);
1493             *obj = NULL;
1494         }
1495     out:
1496         error_propagate(errp, err);
1497     }
1499     void visit_type_q_obj_my_command_arg_members(Visitor *v, q_obj_my_command_arg *obj, Error **errp)
1500     {
1501         Error *err = NULL;
1503         visit_type_UserDefOneList(v, "arg1", &obj->arg1, &err);
1504         if (err) {
1505             goto out;
1506         }
1508     out:
1509         error_propagate(errp, err);
1510     }
1512 [Uninteresting stuff omitted...]
1514 For a modular QAPI schema (see section Include directives), code for
1515 each sub-module SUBDIR/SUBMODULE.json is actually generated into
1517 SUBDIR/$(prefix)qapi-visit-SUBMODULE.h
1518 SUBDIR/$(prefix)qapi-visit-SUBMODULE.c
1520 If qapi-gen.py is run with option --builtins, additional files are
1521 created:
1523 qapi-builtin-visit.h - Visitor functions for built-in types
1525 qapi-builtin-visit.c - Declarations for these visitor functions
1527 === Code generated for commands ===
1529 These are the marshaling/dispatch functions for the commands defined
1530 in the schema.  The generated code provides qmp_marshal_COMMAND(), and
1531 declares qmp_COMMAND() that the user must implement.
1533 The following files are generated:
1535 $(prefix)qapi-commands.c: Command marshal/dispatch functions for each
1536                           QMP command defined in the schema
1538 $(prefix)qapi-commands.h: Function prototypes for the QMP commands
1539                           specified in the schema
1541 $(prefix)qapi-init-commands.h - Command initialization prototype
1543 $(prefix)qapi-init-commands.c - Command initialization code
1545 Example:
1547     $ cat qapi-generated/example-qapi-commands.h
1548 [Uninteresting stuff omitted...]
1550     #ifndef EXAMPLE_QAPI_COMMANDS_H
1551     #define EXAMPLE_QAPI_COMMANDS_H
1553     #include "example-qapi-types.h"
1555     UserDefOne *qmp_my_command(UserDefOneList *arg1, Error **errp);
1556     void qmp_marshal_my_command(QDict *args, QObject **ret, Error **errp);
1558     #endif /* EXAMPLE_QAPI_COMMANDS_H */
1559     $ cat qapi-generated/example-qapi-commands.c
1560 [Uninteresting stuff omitted...]
1562     static void qmp_marshal_output_UserDefOne(UserDefOne *ret_in, QObject **ret_out, Error **errp)
1563     {
1564         Error *err = NULL;
1565         Visitor *v;
1567         v = qobject_output_visitor_new(ret_out);
1568         visit_type_UserDefOne(v, "unused", &ret_in, &err);
1569         if (!err) {
1570             visit_complete(v, ret_out);
1571         }
1572         error_propagate(errp, err);
1573         visit_free(v);
1574         v = qapi_dealloc_visitor_new();
1575         visit_type_UserDefOne(v, "unused", &ret_in, NULL);
1576         visit_free(v);
1577     }
1579     void qmp_marshal_my_command(QDict *args, QObject **ret, Error **errp)
1580     {
1581         Error *err = NULL;
1582         Visitor *v;
1583         UserDefOne *retval;
1584         q_obj_my_command_arg arg = {0};
1586         v = qobject_input_visitor_new(QOBJECT(args));
1587         visit_start_struct(v, NULL, NULL, 0, &err);
1588         if (err) {
1589             goto out;
1590         }
1591         visit_type_q_obj_my_command_arg_members(v, &arg, &err);
1592         if (!err) {
1593             visit_check_struct(v, &err);
1594         }
1595         visit_end_struct(v, NULL);
1596         if (err) {
1597             goto out;
1598         }
1600         retval = qmp_my_command(arg.arg1, &err);
1601         if (err) {
1602             goto out;
1603         }
1605         qmp_marshal_output_UserDefOne(retval, ret, &err);
1607     out:
1608         error_propagate(errp, err);
1609         visit_free(v);
1610         v = qapi_dealloc_visitor_new();
1611         visit_start_struct(v, NULL, NULL, 0, NULL);
1612         visit_type_q_obj_my_command_arg_members(v, &arg, NULL);
1613         visit_end_struct(v, NULL);
1614         visit_free(v);
1615     }
1616 [Uninteresting stuff omitted...]
1617     $ cat qapi-generated/example-qapi-init-commands.h
1618 [Uninteresting stuff omitted...]
1619     #ifndef EXAMPLE_QAPI_INIT_COMMANDS_H
1620     #define EXAMPLE_QAPI_INIT_COMMANDS_H
1622     #include "qapi/qmp/dispatch.h"
1624     void example_qmp_init_marshal(QmpCommandList *cmds);
1626     #endif /* EXAMPLE_QAPI_INIT_COMMANDS_H */
1627     $ cat qapi-generated/example-qapi-init-commands.c
1628 [Uninteresting stuff omitted...]
1629     void example_qmp_init_marshal(QmpCommandList *cmds)
1630     {
1631         QTAILQ_INIT(cmds);
1633         qmp_register_command(cmds, "my-command",
1634                              qmp_marshal_my_command, QCO_NO_OPTIONS);
1635     }
1636 [Uninteresting stuff omitted...]
1638 For a modular QAPI schema (see section Include directives), code for
1639 each sub-module SUBDIR/SUBMODULE.json is actually generated into
1641 SUBDIR/$(prefix)qapi-commands-SUBMODULE.h
1642 SUBDIR/$(prefix)qapi-commands-SUBMODULE.c
1644 === Code generated for events ===
1646 This is the code related to events defined in the schema, providing
1647 qapi_event_send_EVENT().
1649 The following files are created:
1651 $(prefix)qapi-events.h - Function prototypes for each event type
1653 $(prefix)qapi-events.c - Implementation of functions to send an event
1655 $(prefix)qapi-emit-events.h - Enumeration of all event names, and
1656                               common event code declarations
1658 $(prefix)qapi-emit-events.c - Common event code definitions
1660 Example:
1662     $ cat qapi-generated/example-qapi-events.h
1663 [Uninteresting stuff omitted...]
1665     #ifndef EXAMPLE_QAPI_EVENTS_H
1666     #define EXAMPLE_QAPI_EVENTS_H
1668     #include "qapi/util.h"
1669     #include "example-qapi-types.h"
1671     void qapi_event_send_my_event(void);
1673     #endif /* EXAMPLE_QAPI_EVENTS_H */
1674     $ cat qapi-generated/example-qapi-events.c
1675 [Uninteresting stuff omitted...]
1677     void qapi_event_send_my_event(void)
1678     {
1679         QDict *qmp;
1681         qmp = qmp_event_build_dict("MY_EVENT");
1683         example_qapi_event_emit(EXAMPLE_QAPI_EVENT_MY_EVENT, qmp);
1685         qobject_unref(qmp);
1686     }
1688 [Uninteresting stuff omitted...]
1689     $ cat qapi-generated/example-qapi-emit-events.h
1690 [Uninteresting stuff omitted...]
1692     #ifndef EXAMPLE_QAPI_EMIT_EVENTS_H
1693     #define EXAMPLE_QAPI_EMIT_EVENTS_H
1695     #include "qapi/util.h"
1697     typedef enum example_QAPIEvent {
1698         EXAMPLE_QAPI_EVENT_MY_EVENT,
1699         EXAMPLE_QAPI_EVENT__MAX,
1700     } example_QAPIEvent;
1702     #define example_QAPIEvent_str(val) \
1703         qapi_enum_lookup(&example_QAPIEvent_lookup, (val))
1705     extern const QEnumLookup example_QAPIEvent_lookup;
1707     void example_qapi_event_emit(example_QAPIEvent event, QDict *qdict);
1709     #endif /* EXAMPLE_QAPI_EMIT_EVENTS_H */
1710     $ cat qapi-generated/example-qapi-emit-events.c
1711 [Uninteresting stuff omitted...]
1713     const QEnumLookup example_QAPIEvent_lookup = {
1714         .array = (const char *const[]) {
1715             [EXAMPLE_QAPI_EVENT_MY_EVENT] = "MY_EVENT",
1716         },
1717         .size = EXAMPLE_QAPI_EVENT__MAX
1718     };
1720 [Uninteresting stuff omitted...]
1722 For a modular QAPI schema (see section Include directives), code for
1723 each sub-module SUBDIR/SUBMODULE.json is actually generated into
1725 SUBDIR/$(prefix)qapi-events-SUBMODULE.h
1726 SUBDIR/$(prefix)qapi-events-SUBMODULE.c
1728 === Code generated for introspection ===
1730 The following files are created:
1732 $(prefix)qapi-introspect.c - Defines a string holding a JSON
1733                             description of the schema
1735 $(prefix)qapi-introspect.h - Declares the above string
1737 Example:
1739     $ cat qapi-generated/example-qapi-introspect.h
1740 [Uninteresting stuff omitted...]
1742     #ifndef EXAMPLE_QAPI_INTROSPECT_H
1743     #define EXAMPLE_QAPI_INTROSPECT_H
1745     #include "qapi/qmp/qlit.h"
1747     extern const QLitObject example_qmp_schema_qlit;
1749     #endif /* EXAMPLE_QAPI_INTROSPECT_H */
1750     $ cat qapi-generated/example-qapi-introspect.c
1751 [Uninteresting stuff omitted...]
1753     const QLitObject example_qmp_schema_qlit = QLIT_QLIST(((QLitObject[]) {
1754         QLIT_QDICT(((QLitDictEntry[]) {
1755             { "arg-type", QLIT_QSTR("0"), },
1756             { "meta-type", QLIT_QSTR("command"), },
1757             { "name", QLIT_QSTR("my-command"), },
1758             { "ret-type", QLIT_QSTR("1"), },
1759             {}
1760         })),
1761         QLIT_QDICT(((QLitDictEntry[]) {
1762             { "arg-type", QLIT_QSTR("2"), },
1763             { "meta-type", QLIT_QSTR("event"), },
1764             { "name", QLIT_QSTR("MY_EVENT"), },
1765             {}
1766         })),
1767         /* "0" = q_obj_my-command-arg */
1768         QLIT_QDICT(((QLitDictEntry[]) {
1769             { "members", QLIT_QLIST(((QLitObject[]) {
1770                 QLIT_QDICT(((QLitDictEntry[]) {
1771                     { "name", QLIT_QSTR("arg1"), },
1772                     { "type", QLIT_QSTR("[1]"), },
1773                     {}
1774                 })),
1775                 {}
1776             })), },
1777             { "meta-type", QLIT_QSTR("object"), },
1778             { "name", QLIT_QSTR("0"), },
1779             {}
1780         })),
1781         /* "1" = UserDefOne */
1782         QLIT_QDICT(((QLitDictEntry[]) {
1783             { "members", QLIT_QLIST(((QLitObject[]) {
1784                 QLIT_QDICT(((QLitDictEntry[]) {
1785                     { "name", QLIT_QSTR("integer"), },
1786                     { "type", QLIT_QSTR("int"), },
1787                     {}
1788                 })),
1789                 QLIT_QDICT(((QLitDictEntry[]) {
1790                     { "default", QLIT_QNULL, },
1791                     { "name", QLIT_QSTR("string"), },
1792                     { "type", QLIT_QSTR("str"), },
1793                     {}
1794                 })),
1795                 {}
1796             })), },
1797             { "meta-type", QLIT_QSTR("object"), },
1798             { "name", QLIT_QSTR("1"), },
1799             {}
1800         })),
1801         /* "2" = q_empty */
1802         QLIT_QDICT(((QLitDictEntry[]) {
1803             { "members", QLIT_QLIST(((QLitObject[]) {
1804                 {}
1805             })), },
1806             { "meta-type", QLIT_QSTR("object"), },
1807             { "name", QLIT_QSTR("2"), },
1808             {}
1809         })),
1810         QLIT_QDICT(((QLitDictEntry[]) {
1811             { "element-type", QLIT_QSTR("1"), },
1812             { "meta-type", QLIT_QSTR("array"), },
1813             { "name", QLIT_QSTR("[1]"), },
1814             {}
1815         })),
1816         QLIT_QDICT(((QLitDictEntry[]) {
1817             { "json-type", QLIT_QSTR("int"), },
1818             { "meta-type", QLIT_QSTR("builtin"), },
1819             { "name", QLIT_QSTR("int"), },
1820             {}
1821         })),
1822         QLIT_QDICT(((QLitDictEntry[]) {
1823             { "json-type", QLIT_QSTR("string"), },
1824             { "meta-type", QLIT_QSTR("builtin"), },
1825             { "name", QLIT_QSTR("str"), },
1826             {}
1827         })),
1828         {}
1829     }));
1831 [Uninteresting stuff omitted...]