linux-user/sparc: Minor corrections to do_sigreturn
[qemu/ar7.git] / docs / devel / qapi-code-gen.txt
blobc1cb6f987de578c325e504a5135728728706f335
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': {
151                    '*doc-required': BOOL,
152                    '*command-name-exceptions': [ STRING, ... ],
153                    '*command-returns-exceptions': [ STRING, ... ],
154                    '*member-name-exceptions': [ STRING, ... ] } }
156 The pragma directive lets you control optional generator behavior.
158 Pragma's scope is currently the complete schema.  Setting the same
159 pragma to different values in parts of the schema doesn't work.
161 Pragma 'doc-required' takes a boolean value.  If true, documentation
162 is required.  Default is false.
164 Pragma 'command-name-exceptions' takes a list of commands whose names
165 may contain '_' instead of '-'.  Default is none.
167 Pragma 'command-returns-exceptions' takes a list of commands that may
168 violate the rules on permitted return types.  Default is none.
170 Pragma 'member-name-exceptions' takes a list of types whose member
171 names may contain uppercase letters, and '_' instead of '-'.  Default
172 is none.
175 === Enumeration types ===
177 Syntax:
178     ENUM = { 'enum': STRING,
179              'data': [ ENUM-VALUE, ... ],
180              '*prefix': STRING,
181              '*if': COND,
182              '*features': FEATURES }
183     ENUM-VALUE = STRING
184                | { 'name': STRING, '*if': COND }
186 Member 'enum' names the enum type.
188 Each member of the 'data' array defines a value of the enumeration
189 type.  The form STRING is shorthand for { 'name': STRING }.  The
190 'name' values must be be distinct.
192 Example:
194  { 'enum': 'MyEnum', 'data': [ 'value1', 'value2', 'value3' ] }
196 Nothing prevents an empty enumeration, although it is probably not
197 useful.
199 On the wire, an enumeration type's value is represented by its
200 (string) name.  In C, it's represented by an enumeration constant.
201 These are of the form PREFIX_NAME, where PREFIX is derived from the
202 enumeration type's name, and NAME from the value's name.  For the
203 example above, the generator maps 'MyEnum' to MY_ENUM and 'value1' to
204 VALUE1, resulting in the enumeration constant MY_ENUM_VALUE1.  The
205 optional 'prefix' member overrides PREFIX.
207 The generated C enumeration constants have values 0, 1, ..., N-1 (in
208 QAPI schema order), where N is the number of values.  There is an
209 additional enumeration constant PREFIX__MAX with value N.
211 Do not use string or an integer type when an enumeration type can do
212 the job satisfactorily.
214 The optional 'if' member specifies a conditional.  See "Configuring
215 the schema" below for more on this.
217 The optional 'features' member specifies features.  See "Features"
218 below for more on this.
221 === Type references and array types ===
223 Syntax:
224     TYPE-REF = STRING | ARRAY-TYPE
225     ARRAY-TYPE = [ STRING ]
227 A string denotes the type named by the string.
229 A one-element array containing a string denotes an array of the type
230 named by the string.  Example: ['int'] denotes an array of 'int'.
233 === Struct types ===
235 Syntax:
236     STRUCT = { 'struct': STRING,
237                'data': MEMBERS,
238                '*base': STRING,
239                '*if': COND,
240                '*features': FEATURES }
241     MEMBERS = { MEMBER, ... }
242     MEMBER = STRING : TYPE-REF
243            | STRING : { 'type': TYPE-REF,
244                         '*if': COND,
245                         '*features': FEATURES }
247 Member 'struct' names the struct type.
249 Each MEMBER of the 'data' object defines a member of the struct type.
251 The MEMBER's STRING name consists of an optional '*' prefix and the
252 struct member name.  If '*' is present, the member is optional.
254 The MEMBER's value defines its properties, in particular its type.
255 The form TYPE-REF is shorthand for { 'type': TYPE-REF }.
257 Example:
259  { 'struct': 'MyType',
260    'data': { 'member1': 'str', 'member2': ['int'], '*member3': 'str' } }
262 A struct type corresponds to a struct in C, and an object in JSON.
263 The C struct's members are generated in QAPI schema order.
265 The optional 'base' member names a struct type whose members are to be
266 included in this type.  They go first in the C struct.
268 Example:
270  { 'struct': 'BlockdevOptionsGenericFormat',
271    'data': { 'file': 'str' } }
272  { 'struct': 'BlockdevOptionsGenericCOWFormat',
273    'base': 'BlockdevOptionsGenericFormat',
274    'data': { '*backing': 'str' } }
276 An example BlockdevOptionsGenericCOWFormat object on the wire could use
277 both members like this:
279  { "file": "/some/place/my-image",
280    "backing": "/some/place/my-backing-file" }
282 The optional 'if' member specifies a conditional.  See "Configuring
283 the schema" below for more on this.
285 The optional 'features' member specifies features.  See "Features"
286 below for more on this.
289 === Union types ===
291 Syntax:
292     UNION = { 'union': STRING,
293               'data': BRANCHES,
294               '*if': COND,
295               '*features': FEATURES }
296           | { 'union': STRING,
297               'data': BRANCHES,
298               'base': ( MEMBERS | STRING ),
299               'discriminator': STRING,
300               '*if': COND,
301               '*features': FEATURES }
302     BRANCHES = { BRANCH, ... }
303     BRANCH = STRING : TYPE-REF
304            | STRING : { 'type': TYPE-REF, '*if': COND }
306 Member 'union' names the union type.
308 There are two flavors of union types: simple (no discriminator or
309 base), and flat (both discriminator and base).
311 Each BRANCH of the 'data' object defines a branch of the union.  A
312 union must have at least one branch.
314 The BRANCH's STRING name is the branch name.
316 The BRANCH's value defines the branch's properties, in particular its
317 type.  The form TYPE-REF is shorthand for { 'type': TYPE-REF }.
319 A simple union type defines a mapping from automatic discriminator
320 values to data types like in this example:
322  { 'struct': 'BlockdevOptionsFile', 'data': { 'filename': 'str' } }
323  { 'struct': 'BlockdevOptionsQcow2',
324    'data': { 'backing': 'str', '*lazy-refcounts': 'bool' } }
326  { 'union': 'BlockdevOptionsSimple',
327    'data': { 'file': 'BlockdevOptionsFile',
328              'qcow2': 'BlockdevOptionsQcow2' } }
330 In the Client JSON Protocol, a simple union is represented by an
331 object that contains the 'type' member as a discriminator, and a
332 'data' member that is of the specified data type corresponding to the
333 discriminator value, as in these examples:
335  { "type": "file", "data": { "filename": "/some/place/my-image" } }
336  { "type": "qcow2", "data": { "backing": "/some/place/my-image",
337                               "lazy-refcounts": true } }
339 The generated C code uses a struct containing a union.  Additionally,
340 an implicit C enum 'NameKind' is created, corresponding to the union
341 'Name', for accessing the various branches of the union.  The value
342 for each branch can be of any type.
344 Flat unions permit arbitrary common members that occur in all variants
345 of the union, not just a discriminator.  Their discriminators need not
346 be named 'type'.  They also avoid nesting on the wire.
348 The 'base' member defines the common members.  If it is a MEMBERS
349 object, it defines common members just like a struct type's 'data'
350 member defines struct type members.  If it is a STRING, it names a
351 struct type whose members are the common members.
353 All flat union branches must be of struct type.
355 In the Client JSON Protocol, a flat union is represented by an object
356 with the common members (from the base type) and the selected branch's
357 members.  The two sets of member names must be disjoint.  Member
358 'discriminator' must name a non-optional enum-typed member of the base
359 struct.
361 The following example enhances the above simple union example by
362 adding an optional common member 'read-only', renaming the
363 discriminator to something more applicable than the simple union's
364 default of 'type', and reducing the number of {} required on the wire:
366  { 'enum': 'BlockdevDriver', 'data': [ 'file', 'qcow2' ] }
367  { 'union': 'BlockdevOptions',
368    'base': { 'driver': 'BlockdevDriver', '*read-only': 'bool' },
369    'discriminator': 'driver',
370    'data': { 'file': 'BlockdevOptionsFile',
371              'qcow2': 'BlockdevOptionsQcow2' } }
373 Resulting in these JSON objects:
375  { "driver": "file", "read-only": true,
376    "filename": "/some/place/my-image" }
377  { "driver": "qcow2", "read-only": false,
378    "backing": "/some/place/my-image", "lazy-refcounts": true }
380 Notice that in a flat union, the discriminator name is controlled by
381 the user, but because it must map to a base member with enum type, the
382 code generator ensures that branches match the existing values of the
383 enum.  The order of branches need not match the order of the enum
384 values.  The branches need not cover all possible enum values.
385 Omitted enum values are still valid branches that add no additional
386 members to the data type.  In the resulting generated C data types, a
387 flat union is represented as a struct with the base members in QAPI
388 schema order, and then a union of structures for each branch of the
389 struct.
391 A simple union can always be re-written as a flat union where the base
392 class has a single member named 'type', and where each branch of the
393 union has a struct with a single member named 'data'.  That is,
395  { 'union': 'Simple', 'data': { 'one': 'str', 'two': 'int' } }
397 is identical on the wire to:
399  { 'enum': 'Enum', 'data': ['one', 'two'] }
400  { 'struct': 'Branch1', 'data': { 'data': 'str' } }
401  { 'struct': 'Branch2', 'data': { 'data': 'int' } }
402  { 'union': 'Flat', 'base': { 'type': 'Enum' }, 'discriminator': 'type',
403    'data': { 'one': 'Branch1', 'two': 'Branch2' } }
405 The optional 'if' member specifies a conditional.  See "Configuring
406 the schema" below for more on this.
408 The optional 'features' member specifies features.  See "Features"
409 below for more on this.
412 === Alternate types ===
414 Syntax:
415     ALTERNATE = { 'alternate': STRING,
416                   'data': ALTERNATIVES,
417                   '*if': COND,
418                   '*features': FEATURES }
419     ALTERNATIVES = { ALTERNATIVE, ... }
420     ALTERNATIVE = STRING : STRING
421                 | STRING : { 'type': STRING, '*if': COND }
423 Member 'alternate' names the alternate type.
425 Each ALTERNATIVE of the 'data' object defines a branch of the
426 alternate.  An alternate must have at least one branch.
428 The ALTERNATIVE's STRING name is the branch name.
430 The ALTERNATIVE's value defines the branch's properties, in particular
431 its type.  The form STRING is shorthand for { 'type': STRING }.
433 Example:
435  { 'alternate': 'BlockdevRef',
436    'data': { 'definition': 'BlockdevOptions',
437              'reference': 'str' } }
439 An alternate type is like a union type, except there is no
440 discriminator on the wire.  Instead, the branch to use is inferred
441 from the value.  An alternate can only express a choice between types
442 represented differently on the wire.
444 If a branch is typed as the 'bool' built-in, the alternate accepts
445 true and false; if it is typed as any of the various numeric
446 built-ins, it accepts a JSON number; if it is typed as a 'str'
447 built-in or named enum type, it accepts a JSON string; if it is typed
448 as the 'null' built-in, it accepts JSON null; and if it is typed as a
449 complex type (struct or union), it accepts a JSON object.
451 The example alternate declaration above allows using both of the
452 following example objects:
454  { "file": "my_existing_block_device_id" }
455  { "file": { "driver": "file",
456              "read-only": false,
457              "filename": "/tmp/mydisk.qcow2" } }
459 The optional 'if' member specifies a conditional.  See "Configuring
460 the schema" below for more on this.
462 The optional 'features' member specifies features.  See "Features"
463 below for more on this.
466 === Commands ===
468 Syntax:
469     COMMAND = { 'command': STRING,
470                 (
471                 '*data': ( MEMBERS | STRING ),
472                 |
473                 'data': STRING,
474                 'boxed': true,
475                 )
476                 '*returns': TYPE-REF,
477                 '*success-response': false,
478                 '*gen': false,
479                 '*allow-oob': true,
480                 '*allow-preconfig': true,
481                 '*coroutine': true,
482                 '*if': COND,
483                 '*features': FEATURES }
485 Member 'command' names the command.
487 Member 'data' defines the arguments.  It defaults to an empty MEMBERS
488 object.
490 If 'data' is a MEMBERS object, then MEMBERS defines arguments just
491 like a struct type's 'data' defines struct type members.
493 If 'data' is a STRING, then STRING names a complex type whose members
494 are the arguments.  A union type requires 'boxed': true.
496 Member 'returns' defines the command's return type.  It defaults to an
497 empty struct type.  It must normally be a complex type or an array of
498 a complex type.  To return anything else, the command must be listed
499 in pragma 'commands-returns-exceptions'.  If you do this, extending
500 the command to return additional information will be harder.  Use of
501 the pragma for new commands is strongly discouraged.
503 A command's error responses are not specified in the QAPI schema.
504 Error conditions should be documented in comments.
506 In the Client JSON Protocol, the value of the "execute" or "exec-oob"
507 member is the command name.  The value of the "arguments" member then
508 has to conform to the arguments, and the value of the success
509 response's "return" member will conform to the return type.
511 Some example commands:
513  { 'command': 'my-first-command',
514    'data': { 'arg1': 'str', '*arg2': 'str' } }
515  { 'struct': 'MyType', 'data': { '*value': 'str' } }
516  { 'command': 'my-second-command',
517    'returns': [ 'MyType' ] }
519 which would validate this Client JSON Protocol transaction:
521  => { "execute": "my-first-command",
522       "arguments": { "arg1": "hello" } }
523  <= { "return": { } }
524  => { "execute": "my-second-command" }
525  <= { "return": [ { "value": "one" }, { } ] }
527 The generator emits a prototype for the C function implementing the
528 command.  The function itself needs to be written by hand.  See
529 section "Code generated for commands" for examples.
531 The function returns the return type.  When member 'boxed' is absent,
532 it takes the command arguments as arguments one by one, in QAPI schema
533 order.  Else it takes them wrapped in the C struct generated for the
534 complex argument type.  It takes an additional Error ** argument in
535 either case.
537 The generator also emits a marshalling function that extracts
538 arguments for the user's function out of an input QDict, calls the
539 user's function, and if it succeeded, builds an output QObject from
540 its return value.  This is for use by the QMP monitor core.
542 In rare cases, QAPI cannot express a type-safe representation of a
543 corresponding Client JSON Protocol command.  You then have to suppress
544 generation of a marshalling function by including a member 'gen' with
545 boolean value false, and instead write your own function.  For
546 example:
548  { 'command': 'netdev_add',
549    'data': {'type': 'str', 'id': 'str'},
550    'gen': false }
552 Please try to avoid adding new commands that rely on this, and instead
553 use type-safe unions.
555 Normally, the QAPI schema is used to describe synchronous exchanges,
556 where a response is expected.  But in some cases, the action of a
557 command is expected to change state in a way that a successful
558 response is not possible (although the command will still return an
559 error object on failure).  When a successful reply is not possible,
560 the command definition includes the optional member 'success-response'
561 with boolean value false.  So far, only QGA makes use of this member.
563 Member 'allow-oob' declares whether the command supports out-of-band
564 (OOB) execution.  It defaults to false.  For example:
566  { 'command': 'migrate_recover',
567    'data': { 'uri': 'str' }, 'allow-oob': true }
569 See qmp-spec.txt for out-of-band execution syntax and semantics.
571 Commands supporting out-of-band execution can still be executed
572 in-band.
574 When a command is executed in-band, its handler runs in the main
575 thread with the BQL held.
577 When a command is executed out-of-band, its handler runs in a
578 dedicated monitor I/O thread with the BQL *not* held.
580 An OOB-capable command handler must satisfy the following conditions:
582 - It terminates quickly.
583 - It does not invoke system calls that may block.
584 - It does not access guest RAM that may block when userfaultfd is
585   enabled for postcopy live migration.
586 - It takes only "fast" locks, i.e. all critical sections protected by
587   any lock it takes also satisfy the conditions for OOB command
588   handler code.
590 The restrictions on locking limit access to shared state.  Such access
591 requires synchronization, but OOB commands can't take the BQL or any
592 other "slow" lock.
594 When in doubt, do not implement OOB execution support.
596 Member 'allow-preconfig' declares whether the command is available
597 before the machine is built.  It defaults to false.  For example:
599  { 'enum': 'QMPCapability',
600    'data': [ 'oob' ] }
601  { 'command': 'qmp_capabilities',
602    'data': { '*enable': [ 'QMPCapability' ] },
603    'allow-preconfig': true }
605 QMP is available before the machine is built only when QEMU was
606 started with --preconfig.
608 Member 'coroutine' tells the QMP dispatcher whether the command handler
609 is safe to be run in a coroutine.  It defaults to false.  If it is true,
610 the command handler is called from coroutine context and may yield while
611 waiting for an external event (such as I/O completion) in order to avoid
612 blocking the guest and other background operations.
614 Coroutine safety can be hard to prove, similar to thread safety.  Common
615 pitfalls are:
617 - The global mutex isn't held across qemu_coroutine_yield(), so
618   operations that used to assume that they execute atomically may have
619   to be more careful to protect against changes in the global state.
621 - Nested event loops (AIO_WAIT_WHILE() etc.) are problematic in
622   coroutine context and can easily lead to deadlocks.  They should be
623   replaced by yielding and reentering the coroutine when the condition
624   becomes false.
626 Since the command handler may assume coroutine context, any callers
627 other than the QMP dispatcher must also call it in coroutine context.
628 In particular, HMP commands calling such a QMP command handler must be
629 marked .coroutine = true in hmp-commands.hx.
631 It is an error to specify both 'coroutine': true and 'allow-oob': true
632 for a command.  We don't currently have a use case for both together and
633 without a use case, it's not entirely clear what the semantics should
636 The optional 'if' member specifies a conditional.  See "Configuring
637 the schema" below for more on this.
639 The optional 'features' member specifies features.  See "Features"
640 below for more on this.
643 === Events ===
645 Syntax:
646     EVENT = { 'event': STRING,
647               (
648               '*data': ( MEMBERS | STRING ),
649               |
650               'data': STRING,
651               'boxed': true,
652               )
653               '*if': COND,
654               '*features': FEATURES }
656 Member 'event' names the event.  This is the event name used in the
657 Client JSON Protocol.
659 Member 'data' defines the event-specific data.  It defaults to an
660 empty MEMBERS object.
662 If 'data' is a MEMBERS object, then MEMBERS defines event-specific
663 data just like a struct type's 'data' defines struct type members.
665 If 'data' is a STRING, then STRING names a complex type whose members
666 are the event-specific data.  A union type requires 'boxed': true.
668 An example event is:
670 { 'event': 'EVENT_C',
671   'data': { '*a': 'int', 'b': 'str' } }
673 Resulting in this JSON object:
675 { "event": "EVENT_C",
676   "data": { "b": "test string" },
677   "timestamp": { "seconds": 1267020223, "microseconds": 435656 } }
679 The generator emits a function to send the event.  When member 'boxed'
680 is absent, it takes event-specific data one by one, in QAPI schema
681 order.  Else it takes them wrapped in the C struct generated for the
682 complex type.  See section "Code generated for events" for examples.
684 The optional 'if' member specifies a conditional.  See "Configuring
685 the schema" below for more on this.
687 The optional 'features' member specifies features.  See "Features"
688 below for more on this.
691 === Features ===
693 Syntax:
694     FEATURES = [ FEATURE, ... ]
695     FEATURE = STRING
696             | { 'name': STRING, '*if': COND }
698 Sometimes, the behaviour of QEMU changes compatibly, but without a
699 change in the QMP syntax (usually by allowing values or operations
700 that previously resulted in an error).  QMP clients may still need to
701 know whether the extension is available.
703 For this purpose, a list of features can be specified for a command or
704 struct type.  Each list member can either be { 'name': STRING, '*if':
705 COND }, or STRING, which is shorthand for { 'name': STRING }.
707 The optional 'if' member specifies a conditional.  See "Configuring
708 the schema" below for more on this.
710 Example:
712 { 'struct': 'TestType',
713   'data': { 'number': 'int' },
714   'features': [ 'allow-negative-numbers' ] }
716 The feature strings are exposed to clients in introspection, as
717 explained in section "Client JSON Protocol introspection".
719 Intended use is to have each feature string signal that this build of
720 QEMU shows a certain behaviour.
723 ==== Special features ====
725 Feature "deprecated" marks a command, event, or struct member as
726 deprecated.  It is not supported elsewhere so far.
729 === Naming rules and reserved names ===
731 All names must begin with a letter, and contain only ASCII letters,
732 digits, hyphen, and underscore.  There are two exceptions: enum values
733 may start with a digit, and names that are downstream extensions (see
734 section Downstream extensions) start with underscore.
736 Names beginning with 'q_' are reserved for the generator, which uses
737 them for munging QMP names that resemble C keywords or other
738 problematic strings.  For example, a member named "default" in qapi
739 becomes "q_default" in the generated C code.
741 Types, commands, and events share a common namespace.  Therefore,
742 generally speaking, type definitions should always use CamelCase for
743 user-defined type names, while built-in types are lowercase.
745 Type names ending with 'Kind' or 'List' are reserved for the
746 generator, which uses them for implicit union enums and array types,
747 respectively.
749 Command names, and member names within a type, should be all lower
750 case with words separated by a hyphen.  However, some existing older
751 commands and complex types use underscore; when extending them,
752 consistency is preferred over blindly avoiding underscore.
754 Event names should be ALL_CAPS with words separated by underscore.
756 Member name 'u' and names starting with 'has-' or 'has_' are reserved
757 for the generator, which uses them for unions and for tracking
758 optional members.
760 Any name (command, event, type, member, or enum value) beginning with
761 "x-" is marked experimental, and may be withdrawn or changed
762 incompatibly in a future release.
764 Pragmas 'command-name-exceptions' and 'member-name-exceptions' let you
765 violate naming rules.  Use for new code is strongly discouraged.
768 === Downstream extensions ===
770 QAPI schema names that are externally visible, say in the Client JSON
771 Protocol, need to be managed with care.  Names starting with a
772 downstream prefix of the form __RFQDN_ are reserved for the downstream
773 who controls the valid, reverse fully qualified domain name RFQDN.
774 RFQDN may only contain ASCII letters, digits, hyphen and period.
776 Example: Red Hat, Inc. controls redhat.com, and may therefore add a
777 downstream command __com.redhat_drive-mirror.
780 === Configuring the schema ===
782 Syntax:
783     COND = STRING
784          | [ STRING, ... ]
786 All definitions take an optional 'if' member.  Its value must be a
787 string or a list of strings.  A string is shorthand for a list
788 containing just that string.  The code generated for the definition
789 will then be guarded by #if STRING for each STRING in the COND list.
791 Example: a conditional struct
793  { 'struct': 'IfStruct', 'data': { 'foo': 'int' },
794    'if': ['defined(CONFIG_FOO)', 'defined(HAVE_BAR)'] }
796 gets its generated code guarded like this:
798  #if defined(CONFIG_FOO)
799  #if defined(HAVE_BAR)
800  ... generated code ...
801  #endif /* defined(HAVE_BAR) */
802  #endif /* defined(CONFIG_FOO) */
804 Individual members of complex types, commands arguments, and
805 event-specific data can also be made conditional.  This requires the
806 longhand form of MEMBER.
808 Example: a struct type with unconditional member 'foo' and conditional
809 member 'bar'
811 { 'struct': 'IfStruct', 'data':
812   { 'foo': 'int',
813     'bar': { 'type': 'int', 'if': 'defined(IFCOND)'} } }
815 A union's discriminator may not be conditional.
817 Likewise, individual enumeration values be conditional.  This requires
818 the longhand form of ENUM-VALUE.
820 Example: an enum type with unconditional value 'foo' and conditional
821 value 'bar'
823 { 'enum': 'IfEnum', 'data':
824   [ 'foo',
825     { 'name' : 'bar', 'if': 'defined(IFCOND)' } ] }
827 Likewise, features can be conditional.  This requires the longhand
828 form of FEATURE.
830 Example: a struct with conditional feature 'allow-negative-numbers'
832 { 'struct': 'TestType',
833   'data': { 'number': 'int' },
834   'features': [ { 'name': 'allow-negative-numbers',
835                   'if': 'defined(IFCOND)' } ] }
837 Please note that you are responsible to ensure that the C code will
838 compile with an arbitrary combination of conditions, since the
839 generator is unable to check it at this point.
841 The conditions apply to introspection as well, i.e. introspection
842 shows a conditional entity only when the condition is satisfied in
843 this particular build.
846 === Documentation comments ===
848 A multi-line comment that starts and ends with a '##' line is a
849 documentation comment.
851 If the documentation comment starts like
853     ##
854     # @SYMBOL:
856 it documents the definition if SYMBOL, else it's free-form
857 documentation.
859 See below for more on definition documentation.
861 Free-form documentation may be used to provide additional text and
862 structuring content.
864 ==== Headings and subheadings ====
866 A free-form documentation comment containing a line which starts with
867 some '=' symbols and then a space defines a section heading:
869     ##
870     # = This is a top level heading
871     #
872     # This is a free-form comment which will go under the
873     # top level heading.
874     ##
876     ##
877     # == This is a second level heading
878     ##
880 A heading line must be the first line of the documentation
881 comment block.
883 Section headings must always be correctly nested, so you can only
884 define a third-level heading inside a second-level heading, and so on.
886 ==== Documentation markup ====
888 Documentation comments can use most rST markup.  In particular,
889 a '::' literal block can be used for examples:
891     # ::
892     #
893     #   Text of the example, may span
894     #   multiple lines
896 '*' starts an itemized list:
898     # * First item, may span
899     #   multiple lines
900     # * Second item
902 You can also use '-' instead of '*'.
904 A decimal number followed by '.' starts a numbered list:
906     # 1. First item, may span
907     #    multiple lines
908     # 2. Second item
910 The actual number doesn't matter.
912 Lists of either kind must be preceded and followed by a blank line.
913 If a list item's text spans multiple lines, then the second and
914 subsequent lines must be correctly indented to line up with the
915 first character of the first line.
917 The usual '**strong**', '*emphasised*' and '``literal``' markup should
918 be used.  If you need a single literal '*' you will need to
919 backslash-escape it.  As an extension beyond the usual rST syntax, you
920 can also use '@foo' to reference a name in the schema; this is
921 rendered the same way as '``foo``'.
923 Example:
926 # Some text foo with **bold** and *emphasis*
927 # 1. with a list
928 # 2. like that
930 # And some code:
932 # ::
934 #   $ echo foo
935 #   -> do this
936 #   <- get that
940 ==== Definition documentation ====
942 Definition documentation, if present, must immediately precede the
943 definition it documents.
945 When documentation is required (see pragma 'doc-required'), every
946 definition must have documentation.
948 Definition documentation starts with a line naming the definition,
949 followed by an optional overview, a description of each argument (for
950 commands and events), member (for structs and unions), branch (for
951 alternates), or value (for enums), and finally optional tagged
952 sections.
954 Descriptions of arguments can span multiple lines.  The description
955 text can start on the line following the '@argname:', in which case it
956 must not be indented at all.  It can also start on the same line as
957 the '@argname:'.  In this case if it spans multiple lines then second
958 and subsequent lines must be indented to line up with the first
959 character of the first line of the description:
961 # @argone:
962 # This is a two line description
963 # in the first style.
965 # @argtwo: This is a two line description
966 #          in the second style.
968 The number of spaces between the ':' and the text is not significant.
970 FIXME: the parser accepts these things in almost any order.
971 FIXME: union branches should be described, too.
973 Extensions added after the definition was first released carry a
974 '(since x.y.z)' comment.
976 A tagged section starts with one of the following words:
977 "Note:"/"Notes:", "Since:", "Example"/"Examples", "Returns:", "TODO:".
978 The section ends with the start of a new section.
980 The text of a section can start on a new line, in
981 which case it must not be indented at all.  It can also start
982 on the same line as the 'Note:', 'Returns:', etc tag.  In this
983 case if it spans multiple lines then second and subsequent
984 lines must be indented to match the first, in the same way as
985 multiline argument descriptions.
987 A 'Since: x.y.z' tagged section lists the release that introduced the
988 definition.
990 The text of a section can start on a new line, in
991 which case it must not be indented at all.  It can also start
992 on the same line as the 'Note:', 'Returns:', etc tag.  In this
993 case if it spans multiple lines then second and subsequent
994 lines must be indented to match the first.
996 An 'Example' or 'Examples' section is automatically rendered
997 entirely as literal fixed-width text.  In other sections,
998 the text is formatted, and rST markup can be used.
1000 For example:
1003 # @BlockStats:
1005 # Statistics of a virtual block device or a block backing device.
1007 # @device: If the stats are for a virtual block device, the name
1008 #          corresponding to the virtual block device.
1010 # @node-name: The node name of the device. (since 2.3)
1012 # ... more members ...
1014 # Since: 0.14.0
1016 { 'struct': 'BlockStats',
1017   'data': {'*device': 'str', '*node-name': 'str',
1018            ... more members ... } }
1021 # @query-blockstats:
1023 # Query the @BlockStats for all virtual block devices.
1025 # @query-nodes: If true, the command will query all the
1026 #               block nodes ... explain, explain ...  (since 2.3)
1028 # Returns: A list of @BlockStats for each virtual block devices.
1030 # Since: 0.14.0
1032 # Example:
1034 # -> { "execute": "query-blockstats" }
1035 # <- {
1036 #      ... lots of output ...
1037 #    }
1040 { 'command': 'query-blockstats',
1041   'data': { '*query-nodes': 'bool' },
1042   'returns': ['BlockStats'] }
1045 == Client JSON Protocol introspection ==
1047 Clients of a Client JSON Protocol commonly need to figure out what
1048 exactly the server (QEMU) supports.
1050 For this purpose, QMP provides introspection via command
1051 query-qmp-schema.  QGA currently doesn't support introspection.
1053 While Client JSON Protocol wire compatibility should be maintained
1054 between qemu versions, we cannot make the same guarantees for
1055 introspection stability.  For example, one version of qemu may provide
1056 a non-variant optional member of a struct, and a later version rework
1057 the member to instead be non-optional and associated with a variant.
1058 Likewise, one version of qemu may list a member with open-ended type
1059 'str', and a later version could convert it to a finite set of strings
1060 via an enum type; or a member may be converted from a specific type to
1061 an alternate that represents a choice between the original type and
1062 something else.
1064 query-qmp-schema returns a JSON array of SchemaInfo objects.  These
1065 objects together describe the wire ABI, as defined in the QAPI schema.
1066 There is no specified order to the SchemaInfo objects returned; a
1067 client must search for a particular name throughout the entire array
1068 to learn more about that name, but is at least guaranteed that there
1069 will be no collisions between type, command, and event names.
1071 However, the SchemaInfo can't reflect all the rules and restrictions
1072 that apply to QMP.  It's interface introspection (figuring out what's
1073 there), not interface specification.  The specification is in the QAPI
1074 schema.  To understand how QMP is to be used, you need to study the
1075 QAPI schema.
1077 Like any other command, query-qmp-schema is itself defined in the QAPI
1078 schema, along with the SchemaInfo type.  This text attempts to give an
1079 overview how things work.  For details you need to consult the QAPI
1080 schema.
1082 SchemaInfo objects have common members "name", "meta-type",
1083 "features", and additional variant members depending on the value of
1084 meta-type.
1086 Each SchemaInfo object describes a wire ABI entity of a certain
1087 meta-type: a command, event or one of several kinds of type.
1089 SchemaInfo for commands and events have the same name as in the QAPI
1090 schema.
1092 Command and event names are part of the wire ABI, but type names are
1093 not.  Therefore, the SchemaInfo for types have auto-generated
1094 meaningless names.  For readability, the examples in this section use
1095 meaningful type names instead.
1097 Optional member "features" exposes the entity's feature strings as a
1098 JSON array of strings.
1100 To examine a type, start with a command or event using it, then follow
1101 references by name.
1103 QAPI schema definitions not reachable that way are omitted.
1105 The SchemaInfo for a command has meta-type "command", and variant
1106 members "arg-type", "ret-type" and "allow-oob".  On the wire, the
1107 "arguments" member of a client's "execute" command must conform to the
1108 object type named by "arg-type".  The "return" member that the server
1109 passes in a success response conforms to the type named by "ret-type".
1110 When "allow-oob" is true, it means the command supports out-of-band
1111 execution.  It defaults to false.
1113 If the command takes no arguments, "arg-type" names an object type
1114 without members.  Likewise, if the command returns nothing, "ret-type"
1115 names an object type without members.
1117 Example: the SchemaInfo for command query-qmp-schema
1119     { "name": "query-qmp-schema", "meta-type": "command",
1120       "arg-type": "q_empty", "ret-type": "SchemaInfoList" }
1122     Type "q_empty" is an automatic object type without members, and type
1123     "SchemaInfoList" is the array of SchemaInfo type.
1125 The SchemaInfo for an event has meta-type "event", and variant member
1126 "arg-type".  On the wire, a "data" member that the server passes in an
1127 event conforms to the object type named by "arg-type".
1129 If the event carries no additional information, "arg-type" names an
1130 object type without members.  The event may not have a data member on
1131 the wire then.
1133 Each command or event defined with 'data' as MEMBERS object in the
1134 QAPI schema implicitly defines an object type.
1136 Example: the SchemaInfo for EVENT_C from section Events
1138     { "name": "EVENT_C", "meta-type": "event",
1139       "arg-type": "q_obj-EVENT_C-arg" }
1141     Type "q_obj-EVENT_C-arg" is an implicitly defined object type with
1142     the two members from the event's definition.
1144 The SchemaInfo for struct and union types has meta-type "object".
1146 The SchemaInfo for a struct type has variant member "members".
1148 The SchemaInfo for a union type additionally has variant members "tag"
1149 and "variants".
1151 "members" is a JSON array describing the object's common members, if
1152 any.  Each element is a JSON object with members "name" (the member's
1153 name), "type" (the name of its type), and optionally "default".  The
1154 member is optional if "default" is present.  Currently, "default" can
1155 only have value null.  Other values are reserved for future
1156 extensions.  The "members" array is in no particular order; clients
1157 must search the entire object when learning whether a particular
1158 member is supported.
1160 Example: the SchemaInfo for MyType from section Struct types
1162     { "name": "MyType", "meta-type": "object",
1163       "members": [
1164           { "name": "member1", "type": "str" },
1165           { "name": "member2", "type": "int" },
1166           { "name": "member3", "type": "str", "default": null } ] }
1168 "features" exposes the command's feature strings as a JSON array of
1169 strings.
1171 Example: the SchemaInfo for TestType from section Features:
1173     { "name": "TestType", "meta-type": "object",
1174       "members": [
1175           { "name": "number", "type": "int" } ],
1176       "features": ["allow-negative-numbers"] }
1178 "tag" is the name of the common member serving as type tag.
1179 "variants" is a JSON array describing the object's variant members.
1180 Each element is a JSON object with members "case" (the value of type
1181 tag this element applies to) and "type" (the name of an object type
1182 that provides the variant members for this type tag value).  The
1183 "variants" array is in no particular order, and is not guaranteed to
1184 list cases in the same order as the corresponding "tag" enum type.
1186 Example: the SchemaInfo for flat union BlockdevOptions from section
1187 Union types
1189     { "name": "BlockdevOptions", "meta-type": "object",
1190       "members": [
1191           { "name": "driver", "type": "BlockdevDriver" },
1192           { "name": "read-only", "type": "bool", "default": null } ],
1193       "tag": "driver",
1194       "variants": [
1195           { "case": "file", "type": "BlockdevOptionsFile" },
1196           { "case": "qcow2", "type": "BlockdevOptionsQcow2" } ] }
1198 Note that base types are "flattened": its members are included in the
1199 "members" array.
1201 A simple union implicitly defines an enumeration type for its implicit
1202 discriminator (called "type" on the wire, see section Union types).
1204 A simple union implicitly defines an object type for each of its
1205 variants.
1207 Example: the SchemaInfo for simple union BlockdevOptionsSimple from section
1208 Union types
1210     { "name": "BlockdevOptionsSimple", "meta-type": "object",
1211       "members": [
1212           { "name": "type", "type": "BlockdevOptionsSimpleKind" } ],
1213       "tag": "type",
1214       "variants": [
1215           { "case": "file", "type": "q_obj-BlockdevOptionsFile-wrapper" },
1216           { "case": "qcow2", "type": "q_obj-BlockdevOptionsQcow2-wrapper" } ] }
1218     Enumeration type "BlockdevOptionsSimpleKind" and the object types
1219     "q_obj-BlockdevOptionsFile-wrapper", "q_obj-BlockdevOptionsQcow2-wrapper"
1220     are implicitly defined.
1222 The SchemaInfo for an alternate type has meta-type "alternate", and
1223 variant member "members".  "members" is a JSON array.  Each element is
1224 a JSON object with member "type", which names a type.  Values of the
1225 alternate type conform to exactly one of its member types.  There is
1226 no guarantee on the order in which "members" will be listed.
1228 Example: the SchemaInfo for BlockdevRef from section Alternate types
1230     { "name": "BlockdevRef", "meta-type": "alternate",
1231       "members": [
1232           { "type": "BlockdevOptions" },
1233           { "type": "str" } ] }
1235 The SchemaInfo for an array type has meta-type "array", and variant
1236 member "element-type", which names the array's element type.  Array
1237 types are implicitly defined.  For convenience, the array's name may
1238 resemble the element type; however, clients should examine member
1239 "element-type" instead of making assumptions based on parsing member
1240 "name".
1242 Example: the SchemaInfo for ['str']
1244     { "name": "[str]", "meta-type": "array",
1245       "element-type": "str" }
1247 The SchemaInfo for an enumeration type has meta-type "enum" and
1248 variant member "values".  The values are listed in no particular
1249 order; clients must search the entire enum when learning whether a
1250 particular value is supported.
1252 Example: the SchemaInfo for MyEnum from section Enumeration types
1254     { "name": "MyEnum", "meta-type": "enum",
1255       "values": [ "value1", "value2", "value3" ] }
1257 The SchemaInfo for a built-in type has the same name as the type in
1258 the QAPI schema (see section Built-in Types), with one exception
1259 detailed below.  It has variant member "json-type" that shows how
1260 values of this type are encoded on the wire.
1262 Example: the SchemaInfo for str
1264     { "name": "str", "meta-type": "builtin", "json-type": "string" }
1266 The QAPI schema supports a number of integer types that only differ in
1267 how they map to C.  They are identical as far as SchemaInfo is
1268 concerned.  Therefore, they get all mapped to a single type "int" in
1269 SchemaInfo.
1271 As explained above, type names are not part of the wire ABI.  Not even
1272 the names of built-in types.  Clients should examine member
1273 "json-type" instead of hard-coding names of built-in types.
1276 == Compatibility considerations ==
1278 Maintaining backward compatibility at the Client JSON Protocol level
1279 while evolving the schema requires some care.  This section is about
1280 syntactic compatibility, which is necessary, but not sufficient, for
1281 actual compatibility.
1283 Clients send commands with argument data, and receive command
1284 responses with return data and events with event data.
1286 Adding opt-in functionality to the send direction is backwards
1287 compatible: adding commands, optional arguments, enumeration values,
1288 union and alternate branches; turning an argument type into an
1289 alternate of that type; making mandatory arguments optional.  Clients
1290 oblivious of the new functionality continue to work.
1292 Incompatible changes include removing commands, command arguments,
1293 enumeration values, union and alternate branches, adding mandatory
1294 command arguments, and making optional arguments mandatory.
1296 The specified behavior of an absent optional argument should remain
1297 the same.  With proper documentation, this policy still allows some
1298 flexibility; for example, when an optional 'buffer-size' argument is
1299 specified to default to a sensible buffer size, the actual default
1300 value can still be changed.  The specified default behavior is not the
1301 exact size of the buffer, only that the default size is sensible.
1303 Adding functionality to the receive direction is generally backwards
1304 compatible: adding events, adding return and event data members.
1305 Clients are expected to ignore the ones they don't know.
1307 Removing "unreachable" stuff like events that can't be triggered
1308 anymore, optional return or event data members that can't be sent
1309 anymore, and return or event data member (enumeration) values that
1310 can't be sent anymore makes no difference to clients, except for
1311 introspection.  The latter can conceivably confuse clients, so tread
1312 carefully.
1314 Incompatible changes include removing return and event data members.
1316 Any change to a command definition's 'data' or one of the types used
1317 there (recursively) needs to consider send direction compatibility.
1319 Any change to a command definition's 'return', an event definition's
1320 'data', or one of the types used there (recursively) needs to consider
1321 receive direction compatibility.
1323 Any change to types used in both contexts need to consider both.
1325 Enumeration type values and complex and alternate type members may be
1326 reordered freely.  For enumerations and alternate types, this doesn't
1327 affect the wire encoding.  For complex types, this might make the
1328 implementation emit JSON object members in a different order, which
1329 the Client JSON Protocol permits.
1331 Since type names are not visible in the Client JSON Protocol, types
1332 may be freely renamed.  Even certain refactorings are invisible, such
1333 as splitting members from one type into a common base type.
1336 == Code generation ==
1338 The QAPI code generator qapi-gen.py generates code and documentation
1339 from the schema.  Together with the core QAPI libraries, this code
1340 provides everything required to take JSON commands read in by a Client
1341 JSON Protocol server, unmarshal the arguments into the underlying C
1342 types, call into the corresponding C function, map the response back
1343 to a Client JSON Protocol response to be returned to the user, and
1344 introspect the commands.
1346 As an example, we'll use the following schema, which describes a
1347 single complex user-defined type, along with command which takes a
1348 list of that type as a parameter, and returns a single element of that
1349 type.  The user is responsible for writing the implementation of
1350 qmp_my_command(); everything else is produced by the generator.
1352     $ cat example-schema.json
1353     { 'struct': 'UserDefOne',
1354       'data': { 'integer': 'int', '*string': 'str' } }
1356     { 'command': 'my-command',
1357       'data': { 'arg1': ['UserDefOne'] },
1358       'returns': 'UserDefOne' }
1360     { 'event': 'MY_EVENT' }
1362 We run qapi-gen.py like this:
1364     $ python scripts/qapi-gen.py --output-dir="qapi-generated" \
1365     --prefix="example-" example-schema.json
1367 For a more thorough look at generated code, the testsuite includes
1368 tests/qapi-schema/qapi-schema-tests.json that covers more examples of
1369 what the generator will accept, and compiles the resulting C code as
1370 part of 'make check-unit'.
1372 === Code generated for QAPI types ===
1374 The following files are created:
1376 $(prefix)qapi-types.h - C types corresponding to types defined in
1377                         the schema
1379 $(prefix)qapi-types.c - Cleanup functions for the above C types
1381 The $(prefix) is an optional parameter used as a namespace to keep the
1382 generated code from one schema/code-generation separated from others so code
1383 can be generated/used from multiple schemas without clobbering previously
1384 created code.
1386 Example:
1388     $ cat qapi-generated/example-qapi-types.h
1389 [Uninteresting stuff omitted...]
1391     #ifndef EXAMPLE_QAPI_TYPES_H
1392     #define EXAMPLE_QAPI_TYPES_H
1394     #include "qapi/qapi-builtin-types.h"
1396     typedef struct UserDefOne UserDefOne;
1398     typedef struct UserDefOneList UserDefOneList;
1400     typedef struct q_obj_my_command_arg q_obj_my_command_arg;
1402     struct UserDefOne {
1403         int64_t integer;
1404         bool has_string;
1405         char *string;
1406     };
1408     void qapi_free_UserDefOne(UserDefOne *obj);
1409     G_DEFINE_AUTOPTR_CLEANUP_FUNC(UserDefOne, qapi_free_UserDefOne)
1411     struct UserDefOneList {
1412         UserDefOneList *next;
1413         UserDefOne *value;
1414     };
1416     void qapi_free_UserDefOneList(UserDefOneList *obj);
1417     G_DEFINE_AUTOPTR_CLEANUP_FUNC(UserDefOneList, qapi_free_UserDefOneList)
1419     struct q_obj_my_command_arg {
1420         UserDefOneList *arg1;
1421     };
1423     #endif /* EXAMPLE_QAPI_TYPES_H */
1424     $ cat qapi-generated/example-qapi-types.c
1425 [Uninteresting stuff omitted...]
1427     void qapi_free_UserDefOne(UserDefOne *obj)
1428     {
1429         Visitor *v;
1431         if (!obj) {
1432             return;
1433         }
1435         v = qapi_dealloc_visitor_new();
1436         visit_type_UserDefOne(v, NULL, &obj, NULL);
1437         visit_free(v);
1438     }
1440     void qapi_free_UserDefOneList(UserDefOneList *obj)
1441     {
1442         Visitor *v;
1444         if (!obj) {
1445             return;
1446         }
1448         v = qapi_dealloc_visitor_new();
1449         visit_type_UserDefOneList(v, NULL, &obj, NULL);
1450         visit_free(v);
1451     }
1453 [Uninteresting stuff omitted...]
1455 For a modular QAPI schema (see section Include directives), code for
1456 each sub-module SUBDIR/SUBMODULE.json is actually generated into
1458 SUBDIR/$(prefix)qapi-types-SUBMODULE.h
1459 SUBDIR/$(prefix)qapi-types-SUBMODULE.c
1461 If qapi-gen.py is run with option --builtins, additional files are
1462 created:
1464 qapi-builtin-types.h - C types corresponding to built-in types
1466 qapi-builtin-types.c - Cleanup functions for the above C types
1468 === Code generated for visiting QAPI types ===
1470 These are the visitor functions used to walk through and convert
1471 between a native QAPI C data structure and some other format (such as
1472 QObject); the generated functions are named visit_type_FOO() and
1473 visit_type_FOO_members().
1475 The following files are generated:
1477 $(prefix)qapi-visit.c: Visitor function for a particular C type, used
1478                        to automagically convert QObjects into the
1479                        corresponding C type and vice-versa, as well
1480                        as for deallocating memory for an existing C
1481                        type
1483 $(prefix)qapi-visit.h: Declarations for previously mentioned visitor
1484                        functions
1486 Example:
1488     $ cat qapi-generated/example-qapi-visit.h
1489 [Uninteresting stuff omitted...]
1491     #ifndef EXAMPLE_QAPI_VISIT_H
1492     #define EXAMPLE_QAPI_VISIT_H
1494     #include "qapi/qapi-builtin-visit.h"
1495     #include "example-qapi-types.h"
1498     bool visit_type_UserDefOne_members(Visitor *v, UserDefOne *obj, Error **errp);
1499     bool visit_type_UserDefOne(Visitor *v, const char *name, UserDefOne **obj, Error **errp);
1500     bool visit_type_UserDefOneList(Visitor *v, const char *name, UserDefOneList **obj, Error **errp);
1502     bool visit_type_q_obj_my_command_arg_members(Visitor *v, q_obj_my_command_arg *obj, Error **errp);
1504     #endif /* EXAMPLE_QAPI_VISIT_H */
1505     $ cat qapi-generated/example-qapi-visit.c
1506 [Uninteresting stuff omitted...]
1508     bool visit_type_UserDefOne_members(Visitor *v, UserDefOne *obj, Error **errp)
1509     {
1510         if (!visit_type_int(v, "integer", &obj->integer, errp)) {
1511             return false;
1512         }
1513         if (visit_optional(v, "string", &obj->has_string)) {
1514             if (!visit_type_str(v, "string", &obj->string, errp)) {
1515                 return false;
1516             }
1517         }
1518         return true;
1519     }
1521     bool visit_type_UserDefOne(Visitor *v, const char *name, UserDefOne **obj, Error **errp)
1522     {
1523         bool ok = false;
1525         if (!visit_start_struct(v, name, (void **)obj, sizeof(UserDefOne), errp)) {
1526             return false;
1527         }
1528         if (!*obj) {
1529             /* incomplete */
1530             assert(visit_is_dealloc(v));
1531             goto out_obj;
1532         }
1533         if (!visit_type_UserDefOne_members(v, *obj, errp)) {
1534             goto out_obj;
1535         }
1536         ok = visit_check_struct(v, errp);
1537     out_obj:
1538         visit_end_struct(v, (void **)obj);
1539         if (!ok && visit_is_input(v)) {
1540             qapi_free_UserDefOne(*obj);
1541             *obj = NULL;
1542         }
1543         return ok;
1544     }
1546     bool visit_type_UserDefOneList(Visitor *v, const char *name, UserDefOneList **obj, Error **errp)
1547     {
1548         bool ok = false;
1549         UserDefOneList *tail;
1550         size_t size = sizeof(**obj);
1552         if (!visit_start_list(v, name, (GenericList **)obj, size, errp)) {
1553             return false;
1554         }
1556         for (tail = *obj; tail;
1557              tail = (UserDefOneList *)visit_next_list(v, (GenericList *)tail, size)) {
1558             if (!visit_type_UserDefOne(v, NULL, &tail->value, errp)) {
1559                 goto out_obj;
1560             }
1561         }
1563         ok = visit_check_list(v, errp);
1564     out_obj:
1565         visit_end_list(v, (void **)obj);
1566         if (!ok && visit_is_input(v)) {
1567             qapi_free_UserDefOneList(*obj);
1568             *obj = NULL;
1569         }
1570         return ok;
1571     }
1573     bool visit_type_q_obj_my_command_arg_members(Visitor *v, q_obj_my_command_arg *obj, Error **errp)
1574     {
1575         if (!visit_type_UserDefOneList(v, "arg1", &obj->arg1, errp)) {
1576             return false;
1577         }
1578         return true;
1579     }
1581 [Uninteresting stuff omitted...]
1583 For a modular QAPI schema (see section Include directives), code for
1584 each sub-module SUBDIR/SUBMODULE.json is actually generated into
1586 SUBDIR/$(prefix)qapi-visit-SUBMODULE.h
1587 SUBDIR/$(prefix)qapi-visit-SUBMODULE.c
1589 If qapi-gen.py is run with option --builtins, additional files are
1590 created:
1592 qapi-builtin-visit.h - Visitor functions for built-in types
1594 qapi-builtin-visit.c - Declarations for these visitor functions
1596 === Code generated for commands ===
1598 These are the marshaling/dispatch functions for the commands defined
1599 in the schema.  The generated code provides qmp_marshal_COMMAND(), and
1600 declares qmp_COMMAND() that the user must implement.
1602 The following files are generated:
1604 $(prefix)qapi-commands.c: Command marshal/dispatch functions for each
1605                           QMP command defined in the schema
1607 $(prefix)qapi-commands.h: Function prototypes for the QMP commands
1608                           specified in the schema
1610 $(prefix)qapi-init-commands.h - Command initialization prototype
1612 $(prefix)qapi-init-commands.c - Command initialization code
1614 Example:
1616     $ cat qapi-generated/example-qapi-commands.h
1617 [Uninteresting stuff omitted...]
1619     #ifndef EXAMPLE_QAPI_COMMANDS_H
1620     #define EXAMPLE_QAPI_COMMANDS_H
1622     #include "example-qapi-types.h"
1624     UserDefOne *qmp_my_command(UserDefOneList *arg1, Error **errp);
1625     void qmp_marshal_my_command(QDict *args, QObject **ret, Error **errp);
1627     #endif /* EXAMPLE_QAPI_COMMANDS_H */
1628     $ cat qapi-generated/example-qapi-commands.c
1629 [Uninteresting stuff omitted...]
1631     static void qmp_marshal_output_UserDefOne(UserDefOne *ret_in, QObject **ret_out, Error **errp)
1632     {
1633         Visitor *v;
1635         v = qobject_output_visitor_new(ret_out);
1636         if (visit_type_UserDefOne(v, "unused", &ret_in, errp)) {
1637             visit_complete(v, ret_out);
1638         }
1639         visit_free(v);
1640         v = qapi_dealloc_visitor_new();
1641         visit_type_UserDefOne(v, "unused", &ret_in, NULL);
1642         visit_free(v);
1643     }
1645     void qmp_marshal_my_command(QDict *args, QObject **ret, Error **errp)
1646     {
1647         Error *err = NULL;
1648         bool ok = false;
1649         Visitor *v;
1650         UserDefOne *retval;
1651         q_obj_my_command_arg arg = {0};
1653         v = qobject_input_visitor_new(QOBJECT(args));
1654         if (!visit_start_struct(v, NULL, NULL, 0, errp)) {
1655             goto out;
1656         }
1657         if (visit_type_q_obj_my_command_arg_members(v, &arg, errp)) {
1658             ok = visit_check_struct(v, errp);
1659         }
1660         visit_end_struct(v, NULL);
1661         if (!ok) {
1662             goto out;
1663         }
1665         retval = qmp_my_command(arg.arg1, &err);
1666         error_propagate(errp, err);
1667         if (err) {
1668             goto out;
1669         }
1671         qmp_marshal_output_UserDefOne(retval, ret, errp);
1673     out:
1674         visit_free(v);
1675         v = qapi_dealloc_visitor_new();
1676         visit_start_struct(v, NULL, NULL, 0, NULL);
1677         visit_type_q_obj_my_command_arg_members(v, &arg, NULL);
1678         visit_end_struct(v, NULL);
1679         visit_free(v);
1680     }
1682 [Uninteresting stuff omitted...]
1683     $ cat qapi-generated/example-qapi-init-commands.h
1684 [Uninteresting stuff omitted...]
1685     #ifndef EXAMPLE_QAPI_INIT_COMMANDS_H
1686     #define EXAMPLE_QAPI_INIT_COMMANDS_H
1688     #include "qapi/qmp/dispatch.h"
1690     void example_qmp_init_marshal(QmpCommandList *cmds);
1692     #endif /* EXAMPLE_QAPI_INIT_COMMANDS_H */
1693     $ cat qapi-generated/example-qapi-init-commands.c
1694 [Uninteresting stuff omitted...]
1695     void example_qmp_init_marshal(QmpCommandList *cmds)
1696     {
1697         QTAILQ_INIT(cmds);
1699         qmp_register_command(cmds, "my-command",
1700                              qmp_marshal_my_command, QCO_NO_OPTIONS);
1701     }
1702 [Uninteresting stuff omitted...]
1704 For a modular QAPI schema (see section Include directives), code for
1705 each sub-module SUBDIR/SUBMODULE.json is actually generated into
1707 SUBDIR/$(prefix)qapi-commands-SUBMODULE.h
1708 SUBDIR/$(prefix)qapi-commands-SUBMODULE.c
1710 === Code generated for events ===
1712 This is the code related to events defined in the schema, providing
1713 qapi_event_send_EVENT().
1715 The following files are created:
1717 $(prefix)qapi-events.h - Function prototypes for each event type
1719 $(prefix)qapi-events.c - Implementation of functions to send an event
1721 $(prefix)qapi-emit-events.h - Enumeration of all event names, and
1722                               common event code declarations
1724 $(prefix)qapi-emit-events.c - Common event code definitions
1726 Example:
1728     $ cat qapi-generated/example-qapi-events.h
1729 [Uninteresting stuff omitted...]
1731     #ifndef EXAMPLE_QAPI_EVENTS_H
1732     #define EXAMPLE_QAPI_EVENTS_H
1734     #include "qapi/util.h"
1735     #include "example-qapi-types.h"
1737     void qapi_event_send_my_event(void);
1739     #endif /* EXAMPLE_QAPI_EVENTS_H */
1740     $ cat qapi-generated/example-qapi-events.c
1741 [Uninteresting stuff omitted...]
1743     void qapi_event_send_my_event(void)
1744     {
1745         QDict *qmp;
1747         qmp = qmp_event_build_dict("MY_EVENT");
1749         example_qapi_event_emit(EXAMPLE_QAPI_EVENT_MY_EVENT, qmp);
1751         qobject_unref(qmp);
1752     }
1754 [Uninteresting stuff omitted...]
1755     $ cat qapi-generated/example-qapi-emit-events.h
1756 [Uninteresting stuff omitted...]
1758     #ifndef EXAMPLE_QAPI_EMIT_EVENTS_H
1759     #define EXAMPLE_QAPI_EMIT_EVENTS_H
1761     #include "qapi/util.h"
1763     typedef enum example_QAPIEvent {
1764         EXAMPLE_QAPI_EVENT_MY_EVENT,
1765         EXAMPLE_QAPI_EVENT__MAX,
1766     } example_QAPIEvent;
1768     #define example_QAPIEvent_str(val) \
1769         qapi_enum_lookup(&example_QAPIEvent_lookup, (val))
1771     extern const QEnumLookup example_QAPIEvent_lookup;
1773     void example_qapi_event_emit(example_QAPIEvent event, QDict *qdict);
1775     #endif /* EXAMPLE_QAPI_EMIT_EVENTS_H */
1776     $ cat qapi-generated/example-qapi-emit-events.c
1777 [Uninteresting stuff omitted...]
1779     const QEnumLookup example_QAPIEvent_lookup = {
1780         .array = (const char *const[]) {
1781             [EXAMPLE_QAPI_EVENT_MY_EVENT] = "MY_EVENT",
1782         },
1783         .size = EXAMPLE_QAPI_EVENT__MAX
1784     };
1786 [Uninteresting stuff omitted...]
1788 For a modular QAPI schema (see section Include directives), code for
1789 each sub-module SUBDIR/SUBMODULE.json is actually generated into
1791 SUBDIR/$(prefix)qapi-events-SUBMODULE.h
1792 SUBDIR/$(prefix)qapi-events-SUBMODULE.c
1794 === Code generated for introspection ===
1796 The following files are created:
1798 $(prefix)qapi-introspect.c - Defines a string holding a JSON
1799                             description of the schema
1801 $(prefix)qapi-introspect.h - Declares the above string
1803 Example:
1805     $ cat qapi-generated/example-qapi-introspect.h
1806 [Uninteresting stuff omitted...]
1808     #ifndef EXAMPLE_QAPI_INTROSPECT_H
1809     #define EXAMPLE_QAPI_INTROSPECT_H
1811     #include "qapi/qmp/qlit.h"
1813     extern const QLitObject example_qmp_schema_qlit;
1815     #endif /* EXAMPLE_QAPI_INTROSPECT_H */
1816     $ cat qapi-generated/example-qapi-introspect.c
1817 [Uninteresting stuff omitted...]
1819     const QLitObject example_qmp_schema_qlit = QLIT_QLIST(((QLitObject[]) {
1820         QLIT_QDICT(((QLitDictEntry[]) {
1821             { "arg-type", QLIT_QSTR("0"), },
1822             { "meta-type", QLIT_QSTR("command"), },
1823             { "name", QLIT_QSTR("my-command"), },
1824             { "ret-type", QLIT_QSTR("1"), },
1825             {}
1826         })),
1827         QLIT_QDICT(((QLitDictEntry[]) {
1828             { "arg-type", QLIT_QSTR("2"), },
1829             { "meta-type", QLIT_QSTR("event"), },
1830             { "name", QLIT_QSTR("MY_EVENT"), },
1831             {}
1832         })),
1833         /* "0" = q_obj_my-command-arg */
1834         QLIT_QDICT(((QLitDictEntry[]) {
1835             { "members", QLIT_QLIST(((QLitObject[]) {
1836                 QLIT_QDICT(((QLitDictEntry[]) {
1837                     { "name", QLIT_QSTR("arg1"), },
1838                     { "type", QLIT_QSTR("[1]"), },
1839                     {}
1840                 })),
1841                 {}
1842             })), },
1843             { "meta-type", QLIT_QSTR("object"), },
1844             { "name", QLIT_QSTR("0"), },
1845             {}
1846         })),
1847         /* "1" = UserDefOne */
1848         QLIT_QDICT(((QLitDictEntry[]) {
1849             { "members", QLIT_QLIST(((QLitObject[]) {
1850                 QLIT_QDICT(((QLitDictEntry[]) {
1851                     { "name", QLIT_QSTR("integer"), },
1852                     { "type", QLIT_QSTR("int"), },
1853                     {}
1854                 })),
1855                 QLIT_QDICT(((QLitDictEntry[]) {
1856                     { "default", QLIT_QNULL, },
1857                     { "name", QLIT_QSTR("string"), },
1858                     { "type", QLIT_QSTR("str"), },
1859                     {}
1860                 })),
1861                 {}
1862             })), },
1863             { "meta-type", QLIT_QSTR("object"), },
1864             { "name", QLIT_QSTR("1"), },
1865             {}
1866         })),
1867         /* "2" = q_empty */
1868         QLIT_QDICT(((QLitDictEntry[]) {
1869             { "members", QLIT_QLIST(((QLitObject[]) {
1870                 {}
1871             })), },
1872             { "meta-type", QLIT_QSTR("object"), },
1873             { "name", QLIT_QSTR("2"), },
1874             {}
1875         })),
1876         QLIT_QDICT(((QLitDictEntry[]) {
1877             { "element-type", QLIT_QSTR("1"), },
1878             { "meta-type", QLIT_QSTR("array"), },
1879             { "name", QLIT_QSTR("[1]"), },
1880             {}
1881         })),
1882         QLIT_QDICT(((QLitDictEntry[]) {
1883             { "json-type", QLIT_QSTR("int"), },
1884             { "meta-type", QLIT_QSTR("builtin"), },
1885             { "name", QLIT_QSTR("int"), },
1886             {}
1887         })),
1888         QLIT_QDICT(((QLitDictEntry[]) {
1889             { "json-type", QLIT_QSTR("string"), },
1890             { "meta-type", QLIT_QSTR("builtin"), },
1891             { "name", QLIT_QSTR("str"), },
1892             {}
1893         })),
1894         {}
1895     }));
1897 [Uninteresting stuff omitted...]