qapi: Recognize section tags and 'Features:' only after blank line
[qemu/armbru.git] / docs / devel / qapi-code-gen.rst
blob6804a4b5963a36e409ca520da73859c9c2a8ace1
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                    '*documentation-exceptions': [ STRING, ... ],
171                    '*member-name-exceptions': [ STRING, ... ] } }
173 The pragma directive lets you control optional generator behavior.
175 Pragma's scope is currently the complete schema.  Setting the same
176 pragma to different values in parts of the schema doesn't work.
178 Pragma 'doc-required' takes a boolean value.  If true, documentation
179 is required.  Default is false.
181 Pragma 'command-name-exceptions' takes a list of commands whose names
182 may contain ``"_"`` instead of ``"-"``.  Default is none.
184 Pragma 'command-returns-exceptions' takes a list of commands that may
185 violate the rules on permitted return types.  Default is none.
187 Pragma 'documentation-exceptions' takes a list of types, commands, and
188 events whose members / arguments need not be documented.  Default is
189 none.
191 Pragma 'member-name-exceptions' takes a list of types whose member
192 names may contain uppercase letters, and ``"_"`` instead of ``"-"``.
193 Default is none.
195 .. _ENUM-VALUE:
197 Enumeration types
198 -----------------
200 Syntax::
202     ENUM = { 'enum': STRING,
203              'data': [ ENUM-VALUE, ... ],
204              '*prefix': STRING,
205              '*if': COND,
206              '*features': FEATURES }
207     ENUM-VALUE = STRING
208                | { 'name': STRING,
209                    '*if': COND,
210                    '*features': FEATURES }
212 Member 'enum' names the enum type.
214 Each member of the 'data' array defines a value of the enumeration
215 type.  The form STRING is shorthand for :code:`{ 'name': STRING }`.  The
216 'name' values must be be distinct.
218 Example::
220  { 'enum': 'MyEnum', 'data': [ 'value1', 'value2', 'value3' ] }
222 Nothing prevents an empty enumeration, although it is probably not
223 useful.
225 On the wire, an enumeration type's value is represented by its
226 (string) name.  In C, it's represented by an enumeration constant.
227 These are of the form PREFIX_NAME, where PREFIX is derived from the
228 enumeration type's name, and NAME from the value's name.  For the
229 example above, the generator maps 'MyEnum' to MY_ENUM and 'value1' to
230 VALUE1, resulting in the enumeration constant MY_ENUM_VALUE1.  The
231 optional 'prefix' member overrides PREFIX.
233 The generated C enumeration constants have values 0, 1, ..., N-1 (in
234 QAPI schema order), where N is the number of values.  There is an
235 additional enumeration constant PREFIX__MAX with value N.
237 Do not use string or an integer type when an enumeration type can do
238 the job satisfactorily.
240 The optional 'if' member specifies a conditional.  See `Configuring the
241 schema`_ below for more on this.
243 The optional 'features' member specifies features.  See Features_
244 below for more on this.
247 .. _TYPE-REF:
249 Type references and array types
250 -------------------------------
252 Syntax::
254     TYPE-REF = STRING | ARRAY-TYPE
255     ARRAY-TYPE = [ STRING ]
257 A string denotes the type named by the string.
259 A one-element array containing a string denotes an array of the type
260 named by the string.  Example: ``['int']`` denotes an array of ``int``.
263 Struct types
264 ------------
266 Syntax::
268     STRUCT = { 'struct': STRING,
269                'data': MEMBERS,
270                '*base': STRING,
271                '*if': COND,
272                '*features': FEATURES }
273     MEMBERS = { MEMBER, ... }
274     MEMBER = STRING : TYPE-REF
275            | STRING : { 'type': TYPE-REF,
276                         '*if': COND,
277                         '*features': FEATURES }
279 Member 'struct' names the struct type.
281 Each MEMBER of the 'data' object defines a member of the struct type.
283 .. _MEMBERS:
285 The MEMBER's STRING name consists of an optional ``*`` prefix and the
286 struct member name.  If ``*`` is present, the member is optional.
288 The MEMBER's value defines its properties, in particular its type.
289 The form TYPE-REF_ is shorthand for :code:`{ 'type': TYPE-REF }`.
291 Example::
293  { 'struct': 'MyType',
294    'data': { 'member1': 'str', 'member2': ['int'], '*member3': 'str' } }
296 A struct type corresponds to a struct in C, and an object in JSON.
297 The C struct's members are generated in QAPI schema order.
299 The optional 'base' member names a struct type whose members are to be
300 included in this type.  They go first in the C struct.
302 Example::
304  { 'struct': 'BlockdevOptionsGenericFormat',
305    'data': { 'file': 'str' } }
306  { 'struct': 'BlockdevOptionsGenericCOWFormat',
307    'base': 'BlockdevOptionsGenericFormat',
308    'data': { '*backing': 'str' } }
310 An example BlockdevOptionsGenericCOWFormat object on the wire could use
311 both members like this::
313  { "file": "/some/place/my-image",
314    "backing": "/some/place/my-backing-file" }
316 The optional 'if' member specifies a conditional.  See `Configuring
317 the schema`_ below for more on this.
319 The optional 'features' member specifies features.  See Features_
320 below for more on this.
323 Union types
324 -----------
326 Syntax::
328     UNION = { 'union': STRING,
329               'base': ( MEMBERS | STRING ),
330               'discriminator': STRING,
331               'data': BRANCHES,
332               '*if': COND,
333               '*features': FEATURES }
334     BRANCHES = { BRANCH, ... }
335     BRANCH = STRING : TYPE-REF
336            | STRING : { 'type': TYPE-REF, '*if': COND }
338 Member 'union' names the union type.
340 The 'base' member defines the common members.  If it is a MEMBERS_
341 object, it defines common members just like a struct type's 'data'
342 member defines struct type members.  If it is a STRING, it names a
343 struct type whose members are the common members.
345 Member 'discriminator' must name a non-optional enum-typed member of
346 the base struct.  That member's value selects a branch by its name.
347 If no such branch exists, an empty branch is assumed.
349 Each BRANCH of the 'data' object defines a branch of the union.  A
350 union must have at least one branch.
352 The BRANCH's STRING name is the branch name.  It must be a value of
353 the discriminator enum type.
355 The BRANCH's value defines the branch's properties, in particular its
356 type.  The type must a struct type.  The form TYPE-REF_ is shorthand
357 for :code:`{ 'type': TYPE-REF }`.
359 In the Client JSON Protocol, a union is represented by an object with
360 the common members (from the base type) and the selected branch's
361 members.  The two sets of member names must be disjoint.
363 Example::
365  { 'enum': 'BlockdevDriver', 'data': [ 'file', 'qcow2' ] }
366  { 'union': 'BlockdevOptions',
367    'base': { 'driver': 'BlockdevDriver', '*read-only': 'bool' },
368    'discriminator': 'driver',
369    'data': { 'file': 'BlockdevOptionsFile',
370              'qcow2': 'BlockdevOptionsQcow2' } }
372 Resulting in these JSON objects::
374  { "driver": "file", "read-only": true,
375    "filename": "/some/place/my-image" }
376  { "driver": "qcow2", "read-only": false,
377    "backing": "/some/place/my-image", "lazy-refcounts": true }
379 The order of branches need not match the order of the enum values.
380 The branches need not cover all possible enum values.  In the
381 resulting generated C data types, a union is represented as a struct
382 with the base members in QAPI schema order, and then a union of
383 structures for each branch of the struct.
385 The optional 'if' member specifies a conditional.  See `Configuring
386 the schema`_ below for more on this.
388 The optional 'features' member specifies features.  See Features_
389 below for more on this.
392 Alternate types
393 ---------------
395 Syntax::
397     ALTERNATE = { 'alternate': STRING,
398                   'data': ALTERNATIVES,
399                   '*if': COND,
400                   '*features': FEATURES }
401     ALTERNATIVES = { ALTERNATIVE, ... }
402     ALTERNATIVE = STRING : STRING
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 :code:`{ '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.
444 The optional 'features' member specifies features.  See Features_
445 below for more on this.
448 Commands
449 --------
451 Syntax::
453     COMMAND = { 'command': STRING,
454                 (
455                 '*data': ( MEMBERS | STRING ),
456                 |
457                 'data': STRING,
458                 'boxed': true,
459                 )
460                 '*returns': TYPE-REF,
461                 '*success-response': false,
462                 '*gen': false,
463                 '*allow-oob': true,
464                 '*allow-preconfig': true,
465                 '*coroutine': true,
466                 '*if': COND,
467                 '*features': FEATURES }
469 Member 'command' names the command.
471 Member 'data' defines the arguments.  It defaults to an empty MEMBERS_
472 object.
474 If 'data' is a MEMBERS_ object, then MEMBERS defines arguments just
475 like a struct type's 'data' defines struct type members.
477 If 'data' is a STRING, then STRING names a complex type whose members
478 are the arguments.  A union type requires ``'boxed': true``.
480 Member 'returns' defines the command's return type.  It defaults to an
481 empty struct type.  It must normally be a complex type or an array of
482 a complex type.  To return anything else, the command must be listed
483 in pragma 'commands-returns-exceptions'.  If you do this, extending
484 the command to return additional information will be harder.  Use of
485 the pragma for new commands is strongly discouraged.
487 A command's error responses are not specified in the QAPI schema.
488 Error conditions should be documented in comments.
490 In the Client JSON Protocol, the value of the "execute" or "exec-oob"
491 member is the command name.  The value of the "arguments" member then
492 has to conform to the arguments, and the value of the success
493 response's "return" member will conform to the return type.
495 Some example commands::
497  { 'command': 'my-first-command',
498    'data': { 'arg1': 'str', '*arg2': 'str' } }
499  { 'struct': 'MyType', 'data': { '*value': 'str' } }
500  { 'command': 'my-second-command',
501    'returns': [ 'MyType' ] }
503 which would validate this Client JSON Protocol transaction::
505  => { "execute": "my-first-command",
506       "arguments": { "arg1": "hello" } }
507  <= { "return": { } }
508  => { "execute": "my-second-command" }
509  <= { "return": [ { "value": "one" }, { } ] }
511 The generator emits a prototype for the C function implementing the
512 command.  The function itself needs to be written by hand.  See
513 section `Code generated for commands`_ for examples.
515 The function returns the return type.  When member 'boxed' is absent,
516 it takes the command arguments as arguments one by one, in QAPI schema
517 order.  Else it takes them wrapped in the C struct generated for the
518 complex argument type.  It takes an additional ``Error **`` argument in
519 either case.
521 The generator also emits a marshalling function that extracts
522 arguments for the user's function out of an input QDict, calls the
523 user's function, and if it succeeded, builds an output QObject from
524 its return value.  This is for use by the QMP monitor core.
526 In rare cases, QAPI cannot express a type-safe representation of a
527 corresponding Client JSON Protocol command.  You then have to suppress
528 generation of a marshalling function by including a member 'gen' with
529 boolean value false, and instead write your own function.  For
530 example::
532  { 'command': 'netdev_add',
533    'data': {'type': 'str', 'id': 'str'},
534    'gen': false }
536 Please try to avoid adding new commands that rely on this, and instead
537 use type-safe unions.
539 Normally, the QAPI schema is used to describe synchronous exchanges,
540 where a response is expected.  But in some cases, the action of a
541 command is expected to change state in a way that a successful
542 response is not possible (although the command will still return an
543 error object on failure).  When a successful reply is not possible,
544 the command definition includes the optional member 'success-response'
545 with boolean value false.  So far, only QGA makes use of this member.
547 Member 'allow-oob' declares whether the command supports out-of-band
548 (OOB) execution.  It defaults to false.  For example::
550  { 'command': 'migrate_recover',
551    'data': { 'uri': 'str' }, 'allow-oob': true }
553 See the :doc:`/interop/qmp-spec` for out-of-band execution syntax
554 and semantics.
556 Commands supporting out-of-band execution can still be executed
557 in-band.
559 When a command is executed in-band, its handler runs in the main
560 thread with the BQL held.
562 When a command is executed out-of-band, its handler runs in a
563 dedicated monitor I/O thread with the BQL *not* held.
565 An OOB-capable command handler must satisfy the following conditions:
567 - It terminates quickly.
568 - It does not invoke system calls that may block.
569 - It does not access guest RAM that may block when userfaultfd is
570   enabled for postcopy live migration.
571 - It takes only "fast" locks, i.e. all critical sections protected by
572   any lock it takes also satisfy the conditions for OOB command
573   handler code.
575 The restrictions on locking limit access to shared state.  Such access
576 requires synchronization, but OOB commands can't take the BQL or any
577 other "slow" lock.
579 When in doubt, do not implement OOB execution support.
581 Member 'allow-preconfig' declares whether the command is available
582 before the machine is built.  It defaults to false.  For example::
584  { 'enum': 'QMPCapability',
585    'data': [ 'oob' ] }
586  { 'command': 'qmp_capabilities',
587    'data': { '*enable': [ 'QMPCapability' ] },
588    'allow-preconfig': true }
590 QMP is available before the machine is built only when QEMU was
591 started with --preconfig.
593 Member 'coroutine' tells the QMP dispatcher whether the command handler
594 is safe to be run in a coroutine.  It defaults to false.  If it is true,
595 the command handler is called from coroutine context and may yield while
596 waiting for an external event (such as I/O completion) in order to avoid
597 blocking the guest and other background operations.
599 Coroutine safety can be hard to prove, similar to thread safety.  Common
600 pitfalls are:
602 - The BQL isn't held across ``qemu_coroutine_yield()``, so
603   operations that used to assume that they execute atomically may have
604   to be more careful to protect against changes in the global state.
606 - Nested event loops (``AIO_WAIT_WHILE()`` etc.) are problematic in
607   coroutine context and can easily lead to deadlocks.  They should be
608   replaced by yielding and reentering the coroutine when the condition
609   becomes false.
611 Since the command handler may assume coroutine context, any callers
612 other than the QMP dispatcher must also call it in coroutine context.
613 In particular, HMP commands calling such a QMP command handler must be
614 marked ``.coroutine = true`` in hmp-commands.hx.
616 It is an error to specify both ``'coroutine': true`` and ``'allow-oob': true``
617 for a command.  We don't currently have a use case for both together and
618 without a use case, it's not entirely clear what the semantics should
621 The optional 'if' member specifies a conditional.  See `Configuring
622 the schema`_ below for more on this.
624 The optional 'features' member specifies features.  See Features_
625 below for more on this.
628 Events
629 ------
631 Syntax::
633     EVENT = { 'event': STRING,
634               (
635               '*data': ( MEMBERS | STRING ),
636               |
637               'data': STRING,
638               'boxed': true,
639               )
640               '*if': COND,
641               '*features': FEATURES }
643 Member 'event' names the event.  This is the event name used in the
644 Client JSON Protocol.
646 Member 'data' defines the event-specific data.  It defaults to an
647 empty MEMBERS object.
649 If 'data' is a MEMBERS object, then MEMBERS defines event-specific
650 data just like a struct type's 'data' defines struct type members.
652 If 'data' is a STRING, then STRING names a complex type whose members
653 are the event-specific data.  A union type requires ``'boxed': true``.
655 An example event is::
657  { 'event': 'EVENT_C',
658    'data': { '*a': 'int', 'b': 'str' } }
660 Resulting in this JSON object::
662  { "event": "EVENT_C",
663    "data": { "b": "test string" },
664    "timestamp": { "seconds": 1267020223, "microseconds": 435656 } }
666 The generator emits a function to send the event.  When member 'boxed'
667 is absent, it takes event-specific data one by one, in QAPI schema
668 order.  Else it takes them wrapped in the C struct generated for the
669 complex type.  See section `Code generated for events`_ for examples.
671 The optional 'if' member specifies a conditional.  See `Configuring
672 the schema`_ below for more on this.
674 The optional 'features' member specifies features.  See Features_
675 below for more on this.
678 .. _FEATURE:
680 Features
681 --------
683 Syntax::
685     FEATURES = [ FEATURE, ... ]
686     FEATURE = STRING
687             | { 'name': STRING, '*if': COND }
689 Sometimes, the behaviour of QEMU changes compatibly, but without a
690 change in the QMP syntax (usually by allowing values or operations
691 that previously resulted in an error).  QMP clients may still need to
692 know whether the extension is available.
694 For this purpose, a list of features can be specified for definitions,
695 enumeration values, and struct members.  Each feature list member can
696 either be ``{ 'name': STRING, '*if': COND }``, or STRING, which is
697 shorthand for ``{ 'name': STRING }``.
699 The optional 'if' member specifies a conditional.  See `Configuring
700 the schema`_ below for more on this.
702 Example::
704  { 'struct': 'TestType',
705    'data': { 'number': 'int' },
706    'features': [ 'allow-negative-numbers' ] }
708 The feature strings are exposed to clients in introspection, as
709 explained in section `Client JSON Protocol introspection`_.
711 Intended use is to have each feature string signal that this build of
712 QEMU shows a certain behaviour.
715 Special features
716 ~~~~~~~~~~~~~~~~
718 Feature "deprecated" marks a command, event, enum value, or struct
719 member as deprecated.  It is not supported elsewhere so far.
720 Interfaces so marked may be withdrawn in future releases in accordance
721 with QEMU's deprecation policy.
723 Feature "unstable" marks a command, event, enum value, or struct
724 member as unstable.  It is not supported elsewhere so far.  Interfaces
725 so marked may be withdrawn or changed incompatibly in future releases.
728 Naming rules and reserved names
729 -------------------------------
731 All names must begin with a letter, and contain only ASCII letters,
732 digits, hyphen, and underscore.  There are two exceptions: enum values
733 may start with a digit, and names that are downstream extensions (see
734 section `Downstream extensions`_) start with underscore.
736 Names beginning with ``q_`` are reserved for the generator, which uses
737 them for munging QMP names that resemble C keywords or other
738 problematic strings.  For example, a member named ``default`` in qapi
739 becomes ``q_default`` in the generated C code.
741 Types, commands, and events share a common namespace.  Therefore,
742 generally speaking, type definitions should always use CamelCase for
743 user-defined type names, while built-in types are lowercase.
745 Type names ending with ``List`` are reserved for the generator, which
746 uses them for array types.
748 Command names, member names within a type, and feature names should be
749 all lower case with words separated by a hyphen.  However, some
750 existing older commands and complex types use underscore; when
751 extending them, consistency is preferred over blindly avoiding
752 underscore.
754 Event names should be ALL_CAPS with words separated by underscore.
756 Member name ``u`` and names starting with ``has-`` or ``has_`` are reserved
757 for the generator, which uses them for unions and for tracking
758 optional members.
760 Names beginning with ``x-`` used to signify "experimental".  This
761 convention has been replaced by special feature "unstable".
763 Pragmas ``command-name-exceptions`` and ``member-name-exceptions`` let
764 you violate naming rules.  Use for new code is strongly discouraged. See
765 `Pragma directives`_ for details.
768 Downstream extensions
769 ---------------------
771 QAPI schema names that are externally visible, say in the Client JSON
772 Protocol, need to be managed with care.  Names starting with a
773 downstream prefix of the form __RFQDN_ are reserved for the downstream
774 who controls the valid, reverse fully qualified domain name RFQDN.
775 RFQDN may only contain ASCII letters, digits, hyphen and period.
777 Example: Red Hat, Inc. controls redhat.com, and may therefore add a
778 downstream command ``__com.redhat_drive-mirror``.
781 Configuring the schema
782 ----------------------
784 Syntax::
786     COND = STRING
787          | { 'all: [ COND, ... ] }
788          | { 'any: [ COND, ... ] }
789          | { 'not': COND }
791 All definitions take an optional 'if' member.  Its value must be a
792 string, or an object with a single member 'all', 'any' or 'not'.
794 The C code generated for the definition will then be guarded by an #if
795 preprocessing directive with an operand generated from that condition:
797  * STRING will generate defined(STRING)
798  * { 'all': [COND, ...] } will generate (COND && ...)
799  * { 'any': [COND, ...] } will generate (COND || ...)
800  * { 'not': COND } will generate !COND
802 Example: a conditional struct ::
804  { 'struct': 'IfStruct', 'data': { 'foo': 'int' },
805    'if': { 'all': [ 'CONFIG_FOO', 'HAVE_BAR' ] } }
807 gets its generated code guarded like this::
809  #if defined(CONFIG_FOO) && defined(HAVE_BAR)
810  ... generated code ...
811  #endif /* defined(HAVE_BAR) && defined(CONFIG_FOO) */
813 Individual members of complex types can also be made conditional.
814 This requires the longhand form of MEMBER.
816 Example: a struct type with unconditional member 'foo' and conditional
817 member 'bar' ::
819  { 'struct': 'IfStruct',
820    'data': { 'foo': 'int',
821              'bar': { 'type': 'int', 'if': 'IFCOND'} } }
823 A union's discriminator may not be conditional.
825 Likewise, individual enumeration values may be conditional.  This
826 requires the longhand form of ENUM-VALUE_.
828 Example: an enum type with unconditional value 'foo' and conditional
829 value 'bar' ::
831  { 'enum': 'IfEnum',
832    'data': [ 'foo',
833              { 'name' : 'bar', 'if': 'IFCOND' } ] }
835 Likewise, features can be conditional.  This requires the longhand
836 form of FEATURE_.
838 Example: a struct with conditional feature 'allow-negative-numbers' ::
840  { 'struct': 'TestType',
841    'data': { 'number': 'int' },
842    'features': [ { 'name': 'allow-negative-numbers',
843                    'if': 'IFCOND' } ] }
845 Please note that you are responsible to ensure that the C code will
846 compile with an arbitrary combination of conditions, since the
847 generator is unable to check it at this point.
849 The conditions apply to introspection as well, i.e. introspection
850 shows a conditional entity only when the condition is satisfied in
851 this particular build.
854 Documentation comments
855 ----------------------
857 A multi-line comment that starts and ends with a ``##`` line is a
858 documentation comment.
860 If the documentation comment starts like ::
862     ##
863     # @SYMBOL:
865 it documents the definition of SYMBOL, else it's free-form
866 documentation.
868 See below for more on `Definition documentation`_.
870 Free-form documentation may be used to provide additional text and
871 structuring content.
874 Headings and subheadings
875 ~~~~~~~~~~~~~~~~~~~~~~~~
877 A free-form documentation comment containing a line which starts with
878 some ``=`` symbols and then a space defines a section heading::
880     ##
881     # = This is a top level heading
882     #
883     # This is a free-form comment which will go under the
884     # top level heading.
885     ##
887     ##
888     # == This is a second level heading
889     ##
891 A heading line must be the first line of the documentation
892 comment block.
894 Section headings must always be correctly nested, so you can only
895 define a third-level heading inside a second-level heading, and so on.
898 Documentation markup
899 ~~~~~~~~~~~~~~~~~~~~
901 Documentation comments can use most rST markup.  In particular,
902 a ``::`` literal block can be used for examples::
904     # ::
905     #
906     #   Text of the example, may span
907     #   multiple lines
909 ``*`` starts an itemized list::
911     # * First item, may span
912     #   multiple lines
913     # * Second item
915 You can also use ``-`` instead of ``*``.
917 A decimal number followed by ``.`` starts a numbered list::
919     # 1. First item, may span
920     #    multiple lines
921     # 2. Second item
923 The actual number doesn't matter.
925 Lists of either kind must be preceded and followed by a blank line.
926 If a list item's text spans multiple lines, then the second and
927 subsequent lines must be correctly indented to line up with the
928 first character of the first line.
930 The usual ****strong****, *\*emphasized\** and ````literal```` markup
931 should be used.  If you need a single literal ``*``, you will need to
932 backslash-escape it.
934 Use ``@foo`` to reference a name in the schema.  This is an rST
935 extension.  It is rendered the same way as ````foo````, but carries
936 additional meaning.
938 Example::
940  ##
941  # Some text foo with **bold** and *emphasis*
943  # 1. with a list
944  # 2. like that
946  # And some code:
948  # ::
950  #   $ echo foo
951  #   -> do this
952  #   <- get that
953  ##
955 For legibility, wrap text paragraphs so every line is at most 70
956 characters long.
958 Separate sentences with two spaces.
961 Definition documentation
962 ~~~~~~~~~~~~~~~~~~~~~~~~
964 Definition documentation, if present, must immediately precede the
965 definition it documents.
967 When documentation is required (see pragma_ 'doc-required'), every
968 definition must have documentation.
970 Definition documentation starts with a line naming the definition,
971 followed by an optional overview, a description of each argument (for
972 commands and events), member (for structs and unions), branch (for
973 alternates), or value (for enums), a description of each feature (if
974 any), and finally optional tagged sections.
976 Descriptions start with '\@name:'.  The description text must be
977 indented like this::
979  # @name: Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed
980  #     do eiusmod tempor incididunt ut labore et dolore magna aliqua.
982 .. FIXME The parser accepts these things in almost any order.
984 .. FIXME union branches should be described, too.
986 Extensions added after the definition was first released carry a
987 "(since x.y.z)" comment.
989 The feature descriptions must be preceded by a blank line and then a
990 line "Features:", like this::
992   #
993   # Features:
994   #
995   # @feature: Description text
997 A tagged section begins with a paragraph that starts with one of the
998 following words: "Note:"/"Notes:", "Since:", "Example:"/"Examples:",
999 "Returns:", "TODO:".  It ends with the start of a new section.
1001 The second and subsequent lines of tagged sections must be indented
1002 like this::
1004  # Note: Ut enim ad minim veniam, quis nostrud exercitation ullamco
1005  #     laboris nisi ut aliquip ex ea commodo consequat.
1007  #     Duis aute irure dolor in reprehenderit in voluptate velit esse
1008  #     cillum dolore eu fugiat nulla pariatur.
1010 A "Since: x.y.z" tagged section lists the release that introduced the
1011 definition.
1013 An "Example" or "Examples" section is rendered entirely
1014 as literal fixed-width text.  "TODO" sections are not rendered at all
1015 (they are for developers, not users of QMP).  In other sections, the
1016 text is formatted, and rST markup can be used.
1018 For example::
1020  ##
1021  # @BlockStats:
1023  # Statistics of a virtual block device or a block backing device.
1025  # @device: If the stats are for a virtual block device, the name
1026  #     corresponding to the virtual block device.
1028  # @node-name: The node name of the device.  (Since 2.3)
1030  # ... more members ...
1032  # Since: 0.14
1033  ##
1034  { 'struct': 'BlockStats',
1035    'data': {'*device': 'str', '*node-name': 'str',
1036             ... more members ... } }
1038  ##
1039  # @query-blockstats:
1041  # Query the @BlockStats for all virtual block devices.
1043  # @query-nodes: If true, the command will query all the block nodes
1044  #     ... explain, explain ...
1045  #     (Since 2.3)
1047  # Returns: A list of @BlockStats for each virtual block devices.
1049  # Since: 0.14
1051  # Example:
1053  #     -> { "execute": "query-blockstats" }
1054  #     <- {
1055  #          ... lots of output ...
1056  #        }
1057  ##
1058  { 'command': 'query-blockstats',
1059    'data': { '*query-nodes': 'bool' },
1060    'returns': ['BlockStats'] }
1063 Markup pitfalls
1064 ~~~~~~~~~~~~~~~
1066 A blank line is required between list items and paragraphs.  Without
1067 it, the list may not be recognized, resulting in garbled output.  Good
1068 example::
1070  # An event's state is modified if:
1072  # - its name matches the @name pattern, and
1073  # - if @vcpu is given, the event has the "vcpu" property.
1075 Without the blank line this would be a single paragraph.
1077 Indentation matters.  Bad example::
1079  # @none: None (no memory side cache in this proximity domain,
1080  #              or cache associativity unknown)
1081  #     (since 5.0)
1083 The last line's de-indent is wrong.  The second and subsequent lines
1084 need to line up with each other, like this::
1086  # @none: None (no memory side cache in this proximity domain,
1087  #     or cache associativity unknown)
1088  #     (since 5.0)
1090 Section tags are case-sensitive and end with a colon.  They are only
1091 recognized after a blank line.  Good example::
1094  # Since: 7.1
1096 Bad examples (all ordinary paragraphs)::
1098  # since: 7.1
1100  # Since 7.1
1102  # Since : 7.1
1104 Likewise, member descriptions require a colon.  Good example::
1106  # @interface-id: Interface ID
1108 Bad examples (all ordinary paragraphs)::
1110  # @interface-id   Interface ID
1112  # @interface-id : Interface ID
1114 Undocumented members are not flagged, yet.  Instead, the generated
1115 documentation describes them as "Not documented".  Think twice before
1116 adding more undocumented members.
1118 When you change documentation comments, please check the generated
1119 documentation comes out as intended!
1122 Client JSON Protocol introspection
1123 ==================================
1125 Clients of a Client JSON Protocol commonly need to figure out what
1126 exactly the server (QEMU) supports.
1128 For this purpose, QMP provides introspection via command
1129 query-qmp-schema.  QGA currently doesn't support introspection.
1131 While Client JSON Protocol wire compatibility should be maintained
1132 between qemu versions, we cannot make the same guarantees for
1133 introspection stability.  For example, one version of qemu may provide
1134 a non-variant optional member of a struct, and a later version rework
1135 the member to instead be non-optional and associated with a variant.
1136 Likewise, one version of qemu may list a member with open-ended type
1137 'str', and a later version could convert it to a finite set of strings
1138 via an enum type; or a member may be converted from a specific type to
1139 an alternate that represents a choice between the original type and
1140 something else.
1142 query-qmp-schema returns a JSON array of SchemaInfo objects.  These
1143 objects together describe the wire ABI, as defined in the QAPI schema.
1144 There is no specified order to the SchemaInfo objects returned; a
1145 client must search for a particular name throughout the entire array
1146 to learn more about that name, but is at least guaranteed that there
1147 will be no collisions between type, command, and event names.
1149 However, the SchemaInfo can't reflect all the rules and restrictions
1150 that apply to QMP.  It's interface introspection (figuring out what's
1151 there), not interface specification.  The specification is in the QAPI
1152 schema.  To understand how QMP is to be used, you need to study the
1153 QAPI schema.
1155 Like any other command, query-qmp-schema is itself defined in the QAPI
1156 schema, along with the SchemaInfo type.  This text attempts to give an
1157 overview how things work.  For details you need to consult the QAPI
1158 schema.
1160 SchemaInfo objects have common members "name", "meta-type",
1161 "features", and additional variant members depending on the value of
1162 meta-type.
1164 Each SchemaInfo object describes a wire ABI entity of a certain
1165 meta-type: a command, event or one of several kinds of type.
1167 SchemaInfo for commands and events have the same name as in the QAPI
1168 schema.
1170 Command and event names are part of the wire ABI, but type names are
1171 not.  Therefore, the SchemaInfo for types have auto-generated
1172 meaningless names.  For readability, the examples in this section use
1173 meaningful type names instead.
1175 Optional member "features" exposes the entity's feature strings as a
1176 JSON array of strings.
1178 To examine a type, start with a command or event using it, then follow
1179 references by name.
1181 QAPI schema definitions not reachable that way are omitted.
1183 The SchemaInfo for a command has meta-type "command", and variant
1184 members "arg-type", "ret-type" and "allow-oob".  On the wire, the
1185 "arguments" member of a client's "execute" command must conform to the
1186 object type named by "arg-type".  The "return" member that the server
1187 passes in a success response conforms to the type named by "ret-type".
1188 When "allow-oob" is true, it means the command supports out-of-band
1189 execution.  It defaults to false.
1191 If the command takes no arguments, "arg-type" names an object type
1192 without members.  Likewise, if the command returns nothing, "ret-type"
1193 names an object type without members.
1195 Example: the SchemaInfo for command query-qmp-schema ::
1197  { "name": "query-qmp-schema", "meta-type": "command",
1198    "arg-type": "q_empty", "ret-type": "SchemaInfoList" }
1200    Type "q_empty" is an automatic object type without members, and type
1201    "SchemaInfoList" is the array of SchemaInfo type.
1203 The SchemaInfo for an event has meta-type "event", and variant member
1204 "arg-type".  On the wire, a "data" member that the server passes in an
1205 event conforms to the object type named by "arg-type".
1207 If the event carries no additional information, "arg-type" names an
1208 object type without members.  The event may not have a data member on
1209 the wire then.
1211 Each command or event defined with 'data' as MEMBERS object in the
1212 QAPI schema implicitly defines an object type.
1214 Example: the SchemaInfo for EVENT_C from section Events_ ::
1216     { "name": "EVENT_C", "meta-type": "event",
1217       "arg-type": "q_obj-EVENT_C-arg" }
1219     Type "q_obj-EVENT_C-arg" is an implicitly defined object type with
1220     the two members from the event's definition.
1222 The SchemaInfo for struct and union types has meta-type "object" and
1223 variant member "members".
1225 The SchemaInfo for a union type additionally has variant members "tag"
1226 and "variants".
1228 "members" is a JSON array describing the object's common members, if
1229 any.  Each element is a JSON object with members "name" (the member's
1230 name), "type" (the name of its type), "features" (a JSON array of
1231 feature strings), and "default".  The latter two are optional.  The
1232 member is optional if "default" is present.  Currently, "default" can
1233 only have value null.  Other values are reserved for future
1234 extensions.  The "members" array is in no particular order; clients
1235 must search the entire object when learning whether a particular
1236 member is supported.
1238 Example: the SchemaInfo for MyType from section `Struct types`_ ::
1240     { "name": "MyType", "meta-type": "object",
1241       "members": [
1242           { "name": "member1", "type": "str" },
1243           { "name": "member2", "type": "int" },
1244           { "name": "member3", "type": "str", "default": null } ] }
1246 "features" exposes the command's feature strings as a JSON array of
1247 strings.
1249 Example: the SchemaInfo for TestType from section Features_::
1251     { "name": "TestType", "meta-type": "object",
1252       "members": [
1253           { "name": "number", "type": "int" } ],
1254       "features": ["allow-negative-numbers"] }
1256 "tag" is the name of the common member serving as type tag.
1257 "variants" is a JSON array describing the object's variant members.
1258 Each element is a JSON object with members "case" (the value of type
1259 tag this element applies to) and "type" (the name of an object type
1260 that provides the variant members for this type tag value).  The
1261 "variants" array is in no particular order, and is not guaranteed to
1262 list cases in the same order as the corresponding "tag" enum type.
1264 Example: the SchemaInfo for union BlockdevOptions from section
1265 `Union types`_ ::
1267     { "name": "BlockdevOptions", "meta-type": "object",
1268       "members": [
1269           { "name": "driver", "type": "BlockdevDriver" },
1270           { "name": "read-only", "type": "bool", "default": null } ],
1271       "tag": "driver",
1272       "variants": [
1273           { "case": "file", "type": "BlockdevOptionsFile" },
1274           { "case": "qcow2", "type": "BlockdevOptionsQcow2" } ] }
1276 Note that base types are "flattened": its members are included in the
1277 "members" array.
1279 The SchemaInfo for an alternate type has meta-type "alternate", and
1280 variant member "members".  "members" is a JSON array.  Each element is
1281 a JSON object with member "type", which names a type.  Values of the
1282 alternate type conform to exactly one of its member types.  There is
1283 no guarantee on the order in which "members" will be listed.
1285 Example: the SchemaInfo for BlockdevRef from section `Alternate types`_ ::
1287     { "name": "BlockdevRef", "meta-type": "alternate",
1288       "members": [
1289           { "type": "BlockdevOptions" },
1290           { "type": "str" } ] }
1292 The SchemaInfo for an array type has meta-type "array", and variant
1293 member "element-type", which names the array's element type.  Array
1294 types are implicitly defined.  For convenience, the array's name may
1295 resemble the element type; however, clients should examine member
1296 "element-type" instead of making assumptions based on parsing member
1297 "name".
1299 Example: the SchemaInfo for ['str'] ::
1301     { "name": "[str]", "meta-type": "array",
1302       "element-type": "str" }
1304 The SchemaInfo for an enumeration type has meta-type "enum" and
1305 variant member "members".
1307 "members" is a JSON array describing the enumeration values.  Each
1308 element is a JSON object with member "name" (the member's name), and
1309 optionally "features" (a JSON array of feature strings).  The
1310 "members" array is in no particular order; clients must search the
1311 entire array when learning whether a particular value is supported.
1313 Example: the SchemaInfo for MyEnum from section `Enumeration types`_ ::
1315     { "name": "MyEnum", "meta-type": "enum",
1316       "members": [
1317         { "name": "value1" },
1318         { "name": "value2" },
1319         { "name": "value3" }
1320       ] }
1322 The SchemaInfo for a built-in type has the same name as the type in
1323 the QAPI schema (see section `Built-in Types`_), with one exception
1324 detailed below.  It has variant member "json-type" that shows how
1325 values of this type are encoded on the wire.
1327 Example: the SchemaInfo for str ::
1329     { "name": "str", "meta-type": "builtin", "json-type": "string" }
1331 The QAPI schema supports a number of integer types that only differ in
1332 how they map to C.  They are identical as far as SchemaInfo is
1333 concerned.  Therefore, they get all mapped to a single type "int" in
1334 SchemaInfo.
1336 As explained above, type names are not part of the wire ABI.  Not even
1337 the names of built-in types.  Clients should examine member
1338 "json-type" instead of hard-coding names of built-in types.
1341 Compatibility considerations
1342 ============================
1344 Maintaining backward compatibility at the Client JSON Protocol level
1345 while evolving the schema requires some care.  This section is about
1346 syntactic compatibility, which is necessary, but not sufficient, for
1347 actual compatibility.
1349 Clients send commands with argument data, and receive command
1350 responses with return data and events with event data.
1352 Adding opt-in functionality to the send direction is backwards
1353 compatible: adding commands, optional arguments, enumeration values,
1354 union and alternate branches; turning an argument type into an
1355 alternate of that type; making mandatory arguments optional.  Clients
1356 oblivious of the new functionality continue to work.
1358 Incompatible changes include removing commands, command arguments,
1359 enumeration values, union and alternate branches, adding mandatory
1360 command arguments, and making optional arguments mandatory.
1362 The specified behavior of an absent optional argument should remain
1363 the same.  With proper documentation, this policy still allows some
1364 flexibility; for example, when an optional 'buffer-size' argument is
1365 specified to default to a sensible buffer size, the actual default
1366 value can still be changed.  The specified default behavior is not the
1367 exact size of the buffer, only that the default size is sensible.
1369 Adding functionality to the receive direction is generally backwards
1370 compatible: adding events, adding return and event data members.
1371 Clients are expected to ignore the ones they don't know.
1373 Removing "unreachable" stuff like events that can't be triggered
1374 anymore, optional return or event data members that can't be sent
1375 anymore, and return or event data member (enumeration) values that
1376 can't be sent anymore makes no difference to clients, except for
1377 introspection.  The latter can conceivably confuse clients, so tread
1378 carefully.
1380 Incompatible changes include removing return and event data members.
1382 Any change to a command definition's 'data' or one of the types used
1383 there (recursively) needs to consider send direction compatibility.
1385 Any change to a command definition's 'return', an event definition's
1386 'data', or one of the types used there (recursively) needs to consider
1387 receive direction compatibility.
1389 Any change to types used in both contexts need to consider both.
1391 Enumeration type values and complex and alternate type members may be
1392 reordered freely.  For enumerations and alternate types, this doesn't
1393 affect the wire encoding.  For complex types, this might make the
1394 implementation emit JSON object members in a different order, which
1395 the Client JSON Protocol permits.
1397 Since type names are not visible in the Client JSON Protocol, types
1398 may be freely renamed.  Even certain refactorings are invisible, such
1399 as splitting members from one type into a common base type.
1402 Code generation
1403 ===============
1405 The QAPI code generator qapi-gen.py generates code and documentation
1406 from the schema.  Together with the core QAPI libraries, this code
1407 provides everything required to take JSON commands read in by a Client
1408 JSON Protocol server, unmarshal the arguments into the underlying C
1409 types, call into the corresponding C function, map the response back
1410 to a Client JSON Protocol response to be returned to the user, and
1411 introspect the commands.
1413 As an example, we'll use the following schema, which describes a
1414 single complex user-defined type, along with command which takes a
1415 list of that type as a parameter, and returns a single element of that
1416 type.  The user is responsible for writing the implementation of
1417 qmp_my_command(); everything else is produced by the generator. ::
1419     $ cat example-schema.json
1420     { 'struct': 'UserDefOne',
1421       'data': { 'integer': 'int', '*string': 'str', '*flag': 'bool' } }
1423     { 'command': 'my-command',
1424       'data': { 'arg1': ['UserDefOne'] },
1425       'returns': 'UserDefOne' }
1427     { 'event': 'MY_EVENT' }
1429 We run qapi-gen.py like this::
1431     $ python scripts/qapi-gen.py --output-dir="qapi-generated" \
1432     --prefix="example-" example-schema.json
1434 For a more thorough look at generated code, the testsuite includes
1435 tests/qapi-schema/qapi-schema-tests.json that covers more examples of
1436 what the generator will accept, and compiles the resulting C code as
1437 part of 'make check-unit'.
1440 Code generated for QAPI types
1441 -----------------------------
1443 The following files are created:
1445  ``$(prefix)qapi-types.h``
1446      C types corresponding to types defined in the schema
1448  ``$(prefix)qapi-types.c``
1449      Cleanup functions for the above C types
1451 The $(prefix) is an optional parameter used as a namespace to keep the
1452 generated code from one schema/code-generation separated from others so code
1453 can be generated/used from multiple schemas without clobbering previously
1454 created code.
1456 Example::
1458     $ cat qapi-generated/example-qapi-types.h
1459     [Uninteresting stuff omitted...]
1461     #ifndef EXAMPLE_QAPI_TYPES_H
1462     #define EXAMPLE_QAPI_TYPES_H
1464     #include "qapi/qapi-builtin-types.h"
1466     typedef struct UserDefOne UserDefOne;
1468     typedef struct UserDefOneList UserDefOneList;
1470     typedef struct q_obj_my_command_arg q_obj_my_command_arg;
1472     struct UserDefOne {
1473         int64_t integer;
1474         char *string;
1475         bool has_flag;
1476         bool flag;
1477     };
1479     void qapi_free_UserDefOne(UserDefOne *obj);
1480     G_DEFINE_AUTOPTR_CLEANUP_FUNC(UserDefOne, qapi_free_UserDefOne)
1482     struct UserDefOneList {
1483         UserDefOneList *next;
1484         UserDefOne *value;
1485     };
1487     void qapi_free_UserDefOneList(UserDefOneList *obj);
1488     G_DEFINE_AUTOPTR_CLEANUP_FUNC(UserDefOneList, qapi_free_UserDefOneList)
1490     struct q_obj_my_command_arg {
1491         UserDefOneList *arg1;
1492     };
1494     #endif /* EXAMPLE_QAPI_TYPES_H */
1495     $ cat qapi-generated/example-qapi-types.c
1496     [Uninteresting stuff omitted...]
1498     void qapi_free_UserDefOne(UserDefOne *obj)
1499     {
1500         Visitor *v;
1502         if (!obj) {
1503             return;
1504         }
1506         v = qapi_dealloc_visitor_new();
1507         visit_type_UserDefOne(v, NULL, &obj, NULL);
1508         visit_free(v);
1509     }
1511     void qapi_free_UserDefOneList(UserDefOneList *obj)
1512     {
1513         Visitor *v;
1515         if (!obj) {
1516             return;
1517         }
1519         v = qapi_dealloc_visitor_new();
1520         visit_type_UserDefOneList(v, NULL, &obj, NULL);
1521         visit_free(v);
1522     }
1524     [Uninteresting stuff omitted...]
1526 For a modular QAPI schema (see section `Include directives`_), code for
1527 each sub-module SUBDIR/SUBMODULE.json is actually generated into ::
1529  SUBDIR/$(prefix)qapi-types-SUBMODULE.h
1530  SUBDIR/$(prefix)qapi-types-SUBMODULE.c
1532 If qapi-gen.py is run with option --builtins, additional files are
1533 created:
1535  ``qapi-builtin-types.h``
1536      C types corresponding to built-in types
1538  ``qapi-builtin-types.c``
1539      Cleanup functions for the above C types
1542 Code generated for visiting QAPI types
1543 --------------------------------------
1545 These are the visitor functions used to walk through and convert
1546 between a native QAPI C data structure and some other format (such as
1547 QObject); the generated functions are named visit_type_FOO() and
1548 visit_type_FOO_members().
1550 The following files are generated:
1552  ``$(prefix)qapi-visit.c``
1553      Visitor function for a particular C type, used to automagically
1554      convert QObjects into the corresponding C type and vice-versa, as
1555      well as for deallocating memory for an existing C type
1557  ``$(prefix)qapi-visit.h``
1558      Declarations for previously mentioned visitor functions
1560 Example::
1562     $ cat qapi-generated/example-qapi-visit.h
1563     [Uninteresting stuff omitted...]
1565     #ifndef EXAMPLE_QAPI_VISIT_H
1566     #define EXAMPLE_QAPI_VISIT_H
1568     #include "qapi/qapi-builtin-visit.h"
1569     #include "example-qapi-types.h"
1572     bool visit_type_UserDefOne_members(Visitor *v, UserDefOne *obj, Error **errp);
1574     bool visit_type_UserDefOne(Visitor *v, const char *name,
1575                      UserDefOne **obj, Error **errp);
1577     bool visit_type_UserDefOneList(Visitor *v, const char *name,
1578                      UserDefOneList **obj, Error **errp);
1580     bool visit_type_q_obj_my_command_arg_members(Visitor *v, q_obj_my_command_arg *obj, Error **errp);
1582     #endif /* EXAMPLE_QAPI_VISIT_H */
1583     $ cat qapi-generated/example-qapi-visit.c
1584     [Uninteresting stuff omitted...]
1586     bool visit_type_UserDefOne_members(Visitor *v, UserDefOne *obj, Error **errp)
1587     {
1588         bool has_string = !!obj->string;
1590         if (!visit_type_int(v, "integer", &obj->integer, errp)) {
1591             return false;
1592         }
1593         if (visit_optional(v, "string", &has_string)) {
1594             if (!visit_type_str(v, "string", &obj->string, errp)) {
1595                 return false;
1596             }
1597         }
1598         if (visit_optional(v, "flag", &obj->has_flag)) {
1599             if (!visit_type_bool(v, "flag", &obj->flag, errp)) {
1600                 return false;
1601             }
1602         }
1603         return true;
1604     }
1606     bool visit_type_UserDefOne(Visitor *v, const char *name,
1607                      UserDefOne **obj, Error **errp)
1608     {
1609         bool ok = false;
1611         if (!visit_start_struct(v, name, (void **)obj, sizeof(UserDefOne), errp)) {
1612             return false;
1613         }
1614         if (!*obj) {
1615             /* incomplete */
1616             assert(visit_is_dealloc(v));
1617             ok = true;
1618             goto out_obj;
1619         }
1620         if (!visit_type_UserDefOne_members(v, *obj, errp)) {
1621             goto out_obj;
1622         }
1623         ok = visit_check_struct(v, errp);
1624     out_obj:
1625         visit_end_struct(v, (void **)obj);
1626         if (!ok && visit_is_input(v)) {
1627             qapi_free_UserDefOne(*obj);
1628             *obj = NULL;
1629         }
1630         return ok;
1631     }
1633     bool visit_type_UserDefOneList(Visitor *v, const char *name,
1634                      UserDefOneList **obj, Error **errp)
1635     {
1636         bool ok = false;
1637         UserDefOneList *tail;
1638         size_t size = sizeof(**obj);
1640         if (!visit_start_list(v, name, (GenericList **)obj, size, errp)) {
1641             return false;
1642         }
1644         for (tail = *obj; tail;
1645              tail = (UserDefOneList *)visit_next_list(v, (GenericList *)tail, size)) {
1646             if (!visit_type_UserDefOne(v, NULL, &tail->value, errp)) {
1647                 goto out_obj;
1648             }
1649         }
1651         ok = visit_check_list(v, errp);
1652     out_obj:
1653         visit_end_list(v, (void **)obj);
1654         if (!ok && visit_is_input(v)) {
1655             qapi_free_UserDefOneList(*obj);
1656             *obj = NULL;
1657         }
1658         return ok;
1659     }
1661     bool visit_type_q_obj_my_command_arg_members(Visitor *v, q_obj_my_command_arg *obj, Error **errp)
1662     {
1663         if (!visit_type_UserDefOneList(v, "arg1", &obj->arg1, errp)) {
1664             return false;
1665         }
1666         return true;
1667     }
1669     [Uninteresting stuff omitted...]
1671 For a modular QAPI schema (see section `Include directives`_), code for
1672 each sub-module SUBDIR/SUBMODULE.json is actually generated into ::
1674  SUBDIR/$(prefix)qapi-visit-SUBMODULE.h
1675  SUBDIR/$(prefix)qapi-visit-SUBMODULE.c
1677 If qapi-gen.py is run with option --builtins, additional files are
1678 created:
1680  ``qapi-builtin-visit.h``
1681      Visitor functions for built-in types
1683  ``qapi-builtin-visit.c``
1684      Declarations for these visitor functions
1687 Code generated for commands
1688 ---------------------------
1690 These are the marshaling/dispatch functions for the commands defined
1691 in the schema.  The generated code provides qmp_marshal_COMMAND(), and
1692 declares qmp_COMMAND() that the user must implement.
1694 The following files are generated:
1696  ``$(prefix)qapi-commands.c``
1697      Command marshal/dispatch functions for each QMP command defined in
1698      the schema
1700  ``$(prefix)qapi-commands.h``
1701      Function prototypes for the QMP commands specified in the schema
1703  ``$(prefix)qapi-commands.trace-events``
1704      Trace event declarations, see :ref:`tracing`.
1706  ``$(prefix)qapi-init-commands.h``
1707      Command initialization prototype
1709  ``$(prefix)qapi-init-commands.c``
1710      Command initialization code
1712 Example::
1714     $ cat qapi-generated/example-qapi-commands.h
1715     [Uninteresting stuff omitted...]
1717     #ifndef EXAMPLE_QAPI_COMMANDS_H
1718     #define EXAMPLE_QAPI_COMMANDS_H
1720     #include "example-qapi-types.h"
1722     UserDefOne *qmp_my_command(UserDefOneList *arg1, Error **errp);
1723     void qmp_marshal_my_command(QDict *args, QObject **ret, Error **errp);
1725     #endif /* EXAMPLE_QAPI_COMMANDS_H */
1727     $ cat qapi-generated/example-qapi-commands.trace-events
1728     # AUTOMATICALLY GENERATED, DO NOT MODIFY
1730     qmp_enter_my_command(const char *json) "%s"
1731     qmp_exit_my_command(const char *result, bool succeeded) "%s %d"
1733     $ cat qapi-generated/example-qapi-commands.c
1734     [Uninteresting stuff omitted...]
1736     static void qmp_marshal_output_UserDefOne(UserDefOne *ret_in,
1737                                     QObject **ret_out, Error **errp)
1738     {
1739         Visitor *v;
1741         v = qobject_output_visitor_new_qmp(ret_out);
1742         if (visit_type_UserDefOne(v, "unused", &ret_in, errp)) {
1743             visit_complete(v, ret_out);
1744         }
1745         visit_free(v);
1746         v = qapi_dealloc_visitor_new();
1747         visit_type_UserDefOne(v, "unused", &ret_in, NULL);
1748         visit_free(v);
1749     }
1751     void qmp_marshal_my_command(QDict *args, QObject **ret, Error **errp)
1752     {
1753         Error *err = NULL;
1754         bool ok = false;
1755         Visitor *v;
1756         UserDefOne *retval;
1757         q_obj_my_command_arg arg = {0};
1759         v = qobject_input_visitor_new_qmp(QOBJECT(args));
1760         if (!visit_start_struct(v, NULL, NULL, 0, errp)) {
1761             goto out;
1762         }
1763         if (visit_type_q_obj_my_command_arg_members(v, &arg, errp)) {
1764             ok = visit_check_struct(v, errp);
1765         }
1766         visit_end_struct(v, NULL);
1767         if (!ok) {
1768             goto out;
1769         }
1771         if (trace_event_get_state_backends(TRACE_QMP_ENTER_MY_COMMAND)) {
1772             g_autoptr(GString) req_json = qobject_to_json(QOBJECT(args));
1774             trace_qmp_enter_my_command(req_json->str);
1775         }
1777         retval = qmp_my_command(arg.arg1, &err);
1778         if (err) {
1779             trace_qmp_exit_my_command(error_get_pretty(err), false);
1780             error_propagate(errp, err);
1781             goto out;
1782         }
1784         qmp_marshal_output_UserDefOne(retval, ret, errp);
1786         if (trace_event_get_state_backends(TRACE_QMP_EXIT_MY_COMMAND)) {
1787             g_autoptr(GString) ret_json = qobject_to_json(*ret);
1789             trace_qmp_exit_my_command(ret_json->str, true);
1790         }
1792     out:
1793         visit_free(v);
1794         v = qapi_dealloc_visitor_new();
1795         visit_start_struct(v, NULL, NULL, 0, NULL);
1796         visit_type_q_obj_my_command_arg_members(v, &arg, NULL);
1797         visit_end_struct(v, NULL);
1798         visit_free(v);
1799     }
1801     [Uninteresting stuff omitted...]
1802     $ cat qapi-generated/example-qapi-init-commands.h
1803     [Uninteresting stuff omitted...]
1804     #ifndef EXAMPLE_QAPI_INIT_COMMANDS_H
1805     #define EXAMPLE_QAPI_INIT_COMMANDS_H
1807     #include "qapi/qmp/dispatch.h"
1809     void example_qmp_init_marshal(QmpCommandList *cmds);
1811     #endif /* EXAMPLE_QAPI_INIT_COMMANDS_H */
1812     $ cat qapi-generated/example-qapi-init-commands.c
1813     [Uninteresting stuff omitted...]
1814     void example_qmp_init_marshal(QmpCommandList *cmds)
1815     {
1816         QTAILQ_INIT(cmds);
1818         qmp_register_command(cmds, "my-command",
1819                              qmp_marshal_my_command, 0, 0);
1820     }
1821     [Uninteresting stuff omitted...]
1823 For a modular QAPI schema (see section `Include directives`_), code for
1824 each sub-module SUBDIR/SUBMODULE.json is actually generated into::
1826  SUBDIR/$(prefix)qapi-commands-SUBMODULE.h
1827  SUBDIR/$(prefix)qapi-commands-SUBMODULE.c
1830 Code generated for events
1831 -------------------------
1833 This is the code related to events defined in the schema, providing
1834 qapi_event_send_EVENT().
1836 The following files are created:
1838  ``$(prefix)qapi-events.h``
1839      Function prototypes for each event type
1841  ``$(prefix)qapi-events.c``
1842      Implementation of functions to send an event
1844  ``$(prefix)qapi-emit-events.h``
1845      Enumeration of all event names, and common event code declarations
1847  ``$(prefix)qapi-emit-events.c``
1848      Common event code definitions
1850 Example::
1852     $ cat qapi-generated/example-qapi-events.h
1853     [Uninteresting stuff omitted...]
1855     #ifndef EXAMPLE_QAPI_EVENTS_H
1856     #define EXAMPLE_QAPI_EVENTS_H
1858     #include "qapi/util.h"
1859     #include "example-qapi-types.h"
1861     void qapi_event_send_my_event(void);
1863     #endif /* EXAMPLE_QAPI_EVENTS_H */
1864     $ cat qapi-generated/example-qapi-events.c
1865     [Uninteresting stuff omitted...]
1867     void qapi_event_send_my_event(void)
1868     {
1869         QDict *qmp;
1871         qmp = qmp_event_build_dict("MY_EVENT");
1873         example_qapi_event_emit(EXAMPLE_QAPI_EVENT_MY_EVENT, qmp);
1875         qobject_unref(qmp);
1876     }
1878     [Uninteresting stuff omitted...]
1879     $ cat qapi-generated/example-qapi-emit-events.h
1880     [Uninteresting stuff omitted...]
1882     #ifndef EXAMPLE_QAPI_EMIT_EVENTS_H
1883     #define EXAMPLE_QAPI_EMIT_EVENTS_H
1885     #include "qapi/util.h"
1887     typedef enum example_QAPIEvent {
1888         EXAMPLE_QAPI_EVENT_MY_EVENT,
1889         EXAMPLE_QAPI_EVENT__MAX,
1890     } example_QAPIEvent;
1892     #define example_QAPIEvent_str(val) \
1893         qapi_enum_lookup(&example_QAPIEvent_lookup, (val))
1895     extern const QEnumLookup example_QAPIEvent_lookup;
1897     void example_qapi_event_emit(example_QAPIEvent event, QDict *qdict);
1899     #endif /* EXAMPLE_QAPI_EMIT_EVENTS_H */
1900     $ cat qapi-generated/example-qapi-emit-events.c
1901     [Uninteresting stuff omitted...]
1903     const QEnumLookup example_QAPIEvent_lookup = {
1904         .array = (const char *const[]) {
1905             [EXAMPLE_QAPI_EVENT_MY_EVENT] = "MY_EVENT",
1906         },
1907         .size = EXAMPLE_QAPI_EVENT__MAX
1908     };
1910     [Uninteresting stuff omitted...]
1912 For a modular QAPI schema (see section `Include directives`_), code for
1913 each sub-module SUBDIR/SUBMODULE.json is actually generated into ::
1915  SUBDIR/$(prefix)qapi-events-SUBMODULE.h
1916  SUBDIR/$(prefix)qapi-events-SUBMODULE.c
1919 Code generated for introspection
1920 --------------------------------
1922 The following files are created:
1924  ``$(prefix)qapi-introspect.c``
1925      Defines a string holding a JSON description of the schema
1927  ``$(prefix)qapi-introspect.h``
1928      Declares the above string
1930 Example::
1932     $ cat qapi-generated/example-qapi-introspect.h
1933     [Uninteresting stuff omitted...]
1935     #ifndef EXAMPLE_QAPI_INTROSPECT_H
1936     #define EXAMPLE_QAPI_INTROSPECT_H
1938     #include "qapi/qmp/qlit.h"
1940     extern const QLitObject example_qmp_schema_qlit;
1942     #endif /* EXAMPLE_QAPI_INTROSPECT_H */
1943     $ cat qapi-generated/example-qapi-introspect.c
1944     [Uninteresting stuff omitted...]
1946     const QLitObject example_qmp_schema_qlit = QLIT_QLIST(((QLitObject[]) {
1947         QLIT_QDICT(((QLitDictEntry[]) {
1948             { "arg-type", QLIT_QSTR("0"), },
1949             { "meta-type", QLIT_QSTR("command"), },
1950             { "name", QLIT_QSTR("my-command"), },
1951             { "ret-type", QLIT_QSTR("1"), },
1952             {}
1953         })),
1954         QLIT_QDICT(((QLitDictEntry[]) {
1955             { "arg-type", QLIT_QSTR("2"), },
1956             { "meta-type", QLIT_QSTR("event"), },
1957             { "name", QLIT_QSTR("MY_EVENT"), },
1958             {}
1959         })),
1960         /* "0" = q_obj_my-command-arg */
1961         QLIT_QDICT(((QLitDictEntry[]) {
1962             { "members", QLIT_QLIST(((QLitObject[]) {
1963                 QLIT_QDICT(((QLitDictEntry[]) {
1964                     { "name", QLIT_QSTR("arg1"), },
1965                     { "type", QLIT_QSTR("[1]"), },
1966                     {}
1967                 })),
1968                 {}
1969             })), },
1970             { "meta-type", QLIT_QSTR("object"), },
1971             { "name", QLIT_QSTR("0"), },
1972             {}
1973         })),
1974         /* "1" = UserDefOne */
1975         QLIT_QDICT(((QLitDictEntry[]) {
1976             { "members", QLIT_QLIST(((QLitObject[]) {
1977                 QLIT_QDICT(((QLitDictEntry[]) {
1978                     { "name", QLIT_QSTR("integer"), },
1979                     { "type", QLIT_QSTR("int"), },
1980                     {}
1981                 })),
1982                 QLIT_QDICT(((QLitDictEntry[]) {
1983                     { "default", QLIT_QNULL, },
1984                     { "name", QLIT_QSTR("string"), },
1985                     { "type", QLIT_QSTR("str"), },
1986                     {}
1987                 })),
1988                 QLIT_QDICT(((QLitDictEntry[]) {
1989                     { "default", QLIT_QNULL, },
1990                     { "name", QLIT_QSTR("flag"), },
1991                     { "type", QLIT_QSTR("bool"), },
1992                     {}
1993                 })),
1994                 {}
1995             })), },
1996             { "meta-type", QLIT_QSTR("object"), },
1997             { "name", QLIT_QSTR("1"), },
1998             {}
1999         })),
2000         /* "2" = q_empty */
2001         QLIT_QDICT(((QLitDictEntry[]) {
2002             { "members", QLIT_QLIST(((QLitObject[]) {
2003                 {}
2004             })), },
2005             { "meta-type", QLIT_QSTR("object"), },
2006             { "name", QLIT_QSTR("2"), },
2007             {}
2008         })),
2009         QLIT_QDICT(((QLitDictEntry[]) {
2010             { "element-type", QLIT_QSTR("1"), },
2011             { "meta-type", QLIT_QSTR("array"), },
2012             { "name", QLIT_QSTR("[1]"), },
2013             {}
2014         })),
2015         QLIT_QDICT(((QLitDictEntry[]) {
2016             { "json-type", QLIT_QSTR("int"), },
2017             { "meta-type", QLIT_QSTR("builtin"), },
2018             { "name", QLIT_QSTR("int"), },
2019             {}
2020         })),
2021         QLIT_QDICT(((QLitDictEntry[]) {
2022             { "json-type", QLIT_QSTR("string"), },
2023             { "meta-type", QLIT_QSTR("builtin"), },
2024             { "name", QLIT_QSTR("str"), },
2025             {}
2026         })),
2027         QLIT_QDICT(((QLitDictEntry[]) {
2028             { "json-type", QLIT_QSTR("boolean"), },
2029             { "meta-type", QLIT_QSTR("builtin"), },
2030             { "name", QLIT_QSTR("bool"), },
2031             {}
2032         })),
2033         {}
2034     }));
2036     [Uninteresting stuff omitted...]