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