monitor: remove target-specific code from monitor.c
[qemu.git] / monitor.c
blobb4578cb8eaa31043b9c08ca693e9a1ec4e2d2c3b
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 <dirent.h>
25 #include "hw/hw.h"
26 #include "monitor/qdev.h"
27 #include "hw/usb.h"
28 #include "hw/i386/pc.h"
29 #include "hw/pci/pci.h"
30 #include "sysemu/watchdog.h"
31 #include "hw/loader.h"
32 #include "exec/gdbstub.h"
33 #include "net/net.h"
34 #include "net/slirp.h"
35 #include "sysemu/char.h"
36 #include "ui/qemu-spice.h"
37 #include "sysemu/sysemu.h"
38 #include "sysemu/numa.h"
39 #include "monitor/monitor.h"
40 #include "qemu/readline.h"
41 #include "ui/console.h"
42 #include "ui/input.h"
43 #include "sysemu/blockdev.h"
44 #include "audio/audio.h"
45 #include "disas/disas.h"
46 #include "sysemu/balloon.h"
47 #include "qemu/timer.h"
48 #include "migration/migration.h"
49 #include "sysemu/kvm.h"
50 #include "qemu/acl.h"
51 #include "sysemu/tpm.h"
52 #include "qapi/qmp/qerror.h"
53 #include "qapi/qmp/qint.h"
54 #include "qapi/qmp/qfloat.h"
55 #include "qapi/qmp/qlist.h"
56 #include "qapi/qmp/qbool.h"
57 #include "qapi/qmp/qstring.h"
58 #include "qapi/qmp/qjson.h"
59 #include "qapi/qmp/json-streamer.h"
60 #include "qapi/qmp/json-parser.h"
61 #include <qom/object_interfaces.h>
62 #include "qemu/osdep.h"
63 #include "cpu.h"
64 #include "trace.h"
65 #include "trace/control.h"
66 #include "monitor/hmp-target.h"
67 #ifdef CONFIG_TRACE_SIMPLE
68 #include "trace/simple.h"
69 #endif
70 #include "exec/memory.h"
71 #include "exec/cpu_ldst.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 "sysemu/block-backend.h"
80 /* for hmp_info_irq/pic */
81 #if defined(TARGET_SPARC)
82 #include "hw/sparc/sun4m.h"
83 #endif
84 #include "hw/lm32/lm32_pic.h"
86 #if defined(TARGET_S390X)
87 #include "hw/s390x/storage-keys.h"
88 #endif
91 * Supported types:
93 * 'F' filename
94 * 'B' block device name
95 * 's' string (accept optional quote)
96 * 'S' it just appends the rest of the string (accept optional quote)
97 * 'O' option string of the form NAME=VALUE,...
98 * parsed according to QemuOptsList given by its name
99 * Example: 'device:O' uses qemu_device_opts.
100 * Restriction: only lists with empty desc are supported
101 * TODO lift the restriction
102 * 'i' 32 bit integer
103 * 'l' target long (32 or 64 bit)
104 * 'M' Non-negative target long (32 or 64 bit), in user mode the
105 * value is multiplied by 2^20 (think Mebibyte)
106 * 'o' octets (aka bytes)
107 * user mode accepts an optional E, e, P, p, T, t, G, g, M, m,
108 * K, k suffix, which multiplies the value by 2^60 for suffixes E
109 * and e, 2^50 for suffixes P and p, 2^40 for suffixes T and t,
110 * 2^30 for suffixes G and g, 2^20 for M and m, 2^10 for K and k
111 * 'T' double
112 * user mode accepts an optional ms, us, ns suffix,
113 * which divides the value by 1e3, 1e6, 1e9, respectively
114 * '/' optional gdb-like print format (like "/10x")
116 * '?' optional type (for all types, except '/')
117 * '.' other form of optional type (for 'i' and 'l')
118 * 'b' boolean
119 * user mode accepts "on" or "off"
120 * '-' optional parameter (eg. '-f')
124 typedef struct mon_cmd_t {
125 const char *name;
126 const char *args_type;
127 const char *params;
128 const char *help;
129 union {
130 void (*cmd)(Monitor *mon, const QDict *qdict);
131 void (*cmd_new)(QDict *params, QObject **ret_data, Error **errp);
132 } mhandler;
133 /* @sub_table is a list of 2nd level of commands. If it do not exist,
134 * mhandler should be used. If it exist, sub_table[?].mhandler should be
135 * used, and mhandler of 1st level plays the role of help function.
137 struct mon_cmd_t *sub_table;
138 void (*command_completion)(ReadLineState *rs, int nb_args, const char *str);
139 } mon_cmd_t;
141 /* file descriptors passed via SCM_RIGHTS */
142 typedef struct mon_fd_t mon_fd_t;
143 struct mon_fd_t {
144 char *name;
145 int fd;
146 QLIST_ENTRY(mon_fd_t) next;
149 /* file descriptor associated with a file descriptor set */
150 typedef struct MonFdsetFd MonFdsetFd;
151 struct MonFdsetFd {
152 int fd;
153 bool removed;
154 char *opaque;
155 QLIST_ENTRY(MonFdsetFd) next;
158 /* file descriptor set containing fds passed via SCM_RIGHTS */
159 typedef struct MonFdset MonFdset;
160 struct MonFdset {
161 int64_t id;
162 QLIST_HEAD(, MonFdsetFd) fds;
163 QLIST_HEAD(, MonFdsetFd) dup_fds;
164 QLIST_ENTRY(MonFdset) next;
167 typedef struct {
168 QObject *id;
169 JSONMessageParser parser;
171 * When a client connects, we're in capabilities negotiation mode.
172 * When command qmp_capabilities succeeds, we go into command
173 * mode.
175 bool in_command_mode; /* are we in command mode? */
176 } MonitorQMP;
179 * To prevent flooding clients, events can be throttled. The
180 * throttling is calculated globally, rather than per-Monitor
181 * instance.
183 typedef struct MonitorQAPIEventState {
184 QAPIEvent event; /* Event being tracked */
185 int64_t rate; /* Minimum time (in ns) between two events */
186 int64_t last; /* QEMU_CLOCK_REALTIME value at last emission */
187 QEMUTimer *timer; /* Timer for handling delayed events */
188 QObject *data; /* Event pending delayed dispatch */
189 } MonitorQAPIEventState;
191 struct Monitor {
192 CharDriverState *chr;
193 int reset_seen;
194 int flags;
195 int suspend_cnt;
196 bool skip_flush;
198 QemuMutex out_lock;
199 QString *outbuf;
200 guint out_watch;
202 /* Read under either BQL or out_lock, written with BQL+out_lock. */
203 int mux_out;
205 ReadLineState *rs;
206 MonitorQMP qmp;
207 CPUState *mon_cpu;
208 BlockCompletionFunc *password_completion_cb;
209 void *password_opaque;
210 mon_cmd_t *cmd_table;
211 QLIST_HEAD(,mon_fd_t) fds;
212 QLIST_ENTRY(Monitor) entry;
215 /* QMP checker flags */
216 #define QMP_ACCEPT_UNKNOWNS 1
218 /* Protects mon_list, monitor_event_state. */
219 static QemuMutex monitor_lock;
221 static QLIST_HEAD(mon_list, Monitor) mon_list;
222 static QLIST_HEAD(mon_fdsets, MonFdset) mon_fdsets;
223 static int mon_refcount;
225 static mon_cmd_t mon_cmds[];
226 static mon_cmd_t info_cmds[];
228 static const mon_cmd_t qmp_cmds[];
230 Monitor *cur_mon;
232 static void monitor_command_cb(void *opaque, const char *cmdline,
233 void *readline_opaque);
236 * Is @mon a QMP monitor?
238 static inline bool monitor_is_qmp(const Monitor *mon)
240 return (mon->flags & MONITOR_USE_CONTROL);
244 * Is the current monitor, if any, a QMP monitor?
246 bool monitor_cur_is_qmp(void)
248 return cur_mon && monitor_is_qmp(cur_mon);
251 void monitor_read_command(Monitor *mon, int show_prompt)
253 if (!mon->rs)
254 return;
256 readline_start(mon->rs, "(qemu) ", 0, monitor_command_cb, NULL);
257 if (show_prompt)
258 readline_show_prompt(mon->rs);
261 int monitor_read_password(Monitor *mon, ReadLineFunc *readline_func,
262 void *opaque)
264 if (mon->rs) {
265 readline_start(mon->rs, "Password: ", 1, readline_func, opaque);
266 /* prompt is printed on return from the command handler */
267 return 0;
268 } else {
269 monitor_printf(mon, "terminal does not support password prompting\n");
270 return -ENOTTY;
274 static void monitor_flush_locked(Monitor *mon);
276 static gboolean monitor_unblocked(GIOChannel *chan, GIOCondition cond,
277 void *opaque)
279 Monitor *mon = opaque;
281 qemu_mutex_lock(&mon->out_lock);
282 mon->out_watch = 0;
283 monitor_flush_locked(mon);
284 qemu_mutex_unlock(&mon->out_lock);
285 return FALSE;
288 /* Called with mon->out_lock held. */
289 static void monitor_flush_locked(Monitor *mon)
291 int rc;
292 size_t len;
293 const char *buf;
295 if (mon->skip_flush) {
296 return;
299 buf = qstring_get_str(mon->outbuf);
300 len = qstring_get_length(mon->outbuf);
302 if (len && !mon->mux_out) {
303 rc = qemu_chr_fe_write(mon->chr, (const uint8_t *) buf, len);
304 if ((rc < 0 && errno != EAGAIN) || (rc == len)) {
305 /* all flushed or error */
306 QDECREF(mon->outbuf);
307 mon->outbuf = qstring_new();
308 return;
310 if (rc > 0) {
311 /* partinal write */
312 QString *tmp = qstring_from_str(buf + rc);
313 QDECREF(mon->outbuf);
314 mon->outbuf = tmp;
316 if (mon->out_watch == 0) {
317 mon->out_watch = 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 static int GCC_FMT_ATTR(2, 3) monitor_fprintf(FILE *stream,
376 const char *fmt, ...)
378 va_list ap;
379 va_start(ap, fmt);
380 monitor_vprintf((Monitor *)stream, fmt, ap);
381 va_end(ap);
382 return 0;
385 static void monitor_json_emitter(Monitor *mon, const QObject *data)
387 QString *json;
389 json = mon->flags & MONITOR_USE_PRETTY ? qobject_to_json_pretty(data) :
390 qobject_to_json(data);
391 assert(json != NULL);
393 qstring_append_chr(json, '\n');
394 monitor_puts(mon, qstring_get_str(json));
396 QDECREF(json);
399 static QDict *build_qmp_error_dict(Error *err)
401 QObject *obj;
403 obj = qobject_from_jsonf("{ 'error': { 'class': %s, 'desc': %s } }",
404 ErrorClass_lookup[error_get_class(err)],
405 error_get_pretty(err));
407 return qobject_to_qdict(obj);
410 static void monitor_protocol_emitter(Monitor *mon, QObject *data,
411 Error *err)
413 QDict *qmp;
415 trace_monitor_protocol_emitter(mon);
417 if (!err) {
418 /* success response */
419 qmp = qdict_new();
420 if (data) {
421 qobject_incref(data);
422 qdict_put_obj(qmp, "return", data);
423 } else {
424 /* return an empty QDict by default */
425 qdict_put(qmp, "return", qdict_new());
427 } else {
428 /* error response */
429 qmp = build_qmp_error_dict(err);
432 if (mon->qmp.id) {
433 qdict_put_obj(qmp, "id", mon->qmp.id);
434 mon->qmp.id = NULL;
437 monitor_json_emitter(mon, QOBJECT(qmp));
438 QDECREF(qmp);
442 static MonitorQAPIEventState monitor_qapi_event_state[QAPI_EVENT_MAX];
445 * Emits the event to every monitor instance, @event is only used for trace
446 * Called with monitor_lock held.
448 static void monitor_qapi_event_emit(QAPIEvent event, QObject *data)
450 Monitor *mon;
452 trace_monitor_protocol_event_emit(event, data);
453 QLIST_FOREACH(mon, &mon_list, entry) {
454 if (monitor_is_qmp(mon) && mon->qmp.in_command_mode) {
455 monitor_json_emitter(mon, data);
461 * Queue a new event for emission to Monitor instances,
462 * applying any rate limiting if required.
464 static void
465 monitor_qapi_event_queue(QAPIEvent event, QDict *data, Error **errp)
467 MonitorQAPIEventState *evstate;
468 assert(event < QAPI_EVENT_MAX);
469 int64_t now = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
471 evstate = &(monitor_qapi_event_state[event]);
472 trace_monitor_protocol_event_queue(event,
473 data,
474 evstate->rate,
475 evstate->last,
476 now);
478 /* Rate limit of 0 indicates no throttling */
479 qemu_mutex_lock(&monitor_lock);
480 if (!evstate->rate) {
481 monitor_qapi_event_emit(event, QOBJECT(data));
482 evstate->last = now;
483 } else {
484 int64_t delta = now - evstate->last;
485 if (evstate->data ||
486 delta < evstate->rate) {
487 /* If there's an existing event pending, replace
488 * it with the new event, otherwise schedule a
489 * timer for delayed emission
491 if (evstate->data) {
492 qobject_decref(evstate->data);
493 } else {
494 int64_t then = evstate->last + evstate->rate;
495 timer_mod_ns(evstate->timer, then);
497 evstate->data = QOBJECT(data);
498 qobject_incref(evstate->data);
499 } else {
500 monitor_qapi_event_emit(event, QOBJECT(data));
501 evstate->last = now;
504 qemu_mutex_unlock(&monitor_lock);
508 * The callback invoked by QemuTimer when a delayed
509 * event is ready to be emitted
511 static void monitor_qapi_event_handler(void *opaque)
513 MonitorQAPIEventState *evstate = opaque;
514 int64_t now = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
516 trace_monitor_protocol_event_handler(evstate->event,
517 evstate->data,
518 evstate->last,
519 now);
520 qemu_mutex_lock(&monitor_lock);
521 if (evstate->data) {
522 monitor_qapi_event_emit(evstate->event, evstate->data);
523 qobject_decref(evstate->data);
524 evstate->data = NULL;
526 evstate->last = now;
527 qemu_mutex_unlock(&monitor_lock);
531 * @event: the event ID to be limited
532 * @rate: the rate limit in milliseconds
534 * Sets a rate limit on a particular event, so no
535 * more than 1 event will be emitted within @rate
536 * milliseconds
538 static void
539 monitor_qapi_event_throttle(QAPIEvent event, int64_t rate)
541 MonitorQAPIEventState *evstate;
542 assert(event < QAPI_EVENT_MAX);
544 evstate = &(monitor_qapi_event_state[event]);
546 trace_monitor_protocol_event_throttle(event, rate);
547 evstate->event = event;
548 assert(rate * SCALE_MS <= INT64_MAX);
549 evstate->rate = rate * SCALE_MS;
550 evstate->last = 0;
551 evstate->data = NULL;
552 evstate->timer = timer_new(QEMU_CLOCK_REALTIME,
553 SCALE_MS,
554 monitor_qapi_event_handler,
555 evstate);
558 static void monitor_qapi_event_init(void)
560 /* Limit guest-triggerable events to 1 per second */
561 monitor_qapi_event_throttle(QAPI_EVENT_RTC_CHANGE, 1000);
562 monitor_qapi_event_throttle(QAPI_EVENT_WATCHDOG, 1000);
563 monitor_qapi_event_throttle(QAPI_EVENT_BALLOON_CHANGE, 1000);
564 monitor_qapi_event_throttle(QAPI_EVENT_QUORUM_REPORT_BAD, 1000);
565 monitor_qapi_event_throttle(QAPI_EVENT_QUORUM_FAILURE, 1000);
566 monitor_qapi_event_throttle(QAPI_EVENT_VSERPORT_CHANGE, 1000);
568 qmp_event_set_func_emit(monitor_qapi_event_queue);
571 static void qmp_capabilities(QDict *params, QObject **ret_data, Error **errp)
573 cur_mon->qmp.in_command_mode = true;
576 static void handle_hmp_command(Monitor *mon, const char *cmdline);
578 static void monitor_data_init(Monitor *mon)
580 memset(mon, 0, sizeof(Monitor));
581 qemu_mutex_init(&mon->out_lock);
582 mon->outbuf = qstring_new();
583 /* Use *mon_cmds by default. */
584 mon->cmd_table = mon_cmds;
587 static void monitor_data_destroy(Monitor *mon)
589 QDECREF(mon->outbuf);
590 qemu_mutex_destroy(&mon->out_lock);
593 char *qmp_human_monitor_command(const char *command_line, bool has_cpu_index,
594 int64_t cpu_index, Error **errp)
596 char *output = NULL;
597 Monitor *old_mon, hmp;
599 monitor_data_init(&hmp);
600 hmp.skip_flush = true;
602 old_mon = cur_mon;
603 cur_mon = &hmp;
605 if (has_cpu_index) {
606 int ret = monitor_set_cpu(cpu_index);
607 if (ret < 0) {
608 cur_mon = old_mon;
609 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cpu-index",
610 "a CPU number");
611 goto out;
615 handle_hmp_command(&hmp, command_line);
616 cur_mon = old_mon;
618 qemu_mutex_lock(&hmp.out_lock);
619 if (qstring_get_length(hmp.outbuf) > 0) {
620 output = g_strdup(qstring_get_str(hmp.outbuf));
621 } else {
622 output = g_strdup("");
624 qemu_mutex_unlock(&hmp.out_lock);
626 out:
627 monitor_data_destroy(&hmp);
628 return output;
631 static int compare_cmd(const char *name, const char *list)
633 const char *p, *pstart;
634 int len;
635 len = strlen(name);
636 p = list;
637 for(;;) {
638 pstart = p;
639 p = strchr(p, '|');
640 if (!p)
641 p = pstart + strlen(pstart);
642 if ((p - pstart) == len && !memcmp(pstart, name, len))
643 return 1;
644 if (*p == '\0')
645 break;
646 p++;
648 return 0;
651 static int get_str(char *buf, int buf_size, const char **pp)
653 const char *p;
654 char *q;
655 int c;
657 q = buf;
658 p = *pp;
659 while (qemu_isspace(*p)) {
660 p++;
662 if (*p == '\0') {
663 fail:
664 *q = '\0';
665 *pp = p;
666 return -1;
668 if (*p == '\"') {
669 p++;
670 while (*p != '\0' && *p != '\"') {
671 if (*p == '\\') {
672 p++;
673 c = *p++;
674 switch (c) {
675 case 'n':
676 c = '\n';
677 break;
678 case 'r':
679 c = '\r';
680 break;
681 case '\\':
682 case '\'':
683 case '\"':
684 break;
685 default:
686 printf("unsupported escape code: '\\%c'\n", c);
687 goto fail;
689 if ((q - buf) < buf_size - 1) {
690 *q++ = c;
692 } else {
693 if ((q - buf) < buf_size - 1) {
694 *q++ = *p;
696 p++;
699 if (*p != '\"') {
700 printf("unterminated string\n");
701 goto fail;
703 p++;
704 } else {
705 while (*p != '\0' && !qemu_isspace(*p)) {
706 if ((q - buf) < buf_size - 1) {
707 *q++ = *p;
709 p++;
712 *q = '\0';
713 *pp = p;
714 return 0;
717 #define MAX_ARGS 16
719 static void free_cmdline_args(char **args, int nb_args)
721 int i;
723 assert(nb_args <= MAX_ARGS);
725 for (i = 0; i < nb_args; i++) {
726 g_free(args[i]);
732 * Parse the command line to get valid args.
733 * @cmdline: command line to be parsed.
734 * @pnb_args: location to store the number of args, must NOT be NULL.
735 * @args: location to store the args, which should be freed by caller, must
736 * NOT be NULL.
738 * Returns 0 on success, negative on failure.
740 * NOTE: this parser is an approximate form of the real command parser. Number
741 * of args have a limit of MAX_ARGS. If cmdline contains more, it will
742 * return with failure.
744 static int parse_cmdline(const char *cmdline,
745 int *pnb_args, char **args)
747 const char *p;
748 int nb_args, ret;
749 char buf[1024];
751 p = cmdline;
752 nb_args = 0;
753 for (;;) {
754 while (qemu_isspace(*p)) {
755 p++;
757 if (*p == '\0') {
758 break;
760 if (nb_args >= MAX_ARGS) {
761 goto fail;
763 ret = get_str(buf, sizeof(buf), &p);
764 if (ret < 0) {
765 goto fail;
767 args[nb_args] = g_strdup(buf);
768 nb_args++;
770 *pnb_args = nb_args;
771 return 0;
773 fail:
774 free_cmdline_args(args, nb_args);
775 return -1;
778 static void help_cmd_dump_one(Monitor *mon,
779 const mon_cmd_t *cmd,
780 char **prefix_args,
781 int prefix_args_nb)
783 int i;
785 for (i = 0; i < prefix_args_nb; i++) {
786 monitor_printf(mon, "%s ", prefix_args[i]);
788 monitor_printf(mon, "%s %s -- %s\n", cmd->name, cmd->params, cmd->help);
791 /* @args[@arg_index] is the valid command need to find in @cmds */
792 static void help_cmd_dump(Monitor *mon, const mon_cmd_t *cmds,
793 char **args, int nb_args, int arg_index)
795 const mon_cmd_t *cmd;
797 /* No valid arg need to compare with, dump all in *cmds */
798 if (arg_index >= nb_args) {
799 for (cmd = cmds; cmd->name != NULL; cmd++) {
800 help_cmd_dump_one(mon, cmd, args, arg_index);
802 return;
805 /* Find one entry to dump */
806 for (cmd = cmds; cmd->name != NULL; cmd++) {
807 if (compare_cmd(args[arg_index], cmd->name)) {
808 if (cmd->sub_table) {
809 /* continue with next arg */
810 help_cmd_dump(mon, cmd->sub_table,
811 args, nb_args, arg_index + 1);
812 } else {
813 help_cmd_dump_one(mon, cmd, args, arg_index);
815 break;
820 static void help_cmd(Monitor *mon, const char *name)
822 char *args[MAX_ARGS];
823 int nb_args = 0;
825 /* 1. parse user input */
826 if (name) {
827 /* special case for log, directly dump and return */
828 if (!strcmp(name, "log")) {
829 const QEMULogItem *item;
830 monitor_printf(mon, "Log items (comma separated):\n");
831 monitor_printf(mon, "%-10s %s\n", "none", "remove all logs");
832 for (item = qemu_log_items; item->mask != 0; item++) {
833 monitor_printf(mon, "%-10s %s\n", item->name, item->help);
835 return;
838 if (parse_cmdline(name, &nb_args, args) < 0) {
839 return;
843 /* 2. dump the contents according to parsed args */
844 help_cmd_dump(mon, mon->cmd_table, args, nb_args, 0);
846 free_cmdline_args(args, nb_args);
849 static void do_help_cmd(Monitor *mon, const QDict *qdict)
851 help_cmd(mon, qdict_get_try_str(qdict, "name"));
854 static void hmp_trace_event(Monitor *mon, const QDict *qdict)
856 const char *tp_name = qdict_get_str(qdict, "name");
857 bool new_state = qdict_get_bool(qdict, "option");
858 Error *local_err = NULL;
860 qmp_trace_event_set_state(tp_name, new_state, true, true, &local_err);
861 if (local_err) {
862 error_report_err(local_err);
866 #ifdef CONFIG_TRACE_SIMPLE
867 static void hmp_trace_file(Monitor *mon, const QDict *qdict)
869 const char *op = qdict_get_try_str(qdict, "op");
870 const char *arg = qdict_get_try_str(qdict, "arg");
872 if (!op) {
873 st_print_trace_file_status((FILE *)mon, &monitor_fprintf);
874 } else if (!strcmp(op, "on")) {
875 st_set_trace_file_enabled(true);
876 } else if (!strcmp(op, "off")) {
877 st_set_trace_file_enabled(false);
878 } else if (!strcmp(op, "flush")) {
879 st_flush_trace_buffer();
880 } else if (!strcmp(op, "set")) {
881 if (arg) {
882 st_set_trace_file(arg);
884 } else {
885 monitor_printf(mon, "unexpected argument \"%s\"\n", op);
886 help_cmd(mon, "trace-file");
889 #endif
891 static void hmp_info_help(Monitor *mon, const QDict *qdict)
893 help_cmd(mon, "info");
896 CommandInfoList *qmp_query_commands(Error **errp)
898 CommandInfoList *info, *cmd_list = NULL;
899 const mon_cmd_t *cmd;
901 for (cmd = qmp_cmds; cmd->name != NULL; cmd++) {
902 info = g_malloc0(sizeof(*info));
903 info->value = g_malloc0(sizeof(*info->value));
904 info->value->name = g_strdup(cmd->name);
906 info->next = cmd_list;
907 cmd_list = info;
910 return cmd_list;
913 EventInfoList *qmp_query_events(Error **errp)
915 EventInfoList *info, *ev_list = NULL;
916 QAPIEvent e;
918 for (e = 0 ; e < QAPI_EVENT_MAX ; e++) {
919 const char *event_name = QAPIEvent_lookup[e];
920 assert(event_name != NULL);
921 info = g_malloc0(sizeof(*info));
922 info->value = g_malloc0(sizeof(*info->value));
923 info->value->name = g_strdup(event_name);
925 info->next = ev_list;
926 ev_list = info;
929 return ev_list;
932 /* set the current CPU defined by the user */
933 int monitor_set_cpu(int cpu_index)
935 CPUState *cpu;
937 cpu = qemu_get_cpu(cpu_index);
938 if (cpu == NULL) {
939 return -1;
941 cur_mon->mon_cpu = cpu;
942 return 0;
945 static CPUState *mon_get_cpu(void)
947 if (!cur_mon->mon_cpu) {
948 monitor_set_cpu(0);
950 cpu_synchronize_state(cur_mon->mon_cpu);
951 return cur_mon->mon_cpu;
954 CPUArchState *mon_get_cpu_env(void)
956 return mon_get_cpu()->env_ptr;
959 int monitor_get_cpu_index(void)
961 return mon_get_cpu()->cpu_index;
964 static void hmp_info_registers(Monitor *mon, const QDict *qdict)
966 cpu_dump_state(mon_get_cpu(), (FILE *)mon, monitor_fprintf, CPU_DUMP_FPU);
969 static void hmp_info_jit(Monitor *mon, const QDict *qdict)
971 dump_exec_info((FILE *)mon, monitor_fprintf);
972 dump_drift_info((FILE *)mon, monitor_fprintf);
975 static void hmp_info_opcount(Monitor *mon, const QDict *qdict)
977 dump_opcount_info((FILE *)mon, monitor_fprintf);
980 static void hmp_info_history(Monitor *mon, const QDict *qdict)
982 int i;
983 const char *str;
985 if (!mon->rs)
986 return;
987 i = 0;
988 for(;;) {
989 str = readline_get_history(mon->rs, i);
990 if (!str)
991 break;
992 monitor_printf(mon, "%d: '%s'\n", i, str);
993 i++;
997 static void hmp_info_cpustats(Monitor *mon, const QDict *qdict)
999 cpu_dump_statistics(mon_get_cpu(), (FILE *)mon, &monitor_fprintf, 0);
1002 static void hmp_info_trace_events(Monitor *mon, const QDict *qdict)
1004 TraceEventInfoList *events = qmp_trace_event_get_state("*", NULL);
1005 TraceEventInfoList *elem;
1007 for (elem = events; elem != NULL; elem = elem->next) {
1008 monitor_printf(mon, "%s : state %u\n",
1009 elem->value->name,
1010 elem->value->state == TRACE_EVENT_STATE_ENABLED ? 1 : 0);
1012 qapi_free_TraceEventInfoList(events);
1015 void qmp_client_migrate_info(const char *protocol, const char *hostname,
1016 bool has_port, int64_t port,
1017 bool has_tls_port, int64_t tls_port,
1018 bool has_cert_subject, const char *cert_subject,
1019 Error **errp)
1021 if (strcmp(protocol, "spice") == 0) {
1022 if (!qemu_using_spice(errp)) {
1023 return;
1026 if (!has_port && !has_tls_port) {
1027 error_setg(errp, QERR_MISSING_PARAMETER, "port/tls-port");
1028 return;
1031 if (qemu_spice_migrate_info(hostname,
1032 has_port ? port : -1,
1033 has_tls_port ? tls_port : -1,
1034 cert_subject)) {
1035 error_setg(errp, QERR_UNDEFINED_ERROR);
1036 return;
1038 return;
1041 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "protocol", "spice");
1044 static void hmp_logfile(Monitor *mon, const QDict *qdict)
1046 qemu_set_log_filename(qdict_get_str(qdict, "filename"));
1049 static void hmp_log(Monitor *mon, const QDict *qdict)
1051 int mask;
1052 const char *items = qdict_get_str(qdict, "items");
1054 if (!strcmp(items, "none")) {
1055 mask = 0;
1056 } else {
1057 mask = qemu_str_to_log_mask(items);
1058 if (!mask) {
1059 help_cmd(mon, "log");
1060 return;
1063 qemu_set_log(mask);
1066 static void hmp_singlestep(Monitor *mon, const QDict *qdict)
1068 const char *option = qdict_get_try_str(qdict, "option");
1069 if (!option || !strcmp(option, "on")) {
1070 singlestep = 1;
1071 } else if (!strcmp(option, "off")) {
1072 singlestep = 0;
1073 } else {
1074 monitor_printf(mon, "unexpected option %s\n", option);
1078 static void hmp_gdbserver(Monitor *mon, const QDict *qdict)
1080 const char *device = qdict_get_try_str(qdict, "device");
1081 if (!device)
1082 device = "tcp::" DEFAULT_GDBSTUB_PORT;
1083 if (gdbserver_start(device) < 0) {
1084 monitor_printf(mon, "Could not open gdbserver on device '%s'\n",
1085 device);
1086 } else if (strcmp(device, "none") == 0) {
1087 monitor_printf(mon, "Disabled gdbserver\n");
1088 } else {
1089 monitor_printf(mon, "Waiting for gdb connection on device '%s'\n",
1090 device);
1094 static void hmp_watchdog_action(Monitor *mon, const QDict *qdict)
1096 const char *action = qdict_get_str(qdict, "action");
1097 if (select_watchdog_action(action) == -1) {
1098 monitor_printf(mon, "Unknown watchdog action '%s'\n", action);
1102 static void monitor_printc(Monitor *mon, int c)
1104 monitor_printf(mon, "'");
1105 switch(c) {
1106 case '\'':
1107 monitor_printf(mon, "\\'");
1108 break;
1109 case '\\':
1110 monitor_printf(mon, "\\\\");
1111 break;
1112 case '\n':
1113 monitor_printf(mon, "\\n");
1114 break;
1115 case '\r':
1116 monitor_printf(mon, "\\r");
1117 break;
1118 default:
1119 if (c >= 32 && c <= 126) {
1120 monitor_printf(mon, "%c", c);
1121 } else {
1122 monitor_printf(mon, "\\x%02x", c);
1124 break;
1126 monitor_printf(mon, "'");
1129 static void memory_dump(Monitor *mon, int count, int format, int wsize,
1130 hwaddr addr, int is_physical)
1132 int l, line_size, i, max_digits, len;
1133 uint8_t buf[16];
1134 uint64_t v;
1136 if (format == 'i') {
1137 int flags = 0;
1138 #ifdef TARGET_I386
1139 CPUArchState *env = mon_get_cpu_env();
1140 if (wsize == 2) {
1141 flags = 1;
1142 } else if (wsize == 4) {
1143 flags = 0;
1144 } else {
1145 /* as default we use the current CS size */
1146 flags = 0;
1147 if (env) {
1148 #ifdef TARGET_X86_64
1149 if ((env->efer & MSR_EFER_LMA) &&
1150 (env->segs[R_CS].flags & DESC_L_MASK))
1151 flags = 2;
1152 else
1153 #endif
1154 if (!(env->segs[R_CS].flags & DESC_B_MASK))
1155 flags = 1;
1158 #endif
1159 #ifdef TARGET_PPC
1160 CPUArchState *env = mon_get_cpu_env();
1161 flags = msr_le << 16;
1162 flags |= env->bfd_mach;
1163 #endif
1164 monitor_disas(mon, mon_get_cpu(), addr, count, is_physical, flags);
1165 return;
1168 len = wsize * count;
1169 if (wsize == 1)
1170 line_size = 8;
1171 else
1172 line_size = 16;
1173 max_digits = 0;
1175 switch(format) {
1176 case 'o':
1177 max_digits = (wsize * 8 + 2) / 3;
1178 break;
1179 default:
1180 case 'x':
1181 max_digits = (wsize * 8) / 4;
1182 break;
1183 case 'u':
1184 case 'd':
1185 max_digits = (wsize * 8 * 10 + 32) / 33;
1186 break;
1187 case 'c':
1188 wsize = 1;
1189 break;
1192 while (len > 0) {
1193 if (is_physical)
1194 monitor_printf(mon, TARGET_FMT_plx ":", addr);
1195 else
1196 monitor_printf(mon, TARGET_FMT_lx ":", (target_ulong)addr);
1197 l = len;
1198 if (l > line_size)
1199 l = line_size;
1200 if (is_physical) {
1201 cpu_physical_memory_read(addr, buf, l);
1202 } else {
1203 if (cpu_memory_rw_debug(mon_get_cpu(), addr, buf, l, 0) < 0) {
1204 monitor_printf(mon, " Cannot access memory\n");
1205 break;
1208 i = 0;
1209 while (i < l) {
1210 switch(wsize) {
1211 default:
1212 case 1:
1213 v = ldub_p(buf + i);
1214 break;
1215 case 2:
1216 v = lduw_p(buf + i);
1217 break;
1218 case 4:
1219 v = (uint32_t)ldl_p(buf + i);
1220 break;
1221 case 8:
1222 v = ldq_p(buf + i);
1223 break;
1225 monitor_printf(mon, " ");
1226 switch(format) {
1227 case 'o':
1228 monitor_printf(mon, "%#*" PRIo64, max_digits, v);
1229 break;
1230 case 'x':
1231 monitor_printf(mon, "0x%0*" PRIx64, max_digits, v);
1232 break;
1233 case 'u':
1234 monitor_printf(mon, "%*" PRIu64, max_digits, v);
1235 break;
1236 case 'd':
1237 monitor_printf(mon, "%*" PRId64, max_digits, v);
1238 break;
1239 case 'c':
1240 monitor_printc(mon, v);
1241 break;
1243 i += wsize;
1245 monitor_printf(mon, "\n");
1246 addr += l;
1247 len -= l;
1251 static void hmp_memory_dump(Monitor *mon, const QDict *qdict)
1253 int count = qdict_get_int(qdict, "count");
1254 int format = qdict_get_int(qdict, "format");
1255 int size = qdict_get_int(qdict, "size");
1256 target_long addr = qdict_get_int(qdict, "addr");
1258 memory_dump(mon, count, format, size, addr, 0);
1261 static void hmp_physical_memory_dump(Monitor *mon, const QDict *qdict)
1263 int count = qdict_get_int(qdict, "count");
1264 int format = qdict_get_int(qdict, "format");
1265 int size = qdict_get_int(qdict, "size");
1266 hwaddr addr = qdict_get_int(qdict, "addr");
1268 memory_dump(mon, count, format, size, addr, 1);
1271 static void do_print(Monitor *mon, const QDict *qdict)
1273 int format = qdict_get_int(qdict, "format");
1274 hwaddr val = qdict_get_int(qdict, "val");
1276 switch(format) {
1277 case 'o':
1278 monitor_printf(mon, "%#" HWADDR_PRIo, val);
1279 break;
1280 case 'x':
1281 monitor_printf(mon, "%#" HWADDR_PRIx, val);
1282 break;
1283 case 'u':
1284 monitor_printf(mon, "%" HWADDR_PRIu, val);
1285 break;
1286 default:
1287 case 'd':
1288 monitor_printf(mon, "%" HWADDR_PRId, val);
1289 break;
1290 case 'c':
1291 monitor_printc(mon, val);
1292 break;
1294 monitor_printf(mon, "\n");
1297 static void hmp_sum(Monitor *mon, const QDict *qdict)
1299 uint32_t addr;
1300 uint16_t sum;
1301 uint32_t start = qdict_get_int(qdict, "start");
1302 uint32_t size = qdict_get_int(qdict, "size");
1304 sum = 0;
1305 for(addr = start; addr < (start + size); addr++) {
1306 uint8_t val = address_space_ldub(&address_space_memory, addr,
1307 MEMTXATTRS_UNSPECIFIED, NULL);
1308 /* BSD sum algorithm ('sum' Unix command) */
1309 sum = (sum >> 1) | (sum << 15);
1310 sum += val;
1312 monitor_printf(mon, "%05d\n", sum);
1315 static int mouse_button_state;
1317 static void hmp_mouse_move(Monitor *mon, const QDict *qdict)
1319 int dx, dy, dz, button;
1320 const char *dx_str = qdict_get_str(qdict, "dx_str");
1321 const char *dy_str = qdict_get_str(qdict, "dy_str");
1322 const char *dz_str = qdict_get_try_str(qdict, "dz_str");
1324 dx = strtol(dx_str, NULL, 0);
1325 dy = strtol(dy_str, NULL, 0);
1326 qemu_input_queue_rel(NULL, INPUT_AXIS_X, dx);
1327 qemu_input_queue_rel(NULL, INPUT_AXIS_Y, dy);
1329 if (dz_str) {
1330 dz = strtol(dz_str, NULL, 0);
1331 if (dz != 0) {
1332 button = (dz > 0) ? INPUT_BUTTON_WHEEL_UP : INPUT_BUTTON_WHEEL_DOWN;
1333 qemu_input_queue_btn(NULL, button, true);
1334 qemu_input_event_sync();
1335 qemu_input_queue_btn(NULL, button, false);
1338 qemu_input_event_sync();
1341 static void hmp_mouse_button(Monitor *mon, const QDict *qdict)
1343 static uint32_t bmap[INPUT_BUTTON_MAX] = {
1344 [INPUT_BUTTON_LEFT] = MOUSE_EVENT_LBUTTON,
1345 [INPUT_BUTTON_MIDDLE] = MOUSE_EVENT_MBUTTON,
1346 [INPUT_BUTTON_RIGHT] = MOUSE_EVENT_RBUTTON,
1348 int button_state = qdict_get_int(qdict, "button_state");
1350 if (mouse_button_state == button_state) {
1351 return;
1353 qemu_input_update_buttons(NULL, bmap, mouse_button_state, button_state);
1354 qemu_input_event_sync();
1355 mouse_button_state = button_state;
1358 static void hmp_ioport_read(Monitor *mon, const QDict *qdict)
1360 int size = qdict_get_int(qdict, "size");
1361 int addr = qdict_get_int(qdict, "addr");
1362 int has_index = qdict_haskey(qdict, "index");
1363 uint32_t val;
1364 int suffix;
1366 if (has_index) {
1367 int index = qdict_get_int(qdict, "index");
1368 cpu_outb(addr & IOPORTS_MASK, index & 0xff);
1369 addr++;
1371 addr &= 0xffff;
1373 switch(size) {
1374 default:
1375 case 1:
1376 val = cpu_inb(addr);
1377 suffix = 'b';
1378 break;
1379 case 2:
1380 val = cpu_inw(addr);
1381 suffix = 'w';
1382 break;
1383 case 4:
1384 val = cpu_inl(addr);
1385 suffix = 'l';
1386 break;
1388 monitor_printf(mon, "port%c[0x%04x] = %#0*x\n",
1389 suffix, addr, size * 2, val);
1392 static void hmp_ioport_write(Monitor *mon, const QDict *qdict)
1394 int size = qdict_get_int(qdict, "size");
1395 int addr = qdict_get_int(qdict, "addr");
1396 int val = qdict_get_int(qdict, "val");
1398 addr &= IOPORTS_MASK;
1400 switch (size) {
1401 default:
1402 case 1:
1403 cpu_outb(addr, val);
1404 break;
1405 case 2:
1406 cpu_outw(addr, val);
1407 break;
1408 case 4:
1409 cpu_outl(addr, val);
1410 break;
1414 static void hmp_boot_set(Monitor *mon, const QDict *qdict)
1416 Error *local_err = NULL;
1417 const char *bootdevice = qdict_get_str(qdict, "bootdevice");
1419 qemu_boot_set(bootdevice, &local_err);
1420 if (local_err) {
1421 monitor_printf(mon, "%s\n", error_get_pretty(local_err));
1422 error_free(local_err);
1423 } else {
1424 monitor_printf(mon, "boot device list now set to %s\n", bootdevice);
1428 static void hmp_info_mtree(Monitor *mon, const QDict *qdict)
1430 mtree_info((fprintf_function)monitor_printf, mon);
1433 static void hmp_info_numa(Monitor *mon, const QDict *qdict)
1435 int i;
1436 CPUState *cpu;
1437 uint64_t *node_mem;
1439 node_mem = g_new0(uint64_t, nb_numa_nodes);
1440 query_numa_node_mem(node_mem);
1441 monitor_printf(mon, "%d nodes\n", nb_numa_nodes);
1442 for (i = 0; i < nb_numa_nodes; i++) {
1443 monitor_printf(mon, "node %d cpus:", i);
1444 CPU_FOREACH(cpu) {
1445 if (cpu->numa_node == i) {
1446 monitor_printf(mon, " %d", cpu->cpu_index);
1449 monitor_printf(mon, "\n");
1450 monitor_printf(mon, "node %d size: %" PRId64 " MB\n", i,
1451 node_mem[i] >> 20);
1453 g_free(node_mem);
1456 #ifdef CONFIG_PROFILER
1458 int64_t tcg_time;
1459 int64_t dev_time;
1461 static void hmp_info_profile(Monitor *mon, const QDict *qdict)
1463 monitor_printf(mon, "async time %" PRId64 " (%0.3f)\n",
1464 dev_time, dev_time / (double)get_ticks_per_sec());
1465 monitor_printf(mon, "qemu time %" PRId64 " (%0.3f)\n",
1466 tcg_time, tcg_time / (double)get_ticks_per_sec());
1467 tcg_time = 0;
1468 dev_time = 0;
1470 #else
1471 static void hmp_info_profile(Monitor *mon, const QDict *qdict)
1473 monitor_printf(mon, "Internal profiler not compiled\n");
1475 #endif
1477 /* Capture support */
1478 static QLIST_HEAD (capture_list_head, CaptureState) capture_head;
1480 static void hmp_info_capture(Monitor *mon, const QDict *qdict)
1482 int i;
1483 CaptureState *s;
1485 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
1486 monitor_printf(mon, "[%d]: ", i);
1487 s->ops.info (s->opaque);
1491 static void hmp_stopcapture(Monitor *mon, const QDict *qdict)
1493 int i;
1494 int n = qdict_get_int(qdict, "n");
1495 CaptureState *s;
1497 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
1498 if (i == n) {
1499 s->ops.destroy (s->opaque);
1500 QLIST_REMOVE (s, entries);
1501 g_free (s);
1502 return;
1507 static void hmp_wavcapture(Monitor *mon, const QDict *qdict)
1509 const char *path = qdict_get_str(qdict, "path");
1510 int has_freq = qdict_haskey(qdict, "freq");
1511 int freq = qdict_get_try_int(qdict, "freq", -1);
1512 int has_bits = qdict_haskey(qdict, "bits");
1513 int bits = qdict_get_try_int(qdict, "bits", -1);
1514 int has_channels = qdict_haskey(qdict, "nchannels");
1515 int nchannels = qdict_get_try_int(qdict, "nchannels", -1);
1516 CaptureState *s;
1518 s = g_malloc0 (sizeof (*s));
1520 freq = has_freq ? freq : 44100;
1521 bits = has_bits ? bits : 16;
1522 nchannels = has_channels ? nchannels : 2;
1524 if (wav_start_capture (s, path, freq, bits, nchannels)) {
1525 monitor_printf(mon, "Failed to add wave capture\n");
1526 g_free (s);
1527 return;
1529 QLIST_INSERT_HEAD (&capture_head, s, entries);
1532 static qemu_acl *find_acl(Monitor *mon, const char *name)
1534 qemu_acl *acl = qemu_acl_find(name);
1536 if (!acl) {
1537 monitor_printf(mon, "acl: unknown list '%s'\n", name);
1539 return acl;
1542 static void hmp_acl_show(Monitor *mon, const QDict *qdict)
1544 const char *aclname = qdict_get_str(qdict, "aclname");
1545 qemu_acl *acl = find_acl(mon, aclname);
1546 qemu_acl_entry *entry;
1547 int i = 0;
1549 if (acl) {
1550 monitor_printf(mon, "policy: %s\n",
1551 acl->defaultDeny ? "deny" : "allow");
1552 QTAILQ_FOREACH(entry, &acl->entries, next) {
1553 i++;
1554 monitor_printf(mon, "%d: %s %s\n", i,
1555 entry->deny ? "deny" : "allow", entry->match);
1560 static void hmp_acl_reset(Monitor *mon, const QDict *qdict)
1562 const char *aclname = qdict_get_str(qdict, "aclname");
1563 qemu_acl *acl = find_acl(mon, aclname);
1565 if (acl) {
1566 qemu_acl_reset(acl);
1567 monitor_printf(mon, "acl: removed all rules\n");
1571 static void hmp_acl_policy(Monitor *mon, const QDict *qdict)
1573 const char *aclname = qdict_get_str(qdict, "aclname");
1574 const char *policy = qdict_get_str(qdict, "policy");
1575 qemu_acl *acl = find_acl(mon, aclname);
1577 if (acl) {
1578 if (strcmp(policy, "allow") == 0) {
1579 acl->defaultDeny = 0;
1580 monitor_printf(mon, "acl: policy set to 'allow'\n");
1581 } else if (strcmp(policy, "deny") == 0) {
1582 acl->defaultDeny = 1;
1583 monitor_printf(mon, "acl: policy set to 'deny'\n");
1584 } else {
1585 monitor_printf(mon, "acl: unknown policy '%s', "
1586 "expected 'deny' or 'allow'\n", policy);
1591 static void hmp_acl_add(Monitor *mon, const QDict *qdict)
1593 const char *aclname = qdict_get_str(qdict, "aclname");
1594 const char *match = qdict_get_str(qdict, "match");
1595 const char *policy = qdict_get_str(qdict, "policy");
1596 int has_index = qdict_haskey(qdict, "index");
1597 int index = qdict_get_try_int(qdict, "index", -1);
1598 qemu_acl *acl = find_acl(mon, aclname);
1599 int deny, ret;
1601 if (acl) {
1602 if (strcmp(policy, "allow") == 0) {
1603 deny = 0;
1604 } else if (strcmp(policy, "deny") == 0) {
1605 deny = 1;
1606 } else {
1607 monitor_printf(mon, "acl: unknown policy '%s', "
1608 "expected 'deny' or 'allow'\n", policy);
1609 return;
1611 if (has_index)
1612 ret = qemu_acl_insert(acl, deny, match, index);
1613 else
1614 ret = qemu_acl_append(acl, deny, match);
1615 if (ret < 0)
1616 monitor_printf(mon, "acl: unable to add acl entry\n");
1617 else
1618 monitor_printf(mon, "acl: added rule at position %d\n", ret);
1622 static void hmp_acl_remove(Monitor *mon, const QDict *qdict)
1624 const char *aclname = qdict_get_str(qdict, "aclname");
1625 const char *match = qdict_get_str(qdict, "match");
1626 qemu_acl *acl = find_acl(mon, aclname);
1627 int ret;
1629 if (acl) {
1630 ret = qemu_acl_remove(acl, match);
1631 if (ret < 0)
1632 monitor_printf(mon, "acl: no matching acl entry\n");
1633 else
1634 monitor_printf(mon, "acl: removed rule at position %d\n", ret);
1638 void qmp_getfd(const char *fdname, Error **errp)
1640 mon_fd_t *monfd;
1641 int fd;
1643 fd = qemu_chr_fe_get_msgfd(cur_mon->chr);
1644 if (fd == -1) {
1645 error_setg(errp, QERR_FD_NOT_SUPPLIED);
1646 return;
1649 if (qemu_isdigit(fdname[0])) {
1650 close(fd);
1651 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "fdname",
1652 "a name not starting with a digit");
1653 return;
1656 QLIST_FOREACH(monfd, &cur_mon->fds, next) {
1657 if (strcmp(monfd->name, fdname) != 0) {
1658 continue;
1661 close(monfd->fd);
1662 monfd->fd = fd;
1663 return;
1666 monfd = g_malloc0(sizeof(mon_fd_t));
1667 monfd->name = g_strdup(fdname);
1668 monfd->fd = fd;
1670 QLIST_INSERT_HEAD(&cur_mon->fds, monfd, next);
1673 void qmp_closefd(const char *fdname, Error **errp)
1675 mon_fd_t *monfd;
1677 QLIST_FOREACH(monfd, &cur_mon->fds, next) {
1678 if (strcmp(monfd->name, fdname) != 0) {
1679 continue;
1682 QLIST_REMOVE(monfd, next);
1683 close(monfd->fd);
1684 g_free(monfd->name);
1685 g_free(monfd);
1686 return;
1689 error_setg(errp, QERR_FD_NOT_FOUND, fdname);
1692 static void hmp_loadvm(Monitor *mon, const QDict *qdict)
1694 int saved_vm_running = runstate_is_running();
1695 const char *name = qdict_get_str(qdict, "name");
1697 vm_stop(RUN_STATE_RESTORE_VM);
1699 if (load_vmstate(name) == 0 && saved_vm_running) {
1700 vm_start();
1704 int monitor_get_fd(Monitor *mon, const char *fdname, Error **errp)
1706 mon_fd_t *monfd;
1708 QLIST_FOREACH(monfd, &mon->fds, next) {
1709 int fd;
1711 if (strcmp(monfd->name, fdname) != 0) {
1712 continue;
1715 fd = monfd->fd;
1717 /* caller takes ownership of fd */
1718 QLIST_REMOVE(monfd, next);
1719 g_free(monfd->name);
1720 g_free(monfd);
1722 return fd;
1725 error_setg(errp, "File descriptor named '%s' has not been found", fdname);
1726 return -1;
1729 static void monitor_fdset_cleanup(MonFdset *mon_fdset)
1731 MonFdsetFd *mon_fdset_fd;
1732 MonFdsetFd *mon_fdset_fd_next;
1734 QLIST_FOREACH_SAFE(mon_fdset_fd, &mon_fdset->fds, next, mon_fdset_fd_next) {
1735 if ((mon_fdset_fd->removed ||
1736 (QLIST_EMPTY(&mon_fdset->dup_fds) && mon_refcount == 0)) &&
1737 runstate_is_running()) {
1738 close(mon_fdset_fd->fd);
1739 g_free(mon_fdset_fd->opaque);
1740 QLIST_REMOVE(mon_fdset_fd, next);
1741 g_free(mon_fdset_fd);
1745 if (QLIST_EMPTY(&mon_fdset->fds) && QLIST_EMPTY(&mon_fdset->dup_fds)) {
1746 QLIST_REMOVE(mon_fdset, next);
1747 g_free(mon_fdset);
1751 static void monitor_fdsets_cleanup(void)
1753 MonFdset *mon_fdset;
1754 MonFdset *mon_fdset_next;
1756 QLIST_FOREACH_SAFE(mon_fdset, &mon_fdsets, next, mon_fdset_next) {
1757 monitor_fdset_cleanup(mon_fdset);
1761 AddfdInfo *qmp_add_fd(bool has_fdset_id, int64_t fdset_id, bool has_opaque,
1762 const char *opaque, Error **errp)
1764 int fd;
1765 Monitor *mon = cur_mon;
1766 AddfdInfo *fdinfo;
1768 fd = qemu_chr_fe_get_msgfd(mon->chr);
1769 if (fd == -1) {
1770 error_setg(errp, QERR_FD_NOT_SUPPLIED);
1771 goto error;
1774 fdinfo = monitor_fdset_add_fd(fd, has_fdset_id, fdset_id,
1775 has_opaque, opaque, errp);
1776 if (fdinfo) {
1777 return fdinfo;
1780 error:
1781 if (fd != -1) {
1782 close(fd);
1784 return NULL;
1787 void qmp_remove_fd(int64_t fdset_id, bool has_fd, int64_t fd, Error **errp)
1789 MonFdset *mon_fdset;
1790 MonFdsetFd *mon_fdset_fd;
1791 char fd_str[60];
1793 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
1794 if (mon_fdset->id != fdset_id) {
1795 continue;
1797 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
1798 if (has_fd) {
1799 if (mon_fdset_fd->fd != fd) {
1800 continue;
1802 mon_fdset_fd->removed = true;
1803 break;
1804 } else {
1805 mon_fdset_fd->removed = true;
1808 if (has_fd && !mon_fdset_fd) {
1809 goto error;
1811 monitor_fdset_cleanup(mon_fdset);
1812 return;
1815 error:
1816 if (has_fd) {
1817 snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64 ", fd:%" PRId64,
1818 fdset_id, fd);
1819 } else {
1820 snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64, fdset_id);
1822 error_setg(errp, QERR_FD_NOT_FOUND, fd_str);
1825 FdsetInfoList *qmp_query_fdsets(Error **errp)
1827 MonFdset *mon_fdset;
1828 MonFdsetFd *mon_fdset_fd;
1829 FdsetInfoList *fdset_list = NULL;
1831 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
1832 FdsetInfoList *fdset_info = g_malloc0(sizeof(*fdset_info));
1833 FdsetFdInfoList *fdsetfd_list = NULL;
1835 fdset_info->value = g_malloc0(sizeof(*fdset_info->value));
1836 fdset_info->value->fdset_id = mon_fdset->id;
1838 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
1839 FdsetFdInfoList *fdsetfd_info;
1841 fdsetfd_info = g_malloc0(sizeof(*fdsetfd_info));
1842 fdsetfd_info->value = g_malloc0(sizeof(*fdsetfd_info->value));
1843 fdsetfd_info->value->fd = mon_fdset_fd->fd;
1844 if (mon_fdset_fd->opaque) {
1845 fdsetfd_info->value->has_opaque = true;
1846 fdsetfd_info->value->opaque = g_strdup(mon_fdset_fd->opaque);
1847 } else {
1848 fdsetfd_info->value->has_opaque = false;
1851 fdsetfd_info->next = fdsetfd_list;
1852 fdsetfd_list = fdsetfd_info;
1855 fdset_info->value->fds = fdsetfd_list;
1857 fdset_info->next = fdset_list;
1858 fdset_list = fdset_info;
1861 return fdset_list;
1864 AddfdInfo *monitor_fdset_add_fd(int fd, bool has_fdset_id, int64_t fdset_id,
1865 bool has_opaque, const char *opaque,
1866 Error **errp)
1868 MonFdset *mon_fdset = NULL;
1869 MonFdsetFd *mon_fdset_fd;
1870 AddfdInfo *fdinfo;
1872 if (has_fdset_id) {
1873 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
1874 /* Break if match found or match impossible due to ordering by ID */
1875 if (fdset_id <= mon_fdset->id) {
1876 if (fdset_id < mon_fdset->id) {
1877 mon_fdset = NULL;
1879 break;
1884 if (mon_fdset == NULL) {
1885 int64_t fdset_id_prev = -1;
1886 MonFdset *mon_fdset_cur = QLIST_FIRST(&mon_fdsets);
1888 if (has_fdset_id) {
1889 if (fdset_id < 0) {
1890 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "fdset-id",
1891 "a non-negative value");
1892 return NULL;
1894 /* Use specified fdset ID */
1895 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
1896 mon_fdset_cur = mon_fdset;
1897 if (fdset_id < mon_fdset_cur->id) {
1898 break;
1901 } else {
1902 /* Use first available fdset ID */
1903 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
1904 mon_fdset_cur = mon_fdset;
1905 if (fdset_id_prev == mon_fdset_cur->id - 1) {
1906 fdset_id_prev = mon_fdset_cur->id;
1907 continue;
1909 break;
1913 mon_fdset = g_malloc0(sizeof(*mon_fdset));
1914 if (has_fdset_id) {
1915 mon_fdset->id = fdset_id;
1916 } else {
1917 mon_fdset->id = fdset_id_prev + 1;
1920 /* The fdset list is ordered by fdset ID */
1921 if (!mon_fdset_cur) {
1922 QLIST_INSERT_HEAD(&mon_fdsets, mon_fdset, next);
1923 } else if (mon_fdset->id < mon_fdset_cur->id) {
1924 QLIST_INSERT_BEFORE(mon_fdset_cur, mon_fdset, next);
1925 } else {
1926 QLIST_INSERT_AFTER(mon_fdset_cur, mon_fdset, next);
1930 mon_fdset_fd = g_malloc0(sizeof(*mon_fdset_fd));
1931 mon_fdset_fd->fd = fd;
1932 mon_fdset_fd->removed = false;
1933 if (has_opaque) {
1934 mon_fdset_fd->opaque = g_strdup(opaque);
1936 QLIST_INSERT_HEAD(&mon_fdset->fds, mon_fdset_fd, next);
1938 fdinfo = g_malloc0(sizeof(*fdinfo));
1939 fdinfo->fdset_id = mon_fdset->id;
1940 fdinfo->fd = mon_fdset_fd->fd;
1942 return fdinfo;
1945 int monitor_fdset_get_fd(int64_t fdset_id, int flags)
1947 #ifndef _WIN32
1948 MonFdset *mon_fdset;
1949 MonFdsetFd *mon_fdset_fd;
1950 int mon_fd_flags;
1952 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
1953 if (mon_fdset->id != fdset_id) {
1954 continue;
1956 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
1957 mon_fd_flags = fcntl(mon_fdset_fd->fd, F_GETFL);
1958 if (mon_fd_flags == -1) {
1959 return -1;
1962 if ((flags & O_ACCMODE) == (mon_fd_flags & O_ACCMODE)) {
1963 return mon_fdset_fd->fd;
1966 errno = EACCES;
1967 return -1;
1969 #endif
1971 errno = ENOENT;
1972 return -1;
1975 int monitor_fdset_dup_fd_add(int64_t fdset_id, int dup_fd)
1977 MonFdset *mon_fdset;
1978 MonFdsetFd *mon_fdset_fd_dup;
1980 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
1981 if (mon_fdset->id != fdset_id) {
1982 continue;
1984 QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
1985 if (mon_fdset_fd_dup->fd == dup_fd) {
1986 return -1;
1989 mon_fdset_fd_dup = g_malloc0(sizeof(*mon_fdset_fd_dup));
1990 mon_fdset_fd_dup->fd = dup_fd;
1991 QLIST_INSERT_HEAD(&mon_fdset->dup_fds, mon_fdset_fd_dup, next);
1992 return 0;
1994 return -1;
1997 static int monitor_fdset_dup_fd_find_remove(int dup_fd, bool remove)
1999 MonFdset *mon_fdset;
2000 MonFdsetFd *mon_fdset_fd_dup;
2002 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2003 QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
2004 if (mon_fdset_fd_dup->fd == dup_fd) {
2005 if (remove) {
2006 QLIST_REMOVE(mon_fdset_fd_dup, next);
2007 if (QLIST_EMPTY(&mon_fdset->dup_fds)) {
2008 monitor_fdset_cleanup(mon_fdset);
2010 return -1;
2011 } else {
2012 return mon_fdset->id;
2017 return -1;
2020 int monitor_fdset_dup_fd_find(int dup_fd)
2022 return monitor_fdset_dup_fd_find_remove(dup_fd, false);
2025 void monitor_fdset_dup_fd_remove(int dup_fd)
2027 monitor_fdset_dup_fd_find_remove(dup_fd, true);
2030 int monitor_fd_param(Monitor *mon, const char *fdname, Error **errp)
2032 int fd;
2033 Error *local_err = NULL;
2035 if (!qemu_isdigit(fdname[0]) && mon) {
2036 fd = monitor_get_fd(mon, fdname, &local_err);
2037 } else {
2038 fd = qemu_parse_fd(fdname);
2039 if (fd == -1) {
2040 error_setg(&local_err, "Invalid file descriptor number '%s'",
2041 fdname);
2044 if (local_err) {
2045 error_propagate(errp, local_err);
2046 assert(fd == -1);
2047 } else {
2048 assert(fd != -1);
2051 return fd;
2054 /* Please update hmp-commands.hx when adding or changing commands */
2055 static mon_cmd_t info_cmds[] = {
2056 #include "hmp-commands-info.h"
2057 { NULL, NULL, },
2060 /* mon_cmds and info_cmds would be sorted at runtime */
2061 static mon_cmd_t mon_cmds[] = {
2062 #include "hmp-commands.h"
2063 { NULL, NULL, },
2066 static const mon_cmd_t qmp_cmds[] = {
2067 #include "qmp-commands-old.h"
2068 { /* NULL */ },
2071 /*******************************************************************/
2073 static const char *pch;
2074 static sigjmp_buf expr_env;
2077 static void GCC_FMT_ATTR(2, 3) QEMU_NORETURN
2078 expr_error(Monitor *mon, const char *fmt, ...)
2080 va_list ap;
2081 va_start(ap, fmt);
2082 monitor_vprintf(mon, fmt, ap);
2083 monitor_printf(mon, "\n");
2084 va_end(ap);
2085 siglongjmp(expr_env, 1);
2088 /* return 0 if OK, -1 if not found */
2089 static int get_monitor_def(target_long *pval, const char *name)
2091 const MonitorDef *md = target_monitor_defs();
2092 void *ptr;
2094 if (md == NULL) {
2095 return -1;
2098 for(; md->name != NULL; md++) {
2099 if (compare_cmd(name, md->name)) {
2100 if (md->get_value) {
2101 *pval = md->get_value(md, md->offset);
2102 } else {
2103 CPUArchState *env = mon_get_cpu_env();
2104 ptr = (uint8_t *)env + md->offset;
2105 switch(md->type) {
2106 case MD_I32:
2107 *pval = *(int32_t *)ptr;
2108 break;
2109 case MD_TLONG:
2110 *pval = *(target_long *)ptr;
2111 break;
2112 default:
2113 *pval = 0;
2114 break;
2117 return 0;
2120 return -1;
2123 static void next(void)
2125 if (*pch != '\0') {
2126 pch++;
2127 while (qemu_isspace(*pch))
2128 pch++;
2132 static int64_t expr_sum(Monitor *mon);
2134 static int64_t expr_unary(Monitor *mon)
2136 int64_t n;
2137 char *p;
2138 int ret;
2140 switch(*pch) {
2141 case '+':
2142 next();
2143 n = expr_unary(mon);
2144 break;
2145 case '-':
2146 next();
2147 n = -expr_unary(mon);
2148 break;
2149 case '~':
2150 next();
2151 n = ~expr_unary(mon);
2152 break;
2153 case '(':
2154 next();
2155 n = expr_sum(mon);
2156 if (*pch != ')') {
2157 expr_error(mon, "')' expected");
2159 next();
2160 break;
2161 case '\'':
2162 pch++;
2163 if (*pch == '\0')
2164 expr_error(mon, "character constant expected");
2165 n = *pch;
2166 pch++;
2167 if (*pch != '\'')
2168 expr_error(mon, "missing terminating \' character");
2169 next();
2170 break;
2171 case '$':
2173 char buf[128], *q;
2174 target_long reg=0;
2176 pch++;
2177 q = buf;
2178 while ((*pch >= 'a' && *pch <= 'z') ||
2179 (*pch >= 'A' && *pch <= 'Z') ||
2180 (*pch >= '0' && *pch <= '9') ||
2181 *pch == '_' || *pch == '.') {
2182 if ((q - buf) < sizeof(buf) - 1)
2183 *q++ = *pch;
2184 pch++;
2186 while (qemu_isspace(*pch))
2187 pch++;
2188 *q = 0;
2189 ret = get_monitor_def(&reg, buf);
2190 if (ret < 0)
2191 expr_error(mon, "unknown register");
2192 n = reg;
2194 break;
2195 case '\0':
2196 expr_error(mon, "unexpected end of expression");
2197 n = 0;
2198 break;
2199 default:
2200 errno = 0;
2201 n = strtoull(pch, &p, 0);
2202 if (errno == ERANGE) {
2203 expr_error(mon, "number too large");
2205 if (pch == p) {
2206 expr_error(mon, "invalid char '%c' in expression", *p);
2208 pch = p;
2209 while (qemu_isspace(*pch))
2210 pch++;
2211 break;
2213 return n;
2217 static int64_t expr_prod(Monitor *mon)
2219 int64_t val, val2;
2220 int op;
2222 val = expr_unary(mon);
2223 for(;;) {
2224 op = *pch;
2225 if (op != '*' && op != '/' && op != '%')
2226 break;
2227 next();
2228 val2 = expr_unary(mon);
2229 switch(op) {
2230 default:
2231 case '*':
2232 val *= val2;
2233 break;
2234 case '/':
2235 case '%':
2236 if (val2 == 0)
2237 expr_error(mon, "division by zero");
2238 if (op == '/')
2239 val /= val2;
2240 else
2241 val %= val2;
2242 break;
2245 return val;
2248 static int64_t expr_logic(Monitor *mon)
2250 int64_t val, val2;
2251 int op;
2253 val = expr_prod(mon);
2254 for(;;) {
2255 op = *pch;
2256 if (op != '&' && op != '|' && op != '^')
2257 break;
2258 next();
2259 val2 = expr_prod(mon);
2260 switch(op) {
2261 default:
2262 case '&':
2263 val &= val2;
2264 break;
2265 case '|':
2266 val |= val2;
2267 break;
2268 case '^':
2269 val ^= val2;
2270 break;
2273 return val;
2276 static int64_t expr_sum(Monitor *mon)
2278 int64_t val, val2;
2279 int op;
2281 val = expr_logic(mon);
2282 for(;;) {
2283 op = *pch;
2284 if (op != '+' && op != '-')
2285 break;
2286 next();
2287 val2 = expr_logic(mon);
2288 if (op == '+')
2289 val += val2;
2290 else
2291 val -= val2;
2293 return val;
2296 static int get_expr(Monitor *mon, int64_t *pval, const char **pp)
2298 pch = *pp;
2299 if (sigsetjmp(expr_env, 0)) {
2300 *pp = pch;
2301 return -1;
2303 while (qemu_isspace(*pch))
2304 pch++;
2305 *pval = expr_sum(mon);
2306 *pp = pch;
2307 return 0;
2310 static int get_double(Monitor *mon, double *pval, const char **pp)
2312 const char *p = *pp;
2313 char *tailp;
2314 double d;
2316 d = strtod(p, &tailp);
2317 if (tailp == p) {
2318 monitor_printf(mon, "Number expected\n");
2319 return -1;
2321 if (d != d || d - d != 0) {
2322 /* NaN or infinity */
2323 monitor_printf(mon, "Bad number\n");
2324 return -1;
2326 *pval = d;
2327 *pp = tailp;
2328 return 0;
2332 * Store the command-name in cmdname, and return a pointer to
2333 * the remaining of the command string.
2335 static const char *get_command_name(const char *cmdline,
2336 char *cmdname, size_t nlen)
2338 size_t len;
2339 const char *p, *pstart;
2341 p = cmdline;
2342 while (qemu_isspace(*p))
2343 p++;
2344 if (*p == '\0')
2345 return NULL;
2346 pstart = p;
2347 while (*p != '\0' && *p != '/' && !qemu_isspace(*p))
2348 p++;
2349 len = p - pstart;
2350 if (len > nlen - 1)
2351 len = nlen - 1;
2352 memcpy(cmdname, pstart, len);
2353 cmdname[len] = '\0';
2354 return p;
2358 * Read key of 'type' into 'key' and return the current
2359 * 'type' pointer.
2361 static char *key_get_info(const char *type, char **key)
2363 size_t len;
2364 char *p, *str;
2366 if (*type == ',')
2367 type++;
2369 p = strchr(type, ':');
2370 if (!p) {
2371 *key = NULL;
2372 return NULL;
2374 len = p - type;
2376 str = g_malloc(len + 1);
2377 memcpy(str, type, len);
2378 str[len] = '\0';
2380 *key = str;
2381 return ++p;
2384 static int default_fmt_format = 'x';
2385 static int default_fmt_size = 4;
2387 static int is_valid_option(const char *c, const char *typestr)
2389 char option[3];
2391 option[0] = '-';
2392 option[1] = *c;
2393 option[2] = '\0';
2395 typestr = strstr(typestr, option);
2396 return (typestr != NULL);
2399 static const mon_cmd_t *search_dispatch_table(const mon_cmd_t *disp_table,
2400 const char *cmdname)
2402 const mon_cmd_t *cmd;
2404 for (cmd = disp_table; cmd->name != NULL; cmd++) {
2405 if (compare_cmd(cmdname, cmd->name)) {
2406 return cmd;
2410 return NULL;
2413 static const mon_cmd_t *qmp_find_cmd(const char *cmdname)
2415 return search_dispatch_table(qmp_cmds, cmdname);
2419 * Parse command name from @cmdp according to command table @table.
2420 * If blank, return NULL.
2421 * Else, if no valid command can be found, report to @mon, and return
2422 * NULL.
2423 * Else, change @cmdp to point right behind the name, and return its
2424 * command table entry.
2425 * Do not assume the return value points into @table! It doesn't when
2426 * the command is found in a sub-command table.
2428 static const mon_cmd_t *monitor_parse_command(Monitor *mon,
2429 const char **cmdp,
2430 mon_cmd_t *table)
2432 const char *p;
2433 const mon_cmd_t *cmd;
2434 char cmdname[256];
2436 /* extract the command name */
2437 p = get_command_name(*cmdp, cmdname, sizeof(cmdname));
2438 if (!p)
2439 return NULL;
2441 cmd = search_dispatch_table(table, cmdname);
2442 if (!cmd) {
2443 monitor_printf(mon, "unknown command: '%.*s'\n",
2444 (int)(p - *cmdp), *cmdp);
2445 return NULL;
2448 /* filter out following useless space */
2449 while (qemu_isspace(*p)) {
2450 p++;
2453 *cmdp = p;
2454 /* search sub command */
2455 if (cmd->sub_table != NULL && *p != '\0') {
2456 return monitor_parse_command(mon, cmdp, cmd->sub_table);
2459 return cmd;
2463 * Parse arguments for @cmd.
2464 * If it can't be parsed, report to @mon, and return NULL.
2465 * Else, insert command arguments into a QDict, and return it.
2466 * Note: On success, caller has to free the QDict structure.
2469 static QDict *monitor_parse_arguments(Monitor *mon,
2470 const char **endp,
2471 const mon_cmd_t *cmd)
2473 const char *typestr;
2474 char *key;
2475 int c;
2476 const char *p = *endp;
2477 char buf[1024];
2478 QDict *qdict = qdict_new();
2480 /* parse the parameters */
2481 typestr = cmd->args_type;
2482 for(;;) {
2483 typestr = key_get_info(typestr, &key);
2484 if (!typestr)
2485 break;
2486 c = *typestr;
2487 typestr++;
2488 switch(c) {
2489 case 'F':
2490 case 'B':
2491 case 's':
2493 int ret;
2495 while (qemu_isspace(*p))
2496 p++;
2497 if (*typestr == '?') {
2498 typestr++;
2499 if (*p == '\0') {
2500 /* no optional string: NULL argument */
2501 break;
2504 ret = get_str(buf, sizeof(buf), &p);
2505 if (ret < 0) {
2506 switch(c) {
2507 case 'F':
2508 monitor_printf(mon, "%s: filename expected\n",
2509 cmd->name);
2510 break;
2511 case 'B':
2512 monitor_printf(mon, "%s: block device name expected\n",
2513 cmd->name);
2514 break;
2515 default:
2516 monitor_printf(mon, "%s: string expected\n", cmd->name);
2517 break;
2519 goto fail;
2521 qdict_put(qdict, key, qstring_from_str(buf));
2523 break;
2524 case 'O':
2526 QemuOptsList *opts_list;
2527 QemuOpts *opts;
2529 opts_list = qemu_find_opts(key);
2530 if (!opts_list || opts_list->desc->name) {
2531 goto bad_type;
2533 while (qemu_isspace(*p)) {
2534 p++;
2536 if (!*p)
2537 break;
2538 if (get_str(buf, sizeof(buf), &p) < 0) {
2539 goto fail;
2541 opts = qemu_opts_parse_noisily(opts_list, buf, true);
2542 if (!opts) {
2543 goto fail;
2545 qemu_opts_to_qdict(opts, qdict);
2546 qemu_opts_del(opts);
2548 break;
2549 case '/':
2551 int count, format, size;
2553 while (qemu_isspace(*p))
2554 p++;
2555 if (*p == '/') {
2556 /* format found */
2557 p++;
2558 count = 1;
2559 if (qemu_isdigit(*p)) {
2560 count = 0;
2561 while (qemu_isdigit(*p)) {
2562 count = count * 10 + (*p - '0');
2563 p++;
2566 size = -1;
2567 format = -1;
2568 for(;;) {
2569 switch(*p) {
2570 case 'o':
2571 case 'd':
2572 case 'u':
2573 case 'x':
2574 case 'i':
2575 case 'c':
2576 format = *p++;
2577 break;
2578 case 'b':
2579 size = 1;
2580 p++;
2581 break;
2582 case 'h':
2583 size = 2;
2584 p++;
2585 break;
2586 case 'w':
2587 size = 4;
2588 p++;
2589 break;
2590 case 'g':
2591 case 'L':
2592 size = 8;
2593 p++;
2594 break;
2595 default:
2596 goto next;
2599 next:
2600 if (*p != '\0' && !qemu_isspace(*p)) {
2601 monitor_printf(mon, "invalid char in format: '%c'\n",
2602 *p);
2603 goto fail;
2605 if (format < 0)
2606 format = default_fmt_format;
2607 if (format != 'i') {
2608 /* for 'i', not specifying a size gives -1 as size */
2609 if (size < 0)
2610 size = default_fmt_size;
2611 default_fmt_size = size;
2613 default_fmt_format = format;
2614 } else {
2615 count = 1;
2616 format = default_fmt_format;
2617 if (format != 'i') {
2618 size = default_fmt_size;
2619 } else {
2620 size = -1;
2623 qdict_put(qdict, "count", qint_from_int(count));
2624 qdict_put(qdict, "format", qint_from_int(format));
2625 qdict_put(qdict, "size", qint_from_int(size));
2627 break;
2628 case 'i':
2629 case 'l':
2630 case 'M':
2632 int64_t val;
2634 while (qemu_isspace(*p))
2635 p++;
2636 if (*typestr == '?' || *typestr == '.') {
2637 if (*typestr == '?') {
2638 if (*p == '\0') {
2639 typestr++;
2640 break;
2642 } else {
2643 if (*p == '.') {
2644 p++;
2645 while (qemu_isspace(*p))
2646 p++;
2647 } else {
2648 typestr++;
2649 break;
2652 typestr++;
2654 if (get_expr(mon, &val, &p))
2655 goto fail;
2656 /* Check if 'i' is greater than 32-bit */
2657 if ((c == 'i') && ((val >> 32) & 0xffffffff)) {
2658 monitor_printf(mon, "\'%s\' has failed: ", cmd->name);
2659 monitor_printf(mon, "integer is for 32-bit values\n");
2660 goto fail;
2661 } else if (c == 'M') {
2662 if (val < 0) {
2663 monitor_printf(mon, "enter a positive value\n");
2664 goto fail;
2666 val <<= 20;
2668 qdict_put(qdict, key, qint_from_int(val));
2670 break;
2671 case 'o':
2673 int64_t val;
2674 char *end;
2676 while (qemu_isspace(*p)) {
2677 p++;
2679 if (*typestr == '?') {
2680 typestr++;
2681 if (*p == '\0') {
2682 break;
2685 val = strtosz(p, &end);
2686 if (val < 0) {
2687 monitor_printf(mon, "invalid size\n");
2688 goto fail;
2690 qdict_put(qdict, key, qint_from_int(val));
2691 p = end;
2693 break;
2694 case 'T':
2696 double val;
2698 while (qemu_isspace(*p))
2699 p++;
2700 if (*typestr == '?') {
2701 typestr++;
2702 if (*p == '\0') {
2703 break;
2706 if (get_double(mon, &val, &p) < 0) {
2707 goto fail;
2709 if (p[0] && p[1] == 's') {
2710 switch (*p) {
2711 case 'm':
2712 val /= 1e3; p += 2; break;
2713 case 'u':
2714 val /= 1e6; p += 2; break;
2715 case 'n':
2716 val /= 1e9; p += 2; break;
2719 if (*p && !qemu_isspace(*p)) {
2720 monitor_printf(mon, "Unknown unit suffix\n");
2721 goto fail;
2723 qdict_put(qdict, key, qfloat_from_double(val));
2725 break;
2726 case 'b':
2728 const char *beg;
2729 bool val;
2731 while (qemu_isspace(*p)) {
2732 p++;
2734 beg = p;
2735 while (qemu_isgraph(*p)) {
2736 p++;
2738 if (p - beg == 2 && !memcmp(beg, "on", p - beg)) {
2739 val = true;
2740 } else if (p - beg == 3 && !memcmp(beg, "off", p - beg)) {
2741 val = false;
2742 } else {
2743 monitor_printf(mon, "Expected 'on' or 'off'\n");
2744 goto fail;
2746 qdict_put(qdict, key, qbool_from_bool(val));
2748 break;
2749 case '-':
2751 const char *tmp = p;
2752 int skip_key = 0;
2753 /* option */
2755 c = *typestr++;
2756 if (c == '\0')
2757 goto bad_type;
2758 while (qemu_isspace(*p))
2759 p++;
2760 if (*p == '-') {
2761 p++;
2762 if(c != *p) {
2763 if(!is_valid_option(p, typestr)) {
2765 monitor_printf(mon, "%s: unsupported option -%c\n",
2766 cmd->name, *p);
2767 goto fail;
2768 } else {
2769 skip_key = 1;
2772 if(skip_key) {
2773 p = tmp;
2774 } else {
2775 /* has option */
2776 p++;
2777 qdict_put(qdict, key, qbool_from_bool(true));
2781 break;
2782 case 'S':
2784 /* package all remaining string */
2785 int len;
2787 while (qemu_isspace(*p)) {
2788 p++;
2790 if (*typestr == '?') {
2791 typestr++;
2792 if (*p == '\0') {
2793 /* no remaining string: NULL argument */
2794 break;
2797 len = strlen(p);
2798 if (len <= 0) {
2799 monitor_printf(mon, "%s: string expected\n",
2800 cmd->name);
2801 goto fail;
2803 qdict_put(qdict, key, qstring_from_str(p));
2804 p += len;
2806 break;
2807 default:
2808 bad_type:
2809 monitor_printf(mon, "%s: unknown type '%c'\n", cmd->name, c);
2810 goto fail;
2812 g_free(key);
2813 key = NULL;
2815 /* check that all arguments were parsed */
2816 while (qemu_isspace(*p))
2817 p++;
2818 if (*p != '\0') {
2819 monitor_printf(mon, "%s: extraneous characters at the end of line\n",
2820 cmd->name);
2821 goto fail;
2824 return qdict;
2826 fail:
2827 QDECREF(qdict);
2828 g_free(key);
2829 return NULL;
2832 static void handle_hmp_command(Monitor *mon, const char *cmdline)
2834 QDict *qdict;
2835 const mon_cmd_t *cmd;
2837 cmd = monitor_parse_command(mon, &cmdline, mon->cmd_table);
2838 if (!cmd) {
2839 return;
2842 qdict = monitor_parse_arguments(mon, &cmdline, cmd);
2843 if (!qdict) {
2844 monitor_printf(mon, "Try \"help %s\" for more information\n",
2845 cmd->name);
2846 return;
2849 cmd->mhandler.cmd(mon, qdict);
2850 QDECREF(qdict);
2853 static void cmd_completion(Monitor *mon, const char *name, const char *list)
2855 const char *p, *pstart;
2856 char cmd[128];
2857 int len;
2859 p = list;
2860 for(;;) {
2861 pstart = p;
2862 p = strchr(p, '|');
2863 if (!p)
2864 p = pstart + strlen(pstart);
2865 len = p - pstart;
2866 if (len > sizeof(cmd) - 2)
2867 len = sizeof(cmd) - 2;
2868 memcpy(cmd, pstart, len);
2869 cmd[len] = '\0';
2870 if (name[0] == '\0' || !strncmp(name, cmd, strlen(name))) {
2871 readline_add_completion(mon->rs, cmd);
2873 if (*p == '\0')
2874 break;
2875 p++;
2879 static void file_completion(Monitor *mon, const char *input)
2881 DIR *ffs;
2882 struct dirent *d;
2883 char path[1024];
2884 char file[1024], file_prefix[1024];
2885 int input_path_len;
2886 const char *p;
2888 p = strrchr(input, '/');
2889 if (!p) {
2890 input_path_len = 0;
2891 pstrcpy(file_prefix, sizeof(file_prefix), input);
2892 pstrcpy(path, sizeof(path), ".");
2893 } else {
2894 input_path_len = p - input + 1;
2895 memcpy(path, input, input_path_len);
2896 if (input_path_len > sizeof(path) - 1)
2897 input_path_len = sizeof(path) - 1;
2898 path[input_path_len] = '\0';
2899 pstrcpy(file_prefix, sizeof(file_prefix), p + 1);
2902 ffs = opendir(path);
2903 if (!ffs)
2904 return;
2905 for(;;) {
2906 struct stat sb;
2907 d = readdir(ffs);
2908 if (!d)
2909 break;
2911 if (strcmp(d->d_name, ".") == 0 || strcmp(d->d_name, "..") == 0) {
2912 continue;
2915 if (strstart(d->d_name, file_prefix, NULL)) {
2916 memcpy(file, input, input_path_len);
2917 if (input_path_len < sizeof(file))
2918 pstrcpy(file + input_path_len, sizeof(file) - input_path_len,
2919 d->d_name);
2920 /* stat the file to find out if it's a directory.
2921 * In that case add a slash to speed up typing long paths
2923 if (stat(file, &sb) == 0 && S_ISDIR(sb.st_mode)) {
2924 pstrcat(file, sizeof(file), "/");
2926 readline_add_completion(mon->rs, file);
2929 closedir(ffs);
2932 static const char *next_arg_type(const char *typestr)
2934 const char *p = strchr(typestr, ':');
2935 return (p != NULL ? ++p : typestr);
2938 static void add_completion_option(ReadLineState *rs, const char *str,
2939 const char *option)
2941 if (!str || !option) {
2942 return;
2944 if (!strncmp(option, str, strlen(str))) {
2945 readline_add_completion(rs, option);
2949 void chardev_add_completion(ReadLineState *rs, int nb_args, const char *str)
2951 size_t len;
2952 ChardevBackendInfoList *list, *start;
2954 if (nb_args != 2) {
2955 return;
2957 len = strlen(str);
2958 readline_set_completion_index(rs, len);
2960 start = list = qmp_query_chardev_backends(NULL);
2961 while (list) {
2962 const char *chr_name = list->value->name;
2964 if (!strncmp(chr_name, str, len)) {
2965 readline_add_completion(rs, chr_name);
2967 list = list->next;
2969 qapi_free_ChardevBackendInfoList(start);
2972 void netdev_add_completion(ReadLineState *rs, int nb_args, const char *str)
2974 size_t len;
2975 int i;
2977 if (nb_args != 2) {
2978 return;
2980 len = strlen(str);
2981 readline_set_completion_index(rs, len);
2982 for (i = 0; NetClientOptionsKind_lookup[i]; i++) {
2983 add_completion_option(rs, str, NetClientOptionsKind_lookup[i]);
2987 void device_add_completion(ReadLineState *rs, int nb_args, const char *str)
2989 GSList *list, *elt;
2990 size_t len;
2992 if (nb_args != 2) {
2993 return;
2996 len = strlen(str);
2997 readline_set_completion_index(rs, len);
2998 list = elt = object_class_get_list(TYPE_DEVICE, false);
2999 while (elt) {
3000 const char *name;
3001 DeviceClass *dc = OBJECT_CLASS_CHECK(DeviceClass, elt->data,
3002 TYPE_DEVICE);
3003 name = object_class_get_name(OBJECT_CLASS(dc));
3005 if (!dc->cannot_instantiate_with_device_add_yet
3006 && !strncmp(name, str, len)) {
3007 readline_add_completion(rs, name);
3009 elt = elt->next;
3011 g_slist_free(list);
3014 void object_add_completion(ReadLineState *rs, int nb_args, const char *str)
3016 GSList *list, *elt;
3017 size_t len;
3019 if (nb_args != 2) {
3020 return;
3023 len = strlen(str);
3024 readline_set_completion_index(rs, len);
3025 list = elt = object_class_get_list(TYPE_USER_CREATABLE, false);
3026 while (elt) {
3027 const char *name;
3029 name = object_class_get_name(OBJECT_CLASS(elt->data));
3030 if (!strncmp(name, str, len) && strcmp(name, TYPE_USER_CREATABLE)) {
3031 readline_add_completion(rs, name);
3033 elt = elt->next;
3035 g_slist_free(list);
3038 static void peripheral_device_del_completion(ReadLineState *rs,
3039 const char *str, size_t len)
3041 Object *peripheral = container_get(qdev_get_machine(), "/peripheral");
3042 GSList *list, *item;
3044 list = qdev_build_hotpluggable_device_list(peripheral);
3045 if (!list) {
3046 return;
3049 for (item = list; item; item = g_slist_next(item)) {
3050 DeviceState *dev = item->data;
3052 if (dev->id && !strncmp(str, dev->id, len)) {
3053 readline_add_completion(rs, dev->id);
3057 g_slist_free(list);
3060 void chardev_remove_completion(ReadLineState *rs, int nb_args, const char *str)
3062 size_t len;
3063 ChardevInfoList *list, *start;
3065 if (nb_args != 2) {
3066 return;
3068 len = strlen(str);
3069 readline_set_completion_index(rs, len);
3071 start = list = qmp_query_chardev(NULL);
3072 while (list) {
3073 ChardevInfo *chr = list->value;
3075 if (!strncmp(chr->label, str, len)) {
3076 readline_add_completion(rs, chr->label);
3078 list = list->next;
3080 qapi_free_ChardevInfoList(start);
3083 static void ringbuf_completion(ReadLineState *rs, const char *str)
3085 size_t len;
3086 ChardevInfoList *list, *start;
3088 len = strlen(str);
3089 readline_set_completion_index(rs, len);
3091 start = list = qmp_query_chardev(NULL);
3092 while (list) {
3093 ChardevInfo *chr_info = list->value;
3095 if (!strncmp(chr_info->label, str, len)) {
3096 CharDriverState *chr = qemu_chr_find(chr_info->label);
3097 if (chr && chr_is_ringbuf(chr)) {
3098 readline_add_completion(rs, chr_info->label);
3101 list = list->next;
3103 qapi_free_ChardevInfoList(start);
3106 void ringbuf_write_completion(ReadLineState *rs, int nb_args, const char *str)
3108 if (nb_args != 2) {
3109 return;
3111 ringbuf_completion(rs, str);
3114 void device_del_completion(ReadLineState *rs, int nb_args, const char *str)
3116 size_t len;
3118 if (nb_args != 2) {
3119 return;
3122 len = strlen(str);
3123 readline_set_completion_index(rs, len);
3124 peripheral_device_del_completion(rs, str, len);
3127 void object_del_completion(ReadLineState *rs, int nb_args, const char *str)
3129 ObjectPropertyInfoList *list, *start;
3130 size_t len;
3132 if (nb_args != 2) {
3133 return;
3135 len = strlen(str);
3136 readline_set_completion_index(rs, len);
3138 start = list = qmp_qom_list("/objects", NULL);
3139 while (list) {
3140 ObjectPropertyInfo *info = list->value;
3142 if (!strncmp(info->type, "child<", 5)
3143 && !strncmp(info->name, str, len)) {
3144 readline_add_completion(rs, info->name);
3146 list = list->next;
3148 qapi_free_ObjectPropertyInfoList(start);
3151 void sendkey_completion(ReadLineState *rs, int nb_args, const char *str)
3153 int i;
3154 char *sep;
3155 size_t len;
3157 if (nb_args != 2) {
3158 return;
3160 sep = strrchr(str, '-');
3161 if (sep) {
3162 str = sep + 1;
3164 len = strlen(str);
3165 readline_set_completion_index(rs, len);
3166 for (i = 0; i < Q_KEY_CODE_MAX; i++) {
3167 if (!strncmp(str, QKeyCode_lookup[i], len)) {
3168 readline_add_completion(rs, QKeyCode_lookup[i]);
3173 void set_link_completion(ReadLineState *rs, int nb_args, const char *str)
3175 size_t len;
3177 len = strlen(str);
3178 readline_set_completion_index(rs, len);
3179 if (nb_args == 2) {
3180 NetClientState *ncs[MAX_QUEUE_NUM];
3181 int count, i;
3182 count = qemu_find_net_clients_except(NULL, ncs,
3183 NET_CLIENT_OPTIONS_KIND_NONE,
3184 MAX_QUEUE_NUM);
3185 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3186 const char *name = ncs[i]->name;
3187 if (!strncmp(str, name, len)) {
3188 readline_add_completion(rs, name);
3191 } else if (nb_args == 3) {
3192 add_completion_option(rs, str, "on");
3193 add_completion_option(rs, str, "off");
3197 void netdev_del_completion(ReadLineState *rs, int nb_args, const char *str)
3199 int len, count, i;
3200 NetClientState *ncs[MAX_QUEUE_NUM];
3202 if (nb_args != 2) {
3203 return;
3206 len = strlen(str);
3207 readline_set_completion_index(rs, len);
3208 count = qemu_find_net_clients_except(NULL, ncs, NET_CLIENT_OPTIONS_KIND_NIC,
3209 MAX_QUEUE_NUM);
3210 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3211 QemuOpts *opts;
3212 const char *name = ncs[i]->name;
3213 if (strncmp(str, name, len)) {
3214 continue;
3216 opts = qemu_opts_find(qemu_find_opts_err("netdev", NULL), name);
3217 if (opts) {
3218 readline_add_completion(rs, name);
3223 void trace_event_completion(ReadLineState *rs, int nb_args, const char *str)
3225 size_t len;
3227 len = strlen(str);
3228 readline_set_completion_index(rs, len);
3229 if (nb_args == 2) {
3230 TraceEventID id;
3231 for (id = 0; id < trace_event_count(); id++) {
3232 const char *event_name = trace_event_get_name(trace_event_id(id));
3233 if (!strncmp(str, event_name, len)) {
3234 readline_add_completion(rs, event_name);
3237 } else if (nb_args == 3) {
3238 add_completion_option(rs, str, "on");
3239 add_completion_option(rs, str, "off");
3243 void watchdog_action_completion(ReadLineState *rs, int nb_args, const char *str)
3245 int i;
3247 if (nb_args != 2) {
3248 return;
3250 readline_set_completion_index(rs, strlen(str));
3251 for (i = 0; WatchdogExpirationAction_lookup[i]; i++) {
3252 add_completion_option(rs, str, WatchdogExpirationAction_lookup[i]);
3256 void migrate_set_capability_completion(ReadLineState *rs, int nb_args,
3257 const char *str)
3259 size_t len;
3261 len = strlen(str);
3262 readline_set_completion_index(rs, len);
3263 if (nb_args == 2) {
3264 int i;
3265 for (i = 0; i < MIGRATION_CAPABILITY_MAX; i++) {
3266 const char *name = MigrationCapability_lookup[i];
3267 if (!strncmp(str, name, len)) {
3268 readline_add_completion(rs, name);
3271 } else if (nb_args == 3) {
3272 add_completion_option(rs, str, "on");
3273 add_completion_option(rs, str, "off");
3277 void migrate_set_parameter_completion(ReadLineState *rs, int nb_args,
3278 const char *str)
3280 size_t len;
3282 len = strlen(str);
3283 readline_set_completion_index(rs, len);
3284 if (nb_args == 2) {
3285 int i;
3286 for (i = 0; i < MIGRATION_PARAMETER_MAX; i++) {
3287 const char *name = MigrationParameter_lookup[i];
3288 if (!strncmp(str, name, len)) {
3289 readline_add_completion(rs, name);
3295 void host_net_add_completion(ReadLineState *rs, int nb_args, const char *str)
3297 int i;
3298 size_t len;
3299 if (nb_args != 2) {
3300 return;
3302 len = strlen(str);
3303 readline_set_completion_index(rs, len);
3304 for (i = 0; host_net_devices[i]; i++) {
3305 if (!strncmp(host_net_devices[i], str, len)) {
3306 readline_add_completion(rs, host_net_devices[i]);
3311 void host_net_remove_completion(ReadLineState *rs, int nb_args, const char *str)
3313 NetClientState *ncs[MAX_QUEUE_NUM];
3314 int count, i, len;
3316 len = strlen(str);
3317 readline_set_completion_index(rs, len);
3318 if (nb_args == 2) {
3319 count = qemu_find_net_clients_except(NULL, ncs,
3320 NET_CLIENT_OPTIONS_KIND_NONE,
3321 MAX_QUEUE_NUM);
3322 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3323 int id;
3324 char name[16];
3326 if (net_hub_id_for_client(ncs[i], &id)) {
3327 continue;
3329 snprintf(name, sizeof(name), "%d", id);
3330 if (!strncmp(str, name, len)) {
3331 readline_add_completion(rs, name);
3334 return;
3335 } else if (nb_args == 3) {
3336 count = qemu_find_net_clients_except(NULL, ncs,
3337 NET_CLIENT_OPTIONS_KIND_NIC,
3338 MAX_QUEUE_NUM);
3339 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3340 int id;
3341 const char *name;
3343 if (ncs[i]->info->type == NET_CLIENT_OPTIONS_KIND_HUBPORT ||
3344 net_hub_id_for_client(ncs[i], &id)) {
3345 continue;
3347 name = ncs[i]->name;
3348 if (!strncmp(str, name, len)) {
3349 readline_add_completion(rs, name);
3352 return;
3356 static void vm_completion(ReadLineState *rs, const char *str)
3358 size_t len;
3359 BlockDriverState *bs = NULL;
3361 len = strlen(str);
3362 readline_set_completion_index(rs, len);
3363 while ((bs = bdrv_next(bs))) {
3364 SnapshotInfoList *snapshots, *snapshot;
3366 if (!bdrv_can_snapshot(bs)) {
3367 continue;
3369 if (bdrv_query_snapshot_info_list(bs, &snapshots, NULL)) {
3370 continue;
3372 snapshot = snapshots;
3373 while (snapshot) {
3374 char *completion = snapshot->value->name;
3375 if (!strncmp(str, completion, len)) {
3376 readline_add_completion(rs, completion);
3378 completion = snapshot->value->id;
3379 if (!strncmp(str, completion, len)) {
3380 readline_add_completion(rs, completion);
3382 snapshot = snapshot->next;
3384 qapi_free_SnapshotInfoList(snapshots);
3389 void delvm_completion(ReadLineState *rs, int nb_args, const char *str)
3391 if (nb_args == 2) {
3392 vm_completion(rs, str);
3396 void loadvm_completion(ReadLineState *rs, int nb_args, const char *str)
3398 if (nb_args == 2) {
3399 vm_completion(rs, str);
3403 static void monitor_find_completion_by_table(Monitor *mon,
3404 const mon_cmd_t *cmd_table,
3405 char **args,
3406 int nb_args)
3408 const char *cmdname;
3409 int i;
3410 const char *ptype, *str, *name;
3411 const mon_cmd_t *cmd;
3412 BlockDriverState *bs;
3414 if (nb_args <= 1) {
3415 /* command completion */
3416 if (nb_args == 0)
3417 cmdname = "";
3418 else
3419 cmdname = args[0];
3420 readline_set_completion_index(mon->rs, strlen(cmdname));
3421 for (cmd = cmd_table; cmd->name != NULL; cmd++) {
3422 cmd_completion(mon, cmdname, cmd->name);
3424 } else {
3425 /* find the command */
3426 for (cmd = cmd_table; cmd->name != NULL; cmd++) {
3427 if (compare_cmd(args[0], cmd->name)) {
3428 break;
3431 if (!cmd->name) {
3432 return;
3435 if (cmd->sub_table) {
3436 /* do the job again */
3437 monitor_find_completion_by_table(mon, cmd->sub_table,
3438 &args[1], nb_args - 1);
3439 return;
3441 if (cmd->command_completion) {
3442 cmd->command_completion(mon->rs, nb_args, args[nb_args - 1]);
3443 return;
3446 ptype = next_arg_type(cmd->args_type);
3447 for(i = 0; i < nb_args - 2; i++) {
3448 if (*ptype != '\0') {
3449 ptype = next_arg_type(ptype);
3450 while (*ptype == '?')
3451 ptype = next_arg_type(ptype);
3454 str = args[nb_args - 1];
3455 while (*ptype == '-' && ptype[1] != '\0') {
3456 ptype = next_arg_type(ptype);
3458 switch(*ptype) {
3459 case 'F':
3460 /* file completion */
3461 readline_set_completion_index(mon->rs, strlen(str));
3462 file_completion(mon, str);
3463 break;
3464 case 'B':
3465 /* block device name completion */
3466 readline_set_completion_index(mon->rs, strlen(str));
3467 for (bs = bdrv_next(NULL); bs; bs = bdrv_next(bs)) {
3468 name = bdrv_get_device_name(bs);
3469 if (str[0] == '\0' ||
3470 !strncmp(name, str, strlen(str))) {
3471 readline_add_completion(mon->rs, name);
3474 break;
3475 case 's':
3476 case 'S':
3477 if (!strcmp(cmd->name, "help|?")) {
3478 monitor_find_completion_by_table(mon, cmd_table,
3479 &args[1], nb_args - 1);
3481 break;
3482 default:
3483 break;
3488 static void monitor_find_completion(void *opaque,
3489 const char *cmdline)
3491 Monitor *mon = opaque;
3492 char *args[MAX_ARGS];
3493 int nb_args, len;
3495 /* 1. parse the cmdline */
3496 if (parse_cmdline(cmdline, &nb_args, args) < 0) {
3497 return;
3500 /* if the line ends with a space, it means we want to complete the
3501 next arg */
3502 len = strlen(cmdline);
3503 if (len > 0 && qemu_isspace(cmdline[len - 1])) {
3504 if (nb_args >= MAX_ARGS) {
3505 goto cleanup;
3507 args[nb_args++] = g_strdup("");
3510 /* 2. auto complete according to args */
3511 monitor_find_completion_by_table(mon, mon->cmd_table, args, nb_args);
3513 cleanup:
3514 free_cmdline_args(args, nb_args);
3517 static int monitor_can_read(void *opaque)
3519 Monitor *mon = opaque;
3521 return (mon->suspend_cnt == 0) ? 1 : 0;
3524 static bool invalid_qmp_mode(const Monitor *mon, const mon_cmd_t *cmd,
3525 Error **errp)
3527 bool is_cap = cmd->mhandler.cmd_new == qmp_capabilities;
3529 if (is_cap && mon->qmp.in_command_mode) {
3530 error_set(errp, ERROR_CLASS_COMMAND_NOT_FOUND,
3531 "Capabilities negotiation is already complete, command "
3532 "'%s' ignored", cmd->name);
3533 return true;
3535 if (!is_cap && !mon->qmp.in_command_mode) {
3536 error_set(errp, ERROR_CLASS_COMMAND_NOT_FOUND,
3537 "Expecting capabilities negotiation with "
3538 "'qmp_capabilities' before command '%s'", cmd->name);
3539 return true;
3541 return false;
3545 * Argument validation rules:
3547 * 1. The argument must exist in cmd_args qdict
3548 * 2. The argument type must be the expected one
3550 * Special case: If the argument doesn't exist in cmd_args and
3551 * the QMP_ACCEPT_UNKNOWNS flag is set, then the
3552 * checking is skipped for it.
3554 static void check_client_args_type(const QDict *client_args,
3555 const QDict *cmd_args, int flags,
3556 Error **errp)
3558 const QDictEntry *ent;
3560 for (ent = qdict_first(client_args); ent;ent = qdict_next(client_args,ent)){
3561 QObject *obj;
3562 QString *arg_type;
3563 const QObject *client_arg = qdict_entry_value(ent);
3564 const char *client_arg_name = qdict_entry_key(ent);
3566 obj = qdict_get(cmd_args, client_arg_name);
3567 if (!obj) {
3568 if (flags & QMP_ACCEPT_UNKNOWNS) {
3569 /* handler accepts unknowns */
3570 continue;
3572 /* client arg doesn't exist */
3573 error_setg(errp, QERR_INVALID_PARAMETER, client_arg_name);
3574 return;
3577 arg_type = qobject_to_qstring(obj);
3578 assert(arg_type != NULL);
3580 /* check if argument's type is correct */
3581 switch (qstring_get_str(arg_type)[0]) {
3582 case 'F':
3583 case 'B':
3584 case 's':
3585 if (qobject_type(client_arg) != QTYPE_QSTRING) {
3586 error_setg(errp, QERR_INVALID_PARAMETER_TYPE,
3587 client_arg_name, "string");
3588 return;
3590 break;
3591 case 'i':
3592 case 'l':
3593 case 'M':
3594 case 'o':
3595 if (qobject_type(client_arg) != QTYPE_QINT) {
3596 error_setg(errp, QERR_INVALID_PARAMETER_TYPE,
3597 client_arg_name, "int");
3598 return;
3600 break;
3601 case 'T':
3602 if (qobject_type(client_arg) != QTYPE_QINT &&
3603 qobject_type(client_arg) != QTYPE_QFLOAT) {
3604 error_setg(errp, QERR_INVALID_PARAMETER_TYPE,
3605 client_arg_name, "number");
3606 return;
3608 break;
3609 case 'b':
3610 case '-':
3611 if (qobject_type(client_arg) != QTYPE_QBOOL) {
3612 error_setg(errp, QERR_INVALID_PARAMETER_TYPE,
3613 client_arg_name, "bool");
3614 return;
3616 break;
3617 case 'O':
3618 assert(flags & QMP_ACCEPT_UNKNOWNS);
3619 break;
3620 case 'q':
3621 /* Any QObject can be passed. */
3622 break;
3623 case '/':
3624 case '.':
3626 * These types are not supported by QMP and thus are not
3627 * handled here. Fall through.
3629 default:
3630 abort();
3636 * - Check if the client has passed all mandatory args
3637 * - Set special flags for argument validation
3639 static void check_mandatory_args(const QDict *cmd_args,
3640 const QDict *client_args, int *flags,
3641 Error **errp)
3643 const QDictEntry *ent;
3645 for (ent = qdict_first(cmd_args); ent; ent = qdict_next(cmd_args, ent)) {
3646 const char *cmd_arg_name = qdict_entry_key(ent);
3647 QString *type = qobject_to_qstring(qdict_entry_value(ent));
3648 assert(type != NULL);
3650 if (qstring_get_str(type)[0] == 'O') {
3651 assert((*flags & QMP_ACCEPT_UNKNOWNS) == 0);
3652 *flags |= QMP_ACCEPT_UNKNOWNS;
3653 } else if (qstring_get_str(type)[0] != '-' &&
3654 qstring_get_str(type)[1] != '?' &&
3655 !qdict_haskey(client_args, cmd_arg_name)) {
3656 error_setg(errp, QERR_MISSING_PARAMETER, cmd_arg_name);
3657 return;
3662 static QDict *qdict_from_args_type(const char *args_type)
3664 int i;
3665 QDict *qdict;
3666 QString *key, *type, *cur_qs;
3668 assert(args_type != NULL);
3670 qdict = qdict_new();
3672 if (args_type == NULL || args_type[0] == '\0') {
3673 /* no args, empty qdict */
3674 goto out;
3677 key = qstring_new();
3678 type = qstring_new();
3680 cur_qs = key;
3682 for (i = 0;; i++) {
3683 switch (args_type[i]) {
3684 case ',':
3685 case '\0':
3686 qdict_put(qdict, qstring_get_str(key), type);
3687 QDECREF(key);
3688 if (args_type[i] == '\0') {
3689 goto out;
3691 type = qstring_new(); /* qdict has ref */
3692 cur_qs = key = qstring_new();
3693 break;
3694 case ':':
3695 cur_qs = type;
3696 break;
3697 default:
3698 qstring_append_chr(cur_qs, args_type[i]);
3699 break;
3703 out:
3704 return qdict;
3708 * Client argument checking rules:
3710 * 1. Client must provide all mandatory arguments
3711 * 2. Each argument provided by the client must be expected
3712 * 3. Each argument provided by the client must have the type expected
3713 * by the command
3715 static void qmp_check_client_args(const mon_cmd_t *cmd, QDict *client_args,
3716 Error **errp)
3718 Error *err = NULL;
3719 int flags;
3720 QDict *cmd_args;
3722 cmd_args = qdict_from_args_type(cmd->args_type);
3724 flags = 0;
3725 check_mandatory_args(cmd_args, client_args, &flags, &err);
3726 if (err) {
3727 goto out;
3730 check_client_args_type(client_args, cmd_args, flags, &err);
3732 out:
3733 error_propagate(errp, err);
3734 QDECREF(cmd_args);
3738 * Input object checking rules
3740 * 1. Input object must be a dict
3741 * 2. The "execute" key must exist
3742 * 3. The "execute" key must be a string
3743 * 4. If the "arguments" key exists, it must be a dict
3744 * 5. If the "id" key exists, it can be anything (ie. json-value)
3745 * 6. Any argument not listed above is considered invalid
3747 static QDict *qmp_check_input_obj(QObject *input_obj, Error **errp)
3749 const QDictEntry *ent;
3750 int has_exec_key = 0;
3751 QDict *input_dict;
3753 if (qobject_type(input_obj) != QTYPE_QDICT) {
3754 error_setg(errp, QERR_QMP_BAD_INPUT_OBJECT, "object");
3755 return NULL;
3758 input_dict = qobject_to_qdict(input_obj);
3760 for (ent = qdict_first(input_dict); ent; ent = qdict_next(input_dict, ent)){
3761 const char *arg_name = qdict_entry_key(ent);
3762 const QObject *arg_obj = qdict_entry_value(ent);
3764 if (!strcmp(arg_name, "execute")) {
3765 if (qobject_type(arg_obj) != QTYPE_QSTRING) {
3766 error_setg(errp, QERR_QMP_BAD_INPUT_OBJECT_MEMBER,
3767 "execute", "string");
3768 return NULL;
3770 has_exec_key = 1;
3771 } else if (!strcmp(arg_name, "arguments")) {
3772 if (qobject_type(arg_obj) != QTYPE_QDICT) {
3773 error_setg(errp, QERR_QMP_BAD_INPUT_OBJECT_MEMBER,
3774 "arguments", "object");
3775 return NULL;
3777 } else if (!strcmp(arg_name, "id")) {
3778 /* Any string is acceptable as "id", so nothing to check */
3779 } else {
3780 error_setg(errp, QERR_QMP_EXTRA_MEMBER, arg_name);
3781 return NULL;
3785 if (!has_exec_key) {
3786 error_setg(errp, QERR_QMP_BAD_INPUT_OBJECT, "execute");
3787 return NULL;
3790 return input_dict;
3793 static void handle_qmp_command(JSONMessageParser *parser, QList *tokens)
3795 Error *local_err = NULL;
3796 QObject *obj, *data;
3797 QDict *input, *args;
3798 const mon_cmd_t *cmd;
3799 const char *cmd_name;
3800 Monitor *mon = cur_mon;
3802 args = input = NULL;
3803 data = NULL;
3805 obj = json_parser_parse(tokens, NULL);
3806 if (!obj) {
3807 // FIXME: should be triggered in json_parser_parse()
3808 error_setg(&local_err, QERR_JSON_PARSING);
3809 goto err_out;
3812 input = qmp_check_input_obj(obj, &local_err);
3813 if (!input) {
3814 qobject_decref(obj);
3815 goto err_out;
3818 mon->qmp.id = qdict_get(input, "id");
3819 qobject_incref(mon->qmp.id);
3821 cmd_name = qdict_get_str(input, "execute");
3822 trace_handle_qmp_command(mon, cmd_name);
3823 cmd = qmp_find_cmd(cmd_name);
3824 if (!cmd) {
3825 error_set(&local_err, ERROR_CLASS_COMMAND_NOT_FOUND,
3826 "The command %s has not been found", cmd_name);
3827 goto err_out;
3829 if (invalid_qmp_mode(mon, cmd, &local_err)) {
3830 goto err_out;
3833 obj = qdict_get(input, "arguments");
3834 if (!obj) {
3835 args = qdict_new();
3836 } else {
3837 args = qobject_to_qdict(obj);
3838 QINCREF(args);
3841 qmp_check_client_args(cmd, args, &local_err);
3842 if (local_err) {
3843 goto err_out;
3846 cmd->mhandler.cmd_new(args, &data, &local_err);
3848 err_out:
3849 monitor_protocol_emitter(mon, data, local_err);
3850 qobject_decref(data);
3851 QDECREF(input);
3852 QDECREF(args);
3855 static void monitor_qmp_read(void *opaque, const uint8_t *buf, int size)
3857 Monitor *old_mon = cur_mon;
3859 cur_mon = opaque;
3861 json_message_parser_feed(&cur_mon->qmp.parser, (const char *) buf, size);
3863 cur_mon = old_mon;
3866 static void monitor_read(void *opaque, const uint8_t *buf, int size)
3868 Monitor *old_mon = cur_mon;
3869 int i;
3871 cur_mon = opaque;
3873 if (cur_mon->rs) {
3874 for (i = 0; i < size; i++)
3875 readline_handle_byte(cur_mon->rs, buf[i]);
3876 } else {
3877 if (size == 0 || buf[size - 1] != 0)
3878 monitor_printf(cur_mon, "corrupted command\n");
3879 else
3880 handle_hmp_command(cur_mon, (char *)buf);
3883 cur_mon = old_mon;
3886 static void monitor_command_cb(void *opaque, const char *cmdline,
3887 void *readline_opaque)
3889 Monitor *mon = opaque;
3891 monitor_suspend(mon);
3892 handle_hmp_command(mon, cmdline);
3893 monitor_resume(mon);
3896 int monitor_suspend(Monitor *mon)
3898 if (!mon->rs)
3899 return -ENOTTY;
3900 mon->suspend_cnt++;
3901 return 0;
3904 void monitor_resume(Monitor *mon)
3906 if (!mon->rs)
3907 return;
3908 if (--mon->suspend_cnt == 0)
3909 readline_show_prompt(mon->rs);
3912 static QObject *get_qmp_greeting(void)
3914 QObject *ver = NULL;
3916 qmp_marshal_input_query_version(NULL, &ver, NULL);
3917 return qobject_from_jsonf("{'QMP':{'version': %p,'capabilities': []}}",ver);
3920 static void monitor_qmp_event(void *opaque, int event)
3922 QObject *data;
3923 Monitor *mon = opaque;
3925 switch (event) {
3926 case CHR_EVENT_OPENED:
3927 mon->qmp.in_command_mode = false;
3928 data = get_qmp_greeting();
3929 monitor_json_emitter(mon, data);
3930 qobject_decref(data);
3931 mon_refcount++;
3932 break;
3933 case CHR_EVENT_CLOSED:
3934 json_message_parser_destroy(&mon->qmp.parser);
3935 json_message_parser_init(&mon->qmp.parser, handle_qmp_command);
3936 mon_refcount--;
3937 monitor_fdsets_cleanup();
3938 break;
3942 static void monitor_event(void *opaque, int event)
3944 Monitor *mon = opaque;
3946 switch (event) {
3947 case CHR_EVENT_MUX_IN:
3948 qemu_mutex_lock(&mon->out_lock);
3949 mon->mux_out = 0;
3950 qemu_mutex_unlock(&mon->out_lock);
3951 if (mon->reset_seen) {
3952 readline_restart(mon->rs);
3953 monitor_resume(mon);
3954 monitor_flush(mon);
3955 } else {
3956 mon->suspend_cnt = 0;
3958 break;
3960 case CHR_EVENT_MUX_OUT:
3961 if (mon->reset_seen) {
3962 if (mon->suspend_cnt == 0) {
3963 monitor_printf(mon, "\n");
3965 monitor_flush(mon);
3966 monitor_suspend(mon);
3967 } else {
3968 mon->suspend_cnt++;
3970 qemu_mutex_lock(&mon->out_lock);
3971 mon->mux_out = 1;
3972 qemu_mutex_unlock(&mon->out_lock);
3973 break;
3975 case CHR_EVENT_OPENED:
3976 monitor_printf(mon, "QEMU %s monitor - type 'help' for more "
3977 "information\n", QEMU_VERSION);
3978 if (!mon->mux_out) {
3979 readline_restart(mon->rs);
3980 readline_show_prompt(mon->rs);
3982 mon->reset_seen = 1;
3983 mon_refcount++;
3984 break;
3986 case CHR_EVENT_CLOSED:
3987 mon_refcount--;
3988 monitor_fdsets_cleanup();
3989 break;
3993 static int
3994 compare_mon_cmd(const void *a, const void *b)
3996 return strcmp(((const mon_cmd_t *)a)->name,
3997 ((const mon_cmd_t *)b)->name);
4000 static void sortcmdlist(void)
4002 int array_num;
4003 int elem_size = sizeof(mon_cmd_t);
4005 array_num = sizeof(mon_cmds)/elem_size-1;
4006 qsort((void *)mon_cmds, array_num, elem_size, compare_mon_cmd);
4008 array_num = sizeof(info_cmds)/elem_size-1;
4009 qsort((void *)info_cmds, array_num, elem_size, compare_mon_cmd);
4014 * Local variables:
4015 * c-indent-level: 4
4016 * c-basic-offset: 4
4017 * tab-width: 8
4018 * End:
4021 /* These functions just adapt the readline interface in a typesafe way. We
4022 * could cast function pointers but that discards compiler checks.
4024 static void GCC_FMT_ATTR(2, 3) monitor_readline_printf(void *opaque,
4025 const char *fmt, ...)
4027 va_list ap;
4028 va_start(ap, fmt);
4029 monitor_vprintf(opaque, fmt, ap);
4030 va_end(ap);
4033 static void monitor_readline_flush(void *opaque)
4035 monitor_flush(opaque);
4038 static void __attribute__((constructor)) monitor_lock_init(void)
4040 qemu_mutex_init(&monitor_lock);
4043 void monitor_init(CharDriverState *chr, int flags)
4045 static int is_first_init = 1;
4046 Monitor *mon;
4048 if (is_first_init) {
4049 monitor_qapi_event_init();
4050 sortcmdlist();
4051 is_first_init = 0;
4054 mon = g_malloc(sizeof(*mon));
4055 monitor_data_init(mon);
4057 mon->chr = chr;
4058 mon->flags = flags;
4059 if (flags & MONITOR_USE_READLINE) {
4060 mon->rs = readline_init(monitor_readline_printf,
4061 monitor_readline_flush,
4062 mon,
4063 monitor_find_completion);
4064 monitor_read_command(mon, 0);
4067 if (monitor_is_qmp(mon)) {
4068 qemu_chr_add_handlers(chr, monitor_can_read, monitor_qmp_read,
4069 monitor_qmp_event, mon);
4070 qemu_chr_fe_set_echo(chr, true);
4071 json_message_parser_init(&mon->qmp.parser, handle_qmp_command);
4072 } else {
4073 qemu_chr_add_handlers(chr, monitor_can_read, monitor_read,
4074 monitor_event, mon);
4077 qemu_mutex_lock(&monitor_lock);
4078 QLIST_INSERT_HEAD(&mon_list, mon, entry);
4079 qemu_mutex_unlock(&monitor_lock);
4082 static void bdrv_password_cb(void *opaque, const char *password,
4083 void *readline_opaque)
4085 Monitor *mon = opaque;
4086 BlockDriverState *bs = readline_opaque;
4087 int ret = 0;
4088 Error *local_err = NULL;
4090 bdrv_add_key(bs, password, &local_err);
4091 if (local_err) {
4092 monitor_printf(mon, "%s\n", error_get_pretty(local_err));
4093 error_free(local_err);
4094 ret = -EPERM;
4096 if (mon->password_completion_cb)
4097 mon->password_completion_cb(mon->password_opaque, ret);
4099 monitor_read_command(mon, 1);
4102 int monitor_read_bdrv_key_start(Monitor *mon, BlockDriverState *bs,
4103 BlockCompletionFunc *completion_cb,
4104 void *opaque)
4106 int err;
4108 monitor_printf(mon, "%s (%s) is encrypted.\n", bdrv_get_device_name(bs),
4109 bdrv_get_encrypted_filename(bs));
4111 mon->password_completion_cb = completion_cb;
4112 mon->password_opaque = opaque;
4114 err = monitor_read_password(mon, bdrv_password_cb, bs);
4116 if (err && completion_cb)
4117 completion_cb(opaque, err);
4119 return err;
4122 int monitor_read_block_device_key(Monitor *mon, const char *device,
4123 BlockCompletionFunc *completion_cb,
4124 void *opaque)
4126 Error *err = NULL;
4127 BlockBackend *blk;
4129 blk = blk_by_name(device);
4130 if (!blk) {
4131 monitor_printf(mon, "Device not found %s\n", device);
4132 return -1;
4135 bdrv_add_key(blk_bs(blk), NULL, &err);
4136 if (err) {
4137 error_free(err);
4138 return monitor_read_bdrv_key_start(mon, blk_bs(blk), completion_cb, opaque);
4141 if (completion_cb) {
4142 completion_cb(opaque, 0);
4144 return 0;
4147 QemuOptsList qemu_mon_opts = {
4148 .name = "mon",
4149 .implied_opt_name = "chardev",
4150 .head = QTAILQ_HEAD_INITIALIZER(qemu_mon_opts.head),
4151 .desc = {
4153 .name = "mode",
4154 .type = QEMU_OPT_STRING,
4156 .name = "chardev",
4157 .type = QEMU_OPT_STRING,
4159 .name = "default",
4160 .type = QEMU_OPT_BOOL,
4162 .name = "pretty",
4163 .type = QEMU_OPT_BOOL,
4165 { /* end of list */ }
4169 #ifndef TARGET_I386
4170 void qmp_rtc_reset_reinjection(Error **errp)
4172 error_setg(errp, QERR_FEATURE_DISABLED, "rtc-reset-reinjection");
4174 #endif
4176 #ifndef TARGET_S390X
4177 void qmp_dump_skeys(const char *filename, Error **errp)
4179 error_setg(errp, QERR_FEATURE_DISABLED, "dump-skeys");
4181 #endif