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