xref: /openbmc/qemu/docs/devel/qapi-code-gen.rst (revision 53dcea58)
1==================================
2How to use the QAPI code generator
3==================================
4
5..
6   Copyright IBM Corp. 2011
7   Copyright (C) 2012-2016 Red Hat, Inc.
8
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.
11
12
13Introduction
14============
15
16QAPI is a native C API within QEMU which provides management-level
17functionality to internal and external users.  For external
18users/processes, this interface is made available by a JSON-based wire
19format for the QEMU Monitor Protocol (QMP) for controlling qemu, as
20well as the QEMU Guest Agent (QGA) for communicating with the guest.
21The remainder of this document uses "Client JSON Protocol" when
22referring to the wire contents of a QMP or QGA connection.
23
24To map between Client JSON Protocol interfaces and the native C API,
25we generate C code from a QAPI schema.  This document describes the
26QAPI schema language, and how it gets mapped to the Client JSON
27Protocol and to C.  It additionally provides guidance on maintaining
28Client JSON Protocol compatibility.
29
30
31The QAPI schema language
32========================
33
34The QAPI schema defines the Client JSON Protocol's commands and
35events, as well as types used by them.  Forward references are
36allowed.
37
38It is permissible for the schema to contain additional types not used
39by any commands or events, for the side effect of generated C code
40used internally.
41
42There are several kinds of types: simple types (a number of built-in
43types, such as ``int`` and ``str``; as well as enumerations), arrays,
44complex types (structs and two flavors of unions), and alternate types
45(a choice between other types).
46
47
48Schema syntax
49-------------
50
51Syntax is loosely based on `JSON <http://www.ietf.org/rfc/rfc8259.txt>`_.
52Differences:
53
54* Comments: start with a hash character (``#``) that is not part of a
55  string, and extend to the end of the line.
56
57* Strings are enclosed in ``'single quotes'``, not ``"double quotes"``.
58
59* Strings are restricted to printable ASCII, and escape sequences to
60  just ``\\``.
61
62* Numbers and ``null`` are not supported.
63
64A second layer of syntax defines the sequences of JSON texts that are
65a correctly structured QAPI schema.  We provide a grammar for this
66syntax in an EBNF-like notation:
67
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
85
86The order of members within JSON objects does not matter unless
87explicitly noted.
88
89A QAPI schema consists of a series of top-level expressions::
90
91    SCHEMA = TOP-LEVEL-EXPR...
92
93The top-level expressions are all JSON objects.  Code and
94documentation is generated in schema definition order.  Code order
95should not matter.
96
97A top-level expressions is either a directive or a definition::
98
99    TOP-LEVEL-EXPR = DIRECTIVE | DEFINITION
100
101There are two kinds of directives and six kinds of definitions::
102
103    DIRECTIVE = INCLUDE | PRAGMA
104    DEFINITION = ENUM | STRUCT | UNION | ALTERNATE | COMMAND | EVENT
105
106These are discussed in detail below.
107
108
109Built-in Types
110--------------
111
112The following types are predefined, and map to C as follows:
113
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  ============= ============== ============================================
136
137
138Include directives
139------------------
140
141Syntax::
142
143    INCLUDE = { 'include': STRING }
144
145The QAPI schema definitions can be modularized using the 'include' directive::
146
147 { 'include': 'path/to/file.json' }
148
149The directive is evaluated recursively, and include paths are relative
150to the file using the directive.  Multiple includes of the same file
151are idempotent.
152
153As a matter of style, it is a good idea to have all files be
154self-contained, but at the moment, nothing prevents an included file
155from making a forward reference to a type that is only introduced by
156an outer file.  The parser may be made stricter in the future to
157prevent incomplete include files.
158
159.. _pragma:
160
161Pragma directives
162-----------------
163
164Syntax::
165
166    PRAGMA = { 'pragma': {
167                   '*doc-required': BOOL,
168                   '*command-name-exceptions': [ STRING, ... ],
169                   '*command-returns-exceptions': [ STRING, ... ],
170                   '*member-name-exceptions': [ STRING, ... ] } }
171
172The pragma directive lets you control optional generator behavior.
173
174Pragma's scope is currently the complete schema.  Setting the same
175pragma to different values in parts of the schema doesn't work.
176
177Pragma 'doc-required' takes a boolean value.  If true, documentation
178is required.  Default is false.
179
180Pragma 'command-name-exceptions' takes a list of commands whose names
181may contain ``"_"`` instead of ``"-"``.  Default is none.
182
183Pragma 'command-returns-exceptions' takes a list of commands that may
184violate the rules on permitted return types.  Default is none.
185
186Pragma 'member-name-exceptions' takes a list of types whose member
187names may contain uppercase letters, and ``"_"`` instead of ``"-"``.
188Default is none.
189
190.. _ENUM-VALUE:
191
192Enumeration types
193-----------------
194
195Syntax::
196
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 }
206
207Member 'enum' names the enum type.
208
209Each member of the 'data' array defines a value of the enumeration
210type.  The form STRING is shorthand for :code:`{ 'name': STRING }`.  The
211'name' values must be be distinct.
212
213Example::
214
215 { 'enum': 'MyEnum', 'data': [ 'value1', 'value2', 'value3' ] }
216
217Nothing prevents an empty enumeration, although it is probably not
218useful.
219
220On the wire, an enumeration type's value is represented by its
221(string) name.  In C, it's represented by an enumeration constant.
222These are of the form PREFIX_NAME, where PREFIX is derived from the
223enumeration type's name, and NAME from the value's name.  For the
224example above, the generator maps 'MyEnum' to MY_ENUM and 'value1' to
225VALUE1, resulting in the enumeration constant MY_ENUM_VALUE1.  The
226optional 'prefix' member overrides PREFIX.
227
228The generated C enumeration constants have values 0, 1, ..., N-1 (in
229QAPI schema order), where N is the number of values.  There is an
230additional enumeration constant PREFIX__MAX with value N.
231
232Do not use string or an integer type when an enumeration type can do
233the job satisfactorily.
234
235The optional 'if' member specifies a conditional.  See `Configuring the
236schema`_ below for more on this.
237
238The optional 'features' member specifies features.  See Features_
239below for more on this.
240
241
242.. _TYPE-REF:
243
244Type references and array types
245-------------------------------
246
247Syntax::
248
249    TYPE-REF = STRING | ARRAY-TYPE
250    ARRAY-TYPE = [ STRING ]
251
252A string denotes the type named by the string.
253
254A one-element array containing a string denotes an array of the type
255named by the string.  Example: ``['int']`` denotes an array of ``int``.
256
257
258Struct types
259------------
260
261Syntax::
262
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 }
273
274Member 'struct' names the struct type.
275
276Each MEMBER of the 'data' object defines a member of the struct type.
277
278.. _MEMBERS:
279
280The MEMBER's STRING name consists of an optional ``*`` prefix and the
281struct member name.  If ``*`` is present, the member is optional.
282
283The MEMBER's value defines its properties, in particular its type.
284The form TYPE-REF_ is shorthand for :code:`{ 'type': TYPE-REF }`.
285
286Example::
287
288 { 'struct': 'MyType',
289   'data': { 'member1': 'str', 'member2': ['int'], '*member3': 'str' } }
290
291A struct type corresponds to a struct in C, and an object in JSON.
292The C struct's members are generated in QAPI schema order.
293
294The optional 'base' member names a struct type whose members are to be
295included in this type.  They go first in the C struct.
296
297Example::
298
299 { 'struct': 'BlockdevOptionsGenericFormat',
300   'data': { 'file': 'str' } }
301 { 'struct': 'BlockdevOptionsGenericCOWFormat',
302   'base': 'BlockdevOptionsGenericFormat',
303   'data': { '*backing': 'str' } }
304
305An example BlockdevOptionsGenericCOWFormat object on the wire could use
306both members like this::
307
308 { "file": "/some/place/my-image",
309   "backing": "/some/place/my-backing-file" }
310
311The optional 'if' member specifies a conditional.  See `Configuring
312the schema`_ below for more on this.
313
314The optional 'features' member specifies features.  See Features_
315below for more on this.
316
317
318Union types
319-----------
320
321Syntax::
322
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 }
332
333Member 'union' names the union type.
334
335The 'base' member defines the common members.  If it is a MEMBERS_
336object, it defines common members just like a struct type's 'data'
337member defines struct type members.  If it is a STRING, it names a
338struct type whose members are the common members.
339
340Member 'discriminator' must name a non-optional enum-typed member of
341the base struct.  That member's value selects a branch by its name.
342If no such branch exists, an empty branch is assumed.
343
344Each BRANCH of the 'data' object defines a branch of the union.  A
345union must have at least one branch.
346
347The BRANCH's STRING name is the branch name.  It must be a value of
348the discriminator enum type.
349
350The BRANCH's value defines the branch's properties, in particular its
351type.  The type must a struct type.  The form TYPE-REF_ is shorthand
352for :code:`{ 'type': TYPE-REF }`.
353
354In the Client JSON Protocol, a union is represented by an object with
355the common members (from the base type) and the selected branch's
356members.  The two sets of member names must be disjoint.
357
358Example::
359
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' } }
366
367Resulting in these JSON objects::
368
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 }
373
374The order of branches need not match the order of the enum values.
375The branches need not cover all possible enum values.  In the
376resulting generated C data types, a union is represented as a struct
377with the base members in QAPI schema order, and then a union of
378structures for each branch of the struct.
379
380The optional 'if' member specifies a conditional.  See `Configuring
381the schema`_ below for more on this.
382
383The optional 'features' member specifies features.  See Features_
384below for more on this.
385
386
387Alternate types
388---------------
389
390Syntax::
391
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 }
399
400Member 'alternate' names the alternate type.
401
402Each ALTERNATIVE of the 'data' object defines a branch of the
403alternate.  An alternate must have at least one branch.
404
405The ALTERNATIVE's STRING name is the branch name.
406
407The ALTERNATIVE's value defines the branch's properties, in particular
408its type.  The form STRING is shorthand for :code:`{ 'type': STRING }`.
409
410Example::
411
412 { 'alternate': 'BlockdevRef',
413   'data': { 'definition': 'BlockdevOptions',
414             'reference': 'str' } }
415
416An alternate type is like a union type, except there is no
417discriminator on the wire.  Instead, the branch to use is inferred
418from the value.  An alternate can only express a choice between types
419represented differently on the wire.
420
421If a branch is typed as the 'bool' built-in, the alternate accepts
422true and false; if it is typed as any of the various numeric
423built-ins, it accepts a JSON number; if it is typed as a 'str'
424built-in or named enum type, it accepts a JSON string; if it is typed
425as the 'null' built-in, it accepts JSON null; and if it is typed as a
426complex type (struct or union), it accepts a JSON object.
427
428The example alternate declaration above allows using both of the
429following example objects::
430
431 { "file": "my_existing_block_device_id" }
432 { "file": { "driver": "file",
433             "read-only": false,
434             "filename": "/tmp/mydisk.qcow2" } }
435
436The optional 'if' member specifies a conditional.  See `Configuring
437the schema`_ below for more on this.
438
439The optional 'features' member specifies features.  See Features_
440below for more on this.
441
442
443Commands
444--------
445
446Syntax::
447
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 }
463
464Member 'command' names the command.
465
466Member 'data' defines the arguments.  It defaults to an empty MEMBERS_
467object.
468
469If 'data' is a MEMBERS_ object, then MEMBERS defines arguments just
470like a struct type's 'data' defines struct type members.
471
472If 'data' is a STRING, then STRING names a complex type whose members
473are the arguments.  A union type requires ``'boxed': true``.
474
475Member 'returns' defines the command's return type.  It defaults to an
476empty struct type.  It must normally be a complex type or an array of
477a complex type.  To return anything else, the command must be listed
478in pragma 'commands-returns-exceptions'.  If you do this, extending
479the command to return additional information will be harder.  Use of
480the pragma for new commands is strongly discouraged.
481
482A command's error responses are not specified in the QAPI schema.
483Error conditions should be documented in comments.
484
485In the Client JSON Protocol, the value of the "execute" or "exec-oob"
486member is the command name.  The value of the "arguments" member then
487has to conform to the arguments, and the value of the success
488response's "return" member will conform to the return type.
489
490Some example commands::
491
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' ] }
497
498which would validate this Client JSON Protocol transaction::
499
500 => { "execute": "my-first-command",
501      "arguments": { "arg1": "hello" } }
502 <= { "return": { } }
503 => { "execute": "my-second-command" }
504 <= { "return": [ { "value": "one" }, { } ] }
505
506The generator emits a prototype for the C function implementing the
507command.  The function itself needs to be written by hand.  See
508section `Code generated for commands`_ for examples.
509
510The function returns the return type.  When member 'boxed' is absent,
511it takes the command arguments as arguments one by one, in QAPI schema
512order.  Else it takes them wrapped in the C struct generated for the
513complex argument type.  It takes an additional ``Error **`` argument in
514either case.
515
516The generator also emits a marshalling function that extracts
517arguments for the user's function out of an input QDict, calls the
518user's function, and if it succeeded, builds an output QObject from
519its return value.  This is for use by the QMP monitor core.
520
521In rare cases, QAPI cannot express a type-safe representation of a
522corresponding Client JSON Protocol command.  You then have to suppress
523generation of a marshalling function by including a member 'gen' with
524boolean value false, and instead write your own function.  For
525example::
526
527 { 'command': 'netdev_add',
528   'data': {'type': 'str', 'id': 'str'},
529   'gen': false }
530
531Please try to avoid adding new commands that rely on this, and instead
532use type-safe unions.
533
534Normally, the QAPI schema is used to describe synchronous exchanges,
535where a response is expected.  But in some cases, the action of a
536command is expected to change state in a way that a successful
537response is not possible (although the command will still return an
538error object on failure).  When a successful reply is not possible,
539the command definition includes the optional member 'success-response'
540with boolean value false.  So far, only QGA makes use of this member.
541
542Member 'allow-oob' declares whether the command supports out-of-band
543(OOB) execution.  It defaults to false.  For example::
544
545 { 'command': 'migrate_recover',
546   'data': { 'uri': 'str' }, 'allow-oob': true }
547
548See qmp-spec.txt for out-of-band execution syntax and semantics.
549
550Commands supporting out-of-band execution can still be executed
551in-band.
552
553When a command is executed in-band, its handler runs in the main
554thread with the BQL held.
555
556When a command is executed out-of-band, its handler runs in a
557dedicated monitor I/O thread with the BQL *not* held.
558
559An OOB-capable command handler must satisfy the following conditions:
560
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.
568
569The restrictions on locking limit access to shared state.  Such access
570requires synchronization, but OOB commands can't take the BQL or any
571other "slow" lock.
572
573When in doubt, do not implement OOB execution support.
574
575Member 'allow-preconfig' declares whether the command is available
576before the machine is built.  It defaults to false.  For example::
577
578 { 'enum': 'QMPCapability',
579   'data': [ 'oob' ] }
580 { 'command': 'qmp_capabilities',
581   'data': { '*enable': [ 'QMPCapability' ] },
582   'allow-preconfig': true }
583
584QMP is available before the machine is built only when QEMU was
585started with --preconfig.
586
587Member 'coroutine' tells the QMP dispatcher whether the command handler
588is safe to be run in a coroutine.  It defaults to false.  If it is true,
589the command handler is called from coroutine context and may yield while
590waiting for an external event (such as I/O completion) in order to avoid
591blocking the guest and other background operations.
592
593Coroutine safety can be hard to prove, similar to thread safety.  Common
594pitfalls are:
595
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.
599
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.
604
605Since the command handler may assume coroutine context, any callers
606other than the QMP dispatcher must also call it in coroutine context.
607In particular, HMP commands calling such a QMP command handler must be
608marked ``.coroutine = true`` in hmp-commands.hx.
609
610It is an error to specify both ``'coroutine': true`` and ``'allow-oob': true``
611for a command.  We don't currently have a use case for both together and
612without a use case, it's not entirely clear what the semantics should
613be.
614
615The optional 'if' member specifies a conditional.  See `Configuring
616the schema`_ below for more on this.
617
618The optional 'features' member specifies features.  See Features_
619below for more on this.
620
621
622Events
623------
624
625Syntax::
626
627    EVENT = { 'event': STRING,
628              (
629              '*data': ( MEMBERS | STRING ),
630              |
631              'data': STRING,
632              'boxed': true,
633              )
634              '*if': COND,
635              '*features': FEATURES }
636
637Member 'event' names the event.  This is the event name used in the
638Client JSON Protocol.
639
640Member 'data' defines the event-specific data.  It defaults to an
641empty MEMBERS object.
642
643If 'data' is a MEMBERS object, then MEMBERS defines event-specific
644data just like a struct type's 'data' defines struct type members.
645
646If 'data' is a STRING, then STRING names a complex type whose members
647are the event-specific data.  A union type requires ``'boxed': true``.
648
649An example event is::
650
651 { 'event': 'EVENT_C',
652   'data': { '*a': 'int', 'b': 'str' } }
653
654Resulting in this JSON object::
655
656 { "event": "EVENT_C",
657   "data": { "b": "test string" },
658   "timestamp": { "seconds": 1267020223, "microseconds": 435656 } }
659
660The generator emits a function to send the event.  When member 'boxed'
661is absent, it takes event-specific data one by one, in QAPI schema
662order.  Else it takes them wrapped in the C struct generated for the
663complex type.  See section `Code generated for events`_ for examples.
664
665The optional 'if' member specifies a conditional.  See `Configuring
666the schema`_ below for more on this.
667
668The optional 'features' member specifies features.  See Features_
669below for more on this.
670
671
672.. _FEATURE:
673
674Features
675--------
676
677Syntax::
678
679    FEATURES = [ FEATURE, ... ]
680    FEATURE = STRING
681            | { 'name': STRING, '*if': COND }
682
683Sometimes, the behaviour of QEMU changes compatibly, but without a
684change in the QMP syntax (usually by allowing values or operations
685that previously resulted in an error).  QMP clients may still need to
686know whether the extension is available.
687
688For this purpose, a list of features can be specified for a command or
689struct type.  Each list member can either be ``{ 'name': STRING, '*if':
690COND }``, or STRING, which is shorthand for ``{ 'name': STRING }``.
691
692The optional 'if' member specifies a conditional.  See `Configuring
693the schema`_ below for more on this.
694
695Example::
696
697 { 'struct': 'TestType',
698   'data': { 'number': 'int' },
699   'features': [ 'allow-negative-numbers' ] }
700
701The feature strings are exposed to clients in introspection, as
702explained in section `Client JSON Protocol introspection`_.
703
704Intended use is to have each feature string signal that this build of
705QEMU shows a certain behaviour.
706
707
708Special features
709~~~~~~~~~~~~~~~~
710
711Feature "deprecated" marks a command, event, enum value, or struct
712member as deprecated.  It is not supported elsewhere so far.
713Interfaces so marked may be withdrawn in future releases in accordance
714with QEMU's deprecation policy.
715
716
717Naming rules and reserved names
718-------------------------------
719
720All names must begin with a letter, and contain only ASCII letters,
721digits, hyphen, and underscore.  There are two exceptions: enum values
722may start with a digit, and names that are downstream extensions (see
723section `Downstream extensions`_) start with underscore.
724
725Names beginning with ``q_`` are reserved for the generator, which uses
726them for munging QMP names that resemble C keywords or other
727problematic strings.  For example, a member named ``default`` in qapi
728becomes ``q_default`` in the generated C code.
729
730Types, commands, and events share a common namespace.  Therefore,
731generally speaking, type definitions should always use CamelCase for
732user-defined type names, while built-in types are lowercase.
733
734Type names ending with ``Kind`` or ``List`` are reserved for the
735generator, which uses them for implicit union enums and array types,
736respectively.
737
738Command names, and member names within a type, should be all lower
739case with words separated by a hyphen.  However, some existing older
740commands and complex types use underscore; when extending them,
741consistency is preferred over blindly avoiding underscore.
742
743Event names should be ALL_CAPS with words separated by underscore.
744
745Member name ``u`` and names starting with ``has-`` or ``has_`` are reserved
746for the generator, which uses them for unions and for tracking
747optional members.
748
749Any name (command, event, type, member, or enum value) beginning with
750``x-`` is marked experimental, and may be withdrawn or changed
751incompatibly in a future release.
752
753Pragmas ``command-name-exceptions`` and ``member-name-exceptions`` let
754you violate naming rules.  Use for new code is strongly discouraged. See
755`Pragma directives`_ for details.
756
757
758Downstream extensions
759---------------------
760
761QAPI schema names that are externally visible, say in the Client JSON
762Protocol, need to be managed with care.  Names starting with a
763downstream prefix of the form __RFQDN_ are reserved for the downstream
764who controls the valid, reverse fully qualified domain name RFQDN.
765RFQDN may only contain ASCII letters, digits, hyphen and period.
766
767Example: Red Hat, Inc. controls redhat.com, and may therefore add a
768downstream command ``__com.redhat_drive-mirror``.
769
770
771Configuring the schema
772----------------------
773
774Syntax::
775
776    COND = STRING
777         | { 'all: [ COND, ... ] }
778         | { 'any: [ COND, ... ] }
779         | { 'not': COND }
780
781All definitions take an optional 'if' member.  Its value must be a
782string, or an object with a single member 'all', 'any' or 'not'.
783
784The C code generated for the definition will then be guarded by an #if
785preprocessing directive with an operand generated from that condition:
786
787 * STRING will generate defined(STRING)
788 * { 'all': [COND, ...] } will generate (COND && ...)
789 * { 'any': [COND, ...] } will generate (COND || ...)
790 * { 'not': COND } will generate !COND
791
792Example: a conditional struct ::
793
794 { 'struct': 'IfStruct', 'data': { 'foo': 'int' },
795   'if': { 'all': [ 'CONFIG_FOO', 'HAVE_BAR' ] } }
796
797gets its generated code guarded like this::
798
799 #if defined(CONFIG_FOO) && defined(HAVE_BAR)
800 ... generated code ...
801 #endif /* defined(HAVE_BAR) && defined(CONFIG_FOO) */
802
803Individual members of complex types, commands arguments, and
804event-specific data can also be made conditional.  This requires the
805longhand form of MEMBER.
806
807Example: a struct type with unconditional member 'foo' and conditional
808member 'bar' ::
809
810 { 'struct': 'IfStruct',
811   'data': { 'foo': 'int',
812             'bar': { 'type': 'int', 'if': 'IFCOND'} } }
813
814A union's discriminator may not be conditional.
815
816Likewise, individual enumeration values be conditional.  This requires
817the longhand form of ENUM-VALUE_.
818
819Example: an enum type with unconditional value 'foo' and conditional
820value 'bar' ::
821
822 { 'enum': 'IfEnum',
823   'data': [ 'foo',
824             { 'name' : 'bar', 'if': 'IFCOND' } ] }
825
826Likewise, features can be conditional.  This requires the longhand
827form of FEATURE_.
828
829Example: a struct with conditional feature 'allow-negative-numbers' ::
830
831 { 'struct': 'TestType',
832   'data': { 'number': 'int' },
833   'features': [ { 'name': 'allow-negative-numbers',
834                   'if': 'IFCOND' } ] }
835
836Please note that you are responsible to ensure that the C code will
837compile with an arbitrary combination of conditions, since the
838generator is unable to check it at this point.
839
840The conditions apply to introspection as well, i.e. introspection
841shows a conditional entity only when the condition is satisfied in
842this particular build.
843
844
845Documentation comments
846----------------------
847
848A multi-line comment that starts and ends with a ``##`` line is a
849documentation comment.
850
851If the documentation comment starts like ::
852
853    ##
854    # @SYMBOL:
855
856it documents the definition of SYMBOL, else it's free-form
857documentation.
858
859See below for more on `Definition documentation`_.
860
861Free-form documentation may be used to provide additional text and
862structuring content.
863
864
865Headings and subheadings
866~~~~~~~~~~~~~~~~~~~~~~~~
867
868A free-form documentation comment containing a line which starts with
869some ``=`` symbols and then a space defines a section heading::
870
871    ##
872    # = This is a top level heading
873    #
874    # This is a free-form comment which will go under the
875    # top level heading.
876    ##
877
878    ##
879    # == This is a second level heading
880    ##
881
882A heading line must be the first line of the documentation
883comment block.
884
885Section headings must always be correctly nested, so you can only
886define a third-level heading inside a second-level heading, and so on.
887
888
889Documentation markup
890~~~~~~~~~~~~~~~~~~~~
891
892Documentation comments can use most rST markup.  In particular,
893a ``::`` literal block can be used for examples::
894
895    # ::
896    #
897    #   Text of the example, may span
898    #   multiple lines
899
900``*`` starts an itemized list::
901
902    # * First item, may span
903    #   multiple lines
904    # * Second item
905
906You can also use ``-`` instead of ``*``.
907
908A decimal number followed by ``.`` starts a numbered list::
909
910    # 1. First item, may span
911    #    multiple lines
912    # 2. Second item
913
914The actual number doesn't matter.
915
916Lists of either kind must be preceded and followed by a blank line.
917If a list item's text spans multiple lines, then the second and
918subsequent lines must be correctly indented to line up with the
919first character of the first line.
920
921The usual ****strong****, *\*emphasized\** and ````literal```` markup
922should be used.  If you need a single literal ``*``, you will need to
923backslash-escape it.  As an extension beyond the usual rST syntax, you
924can also use ``@foo`` to reference a name in the schema; this is rendered
925the same way as ````foo````.
926
927Example::
928
929 ##
930 # Some text foo with **bold** and *emphasis*
931 # 1. with a list
932 # 2. like that
933 #
934 # And some code:
935 #
936 # ::
937 #
938 #   $ echo foo
939 #   -> do this
940 #   <- get that
941 ##
942
943
944Definition documentation
945~~~~~~~~~~~~~~~~~~~~~~~~
946
947Definition documentation, if present, must immediately precede the
948definition it documents.
949
950When documentation is required (see pragma_ 'doc-required'), every
951definition must have documentation.
952
953Definition documentation starts with a line naming the definition,
954followed by an optional overview, a description of each argument (for
955commands and events), member (for structs and unions), branch (for
956alternates), or value (for enums), and finally optional tagged
957sections.
958
959Descriptions of arguments can span multiple lines.  The description
960text can start on the line following the '\@argname:', in which case it
961must not be indented at all.  It can also start on the same line as
962the '\@argname:'.  In this case if it spans multiple lines then second
963and subsequent lines must be indented to line up with the first
964character of the first line of the description::
965
966 # @argone:
967 # This is a two line description
968 # in the first style.
969 #
970 # @argtwo: This is a two line description
971 #          in the second style.
972
973The number of spaces between the ':' and the text is not significant.
974
975.. admonition:: FIXME
976
977   The parser accepts these things in almost any order.
978
979.. admonition:: FIXME
980
981   union branches should be described, too.
982
983Extensions added after the definition was first released carry a
984'(since x.y.z)' comment.
985
986A tagged section starts with one of the following words:
987"Note:"/"Notes:", "Since:", "Example"/"Examples", "Returns:", "TODO:".
988The section ends with the start of a new section.
989
990The text of a section can start on a new line, in
991which case it must not be indented at all.  It can also start
992on the same line as the 'Note:', 'Returns:', etc tag.  In this
993case if it spans multiple lines then second and subsequent
994lines must be indented to match the first, in the same way as
995multiline argument descriptions.
996
997A 'Since: x.y.z' tagged section lists the release that introduced the
998definition.
999
1000The text of a section can start on a new line, in
1001which case it must not be indented at all.  It can also start
1002on the same line as the 'Note:', 'Returns:', etc tag.  In this
1003case if it spans multiple lines then second and subsequent
1004lines must be indented to match the first.
1005
1006An 'Example' or 'Examples' section is automatically rendered
1007entirely as literal fixed-width text.  In other sections,
1008the text is formatted, and rST markup can be used.
1009
1010For example::
1011
1012 ##
1013 # @BlockStats:
1014 #
1015 # Statistics of a virtual block device or a block backing device.
1016 #
1017 # @device: If the stats are for a virtual block device, the name
1018 #          corresponding to the virtual block device.
1019 #
1020 # @node-name: The node name of the device. (since 2.3)
1021 #
1022 # ... more members ...
1023 #
1024 # Since: 0.14.0
1025 ##
1026 { 'struct': 'BlockStats',
1027   'data': {'*device': 'str', '*node-name': 'str',
1028            ... more members ... } }
1029
1030 ##
1031 # @query-blockstats:
1032 #
1033 # Query the @BlockStats for all virtual block devices.
1034 #
1035 # @query-nodes: If true, the command will query all the
1036 #               block nodes ... explain, explain ...  (since 2.3)
1037 #
1038 # Returns: A list of @BlockStats for each virtual block devices.
1039 #
1040 # Since: 0.14.0
1041 #
1042 # Example:
1043 #
1044 # -> { "execute": "query-blockstats" }
1045 # <- {
1046 #      ... lots of output ...
1047 #    }
1048 #
1049 ##
1050 { 'command': 'query-blockstats',
1051   'data': { '*query-nodes': 'bool' },
1052   'returns': ['BlockStats'] }
1053
1054
1055Client JSON Protocol introspection
1056==================================
1057
1058Clients of a Client JSON Protocol commonly need to figure out what
1059exactly the server (QEMU) supports.
1060
1061For this purpose, QMP provides introspection via command
1062query-qmp-schema.  QGA currently doesn't support introspection.
1063
1064While Client JSON Protocol wire compatibility should be maintained
1065between qemu versions, we cannot make the same guarantees for
1066introspection stability.  For example, one version of qemu may provide
1067a non-variant optional member of a struct, and a later version rework
1068the member to instead be non-optional and associated with a variant.
1069Likewise, one version of qemu may list a member with open-ended type
1070'str', and a later version could convert it to a finite set of strings
1071via an enum type; or a member may be converted from a specific type to
1072an alternate that represents a choice between the original type and
1073something else.
1074
1075query-qmp-schema returns a JSON array of SchemaInfo objects.  These
1076objects together describe the wire ABI, as defined in the QAPI schema.
1077There is no specified order to the SchemaInfo objects returned; a
1078client must search for a particular name throughout the entire array
1079to learn more about that name, but is at least guaranteed that there
1080will be no collisions between type, command, and event names.
1081
1082However, the SchemaInfo can't reflect all the rules and restrictions
1083that apply to QMP.  It's interface introspection (figuring out what's
1084there), not interface specification.  The specification is in the QAPI
1085schema.  To understand how QMP is to be used, you need to study the
1086QAPI schema.
1087
1088Like any other command, query-qmp-schema is itself defined in the QAPI
1089schema, along with the SchemaInfo type.  This text attempts to give an
1090overview how things work.  For details you need to consult the QAPI
1091schema.
1092
1093SchemaInfo objects have common members "name", "meta-type",
1094"features", and additional variant members depending on the value of
1095meta-type.
1096
1097Each SchemaInfo object describes a wire ABI entity of a certain
1098meta-type: a command, event or one of several kinds of type.
1099
1100SchemaInfo for commands and events have the same name as in the QAPI
1101schema.
1102
1103Command and event names are part of the wire ABI, but type names are
1104not.  Therefore, the SchemaInfo for types have auto-generated
1105meaningless names.  For readability, the examples in this section use
1106meaningful type names instead.
1107
1108Optional member "features" exposes the entity's feature strings as a
1109JSON array of strings.
1110
1111To examine a type, start with a command or event using it, then follow
1112references by name.
1113
1114QAPI schema definitions not reachable that way are omitted.
1115
1116The SchemaInfo for a command has meta-type "command", and variant
1117members "arg-type", "ret-type" and "allow-oob".  On the wire, the
1118"arguments" member of a client's "execute" command must conform to the
1119object type named by "arg-type".  The "return" member that the server
1120passes in a success response conforms to the type named by "ret-type".
1121When "allow-oob" is true, it means the command supports out-of-band
1122execution.  It defaults to false.
1123
1124If the command takes no arguments, "arg-type" names an object type
1125without members.  Likewise, if the command returns nothing, "ret-type"
1126names an object type without members.
1127
1128Example: the SchemaInfo for command query-qmp-schema ::
1129
1130 { "name": "query-qmp-schema", "meta-type": "command",
1131   "arg-type": "q_empty", "ret-type": "SchemaInfoList" }
1132
1133   Type "q_empty" is an automatic object type without members, and type
1134   "SchemaInfoList" is the array of SchemaInfo type.
1135
1136The SchemaInfo for an event has meta-type "event", and variant member
1137"arg-type".  On the wire, a "data" member that the server passes in an
1138event conforms to the object type named by "arg-type".
1139
1140If the event carries no additional information, "arg-type" names an
1141object type without members.  The event may not have a data member on
1142the wire then.
1143
1144Each command or event defined with 'data' as MEMBERS object in the
1145QAPI schema implicitly defines an object type.
1146
1147Example: the SchemaInfo for EVENT_C from section Events_ ::
1148
1149    { "name": "EVENT_C", "meta-type": "event",
1150      "arg-type": "q_obj-EVENT_C-arg" }
1151
1152    Type "q_obj-EVENT_C-arg" is an implicitly defined object type with
1153    the two members from the event's definition.
1154
1155The SchemaInfo for struct and union types has meta-type "object".
1156
1157The SchemaInfo for a struct type has variant member "members".
1158
1159The SchemaInfo for a union type additionally has variant members "tag"
1160and "variants".
1161
1162"members" is a JSON array describing the object's common members, if
1163any.  Each element is a JSON object with members "name" (the member's
1164name), "type" (the name of its type), "features" (a JSON array of
1165feature strings), and "default".  The latter two are optional.  The
1166member is optional if "default" is present.  Currently, "default" can
1167only have value null.  Other values are reserved for future
1168extensions.  The "members" array is in no particular order; clients
1169must search the entire object when learning whether a particular
1170member is supported.
1171
1172Example: the SchemaInfo for MyType from section `Struct types`_ ::
1173
1174    { "name": "MyType", "meta-type": "object",
1175      "members": [
1176          { "name": "member1", "type": "str" },
1177          { "name": "member2", "type": "int" },
1178          { "name": "member3", "type": "str", "default": null } ] }
1179
1180"features" exposes the command's feature strings as a JSON array of
1181strings.
1182
1183Example: the SchemaInfo for TestType from section Features_::
1184
1185    { "name": "TestType", "meta-type": "object",
1186      "members": [
1187          { "name": "number", "type": "int" } ],
1188      "features": ["allow-negative-numbers"] }
1189
1190"tag" is the name of the common member serving as type tag.
1191"variants" is a JSON array describing the object's variant members.
1192Each element is a JSON object with members "case" (the value of type
1193tag this element applies to) and "type" (the name of an object type
1194that provides the variant members for this type tag value).  The
1195"variants" array is in no particular order, and is not guaranteed to
1196list cases in the same order as the corresponding "tag" enum type.
1197
1198Example: the SchemaInfo for union BlockdevOptions from section
1199`Union types`_ ::
1200
1201    { "name": "BlockdevOptions", "meta-type": "object",
1202      "members": [
1203          { "name": "driver", "type": "BlockdevDriver" },
1204          { "name": "read-only", "type": "bool", "default": null } ],
1205      "tag": "driver",
1206      "variants": [
1207          { "case": "file", "type": "BlockdevOptionsFile" },
1208          { "case": "qcow2", "type": "BlockdevOptionsQcow2" } ] }
1209
1210Note that base types are "flattened": its members are included in the
1211"members" array.
1212
1213The SchemaInfo for an alternate type has meta-type "alternate", and
1214variant member "members".  "members" is a JSON array.  Each element is
1215a JSON object with member "type", which names a type.  Values of the
1216alternate type conform to exactly one of its member types.  There is
1217no guarantee on the order in which "members" will be listed.
1218
1219Example: the SchemaInfo for BlockdevRef from section `Alternate types`_ ::
1220
1221    { "name": "BlockdevRef", "meta-type": "alternate",
1222      "members": [
1223          { "type": "BlockdevOptions" },
1224          { "type": "str" } ] }
1225
1226The SchemaInfo for an array type has meta-type "array", and variant
1227member "element-type", which names the array's element type.  Array
1228types are implicitly defined.  For convenience, the array's name may
1229resemble the element type; however, clients should examine member
1230"element-type" instead of making assumptions based on parsing member
1231"name".
1232
1233Example: the SchemaInfo for ['str'] ::
1234
1235    { "name": "[str]", "meta-type": "array",
1236      "element-type": "str" }
1237
1238The SchemaInfo for an enumeration type has meta-type "enum" and
1239variant member "members".
1240
1241"members" is a JSON array describing the enumeration values.  Each
1242element is a JSON object with member "name" (the member's name), and
1243optionally "features" (a JSON array of feature strings).  The
1244"members" array is in no particular order; clients must search the
1245entire array when learning whether a particular value is supported.
1246
1247Example: the SchemaInfo for MyEnum from section `Enumeration types`_ ::
1248
1249    { "name": "MyEnum", "meta-type": "enum",
1250      "members": [
1251        { "name": "value1" },
1252        { "name": "value2" },
1253        { "name": "value3" }
1254      ] }
1255
1256The SchemaInfo for a built-in type has the same name as the type in
1257the QAPI schema (see section `Built-in Types`_), with one exception
1258detailed below.  It has variant member "json-type" that shows how
1259values of this type are encoded on the wire.
1260
1261Example: the SchemaInfo for str ::
1262
1263    { "name": "str", "meta-type": "builtin", "json-type": "string" }
1264
1265The QAPI schema supports a number of integer types that only differ in
1266how they map to C.  They are identical as far as SchemaInfo is
1267concerned.  Therefore, they get all mapped to a single type "int" in
1268SchemaInfo.
1269
1270As explained above, type names are not part of the wire ABI.  Not even
1271the names of built-in types.  Clients should examine member
1272"json-type" instead of hard-coding names of built-in types.
1273
1274
1275Compatibility considerations
1276============================
1277
1278Maintaining backward compatibility at the Client JSON Protocol level
1279while evolving the schema requires some care.  This section is about
1280syntactic compatibility, which is necessary, but not sufficient, for
1281actual compatibility.
1282
1283Clients send commands with argument data, and receive command
1284responses with return data and events with event data.
1285
1286Adding opt-in functionality to the send direction is backwards
1287compatible: adding commands, optional arguments, enumeration values,
1288union and alternate branches; turning an argument type into an
1289alternate of that type; making mandatory arguments optional.  Clients
1290oblivious of the new functionality continue to work.
1291
1292Incompatible changes include removing commands, command arguments,
1293enumeration values, union and alternate branches, adding mandatory
1294command arguments, and making optional arguments mandatory.
1295
1296The specified behavior of an absent optional argument should remain
1297the same.  With proper documentation, this policy still allows some
1298flexibility; for example, when an optional 'buffer-size' argument is
1299specified to default to a sensible buffer size, the actual default
1300value can still be changed.  The specified default behavior is not the
1301exact size of the buffer, only that the default size is sensible.
1302
1303Adding functionality to the receive direction is generally backwards
1304compatible: adding events, adding return and event data members.
1305Clients are expected to ignore the ones they don't know.
1306
1307Removing "unreachable" stuff like events that can't be triggered
1308anymore, optional return or event data members that can't be sent
1309anymore, and return or event data member (enumeration) values that
1310can't be sent anymore makes no difference to clients, except for
1311introspection.  The latter can conceivably confuse clients, so tread
1312carefully.
1313
1314Incompatible changes include removing return and event data members.
1315
1316Any change to a command definition's 'data' or one of the types used
1317there (recursively) needs to consider send direction compatibility.
1318
1319Any change to a command definition's 'return', an event definition's
1320'data', or one of the types used there (recursively) needs to consider
1321receive direction compatibility.
1322
1323Any change to types used in both contexts need to consider both.
1324
1325Enumeration type values and complex and alternate type members may be
1326reordered freely.  For enumerations and alternate types, this doesn't
1327affect the wire encoding.  For complex types, this might make the
1328implementation emit JSON object members in a different order, which
1329the Client JSON Protocol permits.
1330
1331Since type names are not visible in the Client JSON Protocol, types
1332may be freely renamed.  Even certain refactorings are invisible, such
1333as splitting members from one type into a common base type.
1334
1335
1336Code generation
1337===============
1338
1339The QAPI code generator qapi-gen.py generates code and documentation
1340from the schema.  Together with the core QAPI libraries, this code
1341provides everything required to take JSON commands read in by a Client
1342JSON Protocol server, unmarshal the arguments into the underlying C
1343types, call into the corresponding C function, map the response back
1344to a Client JSON Protocol response to be returned to the user, and
1345introspect the commands.
1346
1347As an example, we'll use the following schema, which describes a
1348single complex user-defined type, along with command which takes a
1349list of that type as a parameter, and returns a single element of that
1350type.  The user is responsible for writing the implementation of
1351qmp_my_command(); everything else is produced by the generator. ::
1352
1353    $ cat example-schema.json
1354    { 'struct': 'UserDefOne',
1355      'data': { 'integer': 'int', '*string': 'str' } }
1356
1357    { 'command': 'my-command',
1358      'data': { 'arg1': ['UserDefOne'] },
1359      'returns': 'UserDefOne' }
1360
1361    { 'event': 'MY_EVENT' }
1362
1363We run qapi-gen.py like this::
1364
1365    $ python scripts/qapi-gen.py --output-dir="qapi-generated" \
1366    --prefix="example-" example-schema.json
1367
1368For a more thorough look at generated code, the testsuite includes
1369tests/qapi-schema/qapi-schema-tests.json that covers more examples of
1370what the generator will accept, and compiles the resulting C code as
1371part of 'make check-unit'.
1372
1373
1374Code generated for QAPI types
1375-----------------------------
1376
1377The following files are created:
1378
1379 ``$(prefix)qapi-types.h``
1380     C types corresponding to types defined in the schema
1381
1382 ``$(prefix)qapi-types.c``
1383     Cleanup functions for the above C types
1384
1385The $(prefix) is an optional parameter used as a namespace to keep the
1386generated code from one schema/code-generation separated from others so code
1387can be generated/used from multiple schemas without clobbering previously
1388created code.
1389
1390Example::
1391
1392    $ cat qapi-generated/example-qapi-types.h
1393    [Uninteresting stuff omitted...]
1394
1395    #ifndef EXAMPLE_QAPI_TYPES_H
1396    #define EXAMPLE_QAPI_TYPES_H
1397
1398    #include "qapi/qapi-builtin-types.h"
1399
1400    typedef struct UserDefOne UserDefOne;
1401
1402    typedef struct UserDefOneList UserDefOneList;
1403
1404    typedef struct q_obj_my_command_arg q_obj_my_command_arg;
1405
1406    struct UserDefOne {
1407        int64_t integer;
1408        bool has_string;
1409        char *string;
1410    };
1411
1412    void qapi_free_UserDefOne(UserDefOne *obj);
1413    G_DEFINE_AUTOPTR_CLEANUP_FUNC(UserDefOne, qapi_free_UserDefOne)
1414
1415    struct UserDefOneList {
1416        UserDefOneList *next;
1417        UserDefOne *value;
1418    };
1419
1420    void qapi_free_UserDefOneList(UserDefOneList *obj);
1421    G_DEFINE_AUTOPTR_CLEANUP_FUNC(UserDefOneList, qapi_free_UserDefOneList)
1422
1423    struct q_obj_my_command_arg {
1424        UserDefOneList *arg1;
1425    };
1426
1427    #endif /* EXAMPLE_QAPI_TYPES_H */
1428    $ cat qapi-generated/example-qapi-types.c
1429    [Uninteresting stuff omitted...]
1430
1431    void qapi_free_UserDefOne(UserDefOne *obj)
1432    {
1433        Visitor *v;
1434
1435        if (!obj) {
1436            return;
1437        }
1438
1439        v = qapi_dealloc_visitor_new();
1440        visit_type_UserDefOne(v, NULL, &obj, NULL);
1441        visit_free(v);
1442    }
1443
1444    void qapi_free_UserDefOneList(UserDefOneList *obj)
1445    {
1446        Visitor *v;
1447
1448        if (!obj) {
1449            return;
1450        }
1451
1452        v = qapi_dealloc_visitor_new();
1453        visit_type_UserDefOneList(v, NULL, &obj, NULL);
1454        visit_free(v);
1455    }
1456
1457    [Uninteresting stuff omitted...]
1458
1459For a modular QAPI schema (see section `Include directives`_), code for
1460each sub-module SUBDIR/SUBMODULE.json is actually generated into ::
1461
1462 SUBDIR/$(prefix)qapi-types-SUBMODULE.h
1463 SUBDIR/$(prefix)qapi-types-SUBMODULE.c
1464
1465If qapi-gen.py is run with option --builtins, additional files are
1466created:
1467
1468 ``qapi-builtin-types.h``
1469     C types corresponding to built-in types
1470
1471 ``qapi-builtin-types.c``
1472     Cleanup functions for the above C types
1473
1474
1475Code generated for visiting QAPI types
1476--------------------------------------
1477
1478These are the visitor functions used to walk through and convert
1479between a native QAPI C data structure and some other format (such as
1480QObject); the generated functions are named visit_type_FOO() and
1481visit_type_FOO_members().
1482
1483The following files are generated:
1484
1485 ``$(prefix)qapi-visit.c``
1486     Visitor function for a particular C type, used to automagically
1487     convert QObjects into the corresponding C type and vice-versa, as
1488     well as for deallocating memory for an existing C type
1489
1490 ``$(prefix)qapi-visit.h``
1491     Declarations for previously mentioned visitor functions
1492
1493Example::
1494
1495    $ cat qapi-generated/example-qapi-visit.h
1496    [Uninteresting stuff omitted...]
1497
1498    #ifndef EXAMPLE_QAPI_VISIT_H
1499    #define EXAMPLE_QAPI_VISIT_H
1500
1501    #include "qapi/qapi-builtin-visit.h"
1502    #include "example-qapi-types.h"
1503
1504
1505    bool visit_type_UserDefOne_members(Visitor *v, UserDefOne *obj, Error **errp);
1506
1507    bool visit_type_UserDefOne(Visitor *v, const char *name,
1508                     UserDefOne **obj, Error **errp);
1509
1510    bool visit_type_UserDefOneList(Visitor *v, const char *name,
1511                     UserDefOneList **obj, Error **errp);
1512
1513    bool visit_type_q_obj_my_command_arg_members(Visitor *v, q_obj_my_command_arg *obj, Error **errp);
1514
1515    #endif /* EXAMPLE_QAPI_VISIT_H */
1516    $ cat qapi-generated/example-qapi-visit.c
1517    [Uninteresting stuff omitted...]
1518
1519    bool visit_type_UserDefOne_members(Visitor *v, UserDefOne *obj, Error **errp)
1520    {
1521        if (!visit_type_int(v, "integer", &obj->integer, errp)) {
1522            return false;
1523        }
1524        if (visit_optional(v, "string", &obj->has_string)) {
1525            if (!visit_type_str(v, "string", &obj->string, errp)) {
1526                return false;
1527            }
1528        }
1529        return true;
1530    }
1531
1532    bool visit_type_UserDefOne(Visitor *v, const char *name,
1533                     UserDefOne **obj, Error **errp)
1534    {
1535        bool ok = false;
1536
1537        if (!visit_start_struct(v, name, (void **)obj, sizeof(UserDefOne), errp)) {
1538            return false;
1539        }
1540        if (!*obj) {
1541            /* incomplete */
1542            assert(visit_is_dealloc(v));
1543            ok = true;
1544            goto out_obj;
1545        }
1546        if (!visit_type_UserDefOne_members(v, *obj, errp)) {
1547            goto out_obj;
1548        }
1549        ok = visit_check_struct(v, errp);
1550    out_obj:
1551        visit_end_struct(v, (void **)obj);
1552        if (!ok && visit_is_input(v)) {
1553            qapi_free_UserDefOne(*obj);
1554            *obj = NULL;
1555        }
1556        return ok;
1557    }
1558
1559    bool visit_type_UserDefOneList(Visitor *v, const char *name,
1560                     UserDefOneList **obj, Error **errp)
1561    {
1562        bool ok = false;
1563        UserDefOneList *tail;
1564        size_t size = sizeof(**obj);
1565
1566        if (!visit_start_list(v, name, (GenericList **)obj, size, errp)) {
1567            return false;
1568        }
1569
1570        for (tail = *obj; tail;
1571             tail = (UserDefOneList *)visit_next_list(v, (GenericList *)tail, size)) {
1572            if (!visit_type_UserDefOne(v, NULL, &tail->value, errp)) {
1573                goto out_obj;
1574            }
1575        }
1576
1577        ok = visit_check_list(v, errp);
1578    out_obj:
1579        visit_end_list(v, (void **)obj);
1580        if (!ok && visit_is_input(v)) {
1581            qapi_free_UserDefOneList(*obj);
1582            *obj = NULL;
1583        }
1584        return ok;
1585    }
1586
1587    bool visit_type_q_obj_my_command_arg_members(Visitor *v, q_obj_my_command_arg *obj, Error **errp)
1588    {
1589        if (!visit_type_UserDefOneList(v, "arg1", &obj->arg1, errp)) {
1590            return false;
1591        }
1592        return true;
1593    }
1594
1595    [Uninteresting stuff omitted...]
1596
1597For a modular QAPI schema (see section `Include directives`_), code for
1598each sub-module SUBDIR/SUBMODULE.json is actually generated into ::
1599
1600 SUBDIR/$(prefix)qapi-visit-SUBMODULE.h
1601 SUBDIR/$(prefix)qapi-visit-SUBMODULE.c
1602
1603If qapi-gen.py is run with option --builtins, additional files are
1604created:
1605
1606 ``qapi-builtin-visit.h``
1607     Visitor functions for built-in types
1608
1609 ``qapi-builtin-visit.c``
1610     Declarations for these visitor functions
1611
1612
1613Code generated for commands
1614---------------------------
1615
1616These are the marshaling/dispatch functions for the commands defined
1617in the schema.  The generated code provides qmp_marshal_COMMAND(), and
1618declares qmp_COMMAND() that the user must implement.
1619
1620The following files are generated:
1621
1622 ``$(prefix)qapi-commands.c``
1623     Command marshal/dispatch functions for each QMP command defined in
1624     the schema
1625
1626 ``$(prefix)qapi-commands.h``
1627     Function prototypes for the QMP commands specified in the schema
1628
1629 ``$(prefix)qapi-init-commands.h``
1630     Command initialization prototype
1631
1632 ``$(prefix)qapi-init-commands.c``
1633     Command initialization code
1634
1635Example::
1636
1637    $ cat qapi-generated/example-qapi-commands.h
1638    [Uninteresting stuff omitted...]
1639
1640    #ifndef EXAMPLE_QAPI_COMMANDS_H
1641    #define EXAMPLE_QAPI_COMMANDS_H
1642
1643    #include "example-qapi-types.h"
1644
1645    UserDefOne *qmp_my_command(UserDefOneList *arg1, Error **errp);
1646    void qmp_marshal_my_command(QDict *args, QObject **ret, Error **errp);
1647
1648    #endif /* EXAMPLE_QAPI_COMMANDS_H */
1649    $ cat qapi-generated/example-qapi-commands.c
1650    [Uninteresting stuff omitted...]
1651
1652
1653    static void qmp_marshal_output_UserDefOne(UserDefOne *ret_in,
1654                                    QObject **ret_out, Error **errp)
1655    {
1656        Visitor *v;
1657
1658        v = qobject_output_visitor_new_qmp(ret_out);
1659        if (visit_type_UserDefOne(v, "unused", &ret_in, errp)) {
1660            visit_complete(v, ret_out);
1661        }
1662        visit_free(v);
1663        v = qapi_dealloc_visitor_new();
1664        visit_type_UserDefOne(v, "unused", &ret_in, NULL);
1665        visit_free(v);
1666    }
1667
1668    void qmp_marshal_my_command(QDict *args, QObject **ret, Error **errp)
1669    {
1670        Error *err = NULL;
1671        bool ok = false;
1672        Visitor *v;
1673        UserDefOne *retval;
1674        q_obj_my_command_arg arg = {0};
1675
1676        v = qobject_input_visitor_new_qmp(QOBJECT(args));
1677        if (!visit_start_struct(v, NULL, NULL, 0, errp)) {
1678            goto out;
1679        }
1680        if (visit_type_q_obj_my_command_arg_members(v, &arg, errp)) {
1681            ok = visit_check_struct(v, errp);
1682        }
1683        visit_end_struct(v, NULL);
1684        if (!ok) {
1685            goto out;
1686        }
1687
1688        retval = qmp_my_command(arg.arg1, &err);
1689        error_propagate(errp, err);
1690        if (err) {
1691            goto out;
1692        }
1693
1694        qmp_marshal_output_UserDefOne(retval, ret, errp);
1695
1696    out:
1697        visit_free(v);
1698        v = qapi_dealloc_visitor_new();
1699        visit_start_struct(v, NULL, NULL, 0, NULL);
1700        visit_type_q_obj_my_command_arg_members(v, &arg, NULL);
1701        visit_end_struct(v, NULL);
1702        visit_free(v);
1703    }
1704
1705    [Uninteresting stuff omitted...]
1706    $ cat qapi-generated/example-qapi-init-commands.h
1707    [Uninteresting stuff omitted...]
1708    #ifndef EXAMPLE_QAPI_INIT_COMMANDS_H
1709    #define EXAMPLE_QAPI_INIT_COMMANDS_H
1710
1711    #include "qapi/qmp/dispatch.h"
1712
1713    void example_qmp_init_marshal(QmpCommandList *cmds);
1714
1715    #endif /* EXAMPLE_QAPI_INIT_COMMANDS_H */
1716    $ cat qapi-generated/example-qapi-init-commands.c
1717    [Uninteresting stuff omitted...]
1718    void example_qmp_init_marshal(QmpCommandList *cmds)
1719    {
1720        QTAILQ_INIT(cmds);
1721
1722        qmp_register_command(cmds, "my-command",
1723                             qmp_marshal_my_command, QCO_NO_OPTIONS);
1724    }
1725    [Uninteresting stuff omitted...]
1726
1727For a modular QAPI schema (see section `Include directives`_), code for
1728each sub-module SUBDIR/SUBMODULE.json is actually generated into::
1729
1730 SUBDIR/$(prefix)qapi-commands-SUBMODULE.h
1731 SUBDIR/$(prefix)qapi-commands-SUBMODULE.c
1732
1733
1734Code generated for events
1735-------------------------
1736
1737This is the code related to events defined in the schema, providing
1738qapi_event_send_EVENT().
1739
1740The following files are created:
1741
1742 ``$(prefix)qapi-events.h``
1743     Function prototypes for each event type
1744
1745 ``$(prefix)qapi-events.c``
1746     Implementation of functions to send an event
1747
1748 ``$(prefix)qapi-emit-events.h``
1749     Enumeration of all event names, and common event code declarations
1750
1751 ``$(prefix)qapi-emit-events.c``
1752     Common event code definitions
1753
1754Example::
1755
1756    $ cat qapi-generated/example-qapi-events.h
1757    [Uninteresting stuff omitted...]
1758
1759    #ifndef EXAMPLE_QAPI_EVENTS_H
1760    #define EXAMPLE_QAPI_EVENTS_H
1761
1762    #include "qapi/util.h"
1763    #include "example-qapi-types.h"
1764
1765    void qapi_event_send_my_event(void);
1766
1767    #endif /* EXAMPLE_QAPI_EVENTS_H */
1768    $ cat qapi-generated/example-qapi-events.c
1769    [Uninteresting stuff omitted...]
1770
1771    void qapi_event_send_my_event(void)
1772    {
1773        QDict *qmp;
1774
1775        qmp = qmp_event_build_dict("MY_EVENT");
1776
1777        example_qapi_event_emit(EXAMPLE_QAPI_EVENT_MY_EVENT, qmp);
1778
1779        qobject_unref(qmp);
1780    }
1781
1782    [Uninteresting stuff omitted...]
1783    $ cat qapi-generated/example-qapi-emit-events.h
1784    [Uninteresting stuff omitted...]
1785
1786    #ifndef EXAMPLE_QAPI_EMIT_EVENTS_H
1787    #define EXAMPLE_QAPI_EMIT_EVENTS_H
1788
1789    #include "qapi/util.h"
1790
1791    typedef enum example_QAPIEvent {
1792        EXAMPLE_QAPI_EVENT_MY_EVENT,
1793        EXAMPLE_QAPI_EVENT__MAX,
1794    } example_QAPIEvent;
1795
1796    #define example_QAPIEvent_str(val) \
1797        qapi_enum_lookup(&example_QAPIEvent_lookup, (val))
1798
1799    extern const QEnumLookup example_QAPIEvent_lookup;
1800
1801    void example_qapi_event_emit(example_QAPIEvent event, QDict *qdict);
1802
1803    #endif /* EXAMPLE_QAPI_EMIT_EVENTS_H */
1804    $ cat qapi-generated/example-qapi-emit-events.c
1805    [Uninteresting stuff omitted...]
1806
1807    const QEnumLookup example_QAPIEvent_lookup = {
1808        .array = (const char *const[]) {
1809            [EXAMPLE_QAPI_EVENT_MY_EVENT] = "MY_EVENT",
1810        },
1811        .size = EXAMPLE_QAPI_EVENT__MAX
1812    };
1813
1814    [Uninteresting stuff omitted...]
1815
1816For a modular QAPI schema (see section `Include directives`_), code for
1817each sub-module SUBDIR/SUBMODULE.json is actually generated into ::
1818
1819 SUBDIR/$(prefix)qapi-events-SUBMODULE.h
1820 SUBDIR/$(prefix)qapi-events-SUBMODULE.c
1821
1822
1823Code generated for introspection
1824--------------------------------
1825
1826The following files are created:
1827
1828 ``$(prefix)qapi-introspect.c``
1829     Defines a string holding a JSON description of the schema
1830
1831 ``$(prefix)qapi-introspect.h``
1832     Declares the above string
1833
1834Example::
1835
1836    $ cat qapi-generated/example-qapi-introspect.h
1837    [Uninteresting stuff omitted...]
1838
1839    #ifndef EXAMPLE_QAPI_INTROSPECT_H
1840    #define EXAMPLE_QAPI_INTROSPECT_H
1841
1842    #include "qapi/qmp/qlit.h"
1843
1844    extern const QLitObject example_qmp_schema_qlit;
1845
1846    #endif /* EXAMPLE_QAPI_INTROSPECT_H */
1847    $ cat qapi-generated/example-qapi-introspect.c
1848    [Uninteresting stuff omitted...]
1849
1850    const QLitObject example_qmp_schema_qlit = QLIT_QLIST(((QLitObject[]) {
1851        QLIT_QDICT(((QLitDictEntry[]) {
1852            { "arg-type", QLIT_QSTR("0"), },
1853            { "meta-type", QLIT_QSTR("command"), },
1854            { "name", QLIT_QSTR("my-command"), },
1855            { "ret-type", QLIT_QSTR("1"), },
1856            {}
1857        })),
1858        QLIT_QDICT(((QLitDictEntry[]) {
1859            { "arg-type", QLIT_QSTR("2"), },
1860            { "meta-type", QLIT_QSTR("event"), },
1861            { "name", QLIT_QSTR("MY_EVENT"), },
1862            {}
1863        })),
1864        /* "0" = q_obj_my-command-arg */
1865        QLIT_QDICT(((QLitDictEntry[]) {
1866            { "members", QLIT_QLIST(((QLitObject[]) {
1867                QLIT_QDICT(((QLitDictEntry[]) {
1868                    { "name", QLIT_QSTR("arg1"), },
1869                    { "type", QLIT_QSTR("[1]"), },
1870                    {}
1871                })),
1872                {}
1873            })), },
1874            { "meta-type", QLIT_QSTR("object"), },
1875            { "name", QLIT_QSTR("0"), },
1876            {}
1877        })),
1878        /* "1" = UserDefOne */
1879        QLIT_QDICT(((QLitDictEntry[]) {
1880            { "members", QLIT_QLIST(((QLitObject[]) {
1881                QLIT_QDICT(((QLitDictEntry[]) {
1882                    { "name", QLIT_QSTR("integer"), },
1883                    { "type", QLIT_QSTR("int"), },
1884                    {}
1885                })),
1886                QLIT_QDICT(((QLitDictEntry[]) {
1887                    { "default", QLIT_QNULL, },
1888                    { "name", QLIT_QSTR("string"), },
1889                    { "type", QLIT_QSTR("str"), },
1890                    {}
1891                })),
1892                {}
1893            })), },
1894            { "meta-type", QLIT_QSTR("object"), },
1895            { "name", QLIT_QSTR("1"), },
1896            {}
1897        })),
1898        /* "2" = q_empty */
1899        QLIT_QDICT(((QLitDictEntry[]) {
1900            { "members", QLIT_QLIST(((QLitObject[]) {
1901                {}
1902            })), },
1903            { "meta-type", QLIT_QSTR("object"), },
1904            { "name", QLIT_QSTR("2"), },
1905            {}
1906        })),
1907        QLIT_QDICT(((QLitDictEntry[]) {
1908            { "element-type", QLIT_QSTR("1"), },
1909            { "meta-type", QLIT_QSTR("array"), },
1910            { "name", QLIT_QSTR("[1]"), },
1911            {}
1912        })),
1913        QLIT_QDICT(((QLitDictEntry[]) {
1914            { "json-type", QLIT_QSTR("int"), },
1915            { "meta-type", QLIT_QSTR("builtin"), },
1916            { "name", QLIT_QSTR("int"), },
1917            {}
1918        })),
1919        QLIT_QDICT(((QLitDictEntry[]) {
1920            { "json-type", QLIT_QSTR("string"), },
1921            { "meta-type", QLIT_QSTR("builtin"), },
1922            { "name", QLIT_QSTR("str"), },
1923            {}
1924        })),
1925        {}
1926    }));
1927
1928    [Uninteresting stuff omitted...]
1929