qapi-code-gen.rst 67 KB

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