writing-monitor-commands.rst 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748
  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. docs/devel/qapi-code-gen.txt. For documentation about the QMP protocol,
  9. start with docs/interop/qmp-intro.txt.
  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": 15,
  52. "major": 0
  53. },
  54. "package": ""
  55. },
  56. "capabilities": [
  57. ]
  58. }
  59. }
  60. The above output is the QMP server saying you're connected. The server is
  61. actually in capabilities negotiation mode. To enter in command mode type::
  62. { "execute": "qmp_capabilities" }
  63. Then the server should respond::
  64. {
  65. "return": {
  66. }
  67. }
  68. Which is QMP's way of saying "the latest command executed OK and didn't return
  69. any data". Now you're ready to enter the QMP example commands as explained in
  70. the following sections.
  71. Writing a simple command: hello-world
  72. -------------------------------------
  73. That's the most simple QMP command that can be written. Usually, this kind of
  74. command carries some meaningful action in QEMU but here it will just print
  75. "Hello, world" to the standard output.
  76. Our command will be called "hello-world". It takes no arguments, nor does it
  77. return any data.
  78. The first step is defining the command in the appropriate QAPI schema
  79. module. We pick module qapi/misc.json, and add the following line at
  80. the bottom::
  81. { 'command': 'hello-world' }
  82. The "command" keyword defines a new QMP command. It's an JSON object. All
  83. schema entries are JSON objects. The line above will instruct the QAPI to
  84. generate any prototypes and the necessary code to marshal and unmarshal
  85. protocol data.
  86. The next step is to write the "hello-world" implementation. As explained
  87. earlier, it's preferable for commands to live in QEMU subsystems. But
  88. "hello-world" doesn't pertain to any, so we put its implementation in
  89. monitor/qmp-cmds.c::
  90. void qmp_hello_world(Error **errp)
  91. {
  92. printf("Hello, world!\n");
  93. }
  94. There are a few things to be noticed:
  95. 1. QMP command implementation functions must be prefixed with "qmp\_"
  96. 2. qmp_hello_world() returns void, this is in accordance with the fact that the
  97. command doesn't return any data
  98. 3. It takes an "Error \*\*" argument. This is required. Later we will see how to
  99. return errors and take additional arguments. The Error argument should not
  100. be touched if the command doesn't return errors
  101. 4. We won't add the function's prototype. That's automatically done by the QAPI
  102. 5. Printing to the terminal is discouraged for QMP commands, we do it here
  103. because it's the easiest way to demonstrate a QMP command
  104. You're done. Now build qemu, run it as suggested in the "Testing" section,
  105. and then type the following QMP command::
  106. { "execute": "hello-world" }
  107. Then check the terminal running qemu and look for the "Hello, world" string. If
  108. you don't see it then something went wrong.
  109. Arguments
  110. ~~~~~~~~~
  111. Let's add an argument called "message" to our "hello-world" command. The new
  112. argument will contain the string to be printed to stdout. It's an optional
  113. argument, if it's not present we print our default "Hello, World" string.
  114. The first change we have to do is to modify the command specification in the
  115. schema file to the following::
  116. { 'command': 'hello-world', 'data': { '*message': 'str' } }
  117. Notice the new 'data' member in the schema. It's an JSON object whose each
  118. element is an argument to the command in question. Also notice the asterisk,
  119. it's used to mark the argument optional (that means that you shouldn't use it
  120. for mandatory arguments). Finally, 'str' is the argument's type, which
  121. stands for "string". The QAPI also supports integers, booleans, enumerations
  122. and user defined types.
  123. Now, let's update our C implementation in monitor/qmp-cmds.c::
  124. void qmp_hello_world(const char *message, Error **errp)
  125. {
  126. if (message) {
  127. printf("%s\n", message);
  128. } else {
  129. printf("Hello, world\n");
  130. }
  131. }
  132. There are two important details to be noticed:
  133. 1. All optional arguments are accompanied by a 'has\_' boolean, which is set
  134. if the optional argument is present or false otherwise
  135. 2. The C implementation signature must follow the schema's argument ordering,
  136. which is defined by the "data" member
  137. Time to test our new version of the "hello-world" command. Build qemu, run it as
  138. described in the "Testing" section and then send two commands::
  139. { "execute": "hello-world" }
  140. {
  141. "return": {
  142. }
  143. }
  144. { "execute": "hello-world", "arguments": { "message": "We love qemu" } }
  145. {
  146. "return": {
  147. }
  148. }
  149. You should see "Hello, world" and "We love qemu" in the terminal running qemu,
  150. if you don't see these strings, then something went wrong.
  151. Errors
  152. ~~~~~~
  153. QMP commands should use the error interface exported by the error.h header
  154. file. Basically, most errors are set by calling the error_setg() function.
  155. Let's say we don't accept the string "message" to contain the word "love". If
  156. it does contain it, we want the "hello-world" command to return an error::
  157. void qmp_hello_world(const char *message, Error **errp)
  158. {
  159. if (message) {
  160. if (strstr(message, "love")) {
  161. error_setg(errp, "the word 'love' is not allowed");
  162. return;
  163. }
  164. printf("%s\n", message);
  165. } else {
  166. printf("Hello, world\n");
  167. }
  168. }
  169. The first argument to the error_setg() function is the Error pointer
  170. to pointer, which is passed to all QMP functions. The next argument is a human
  171. description of the error, this is a free-form printf-like string.
  172. Let's test the example above. Build qemu, run it as defined in the "Testing"
  173. section, and then issue the following command::
  174. { "execute": "hello-world", "arguments": { "message": "all you need is love" } }
  175. The QMP server's response should be::
  176. {
  177. "error": {
  178. "class": "GenericError",
  179. "desc": "the word 'love' is not allowed"
  180. }
  181. }
  182. Note that error_setg() produces a "GenericError" class. In general,
  183. all QMP errors should have that error class. There are two exceptions
  184. to this rule:
  185. 1. To support a management application's need to recognize a specific
  186. error for special handling
  187. 2. Backward compatibility
  188. If the failure you want to report falls into one of the two cases above,
  189. use error_set() with a second argument of an ErrorClass value.
  190. Command Documentation
  191. ~~~~~~~~~~~~~~~~~~~~~
  192. There's only one step missing to make "hello-world"'s implementation complete,
  193. and that's its documentation in the schema file.
  194. There are many examples of such documentation in the schema file already, but
  195. here goes "hello-world"'s new entry for qapi/misc.json::
  196. ##
  197. # @hello-world:
  198. #
  199. # Print a client provided string to the standard output stream.
  200. #
  201. # @message: string to be printed
  202. #
  203. # Returns: Nothing on success.
  204. #
  205. # Notes: if @message is not provided, the "Hello, world" string will
  206. # be printed instead
  207. #
  208. # Since: <next qemu stable release, eg. 1.0>
  209. ##
  210. { 'command': 'hello-world', 'data': { '*message': 'str' } }
  211. Please, note that the "Returns" clause is optional if a command doesn't return
  212. any data nor any errors.
  213. Implementing the HMP command
  214. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  215. Now that the QMP command is in place, we can also make it available in the human
  216. monitor (HMP).
  217. With the introduction of the QAPI, HMP commands make QMP calls. Most of the
  218. time HMP commands are simple wrappers. All HMP commands implementation exist in
  219. the monitor/hmp-cmds.c file.
  220. Here's the implementation of the "hello-world" HMP command::
  221. void hmp_hello_world(Monitor *mon, const QDict *qdict)
  222. {
  223. const char *message = qdict_get_try_str(qdict, "message");
  224. Error *err = NULL;
  225. qmp_hello_world(!!message, message, &err);
  226. if (hmp_handle_error(mon, err)) {
  227. return;
  228. }
  229. }
  230. Also, you have to add the function's prototype to the hmp.h file.
  231. There are three important points to be noticed:
  232. 1. The "mon" and "qdict" arguments are mandatory for all HMP functions. The
  233. former is the monitor object. The latter is how the monitor passes
  234. arguments entered by the user to the command implementation
  235. 2. hmp_hello_world() performs error checking. In this example we just call
  236. hmp_handle_error() which prints a message to the user, but we could do
  237. more, like taking different actions depending on the error
  238. qmp_hello_world() returns
  239. 3. The "err" variable must be initialized to NULL before performing the
  240. QMP call
  241. There's one last step to actually make the command available to monitor users,
  242. we should add it to the hmp-commands.hx file::
  243. {
  244. .name = "hello-world",
  245. .args_type = "message:s?",
  246. .params = "hello-world [message]",
  247. .help = "Print message to the standard output",
  248. .cmd = hmp_hello_world,
  249. },
  250. SRST
  251. ``hello_world`` *message*
  252. Print message to the standard output
  253. ERST
  254. To test this you have to open a user monitor and issue the "hello-world"
  255. command. It might be instructive to check the command's documentation with
  256. HMP's "help" command.
  257. Please, check the "-monitor" command-line option to know how to open a user
  258. monitor.
  259. Writing more complex commands
  260. -----------------------------
  261. A QMP command is capable of returning any data the QAPI supports like integers,
  262. strings, booleans, enumerations and user defined types.
  263. In this section we will focus on user defined types. Please, check the QAPI
  264. documentation for information about the other types.
  265. Modelling data in QAPI
  266. ~~~~~~~~~~~~~~~~~~~~~~
  267. For a QMP command that to be considered stable and supported long term,
  268. there is a requirement returned data should be explicitly modelled
  269. using fine-grained QAPI types. As a general guide, a caller of the QMP
  270. command should never need to parse individual returned data fields. If
  271. a field appears to need parsing, then it should be split into separate
  272. fields corresponding to each distinct data item. This should be the
  273. common case for any new QMP command that is intended to be used by
  274. machines, as opposed to exclusively human operators.
  275. Some QMP commands, however, are only intended as ad hoc debugging aids
  276. for human operators. While they may return large amounts of formatted
  277. data, it is not expected that machines will need to parse the result.
  278. The overhead of defining a fine grained QAPI type for the data may not
  279. be justified by the potential benefit. In such cases, it is permitted
  280. to have a command return a simple string that contains formatted data,
  281. however, it is mandatory for the command to use the 'x-' name prefix.
  282. This indicates that the command is not guaranteed to be long term
  283. stable / liable to change in future and is not following QAPI design
  284. best practices. An example where this approach is taken is the QMP
  285. command "x-query-registers". This returns a formatted dump of the
  286. architecture specific CPU state. The way the data is formatted varies
  287. across QEMU targets, is liable to change over time, and is only
  288. intended to be consumed as an opaque string by machines. Refer to the
  289. `Writing a debugging aid returning unstructured text`_ section for
  290. an illustration.
  291. User Defined Types
  292. ~~~~~~~~~~~~~~~~~~
  293. FIXME This example needs to be redone after commit 6d32717
  294. For this example we will write the query-alarm-clock command, which returns
  295. information about QEMU's timer alarm. For more information about it, please
  296. check the "-clock" command-line option.
  297. We want to return two pieces of information. The first one is the alarm clock's
  298. name. The second one is when the next alarm will fire. The former information is
  299. returned as a string, the latter is an integer in nanoseconds (which is not
  300. very useful in practice, as the timer has probably already fired when the
  301. information reaches the client).
  302. The best way to return that data is to create a new QAPI type, as shown below::
  303. ##
  304. # @QemuAlarmClock
  305. #
  306. # QEMU alarm clock information.
  307. #
  308. # @clock-name: The alarm clock method's name.
  309. #
  310. # @next-deadline: The time (in nanoseconds) the next alarm will fire.
  311. #
  312. # Since: 1.0
  313. ##
  314. { 'type': 'QemuAlarmClock',
  315. 'data': { 'clock-name': 'str', '*next-deadline': 'int' } }
  316. The "type" keyword defines a new QAPI type. Its "data" member contains the
  317. type's members. In this example our members are the "clock-name" and the
  318. "next-deadline" one, which is optional.
  319. Now let's define the query-alarm-clock command::
  320. ##
  321. # @query-alarm-clock
  322. #
  323. # Return information about QEMU's alarm clock.
  324. #
  325. # Returns a @QemuAlarmClock instance describing the alarm clock method
  326. # being currently used by QEMU (this is usually set by the '-clock'
  327. # command-line option).
  328. #
  329. # Since: 1.0
  330. ##
  331. { 'command': 'query-alarm-clock', 'returns': 'QemuAlarmClock' }
  332. Notice the "returns" keyword. As its name suggests, it's used to define the
  333. data returned by a command.
  334. It's time to implement the qmp_query_alarm_clock() function, you can put it
  335. in the qemu-timer.c file::
  336. QemuAlarmClock *qmp_query_alarm_clock(Error **errp)
  337. {
  338. QemuAlarmClock *clock;
  339. int64_t deadline;
  340. clock = g_malloc0(sizeof(*clock));
  341. deadline = qemu_next_alarm_deadline();
  342. if (deadline > 0) {
  343. clock->has_next_deadline = true;
  344. clock->next_deadline = deadline;
  345. }
  346. clock->clock_name = g_strdup(alarm_timer->name);
  347. return clock;
  348. }
  349. There are a number of things to be noticed:
  350. 1. The QemuAlarmClock type is automatically generated by the QAPI framework,
  351. its members correspond to the type's specification in the schema file
  352. 2. As specified in the schema file, the function returns a QemuAlarmClock
  353. instance and takes no arguments (besides the "errp" one, which is mandatory
  354. for all QMP functions)
  355. 3. The "clock" variable (which will point to our QAPI type instance) is
  356. allocated by the regular g_malloc0() function. Note that we chose to
  357. initialize the memory to zero. This is recommended for all QAPI types, as
  358. it helps avoiding bad surprises (specially with booleans)
  359. 4. Remember that "next_deadline" is optional? Non-pointer optional
  360. members have a 'has_TYPE_NAME' member that should be properly set
  361. by the implementation, as shown above
  362. 5. Even static strings, such as "alarm_timer->name", should be dynamically
  363. allocated by the implementation. This is so because the QAPI also generates
  364. a function to free its types and it cannot distinguish between dynamically
  365. or statically allocated strings
  366. 6. You have to include "qapi/qapi-commands-misc.h" in qemu-timer.c
  367. Time to test the new command. Build qemu, run it as described in the "Testing"
  368. section and try this::
  369. { "execute": "query-alarm-clock" }
  370. {
  371. "return": {
  372. "next-deadline": 2368219,
  373. "clock-name": "dynticks"
  374. }
  375. }
  376. The HMP command
  377. ~~~~~~~~~~~~~~~
  378. Here's the HMP counterpart of the query-alarm-clock command::
  379. void hmp_info_alarm_clock(Monitor *mon)
  380. {
  381. QemuAlarmClock *clock;
  382. Error *err = NULL;
  383. clock = qmp_query_alarm_clock(&err);
  384. if (hmp_handle_error(mon, err)) {
  385. return;
  386. }
  387. monitor_printf(mon, "Alarm clock method in use: '%s'\n", clock->clock_name);
  388. if (clock->has_next_deadline) {
  389. monitor_printf(mon, "Next alarm will fire in %" PRId64 " nanoseconds\n",
  390. clock->next_deadline);
  391. }
  392. qapi_free_QemuAlarmClock(clock);
  393. }
  394. It's important to notice that hmp_info_alarm_clock() calls
  395. qapi_free_QemuAlarmClock() to free the data returned by qmp_query_alarm_clock().
  396. For user defined types, the QAPI will generate a qapi_free_QAPI_TYPE_NAME()
  397. function and that's what you have to use to free the types you define and
  398. qapi_free_QAPI_TYPE_NAMEList() for list types (explained in the next section).
  399. If the QMP call returns a string, then you should g_free() to free it.
  400. Also note that hmp_info_alarm_clock() performs error handling. That's not
  401. strictly required if you're sure the QMP function doesn't return errors, but
  402. it's good practice to always check for errors.
  403. Another important detail is that HMP's "info" commands don't go into the
  404. hmp-commands.hx. Instead, they go into the info_cmds[] table, which is defined
  405. in the monitor/misc.c file. The entry for the "info alarmclock" follows::
  406. {
  407. .name = "alarmclock",
  408. .args_type = "",
  409. .params = "",
  410. .help = "show information about the alarm clock",
  411. .cmd = hmp_info_alarm_clock,
  412. },
  413. To test this, run qemu and type "info alarmclock" in the user monitor.
  414. Returning Lists
  415. ~~~~~~~~~~~~~~~
  416. For this example, we're going to return all available methods for the timer
  417. alarm, which is pretty much what the command-line option "-clock ?" does,
  418. except that we're also going to inform which method is in use.
  419. This first step is to define a new type::
  420. ##
  421. # @TimerAlarmMethod
  422. #
  423. # Timer alarm method information.
  424. #
  425. # @method-name: The method's name.
  426. #
  427. # @current: true if this alarm method is currently in use, false otherwise
  428. #
  429. # Since: 1.0
  430. ##
  431. { 'type': 'TimerAlarmMethod',
  432. 'data': { 'method-name': 'str', 'current': 'bool' } }
  433. The command will be called "query-alarm-methods", here is its schema
  434. specification::
  435. ##
  436. # @query-alarm-methods
  437. #
  438. # Returns information about available alarm methods.
  439. #
  440. # Returns: a list of @TimerAlarmMethod for each method
  441. #
  442. # Since: 1.0
  443. ##
  444. { 'command': 'query-alarm-methods', 'returns': ['TimerAlarmMethod'] }
  445. Notice the syntax for returning lists "'returns': ['TimerAlarmMethod']", this
  446. should be read as "returns a list of TimerAlarmMethod instances".
  447. The C implementation follows::
  448. TimerAlarmMethodList *qmp_query_alarm_methods(Error **errp)
  449. {
  450. TimerAlarmMethodList *method_list = NULL;
  451. const struct qemu_alarm_timer *p;
  452. bool current = true;
  453. for (p = alarm_timers; p->name; p++) {
  454. TimerAlarmMethod *value = g_malloc0(*value);
  455. value->method_name = g_strdup(p->name);
  456. value->current = current;
  457. QAPI_LIST_PREPEND(method_list, value);
  458. current = false;
  459. }
  460. return method_list;
  461. }
  462. The most important difference from the previous examples is the
  463. TimerAlarmMethodList type, which is automatically generated by the QAPI from
  464. the TimerAlarmMethod type.
  465. Each list node is represented by a TimerAlarmMethodList instance. We have to
  466. allocate it, and that's done inside the for loop: the "info" pointer points to
  467. an allocated node. We also have to allocate the node's contents, which is
  468. stored in its "value" member. In our example, the "value" member is a pointer
  469. to an TimerAlarmMethod instance.
  470. Notice that the "current" variable is used as "true" only in the first
  471. iteration of the loop. That's because the alarm timer method in use is the
  472. first element of the alarm_timers array. Also notice that QAPI lists are handled
  473. by hand and we return the head of the list.
  474. Now Build qemu, run it as explained in the "Testing" section and try our new
  475. command::
  476. { "execute": "query-alarm-methods" }
  477. {
  478. "return": [
  479. {
  480. "current": false,
  481. "method-name": "unix"
  482. },
  483. {
  484. "current": true,
  485. "method-name": "dynticks"
  486. }
  487. ]
  488. }
  489. The HMP counterpart is a bit more complex than previous examples because it
  490. has to traverse the list, it's shown below for reference::
  491. void hmp_info_alarm_methods(Monitor *mon)
  492. {
  493. TimerAlarmMethodList *method_list, *method;
  494. Error *err = NULL;
  495. method_list = qmp_query_alarm_methods(&err);
  496. if (hmp_handle_error(mon, err)) {
  497. return;
  498. }
  499. for (method = method_list; method; method = method->next) {
  500. monitor_printf(mon, "%c %s\n", method->value->current ? '*' : ' ',
  501. method->value->method_name);
  502. }
  503. qapi_free_TimerAlarmMethodList(method_list);
  504. }
  505. Writing a debugging aid returning unstructured text
  506. ---------------------------------------------------
  507. As discussed in section `Modelling data in QAPI`_, it is required that
  508. commands expecting machine usage be using fine-grained QAPI data types.
  509. The exception to this rule applies when the command is solely intended
  510. as a debugging aid and allows for returning unstructured text. This is
  511. commonly needed for query commands that report aspects of QEMU's
  512. internal state that are useful to human operators.
  513. In this example we will consider a simplified variant of the HMP
  514. command ``info roms``. Following the earlier rules, this command will
  515. need to live under the ``x-`` name prefix, so its QMP implementation
  516. will be called ``x-query-roms``. It will have no parameters and will
  517. return a single text string::
  518. { 'struct': 'HumanReadableText',
  519. 'data': { 'human-readable-text': 'str' } }
  520. { 'command': 'x-query-roms',
  521. 'returns': 'HumanReadableText' }
  522. The ``HumanReadableText`` struct is intended to be used for all
  523. commands, under the ``x-`` name prefix that are returning unstructured
  524. text targeted at humans. It should never be used for commands outside
  525. the ``x-`` name prefix, as those should be using structured QAPI types.
  526. Implementing the QMP command
  527. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  528. The QMP implementation will typically involve creating a ``GString``
  529. object and printing formatted data into it::
  530. HumanReadableText *qmp_x_query_roms(Error **errp)
  531. {
  532. g_autoptr(GString) buf = g_string_new("");
  533. Rom *rom;
  534. QTAILQ_FOREACH(rom, &roms, next) {
  535. g_string_append_printf("%s size=0x%06zx name=\"%s\"\n",
  536. memory_region_name(rom->mr),
  537. rom->romsize,
  538. rom->name);
  539. }
  540. return human_readable_text_from_str(buf);
  541. }
  542. Implementing the HMP command
  543. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  544. Now that the QMP command is in place, we can also make it available in
  545. the human monitor (HMP) as shown in previous examples. The HMP
  546. implementations will all look fairly similar, as all they need do is
  547. invoke the QMP command and then print the resulting text or error
  548. message. Here's the implementation of the "info roms" HMP command::
  549. void hmp_info_roms(Monitor *mon, const QDict *qdict)
  550. {
  551. Error err = NULL;
  552. g_autoptr(HumanReadableText) info = qmp_x_query_roms(&err);
  553. if (hmp_handle_error(mon, err)) {
  554. return;
  555. }
  556. monitor_puts(mon, info->human_readable_text);
  557. }
  558. Also, you have to add the function's prototype to the hmp.h file.
  559. There's one last step to actually make the command available to
  560. monitor users, we should add it to the hmp-commands-info.hx file::
  561. {
  562. .name = "roms",
  563. .args_type = "",
  564. .params = "",
  565. .help = "show roms",
  566. .cmd = hmp_info_roms,
  567. },
  568. The case of writing a HMP info handler that calls a no-parameter QMP query
  569. command is quite common. To simplify the implementation there is a general
  570. purpose HMP info handler for this scenario. All that is required to expose
  571. a no-parameter QMP query command via HMP is to declare it using the
  572. '.cmd_info_hrt' field to point to the QMP handler, and leave the '.cmd'
  573. field NULL::
  574. {
  575. .name = "roms",
  576. .args_type = "",
  577. .params = "",
  578. .help = "show roms",
  579. .cmd_info_hrt = qmp_x_query_roms,
  580. },