qapi: Convert QType into QAPI built-in enum type
[qemu/ar7.git] / docs / qapi-code-gen.txt
blob79bf0726951350351de60b6331dedf342e5e3052
1 = How to use the QAPI code generator =
3 Copyright IBM Corp. 2011
4 Copyright (C) 2012-2015 Red Hat, Inc.
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.
9 == Introduction ==
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.
19 To map Client JSON Protocol interfaces to the native C QAPI
20 implementations, a JSON-based schema is used to define types and
21 function signatures, and a set of scripts is used to generate types,
22 signatures, and marshaling/dispatch code. This document will describe
23 how the schemas, scripts, and resulting code are used.
26 == QMP/Guest agent schema ==
28 A QAPI schema file is designed to be loosely based on JSON
29 (http://www.ietf.org/rfc/rfc7159.txt) with changes for quoting style
30 and the use of comments; a QAPI schema file is then parsed by a python
31 code generation program.  A valid QAPI schema consists of a series of
32 top-level expressions, with no commas between them.  Where
33 dictionaries (JSON objects) are used, they are parsed as python
34 OrderedDicts so that ordering is preserved (for predictable layout of
35 generated C structs and parameter lists).  Ordering doesn't matter
36 between top-level expressions or the keys within an expression, but
37 does matter within dictionary values for 'data' and 'returns' members
38 of a single expression.  QAPI schema input is written using 'single
39 quotes' instead of JSON's "double quotes" (in contrast, Client JSON
40 Protocol uses no comments, and while input accepts 'single quotes' as
41 an extension, output is strict JSON using only "double quotes").  As
42 in JSON, trailing commas are not permitted in arrays or dictionaries.
43 Input must be ASCII (although QMP supports full Unicode strings, the
44 QAPI parser does not).  At present, there is no place where a QAPI
45 schema requires the use of JSON numbers or null.
47 Comments are allowed; anything between an unquoted # and the following
48 newline is ignored.  Although there is not yet a documentation
49 generator, a form of stylized comments has developed for consistently
50 documenting details about an expression and when it was added to the
51 schema.  The documentation is delimited between two lines of ##, then
52 the first line names the expression, an optional overview is provided,
53 then individual documentation about each member of 'data' is provided,
54 and finally, a 'Since: x.y.z' tag lists the release that introduced
55 the expression.  Optional fields are tagged with the phrase
56 '#optional', often with their default value; and extensions added
57 after the expression was first released are also given a '(since
58 x.y.z)' comment.  For example:
60     ##
61     # @BlockStats:
62     #
63     # Statistics of a virtual block device or a block backing device.
64     #
65     # @device: #optional If the stats are for a virtual block device, the name
66     #          corresponding to the virtual block device.
67     #
68     # @stats:  A @BlockDeviceStats for the device.
69     #
70     # @parent: #optional This describes the file block device if it has one.
71     #
72     # @backing: #optional This describes the backing block device if it has one.
73     #           (Since 2.0)
74     #
75     # Since: 0.14.0
76     ##
77     { 'struct': 'BlockStats',
78       'data': {'*device': 'str', 'stats': 'BlockDeviceStats',
79                '*parent': 'BlockStats',
80                '*backing': 'BlockStats'} }
82 The schema sets up a series of types, as well as commands and events
83 that will use those types.  Forward references are allowed: the parser
84 scans in two passes, where the first pass learns all type names, and
85 the second validates the schema and generates the code.  This allows
86 the definition of complex structs that can have mutually recursive
87 types, and allows for indefinite nesting of Client JSON Protocol that
88 satisfies the schema.  A type name should not be defined more than
89 once.  It is permissible for the schema to contain additional types
90 not used by any commands or events in the Client JSON Protocol, for
91 the side effect of generated C code used internally.
93 There are seven top-level expressions recognized by the parser:
94 'include', 'command', 'struct', 'enum', 'union', 'alternate', and
95 'event'.  There are several groups of types: simple types (a number of
96 built-in types, such as 'int' and 'str'; as well as enumerations),
97 complex types (structs and two flavors of unions), and alternate types
98 (a choice between other types).  The 'command' and 'event' expressions
99 can refer to existing types by name, or list an anonymous type as a
100 dictionary. Listing a type name inside an array refers to a
101 single-dimension array of that type; multi-dimension arrays are not
102 directly supported (although an array of a complex struct that
103 contains an array member is possible).
105 Types, commands, and events share a common namespace.  Therefore,
106 generally speaking, type definitions should always use CamelCase for
107 user-defined type names, while built-in types are lowercase. Type
108 definitions should not end in 'Kind', as this namespace is used for
109 creating implicit C enums for visiting union types, or in 'List', as
110 this namespace is used for creating array types.  Command names,
111 and field names within a type, should be all lower case with words
112 separated by a hyphen.  However, some existing older commands and
113 complex types use underscore; when extending such expressions,
114 consistency is preferred over blindly avoiding underscore.  Event
115 names should be ALL_CAPS with words separated by underscore.  Field
116 names cannot start with 'has-' or 'has_', as this is reserved for
117 tracking optional fields.
119 Any name (command, event, type, field, or enum value) beginning with
120 "x-" is marked experimental, and may be withdrawn or changed
121 incompatibly in a future release.  All names must begin with a letter,
122 and contain only ASCII letters, digits, dash, and underscore.  There
123 are two exceptions: enum values may start with a digit, and any
124 extensions added by downstream vendors should start with a prefix
125 matching "__RFQDN_" (for the reverse-fully-qualified-domain-name of
126 the vendor), even if the rest of the name uses dash (example:
127 __com.redhat_drive-mirror).  Names beginning with 'q_' are reserved
128 for the generator: QMP names that resemble C keywords or other
129 problematic strings will be munged in C to use this prefix.  For
130 example, a field named "default" in qapi becomes "q_default" in the
131 generated C code.
133 In the rest of this document, usage lines are given for each
134 expression type, with literal strings written in lower case and
135 placeholders written in capitals.  If a literal string includes a
136 prefix of '*', that key/value pair can be omitted from the expression.
137 For example, a usage statement that includes '*base':STRUCT-NAME
138 means that an expression has an optional key 'base', which if present
139 must have a value that forms a struct name.
142 === Built-in Types ===
144 The following types are predefined, and map to C as follows:
146   Schema    C          JSON
147   str       char *     any JSON string, UTF-8
148   number    double     any JSON number
149   int       int64_t    a JSON number without fractional part
150                        that fits into the C integer type
151   int8      int8_t     likewise
152   int16     int16_t    likewise
153   int32     int32_t    likewise
154   int64     int64_t    likewise
155   uint8     uint8_t    likewise
156   uint16    uint16_t   likewise
157   uint32    uint32_t   likewise
158   uint64    uint64_t   likewise
159   size      uint64_t   like uint64_t, except StringInputVisitor
160                        accepts size suffixes
161   bool      bool       JSON true or false
162   any       QObject *  any JSON value
163   QType     QType      JSON string matching enum QType values
166 === Includes ===
168 Usage: { 'include': STRING }
170 The QAPI schema definitions can be modularized using the 'include' directive:
172  { 'include': 'path/to/file.json' }
174 The directive is evaluated recursively, and include paths are relative to the
175 file using the directive. Multiple includes of the same file are
176 idempotent.  No other keys should appear in the expression, and the include
177 value should be a string.
179 As a matter of style, it is a good idea to have all files be
180 self-contained, but at the moment, nothing prevents an included file
181 from making a forward reference to a type that is only introduced by
182 an outer file.  The parser may be made stricter in the future to
183 prevent incomplete include files.
186 === Struct types ===
188 Usage: { 'struct': STRING, 'data': DICT, '*base': STRUCT-NAME }
190 A struct is a dictionary containing a single 'data' key whose
191 value is a dictionary.  This corresponds to a struct in C or an Object
192 in JSON. Each value of the 'data' dictionary must be the name of a
193 type, or a one-element array containing a type name.  An example of a
194 struct is:
196  { 'struct': 'MyType',
197    'data': { 'member1': 'str', 'member2': 'int', '*member3': 'str' } }
199 The use of '*' as a prefix to the name means the member is optional in
200 the corresponding JSON protocol usage.
202 The default initialization value of an optional argument should not be changed
203 between versions of QEMU unless the new default maintains backward
204 compatibility to the user-visible behavior of the old default.
206 With proper documentation, this policy still allows some flexibility; for
207 example, documenting that a default of 0 picks an optimal buffer size allows
208 one release to declare the optimal size at 512 while another release declares
209 the optimal size at 4096 - the user-visible behavior is not the bytes used by
210 the buffer, but the fact that the buffer was optimal size.
212 On input structures (only mentioned in the 'data' side of a command), changing
213 from mandatory to optional is safe (older clients will supply the option, and
214 newer clients can benefit from the default); changing from optional to
215 mandatory is backwards incompatible (older clients may be omitting the option,
216 and must continue to work).
218 On output structures (only mentioned in the 'returns' side of a command),
219 changing from mandatory to optional is in general unsafe (older clients may be
220 expecting the field, and could crash if it is missing), although it can be done
221 if the only way that the optional argument will be omitted is when it is
222 triggered by the presence of a new input flag to the command that older clients
223 don't know to send.  Changing from optional to mandatory is safe.
225 A structure that is used in both input and output of various commands
226 must consider the backwards compatibility constraints of both directions
227 of use.
229 A struct definition can specify another struct as its base.
230 In this case, the fields of the base type are included as top-level fields
231 of the new struct's dictionary in the Client JSON Protocol wire
232 format. An example definition is:
234  { 'struct': 'BlockdevOptionsGenericFormat', 'data': { 'file': 'str' } }
235  { 'struct': 'BlockdevOptionsGenericCOWFormat',
236    'base': 'BlockdevOptionsGenericFormat',
237    'data': { '*backing': 'str' } }
239 An example BlockdevOptionsGenericCOWFormat object on the wire could use
240 both fields like this:
242  { "file": "/some/place/my-image",
243    "backing": "/some/place/my-backing-file" }
246 === Enumeration types ===
248 Usage: { 'enum': STRING, 'data': ARRAY-OF-STRING }
249        { 'enum': STRING, '*prefix': STRING, 'data': ARRAY-OF-STRING }
251 An enumeration type is a dictionary containing a single 'data' key
252 whose value is a list of strings.  An example enumeration is:
254  { 'enum': 'MyEnum', 'data': [ 'value1', 'value2', 'value3' ] }
256 Nothing prevents an empty enumeration, although it is probably not
257 useful.  The list of strings should be lower case; if an enum name
258 represents multiple words, use '-' between words.  The string 'max' is
259 not allowed as an enum value, and values should not be repeated.
261 The enum constants will be named by using a heuristic to turn the
262 type name into a set of underscore separated words. For the example
263 above, 'MyEnum' will turn into 'MY_ENUM' giving a constant name
264 of 'MY_ENUM_VALUE1' for the first value. If the default heuristic
265 does not result in a desirable name, the optional 'prefix' field
266 can be used when defining the enum.
268 The enumeration values are passed as strings over the Client JSON
269 Protocol, but are encoded as C enum integral values in generated code.
270 While the C code starts numbering at 0, it is better to use explicit
271 comparisons to enum values than implicit comparisons to 0; the C code
272 will also include a generated enum member ending in _MAX for tracking
273 the size of the enum, useful when using common functions for
274 converting between strings and enum values.  Since the wire format
275 always passes by name, it is acceptable to reorder or add new
276 enumeration members in any location without breaking clients of Client
277 JSON Protocol; however, removing enum values would break
278 compatibility.  For any struct that has a field that will only contain
279 a finite set of string values, using an enum type for that field is
280 better than open-coding the field to be type 'str'.
283 === Union types ===
285 Usage: { 'union': STRING, 'data': DICT }
286 or:    { 'union': STRING, 'data': DICT, 'base': STRUCT-NAME,
287          'discriminator': ENUM-MEMBER-OF-BASE }
289 Union types are used to let the user choose between several different
290 variants for an object.  There are two flavors: simple (no
291 discriminator or base), flat (both discriminator and base).  A union
292 type is defined using a data dictionary as explained in the following
293 paragraphs.
295 A simple union type defines a mapping from automatic discriminator
296 values to data types like in this example:
298  { 'struct': 'FileOptions', 'data': { 'filename': 'str' } }
299  { 'struct': 'Qcow2Options',
300    'data': { 'backing-file': 'str', 'lazy-refcounts': 'bool' } }
302  { 'union': 'BlockdevOptions',
303    'data': { 'file': 'FileOptions',
304              'qcow2': 'Qcow2Options' } }
306 In the Client JSON Protocol, a simple union is represented by a
307 dictionary that contains the 'type' field as a discriminator, and a
308 'data' field that is of the specified data type corresponding to the
309 discriminator value, as in these examples:
311  { "type": "file", "data" : { "filename": "/some/place/my-image" } }
312  { "type": "qcow2", "data" : { "backing-file": "/some/place/my-image",
313                                "lazy-refcounts": true } }
315 The generated C code uses a struct containing a union. Additionally,
316 an implicit C enum 'NameKind' is created, corresponding to the union
317 'Name', for accessing the various branches of the union.  No branch of
318 the union can be named 'max', as this would collide with the implicit
319 enum.  The value for each branch can be of any type.
321 A flat union definition specifies a struct as its base, and
322 avoids nesting on the wire.  All branches of the union must be
323 complex types, and the top-level fields of the union dictionary on
324 the wire will be combination of fields from both the base type and the
325 appropriate branch type (when merging two dictionaries, there must be
326 no keys in common).  The 'discriminator' field must be the name of an
327 enum-typed member of the base struct.
329 The following example enhances the above simple union example by
330 adding a common field 'readonly', renaming the discriminator to
331 something more applicable, and reducing the number of {} required on
332 the wire:
334  { 'enum': 'BlockdevDriver', 'data': [ 'file', 'qcow2' ] }
335  { 'struct': 'BlockdevCommonOptions',
336    'data': { 'driver': 'BlockdevDriver', 'readonly': 'bool' } }
337  { 'union': 'BlockdevOptions',
338    'base': 'BlockdevCommonOptions',
339    'discriminator': 'driver',
340    'data': { 'file': 'FileOptions',
341              'qcow2': 'Qcow2Options' } }
343 Resulting in these JSON objects:
345  { "driver": "file", "readonly": true,
346    "filename": "/some/place/my-image" }
347  { "driver": "qcow2", "readonly": false,
348    "backing-file": "/some/place/my-image", "lazy-refcounts": true }
350 Notice that in a flat union, the discriminator name is controlled by
351 the user, but because it must map to a base member with enum type, the
352 code generator can ensure that branches exist for all values of the
353 enum (although the order of the keys need not match the declaration of
354 the enum).  In the resulting generated C data types, a flat union is
355 represented as a struct with the base member fields included directly,
356 and then a union of structures for each branch of the struct.
358 A simple union can always be re-written as a flat union where the base
359 class has a single member named 'type', and where each branch of the
360 union has a struct with a single member named 'data'.  That is,
362  { 'union': 'Simple', 'data': { 'one': 'str', 'two': 'int' } }
364 is identical on the wire to:
366  { 'enum': 'Enum', 'data': ['one', 'two'] }
367  { 'struct': 'Base', 'data': { 'type': 'Enum' } }
368  { 'struct': 'Branch1', 'data': { 'data': 'str' } }
369  { 'struct': 'Branch2', 'data': { 'data': 'int' } }
370  { 'union': 'Flat', 'base': 'Base', 'discriminator': 'type',
371    'data': { 'one': 'Branch1', 'two': 'Branch2' } }
374 === Alternate types ===
376 Usage: { 'alternate': STRING, 'data': DICT }
378 An alternate type is one that allows a choice between two or more JSON
379 data types (string, integer, number, or object, but currently not
380 array) on the wire.  The definition is similar to a simple union type,
381 where each branch of the union names a QAPI type.  For example:
383  { 'alternate': 'BlockRef',
384    'data': { 'definition': 'BlockdevOptions',
385              'reference': 'str' } }
387 Just like for a simple union, an implicit C enum 'NameKind' is created
388 to enumerate the branches for the alternate 'Name'.
390 Unlike a union, the discriminator string is never passed on the wire
391 for the Client JSON Protocol.  Instead, the value's JSON type serves
392 as an implicit discriminator, which in turn means that an alternate
393 can only express a choice between types represented differently in
394 JSON.  If a branch is typed as the 'bool' built-in, the alternate
395 accepts true and false; if it is typed as any of the various numeric
396 built-ins, it accepts a JSON number; if it is typed as a 'str'
397 built-in or named enum type, it accepts a JSON string; and if it is
398 typed as a complex type (struct or union), it accepts a JSON object.
399 Two different complex types, for instance, aren't permitted, because
400 both are represented as a JSON object.
402 The example alternate declaration above allows using both of the
403 following example objects:
405  { "file": "my_existing_block_device_id" }
406  { "file": { "driver": "file",
407              "readonly": false,
408              "filename": "/tmp/mydisk.qcow2" } }
411 === Commands ===
413 Usage: { 'command': STRING, '*data': COMPLEX-TYPE-NAME-OR-DICT,
414          '*returns': TYPE-NAME,
415          '*gen': false, '*success-response': false }
417 Commands are defined by using a dictionary containing several members,
418 where three members are most common.  The 'command' member is a
419 mandatory string, and determines the "execute" value passed in a
420 Client JSON Protocol command exchange.
422 The 'data' argument maps to the "arguments" dictionary passed in as
423 part of a Client JSON Protocol command.  The 'data' member is optional
424 and defaults to {} (an empty dictionary).  If present, it must be the
425 string name of a complex type, or a dictionary that declares an
426 anonymous type with the same semantics as a 'struct' expression, with
427 one exception noted below when 'gen' is used.
429 The 'returns' member describes what will appear in the "return" field
430 of a Client JSON Protocol reply on successful completion of a command.
431 The member is optional from the command declaration; if absent, the
432 "return" field will be an empty dictionary.  If 'returns' is present,
433 it must be the string name of a complex or built-in type, a
434 one-element array containing the name of a complex or built-in type,
435 with one exception noted below when 'gen' is used.  Although it is
436 permitted to have the 'returns' member name a built-in type or an
437 array of built-in types, any command that does this cannot be extended
438 to return additional information in the future; thus, new commands
439 should strongly consider returning a dictionary-based type or an array
440 of dictionaries, even if the dictionary only contains one field at the
441 present.
443 All commands in Client JSON Protocol use a dictionary to report
444 failure, with no way to specify that in QAPI.  Where the error return
445 is different than the usual GenericError class in order to help the
446 client react differently to certain error conditions, it is worth
447 documenting this in the comments before the command declaration.
449 Some example commands:
451  { 'command': 'my-first-command',
452    'data': { 'arg1': 'str', '*arg2': 'str' } }
453  { 'struct': 'MyType', 'data': { '*value': 'str' } }
454  { 'command': 'my-second-command',
455    'returns': [ 'MyType' ] }
457 which would validate this Client JSON Protocol transaction:
459  => { "execute": "my-first-command",
460       "arguments": { "arg1": "hello" } }
461  <= { "return": { } }
462  => { "execute": "my-second-command" }
463  <= { "return": [ { "value": "one" }, { } ] }
465 In rare cases, QAPI cannot express a type-safe representation of a
466 corresponding Client JSON Protocol command.  You then have to suppress
467 generation of a marshalling function by including a key 'gen' with
468 boolean value false, and instead write your own function.  Please try
469 to avoid adding new commands that rely on this, and instead use
470 type-safe unions.  For an example of this usage:
472  { 'command': 'netdev_add',
473    'data': {'type': 'str', 'id': 'str'},
474    'gen': false }
476 Normally, the QAPI schema is used to describe synchronous exchanges,
477 where a response is expected.  But in some cases, the action of a
478 command is expected to change state in a way that a successful
479 response is not possible (although the command will still return a
480 normal dictionary error on failure).  When a successful reply is not
481 possible, the command expression should include the optional key
482 'success-response' with boolean value false.  So far, only QGA makes
483 use of this field.
486 === Events ===
488 Usage: { 'event': STRING, '*data': COMPLEX-TYPE-NAME-OR-DICT }
490 Events are defined with the keyword 'event'.  It is not allowed to
491 name an event 'MAX', since the generator also produces a C enumeration
492 of all event names with a generated _MAX value at the end.  When
493 'data' is also specified, additional info will be included in the
494 event, with similar semantics to a 'struct' expression.  Finally there
495 will be C API generated in qapi-event.h; when called by QEMU code, a
496 message with timestamp will be emitted on the wire.
498 An example event is:
500 { 'event': 'EVENT_C',
501   'data': { '*a': 'int', 'b': 'str' } }
503 Resulting in this JSON object:
505 { "event": "EVENT_C",
506   "data": { "b": "test string" },
507   "timestamp": { "seconds": 1267020223, "microseconds": 435656 } }
510 == Client JSON Protocol introspection ==
512 Clients of a Client JSON Protocol commonly need to figure out what
513 exactly the server (QEMU) supports.
515 For this purpose, QMP provides introspection via command
516 query-qmp-schema.  QGA currently doesn't support introspection.
518 While Client JSON Protocol wire compatibility should be maintained
519 between qemu versions, we cannot make the same guarantees for
520 introspection stability.  For example, one version of qemu may provide
521 a non-variant optional member of a struct, and a later version rework
522 the member to instead be non-optional and associated with a variant.
523 Likewise, one version of qemu may list a member with open-ended type
524 'str', and a later version could convert it to a finite set of strings
525 via an enum type; or a member may be converted from a specific type to
526 an alternate that represents a choice between the original type and
527 something else.
529 query-qmp-schema returns a JSON array of SchemaInfo objects.  These
530 objects together describe the wire ABI, as defined in the QAPI schema.
531 There is no specified order to the SchemaInfo objects returned; a
532 client must search for a particular name throughout the entire array
533 to learn more about that name, but is at least guaranteed that there
534 will be no collisions between type, command, and event names.
536 However, the SchemaInfo can't reflect all the rules and restrictions
537 that apply to QMP.  It's interface introspection (figuring out what's
538 there), not interface specification.  The specification is in the QAPI
539 schema.  To understand how QMP is to be used, you need to study the
540 QAPI schema.
542 Like any other command, query-qmp-schema is itself defined in the QAPI
543 schema, along with the SchemaInfo type.  This text attempts to give an
544 overview how things work.  For details you need to consult the QAPI
545 schema.
547 SchemaInfo objects have common members "name" and "meta-type", and
548 additional variant members depending on the value of meta-type.
550 Each SchemaInfo object describes a wire ABI entity of a certain
551 meta-type: a command, event or one of several kinds of type.
553 SchemaInfo for commands and events have the same name as in the QAPI
554 schema.
556 Command and event names are part of the wire ABI, but type names are
557 not.  Therefore, the SchemaInfo for types have auto-generated
558 meaningless names.  For readability, the examples in this section use
559 meaningful type names instead.
561 To examine a type, start with a command or event using it, then follow
562 references by name.
564 QAPI schema definitions not reachable that way are omitted.
566 The SchemaInfo for a command has meta-type "command", and variant
567 members "arg-type" and "ret-type".  On the wire, the "arguments"
568 member of a client's "execute" command must conform to the object type
569 named by "arg-type".  The "return" member that the server passes in a
570 success response conforms to the type named by "ret-type".
572 If the command takes no arguments, "arg-type" names an object type
573 without members.  Likewise, if the command returns nothing, "ret-type"
574 names an object type without members.
576 Example: the SchemaInfo for command query-qmp-schema
578     { "name": "query-qmp-schema", "meta-type": "command",
579       "arg-type": ":empty", "ret-type": "SchemaInfoList" }
581     Type ":empty" is an object type without members, and type
582     "SchemaInfoList" is the array of SchemaInfo type.
584 The SchemaInfo for an event has meta-type "event", and variant member
585 "arg-type".  On the wire, a "data" member that the server passes in an
586 event conforms to the object type named by "arg-type".
588 If the event carries no additional information, "arg-type" names an
589 object type without members.  The event may not have a data member on
590 the wire then.
592 Each command or event defined with dictionary-valued 'data' in the
593 QAPI schema implicitly defines an object type.
595 Example: the SchemaInfo for EVENT_C from section Events
597     { "name": "EVENT_C", "meta-type": "event",
598       "arg-type": ":obj-EVENT_C-arg" }
600     Type ":obj-EVENT_C-arg" is an implicitly defined object type with
601     the two members from the event's definition.
603 The SchemaInfo for struct and union types has meta-type "object".
605 The SchemaInfo for a struct type has variant member "members".
607 The SchemaInfo for a union type additionally has variant members "tag"
608 and "variants".
610 "members" is a JSON array describing the object's common members, if
611 any.  Each element is a JSON object with members "name" (the member's
612 name), "type" (the name of its type), and optionally "default".  The
613 member is optional if "default" is present.  Currently, "default" can
614 only have value null.  Other values are reserved for future
615 extensions.  The "members" array is in no particular order; clients
616 must search the entire object when learning whether a particular
617 member is supported.
619 Example: the SchemaInfo for MyType from section Struct types
621     { "name": "MyType", "meta-type": "object",
622       "members": [
623           { "name": "member1", "type": "str" },
624           { "name": "member2", "type": "int" },
625           { "name": "member3", "type": "str", "default": null } ] }
627 "tag" is the name of the common member serving as type tag.
628 "variants" is a JSON array describing the object's variant members.
629 Each element is a JSON object with members "case" (the value of type
630 tag this element applies to) and "type" (the name of an object type
631 that provides the variant members for this type tag value).  The
632 "variants" array is in no particular order, and is not guaranteed to
633 list cases in the same order as the corresponding "tag" enum type.
635 Example: the SchemaInfo for flat union BlockdevOptions from section
636 Union types
638     { "name": "BlockdevOptions", "meta-type": "object",
639       "members": [
640           { "name": "driver", "type": "BlockdevDriver" },
641           { "name": "readonly", "type": "bool"} ],
642       "tag": "driver",
643       "variants": [
644           { "case": "file", "type": "FileOptions" },
645           { "case": "qcow2", "type": "Qcow2Options" } ] }
647 Note that base types are "flattened": its members are included in the
648 "members" array.
650 A simple union implicitly defines an enumeration type for its implicit
651 discriminator (called "type" on the wire, see section Union types).
653 A simple union implicitly defines an object type for each of its
654 variants.
656 Example: the SchemaInfo for simple union BlockdevOptions from section
657 Union types
659     { "name": "BlockdevOptions", "meta-type": "object",
660       "members": [
661           { "name": "kind", "type": "BlockdevOptionsKind" } ],
662       "tag": "type",
663       "variants": [
664           { "case": "file", "type": ":obj-FileOptions-wrapper" },
665           { "case": "qcow2", "type": ":obj-Qcow2Options-wrapper" } ] }
667     Enumeration type "BlockdevOptionsKind" and the object types
668     ":obj-FileOptions-wrapper", ":obj-Qcow2Options-wrapper" are
669     implicitly defined.
671 The SchemaInfo for an alternate type has meta-type "alternate", and
672 variant member "members".  "members" is a JSON array.  Each element is
673 a JSON object with member "type", which names a type.  Values of the
674 alternate type conform to exactly one of its member types.  There is
675 no guarantee on the order in which "members" will be listed.
677 Example: the SchemaInfo for BlockRef from section Alternate types
679     { "name": "BlockRef", "meta-type": "alternate",
680       "members": [
681           { "type": "BlockdevOptions" },
682           { "type": "str" } ] }
684 The SchemaInfo for an array type has meta-type "array", and variant
685 member "element-type", which names the array's element type.  Array
686 types are implicitly defined.  For convenience, the array's name may
687 resemble the element type; however, clients should examine member
688 "element-type" instead of making assumptions based on parsing member
689 "name".
691 Example: the SchemaInfo for ['str']
693     { "name": "[str]", "meta-type": "array",
694       "element-type": "str" }
696 The SchemaInfo for an enumeration type has meta-type "enum" and
697 variant member "values".  The values are listed in no particular
698 order; clients must search the entire enum when learning whether a
699 particular value is supported.
701 Example: the SchemaInfo for MyEnum from section Enumeration types
703     { "name": "MyEnum", "meta-type": "enum",
704       "values": [ "value1", "value2", "value3" ] }
706 The SchemaInfo for a built-in type has the same name as the type in
707 the QAPI schema (see section Built-in Types), with one exception
708 detailed below.  It has variant member "json-type" that shows how
709 values of this type are encoded on the wire.
711 Example: the SchemaInfo for str
713     { "name": "str", "meta-type": "builtin", "json-type": "string" }
715 The QAPI schema supports a number of integer types that only differ in
716 how they map to C.  They are identical as far as SchemaInfo is
717 concerned.  Therefore, they get all mapped to a single type "int" in
718 SchemaInfo.
720 As explained above, type names are not part of the wire ABI.  Not even
721 the names of built-in types.  Clients should examine member
722 "json-type" instead of hard-coding names of built-in types.
725 == Code generation ==
727 Schemas are fed into four scripts to generate all the code/files that,
728 paired with the core QAPI libraries, comprise everything required to
729 take JSON commands read in by a Client JSON Protocol server, unmarshal
730 the arguments into the underlying C types, call into the corresponding
731 C function, and map the response back to a Client JSON Protocol
732 response to be returned to the user.
734 As an example, we'll use the following schema, which describes a single
735 complex user-defined type (which will produce a C struct, along with a list
736 node structure that can be used to chain together a list of such types in
737 case we want to accept/return a list of this type with a command), and a
738 command which takes that type as a parameter and returns the same type:
740     $ cat example-schema.json
741     { 'struct': 'UserDefOne',
742       'data': { 'integer': 'int', 'string': 'str' } }
744     { 'command': 'my-command',
745       'data':    {'arg1': 'UserDefOne'},
746       'returns': 'UserDefOne' }
748     { 'event': 'MY_EVENT' }
750 === scripts/qapi-types.py ===
752 Used to generate the C types defined by a schema. The following files are
753 created:
755 $(prefix)qapi-types.h - C types corresponding to types defined in
756                         the schema you pass in
757 $(prefix)qapi-types.c - Cleanup functions for the above C types
759 The $(prefix) is an optional parameter used as a namespace to keep the
760 generated code from one schema/code-generation separated from others so code
761 can be generated/used from multiple schemas without clobbering previously
762 created code.
764 Example:
766     $ python scripts/qapi-types.py --output-dir="qapi-generated" \
767     --prefix="example-" example-schema.json
768     $ cat qapi-generated/example-qapi-types.c
769 [Uninteresting stuff omitted...]
771     void qapi_free_UserDefOne(UserDefOne *obj)
772     {
773         QapiDeallocVisitor *qdv;
774         Visitor *v;
776         if (!obj) {
777             return;
778         }
780         qdv = qapi_dealloc_visitor_new();
781         v = qapi_dealloc_get_visitor(qdv);
782         visit_type_UserDefOne(v, &obj, NULL, NULL);
783         qapi_dealloc_visitor_cleanup(qdv);
784     }
786     void qapi_free_UserDefOneList(UserDefOneList *obj)
787     {
788         QapiDeallocVisitor *qdv;
789         Visitor *v;
791         if (!obj) {
792             return;
793         }
795         qdv = qapi_dealloc_visitor_new();
796         v = qapi_dealloc_get_visitor(qdv);
797         visit_type_UserDefOneList(v, &obj, NULL, NULL);
798         qapi_dealloc_visitor_cleanup(qdv);
799     }
800     $ cat qapi-generated/example-qapi-types.h
801 [Uninteresting stuff omitted...]
803     #ifndef EXAMPLE_QAPI_TYPES_H
804     #define EXAMPLE_QAPI_TYPES_H
806 [Built-in types omitted...]
808     typedef struct UserDefOne UserDefOne;
810     typedef struct UserDefOneList UserDefOneList;
812     struct UserDefOne {
813         int64_t integer;
814         char *string;
815     };
817     void qapi_free_UserDefOne(UserDefOne *obj);
819     struct UserDefOneList {
820         union {
821             UserDefOne *value;
822             uint64_t padding;
823         };
824         UserDefOneList *next;
825     };
827     void qapi_free_UserDefOneList(UserDefOneList *obj);
829     #endif
831 === scripts/qapi-visit.py ===
833 Used to generate the visitor functions used to walk through and convert
834 a QObject (as provided by QMP) to a native C data structure and
835 vice-versa, as well as the visitor function used to dealloc a complex
836 schema-defined C type.
838 The following files are generated:
840 $(prefix)qapi-visit.c: visitor function for a particular C type, used
841                        to automagically convert QObjects into the
842                        corresponding C type and vice-versa, as well
843                        as for deallocating memory for an existing C
844                        type
846 $(prefix)qapi-visit.h: declarations for previously mentioned visitor
847                        functions
849 Example:
851     $ python scripts/qapi-visit.py --output-dir="qapi-generated"
852     --prefix="example-" example-schema.json
853     $ cat qapi-generated/example-qapi-visit.c
854 [Uninteresting stuff omitted...]
856     static void visit_type_UserDefOne_fields(Visitor *v, UserDefOne **obj, Error **errp)
857     {
858         Error *err = NULL;
860         visit_type_int(v, &(*obj)->integer, "integer", &err);
861         if (err) {
862             goto out;
863         }
864         visit_type_str(v, &(*obj)->string, "string", &err);
865         if (err) {
866             goto out;
867         }
869     out:
870         error_propagate(errp, err);
871     }
873     void visit_type_UserDefOne(Visitor *v, UserDefOne **obj, const char *name, Error **errp)
874     {
875         Error *err = NULL;
877         visit_start_struct(v, (void **)obj, "UserDefOne", name, sizeof(UserDefOne), &err);
878         if (!err) {
879             if (*obj) {
880                 visit_type_UserDefOne_fields(v, obj, errp);
881             }
882             visit_end_struct(v, &err);
883         }
884         error_propagate(errp, err);
885     }
887     void visit_type_UserDefOneList(Visitor *v, UserDefOneList **obj, const char *name, Error **errp)
888     {
889         Error *err = NULL;
890         GenericList *i, **prev;
892         visit_start_list(v, name, &err);
893         if (err) {
894             goto out;
895         }
897         for (prev = (GenericList **)obj;
898              !err && (i = visit_next_list(v, prev, &err)) != NULL;
899              prev = &i) {
900             UserDefOneList *native_i = (UserDefOneList *)i;
901             visit_type_UserDefOne(v, &native_i->value, NULL, &err);
902         }
904         error_propagate(errp, err);
905         err = NULL;
906         visit_end_list(v, &err);
907     out:
908         error_propagate(errp, err);
909     }
910     $ cat qapi-generated/example-qapi-visit.h
911 [Uninteresting stuff omitted...]
913     #ifndef EXAMPLE_QAPI_VISIT_H
914     #define EXAMPLE_QAPI_VISIT_H
916 [Visitors for built-in types omitted...]
918     void visit_type_UserDefOne(Visitor *v, UserDefOne **obj, const char *name, Error **errp);
919     void visit_type_UserDefOneList(Visitor *v, UserDefOneList **obj, const char *name, Error **errp);
921     #endif
923 === scripts/qapi-commands.py ===
925 Used to generate the marshaling/dispatch functions for the commands defined
926 in the schema. The following files are generated:
928 $(prefix)qmp-marshal.c: command marshal/dispatch functions for each
929                         QMP command defined in the schema. Functions
930                         generated by qapi-visit.py are used to
931                         convert QObjects received from the wire into
932                         function parameters, and uses the same
933                         visitor functions to convert native C return
934                         values to QObjects from transmission back
935                         over the wire.
937 $(prefix)qmp-commands.h: Function prototypes for the QMP commands
938                          specified in the schema.
940 Example:
942     $ python scripts/qapi-commands.py --output-dir="qapi-generated"
943     --prefix="example-" example-schema.json
944     $ cat qapi-generated/example-qmp-marshal.c
945 [Uninteresting stuff omitted...]
947     static void qmp_marshal_output_UserDefOne(UserDefOne *ret_in, QObject **ret_out, Error **errp)
948     {
949         Error *err = NULL;
950         QmpOutputVisitor *qov = qmp_output_visitor_new();
951         QapiDeallocVisitor *qdv;
952         Visitor *v;
954         v = qmp_output_get_visitor(qov);
955         visit_type_UserDefOne(v, &ret_in, "unused", &err);
956         if (err) {
957             goto out;
958         }
959         *ret_out = qmp_output_get_qobject(qov);
961     out:
962         error_propagate(errp, err);
963         qmp_output_visitor_cleanup(qov);
964         qdv = qapi_dealloc_visitor_new();
965         v = qapi_dealloc_get_visitor(qdv);
966         visit_type_UserDefOne(v, &ret_in, "unused", NULL);
967         qapi_dealloc_visitor_cleanup(qdv);
968     }
970     static void qmp_marshal_my_command(QDict *args, QObject **ret, Error **errp)
971     {
972         Error *err = NULL;
973         UserDefOne *retval;
974         QmpInputVisitor *qiv = qmp_input_visitor_new_strict(QOBJECT(args));
975         QapiDeallocVisitor *qdv;
976         Visitor *v;
977         UserDefOne *arg1 = NULL;
979         v = qmp_input_get_visitor(qiv);
980         visit_type_UserDefOne(v, &arg1, "arg1", &err);
981         if (err) {
982             goto out;
983         }
985         retval = qmp_my_command(arg1, &err);
986         if (err) {
987             goto out;
988         }
990         qmp_marshal_output_UserDefOne(retval, ret, &err);
992     out:
993         error_propagate(errp, err);
994         qmp_input_visitor_cleanup(qiv);
995         qdv = qapi_dealloc_visitor_new();
996         v = qapi_dealloc_get_visitor(qdv);
997         visit_type_UserDefOne(v, &arg1, "arg1", NULL);
998         qapi_dealloc_visitor_cleanup(qdv);
999     }
1001     static void qmp_init_marshal(void)
1002     {
1003         qmp_register_command("my-command", qmp_marshal_my_command, QCO_NO_OPTIONS);
1004     }
1006     qapi_init(qmp_init_marshal);
1007     $ cat qapi-generated/example-qmp-commands.h
1008 [Uninteresting stuff omitted...]
1010     #ifndef EXAMPLE_QMP_COMMANDS_H
1011     #define EXAMPLE_QMP_COMMANDS_H
1013     #include "example-qapi-types.h"
1014     #include "qapi/qmp/qdict.h"
1015     #include "qapi/error.h"
1017     UserDefOne *qmp_my_command(UserDefOne *arg1, Error **errp);
1019     #endif
1021 === scripts/qapi-event.py ===
1023 Used to generate the event-related C code defined by a schema. The
1024 following files are created:
1026 $(prefix)qapi-event.h - Function prototypes for each event type, plus an
1027                         enumeration of all event names
1028 $(prefix)qapi-event.c - Implementation of functions to send an event
1030 Example:
1032     $ python scripts/qapi-event.py --output-dir="qapi-generated"
1033     --prefix="example-" example-schema.json
1034     $ cat qapi-generated/example-qapi-event.c
1035 [Uninteresting stuff omitted...]
1037     void qapi_event_send_my_event(Error **errp)
1038     {
1039         QDict *qmp;
1040         Error *err = NULL;
1041         QMPEventFuncEmit emit;
1042         emit = qmp_event_get_func_emit();
1043         if (!emit) {
1044             return;
1045         }
1047         qmp = qmp_event_build_dict("MY_EVENT");
1049         emit(EXAMPLE_QAPI_EVENT_MY_EVENT, qmp, &err);
1051         error_propagate(errp, err);
1052         QDECREF(qmp);
1053     }
1055     const char *const example_QAPIEvent_lookup[] = {
1056         [EXAMPLE_QAPI_EVENT_MY_EVENT] = "MY_EVENT",
1057         [EXAMPLE_QAPI_EVENT__MAX] = NULL,
1058     };
1059     $ cat qapi-generated/example-qapi-event.h
1060 [Uninteresting stuff omitted...]
1062     #ifndef EXAMPLE_QAPI_EVENT_H
1063     #define EXAMPLE_QAPI_EVENT_H
1065     #include "qapi/error.h"
1066     #include "qapi/qmp/qdict.h"
1067     #include "example-qapi-types.h"
1070     void qapi_event_send_my_event(Error **errp);
1072     typedef enum example_QAPIEvent {
1073         EXAMPLE_QAPI_EVENT_MY_EVENT = 0,
1074         EXAMPLE_QAPI_EVENT__MAX = 1,
1075     } example_QAPIEvent;
1077     extern const char *const example_QAPIEvent_lookup[];
1079     #endif
1081 === scripts/qapi-introspect.py ===
1083 Used to generate the introspection C code for a schema. The following
1084 files are created:
1086 $(prefix)qmp-introspect.c - Defines a string holding a JSON
1087                             description of the schema.
1088 $(prefix)qmp-introspect.h - Declares the above string.
1090 Example:
1092     $ python scripts/qapi-introspect.py --output-dir="qapi-generated"
1093     --prefix="example-" example-schema.json
1094     $ cat qapi-generated/example-qmp-introspect.c
1095 [Uninteresting stuff omitted...]
1097     const char example_qmp_schema_json[] = "["
1098         "{\"arg-type\": \"0\", \"meta-type\": \"event\", \"name\": \"MY_EVENT\"}, "
1099         "{\"arg-type\": \"1\", \"meta-type\": \"command\", \"name\": \"my-command\", \"ret-type\": \"2\"}, "
1100         "{\"members\": [], \"meta-type\": \"object\", \"name\": \"0\"}, "
1101         "{\"members\": [{\"name\": \"arg1\", \"type\": \"2\"}], \"meta-type\": \"object\", \"name\": \"1\"}, "
1102         "{\"members\": [{\"name\": \"integer\", \"type\": \"int\"}, {\"name\": \"string\", \"type\": \"str\"}], \"meta-type\": \"object\", \"name\": \"2\"}, "
1103         "{\"json-type\": \"int\", \"meta-type\": \"builtin\", \"name\": \"int\"}, "
1104         "{\"json-type\": \"string\", \"meta-type\": \"builtin\", \"name\": \"str\"}]";
1105     $ cat qapi-generated/example-qmp-introspect.h
1106 [Uninteresting stuff omitted...]
1108     #ifndef EXAMPLE_QMP_INTROSPECT_H
1109     #define EXAMPLE_QMP_INTROSPECT_H
1111     extern const char example_qmp_schema_json[];
1113     #endif