hw/watchdog/cmsdk-apb-watchdog.c: Switch to transaction-based ptimer API
[qemu/ar7.git] / docs / devel / qapi-code-gen.txt
blob64d9e4c6a9f4765cd96d27690fc698c0b1b902bf
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 }
462 Member 'command' names the command.
464 Member 'data' defines the arguments.  It defaults to an empty MEMBERS
465 object.
467 If 'data' is a MEMBERS object, then MEMBERS defines arguments just
468 like a struct type's 'data' defines struct type members.
470 If 'data' is a STRING, then STRING names a complex type whose members
471 are the arguments.  A union type requires 'boxed': true.
473 Member 'returns' defines the command's return type.  It defaults to an
474 empty struct type.  It must normally be a complex type or an array of
475 a complex type.  To return anything else, the command must be listed
476 in pragma 'returns-whitelist'.  If you do this, extending the command
477 to return additional information will be harder.  Use of
478 'returns-whitelist' for new commands is strongly discouraged.
480 A command's error responses are not specified in the QAPI schema.
481 Error conditions should be documented in comments.
483 In the Client JSON Protocol, the value of the "execute" or "exec-oob"
484 member is the command name.  The value of the "arguments" member then
485 has to conform to the arguments, and the value of the success
486 response's "return" member will conform to the return type.
488 Some example commands:
490  { 'command': 'my-first-command',
491    'data': { 'arg1': 'str', '*arg2': 'str' } }
492  { 'struct': 'MyType', 'data': { '*value': 'str' } }
493  { 'command': 'my-second-command',
494    'returns': [ 'MyType' ] }
496 which would validate this Client JSON Protocol transaction:
498  => { "execute": "my-first-command",
499       "arguments": { "arg1": "hello" } }
500  <= { "return": { } }
501  => { "execute": "my-second-command" }
502  <= { "return": [ { "value": "one" }, { } ] }
504 The generator emits a prototype for the C function implementing the
505 command.  The function itself needs to be written by hand.  See
506 section "Code generated for commands" for examples.
508 The function returns the return type.  When member 'boxed' is absent,
509 it takes the command arguments as arguments one by one, in QAPI schema
510 order.  Else it takes them wrapped in the C struct generated for the
511 complex argument type.  It takes an additional Error ** argument in
512 either case.
514 The generator also emits a marshalling function that extracts
515 arguments for the user's function out of an input QDict, calls the
516 user's function, and if it succeeded, builds an output QObject from
517 its return value.  This is for use by the QMP monitor core.
519 In rare cases, QAPI cannot express a type-safe representation of a
520 corresponding Client JSON Protocol command.  You then have to suppress
521 generation of a marshalling function by including a member 'gen' with
522 boolean value false, and instead write your own function.  For
523 example:
525  { 'command': 'netdev_add',
526    'data': {'type': 'str', 'id': 'str'},
527    'gen': false }
529 Please try to avoid adding new commands that rely on this, and instead
530 use type-safe unions.
532 Normally, the QAPI schema is used to describe synchronous exchanges,
533 where a response is expected.  But in some cases, the action of a
534 command is expected to change state in a way that a successful
535 response is not possible (although the command will still return an
536 error object on failure).  When a successful reply is not possible,
537 the command definition includes the optional member 'success-response'
538 with boolean value false.  So far, only QGA makes use of this member.
540 Member 'allow-oob' declares whether the command supports out-of-band
541 (OOB) execution.  It defaults to false.  For example:
543  { 'command': 'migrate_recover',
544    'data': { 'uri': 'str' }, 'allow-oob': true }
546 See qmp-spec.txt for out-of-band execution syntax and semantics.
548 Commands supporting out-of-band execution can still be executed
549 in-band.
551 When a command is executed in-band, its handler runs in the main
552 thread with the BQL held.
554 When a command is executed out-of-band, its handler runs in a
555 dedicated monitor I/O thread with the BQL *not* held.
557 An OOB-capable command handler must satisfy the following conditions:
559 - It terminates quickly.
560 - It does not invoke system calls that may block.
561 - It does not access guest RAM that may block when userfaultfd is
562   enabled for postcopy live migration.
563 - It takes only "fast" locks, i.e. all critical sections protected by
564   any lock it takes also satisfy the conditions for OOB command
565   handler code.
567 The restrictions on locking limit access to shared state.  Such access
568 requires synchronization, but OOB commands can't take the BQL or any
569 other "slow" lock.
571 When in doubt, do not implement OOB execution support.
573 Member 'allow-preconfig' declares whether the command is available
574 before the machine is built.  It defaults to false.  For example:
576  { 'command': 'qmp_capabilities',
577    'data': { '*enable': [ 'QMPCapability' ] },
578    'allow-preconfig': true }
580 QMP is available before the machine is built only when QEMU was
581 started with --preconfig.
583 The optional 'if' member specifies a conditional.  See "Configuring
584 the schema" below for more on this.
587 === Events ===
589 Syntax:
590     EVENT = { 'event': STRING,
591               (
592               '*data': ( MEMBERS | STRING ),
593               |
594               'data': STRING,
595               'boxed': true,
596               )
597               '*if': COND }
599 Member 'event' names the event.  This is the event name used in the
600 Client JSON Protocol.
602 Member 'data' defines the event-specific data.  It defaults to an
603 empty MEMBERS object.
605 If 'data' is a MEMBERS object, then MEMBERS defines event-specific
606 data just like a struct type's 'data' defines struct type members.
608 If 'data' is a STRING, then STRING names a complex type whose members
609 are the event-specific data.  A union type requires 'boxed': true.
611 An example event is:
613 { 'event': 'EVENT_C',
614   'data': { '*a': 'int', 'b': 'str' } }
616 Resulting in this JSON object:
618 { "event": "EVENT_C",
619   "data": { "b": "test string" },
620   "timestamp": { "seconds": 1267020223, "microseconds": 435656 } }
622 The generator emits a function to send the event.  When member 'boxed'
623 is absent, it takes event-specific data one by one, in QAPI schema
624 order.  Else it takes them wrapped in the C struct generated for the
625 complex type.  See section "Code generated for events" for examples.
627 The optional 'if' member specifies a conditional.  See "Configuring
628 the schema" below for more on this.
631 === Features ===
633 Syntax:
634     FEATURES = [ FEATURE, ... ]
635     FEATURE = STRING
636             | { 'name': STRING, '*if': COND }
638 Sometimes, the behaviour of QEMU changes compatibly, but without a
639 change in the QMP syntax (usually by allowing values or operations
640 that previously resulted in an error).  QMP clients may still need to
641 know whether the extension is available.
643 For this purpose, a list of features can be specified for a struct type.
644 This is exposed to the client as a list of string, where each string
645 signals that this build of QEMU shows a certain behaviour.
647 Each member of the 'features' array defines a feature.  It can either
648 be { 'name': STRING, '*if': COND }, or STRING, which is shorthand for
649 { 'name': STRING }.
651 The optional 'if' member specifies a conditional.  See "Configuring
652 the schema" below for more on this.
654 Example:
656 { 'struct': 'TestType',
657   'data': { 'number': 'int' },
658   'features': [ 'allow-negative-numbers' ] }
661 === Naming rules and reserved names ===
663 All names must begin with a letter, and contain only ASCII letters,
664 digits, hyphen, and underscore.  There are two exceptions: enum values
665 may start with a digit, and names that are downstream extensions (see
666 section Downstream extensions) start with underscore.
668 Names beginning with 'q_' are reserved for the generator, which uses
669 them for munging QMP names that resemble C keywords or other
670 problematic strings.  For example, a member named "default" in qapi
671 becomes "q_default" in the generated C code.
673 Types, commands, and events share a common namespace.  Therefore,
674 generally speaking, type definitions should always use CamelCase for
675 user-defined type names, while built-in types are lowercase.
677 Type names ending with 'Kind' or 'List' are reserved for the
678 generator, which uses them for implicit union enums and array types,
679 respectively.
681 Command names, and member names within a type, should be all lower
682 case with words separated by a hyphen.  However, some existing older
683 commands and complex types use underscore; when extending them,
684 consistency is preferred over blindly avoiding underscore.
686 Event names should be ALL_CAPS with words separated by underscore.
688 Member name 'u' and names starting with 'has-' or 'has_' are reserved
689 for the generator, which uses them for unions and for tracking
690 optional members.
692 Any name (command, event, type, member, or enum value) beginning with
693 "x-" is marked experimental, and may be withdrawn or changed
694 incompatibly in a future release.
696 Pragma 'name-case-whitelist' lets you violate the rules on use of
697 upper and lower case.  Use for new code is strongly discouraged.
700 === Downstream extensions ===
702 QAPI schema names that are externally visible, say in the Client JSON
703 Protocol, need to be managed with care.  Names starting with a
704 downstream prefix of the form __RFQDN_ are reserved for the downstream
705 who controls the valid, reverse fully qualified domain name RFQDN.
706 RFQDN may only contain ASCII letters, digits, hyphen and period.
708 Example: Red Hat, Inc. controls redhat.com, and may therefore add a
709 downstream command __com.redhat_drive-mirror.
712 === Configuring the schema ===
714 Syntax:
715     COND = STRING
716          | [ STRING, ... ]
718 All definitions take an optional 'if' member.  Its value must be a
719 string or a list of strings.  A string is shorthand for a list
720 containing just that string.  The code generated for the definition
721 will then be guarded by #if STRING for each STRING in the COND list.
723 Example: a conditional struct
725  { 'struct': 'IfStruct', 'data': { 'foo': 'int' },
726    'if': ['defined(CONFIG_FOO)', 'defined(HAVE_BAR)'] }
728 gets its generated code guarded like this:
730  #if defined(CONFIG_FOO)
731  #if defined(HAVE_BAR)
732  ... generated code ...
733  #endif /* defined(HAVE_BAR) */
734  #endif /* defined(CONFIG_FOO) */
736 Individual members of complex types, commands arguments, and
737 event-specific data can also be made conditional.  This requires the
738 longhand form of MEMBER.
740 Example: a struct type with unconditional member 'foo' and conditional
741 member 'bar'
743 { 'struct': 'IfStruct', 'data':
744   { 'foo': 'int',
745     'bar': { 'type': 'int', 'if': 'defined(IFCOND)'} } }
747 A union's discriminator may not be conditional.
749 Likewise, individual enumeration values be conditional.  This requires
750 the longhand form of ENUM-VALUE.
752 Example: an enum type with unconditional value 'foo' and conditional
753 value 'bar'
755 { 'enum': 'IfEnum', 'data':
756   [ 'foo',
757     { 'name' : 'bar', 'if': 'defined(IFCOND)' } ] }
759 Likewise, features can be conditional.  This requires the longhand
760 form of FEATURE.
762 Example: a struct with conditional feature 'allow-negative-numbers'
764 { 'struct': 'TestType',
765   'data': { 'number': 'int' },
766   'features': [ { 'name': 'allow-negative-numbers',
767                   'if' 'defined(IFCOND)' } ] }
769 Please note that you are responsible to ensure that the C code will
770 compile with an arbitrary combination of conditions, since the
771 generator is unable to check it at this point.
773 The conditions apply to introspection as well, i.e. introspection
774 shows a conditional entity only when the condition is satisfied in
775 this particular build.
778 === Documentation comments ===
780 A multi-line comment that starts and ends with a '##' line is a
781 documentation comment.
783 If the documentation comment starts like
785     ##
786     # @SYMBOL:
788 it documents the definition if SYMBOL, else it's free-form
789 documentation.
791 See below for more on definition documentation.
793 Free-form documentation may be used to provide additional text and
794 structuring content.
797 ==== Documentation markup ====
799 Comment text starting with '=' is a section title:
801     # = Section title
803 Double the '=' for a subsection title:
805     # == Subsection title
807 '|' denotes examples:
809     # | Text of the example, may span
810     # | multiple lines
812 '*' starts an itemized list:
814     # * First item, may span
815     #   multiple lines
816     # * Second item
818 You can also use '-' instead of '*'.
820 A decimal number followed by '.' starts a numbered list:
822     # 1. First item, may span
823     #    multiple lines
824     # 2. Second item
826 The actual number doesn't matter.  You could even use '*' instead of
827 '2.' for the second item.
829 Lists can't be nested.  Blank lines are currently not supported within
830 lists.
832 Additional whitespace between the initial '#' and the comment text is
833 permitted.
835 *foo* and _foo_ are for strong and emphasis styles respectively (they
836 do not work over multiple lines).  @foo is used to reference a name in
837 the schema.
839 Example:
842 # = Section
843 # == Subsection
845 # Some text foo with *strong* and _emphasis_
846 # 1. with a list
847 # 2. like that
849 # And some code:
850 # | $ echo foo
851 # | -> do this
852 # | <- get that
857 ==== Definition documentation ====
859 Definition documentation, if present, must immediately precede the
860 definition it documents.
862 When documentation is required (see pragma 'doc-required'), every
863 definition must have documentation.
865 Definition documentation starts with a line naming the definition,
866 followed by an optional overview, a description of each argument (for
867 commands and events), member (for structs and unions), branch (for
868 alternates), or value (for enums), and finally optional tagged
869 sections.
871 FIXME: the parser accepts these things in almost any order.
872 FIXME: union branches should be described, too.
874 Extensions added after the definition was first released carry a
875 '(since x.y.z)' comment.
877 A tagged section starts with one of the following words:
878 "Note:"/"Notes:", "Since:", "Example"/"Examples", "Returns:", "TODO:".
879 The section ends with the start of a new section.
881 A 'Since: x.y.z' tagged section lists the release that introduced the
882 definition.
884 For example:
887 # @BlockStats:
889 # Statistics of a virtual block device or a block backing device.
891 # @device: If the stats are for a virtual block device, the name
892 #          corresponding to the virtual block device.
894 # @node-name: The node name of the device. (since 2.3)
896 # ... more members ...
898 # Since: 0.14.0
900 { 'struct': 'BlockStats',
901   'data': {'*device': 'str', '*node-name': 'str',
902            ... more members ... } }
905 # @query-blockstats:
907 # Query the @BlockStats for all virtual block devices.
909 # @query-nodes: If true, the command will query all the
910 #               block nodes ... explain, explain ...  (since 2.3)
912 # Returns: A list of @BlockStats for each virtual block devices.
914 # Since: 0.14.0
916 # Example:
918 # -> { "execute": "query-blockstats" }
919 # <- {
920 #      ... lots of output ...
921 #    }
924 { 'command': 'query-blockstats',
925   'data': { '*query-nodes': 'bool' },
926   'returns': ['BlockStats'] }
929 == Client JSON Protocol introspection ==
931 Clients of a Client JSON Protocol commonly need to figure out what
932 exactly the server (QEMU) supports.
934 For this purpose, QMP provides introspection via command
935 query-qmp-schema.  QGA currently doesn't support introspection.
937 While Client JSON Protocol wire compatibility should be maintained
938 between qemu versions, we cannot make the same guarantees for
939 introspection stability.  For example, one version of qemu may provide
940 a non-variant optional member of a struct, and a later version rework
941 the member to instead be non-optional and associated with a variant.
942 Likewise, one version of qemu may list a member with open-ended type
943 'str', and a later version could convert it to a finite set of strings
944 via an enum type; or a member may be converted from a specific type to
945 an alternate that represents a choice between the original type and
946 something else.
948 query-qmp-schema returns a JSON array of SchemaInfo objects.  These
949 objects together describe the wire ABI, as defined in the QAPI schema.
950 There is no specified order to the SchemaInfo objects returned; a
951 client must search for a particular name throughout the entire array
952 to learn more about that name, but is at least guaranteed that there
953 will be no collisions between type, command, and event names.
955 However, the SchemaInfo can't reflect all the rules and restrictions
956 that apply to QMP.  It's interface introspection (figuring out what's
957 there), not interface specification.  The specification is in the QAPI
958 schema.  To understand how QMP is to be used, you need to study the
959 QAPI schema.
961 Like any other command, query-qmp-schema is itself defined in the QAPI
962 schema, along with the SchemaInfo type.  This text attempts to give an
963 overview how things work.  For details you need to consult the QAPI
964 schema.
966 SchemaInfo objects have common members "name" and "meta-type", and
967 additional variant members depending on the value of meta-type.
969 Each SchemaInfo object describes a wire ABI entity of a certain
970 meta-type: a command, event or one of several kinds of type.
972 SchemaInfo for commands and events have the same name as in the QAPI
973 schema.
975 Command and event names are part of the wire ABI, but type names are
976 not.  Therefore, the SchemaInfo for types have auto-generated
977 meaningless names.  For readability, the examples in this section use
978 meaningful type names instead.
980 To examine a type, start with a command or event using it, then follow
981 references by name.
983 QAPI schema definitions not reachable that way are omitted.
985 The SchemaInfo for a command has meta-type "command", and variant
986 members "arg-type", "ret-type" and "allow-oob".  On the wire, the
987 "arguments" member of a client's "execute" command must conform to the
988 object type named by "arg-type".  The "return" member that the server
989 passes in a success response conforms to the type named by
990 "ret-type".  When "allow-oob" is set, it means the command supports
991 out-of-band execution.
993 If the command takes no arguments, "arg-type" names an object type
994 without members.  Likewise, if the command returns nothing, "ret-type"
995 names an object type without members.
997 Example: the SchemaInfo for command query-qmp-schema
999     { "name": "query-qmp-schema", "meta-type": "command",
1000       "arg-type": "q_empty", "ret-type": "SchemaInfoList" }
1002     Type "q_empty" is an automatic object type without members, and type
1003     "SchemaInfoList" is the array of SchemaInfo type.
1005 The SchemaInfo for an event has meta-type "event", and variant member
1006 "arg-type".  On the wire, a "data" member that the server passes in an
1007 event conforms to the object type named by "arg-type".
1009 If the event carries no additional information, "arg-type" names an
1010 object type without members.  The event may not have a data member on
1011 the wire then.
1013 Each command or event defined with 'data' as MEMBERS object in the
1014 QAPI schema implicitly defines an object type.
1016 Example: the SchemaInfo for EVENT_C from section Events
1018     { "name": "EVENT_C", "meta-type": "event",
1019       "arg-type": "q_obj-EVENT_C-arg" }
1021     Type "q_obj-EVENT_C-arg" is an implicitly defined object type with
1022     the two members from the event's definition.
1024 The SchemaInfo for struct and union types has meta-type "object".
1026 The SchemaInfo for a struct type has variant member "members".
1028 The SchemaInfo for a union type additionally has variant members "tag"
1029 and "variants".
1031 "members" is a JSON array describing the object's common members, if
1032 any.  Each element is a JSON object with members "name" (the member's
1033 name), "type" (the name of its type), and optionally "default".  The
1034 member is optional if "default" is present.  Currently, "default" can
1035 only have value null.  Other values are reserved for future
1036 extensions.  The "members" array is in no particular order; clients
1037 must search the entire object when learning whether a particular
1038 member is supported.
1040 Example: the SchemaInfo for MyType from section Struct types
1042     { "name": "MyType", "meta-type": "object",
1043       "members": [
1044           { "name": "member1", "type": "str" },
1045           { "name": "member2", "type": "int" },
1046           { "name": "member3", "type": "str", "default": null } ] }
1048 "tag" is the name of the common member serving as type tag.
1049 "variants" is a JSON array describing the object's variant members.
1050 Each element is a JSON object with members "case" (the value of type
1051 tag this element applies to) and "type" (the name of an object type
1052 that provides the variant members for this type tag value).  The
1053 "variants" array is in no particular order, and is not guaranteed to
1054 list cases in the same order as the corresponding "tag" enum type.
1056 Example: the SchemaInfo for flat union BlockdevOptions from section
1057 Union types
1059     { "name": "BlockdevOptions", "meta-type": "object",
1060       "members": [
1061           { "name": "driver", "type": "BlockdevDriver" },
1062           { "name": "read-only", "type": "bool", "default": null } ],
1063       "tag": "driver",
1064       "variants": [
1065           { "case": "file", "type": "BlockdevOptionsFile" },
1066           { "case": "qcow2", "type": "BlockdevOptionsQcow2" } ] }
1068 Note that base types are "flattened": its members are included in the
1069 "members" array.
1071 A simple union implicitly defines an enumeration type for its implicit
1072 discriminator (called "type" on the wire, see section Union types).
1074 A simple union implicitly defines an object type for each of its
1075 variants.
1077 Example: the SchemaInfo for simple union BlockdevOptionsSimple from section
1078 Union types
1080     { "name": "BlockdevOptionsSimple", "meta-type": "object",
1081       "members": [
1082           { "name": "type", "type": "BlockdevOptionsSimpleKind" } ],
1083       "tag": "type",
1084       "variants": [
1085           { "case": "file", "type": "q_obj-BlockdevOptionsFile-wrapper" },
1086           { "case": "qcow2", "type": "q_obj-BlockdevOptionsQcow2-wrapper" } ] }
1088     Enumeration type "BlockdevOptionsSimpleKind" and the object types
1089     "q_obj-BlockdevOptionsFile-wrapper", "q_obj-BlockdevOptionsQcow2-wrapper"
1090     are implicitly defined.
1092 The SchemaInfo for an alternate type has meta-type "alternate", and
1093 variant member "members".  "members" is a JSON array.  Each element is
1094 a JSON object with member "type", which names a type.  Values of the
1095 alternate type conform to exactly one of its member types.  There is
1096 no guarantee on the order in which "members" will be listed.
1098 Example: the SchemaInfo for BlockdevRef from section Alternate types
1100     { "name": "BlockdevRef", "meta-type": "alternate",
1101       "members": [
1102           { "type": "BlockdevOptions" },
1103           { "type": "str" } ] }
1105 The SchemaInfo for an array type has meta-type "array", and variant
1106 member "element-type", which names the array's element type.  Array
1107 types are implicitly defined.  For convenience, the array's name may
1108 resemble the element type; however, clients should examine member
1109 "element-type" instead of making assumptions based on parsing member
1110 "name".
1112 Example: the SchemaInfo for ['str']
1114     { "name": "[str]", "meta-type": "array",
1115       "element-type": "str" }
1117 The SchemaInfo for an enumeration type has meta-type "enum" and
1118 variant member "values".  The values are listed in no particular
1119 order; clients must search the entire enum when learning whether a
1120 particular value is supported.
1122 Example: the SchemaInfo for MyEnum from section Enumeration types
1124     { "name": "MyEnum", "meta-type": "enum",
1125       "values": [ "value1", "value2", "value3" ] }
1127 The SchemaInfo for a built-in type has the same name as the type in
1128 the QAPI schema (see section Built-in Types), with one exception
1129 detailed below.  It has variant member "json-type" that shows how
1130 values of this type are encoded on the wire.
1132 Example: the SchemaInfo for str
1134     { "name": "str", "meta-type": "builtin", "json-type": "string" }
1136 The QAPI schema supports a number of integer types that only differ in
1137 how they map to C.  They are identical as far as SchemaInfo is
1138 concerned.  Therefore, they get all mapped to a single type "int" in
1139 SchemaInfo.
1141 As explained above, type names are not part of the wire ABI.  Not even
1142 the names of built-in types.  Clients should examine member
1143 "json-type" instead of hard-coding names of built-in types.
1146 == Compatibility considerations ==
1148 Maintaining backward compatibility at the Client JSON Protocol level
1149 while evolving the schema requires some care.  This section is about
1150 syntactic compatibility, which is necessary, but not sufficient, for
1151 actual compatibility.
1153 Clients send commands with argument data, and receive command
1154 responses with return data and events with event data.
1156 Adding opt-in functionality to the send direction is backwards
1157 compatible: adding commands, optional arguments, enumeration values,
1158 union and alternate branches; turning an argument type into an
1159 alternate of that type; making mandatory arguments optional.  Clients
1160 oblivious of the new functionality continue to work.
1162 Incompatible changes include removing commands, command arguments,
1163 enumeration values, union and alternate branches, adding mandatory
1164 command arguments, and making optional arguments mandatory.
1166 The specified behavior of an absent optional argument should remain
1167 the same.  With proper documentation, this policy still allows some
1168 flexibility; for example, when an optional 'buffer-size' argument is
1169 specified to default to a sensible buffer size, the actual default
1170 value can still be changed.  The specified default behavior is not the
1171 exact size of the buffer, only that the default size is sensible.
1173 Adding functionality to the receive direction is generally backwards
1174 compatible: adding events, adding return and event data members.
1175 Clients are expected to ignore the ones they don't know.
1177 Removing "unreachable" stuff like events that can't be triggered
1178 anymore, optional return or event data members that can't be sent
1179 anymore, and return or event data member (enumeration) values that
1180 can't be sent anymore makes no difference to clients, except for
1181 introspection.  The latter can conceivably confuse clients, so tread
1182 carefully.
1184 Incompatible changes include removing return and event data members.
1186 Any change to a command definition's 'data' or one of the types used
1187 there (recursively) needs to consider send direction compatibility.
1189 Any change to a command definition's 'return', an event definition's
1190 'data', or one of the types used there (recursively) needs to consider
1191 receive direction compatibility.
1193 Any change to types used in both contexts need to consider both.
1195 Enumeration type values and complex and alternate type members may be
1196 reordered freely.  For enumerations and alternate types, this doesn't
1197 affect the wire encoding.  For complex types, this might make the
1198 implementation emit JSON object members in a different order, which
1199 the Client JSON Protocol permits.
1201 Since type names are not visible in the Client JSON Protocol, types
1202 may be freely renamed.  Even certain refactorings are invisible, such
1203 as splitting members from one type into a common base type.
1206 == Code generation ==
1208 The QAPI code generator qapi-gen.py generates code and documentation
1209 from the schema.  Together with the core QAPI libraries, this code
1210 provides everything required to take JSON commands read in by a Client
1211 JSON Protocol server, unmarshal the arguments into the underlying C
1212 types, call into the corresponding C function, map the response back
1213 to a Client JSON Protocol response to be returned to the user, and
1214 introspect the commands.
1216 As an example, we'll use the following schema, which describes a
1217 single complex user-defined type, along with command which takes a
1218 list of that type as a parameter, and returns a single element of that
1219 type.  The user is responsible for writing the implementation of
1220 qmp_my_command(); everything else is produced by the generator.
1222     $ cat example-schema.json
1223     { 'struct': 'UserDefOne',
1224       'data': { 'integer': 'int', '*string': 'str' } }
1226     { 'command': 'my-command',
1227       'data': { 'arg1': ['UserDefOne'] },
1228       'returns': 'UserDefOne' }
1230     { 'event': 'MY_EVENT' }
1232 We run qapi-gen.py like this:
1234     $ python scripts/qapi-gen.py --output-dir="qapi-generated" \
1235     --prefix="example-" example-schema.json
1237 For a more thorough look at generated code, the testsuite includes
1238 tests/qapi-schema/qapi-schema-tests.json that covers more examples of
1239 what the generator will accept, and compiles the resulting C code as
1240 part of 'make check-unit'.
1242 === Code generated for QAPI types ===
1244 The following files are created:
1246 $(prefix)qapi-types.h - C types corresponding to types defined in
1247                         the schema
1249 $(prefix)qapi-types.c - Cleanup functions for the above C types
1251 The $(prefix) is an optional parameter used as a namespace to keep the
1252 generated code from one schema/code-generation separated from others so code
1253 can be generated/used from multiple schemas without clobbering previously
1254 created code.
1256 Example:
1258     $ cat qapi-generated/example-qapi-types.h
1259 [Uninteresting stuff omitted...]
1261     #ifndef EXAMPLE_QAPI_TYPES_H
1262     #define EXAMPLE_QAPI_TYPES_H
1264     #include "qapi/qapi-builtin-types.h"
1266     typedef struct UserDefOne UserDefOne;
1268     typedef struct UserDefOneList UserDefOneList;
1270     typedef struct q_obj_my_command_arg q_obj_my_command_arg;
1272     struct UserDefOne {
1273         int64_t integer;
1274         bool has_string;
1275         char *string;
1276     };
1278     void qapi_free_UserDefOne(UserDefOne *obj);
1280     struct UserDefOneList {
1281         UserDefOneList *next;
1282         UserDefOne *value;
1283     };
1285     void qapi_free_UserDefOneList(UserDefOneList *obj);
1287     struct q_obj_my_command_arg {
1288         UserDefOneList *arg1;
1289     };
1291     #endif /* EXAMPLE_QAPI_TYPES_H */
1292     $ cat qapi-generated/example-qapi-types.c
1293 [Uninteresting stuff omitted...]
1295     void qapi_free_UserDefOne(UserDefOne *obj)
1296     {
1297         Visitor *v;
1299         if (!obj) {
1300             return;
1301         }
1303         v = qapi_dealloc_visitor_new();
1304         visit_type_UserDefOne(v, NULL, &obj, NULL);
1305         visit_free(v);
1306     }
1308     void qapi_free_UserDefOneList(UserDefOneList *obj)
1309     {
1310         Visitor *v;
1312         if (!obj) {
1313             return;
1314         }
1316         v = qapi_dealloc_visitor_new();
1317         visit_type_UserDefOneList(v, NULL, &obj, NULL);
1318         visit_free(v);
1319     }
1321 [Uninteresting stuff omitted...]
1323 For a modular QAPI schema (see section Include directives), code for
1324 each sub-module SUBDIR/SUBMODULE.json is actually generated into
1326 SUBDIR/$(prefix)qapi-types-SUBMODULE.h
1327 SUBDIR/$(prefix)qapi-types-SUBMODULE.c
1329 If qapi-gen.py is run with option --builtins, additional files are
1330 created:
1332 qapi-builtin-types.h - C types corresponding to built-in types
1334 qapi-builtin-types.c - Cleanup functions for the above C types
1336 === Code generated for visiting QAPI types ===
1338 These are the visitor functions used to walk through and convert
1339 between a native QAPI C data structure and some other format (such as
1340 QObject); the generated functions are named visit_type_FOO() and
1341 visit_type_FOO_members().
1343 The following files are generated:
1345 $(prefix)qapi-visit.c: Visitor function for a particular C type, used
1346                        to automagically convert QObjects into the
1347                        corresponding C type and vice-versa, as well
1348                        as for deallocating memory for an existing C
1349                        type
1351 $(prefix)qapi-visit.h: Declarations for previously mentioned visitor
1352                        functions
1354 Example:
1356     $ cat qapi-generated/example-qapi-visit.h
1357 [Uninteresting stuff omitted...]
1359     #ifndef EXAMPLE_QAPI_VISIT_H
1360     #define EXAMPLE_QAPI_VISIT_H
1362     #include "qapi/qapi-builtin-visit.h"
1363     #include "example-qapi-types.h"
1366     void visit_type_UserDefOne_members(Visitor *v, UserDefOne *obj, Error **errp);
1367     void visit_type_UserDefOne(Visitor *v, const char *name, UserDefOne **obj, Error **errp);
1368     void visit_type_UserDefOneList(Visitor *v, const char *name, UserDefOneList **obj, Error **errp);
1370     void visit_type_q_obj_my_command_arg_members(Visitor *v, q_obj_my_command_arg *obj, Error **errp);
1372     #endif /* EXAMPLE_QAPI_VISIT_H */
1373     $ cat qapi-generated/example-qapi-visit.c
1374 [Uninteresting stuff omitted...]
1376     void visit_type_UserDefOne_members(Visitor *v, UserDefOne *obj, Error **errp)
1377     {
1378         Error *err = NULL;
1380         visit_type_int(v, "integer", &obj->integer, &err);
1381         if (err) {
1382             goto out;
1383         }
1384         if (visit_optional(v, "string", &obj->has_string)) {
1385             visit_type_str(v, "string", &obj->string, &err);
1386             if (err) {
1387                 goto out;
1388             }
1389         }
1391     out:
1392         error_propagate(errp, err);
1393     }
1395     void visit_type_UserDefOne(Visitor *v, const char *name, UserDefOne **obj, Error **errp)
1396     {
1397         Error *err = NULL;
1399         visit_start_struct(v, name, (void **)obj, sizeof(UserDefOne), &err);
1400         if (err) {
1401             goto out;
1402         }
1403         if (!*obj) {
1404             goto out_obj;
1405         }
1406         visit_type_UserDefOne_members(v, *obj, &err);
1407         if (err) {
1408             goto out_obj;
1409         }
1410         visit_check_struct(v, &err);
1411     out_obj:
1412         visit_end_struct(v, (void **)obj);
1413         if (err && visit_is_input(v)) {
1414             qapi_free_UserDefOne(*obj);
1415             *obj = NULL;
1416         }
1417     out:
1418         error_propagate(errp, err);
1419     }
1421     void visit_type_UserDefOneList(Visitor *v, const char *name, UserDefOneList **obj, Error **errp)
1422     {
1423         Error *err = NULL;
1424         UserDefOneList *tail;
1425         size_t size = sizeof(**obj);
1427         visit_start_list(v, name, (GenericList **)obj, size, &err);
1428         if (err) {
1429             goto out;
1430         }
1432         for (tail = *obj; tail;
1433              tail = (UserDefOneList *)visit_next_list(v, (GenericList *)tail, size)) {
1434             visit_type_UserDefOne(v, NULL, &tail->value, &err);
1435             if (err) {
1436                 break;
1437             }
1438         }
1440         if (!err) {
1441             visit_check_list(v, &err);
1442         }
1443         visit_end_list(v, (void **)obj);
1444         if (err && visit_is_input(v)) {
1445             qapi_free_UserDefOneList(*obj);
1446             *obj = NULL;
1447         }
1448     out:
1449         error_propagate(errp, err);
1450     }
1452     void visit_type_q_obj_my_command_arg_members(Visitor *v, q_obj_my_command_arg *obj, Error **errp)
1453     {
1454         Error *err = NULL;
1456         visit_type_UserDefOneList(v, "arg1", &obj->arg1, &err);
1457         if (err) {
1458             goto out;
1459         }
1461     out:
1462         error_propagate(errp, err);
1463     }
1465 [Uninteresting stuff omitted...]
1467 For a modular QAPI schema (see section Include directives), code for
1468 each sub-module SUBDIR/SUBMODULE.json is actually generated into
1470 SUBDIR/$(prefix)qapi-visit-SUBMODULE.h
1471 SUBDIR/$(prefix)qapi-visit-SUBMODULE.c
1473 If qapi-gen.py is run with option --builtins, additional files are
1474 created:
1476 qapi-builtin-visit.h - Visitor functions for built-in types
1478 qapi-builtin-visit.c - Declarations for these visitor functions
1480 === Code generated for commands ===
1482 These are the marshaling/dispatch functions for the commands defined
1483 in the schema.  The generated code provides qmp_marshal_COMMAND(), and
1484 declares qmp_COMMAND() that the user must implement.
1486 The following files are generated:
1488 $(prefix)qapi-commands.c: Command marshal/dispatch functions for each
1489                           QMP command defined in the schema
1491 $(prefix)qapi-commands.h: Function prototypes for the QMP commands
1492                           specified in the schema
1494 Example:
1496     $ cat qapi-generated/example-qapi-commands.h
1497 [Uninteresting stuff omitted...]
1499     #ifndef EXAMPLE_QAPI_COMMANDS_H
1500     #define EXAMPLE_QAPI_COMMANDS_H
1502     #include "example-qapi-types.h"
1503     #include "qapi/qmp/dispatch.h"
1505     UserDefOne *qmp_my_command(UserDefOneList *arg1, Error **errp);
1506     void qmp_marshal_my_command(QDict *args, QObject **ret, Error **errp);
1507     void example_qmp_init_marshal(QmpCommandList *cmds);
1509     #endif /* EXAMPLE_QAPI_COMMANDS_H */
1510     $ cat qapi-generated/example-qapi-commands.c
1511 [Uninteresting stuff omitted...]
1513     static void qmp_marshal_output_UserDefOne(UserDefOne *ret_in, QObject **ret_out, Error **errp)
1514     {
1515         Error *err = NULL;
1516         Visitor *v;
1518         v = qobject_output_visitor_new(ret_out);
1519         visit_type_UserDefOne(v, "unused", &ret_in, &err);
1520         if (!err) {
1521             visit_complete(v, ret_out);
1522         }
1523         error_propagate(errp, err);
1524         visit_free(v);
1525         v = qapi_dealloc_visitor_new();
1526         visit_type_UserDefOne(v, "unused", &ret_in, NULL);
1527         visit_free(v);
1528     }
1530     void qmp_marshal_my_command(QDict *args, QObject **ret, Error **errp)
1531     {
1532         Error *err = NULL;
1533         UserDefOne *retval;
1534         Visitor *v;
1535         q_obj_my_command_arg arg = {0};
1537         v = qobject_input_visitor_new(QOBJECT(args));
1538         visit_start_struct(v, NULL, NULL, 0, &err);
1539         if (err) {
1540             goto out;
1541         }
1542         visit_type_q_obj_my_command_arg_members(v, &arg, &err);
1543         if (!err) {
1544             visit_check_struct(v, &err);
1545         }
1546         visit_end_struct(v, NULL);
1547         if (err) {
1548             goto out;
1549         }
1551         retval = qmp_my_command(arg.arg1, &err);
1552         if (err) {
1553             goto out;
1554         }
1556         qmp_marshal_output_UserDefOne(retval, ret, &err);
1558     out:
1559         error_propagate(errp, err);
1560         visit_free(v);
1561         v = qapi_dealloc_visitor_new();
1562         visit_start_struct(v, NULL, NULL, 0, NULL);
1563         visit_type_q_obj_my_command_arg_members(v, &arg, NULL);
1564         visit_end_struct(v, NULL);
1565         visit_free(v);
1566     }
1568     void example_qmp_init_marshal(QmpCommandList *cmds)
1569     {
1570         QTAILQ_INIT(cmds);
1572         qmp_register_command(cmds, "my-command",
1573                              qmp_marshal_my_command, QCO_NO_OPTIONS);
1574     }
1576 [Uninteresting stuff omitted...]
1578 For a modular QAPI schema (see section Include directives), code for
1579 each sub-module SUBDIR/SUBMODULE.json is actually generated into
1581 SUBDIR/$(prefix)qapi-commands-SUBMODULE.h
1582 SUBDIR/$(prefix)qapi-commands-SUBMODULE.c
1584 === Code generated for events ===
1586 This is the code related to events defined in the schema, providing
1587 qapi_event_send_EVENT().
1589 The following files are created:
1591 $(prefix)qapi-events.h - Function prototypes for each event type
1593 $(prefix)qapi-events.c - Implementation of functions to send an event
1595 $(prefix)qapi-emit-events.h - Enumeration of all event names, and
1596                               common event code declarations
1598 $(prefix)qapi-emit-events.c - Common event code definitions
1600 Example:
1602     $ cat qapi-generated/example-qapi-events.h
1603 [Uninteresting stuff omitted...]
1605     #ifndef EXAMPLE_QAPI_EVENTS_H
1606     #define EXAMPLE_QAPI_EVENTS_H
1608     #include "qapi/util.h"
1609     #include "example-qapi-types.h"
1611     void qapi_event_send_my_event(void);
1613     #endif /* EXAMPLE_QAPI_EVENTS_H */
1614     $ cat qapi-generated/example-qapi-events.c
1615 [Uninteresting stuff omitted...]
1617     void qapi_event_send_my_event(void)
1618     {
1619         QDict *qmp;
1621         qmp = qmp_event_build_dict("MY_EVENT");
1623         example_qapi_event_emit(EXAMPLE_QAPI_EVENT_MY_EVENT, qmp);
1625         qobject_unref(qmp);
1626     }
1628 [Uninteresting stuff omitted...]
1629     $ cat qapi-generated/example-qapi-emit-events.h
1630 [Uninteresting stuff omitted...]
1632     #ifndef EXAMPLE_QAPI_EMIT_EVENTS_H
1633     #define EXAMPLE_QAPI_EMIT_EVENTS_H
1635     #include "qapi/util.h"
1637     typedef enum example_QAPIEvent {
1638         EXAMPLE_QAPI_EVENT_MY_EVENT,
1639         EXAMPLE_QAPI_EVENT__MAX,
1640     } example_QAPIEvent;
1642     #define example_QAPIEvent_str(val) \
1643         qapi_enum_lookup(&example_QAPIEvent_lookup, (val))
1645     extern const QEnumLookup example_QAPIEvent_lookup;
1647     void example_qapi_event_emit(example_QAPIEvent event, QDict *qdict);
1649     #endif /* EXAMPLE_QAPI_EMIT_EVENTS_H */
1650     $ cat qapi-generated/example-qapi-emit-events.c
1651 [Uninteresting stuff omitted...]
1653     const QEnumLookup example_QAPIEvent_lookup = {
1654         .array = (const char *const[]) {
1655             [EXAMPLE_QAPI_EVENT_MY_EVENT] = "MY_EVENT",
1656         },
1657         .size = EXAMPLE_QAPI_EVENT__MAX
1658     };
1660 [Uninteresting stuff omitted...]
1662 For a modular QAPI schema (see section Include directives), code for
1663 each sub-module SUBDIR/SUBMODULE.json is actually generated into
1665 SUBDIR/$(prefix)qapi-events-SUBMODULE.h
1666 SUBDIR/$(prefix)qapi-events-SUBMODULE.c
1668 === Code generated for introspection ===
1670 The following files are created:
1672 $(prefix)qapi-introspect.c - Defines a string holding a JSON
1673                             description of the schema
1675 $(prefix)qapi-introspect.h - Declares the above string
1677 Example:
1679     $ cat qapi-generated/example-qapi-introspect.h
1680 [Uninteresting stuff omitted...]
1682     #ifndef EXAMPLE_QAPI_INTROSPECT_H
1683     #define EXAMPLE_QAPI_INTROSPECT_H
1685     #include "qapi/qmp/qlit.h"
1687     extern const QLitObject example_qmp_schema_qlit;
1689     #endif /* EXAMPLE_QAPI_INTROSPECT_H */
1690     $ cat qapi-generated/example-qapi-introspect.c
1691 [Uninteresting stuff omitted...]
1693     const QLitObject example_qmp_schema_qlit = QLIT_QLIST(((QLitObject[]) {
1694         QLIT_QDICT(((QLitDictEntry[]) {
1695             { "arg-type", QLIT_QSTR("0"), },
1696             { "meta-type", QLIT_QSTR("command"), },
1697             { "name", QLIT_QSTR("my-command"), },
1698             { "ret-type", QLIT_QSTR("1"), },
1699             {}
1700         })),
1701         QLIT_QDICT(((QLitDictEntry[]) {
1702             { "arg-type", QLIT_QSTR("2"), },
1703             { "meta-type", QLIT_QSTR("event"), },
1704             { "name", QLIT_QSTR("MY_EVENT"), },
1705             {}
1706         })),
1707         /* "0" = q_obj_my-command-arg */
1708         QLIT_QDICT(((QLitDictEntry[]) {
1709             { "members", QLIT_QLIST(((QLitObject[]) {
1710                 QLIT_QDICT(((QLitDictEntry[]) {
1711                     { "name", QLIT_QSTR("arg1"), },
1712                     { "type", QLIT_QSTR("[1]"), },
1713                     {}
1714                 })),
1715                 {}
1716             })), },
1717             { "meta-type", QLIT_QSTR("object"), },
1718             { "name", QLIT_QSTR("0"), },
1719             {}
1720         })),
1721         /* "1" = UserDefOne */
1722         QLIT_QDICT(((QLitDictEntry[]) {
1723             { "members", QLIT_QLIST(((QLitObject[]) {
1724                 QLIT_QDICT(((QLitDictEntry[]) {
1725                     { "name", QLIT_QSTR("integer"), },
1726                     { "type", QLIT_QSTR("int"), },
1727                     {}
1728                 })),
1729                 QLIT_QDICT(((QLitDictEntry[]) {
1730                     { "default", QLIT_QNULL, },
1731                     { "name", QLIT_QSTR("string"), },
1732                     { "type", QLIT_QSTR("str"), },
1733                     {}
1734                 })),
1735                 {}
1736             })), },
1737             { "meta-type", QLIT_QSTR("object"), },
1738             { "name", QLIT_QSTR("1"), },
1739             {}
1740         })),
1741         /* "2" = q_empty */
1742         QLIT_QDICT(((QLitDictEntry[]) {
1743             { "members", QLIT_QLIST(((QLitObject[]) {
1744                 {}
1745             })), },
1746             { "meta-type", QLIT_QSTR("object"), },
1747             { "name", QLIT_QSTR("2"), },
1748             {}
1749         })),
1750         QLIT_QDICT(((QLitDictEntry[]) {
1751             { "element-type", QLIT_QSTR("1"), },
1752             { "meta-type", QLIT_QSTR("array"), },
1753             { "name", QLIT_QSTR("[1]"), },
1754             {}
1755         })),
1756         QLIT_QDICT(((QLitDictEntry[]) {
1757             { "json-type", QLIT_QSTR("int"), },
1758             { "meta-type", QLIT_QSTR("builtin"), },
1759             { "name", QLIT_QSTR("int"), },
1760             {}
1761         })),
1762         QLIT_QDICT(((QLitDictEntry[]) {
1763             { "json-type", QLIT_QSTR("string"), },
1764             { "meta-type", QLIT_QSTR("builtin"), },
1765             { "name", QLIT_QSTR("str"), },
1766             {}
1767         })),
1768         {}
1769     }));
1771 [Uninteresting stuff omitted...]