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