migration: Call blk_resume_after_migration() for postcopy
[qemu/ar7.git] / monitor.c
blob6289e5256cd297c7f74287ebfef46fb85a4ec95a
1 /*
2 * QEMU monitor
4 * Copyright (c) 2003-2004 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
24 #include "qemu/osdep.h"
25 #include <dirent.h>
26 #include "qemu-common.h"
27 #include "cpu.h"
28 #include "hw/hw.h"
29 #include "monitor/qdev.h"
30 #include "hw/usb.h"
31 #include "hw/i386/pc.h"
32 #include "hw/pci/pci.h"
33 #include "sysemu/watchdog.h"
34 #include "hw/loader.h"
35 #include "exec/gdbstub.h"
36 #include "net/net.h"
37 #include "net/slirp.h"
38 #include "sysemu/char.h"
39 #include "ui/qemu-spice.h"
40 #include "sysemu/sysemu.h"
41 #include "sysemu/numa.h"
42 #include "monitor/monitor.h"
43 #include "qemu/config-file.h"
44 #include "qemu/readline.h"
45 #include "ui/console.h"
46 #include "ui/input.h"
47 #include "sysemu/blockdev.h"
48 #include "sysemu/block-backend.h"
49 #include "audio/audio.h"
50 #include "disas/disas.h"
51 #include "sysemu/balloon.h"
52 #include "qemu/timer.h"
53 #include "migration/migration.h"
54 #include "sysemu/hw_accel.h"
55 #include "qemu/acl.h"
56 #include "sysemu/tpm.h"
57 #include "qapi/qmp/qerror.h"
58 #include "qapi/qmp/types.h"
59 #include "qapi/qmp/qjson.h"
60 #include "qapi/qmp/json-streamer.h"
61 #include "qapi/qmp/json-parser.h"
62 #include "qom/object_interfaces.h"
63 #include "trace-root.h"
64 #include "trace/control.h"
65 #include "monitor/hmp-target.h"
66 #ifdef CONFIG_TRACE_SIMPLE
67 #include "trace/simple.h"
68 #endif
69 #include "exec/memory.h"
70 #include "exec/exec-all.h"
71 #include "qemu/log.h"
72 #include "qmp-commands.h"
73 #include "hmp.h"
74 #include "qemu/thread.h"
75 #include "block/qapi.h"
76 #include "qapi/qmp-event.h"
77 #include "qapi-event.h"
78 #include "qmp-introspect.h"
79 #include "sysemu/qtest.h"
80 #include "sysemu/cpus.h"
81 #include "qemu/cutils.h"
82 #include "qapi/qmp/dispatch.h"
84 #if defined(TARGET_S390X)
85 #include "hw/s390x/storage-keys.h"
86 #endif
89 * Supported types:
91 * 'F' filename
92 * 'B' block device name
93 * 's' string (accept optional quote)
94 * 'S' it just appends the rest of the string (accept optional quote)
95 * 'O' option string of the form NAME=VALUE,...
96 * parsed according to QemuOptsList given by its name
97 * Example: 'device:O' uses qemu_device_opts.
98 * Restriction: only lists with empty desc are supported
99 * TODO lift the restriction
100 * 'i' 32 bit integer
101 * 'l' target long (32 or 64 bit)
102 * 'M' Non-negative target long (32 or 64 bit), in user mode the
103 * value is multiplied by 2^20 (think Mebibyte)
104 * 'o' octets (aka bytes)
105 * user mode accepts an optional E, e, P, p, T, t, G, g, M, m,
106 * K, k suffix, which multiplies the value by 2^60 for suffixes E
107 * and e, 2^50 for suffixes P and p, 2^40 for suffixes T and t,
108 * 2^30 for suffixes G and g, 2^20 for M and m, 2^10 for K and k
109 * 'T' double
110 * user mode accepts an optional ms, us, ns suffix,
111 * which divides the value by 1e3, 1e6, 1e9, respectively
112 * '/' optional gdb-like print format (like "/10x")
114 * '?' optional type (for all types, except '/')
115 * '.' other form of optional type (for 'i' and 'l')
116 * 'b' boolean
117 * user mode accepts "on" or "off"
118 * '-' optional parameter (eg. '-f')
122 typedef struct mon_cmd_t {
123 const char *name;
124 const char *args_type;
125 const char *params;
126 const char *help;
127 void (*cmd)(Monitor *mon, const QDict *qdict);
128 /* @sub_table is a list of 2nd level of commands. If it does not exist,
129 * cmd should be used. If it exists, sub_table[?].cmd should be
130 * used, and cmd of 1st level plays the role of help function.
132 struct mon_cmd_t *sub_table;
133 void (*command_completion)(ReadLineState *rs, int nb_args, const char *str);
134 } mon_cmd_t;
136 /* file descriptors passed via SCM_RIGHTS */
137 typedef struct mon_fd_t mon_fd_t;
138 struct mon_fd_t {
139 char *name;
140 int fd;
141 QLIST_ENTRY(mon_fd_t) next;
144 /* file descriptor associated with a file descriptor set */
145 typedef struct MonFdsetFd MonFdsetFd;
146 struct MonFdsetFd {
147 int fd;
148 bool removed;
149 char *opaque;
150 QLIST_ENTRY(MonFdsetFd) next;
153 /* file descriptor set containing fds passed via SCM_RIGHTS */
154 typedef struct MonFdset MonFdset;
155 struct MonFdset {
156 int64_t id;
157 QLIST_HEAD(, MonFdsetFd) fds;
158 QLIST_HEAD(, MonFdsetFd) dup_fds;
159 QLIST_ENTRY(MonFdset) next;
162 typedef struct {
163 JSONMessageParser parser;
165 * When a client connects, we're in capabilities negotiation mode.
166 * When command qmp_capabilities succeeds, we go into command
167 * mode.
169 QmpCommandList *commands;
170 } MonitorQMP;
173 * To prevent flooding clients, events can be throttled. The
174 * throttling is calculated globally, rather than per-Monitor
175 * instance.
177 typedef struct MonitorQAPIEventState {
178 QAPIEvent event; /* Throttling state for this event type and... */
179 QDict *data; /* ... data, see qapi_event_throttle_equal() */
180 QEMUTimer *timer; /* Timer for handling delayed events */
181 QDict *qdict; /* Delayed event (if any) */
182 } MonitorQAPIEventState;
184 typedef struct {
185 int64_t rate; /* Minimum time (in ns) between two events */
186 } MonitorQAPIEventConf;
188 struct Monitor {
189 CharBackend chr;
190 int reset_seen;
191 int flags;
192 int suspend_cnt;
193 bool skip_flush;
195 QemuMutex out_lock;
196 QString *outbuf;
197 guint out_watch;
199 /* Read under either BQL or out_lock, written with BQL+out_lock. */
200 int mux_out;
202 ReadLineState *rs;
203 MonitorQMP qmp;
204 CPUState *mon_cpu;
205 BlockCompletionFunc *password_completion_cb;
206 void *password_opaque;
207 mon_cmd_t *cmd_table;
208 QLIST_HEAD(,mon_fd_t) fds;
209 QLIST_ENTRY(Monitor) entry;
212 /* QMP checker flags */
213 #define QMP_ACCEPT_UNKNOWNS 1
215 /* Protects mon_list, monitor_event_state. */
216 static QemuMutex monitor_lock;
218 static QLIST_HEAD(mon_list, Monitor) mon_list;
219 static QLIST_HEAD(mon_fdsets, MonFdset) mon_fdsets;
220 static int mon_refcount;
222 static mon_cmd_t mon_cmds[];
223 static mon_cmd_t info_cmds[];
225 QmpCommandList qmp_commands, qmp_cap_negotiation_commands;
227 Monitor *cur_mon;
229 static QEMUClockType event_clock_type = QEMU_CLOCK_REALTIME;
231 static void monitor_command_cb(void *opaque, const char *cmdline,
232 void *readline_opaque);
235 * Is @mon a QMP monitor?
237 static inline bool monitor_is_qmp(const Monitor *mon)
239 return (mon->flags & MONITOR_USE_CONTROL);
243 * Is the current monitor, if any, a QMP monitor?
245 bool monitor_cur_is_qmp(void)
247 return cur_mon && monitor_is_qmp(cur_mon);
250 void monitor_read_command(Monitor *mon, int show_prompt)
252 if (!mon->rs)
253 return;
255 readline_start(mon->rs, "(qemu) ", 0, monitor_command_cb, NULL);
256 if (show_prompt)
257 readline_show_prompt(mon->rs);
260 int monitor_read_password(Monitor *mon, ReadLineFunc *readline_func,
261 void *opaque)
263 if (mon->rs) {
264 readline_start(mon->rs, "Password: ", 1, readline_func, opaque);
265 /* prompt is printed on return from the command handler */
266 return 0;
267 } else {
268 monitor_printf(mon, "terminal does not support password prompting\n");
269 return -ENOTTY;
273 static void monitor_flush_locked(Monitor *mon);
275 static gboolean monitor_unblocked(GIOChannel *chan, GIOCondition cond,
276 void *opaque)
278 Monitor *mon = opaque;
280 qemu_mutex_lock(&mon->out_lock);
281 mon->out_watch = 0;
282 monitor_flush_locked(mon);
283 qemu_mutex_unlock(&mon->out_lock);
284 return FALSE;
287 /* Called with mon->out_lock held. */
288 static void monitor_flush_locked(Monitor *mon)
290 int rc;
291 size_t len;
292 const char *buf;
294 if (mon->skip_flush) {
295 return;
298 buf = qstring_get_str(mon->outbuf);
299 len = qstring_get_length(mon->outbuf);
301 if (len && !mon->mux_out) {
302 rc = qemu_chr_fe_write(&mon->chr, (const uint8_t *) buf, len);
303 if ((rc < 0 && errno != EAGAIN) || (rc == len)) {
304 /* all flushed or error */
305 QDECREF(mon->outbuf);
306 mon->outbuf = qstring_new();
307 return;
309 if (rc > 0) {
310 /* partial write */
311 QString *tmp = qstring_from_str(buf + rc);
312 QDECREF(mon->outbuf);
313 mon->outbuf = tmp;
315 if (mon->out_watch == 0) {
316 mon->out_watch =
317 qemu_chr_fe_add_watch(&mon->chr, G_IO_OUT | G_IO_HUP,
318 monitor_unblocked, mon);
323 void monitor_flush(Monitor *mon)
325 qemu_mutex_lock(&mon->out_lock);
326 monitor_flush_locked(mon);
327 qemu_mutex_unlock(&mon->out_lock);
330 /* flush at every end of line */
331 static void monitor_puts(Monitor *mon, const char *str)
333 char c;
335 qemu_mutex_lock(&mon->out_lock);
336 for(;;) {
337 c = *str++;
338 if (c == '\0')
339 break;
340 if (c == '\n') {
341 qstring_append_chr(mon->outbuf, '\r');
343 qstring_append_chr(mon->outbuf, c);
344 if (c == '\n') {
345 monitor_flush_locked(mon);
348 qemu_mutex_unlock(&mon->out_lock);
351 void monitor_vprintf(Monitor *mon, const char *fmt, va_list ap)
353 char *buf;
355 if (!mon)
356 return;
358 if (monitor_is_qmp(mon)) {
359 return;
362 buf = g_strdup_vprintf(fmt, ap);
363 monitor_puts(mon, buf);
364 g_free(buf);
367 void monitor_printf(Monitor *mon, const char *fmt, ...)
369 va_list ap;
370 va_start(ap, fmt);
371 monitor_vprintf(mon, fmt, ap);
372 va_end(ap);
375 int monitor_fprintf(FILE *stream, const char *fmt, ...)
377 va_list ap;
378 va_start(ap, fmt);
379 monitor_vprintf((Monitor *)stream, fmt, ap);
380 va_end(ap);
381 return 0;
384 static void monitor_json_emitter(Monitor *mon, const QObject *data)
386 QString *json;
388 json = mon->flags & MONITOR_USE_PRETTY ? qobject_to_json_pretty(data) :
389 qobject_to_json(data);
390 assert(json != NULL);
392 qstring_append_chr(json, '\n');
393 monitor_puts(mon, qstring_get_str(json));
395 QDECREF(json);
398 static MonitorQAPIEventConf monitor_qapi_event_conf[QAPI_EVENT__MAX] = {
399 /* Limit guest-triggerable events to 1 per second */
400 [QAPI_EVENT_RTC_CHANGE] = { 1000 * SCALE_MS },
401 [QAPI_EVENT_WATCHDOG] = { 1000 * SCALE_MS },
402 [QAPI_EVENT_BALLOON_CHANGE] = { 1000 * SCALE_MS },
403 [QAPI_EVENT_QUORUM_REPORT_BAD] = { 1000 * SCALE_MS },
404 [QAPI_EVENT_QUORUM_FAILURE] = { 1000 * SCALE_MS },
405 [QAPI_EVENT_VSERPORT_CHANGE] = { 1000 * SCALE_MS },
408 GHashTable *monitor_qapi_event_state;
411 * Emits the event to every monitor instance, @event is only used for trace
412 * Called with monitor_lock held.
414 static void monitor_qapi_event_emit(QAPIEvent event, QDict *qdict)
416 Monitor *mon;
418 trace_monitor_protocol_event_emit(event, qdict);
419 QLIST_FOREACH(mon, &mon_list, entry) {
420 if (monitor_is_qmp(mon)
421 && mon->qmp.commands != &qmp_cap_negotiation_commands) {
422 monitor_json_emitter(mon, QOBJECT(qdict));
427 static void monitor_qapi_event_handler(void *opaque);
430 * Queue a new event for emission to Monitor instances,
431 * applying any rate limiting if required.
433 static void
434 monitor_qapi_event_queue(QAPIEvent event, QDict *qdict, Error **errp)
436 MonitorQAPIEventConf *evconf;
437 MonitorQAPIEventState *evstate;
439 assert(event < QAPI_EVENT__MAX);
440 evconf = &monitor_qapi_event_conf[event];
441 trace_monitor_protocol_event_queue(event, qdict, evconf->rate);
443 qemu_mutex_lock(&monitor_lock);
445 if (!evconf->rate) {
446 /* Unthrottled event */
447 monitor_qapi_event_emit(event, qdict);
448 } else {
449 QDict *data = qobject_to_qdict(qdict_get(qdict, "data"));
450 MonitorQAPIEventState key = { .event = event, .data = data };
452 evstate = g_hash_table_lookup(monitor_qapi_event_state, &key);
453 assert(!evstate || timer_pending(evstate->timer));
455 if (evstate) {
457 * Timer is pending for (at least) evconf->rate ns after
458 * last send. Store event for sending when timer fires,
459 * replacing a prior stored event if any.
461 QDECREF(evstate->qdict);
462 evstate->qdict = qdict;
463 QINCREF(evstate->qdict);
464 } else {
466 * Last send was (at least) evconf->rate ns ago.
467 * Send immediately, and arm the timer to call
468 * monitor_qapi_event_handler() in evconf->rate ns. Any
469 * events arriving before then will be delayed until then.
471 int64_t now = qemu_clock_get_ns(event_clock_type);
473 monitor_qapi_event_emit(event, qdict);
475 evstate = g_new(MonitorQAPIEventState, 1);
476 evstate->event = event;
477 evstate->data = data;
478 QINCREF(evstate->data);
479 evstate->qdict = NULL;
480 evstate->timer = timer_new_ns(event_clock_type,
481 monitor_qapi_event_handler,
482 evstate);
483 g_hash_table_add(monitor_qapi_event_state, evstate);
484 timer_mod_ns(evstate->timer, now + evconf->rate);
488 qemu_mutex_unlock(&monitor_lock);
492 * This function runs evconf->rate ns after sending a throttled
493 * event.
494 * If another event has since been stored, send it.
496 static void monitor_qapi_event_handler(void *opaque)
498 MonitorQAPIEventState *evstate = opaque;
499 MonitorQAPIEventConf *evconf = &monitor_qapi_event_conf[evstate->event];
501 trace_monitor_protocol_event_handler(evstate->event, evstate->qdict);
502 qemu_mutex_lock(&monitor_lock);
504 if (evstate->qdict) {
505 int64_t now = qemu_clock_get_ns(event_clock_type);
507 monitor_qapi_event_emit(evstate->event, evstate->qdict);
508 QDECREF(evstate->qdict);
509 evstate->qdict = NULL;
510 timer_mod_ns(evstate->timer, now + evconf->rate);
511 } else {
512 g_hash_table_remove(monitor_qapi_event_state, evstate);
513 QDECREF(evstate->data);
514 timer_free(evstate->timer);
515 g_free(evstate);
518 qemu_mutex_unlock(&monitor_lock);
521 static unsigned int qapi_event_throttle_hash(const void *key)
523 const MonitorQAPIEventState *evstate = key;
524 unsigned int hash = evstate->event * 255;
526 if (evstate->event == QAPI_EVENT_VSERPORT_CHANGE) {
527 hash += g_str_hash(qdict_get_str(evstate->data, "id"));
530 if (evstate->event == QAPI_EVENT_QUORUM_REPORT_BAD) {
531 hash += g_str_hash(qdict_get_str(evstate->data, "node-name"));
534 return hash;
537 static gboolean qapi_event_throttle_equal(const void *a, const void *b)
539 const MonitorQAPIEventState *eva = a;
540 const MonitorQAPIEventState *evb = b;
542 if (eva->event != evb->event) {
543 return FALSE;
546 if (eva->event == QAPI_EVENT_VSERPORT_CHANGE) {
547 return !strcmp(qdict_get_str(eva->data, "id"),
548 qdict_get_str(evb->data, "id"));
551 if (eva->event == QAPI_EVENT_QUORUM_REPORT_BAD) {
552 return !strcmp(qdict_get_str(eva->data, "node-name"),
553 qdict_get_str(evb->data, "node-name"));
556 return TRUE;
559 static void monitor_qapi_event_init(void)
561 if (qtest_enabled()) {
562 event_clock_type = QEMU_CLOCK_VIRTUAL;
565 monitor_qapi_event_state = g_hash_table_new(qapi_event_throttle_hash,
566 qapi_event_throttle_equal);
567 qmp_event_set_func_emit(monitor_qapi_event_queue);
570 static void handle_hmp_command(Monitor *mon, const char *cmdline);
572 static void monitor_data_init(Monitor *mon)
574 memset(mon, 0, sizeof(Monitor));
575 qemu_mutex_init(&mon->out_lock);
576 mon->outbuf = qstring_new();
577 /* Use *mon_cmds by default. */
578 mon->cmd_table = mon_cmds;
581 static void monitor_data_destroy(Monitor *mon)
583 qemu_chr_fe_deinit(&mon->chr);
584 if (monitor_is_qmp(mon)) {
585 json_message_parser_destroy(&mon->qmp.parser);
587 g_free(mon->rs);
588 QDECREF(mon->outbuf);
589 qemu_mutex_destroy(&mon->out_lock);
592 char *qmp_human_monitor_command(const char *command_line, bool has_cpu_index,
593 int64_t cpu_index, Error **errp)
595 char *output = NULL;
596 Monitor *old_mon, hmp;
598 monitor_data_init(&hmp);
599 hmp.skip_flush = true;
601 old_mon = cur_mon;
602 cur_mon = &hmp;
604 if (has_cpu_index) {
605 int ret = monitor_set_cpu(cpu_index);
606 if (ret < 0) {
607 cur_mon = old_mon;
608 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cpu-index",
609 "a CPU number");
610 goto out;
614 handle_hmp_command(&hmp, command_line);
615 cur_mon = old_mon;
617 qemu_mutex_lock(&hmp.out_lock);
618 if (qstring_get_length(hmp.outbuf) > 0) {
619 output = g_strdup(qstring_get_str(hmp.outbuf));
620 } else {
621 output = g_strdup("");
623 qemu_mutex_unlock(&hmp.out_lock);
625 out:
626 monitor_data_destroy(&hmp);
627 return output;
630 static int compare_cmd(const char *name, const char *list)
632 const char *p, *pstart;
633 int len;
634 len = strlen(name);
635 p = list;
636 for(;;) {
637 pstart = p;
638 p = strchr(p, '|');
639 if (!p)
640 p = pstart + strlen(pstart);
641 if ((p - pstart) == len && !memcmp(pstart, name, len))
642 return 1;
643 if (*p == '\0')
644 break;
645 p++;
647 return 0;
650 static int get_str(char *buf, int buf_size, const char **pp)
652 const char *p;
653 char *q;
654 int c;
656 q = buf;
657 p = *pp;
658 while (qemu_isspace(*p)) {
659 p++;
661 if (*p == '\0') {
662 fail:
663 *q = '\0';
664 *pp = p;
665 return -1;
667 if (*p == '\"') {
668 p++;
669 while (*p != '\0' && *p != '\"') {
670 if (*p == '\\') {
671 p++;
672 c = *p++;
673 switch (c) {
674 case 'n':
675 c = '\n';
676 break;
677 case 'r':
678 c = '\r';
679 break;
680 case '\\':
681 case '\'':
682 case '\"':
683 break;
684 default:
685 printf("unsupported escape code: '\\%c'\n", c);
686 goto fail;
688 if ((q - buf) < buf_size - 1) {
689 *q++ = c;
691 } else {
692 if ((q - buf) < buf_size - 1) {
693 *q++ = *p;
695 p++;
698 if (*p != '\"') {
699 printf("unterminated string\n");
700 goto fail;
702 p++;
703 } else {
704 while (*p != '\0' && !qemu_isspace(*p)) {
705 if ((q - buf) < buf_size - 1) {
706 *q++ = *p;
708 p++;
711 *q = '\0';
712 *pp = p;
713 return 0;
716 #define MAX_ARGS 16
718 static void free_cmdline_args(char **args, int nb_args)
720 int i;
722 assert(nb_args <= MAX_ARGS);
724 for (i = 0; i < nb_args; i++) {
725 g_free(args[i]);
731 * Parse the command line to get valid args.
732 * @cmdline: command line to be parsed.
733 * @pnb_args: location to store the number of args, must NOT be NULL.
734 * @args: location to store the args, which should be freed by caller, must
735 * NOT be NULL.
737 * Returns 0 on success, negative on failure.
739 * NOTE: this parser is an approximate form of the real command parser. Number
740 * of args have a limit of MAX_ARGS. If cmdline contains more, it will
741 * return with failure.
743 static int parse_cmdline(const char *cmdline,
744 int *pnb_args, char **args)
746 const char *p;
747 int nb_args, ret;
748 char buf[1024];
750 p = cmdline;
751 nb_args = 0;
752 for (;;) {
753 while (qemu_isspace(*p)) {
754 p++;
756 if (*p == '\0') {
757 break;
759 if (nb_args >= MAX_ARGS) {
760 goto fail;
762 ret = get_str(buf, sizeof(buf), &p);
763 if (ret < 0) {
764 goto fail;
766 args[nb_args] = g_strdup(buf);
767 nb_args++;
769 *pnb_args = nb_args;
770 return 0;
772 fail:
773 free_cmdline_args(args, nb_args);
774 return -1;
777 static void help_cmd_dump_one(Monitor *mon,
778 const mon_cmd_t *cmd,
779 char **prefix_args,
780 int prefix_args_nb)
782 int i;
784 for (i = 0; i < prefix_args_nb; i++) {
785 monitor_printf(mon, "%s ", prefix_args[i]);
787 monitor_printf(mon, "%s %s -- %s\n", cmd->name, cmd->params, cmd->help);
790 /* @args[@arg_index] is the valid command need to find in @cmds */
791 static void help_cmd_dump(Monitor *mon, const mon_cmd_t *cmds,
792 char **args, int nb_args, int arg_index)
794 const mon_cmd_t *cmd;
796 /* No valid arg need to compare with, dump all in *cmds */
797 if (arg_index >= nb_args) {
798 for (cmd = cmds; cmd->name != NULL; cmd++) {
799 help_cmd_dump_one(mon, cmd, args, arg_index);
801 return;
804 /* Find one entry to dump */
805 for (cmd = cmds; cmd->name != NULL; cmd++) {
806 if (compare_cmd(args[arg_index], cmd->name)) {
807 if (cmd->sub_table) {
808 /* continue with next arg */
809 help_cmd_dump(mon, cmd->sub_table,
810 args, nb_args, arg_index + 1);
811 } else {
812 help_cmd_dump_one(mon, cmd, args, arg_index);
814 break;
819 static void help_cmd(Monitor *mon, const char *name)
821 char *args[MAX_ARGS];
822 int nb_args = 0;
824 /* 1. parse user input */
825 if (name) {
826 /* special case for log, directly dump and return */
827 if (!strcmp(name, "log")) {
828 const QEMULogItem *item;
829 monitor_printf(mon, "Log items (comma separated):\n");
830 monitor_printf(mon, "%-10s %s\n", "none", "remove all logs");
831 for (item = qemu_log_items; item->mask != 0; item++) {
832 monitor_printf(mon, "%-10s %s\n", item->name, item->help);
834 return;
837 if (parse_cmdline(name, &nb_args, args) < 0) {
838 return;
842 /* 2. dump the contents according to parsed args */
843 help_cmd_dump(mon, mon->cmd_table, args, nb_args, 0);
845 free_cmdline_args(args, nb_args);
848 static void do_help_cmd(Monitor *mon, const QDict *qdict)
850 help_cmd(mon, qdict_get_try_str(qdict, "name"));
853 static void hmp_trace_event(Monitor *mon, const QDict *qdict)
855 const char *tp_name = qdict_get_str(qdict, "name");
856 bool new_state = qdict_get_bool(qdict, "option");
857 bool has_vcpu = qdict_haskey(qdict, "vcpu");
858 int vcpu = qdict_get_try_int(qdict, "vcpu", 0);
859 Error *local_err = NULL;
861 if (vcpu < 0) {
862 monitor_printf(mon, "argument vcpu must be positive");
863 return;
866 qmp_trace_event_set_state(tp_name, new_state, true, true, has_vcpu, vcpu, &local_err);
867 if (local_err) {
868 error_report_err(local_err);
872 #ifdef CONFIG_TRACE_SIMPLE
873 static void hmp_trace_file(Monitor *mon, const QDict *qdict)
875 const char *op = qdict_get_try_str(qdict, "op");
876 const char *arg = qdict_get_try_str(qdict, "arg");
878 if (!op) {
879 st_print_trace_file_status((FILE *)mon, &monitor_fprintf);
880 } else if (!strcmp(op, "on")) {
881 st_set_trace_file_enabled(true);
882 } else if (!strcmp(op, "off")) {
883 st_set_trace_file_enabled(false);
884 } else if (!strcmp(op, "flush")) {
885 st_flush_trace_buffer();
886 } else if (!strcmp(op, "set")) {
887 if (arg) {
888 st_set_trace_file(arg);
890 } else {
891 monitor_printf(mon, "unexpected argument \"%s\"\n", op);
892 help_cmd(mon, "trace-file");
895 #endif
897 static void hmp_info_help(Monitor *mon, const QDict *qdict)
899 help_cmd(mon, "info");
902 static void query_commands_cb(QmpCommand *cmd, void *opaque)
904 CommandInfoList *info, **list = opaque;
906 if (!cmd->enabled) {
907 return;
910 info = g_malloc0(sizeof(*info));
911 info->value = g_malloc0(sizeof(*info->value));
912 info->value->name = g_strdup(cmd->name);
913 info->next = *list;
914 *list = info;
917 CommandInfoList *qmp_query_commands(Error **errp)
919 CommandInfoList *list = NULL;
921 qmp_for_each_command(cur_mon->qmp.commands, query_commands_cb, &list);
923 return list;
926 EventInfoList *qmp_query_events(Error **errp)
928 EventInfoList *info, *ev_list = NULL;
929 QAPIEvent e;
931 for (e = 0 ; e < QAPI_EVENT__MAX ; e++) {
932 const char *event_name = QAPIEvent_lookup[e];
933 assert(event_name != NULL);
934 info = g_malloc0(sizeof(*info));
935 info->value = g_malloc0(sizeof(*info->value));
936 info->value->name = g_strdup(event_name);
938 info->next = ev_list;
939 ev_list = info;
942 return ev_list;
946 * Minor hack: generated marshalling suppressed for this command
947 * ('gen': false in the schema) so we can parse the JSON string
948 * directly into QObject instead of first parsing it with
949 * visit_type_SchemaInfoList() into a SchemaInfoList, then marshal it
950 * to QObject with generated output marshallers, every time. Instead,
951 * we do it in test-qobject-input-visitor.c, just to make sure
952 * qapi-introspect.py's output actually conforms to the schema.
954 static void qmp_query_qmp_schema(QDict *qdict, QObject **ret_data,
955 Error **errp)
957 *ret_data = qobject_from_json(qmp_schema_json, &error_abort);
961 * We used to define commands in qmp-commands.hx in addition to the
962 * QAPI schema. This permitted defining some of them only in certain
963 * configurations. query-commands has always reflected that (good,
964 * because it lets QMP clients figure out what's actually available),
965 * while query-qmp-schema never did (not so good). This function is a
966 * hack to keep the configuration-specific commands defined exactly as
967 * before, even though qmp-commands.hx is gone.
969 * FIXME Educate the QAPI schema on configuration-specific commands,
970 * and drop this hack.
972 static void qmp_unregister_commands_hack(void)
974 #ifndef CONFIG_SPICE
975 qmp_unregister_command(&qmp_commands, "query-spice");
976 #endif
977 #ifndef TARGET_I386
978 qmp_unregister_command(&qmp_commands, "rtc-reset-reinjection");
979 #endif
980 #ifndef TARGET_S390X
981 qmp_unregister_command(&qmp_commands, "dump-skeys");
982 #endif
983 #ifndef TARGET_ARM
984 qmp_unregister_command(&qmp_commands, "query-gic-capabilities");
985 #endif
986 #if !defined(TARGET_S390X) && !defined(TARGET_I386)
987 qmp_unregister_command(&qmp_commands, "query-cpu-model-expansion");
988 #endif
989 #if !defined(TARGET_S390X)
990 qmp_unregister_command(&qmp_commands, "query-cpu-model-baseline");
991 qmp_unregister_command(&qmp_commands, "query-cpu-model-comparison");
992 #endif
993 #if !defined(TARGET_PPC) && !defined(TARGET_ARM) && !defined(TARGET_I386) \
994 && !defined(TARGET_S390X)
995 qmp_unregister_command(&qmp_commands, "query-cpu-definitions");
996 #endif
999 void monitor_init_qmp_commands(void)
1002 * Two command lists:
1003 * - qmp_commands contains all QMP commands
1004 * - qmp_cap_negotiation_commands contains just
1005 * "qmp_capabilities", to enforce capability negotiation
1008 qmp_init_marshal(&qmp_commands);
1010 qmp_register_command(&qmp_commands, "query-qmp-schema",
1011 qmp_query_qmp_schema,
1012 QCO_NO_OPTIONS);
1013 qmp_register_command(&qmp_commands, "device_add", qmp_device_add,
1014 QCO_NO_OPTIONS);
1015 qmp_register_command(&qmp_commands, "netdev_add", qmp_netdev_add,
1016 QCO_NO_OPTIONS);
1018 qmp_unregister_commands_hack();
1020 QTAILQ_INIT(&qmp_cap_negotiation_commands);
1021 qmp_register_command(&qmp_cap_negotiation_commands, "qmp_capabilities",
1022 qmp_marshal_qmp_capabilities, QCO_NO_OPTIONS);
1025 void qmp_qmp_capabilities(Error **errp)
1027 if (cur_mon->qmp.commands == &qmp_commands) {
1028 error_set(errp, ERROR_CLASS_COMMAND_NOT_FOUND,
1029 "Capabilities negotiation is already complete, command "
1030 "ignored");
1031 return;
1034 cur_mon->qmp.commands = &qmp_commands;
1037 /* set the current CPU defined by the user */
1038 int monitor_set_cpu(int cpu_index)
1040 CPUState *cpu;
1042 cpu = qemu_get_cpu(cpu_index);
1043 if (cpu == NULL) {
1044 return -1;
1046 cur_mon->mon_cpu = cpu;
1047 return 0;
1050 CPUState *mon_get_cpu(void)
1052 if (!cur_mon->mon_cpu) {
1053 if (!first_cpu) {
1054 return NULL;
1056 monitor_set_cpu(first_cpu->cpu_index);
1058 cpu_synchronize_state(cur_mon->mon_cpu);
1059 return cur_mon->mon_cpu;
1062 CPUArchState *mon_get_cpu_env(void)
1064 CPUState *cs = mon_get_cpu();
1066 return cs ? cs->env_ptr : NULL;
1069 int monitor_get_cpu_index(void)
1071 CPUState *cs = mon_get_cpu();
1073 return cs ? cs->cpu_index : UNASSIGNED_CPU_INDEX;
1076 static void hmp_info_registers(Monitor *mon, const QDict *qdict)
1078 CPUState *cs = mon_get_cpu();
1080 if (!cs) {
1081 monitor_printf(mon, "No CPU available\n");
1082 return;
1084 cpu_dump_state(cs, (FILE *)mon, monitor_fprintf, CPU_DUMP_FPU);
1087 static void hmp_info_jit(Monitor *mon, const QDict *qdict)
1089 if (!tcg_enabled()) {
1090 error_report("JIT information is only available with accel=tcg");
1091 return;
1094 dump_exec_info((FILE *)mon, monitor_fprintf);
1095 dump_drift_info((FILE *)mon, monitor_fprintf);
1098 static void hmp_info_opcount(Monitor *mon, const QDict *qdict)
1100 dump_opcount_info((FILE *)mon, monitor_fprintf);
1103 static void hmp_info_history(Monitor *mon, const QDict *qdict)
1105 int i;
1106 const char *str;
1108 if (!mon->rs)
1109 return;
1110 i = 0;
1111 for(;;) {
1112 str = readline_get_history(mon->rs, i);
1113 if (!str)
1114 break;
1115 monitor_printf(mon, "%d: '%s'\n", i, str);
1116 i++;
1120 static void hmp_info_cpustats(Monitor *mon, const QDict *qdict)
1122 CPUState *cs = mon_get_cpu();
1124 if (!cs) {
1125 monitor_printf(mon, "No CPU available\n");
1126 return;
1128 cpu_dump_statistics(cs, (FILE *)mon, &monitor_fprintf, 0);
1131 static void hmp_info_trace_events(Monitor *mon, const QDict *qdict)
1133 const char *name = qdict_get_try_str(qdict, "name");
1134 bool has_vcpu = qdict_haskey(qdict, "vcpu");
1135 int vcpu = qdict_get_try_int(qdict, "vcpu", 0);
1136 TraceEventInfoList *events;
1137 TraceEventInfoList *elem;
1138 Error *local_err = NULL;
1140 if (name == NULL) {
1141 name = "*";
1143 if (vcpu < 0) {
1144 monitor_printf(mon, "argument vcpu must be positive");
1145 return;
1148 events = qmp_trace_event_get_state(name, has_vcpu, vcpu, &local_err);
1149 if (local_err) {
1150 error_report_err(local_err);
1151 return;
1154 for (elem = events; elem != NULL; elem = elem->next) {
1155 monitor_printf(mon, "%s : state %u\n",
1156 elem->value->name,
1157 elem->value->state == TRACE_EVENT_STATE_ENABLED ? 1 : 0);
1159 qapi_free_TraceEventInfoList(events);
1162 void qmp_client_migrate_info(const char *protocol, const char *hostname,
1163 bool has_port, int64_t port,
1164 bool has_tls_port, int64_t tls_port,
1165 bool has_cert_subject, const char *cert_subject,
1166 Error **errp)
1168 if (strcmp(protocol, "spice") == 0) {
1169 if (!qemu_using_spice(errp)) {
1170 return;
1173 if (!has_port && !has_tls_port) {
1174 error_setg(errp, QERR_MISSING_PARAMETER, "port/tls-port");
1175 return;
1178 if (qemu_spice_migrate_info(hostname,
1179 has_port ? port : -1,
1180 has_tls_port ? tls_port : -1,
1181 cert_subject)) {
1182 error_setg(errp, QERR_UNDEFINED_ERROR);
1183 return;
1185 return;
1188 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "protocol", "spice");
1191 static void hmp_logfile(Monitor *mon, const QDict *qdict)
1193 Error *err = NULL;
1195 qemu_set_log_filename(qdict_get_str(qdict, "filename"), &err);
1196 if (err) {
1197 error_report_err(err);
1201 static void hmp_log(Monitor *mon, const QDict *qdict)
1203 int mask;
1204 const char *items = qdict_get_str(qdict, "items");
1206 if (!strcmp(items, "none")) {
1207 mask = 0;
1208 } else {
1209 mask = qemu_str_to_log_mask(items);
1210 if (!mask) {
1211 help_cmd(mon, "log");
1212 return;
1215 qemu_set_log(mask);
1218 static void hmp_singlestep(Monitor *mon, const QDict *qdict)
1220 const char *option = qdict_get_try_str(qdict, "option");
1221 if (!option || !strcmp(option, "on")) {
1222 singlestep = 1;
1223 } else if (!strcmp(option, "off")) {
1224 singlestep = 0;
1225 } else {
1226 monitor_printf(mon, "unexpected option %s\n", option);
1230 static void hmp_gdbserver(Monitor *mon, const QDict *qdict)
1232 const char *device = qdict_get_try_str(qdict, "device");
1233 if (!device)
1234 device = "tcp::" DEFAULT_GDBSTUB_PORT;
1235 if (gdbserver_start(device) < 0) {
1236 monitor_printf(mon, "Could not open gdbserver on device '%s'\n",
1237 device);
1238 } else if (strcmp(device, "none") == 0) {
1239 monitor_printf(mon, "Disabled gdbserver\n");
1240 } else {
1241 monitor_printf(mon, "Waiting for gdb connection on device '%s'\n",
1242 device);
1246 static void hmp_watchdog_action(Monitor *mon, const QDict *qdict)
1248 const char *action = qdict_get_str(qdict, "action");
1249 if (select_watchdog_action(action) == -1) {
1250 monitor_printf(mon, "Unknown watchdog action '%s'\n", action);
1254 static void monitor_printc(Monitor *mon, int c)
1256 monitor_printf(mon, "'");
1257 switch(c) {
1258 case '\'':
1259 monitor_printf(mon, "\\'");
1260 break;
1261 case '\\':
1262 monitor_printf(mon, "\\\\");
1263 break;
1264 case '\n':
1265 monitor_printf(mon, "\\n");
1266 break;
1267 case '\r':
1268 monitor_printf(mon, "\\r");
1269 break;
1270 default:
1271 if (c >= 32 && c <= 126) {
1272 monitor_printf(mon, "%c", c);
1273 } else {
1274 monitor_printf(mon, "\\x%02x", c);
1276 break;
1278 monitor_printf(mon, "'");
1281 static void memory_dump(Monitor *mon, int count, int format, int wsize,
1282 hwaddr addr, int is_physical)
1284 int l, line_size, i, max_digits, len;
1285 uint8_t buf[16];
1286 uint64_t v;
1287 CPUState *cs = mon_get_cpu();
1289 if (!cs && (format == 'i' || !is_physical)) {
1290 monitor_printf(mon, "Can not dump without CPU\n");
1291 return;
1294 if (format == 'i') {
1295 int flags = 0;
1296 #ifdef TARGET_I386
1297 CPUArchState *env = mon_get_cpu_env();
1298 if (wsize == 2) {
1299 flags = 1;
1300 } else if (wsize == 4) {
1301 flags = 0;
1302 } else {
1303 /* as default we use the current CS size */
1304 flags = 0;
1305 if (env) {
1306 #ifdef TARGET_X86_64
1307 if ((env->efer & MSR_EFER_LMA) &&
1308 (env->segs[R_CS].flags & DESC_L_MASK))
1309 flags = 2;
1310 else
1311 #endif
1312 if (!(env->segs[R_CS].flags & DESC_B_MASK))
1313 flags = 1;
1316 #endif
1317 #ifdef TARGET_PPC
1318 CPUArchState *env = mon_get_cpu_env();
1319 flags = msr_le << 16;
1320 flags |= env->bfd_mach;
1321 #endif
1322 monitor_disas(mon, cs, addr, count, is_physical, flags);
1323 return;
1326 len = wsize * count;
1327 if (wsize == 1)
1328 line_size = 8;
1329 else
1330 line_size = 16;
1331 max_digits = 0;
1333 switch(format) {
1334 case 'o':
1335 max_digits = (wsize * 8 + 2) / 3;
1336 break;
1337 default:
1338 case 'x':
1339 max_digits = (wsize * 8) / 4;
1340 break;
1341 case 'u':
1342 case 'd':
1343 max_digits = (wsize * 8 * 10 + 32) / 33;
1344 break;
1345 case 'c':
1346 wsize = 1;
1347 break;
1350 while (len > 0) {
1351 if (is_physical)
1352 monitor_printf(mon, TARGET_FMT_plx ":", addr);
1353 else
1354 monitor_printf(mon, TARGET_FMT_lx ":", (target_ulong)addr);
1355 l = len;
1356 if (l > line_size)
1357 l = line_size;
1358 if (is_physical) {
1359 cpu_physical_memory_read(addr, buf, l);
1360 } else {
1361 if (cpu_memory_rw_debug(cs, addr, buf, l, 0) < 0) {
1362 monitor_printf(mon, " Cannot access memory\n");
1363 break;
1366 i = 0;
1367 while (i < l) {
1368 switch(wsize) {
1369 default:
1370 case 1:
1371 v = ldub_p(buf + i);
1372 break;
1373 case 2:
1374 v = lduw_p(buf + i);
1375 break;
1376 case 4:
1377 v = (uint32_t)ldl_p(buf + i);
1378 break;
1379 case 8:
1380 v = ldq_p(buf + i);
1381 break;
1383 monitor_printf(mon, " ");
1384 switch(format) {
1385 case 'o':
1386 monitor_printf(mon, "%#*" PRIo64, max_digits, v);
1387 break;
1388 case 'x':
1389 monitor_printf(mon, "0x%0*" PRIx64, max_digits, v);
1390 break;
1391 case 'u':
1392 monitor_printf(mon, "%*" PRIu64, max_digits, v);
1393 break;
1394 case 'd':
1395 monitor_printf(mon, "%*" PRId64, max_digits, v);
1396 break;
1397 case 'c':
1398 monitor_printc(mon, v);
1399 break;
1401 i += wsize;
1403 monitor_printf(mon, "\n");
1404 addr += l;
1405 len -= l;
1409 static void hmp_memory_dump(Monitor *mon, const QDict *qdict)
1411 int count = qdict_get_int(qdict, "count");
1412 int format = qdict_get_int(qdict, "format");
1413 int size = qdict_get_int(qdict, "size");
1414 target_long addr = qdict_get_int(qdict, "addr");
1416 memory_dump(mon, count, format, size, addr, 0);
1419 static void hmp_physical_memory_dump(Monitor *mon, const QDict *qdict)
1421 int count = qdict_get_int(qdict, "count");
1422 int format = qdict_get_int(qdict, "format");
1423 int size = qdict_get_int(qdict, "size");
1424 hwaddr addr = qdict_get_int(qdict, "addr");
1426 memory_dump(mon, count, format, size, addr, 1);
1429 static void *gpa2hva(MemoryRegion **p_mr, hwaddr addr, Error **errp)
1431 MemoryRegionSection mrs = memory_region_find(get_system_memory(),
1432 addr, 1);
1434 if (!mrs.mr) {
1435 error_setg(errp, "No memory is mapped at address 0x%" HWADDR_PRIx, addr);
1436 return NULL;
1439 if (!memory_region_is_ram(mrs.mr) && !memory_region_is_romd(mrs.mr)) {
1440 error_setg(errp, "Memory at address 0x%" HWADDR_PRIx "is not RAM", addr);
1441 memory_region_unref(mrs.mr);
1442 return NULL;
1445 *p_mr = mrs.mr;
1446 return qemu_map_ram_ptr(mrs.mr->ram_block, mrs.offset_within_region);
1449 static void hmp_gpa2hva(Monitor *mon, const QDict *qdict)
1451 hwaddr addr = qdict_get_int(qdict, "addr");
1452 Error *local_err = NULL;
1453 MemoryRegion *mr = NULL;
1454 void *ptr;
1456 ptr = gpa2hva(&mr, addr, &local_err);
1457 if (local_err) {
1458 error_report_err(local_err);
1459 return;
1462 monitor_printf(mon, "Host virtual address for 0x%" HWADDR_PRIx
1463 " (%s) is %p\n",
1464 addr, mr->name, ptr);
1466 memory_region_unref(mr);
1469 #ifdef CONFIG_LINUX
1470 static uint64_t vtop(void *ptr, Error **errp)
1472 uint64_t pinfo;
1473 uint64_t ret = -1;
1474 uintptr_t addr = (uintptr_t) ptr;
1475 uintptr_t pagesize = getpagesize();
1476 off_t offset = addr / pagesize * sizeof(pinfo);
1477 int fd;
1479 fd = open("/proc/self/pagemap", O_RDONLY);
1480 if (fd == -1) {
1481 error_setg_errno(errp, errno, "Cannot open /proc/self/pagemap");
1482 return -1;
1485 /* Force copy-on-write if necessary. */
1486 atomic_add((uint8_t *)ptr, 0);
1488 if (pread(fd, &pinfo, sizeof(pinfo), offset) != sizeof(pinfo)) {
1489 error_setg_errno(errp, errno, "Cannot read pagemap");
1490 goto out;
1492 if ((pinfo & (1ull << 63)) == 0) {
1493 error_setg(errp, "Page not present");
1494 goto out;
1496 ret = ((pinfo & 0x007fffffffffffffull) * pagesize) | (addr & (pagesize - 1));
1498 out:
1499 close(fd);
1500 return ret;
1503 static void hmp_gpa2hpa(Monitor *mon, const QDict *qdict)
1505 hwaddr addr = qdict_get_int(qdict, "addr");
1506 Error *local_err = NULL;
1507 MemoryRegion *mr = NULL;
1508 void *ptr;
1509 uint64_t physaddr;
1511 ptr = gpa2hva(&mr, addr, &local_err);
1512 if (local_err) {
1513 error_report_err(local_err);
1514 return;
1517 physaddr = vtop(ptr, &local_err);
1518 if (local_err) {
1519 error_report_err(local_err);
1520 } else {
1521 monitor_printf(mon, "Host physical address for 0x%" HWADDR_PRIx
1522 " (%s) is 0x%" PRIx64 "\n",
1523 addr, mr->name, (uint64_t) physaddr);
1526 memory_region_unref(mr);
1528 #endif
1530 static void do_print(Monitor *mon, const QDict *qdict)
1532 int format = qdict_get_int(qdict, "format");
1533 hwaddr val = qdict_get_int(qdict, "val");
1535 switch(format) {
1536 case 'o':
1537 monitor_printf(mon, "%#" HWADDR_PRIo, val);
1538 break;
1539 case 'x':
1540 monitor_printf(mon, "%#" HWADDR_PRIx, val);
1541 break;
1542 case 'u':
1543 monitor_printf(mon, "%" HWADDR_PRIu, val);
1544 break;
1545 default:
1546 case 'd':
1547 monitor_printf(mon, "%" HWADDR_PRId, val);
1548 break;
1549 case 'c':
1550 monitor_printc(mon, val);
1551 break;
1553 monitor_printf(mon, "\n");
1556 static void hmp_sum(Monitor *mon, const QDict *qdict)
1558 uint32_t addr;
1559 uint16_t sum;
1560 uint32_t start = qdict_get_int(qdict, "start");
1561 uint32_t size = qdict_get_int(qdict, "size");
1563 sum = 0;
1564 for(addr = start; addr < (start + size); addr++) {
1565 uint8_t val = address_space_ldub(&address_space_memory, addr,
1566 MEMTXATTRS_UNSPECIFIED, NULL);
1567 /* BSD sum algorithm ('sum' Unix command) */
1568 sum = (sum >> 1) | (sum << 15);
1569 sum += val;
1571 monitor_printf(mon, "%05d\n", sum);
1574 static int mouse_button_state;
1576 static void hmp_mouse_move(Monitor *mon, const QDict *qdict)
1578 int dx, dy, dz, button;
1579 const char *dx_str = qdict_get_str(qdict, "dx_str");
1580 const char *dy_str = qdict_get_str(qdict, "dy_str");
1581 const char *dz_str = qdict_get_try_str(qdict, "dz_str");
1583 dx = strtol(dx_str, NULL, 0);
1584 dy = strtol(dy_str, NULL, 0);
1585 qemu_input_queue_rel(NULL, INPUT_AXIS_X, dx);
1586 qemu_input_queue_rel(NULL, INPUT_AXIS_Y, dy);
1588 if (dz_str) {
1589 dz = strtol(dz_str, NULL, 0);
1590 if (dz != 0) {
1591 button = (dz > 0) ? INPUT_BUTTON_WHEEL_UP : INPUT_BUTTON_WHEEL_DOWN;
1592 qemu_input_queue_btn(NULL, button, true);
1593 qemu_input_event_sync();
1594 qemu_input_queue_btn(NULL, button, false);
1597 qemu_input_event_sync();
1600 static void hmp_mouse_button(Monitor *mon, const QDict *qdict)
1602 static uint32_t bmap[INPUT_BUTTON__MAX] = {
1603 [INPUT_BUTTON_LEFT] = MOUSE_EVENT_LBUTTON,
1604 [INPUT_BUTTON_MIDDLE] = MOUSE_EVENT_MBUTTON,
1605 [INPUT_BUTTON_RIGHT] = MOUSE_EVENT_RBUTTON,
1607 int button_state = qdict_get_int(qdict, "button_state");
1609 if (mouse_button_state == button_state) {
1610 return;
1612 qemu_input_update_buttons(NULL, bmap, mouse_button_state, button_state);
1613 qemu_input_event_sync();
1614 mouse_button_state = button_state;
1617 static void hmp_ioport_read(Monitor *mon, const QDict *qdict)
1619 int size = qdict_get_int(qdict, "size");
1620 int addr = qdict_get_int(qdict, "addr");
1621 int has_index = qdict_haskey(qdict, "index");
1622 uint32_t val;
1623 int suffix;
1625 if (has_index) {
1626 int index = qdict_get_int(qdict, "index");
1627 cpu_outb(addr & IOPORTS_MASK, index & 0xff);
1628 addr++;
1630 addr &= 0xffff;
1632 switch(size) {
1633 default:
1634 case 1:
1635 val = cpu_inb(addr);
1636 suffix = 'b';
1637 break;
1638 case 2:
1639 val = cpu_inw(addr);
1640 suffix = 'w';
1641 break;
1642 case 4:
1643 val = cpu_inl(addr);
1644 suffix = 'l';
1645 break;
1647 monitor_printf(mon, "port%c[0x%04x] = %#0*x\n",
1648 suffix, addr, size * 2, val);
1651 static void hmp_ioport_write(Monitor *mon, const QDict *qdict)
1653 int size = qdict_get_int(qdict, "size");
1654 int addr = qdict_get_int(qdict, "addr");
1655 int val = qdict_get_int(qdict, "val");
1657 addr &= IOPORTS_MASK;
1659 switch (size) {
1660 default:
1661 case 1:
1662 cpu_outb(addr, val);
1663 break;
1664 case 2:
1665 cpu_outw(addr, val);
1666 break;
1667 case 4:
1668 cpu_outl(addr, val);
1669 break;
1673 static void hmp_boot_set(Monitor *mon, const QDict *qdict)
1675 Error *local_err = NULL;
1676 const char *bootdevice = qdict_get_str(qdict, "bootdevice");
1678 qemu_boot_set(bootdevice, &local_err);
1679 if (local_err) {
1680 error_report_err(local_err);
1681 } else {
1682 monitor_printf(mon, "boot device list now set to %s\n", bootdevice);
1686 static void hmp_info_mtree(Monitor *mon, const QDict *qdict)
1688 bool flatview = qdict_get_try_bool(qdict, "flatview", false);
1690 mtree_info((fprintf_function)monitor_printf, mon, flatview);
1693 static void hmp_info_numa(Monitor *mon, const QDict *qdict)
1695 int i;
1696 CPUState *cpu;
1697 uint64_t *node_mem;
1699 node_mem = g_new0(uint64_t, nb_numa_nodes);
1700 query_numa_node_mem(node_mem);
1701 monitor_printf(mon, "%d nodes\n", nb_numa_nodes);
1702 for (i = 0; i < nb_numa_nodes; i++) {
1703 monitor_printf(mon, "node %d cpus:", i);
1704 CPU_FOREACH(cpu) {
1705 if (cpu->numa_node == i) {
1706 monitor_printf(mon, " %d", cpu->cpu_index);
1709 monitor_printf(mon, "\n");
1710 monitor_printf(mon, "node %d size: %" PRId64 " MB\n", i,
1711 node_mem[i] >> 20);
1713 g_free(node_mem);
1716 #ifdef CONFIG_PROFILER
1718 int64_t tcg_time;
1719 int64_t dev_time;
1721 static void hmp_info_profile(Monitor *mon, const QDict *qdict)
1723 monitor_printf(mon, "async time %" PRId64 " (%0.3f)\n",
1724 dev_time, dev_time / (double)NANOSECONDS_PER_SECOND);
1725 monitor_printf(mon, "qemu time %" PRId64 " (%0.3f)\n",
1726 tcg_time, tcg_time / (double)NANOSECONDS_PER_SECOND);
1727 tcg_time = 0;
1728 dev_time = 0;
1730 #else
1731 static void hmp_info_profile(Monitor *mon, const QDict *qdict)
1733 monitor_printf(mon, "Internal profiler not compiled\n");
1735 #endif
1737 /* Capture support */
1738 static QLIST_HEAD (capture_list_head, CaptureState) capture_head;
1740 static void hmp_info_capture(Monitor *mon, const QDict *qdict)
1742 int i;
1743 CaptureState *s;
1745 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
1746 monitor_printf(mon, "[%d]: ", i);
1747 s->ops.info (s->opaque);
1751 static void hmp_stopcapture(Monitor *mon, const QDict *qdict)
1753 int i;
1754 int n = qdict_get_int(qdict, "n");
1755 CaptureState *s;
1757 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
1758 if (i == n) {
1759 s->ops.destroy (s->opaque);
1760 QLIST_REMOVE (s, entries);
1761 g_free (s);
1762 return;
1767 static void hmp_wavcapture(Monitor *mon, const QDict *qdict)
1769 const char *path = qdict_get_str(qdict, "path");
1770 int has_freq = qdict_haskey(qdict, "freq");
1771 int freq = qdict_get_try_int(qdict, "freq", -1);
1772 int has_bits = qdict_haskey(qdict, "bits");
1773 int bits = qdict_get_try_int(qdict, "bits", -1);
1774 int has_channels = qdict_haskey(qdict, "nchannels");
1775 int nchannels = qdict_get_try_int(qdict, "nchannels", -1);
1776 CaptureState *s;
1778 s = g_malloc0 (sizeof (*s));
1780 freq = has_freq ? freq : 44100;
1781 bits = has_bits ? bits : 16;
1782 nchannels = has_channels ? nchannels : 2;
1784 if (wav_start_capture (s, path, freq, bits, nchannels)) {
1785 monitor_printf(mon, "Failed to add wave capture\n");
1786 g_free (s);
1787 return;
1789 QLIST_INSERT_HEAD (&capture_head, s, entries);
1792 static qemu_acl *find_acl(Monitor *mon, const char *name)
1794 qemu_acl *acl = qemu_acl_find(name);
1796 if (!acl) {
1797 monitor_printf(mon, "acl: unknown list '%s'\n", name);
1799 return acl;
1802 static void hmp_acl_show(Monitor *mon, const QDict *qdict)
1804 const char *aclname = qdict_get_str(qdict, "aclname");
1805 qemu_acl *acl = find_acl(mon, aclname);
1806 qemu_acl_entry *entry;
1807 int i = 0;
1809 if (acl) {
1810 monitor_printf(mon, "policy: %s\n",
1811 acl->defaultDeny ? "deny" : "allow");
1812 QTAILQ_FOREACH(entry, &acl->entries, next) {
1813 i++;
1814 monitor_printf(mon, "%d: %s %s\n", i,
1815 entry->deny ? "deny" : "allow", entry->match);
1820 static void hmp_acl_reset(Monitor *mon, const QDict *qdict)
1822 const char *aclname = qdict_get_str(qdict, "aclname");
1823 qemu_acl *acl = find_acl(mon, aclname);
1825 if (acl) {
1826 qemu_acl_reset(acl);
1827 monitor_printf(mon, "acl: removed all rules\n");
1831 static void hmp_acl_policy(Monitor *mon, const QDict *qdict)
1833 const char *aclname = qdict_get_str(qdict, "aclname");
1834 const char *policy = qdict_get_str(qdict, "policy");
1835 qemu_acl *acl = find_acl(mon, aclname);
1837 if (acl) {
1838 if (strcmp(policy, "allow") == 0) {
1839 acl->defaultDeny = 0;
1840 monitor_printf(mon, "acl: policy set to 'allow'\n");
1841 } else if (strcmp(policy, "deny") == 0) {
1842 acl->defaultDeny = 1;
1843 monitor_printf(mon, "acl: policy set to 'deny'\n");
1844 } else {
1845 monitor_printf(mon, "acl: unknown policy '%s', "
1846 "expected 'deny' or 'allow'\n", policy);
1851 static void hmp_acl_add(Monitor *mon, const QDict *qdict)
1853 const char *aclname = qdict_get_str(qdict, "aclname");
1854 const char *match = qdict_get_str(qdict, "match");
1855 const char *policy = qdict_get_str(qdict, "policy");
1856 int has_index = qdict_haskey(qdict, "index");
1857 int index = qdict_get_try_int(qdict, "index", -1);
1858 qemu_acl *acl = find_acl(mon, aclname);
1859 int deny, ret;
1861 if (acl) {
1862 if (strcmp(policy, "allow") == 0) {
1863 deny = 0;
1864 } else if (strcmp(policy, "deny") == 0) {
1865 deny = 1;
1866 } else {
1867 monitor_printf(mon, "acl: unknown policy '%s', "
1868 "expected 'deny' or 'allow'\n", policy);
1869 return;
1871 if (has_index)
1872 ret = qemu_acl_insert(acl, deny, match, index);
1873 else
1874 ret = qemu_acl_append(acl, deny, match);
1875 if (ret < 0)
1876 monitor_printf(mon, "acl: unable to add acl entry\n");
1877 else
1878 monitor_printf(mon, "acl: added rule at position %d\n", ret);
1882 static void hmp_acl_remove(Monitor *mon, const QDict *qdict)
1884 const char *aclname = qdict_get_str(qdict, "aclname");
1885 const char *match = qdict_get_str(qdict, "match");
1886 qemu_acl *acl = find_acl(mon, aclname);
1887 int ret;
1889 if (acl) {
1890 ret = qemu_acl_remove(acl, match);
1891 if (ret < 0)
1892 monitor_printf(mon, "acl: no matching acl entry\n");
1893 else
1894 monitor_printf(mon, "acl: removed rule at position %d\n", ret);
1898 void qmp_getfd(const char *fdname, Error **errp)
1900 mon_fd_t *monfd;
1901 int fd;
1903 fd = qemu_chr_fe_get_msgfd(&cur_mon->chr);
1904 if (fd == -1) {
1905 error_setg(errp, QERR_FD_NOT_SUPPLIED);
1906 return;
1909 if (qemu_isdigit(fdname[0])) {
1910 close(fd);
1911 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "fdname",
1912 "a name not starting with a digit");
1913 return;
1916 QLIST_FOREACH(monfd, &cur_mon->fds, next) {
1917 if (strcmp(monfd->name, fdname) != 0) {
1918 continue;
1921 close(monfd->fd);
1922 monfd->fd = fd;
1923 return;
1926 monfd = g_malloc0(sizeof(mon_fd_t));
1927 monfd->name = g_strdup(fdname);
1928 monfd->fd = fd;
1930 QLIST_INSERT_HEAD(&cur_mon->fds, monfd, next);
1933 void qmp_closefd(const char *fdname, Error **errp)
1935 mon_fd_t *monfd;
1937 QLIST_FOREACH(monfd, &cur_mon->fds, next) {
1938 if (strcmp(monfd->name, fdname) != 0) {
1939 continue;
1942 QLIST_REMOVE(monfd, next);
1943 close(monfd->fd);
1944 g_free(monfd->name);
1945 g_free(monfd);
1946 return;
1949 error_setg(errp, QERR_FD_NOT_FOUND, fdname);
1952 static void hmp_loadvm(Monitor *mon, const QDict *qdict)
1954 int saved_vm_running = runstate_is_running();
1955 const char *name = qdict_get_str(qdict, "name");
1957 vm_stop(RUN_STATE_RESTORE_VM);
1959 if (load_vmstate(name) == 0 && saved_vm_running) {
1960 vm_start();
1964 int monitor_get_fd(Monitor *mon, const char *fdname, Error **errp)
1966 mon_fd_t *monfd;
1968 QLIST_FOREACH(monfd, &mon->fds, next) {
1969 int fd;
1971 if (strcmp(monfd->name, fdname) != 0) {
1972 continue;
1975 fd = monfd->fd;
1977 /* caller takes ownership of fd */
1978 QLIST_REMOVE(monfd, next);
1979 g_free(monfd->name);
1980 g_free(monfd);
1982 return fd;
1985 error_setg(errp, "File descriptor named '%s' has not been found", fdname);
1986 return -1;
1989 static void monitor_fdset_cleanup(MonFdset *mon_fdset)
1991 MonFdsetFd *mon_fdset_fd;
1992 MonFdsetFd *mon_fdset_fd_next;
1994 QLIST_FOREACH_SAFE(mon_fdset_fd, &mon_fdset->fds, next, mon_fdset_fd_next) {
1995 if ((mon_fdset_fd->removed ||
1996 (QLIST_EMPTY(&mon_fdset->dup_fds) && mon_refcount == 0)) &&
1997 runstate_is_running()) {
1998 close(mon_fdset_fd->fd);
1999 g_free(mon_fdset_fd->opaque);
2000 QLIST_REMOVE(mon_fdset_fd, next);
2001 g_free(mon_fdset_fd);
2005 if (QLIST_EMPTY(&mon_fdset->fds) && QLIST_EMPTY(&mon_fdset->dup_fds)) {
2006 QLIST_REMOVE(mon_fdset, next);
2007 g_free(mon_fdset);
2011 static void monitor_fdsets_cleanup(void)
2013 MonFdset *mon_fdset;
2014 MonFdset *mon_fdset_next;
2016 QLIST_FOREACH_SAFE(mon_fdset, &mon_fdsets, next, mon_fdset_next) {
2017 monitor_fdset_cleanup(mon_fdset);
2021 AddfdInfo *qmp_add_fd(bool has_fdset_id, int64_t fdset_id, bool has_opaque,
2022 const char *opaque, Error **errp)
2024 int fd;
2025 Monitor *mon = cur_mon;
2026 AddfdInfo *fdinfo;
2028 fd = qemu_chr_fe_get_msgfd(&mon->chr);
2029 if (fd == -1) {
2030 error_setg(errp, QERR_FD_NOT_SUPPLIED);
2031 goto error;
2034 fdinfo = monitor_fdset_add_fd(fd, has_fdset_id, fdset_id,
2035 has_opaque, opaque, errp);
2036 if (fdinfo) {
2037 return fdinfo;
2040 error:
2041 if (fd != -1) {
2042 close(fd);
2044 return NULL;
2047 void qmp_remove_fd(int64_t fdset_id, bool has_fd, int64_t fd, Error **errp)
2049 MonFdset *mon_fdset;
2050 MonFdsetFd *mon_fdset_fd;
2051 char fd_str[60];
2053 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2054 if (mon_fdset->id != fdset_id) {
2055 continue;
2057 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2058 if (has_fd) {
2059 if (mon_fdset_fd->fd != fd) {
2060 continue;
2062 mon_fdset_fd->removed = true;
2063 break;
2064 } else {
2065 mon_fdset_fd->removed = true;
2068 if (has_fd && !mon_fdset_fd) {
2069 goto error;
2071 monitor_fdset_cleanup(mon_fdset);
2072 return;
2075 error:
2076 if (has_fd) {
2077 snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64 ", fd:%" PRId64,
2078 fdset_id, fd);
2079 } else {
2080 snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64, fdset_id);
2082 error_setg(errp, QERR_FD_NOT_FOUND, fd_str);
2085 FdsetInfoList *qmp_query_fdsets(Error **errp)
2087 MonFdset *mon_fdset;
2088 MonFdsetFd *mon_fdset_fd;
2089 FdsetInfoList *fdset_list = NULL;
2091 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2092 FdsetInfoList *fdset_info = g_malloc0(sizeof(*fdset_info));
2093 FdsetFdInfoList *fdsetfd_list = NULL;
2095 fdset_info->value = g_malloc0(sizeof(*fdset_info->value));
2096 fdset_info->value->fdset_id = mon_fdset->id;
2098 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2099 FdsetFdInfoList *fdsetfd_info;
2101 fdsetfd_info = g_malloc0(sizeof(*fdsetfd_info));
2102 fdsetfd_info->value = g_malloc0(sizeof(*fdsetfd_info->value));
2103 fdsetfd_info->value->fd = mon_fdset_fd->fd;
2104 if (mon_fdset_fd->opaque) {
2105 fdsetfd_info->value->has_opaque = true;
2106 fdsetfd_info->value->opaque = g_strdup(mon_fdset_fd->opaque);
2107 } else {
2108 fdsetfd_info->value->has_opaque = false;
2111 fdsetfd_info->next = fdsetfd_list;
2112 fdsetfd_list = fdsetfd_info;
2115 fdset_info->value->fds = fdsetfd_list;
2117 fdset_info->next = fdset_list;
2118 fdset_list = fdset_info;
2121 return fdset_list;
2124 AddfdInfo *monitor_fdset_add_fd(int fd, bool has_fdset_id, int64_t fdset_id,
2125 bool has_opaque, const char *opaque,
2126 Error **errp)
2128 MonFdset *mon_fdset = NULL;
2129 MonFdsetFd *mon_fdset_fd;
2130 AddfdInfo *fdinfo;
2132 if (has_fdset_id) {
2133 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2134 /* Break if match found or match impossible due to ordering by ID */
2135 if (fdset_id <= mon_fdset->id) {
2136 if (fdset_id < mon_fdset->id) {
2137 mon_fdset = NULL;
2139 break;
2144 if (mon_fdset == NULL) {
2145 int64_t fdset_id_prev = -1;
2146 MonFdset *mon_fdset_cur = QLIST_FIRST(&mon_fdsets);
2148 if (has_fdset_id) {
2149 if (fdset_id < 0) {
2150 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "fdset-id",
2151 "a non-negative value");
2152 return NULL;
2154 /* Use specified fdset ID */
2155 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2156 mon_fdset_cur = mon_fdset;
2157 if (fdset_id < mon_fdset_cur->id) {
2158 break;
2161 } else {
2162 /* Use first available fdset ID */
2163 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2164 mon_fdset_cur = mon_fdset;
2165 if (fdset_id_prev == mon_fdset_cur->id - 1) {
2166 fdset_id_prev = mon_fdset_cur->id;
2167 continue;
2169 break;
2173 mon_fdset = g_malloc0(sizeof(*mon_fdset));
2174 if (has_fdset_id) {
2175 mon_fdset->id = fdset_id;
2176 } else {
2177 mon_fdset->id = fdset_id_prev + 1;
2180 /* The fdset list is ordered by fdset ID */
2181 if (!mon_fdset_cur) {
2182 QLIST_INSERT_HEAD(&mon_fdsets, mon_fdset, next);
2183 } else if (mon_fdset->id < mon_fdset_cur->id) {
2184 QLIST_INSERT_BEFORE(mon_fdset_cur, mon_fdset, next);
2185 } else {
2186 QLIST_INSERT_AFTER(mon_fdset_cur, mon_fdset, next);
2190 mon_fdset_fd = g_malloc0(sizeof(*mon_fdset_fd));
2191 mon_fdset_fd->fd = fd;
2192 mon_fdset_fd->removed = false;
2193 if (has_opaque) {
2194 mon_fdset_fd->opaque = g_strdup(opaque);
2196 QLIST_INSERT_HEAD(&mon_fdset->fds, mon_fdset_fd, next);
2198 fdinfo = g_malloc0(sizeof(*fdinfo));
2199 fdinfo->fdset_id = mon_fdset->id;
2200 fdinfo->fd = mon_fdset_fd->fd;
2202 return fdinfo;
2205 int monitor_fdset_get_fd(int64_t fdset_id, int flags)
2207 #ifndef _WIN32
2208 MonFdset *mon_fdset;
2209 MonFdsetFd *mon_fdset_fd;
2210 int mon_fd_flags;
2212 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2213 if (mon_fdset->id != fdset_id) {
2214 continue;
2216 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2217 mon_fd_flags = fcntl(mon_fdset_fd->fd, F_GETFL);
2218 if (mon_fd_flags == -1) {
2219 return -1;
2222 if ((flags & O_ACCMODE) == (mon_fd_flags & O_ACCMODE)) {
2223 return mon_fdset_fd->fd;
2226 errno = EACCES;
2227 return -1;
2229 #endif
2231 errno = ENOENT;
2232 return -1;
2235 int monitor_fdset_dup_fd_add(int64_t fdset_id, int dup_fd)
2237 MonFdset *mon_fdset;
2238 MonFdsetFd *mon_fdset_fd_dup;
2240 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2241 if (mon_fdset->id != fdset_id) {
2242 continue;
2244 QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
2245 if (mon_fdset_fd_dup->fd == dup_fd) {
2246 return -1;
2249 mon_fdset_fd_dup = g_malloc0(sizeof(*mon_fdset_fd_dup));
2250 mon_fdset_fd_dup->fd = dup_fd;
2251 QLIST_INSERT_HEAD(&mon_fdset->dup_fds, mon_fdset_fd_dup, next);
2252 return 0;
2254 return -1;
2257 static int monitor_fdset_dup_fd_find_remove(int dup_fd, bool remove)
2259 MonFdset *mon_fdset;
2260 MonFdsetFd *mon_fdset_fd_dup;
2262 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2263 QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
2264 if (mon_fdset_fd_dup->fd == dup_fd) {
2265 if (remove) {
2266 QLIST_REMOVE(mon_fdset_fd_dup, next);
2267 if (QLIST_EMPTY(&mon_fdset->dup_fds)) {
2268 monitor_fdset_cleanup(mon_fdset);
2270 return -1;
2271 } else {
2272 return mon_fdset->id;
2277 return -1;
2280 int monitor_fdset_dup_fd_find(int dup_fd)
2282 return monitor_fdset_dup_fd_find_remove(dup_fd, false);
2285 void monitor_fdset_dup_fd_remove(int dup_fd)
2287 monitor_fdset_dup_fd_find_remove(dup_fd, true);
2290 int monitor_fd_param(Monitor *mon, const char *fdname, Error **errp)
2292 int fd;
2293 Error *local_err = NULL;
2295 if (!qemu_isdigit(fdname[0]) && mon) {
2296 fd = monitor_get_fd(mon, fdname, &local_err);
2297 } else {
2298 fd = qemu_parse_fd(fdname);
2299 if (fd == -1) {
2300 error_setg(&local_err, "Invalid file descriptor number '%s'",
2301 fdname);
2304 if (local_err) {
2305 error_propagate(errp, local_err);
2306 assert(fd == -1);
2307 } else {
2308 assert(fd != -1);
2311 return fd;
2314 /* Please update hmp-commands.hx when adding or changing commands */
2315 static mon_cmd_t info_cmds[] = {
2316 #include "hmp-commands-info.h"
2317 { NULL, NULL, },
2320 /* mon_cmds and info_cmds would be sorted at runtime */
2321 static mon_cmd_t mon_cmds[] = {
2322 #include "hmp-commands.h"
2323 { NULL, NULL, },
2326 /*******************************************************************/
2328 static const char *pch;
2329 static sigjmp_buf expr_env;
2332 static void GCC_FMT_ATTR(2, 3) QEMU_NORETURN
2333 expr_error(Monitor *mon, const char *fmt, ...)
2335 va_list ap;
2336 va_start(ap, fmt);
2337 monitor_vprintf(mon, fmt, ap);
2338 monitor_printf(mon, "\n");
2339 va_end(ap);
2340 siglongjmp(expr_env, 1);
2343 /* return 0 if OK, -1 if not found */
2344 static int get_monitor_def(target_long *pval, const char *name)
2346 const MonitorDef *md = target_monitor_defs();
2347 CPUState *cs = mon_get_cpu();
2348 void *ptr;
2349 uint64_t tmp = 0;
2350 int ret;
2352 if (cs == NULL || md == NULL) {
2353 return -1;
2356 for(; md->name != NULL; md++) {
2357 if (compare_cmd(name, md->name)) {
2358 if (md->get_value) {
2359 *pval = md->get_value(md, md->offset);
2360 } else {
2361 CPUArchState *env = mon_get_cpu_env();
2362 ptr = (uint8_t *)env + md->offset;
2363 switch(md->type) {
2364 case MD_I32:
2365 *pval = *(int32_t *)ptr;
2366 break;
2367 case MD_TLONG:
2368 *pval = *(target_long *)ptr;
2369 break;
2370 default:
2371 *pval = 0;
2372 break;
2375 return 0;
2379 ret = target_get_monitor_def(cs, name, &tmp);
2380 if (!ret) {
2381 *pval = (target_long) tmp;
2384 return ret;
2387 static void next(void)
2389 if (*pch != '\0') {
2390 pch++;
2391 while (qemu_isspace(*pch))
2392 pch++;
2396 static int64_t expr_sum(Monitor *mon);
2398 static int64_t expr_unary(Monitor *mon)
2400 int64_t n;
2401 char *p;
2402 int ret;
2404 switch(*pch) {
2405 case '+':
2406 next();
2407 n = expr_unary(mon);
2408 break;
2409 case '-':
2410 next();
2411 n = -expr_unary(mon);
2412 break;
2413 case '~':
2414 next();
2415 n = ~expr_unary(mon);
2416 break;
2417 case '(':
2418 next();
2419 n = expr_sum(mon);
2420 if (*pch != ')') {
2421 expr_error(mon, "')' expected");
2423 next();
2424 break;
2425 case '\'':
2426 pch++;
2427 if (*pch == '\0')
2428 expr_error(mon, "character constant expected");
2429 n = *pch;
2430 pch++;
2431 if (*pch != '\'')
2432 expr_error(mon, "missing terminating \' character");
2433 next();
2434 break;
2435 case '$':
2437 char buf[128], *q;
2438 target_long reg=0;
2440 pch++;
2441 q = buf;
2442 while ((*pch >= 'a' && *pch <= 'z') ||
2443 (*pch >= 'A' && *pch <= 'Z') ||
2444 (*pch >= '0' && *pch <= '9') ||
2445 *pch == '_' || *pch == '.') {
2446 if ((q - buf) < sizeof(buf) - 1)
2447 *q++ = *pch;
2448 pch++;
2450 while (qemu_isspace(*pch))
2451 pch++;
2452 *q = 0;
2453 ret = get_monitor_def(&reg, buf);
2454 if (ret < 0)
2455 expr_error(mon, "unknown register");
2456 n = reg;
2458 break;
2459 case '\0':
2460 expr_error(mon, "unexpected end of expression");
2461 n = 0;
2462 break;
2463 default:
2464 errno = 0;
2465 n = strtoull(pch, &p, 0);
2466 if (errno == ERANGE) {
2467 expr_error(mon, "number too large");
2469 if (pch == p) {
2470 expr_error(mon, "invalid char '%c' in expression", *p);
2472 pch = p;
2473 while (qemu_isspace(*pch))
2474 pch++;
2475 break;
2477 return n;
2481 static int64_t expr_prod(Monitor *mon)
2483 int64_t val, val2;
2484 int op;
2486 val = expr_unary(mon);
2487 for(;;) {
2488 op = *pch;
2489 if (op != '*' && op != '/' && op != '%')
2490 break;
2491 next();
2492 val2 = expr_unary(mon);
2493 switch(op) {
2494 default:
2495 case '*':
2496 val *= val2;
2497 break;
2498 case '/':
2499 case '%':
2500 if (val2 == 0)
2501 expr_error(mon, "division by zero");
2502 if (op == '/')
2503 val /= val2;
2504 else
2505 val %= val2;
2506 break;
2509 return val;
2512 static int64_t expr_logic(Monitor *mon)
2514 int64_t val, val2;
2515 int op;
2517 val = expr_prod(mon);
2518 for(;;) {
2519 op = *pch;
2520 if (op != '&' && op != '|' && op != '^')
2521 break;
2522 next();
2523 val2 = expr_prod(mon);
2524 switch(op) {
2525 default:
2526 case '&':
2527 val &= val2;
2528 break;
2529 case '|':
2530 val |= val2;
2531 break;
2532 case '^':
2533 val ^= val2;
2534 break;
2537 return val;
2540 static int64_t expr_sum(Monitor *mon)
2542 int64_t val, val2;
2543 int op;
2545 val = expr_logic(mon);
2546 for(;;) {
2547 op = *pch;
2548 if (op != '+' && op != '-')
2549 break;
2550 next();
2551 val2 = expr_logic(mon);
2552 if (op == '+')
2553 val += val2;
2554 else
2555 val -= val2;
2557 return val;
2560 static int get_expr(Monitor *mon, int64_t *pval, const char **pp)
2562 pch = *pp;
2563 if (sigsetjmp(expr_env, 0)) {
2564 *pp = pch;
2565 return -1;
2567 while (qemu_isspace(*pch))
2568 pch++;
2569 *pval = expr_sum(mon);
2570 *pp = pch;
2571 return 0;
2574 static int get_double(Monitor *mon, double *pval, const char **pp)
2576 const char *p = *pp;
2577 char *tailp;
2578 double d;
2580 d = strtod(p, &tailp);
2581 if (tailp == p) {
2582 monitor_printf(mon, "Number expected\n");
2583 return -1;
2585 if (d != d || d - d != 0) {
2586 /* NaN or infinity */
2587 monitor_printf(mon, "Bad number\n");
2588 return -1;
2590 *pval = d;
2591 *pp = tailp;
2592 return 0;
2596 * Store the command-name in cmdname, and return a pointer to
2597 * the remaining of the command string.
2599 static const char *get_command_name(const char *cmdline,
2600 char *cmdname, size_t nlen)
2602 size_t len;
2603 const char *p, *pstart;
2605 p = cmdline;
2606 while (qemu_isspace(*p))
2607 p++;
2608 if (*p == '\0')
2609 return NULL;
2610 pstart = p;
2611 while (*p != '\0' && *p != '/' && !qemu_isspace(*p))
2612 p++;
2613 len = p - pstart;
2614 if (len > nlen - 1)
2615 len = nlen - 1;
2616 memcpy(cmdname, pstart, len);
2617 cmdname[len] = '\0';
2618 return p;
2622 * Read key of 'type' into 'key' and return the current
2623 * 'type' pointer.
2625 static char *key_get_info(const char *type, char **key)
2627 size_t len;
2628 char *p, *str;
2630 if (*type == ',')
2631 type++;
2633 p = strchr(type, ':');
2634 if (!p) {
2635 *key = NULL;
2636 return NULL;
2638 len = p - type;
2640 str = g_malloc(len + 1);
2641 memcpy(str, type, len);
2642 str[len] = '\0';
2644 *key = str;
2645 return ++p;
2648 static int default_fmt_format = 'x';
2649 static int default_fmt_size = 4;
2651 static int is_valid_option(const char *c, const char *typestr)
2653 char option[3];
2655 option[0] = '-';
2656 option[1] = *c;
2657 option[2] = '\0';
2659 typestr = strstr(typestr, option);
2660 return (typestr != NULL);
2663 static const mon_cmd_t *search_dispatch_table(const mon_cmd_t *disp_table,
2664 const char *cmdname)
2666 const mon_cmd_t *cmd;
2668 for (cmd = disp_table; cmd->name != NULL; cmd++) {
2669 if (compare_cmd(cmdname, cmd->name)) {
2670 return cmd;
2674 return NULL;
2678 * Parse command name from @cmdp according to command table @table.
2679 * If blank, return NULL.
2680 * Else, if no valid command can be found, report to @mon, and return
2681 * NULL.
2682 * Else, change @cmdp to point right behind the name, and return its
2683 * command table entry.
2684 * Do not assume the return value points into @table! It doesn't when
2685 * the command is found in a sub-command table.
2687 static const mon_cmd_t *monitor_parse_command(Monitor *mon,
2688 const char **cmdp,
2689 mon_cmd_t *table)
2691 const char *p;
2692 const mon_cmd_t *cmd;
2693 char cmdname[256];
2695 /* extract the command name */
2696 p = get_command_name(*cmdp, cmdname, sizeof(cmdname));
2697 if (!p)
2698 return NULL;
2700 cmd = search_dispatch_table(table, cmdname);
2701 if (!cmd) {
2702 monitor_printf(mon, "unknown command: '%.*s'\n",
2703 (int)(p - *cmdp), *cmdp);
2704 return NULL;
2707 /* filter out following useless space */
2708 while (qemu_isspace(*p)) {
2709 p++;
2712 *cmdp = p;
2713 /* search sub command */
2714 if (cmd->sub_table != NULL && *p != '\0') {
2715 return monitor_parse_command(mon, cmdp, cmd->sub_table);
2718 return cmd;
2722 * Parse arguments for @cmd.
2723 * If it can't be parsed, report to @mon, and return NULL.
2724 * Else, insert command arguments into a QDict, and return it.
2725 * Note: On success, caller has to free the QDict structure.
2728 static QDict *monitor_parse_arguments(Monitor *mon,
2729 const char **endp,
2730 const mon_cmd_t *cmd)
2732 const char *typestr;
2733 char *key;
2734 int c;
2735 const char *p = *endp;
2736 char buf[1024];
2737 QDict *qdict = qdict_new();
2739 /* parse the parameters */
2740 typestr = cmd->args_type;
2741 for(;;) {
2742 typestr = key_get_info(typestr, &key);
2743 if (!typestr)
2744 break;
2745 c = *typestr;
2746 typestr++;
2747 switch(c) {
2748 case 'F':
2749 case 'B':
2750 case 's':
2752 int ret;
2754 while (qemu_isspace(*p))
2755 p++;
2756 if (*typestr == '?') {
2757 typestr++;
2758 if (*p == '\0') {
2759 /* no optional string: NULL argument */
2760 break;
2763 ret = get_str(buf, sizeof(buf), &p);
2764 if (ret < 0) {
2765 switch(c) {
2766 case 'F':
2767 monitor_printf(mon, "%s: filename expected\n",
2768 cmd->name);
2769 break;
2770 case 'B':
2771 monitor_printf(mon, "%s: block device name expected\n",
2772 cmd->name);
2773 break;
2774 default:
2775 monitor_printf(mon, "%s: string expected\n", cmd->name);
2776 break;
2778 goto fail;
2780 qdict_put(qdict, key, qstring_from_str(buf));
2782 break;
2783 case 'O':
2785 QemuOptsList *opts_list;
2786 QemuOpts *opts;
2788 opts_list = qemu_find_opts(key);
2789 if (!opts_list || opts_list->desc->name) {
2790 goto bad_type;
2792 while (qemu_isspace(*p)) {
2793 p++;
2795 if (!*p)
2796 break;
2797 if (get_str(buf, sizeof(buf), &p) < 0) {
2798 goto fail;
2800 opts = qemu_opts_parse_noisily(opts_list, buf, true);
2801 if (!opts) {
2802 goto fail;
2804 qemu_opts_to_qdict(opts, qdict);
2805 qemu_opts_del(opts);
2807 break;
2808 case '/':
2810 int count, format, size;
2812 while (qemu_isspace(*p))
2813 p++;
2814 if (*p == '/') {
2815 /* format found */
2816 p++;
2817 count = 1;
2818 if (qemu_isdigit(*p)) {
2819 count = 0;
2820 while (qemu_isdigit(*p)) {
2821 count = count * 10 + (*p - '0');
2822 p++;
2825 size = -1;
2826 format = -1;
2827 for(;;) {
2828 switch(*p) {
2829 case 'o':
2830 case 'd':
2831 case 'u':
2832 case 'x':
2833 case 'i':
2834 case 'c':
2835 format = *p++;
2836 break;
2837 case 'b':
2838 size = 1;
2839 p++;
2840 break;
2841 case 'h':
2842 size = 2;
2843 p++;
2844 break;
2845 case 'w':
2846 size = 4;
2847 p++;
2848 break;
2849 case 'g':
2850 case 'L':
2851 size = 8;
2852 p++;
2853 break;
2854 default:
2855 goto next;
2858 next:
2859 if (*p != '\0' && !qemu_isspace(*p)) {
2860 monitor_printf(mon, "invalid char in format: '%c'\n",
2861 *p);
2862 goto fail;
2864 if (format < 0)
2865 format = default_fmt_format;
2866 if (format != 'i') {
2867 /* for 'i', not specifying a size gives -1 as size */
2868 if (size < 0)
2869 size = default_fmt_size;
2870 default_fmt_size = size;
2872 default_fmt_format = format;
2873 } else {
2874 count = 1;
2875 format = default_fmt_format;
2876 if (format != 'i') {
2877 size = default_fmt_size;
2878 } else {
2879 size = -1;
2882 qdict_put(qdict, "count", qint_from_int(count));
2883 qdict_put(qdict, "format", qint_from_int(format));
2884 qdict_put(qdict, "size", qint_from_int(size));
2886 break;
2887 case 'i':
2888 case 'l':
2889 case 'M':
2891 int64_t val;
2893 while (qemu_isspace(*p))
2894 p++;
2895 if (*typestr == '?' || *typestr == '.') {
2896 if (*typestr == '?') {
2897 if (*p == '\0') {
2898 typestr++;
2899 break;
2901 } else {
2902 if (*p == '.') {
2903 p++;
2904 while (qemu_isspace(*p))
2905 p++;
2906 } else {
2907 typestr++;
2908 break;
2911 typestr++;
2913 if (get_expr(mon, &val, &p))
2914 goto fail;
2915 /* Check if 'i' is greater than 32-bit */
2916 if ((c == 'i') && ((val >> 32) & 0xffffffff)) {
2917 monitor_printf(mon, "\'%s\' has failed: ", cmd->name);
2918 monitor_printf(mon, "integer is for 32-bit values\n");
2919 goto fail;
2920 } else if (c == 'M') {
2921 if (val < 0) {
2922 monitor_printf(mon, "enter a positive value\n");
2923 goto fail;
2925 val <<= 20;
2927 qdict_put(qdict, key, qint_from_int(val));
2929 break;
2930 case 'o':
2932 int ret;
2933 uint64_t val;
2934 char *end;
2936 while (qemu_isspace(*p)) {
2937 p++;
2939 if (*typestr == '?') {
2940 typestr++;
2941 if (*p == '\0') {
2942 break;
2945 ret = qemu_strtosz_MiB(p, &end, &val);
2946 if (ret < 0 || val > INT64_MAX) {
2947 monitor_printf(mon, "invalid size\n");
2948 goto fail;
2950 qdict_put(qdict, key, qint_from_int(val));
2951 p = end;
2953 break;
2954 case 'T':
2956 double val;
2958 while (qemu_isspace(*p))
2959 p++;
2960 if (*typestr == '?') {
2961 typestr++;
2962 if (*p == '\0') {
2963 break;
2966 if (get_double(mon, &val, &p) < 0) {
2967 goto fail;
2969 if (p[0] && p[1] == 's') {
2970 switch (*p) {
2971 case 'm':
2972 val /= 1e3; p += 2; break;
2973 case 'u':
2974 val /= 1e6; p += 2; break;
2975 case 'n':
2976 val /= 1e9; p += 2; break;
2979 if (*p && !qemu_isspace(*p)) {
2980 monitor_printf(mon, "Unknown unit suffix\n");
2981 goto fail;
2983 qdict_put(qdict, key, qfloat_from_double(val));
2985 break;
2986 case 'b':
2988 const char *beg;
2989 bool val;
2991 while (qemu_isspace(*p)) {
2992 p++;
2994 beg = p;
2995 while (qemu_isgraph(*p)) {
2996 p++;
2998 if (p - beg == 2 && !memcmp(beg, "on", p - beg)) {
2999 val = true;
3000 } else if (p - beg == 3 && !memcmp(beg, "off", p - beg)) {
3001 val = false;
3002 } else {
3003 monitor_printf(mon, "Expected 'on' or 'off'\n");
3004 goto fail;
3006 qdict_put(qdict, key, qbool_from_bool(val));
3008 break;
3009 case '-':
3011 const char *tmp = p;
3012 int skip_key = 0;
3013 /* option */
3015 c = *typestr++;
3016 if (c == '\0')
3017 goto bad_type;
3018 while (qemu_isspace(*p))
3019 p++;
3020 if (*p == '-') {
3021 p++;
3022 if(c != *p) {
3023 if(!is_valid_option(p, typestr)) {
3025 monitor_printf(mon, "%s: unsupported option -%c\n",
3026 cmd->name, *p);
3027 goto fail;
3028 } else {
3029 skip_key = 1;
3032 if(skip_key) {
3033 p = tmp;
3034 } else {
3035 /* has option */
3036 p++;
3037 qdict_put(qdict, key, qbool_from_bool(true));
3041 break;
3042 case 'S':
3044 /* package all remaining string */
3045 int len;
3047 while (qemu_isspace(*p)) {
3048 p++;
3050 if (*typestr == '?') {
3051 typestr++;
3052 if (*p == '\0') {
3053 /* no remaining string: NULL argument */
3054 break;
3057 len = strlen(p);
3058 if (len <= 0) {
3059 monitor_printf(mon, "%s: string expected\n",
3060 cmd->name);
3061 goto fail;
3063 qdict_put(qdict, key, qstring_from_str(p));
3064 p += len;
3066 break;
3067 default:
3068 bad_type:
3069 monitor_printf(mon, "%s: unknown type '%c'\n", cmd->name, c);
3070 goto fail;
3072 g_free(key);
3073 key = NULL;
3075 /* check that all arguments were parsed */
3076 while (qemu_isspace(*p))
3077 p++;
3078 if (*p != '\0') {
3079 monitor_printf(mon, "%s: extraneous characters at the end of line\n",
3080 cmd->name);
3081 goto fail;
3084 return qdict;
3086 fail:
3087 QDECREF(qdict);
3088 g_free(key);
3089 return NULL;
3092 static void handle_hmp_command(Monitor *mon, const char *cmdline)
3094 QDict *qdict;
3095 const mon_cmd_t *cmd;
3097 cmd = monitor_parse_command(mon, &cmdline, mon->cmd_table);
3098 if (!cmd) {
3099 return;
3102 qdict = monitor_parse_arguments(mon, &cmdline, cmd);
3103 if (!qdict) {
3104 monitor_printf(mon, "Try \"help %s\" for more information\n",
3105 cmd->name);
3106 return;
3109 cmd->cmd(mon, qdict);
3110 QDECREF(qdict);
3113 static void cmd_completion(Monitor *mon, const char *name, const char *list)
3115 const char *p, *pstart;
3116 char cmd[128];
3117 int len;
3119 p = list;
3120 for(;;) {
3121 pstart = p;
3122 p = strchr(p, '|');
3123 if (!p)
3124 p = pstart + strlen(pstart);
3125 len = p - pstart;
3126 if (len > sizeof(cmd) - 2)
3127 len = sizeof(cmd) - 2;
3128 memcpy(cmd, pstart, len);
3129 cmd[len] = '\0';
3130 if (name[0] == '\0' || !strncmp(name, cmd, strlen(name))) {
3131 readline_add_completion(mon->rs, cmd);
3133 if (*p == '\0')
3134 break;
3135 p++;
3139 static void file_completion(Monitor *mon, const char *input)
3141 DIR *ffs;
3142 struct dirent *d;
3143 char path[1024];
3144 char file[1024], file_prefix[1024];
3145 int input_path_len;
3146 const char *p;
3148 p = strrchr(input, '/');
3149 if (!p) {
3150 input_path_len = 0;
3151 pstrcpy(file_prefix, sizeof(file_prefix), input);
3152 pstrcpy(path, sizeof(path), ".");
3153 } else {
3154 input_path_len = p - input + 1;
3155 memcpy(path, input, input_path_len);
3156 if (input_path_len > sizeof(path) - 1)
3157 input_path_len = sizeof(path) - 1;
3158 path[input_path_len] = '\0';
3159 pstrcpy(file_prefix, sizeof(file_prefix), p + 1);
3162 ffs = opendir(path);
3163 if (!ffs)
3164 return;
3165 for(;;) {
3166 struct stat sb;
3167 d = readdir(ffs);
3168 if (!d)
3169 break;
3171 if (strcmp(d->d_name, ".") == 0 || strcmp(d->d_name, "..") == 0) {
3172 continue;
3175 if (strstart(d->d_name, file_prefix, NULL)) {
3176 memcpy(file, input, input_path_len);
3177 if (input_path_len < sizeof(file))
3178 pstrcpy(file + input_path_len, sizeof(file) - input_path_len,
3179 d->d_name);
3180 /* stat the file to find out if it's a directory.
3181 * In that case add a slash to speed up typing long paths
3183 if (stat(file, &sb) == 0 && S_ISDIR(sb.st_mode)) {
3184 pstrcat(file, sizeof(file), "/");
3186 readline_add_completion(mon->rs, file);
3189 closedir(ffs);
3192 static const char *next_arg_type(const char *typestr)
3194 const char *p = strchr(typestr, ':');
3195 return (p != NULL ? ++p : typestr);
3198 static void add_completion_option(ReadLineState *rs, const char *str,
3199 const char *option)
3201 if (!str || !option) {
3202 return;
3204 if (!strncmp(option, str, strlen(str))) {
3205 readline_add_completion(rs, option);
3209 void chardev_add_completion(ReadLineState *rs, int nb_args, const char *str)
3211 size_t len;
3212 ChardevBackendInfoList *list, *start;
3214 if (nb_args != 2) {
3215 return;
3217 len = strlen(str);
3218 readline_set_completion_index(rs, len);
3220 start = list = qmp_query_chardev_backends(NULL);
3221 while (list) {
3222 const char *chr_name = list->value->name;
3224 if (!strncmp(chr_name, str, len)) {
3225 readline_add_completion(rs, chr_name);
3227 list = list->next;
3229 qapi_free_ChardevBackendInfoList(start);
3232 void netdev_add_completion(ReadLineState *rs, int nb_args, const char *str)
3234 size_t len;
3235 int i;
3237 if (nb_args != 2) {
3238 return;
3240 len = strlen(str);
3241 readline_set_completion_index(rs, len);
3242 for (i = 0; NetClientDriver_lookup[i]; i++) {
3243 add_completion_option(rs, str, NetClientDriver_lookup[i]);
3247 void device_add_completion(ReadLineState *rs, int nb_args, const char *str)
3249 GSList *list, *elt;
3250 size_t len;
3252 if (nb_args != 2) {
3253 return;
3256 len = strlen(str);
3257 readline_set_completion_index(rs, len);
3258 list = elt = object_class_get_list(TYPE_DEVICE, false);
3259 while (elt) {
3260 const char *name;
3261 DeviceClass *dc = OBJECT_CLASS_CHECK(DeviceClass, elt->data,
3262 TYPE_DEVICE);
3263 name = object_class_get_name(OBJECT_CLASS(dc));
3265 if (!dc->cannot_instantiate_with_device_add_yet
3266 && !strncmp(name, str, len)) {
3267 readline_add_completion(rs, name);
3269 elt = elt->next;
3271 g_slist_free(list);
3274 void object_add_completion(ReadLineState *rs, int nb_args, const char *str)
3276 GSList *list, *elt;
3277 size_t len;
3279 if (nb_args != 2) {
3280 return;
3283 len = strlen(str);
3284 readline_set_completion_index(rs, len);
3285 list = elt = object_class_get_list(TYPE_USER_CREATABLE, false);
3286 while (elt) {
3287 const char *name;
3289 name = object_class_get_name(OBJECT_CLASS(elt->data));
3290 if (!strncmp(name, str, len) && strcmp(name, TYPE_USER_CREATABLE)) {
3291 readline_add_completion(rs, name);
3293 elt = elt->next;
3295 g_slist_free(list);
3298 static void peripheral_device_del_completion(ReadLineState *rs,
3299 const char *str, size_t len)
3301 Object *peripheral = container_get(qdev_get_machine(), "/peripheral");
3302 GSList *list, *item;
3304 list = qdev_build_hotpluggable_device_list(peripheral);
3305 if (!list) {
3306 return;
3309 for (item = list; item; item = g_slist_next(item)) {
3310 DeviceState *dev = item->data;
3312 if (dev->id && !strncmp(str, dev->id, len)) {
3313 readline_add_completion(rs, dev->id);
3317 g_slist_free(list);
3320 void chardev_remove_completion(ReadLineState *rs, int nb_args, const char *str)
3322 size_t len;
3323 ChardevInfoList *list, *start;
3325 if (nb_args != 2) {
3326 return;
3328 len = strlen(str);
3329 readline_set_completion_index(rs, len);
3331 start = list = qmp_query_chardev(NULL);
3332 while (list) {
3333 ChardevInfo *chr = list->value;
3335 if (!strncmp(chr->label, str, len)) {
3336 readline_add_completion(rs, chr->label);
3338 list = list->next;
3340 qapi_free_ChardevInfoList(start);
3343 static void ringbuf_completion(ReadLineState *rs, const char *str)
3345 size_t len;
3346 ChardevInfoList *list, *start;
3348 len = strlen(str);
3349 readline_set_completion_index(rs, len);
3351 start = list = qmp_query_chardev(NULL);
3352 while (list) {
3353 ChardevInfo *chr_info = list->value;
3355 if (!strncmp(chr_info->label, str, len)) {
3356 Chardev *chr = qemu_chr_find(chr_info->label);
3357 if (chr && CHARDEV_IS_RINGBUF(chr)) {
3358 readline_add_completion(rs, chr_info->label);
3361 list = list->next;
3363 qapi_free_ChardevInfoList(start);
3366 void ringbuf_write_completion(ReadLineState *rs, int nb_args, const char *str)
3368 if (nb_args != 2) {
3369 return;
3371 ringbuf_completion(rs, str);
3374 void device_del_completion(ReadLineState *rs, int nb_args, const char *str)
3376 size_t len;
3378 if (nb_args != 2) {
3379 return;
3382 len = strlen(str);
3383 readline_set_completion_index(rs, len);
3384 peripheral_device_del_completion(rs, str, len);
3387 void object_del_completion(ReadLineState *rs, int nb_args, const char *str)
3389 ObjectPropertyInfoList *list, *start;
3390 size_t len;
3392 if (nb_args != 2) {
3393 return;
3395 len = strlen(str);
3396 readline_set_completion_index(rs, len);
3398 start = list = qmp_qom_list("/objects", NULL);
3399 while (list) {
3400 ObjectPropertyInfo *info = list->value;
3402 if (!strncmp(info->type, "child<", 5)
3403 && !strncmp(info->name, str, len)) {
3404 readline_add_completion(rs, info->name);
3406 list = list->next;
3408 qapi_free_ObjectPropertyInfoList(start);
3411 void sendkey_completion(ReadLineState *rs, int nb_args, const char *str)
3413 int i;
3414 char *sep;
3415 size_t len;
3417 if (nb_args != 2) {
3418 return;
3420 sep = strrchr(str, '-');
3421 if (sep) {
3422 str = sep + 1;
3424 len = strlen(str);
3425 readline_set_completion_index(rs, len);
3426 for (i = 0; i < Q_KEY_CODE__MAX; i++) {
3427 if (!strncmp(str, QKeyCode_lookup[i], len)) {
3428 readline_add_completion(rs, QKeyCode_lookup[i]);
3433 void set_link_completion(ReadLineState *rs, int nb_args, const char *str)
3435 size_t len;
3437 len = strlen(str);
3438 readline_set_completion_index(rs, len);
3439 if (nb_args == 2) {
3440 NetClientState *ncs[MAX_QUEUE_NUM];
3441 int count, i;
3442 count = qemu_find_net_clients_except(NULL, ncs,
3443 NET_CLIENT_DRIVER_NONE,
3444 MAX_QUEUE_NUM);
3445 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3446 const char *name = ncs[i]->name;
3447 if (!strncmp(str, name, len)) {
3448 readline_add_completion(rs, name);
3451 } else if (nb_args == 3) {
3452 add_completion_option(rs, str, "on");
3453 add_completion_option(rs, str, "off");
3457 void netdev_del_completion(ReadLineState *rs, int nb_args, const char *str)
3459 int len, count, i;
3460 NetClientState *ncs[MAX_QUEUE_NUM];
3462 if (nb_args != 2) {
3463 return;
3466 len = strlen(str);
3467 readline_set_completion_index(rs, len);
3468 count = qemu_find_net_clients_except(NULL, ncs, NET_CLIENT_DRIVER_NIC,
3469 MAX_QUEUE_NUM);
3470 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3471 QemuOpts *opts;
3472 const char *name = ncs[i]->name;
3473 if (strncmp(str, name, len)) {
3474 continue;
3476 opts = qemu_opts_find(qemu_find_opts_err("netdev", NULL), name);
3477 if (opts) {
3478 readline_add_completion(rs, name);
3483 void info_trace_events_completion(ReadLineState *rs, int nb_args, const char *str)
3485 size_t len;
3487 len = strlen(str);
3488 readline_set_completion_index(rs, len);
3489 if (nb_args == 2) {
3490 TraceEventIter iter;
3491 TraceEvent *ev;
3492 char *pattern = g_strdup_printf("%s*", str);
3493 trace_event_iter_init(&iter, pattern);
3494 while ((ev = trace_event_iter_next(&iter)) != NULL) {
3495 readline_add_completion(rs, trace_event_get_name(ev));
3497 g_free(pattern);
3501 void trace_event_completion(ReadLineState *rs, int nb_args, const char *str)
3503 size_t len;
3505 len = strlen(str);
3506 readline_set_completion_index(rs, len);
3507 if (nb_args == 2) {
3508 TraceEventIter iter;
3509 TraceEvent *ev;
3510 char *pattern = g_strdup_printf("%s*", str);
3511 trace_event_iter_init(&iter, pattern);
3512 while ((ev = trace_event_iter_next(&iter)) != NULL) {
3513 readline_add_completion(rs, trace_event_get_name(ev));
3515 g_free(pattern);
3516 } else if (nb_args == 3) {
3517 add_completion_option(rs, str, "on");
3518 add_completion_option(rs, str, "off");
3522 void watchdog_action_completion(ReadLineState *rs, int nb_args, const char *str)
3524 int i;
3526 if (nb_args != 2) {
3527 return;
3529 readline_set_completion_index(rs, strlen(str));
3530 for (i = 0; WatchdogExpirationAction_lookup[i]; i++) {
3531 add_completion_option(rs, str, WatchdogExpirationAction_lookup[i]);
3535 void migrate_set_capability_completion(ReadLineState *rs, int nb_args,
3536 const char *str)
3538 size_t len;
3540 len = strlen(str);
3541 readline_set_completion_index(rs, len);
3542 if (nb_args == 2) {
3543 int i;
3544 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
3545 const char *name = MigrationCapability_lookup[i];
3546 if (!strncmp(str, name, len)) {
3547 readline_add_completion(rs, name);
3550 } else if (nb_args == 3) {
3551 add_completion_option(rs, str, "on");
3552 add_completion_option(rs, str, "off");
3556 void migrate_set_parameter_completion(ReadLineState *rs, int nb_args,
3557 const char *str)
3559 size_t len;
3561 len = strlen(str);
3562 readline_set_completion_index(rs, len);
3563 if (nb_args == 2) {
3564 int i;
3565 for (i = 0; i < MIGRATION_PARAMETER__MAX; i++) {
3566 const char *name = MigrationParameter_lookup[i];
3567 if (!strncmp(str, name, len)) {
3568 readline_add_completion(rs, name);
3574 void host_net_add_completion(ReadLineState *rs, int nb_args, const char *str)
3576 int i;
3577 size_t len;
3578 if (nb_args != 2) {
3579 return;
3581 len = strlen(str);
3582 readline_set_completion_index(rs, len);
3583 for (i = 0; host_net_devices[i]; i++) {
3584 if (!strncmp(host_net_devices[i], str, len)) {
3585 readline_add_completion(rs, host_net_devices[i]);
3590 void host_net_remove_completion(ReadLineState *rs, int nb_args, const char *str)
3592 NetClientState *ncs[MAX_QUEUE_NUM];
3593 int count, i, len;
3595 len = strlen(str);
3596 readline_set_completion_index(rs, len);
3597 if (nb_args == 2) {
3598 count = qemu_find_net_clients_except(NULL, ncs,
3599 NET_CLIENT_DRIVER_NONE,
3600 MAX_QUEUE_NUM);
3601 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3602 int id;
3603 char name[16];
3605 if (net_hub_id_for_client(ncs[i], &id)) {
3606 continue;
3608 snprintf(name, sizeof(name), "%d", id);
3609 if (!strncmp(str, name, len)) {
3610 readline_add_completion(rs, name);
3613 return;
3614 } else if (nb_args == 3) {
3615 count = qemu_find_net_clients_except(NULL, ncs,
3616 NET_CLIENT_DRIVER_NIC,
3617 MAX_QUEUE_NUM);
3618 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3619 int id;
3620 const char *name;
3622 if (ncs[i]->info->type == NET_CLIENT_DRIVER_HUBPORT ||
3623 net_hub_id_for_client(ncs[i], &id)) {
3624 continue;
3626 name = ncs[i]->name;
3627 if (!strncmp(str, name, len)) {
3628 readline_add_completion(rs, name);
3631 return;
3635 static void vm_completion(ReadLineState *rs, const char *str)
3637 size_t len;
3638 BlockDriverState *bs;
3639 BdrvNextIterator it;
3641 len = strlen(str);
3642 readline_set_completion_index(rs, len);
3644 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
3645 SnapshotInfoList *snapshots, *snapshot;
3646 AioContext *ctx = bdrv_get_aio_context(bs);
3647 bool ok = false;
3649 aio_context_acquire(ctx);
3650 if (bdrv_can_snapshot(bs)) {
3651 ok = bdrv_query_snapshot_info_list(bs, &snapshots, NULL) == 0;
3653 aio_context_release(ctx);
3654 if (!ok) {
3655 continue;
3658 snapshot = snapshots;
3659 while (snapshot) {
3660 char *completion = snapshot->value->name;
3661 if (!strncmp(str, completion, len)) {
3662 readline_add_completion(rs, completion);
3664 completion = snapshot->value->id;
3665 if (!strncmp(str, completion, len)) {
3666 readline_add_completion(rs, completion);
3668 snapshot = snapshot->next;
3670 qapi_free_SnapshotInfoList(snapshots);
3675 void delvm_completion(ReadLineState *rs, int nb_args, const char *str)
3677 if (nb_args == 2) {
3678 vm_completion(rs, str);
3682 void loadvm_completion(ReadLineState *rs, int nb_args, const char *str)
3684 if (nb_args == 2) {
3685 vm_completion(rs, str);
3689 static void monitor_find_completion_by_table(Monitor *mon,
3690 const mon_cmd_t *cmd_table,
3691 char **args,
3692 int nb_args)
3694 const char *cmdname;
3695 int i;
3696 const char *ptype, *str, *name;
3697 const mon_cmd_t *cmd;
3698 BlockBackend *blk = NULL;
3700 if (nb_args <= 1) {
3701 /* command completion */
3702 if (nb_args == 0)
3703 cmdname = "";
3704 else
3705 cmdname = args[0];
3706 readline_set_completion_index(mon->rs, strlen(cmdname));
3707 for (cmd = cmd_table; cmd->name != NULL; cmd++) {
3708 cmd_completion(mon, cmdname, cmd->name);
3710 } else {
3711 /* find the command */
3712 for (cmd = cmd_table; cmd->name != NULL; cmd++) {
3713 if (compare_cmd(args[0], cmd->name)) {
3714 break;
3717 if (!cmd->name) {
3718 return;
3721 if (cmd->sub_table) {
3722 /* do the job again */
3723 monitor_find_completion_by_table(mon, cmd->sub_table,
3724 &args[1], nb_args - 1);
3725 return;
3727 if (cmd->command_completion) {
3728 cmd->command_completion(mon->rs, nb_args, args[nb_args - 1]);
3729 return;
3732 ptype = next_arg_type(cmd->args_type);
3733 for(i = 0; i < nb_args - 2; i++) {
3734 if (*ptype != '\0') {
3735 ptype = next_arg_type(ptype);
3736 while (*ptype == '?')
3737 ptype = next_arg_type(ptype);
3740 str = args[nb_args - 1];
3741 while (*ptype == '-' && ptype[1] != '\0') {
3742 ptype = next_arg_type(ptype);
3744 switch(*ptype) {
3745 case 'F':
3746 /* file completion */
3747 readline_set_completion_index(mon->rs, strlen(str));
3748 file_completion(mon, str);
3749 break;
3750 case 'B':
3751 /* block device name completion */
3752 readline_set_completion_index(mon->rs, strlen(str));
3753 while ((blk = blk_next(blk)) != NULL) {
3754 name = blk_name(blk);
3755 if (str[0] == '\0' ||
3756 !strncmp(name, str, strlen(str))) {
3757 readline_add_completion(mon->rs, name);
3760 break;
3761 case 's':
3762 case 'S':
3763 if (!strcmp(cmd->name, "help|?")) {
3764 monitor_find_completion_by_table(mon, cmd_table,
3765 &args[1], nb_args - 1);
3767 break;
3768 default:
3769 break;
3774 static void monitor_find_completion(void *opaque,
3775 const char *cmdline)
3777 Monitor *mon = opaque;
3778 char *args[MAX_ARGS];
3779 int nb_args, len;
3781 /* 1. parse the cmdline */
3782 if (parse_cmdline(cmdline, &nb_args, args) < 0) {
3783 return;
3786 /* if the line ends with a space, it means we want to complete the
3787 next arg */
3788 len = strlen(cmdline);
3789 if (len > 0 && qemu_isspace(cmdline[len - 1])) {
3790 if (nb_args >= MAX_ARGS) {
3791 goto cleanup;
3793 args[nb_args++] = g_strdup("");
3796 /* 2. auto complete according to args */
3797 monitor_find_completion_by_table(mon, mon->cmd_table, args, nb_args);
3799 cleanup:
3800 free_cmdline_args(args, nb_args);
3803 static int monitor_can_read(void *opaque)
3805 Monitor *mon = opaque;
3807 return (mon->suspend_cnt == 0) ? 1 : 0;
3810 static void handle_qmp_command(JSONMessageParser *parser, GQueue *tokens)
3812 QObject *req, *rsp = NULL, *id = NULL;
3813 QDict *qdict = NULL;
3814 Monitor *mon = cur_mon;
3815 Error *err = NULL;
3817 req = json_parser_parse_err(tokens, NULL, &err);
3818 if (!req && !err) {
3819 /* json_parser_parse_err() sucks: can fail without setting @err */
3820 error_setg(&err, QERR_JSON_PARSING);
3822 if (err) {
3823 goto err_out;
3826 qdict = qobject_to_qdict(req);
3827 if (qdict) {
3828 id = qdict_get(qdict, "id");
3829 qobject_incref(id);
3830 qdict_del(qdict, "id");
3831 } /* else will fail qmp_dispatch() */
3833 rsp = qmp_dispatch(cur_mon->qmp.commands, req);
3835 if (mon->qmp.commands == &qmp_cap_negotiation_commands) {
3836 qdict = qdict_get_qdict(qobject_to_qdict(rsp), "error");
3837 if (qdict
3838 && !g_strcmp0(qdict_get_try_str(qdict, "class"),
3839 QapiErrorClass_lookup[ERROR_CLASS_COMMAND_NOT_FOUND])) {
3840 /* Provide a more useful error message */
3841 qdict_del(qdict, "desc");
3842 qdict_put(qdict, "desc",
3843 qstring_from_str("Expecting capabilities negotiation"
3844 " with 'qmp_capabilities'"));
3848 err_out:
3849 if (err) {
3850 qdict = qdict_new();
3851 qdict_put_obj(qdict, "error", qmp_build_error_object(err));
3852 error_free(err);
3853 rsp = QOBJECT(qdict);
3856 if (rsp) {
3857 if (id) {
3858 qdict_put_obj(qobject_to_qdict(rsp), "id", id);
3859 id = NULL;
3862 monitor_json_emitter(mon, rsp);
3865 qobject_decref(id);
3866 qobject_decref(rsp);
3867 qobject_decref(req);
3870 static void monitor_qmp_read(void *opaque, const uint8_t *buf, int size)
3872 Monitor *old_mon = cur_mon;
3874 cur_mon = opaque;
3876 json_message_parser_feed(&cur_mon->qmp.parser, (const char *) buf, size);
3878 cur_mon = old_mon;
3881 static void monitor_read(void *opaque, const uint8_t *buf, int size)
3883 Monitor *old_mon = cur_mon;
3884 int i;
3886 cur_mon = opaque;
3888 if (cur_mon->rs) {
3889 for (i = 0; i < size; i++)
3890 readline_handle_byte(cur_mon->rs, buf[i]);
3891 } else {
3892 if (size == 0 || buf[size - 1] != 0)
3893 monitor_printf(cur_mon, "corrupted command\n");
3894 else
3895 handle_hmp_command(cur_mon, (char *)buf);
3898 cur_mon = old_mon;
3901 static void monitor_command_cb(void *opaque, const char *cmdline,
3902 void *readline_opaque)
3904 Monitor *mon = opaque;
3906 monitor_suspend(mon);
3907 handle_hmp_command(mon, cmdline);
3908 monitor_resume(mon);
3911 int monitor_suspend(Monitor *mon)
3913 if (!mon->rs)
3914 return -ENOTTY;
3915 mon->suspend_cnt++;
3916 return 0;
3919 void monitor_resume(Monitor *mon)
3921 if (!mon->rs)
3922 return;
3923 if (--mon->suspend_cnt == 0)
3924 readline_show_prompt(mon->rs);
3927 static QObject *get_qmp_greeting(void)
3929 QObject *ver = NULL;
3931 qmp_marshal_query_version(NULL, &ver, NULL);
3933 return qobject_from_jsonf("{'QMP': {'version': %p, 'capabilities': []}}",
3934 ver);
3937 static void monitor_qmp_event(void *opaque, int event)
3939 QObject *data;
3940 Monitor *mon = opaque;
3942 switch (event) {
3943 case CHR_EVENT_OPENED:
3944 mon->qmp.commands = &qmp_cap_negotiation_commands;
3945 data = get_qmp_greeting();
3946 monitor_json_emitter(mon, data);
3947 qobject_decref(data);
3948 mon_refcount++;
3949 break;
3950 case CHR_EVENT_CLOSED:
3951 json_message_parser_destroy(&mon->qmp.parser);
3952 json_message_parser_init(&mon->qmp.parser, handle_qmp_command);
3953 mon_refcount--;
3954 monitor_fdsets_cleanup();
3955 break;
3959 static void monitor_event(void *opaque, int event)
3961 Monitor *mon = opaque;
3963 switch (event) {
3964 case CHR_EVENT_MUX_IN:
3965 qemu_mutex_lock(&mon->out_lock);
3966 mon->mux_out = 0;
3967 qemu_mutex_unlock(&mon->out_lock);
3968 if (mon->reset_seen) {
3969 readline_restart(mon->rs);
3970 monitor_resume(mon);
3971 monitor_flush(mon);
3972 } else {
3973 mon->suspend_cnt = 0;
3975 break;
3977 case CHR_EVENT_MUX_OUT:
3978 if (mon->reset_seen) {
3979 if (mon->suspend_cnt == 0) {
3980 monitor_printf(mon, "\n");
3982 monitor_flush(mon);
3983 monitor_suspend(mon);
3984 } else {
3985 mon->suspend_cnt++;
3987 qemu_mutex_lock(&mon->out_lock);
3988 mon->mux_out = 1;
3989 qemu_mutex_unlock(&mon->out_lock);
3990 break;
3992 case CHR_EVENT_OPENED:
3993 monitor_printf(mon, "QEMU %s monitor - type 'help' for more "
3994 "information\n", QEMU_VERSION);
3995 if (!mon->mux_out) {
3996 readline_restart(mon->rs);
3997 readline_show_prompt(mon->rs);
3999 mon->reset_seen = 1;
4000 mon_refcount++;
4001 break;
4003 case CHR_EVENT_CLOSED:
4004 mon_refcount--;
4005 monitor_fdsets_cleanup();
4006 break;
4010 static int
4011 compare_mon_cmd(const void *a, const void *b)
4013 return strcmp(((const mon_cmd_t *)a)->name,
4014 ((const mon_cmd_t *)b)->name);
4017 static void sortcmdlist(void)
4019 int array_num;
4020 int elem_size = sizeof(mon_cmd_t);
4022 array_num = sizeof(mon_cmds)/elem_size-1;
4023 qsort((void *)mon_cmds, array_num, elem_size, compare_mon_cmd);
4025 array_num = sizeof(info_cmds)/elem_size-1;
4026 qsort((void *)info_cmds, array_num, elem_size, compare_mon_cmd);
4029 /* These functions just adapt the readline interface in a typesafe way. We
4030 * could cast function pointers but that discards compiler checks.
4032 static void GCC_FMT_ATTR(2, 3) monitor_readline_printf(void *opaque,
4033 const char *fmt, ...)
4035 va_list ap;
4036 va_start(ap, fmt);
4037 monitor_vprintf(opaque, fmt, ap);
4038 va_end(ap);
4041 static void monitor_readline_flush(void *opaque)
4043 monitor_flush(opaque);
4047 * Print to current monitor if we have one, else to stderr.
4048 * TODO should return int, so callers can calculate width, but that
4049 * requires surgery to monitor_vprintf(). Left for another day.
4051 void error_vprintf(const char *fmt, va_list ap)
4053 if (cur_mon && !monitor_cur_is_qmp()) {
4054 monitor_vprintf(cur_mon, fmt, ap);
4055 } else {
4056 vfprintf(stderr, fmt, ap);
4060 void error_vprintf_unless_qmp(const char *fmt, va_list ap)
4062 if (cur_mon && !monitor_cur_is_qmp()) {
4063 monitor_vprintf(cur_mon, fmt, ap);
4064 } else if (!cur_mon) {
4065 vfprintf(stderr, fmt, ap);
4069 static void __attribute__((constructor)) monitor_lock_init(void)
4071 qemu_mutex_init(&monitor_lock);
4074 void monitor_init(Chardev *chr, int flags)
4076 static int is_first_init = 1;
4077 Monitor *mon;
4079 if (is_first_init) {
4080 monitor_qapi_event_init();
4081 sortcmdlist();
4082 is_first_init = 0;
4085 mon = g_malloc(sizeof(*mon));
4086 monitor_data_init(mon);
4088 qemu_chr_fe_init(&mon->chr, chr, &error_abort);
4089 mon->flags = flags;
4090 if (flags & MONITOR_USE_READLINE) {
4091 mon->rs = readline_init(monitor_readline_printf,
4092 monitor_readline_flush,
4093 mon,
4094 monitor_find_completion);
4095 monitor_read_command(mon, 0);
4098 if (monitor_is_qmp(mon)) {
4099 qemu_chr_fe_set_handlers(&mon->chr, monitor_can_read, monitor_qmp_read,
4100 monitor_qmp_event, mon, NULL, true);
4101 qemu_chr_fe_set_echo(&mon->chr, true);
4102 json_message_parser_init(&mon->qmp.parser, handle_qmp_command);
4103 } else {
4104 qemu_chr_fe_set_handlers(&mon->chr, monitor_can_read, monitor_read,
4105 monitor_event, mon, NULL, true);
4108 qemu_mutex_lock(&monitor_lock);
4109 QLIST_INSERT_HEAD(&mon_list, mon, entry);
4110 qemu_mutex_unlock(&monitor_lock);
4113 void monitor_cleanup(void)
4115 Monitor *mon, *next;
4117 qemu_mutex_lock(&monitor_lock);
4118 QLIST_FOREACH_SAFE(mon, &mon_list, entry, next) {
4119 QLIST_REMOVE(mon, entry);
4120 monitor_data_destroy(mon);
4121 g_free(mon);
4123 qemu_mutex_unlock(&monitor_lock);
4126 static void bdrv_password_cb(void *opaque, const char *password,
4127 void *readline_opaque)
4129 Monitor *mon = opaque;
4130 BlockDriverState *bs = readline_opaque;
4131 int ret = 0;
4132 Error *local_err = NULL;
4134 bdrv_add_key(bs, password, &local_err);
4135 if (local_err) {
4136 error_report_err(local_err);
4137 ret = -EPERM;
4139 if (mon->password_completion_cb)
4140 mon->password_completion_cb(mon->password_opaque, ret);
4142 monitor_read_command(mon, 1);
4145 int monitor_read_bdrv_key_start(Monitor *mon, BlockDriverState *bs,
4146 BlockCompletionFunc *completion_cb,
4147 void *opaque)
4149 int err;
4151 monitor_printf(mon, "%s (%s) is encrypted.\n", bdrv_get_device_name(bs),
4152 bdrv_get_encrypted_filename(bs));
4154 mon->password_completion_cb = completion_cb;
4155 mon->password_opaque = opaque;
4157 err = monitor_read_password(mon, bdrv_password_cb, bs);
4159 if (err && completion_cb)
4160 completion_cb(opaque, err);
4162 return err;
4165 int monitor_read_block_device_key(Monitor *mon, const char *device,
4166 BlockCompletionFunc *completion_cb,
4167 void *opaque)
4169 Error *err = NULL;
4170 BlockBackend *blk;
4172 blk = blk_by_name(device);
4173 if (!blk) {
4174 monitor_printf(mon, "Device not found %s\n", device);
4175 return -1;
4177 if (!blk_bs(blk)) {
4178 monitor_printf(mon, "Device '%s' has no medium\n", device);
4179 return -1;
4182 bdrv_add_key(blk_bs(blk), NULL, &err);
4183 if (err) {
4184 error_free(err);
4185 return monitor_read_bdrv_key_start(mon, blk_bs(blk), completion_cb, opaque);
4188 if (completion_cb) {
4189 completion_cb(opaque, 0);
4191 return 0;
4194 QemuOptsList qemu_mon_opts = {
4195 .name = "mon",
4196 .implied_opt_name = "chardev",
4197 .head = QTAILQ_HEAD_INITIALIZER(qemu_mon_opts.head),
4198 .desc = {
4200 .name = "mode",
4201 .type = QEMU_OPT_STRING,
4203 .name = "chardev",
4204 .type = QEMU_OPT_STRING,
4206 .name = "default", /* deprecated */
4207 .type = QEMU_OPT_BOOL,
4209 .name = "pretty",
4210 .type = QEMU_OPT_BOOL,
4212 { /* end of list */ }
4216 #ifndef TARGET_I386
4217 void qmp_rtc_reset_reinjection(Error **errp)
4219 error_setg(errp, QERR_FEATURE_DISABLED, "rtc-reset-reinjection");
4221 #endif
4223 #ifndef TARGET_S390X
4224 void qmp_dump_skeys(const char *filename, Error **errp)
4226 error_setg(errp, QERR_FEATURE_DISABLED, "dump-skeys");
4228 #endif
4230 #ifndef TARGET_ARM
4231 GICCapabilityList *qmp_query_gic_capabilities(Error **errp)
4233 error_setg(errp, QERR_FEATURE_DISABLED, "query-gic-capabilities");
4234 return NULL;
4236 #endif
4238 HotpluggableCPUList *qmp_query_hotpluggable_cpus(Error **errp)
4240 MachineState *ms = MACHINE(qdev_get_machine());
4241 MachineClass *mc = MACHINE_GET_CLASS(ms);
4243 if (!mc->has_hotpluggable_cpus) {
4244 error_setg(errp, QERR_FEATURE_DISABLED, "query-hotpluggable-cpus");
4245 return NULL;
4248 return machine_query_hotpluggable_cpus(ms);