tests/qapi-schema: Improve union discriminator coverage
[qemu/kevin.git] / docs / devel / qapi-code-gen.rst
blob23e7f2fb1c372fd91c3a4e70a130b535c3486b45
1 ==================================
2 How to use the QAPI code generator
3 ==================================
5 ..
6    Copyright IBM Corp. 2011
7    Copyright (C) 2012-2016 Red Hat, Inc.
9    This work is licensed under the terms of the GNU GPL, version 2 or
10    later.  See the COPYING file in the top-level directory.
13 Introduction
14 ============
16 QAPI is a native C API within QEMU which provides management-level
17 functionality to internal and external users.  For external
18 users/processes, this interface is made available by a JSON-based wire
19 format for the QEMU Monitor Protocol (QMP) for controlling qemu, as
20 well as the QEMU Guest Agent (QGA) for communicating with the guest.
21 The remainder of this document uses "Client JSON Protocol" when
22 referring to the wire contents of a QMP or QGA connection.
24 To map between Client JSON Protocol interfaces and the native C API,
25 we generate C code from a QAPI schema.  This document describes the
26 QAPI schema language, and how it gets mapped to the Client JSON
27 Protocol and to C.  It additionally provides guidance on maintaining
28 Client JSON Protocol compatibility.
31 The QAPI schema language
32 ========================
34 The QAPI schema defines the Client JSON Protocol's commands and
35 events, as well as types used by them.  Forward references are
36 allowed.
38 It is permissible for the schema to contain additional types not used
39 by any commands or events, for the side effect of generated C code
40 used internally.
42 There are several kinds of types: simple types (a number of built-in
43 types, such as ``int`` and ``str``; as well as enumerations), arrays,
44 complex types (structs and unions), and alternate types (a choice
45 between other types).
48 Schema syntax
49 -------------
51 Syntax is loosely based on `JSON <http://www.ietf.org/rfc/rfc8259.txt>`_.
52 Differences:
54 * Comments: start with a hash character (``#``) that is not part of a
55   string, and extend to the end of the line.
57 * Strings are enclosed in ``'single quotes'``, not ``"double quotes"``.
59 * Strings are restricted to printable ASCII, and escape sequences to
60   just ``\\``.
62 * Numbers and ``null`` are not supported.
64 A second layer of syntax defines the sequences of JSON texts that are
65 a correctly structured QAPI schema.  We provide a grammar for this
66 syntax in an EBNF-like notation:
68 * Production rules look like ``non-terminal = expression``
69 * Concatenation: expression ``A B`` matches expression ``A``, then ``B``
70 * Alternation: expression ``A | B`` matches expression ``A`` or ``B``
71 * Repetition: expression ``A...`` matches zero or more occurrences of
72   expression ``A``
73 * Repetition: expression ``A, ...`` matches zero or more occurrences of
74   expression ``A`` separated by ``,``
75 * Grouping: expression ``( A )`` matches expression ``A``
76 * JSON's structural characters are terminals: ``{ } [ ] : ,``
77 * JSON's literal names are terminals: ``false true``
78 * String literals enclosed in ``'single quotes'`` are terminal, and match
79   this JSON string, with a leading ``*`` stripped off
80 * When JSON object member's name starts with ``*``, the member is
81   optional.
82 * The symbol ``STRING`` is a terminal, and matches any JSON string
83 * The symbol ``BOOL`` is a terminal, and matches JSON ``false`` or ``true``
84 * ALL-CAPS words other than ``STRING`` are non-terminals
86 The order of members within JSON objects does not matter unless
87 explicitly noted.
89 A QAPI schema consists of a series of top-level expressions::
91     SCHEMA = TOP-LEVEL-EXPR...
93 The top-level expressions are all JSON objects.  Code and
94 documentation is generated in schema definition order.  Code order
95 should not matter.
97 A top-level expressions is either a directive or a definition::
99     TOP-LEVEL-EXPR = DIRECTIVE | DEFINITION
101 There are two kinds of directives and six kinds of definitions::
103     DIRECTIVE = INCLUDE | PRAGMA
104     DEFINITION = ENUM | STRUCT | UNION | ALTERNATE | COMMAND | EVENT
106 These are discussed in detail below.
109 Built-in Types
110 --------------
112 The following types are predefined, and map to C as follows:
114   ============= ============== ============================================
115   Schema        C              JSON
116   ============= ============== ============================================
117   ``str``       ``char *``     any JSON string, UTF-8
118   ``number``    ``double``     any JSON number
119   ``int``       ``int64_t``    a JSON number without fractional part
120                                that fits into the C integer type
121   ``int8``      ``int8_t``     likewise
122   ``int16``     ``int16_t``    likewise
123   ``int32``     ``int32_t``    likewise
124   ``int64``     ``int64_t``    likewise
125   ``uint8``     ``uint8_t``    likewise
126   ``uint16``    ``uint16_t``   likewise
127   ``uint32``    ``uint32_t``   likewise
128   ``uint64``    ``uint64_t``   likewise
129   ``size``      ``uint64_t``   like ``uint64_t``, except
130                                ``StringInputVisitor`` accepts size suffixes
131   ``bool``      ``bool``       JSON ``true`` or ``false``
132   ``null``      ``QNull *``    JSON ``null``
133   ``any``       ``QObject *``  any JSON value
134   ``QType``     ``QType``      JSON string matching enum ``QType`` values
135   ============= ============== ============================================
138 Include directives
139 ------------------
141 Syntax::
143     INCLUDE = { 'include': STRING }
145 The QAPI schema definitions can be modularized using the 'include' directive::
147  { 'include': 'path/to/file.json' }
149 The directive is evaluated recursively, and include paths are relative
150 to the file using the directive.  Multiple includes of the same file
151 are idempotent.
153 As a matter of style, it is a good idea to have all files be
154 self-contained, but at the moment, nothing prevents an included file
155 from making a forward reference to a type that is only introduced by
156 an outer file.  The parser may be made stricter in the future to
157 prevent incomplete include files.
159 .. _pragma:
161 Pragma directives
162 -----------------
164 Syntax::
166     PRAGMA = { 'pragma': {
167                    '*doc-required': BOOL,
168                    '*command-name-exceptions': [ STRING, ... ],
169                    '*command-returns-exceptions': [ STRING, ... ],
170                    '*member-name-exceptions': [ STRING, ... ] } }
172 The pragma directive lets you control optional generator behavior.
174 Pragma's scope is currently the complete schema.  Setting the same
175 pragma to different values in parts of the schema doesn't work.
177 Pragma 'doc-required' takes a boolean value.  If true, documentation
178 is required.  Default is false.
180 Pragma 'command-name-exceptions' takes a list of commands whose names
181 may contain ``"_"`` instead of ``"-"``.  Default is none.
183 Pragma 'command-returns-exceptions' takes a list of commands that may
184 violate the rules on permitted return types.  Default is none.
186 Pragma 'member-name-exceptions' takes a list of types whose member
187 names may contain uppercase letters, and ``"_"`` instead of ``"-"``.
188 Default is none.
190 .. _ENUM-VALUE:
192 Enumeration types
193 -----------------
195 Syntax::
197     ENUM = { 'enum': STRING,
198              'data': [ ENUM-VALUE, ... ],
199              '*prefix': STRING,
200              '*if': COND,
201              '*features': FEATURES }
202     ENUM-VALUE = STRING
203                | { 'name': STRING,
204                    '*if': COND,
205                    '*features': FEATURES }
207 Member 'enum' names the enum type.
209 Each member of the 'data' array defines a value of the enumeration
210 type.  The form STRING is shorthand for :code:`{ 'name': STRING }`.  The
211 'name' values must be be distinct.
213 Example::
215  { 'enum': 'MyEnum', 'data': [ 'value1', 'value2', 'value3' ] }
217 Nothing prevents an empty enumeration, although it is probably not
218 useful.
220 On the wire, an enumeration type's value is represented by its
221 (string) name.  In C, it's represented by an enumeration constant.
222 These are of the form PREFIX_NAME, where PREFIX is derived from the
223 enumeration type's name, and NAME from the value's name.  For the
224 example above, the generator maps 'MyEnum' to MY_ENUM and 'value1' to
225 VALUE1, resulting in the enumeration constant MY_ENUM_VALUE1.  The
226 optional 'prefix' member overrides PREFIX.
228 The generated C enumeration constants have values 0, 1, ..., N-1 (in
229 QAPI schema order), where N is the number of values.  There is an
230 additional enumeration constant PREFIX__MAX with value N.
232 Do not use string or an integer type when an enumeration type can do
233 the job satisfactorily.
235 The optional 'if' member specifies a conditional.  See `Configuring the
236 schema`_ below for more on this.
238 The optional 'features' member specifies features.  See Features_
239 below for more on this.
242 .. _TYPE-REF:
244 Type references and array types
245 -------------------------------
247 Syntax::
249     TYPE-REF = STRING | ARRAY-TYPE
250     ARRAY-TYPE = [ STRING ]
252 A string denotes the type named by the string.
254 A one-element array containing a string denotes an array of the type
255 named by the string.  Example: ``['int']`` denotes an array of ``int``.
258 Struct types
259 ------------
261 Syntax::
263     STRUCT = { 'struct': STRING,
264                'data': MEMBERS,
265                '*base': STRING,
266                '*if': COND,
267                '*features': FEATURES }
268     MEMBERS = { MEMBER, ... }
269     MEMBER = STRING : TYPE-REF
270            | STRING : { 'type': TYPE-REF,
271                         '*if': COND,
272                         '*features': FEATURES }
274 Member 'struct' names the struct type.
276 Each MEMBER of the 'data' object defines a member of the struct type.
278 .. _MEMBERS:
280 The MEMBER's STRING name consists of an optional ``*`` prefix and the
281 struct member name.  If ``*`` is present, the member is optional.
283 The MEMBER's value defines its properties, in particular its type.
284 The form TYPE-REF_ is shorthand for :code:`{ 'type': TYPE-REF }`.
286 Example::
288  { 'struct': 'MyType',
289    'data': { 'member1': 'str', 'member2': ['int'], '*member3': 'str' } }
291 A struct type corresponds to a struct in C, and an object in JSON.
292 The C struct's members are generated in QAPI schema order.
294 The optional 'base' member names a struct type whose members are to be
295 included in this type.  They go first in the C struct.
297 Example::
299  { 'struct': 'BlockdevOptionsGenericFormat',
300    'data': { 'file': 'str' } }
301  { 'struct': 'BlockdevOptionsGenericCOWFormat',
302    'base': 'BlockdevOptionsGenericFormat',
303    'data': { '*backing': 'str' } }
305 An example BlockdevOptionsGenericCOWFormat object on the wire could use
306 both members like this::
308  { "file": "/some/place/my-image",
309    "backing": "/some/place/my-backing-file" }
311 The optional 'if' member specifies a conditional.  See `Configuring
312 the schema`_ below for more on this.
314 The optional 'features' member specifies features.  See Features_
315 below for more on this.
318 Union types
319 -----------
321 Syntax::
323     UNION = { 'union': STRING,
324               'base': ( MEMBERS | STRING ),
325               'discriminator': STRING,
326               'data': BRANCHES,
327               '*if': COND,
328               '*features': FEATURES }
329     BRANCHES = { BRANCH, ... }
330     BRANCH = STRING : TYPE-REF
331            | STRING : { 'type': TYPE-REF, '*if': COND }
333 Member 'union' names the union type.
335 The 'base' member defines the common members.  If it is a MEMBERS_
336 object, it defines common members just like a struct type's 'data'
337 member defines struct type members.  If it is a STRING, it names a
338 struct type whose members are the common members.
340 Member 'discriminator' must name a non-optional enum-typed member of
341 the base struct.  That member's value selects a branch by its name.
342 If no such branch exists, an empty branch is assumed.
344 Each BRANCH of the 'data' object defines a branch of the union.  A
345 union must have at least one branch.
347 The BRANCH's STRING name is the branch name.  It must be a value of
348 the discriminator enum type.
350 The BRANCH's value defines the branch's properties, in particular its
351 type.  The type must a struct type.  The form TYPE-REF_ is shorthand
352 for :code:`{ 'type': TYPE-REF }`.
354 In the Client JSON Protocol, a union is represented by an object with
355 the common members (from the base type) and the selected branch's
356 members.  The two sets of member names must be disjoint.
358 Example::
360  { 'enum': 'BlockdevDriver', 'data': [ 'file', 'qcow2' ] }
361  { 'union': 'BlockdevOptions',
362    'base': { 'driver': 'BlockdevDriver', '*read-only': 'bool' },
363    'discriminator': 'driver',
364    'data': { 'file': 'BlockdevOptionsFile',
365              'qcow2': 'BlockdevOptionsQcow2' } }
367 Resulting in these JSON objects::
369  { "driver": "file", "read-only": true,
370    "filename": "/some/place/my-image" }
371  { "driver": "qcow2", "read-only": false,
372    "backing": "/some/place/my-image", "lazy-refcounts": true }
374 The order of branches need not match the order of the enum values.
375 The branches need not cover all possible enum values.  In the
376 resulting generated C data types, a union is represented as a struct
377 with the base members in QAPI schema order, and then a union of
378 structures for each branch of the struct.
380 The optional 'if' member specifies a conditional.  See `Configuring
381 the schema`_ below for more on this.
383 The optional 'features' member specifies features.  See Features_
384 below for more on this.
387 Alternate types
388 ---------------
390 Syntax::
392     ALTERNATE = { 'alternate': STRING,
393                   'data': ALTERNATIVES,
394                   '*if': COND,
395                   '*features': FEATURES }
396     ALTERNATIVES = { ALTERNATIVE, ... }
397     ALTERNATIVE = STRING : STRING
398                 | STRING : { 'type': STRING, '*if': COND }
400 Member 'alternate' names the alternate type.
402 Each ALTERNATIVE of the 'data' object defines a branch of the
403 alternate.  An alternate must have at least one branch.
405 The ALTERNATIVE's STRING name is the branch name.
407 The ALTERNATIVE's value defines the branch's properties, in particular
408 its type.  The form STRING is shorthand for :code:`{ 'type': STRING }`.
410 Example::
412  { 'alternate': 'BlockdevRef',
413    'data': { 'definition': 'BlockdevOptions',
414              'reference': 'str' } }
416 An alternate type is like a union type, except there is no
417 discriminator on the wire.  Instead, the branch to use is inferred
418 from the value.  An alternate can only express a choice between types
419 represented differently on the wire.
421 If a branch is typed as the 'bool' built-in, the alternate accepts
422 true and false; if it is typed as any of the various numeric
423 built-ins, it accepts a JSON number; if it is typed as a 'str'
424 built-in or named enum type, it accepts a JSON string; if it is typed
425 as the 'null' built-in, it accepts JSON null; and if it is typed as a
426 complex type (struct or union), it accepts a JSON object.
428 The example alternate declaration above allows using both of the
429 following example objects::
431  { "file": "my_existing_block_device_id" }
432  { "file": { "driver": "file",
433              "read-only": false,
434              "filename": "/tmp/mydisk.qcow2" } }
436 The optional 'if' member specifies a conditional.  See `Configuring
437 the schema`_ below for more on this.
439 The optional 'features' member specifies features.  See Features_
440 below for more on this.
443 Commands
444 --------
446 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                 '*coroutine': true,
461                 '*if': COND,
462                 '*features': FEATURES }
464 Member 'command' names the command.
466 Member 'data' defines the arguments.  It defaults to an empty MEMBERS_
467 object.
469 If 'data' is a MEMBERS_ object, then MEMBERS defines arguments just
470 like a struct type's 'data' defines struct type members.
472 If 'data' is a STRING, then STRING names a complex type whose members
473 are the arguments.  A union type requires ``'boxed': true``.
475 Member 'returns' defines the command's return type.  It defaults to an
476 empty struct type.  It must normally be a complex type or an array of
477 a complex type.  To return anything else, the command must be listed
478 in pragma 'commands-returns-exceptions'.  If you do this, extending
479 the command to return additional information will be harder.  Use of
480 the pragma for new commands is strongly discouraged.
482 A command's error responses are not specified in the QAPI schema.
483 Error conditions should be documented in comments.
485 In the Client JSON Protocol, the value of the "execute" or "exec-oob"
486 member is the command name.  The value of the "arguments" member then
487 has to conform to the arguments, and the value of the success
488 response's "return" member will conform to the return type.
490 Some example commands::
492  { 'command': 'my-first-command',
493    'data': { 'arg1': 'str', '*arg2': 'str' } }
494  { 'struct': 'MyType', 'data': { '*value': 'str' } }
495  { 'command': 'my-second-command',
496    'returns': [ 'MyType' ] }
498 which would validate this Client JSON Protocol transaction::
500  => { "execute": "my-first-command",
501       "arguments": { "arg1": "hello" } }
502  <= { "return": { } }
503  => { "execute": "my-second-command" }
504  <= { "return": [ { "value": "one" }, { } ] }
506 The generator emits a prototype for the C function implementing the
507 command.  The function itself needs to be written by hand.  See
508 section `Code generated for commands`_ for examples.
510 The function returns the return type.  When member 'boxed' is absent,
511 it takes the command arguments as arguments one by one, in QAPI schema
512 order.  Else it takes them wrapped in the C struct generated for the
513 complex argument type.  It takes an additional ``Error **`` argument in
514 either case.
516 The generator also emits a marshalling function that extracts
517 arguments for the user's function out of an input QDict, calls the
518 user's function, and if it succeeded, builds an output QObject from
519 its return value.  This is for use by the QMP monitor core.
521 In rare cases, QAPI cannot express a type-safe representation of a
522 corresponding Client JSON Protocol command.  You then have to suppress
523 generation of a marshalling function by including a member 'gen' with
524 boolean value false, and instead write your own function.  For
525 example::
527  { 'command': 'netdev_add',
528    'data': {'type': 'str', 'id': 'str'},
529    'gen': false }
531 Please try to avoid adding new commands that rely on this, and instead
532 use type-safe unions.
534 Normally, the QAPI schema is used to describe synchronous exchanges,
535 where a response is expected.  But in some cases, the action of a
536 command is expected to change state in a way that a successful
537 response is not possible (although the command will still return an
538 error object on failure).  When a successful reply is not possible,
539 the command definition includes the optional member 'success-response'
540 with boolean value false.  So far, only QGA makes use of this member.
542 Member 'allow-oob' declares whether the command supports out-of-band
543 (OOB) execution.  It defaults to false.  For example::
545  { 'command': 'migrate_recover',
546    'data': { 'uri': 'str' }, 'allow-oob': true }
548 See qmp-spec.txt for out-of-band execution syntax and semantics.
550 Commands supporting out-of-band execution can still be executed
551 in-band.
553 When a command is executed in-band, its handler runs in the main
554 thread with the BQL held.
556 When a command is executed out-of-band, its handler runs in a
557 dedicated monitor I/O thread with the BQL *not* held.
559 An OOB-capable command handler must satisfy the following conditions:
561 - It terminates quickly.
562 - It does not invoke system calls that may block.
563 - It does not access guest RAM that may block when userfaultfd is
564   enabled for postcopy live migration.
565 - It takes only "fast" locks, i.e. all critical sections protected by
566   any lock it takes also satisfy the conditions for OOB command
567   handler code.
569 The restrictions on locking limit access to shared state.  Such access
570 requires synchronization, but OOB commands can't take the BQL or any
571 other "slow" lock.
573 When in doubt, do not implement OOB execution support.
575 Member 'allow-preconfig' declares whether the command is available
576 before the machine is built.  It defaults to false.  For example::
578  { 'enum': 'QMPCapability',
579    'data': [ 'oob' ] }
580  { 'command': 'qmp_capabilities',
581    'data': { '*enable': [ 'QMPCapability' ] },
582    'allow-preconfig': true }
584 QMP is available before the machine is built only when QEMU was
585 started with --preconfig.
587 Member 'coroutine' tells the QMP dispatcher whether the command handler
588 is safe to be run in a coroutine.  It defaults to false.  If it is true,
589 the command handler is called from coroutine context and may yield while
590 waiting for an external event (such as I/O completion) in order to avoid
591 blocking the guest and other background operations.
593 Coroutine safety can be hard to prove, similar to thread safety.  Common
594 pitfalls are:
596 - The global mutex isn't held across ``qemu_coroutine_yield()``, so
597   operations that used to assume that they execute atomically may have
598   to be more careful to protect against changes in the global state.
600 - Nested event loops (``AIO_WAIT_WHILE()`` etc.) are problematic in
601   coroutine context and can easily lead to deadlocks.  They should be
602   replaced by yielding and reentering the coroutine when the condition
603   becomes false.
605 Since the command handler may assume coroutine context, any callers
606 other than the QMP dispatcher must also call it in coroutine context.
607 In particular, HMP commands calling such a QMP command handler must be
608 marked ``.coroutine = true`` in hmp-commands.hx.
610 It is an error to specify both ``'coroutine': true`` and ``'allow-oob': true``
611 for a command.  We don't currently have a use case for both together and
612 without a use case, it's not entirely clear what the semantics should
615 The optional 'if' member specifies a conditional.  See `Configuring
616 the schema`_ below for more on this.
618 The optional 'features' member specifies features.  See Features_
619 below for more on this.
622 Events
623 ------
625 Syntax::
627     EVENT = { 'event': STRING,
628               (
629               '*data': ( MEMBERS | STRING ),
630               |
631               'data': STRING,
632               'boxed': true,
633               )
634               '*if': COND,
635               '*features': FEATURES }
637 Member 'event' names the event.  This is the event name used in the
638 Client JSON Protocol.
640 Member 'data' defines the event-specific data.  It defaults to an
641 empty MEMBERS object.
643 If 'data' is a MEMBERS object, then MEMBERS defines event-specific
644 data just like a struct type's 'data' defines struct type members.
646 If 'data' is a STRING, then STRING names a complex type whose members
647 are the event-specific data.  A union type requires ``'boxed': true``.
649 An example event is::
651  { 'event': 'EVENT_C',
652    'data': { '*a': 'int', 'b': 'str' } }
654 Resulting in this JSON object::
656  { "event": "EVENT_C",
657    "data": { "b": "test string" },
658    "timestamp": { "seconds": 1267020223, "microseconds": 435656 } }
660 The generator emits a function to send the event.  When member 'boxed'
661 is absent, it takes event-specific data one by one, in QAPI schema
662 order.  Else it takes them wrapped in the C struct generated for the
663 complex type.  See section `Code generated for events`_ for examples.
665 The optional 'if' member specifies a conditional.  See `Configuring
666 the schema`_ below for more on this.
668 The optional 'features' member specifies features.  See Features_
669 below for more on this.
672 .. _FEATURE:
674 Features
675 --------
677 Syntax::
679     FEATURES = [ FEATURE, ... ]
680     FEATURE = STRING
681             | { 'name': STRING, '*if': COND }
683 Sometimes, the behaviour of QEMU changes compatibly, but without a
684 change in the QMP syntax (usually by allowing values or operations
685 that previously resulted in an error).  QMP clients may still need to
686 know whether the extension is available.
688 For this purpose, a list of features can be specified for definitions,
689 enumeration values, and struct members.  Each feature list member can
690 either be ``{ 'name': STRING, '*if': COND }``, or STRING, which is
691 shorthand for ``{ 'name': STRING }``.
693 The optional 'if' member specifies a conditional.  See `Configuring
694 the schema`_ below for more on this.
696 Example::
698  { 'struct': 'TestType',
699    'data': { 'number': 'int' },
700    'features': [ 'allow-negative-numbers' ] }
702 The feature strings are exposed to clients in introspection, as
703 explained in section `Client JSON Protocol introspection`_.
705 Intended use is to have each feature string signal that this build of
706 QEMU shows a certain behaviour.
709 Special features
710 ~~~~~~~~~~~~~~~~
712 Feature "deprecated" marks a command, event, enum value, or struct
713 member as deprecated.  It is not supported elsewhere so far.
714 Interfaces so marked may be withdrawn in future releases in accordance
715 with QEMU's deprecation policy.
717 Feature "unstable" marks a command, event, enum value, or struct
718 member as unstable.  It is not supported elsewhere so far.  Interfaces
719 so marked may be withdrawn or changed incompatibly in future releases.
722 Naming rules and reserved names
723 -------------------------------
725 All names must begin with a letter, and contain only ASCII letters,
726 digits, hyphen, and underscore.  There are two exceptions: enum values
727 may start with a digit, and names that are downstream extensions (see
728 section `Downstream extensions`_) start with underscore.
730 Names beginning with ``q_`` are reserved for the generator, which uses
731 them for munging QMP names that resemble C keywords or other
732 problematic strings.  For example, a member named ``default`` in qapi
733 becomes ``q_default`` in the generated C code.
735 Types, commands, and events share a common namespace.  Therefore,
736 generally speaking, type definitions should always use CamelCase for
737 user-defined type names, while built-in types are lowercase.
739 Type names ending with ``Kind`` or ``List`` are reserved for the
740 generator, which uses them for implicit union enums and array types,
741 respectively.
743 Command names, member names within a type, and feature names should be
744 all lower case with words separated by a hyphen.  However, some
745 existing older commands and complex types use underscore; when
746 extending them, consistency is preferred over blindly avoiding
747 underscore.
749 Event names should be ALL_CAPS with words separated by underscore.
751 Member name ``u`` and names starting with ``has-`` or ``has_`` are reserved
752 for the generator, which uses them for unions and for tracking
753 optional members.
755 Names beginning with ``x-`` used to signify "experimental".  This
756 convention has been replaced by special feature "unstable".
758 Pragmas ``command-name-exceptions`` and ``member-name-exceptions`` let
759 you violate naming rules.  Use for new code is strongly discouraged. See
760 `Pragma directives`_ for details.
763 Downstream extensions
764 ---------------------
766 QAPI schema names that are externally visible, say in the Client JSON
767 Protocol, need to be managed with care.  Names starting with a
768 downstream prefix of the form __RFQDN_ are reserved for the downstream
769 who controls the valid, reverse fully qualified domain name RFQDN.
770 RFQDN may only contain ASCII letters, digits, hyphen and period.
772 Example: Red Hat, Inc. controls redhat.com, and may therefore add a
773 downstream command ``__com.redhat_drive-mirror``.
776 Configuring the schema
777 ----------------------
779 Syntax::
781     COND = STRING
782          | { 'all: [ COND, ... ] }
783          | { 'any: [ COND, ... ] }
784          | { 'not': COND }
786 All definitions take an optional 'if' member.  Its value must be a
787 string, or an object with a single member 'all', 'any' or 'not'.
789 The C code generated for the definition will then be guarded by an #if
790 preprocessing directive with an operand generated from that condition:
792  * STRING will generate defined(STRING)
793  * { 'all': [COND, ...] } will generate (COND && ...)
794  * { 'any': [COND, ...] } will generate (COND || ...)
795  * { 'not': COND } will generate !COND
797 Example: a conditional struct ::
799  { 'struct': 'IfStruct', 'data': { 'foo': 'int' },
800    'if': { 'all': [ 'CONFIG_FOO', 'HAVE_BAR' ] } }
802 gets its generated code guarded like this::
804  #if defined(CONFIG_FOO) && defined(HAVE_BAR)
805  ... generated code ...
806  #endif /* defined(HAVE_BAR) && defined(CONFIG_FOO) */
808 Individual members of complex types, commands arguments, and
809 event-specific data can also be made conditional.  This requires the
810 longhand form of MEMBER.
812 Example: a struct type with unconditional member 'foo' and conditional
813 member 'bar' ::
815  { 'struct': 'IfStruct',
816    'data': { 'foo': 'int',
817              'bar': { 'type': 'int', 'if': 'IFCOND'} } }
819 A union's discriminator may not be conditional.
821 Likewise, individual enumeration values may be conditional.  This
822 requires the longhand form of ENUM-VALUE_.
824 Example: an enum type with unconditional value 'foo' and conditional
825 value 'bar' ::
827  { 'enum': 'IfEnum',
828    'data': [ 'foo',
829              { 'name' : 'bar', 'if': 'IFCOND' } ] }
831 Likewise, features can be conditional.  This requires the longhand
832 form of FEATURE_.
834 Example: a struct with conditional feature 'allow-negative-numbers' ::
836  { 'struct': 'TestType',
837    'data': { 'number': 'int' },
838    'features': [ { 'name': 'allow-negative-numbers',
839                    'if': 'IFCOND' } ] }
841 Please note that you are responsible to ensure that the C code will
842 compile with an arbitrary combination of conditions, since the
843 generator is unable to check it at this point.
845 The conditions apply to introspection as well, i.e. introspection
846 shows a conditional entity only when the condition is satisfied in
847 this particular build.
850 Documentation comments
851 ----------------------
853 A multi-line comment that starts and ends with a ``##`` line is a
854 documentation comment.
856 If the documentation comment starts like ::
858     ##
859     # @SYMBOL:
861 it documents the definition of SYMBOL, else it's free-form
862 documentation.
864 See below for more on `Definition documentation`_.
866 Free-form documentation may be used to provide additional text and
867 structuring content.
870 Headings and subheadings
871 ~~~~~~~~~~~~~~~~~~~~~~~~
873 A free-form documentation comment containing a line which starts with
874 some ``=`` symbols and then a space defines a section heading::
876     ##
877     # = This is a top level heading
878     #
879     # This is a free-form comment which will go under the
880     # top level heading.
881     ##
883     ##
884     # == This is a second level heading
885     ##
887 A heading line must be the first line of the documentation
888 comment block.
890 Section headings must always be correctly nested, so you can only
891 define a third-level heading inside a second-level heading, and so on.
894 Documentation markup
895 ~~~~~~~~~~~~~~~~~~~~
897 Documentation comments can use most rST markup.  In particular,
898 a ``::`` literal block can be used for examples::
900     # ::
901     #
902     #   Text of the example, may span
903     #   multiple lines
905 ``*`` starts an itemized list::
907     # * First item, may span
908     #   multiple lines
909     # * Second item
911 You can also use ``-`` instead of ``*``.
913 A decimal number followed by ``.`` starts a numbered list::
915     # 1. First item, may span
916     #    multiple lines
917     # 2. Second item
919 The actual number doesn't matter.
921 Lists of either kind must be preceded and followed by a blank line.
922 If a list item's text spans multiple lines, then the second and
923 subsequent lines must be correctly indented to line up with the
924 first character of the first line.
926 The usual ****strong****, *\*emphasized\** and ````literal```` markup
927 should be used.  If you need a single literal ``*``, you will need to
928 backslash-escape it.  As an extension beyond the usual rST syntax, you
929 can also use ``@foo`` to reference a name in the schema; this is rendered
930 the same way as ````foo````.
932 Example::
934  ##
935  # Some text foo with **bold** and *emphasis*
936  # 1. with a list
937  # 2. like that
939  # And some code:
941  # ::
943  #   $ echo foo
944  #   -> do this
945  #   <- get that
946  ##
949 Definition documentation
950 ~~~~~~~~~~~~~~~~~~~~~~~~
952 Definition documentation, if present, must immediately precede the
953 definition it documents.
955 When documentation is required (see pragma_ 'doc-required'), every
956 definition must have documentation.
958 Definition documentation starts with a line naming the definition,
959 followed by an optional overview, a description of each argument (for
960 commands and events), member (for structs and unions), branch (for
961 alternates), or value (for enums), a description of each feature (if
962 any), and finally optional tagged sections.
964 The description of an argument or feature 'name' starts with
965 '\@name:'.  The description text can start on the line following the
966 '\@name:', in which case it must not be indented at all.  It can also
967 start on the same line as the '\@name:'.  In this case if it spans
968 multiple lines then second and subsequent lines must be indented to
969 line up with the first character of the first line of the
970 description::
972  # @argone:
973  # This is a two line description
974  # in the first style.
976  # @argtwo: This is a two line description
977  #          in the second style.
979 The number of spaces between the ':' and the text is not significant.
981 .. admonition:: FIXME
983    The parser accepts these things in almost any order.
985 .. admonition:: FIXME
987    union branches should be described, too.
989 Extensions added after the definition was first released carry a
990 '(since x.y.z)' comment.
992 The feature descriptions must be preceded by a line "Features:", like
993 this::
995   # Features:
996   # @feature: Description text
998 A tagged section starts with one of the following words:
999 "Note:"/"Notes:", "Since:", "Example"/"Examples", "Returns:", "TODO:".
1000 The section ends with the start of a new section.
1002 The text of a section can start on a new line, in
1003 which case it must not be indented at all.  It can also start
1004 on the same line as the 'Note:', 'Returns:', etc tag.  In this
1005 case if it spans multiple lines then second and subsequent
1006 lines must be indented to match the first, in the same way as
1007 multiline argument descriptions.
1009 A 'Since: x.y.z' tagged section lists the release that introduced the
1010 definition.
1012 An 'Example' or 'Examples' section is automatically rendered
1013 entirely as literal fixed-width text.  In other sections,
1014 the text is formatted, and rST markup can be used.
1016 For example::
1018  ##
1019  # @BlockStats:
1021  # Statistics of a virtual block device or a block backing device.
1023  # @device: If the stats are for a virtual block device, the name
1024  #          corresponding to the virtual block device.
1026  # @node-name: The node name of the device. (since 2.3)
1028  # ... more members ...
1030  # Since: 0.14.0
1031  ##
1032  { 'struct': 'BlockStats',
1033    'data': {'*device': 'str', '*node-name': 'str',
1034             ... more members ... } }
1036  ##
1037  # @query-blockstats:
1039  # Query the @BlockStats for all virtual block devices.
1041  # @query-nodes: If true, the command will query all the
1042  #               block nodes ... explain, explain ...  (since 2.3)
1044  # Returns: A list of @BlockStats for each virtual block devices.
1046  # Since: 0.14.0
1048  # Example:
1050  # -> { "execute": "query-blockstats" }
1051  # <- {
1052  #      ... lots of output ...
1053  #    }
1055  ##
1056  { 'command': 'query-blockstats',
1057    'data': { '*query-nodes': 'bool' },
1058    'returns': ['BlockStats'] }
1061 Client JSON Protocol introspection
1062 ==================================
1064 Clients of a Client JSON Protocol commonly need to figure out what
1065 exactly the server (QEMU) supports.
1067 For this purpose, QMP provides introspection via command
1068 query-qmp-schema.  QGA currently doesn't support introspection.
1070 While Client JSON Protocol wire compatibility should be maintained
1071 between qemu versions, we cannot make the same guarantees for
1072 introspection stability.  For example, one version of qemu may provide
1073 a non-variant optional member of a struct, and a later version rework
1074 the member to instead be non-optional and associated with a variant.
1075 Likewise, one version of qemu may list a member with open-ended type
1076 'str', and a later version could convert it to a finite set of strings
1077 via an enum type; or a member may be converted from a specific type to
1078 an alternate that represents a choice between the original type and
1079 something else.
1081 query-qmp-schema returns a JSON array of SchemaInfo objects.  These
1082 objects together describe the wire ABI, as defined in the QAPI schema.
1083 There is no specified order to the SchemaInfo objects returned; a
1084 client must search for a particular name throughout the entire array
1085 to learn more about that name, but is at least guaranteed that there
1086 will be no collisions between type, command, and event names.
1088 However, the SchemaInfo can't reflect all the rules and restrictions
1089 that apply to QMP.  It's interface introspection (figuring out what's
1090 there), not interface specification.  The specification is in the QAPI
1091 schema.  To understand how QMP is to be used, you need to study the
1092 QAPI schema.
1094 Like any other command, query-qmp-schema is itself defined in the QAPI
1095 schema, along with the SchemaInfo type.  This text attempts to give an
1096 overview how things work.  For details you need to consult the QAPI
1097 schema.
1099 SchemaInfo objects have common members "name", "meta-type",
1100 "features", and additional variant members depending on the value of
1101 meta-type.
1103 Each SchemaInfo object describes a wire ABI entity of a certain
1104 meta-type: a command, event or one of several kinds of type.
1106 SchemaInfo for commands and events have the same name as in the QAPI
1107 schema.
1109 Command and event names are part of the wire ABI, but type names are
1110 not.  Therefore, the SchemaInfo for types have auto-generated
1111 meaningless names.  For readability, the examples in this section use
1112 meaningful type names instead.
1114 Optional member "features" exposes the entity's feature strings as a
1115 JSON array of strings.
1117 To examine a type, start with a command or event using it, then follow
1118 references by name.
1120 QAPI schema definitions not reachable that way are omitted.
1122 The SchemaInfo for a command has meta-type "command", and variant
1123 members "arg-type", "ret-type" and "allow-oob".  On the wire, the
1124 "arguments" member of a client's "execute" command must conform to the
1125 object type named by "arg-type".  The "return" member that the server
1126 passes in a success response conforms to the type named by "ret-type".
1127 When "allow-oob" is true, it means the command supports out-of-band
1128 execution.  It defaults to false.
1130 If the command takes no arguments, "arg-type" names an object type
1131 without members.  Likewise, if the command returns nothing, "ret-type"
1132 names an object type without members.
1134 Example: the SchemaInfo for command query-qmp-schema ::
1136  { "name": "query-qmp-schema", "meta-type": "command",
1137    "arg-type": "q_empty", "ret-type": "SchemaInfoList" }
1139    Type "q_empty" is an automatic object type without members, and type
1140    "SchemaInfoList" is the array of SchemaInfo type.
1142 The SchemaInfo for an event has meta-type "event", and variant member
1143 "arg-type".  On the wire, a "data" member that the server passes in an
1144 event conforms to the object type named by "arg-type".
1146 If the event carries no additional information, "arg-type" names an
1147 object type without members.  The event may not have a data member on
1148 the wire then.
1150 Each command or event defined with 'data' as MEMBERS object in the
1151 QAPI schema implicitly defines an object type.
1153 Example: the SchemaInfo for EVENT_C from section Events_ ::
1155     { "name": "EVENT_C", "meta-type": "event",
1156       "arg-type": "q_obj-EVENT_C-arg" }
1158     Type "q_obj-EVENT_C-arg" is an implicitly defined object type with
1159     the two members from the event's definition.
1161 The SchemaInfo for struct and union types has meta-type "object" and
1162 variant member "members".
1164 The SchemaInfo for a union type additionally has variant members "tag"
1165 and "variants".
1167 "members" is a JSON array describing the object's common members, if
1168 any.  Each element is a JSON object with members "name" (the member's
1169 name), "type" (the name of its type), "features" (a JSON array of
1170 feature strings), and "default".  The latter two are optional.  The
1171 member is optional if "default" is present.  Currently, "default" can
1172 only have value null.  Other values are reserved for future
1173 extensions.  The "members" array is in no particular order; clients
1174 must search the entire object when learning whether a particular
1175 member is supported.
1177 Example: the SchemaInfo for MyType from section `Struct types`_ ::
1179     { "name": "MyType", "meta-type": "object",
1180       "members": [
1181           { "name": "member1", "type": "str" },
1182           { "name": "member2", "type": "int" },
1183           { "name": "member3", "type": "str", "default": null } ] }
1185 "features" exposes the command's feature strings as a JSON array of
1186 strings.
1188 Example: the SchemaInfo for TestType from section Features_::
1190     { "name": "TestType", "meta-type": "object",
1191       "members": [
1192           { "name": "number", "type": "int" } ],
1193       "features": ["allow-negative-numbers"] }
1195 "tag" is the name of the common member serving as type tag.
1196 "variants" is a JSON array describing the object's variant members.
1197 Each element is a JSON object with members "case" (the value of type
1198 tag this element applies to) and "type" (the name of an object type
1199 that provides the variant members for this type tag value).  The
1200 "variants" array is in no particular order, and is not guaranteed to
1201 list cases in the same order as the corresponding "tag" enum type.
1203 Example: the SchemaInfo for union BlockdevOptions from section
1204 `Union types`_ ::
1206     { "name": "BlockdevOptions", "meta-type": "object",
1207       "members": [
1208           { "name": "driver", "type": "BlockdevDriver" },
1209           { "name": "read-only", "type": "bool", "default": null } ],
1210       "tag": "driver",
1211       "variants": [
1212           { "case": "file", "type": "BlockdevOptionsFile" },
1213           { "case": "qcow2", "type": "BlockdevOptionsQcow2" } ] }
1215 Note that base types are "flattened": its members are included in the
1216 "members" array.
1218 The SchemaInfo for an alternate type has meta-type "alternate", and
1219 variant member "members".  "members" is a JSON array.  Each element is
1220 a JSON object with member "type", which names a type.  Values of the
1221 alternate type conform to exactly one of its member types.  There is
1222 no guarantee on the order in which "members" will be listed.
1224 Example: the SchemaInfo for BlockdevRef from section `Alternate types`_ ::
1226     { "name": "BlockdevRef", "meta-type": "alternate",
1227       "members": [
1228           { "type": "BlockdevOptions" },
1229           { "type": "str" } ] }
1231 The SchemaInfo for an array type has meta-type "array", and variant
1232 member "element-type", which names the array's element type.  Array
1233 types are implicitly defined.  For convenience, the array's name may
1234 resemble the element type; however, clients should examine member
1235 "element-type" instead of making assumptions based on parsing member
1236 "name".
1238 Example: the SchemaInfo for ['str'] ::
1240     { "name": "[str]", "meta-type": "array",
1241       "element-type": "str" }
1243 The SchemaInfo for an enumeration type has meta-type "enum" and
1244 variant member "members".
1246 "members" is a JSON array describing the enumeration values.  Each
1247 element is a JSON object with member "name" (the member's name), and
1248 optionally "features" (a JSON array of feature strings).  The
1249 "members" array is in no particular order; clients must search the
1250 entire array when learning whether a particular value is supported.
1252 Example: the SchemaInfo for MyEnum from section `Enumeration types`_ ::
1254     { "name": "MyEnum", "meta-type": "enum",
1255       "members": [
1256         { "name": "value1" },
1257         { "name": "value2" },
1258         { "name": "value3" }
1259       ] }
1261 The SchemaInfo for a built-in type has the same name as the type in
1262 the QAPI schema (see section `Built-in Types`_), with one exception
1263 detailed below.  It has variant member "json-type" that shows how
1264 values of this type are encoded on the wire.
1266 Example: the SchemaInfo for str ::
1268     { "name": "str", "meta-type": "builtin", "json-type": "string" }
1270 The QAPI schema supports a number of integer types that only differ in
1271 how they map to C.  They are identical as far as SchemaInfo is
1272 concerned.  Therefore, they get all mapped to a single type "int" in
1273 SchemaInfo.
1275 As explained above, type names are not part of the wire ABI.  Not even
1276 the names of built-in types.  Clients should examine member
1277 "json-type" instead of hard-coding names of built-in types.
1280 Compatibility considerations
1281 ============================
1283 Maintaining backward compatibility at the Client JSON Protocol level
1284 while evolving the schema requires some care.  This section is about
1285 syntactic compatibility, which is necessary, but not sufficient, for
1286 actual compatibility.
1288 Clients send commands with argument data, and receive command
1289 responses with return data and events with event data.
1291 Adding opt-in functionality to the send direction is backwards
1292 compatible: adding commands, optional arguments, enumeration values,
1293 union and alternate branches; turning an argument type into an
1294 alternate of that type; making mandatory arguments optional.  Clients
1295 oblivious of the new functionality continue to work.
1297 Incompatible changes include removing commands, command arguments,
1298 enumeration values, union and alternate branches, adding mandatory
1299 command arguments, and making optional arguments mandatory.
1301 The specified behavior of an absent optional argument should remain
1302 the same.  With proper documentation, this policy still allows some
1303 flexibility; for example, when an optional 'buffer-size' argument is
1304 specified to default to a sensible buffer size, the actual default
1305 value can still be changed.  The specified default behavior is not the
1306 exact size of the buffer, only that the default size is sensible.
1308 Adding functionality to the receive direction is generally backwards
1309 compatible: adding events, adding return and event data members.
1310 Clients are expected to ignore the ones they don't know.
1312 Removing "unreachable" stuff like events that can't be triggered
1313 anymore, optional return or event data members that can't be sent
1314 anymore, and return or event data member (enumeration) values that
1315 can't be sent anymore makes no difference to clients, except for
1316 introspection.  The latter can conceivably confuse clients, so tread
1317 carefully.
1319 Incompatible changes include removing return and event data members.
1321 Any change to a command definition's 'data' or one of the types used
1322 there (recursively) needs to consider send direction compatibility.
1324 Any change to a command definition's 'return', an event definition's
1325 'data', or one of the types used there (recursively) needs to consider
1326 receive direction compatibility.
1328 Any change to types used in both contexts need to consider both.
1330 Enumeration type values and complex and alternate type members may be
1331 reordered freely.  For enumerations and alternate types, this doesn't
1332 affect the wire encoding.  For complex types, this might make the
1333 implementation emit JSON object members in a different order, which
1334 the Client JSON Protocol permits.
1336 Since type names are not visible in the Client JSON Protocol, types
1337 may be freely renamed.  Even certain refactorings are invisible, such
1338 as splitting members from one type into a common base type.
1341 Code generation
1342 ===============
1344 The QAPI code generator qapi-gen.py generates code and documentation
1345 from the schema.  Together with the core QAPI libraries, this code
1346 provides everything required to take JSON commands read in by a Client
1347 JSON Protocol server, unmarshal the arguments into the underlying C
1348 types, call into the corresponding C function, map the response back
1349 to a Client JSON Protocol response to be returned to the user, and
1350 introspect the commands.
1352 As an example, we'll use the following schema, which describes a
1353 single complex user-defined type, along with command which takes a
1354 list of that type as a parameter, and returns a single element of that
1355 type.  The user is responsible for writing the implementation of
1356 qmp_my_command(); everything else is produced by the generator. ::
1358     $ cat example-schema.json
1359     { 'struct': 'UserDefOne',
1360       'data': { 'integer': 'int', '*string': 'str', '*flag': 'bool' } }
1362     { 'command': 'my-command',
1363       'data': { 'arg1': ['UserDefOne'] },
1364       'returns': 'UserDefOne' }
1366     { 'event': 'MY_EVENT' }
1368 We run qapi-gen.py like this::
1370     $ python scripts/qapi-gen.py --output-dir="qapi-generated" \
1371     --prefix="example-" example-schema.json
1373 For a more thorough look at generated code, the testsuite includes
1374 tests/qapi-schema/qapi-schema-tests.json that covers more examples of
1375 what the generator will accept, and compiles the resulting C code as
1376 part of 'make check-unit'.
1379 Code generated for QAPI types
1380 -----------------------------
1382 The following files are created:
1384  ``$(prefix)qapi-types.h``
1385      C types corresponding to types defined in the schema
1387  ``$(prefix)qapi-types.c``
1388      Cleanup functions for the above C types
1390 The $(prefix) is an optional parameter used as a namespace to keep the
1391 generated code from one schema/code-generation separated from others so code
1392 can be generated/used from multiple schemas without clobbering previously
1393 created code.
1395 Example::
1397     $ cat qapi-generated/example-qapi-types.h
1398     [Uninteresting stuff omitted...]
1400     #ifndef EXAMPLE_QAPI_TYPES_H
1401     #define EXAMPLE_QAPI_TYPES_H
1403     #include "qapi/qapi-builtin-types.h"
1405     typedef struct UserDefOne UserDefOne;
1407     typedef struct UserDefOneList UserDefOneList;
1409     typedef struct q_obj_my_command_arg q_obj_my_command_arg;
1411     struct UserDefOne {
1412         int64_t integer;
1413         char *string;
1414         bool has_flag;
1415         bool flag;
1416     };
1418     void qapi_free_UserDefOne(UserDefOne *obj);
1419     G_DEFINE_AUTOPTR_CLEANUP_FUNC(UserDefOne, qapi_free_UserDefOne)
1421     struct UserDefOneList {
1422         UserDefOneList *next;
1423         UserDefOne *value;
1424     };
1426     void qapi_free_UserDefOneList(UserDefOneList *obj);
1427     G_DEFINE_AUTOPTR_CLEANUP_FUNC(UserDefOneList, qapi_free_UserDefOneList)
1429     struct q_obj_my_command_arg {
1430         UserDefOneList *arg1;
1431     };
1433     #endif /* EXAMPLE_QAPI_TYPES_H */
1434     $ cat qapi-generated/example-qapi-types.c
1435     [Uninteresting stuff omitted...]
1437     void qapi_free_UserDefOne(UserDefOne *obj)
1438     {
1439         Visitor *v;
1441         if (!obj) {
1442             return;
1443         }
1445         v = qapi_dealloc_visitor_new();
1446         visit_type_UserDefOne(v, NULL, &obj, NULL);
1447         visit_free(v);
1448     }
1450     void qapi_free_UserDefOneList(UserDefOneList *obj)
1451     {
1452         Visitor *v;
1454         if (!obj) {
1455             return;
1456         }
1458         v = qapi_dealloc_visitor_new();
1459         visit_type_UserDefOneList(v, NULL, &obj, NULL);
1460         visit_free(v);
1461     }
1463     [Uninteresting stuff omitted...]
1465 For a modular QAPI schema (see section `Include directives`_), code for
1466 each sub-module SUBDIR/SUBMODULE.json is actually generated into ::
1468  SUBDIR/$(prefix)qapi-types-SUBMODULE.h
1469  SUBDIR/$(prefix)qapi-types-SUBMODULE.c
1471 If qapi-gen.py is run with option --builtins, additional files are
1472 created:
1474  ``qapi-builtin-types.h``
1475      C types corresponding to built-in types
1477  ``qapi-builtin-types.c``
1478      Cleanup functions for the above C types
1481 Code generated for visiting QAPI types
1482 --------------------------------------
1484 These are the visitor functions used to walk through and convert
1485 between a native QAPI C data structure and some other format (such as
1486 QObject); the generated functions are named visit_type_FOO() and
1487 visit_type_FOO_members().
1489 The following files are generated:
1491  ``$(prefix)qapi-visit.c``
1492      Visitor function for a particular C type, used to automagically
1493      convert QObjects into the corresponding C type and vice-versa, as
1494      well as for deallocating memory for an existing C type
1496  ``$(prefix)qapi-visit.h``
1497      Declarations for previously mentioned visitor functions
1499 Example::
1501     $ cat qapi-generated/example-qapi-visit.h
1502     [Uninteresting stuff omitted...]
1504     #ifndef EXAMPLE_QAPI_VISIT_H
1505     #define EXAMPLE_QAPI_VISIT_H
1507     #include "qapi/qapi-builtin-visit.h"
1508     #include "example-qapi-types.h"
1511     bool visit_type_UserDefOne_members(Visitor *v, UserDefOne *obj, Error **errp);
1513     bool visit_type_UserDefOne(Visitor *v, const char *name,
1514                      UserDefOne **obj, Error **errp);
1516     bool visit_type_UserDefOneList(Visitor *v, const char *name,
1517                      UserDefOneList **obj, Error **errp);
1519     bool visit_type_q_obj_my_command_arg_members(Visitor *v, q_obj_my_command_arg *obj, Error **errp);
1521     #endif /* EXAMPLE_QAPI_VISIT_H */
1522     $ cat qapi-generated/example-qapi-visit.c
1523     [Uninteresting stuff omitted...]
1525     bool visit_type_UserDefOne_members(Visitor *v, UserDefOne *obj, Error **errp)
1526     {
1527         bool has_string = !!obj->string;
1529         if (!visit_type_int(v, "integer", &obj->integer, errp)) {
1530             return false;
1531         }
1532         if (visit_optional(v, "string", &has_string)) {
1533             if (!visit_type_str(v, "string", &obj->string, errp)) {
1534                 return false;
1535             }
1536         }
1537         if (visit_optional(v, "flag", &obj->has_flag)) {
1538             if (!visit_type_bool(v, "flag", &obj->flag, errp)) {
1539                 return false;
1540             }
1541         }
1542         return true;
1543     }
1545     bool visit_type_UserDefOne(Visitor *v, const char *name,
1546                      UserDefOne **obj, Error **errp)
1547     {
1548         bool ok = false;
1550         if (!visit_start_struct(v, name, (void **)obj, sizeof(UserDefOne), errp)) {
1551             return false;
1552         }
1553         if (!*obj) {
1554             /* incomplete */
1555             assert(visit_is_dealloc(v));
1556             ok = true;
1557             goto out_obj;
1558         }
1559         if (!visit_type_UserDefOne_members(v, *obj, errp)) {
1560             goto out_obj;
1561         }
1562         ok = visit_check_struct(v, errp);
1563     out_obj:
1564         visit_end_struct(v, (void **)obj);
1565         if (!ok && visit_is_input(v)) {
1566             qapi_free_UserDefOne(*obj);
1567             *obj = NULL;
1568         }
1569         return ok;
1570     }
1572     bool visit_type_UserDefOneList(Visitor *v, const char *name,
1573                      UserDefOneList **obj, Error **errp)
1574     {
1575         bool ok = false;
1576         UserDefOneList *tail;
1577         size_t size = sizeof(**obj);
1579         if (!visit_start_list(v, name, (GenericList **)obj, size, errp)) {
1580             return false;
1581         }
1583         for (tail = *obj; tail;
1584              tail = (UserDefOneList *)visit_next_list(v, (GenericList *)tail, size)) {
1585             if (!visit_type_UserDefOne(v, NULL, &tail->value, errp)) {
1586                 goto out_obj;
1587             }
1588         }
1590         ok = visit_check_list(v, errp);
1591     out_obj:
1592         visit_end_list(v, (void **)obj);
1593         if (!ok && visit_is_input(v)) {
1594             qapi_free_UserDefOneList(*obj);
1595             *obj = NULL;
1596         }
1597         return ok;
1598     }
1600     bool visit_type_q_obj_my_command_arg_members(Visitor *v, q_obj_my_command_arg *obj, Error **errp)
1601     {
1602         if (!visit_type_UserDefOneList(v, "arg1", &obj->arg1, errp)) {
1603             return false;
1604         }
1605         return true;
1606     }
1608     [Uninteresting stuff omitted...]
1610 For a modular QAPI schema (see section `Include directives`_), code for
1611 each sub-module SUBDIR/SUBMODULE.json is actually generated into ::
1613  SUBDIR/$(prefix)qapi-visit-SUBMODULE.h
1614  SUBDIR/$(prefix)qapi-visit-SUBMODULE.c
1616 If qapi-gen.py is run with option --builtins, additional files are
1617 created:
1619  ``qapi-builtin-visit.h``
1620      Visitor functions for built-in types
1622  ``qapi-builtin-visit.c``
1623      Declarations for these visitor functions
1626 Code generated for commands
1627 ---------------------------
1629 These are the marshaling/dispatch functions for the commands defined
1630 in the schema.  The generated code provides qmp_marshal_COMMAND(), and
1631 declares qmp_COMMAND() that the user must implement.
1633 The following files are generated:
1635  ``$(prefix)qapi-commands.c``
1636      Command marshal/dispatch functions for each QMP command defined in
1637      the schema
1639  ``$(prefix)qapi-commands.h``
1640      Function prototypes for the QMP commands specified in the schema
1642  ``$(prefix)qapi-commands.trace-events``
1643      Trace event declarations, see :ref:`tracing`.
1645  ``$(prefix)qapi-init-commands.h``
1646      Command initialization prototype
1648  ``$(prefix)qapi-init-commands.c``
1649      Command initialization code
1651 Example::
1653     $ cat qapi-generated/example-qapi-commands.h
1654     [Uninteresting stuff omitted...]
1656     #ifndef EXAMPLE_QAPI_COMMANDS_H
1657     #define EXAMPLE_QAPI_COMMANDS_H
1659     #include "example-qapi-types.h"
1661     UserDefOne *qmp_my_command(UserDefOneList *arg1, Error **errp);
1662     void qmp_marshal_my_command(QDict *args, QObject **ret, Error **errp);
1664     #endif /* EXAMPLE_QAPI_COMMANDS_H */
1666     $ cat qapi-generated/example-qapi-commands.trace-events
1667     # AUTOMATICALLY GENERATED, DO NOT MODIFY
1669     qmp_enter_my_command(const char *json) "%s"
1670     qmp_exit_my_command(const char *result, bool succeeded) "%s %d"
1672     $ cat qapi-generated/example-qapi-commands.c
1673     [Uninteresting stuff omitted...]
1675     static void qmp_marshal_output_UserDefOne(UserDefOne *ret_in,
1676                                     QObject **ret_out, Error **errp)
1677     {
1678         Visitor *v;
1680         v = qobject_output_visitor_new_qmp(ret_out);
1681         if (visit_type_UserDefOne(v, "unused", &ret_in, errp)) {
1682             visit_complete(v, ret_out);
1683         }
1684         visit_free(v);
1685         v = qapi_dealloc_visitor_new();
1686         visit_type_UserDefOne(v, "unused", &ret_in, NULL);
1687         visit_free(v);
1688     }
1690     void qmp_marshal_my_command(QDict *args, QObject **ret, Error **errp)
1691     {
1692         Error *err = NULL;
1693         bool ok = false;
1694         Visitor *v;
1695         UserDefOne *retval;
1696         q_obj_my_command_arg arg = {0};
1698         v = qobject_input_visitor_new_qmp(QOBJECT(args));
1699         if (!visit_start_struct(v, NULL, NULL, 0, errp)) {
1700             goto out;
1701         }
1702         if (visit_type_q_obj_my_command_arg_members(v, &arg, errp)) {
1703             ok = visit_check_struct(v, errp);
1704         }
1705         visit_end_struct(v, NULL);
1706         if (!ok) {
1707             goto out;
1708         }
1710         if (trace_event_get_state_backends(TRACE_QMP_ENTER_MY_COMMAND)) {
1711             g_autoptr(GString) req_json = qobject_to_json(QOBJECT(args));
1713             trace_qmp_enter_my_command(req_json->str);
1714         }
1716         retval = qmp_my_command(arg.arg1, &err);
1717         if (err) {
1718             trace_qmp_exit_my_command(error_get_pretty(err), false);
1719             error_propagate(errp, err);
1720             goto out;
1721         }
1723         qmp_marshal_output_UserDefOne(retval, ret, errp);
1725         if (trace_event_get_state_backends(TRACE_QMP_EXIT_MY_COMMAND)) {
1726             g_autoptr(GString) ret_json = qobject_to_json(*ret);
1728             trace_qmp_exit_my_command(ret_json->str, true);
1729         }
1731     out:
1732         visit_free(v);
1733         v = qapi_dealloc_visitor_new();
1734         visit_start_struct(v, NULL, NULL, 0, NULL);
1735         visit_type_q_obj_my_command_arg_members(v, &arg, NULL);
1736         visit_end_struct(v, NULL);
1737         visit_free(v);
1738     }
1740     [Uninteresting stuff omitted...]
1741     $ cat qapi-generated/example-qapi-init-commands.h
1742     [Uninteresting stuff omitted...]
1743     #ifndef EXAMPLE_QAPI_INIT_COMMANDS_H
1744     #define EXAMPLE_QAPI_INIT_COMMANDS_H
1746     #include "qapi/qmp/dispatch.h"
1748     void example_qmp_init_marshal(QmpCommandList *cmds);
1750     #endif /* EXAMPLE_QAPI_INIT_COMMANDS_H */
1751     $ cat qapi-generated/example-qapi-init-commands.c
1752     [Uninteresting stuff omitted...]
1753     void example_qmp_init_marshal(QmpCommandList *cmds)
1754     {
1755         QTAILQ_INIT(cmds);
1757         qmp_register_command(cmds, "my-command",
1758                              qmp_marshal_my_command, 0, 0);
1759     }
1760     [Uninteresting stuff omitted...]
1762 For a modular QAPI schema (see section `Include directives`_), code for
1763 each sub-module SUBDIR/SUBMODULE.json is actually generated into::
1765  SUBDIR/$(prefix)qapi-commands-SUBMODULE.h
1766  SUBDIR/$(prefix)qapi-commands-SUBMODULE.c
1769 Code generated for events
1770 -------------------------
1772 This is the code related to events defined in the schema, providing
1773 qapi_event_send_EVENT().
1775 The following files are created:
1777  ``$(prefix)qapi-events.h``
1778      Function prototypes for each event type
1780  ``$(prefix)qapi-events.c``
1781      Implementation of functions to send an event
1783  ``$(prefix)qapi-emit-events.h``
1784      Enumeration of all event names, and common event code declarations
1786  ``$(prefix)qapi-emit-events.c``
1787      Common event code definitions
1789 Example::
1791     $ cat qapi-generated/example-qapi-events.h
1792     [Uninteresting stuff omitted...]
1794     #ifndef EXAMPLE_QAPI_EVENTS_H
1795     #define EXAMPLE_QAPI_EVENTS_H
1797     #include "qapi/util.h"
1798     #include "example-qapi-types.h"
1800     void qapi_event_send_my_event(void);
1802     #endif /* EXAMPLE_QAPI_EVENTS_H */
1803     $ cat qapi-generated/example-qapi-events.c
1804     [Uninteresting stuff omitted...]
1806     void qapi_event_send_my_event(void)
1807     {
1808         QDict *qmp;
1810         qmp = qmp_event_build_dict("MY_EVENT");
1812         example_qapi_event_emit(EXAMPLE_QAPI_EVENT_MY_EVENT, qmp);
1814         qobject_unref(qmp);
1815     }
1817     [Uninteresting stuff omitted...]
1818     $ cat qapi-generated/example-qapi-emit-events.h
1819     [Uninteresting stuff omitted...]
1821     #ifndef EXAMPLE_QAPI_EMIT_EVENTS_H
1822     #define EXAMPLE_QAPI_EMIT_EVENTS_H
1824     #include "qapi/util.h"
1826     typedef enum example_QAPIEvent {
1827         EXAMPLE_QAPI_EVENT_MY_EVENT,
1828         EXAMPLE_QAPI_EVENT__MAX,
1829     } example_QAPIEvent;
1831     #define example_QAPIEvent_str(val) \
1832         qapi_enum_lookup(&example_QAPIEvent_lookup, (val))
1834     extern const QEnumLookup example_QAPIEvent_lookup;
1836     void example_qapi_event_emit(example_QAPIEvent event, QDict *qdict);
1838     #endif /* EXAMPLE_QAPI_EMIT_EVENTS_H */
1839     $ cat qapi-generated/example-qapi-emit-events.c
1840     [Uninteresting stuff omitted...]
1842     const QEnumLookup example_QAPIEvent_lookup = {
1843         .array = (const char *const[]) {
1844             [EXAMPLE_QAPI_EVENT_MY_EVENT] = "MY_EVENT",
1845         },
1846         .size = EXAMPLE_QAPI_EVENT__MAX
1847     };
1849     [Uninteresting stuff omitted...]
1851 For a modular QAPI schema (see section `Include directives`_), code for
1852 each sub-module SUBDIR/SUBMODULE.json is actually generated into ::
1854  SUBDIR/$(prefix)qapi-events-SUBMODULE.h
1855  SUBDIR/$(prefix)qapi-events-SUBMODULE.c
1858 Code generated for introspection
1859 --------------------------------
1861 The following files are created:
1863  ``$(prefix)qapi-introspect.c``
1864      Defines a string holding a JSON description of the schema
1866  ``$(prefix)qapi-introspect.h``
1867      Declares the above string
1869 Example::
1871     $ cat qapi-generated/example-qapi-introspect.h
1872     [Uninteresting stuff omitted...]
1874     #ifndef EXAMPLE_QAPI_INTROSPECT_H
1875     #define EXAMPLE_QAPI_INTROSPECT_H
1877     #include "qapi/qmp/qlit.h"
1879     extern const QLitObject example_qmp_schema_qlit;
1881     #endif /* EXAMPLE_QAPI_INTROSPECT_H */
1882     $ cat qapi-generated/example-qapi-introspect.c
1883     [Uninteresting stuff omitted...]
1885     const QLitObject example_qmp_schema_qlit = QLIT_QLIST(((QLitObject[]) {
1886         QLIT_QDICT(((QLitDictEntry[]) {
1887             { "arg-type", QLIT_QSTR("0"), },
1888             { "meta-type", QLIT_QSTR("command"), },
1889             { "name", QLIT_QSTR("my-command"), },
1890             { "ret-type", QLIT_QSTR("1"), },
1891             {}
1892         })),
1893         QLIT_QDICT(((QLitDictEntry[]) {
1894             { "arg-type", QLIT_QSTR("2"), },
1895             { "meta-type", QLIT_QSTR("event"), },
1896             { "name", QLIT_QSTR("MY_EVENT"), },
1897             {}
1898         })),
1899         /* "0" = q_obj_my-command-arg */
1900         QLIT_QDICT(((QLitDictEntry[]) {
1901             { "members", QLIT_QLIST(((QLitObject[]) {
1902                 QLIT_QDICT(((QLitDictEntry[]) {
1903                     { "name", QLIT_QSTR("arg1"), },
1904                     { "type", QLIT_QSTR("[1]"), },
1905                     {}
1906                 })),
1907                 {}
1908             })), },
1909             { "meta-type", QLIT_QSTR("object"), },
1910             { "name", QLIT_QSTR("0"), },
1911             {}
1912         })),
1913         /* "1" = UserDefOne */
1914         QLIT_QDICT(((QLitDictEntry[]) {
1915             { "members", QLIT_QLIST(((QLitObject[]) {
1916                 QLIT_QDICT(((QLitDictEntry[]) {
1917                     { "name", QLIT_QSTR("integer"), },
1918                     { "type", QLIT_QSTR("int"), },
1919                     {}
1920                 })),
1921                 QLIT_QDICT(((QLitDictEntry[]) {
1922                     { "default", QLIT_QNULL, },
1923                     { "name", QLIT_QSTR("string"), },
1924                     { "type", QLIT_QSTR("str"), },
1925                     {}
1926                 })),
1927                 QLIT_QDICT(((QLitDictEntry[]) {
1928                     { "default", QLIT_QNULL, },
1929                     { "name", QLIT_QSTR("flag"), },
1930                     { "type", QLIT_QSTR("bool"), },
1931                     {}
1932                 })),
1933                 {}
1934             })), },
1935             { "meta-type", QLIT_QSTR("object"), },
1936             { "name", QLIT_QSTR("1"), },
1937             {}
1938         })),
1939         /* "2" = q_empty */
1940         QLIT_QDICT(((QLitDictEntry[]) {
1941             { "members", QLIT_QLIST(((QLitObject[]) {
1942                 {}
1943             })), },
1944             { "meta-type", QLIT_QSTR("object"), },
1945             { "name", QLIT_QSTR("2"), },
1946             {}
1947         })),
1948         QLIT_QDICT(((QLitDictEntry[]) {
1949             { "element-type", QLIT_QSTR("1"), },
1950             { "meta-type", QLIT_QSTR("array"), },
1951             { "name", QLIT_QSTR("[1]"), },
1952             {}
1953         })),
1954         QLIT_QDICT(((QLitDictEntry[]) {
1955             { "json-type", QLIT_QSTR("int"), },
1956             { "meta-type", QLIT_QSTR("builtin"), },
1957             { "name", QLIT_QSTR("int"), },
1958             {}
1959         })),
1960         QLIT_QDICT(((QLitDictEntry[]) {
1961             { "json-type", QLIT_QSTR("string"), },
1962             { "meta-type", QLIT_QSTR("builtin"), },
1963             { "name", QLIT_QSTR("str"), },
1964             {}
1965         })),
1966         QLIT_QDICT(((QLitDictEntry[]) {
1967             { "json-type", QLIT_QSTR("boolean"), },
1968             { "meta-type", QLIT_QSTR("builtin"), },
1969             { "name", QLIT_QSTR("bool"), },
1970             {}
1971         })),
1972         {}
1973     }));
1975     [Uninteresting stuff omitted...]