]> git.proxmox.com Git - mirror_qemu.git/blame - docs/devel/qapi-code-gen.txt
qapi: Permit omitting all flat union branches
[mirror_qemu.git] / docs / devel / qapi-code-gen.txt
CommitLineData
b84da831
MR
1= How to use the QAPI code generator =
2
6fb55451 3Copyright IBM Corp. 2011
9ee86b85 4Copyright (C) 2012-2016 Red Hat, Inc.
6fb55451
EB
5
6This work is licensed under the terms of the GNU GPL, version 2 or
7later. See the COPYING file in the top-level directory.
8
9== Introduction ==
10
b84da831 11QAPI is a native C API within QEMU which provides management-level
e790e666
EB
12functionality to internal and external users. For external
13users/processes, this interface is made available by a JSON-based wire
14format for the QEMU Monitor Protocol (QMP) for controlling qemu, as
15well as the QEMU Guest Agent (QGA) for communicating with the guest.
363b4262
EB
16The remainder of this document uses "Client JSON Protocol" when
17referring to the wire contents of a QMP or QGA connection.
b84da831 18
363b4262
EB
19To map Client JSON Protocol interfaces to the native C QAPI
20implementations, a JSON-based schema is used to define types and
21function signatures, and a set of scripts is used to generate types,
22signatures, and marshaling/dispatch code. This document will describe
23how the schemas, scripts, and resulting code are used.
b84da831
MR
24
25
26== QMP/Guest agent schema ==
27
e790e666 28A QAPI schema file is designed to be loosely based on JSON
aee03bf3 29(http://www.ietf.org/rfc/rfc8259.txt) with changes for quoting style
e790e666
EB
30and the use of comments; a QAPI schema file is then parsed by a python
31code generation program. A valid QAPI schema consists of a series of
32top-level expressions, with no commas between them. Where
33dictionaries (JSON objects) are used, they are parsed as python
34OrderedDicts so that ordering is preserved (for predictable layout of
35generated C structs and parameter lists). Ordering doesn't matter
36between top-level expressions or the keys within an expression, but
37does matter within dictionary values for 'data' and 'returns' members
38of a single expression. QAPI schema input is written using 'single
363b4262
EB
39quotes' instead of JSON's "double quotes" (in contrast, Client JSON
40Protocol uses no comments, and while input accepts 'single quotes' as
41an extension, output is strict JSON using only "double quotes"). As
42in JSON, trailing commas are not permitted in arrays or dictionaries.
43Input must be ASCII (although QMP supports full Unicode strings, the
44QAPI parser does not). At present, there is no place where a QAPI
45schema requires the use of JSON numbers or null.
e790e666 46
3313b612
MAL
47
48=== Comments ===
49
e790e666 50Comments are allowed; anything between an unquoted # and the following
3313b612
MAL
51newline is ignored.
52
53A multi-line comment that starts and ends with a '##' line is a
54documentation comment. These are parsed by the documentation
55generator, which recognizes certain markup detailed below.
56
57
58==== Documentation markup ====
59
60Comment text starting with '=' is a section title:
61
62 # = Section title
63
64Double the '=' for a subsection title:
65
0b263ecb 66 # == Subsection title
3313b612
MAL
67
68'|' denotes examples:
69
70 # | Text of the example, may span
71 # | multiple lines
72
73'*' starts an itemized list:
74
75 # * First item, may span
76 # multiple lines
77 # * Second item
78
79You can also use '-' instead of '*'.
80
81A decimal number followed by '.' starts a numbered list:
82
83 # 1. First item, may span
84 # multiple lines
85 # 2. Second item
86
87The actual number doesn't matter. You could even use '*' instead of
88'2.' for the second item.
89
90Lists can't be nested. Blank lines are currently not supported within
91lists.
92
93Additional whitespace between the initial '#' and the comment text is
94permitted.
95
96*foo* and _foo_ are for strong and emphasis styles respectively (they
97do not work over multiple lines). @foo is used to reference a name in
98the schema.
99
100Example:
101
102##
103# = Section
104# == Subsection
105#
106# Some text foo with *strong* and _emphasis_
107# 1. with a list
108# 2. like that
109#
110# And some code:
111# | $ echo foo
112# | -> do this
113# | <- get that
114#
115##
116
117
118==== Expression documentation ====
119
e24fe238
MA
120Expressions other than include and pragma directives may be preceded
121by a documentation block. Such blocks are called expression
122documentation blocks.
3313b612 123
bc52d03f
MA
124When documentation is required (see pragma 'doc-required'), expression
125documentation blocks are mandatory.
126
3313b612
MAL
127The documentation block consists of a first line naming the
128expression, an optional overview, a description of each argument (for
129commands and events) or member (for structs, unions and alternates),
130and optional tagged sections.
131
132FIXME: the parser accepts these things in almost any order.
133
1d8bda12
MA
134Extensions added after the expression was first released carry a
135'(since x.y.z)' comment.
3313b612
MAL
136
137A tagged section starts with one of the following words:
138"Note:"/"Notes:", "Since:", "Example"/"Examples", "Returns:", "TODO:".
139The section ends with the start of a new section.
140
141A 'Since: x.y.z' tagged section lists the release that introduced the
142expression.
143
144For example:
145
146##
147# @BlockStats:
148#
149# Statistics of a virtual block device or a block backing device.
150#
1d8bda12 151# @device: If the stats are for a virtual block device, the name
3313b612
MAL
152# corresponding to the virtual block device.
153#
1d8bda12 154# @node-name: The node name of the device. (since 2.3)
3313b612
MAL
155#
156# ... more members ...
157#
158# Since: 0.14.0
159##
160{ 'struct': 'BlockStats',
161 'data': {'*device': 'str', '*node-name': 'str',
162 ... more members ... } }
163
164##
165# @query-blockstats:
166#
167# Query the @BlockStats for all virtual block devices.
168#
1d8bda12 169# @query-nodes: If true, the command will query all the
3313b612
MAL
170# block nodes ... explain, explain ... (since 2.3)
171#
172# Returns: A list of @BlockStats for each virtual block devices.
173#
174# Since: 0.14.0
175#
176# Example:
177#
178# -> { "execute": "query-blockstats" }
179# <- {
180# ... lots of output ...
181# }
182#
183##
184{ 'command': 'query-blockstats',
185 'data': { '*query-nodes': 'bool' },
186 'returns': ['BlockStats'] }
187
188==== Free-form documentation ====
189
190A documentation block that isn't an expression documentation block is
191a free-form documentation block. These may be used to provide
192additional text and structuring content.
193
194
195=== Schema overview ===
e790e666
EB
196
197The schema sets up a series of types, as well as commands and events
198that will use those types. Forward references are allowed: the parser
199scans in two passes, where the first pass learns all type names, and
200the second validates the schema and generates the code. This allows
201the definition of complex structs that can have mutually recursive
363b4262
EB
202types, and allows for indefinite nesting of Client JSON Protocol that
203satisfies the schema. A type name should not be defined more than
204once. It is permissible for the schema to contain additional types
205not used by any commands or events in the Client JSON Protocol, for
206the side effect of generated C code used internally.
e790e666 207
bc52d03f
MA
208There are eight top-level expressions recognized by the parser:
209'include', 'pragma', 'command', 'struct', 'enum', 'union',
210'alternate', and 'event'. There are several groups of types: simple
211types (a number of built-in types, such as 'int' and 'str'; as well as
212enumerations), complex types (structs and two flavors of unions), and
213alternate types (a choice between other types). The 'command' and
214'event' expressions can refer to existing types by name, or list an
215anonymous type as a dictionary. Listing a type name inside an array
216refers to a single-dimension array of that type; multi-dimension
217arrays are not directly supported (although an array of a complex
218struct that contains an array member is possible).
e790e666 219
79f75981
MA
220All names must begin with a letter, and contain only ASCII letters,
221digits, hyphen, and underscore. There are two exceptions: enum values
222may start with a digit, and names that are downstream extensions (see
223section Downstream extensions) start with underscore.
224
225Names beginning with 'q_' are reserved for the generator, which uses
226them for munging QMP names that resemble C keywords or other
227problematic strings. For example, a member named "default" in qapi
228becomes "q_default" in the generated C code.
229
e790e666
EB
230Types, commands, and events share a common namespace. Therefore,
231generally speaking, type definitions should always use CamelCase for
79f75981
MA
232user-defined type names, while built-in types are lowercase.
233
234Type names ending with 'Kind' or 'List' are reserved for the
235generator, which uses them for implicit union enums and array types,
236respectively.
237
238Command names, and member names within a type, should be all lower
239case with words separated by a hyphen. However, some existing older
240commands and complex types use underscore; when extending such
241expressions, consistency is preferred over blindly avoiding
242underscore.
243
244Event names should be ALL_CAPS with words separated by underscore.
245
e24fe238
MA
246Member name 'u' and names starting with 'has-' or 'has_' are reserved
247for the generator, which uses them for unions and for tracking
248optional members.
e790e666 249
9ee86b85 250Any name (command, event, type, member, or enum value) beginning with
e790e666 251"x-" is marked experimental, and may be withdrawn or changed
79f75981 252incompatibly in a future release.
e790e666 253
2cfbae3c
MA
254Pragma 'name-case-whitelist' lets you violate the rules on use of
255upper and lower case. Use for new code is strongly discouraged.
256
e790e666
EB
257In the rest of this document, usage lines are given for each
258expression type, with literal strings written in lower case and
259placeholders written in capitals. If a literal string includes a
260prefix of '*', that key/value pair can be omitted from the expression.
3b2a8b85 261For example, a usage statement that includes '*base':STRUCT-NAME
e790e666 262means that an expression has an optional key 'base', which if present
3b2a8b85 263must have a value that forms a struct name.
e790e666
EB
264
265
266=== Built-in Types ===
267
f133f2db
MA
268The following types are predefined, and map to C as follows:
269
270 Schema C JSON
271 str char * any JSON string, UTF-8
272 number double any JSON number
273 int int64_t a JSON number without fractional part
274 that fits into the C integer type
275 int8 int8_t likewise
276 int16 int16_t likewise
277 int32 int32_t likewise
278 int64 int64_t likewise
279 uint8 uint8_t likewise
280 uint16 uint16_t likewise
281 uint32 uint32_t likewise
282 uint64 uint64_t likewise
283 size uint64_t like uint64_t, except StringInputVisitor
284 accepts size suffixes
285 bool bool JSON true or false
4d2d5c41 286 null QNull * JSON null
28770e05 287 any QObject * any JSON value
7264f5c5 288 QType QType JSON string matching enum QType values
51631493 289
a719a27c 290
bc52d03f 291=== Include directives ===
a719a27c 292
e790e666
EB
293Usage: { 'include': STRING }
294
a719a27c
LV
295The QAPI schema definitions can be modularized using the 'include' directive:
296
e790e666 297 { 'include': 'path/to/file.json' }
a719a27c
LV
298
299The directive is evaluated recursively, and include paths are relative to the
e790e666 300file using the directive. Multiple includes of the same file are
4247f839 301idempotent. No other keys should appear in the expression, and the include
e790e666
EB
302value should be a string.
303
304As a matter of style, it is a good idea to have all files be
305self-contained, but at the moment, nothing prevents an included file
306from making a forward reference to a type that is only introduced by
307an outer file. The parser may be made stricter in the future to
308prevent incomplete include files.
a719a27c
LV
309
310
bc52d03f
MA
311=== Pragma directives ===
312
313Usage: { 'pragma': DICT }
314
315The pragma directive lets you control optional generator behavior.
316The dictionary's entries are pragma names and values.
317
318Pragma's scope is currently the complete schema. Setting the same
319pragma to different values in parts of the schema doesn't work.
320
321Pragma 'doc-required' takes a boolean value. If true, documentation
322is required. Default is false.
323
1554a8fa
MA
324Pragma 'returns-whitelist' takes a list of command names that may
325violate the rules on permitted return types. Default is none.
326
2cfbae3c
MA
327Pragma 'name-case-whitelist' takes a list of names that may violate
328rules on use of upper- vs. lower-case letters. Default is none.
329
bc52d03f 330
3b2a8b85 331=== Struct types ===
51631493 332
3b2a8b85 333Usage: { 'struct': STRING, 'data': DICT, '*base': STRUCT-NAME }
e790e666 334
02a57ae3
EB
335A struct is a dictionary containing a single 'data' key whose value is
336a dictionary; the dictionary may be empty. This corresponds to a
337struct in C or an Object in JSON. Each value of the 'data' dictionary
338must be the name of a type, or a one-element array containing a type
339name. An example of a struct is:
b84da831 340
3b2a8b85 341 { 'struct': 'MyType',
acf8394e 342 'data': { 'member1': 'str', 'member2': 'int', '*member3': 'str' } }
b84da831 343
e790e666 344The use of '*' as a prefix to the name means the member is optional in
363b4262 345the corresponding JSON protocol usage.
cc162655
EB
346
347The default initialization value of an optional argument should not be changed
348between versions of QEMU unless the new default maintains backward
349compatibility to the user-visible behavior of the old default.
350
351With proper documentation, this policy still allows some flexibility; for
352example, documenting that a default of 0 picks an optimal buffer size allows
353one release to declare the optimal size at 512 while another release declares
354the optimal size at 4096 - the user-visible behavior is not the bytes used by
355the buffer, but the fact that the buffer was optimal size.
356
357On input structures (only mentioned in the 'data' side of a command), changing
358from mandatory to optional is safe (older clients will supply the option, and
359newer clients can benefit from the default); changing from optional to
360mandatory is backwards incompatible (older clients may be omitting the option,
361and must continue to work).
362
363On output structures (only mentioned in the 'returns' side of a command),
364changing from mandatory to optional is in general unsafe (older clients may be
9ee86b85
EB
365expecting the member, and could crash if it is missing), although it
366can be done if the only way that the optional argument will be omitted
367is when it is triggered by the presence of a new input flag to the
368command that older clients don't know to send. Changing from optional
369to mandatory is safe.
cc162655
EB
370
371A structure that is used in both input and output of various commands
372must consider the backwards compatibility constraints of both directions
373of use.
622f557f 374
3b2a8b85 375A struct definition can specify another struct as its base.
9ee86b85 376In this case, the members of the base type are included as top-level members
363b4262
EB
377of the new struct's dictionary in the Client JSON Protocol wire
378format. An example definition is:
622f557f 379
3b2a8b85
EB
380 { 'struct': 'BlockdevOptionsGenericFormat', 'data': { 'file': 'str' } }
381 { 'struct': 'BlockdevOptionsGenericCOWFormat',
622f557f
KW
382 'base': 'BlockdevOptionsGenericFormat',
383 'data': { '*backing': 'str' } }
384
385An example BlockdevOptionsGenericCOWFormat object on the wire could use
9ee86b85 386both members like this:
622f557f
KW
387
388 { "file": "/some/place/my-image",
389 "backing": "/some/place/my-backing-file" }
390
e790e666 391
51631493
KW
392=== Enumeration types ===
393
e790e666 394Usage: { 'enum': STRING, 'data': ARRAY-OF-STRING }
351d36e4 395 { 'enum': STRING, '*prefix': STRING, 'data': ARRAY-OF-STRING }
e790e666
EB
396
397An enumeration type is a dictionary containing a single 'data' key
398whose value is a list of strings. An example enumeration is:
b84da831
MR
399
400 { 'enum': 'MyEnum', 'data': [ 'value1', 'value2', 'value3' ] }
401
e790e666
EB
402Nothing prevents an empty enumeration, although it is probably not
403useful. The list of strings should be lower case; if an enum name
404represents multiple words, use '-' between words. The string 'max' is
405not allowed as an enum value, and values should not be repeated.
406
351d36e4
DB
407The enum constants will be named by using a heuristic to turn the
408type name into a set of underscore separated words. For the example
409above, 'MyEnum' will turn into 'MY_ENUM' giving a constant name
410of 'MY_ENUM_VALUE1' for the first value. If the default heuristic
9ee86b85 411does not result in a desirable name, the optional 'prefix' member
351d36e4
DB
412can be used when defining the enum.
413
363b4262
EB
414The enumeration values are passed as strings over the Client JSON
415Protocol, but are encoded as C enum integral values in generated code.
416While the C code starts numbering at 0, it is better to use explicit
e790e666
EB
417comparisons to enum values than implicit comparisons to 0; the C code
418will also include a generated enum member ending in _MAX for tracking
419the size of the enum, useful when using common functions for
420converting between strings and enum values. Since the wire format
421always passes by name, it is acceptable to reorder or add new
363b4262
EB
422enumeration members in any location without breaking clients of Client
423JSON Protocol; however, removing enum values would break
9ee86b85
EB
424compatibility. For any struct that has a member that will only contain
425a finite set of string values, using an enum type for that member is
426better than open-coding the member to be type 'str'.
e790e666
EB
427
428
51631493
KW
429=== Union types ===
430
e790e666 431Usage: { 'union': STRING, 'data': DICT }
ac4338f8 432or: { 'union': STRING, 'data': DICT, 'base': STRUCT-NAME-OR-DICT,
e790e666 433 'discriminator': ENUM-MEMBER-OF-BASE }
51631493 434
e790e666 435Union types are used to let the user choose between several different
7b1b98c4 436variants for an object. There are two flavors: simple (no
02a57ae3 437discriminator or base), and flat (both discriminator and base). A union
7b1b98c4 438type is defined using a data dictionary as explained in the following
0ced9531 439paragraphs. Unions must have at least one branch.
51631493 440
e790e666
EB
441A simple union type defines a mapping from automatic discriminator
442values to data types like in this example:
51631493 443
bd59adce
EB
444 { 'struct': 'BlockdevOptionsFile', 'data': { 'filename': 'str' } }
445 { 'struct': 'BlockdevOptionsQcow2',
446 'data': { 'backing': 'str', '*lazy-refcounts': 'bool' } }
51631493 447
bd59adce
EB
448 { 'union': 'BlockdevOptionsSimple',
449 'data': { 'file': 'BlockdevOptionsFile',
450 'qcow2': 'BlockdevOptionsQcow2' } }
51631493 451
363b4262 452In the Client JSON Protocol, a simple union is represented by a
9ee86b85
EB
453dictionary that contains the 'type' member as a discriminator, and a
454'data' member that is of the specified data type corresponding to the
363b4262 455discriminator value, as in these examples:
51631493 456
bd59adce
EB
457 { "type": "file", "data": { "filename": "/some/place/my-image" } }
458 { "type": "qcow2", "data": { "backing": "/some/place/my-image",
459 "lazy-refcounts": true } }
51631493 460
e790e666
EB
461The generated C code uses a struct containing a union. Additionally,
462an implicit C enum 'NameKind' is created, corresponding to the union
e24fe238
MA
463'Name', for accessing the various branches of the union. The value
464for each branch can be of any type.
51631493 465
ac4338f8
EB
466A flat union definition avoids nesting on the wire, and specifies a
467set of common members that occur in all variants of the union. The
d33c8a7d 468'base' key must specify either a type name (the type must be a
ac4338f8 469struct, not a union), or a dictionary representing an anonymous type.
e24fe238 470All branches of the union must be struct types, and the top-level
ac4338f8
EB
471members of the union dictionary on the wire will be combination of
472members from both the base type and the appropriate branch type (when
473merging two dictionaries, there must be no keys in common). The
474'discriminator' member must be the name of a non-optional enum-typed
475member of the base struct.
51631493 476
e790e666 477The following example enhances the above simple union example by
bd59adce
EB
478adding an optional common member 'read-only', renaming the
479discriminator to something more applicable than the simple union's
480default of 'type', and reducing the number of {} required on the wire:
50f2bdc7 481
94a3f0af 482 { 'enum': 'BlockdevDriver', 'data': [ 'file', 'qcow2' ] }
50f2bdc7 483 { 'union': 'BlockdevOptions',
ac4338f8 484 'base': { 'driver': 'BlockdevDriver', '*read-only': 'bool' },
50f2bdc7 485 'discriminator': 'driver',
bd59adce
EB
486 'data': { 'file': 'BlockdevOptionsFile',
487 'qcow2': 'BlockdevOptionsQcow2' } }
50f2bdc7 488
e790e666
EB
489Resulting in these JSON objects:
490
bd59adce 491 { "driver": "file", "read-only": true,
e790e666 492 "filename": "/some/place/my-image" }
bd59adce
EB
493 { "driver": "qcow2", "read-only": false,
494 "backing": "/some/place/my-image", "lazy-refcounts": true }
e790e666
EB
495
496Notice that in a flat union, the discriminator name is controlled by
497the user, but because it must map to a base member with enum type, the
800877bb
AN
498code generator ensures that branches match the existing values of the
499enum. The order of the keys need not match the declaration of the enum.
500The keys need not cover all possible enum values. Omitted enum values
501are still valid branches that add no additional members to the data type.
502In the resulting generated C data types, a flat union is
9ee86b85
EB
503represented as a struct with the base members included directly, and
504then a union of structures for each branch of the struct.
e790e666
EB
505
506A simple union can always be re-written as a flat union where the base
507class has a single member named 'type', and where each branch of the
3b2a8b85 508union has a struct with a single member named 'data'. That is,
50f2bdc7 509
e790e666 510 { 'union': 'Simple', 'data': { 'one': 'str', 'two': 'int' } }
50f2bdc7 511
e790e666 512is identical on the wire to:
50f2bdc7 513
e790e666 514 { 'enum': 'Enum', 'data': ['one', 'two'] }
3b2a8b85
EB
515 { 'struct': 'Branch1', 'data': { 'data': 'str' } }
516 { 'struct': 'Branch2', 'data': { 'data': 'int' } }
ac4338f8 517 { 'union': 'Flat': 'base': { 'type': 'Enum' }, 'discriminator': 'type',
e790e666 518 'data': { 'one': 'Branch1', 'two': 'Branch2' } }
69dd62df 519
e790e666 520
7b1b98c4 521=== Alternate types ===
69dd62df 522
7b1b98c4
EB
523Usage: { 'alternate': STRING, 'data': DICT }
524
525An alternate type is one that allows a choice between two or more JSON
526data types (string, integer, number, or object, but currently not
527array) on the wire. The definition is similar to a simple union type,
528where each branch of the union names a QAPI type. For example:
529
bd59adce 530 { 'alternate': 'BlockdevRef',
69dd62df
KW
531 'data': { 'definition': 'BlockdevOptions',
532 'reference': 'str' } }
533
7b1b98c4 534Unlike a union, the discriminator string is never passed on the wire
363b4262
EB
535for the Client JSON Protocol. Instead, the value's JSON type serves
536as an implicit discriminator, which in turn means that an alternate
537can only express a choice between types represented differently in
538JSON. If a branch is typed as the 'bool' built-in, the alternate
539accepts true and false; if it is typed as any of the various numeric
540built-ins, it accepts a JSON number; if it is typed as a 'str'
4d2d5c41
MA
541built-in or named enum type, it accepts a JSON string; if it is typed
542as the 'null' built-in, it accepts JSON null; and if it is typed as a
543complex type (struct or union), it accepts a JSON object. Two
544different complex types, for instance, aren't permitted, because both
545are represented as a JSON object.
7b1b98c4
EB
546
547The example alternate declaration above allows using both of the
548following example objects:
69dd62df
KW
549
550 { "file": "my_existing_block_device_id" }
551 { "file": { "driver": "file",
bd59adce 552 "read-only": false,
63922c64 553 "filename": "/tmp/mydisk.qcow2" } }
69dd62df
KW
554
555
51631493 556=== Commands ===
b84da831 557
378112b0
PX
558--- General Command Layout ---
559
e790e666 560Usage: { 'command': STRING, '*data': COMPLEX-TYPE-NAME-OR-DICT,
c818408e 561 '*returns': TYPE-NAME, '*boxed': true,
378112b0 562 '*gen': false, '*success-response': false,
d6fe3d02 563 '*allow-oob': true, '*allow-preconfig': true }
e790e666
EB
564
565Commands are defined by using a dictionary containing several members,
566where three members are most common. The 'command' member is a
363b4262
EB
567mandatory string, and determines the "execute" value passed in a
568Client JSON Protocol command exchange.
e790e666
EB
569
570The 'data' argument maps to the "arguments" dictionary passed in as
363b4262
EB
571part of a Client JSON Protocol command. The 'data' member is optional
572and defaults to {} (an empty dictionary). If present, it must be the
315932b5 573string name of a complex type, or a dictionary that declares an
700dc9f5 574anonymous type with the same semantics as a 'struct' expression.
e790e666 575
9ee86b85 576The 'returns' member describes what will appear in the "return" member
363b4262
EB
577of a Client JSON Protocol reply on successful completion of a command.
578The member is optional from the command declaration; if absent, the
9ee86b85 579"return" member will be an empty dictionary. If 'returns' is present,
e24fe238
MA
580it must be the string name of a complex type, or a
581one-element array containing the name of a complex type.
1554a8fa
MA
582To return anything else, you have to list the command in pragma
583'returns-whitelist'. If you do this, the command cannot be extended
584to return additional information in the future. Use of
585'returns-whitelist' for new commands is strongly discouraged.
363b4262
EB
586
587All commands in Client JSON Protocol use a dictionary to report
588failure, with no way to specify that in QAPI. Where the error return
589is different than the usual GenericError class in order to help the
590client react differently to certain error conditions, it is worth
591documenting this in the comments before the command declaration.
e790e666
EB
592
593Some example commands:
594
595 { 'command': 'my-first-command',
596 'data': { 'arg1': 'str', '*arg2': 'str' } }
3b2a8b85 597 { 'struct': 'MyType', 'data': { '*value': 'str' } }
e790e666
EB
598 { 'command': 'my-second-command',
599 'returns': [ 'MyType' ] }
600
363b4262 601which would validate this Client JSON Protocol transaction:
e790e666
EB
602
603 => { "execute": "my-first-command",
604 "arguments": { "arg1": "hello" } }
605 <= { "return": { } }
606 => { "execute": "my-second-command" }
607 <= { "return": [ { "value": "one" }, { } ] }
608
c818408e
EB
609The generator emits a prototype for the user's function implementing
610the command. Normally, 'data' is a dictionary for an anonymous type,
611or names a struct type (possibly empty, but not a union), and its
612members are passed as separate arguments to this function. If the
613command definition includes a key 'boxed' with the boolean value true,
b22e8658
MA
614then 'data' is instead the name of any non-empty complex type (struct
615or union), and a pointer to that QAPI type is passed as a single
616argument.
c818408e
EB
617
618The generator also emits a marshalling function that extracts
619arguments for the user's function out of an input QDict, calls the
620user's function, and if it succeeded, builds an output QObject from
621its return value.
622
e790e666 623In rare cases, QAPI cannot express a type-safe representation of a
2d21291a
MA
624corresponding Client JSON Protocol command. You then have to suppress
625generation of a marshalling function by including a key 'gen' with
153d73f3
MA
626boolean value false, and instead write your own function. For
627example:
e790e666
EB
628
629 { 'command': 'netdev_add',
b8a98326 630 'data': {'type': 'str', 'id': 'str'},
e790e666
EB
631 'gen': false }
632
153d73f3
MA
633Please try to avoid adding new commands that rely on this, and instead
634use type-safe unions.
635
e790e666
EB
636Normally, the QAPI schema is used to describe synchronous exchanges,
637where a response is expected. But in some cases, the action of a
638command is expected to change state in a way that a successful
639response is not possible (although the command will still return a
640normal dictionary error on failure). When a successful reply is not
153d73f3 641possible, the command expression includes the optional key
e790e666 642'success-response' with boolean value false. So far, only QGA makes
9ee86b85 643use of this member.
b84da831 644
153d73f3
MA
645Key 'allow-oob' declares whether the command supports out-of-band
646(OOB) execution. It defaults to false. For example:
378112b0
PX
647
648 { 'command': 'migrate_recover',
649 'data': { 'uri': 'str' }, 'allow-oob': true }
650
153d73f3 651See qmp-spec.txt for out-of-band execution syntax and semantics.
378112b0 652
153d73f3
MA
653Commands supporting out-of-band execution can still be executed
654in-band.
378112b0 655
153d73f3
MA
656When a command is executed in-band, its handler runs in the main
657thread with the BQL held.
378112b0 658
153d73f3
MA
659When a command is executed out-of-band, its handler runs in a
660dedicated monitor I/O thread with the BQL *not* held.
378112b0 661
153d73f3 662An OOB-capable command handler must satisfy the following conditions:
378112b0 663
153d73f3
MA
664- It terminates quickly.
665- It does not invoke system calls that may block.
378112b0 666- It does not access guest RAM that may block when userfaultfd is
153d73f3 667 enabled for postcopy live migration.
4bfa7974
PX
668- It takes only "fast" locks, i.e. all critical sections protected by
669 any lock it takes also satisfy the conditions for OOB command
670 handler code.
671
672The restrictions on locking limit access to shared state. Such access
673requires synchronization, but OOB commands can't take the BQL or any
674other "slow" lock.
378112b0 675
153d73f3 676When in doubt, do not implement OOB execution support.
b84da831 677
153d73f3
MA
678Key 'allow-preconfig' declares whether the command is available before
679the machine is built. It defaults to false. For example:
d6fe3d02 680
d6fe3d02
IM
681 { 'command': 'qmp_capabilities',
682 'data': { '*enable': [ 'QMPCapability' ] },
683 'allow-preconfig': true }
684
153d73f3
MA
685QMP is available before the machine is built only when QEMU was
686started with --preconfig.
687
21cd70df
WX
688=== Events ===
689
c818408e
EB
690Usage: { 'event': STRING, '*data': COMPLEX-TYPE-NAME-OR-DICT,
691 '*boxed': true }
e790e666 692
e24fe238
MA
693Events are defined with the keyword 'event'. When 'data' is also
694specified, additional info will be included in the event, with similar
695semantics to a 'struct' expression. Finally there will be C API
696generated in qapi-events.h; when called by QEMU code, a message with
697timestamp will be emitted on the wire.
21cd70df
WX
698
699An example event is:
700
701{ 'event': 'EVENT_C',
702 'data': { '*a': 'int', 'b': 'str' } }
703
704Resulting in this JSON object:
705
706{ "event": "EVENT_C",
707 "data": { "b": "test string" },
708 "timestamp": { "seconds": 1267020223, "microseconds": 435656 } }
b84da831 709
c818408e
EB
710The generator emits a function to send the event. Normally, 'data' is
711a dictionary for an anonymous type, or names a struct type (possibly
712empty, but not a union), and its members are passed as separate
713arguments to this function. If the event definition includes a key
b22e8658
MA
714'boxed' with the boolean value true, then 'data' is instead the name
715of any non-empty complex type (struct or union), and a pointer to that
716QAPI type is passed as a single argument.
c818408e 717
59a2c4ce 718
6a8c0b51
KW
719=== Features ===
720
721Sometimes, the behaviour of QEMU changes compatibly, but without a
722change in the QMP syntax (usually by allowing values or operations that
723previously resulted in an error). QMP clients may still need to know
724whether the extension is available.
725
726For this purpose, a list of features can be specified for a struct type.
727This is exposed to the client as a list of string, where each string
728signals that this build of QEMU shows a certain behaviour.
729
730In the schema, features can be specified as simple strings, for example:
731
732{ 'struct': 'TestType',
733 'data': { 'number': 'int' },
734 'features': [ 'allow-negative-numbers' ] }
735
736Another option is to specify features as dictionaries, where the key
737'name' specifies the feature string to be exposed to clients:
738
739{ 'struct': 'TestType',
740 'data': { 'number': 'int' },
741 'features': [ { 'name': 'allow-negative-numbers' } ] }
742
743This expanded form is necessary if you want to make the feature
744conditional (see below in "Configuring the schema").
745
746
79f75981
MA
747=== Downstream extensions ===
748
749QAPI schema names that are externally visible, say in the Client JSON
750Protocol, need to be managed with care. Names starting with a
751downstream prefix of the form __RFQDN_ are reserved for the downstream
752who controls the valid, reverse fully qualified domain name RFQDN.
753RFQDN may only contain ASCII letters, digits, hyphen and period.
754
755Example: Red Hat, Inc. controls redhat.com, and may therefore add a
756downstream command __com.redhat_drive-mirror.
757
758
967c8851
MAL
759=== Configuring the schema ===
760
761The 'struct', 'enum', 'union', 'alternate', 'command' and 'event'
762top-level expressions can take an 'if' key. Its value must be a string
763or a list of strings. A string is shorthand for a list containing just
764that string. The code generated for the top-level expression will then
765be guarded by #if COND for each COND in the list.
766
767Example: a conditional struct
768
769 { 'struct': 'IfStruct', 'data': { 'foo': 'int' },
770 'if': ['defined(CONFIG_FOO)', 'defined(HAVE_BAR)'] }
771
772gets its generated code guarded like this:
773
774 #if defined(CONFIG_FOO)
775 #if defined(HAVE_BAR)
776 ... generated code ...
777 #endif /* defined(HAVE_BAR) */
778 #endif /* defined(CONFIG_FOO) */
779
ccadd6bc
MAL
780Where a member can be defined with a single string value for its type,
781it is also possible to supply a dictionary instead with both 'type'
3e270dca 782and 'if' keys.
ccadd6bc
MAL
783
784Example: a conditional 'bar' member
785
786{ 'struct': 'IfStruct', 'data':
787 { 'foo': 'int',
788 'bar': { 'type': 'int', 'if': 'defined(IFCOND)'} } }
789
6cc32b0e
MAL
790An enum value can be replaced by a dictionary with a 'name' and a 'if'
791key.
792
793Example: a conditional 'bar' enum member.
794
795{ 'enum': 'IfEnum', 'data':
796 [ 'foo',
797 { 'name' : 'bar', 'if': 'defined(IFCOND)' } ] }
798
6a8c0b51
KW
799Similarly, features can be specified as a dictionary with a 'name' and
800an 'if' key.
801
802Example: a conditional 'allow-negative-numbers' feature
803
804{ 'struct': 'TestType',
805 'data': { 'number': 'int' },
806 'features': [ { 'name': 'allow-negative-numbers',
807 'if' 'defined(IFCOND)' } ] }
808
967c8851
MAL
809Please note that you are responsible to ensure that the C code will
810compile with an arbitrary combination of conditions, since the
811generators are unable to check it at this point.
812
813The presence of 'if' keys in the schema is reflected through to the
814introspection output depending on the build configuration.
815
816
39a18158
MA
817== Client JSON Protocol introspection ==
818
819Clients of a Client JSON Protocol commonly need to figure out what
820exactly the server (QEMU) supports.
821
822For this purpose, QMP provides introspection via command
823query-qmp-schema. QGA currently doesn't support introspection.
824
39a65e2c
EB
825While Client JSON Protocol wire compatibility should be maintained
826between qemu versions, we cannot make the same guarantees for
827introspection stability. For example, one version of qemu may provide
828a non-variant optional member of a struct, and a later version rework
829the member to instead be non-optional and associated with a variant.
830Likewise, one version of qemu may list a member with open-ended type
831'str', and a later version could convert it to a finite set of strings
832via an enum type; or a member may be converted from a specific type to
833an alternate that represents a choice between the original type and
834something else.
835
39a18158
MA
836query-qmp-schema returns a JSON array of SchemaInfo objects. These
837objects together describe the wire ABI, as defined in the QAPI schema.
f5455044
EB
838There is no specified order to the SchemaInfo objects returned; a
839client must search for a particular name throughout the entire array
840to learn more about that name, but is at least guaranteed that there
841will be no collisions between type, command, and event names.
39a18158
MA
842
843However, the SchemaInfo can't reflect all the rules and restrictions
844that apply to QMP. It's interface introspection (figuring out what's
845there), not interface specification. The specification is in the QAPI
846schema. To understand how QMP is to be used, you need to study the
847QAPI schema.
848
849Like any other command, query-qmp-schema is itself defined in the QAPI
850schema, along with the SchemaInfo type. This text attempts to give an
851overview how things work. For details you need to consult the QAPI
852schema.
853
854SchemaInfo objects have common members "name" and "meta-type", and
855additional variant members depending on the value of meta-type.
856
857Each SchemaInfo object describes a wire ABI entity of a certain
858meta-type: a command, event or one of several kinds of type.
859
1a9a507b
MA
860SchemaInfo for commands and events have the same name as in the QAPI
861schema.
39a18158
MA
862
863Command and event names are part of the wire ABI, but type names are
1a9a507b
MA
864not. Therefore, the SchemaInfo for types have auto-generated
865meaningless names. For readability, the examples in this section use
866meaningful type names instead.
867
868To examine a type, start with a command or event using it, then follow
869references by name.
39a18158
MA
870
871QAPI schema definitions not reachable that way are omitted.
872
873The SchemaInfo for a command has meta-type "command", and variant
378112b0
PX
874members "arg-type", "ret-type" and "allow-oob". On the wire, the
875"arguments" member of a client's "execute" command must conform to the
876object type named by "arg-type". The "return" member that the server
877passes in a success response conforms to the type named by
878"ret-type". When "allow-oob" is set, it means the command supports
879out-of-band execution.
39a18158
MA
880
881If the command takes no arguments, "arg-type" names an object type
882without members. Likewise, if the command returns nothing, "ret-type"
883names an object type without members.
884
885Example: the SchemaInfo for command query-qmp-schema
886
887 { "name": "query-qmp-schema", "meta-type": "command",
7599697c 888 "arg-type": "q_empty", "ret-type": "SchemaInfoList" }
39a18158 889
7599697c 890 Type "q_empty" is an automatic object type without members, and type
39a18158
MA
891 "SchemaInfoList" is the array of SchemaInfo type.
892
893The SchemaInfo for an event has meta-type "event", and variant member
894"arg-type". On the wire, a "data" member that the server passes in an
895event conforms to the object type named by "arg-type".
896
897If the event carries no additional information, "arg-type" names an
898object type without members. The event may not have a data member on
899the wire then.
900
901Each command or event defined with dictionary-valued 'data' in the
1a9a507b 902QAPI schema implicitly defines an object type.
39a18158
MA
903
904Example: the SchemaInfo for EVENT_C from section Events
905
906 { "name": "EVENT_C", "meta-type": "event",
7599697c 907 "arg-type": "q_obj-EVENT_C-arg" }
39a18158 908
7599697c 909 Type "q_obj-EVENT_C-arg" is an implicitly defined object type with
39a18158
MA
910 the two members from the event's definition.
911
912The SchemaInfo for struct and union types has meta-type "object".
913
914The SchemaInfo for a struct type has variant member "members".
915
916The SchemaInfo for a union type additionally has variant members "tag"
917and "variants".
918
919"members" is a JSON array describing the object's common members, if
920any. Each element is a JSON object with members "name" (the member's
921name), "type" (the name of its type), and optionally "default". The
922member is optional if "default" is present. Currently, "default" can
923only have value null. Other values are reserved for future
f5455044
EB
924extensions. The "members" array is in no particular order; clients
925must search the entire object when learning whether a particular
926member is supported.
39a18158
MA
927
928Example: the SchemaInfo for MyType from section Struct types
929
930 { "name": "MyType", "meta-type": "object",
931 "members": [
932 { "name": "member1", "type": "str" },
933 { "name": "member2", "type": "int" },
934 { "name": "member3", "type": "str", "default": null } ] }
935
936"tag" is the name of the common member serving as type tag.
937"variants" is a JSON array describing the object's variant members.
938Each element is a JSON object with members "case" (the value of type
939tag this element applies to) and "type" (the name of an object type
f5455044
EB
940that provides the variant members for this type tag value). The
941"variants" array is in no particular order, and is not guaranteed to
942list cases in the same order as the corresponding "tag" enum type.
39a18158
MA
943
944Example: the SchemaInfo for flat union BlockdevOptions from section
945Union types
946
947 { "name": "BlockdevOptions", "meta-type": "object",
948 "members": [
949 { "name": "driver", "type": "BlockdevDriver" },
bd59adce 950 { "name": "read-only", "type": "bool", "default": null } ],
39a18158
MA
951 "tag": "driver",
952 "variants": [
bd59adce
EB
953 { "case": "file", "type": "BlockdevOptionsFile" },
954 { "case": "qcow2", "type": "BlockdevOptionsQcow2" } ] }
39a18158
MA
955
956Note that base types are "flattened": its members are included in the
957"members" array.
958
959A simple union implicitly defines an enumeration type for its implicit
960discriminator (called "type" on the wire, see section Union types).
39a18158
MA
961
962A simple union implicitly defines an object type for each of its
1a9a507b 963variants.
39a18158 964
bd59adce 965Example: the SchemaInfo for simple union BlockdevOptionsSimple from section
39a18158
MA
966Union types
967
bd59adce 968 { "name": "BlockdevOptionsSimple", "meta-type": "object",
39a18158 969 "members": [
bd59adce 970 { "name": "type", "type": "BlockdevOptionsSimpleKind" } ],
39a18158
MA
971 "tag": "type",
972 "variants": [
bd59adce
EB
973 { "case": "file", "type": "q_obj-BlockdevOptionsFile-wrapper" },
974 { "case": "qcow2", "type": "q_obj-BlockdevOptionsQcow2-wrapper" } ] }
39a18158 975
bd59adce
EB
976 Enumeration type "BlockdevOptionsSimpleKind" and the object types
977 "q_obj-BlockdevOptionsFile-wrapper", "q_obj-BlockdevOptionsQcow2-wrapper"
978 are implicitly defined.
39a18158
MA
979
980The SchemaInfo for an alternate type has meta-type "alternate", and
981variant member "members". "members" is a JSON array. Each element is
982a JSON object with member "type", which names a type. Values of the
f5455044
EB
983alternate type conform to exactly one of its member types. There is
984no guarantee on the order in which "members" will be listed.
39a18158 985
bd59adce 986Example: the SchemaInfo for BlockdevRef from section Alternate types
39a18158 987
bd59adce 988 { "name": "BlockdevRef", "meta-type": "alternate",
39a18158
MA
989 "members": [
990 { "type": "BlockdevOptions" },
991 { "type": "str" } ] }
992
993The SchemaInfo for an array type has meta-type "array", and variant
994member "element-type", which names the array's element type. Array
ce5fcb47
EB
995types are implicitly defined. For convenience, the array's name may
996resemble the element type; however, clients should examine member
997"element-type" instead of making assumptions based on parsing member
998"name".
39a18158
MA
999
1000Example: the SchemaInfo for ['str']
1001
ce5fcb47 1002 { "name": "[str]", "meta-type": "array",
39a18158
MA
1003 "element-type": "str" }
1004
1005The SchemaInfo for an enumeration type has meta-type "enum" and
f5455044
EB
1006variant member "values". The values are listed in no particular
1007order; clients must search the entire enum when learning whether a
1008particular value is supported.
39a18158
MA
1009
1010Example: the SchemaInfo for MyEnum from section Enumeration types
1011
1012 { "name": "MyEnum", "meta-type": "enum",
1013 "values": [ "value1", "value2", "value3" ] }
1014
1015The SchemaInfo for a built-in type has the same name as the type in
1016the QAPI schema (see section Built-in Types), with one exception
1017detailed below. It has variant member "json-type" that shows how
1018values of this type are encoded on the wire.
1019
1020Example: the SchemaInfo for str
1021
1022 { "name": "str", "meta-type": "builtin", "json-type": "string" }
1023
1024The QAPI schema supports a number of integer types that only differ in
1025how they map to C. They are identical as far as SchemaInfo is
1026concerned. Therefore, they get all mapped to a single type "int" in
1027SchemaInfo.
1028
1029As explained above, type names are not part of the wire ABI. Not even
1030the names of built-in types. Clients should examine member
1031"json-type" instead of hard-coding names of built-in types.
1032
1033
b84da831
MR
1034== Code generation ==
1035
fb0bc835
MA
1036The QAPI code generator qapi-gen.py generates code and documentation
1037from the schema. Together with the core QAPI libraries, this code
1038provides everything required to take JSON commands read in by a Client
1039JSON Protocol server, unmarshal the arguments into the underlying C
1040types, call into the corresponding C function, map the response back
1041to a Client JSON Protocol response to be returned to the user, and
1042introspect the commands.
b84da831 1043
9ee86b85
EB
1044As an example, we'll use the following schema, which describes a
1045single complex user-defined type, along with command which takes a
1046list of that type as a parameter, and returns a single element of that
1047type. The user is responsible for writing the implementation of
1048qmp_my_command(); everything else is produced by the generator.
b84da831 1049
87a560c4 1050 $ cat example-schema.json
3b2a8b85 1051 { 'struct': 'UserDefOne',
9ee86b85 1052 'data': { 'integer': 'int', '*string': 'str' } }
b84da831
MR
1053
1054 { 'command': 'my-command',
9ee86b85 1055 'data': { 'arg1': ['UserDefOne'] },
b84da831 1056 'returns': 'UserDefOne' }
b84da831 1057
59a2c4ce
EB
1058 { 'event': 'MY_EVENT' }
1059
fb0bc835
MA
1060We run qapi-gen.py like this:
1061
1062 $ python scripts/qapi-gen.py --output-dir="qapi-generated" \
1063 --prefix="example-" example-schema.json
1064
9ee86b85
EB
1065For a more thorough look at generated code, the testsuite includes
1066tests/qapi-schema/qapi-schema-tests.json that covers more examples of
1067what the generator will accept, and compiles the resulting C code as
1068part of 'make check-unit'.
1069
fb0bc835 1070=== Code generated for QAPI types ===
b84da831 1071
fb0bc835 1072The following files are created:
b84da831
MR
1073
1074$(prefix)qapi-types.h - C types corresponding to types defined in
fb0bc835
MA
1075 the schema
1076
b84da831
MR
1077$(prefix)qapi-types.c - Cleanup functions for the above C types
1078
1079The $(prefix) is an optional parameter used as a namespace to keep the
1080generated code from one schema/code-generation separated from others so code
1081can be generated/used from multiple schemas without clobbering previously
1082created code.
1083
1084Example:
1085
9ee86b85
EB
1086 $ cat qapi-generated/example-qapi-types.h
1087[Uninteresting stuff omitted...]
1088
1089 #ifndef EXAMPLE_QAPI_TYPES_H
1090 #define EXAMPLE_QAPI_TYPES_H
1091
913b5e28 1092 #include "qapi/qapi-builtin-types.h"
9ee86b85
EB
1093
1094 typedef struct UserDefOne UserDefOne;
1095
1096 typedef struct UserDefOneList UserDefOneList;
1097
64355088
MA
1098 typedef struct q_obj_my_command_arg q_obj_my_command_arg;
1099
9ee86b85
EB
1100 struct UserDefOne {
1101 int64_t integer;
1102 bool has_string;
1103 char *string;
1104 };
1105
1106 void qapi_free_UserDefOne(UserDefOne *obj);
1107
1108 struct UserDefOneList {
1109 UserDefOneList *next;
1110 UserDefOne *value;
1111 };
1112
1113 void qapi_free_UserDefOneList(UserDefOneList *obj);
1114
64355088
MA
1115 struct q_obj_my_command_arg {
1116 UserDefOneList *arg1;
1117 };
1118
913b5e28 1119 #endif /* EXAMPLE_QAPI_TYPES_H */
87a560c4 1120 $ cat qapi-generated/example-qapi-types.c
6e2bb3ec
MA
1121[Uninteresting stuff omitted...]
1122
2b162ccb 1123 void qapi_free_UserDefOne(UserDefOne *obj)
6e2bb3ec 1124 {
6e2bb3ec
MA
1125 Visitor *v;
1126
1127 if (!obj) {
1128 return;
1129 }
1130
2c0ef9f4 1131 v = qapi_dealloc_visitor_new();
9ee86b85 1132 visit_type_UserDefOne(v, NULL, &obj, NULL);
2c0ef9f4 1133 visit_free(v);
6e2bb3ec 1134 }
b84da831 1135
2b162ccb 1136 void qapi_free_UserDefOneList(UserDefOneList *obj)
b84da831 1137 {
b84da831
MR
1138 Visitor *v;
1139
1140 if (!obj) {
1141 return;
1142 }
1143
2c0ef9f4 1144 v = qapi_dealloc_visitor_new();
9ee86b85 1145 visit_type_UserDefOneList(v, NULL, &obj, NULL);
2c0ef9f4 1146 visit_free(v);
b84da831 1147 }
b84da831 1148
913b5e28
MA
1149[Uninteresting stuff omitted...]
1150
ce32bf85
MA
1151For a modular QAPI schema (see section Include directives), code for
1152each sub-module SUBDIR/SUBMODULE.json is actually generated into
1153
1154SUBDIR/$(prefix)qapi-types-SUBMODULE.h
1155SUBDIR/$(prefix)qapi-types-SUBMODULE.c
1156
1157If qapi-gen.py is run with option --builtins, additional files are
1158created:
1159
1160qapi-builtin-types.h - C types corresponding to built-in types
1161
1162qapi-builtin-types.c - Cleanup functions for the above C types
1163
fb0bc835 1164=== Code generated for visiting QAPI types ===
b84da831 1165
fb0bc835
MA
1166These are the visitor functions used to walk through and convert
1167between a native QAPI C data structure and some other format (such as
1168QObject); the generated functions are named visit_type_FOO() and
1169visit_type_FOO_members().
b84da831
MR
1170
1171The following files are generated:
1172
fb0bc835 1173$(prefix)qapi-visit.c: Visitor function for a particular C type, used
b84da831
MR
1174 to automagically convert QObjects into the
1175 corresponding C type and vice-versa, as well
1176 as for deallocating memory for an existing C
1177 type
1178
fb0bc835 1179$(prefix)qapi-visit.h: Declarations for previously mentioned visitor
b84da831
MR
1180 functions
1181
1182Example:
1183
9ee86b85
EB
1184 $ cat qapi-generated/example-qapi-visit.h
1185[Uninteresting stuff omitted...]
1186
1187 #ifndef EXAMPLE_QAPI_VISIT_H
1188 #define EXAMPLE_QAPI_VISIT_H
1189
913b5e28
MA
1190 #include "qapi/qapi-builtin-visit.h"
1191 #include "example-qapi-types.h"
1192
9ee86b85
EB
1193
1194 void visit_type_UserDefOne_members(Visitor *v, UserDefOne *obj, Error **errp);
1195 void visit_type_UserDefOne(Visitor *v, const char *name, UserDefOne **obj, Error **errp);
1196 void visit_type_UserDefOneList(Visitor *v, const char *name, UserDefOneList **obj, Error **errp);
1197
64355088
MA
1198 void visit_type_q_obj_my_command_arg_members(Visitor *v, q_obj_my_command_arg *obj, Error **errp);
1199
913b5e28 1200 #endif /* EXAMPLE_QAPI_VISIT_H */
87a560c4 1201 $ cat qapi-generated/example-qapi-visit.c
6e2bb3ec 1202[Uninteresting stuff omitted...]
b84da831 1203
9ee86b85 1204 void visit_type_UserDefOne_members(Visitor *v, UserDefOne *obj, Error **errp)
6e2bb3ec
MA
1205 {
1206 Error *err = NULL;
3a864e7c 1207
9ee86b85 1208 visit_type_int(v, "integer", &obj->integer, &err);
297a3646
MA
1209 if (err) {
1210 goto out;
1211 }
9ee86b85
EB
1212 if (visit_optional(v, "string", &obj->has_string)) {
1213 visit_type_str(v, "string", &obj->string, &err);
1214 if (err) {
1215 goto out;
1216 }
297a3646 1217 }
6e2bb3ec 1218
297a3646 1219 out:
6e2bb3ec
MA
1220 error_propagate(errp, err);
1221 }
b84da831 1222
9ee86b85 1223 void visit_type_UserDefOne(Visitor *v, const char *name, UserDefOne **obj, Error **errp)
b84da831 1224 {
297a3646
MA
1225 Error *err = NULL;
1226
9ee86b85
EB
1227 visit_start_struct(v, name, (void **)obj, sizeof(UserDefOne), &err);
1228 if (err) {
1229 goto out;
1230 }
1231 if (!*obj) {
1232 goto out_obj;
6e2bb3ec 1233 }
9ee86b85 1234 visit_type_UserDefOne_members(v, *obj, &err);
15c2f669
EB
1235 if (err) {
1236 goto out_obj;
1237 }
1238 visit_check_struct(v, &err);
9ee86b85 1239 out_obj:
1158bb2a 1240 visit_end_struct(v, (void **)obj);
68ab47e4
EB
1241 if (err && visit_is_input(v)) {
1242 qapi_free_UserDefOne(*obj);
1243 *obj = NULL;
1244 }
9ee86b85 1245 out:
297a3646 1246 error_propagate(errp, err);
b84da831
MR
1247 }
1248
9ee86b85 1249 void visit_type_UserDefOneList(Visitor *v, const char *name, UserDefOneList **obj, Error **errp)
b84da831 1250 {
6e2bb3ec 1251 Error *err = NULL;
d9f62dde
EB
1252 UserDefOneList *tail;
1253 size_t size = sizeof(**obj);
6e2bb3ec 1254
d9f62dde 1255 visit_start_list(v, name, (GenericList **)obj, size, &err);
297a3646
MA
1256 if (err) {
1257 goto out;
1258 }
1259
d9f62dde
EB
1260 for (tail = *obj; tail;
1261 tail = (UserDefOneList *)visit_next_list(v, (GenericList *)tail, size)) {
1262 visit_type_UserDefOne(v, NULL, &tail->value, &err);
1263 if (err) {
1264 break;
1265 }
b84da831 1266 }
297a3646 1267
64355088
MA
1268 if (!err) {
1269 visit_check_list(v, &err);
1270 }
1158bb2a 1271 visit_end_list(v, (void **)obj);
68ab47e4
EB
1272 if (err && visit_is_input(v)) {
1273 qapi_free_UserDefOneList(*obj);
1274 *obj = NULL;
1275 }
297a3646
MA
1276 out:
1277 error_propagate(errp, err);
b84da831 1278 }
b84da831 1279
64355088
MA
1280 void visit_type_q_obj_my_command_arg_members(Visitor *v, q_obj_my_command_arg *obj, Error **errp)
1281 {
1282 Error *err = NULL;
1283
1284 visit_type_UserDefOneList(v, "arg1", &obj->arg1, &err);
1285 if (err) {
1286 goto out;
1287 }
1288
1289 out:
1290 error_propagate(errp, err);
1291 }
1292
913b5e28
MA
1293[Uninteresting stuff omitted...]
1294
ce32bf85
MA
1295For a modular QAPI schema (see section Include directives), code for
1296each sub-module SUBDIR/SUBMODULE.json is actually generated into
1297
1298SUBDIR/$(prefix)qapi-visit-SUBMODULE.h
1299SUBDIR/$(prefix)qapi-visit-SUBMODULE.c
1300
1301If qapi-gen.py is run with option --builtins, additional files are
1302created:
1303
1304qapi-builtin-visit.h - Visitor functions for built-in types
1305
1306qapi-builtin-visit.c - Declarations for these visitor functions
1307
fb0bc835
MA
1308=== Code generated for commands ===
1309
1310These are the marshaling/dispatch functions for the commands defined
1311in the schema. The generated code provides qmp_marshal_COMMAND(), and
1312declares qmp_COMMAND() that the user must implement.
b84da831 1313
fb0bc835 1314The following files are generated:
b84da831 1315
eb815e24
MA
1316$(prefix)qapi-commands.c: Command marshal/dispatch functions for each
1317 QMP command defined in the schema
b84da831 1318
eb815e24
MA
1319$(prefix)qapi-commands.h: Function prototypes for the QMP commands
1320 specified in the schema
b84da831
MR
1321
1322Example:
1323
eb815e24 1324 $ cat qapi-generated/example-qapi-commands.h
9ee86b85
EB
1325[Uninteresting stuff omitted...]
1326
913b5e28
MA
1327 #ifndef EXAMPLE_QAPI_COMMANDS_H
1328 #define EXAMPLE_QAPI_COMMANDS_H
9ee86b85
EB
1329
1330 #include "example-qapi-types.h"
64355088 1331 #include "qapi/qmp/dispatch.h"
9ee86b85
EB
1332
1333 UserDefOne *qmp_my_command(UserDefOneList *arg1, Error **errp);
64355088 1334 void qmp_marshal_my_command(QDict *args, QObject **ret, Error **errp);
913b5e28 1335 void example_qmp_init_marshal(QmpCommandList *cmds);
9ee86b85 1336
913b5e28 1337 #endif /* EXAMPLE_QAPI_COMMANDS_H */
eb815e24 1338 $ cat qapi-generated/example-qapi-commands.c
6e2bb3ec 1339[Uninteresting stuff omitted...]
b84da831 1340
56d92b00 1341 static void qmp_marshal_output_UserDefOne(UserDefOne *ret_in, QObject **ret_out, Error **errp)
b84da831 1342 {
2a0f50e8 1343 Error *err = NULL;
b84da831
MR
1344 Visitor *v;
1345
7d5e199a 1346 v = qobject_output_visitor_new(ret_out);
9ee86b85 1347 visit_type_UserDefOne(v, "unused", &ret_in, &err);
3b098d56
EB
1348 if (!err) {
1349 visit_complete(v, ret_out);
6e2bb3ec 1350 }
2a0f50e8 1351 error_propagate(errp, err);
2c0ef9f4
EB
1352 visit_free(v);
1353 v = qapi_dealloc_visitor_new();
9ee86b85 1354 visit_type_UserDefOne(v, "unused", &ret_in, NULL);
2c0ef9f4 1355 visit_free(v);
b84da831
MR
1356 }
1357
64355088 1358 void qmp_marshal_my_command(QDict *args, QObject **ret, Error **errp)
b84da831 1359 {
2a0f50e8 1360 Error *err = NULL;
3f99144c 1361 UserDefOne *retval;
b84da831 1362 Visitor *v;
64355088 1363 q_obj_my_command_arg arg = {0};
b84da831 1364
048abb7b 1365 v = qobject_input_visitor_new(QOBJECT(args));
ed841535
EB
1366 visit_start_struct(v, NULL, NULL, 0, &err);
1367 if (err) {
1368 goto out;
1369 }
64355088 1370 visit_type_q_obj_my_command_arg_members(v, &arg, &err);
15c2f669
EB
1371 if (!err) {
1372 visit_check_struct(v, &err);
1373 }
1158bb2a 1374 visit_end_struct(v, NULL);
2a0f50e8 1375 if (err) {
b84da831
MR
1376 goto out;
1377 }
297a3646 1378
64355088 1379 retval = qmp_my_command(arg.arg1, &err);
2a0f50e8 1380 if (err) {
297a3646 1381 goto out;
6e2bb3ec 1382 }
b84da831 1383
2a0f50e8 1384 qmp_marshal_output_UserDefOne(retval, ret, &err);
297a3646 1385
b84da831 1386 out:
2a0f50e8 1387 error_propagate(errp, err);
2c0ef9f4
EB
1388 visit_free(v);
1389 v = qapi_dealloc_visitor_new();
ed841535 1390 visit_start_struct(v, NULL, NULL, 0, NULL);
64355088 1391 visit_type_q_obj_my_command_arg_members(v, &arg, NULL);
1158bb2a 1392 visit_end_struct(v, NULL);
2c0ef9f4 1393 visit_free(v);
b84da831
MR
1394 }
1395
64355088 1396 void example_qmp_init_marshal(QmpCommandList *cmds)
b84da831 1397 {
64355088 1398 QTAILQ_INIT(cmds);
b84da831 1399
64355088
MA
1400 qmp_register_command(cmds, "my-command",
1401 qmp_marshal_my_command, QCO_NO_OPTIONS);
1402 }
59a2c4ce 1403
913b5e28
MA
1404[Uninteresting stuff omitted...]
1405
ce32bf85
MA
1406For a modular QAPI schema (see section Include directives), code for
1407each sub-module SUBDIR/SUBMODULE.json is actually generated into
1408
1409SUBDIR/$(prefix)qapi-commands-SUBMODULE.h
1410SUBDIR/$(prefix)qapi-commands-SUBMODULE.c
1411
fb0bc835 1412=== Code generated for events ===
59a2c4ce 1413
fb0bc835
MA
1414This is the code related to events defined in the schema, providing
1415qapi_event_send_EVENT().
1416
1417The following files are created:
59a2c4ce 1418
5d75648b 1419$(prefix)qapi-events.h - Function prototypes for each event type
fb0bc835 1420
eb815e24 1421$(prefix)qapi-events.c - Implementation of functions to send an event
59a2c4ce 1422
5d75648b
MA
1423$(prefix)qapi-emit-events.h - Enumeration of all event names, and
1424 common event code declarations
1425
1426$(prefix)qapi-emit-events.c - Common event code definitions
1427
59a2c4ce
EB
1428Example:
1429
eb815e24 1430 $ cat qapi-generated/example-qapi-events.h
9ee86b85
EB
1431[Uninteresting stuff omitted...]
1432
913b5e28
MA
1433 #ifndef EXAMPLE_QAPI_EVENTS_H
1434 #define EXAMPLE_QAPI_EVENTS_H
9ee86b85 1435
913b5e28 1436 #include "qapi/util.h"
9ee86b85
EB
1437 #include "example-qapi-types.h"
1438
3ab72385 1439 void qapi_event_send_my_event(void);
9ee86b85 1440
913b5e28 1441 #endif /* EXAMPLE_QAPI_EVENTS_H */
eb815e24 1442 $ cat qapi-generated/example-qapi-events.c
59a2c4ce
EB
1443[Uninteresting stuff omitted...]
1444
3ab72385 1445 void qapi_event_send_my_event(void)
59a2c4ce
EB
1446 {
1447 QDict *qmp;
59a2c4ce
EB
1448
1449 qmp = qmp_event_build_dict("MY_EVENT");
1450
a9529100 1451 example_qapi_event_emit(EXAMPLE_QAPI_EVENT_MY_EVENT, qmp);
59a2c4ce 1452
cb3e7f08 1453 qobject_unref(qmp);
59a2c4ce
EB
1454 }
1455
5d75648b
MA
1456[Uninteresting stuff omitted...]
1457 $ cat qapi-generated/example-qapi-emit-events.h
1458[Uninteresting stuff omitted...]
1459
1460 #ifndef EXAMPLE_QAPI_EMIT_EVENTS_H
1461 #define EXAMPLE_QAPI_EMIT_EVENTS_H
1462
1463 #include "qapi/util.h"
1464
1465 typedef enum example_QAPIEvent {
1466 EXAMPLE_QAPI_EVENT_MY_EVENT,
1467 EXAMPLE_QAPI_EVENT__MAX,
1468 } example_QAPIEvent;
1469
1470 #define example_QAPIEvent_str(val) \
1471 qapi_enum_lookup(&example_QAPIEvent_lookup, (val))
1472
1473 extern const QEnumLookup example_QAPIEvent_lookup;
1474
1475 void example_qapi_event_emit(example_QAPIEvent event, QDict *qdict);
1476
1477 #endif /* EXAMPLE_QAPI_EMIT_EVENTS_H */
1478 $ cat qapi-generated/example-qapi-emit-events.c
1479[Uninteresting stuff omitted...]
1480
fb0bc835
MA
1481 const QEnumLookup example_QAPIEvent_lookup = {
1482 .array = (const char *const[]) {
1483 [EXAMPLE_QAPI_EVENT_MY_EVENT] = "MY_EVENT",
1484 },
1485 .size = EXAMPLE_QAPI_EVENT__MAX
59a2c4ce 1486 };
39a18158 1487
913b5e28
MA
1488[Uninteresting stuff omitted...]
1489
ce32bf85
MA
1490For a modular QAPI schema (see section Include directives), code for
1491each sub-module SUBDIR/SUBMODULE.json is actually generated into
1492
1493SUBDIR/$(prefix)qapi-events-SUBMODULE.h
1494SUBDIR/$(prefix)qapi-events-SUBMODULE.c
1495
fb0bc835 1496=== Code generated for introspection ===
39a18158 1497
fb0bc835 1498The following files are created:
39a18158 1499
eb815e24 1500$(prefix)qapi-introspect.c - Defines a string holding a JSON
fb0bc835
MA
1501 description of the schema
1502
eb815e24 1503$(prefix)qapi-introspect.h - Declares the above string
39a18158
MA
1504
1505Example:
1506
eb815e24 1507 $ cat qapi-generated/example-qapi-introspect.h
39a18158
MA
1508[Uninteresting stuff omitted...]
1509
913b5e28
MA
1510 #ifndef EXAMPLE_QAPI_INTROSPECT_H
1511 #define EXAMPLE_QAPI_INTROSPECT_H
39a18158 1512
913b5e28 1513 #include "qapi/qmp/qlit.h"
39a18158 1514
913b5e28
MA
1515 extern const QLitObject example_qmp_schema_qlit;
1516
1517 #endif /* EXAMPLE_QAPI_INTROSPECT_H */
eb815e24 1518 $ cat qapi-generated/example-qapi-introspect.c
9ee86b85
EB
1519[Uninteresting stuff omitted...]
1520
7d0f982b
MAL
1521 const QLitObject example_qmp_schema_qlit = QLIT_QLIST(((QLitObject[]) {
1522 QLIT_QDICT(((QLitDictEntry[]) {
913b5e28
MA
1523 { "arg-type", QLIT_QSTR("0"), },
1524 { "meta-type", QLIT_QSTR("command"), },
1525 { "name", QLIT_QSTR("my-command"), },
1526 { "ret-type", QLIT_QSTR("1"), },
1527 {}
1528 })),
1529 QLIT_QDICT(((QLitDictEntry[]) {
1530 { "arg-type", QLIT_QSTR("2"), },
1531 { "meta-type", QLIT_QSTR("event"), },
1532 { "name", QLIT_QSTR("MY_EVENT"), },
1533 {}
7d0f982b 1534 })),
8c643361 1535 /* "0" = q_obj_my-command-arg */
7d0f982b
MAL
1536 QLIT_QDICT(((QLitDictEntry[]) {
1537 { "members", QLIT_QLIST(((QLitObject[]) {
913b5e28
MA
1538 QLIT_QDICT(((QLitDictEntry[]) {
1539 { "name", QLIT_QSTR("arg1"), },
1540 { "type", QLIT_QSTR("[1]"), },
1541 {}
1542 })),
1543 {}
1544 })), },
1545 { "meta-type", QLIT_QSTR("object"), },
1546 { "name", QLIT_QSTR("0"), },
1547 {}
7d0f982b 1548 })),
8c643361 1549 /* "1" = UserDefOne */
913b5e28
MA
1550 QLIT_QDICT(((QLitDictEntry[]) {
1551 { "members", QLIT_QLIST(((QLitObject[]) {
1552 QLIT_QDICT(((QLitDictEntry[]) {
1553 { "name", QLIT_QSTR("integer"), },
1554 { "type", QLIT_QSTR("int"), },
1555 {}
1556 })),
1557 QLIT_QDICT(((QLitDictEntry[]) {
1558 { "default", QLIT_QNULL, },
1559 { "name", QLIT_QSTR("string"), },
1560 { "type", QLIT_QSTR("str"), },
1561 {}
1562 })),
1563 {}
1564 })), },
1565 { "meta-type", QLIT_QSTR("object"), },
1566 { "name", QLIT_QSTR("1"), },
1567 {}
1568 })),
8c643361 1569 /* "2" = q_empty */
913b5e28
MA
1570 QLIT_QDICT(((QLitDictEntry[]) {
1571 { "members", QLIT_QLIST(((QLitObject[]) {
1572 {}
1573 })), },
1574 { "meta-type", QLIT_QSTR("object"), },
1575 { "name", QLIT_QSTR("2"), },
1576 {}
1577 })),
1578 QLIT_QDICT(((QLitDictEntry[]) {
1579 { "element-type", QLIT_QSTR("1"), },
1580 { "meta-type", QLIT_QSTR("array"), },
1581 { "name", QLIT_QSTR("[1]"), },
1582 {}
1583 })),
1584 QLIT_QDICT(((QLitDictEntry[]) {
1585 { "json-type", QLIT_QSTR("int"), },
1586 { "meta-type", QLIT_QSTR("builtin"), },
1587 { "name", QLIT_QSTR("int"), },
1588 {}
1589 })),
1590 QLIT_QDICT(((QLitDictEntry[]) {
1591 { "json-type", QLIT_QSTR("string"), },
1592 { "meta-type", QLIT_QSTR("builtin"), },
1593 { "name", QLIT_QSTR("str"), },
1594 {}
1595 })),
1596 {}
7d0f982b 1597 }));
913b5e28
MA
1598
1599[Uninteresting stuff omitted...]