writing-monitor-commands.rst 20 KB

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