writing-monitor-commands.rst 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650
  1. How to write monitor commands
  2. =============================
  3. This document is a step-by-step guide on how to write new QMP commands using
  4. the QAPI framework and HMP commands.
  5. This document doesn't discuss QMP protocol level details, nor does it dive
  6. into the QAPI framework implementation.
  7. For an in-depth introduction to the QAPI framework, please refer to
  8. :doc:`qapi-code-gen`. For the QMP protocol, see the
  9. :doc:`/interop/qmp-spec`.
  10. New commands may be implemented in QMP only. New HMP commands should be
  11. implemented on top of QMP. The typical HMP command wraps around an
  12. equivalent QMP command, but HMP convenience commands built from QMP
  13. building blocks are also fine. The long term goal is to make all
  14. existing HMP commands conform to this, to fully isolate HMP from the
  15. internals of QEMU. Refer to the `Writing a debugging aid returning
  16. unstructured text`_ section for further guidance on commands that
  17. would have traditionally been HMP only.
  18. Overview
  19. --------
  20. Generally speaking, the following steps should be taken in order to write a
  21. new QMP command.
  22. 1. Define the command and any types it needs in the appropriate QAPI
  23. schema module.
  24. 2. Write the QMP command itself, which is a regular C function. Preferably,
  25. the command should be exported by some QEMU subsystem. But it can also be
  26. added to the monitor/qmp-cmds.c file
  27. 3. At this point the command can be tested under the QMP protocol
  28. 4. Write the HMP command equivalent. This is not required and should only be
  29. done if it does make sense to have the functionality in HMP. The HMP command
  30. is implemented in terms of the QMP command
  31. The following sections will demonstrate each of the steps above. We will start
  32. very simple and get more complex as we progress.
  33. Testing
  34. -------
  35. For all the examples in the next sections, the test setup is the same and is
  36. shown here.
  37. First, QEMU should be started like this::
  38. # qemu-system-TARGET [...] \
  39. -chardev socket,id=qmp,port=4444,host=localhost,server=on \
  40. -mon chardev=qmp,mode=control,pretty=on
  41. Then, in a different terminal::
  42. $ telnet localhost 4444
  43. Trying 127.0.0.1...
  44. Connected to localhost.
  45. Escape character is '^]'.
  46. {
  47. "QMP": {
  48. "version": {
  49. "qemu": {
  50. "micro": 50,
  51. "minor": 2,
  52. "major": 8
  53. },
  54. "package": ...
  55. },
  56. "capabilities": [
  57. "oob"
  58. ]
  59. }
  60. }
  61. The above output is the QMP server saying you're connected. The server is
  62. actually in capabilities negotiation mode. To enter in command mode type::
  63. { "execute": "qmp_capabilities" }
  64. Then the server should respond::
  65. {
  66. "return": {
  67. }
  68. }
  69. Which is QMP's way of saying "the latest command executed OK and didn't return
  70. any data". Now you're ready to enter the QMP example commands as explained in
  71. the following sections.
  72. Writing a simple command: hello-world
  73. -------------------------------------
  74. That's the most simple QMP command that can be written. Usually, this kind of
  75. command carries some meaningful action in QEMU but here it will just print
  76. "Hello, world" to the standard output.
  77. Our command will be called "hello-world". It takes no arguments, nor does it
  78. return any data.
  79. The first step is defining the command in the appropriate QAPI schema
  80. module. We pick module qapi/misc.json, and add the following line at
  81. the bottom::
  82. ##
  83. # @hello-world:
  84. #
  85. # Since: 9.0
  86. ##
  87. { 'command': 'hello-world' }
  88. The "command" keyword defines a new QMP command. It's an JSON object. All
  89. schema entries are JSON objects. The line above will instruct the QAPI to
  90. generate any prototypes and the necessary code to marshal and unmarshal
  91. protocol data.
  92. The next step is to write the "hello-world" implementation. As explained
  93. earlier, it's preferable for commands to live in QEMU subsystems. But
  94. "hello-world" doesn't pertain to any, so we put its implementation in
  95. monitor/qmp-cmds.c::
  96. void qmp_hello_world(Error **errp)
  97. {
  98. printf("Hello, world!\n");
  99. }
  100. There are a few things to be noticed:
  101. 1. QMP command implementation functions must be prefixed with "qmp\_"
  102. 2. qmp_hello_world() returns void, this is in accordance with the fact that the
  103. command doesn't return any data
  104. 3. It takes an "Error \*\*" argument. This is required. Later we will see how to
  105. return errors and take additional arguments. The Error argument should not
  106. be touched if the command doesn't return errors
  107. 4. We won't add the function's prototype. That's automatically done by the QAPI
  108. 5. Printing to the terminal is discouraged for QMP commands, we do it here
  109. because it's the easiest way to demonstrate a QMP command
  110. You're done. Now build qemu, run it as suggested in the "Testing" section,
  111. and then type the following QMP command::
  112. { "execute": "hello-world" }
  113. Then check the terminal running qemu and look for the "Hello, world" string. If
  114. you don't see it then something went wrong.
  115. Arguments
  116. ~~~~~~~~~
  117. Let's add arguments to our "hello-world" command.
  118. The first change we have to do is to modify the command specification in the
  119. schema file to the following::
  120. ##
  121. # @hello-world:
  122. #
  123. # @message: message to be printed (default: "Hello, world!")
  124. #
  125. # @times: how many times to print the message (default: 1)
  126. #
  127. # Since: 9.0
  128. ##
  129. { 'command': 'hello-world',
  130. 'data': { '*message': 'str', '*times': 'int' } }
  131. Notice the new 'data' member in the schema. It specifies an argument
  132. 'message' of QAPI type 'str', and an argument 'times' of QAPI type
  133. 'int'. Also notice the asterisk, it's used to mark the argument
  134. optional.
  135. Now, let's update our C implementation in monitor/qmp-cmds.c::
  136. void qmp_hello_world(const char *message, bool has_times, int64_t times,
  137. Error **errp)
  138. {
  139. if (!message) {
  140. message = "Hello, world";
  141. }
  142. if (!has_times) {
  143. times = 1;
  144. }
  145. for (int i = 0; i < times; i++) {
  146. printf("%s\n", message);
  147. }
  148. }
  149. There are two important details to be noticed:
  150. 1. Optional arguments other than pointers are accompanied by a 'has\_'
  151. boolean, which is set if the optional argument is present or false
  152. otherwise
  153. 2. The C implementation signature must follow the schema's argument ordering,
  154. which is defined by the "data" member
  155. Time to test our new version of the "hello-world" command. Build qemu, run it as
  156. described in the "Testing" section and then send two commands::
  157. { "execute": "hello-world" }
  158. {
  159. "return": {
  160. }
  161. }
  162. { "execute": "hello-world", "arguments": { "message": "We love qemu" } }
  163. {
  164. "return": {
  165. }
  166. }
  167. You should see "Hello, world" and "We love qemu" in the terminal running qemu,
  168. if you don't see these strings, then something went wrong.
  169. Errors
  170. ~~~~~~
  171. QMP commands should use the error interface exported by the error.h header
  172. file. Basically, most errors are set by calling the error_setg() function.
  173. Let's say we don't accept the string "message" to contain the word "love". If
  174. it does contain it, we want the "hello-world" command to return an error::
  175. void qmp_hello_world(const char *message, Error **errp)
  176. {
  177. if (message) {
  178. if (strstr(message, "love")) {
  179. error_setg(errp, "the word 'love' is not allowed");
  180. return;
  181. }
  182. printf("%s\n", message);
  183. } else {
  184. printf("Hello, world\n");
  185. }
  186. }
  187. The first argument to the error_setg() function is the Error pointer
  188. to pointer, which is passed to all QMP functions. The next argument is a human
  189. description of the error, this is a free-form printf-like string.
  190. Let's test the example above. Build qemu, run it as defined in the "Testing"
  191. section, and then issue the following command::
  192. { "execute": "hello-world", "arguments": { "message": "all you need is love" } }
  193. The QMP server's response should be::
  194. {
  195. "error": {
  196. "class": "GenericError",
  197. "desc": "the word 'love' is not allowed"
  198. }
  199. }
  200. Note that error_setg() produces a "GenericError" class. In general,
  201. all QMP errors should have that error class. There are two exceptions
  202. to this rule:
  203. 1. To support a management application's need to recognize a specific
  204. error for special handling
  205. 2. Backward compatibility
  206. If the failure you want to report falls into one of the two cases above,
  207. use error_set() with a second argument of an ErrorClass value.
  208. Implementing the HMP command
  209. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  210. Now that the QMP command is in place, we can also make it available in the human
  211. monitor (HMP).
  212. With the introduction of the QAPI, HMP commands make QMP calls. Most of the
  213. time HMP commands are simple wrappers. All HMP commands implementation exist in
  214. the monitor/hmp-cmds.c file.
  215. Here's the implementation of the "hello-world" HMP command::
  216. void hmp_hello_world(Monitor *mon, const QDict *qdict)
  217. {
  218. const char *message = qdict_get_try_str(qdict, "message");
  219. Error *err = NULL;
  220. qmp_hello_world(!!message, message, &err);
  221. if (hmp_handle_error(mon, err)) {
  222. return;
  223. }
  224. }
  225. Add it to monitor/hmp-cmds.c. Also, add its prototype to
  226. include/monitor/hmp.h.
  227. There are four important points to be noticed:
  228. 1. The "mon" and "qdict" arguments are mandatory for all HMP functions. The
  229. former is the monitor object. The latter is how the monitor passes
  230. arguments entered by the user to the command implementation
  231. 2. We chose not to support the "times" argument in HMP
  232. 3. hmp_hello_world() performs error checking. In this example we just call
  233. hmp_handle_error() which prints a message to the user, but we could do
  234. more, like taking different actions depending on the error
  235. qmp_hello_world() returns
  236. 4. The "err" variable must be initialized to NULL before performing the
  237. QMP call
  238. There's one last step to actually make the command available to monitor users,
  239. we should add it to the hmp-commands.hx file::
  240. {
  241. .name = "hello-world",
  242. .args_type = "message:s?",
  243. .params = "hello-world [message]",
  244. .help = "Print message to the standard output",
  245. .cmd = hmp_hello_world,
  246. },
  247. SRST
  248. ``hello_world`` *message*
  249. Print message to the standard output
  250. ERST
  251. To test this you have to open a user monitor and issue the "hello-world"
  252. command. It might be instructive to check the command's documentation with
  253. HMP's "help" command.
  254. Please, check the "-monitor" command-line option to know how to open a user
  255. monitor.
  256. Writing more complex commands
  257. -----------------------------
  258. A QMP command is capable of returning any data the QAPI supports like integers,
  259. strings, booleans, enumerations and user defined types.
  260. In this section we will focus on user defined types. Please, check the QAPI
  261. documentation for information about the other types.
  262. Modelling data in QAPI
  263. ~~~~~~~~~~~~~~~~~~~~~~
  264. For a QMP command that to be considered stable and supported long term,
  265. there is a requirement returned data should be explicitly modelled
  266. using fine-grained QAPI types. As a general guide, a caller of the QMP
  267. command should never need to parse individual returned data fields. If
  268. a field appears to need parsing, then it should be split into separate
  269. fields corresponding to each distinct data item. This should be the
  270. common case for any new QMP command that is intended to be used by
  271. machines, as opposed to exclusively human operators.
  272. Some QMP commands, however, are only intended as ad hoc debugging aids
  273. for human operators. While they may return large amounts of formatted
  274. data, it is not expected that machines will need to parse the result.
  275. The overhead of defining a fine grained QAPI type for the data may not
  276. be justified by the potential benefit. In such cases, it is permitted
  277. to have a command return a simple string that contains formatted data,
  278. however, it is mandatory for the command to be marked unstable.
  279. This indicates that the command is not guaranteed to be long term
  280. stable / liable to change in future and is not following QAPI design
  281. best practices. An example where this approach is taken is the QMP
  282. command "x-query-registers". This returns a formatted dump of the
  283. architecture specific CPU state. The way the data is formatted varies
  284. across QEMU targets, is liable to change over time, and is only
  285. intended to be consumed as an opaque string by machines. Refer to the
  286. `Writing a debugging aid returning unstructured text`_ section for
  287. an illustration.
  288. User Defined Types
  289. ~~~~~~~~~~~~~~~~~~
  290. For this example we will write the query-option-roms command, which
  291. returns information about ROMs loaded into the option ROM space. For
  292. more information about it, please check the "-option-rom" command-line
  293. option.
  294. For each option ROM, we want to return two pieces of information: the
  295. ROM image's file name, and its bootindex, if any. We need to create a
  296. new QAPI type for that, as shown below::
  297. ##
  298. # @OptionRomInfo:
  299. #
  300. # @filename: option ROM image file name
  301. #
  302. # @bootindex: option ROM's bootindex
  303. #
  304. # Since: 9.0
  305. ##
  306. { 'struct': 'OptionRomInfo',
  307. 'data': { 'filename': 'str', '*bootindex': 'int' } }
  308. The "struct" keyword defines a new QAPI type. Its "data" member
  309. contains the type's members. In this example our members are
  310. "filename" and "bootindex". The latter is optional.
  311. Now let's define the query-option-roms command::
  312. ##
  313. # @query-option-roms:
  314. #
  315. # Query information on ROMs loaded into the option ROM space.
  316. #
  317. # Returns: OptionRomInfo
  318. #
  319. # Since: 9.0
  320. ##
  321. { 'command': 'query-option-roms',
  322. 'returns': ['OptionRomInfo'] }
  323. Notice the "returns" keyword. As its name suggests, it's used to define the
  324. data returned by a command.
  325. Notice the syntax ['OptionRomInfo']". This should be read as "returns
  326. a list of OptionRomInfo".
  327. It's time to implement the qmp_query_option_roms() function. Add to
  328. monitor/qmp-cmds.c::
  329. OptionRomInfoList *qmp_query_option_roms(Error **errp)
  330. {
  331. OptionRomInfoList *info_list = NULL;
  332. OptionRomInfoList **tailp = &info_list;
  333. OptionRomInfo *info;
  334. for (int i = 0; i < nb_option_roms; i++) {
  335. info = g_malloc0(sizeof(*info));
  336. info->filename = g_strdup(option_rom[i].name);
  337. info->has_bootindex = option_rom[i].bootindex >= 0;
  338. if (info->has_bootindex) {
  339. info->bootindex = option_rom[i].bootindex;
  340. }
  341. QAPI_LIST_APPEND(tailp, info);
  342. }
  343. return info_list;
  344. }
  345. There are a number of things to be noticed:
  346. 1. Type OptionRomInfo is automatically generated by the QAPI framework,
  347. its members correspond to the type's specification in the schema
  348. file
  349. 2. Type OptionRomInfoList is also generated. It's a singly linked
  350. list.
  351. 3. As specified in the schema file, the function returns a
  352. OptionRomInfoList, and takes no arguments (besides the "errp" one,
  353. which is mandatory for all QMP functions)
  354. 4. The returned object is dynamically allocated
  355. 5. All strings are dynamically allocated. This is so because QAPI also
  356. generates a function to free its types and it cannot distinguish
  357. between dynamically or statically allocated strings
  358. 6. Remember that "bootindex" is optional? As a non-pointer optional
  359. member, it comes with a 'has_bootindex' member that needs to be set
  360. by the implementation, as shown above
  361. Time to test the new command. Build qemu, run it as described in the "Testing"
  362. section and try this::
  363. { "execute": "query-option-rom" }
  364. {
  365. "return": [
  366. {
  367. "filename": "kvmvapic.bin"
  368. }
  369. ]
  370. }
  371. The HMP command
  372. ~~~~~~~~~~~~~~~
  373. Here's the HMP counterpart of the query-option-roms command::
  374. void hmp_info_option_roms(Monitor *mon, const QDict *qdict)
  375. {
  376. Error *err = NULL;
  377. OptionRomInfoList *info_list, *tail;
  378. OptionRomInfo *info;
  379. info_list = qmp_query_option_roms(&err);
  380. if (hmp_handle_error(mon, err)) {
  381. return;
  382. }
  383. for (tail = info_list; tail; tail = tail->next) {
  384. info = tail->value;
  385. monitor_printf(mon, "%s", info->filename);
  386. if (info->has_bootindex) {
  387. monitor_printf(mon, " %" PRId64, info->bootindex);
  388. }
  389. monitor_printf(mon, "\n");
  390. }
  391. qapi_free_OptionRomInfoList(info_list);
  392. }
  393. It's important to notice that hmp_info_option_roms() calls
  394. qapi_free_OptionRomInfoList() to free the data returned by
  395. qmp_query_option_roms(). For user defined types, QAPI will generate a
  396. qapi_free_QAPI_TYPE_NAME() function, and that's what you have to use to
  397. free the types you define and qapi_free_QAPI_TYPE_NAMEList() for list
  398. types (explained in the next section). If the QMP function returns a
  399. string, then you should g_free() to free it.
  400. Also note that hmp_info_option_roms() performs error handling. That's
  401. not strictly required when you're sure the QMP function doesn't return
  402. errors; you could instead pass it &error_abort then.
  403. Another important detail is that HMP's "info" commands go into
  404. hmp-commands-info.hx, not hmp-commands.hx. The entry for the "info
  405. option-roms" follows::
  406. {
  407. .name = "option-roms",
  408. .args_type = "",
  409. .params = "",
  410. .help = "show roms",
  411. .cmd = hmp_info_option_roms,
  412. },
  413. SRST
  414. ``info option-roms``
  415. Show the option ROMs.
  416. ERST
  417. To test this, run qemu and type "info option-roms" in the user monitor.
  418. Writing a debugging aid returning unstructured text
  419. ---------------------------------------------------
  420. As discussed in section `Modelling data in QAPI`_, it is required that
  421. commands expecting machine usage be using fine-grained QAPI data types.
  422. The exception to this rule applies when the command is solely intended
  423. as a debugging aid and allows for returning unstructured text, such as
  424. a query command that report aspects of QEMU's internal state that are
  425. useful only to human operators.
  426. In this example we will consider the existing QMP command
  427. ``x-query-roms`` in qapi/machine.json. It has no parameters and
  428. returns a ``HumanReadableText``::
  429. ##
  430. # @x-query-roms:
  431. #
  432. # Query information on the registered ROMS
  433. #
  434. # Features:
  435. #
  436. # @unstable: This command is meant for debugging.
  437. #
  438. # Returns: registered ROMs
  439. #
  440. # Since: 6.2
  441. ##
  442. { 'command': 'x-query-roms',
  443. 'returns': 'HumanReadableText',
  444. 'features': [ 'unstable' ] }
  445. The ``HumanReadableText`` struct is defined in qapi/common.json as a
  446. struct with a string member. It is intended to be used for all
  447. commands that are returning unstructured text targeted at
  448. humans. These should all have feature 'unstable'. Note that the
  449. feature's documentation states why the command is unstable. We
  450. commonly use a ``x-`` command name prefix to make lack of stability
  451. obvious to human users.
  452. Implementing the QMP command
  453. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  454. The QMP implementation will typically involve creating a ``GString``
  455. object and printing formatted data into it, like this::
  456. HumanReadableText *qmp_x_query_roms(Error **errp)
  457. {
  458. g_autoptr(GString) buf = g_string_new("");
  459. Rom *rom;
  460. QTAILQ_FOREACH(rom, &roms, next) {
  461. g_string_append_printf("%s size=0x%06zx name=\"%s\"\n",
  462. memory_region_name(rom->mr),
  463. rom->romsize,
  464. rom->name);
  465. }
  466. return human_readable_text_from_str(buf);
  467. }
  468. The actual implementation emits more information. You can find it in
  469. hw/core/loader.c.
  470. Implementing the HMP command
  471. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  472. Now that the QMP command is in place, we can also make it available in
  473. the human monitor (HMP) as shown in previous examples. The HMP
  474. implementations will all look fairly similar, as all they need do is
  475. invoke the QMP command and then print the resulting text or error
  476. message. Here's an implementation of the "info roms" HMP command::
  477. void hmp_info_roms(Monitor *mon, const QDict *qdict)
  478. {
  479. Error err = NULL;
  480. g_autoptr(HumanReadableText) info = qmp_x_query_roms(&err);
  481. if (hmp_handle_error(mon, err)) {
  482. return;
  483. }
  484. monitor_puts(mon, info->human_readable_text);
  485. }
  486. Also, you have to add the function's prototype to the hmp.h file.
  487. There's one last step to actually make the command available to
  488. monitor users, we should add it to the hmp-commands-info.hx file::
  489. {
  490. .name = "roms",
  491. .args_type = "",
  492. .params = "",
  493. .help = "show roms",
  494. .cmd = hmp_info_roms,
  495. },
  496. The case of writing a HMP info handler that calls a no-parameter QMP query
  497. command is quite common. To simplify the implementation there is a general
  498. purpose HMP info handler for this scenario. All that is required to expose
  499. a no-parameter QMP query command via HMP is to declare it using the
  500. '.cmd_info_hrt' field to point to the QMP handler, and leave the '.cmd'
  501. field NULL::
  502. {
  503. .name = "roms",
  504. .args_type = "",
  505. .params = "",
  506. .help = "show roms",
  507. .cmd_info_hrt = qmp_x_query_roms,
  508. },
  509. This is how the actual HMP command is done.