spapr/xive: Configure number of servers in KVM
[qemu/ar7.git] / docs / devel / qapi-code-gen.txt
blob45c93a43cc36c900f666b973164957ec8e81b08b
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     ENUM-VALUE = STRING
177                | { 'name': STRING, '*if': COND }
179 Member 'enum' names the enum type.
181 Each member of the 'data' array defines a value of the enumeration
182 type.  The form STRING is shorthand for { 'name': STRING }.  The
183 'name' values must be be distinct.
185 Example:
187  { 'enum': 'MyEnum', 'data': [ 'value1', 'value2', 'value3' ] }
189 Nothing prevents an empty enumeration, although it is probably not
190 useful.
192 On the wire, an enumeration type's value is represented by its
193 (string) name.  In C, it's represented by an enumeration constant.
194 These are of the form PREFIX_NAME, where PREFIX is derived from the
195 enumeration type's name, and NAME from the value's name.  For the
196 example above, the generator maps 'MyEnum' to MY_ENUM and 'value1' to
197 VALUE1, resulting in the enumeration constant MY_ENUM_VALUE1.  The
198 optional 'prefix' member overrides PREFIX.
200 The generated C enumeration constants have values 0, 1, ..., N-1 (in
201 QAPI schema order), where N is the number of values.  There is an
202 additional enumeration constant PREFIX__MAX with value N.
204 Do not use string or an integer type when an enumeration type can do
205 the job satisfactorily.
207 The optional 'if' member specifies a conditional.  See "Configuring
208 the schema" below for more on this.
211 === Type references and array types ===
213 Syntax:
214     TYPE-REF = STRING | ARRAY-TYPE
215     ARRAY-TYPE = [ STRING ]
217 A string denotes the type named by the string.
219 A one-element array containing a string denotes an array of the type
220 named by the string.  Example: ['int'] denotes an array of 'int'.
223 === Struct types ===
225 Syntax:
226     STRUCT = { 'struct': STRING,
227                'data': MEMBERS,
228                '*base': STRING,
229                '*if': COND,
230                '*features': FEATURES }
231     MEMBERS = { MEMBER, ... }
232     MEMBER = STRING : TYPE-REF
233            | STRING : { 'type': TYPE-REF, '*if': COND }
235 Member 'struct' names the struct type.
237 Each MEMBER of the 'data' object defines a member of the struct type.
239 The MEMBER's STRING name consists of an optional '*' prefix and the
240 struct member name.  If '*' is present, the member is optional.
242 The MEMBER's value defines its properties, in particular its type.
243 The form TYPE-REF is shorthand for { 'type': TYPE-REF }.
245 Example:
247  { 'struct': 'MyType',
248    'data': { 'member1': 'str', 'member2': ['int'], '*member3': 'str' } }
250 A struct type corresponds to a struct in C, and an object in JSON.
251 The C struct's members are generated in QAPI schema order.
253 The optional 'base' member names a struct type whose members are to be
254 included in this type.  They go first in the C struct.
256 Example:
258  { 'struct': 'BlockdevOptionsGenericFormat',
259    'data': { 'file': 'str' } }
260  { 'struct': 'BlockdevOptionsGenericCOWFormat',
261    'base': 'BlockdevOptionsGenericFormat',
262    'data': { '*backing': 'str' } }
264 An example BlockdevOptionsGenericCOWFormat object on the wire could use
265 both members like this:
267  { "file": "/some/place/my-image",
268    "backing": "/some/place/my-backing-file" }
270 The optional 'if' member specifies a conditional.  See "Configuring
271 the schema" below for more on this.
273 The optional 'features' member specifies features.  See "Features"
274 below for more on this.
277 === Union types ===
279 Syntax:
280     UNION = { 'union': STRING,
281               'data': BRANCHES,
282               '*if': COND }
283           | { 'union': STRING,
284               'data': BRANCHES,
285               'base': ( MEMBERS | STRING ),
286               'discriminator': STRING,
287               '*if': COND }
288     BRANCHES = { BRANCH, ... }
289     BRANCH = STRING : TYPE-REF
290            | STRING : { 'type': TYPE-REF, '*if': COND }
292 Member 'union' names the union type.
294 There are two flavors of union types: simple (no discriminator or
295 base), and flat (both discriminator and base).
297 Each BRANCH of the 'data' object defines a branch of the union.  A
298 union must have at least one branch.
300 The BRANCH's STRING name is the branch name.
302 The BRANCH's value defines the branch's properties, in particular its
303 type.  The form TYPE-REF is shorthand for { 'type': TYPE-REF }.
305 A simple union type defines a mapping from automatic discriminator
306 values to data types like in this example:
308  { 'struct': 'BlockdevOptionsFile', 'data': { 'filename': 'str' } }
309  { 'struct': 'BlockdevOptionsQcow2',
310    'data': { 'backing': 'str', '*lazy-refcounts': 'bool' } }
312  { 'union': 'BlockdevOptionsSimple',
313    'data': { 'file': 'BlockdevOptionsFile',
314              'qcow2': 'BlockdevOptionsQcow2' } }
316 In the Client JSON Protocol, a simple union is represented by an
317 object that contains the 'type' member as a discriminator, and a
318 'data' member that is of the specified data type corresponding to the
319 discriminator value, as in these examples:
321  { "type": "file", "data": { "filename": "/some/place/my-image" } }
322  { "type": "qcow2", "data": { "backing": "/some/place/my-image",
323                               "lazy-refcounts": true } }
325 The generated C code uses a struct containing a union.  Additionally,
326 an implicit C enum 'NameKind' is created, corresponding to the union
327 'Name', for accessing the various branches of the union.  The value
328 for each branch can be of any type.
330 Flat unions permit arbitrary common members that occur in all variants
331 of the union, not just a discriminator.  Their discriminators need not
332 be named 'type'.  They also avoid nesting on the wire.
334 The 'base' member defines the common members.  If it is a MEMBERS
335 object, it defines common members just like a struct type's 'data'
336 member defines struct type members.  If it is a STRING, it names a
337 struct type whose members are the common members.
339 All flat union branches must be of struct type.
341 In the Client JSON Protocol, a flat union is represented by an object
342 with the common members (from the base type) and the selected branch's
343 members.  The two sets of member names must be disjoint.  Member
344 'discriminator' must name a non-optional enum-typed member of the base
345 struct.
347 The following example enhances the above simple union example by
348 adding an optional common member 'read-only', renaming the
349 discriminator to something more applicable than the simple union's
350 default of 'type', and reducing the number of {} required on the wire:
352  { 'enum': 'BlockdevDriver', 'data': [ 'file', 'qcow2' ] }
353  { 'union': 'BlockdevOptions',
354    'base': { 'driver': 'BlockdevDriver', '*read-only': 'bool' },
355    'discriminator': 'driver',
356    'data': { 'file': 'BlockdevOptionsFile',
357              'qcow2': 'BlockdevOptionsQcow2' } }
359 Resulting in these JSON objects:
361  { "driver": "file", "read-only": true,
362    "filename": "/some/place/my-image" }
363  { "driver": "qcow2", "read-only": false,
364    "backing": "/some/place/my-image", "lazy-refcounts": true }
366 Notice that in a flat union, the discriminator name is controlled by
367 the user, but because it must map to a base member with enum type, the
368 code generator ensures that branches match the existing values of the
369 enum.  The order of branches need not match the order of the enum
370 values.  The branches need not cover all possible enum values.
371 Omitted enum values are still valid branches that add no additional
372 members to the data type.  In the resulting generated C data types, a
373 flat union is represented as a struct with the base members in QAPI
374 schema order, and then a union of structures for each branch of the
375 struct.
377 A simple union can always be re-written as a flat union where the base
378 class has a single member named 'type', and where each branch of the
379 union has a struct with a single member named 'data'.  That is,
381  { 'union': 'Simple', 'data': { 'one': 'str', 'two': 'int' } }
383 is identical on the wire to:
385  { 'enum': 'Enum', 'data': ['one', 'two'] }
386  { 'struct': 'Branch1', 'data': { 'data': 'str' } }
387  { 'struct': 'Branch2', 'data': { 'data': 'int' } }
388  { 'union': 'Flat': 'base': { 'type': 'Enum' }, 'discriminator': 'type',
389    'data': { 'one': 'Branch1', 'two': 'Branch2' } }
391 The optional 'if' member specifies a conditional.  See "Configuring
392 the schema" below for more on this.
395 === Alternate types ===
397 Syntax:
398     ALTERNATE = { 'alternate': STRING,
399                   'data': ALTERNATIVES,
400                   '*if': COND }
401     ALTERNATIVES = { ALTERNATIVE, ... }
402     ALTERNATIVE = STRING : TYPE-REF
403                 | STRING : { 'type': STRING, '*if': COND }
405 Member 'alternate' names the alternate type.
407 Each ALTERNATIVE of the 'data' object defines a branch of the
408 alternate.  An alternate must have at least one branch.
410 The ALTERNATIVE's STRING name is the branch name.
412 The ALTERNATIVE's value defines the branch's properties, in particular
413 its type.  The form STRING is shorthand for { 'type': STRING }.
415 Example:
417  { 'alternate': 'BlockdevRef',
418    'data': { 'definition': 'BlockdevOptions',
419              'reference': 'str' } }
421 An alternate type is like a union type, except there is no
422 discriminator on the wire.  Instead, the branch to use is inferred
423 from the value.  An alternate can only express a choice between types
424 represented differently on the wire.
426 If a branch is typed as the 'bool' built-in, the alternate accepts
427 true and false; if it is typed as any of the various numeric
428 built-ins, it accepts a JSON number; if it is typed as a 'str'
429 built-in or named enum type, it accepts a JSON string; if it is typed
430 as the 'null' built-in, it accepts JSON null; and if it is typed as a
431 complex type (struct or union), it accepts a JSON object.
433 The example alternate declaration above allows using both of the
434 following example objects:
436  { "file": "my_existing_block_device_id" }
437  { "file": { "driver": "file",
438              "read-only": false,
439              "filename": "/tmp/mydisk.qcow2" } }
441 The optional 'if' member specifies a conditional.  See "Configuring
442 the schema" below for more on this.
445 === Commands ===
447 Syntax:
448     COMMAND = { 'command': STRING,
449                 (
450                 '*data': ( MEMBERS | STRING ),
451                 |
452                 'data': STRING,
453                 'boxed': true,
454                 )
455                 '*returns': TYPE-REF,
456                 '*success-response': false,
457                 '*gen': false,
458                 '*allow-oob': true,
459                 '*allow-preconfig': true,
460                 '*if': COND,
461                 '*features': FEATURES }
463 Member 'command' names the command.
465 Member 'data' defines the arguments.  It defaults to an empty MEMBERS
466 object.
468 If 'data' is a MEMBERS object, then MEMBERS defines arguments just
469 like a struct type's 'data' defines struct type members.
471 If 'data' is a STRING, then STRING names a complex type whose members
472 are the arguments.  A union type requires 'boxed': true.
474 Member 'returns' defines the command's return type.  It defaults to an
475 empty struct type.  It must normally be a complex type or an array of
476 a complex type.  To return anything else, the command must be listed
477 in pragma 'returns-whitelist'.  If you do this, extending the command
478 to return additional information will be harder.  Use of
479 'returns-whitelist' for new commands is strongly discouraged.
481 A command's error responses are not specified in the QAPI schema.
482 Error conditions should be documented in comments.
484 In the Client JSON Protocol, the value of the "execute" or "exec-oob"
485 member is the command name.  The value of the "arguments" member then
486 has to conform to the arguments, and the value of the success
487 response's "return" member will conform to the return type.
489 Some example commands:
491  { 'command': 'my-first-command',
492    'data': { 'arg1': 'str', '*arg2': 'str' } }
493  { 'struct': 'MyType', 'data': { '*value': 'str' } }
494  { 'command': 'my-second-command',
495    'returns': [ 'MyType' ] }
497 which would validate this Client JSON Protocol transaction:
499  => { "execute": "my-first-command",
500       "arguments": { "arg1": "hello" } }
501  <= { "return": { } }
502  => { "execute": "my-second-command" }
503  <= { "return": [ { "value": "one" }, { } ] }
505 The generator emits a prototype for the C function implementing the
506 command.  The function itself needs to be written by hand.  See
507 section "Code generated for commands" for examples.
509 The function returns the return type.  When member 'boxed' is absent,
510 it takes the command arguments as arguments one by one, in QAPI schema
511 order.  Else it takes them wrapped in the C struct generated for the
512 complex argument type.  It takes an additional Error ** argument in
513 either case.
515 The generator also emits a marshalling function that extracts
516 arguments for the user's function out of an input QDict, calls the
517 user's function, and if it succeeded, builds an output QObject from
518 its return value.  This is for use by the QMP monitor core.
520 In rare cases, QAPI cannot express a type-safe representation of a
521 corresponding Client JSON Protocol command.  You then have to suppress
522 generation of a marshalling function by including a member 'gen' with
523 boolean value false, and instead write your own function.  For
524 example:
526  { 'command': 'netdev_add',
527    'data': {'type': 'str', 'id': 'str'},
528    'gen': false }
530 Please try to avoid adding new commands that rely on this, and instead
531 use type-safe unions.
533 Normally, the QAPI schema is used to describe synchronous exchanges,
534 where a response is expected.  But in some cases, the action of a
535 command is expected to change state in a way that a successful
536 response is not possible (although the command will still return an
537 error object on failure).  When a successful reply is not possible,
538 the command definition includes the optional member 'success-response'
539 with boolean value false.  So far, only QGA makes use of this member.
541 Member 'allow-oob' declares whether the command supports out-of-band
542 (OOB) execution.  It defaults to false.  For example:
544  { 'command': 'migrate_recover',
545    'data': { 'uri': 'str' }, 'allow-oob': true }
547 See qmp-spec.txt for out-of-band execution syntax and semantics.
549 Commands supporting out-of-band execution can still be executed
550 in-band.
552 When a command is executed in-band, its handler runs in the main
553 thread with the BQL held.
555 When a command is executed out-of-band, its handler runs in a
556 dedicated monitor I/O thread with the BQL *not* held.
558 An OOB-capable command handler must satisfy the following conditions:
560 - It terminates quickly.
561 - It does not invoke system calls that may block.
562 - It does not access guest RAM that may block when userfaultfd is
563   enabled for postcopy live migration.
564 - It takes only "fast" locks, i.e. all critical sections protected by
565   any lock it takes also satisfy the conditions for OOB command
566   handler code.
568 The restrictions on locking limit access to shared state.  Such access
569 requires synchronization, but OOB commands can't take the BQL or any
570 other "slow" lock.
572 When in doubt, do not implement OOB execution support.
574 Member 'allow-preconfig' declares whether the command is available
575 before the machine is built.  It defaults to false.  For example:
577  { 'command': 'qmp_capabilities',
578    'data': { '*enable': [ 'QMPCapability' ] },
579    'allow-preconfig': true }
581 QMP is available before the machine is built only when QEMU was
582 started with --preconfig.
584 The optional 'if' member specifies a conditional.  See "Configuring
585 the schema" below for more on this.
588 === Events ===
590 Syntax:
591     EVENT = { 'event': STRING,
592               (
593               '*data': ( MEMBERS | STRING ),
594               |
595               'data': STRING,
596               'boxed': true,
597               )
598               '*if': COND }
600 Member 'event' names the event.  This is the event name used in the
601 Client JSON Protocol.
603 Member 'data' defines the event-specific data.  It defaults to an
604 empty MEMBERS object.
606 If 'data' is a MEMBERS object, then MEMBERS defines event-specific
607 data just like a struct type's 'data' defines struct type members.
609 If 'data' is a STRING, then STRING names a complex type whose members
610 are the event-specific data.  A union type requires 'boxed': true.
612 An example event is:
614 { 'event': 'EVENT_C',
615   'data': { '*a': 'int', 'b': 'str' } }
617 Resulting in this JSON object:
619 { "event": "EVENT_C",
620   "data": { "b": "test string" },
621   "timestamp": { "seconds": 1267020223, "microseconds": 435656 } }
623 The generator emits a function to send the event.  When member 'boxed'
624 is absent, it takes event-specific data one by one, in QAPI schema
625 order.  Else it takes them wrapped in the C struct generated for the
626 complex type.  See section "Code generated for events" for examples.
628 The optional 'if' member specifies a conditional.  See "Configuring
629 the schema" below for more on this.
632 === Features ===
634 Syntax:
635     FEATURES = [ FEATURE, ... ]
636     FEATURE = STRING
637             | { 'name': STRING, '*if': COND }
639 Sometimes, the behaviour of QEMU changes compatibly, but without a
640 change in the QMP syntax (usually by allowing values or operations
641 that previously resulted in an error).  QMP clients may still need to
642 know whether the extension is available.
644 For this purpose, a list of features can be specified for a command or
645 struct type.  This is exposed to the client as a list of strings,
646 where each string signals that this build of QEMU shows a certain
647 behaviour.
649 Each member of the 'features' array defines a feature.  It can either
650 be { 'name': STRING, '*if': COND }, or STRING, which is shorthand for
651 { 'name': STRING }.
653 The optional 'if' member specifies a conditional.  See "Configuring
654 the schema" below for more on this.
656 Example:
658 { 'struct': 'TestType',
659   'data': { 'number': 'int' },
660   'features': [ 'allow-negative-numbers' ] }
663 === Naming rules and reserved names ===
665 All names must begin with a letter, and contain only ASCII letters,
666 digits, hyphen, and underscore.  There are two exceptions: enum values
667 may start with a digit, and names that are downstream extensions (see
668 section Downstream extensions) start with underscore.
670 Names beginning with 'q_' are reserved for the generator, which uses
671 them for munging QMP names that resemble C keywords or other
672 problematic strings.  For example, a member named "default" in qapi
673 becomes "q_default" in the generated C code.
675 Types, commands, and events share a common namespace.  Therefore,
676 generally speaking, type definitions should always use CamelCase for
677 user-defined type names, while built-in types are lowercase.
679 Type names ending with 'Kind' or 'List' are reserved for the
680 generator, which uses them for implicit union enums and array types,
681 respectively.
683 Command names, and member names within a type, should be all lower
684 case with words separated by a hyphen.  However, some existing older
685 commands and complex types use underscore; when extending them,
686 consistency is preferred over blindly avoiding underscore.
688 Event names should be ALL_CAPS with words separated by underscore.
690 Member name 'u' and names starting with 'has-' or 'has_' are reserved
691 for the generator, which uses them for unions and for tracking
692 optional members.
694 Any name (command, event, type, member, or enum value) beginning with
695 "x-" is marked experimental, and may be withdrawn or changed
696 incompatibly in a future release.
698 Pragma 'name-case-whitelist' lets you violate the rules on use of
699 upper and lower case.  Use for new code is strongly discouraged.
702 === Downstream extensions ===
704 QAPI schema names that are externally visible, say in the Client JSON
705 Protocol, need to be managed with care.  Names starting with a
706 downstream prefix of the form __RFQDN_ are reserved for the downstream
707 who controls the valid, reverse fully qualified domain name RFQDN.
708 RFQDN may only contain ASCII letters, digits, hyphen and period.
710 Example: Red Hat, Inc. controls redhat.com, and may therefore add a
711 downstream command __com.redhat_drive-mirror.
714 === Configuring the schema ===
716 Syntax:
717     COND = STRING
718          | [ STRING, ... ]
720 All definitions take an optional 'if' member.  Its value must be a
721 string or a list of strings.  A string is shorthand for a list
722 containing just that string.  The code generated for the definition
723 will then be guarded by #if STRING for each STRING in the COND list.
725 Example: a conditional struct
727  { 'struct': 'IfStruct', 'data': { 'foo': 'int' },
728    'if': ['defined(CONFIG_FOO)', 'defined(HAVE_BAR)'] }
730 gets its generated code guarded like this:
732  #if defined(CONFIG_FOO)
733  #if defined(HAVE_BAR)
734  ... generated code ...
735  #endif /* defined(HAVE_BAR) */
736  #endif /* defined(CONFIG_FOO) */
738 Individual members of complex types, commands arguments, and
739 event-specific data can also be made conditional.  This requires the
740 longhand form of MEMBER.
742 Example: a struct type with unconditional member 'foo' and conditional
743 member 'bar'
745 { 'struct': 'IfStruct', 'data':
746   { 'foo': 'int',
747     'bar': { 'type': 'int', 'if': 'defined(IFCOND)'} } }
749 A union's discriminator may not be conditional.
751 Likewise, individual enumeration values be conditional.  This requires
752 the longhand form of ENUM-VALUE.
754 Example: an enum type with unconditional value 'foo' and conditional
755 value 'bar'
757 { 'enum': 'IfEnum', 'data':
758   [ 'foo',
759     { 'name' : 'bar', 'if': 'defined(IFCOND)' } ] }
761 Likewise, features can be conditional.  This requires the longhand
762 form of FEATURE.
764 Example: a struct with conditional feature 'allow-negative-numbers'
766 { 'struct': 'TestType',
767   'data': { 'number': 'int' },
768   'features': [ { 'name': 'allow-negative-numbers',
769                   'if' 'defined(IFCOND)' } ] }
771 Please note that you are responsible to ensure that the C code will
772 compile with an arbitrary combination of conditions, since the
773 generator is unable to check it at this point.
775 The conditions apply to introspection as well, i.e. introspection
776 shows a conditional entity only when the condition is satisfied in
777 this particular build.
780 === Documentation comments ===
782 A multi-line comment that starts and ends with a '##' line is a
783 documentation comment.
785 If the documentation comment starts like
787     ##
788     # @SYMBOL:
790 it documents the definition if SYMBOL, else it's free-form
791 documentation.
793 See below for more on definition documentation.
795 Free-form documentation may be used to provide additional text and
796 structuring content.
799 ==== Documentation markup ====
801 Comment text starting with '=' is a section title:
803     # = Section title
805 Double the '=' for a subsection title:
807     # == Subsection title
809 '|' denotes examples:
811     # | Text of the example, may span
812     # | multiple lines
814 '*' starts an itemized list:
816     # * First item, may span
817     #   multiple lines
818     # * Second item
820 You can also use '-' instead of '*'.
822 A decimal number followed by '.' starts a numbered list:
824     # 1. First item, may span
825     #    multiple lines
826     # 2. Second item
828 The actual number doesn't matter.  You could even use '*' instead of
829 '2.' for the second item.
831 Lists can't be nested.  Blank lines are currently not supported within
832 lists.
834 Additional whitespace between the initial '#' and the comment text is
835 permitted.
837 *foo* and _foo_ are for strong and emphasis styles respectively (they
838 do not work over multiple lines).  @foo is used to reference a name in
839 the schema.
841 Example:
844 # = Section
845 # == Subsection
847 # Some text foo with *strong* and _emphasis_
848 # 1. with a list
849 # 2. like that
851 # And some code:
852 # | $ echo foo
853 # | -> do this
854 # | <- get that
859 ==== Definition documentation ====
861 Definition documentation, if present, must immediately precede the
862 definition it documents.
864 When documentation is required (see pragma 'doc-required'), every
865 definition must have documentation.
867 Definition documentation starts with a line naming the definition,
868 followed by an optional overview, a description of each argument (for
869 commands and events), member (for structs and unions), branch (for
870 alternates), or value (for enums), and finally optional tagged
871 sections.
873 FIXME: the parser accepts these things in almost any order.
874 FIXME: union branches should be described, too.
876 Extensions added after the definition was first released carry a
877 '(since x.y.z)' comment.
879 A tagged section starts with one of the following words:
880 "Note:"/"Notes:", "Since:", "Example"/"Examples", "Returns:", "TODO:".
881 The section ends with the start of a new section.
883 A 'Since: x.y.z' tagged section lists the release that introduced the
884 definition.
886 For example:
889 # @BlockStats:
891 # Statistics of a virtual block device or a block backing device.
893 # @device: If the stats are for a virtual block device, the name
894 #          corresponding to the virtual block device.
896 # @node-name: The node name of the device. (since 2.3)
898 # ... more members ...
900 # Since: 0.14.0
902 { 'struct': 'BlockStats',
903   'data': {'*device': 'str', '*node-name': 'str',
904            ... more members ... } }
907 # @query-blockstats:
909 # Query the @BlockStats for all virtual block devices.
911 # @query-nodes: If true, the command will query all the
912 #               block nodes ... explain, explain ...  (since 2.3)
914 # Returns: A list of @BlockStats for each virtual block devices.
916 # Since: 0.14.0
918 # Example:
920 # -> { "execute": "query-blockstats" }
921 # <- {
922 #      ... lots of output ...
923 #    }
926 { 'command': 'query-blockstats',
927   'data': { '*query-nodes': 'bool' },
928   'returns': ['BlockStats'] }
931 == Client JSON Protocol introspection ==
933 Clients of a Client JSON Protocol commonly need to figure out what
934 exactly the server (QEMU) supports.
936 For this purpose, QMP provides introspection via command
937 query-qmp-schema.  QGA currently doesn't support introspection.
939 While Client JSON Protocol wire compatibility should be maintained
940 between qemu versions, we cannot make the same guarantees for
941 introspection stability.  For example, one version of qemu may provide
942 a non-variant optional member of a struct, and a later version rework
943 the member to instead be non-optional and associated with a variant.
944 Likewise, one version of qemu may list a member with open-ended type
945 'str', and a later version could convert it to a finite set of strings
946 via an enum type; or a member may be converted from a specific type to
947 an alternate that represents a choice between the original type and
948 something else.
950 query-qmp-schema returns a JSON array of SchemaInfo objects.  These
951 objects together describe the wire ABI, as defined in the QAPI schema.
952 There is no specified order to the SchemaInfo objects returned; a
953 client must search for a particular name throughout the entire array
954 to learn more about that name, but is at least guaranteed that there
955 will be no collisions between type, command, and event names.
957 However, the SchemaInfo can't reflect all the rules and restrictions
958 that apply to QMP.  It's interface introspection (figuring out what's
959 there), not interface specification.  The specification is in the QAPI
960 schema.  To understand how QMP is to be used, you need to study the
961 QAPI schema.
963 Like any other command, query-qmp-schema is itself defined in the QAPI
964 schema, along with the SchemaInfo type.  This text attempts to give an
965 overview how things work.  For details you need to consult the QAPI
966 schema.
968 SchemaInfo objects have common members "name" and "meta-type", and
969 additional variant members depending on the value of meta-type.
971 Each SchemaInfo object describes a wire ABI entity of a certain
972 meta-type: a command, event or one of several kinds of type.
974 SchemaInfo for commands and events have the same name as in the QAPI
975 schema.
977 Command and event names are part of the wire ABI, but type names are
978 not.  Therefore, the SchemaInfo for types have auto-generated
979 meaningless names.  For readability, the examples in this section use
980 meaningful type names instead.
982 To examine a type, start with a command or event using it, then follow
983 references by name.
985 QAPI schema definitions not reachable that way are omitted.
987 The SchemaInfo for a command has meta-type "command", and variant
988 members "arg-type", "ret-type" and "allow-oob".  On the wire, the
989 "arguments" member of a client's "execute" command must conform to the
990 object type named by "arg-type".  The "return" member that the server
991 passes in a success response conforms to the type named by
992 "ret-type".  When "allow-oob" is set, it means the command supports
993 out-of-band execution.
995 If the command takes no arguments, "arg-type" names an object type
996 without members.  Likewise, if the command returns nothing, "ret-type"
997 names an object type without members.
999 Example: the SchemaInfo for command query-qmp-schema
1001     { "name": "query-qmp-schema", "meta-type": "command",
1002       "arg-type": "q_empty", "ret-type": "SchemaInfoList" }
1004     Type "q_empty" is an automatic object type without members, and type
1005     "SchemaInfoList" is the array of SchemaInfo type.
1007 The SchemaInfo for an event has meta-type "event", and variant member
1008 "arg-type".  On the wire, a "data" member that the server passes in an
1009 event conforms to the object type named by "arg-type".
1011 If the event carries no additional information, "arg-type" names an
1012 object type without members.  The event may not have a data member on
1013 the wire then.
1015 Each command or event defined with 'data' as MEMBERS object in the
1016 QAPI schema implicitly defines an object type.
1018 Example: the SchemaInfo for EVENT_C from section Events
1020     { "name": "EVENT_C", "meta-type": "event",
1021       "arg-type": "q_obj-EVENT_C-arg" }
1023     Type "q_obj-EVENT_C-arg" is an implicitly defined object type with
1024     the two members from the event's definition.
1026 The SchemaInfo for struct and union types has meta-type "object".
1028 The SchemaInfo for a struct type has variant member "members".
1030 The SchemaInfo for a union type additionally has variant members "tag"
1031 and "variants".
1033 "members" is a JSON array describing the object's common members, if
1034 any.  Each element is a JSON object with members "name" (the member's
1035 name), "type" (the name of its type), and optionally "default".  The
1036 member is optional if "default" is present.  Currently, "default" can
1037 only have value null.  Other values are reserved for future
1038 extensions.  The "members" array is in no particular order; clients
1039 must search the entire object when learning whether a particular
1040 member is supported.
1042 Example: the SchemaInfo for MyType from section Struct types
1044     { "name": "MyType", "meta-type": "object",
1045       "members": [
1046           { "name": "member1", "type": "str" },
1047           { "name": "member2", "type": "int" },
1048           { "name": "member3", "type": "str", "default": null } ] }
1050 "tag" is the name of the common member serving as type tag.
1051 "variants" is a JSON array describing the object's variant members.
1052 Each element is a JSON object with members "case" (the value of type
1053 tag this element applies to) and "type" (the name of an object type
1054 that provides the variant members for this type tag value).  The
1055 "variants" array is in no particular order, and is not guaranteed to
1056 list cases in the same order as the corresponding "tag" enum type.
1058 Example: the SchemaInfo for flat union BlockdevOptions from section
1059 Union types
1061     { "name": "BlockdevOptions", "meta-type": "object",
1062       "members": [
1063           { "name": "driver", "type": "BlockdevDriver" },
1064           { "name": "read-only", "type": "bool", "default": null } ],
1065       "tag": "driver",
1066       "variants": [
1067           { "case": "file", "type": "BlockdevOptionsFile" },
1068           { "case": "qcow2", "type": "BlockdevOptionsQcow2" } ] }
1070 Note that base types are "flattened": its members are included in the
1071 "members" array.
1073 A simple union implicitly defines an enumeration type for its implicit
1074 discriminator (called "type" on the wire, see section Union types).
1076 A simple union implicitly defines an object type for each of its
1077 variants.
1079 Example: the SchemaInfo for simple union BlockdevOptionsSimple from section
1080 Union types
1082     { "name": "BlockdevOptionsSimple", "meta-type": "object",
1083       "members": [
1084           { "name": "type", "type": "BlockdevOptionsSimpleKind" } ],
1085       "tag": "type",
1086       "variants": [
1087           { "case": "file", "type": "q_obj-BlockdevOptionsFile-wrapper" },
1088           { "case": "qcow2", "type": "q_obj-BlockdevOptionsQcow2-wrapper" } ] }
1090     Enumeration type "BlockdevOptionsSimpleKind" and the object types
1091     "q_obj-BlockdevOptionsFile-wrapper", "q_obj-BlockdevOptionsQcow2-wrapper"
1092     are implicitly defined.
1094 The SchemaInfo for an alternate type has meta-type "alternate", and
1095 variant member "members".  "members" is a JSON array.  Each element is
1096 a JSON object with member "type", which names a type.  Values of the
1097 alternate type conform to exactly one of its member types.  There is
1098 no guarantee on the order in which "members" will be listed.
1100 Example: the SchemaInfo for BlockdevRef from section Alternate types
1102     { "name": "BlockdevRef", "meta-type": "alternate",
1103       "members": [
1104           { "type": "BlockdevOptions" },
1105           { "type": "str" } ] }
1107 The SchemaInfo for an array type has meta-type "array", and variant
1108 member "element-type", which names the array's element type.  Array
1109 types are implicitly defined.  For convenience, the array's name may
1110 resemble the element type; however, clients should examine member
1111 "element-type" instead of making assumptions based on parsing member
1112 "name".
1114 Example: the SchemaInfo for ['str']
1116     { "name": "[str]", "meta-type": "array",
1117       "element-type": "str" }
1119 The SchemaInfo for an enumeration type has meta-type "enum" and
1120 variant member "values".  The values are listed in no particular
1121 order; clients must search the entire enum when learning whether a
1122 particular value is supported.
1124 Example: the SchemaInfo for MyEnum from section Enumeration types
1126     { "name": "MyEnum", "meta-type": "enum",
1127       "values": [ "value1", "value2", "value3" ] }
1129 The SchemaInfo for a built-in type has the same name as the type in
1130 the QAPI schema (see section Built-in Types), with one exception
1131 detailed below.  It has variant member "json-type" that shows how
1132 values of this type are encoded on the wire.
1134 Example: the SchemaInfo for str
1136     { "name": "str", "meta-type": "builtin", "json-type": "string" }
1138 The QAPI schema supports a number of integer types that only differ in
1139 how they map to C.  They are identical as far as SchemaInfo is
1140 concerned.  Therefore, they get all mapped to a single type "int" in
1141 SchemaInfo.
1143 As explained above, type names are not part of the wire ABI.  Not even
1144 the names of built-in types.  Clients should examine member
1145 "json-type" instead of hard-coding names of built-in types.
1148 == Compatibility considerations ==
1150 Maintaining backward compatibility at the Client JSON Protocol level
1151 while evolving the schema requires some care.  This section is about
1152 syntactic compatibility, which is necessary, but not sufficient, for
1153 actual compatibility.
1155 Clients send commands with argument data, and receive command
1156 responses with return data and events with event data.
1158 Adding opt-in functionality to the send direction is backwards
1159 compatible: adding commands, optional arguments, enumeration values,
1160 union and alternate branches; turning an argument type into an
1161 alternate of that type; making mandatory arguments optional.  Clients
1162 oblivious of the new functionality continue to work.
1164 Incompatible changes include removing commands, command arguments,
1165 enumeration values, union and alternate branches, adding mandatory
1166 command arguments, and making optional arguments mandatory.
1168 The specified behavior of an absent optional argument should remain
1169 the same.  With proper documentation, this policy still allows some
1170 flexibility; for example, when an optional 'buffer-size' argument is
1171 specified to default to a sensible buffer size, the actual default
1172 value can still be changed.  The specified default behavior is not the
1173 exact size of the buffer, only that the default size is sensible.
1175 Adding functionality to the receive direction is generally backwards
1176 compatible: adding events, adding return and event data members.
1177 Clients are expected to ignore the ones they don't know.
1179 Removing "unreachable" stuff like events that can't be triggered
1180 anymore, optional return or event data members that can't be sent
1181 anymore, and return or event data member (enumeration) values that
1182 can't be sent anymore makes no difference to clients, except for
1183 introspection.  The latter can conceivably confuse clients, so tread
1184 carefully.
1186 Incompatible changes include removing return and event data members.
1188 Any change to a command definition's 'data' or one of the types used
1189 there (recursively) needs to consider send direction compatibility.
1191 Any change to a command definition's 'return', an event definition's
1192 'data', or one of the types used there (recursively) needs to consider
1193 receive direction compatibility.
1195 Any change to types used in both contexts need to consider both.
1197 Enumeration type values and complex and alternate type members may be
1198 reordered freely.  For enumerations and alternate types, this doesn't
1199 affect the wire encoding.  For complex types, this might make the
1200 implementation emit JSON object members in a different order, which
1201 the Client JSON Protocol permits.
1203 Since type names are not visible in the Client JSON Protocol, types
1204 may be freely renamed.  Even certain refactorings are invisible, such
1205 as splitting members from one type into a common base type.
1208 == Code generation ==
1210 The QAPI code generator qapi-gen.py generates code and documentation
1211 from the schema.  Together with the core QAPI libraries, this code
1212 provides everything required to take JSON commands read in by a Client
1213 JSON Protocol server, unmarshal the arguments into the underlying C
1214 types, call into the corresponding C function, map the response back
1215 to a Client JSON Protocol response to be returned to the user, and
1216 introspect the commands.
1218 As an example, we'll use the following schema, which describes a
1219 single complex user-defined type, along with command which takes a
1220 list of that type as a parameter, and returns a single element of that
1221 type.  The user is responsible for writing the implementation of
1222 qmp_my_command(); everything else is produced by the generator.
1224     $ cat example-schema.json
1225     { 'struct': 'UserDefOne',
1226       'data': { 'integer': 'int', '*string': 'str' } }
1228     { 'command': 'my-command',
1229       'data': { 'arg1': ['UserDefOne'] },
1230       'returns': 'UserDefOne' }
1232     { 'event': 'MY_EVENT' }
1234 We run qapi-gen.py like this:
1236     $ python scripts/qapi-gen.py --output-dir="qapi-generated" \
1237     --prefix="example-" example-schema.json
1239 For a more thorough look at generated code, the testsuite includes
1240 tests/qapi-schema/qapi-schema-tests.json that covers more examples of
1241 what the generator will accept, and compiles the resulting C code as
1242 part of 'make check-unit'.
1244 === Code generated for QAPI types ===
1246 The following files are created:
1248 $(prefix)qapi-types.h - C types corresponding to types defined in
1249                         the schema
1251 $(prefix)qapi-types.c - Cleanup functions for the above C types
1253 The $(prefix) is an optional parameter used as a namespace to keep the
1254 generated code from one schema/code-generation separated from others so code
1255 can be generated/used from multiple schemas without clobbering previously
1256 created code.
1258 Example:
1260     $ cat qapi-generated/example-qapi-types.h
1261 [Uninteresting stuff omitted...]
1263     #ifndef EXAMPLE_QAPI_TYPES_H
1264     #define EXAMPLE_QAPI_TYPES_H
1266     #include "qapi/qapi-builtin-types.h"
1268     typedef struct UserDefOne UserDefOne;
1270     typedef struct UserDefOneList UserDefOneList;
1272     typedef struct q_obj_my_command_arg q_obj_my_command_arg;
1274     struct UserDefOne {
1275         int64_t integer;
1276         bool has_string;
1277         char *string;
1278     };
1280     void qapi_free_UserDefOne(UserDefOne *obj);
1282     struct UserDefOneList {
1283         UserDefOneList *next;
1284         UserDefOne *value;
1285     };
1287     void qapi_free_UserDefOneList(UserDefOneList *obj);
1289     struct q_obj_my_command_arg {
1290         UserDefOneList *arg1;
1291     };
1293     #endif /* EXAMPLE_QAPI_TYPES_H */
1294     $ cat qapi-generated/example-qapi-types.c
1295 [Uninteresting stuff omitted...]
1297     void qapi_free_UserDefOne(UserDefOne *obj)
1298     {
1299         Visitor *v;
1301         if (!obj) {
1302             return;
1303         }
1305         v = qapi_dealloc_visitor_new();
1306         visit_type_UserDefOne(v, NULL, &obj, NULL);
1307         visit_free(v);
1308     }
1310     void qapi_free_UserDefOneList(UserDefOneList *obj)
1311     {
1312         Visitor *v;
1314         if (!obj) {
1315             return;
1316         }
1318         v = qapi_dealloc_visitor_new();
1319         visit_type_UserDefOneList(v, NULL, &obj, NULL);
1320         visit_free(v);
1321     }
1323 [Uninteresting stuff omitted...]
1325 For a modular QAPI schema (see section Include directives), code for
1326 each sub-module SUBDIR/SUBMODULE.json is actually generated into
1328 SUBDIR/$(prefix)qapi-types-SUBMODULE.h
1329 SUBDIR/$(prefix)qapi-types-SUBMODULE.c
1331 If qapi-gen.py is run with option --builtins, additional files are
1332 created:
1334 qapi-builtin-types.h - C types corresponding to built-in types
1336 qapi-builtin-types.c - Cleanup functions for the above C types
1338 === Code generated for visiting QAPI types ===
1340 These are the visitor functions used to walk through and convert
1341 between a native QAPI C data structure and some other format (such as
1342 QObject); the generated functions are named visit_type_FOO() and
1343 visit_type_FOO_members().
1345 The following files are generated:
1347 $(prefix)qapi-visit.c: Visitor function for a particular C type, used
1348                        to automagically convert QObjects into the
1349                        corresponding C type and vice-versa, as well
1350                        as for deallocating memory for an existing C
1351                        type
1353 $(prefix)qapi-visit.h: Declarations for previously mentioned visitor
1354                        functions
1356 Example:
1358     $ cat qapi-generated/example-qapi-visit.h
1359 [Uninteresting stuff omitted...]
1361     #ifndef EXAMPLE_QAPI_VISIT_H
1362     #define EXAMPLE_QAPI_VISIT_H
1364     #include "qapi/qapi-builtin-visit.h"
1365     #include "example-qapi-types.h"
1368     void visit_type_UserDefOne_members(Visitor *v, UserDefOne *obj, Error **errp);
1369     void visit_type_UserDefOne(Visitor *v, const char *name, UserDefOne **obj, Error **errp);
1370     void visit_type_UserDefOneList(Visitor *v, const char *name, UserDefOneList **obj, Error **errp);
1372     void visit_type_q_obj_my_command_arg_members(Visitor *v, q_obj_my_command_arg *obj, Error **errp);
1374     #endif /* EXAMPLE_QAPI_VISIT_H */
1375     $ cat qapi-generated/example-qapi-visit.c
1376 [Uninteresting stuff omitted...]
1378     void visit_type_UserDefOne_members(Visitor *v, UserDefOne *obj, Error **errp)
1379     {
1380         Error *err = NULL;
1382         visit_type_int(v, "integer", &obj->integer, &err);
1383         if (err) {
1384             goto out;
1385         }
1386         if (visit_optional(v, "string", &obj->has_string)) {
1387             visit_type_str(v, "string", &obj->string, &err);
1388             if (err) {
1389                 goto out;
1390             }
1391         }
1393     out:
1394         error_propagate(errp, err);
1395     }
1397     void visit_type_UserDefOne(Visitor *v, const char *name, UserDefOne **obj, Error **errp)
1398     {
1399         Error *err = NULL;
1401         visit_start_struct(v, name, (void **)obj, sizeof(UserDefOne), &err);
1402         if (err) {
1403             goto out;
1404         }
1405         if (!*obj) {
1406             goto out_obj;
1407         }
1408         visit_type_UserDefOne_members(v, *obj, &err);
1409         if (err) {
1410             goto out_obj;
1411         }
1412         visit_check_struct(v, &err);
1413     out_obj:
1414         visit_end_struct(v, (void **)obj);
1415         if (err && visit_is_input(v)) {
1416             qapi_free_UserDefOne(*obj);
1417             *obj = NULL;
1418         }
1419     out:
1420         error_propagate(errp, err);
1421     }
1423     void visit_type_UserDefOneList(Visitor *v, const char *name, UserDefOneList **obj, Error **errp)
1424     {
1425         Error *err = NULL;
1426         UserDefOneList *tail;
1427         size_t size = sizeof(**obj);
1429         visit_start_list(v, name, (GenericList **)obj, size, &err);
1430         if (err) {
1431             goto out;
1432         }
1434         for (tail = *obj; tail;
1435              tail = (UserDefOneList *)visit_next_list(v, (GenericList *)tail, size)) {
1436             visit_type_UserDefOne(v, NULL, &tail->value, &err);
1437             if (err) {
1438                 break;
1439             }
1440         }
1442         if (!err) {
1443             visit_check_list(v, &err);
1444         }
1445         visit_end_list(v, (void **)obj);
1446         if (err && visit_is_input(v)) {
1447             qapi_free_UserDefOneList(*obj);
1448             *obj = NULL;
1449         }
1450     out:
1451         error_propagate(errp, err);
1452     }
1454     void visit_type_q_obj_my_command_arg_members(Visitor *v, q_obj_my_command_arg *obj, Error **errp)
1455     {
1456         Error *err = NULL;
1458         visit_type_UserDefOneList(v, "arg1", &obj->arg1, &err);
1459         if (err) {
1460             goto out;
1461         }
1463     out:
1464         error_propagate(errp, err);
1465     }
1467 [Uninteresting stuff omitted...]
1469 For a modular QAPI schema (see section Include directives), code for
1470 each sub-module SUBDIR/SUBMODULE.json is actually generated into
1472 SUBDIR/$(prefix)qapi-visit-SUBMODULE.h
1473 SUBDIR/$(prefix)qapi-visit-SUBMODULE.c
1475 If qapi-gen.py is run with option --builtins, additional files are
1476 created:
1478 qapi-builtin-visit.h - Visitor functions for built-in types
1480 qapi-builtin-visit.c - Declarations for these visitor functions
1482 === Code generated for commands ===
1484 These are the marshaling/dispatch functions for the commands defined
1485 in the schema.  The generated code provides qmp_marshal_COMMAND(), and
1486 declares qmp_COMMAND() that the user must implement.
1488 The following files are generated:
1490 $(prefix)qapi-commands.c: Command marshal/dispatch functions for each
1491                           QMP command defined in the schema
1493 $(prefix)qapi-commands.h: Function prototypes for the QMP commands
1494                           specified in the schema
1496 Example:
1498     $ cat qapi-generated/example-qapi-commands.h
1499 [Uninteresting stuff omitted...]
1501     #ifndef EXAMPLE_QAPI_COMMANDS_H
1502     #define EXAMPLE_QAPI_COMMANDS_H
1504     #include "example-qapi-types.h"
1505     #include "qapi/qmp/dispatch.h"
1507     UserDefOne *qmp_my_command(UserDefOneList *arg1, Error **errp);
1508     void qmp_marshal_my_command(QDict *args, QObject **ret, Error **errp);
1509     void example_qmp_init_marshal(QmpCommandList *cmds);
1511     #endif /* EXAMPLE_QAPI_COMMANDS_H */
1512     $ cat qapi-generated/example-qapi-commands.c
1513 [Uninteresting stuff omitted...]
1515     static void qmp_marshal_output_UserDefOne(UserDefOne *ret_in, QObject **ret_out, Error **errp)
1516     {
1517         Error *err = NULL;
1518         Visitor *v;
1520         v = qobject_output_visitor_new(ret_out);
1521         visit_type_UserDefOne(v, "unused", &ret_in, &err);
1522         if (!err) {
1523             visit_complete(v, ret_out);
1524         }
1525         error_propagate(errp, err);
1526         visit_free(v);
1527         v = qapi_dealloc_visitor_new();
1528         visit_type_UserDefOne(v, "unused", &ret_in, NULL);
1529         visit_free(v);
1530     }
1532     void qmp_marshal_my_command(QDict *args, QObject **ret, Error **errp)
1533     {
1534         Error *err = NULL;
1535         UserDefOne *retval;
1536         Visitor *v;
1537         q_obj_my_command_arg arg = {0};
1539         v = qobject_input_visitor_new(QOBJECT(args));
1540         visit_start_struct(v, NULL, NULL, 0, &err);
1541         if (err) {
1542             goto out;
1543         }
1544         visit_type_q_obj_my_command_arg_members(v, &arg, &err);
1545         if (!err) {
1546             visit_check_struct(v, &err);
1547         }
1548         visit_end_struct(v, NULL);
1549         if (err) {
1550             goto out;
1551         }
1553         retval = qmp_my_command(arg.arg1, &err);
1554         if (err) {
1555             goto out;
1556         }
1558         qmp_marshal_output_UserDefOne(retval, ret, &err);
1560     out:
1561         error_propagate(errp, err);
1562         visit_free(v);
1563         v = qapi_dealloc_visitor_new();
1564         visit_start_struct(v, NULL, NULL, 0, NULL);
1565         visit_type_q_obj_my_command_arg_members(v, &arg, NULL);
1566         visit_end_struct(v, NULL);
1567         visit_free(v);
1568     }
1570     void example_qmp_init_marshal(QmpCommandList *cmds)
1571     {
1572         QTAILQ_INIT(cmds);
1574         qmp_register_command(cmds, "my-command",
1575                              qmp_marshal_my_command, QCO_NO_OPTIONS);
1576     }
1578 [Uninteresting stuff omitted...]
1580 For a modular QAPI schema (see section Include directives), code for
1581 each sub-module SUBDIR/SUBMODULE.json is actually generated into
1583 SUBDIR/$(prefix)qapi-commands-SUBMODULE.h
1584 SUBDIR/$(prefix)qapi-commands-SUBMODULE.c
1586 === Code generated for events ===
1588 This is the code related to events defined in the schema, providing
1589 qapi_event_send_EVENT().
1591 The following files are created:
1593 $(prefix)qapi-events.h - Function prototypes for each event type
1595 $(prefix)qapi-events.c - Implementation of functions to send an event
1597 $(prefix)qapi-emit-events.h - Enumeration of all event names, and
1598                               common event code declarations
1600 $(prefix)qapi-emit-events.c - Common event code definitions
1602 Example:
1604     $ cat qapi-generated/example-qapi-events.h
1605 [Uninteresting stuff omitted...]
1607     #ifndef EXAMPLE_QAPI_EVENTS_H
1608     #define EXAMPLE_QAPI_EVENTS_H
1610     #include "qapi/util.h"
1611     #include "example-qapi-types.h"
1613     void qapi_event_send_my_event(void);
1615     #endif /* EXAMPLE_QAPI_EVENTS_H */
1616     $ cat qapi-generated/example-qapi-events.c
1617 [Uninteresting stuff omitted...]
1619     void qapi_event_send_my_event(void)
1620     {
1621         QDict *qmp;
1623         qmp = qmp_event_build_dict("MY_EVENT");
1625         example_qapi_event_emit(EXAMPLE_QAPI_EVENT_MY_EVENT, qmp);
1627         qobject_unref(qmp);
1628     }
1630 [Uninteresting stuff omitted...]
1631     $ cat qapi-generated/example-qapi-emit-events.h
1632 [Uninteresting stuff omitted...]
1634     #ifndef EXAMPLE_QAPI_EMIT_EVENTS_H
1635     #define EXAMPLE_QAPI_EMIT_EVENTS_H
1637     #include "qapi/util.h"
1639     typedef enum example_QAPIEvent {
1640         EXAMPLE_QAPI_EVENT_MY_EVENT,
1641         EXAMPLE_QAPI_EVENT__MAX,
1642     } example_QAPIEvent;
1644     #define example_QAPIEvent_str(val) \
1645         qapi_enum_lookup(&example_QAPIEvent_lookup, (val))
1647     extern const QEnumLookup example_QAPIEvent_lookup;
1649     void example_qapi_event_emit(example_QAPIEvent event, QDict *qdict);
1651     #endif /* EXAMPLE_QAPI_EMIT_EVENTS_H */
1652     $ cat qapi-generated/example-qapi-emit-events.c
1653 [Uninteresting stuff omitted...]
1655     const QEnumLookup example_QAPIEvent_lookup = {
1656         .array = (const char *const[]) {
1657             [EXAMPLE_QAPI_EVENT_MY_EVENT] = "MY_EVENT",
1658         },
1659         .size = EXAMPLE_QAPI_EVENT__MAX
1660     };
1662 [Uninteresting stuff omitted...]
1664 For a modular QAPI schema (see section Include directives), code for
1665 each sub-module SUBDIR/SUBMODULE.json is actually generated into
1667 SUBDIR/$(prefix)qapi-events-SUBMODULE.h
1668 SUBDIR/$(prefix)qapi-events-SUBMODULE.c
1670 === Code generated for introspection ===
1672 The following files are created:
1674 $(prefix)qapi-introspect.c - Defines a string holding a JSON
1675                             description of the schema
1677 $(prefix)qapi-introspect.h - Declares the above string
1679 Example:
1681     $ cat qapi-generated/example-qapi-introspect.h
1682 [Uninteresting stuff omitted...]
1684     #ifndef EXAMPLE_QAPI_INTROSPECT_H
1685     #define EXAMPLE_QAPI_INTROSPECT_H
1687     #include "qapi/qmp/qlit.h"
1689     extern const QLitObject example_qmp_schema_qlit;
1691     #endif /* EXAMPLE_QAPI_INTROSPECT_H */
1692     $ cat qapi-generated/example-qapi-introspect.c
1693 [Uninteresting stuff omitted...]
1695     const QLitObject example_qmp_schema_qlit = QLIT_QLIST(((QLitObject[]) {
1696         QLIT_QDICT(((QLitDictEntry[]) {
1697             { "arg-type", QLIT_QSTR("0"), },
1698             { "meta-type", QLIT_QSTR("command"), },
1699             { "name", QLIT_QSTR("my-command"), },
1700             { "ret-type", QLIT_QSTR("1"), },
1701             {}
1702         })),
1703         QLIT_QDICT(((QLitDictEntry[]) {
1704             { "arg-type", QLIT_QSTR("2"), },
1705             { "meta-type", QLIT_QSTR("event"), },
1706             { "name", QLIT_QSTR("MY_EVENT"), },
1707             {}
1708         })),
1709         /* "0" = q_obj_my-command-arg */
1710         QLIT_QDICT(((QLitDictEntry[]) {
1711             { "members", QLIT_QLIST(((QLitObject[]) {
1712                 QLIT_QDICT(((QLitDictEntry[]) {
1713                     { "name", QLIT_QSTR("arg1"), },
1714                     { "type", QLIT_QSTR("[1]"), },
1715                     {}
1716                 })),
1717                 {}
1718             })), },
1719             { "meta-type", QLIT_QSTR("object"), },
1720             { "name", QLIT_QSTR("0"), },
1721             {}
1722         })),
1723         /* "1" = UserDefOne */
1724         QLIT_QDICT(((QLitDictEntry[]) {
1725             { "members", QLIT_QLIST(((QLitObject[]) {
1726                 QLIT_QDICT(((QLitDictEntry[]) {
1727                     { "name", QLIT_QSTR("integer"), },
1728                     { "type", QLIT_QSTR("int"), },
1729                     {}
1730                 })),
1731                 QLIT_QDICT(((QLitDictEntry[]) {
1732                     { "default", QLIT_QNULL, },
1733                     { "name", QLIT_QSTR("string"), },
1734                     { "type", QLIT_QSTR("str"), },
1735                     {}
1736                 })),
1737                 {}
1738             })), },
1739             { "meta-type", QLIT_QSTR("object"), },
1740             { "name", QLIT_QSTR("1"), },
1741             {}
1742         })),
1743         /* "2" = q_empty */
1744         QLIT_QDICT(((QLitDictEntry[]) {
1745             { "members", QLIT_QLIST(((QLitObject[]) {
1746                 {}
1747             })), },
1748             { "meta-type", QLIT_QSTR("object"), },
1749             { "name", QLIT_QSTR("2"), },
1750             {}
1751         })),
1752         QLIT_QDICT(((QLitDictEntry[]) {
1753             { "element-type", QLIT_QSTR("1"), },
1754             { "meta-type", QLIT_QSTR("array"), },
1755             { "name", QLIT_QSTR("[1]"), },
1756             {}
1757         })),
1758         QLIT_QDICT(((QLitDictEntry[]) {
1759             { "json-type", QLIT_QSTR("int"), },
1760             { "meta-type", QLIT_QSTR("builtin"), },
1761             { "name", QLIT_QSTR("int"), },
1762             {}
1763         })),
1764         QLIT_QDICT(((QLitDictEntry[]) {
1765             { "json-type", QLIT_QSTR("string"), },
1766             { "meta-type", QLIT_QSTR("builtin"), },
1767             { "name", QLIT_QSTR("str"), },
1768             {}
1769         })),
1770         {}
1771     }));
1773 [Uninteresting stuff omitted...]