qapi-code-gen.txt 60 KB

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