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