]> git.proxmox.com Git - mirror_qemu.git/blame - docs/writing-qmp-commands.txt
hmp: fix "dump-quest-memory" segfault
[mirror_qemu.git] / docs / writing-qmp-commands.txt
CommitLineData
4b389b5d
LC
1= How to write QMP commands using the QAPI framework =
2
3This document is a step-by-step guide on how to write new QMP commands using
4the QAPI framework. It also shows how to implement new style HMP commands.
5
6This document doesn't discuss QMP protocol level details, nor does it dive
7into the QAPI framework implementation.
8
9For an in-depth introduction to the QAPI framework, please refer to
77a6da26
MA
10docs/qapi-code-gen.txt. For documentation about the QMP protocol,
11start with docs/qmp-intro.txt.
4b389b5d
LC
12
13== Overview ==
14
15Generally speaking, the following steps should be taken in order to write a
16new QMP command.
17
181. Write the command's and type(s) specification in the QAPI schema file
19 (qapi-schema.json in the root source directory)
20
212. Write the QMP command itself, which is a regular C function. Preferably,
22 the command should be exported by some QEMU subsystem. But it can also be
23 added to the qmp.c file
24
253. At this point the command can be tested under the QMP protocol
26
274. Write the HMP command equivalent. This is not required and should only be
28 done if it does make sense to have the functionality in HMP. The HMP command
29 is implemented in terms of the QMP command
30
31The following sections will demonstrate each of the steps above. We will start
32very simple and get more complex as we progress.
33
34=== Testing ===
35
36For all the examples in the next sections, the test setup is the same and is
37shown here.
38
39First, QEMU should be started as:
40
41# /path/to/your/source/qemu [...] \
42 -chardev socket,id=qmp,port=4444,host=localhost,server \
43 -mon chardev=qmp,mode=control,pretty=on
44
45Then, in a different terminal:
46
47$ telnet localhost 4444
48Trying 127.0.0.1...
49Connected to localhost.
50Escape character is '^]'.
51{
52 "QMP": {
53 "version": {
54 "qemu": {
55 "micro": 50,
56 "minor": 15,
57 "major": 0
58 },
59 "package": ""
60 },
61 "capabilities": [
62 ]
63 }
64}
65
66The above output is the QMP server saying you're connected. The server is
67actually in capabilities negotiation mode. To enter in command mode type:
68
69{ "execute": "qmp_capabilities" }
70
71Then the server should respond:
72
73{
74 "return": {
75 }
76}
77
78Which is QMP's way of saying "the latest command executed OK and didn't return
79any data". Now you're ready to enter the QMP example commands as explained in
80the following sections.
81
82== Writing a command that doesn't return data ==
83
84That's the most simple QMP command that can be written. Usually, this kind of
85command carries some meaningful action in QEMU but here it will just print
86"Hello, world" to the standard output.
87
88Our command will be called "hello-world". It takes no arguments, nor does it
89return any data.
90
91The first step is to add the following line to the bottom of the
92qapi-schema.json file:
93
94{ 'command': 'hello-world' }
95
96The "command" keyword defines a new QMP command. It's an JSON object. All
97schema entries are JSON objects. The line above will instruct the QAPI to
98generate any prototypes and the necessary code to marshal and unmarshal
99protocol data.
100
101The next step is to write the "hello-world" implementation. As explained
102earlier, it's preferable for commands to live in QEMU subsystems. But
103"hello-world" doesn't pertain to any, so we put its implementation in qmp.c:
104
105void qmp_hello_world(Error **errp)
106{
107 printf("Hello, world!\n");
108}
109
110There are a few things to be noticed:
111
1121. QMP command implementation functions must be prefixed with "qmp_"
1132. qmp_hello_world() returns void, this is in accordance with the fact that the
114 command doesn't return any data
1153. It takes an "Error **" argument. This is required. Later we will see how to
116 return errors and take additional arguments. The Error argument should not
117 be touched if the command doesn't return errors
1184. We won't add the function's prototype. That's automatically done by the QAPI
1195. Printing to the terminal is discouraged for QMP commands, we do it here
120 because it's the easiest way to demonstrate a QMP command
121
4b389b5d
LC
122You're done. Now build qemu, run it as suggested in the "Testing" section,
123and then type the following QMP command:
124
125{ "execute": "hello-world" }
126
127Then check the terminal running qemu and look for the "Hello, world" string. If
128you don't see it then something went wrong.
129
130=== Arguments ===
131
132Let's add an argument called "message" to our "hello-world" command. The new
133argument will contain the string to be printed to stdout. It's an optional
134argument, if it's not present we print our default "Hello, World" string.
135
136The first change we have to do is to modify the command specification in the
137schema file to the following:
138
139{ 'command': 'hello-world', 'data': { '*message': 'str' } }
140
141Notice the new 'data' member in the schema. It's an JSON object whose each
142element is an argument to the command in question. Also notice the asterisk,
143it's used to mark the argument optional (that means that you shouldn't use it
144for mandatory arguments). Finally, 'str' is the argument's type, which
145stands for "string". The QAPI also supports integers, booleans, enumerations
146and user defined types.
147
148Now, let's update our C implementation in qmp.c:
149
150void qmp_hello_world(bool has_message, const char *message, Error **errp)
151{
152 if (has_message) {
153 printf("%s\n", message);
154 } else {
155 printf("Hello, world\n");
156 }
157}
158
159There are two important details to be noticed:
160
1611. All optional arguments are accompanied by a 'has_' boolean, which is set
162 if the optional argument is present or false otherwise
1632. The C implementation signature must follow the schema's argument ordering,
164 which is defined by the "data" member
165
4b389b5d
LC
166Time to test our new version of the "hello-world" command. Build qemu, run it as
167described in the "Testing" section and then send two commands:
168
169{ "execute": "hello-world" }
170{
171 "return": {
172 }
173}
174
175{ "execute": "hello-world", "arguments": { "message": "We love qemu" } }
176{
177 "return": {
178 }
179}
180
181You should see "Hello, world" and "we love qemu" in the terminal running qemu,
182if you don't see these strings, then something went wrong.
183
184=== Errors ===
185
186QMP commands should use the error interface exported by the error.h header
455b0fde 187file. Basically, most errors are set by calling the error_setg() function.
4b389b5d
LC
188
189Let's say we don't accept the string "message" to contain the word "love". If
adb2072e 190it does contain it, we want the "hello-world" command to return an error:
4b389b5d
LC
191
192void qmp_hello_world(bool has_message, const char *message, Error **errp)
193{
194 if (has_message) {
195 if (strstr(message, "love")) {
455b0fde 196 error_setg(errp, "the word 'love' is not allowed");
4b389b5d
LC
197 return;
198 }
199 printf("%s\n", message);
200 } else {
201 printf("Hello, world\n");
202 }
203}
204
455b0fde
EB
205The first argument to the error_setg() function is the Error pointer
206to pointer, which is passed to all QMP functions. The next argument is a human
adb2072e
LC
207description of the error, this is a free-form printf-like string.
208
209Let's test the example above. Build qemu, run it as defined in the "Testing"
210section, and then issue the following command:
4b389b5d 211
adb2072e 212{ "execute": "hello-world", "arguments": { "message": "all you need is love" } }
4b389b5d
LC
213
214The QMP server's response should be:
215
216{
217 "error": {
adb2072e
LC
218 "class": "GenericError",
219 "desc": "the word 'love' is not allowed"
4b389b5d
LC
220 }
221}
222
455b0fde
EB
223As a general rule, all QMP errors should use ERROR_CLASS_GENERIC_ERROR
224(done by default when using error_setg()). There are two exceptions to
225this rule:
adb2072e
LC
226
227 1. A non-generic ErrorClass value exists* for the failure you want to report
228 (eg. DeviceNotFound)
229
230 2. Management applications have to take special action on the failure you
231 want to report, hence you have to add a new ErrorClass value so that they
232 can check for it
4b389b5d 233
455b0fde
EB
234If the failure you want to report falls into one of the two cases above,
235use error_set() with a second argument of an ErrorClass value.
4b389b5d 236
adb2072e 237 * All existing ErrorClass values are defined in the qapi-schema.json file
4b389b5d
LC
238
239=== Command Documentation ===
240
241There's only one step missing to make "hello-world"'s implementation complete,
242and that's its documentation in the schema file.
243
244This is very important. No QMP command will be accepted in QEMU without proper
245documentation.
246
247There are many examples of such documentation in the schema file already, but
248here goes "hello-world"'s new entry for the qapi-schema.json file:
249
250##
251# @hello-world
252#
253# Print a client provided string to the standard output stream.
254#
1d8bda12 255# @message: string to be printed
4b389b5d
LC
256#
257# Returns: Nothing on success.
4b389b5d
LC
258#
259# Notes: if @message is not provided, the "Hello, world" string will
260# be printed instead
261#
262# Since: <next qemu stable release, eg. 1.0>
263##
264{ 'command': 'hello-world', 'data': { '*message': 'str' } }
265
266Please, note that the "Returns" clause is optional if a command doesn't return
267any data nor any errors.
268
269=== Implementing the HMP command ===
270
271Now that the QMP command is in place, we can also make it available in the human
272monitor (HMP).
273
274With the introduction of the QAPI, HMP commands make QMP calls. Most of the
275time HMP commands are simple wrappers. All HMP commands implementation exist in
276the hmp.c file.
277
278Here's the implementation of the "hello-world" HMP command:
279
280void hmp_hello_world(Monitor *mon, const QDict *qdict)
281{
282 const char *message = qdict_get_try_str(qdict, "message");
e940f543 283 Error *err = NULL;
4b389b5d 284
e940f543
MA
285 qmp_hello_world(!!message, message, &err);
286 if (err) {
287 monitor_printf(mon, "%s\n", error_get_pretty(err));
288 error_free(err);
4b389b5d
LC
289 return;
290 }
291}
292
293Also, you have to add the function's prototype to the hmp.h file.
294
295There are three important points to be noticed:
296
2971. The "mon" and "qdict" arguments are mandatory for all HMP functions. The
298 former is the monitor object. The latter is how the monitor passes
299 arguments entered by the user to the command implementation
3002. hmp_hello_world() performs error checking. In this example we just print
301 the error description to the user, but we could do more, like taking
302 different actions depending on the error qmp_hello_world() returns
e940f543 3033. The "err" variable must be initialized to NULL before performing the
4b389b5d
LC
304 QMP call
305
306There's one last step to actually make the command available to monitor users,
307we should add it to the hmp-commands.hx file:
308
309 {
310 .name = "hello-world",
311 .args_type = "message:s?",
312 .params = "hello-world [message]",
313 .help = "Print message to the standard output",
2b9e3576 314 .cmd = hmp_hello_world,
4b389b5d
LC
315 },
316
317STEXI
318@item hello_world @var{message}
319@findex hello_world
320Print message to the standard output
321ETEXI
322
323To test this you have to open a user monitor and issue the "hello-world"
324command. It might be instructive to check the command's documentation with
325HMP's "help" command.
326
327Please, check the "-monitor" command-line option to know how to open a user
328monitor.
329
330== Writing a command that returns data ==
331
332A QMP command is capable of returning any data the QAPI supports like integers,
333strings, booleans, enumerations and user defined types.
334
335In this section we will focus on user defined types. Please, check the QAPI
336documentation for information about the other types.
337
338=== User Defined Types ===
339
e218052f
MA
340FIXME This example needs to be redone after commit 6d32717
341
4b389b5d
LC
342For this example we will write the query-alarm-clock command, which returns
343information about QEMU's timer alarm. For more information about it, please
344check the "-clock" command-line option.
345
346We want to return two pieces of information. The first one is the alarm clock's
347name. The second one is when the next alarm will fire. The former information is
348returned as a string, the latter is an integer in nanoseconds (which is not
349very useful in practice, as the timer has probably already fired when the
350information reaches the client).
351
352The best way to return that data is to create a new QAPI type, as shown below:
353
354##
355# @QemuAlarmClock
356#
357# QEMU alarm clock information.
358#
359# @clock-name: The alarm clock method's name.
360#
1d8bda12 361# @next-deadline: The time (in nanoseconds) the next alarm will fire.
4b389b5d
LC
362#
363# Since: 1.0
364##
365{ 'type': 'QemuAlarmClock',
366 'data': { 'clock-name': 'str', '*next-deadline': 'int' } }
367
368The "type" keyword defines a new QAPI type. Its "data" member contains the
369type's members. In this example our members are the "clock-name" and the
370"next-deadline" one, which is optional.
371
372Now let's define the query-alarm-clock command:
373
374##
375# @query-alarm-clock
376#
377# Return information about QEMU's alarm clock.
378#
379# Returns a @QemuAlarmClock instance describing the alarm clock method
380# being currently used by QEMU (this is usually set by the '-clock'
381# command-line option).
382#
383# Since: 1.0
384##
385{ 'command': 'query-alarm-clock', 'returns': 'QemuAlarmClock' }
386
387Notice the "returns" keyword. As its name suggests, it's used to define the
388data returned by a command.
389
390It's time to implement the qmp_query_alarm_clock() function, you can put it
391in the qemu-timer.c file:
392
393QemuAlarmClock *qmp_query_alarm_clock(Error **errp)
394{
395 QemuAlarmClock *clock;
396 int64_t deadline;
397
398 clock = g_malloc0(sizeof(*clock));
399
400 deadline = qemu_next_alarm_deadline();
401 if (deadline > 0) {
402 clock->has_next_deadline = true;
403 clock->next_deadline = deadline;
404 }
405 clock->clock_name = g_strdup(alarm_timer->name);
406
407 return clock;
408}
409
410There are a number of things to be noticed:
411
4121. The QemuAlarmClock type is automatically generated by the QAPI framework,
413 its members correspond to the type's specification in the schema file
4142. As specified in the schema file, the function returns a QemuAlarmClock
415 instance and takes no arguments (besides the "errp" one, which is mandatory
416 for all QMP functions)
4173. The "clock" variable (which will point to our QAPI type instance) is
418 allocated by the regular g_malloc0() function. Note that we chose to
dabdf394 419 initialize the memory to zero. This is recommended for all QAPI types, as
4b389b5d
LC
420 it helps avoiding bad surprises (specially with booleans)
4214. Remember that "next_deadline" is optional? All optional members have a
422 'has_TYPE_NAME' member that should be properly set by the implementation,
423 as shown above
4245. Even static strings, such as "alarm_timer->name", should be dynamically
425 allocated by the implementation. This is so because the QAPI also generates
426 a function to free its types and it cannot distinguish between dynamically
427 or statically allocated strings
4286. You have to include the "qmp-commands.h" header file in qemu-timer.c,
429 otherwise qemu won't build
430
4b389b5d
LC
431Time to test the new command. Build qemu, run it as described in the "Testing"
432section and try this:
433
434{ "execute": "query-alarm-clock" }
435{
436 "return": {
437 "next-deadline": 2368219,
438 "clock-name": "dynticks"
439 }
440}
441
442==== The HMP command ====
443
444Here's the HMP counterpart of the query-alarm-clock command:
445
446void hmp_info_alarm_clock(Monitor *mon)
447{
448 QemuAlarmClock *clock;
e940f543 449 Error *err = NULL;
4b389b5d 450
e940f543
MA
451 clock = qmp_query_alarm_clock(&err);
452 if (err) {
4b389b5d 453 monitor_printf(mon, "Could not query alarm clock information\n");
e940f543 454 error_free(err);
4b389b5d
LC
455 return;
456 }
457
458 monitor_printf(mon, "Alarm clock method in use: '%s'\n", clock->clock_name);
459 if (clock->has_next_deadline) {
460 monitor_printf(mon, "Next alarm will fire in %" PRId64 " nanoseconds\n",
461 clock->next_deadline);
462 }
463
464 qapi_free_QemuAlarmClock(clock);
465}
466
467It's important to notice that hmp_info_alarm_clock() calls
468qapi_free_QemuAlarmClock() to free the data returned by qmp_query_alarm_clock().
469For user defined types, the QAPI will generate a qapi_free_QAPI_TYPE_NAME()
470function and that's what you have to use to free the types you define and
471qapi_free_QAPI_TYPE_NAMEList() for list types (explained in the next section).
472If the QMP call returns a string, then you should g_free() to free it.
473
474Also note that hmp_info_alarm_clock() performs error handling. That's not
475strictly required if you're sure the QMP function doesn't return errors, but
476it's good practice to always check for errors.
477
478Another important detail is that HMP's "info" commands don't go into the
479hmp-commands.hx. Instead, they go into the info_cmds[] table, which is defined
480in the monitor.c file. The entry for the "info alarmclock" follows:
481
482 {
483 .name = "alarmclock",
484 .args_type = "",
485 .params = "",
486 .help = "show information about the alarm clock",
2b9e3576 487 .cmd = hmp_info_alarm_clock,
4b389b5d
LC
488 },
489
490To test this, run qemu and type "info alarmclock" in the user monitor.
491
492=== Returning Lists ===
493
494For this example, we're going to return all available methods for the timer
495alarm, which is pretty much what the command-line option "-clock ?" does,
496except that we're also going to inform which method is in use.
497
498This first step is to define a new type:
499
500##
501# @TimerAlarmMethod
502#
503# Timer alarm method information.
504#
505# @method-name: The method's name.
506#
507# @current: true if this alarm method is currently in use, false otherwise
508#
509# Since: 1.0
510##
511{ 'type': 'TimerAlarmMethod',
512 'data': { 'method-name': 'str', 'current': 'bool' } }
513
514The command will be called "query-alarm-methods", here is its schema
515specification:
516
517##
518# @query-alarm-methods
519#
520# Returns information about available alarm methods.
521#
522# Returns: a list of @TimerAlarmMethod for each method
523#
524# Since: 1.0
525##
526{ 'command': 'query-alarm-methods', 'returns': ['TimerAlarmMethod'] }
527
528Notice the syntax for returning lists "'returns': ['TimerAlarmMethod']", this
529should be read as "returns a list of TimerAlarmMethod instances".
530
531The C implementation follows:
532
533TimerAlarmMethodList *qmp_query_alarm_methods(Error **errp)
534{
535 TimerAlarmMethodList *method_list = NULL;
536 const struct qemu_alarm_timer *p;
537 bool current = true;
538
539 for (p = alarm_timers; p->name; p++) {
540 TimerAlarmMethodList *info = g_malloc0(sizeof(*info));
541 info->value = g_malloc0(sizeof(*info->value));
542 info->value->method_name = g_strdup(p->name);
543 info->value->current = current;
544
545 current = false;
546
547 info->next = method_list;
548 method_list = info;
549 }
550
551 return method_list;
552}
553
554The most important difference from the previous examples is the
555TimerAlarmMethodList type, which is automatically generated by the QAPI from
556the TimerAlarmMethod type.
557
558Each list node is represented by a TimerAlarmMethodList instance. We have to
559allocate it, and that's done inside the for loop: the "info" pointer points to
560an allocated node. We also have to allocate the node's contents, which is
561stored in its "value" member. In our example, the "value" member is a pointer
562to an TimerAlarmMethod instance.
563
564Notice that the "current" variable is used as "true" only in the first
5708b2b7 565iteration of the loop. That's because the alarm timer method in use is the
4b389b5d
LC
566first element of the alarm_timers array. Also notice that QAPI lists are handled
567by hand and we return the head of the list.
568
4b389b5d
LC
569Now Build qemu, run it as explained in the "Testing" section and try our new
570command:
571
572{ "execute": "query-alarm-methods" }
573{
574 "return": [
575 {
576 "current": false,
577 "method-name": "unix"
578 },
579 {
580 "current": true,
581 "method-name": "dynticks"
582 }
583 ]
584}
585
586The HMP counterpart is a bit more complex than previous examples because it
587has to traverse the list, it's shown below for reference:
588
589void hmp_info_alarm_methods(Monitor *mon)
590{
591 TimerAlarmMethodList *method_list, *method;
e940f543 592 Error *err = NULL;
4b389b5d 593
e940f543
MA
594 method_list = qmp_query_alarm_methods(&err);
595 if (err) {
4b389b5d 596 monitor_printf(mon, "Could not query alarm methods\n");
e940f543 597 error_free(err);
4b389b5d
LC
598 return;
599 }
600
601 for (method = method_list; method; method = method->next) {
602 monitor_printf(mon, "%c %s\n", method->value->current ? '*' : ' ',
603 method->value->method_name);
604 }
605
606 qapi_free_TimerAlarmMethodList(method_list);
607}