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