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