Merge remote-tracking branch 'remotes/pmaydell/tags/pull-target-arm-20160316-1' into...
[qemu.git] / monitor.c
blob894f862dd31f7359cb517c54cce15a206551544d
1 /*
2 * QEMU monitor
4 * Copyright (c) 2003-2004 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
24 #include "qemu/osdep.h"
25 #include <dirent.h>
26 #include "hw/hw.h"
27 #include "monitor/qdev.h"
28 #include "hw/usb.h"
29 #include "hw/i386/pc.h"
30 #include "hw/pci/pci.h"
31 #include "sysemu/watchdog.h"
32 #include "hw/loader.h"
33 #include "exec/gdbstub.h"
34 #include "net/net.h"
35 #include "net/slirp.h"
36 #include "sysemu/char.h"
37 #include "ui/qemu-spice.h"
38 #include "sysemu/sysemu.h"
39 #include "sysemu/numa.h"
40 #include "monitor/monitor.h"
41 #include "qemu/readline.h"
42 #include "ui/console.h"
43 #include "ui/input.h"
44 #include "sysemu/blockdev.h"
45 #include "audio/audio.h"
46 #include "disas/disas.h"
47 #include "sysemu/balloon.h"
48 #include "qemu/timer.h"
49 #include "migration/migration.h"
50 #include "sysemu/kvm.h"
51 #include "qemu/acl.h"
52 #include "sysemu/tpm.h"
53 #include "qapi/qmp/qerror.h"
54 #include "qapi/qmp/qint.h"
55 #include "qapi/qmp/qfloat.h"
56 #include "qapi/qmp/qlist.h"
57 #include "qapi/qmp/qbool.h"
58 #include "qapi/qmp/qstring.h"
59 #include "qapi/qmp/qjson.h"
60 #include "qapi/qmp/json-streamer.h"
61 #include "qapi/qmp/json-parser.h"
62 #include <qom/object_interfaces.h>
63 #include "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 "qmp-commands.h"
72 #include "hmp.h"
73 #include "qemu/thread.h"
74 #include "block/qapi.h"
75 #include "qapi/qmp-event.h"
76 #include "qapi-event.h"
77 #include "qmp-introspect.h"
78 #include "sysemu/block-backend.h"
79 #include "sysemu/qtest.h"
81 /* for hmp_info_irq/pic */
82 #if defined(TARGET_SPARC)
83 #include "hw/sparc/sun4m.h"
84 #endif
85 #include "hw/lm32/lm32_pic.h"
87 #if defined(TARGET_S390X)
88 #include "hw/s390x/storage-keys.h"
89 #endif
92 * Supported types:
94 * 'F' filename
95 * 'B' block device name
96 * 's' string (accept optional quote)
97 * 'S' it just appends the rest of the string (accept optional quote)
98 * 'O' option string of the form NAME=VALUE,...
99 * parsed according to QemuOptsList given by its name
100 * Example: 'device:O' uses qemu_device_opts.
101 * Restriction: only lists with empty desc are supported
102 * TODO lift the restriction
103 * 'i' 32 bit integer
104 * 'l' target long (32 or 64 bit)
105 * 'M' Non-negative target long (32 or 64 bit), in user mode the
106 * value is multiplied by 2^20 (think Mebibyte)
107 * 'o' octets (aka bytes)
108 * user mode accepts an optional E, e, P, p, T, t, G, g, M, m,
109 * K, k suffix, which multiplies the value by 2^60 for suffixes E
110 * and e, 2^50 for suffixes P and p, 2^40 for suffixes T and t,
111 * 2^30 for suffixes G and g, 2^20 for M and m, 2^10 for K and k
112 * 'T' double
113 * user mode accepts an optional ms, us, ns suffix,
114 * which divides the value by 1e3, 1e6, 1e9, respectively
115 * '/' optional gdb-like print format (like "/10x")
117 * '?' optional type (for all types, except '/')
118 * '.' other form of optional type (for 'i' and 'l')
119 * 'b' boolean
120 * user mode accepts "on" or "off"
121 * '-' optional parameter (eg. '-f')
125 typedef struct mon_cmd_t {
126 const char *name;
127 const char *args_type;
128 const char *params;
129 const char *help;
130 union {
131 void (*cmd)(Monitor *mon, const QDict *qdict);
132 void (*cmd_new)(QDict *params, QObject **ret_data, Error **errp);
133 } mhandler;
134 /* @sub_table is a list of 2nd level of commands. If it do not exist,
135 * mhandler should be used. If it exist, sub_table[?].mhandler should be
136 * used, and mhandler of 1st level plays the role of help function.
138 struct mon_cmd_t *sub_table;
139 void (*command_completion)(ReadLineState *rs, int nb_args, const char *str);
140 } mon_cmd_t;
142 /* file descriptors passed via SCM_RIGHTS */
143 typedef struct mon_fd_t mon_fd_t;
144 struct mon_fd_t {
145 char *name;
146 int fd;
147 QLIST_ENTRY(mon_fd_t) next;
150 /* file descriptor associated with a file descriptor set */
151 typedef struct MonFdsetFd MonFdsetFd;
152 struct MonFdsetFd {
153 int fd;
154 bool removed;
155 char *opaque;
156 QLIST_ENTRY(MonFdsetFd) next;
159 /* file descriptor set containing fds passed via SCM_RIGHTS */
160 typedef struct MonFdset MonFdset;
161 struct MonFdset {
162 int64_t id;
163 QLIST_HEAD(, MonFdsetFd) fds;
164 QLIST_HEAD(, MonFdsetFd) dup_fds;
165 QLIST_ENTRY(MonFdset) next;
168 typedef struct {
169 QObject *id;
170 JSONMessageParser parser;
172 * When a client connects, we're in capabilities negotiation mode.
173 * When command qmp_capabilities succeeds, we go into command
174 * mode.
176 bool in_command_mode; /* are we in command mode? */
177 } MonitorQMP;
180 * To prevent flooding clients, events can be throttled. The
181 * throttling is calculated globally, rather than per-Monitor
182 * instance.
184 typedef struct MonitorQAPIEventState {
185 QAPIEvent event; /* Throttling state for this event type and... */
186 QDict *data; /* ... data, see qapi_event_throttle_equal() */
187 QEMUTimer *timer; /* Timer for handling delayed events */
188 QDict *qdict; /* Delayed event (if any) */
189 } MonitorQAPIEventState;
191 typedef struct {
192 int64_t rate; /* Minimum time (in ns) between two events */
193 } MonitorQAPIEventConf;
195 struct Monitor {
196 CharDriverState *chr;
197 int reset_seen;
198 int flags;
199 int suspend_cnt;
200 bool skip_flush;
202 QemuMutex out_lock;
203 QString *outbuf;
204 guint out_watch;
206 /* Read under either BQL or out_lock, written with BQL+out_lock. */
207 int mux_out;
209 ReadLineState *rs;
210 MonitorQMP qmp;
211 CPUState *mon_cpu;
212 BlockCompletionFunc *password_completion_cb;
213 void *password_opaque;
214 mon_cmd_t *cmd_table;
215 QLIST_HEAD(,mon_fd_t) fds;
216 QLIST_ENTRY(Monitor) entry;
219 /* QMP checker flags */
220 #define QMP_ACCEPT_UNKNOWNS 1
222 /* Protects mon_list, monitor_event_state. */
223 static QemuMutex monitor_lock;
225 static QLIST_HEAD(mon_list, Monitor) mon_list;
226 static QLIST_HEAD(mon_fdsets, MonFdset) mon_fdsets;
227 static int mon_refcount;
229 static mon_cmd_t mon_cmds[];
230 static mon_cmd_t info_cmds[];
232 static const mon_cmd_t qmp_cmds[];
234 Monitor *cur_mon;
236 static QEMUClockType event_clock_type = QEMU_CLOCK_REALTIME;
238 static void monitor_command_cb(void *opaque, const char *cmdline,
239 void *readline_opaque);
242 * Is @mon a QMP monitor?
244 static inline bool monitor_is_qmp(const Monitor *mon)
246 return (mon->flags & MONITOR_USE_CONTROL);
250 * Is the current monitor, if any, a QMP monitor?
252 bool monitor_cur_is_qmp(void)
254 return cur_mon && monitor_is_qmp(cur_mon);
257 void monitor_read_command(Monitor *mon, int show_prompt)
259 if (!mon->rs)
260 return;
262 readline_start(mon->rs, "(qemu) ", 0, monitor_command_cb, NULL);
263 if (show_prompt)
264 readline_show_prompt(mon->rs);
267 int monitor_read_password(Monitor *mon, ReadLineFunc *readline_func,
268 void *opaque)
270 if (mon->rs) {
271 readline_start(mon->rs, "Password: ", 1, readline_func, opaque);
272 /* prompt is printed on return from the command handler */
273 return 0;
274 } else {
275 monitor_printf(mon, "terminal does not support password prompting\n");
276 return -ENOTTY;
280 static void monitor_flush_locked(Monitor *mon);
282 static gboolean monitor_unblocked(GIOChannel *chan, GIOCondition cond,
283 void *opaque)
285 Monitor *mon = opaque;
287 qemu_mutex_lock(&mon->out_lock);
288 mon->out_watch = 0;
289 monitor_flush_locked(mon);
290 qemu_mutex_unlock(&mon->out_lock);
291 return FALSE;
294 /* Called with mon->out_lock held. */
295 static void monitor_flush_locked(Monitor *mon)
297 int rc;
298 size_t len;
299 const char *buf;
301 if (mon->skip_flush) {
302 return;
305 buf = qstring_get_str(mon->outbuf);
306 len = qstring_get_length(mon->outbuf);
308 if (len && !mon->mux_out) {
309 rc = qemu_chr_fe_write(mon->chr, (const uint8_t *) buf, len);
310 if ((rc < 0 && errno != EAGAIN) || (rc == len)) {
311 /* all flushed or error */
312 QDECREF(mon->outbuf);
313 mon->outbuf = qstring_new();
314 return;
316 if (rc > 0) {
317 /* partinal write */
318 QString *tmp = qstring_from_str(buf + rc);
319 QDECREF(mon->outbuf);
320 mon->outbuf = tmp;
322 if (mon->out_watch == 0) {
323 mon->out_watch = qemu_chr_fe_add_watch(mon->chr, G_IO_OUT|G_IO_HUP,
324 monitor_unblocked, mon);
329 void monitor_flush(Monitor *mon)
331 qemu_mutex_lock(&mon->out_lock);
332 monitor_flush_locked(mon);
333 qemu_mutex_unlock(&mon->out_lock);
336 /* flush at every end of line */
337 static void monitor_puts(Monitor *mon, const char *str)
339 char c;
341 qemu_mutex_lock(&mon->out_lock);
342 for(;;) {
343 c = *str++;
344 if (c == '\0')
345 break;
346 if (c == '\n') {
347 qstring_append_chr(mon->outbuf, '\r');
349 qstring_append_chr(mon->outbuf, c);
350 if (c == '\n') {
351 monitor_flush_locked(mon);
354 qemu_mutex_unlock(&mon->out_lock);
357 void monitor_vprintf(Monitor *mon, const char *fmt, va_list ap)
359 char *buf;
361 if (!mon)
362 return;
364 if (monitor_is_qmp(mon)) {
365 return;
368 buf = g_strdup_vprintf(fmt, ap);
369 monitor_puts(mon, buf);
370 g_free(buf);
373 void monitor_printf(Monitor *mon, const char *fmt, ...)
375 va_list ap;
376 va_start(ap, fmt);
377 monitor_vprintf(mon, fmt, ap);
378 va_end(ap);
381 int monitor_fprintf(FILE *stream, const char *fmt, ...)
383 va_list ap;
384 va_start(ap, fmt);
385 monitor_vprintf((Monitor *)stream, fmt, ap);
386 va_end(ap);
387 return 0;
390 static void monitor_json_emitter(Monitor *mon, const QObject *data)
392 QString *json;
394 json = mon->flags & MONITOR_USE_PRETTY ? qobject_to_json_pretty(data) :
395 qobject_to_json(data);
396 assert(json != NULL);
398 qstring_append_chr(json, '\n');
399 monitor_puts(mon, qstring_get_str(json));
401 QDECREF(json);
404 static QDict *build_qmp_error_dict(Error *err)
406 QObject *obj;
408 obj = qobject_from_jsonf("{ 'error': { 'class': %s, 'desc': %s } }",
409 QapiErrorClass_lookup[error_get_class(err)],
410 error_get_pretty(err));
412 return qobject_to_qdict(obj);
415 static void monitor_protocol_emitter(Monitor *mon, QObject *data,
416 Error *err)
418 QDict *qmp;
420 trace_monitor_protocol_emitter(mon);
422 if (!err) {
423 /* success response */
424 qmp = qdict_new();
425 if (data) {
426 qobject_incref(data);
427 qdict_put_obj(qmp, "return", data);
428 } else {
429 /* return an empty QDict by default */
430 qdict_put(qmp, "return", qdict_new());
432 } else {
433 /* error response */
434 qmp = build_qmp_error_dict(err);
437 if (mon->qmp.id) {
438 qdict_put_obj(qmp, "id", mon->qmp.id);
439 mon->qmp.id = NULL;
442 monitor_json_emitter(mon, QOBJECT(qmp));
443 QDECREF(qmp);
447 static MonitorQAPIEventConf monitor_qapi_event_conf[QAPI_EVENT__MAX] = {
448 /* Limit guest-triggerable events to 1 per second */
449 [QAPI_EVENT_RTC_CHANGE] = { 1000 * SCALE_MS },
450 [QAPI_EVENT_WATCHDOG] = { 1000 * SCALE_MS },
451 [QAPI_EVENT_BALLOON_CHANGE] = { 1000 * SCALE_MS },
452 [QAPI_EVENT_QUORUM_REPORT_BAD] = { 1000 * SCALE_MS },
453 [QAPI_EVENT_QUORUM_FAILURE] = { 1000 * SCALE_MS },
454 [QAPI_EVENT_VSERPORT_CHANGE] = { 1000 * SCALE_MS },
457 GHashTable *monitor_qapi_event_state;
460 * Emits the event to every monitor instance, @event is only used for trace
461 * Called with monitor_lock held.
463 static void monitor_qapi_event_emit(QAPIEvent event, QDict *qdict)
465 Monitor *mon;
467 trace_monitor_protocol_event_emit(event, qdict);
468 QLIST_FOREACH(mon, &mon_list, entry) {
469 if (monitor_is_qmp(mon) && mon->qmp.in_command_mode) {
470 monitor_json_emitter(mon, QOBJECT(qdict));
475 static void monitor_qapi_event_handler(void *opaque);
478 * Queue a new event for emission to Monitor instances,
479 * applying any rate limiting if required.
481 static void
482 monitor_qapi_event_queue(QAPIEvent event, QDict *qdict, Error **errp)
484 MonitorQAPIEventConf *evconf;
485 MonitorQAPIEventState *evstate;
487 assert(event < QAPI_EVENT__MAX);
488 evconf = &monitor_qapi_event_conf[event];
489 trace_monitor_protocol_event_queue(event, qdict, evconf->rate);
491 qemu_mutex_lock(&monitor_lock);
493 if (!evconf->rate) {
494 /* Unthrottled event */
495 monitor_qapi_event_emit(event, qdict);
496 } else {
497 QDict *data = qobject_to_qdict(qdict_get(qdict, "data"));
498 MonitorQAPIEventState key = { .event = event, .data = data };
500 evstate = g_hash_table_lookup(monitor_qapi_event_state, &key);
501 assert(!evstate || timer_pending(evstate->timer));
503 if (evstate) {
505 * Timer is pending for (at least) evconf->rate ns after
506 * last send. Store event for sending when timer fires,
507 * replacing a prior stored event if any.
509 QDECREF(evstate->qdict);
510 evstate->qdict = qdict;
511 QINCREF(evstate->qdict);
512 } else {
514 * Last send was (at least) evconf->rate ns ago.
515 * Send immediately, and arm the timer to call
516 * monitor_qapi_event_handler() in evconf->rate ns. Any
517 * events arriving before then will be delayed until then.
519 int64_t now = qemu_clock_get_ns(event_clock_type);
521 monitor_qapi_event_emit(event, qdict);
523 evstate = g_new(MonitorQAPIEventState, 1);
524 evstate->event = event;
525 evstate->data = data;
526 QINCREF(evstate->data);
527 evstate->qdict = NULL;
528 evstate->timer = timer_new_ns(event_clock_type,
529 monitor_qapi_event_handler,
530 evstate);
531 g_hash_table_add(monitor_qapi_event_state, evstate);
532 timer_mod_ns(evstate->timer, now + evconf->rate);
536 qemu_mutex_unlock(&monitor_lock);
540 * This function runs evconf->rate ns after sending a throttled
541 * event.
542 * If another event has since been stored, send it.
544 static void monitor_qapi_event_handler(void *opaque)
546 MonitorQAPIEventState *evstate = opaque;
547 MonitorQAPIEventConf *evconf = &monitor_qapi_event_conf[evstate->event];
549 trace_monitor_protocol_event_handler(evstate->event, evstate->qdict);
550 qemu_mutex_lock(&monitor_lock);
552 if (evstate->qdict) {
553 int64_t now = qemu_clock_get_ns(event_clock_type);
555 monitor_qapi_event_emit(evstate->event, evstate->qdict);
556 QDECREF(evstate->qdict);
557 evstate->qdict = NULL;
558 timer_mod_ns(evstate->timer, now + evconf->rate);
559 } else {
560 g_hash_table_remove(monitor_qapi_event_state, evstate);
561 QDECREF(evstate->data);
562 timer_free(evstate->timer);
563 g_free(evstate);
566 qemu_mutex_unlock(&monitor_lock);
569 static unsigned int qapi_event_throttle_hash(const void *key)
571 const MonitorQAPIEventState *evstate = key;
572 unsigned int hash = evstate->event * 255;
574 if (evstate->event == QAPI_EVENT_VSERPORT_CHANGE) {
575 hash += g_str_hash(qdict_get_str(evstate->data, "id"));
578 if (evstate->event == QAPI_EVENT_QUORUM_REPORT_BAD) {
579 hash += g_str_hash(qdict_get_str(evstate->data, "node-name"));
582 return hash;
585 static gboolean qapi_event_throttle_equal(const void *a, const void *b)
587 const MonitorQAPIEventState *eva = a;
588 const MonitorQAPIEventState *evb = b;
590 if (eva->event != evb->event) {
591 return FALSE;
594 if (eva->event == QAPI_EVENT_VSERPORT_CHANGE) {
595 return !strcmp(qdict_get_str(eva->data, "id"),
596 qdict_get_str(evb->data, "id"));
599 if (eva->event == QAPI_EVENT_QUORUM_REPORT_BAD) {
600 return !strcmp(qdict_get_str(eva->data, "node-name"),
601 qdict_get_str(evb->data, "node-name"));
604 return TRUE;
607 static void monitor_qapi_event_init(void)
609 if (qtest_enabled()) {
610 event_clock_type = QEMU_CLOCK_VIRTUAL;
613 monitor_qapi_event_state = g_hash_table_new(qapi_event_throttle_hash,
614 qapi_event_throttle_equal);
615 qmp_event_set_func_emit(monitor_qapi_event_queue);
618 static void qmp_capabilities(QDict *params, QObject **ret_data, Error **errp)
620 cur_mon->qmp.in_command_mode = true;
623 static void handle_hmp_command(Monitor *mon, const char *cmdline);
625 static void monitor_data_init(Monitor *mon)
627 memset(mon, 0, sizeof(Monitor));
628 qemu_mutex_init(&mon->out_lock);
629 mon->outbuf = qstring_new();
630 /* Use *mon_cmds by default. */
631 mon->cmd_table = mon_cmds;
634 static void monitor_data_destroy(Monitor *mon)
636 QDECREF(mon->outbuf);
637 qemu_mutex_destroy(&mon->out_lock);
640 char *qmp_human_monitor_command(const char *command_line, bool has_cpu_index,
641 int64_t cpu_index, Error **errp)
643 char *output = NULL;
644 Monitor *old_mon, hmp;
646 monitor_data_init(&hmp);
647 hmp.skip_flush = true;
649 old_mon = cur_mon;
650 cur_mon = &hmp;
652 if (has_cpu_index) {
653 int ret = monitor_set_cpu(cpu_index);
654 if (ret < 0) {
655 cur_mon = old_mon;
656 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cpu-index",
657 "a CPU number");
658 goto out;
662 handle_hmp_command(&hmp, command_line);
663 cur_mon = old_mon;
665 qemu_mutex_lock(&hmp.out_lock);
666 if (qstring_get_length(hmp.outbuf) > 0) {
667 output = g_strdup(qstring_get_str(hmp.outbuf));
668 } else {
669 output = g_strdup("");
671 qemu_mutex_unlock(&hmp.out_lock);
673 out:
674 monitor_data_destroy(&hmp);
675 return output;
678 static int compare_cmd(const char *name, const char *list)
680 const char *p, *pstart;
681 int len;
682 len = strlen(name);
683 p = list;
684 for(;;) {
685 pstart = p;
686 p = strchr(p, '|');
687 if (!p)
688 p = pstart + strlen(pstart);
689 if ((p - pstart) == len && !memcmp(pstart, name, len))
690 return 1;
691 if (*p == '\0')
692 break;
693 p++;
695 return 0;
698 static int get_str(char *buf, int buf_size, const char **pp)
700 const char *p;
701 char *q;
702 int c;
704 q = buf;
705 p = *pp;
706 while (qemu_isspace(*p)) {
707 p++;
709 if (*p == '\0') {
710 fail:
711 *q = '\0';
712 *pp = p;
713 return -1;
715 if (*p == '\"') {
716 p++;
717 while (*p != '\0' && *p != '\"') {
718 if (*p == '\\') {
719 p++;
720 c = *p++;
721 switch (c) {
722 case 'n':
723 c = '\n';
724 break;
725 case 'r':
726 c = '\r';
727 break;
728 case '\\':
729 case '\'':
730 case '\"':
731 break;
732 default:
733 printf("unsupported escape code: '\\%c'\n", c);
734 goto fail;
736 if ((q - buf) < buf_size - 1) {
737 *q++ = c;
739 } else {
740 if ((q - buf) < buf_size - 1) {
741 *q++ = *p;
743 p++;
746 if (*p != '\"') {
747 printf("unterminated string\n");
748 goto fail;
750 p++;
751 } else {
752 while (*p != '\0' && !qemu_isspace(*p)) {
753 if ((q - buf) < buf_size - 1) {
754 *q++ = *p;
756 p++;
759 *q = '\0';
760 *pp = p;
761 return 0;
764 #define MAX_ARGS 16
766 static void free_cmdline_args(char **args, int nb_args)
768 int i;
770 assert(nb_args <= MAX_ARGS);
772 for (i = 0; i < nb_args; i++) {
773 g_free(args[i]);
779 * Parse the command line to get valid args.
780 * @cmdline: command line to be parsed.
781 * @pnb_args: location to store the number of args, must NOT be NULL.
782 * @args: location to store the args, which should be freed by caller, must
783 * NOT be NULL.
785 * Returns 0 on success, negative on failure.
787 * NOTE: this parser is an approximate form of the real command parser. Number
788 * of args have a limit of MAX_ARGS. If cmdline contains more, it will
789 * return with failure.
791 static int parse_cmdline(const char *cmdline,
792 int *pnb_args, char **args)
794 const char *p;
795 int nb_args, ret;
796 char buf[1024];
798 p = cmdline;
799 nb_args = 0;
800 for (;;) {
801 while (qemu_isspace(*p)) {
802 p++;
804 if (*p == '\0') {
805 break;
807 if (nb_args >= MAX_ARGS) {
808 goto fail;
810 ret = get_str(buf, sizeof(buf), &p);
811 if (ret < 0) {
812 goto fail;
814 args[nb_args] = g_strdup(buf);
815 nb_args++;
817 *pnb_args = nb_args;
818 return 0;
820 fail:
821 free_cmdline_args(args, nb_args);
822 return -1;
825 static void help_cmd_dump_one(Monitor *mon,
826 const mon_cmd_t *cmd,
827 char **prefix_args,
828 int prefix_args_nb)
830 int i;
832 for (i = 0; i < prefix_args_nb; i++) {
833 monitor_printf(mon, "%s ", prefix_args[i]);
835 monitor_printf(mon, "%s %s -- %s\n", cmd->name, cmd->params, cmd->help);
838 /* @args[@arg_index] is the valid command need to find in @cmds */
839 static void help_cmd_dump(Monitor *mon, const mon_cmd_t *cmds,
840 char **args, int nb_args, int arg_index)
842 const mon_cmd_t *cmd;
844 /* No valid arg need to compare with, dump all in *cmds */
845 if (arg_index >= nb_args) {
846 for (cmd = cmds; cmd->name != NULL; cmd++) {
847 help_cmd_dump_one(mon, cmd, args, arg_index);
849 return;
852 /* Find one entry to dump */
853 for (cmd = cmds; cmd->name != NULL; cmd++) {
854 if (compare_cmd(args[arg_index], cmd->name)) {
855 if (cmd->sub_table) {
856 /* continue with next arg */
857 help_cmd_dump(mon, cmd->sub_table,
858 args, nb_args, arg_index + 1);
859 } else {
860 help_cmd_dump_one(mon, cmd, args, arg_index);
862 break;
867 static void help_cmd(Monitor *mon, const char *name)
869 char *args[MAX_ARGS];
870 int nb_args = 0;
872 /* 1. parse user input */
873 if (name) {
874 /* special case for log, directly dump and return */
875 if (!strcmp(name, "log")) {
876 const QEMULogItem *item;
877 monitor_printf(mon, "Log items (comma separated):\n");
878 monitor_printf(mon, "%-10s %s\n", "none", "remove all logs");
879 for (item = qemu_log_items; item->mask != 0; item++) {
880 monitor_printf(mon, "%-10s %s\n", item->name, item->help);
882 return;
885 if (parse_cmdline(name, &nb_args, args) < 0) {
886 return;
890 /* 2. dump the contents according to parsed args */
891 help_cmd_dump(mon, mon->cmd_table, args, nb_args, 0);
893 free_cmdline_args(args, nb_args);
896 static void do_help_cmd(Monitor *mon, const QDict *qdict)
898 help_cmd(mon, qdict_get_try_str(qdict, "name"));
901 static void hmp_trace_event(Monitor *mon, const QDict *qdict)
903 const char *tp_name = qdict_get_str(qdict, "name");
904 bool new_state = qdict_get_bool(qdict, "option");
905 Error *local_err = NULL;
907 qmp_trace_event_set_state(tp_name, new_state, true, true, &local_err);
908 if (local_err) {
909 error_report_err(local_err);
913 #ifdef CONFIG_TRACE_SIMPLE
914 static void hmp_trace_file(Monitor *mon, const QDict *qdict)
916 const char *op = qdict_get_try_str(qdict, "op");
917 const char *arg = qdict_get_try_str(qdict, "arg");
919 if (!op) {
920 st_print_trace_file_status((FILE *)mon, &monitor_fprintf);
921 } else if (!strcmp(op, "on")) {
922 st_set_trace_file_enabled(true);
923 } else if (!strcmp(op, "off")) {
924 st_set_trace_file_enabled(false);
925 } else if (!strcmp(op, "flush")) {
926 st_flush_trace_buffer();
927 } else if (!strcmp(op, "set")) {
928 if (arg) {
929 st_set_trace_file(arg);
931 } else {
932 monitor_printf(mon, "unexpected argument \"%s\"\n", op);
933 help_cmd(mon, "trace-file");
936 #endif
938 static void hmp_info_help(Monitor *mon, const QDict *qdict)
940 help_cmd(mon, "info");
943 CommandInfoList *qmp_query_commands(Error **errp)
945 CommandInfoList *info, *cmd_list = NULL;
946 const mon_cmd_t *cmd;
948 for (cmd = qmp_cmds; cmd->name != NULL; cmd++) {
949 info = g_malloc0(sizeof(*info));
950 info->value = g_malloc0(sizeof(*info->value));
951 info->value->name = g_strdup(cmd->name);
953 info->next = cmd_list;
954 cmd_list = info;
957 return cmd_list;
960 EventInfoList *qmp_query_events(Error **errp)
962 EventInfoList *info, *ev_list = NULL;
963 QAPIEvent e;
965 for (e = 0 ; e < QAPI_EVENT__MAX ; e++) {
966 const char *event_name = QAPIEvent_lookup[e];
967 assert(event_name != NULL);
968 info = g_malloc0(sizeof(*info));
969 info->value = g_malloc0(sizeof(*info->value));
970 info->value->name = g_strdup(event_name);
972 info->next = ev_list;
973 ev_list = info;
976 return ev_list;
980 * Minor hack: generated marshalling suppressed for this command
981 * ('gen': false in the schema) so we can parse the JSON string
982 * directly into QObject instead of first parsing it with
983 * visit_type_SchemaInfoList() into a SchemaInfoList, then marshal it
984 * to QObject with generated output marshallers, every time. Instead,
985 * we do it in test-qmp-input-visitor.c, just to make sure
986 * qapi-introspect.py's output actually conforms to the schema.
988 static void qmp_query_qmp_schema(QDict *qdict, QObject **ret_data,
989 Error **errp)
991 *ret_data = qobject_from_json(qmp_schema_json);
994 /* set the current CPU defined by the user */
995 int monitor_set_cpu(int cpu_index)
997 CPUState *cpu;
999 cpu = qemu_get_cpu(cpu_index);
1000 if (cpu == NULL) {
1001 return -1;
1003 cur_mon->mon_cpu = cpu;
1004 return 0;
1007 CPUState *mon_get_cpu(void)
1009 if (!cur_mon->mon_cpu) {
1010 monitor_set_cpu(0);
1012 cpu_synchronize_state(cur_mon->mon_cpu);
1013 return cur_mon->mon_cpu;
1016 CPUArchState *mon_get_cpu_env(void)
1018 return mon_get_cpu()->env_ptr;
1021 int monitor_get_cpu_index(void)
1023 return mon_get_cpu()->cpu_index;
1026 static void hmp_info_registers(Monitor *mon, const QDict *qdict)
1028 cpu_dump_state(mon_get_cpu(), (FILE *)mon, monitor_fprintf, CPU_DUMP_FPU);
1031 static void hmp_info_jit(Monitor *mon, const QDict *qdict)
1033 dump_exec_info((FILE *)mon, monitor_fprintf);
1034 dump_drift_info((FILE *)mon, monitor_fprintf);
1037 static void hmp_info_opcount(Monitor *mon, const QDict *qdict)
1039 dump_opcount_info((FILE *)mon, monitor_fprintf);
1042 static void hmp_info_history(Monitor *mon, const QDict *qdict)
1044 int i;
1045 const char *str;
1047 if (!mon->rs)
1048 return;
1049 i = 0;
1050 for(;;) {
1051 str = readline_get_history(mon->rs, i);
1052 if (!str)
1053 break;
1054 monitor_printf(mon, "%d: '%s'\n", i, str);
1055 i++;
1059 static void hmp_info_cpustats(Monitor *mon, const QDict *qdict)
1061 cpu_dump_statistics(mon_get_cpu(), (FILE *)mon, &monitor_fprintf, 0);
1064 static void hmp_info_trace_events(Monitor *mon, const QDict *qdict)
1066 TraceEventInfoList *events = qmp_trace_event_get_state("*", NULL);
1067 TraceEventInfoList *elem;
1069 for (elem = events; elem != NULL; elem = elem->next) {
1070 monitor_printf(mon, "%s : state %u\n",
1071 elem->value->name,
1072 elem->value->state == TRACE_EVENT_STATE_ENABLED ? 1 : 0);
1074 qapi_free_TraceEventInfoList(events);
1077 void qmp_client_migrate_info(const char *protocol, const char *hostname,
1078 bool has_port, int64_t port,
1079 bool has_tls_port, int64_t tls_port,
1080 bool has_cert_subject, const char *cert_subject,
1081 Error **errp)
1083 if (strcmp(protocol, "spice") == 0) {
1084 if (!qemu_using_spice(errp)) {
1085 return;
1088 if (!has_port && !has_tls_port) {
1089 error_setg(errp, QERR_MISSING_PARAMETER, "port/tls-port");
1090 return;
1093 if (qemu_spice_migrate_info(hostname,
1094 has_port ? port : -1,
1095 has_tls_port ? tls_port : -1,
1096 cert_subject)) {
1097 error_setg(errp, QERR_UNDEFINED_ERROR);
1098 return;
1100 return;
1103 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "protocol", "spice");
1106 static void hmp_logfile(Monitor *mon, const QDict *qdict)
1108 qemu_set_log_filename(qdict_get_str(qdict, "filename"));
1111 static void hmp_log(Monitor *mon, const QDict *qdict)
1113 int mask;
1114 const char *items = qdict_get_str(qdict, "items");
1116 if (!strcmp(items, "none")) {
1117 mask = 0;
1118 } else {
1119 mask = qemu_str_to_log_mask(items);
1120 if (!mask) {
1121 help_cmd(mon, "log");
1122 return;
1125 qemu_set_log(mask);
1128 static void hmp_singlestep(Monitor *mon, const QDict *qdict)
1130 const char *option = qdict_get_try_str(qdict, "option");
1131 if (!option || !strcmp(option, "on")) {
1132 singlestep = 1;
1133 } else if (!strcmp(option, "off")) {
1134 singlestep = 0;
1135 } else {
1136 monitor_printf(mon, "unexpected option %s\n", option);
1140 static void hmp_gdbserver(Monitor *mon, const QDict *qdict)
1142 const char *device = qdict_get_try_str(qdict, "device");
1143 if (!device)
1144 device = "tcp::" DEFAULT_GDBSTUB_PORT;
1145 if (gdbserver_start(device) < 0) {
1146 monitor_printf(mon, "Could not open gdbserver on device '%s'\n",
1147 device);
1148 } else if (strcmp(device, "none") == 0) {
1149 monitor_printf(mon, "Disabled gdbserver\n");
1150 } else {
1151 monitor_printf(mon, "Waiting for gdb connection on device '%s'\n",
1152 device);
1156 static void hmp_watchdog_action(Monitor *mon, const QDict *qdict)
1158 const char *action = qdict_get_str(qdict, "action");
1159 if (select_watchdog_action(action) == -1) {
1160 monitor_printf(mon, "Unknown watchdog action '%s'\n", action);
1164 static void monitor_printc(Monitor *mon, int c)
1166 monitor_printf(mon, "'");
1167 switch(c) {
1168 case '\'':
1169 monitor_printf(mon, "\\'");
1170 break;
1171 case '\\':
1172 monitor_printf(mon, "\\\\");
1173 break;
1174 case '\n':
1175 monitor_printf(mon, "\\n");
1176 break;
1177 case '\r':
1178 monitor_printf(mon, "\\r");
1179 break;
1180 default:
1181 if (c >= 32 && c <= 126) {
1182 monitor_printf(mon, "%c", c);
1183 } else {
1184 monitor_printf(mon, "\\x%02x", c);
1186 break;
1188 monitor_printf(mon, "'");
1191 static void memory_dump(Monitor *mon, int count, int format, int wsize,
1192 hwaddr addr, int is_physical)
1194 int l, line_size, i, max_digits, len;
1195 uint8_t buf[16];
1196 uint64_t v;
1198 if (format == 'i') {
1199 int flags = 0;
1200 #ifdef TARGET_I386
1201 CPUArchState *env = mon_get_cpu_env();
1202 if (wsize == 2) {
1203 flags = 1;
1204 } else if (wsize == 4) {
1205 flags = 0;
1206 } else {
1207 /* as default we use the current CS size */
1208 flags = 0;
1209 if (env) {
1210 #ifdef TARGET_X86_64
1211 if ((env->efer & MSR_EFER_LMA) &&
1212 (env->segs[R_CS].flags & DESC_L_MASK))
1213 flags = 2;
1214 else
1215 #endif
1216 if (!(env->segs[R_CS].flags & DESC_B_MASK))
1217 flags = 1;
1220 #endif
1221 #ifdef TARGET_PPC
1222 CPUArchState *env = mon_get_cpu_env();
1223 flags = msr_le << 16;
1224 flags |= env->bfd_mach;
1225 #endif
1226 monitor_disas(mon, mon_get_cpu(), addr, count, is_physical, flags);
1227 return;
1230 len = wsize * count;
1231 if (wsize == 1)
1232 line_size = 8;
1233 else
1234 line_size = 16;
1235 max_digits = 0;
1237 switch(format) {
1238 case 'o':
1239 max_digits = (wsize * 8 + 2) / 3;
1240 break;
1241 default:
1242 case 'x':
1243 max_digits = (wsize * 8) / 4;
1244 break;
1245 case 'u':
1246 case 'd':
1247 max_digits = (wsize * 8 * 10 + 32) / 33;
1248 break;
1249 case 'c':
1250 wsize = 1;
1251 break;
1254 while (len > 0) {
1255 if (is_physical)
1256 monitor_printf(mon, TARGET_FMT_plx ":", addr);
1257 else
1258 monitor_printf(mon, TARGET_FMT_lx ":", (target_ulong)addr);
1259 l = len;
1260 if (l > line_size)
1261 l = line_size;
1262 if (is_physical) {
1263 cpu_physical_memory_read(addr, buf, l);
1264 } else {
1265 if (cpu_memory_rw_debug(mon_get_cpu(), addr, buf, l, 0) < 0) {
1266 monitor_printf(mon, " Cannot access memory\n");
1267 break;
1270 i = 0;
1271 while (i < l) {
1272 switch(wsize) {
1273 default:
1274 case 1:
1275 v = ldub_p(buf + i);
1276 break;
1277 case 2:
1278 v = lduw_p(buf + i);
1279 break;
1280 case 4:
1281 v = (uint32_t)ldl_p(buf + i);
1282 break;
1283 case 8:
1284 v = ldq_p(buf + i);
1285 break;
1287 monitor_printf(mon, " ");
1288 switch(format) {
1289 case 'o':
1290 monitor_printf(mon, "%#*" PRIo64, max_digits, v);
1291 break;
1292 case 'x':
1293 monitor_printf(mon, "0x%0*" PRIx64, max_digits, v);
1294 break;
1295 case 'u':
1296 monitor_printf(mon, "%*" PRIu64, max_digits, v);
1297 break;
1298 case 'd':
1299 monitor_printf(mon, "%*" PRId64, max_digits, v);
1300 break;
1301 case 'c':
1302 monitor_printc(mon, v);
1303 break;
1305 i += wsize;
1307 monitor_printf(mon, "\n");
1308 addr += l;
1309 len -= l;
1313 static void hmp_memory_dump(Monitor *mon, const QDict *qdict)
1315 int count = qdict_get_int(qdict, "count");
1316 int format = qdict_get_int(qdict, "format");
1317 int size = qdict_get_int(qdict, "size");
1318 target_long addr = qdict_get_int(qdict, "addr");
1320 memory_dump(mon, count, format, size, addr, 0);
1323 static void hmp_physical_memory_dump(Monitor *mon, const QDict *qdict)
1325 int count = qdict_get_int(qdict, "count");
1326 int format = qdict_get_int(qdict, "format");
1327 int size = qdict_get_int(qdict, "size");
1328 hwaddr addr = qdict_get_int(qdict, "addr");
1330 memory_dump(mon, count, format, size, addr, 1);
1333 static void do_print(Monitor *mon, const QDict *qdict)
1335 int format = qdict_get_int(qdict, "format");
1336 hwaddr val = qdict_get_int(qdict, "val");
1338 switch(format) {
1339 case 'o':
1340 monitor_printf(mon, "%#" HWADDR_PRIo, val);
1341 break;
1342 case 'x':
1343 monitor_printf(mon, "%#" HWADDR_PRIx, val);
1344 break;
1345 case 'u':
1346 monitor_printf(mon, "%" HWADDR_PRIu, val);
1347 break;
1348 default:
1349 case 'd':
1350 monitor_printf(mon, "%" HWADDR_PRId, val);
1351 break;
1352 case 'c':
1353 monitor_printc(mon, val);
1354 break;
1356 monitor_printf(mon, "\n");
1359 static void hmp_sum(Monitor *mon, const QDict *qdict)
1361 uint32_t addr;
1362 uint16_t sum;
1363 uint32_t start = qdict_get_int(qdict, "start");
1364 uint32_t size = qdict_get_int(qdict, "size");
1366 sum = 0;
1367 for(addr = start; addr < (start + size); addr++) {
1368 uint8_t val = address_space_ldub(&address_space_memory, addr,
1369 MEMTXATTRS_UNSPECIFIED, NULL);
1370 /* BSD sum algorithm ('sum' Unix command) */
1371 sum = (sum >> 1) | (sum << 15);
1372 sum += val;
1374 monitor_printf(mon, "%05d\n", sum);
1377 static int mouse_button_state;
1379 static void hmp_mouse_move(Monitor *mon, const QDict *qdict)
1381 int dx, dy, dz, button;
1382 const char *dx_str = qdict_get_str(qdict, "dx_str");
1383 const char *dy_str = qdict_get_str(qdict, "dy_str");
1384 const char *dz_str = qdict_get_try_str(qdict, "dz_str");
1386 dx = strtol(dx_str, NULL, 0);
1387 dy = strtol(dy_str, NULL, 0);
1388 qemu_input_queue_rel(NULL, INPUT_AXIS_X, dx);
1389 qemu_input_queue_rel(NULL, INPUT_AXIS_Y, dy);
1391 if (dz_str) {
1392 dz = strtol(dz_str, NULL, 0);
1393 if (dz != 0) {
1394 button = (dz > 0) ? INPUT_BUTTON_WHEEL_UP : INPUT_BUTTON_WHEEL_DOWN;
1395 qemu_input_queue_btn(NULL, button, true);
1396 qemu_input_event_sync();
1397 qemu_input_queue_btn(NULL, button, false);
1400 qemu_input_event_sync();
1403 static void hmp_mouse_button(Monitor *mon, const QDict *qdict)
1405 static uint32_t bmap[INPUT_BUTTON__MAX] = {
1406 [INPUT_BUTTON_LEFT] = MOUSE_EVENT_LBUTTON,
1407 [INPUT_BUTTON_MIDDLE] = MOUSE_EVENT_MBUTTON,
1408 [INPUT_BUTTON_RIGHT] = MOUSE_EVENT_RBUTTON,
1410 int button_state = qdict_get_int(qdict, "button_state");
1412 if (mouse_button_state == button_state) {
1413 return;
1415 qemu_input_update_buttons(NULL, bmap, mouse_button_state, button_state);
1416 qemu_input_event_sync();
1417 mouse_button_state = button_state;
1420 static void hmp_ioport_read(Monitor *mon, const QDict *qdict)
1422 int size = qdict_get_int(qdict, "size");
1423 int addr = qdict_get_int(qdict, "addr");
1424 int has_index = qdict_haskey(qdict, "index");
1425 uint32_t val;
1426 int suffix;
1428 if (has_index) {
1429 int index = qdict_get_int(qdict, "index");
1430 cpu_outb(addr & IOPORTS_MASK, index & 0xff);
1431 addr++;
1433 addr &= 0xffff;
1435 switch(size) {
1436 default:
1437 case 1:
1438 val = cpu_inb(addr);
1439 suffix = 'b';
1440 break;
1441 case 2:
1442 val = cpu_inw(addr);
1443 suffix = 'w';
1444 break;
1445 case 4:
1446 val = cpu_inl(addr);
1447 suffix = 'l';
1448 break;
1450 monitor_printf(mon, "port%c[0x%04x] = %#0*x\n",
1451 suffix, addr, size * 2, val);
1454 static void hmp_ioport_write(Monitor *mon, const QDict *qdict)
1456 int size = qdict_get_int(qdict, "size");
1457 int addr = qdict_get_int(qdict, "addr");
1458 int val = qdict_get_int(qdict, "val");
1460 addr &= IOPORTS_MASK;
1462 switch (size) {
1463 default:
1464 case 1:
1465 cpu_outb(addr, val);
1466 break;
1467 case 2:
1468 cpu_outw(addr, val);
1469 break;
1470 case 4:
1471 cpu_outl(addr, val);
1472 break;
1476 static void hmp_boot_set(Monitor *mon, const QDict *qdict)
1478 Error *local_err = NULL;
1479 const char *bootdevice = qdict_get_str(qdict, "bootdevice");
1481 qemu_boot_set(bootdevice, &local_err);
1482 if (local_err) {
1483 error_report_err(local_err);
1484 } else {
1485 monitor_printf(mon, "boot device list now set to %s\n", bootdevice);
1489 static void hmp_info_mtree(Monitor *mon, const QDict *qdict)
1491 mtree_info((fprintf_function)monitor_printf, mon);
1494 static void hmp_info_numa(Monitor *mon, const QDict *qdict)
1496 int i;
1497 CPUState *cpu;
1498 uint64_t *node_mem;
1500 node_mem = g_new0(uint64_t, nb_numa_nodes);
1501 query_numa_node_mem(node_mem);
1502 monitor_printf(mon, "%d nodes\n", nb_numa_nodes);
1503 for (i = 0; i < nb_numa_nodes; i++) {
1504 monitor_printf(mon, "node %d cpus:", i);
1505 CPU_FOREACH(cpu) {
1506 if (cpu->numa_node == i) {
1507 monitor_printf(mon, " %d", cpu->cpu_index);
1510 monitor_printf(mon, "\n");
1511 monitor_printf(mon, "node %d size: %" PRId64 " MB\n", i,
1512 node_mem[i] >> 20);
1514 g_free(node_mem);
1517 #ifdef CONFIG_PROFILER
1519 int64_t tcg_time;
1520 int64_t dev_time;
1522 static void hmp_info_profile(Monitor *mon, const QDict *qdict)
1524 monitor_printf(mon, "async time %" PRId64 " (%0.3f)\n",
1525 dev_time, dev_time / (double)get_ticks_per_sec());
1526 monitor_printf(mon, "qemu time %" PRId64 " (%0.3f)\n",
1527 tcg_time, tcg_time / (double)get_ticks_per_sec());
1528 tcg_time = 0;
1529 dev_time = 0;
1531 #else
1532 static void hmp_info_profile(Monitor *mon, const QDict *qdict)
1534 monitor_printf(mon, "Internal profiler not compiled\n");
1536 #endif
1538 /* Capture support */
1539 static QLIST_HEAD (capture_list_head, CaptureState) capture_head;
1541 static void hmp_info_capture(Monitor *mon, const QDict *qdict)
1543 int i;
1544 CaptureState *s;
1546 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
1547 monitor_printf(mon, "[%d]: ", i);
1548 s->ops.info (s->opaque);
1552 static void hmp_stopcapture(Monitor *mon, const QDict *qdict)
1554 int i;
1555 int n = qdict_get_int(qdict, "n");
1556 CaptureState *s;
1558 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
1559 if (i == n) {
1560 s->ops.destroy (s->opaque);
1561 QLIST_REMOVE (s, entries);
1562 g_free (s);
1563 return;
1568 static void hmp_wavcapture(Monitor *mon, const QDict *qdict)
1570 const char *path = qdict_get_str(qdict, "path");
1571 int has_freq = qdict_haskey(qdict, "freq");
1572 int freq = qdict_get_try_int(qdict, "freq", -1);
1573 int has_bits = qdict_haskey(qdict, "bits");
1574 int bits = qdict_get_try_int(qdict, "bits", -1);
1575 int has_channels = qdict_haskey(qdict, "nchannels");
1576 int nchannels = qdict_get_try_int(qdict, "nchannels", -1);
1577 CaptureState *s;
1579 s = g_malloc0 (sizeof (*s));
1581 freq = has_freq ? freq : 44100;
1582 bits = has_bits ? bits : 16;
1583 nchannels = has_channels ? nchannels : 2;
1585 if (wav_start_capture (s, path, freq, bits, nchannels)) {
1586 monitor_printf(mon, "Failed to add wave capture\n");
1587 g_free (s);
1588 return;
1590 QLIST_INSERT_HEAD (&capture_head, s, entries);
1593 static qemu_acl *find_acl(Monitor *mon, const char *name)
1595 qemu_acl *acl = qemu_acl_find(name);
1597 if (!acl) {
1598 monitor_printf(mon, "acl: unknown list '%s'\n", name);
1600 return acl;
1603 static void hmp_acl_show(Monitor *mon, const QDict *qdict)
1605 const char *aclname = qdict_get_str(qdict, "aclname");
1606 qemu_acl *acl = find_acl(mon, aclname);
1607 qemu_acl_entry *entry;
1608 int i = 0;
1610 if (acl) {
1611 monitor_printf(mon, "policy: %s\n",
1612 acl->defaultDeny ? "deny" : "allow");
1613 QTAILQ_FOREACH(entry, &acl->entries, next) {
1614 i++;
1615 monitor_printf(mon, "%d: %s %s\n", i,
1616 entry->deny ? "deny" : "allow", entry->match);
1621 static void hmp_acl_reset(Monitor *mon, const QDict *qdict)
1623 const char *aclname = qdict_get_str(qdict, "aclname");
1624 qemu_acl *acl = find_acl(mon, aclname);
1626 if (acl) {
1627 qemu_acl_reset(acl);
1628 monitor_printf(mon, "acl: removed all rules\n");
1632 static void hmp_acl_policy(Monitor *mon, const QDict *qdict)
1634 const char *aclname = qdict_get_str(qdict, "aclname");
1635 const char *policy = qdict_get_str(qdict, "policy");
1636 qemu_acl *acl = find_acl(mon, aclname);
1638 if (acl) {
1639 if (strcmp(policy, "allow") == 0) {
1640 acl->defaultDeny = 0;
1641 monitor_printf(mon, "acl: policy set to 'allow'\n");
1642 } else if (strcmp(policy, "deny") == 0) {
1643 acl->defaultDeny = 1;
1644 monitor_printf(mon, "acl: policy set to 'deny'\n");
1645 } else {
1646 monitor_printf(mon, "acl: unknown policy '%s', "
1647 "expected 'deny' or 'allow'\n", policy);
1652 static void hmp_acl_add(Monitor *mon, const QDict *qdict)
1654 const char *aclname = qdict_get_str(qdict, "aclname");
1655 const char *match = qdict_get_str(qdict, "match");
1656 const char *policy = qdict_get_str(qdict, "policy");
1657 int has_index = qdict_haskey(qdict, "index");
1658 int index = qdict_get_try_int(qdict, "index", -1);
1659 qemu_acl *acl = find_acl(mon, aclname);
1660 int deny, ret;
1662 if (acl) {
1663 if (strcmp(policy, "allow") == 0) {
1664 deny = 0;
1665 } else if (strcmp(policy, "deny") == 0) {
1666 deny = 1;
1667 } else {
1668 monitor_printf(mon, "acl: unknown policy '%s', "
1669 "expected 'deny' or 'allow'\n", policy);
1670 return;
1672 if (has_index)
1673 ret = qemu_acl_insert(acl, deny, match, index);
1674 else
1675 ret = qemu_acl_append(acl, deny, match);
1676 if (ret < 0)
1677 monitor_printf(mon, "acl: unable to add acl entry\n");
1678 else
1679 monitor_printf(mon, "acl: added rule at position %d\n", ret);
1683 static void hmp_acl_remove(Monitor *mon, const QDict *qdict)
1685 const char *aclname = qdict_get_str(qdict, "aclname");
1686 const char *match = qdict_get_str(qdict, "match");
1687 qemu_acl *acl = find_acl(mon, aclname);
1688 int ret;
1690 if (acl) {
1691 ret = qemu_acl_remove(acl, match);
1692 if (ret < 0)
1693 monitor_printf(mon, "acl: no matching acl entry\n");
1694 else
1695 monitor_printf(mon, "acl: removed rule at position %d\n", ret);
1699 void qmp_getfd(const char *fdname, Error **errp)
1701 mon_fd_t *monfd;
1702 int fd;
1704 fd = qemu_chr_fe_get_msgfd(cur_mon->chr);
1705 if (fd == -1) {
1706 error_setg(errp, QERR_FD_NOT_SUPPLIED);
1707 return;
1710 if (qemu_isdigit(fdname[0])) {
1711 close(fd);
1712 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "fdname",
1713 "a name not starting with a digit");
1714 return;
1717 QLIST_FOREACH(monfd, &cur_mon->fds, next) {
1718 if (strcmp(monfd->name, fdname) != 0) {
1719 continue;
1722 close(monfd->fd);
1723 monfd->fd = fd;
1724 return;
1727 monfd = g_malloc0(sizeof(mon_fd_t));
1728 monfd->name = g_strdup(fdname);
1729 monfd->fd = fd;
1731 QLIST_INSERT_HEAD(&cur_mon->fds, monfd, next);
1734 void qmp_closefd(const char *fdname, Error **errp)
1736 mon_fd_t *monfd;
1738 QLIST_FOREACH(monfd, &cur_mon->fds, next) {
1739 if (strcmp(monfd->name, fdname) != 0) {
1740 continue;
1743 QLIST_REMOVE(monfd, next);
1744 close(monfd->fd);
1745 g_free(monfd->name);
1746 g_free(monfd);
1747 return;
1750 error_setg(errp, QERR_FD_NOT_FOUND, fdname);
1753 static void hmp_loadvm(Monitor *mon, const QDict *qdict)
1755 int saved_vm_running = runstate_is_running();
1756 const char *name = qdict_get_str(qdict, "name");
1758 vm_stop(RUN_STATE_RESTORE_VM);
1760 if (load_vmstate(name) == 0 && saved_vm_running) {
1761 vm_start();
1765 int monitor_get_fd(Monitor *mon, const char *fdname, Error **errp)
1767 mon_fd_t *monfd;
1769 QLIST_FOREACH(monfd, &mon->fds, next) {
1770 int fd;
1772 if (strcmp(monfd->name, fdname) != 0) {
1773 continue;
1776 fd = monfd->fd;
1778 /* caller takes ownership of fd */
1779 QLIST_REMOVE(monfd, next);
1780 g_free(monfd->name);
1781 g_free(monfd);
1783 return fd;
1786 error_setg(errp, "File descriptor named '%s' has not been found", fdname);
1787 return -1;
1790 static void monitor_fdset_cleanup(MonFdset *mon_fdset)
1792 MonFdsetFd *mon_fdset_fd;
1793 MonFdsetFd *mon_fdset_fd_next;
1795 QLIST_FOREACH_SAFE(mon_fdset_fd, &mon_fdset->fds, next, mon_fdset_fd_next) {
1796 if ((mon_fdset_fd->removed ||
1797 (QLIST_EMPTY(&mon_fdset->dup_fds) && mon_refcount == 0)) &&
1798 runstate_is_running()) {
1799 close(mon_fdset_fd->fd);
1800 g_free(mon_fdset_fd->opaque);
1801 QLIST_REMOVE(mon_fdset_fd, next);
1802 g_free(mon_fdset_fd);
1806 if (QLIST_EMPTY(&mon_fdset->fds) && QLIST_EMPTY(&mon_fdset->dup_fds)) {
1807 QLIST_REMOVE(mon_fdset, next);
1808 g_free(mon_fdset);
1812 static void monitor_fdsets_cleanup(void)
1814 MonFdset *mon_fdset;
1815 MonFdset *mon_fdset_next;
1817 QLIST_FOREACH_SAFE(mon_fdset, &mon_fdsets, next, mon_fdset_next) {
1818 monitor_fdset_cleanup(mon_fdset);
1822 AddfdInfo *qmp_add_fd(bool has_fdset_id, int64_t fdset_id, bool has_opaque,
1823 const char *opaque, Error **errp)
1825 int fd;
1826 Monitor *mon = cur_mon;
1827 AddfdInfo *fdinfo;
1829 fd = qemu_chr_fe_get_msgfd(mon->chr);
1830 if (fd == -1) {
1831 error_setg(errp, QERR_FD_NOT_SUPPLIED);
1832 goto error;
1835 fdinfo = monitor_fdset_add_fd(fd, has_fdset_id, fdset_id,
1836 has_opaque, opaque, errp);
1837 if (fdinfo) {
1838 return fdinfo;
1841 error:
1842 if (fd != -1) {
1843 close(fd);
1845 return NULL;
1848 void qmp_remove_fd(int64_t fdset_id, bool has_fd, int64_t fd, Error **errp)
1850 MonFdset *mon_fdset;
1851 MonFdsetFd *mon_fdset_fd;
1852 char fd_str[60];
1854 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
1855 if (mon_fdset->id != fdset_id) {
1856 continue;
1858 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
1859 if (has_fd) {
1860 if (mon_fdset_fd->fd != fd) {
1861 continue;
1863 mon_fdset_fd->removed = true;
1864 break;
1865 } else {
1866 mon_fdset_fd->removed = true;
1869 if (has_fd && !mon_fdset_fd) {
1870 goto error;
1872 monitor_fdset_cleanup(mon_fdset);
1873 return;
1876 error:
1877 if (has_fd) {
1878 snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64 ", fd:%" PRId64,
1879 fdset_id, fd);
1880 } else {
1881 snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64, fdset_id);
1883 error_setg(errp, QERR_FD_NOT_FOUND, fd_str);
1886 FdsetInfoList *qmp_query_fdsets(Error **errp)
1888 MonFdset *mon_fdset;
1889 MonFdsetFd *mon_fdset_fd;
1890 FdsetInfoList *fdset_list = NULL;
1892 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
1893 FdsetInfoList *fdset_info = g_malloc0(sizeof(*fdset_info));
1894 FdsetFdInfoList *fdsetfd_list = NULL;
1896 fdset_info->value = g_malloc0(sizeof(*fdset_info->value));
1897 fdset_info->value->fdset_id = mon_fdset->id;
1899 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
1900 FdsetFdInfoList *fdsetfd_info;
1902 fdsetfd_info = g_malloc0(sizeof(*fdsetfd_info));
1903 fdsetfd_info->value = g_malloc0(sizeof(*fdsetfd_info->value));
1904 fdsetfd_info->value->fd = mon_fdset_fd->fd;
1905 if (mon_fdset_fd->opaque) {
1906 fdsetfd_info->value->has_opaque = true;
1907 fdsetfd_info->value->opaque = g_strdup(mon_fdset_fd->opaque);
1908 } else {
1909 fdsetfd_info->value->has_opaque = false;
1912 fdsetfd_info->next = fdsetfd_list;
1913 fdsetfd_list = fdsetfd_info;
1916 fdset_info->value->fds = fdsetfd_list;
1918 fdset_info->next = fdset_list;
1919 fdset_list = fdset_info;
1922 return fdset_list;
1925 AddfdInfo *monitor_fdset_add_fd(int fd, bool has_fdset_id, int64_t fdset_id,
1926 bool has_opaque, const char *opaque,
1927 Error **errp)
1929 MonFdset *mon_fdset = NULL;
1930 MonFdsetFd *mon_fdset_fd;
1931 AddfdInfo *fdinfo;
1933 if (has_fdset_id) {
1934 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
1935 /* Break if match found or match impossible due to ordering by ID */
1936 if (fdset_id <= mon_fdset->id) {
1937 if (fdset_id < mon_fdset->id) {
1938 mon_fdset = NULL;
1940 break;
1945 if (mon_fdset == NULL) {
1946 int64_t fdset_id_prev = -1;
1947 MonFdset *mon_fdset_cur = QLIST_FIRST(&mon_fdsets);
1949 if (has_fdset_id) {
1950 if (fdset_id < 0) {
1951 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "fdset-id",
1952 "a non-negative value");
1953 return NULL;
1955 /* Use specified fdset ID */
1956 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
1957 mon_fdset_cur = mon_fdset;
1958 if (fdset_id < mon_fdset_cur->id) {
1959 break;
1962 } else {
1963 /* Use first available fdset ID */
1964 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
1965 mon_fdset_cur = mon_fdset;
1966 if (fdset_id_prev == mon_fdset_cur->id - 1) {
1967 fdset_id_prev = mon_fdset_cur->id;
1968 continue;
1970 break;
1974 mon_fdset = g_malloc0(sizeof(*mon_fdset));
1975 if (has_fdset_id) {
1976 mon_fdset->id = fdset_id;
1977 } else {
1978 mon_fdset->id = fdset_id_prev + 1;
1981 /* The fdset list is ordered by fdset ID */
1982 if (!mon_fdset_cur) {
1983 QLIST_INSERT_HEAD(&mon_fdsets, mon_fdset, next);
1984 } else if (mon_fdset->id < mon_fdset_cur->id) {
1985 QLIST_INSERT_BEFORE(mon_fdset_cur, mon_fdset, next);
1986 } else {
1987 QLIST_INSERT_AFTER(mon_fdset_cur, mon_fdset, next);
1991 mon_fdset_fd = g_malloc0(sizeof(*mon_fdset_fd));
1992 mon_fdset_fd->fd = fd;
1993 mon_fdset_fd->removed = false;
1994 if (has_opaque) {
1995 mon_fdset_fd->opaque = g_strdup(opaque);
1997 QLIST_INSERT_HEAD(&mon_fdset->fds, mon_fdset_fd, next);
1999 fdinfo = g_malloc0(sizeof(*fdinfo));
2000 fdinfo->fdset_id = mon_fdset->id;
2001 fdinfo->fd = mon_fdset_fd->fd;
2003 return fdinfo;
2006 int monitor_fdset_get_fd(int64_t fdset_id, int flags)
2008 #ifndef _WIN32
2009 MonFdset *mon_fdset;
2010 MonFdsetFd *mon_fdset_fd;
2011 int mon_fd_flags;
2013 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2014 if (mon_fdset->id != fdset_id) {
2015 continue;
2017 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2018 mon_fd_flags = fcntl(mon_fdset_fd->fd, F_GETFL);
2019 if (mon_fd_flags == -1) {
2020 return -1;
2023 if ((flags & O_ACCMODE) == (mon_fd_flags & O_ACCMODE)) {
2024 return mon_fdset_fd->fd;
2027 errno = EACCES;
2028 return -1;
2030 #endif
2032 errno = ENOENT;
2033 return -1;
2036 int monitor_fdset_dup_fd_add(int64_t fdset_id, int dup_fd)
2038 MonFdset *mon_fdset;
2039 MonFdsetFd *mon_fdset_fd_dup;
2041 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2042 if (mon_fdset->id != fdset_id) {
2043 continue;
2045 QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
2046 if (mon_fdset_fd_dup->fd == dup_fd) {
2047 return -1;
2050 mon_fdset_fd_dup = g_malloc0(sizeof(*mon_fdset_fd_dup));
2051 mon_fdset_fd_dup->fd = dup_fd;
2052 QLIST_INSERT_HEAD(&mon_fdset->dup_fds, mon_fdset_fd_dup, next);
2053 return 0;
2055 return -1;
2058 static int monitor_fdset_dup_fd_find_remove(int dup_fd, bool remove)
2060 MonFdset *mon_fdset;
2061 MonFdsetFd *mon_fdset_fd_dup;
2063 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2064 QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
2065 if (mon_fdset_fd_dup->fd == dup_fd) {
2066 if (remove) {
2067 QLIST_REMOVE(mon_fdset_fd_dup, next);
2068 if (QLIST_EMPTY(&mon_fdset->dup_fds)) {
2069 monitor_fdset_cleanup(mon_fdset);
2071 return -1;
2072 } else {
2073 return mon_fdset->id;
2078 return -1;
2081 int monitor_fdset_dup_fd_find(int dup_fd)
2083 return monitor_fdset_dup_fd_find_remove(dup_fd, false);
2086 void monitor_fdset_dup_fd_remove(int dup_fd)
2088 monitor_fdset_dup_fd_find_remove(dup_fd, true);
2091 int monitor_fd_param(Monitor *mon, const char *fdname, Error **errp)
2093 int fd;
2094 Error *local_err = NULL;
2096 if (!qemu_isdigit(fdname[0]) && mon) {
2097 fd = monitor_get_fd(mon, fdname, &local_err);
2098 } else {
2099 fd = qemu_parse_fd(fdname);
2100 if (fd == -1) {
2101 error_setg(&local_err, "Invalid file descriptor number '%s'",
2102 fdname);
2105 if (local_err) {
2106 error_propagate(errp, local_err);
2107 assert(fd == -1);
2108 } else {
2109 assert(fd != -1);
2112 return fd;
2115 /* Please update hmp-commands.hx when adding or changing commands */
2116 static mon_cmd_t info_cmds[] = {
2117 #include "hmp-commands-info.h"
2118 { NULL, NULL, },
2121 /* mon_cmds and info_cmds would be sorted at runtime */
2122 static mon_cmd_t mon_cmds[] = {
2123 #include "hmp-commands.h"
2124 { NULL, NULL, },
2127 static const mon_cmd_t qmp_cmds[] = {
2128 #include "qmp-commands-old.h"
2129 { /* NULL */ },
2132 /*******************************************************************/
2134 static const char *pch;
2135 static sigjmp_buf expr_env;
2138 static void GCC_FMT_ATTR(2, 3) QEMU_NORETURN
2139 expr_error(Monitor *mon, const char *fmt, ...)
2141 va_list ap;
2142 va_start(ap, fmt);
2143 monitor_vprintf(mon, fmt, ap);
2144 monitor_printf(mon, "\n");
2145 va_end(ap);
2146 siglongjmp(expr_env, 1);
2149 /* return 0 if OK, -1 if not found */
2150 static int get_monitor_def(target_long *pval, const char *name)
2152 const MonitorDef *md = target_monitor_defs();
2153 void *ptr;
2154 uint64_t tmp = 0;
2155 int ret;
2157 if (md == NULL) {
2158 return -1;
2161 for(; md->name != NULL; md++) {
2162 if (compare_cmd(name, md->name)) {
2163 if (md->get_value) {
2164 *pval = md->get_value(md, md->offset);
2165 } else {
2166 CPUArchState *env = mon_get_cpu_env();
2167 ptr = (uint8_t *)env + md->offset;
2168 switch(md->type) {
2169 case MD_I32:
2170 *pval = *(int32_t *)ptr;
2171 break;
2172 case MD_TLONG:
2173 *pval = *(target_long *)ptr;
2174 break;
2175 default:
2176 *pval = 0;
2177 break;
2180 return 0;
2184 ret = target_get_monitor_def(mon_get_cpu(), name, &tmp);
2185 if (!ret) {
2186 *pval = (target_long) tmp;
2189 return ret;
2192 static void next(void)
2194 if (*pch != '\0') {
2195 pch++;
2196 while (qemu_isspace(*pch))
2197 pch++;
2201 static int64_t expr_sum(Monitor *mon);
2203 static int64_t expr_unary(Monitor *mon)
2205 int64_t n;
2206 char *p;
2207 int ret;
2209 switch(*pch) {
2210 case '+':
2211 next();
2212 n = expr_unary(mon);
2213 break;
2214 case '-':
2215 next();
2216 n = -expr_unary(mon);
2217 break;
2218 case '~':
2219 next();
2220 n = ~expr_unary(mon);
2221 break;
2222 case '(':
2223 next();
2224 n = expr_sum(mon);
2225 if (*pch != ')') {
2226 expr_error(mon, "')' expected");
2228 next();
2229 break;
2230 case '\'':
2231 pch++;
2232 if (*pch == '\0')
2233 expr_error(mon, "character constant expected");
2234 n = *pch;
2235 pch++;
2236 if (*pch != '\'')
2237 expr_error(mon, "missing terminating \' character");
2238 next();
2239 break;
2240 case '$':
2242 char buf[128], *q;
2243 target_long reg=0;
2245 pch++;
2246 q = buf;
2247 while ((*pch >= 'a' && *pch <= 'z') ||
2248 (*pch >= 'A' && *pch <= 'Z') ||
2249 (*pch >= '0' && *pch <= '9') ||
2250 *pch == '_' || *pch == '.') {
2251 if ((q - buf) < sizeof(buf) - 1)
2252 *q++ = *pch;
2253 pch++;
2255 while (qemu_isspace(*pch))
2256 pch++;
2257 *q = 0;
2258 ret = get_monitor_def(&reg, buf);
2259 if (ret < 0)
2260 expr_error(mon, "unknown register");
2261 n = reg;
2263 break;
2264 case '\0':
2265 expr_error(mon, "unexpected end of expression");
2266 n = 0;
2267 break;
2268 default:
2269 errno = 0;
2270 n = strtoull(pch, &p, 0);
2271 if (errno == ERANGE) {
2272 expr_error(mon, "number too large");
2274 if (pch == p) {
2275 expr_error(mon, "invalid char '%c' in expression", *p);
2277 pch = p;
2278 while (qemu_isspace(*pch))
2279 pch++;
2280 break;
2282 return n;
2286 static int64_t expr_prod(Monitor *mon)
2288 int64_t val, val2;
2289 int op;
2291 val = expr_unary(mon);
2292 for(;;) {
2293 op = *pch;
2294 if (op != '*' && op != '/' && op != '%')
2295 break;
2296 next();
2297 val2 = expr_unary(mon);
2298 switch(op) {
2299 default:
2300 case '*':
2301 val *= val2;
2302 break;
2303 case '/':
2304 case '%':
2305 if (val2 == 0)
2306 expr_error(mon, "division by zero");
2307 if (op == '/')
2308 val /= val2;
2309 else
2310 val %= val2;
2311 break;
2314 return val;
2317 static int64_t expr_logic(Monitor *mon)
2319 int64_t val, val2;
2320 int op;
2322 val = expr_prod(mon);
2323 for(;;) {
2324 op = *pch;
2325 if (op != '&' && op != '|' && op != '^')
2326 break;
2327 next();
2328 val2 = expr_prod(mon);
2329 switch(op) {
2330 default:
2331 case '&':
2332 val &= val2;
2333 break;
2334 case '|':
2335 val |= val2;
2336 break;
2337 case '^':
2338 val ^= val2;
2339 break;
2342 return val;
2345 static int64_t expr_sum(Monitor *mon)
2347 int64_t val, val2;
2348 int op;
2350 val = expr_logic(mon);
2351 for(;;) {
2352 op = *pch;
2353 if (op != '+' && op != '-')
2354 break;
2355 next();
2356 val2 = expr_logic(mon);
2357 if (op == '+')
2358 val += val2;
2359 else
2360 val -= val2;
2362 return val;
2365 static int get_expr(Monitor *mon, int64_t *pval, const char **pp)
2367 pch = *pp;
2368 if (sigsetjmp(expr_env, 0)) {
2369 *pp = pch;
2370 return -1;
2372 while (qemu_isspace(*pch))
2373 pch++;
2374 *pval = expr_sum(mon);
2375 *pp = pch;
2376 return 0;
2379 static int get_double(Monitor *mon, double *pval, const char **pp)
2381 const char *p = *pp;
2382 char *tailp;
2383 double d;
2385 d = strtod(p, &tailp);
2386 if (tailp == p) {
2387 monitor_printf(mon, "Number expected\n");
2388 return -1;
2390 if (d != d || d - d != 0) {
2391 /* NaN or infinity */
2392 monitor_printf(mon, "Bad number\n");
2393 return -1;
2395 *pval = d;
2396 *pp = tailp;
2397 return 0;
2401 * Store the command-name in cmdname, and return a pointer to
2402 * the remaining of the command string.
2404 static const char *get_command_name(const char *cmdline,
2405 char *cmdname, size_t nlen)
2407 size_t len;
2408 const char *p, *pstart;
2410 p = cmdline;
2411 while (qemu_isspace(*p))
2412 p++;
2413 if (*p == '\0')
2414 return NULL;
2415 pstart = p;
2416 while (*p != '\0' && *p != '/' && !qemu_isspace(*p))
2417 p++;
2418 len = p - pstart;
2419 if (len > nlen - 1)
2420 len = nlen - 1;
2421 memcpy(cmdname, pstart, len);
2422 cmdname[len] = '\0';
2423 return p;
2427 * Read key of 'type' into 'key' and return the current
2428 * 'type' pointer.
2430 static char *key_get_info(const char *type, char **key)
2432 size_t len;
2433 char *p, *str;
2435 if (*type == ',')
2436 type++;
2438 p = strchr(type, ':');
2439 if (!p) {
2440 *key = NULL;
2441 return NULL;
2443 len = p - type;
2445 str = g_malloc(len + 1);
2446 memcpy(str, type, len);
2447 str[len] = '\0';
2449 *key = str;
2450 return ++p;
2453 static int default_fmt_format = 'x';
2454 static int default_fmt_size = 4;
2456 static int is_valid_option(const char *c, const char *typestr)
2458 char option[3];
2460 option[0] = '-';
2461 option[1] = *c;
2462 option[2] = '\0';
2464 typestr = strstr(typestr, option);
2465 return (typestr != NULL);
2468 static const mon_cmd_t *search_dispatch_table(const mon_cmd_t *disp_table,
2469 const char *cmdname)
2471 const mon_cmd_t *cmd;
2473 for (cmd = disp_table; cmd->name != NULL; cmd++) {
2474 if (compare_cmd(cmdname, cmd->name)) {
2475 return cmd;
2479 return NULL;
2482 static const mon_cmd_t *qmp_find_cmd(const char *cmdname)
2484 return search_dispatch_table(qmp_cmds, cmdname);
2488 * Parse command name from @cmdp according to command table @table.
2489 * If blank, return NULL.
2490 * Else, if no valid command can be found, report to @mon, and return
2491 * NULL.
2492 * Else, change @cmdp to point right behind the name, and return its
2493 * command table entry.
2494 * Do not assume the return value points into @table! It doesn't when
2495 * the command is found in a sub-command table.
2497 static const mon_cmd_t *monitor_parse_command(Monitor *mon,
2498 const char **cmdp,
2499 mon_cmd_t *table)
2501 const char *p;
2502 const mon_cmd_t *cmd;
2503 char cmdname[256];
2505 /* extract the command name */
2506 p = get_command_name(*cmdp, cmdname, sizeof(cmdname));
2507 if (!p)
2508 return NULL;
2510 cmd = search_dispatch_table(table, cmdname);
2511 if (!cmd) {
2512 monitor_printf(mon, "unknown command: '%.*s'\n",
2513 (int)(p - *cmdp), *cmdp);
2514 return NULL;
2517 /* filter out following useless space */
2518 while (qemu_isspace(*p)) {
2519 p++;
2522 *cmdp = p;
2523 /* search sub command */
2524 if (cmd->sub_table != NULL && *p != '\0') {
2525 return monitor_parse_command(mon, cmdp, cmd->sub_table);
2528 return cmd;
2532 * Parse arguments for @cmd.
2533 * If it can't be parsed, report to @mon, and return NULL.
2534 * Else, insert command arguments into a QDict, and return it.
2535 * Note: On success, caller has to free the QDict structure.
2538 static QDict *monitor_parse_arguments(Monitor *mon,
2539 const char **endp,
2540 const mon_cmd_t *cmd)
2542 const char *typestr;
2543 char *key;
2544 int c;
2545 const char *p = *endp;
2546 char buf[1024];
2547 QDict *qdict = qdict_new();
2549 /* parse the parameters */
2550 typestr = cmd->args_type;
2551 for(;;) {
2552 typestr = key_get_info(typestr, &key);
2553 if (!typestr)
2554 break;
2555 c = *typestr;
2556 typestr++;
2557 switch(c) {
2558 case 'F':
2559 case 'B':
2560 case 's':
2562 int ret;
2564 while (qemu_isspace(*p))
2565 p++;
2566 if (*typestr == '?') {
2567 typestr++;
2568 if (*p == '\0') {
2569 /* no optional string: NULL argument */
2570 break;
2573 ret = get_str(buf, sizeof(buf), &p);
2574 if (ret < 0) {
2575 switch(c) {
2576 case 'F':
2577 monitor_printf(mon, "%s: filename expected\n",
2578 cmd->name);
2579 break;
2580 case 'B':
2581 monitor_printf(mon, "%s: block device name expected\n",
2582 cmd->name);
2583 break;
2584 default:
2585 monitor_printf(mon, "%s: string expected\n", cmd->name);
2586 break;
2588 goto fail;
2590 qdict_put(qdict, key, qstring_from_str(buf));
2592 break;
2593 case 'O':
2595 QemuOptsList *opts_list;
2596 QemuOpts *opts;
2598 opts_list = qemu_find_opts(key);
2599 if (!opts_list || opts_list->desc->name) {
2600 goto bad_type;
2602 while (qemu_isspace(*p)) {
2603 p++;
2605 if (!*p)
2606 break;
2607 if (get_str(buf, sizeof(buf), &p) < 0) {
2608 goto fail;
2610 opts = qemu_opts_parse_noisily(opts_list, buf, true);
2611 if (!opts) {
2612 goto fail;
2614 qemu_opts_to_qdict(opts, qdict);
2615 qemu_opts_del(opts);
2617 break;
2618 case '/':
2620 int count, format, size;
2622 while (qemu_isspace(*p))
2623 p++;
2624 if (*p == '/') {
2625 /* format found */
2626 p++;
2627 count = 1;
2628 if (qemu_isdigit(*p)) {
2629 count = 0;
2630 while (qemu_isdigit(*p)) {
2631 count = count * 10 + (*p - '0');
2632 p++;
2635 size = -1;
2636 format = -1;
2637 for(;;) {
2638 switch(*p) {
2639 case 'o':
2640 case 'd':
2641 case 'u':
2642 case 'x':
2643 case 'i':
2644 case 'c':
2645 format = *p++;
2646 break;
2647 case 'b':
2648 size = 1;
2649 p++;
2650 break;
2651 case 'h':
2652 size = 2;
2653 p++;
2654 break;
2655 case 'w':
2656 size = 4;
2657 p++;
2658 break;
2659 case 'g':
2660 case 'L':
2661 size = 8;
2662 p++;
2663 break;
2664 default:
2665 goto next;
2668 next:
2669 if (*p != '\0' && !qemu_isspace(*p)) {
2670 monitor_printf(mon, "invalid char in format: '%c'\n",
2671 *p);
2672 goto fail;
2674 if (format < 0)
2675 format = default_fmt_format;
2676 if (format != 'i') {
2677 /* for 'i', not specifying a size gives -1 as size */
2678 if (size < 0)
2679 size = default_fmt_size;
2680 default_fmt_size = size;
2682 default_fmt_format = format;
2683 } else {
2684 count = 1;
2685 format = default_fmt_format;
2686 if (format != 'i') {
2687 size = default_fmt_size;
2688 } else {
2689 size = -1;
2692 qdict_put(qdict, "count", qint_from_int(count));
2693 qdict_put(qdict, "format", qint_from_int(format));
2694 qdict_put(qdict, "size", qint_from_int(size));
2696 break;
2697 case 'i':
2698 case 'l':
2699 case 'M':
2701 int64_t val;
2703 while (qemu_isspace(*p))
2704 p++;
2705 if (*typestr == '?' || *typestr == '.') {
2706 if (*typestr == '?') {
2707 if (*p == '\0') {
2708 typestr++;
2709 break;
2711 } else {
2712 if (*p == '.') {
2713 p++;
2714 while (qemu_isspace(*p))
2715 p++;
2716 } else {
2717 typestr++;
2718 break;
2721 typestr++;
2723 if (get_expr(mon, &val, &p))
2724 goto fail;
2725 /* Check if 'i' is greater than 32-bit */
2726 if ((c == 'i') && ((val >> 32) & 0xffffffff)) {
2727 monitor_printf(mon, "\'%s\' has failed: ", cmd->name);
2728 monitor_printf(mon, "integer is for 32-bit values\n");
2729 goto fail;
2730 } else if (c == 'M') {
2731 if (val < 0) {
2732 monitor_printf(mon, "enter a positive value\n");
2733 goto fail;
2735 val <<= 20;
2737 qdict_put(qdict, key, qint_from_int(val));
2739 break;
2740 case 'o':
2742 int64_t val;
2743 char *end;
2745 while (qemu_isspace(*p)) {
2746 p++;
2748 if (*typestr == '?') {
2749 typestr++;
2750 if (*p == '\0') {
2751 break;
2754 val = qemu_strtosz(p, &end);
2755 if (val < 0) {
2756 monitor_printf(mon, "invalid size\n");
2757 goto fail;
2759 qdict_put(qdict, key, qint_from_int(val));
2760 p = end;
2762 break;
2763 case 'T':
2765 double val;
2767 while (qemu_isspace(*p))
2768 p++;
2769 if (*typestr == '?') {
2770 typestr++;
2771 if (*p == '\0') {
2772 break;
2775 if (get_double(mon, &val, &p) < 0) {
2776 goto fail;
2778 if (p[0] && p[1] == 's') {
2779 switch (*p) {
2780 case 'm':
2781 val /= 1e3; p += 2; break;
2782 case 'u':
2783 val /= 1e6; p += 2; break;
2784 case 'n':
2785 val /= 1e9; p += 2; break;
2788 if (*p && !qemu_isspace(*p)) {
2789 monitor_printf(mon, "Unknown unit suffix\n");
2790 goto fail;
2792 qdict_put(qdict, key, qfloat_from_double(val));
2794 break;
2795 case 'b':
2797 const char *beg;
2798 bool val;
2800 while (qemu_isspace(*p)) {
2801 p++;
2803 beg = p;
2804 while (qemu_isgraph(*p)) {
2805 p++;
2807 if (p - beg == 2 && !memcmp(beg, "on", p - beg)) {
2808 val = true;
2809 } else if (p - beg == 3 && !memcmp(beg, "off", p - beg)) {
2810 val = false;
2811 } else {
2812 monitor_printf(mon, "Expected 'on' or 'off'\n");
2813 goto fail;
2815 qdict_put(qdict, key, qbool_from_bool(val));
2817 break;
2818 case '-':
2820 const char *tmp = p;
2821 int skip_key = 0;
2822 /* option */
2824 c = *typestr++;
2825 if (c == '\0')
2826 goto bad_type;
2827 while (qemu_isspace(*p))
2828 p++;
2829 if (*p == '-') {
2830 p++;
2831 if(c != *p) {
2832 if(!is_valid_option(p, typestr)) {
2834 monitor_printf(mon, "%s: unsupported option -%c\n",
2835 cmd->name, *p);
2836 goto fail;
2837 } else {
2838 skip_key = 1;
2841 if(skip_key) {
2842 p = tmp;
2843 } else {
2844 /* has option */
2845 p++;
2846 qdict_put(qdict, key, qbool_from_bool(true));
2850 break;
2851 case 'S':
2853 /* package all remaining string */
2854 int len;
2856 while (qemu_isspace(*p)) {
2857 p++;
2859 if (*typestr == '?') {
2860 typestr++;
2861 if (*p == '\0') {
2862 /* no remaining string: NULL argument */
2863 break;
2866 len = strlen(p);
2867 if (len <= 0) {
2868 monitor_printf(mon, "%s: string expected\n",
2869 cmd->name);
2870 goto fail;
2872 qdict_put(qdict, key, qstring_from_str(p));
2873 p += len;
2875 break;
2876 default:
2877 bad_type:
2878 monitor_printf(mon, "%s: unknown type '%c'\n", cmd->name, c);
2879 goto fail;
2881 g_free(key);
2882 key = NULL;
2884 /* check that all arguments were parsed */
2885 while (qemu_isspace(*p))
2886 p++;
2887 if (*p != '\0') {
2888 monitor_printf(mon, "%s: extraneous characters at the end of line\n",
2889 cmd->name);
2890 goto fail;
2893 return qdict;
2895 fail:
2896 QDECREF(qdict);
2897 g_free(key);
2898 return NULL;
2901 static void handle_hmp_command(Monitor *mon, const char *cmdline)
2903 QDict *qdict;
2904 const mon_cmd_t *cmd;
2906 cmd = monitor_parse_command(mon, &cmdline, mon->cmd_table);
2907 if (!cmd) {
2908 return;
2911 qdict = monitor_parse_arguments(mon, &cmdline, cmd);
2912 if (!qdict) {
2913 monitor_printf(mon, "Try \"help %s\" for more information\n",
2914 cmd->name);
2915 return;
2918 cmd->mhandler.cmd(mon, qdict);
2919 QDECREF(qdict);
2922 static void cmd_completion(Monitor *mon, const char *name, const char *list)
2924 const char *p, *pstart;
2925 char cmd[128];
2926 int len;
2928 p = list;
2929 for(;;) {
2930 pstart = p;
2931 p = strchr(p, '|');
2932 if (!p)
2933 p = pstart + strlen(pstart);
2934 len = p - pstart;
2935 if (len > sizeof(cmd) - 2)
2936 len = sizeof(cmd) - 2;
2937 memcpy(cmd, pstart, len);
2938 cmd[len] = '\0';
2939 if (name[0] == '\0' || !strncmp(name, cmd, strlen(name))) {
2940 readline_add_completion(mon->rs, cmd);
2942 if (*p == '\0')
2943 break;
2944 p++;
2948 static void file_completion(Monitor *mon, const char *input)
2950 DIR *ffs;
2951 struct dirent *d;
2952 char path[1024];
2953 char file[1024], file_prefix[1024];
2954 int input_path_len;
2955 const char *p;
2957 p = strrchr(input, '/');
2958 if (!p) {
2959 input_path_len = 0;
2960 pstrcpy(file_prefix, sizeof(file_prefix), input);
2961 pstrcpy(path, sizeof(path), ".");
2962 } else {
2963 input_path_len = p - input + 1;
2964 memcpy(path, input, input_path_len);
2965 if (input_path_len > sizeof(path) - 1)
2966 input_path_len = sizeof(path) - 1;
2967 path[input_path_len] = '\0';
2968 pstrcpy(file_prefix, sizeof(file_prefix), p + 1);
2971 ffs = opendir(path);
2972 if (!ffs)
2973 return;
2974 for(;;) {
2975 struct stat sb;
2976 d = readdir(ffs);
2977 if (!d)
2978 break;
2980 if (strcmp(d->d_name, ".") == 0 || strcmp(d->d_name, "..") == 0) {
2981 continue;
2984 if (strstart(d->d_name, file_prefix, NULL)) {
2985 memcpy(file, input, input_path_len);
2986 if (input_path_len < sizeof(file))
2987 pstrcpy(file + input_path_len, sizeof(file) - input_path_len,
2988 d->d_name);
2989 /* stat the file to find out if it's a directory.
2990 * In that case add a slash to speed up typing long paths
2992 if (stat(file, &sb) == 0 && S_ISDIR(sb.st_mode)) {
2993 pstrcat(file, sizeof(file), "/");
2995 readline_add_completion(mon->rs, file);
2998 closedir(ffs);
3001 static const char *next_arg_type(const char *typestr)
3003 const char *p = strchr(typestr, ':');
3004 return (p != NULL ? ++p : typestr);
3007 static void add_completion_option(ReadLineState *rs, const char *str,
3008 const char *option)
3010 if (!str || !option) {
3011 return;
3013 if (!strncmp(option, str, strlen(str))) {
3014 readline_add_completion(rs, option);
3018 void chardev_add_completion(ReadLineState *rs, int nb_args, const char *str)
3020 size_t len;
3021 ChardevBackendInfoList *list, *start;
3023 if (nb_args != 2) {
3024 return;
3026 len = strlen(str);
3027 readline_set_completion_index(rs, len);
3029 start = list = qmp_query_chardev_backends(NULL);
3030 while (list) {
3031 const char *chr_name = list->value->name;
3033 if (!strncmp(chr_name, str, len)) {
3034 readline_add_completion(rs, chr_name);
3036 list = list->next;
3038 qapi_free_ChardevBackendInfoList(start);
3041 void netdev_add_completion(ReadLineState *rs, int nb_args, const char *str)
3043 size_t len;
3044 int i;
3046 if (nb_args != 2) {
3047 return;
3049 len = strlen(str);
3050 readline_set_completion_index(rs, len);
3051 for (i = 0; NetClientOptionsKind_lookup[i]; i++) {
3052 add_completion_option(rs, str, NetClientOptionsKind_lookup[i]);
3056 void device_add_completion(ReadLineState *rs, int nb_args, const char *str)
3058 GSList *list, *elt;
3059 size_t len;
3061 if (nb_args != 2) {
3062 return;
3065 len = strlen(str);
3066 readline_set_completion_index(rs, len);
3067 list = elt = object_class_get_list(TYPE_DEVICE, false);
3068 while (elt) {
3069 const char *name;
3070 DeviceClass *dc = OBJECT_CLASS_CHECK(DeviceClass, elt->data,
3071 TYPE_DEVICE);
3072 name = object_class_get_name(OBJECT_CLASS(dc));
3074 if (!dc->cannot_instantiate_with_device_add_yet
3075 && !strncmp(name, str, len)) {
3076 readline_add_completion(rs, name);
3078 elt = elt->next;
3080 g_slist_free(list);
3083 void object_add_completion(ReadLineState *rs, int nb_args, const char *str)
3085 GSList *list, *elt;
3086 size_t len;
3088 if (nb_args != 2) {
3089 return;
3092 len = strlen(str);
3093 readline_set_completion_index(rs, len);
3094 list = elt = object_class_get_list(TYPE_USER_CREATABLE, false);
3095 while (elt) {
3096 const char *name;
3098 name = object_class_get_name(OBJECT_CLASS(elt->data));
3099 if (!strncmp(name, str, len) && strcmp(name, TYPE_USER_CREATABLE)) {
3100 readline_add_completion(rs, name);
3102 elt = elt->next;
3104 g_slist_free(list);
3107 static void peripheral_device_del_completion(ReadLineState *rs,
3108 const char *str, size_t len)
3110 Object *peripheral = container_get(qdev_get_machine(), "/peripheral");
3111 GSList *list, *item;
3113 list = qdev_build_hotpluggable_device_list(peripheral);
3114 if (!list) {
3115 return;
3118 for (item = list; item; item = g_slist_next(item)) {
3119 DeviceState *dev = item->data;
3121 if (dev->id && !strncmp(str, dev->id, len)) {
3122 readline_add_completion(rs, dev->id);
3126 g_slist_free(list);
3129 void chardev_remove_completion(ReadLineState *rs, int nb_args, const char *str)
3131 size_t len;
3132 ChardevInfoList *list, *start;
3134 if (nb_args != 2) {
3135 return;
3137 len = strlen(str);
3138 readline_set_completion_index(rs, len);
3140 start = list = qmp_query_chardev(NULL);
3141 while (list) {
3142 ChardevInfo *chr = list->value;
3144 if (!strncmp(chr->label, str, len)) {
3145 readline_add_completion(rs, chr->label);
3147 list = list->next;
3149 qapi_free_ChardevInfoList(start);
3152 static void ringbuf_completion(ReadLineState *rs, const char *str)
3154 size_t len;
3155 ChardevInfoList *list, *start;
3157 len = strlen(str);
3158 readline_set_completion_index(rs, len);
3160 start = list = qmp_query_chardev(NULL);
3161 while (list) {
3162 ChardevInfo *chr_info = list->value;
3164 if (!strncmp(chr_info->label, str, len)) {
3165 CharDriverState *chr = qemu_chr_find(chr_info->label);
3166 if (chr && chr_is_ringbuf(chr)) {
3167 readline_add_completion(rs, chr_info->label);
3170 list = list->next;
3172 qapi_free_ChardevInfoList(start);
3175 void ringbuf_write_completion(ReadLineState *rs, int nb_args, const char *str)
3177 if (nb_args != 2) {
3178 return;
3180 ringbuf_completion(rs, str);
3183 void device_del_completion(ReadLineState *rs, int nb_args, const char *str)
3185 size_t len;
3187 if (nb_args != 2) {
3188 return;
3191 len = strlen(str);
3192 readline_set_completion_index(rs, len);
3193 peripheral_device_del_completion(rs, str, len);
3196 void object_del_completion(ReadLineState *rs, int nb_args, const char *str)
3198 ObjectPropertyInfoList *list, *start;
3199 size_t len;
3201 if (nb_args != 2) {
3202 return;
3204 len = strlen(str);
3205 readline_set_completion_index(rs, len);
3207 start = list = qmp_qom_list("/objects", NULL);
3208 while (list) {
3209 ObjectPropertyInfo *info = list->value;
3211 if (!strncmp(info->type, "child<", 5)
3212 && !strncmp(info->name, str, len)) {
3213 readline_add_completion(rs, info->name);
3215 list = list->next;
3217 qapi_free_ObjectPropertyInfoList(start);
3220 void sendkey_completion(ReadLineState *rs, int nb_args, const char *str)
3222 int i;
3223 char *sep;
3224 size_t len;
3226 if (nb_args != 2) {
3227 return;
3229 sep = strrchr(str, '-');
3230 if (sep) {
3231 str = sep + 1;
3233 len = strlen(str);
3234 readline_set_completion_index(rs, len);
3235 for (i = 0; i < Q_KEY_CODE__MAX; i++) {
3236 if (!strncmp(str, QKeyCode_lookup[i], len)) {
3237 readline_add_completion(rs, QKeyCode_lookup[i]);
3242 void set_link_completion(ReadLineState *rs, int nb_args, const char *str)
3244 size_t len;
3246 len = strlen(str);
3247 readline_set_completion_index(rs, len);
3248 if (nb_args == 2) {
3249 NetClientState *ncs[MAX_QUEUE_NUM];
3250 int count, i;
3251 count = qemu_find_net_clients_except(NULL, ncs,
3252 NET_CLIENT_OPTIONS_KIND_NONE,
3253 MAX_QUEUE_NUM);
3254 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3255 const char *name = ncs[i]->name;
3256 if (!strncmp(str, name, len)) {
3257 readline_add_completion(rs, name);
3260 } else if (nb_args == 3) {
3261 add_completion_option(rs, str, "on");
3262 add_completion_option(rs, str, "off");
3266 void netdev_del_completion(ReadLineState *rs, int nb_args, const char *str)
3268 int len, count, i;
3269 NetClientState *ncs[MAX_QUEUE_NUM];
3271 if (nb_args != 2) {
3272 return;
3275 len = strlen(str);
3276 readline_set_completion_index(rs, len);
3277 count = qemu_find_net_clients_except(NULL, ncs, NET_CLIENT_OPTIONS_KIND_NIC,
3278 MAX_QUEUE_NUM);
3279 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3280 QemuOpts *opts;
3281 const char *name = ncs[i]->name;
3282 if (strncmp(str, name, len)) {
3283 continue;
3285 opts = qemu_opts_find(qemu_find_opts_err("netdev", NULL), name);
3286 if (opts) {
3287 readline_add_completion(rs, name);
3292 void trace_event_completion(ReadLineState *rs, int nb_args, const char *str)
3294 size_t len;
3296 len = strlen(str);
3297 readline_set_completion_index(rs, len);
3298 if (nb_args == 2) {
3299 TraceEventID id;
3300 for (id = 0; id < trace_event_count(); id++) {
3301 const char *event_name = trace_event_get_name(trace_event_id(id));
3302 if (!strncmp(str, event_name, len)) {
3303 readline_add_completion(rs, event_name);
3306 } else if (nb_args == 3) {
3307 add_completion_option(rs, str, "on");
3308 add_completion_option(rs, str, "off");
3312 void watchdog_action_completion(ReadLineState *rs, int nb_args, const char *str)
3314 int i;
3316 if (nb_args != 2) {
3317 return;
3319 readline_set_completion_index(rs, strlen(str));
3320 for (i = 0; WatchdogExpirationAction_lookup[i]; i++) {
3321 add_completion_option(rs, str, WatchdogExpirationAction_lookup[i]);
3325 void migrate_set_capability_completion(ReadLineState *rs, int nb_args,
3326 const char *str)
3328 size_t len;
3330 len = strlen(str);
3331 readline_set_completion_index(rs, len);
3332 if (nb_args == 2) {
3333 int i;
3334 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
3335 const char *name = MigrationCapability_lookup[i];
3336 if (!strncmp(str, name, len)) {
3337 readline_add_completion(rs, name);
3340 } else if (nb_args == 3) {
3341 add_completion_option(rs, str, "on");
3342 add_completion_option(rs, str, "off");
3346 void migrate_set_parameter_completion(ReadLineState *rs, int nb_args,
3347 const char *str)
3349 size_t len;
3351 len = strlen(str);
3352 readline_set_completion_index(rs, len);
3353 if (nb_args == 2) {
3354 int i;
3355 for (i = 0; i < MIGRATION_PARAMETER__MAX; i++) {
3356 const char *name = MigrationParameter_lookup[i];
3357 if (!strncmp(str, name, len)) {
3358 readline_add_completion(rs, name);
3364 void host_net_add_completion(ReadLineState *rs, int nb_args, const char *str)
3366 int i;
3367 size_t len;
3368 if (nb_args != 2) {
3369 return;
3371 len = strlen(str);
3372 readline_set_completion_index(rs, len);
3373 for (i = 0; host_net_devices[i]; i++) {
3374 if (!strncmp(host_net_devices[i], str, len)) {
3375 readline_add_completion(rs, host_net_devices[i]);
3380 void host_net_remove_completion(ReadLineState *rs, int nb_args, const char *str)
3382 NetClientState *ncs[MAX_QUEUE_NUM];
3383 int count, i, len;
3385 len = strlen(str);
3386 readline_set_completion_index(rs, len);
3387 if (nb_args == 2) {
3388 count = qemu_find_net_clients_except(NULL, ncs,
3389 NET_CLIENT_OPTIONS_KIND_NONE,
3390 MAX_QUEUE_NUM);
3391 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3392 int id;
3393 char name[16];
3395 if (net_hub_id_for_client(ncs[i], &id)) {
3396 continue;
3398 snprintf(name, sizeof(name), "%d", id);
3399 if (!strncmp(str, name, len)) {
3400 readline_add_completion(rs, name);
3403 return;
3404 } else if (nb_args == 3) {
3405 count = qemu_find_net_clients_except(NULL, ncs,
3406 NET_CLIENT_OPTIONS_KIND_NIC,
3407 MAX_QUEUE_NUM);
3408 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3409 int id;
3410 const char *name;
3412 if (ncs[i]->info->type == NET_CLIENT_OPTIONS_KIND_HUBPORT ||
3413 net_hub_id_for_client(ncs[i], &id)) {
3414 continue;
3416 name = ncs[i]->name;
3417 if (!strncmp(str, name, len)) {
3418 readline_add_completion(rs, name);
3421 return;
3425 static void vm_completion(ReadLineState *rs, const char *str)
3427 size_t len;
3428 BlockDriverState *bs = NULL;
3430 len = strlen(str);
3431 readline_set_completion_index(rs, len);
3432 while ((bs = bdrv_next(bs))) {
3433 SnapshotInfoList *snapshots, *snapshot;
3434 AioContext *ctx = bdrv_get_aio_context(bs);
3435 bool ok = false;
3437 aio_context_acquire(ctx);
3438 if (bdrv_can_snapshot(bs)) {
3439 ok = bdrv_query_snapshot_info_list(bs, &snapshots, NULL) == 0;
3441 aio_context_release(ctx);
3442 if (!ok) {
3443 continue;
3446 snapshot = snapshots;
3447 while (snapshot) {
3448 char *completion = snapshot->value->name;
3449 if (!strncmp(str, completion, len)) {
3450 readline_add_completion(rs, completion);
3452 completion = snapshot->value->id;
3453 if (!strncmp(str, completion, len)) {
3454 readline_add_completion(rs, completion);
3456 snapshot = snapshot->next;
3458 qapi_free_SnapshotInfoList(snapshots);
3463 void delvm_completion(ReadLineState *rs, int nb_args, const char *str)
3465 if (nb_args == 2) {
3466 vm_completion(rs, str);
3470 void loadvm_completion(ReadLineState *rs, int nb_args, const char *str)
3472 if (nb_args == 2) {
3473 vm_completion(rs, str);
3477 static void monitor_find_completion_by_table(Monitor *mon,
3478 const mon_cmd_t *cmd_table,
3479 char **args,
3480 int nb_args)
3482 const char *cmdname;
3483 int i;
3484 const char *ptype, *str, *name;
3485 const mon_cmd_t *cmd;
3486 BlockDriverState *bs;
3488 if (nb_args <= 1) {
3489 /* command completion */
3490 if (nb_args == 0)
3491 cmdname = "";
3492 else
3493 cmdname = args[0];
3494 readline_set_completion_index(mon->rs, strlen(cmdname));
3495 for (cmd = cmd_table; cmd->name != NULL; cmd++) {
3496 cmd_completion(mon, cmdname, cmd->name);
3498 } else {
3499 /* find the command */
3500 for (cmd = cmd_table; cmd->name != NULL; cmd++) {
3501 if (compare_cmd(args[0], cmd->name)) {
3502 break;
3505 if (!cmd->name) {
3506 return;
3509 if (cmd->sub_table) {
3510 /* do the job again */
3511 monitor_find_completion_by_table(mon, cmd->sub_table,
3512 &args[1], nb_args - 1);
3513 return;
3515 if (cmd->command_completion) {
3516 cmd->command_completion(mon->rs, nb_args, args[nb_args - 1]);
3517 return;
3520 ptype = next_arg_type(cmd->args_type);
3521 for(i = 0; i < nb_args - 2; i++) {
3522 if (*ptype != '\0') {
3523 ptype = next_arg_type(ptype);
3524 while (*ptype == '?')
3525 ptype = next_arg_type(ptype);
3528 str = args[nb_args - 1];
3529 while (*ptype == '-' && ptype[1] != '\0') {
3530 ptype = next_arg_type(ptype);
3532 switch(*ptype) {
3533 case 'F':
3534 /* file completion */
3535 readline_set_completion_index(mon->rs, strlen(str));
3536 file_completion(mon, str);
3537 break;
3538 case 'B':
3539 /* block device name completion */
3540 readline_set_completion_index(mon->rs, strlen(str));
3541 for (bs = bdrv_next(NULL); bs; bs = bdrv_next(bs)) {
3542 name = bdrv_get_device_name(bs);
3543 if (str[0] == '\0' ||
3544 !strncmp(name, str, strlen(str))) {
3545 readline_add_completion(mon->rs, name);
3548 break;
3549 case 's':
3550 case 'S':
3551 if (!strcmp(cmd->name, "help|?")) {
3552 monitor_find_completion_by_table(mon, cmd_table,
3553 &args[1], nb_args - 1);
3555 break;
3556 default:
3557 break;
3562 static void monitor_find_completion(void *opaque,
3563 const char *cmdline)
3565 Monitor *mon = opaque;
3566 char *args[MAX_ARGS];
3567 int nb_args, len;
3569 /* 1. parse the cmdline */
3570 if (parse_cmdline(cmdline, &nb_args, args) < 0) {
3571 return;
3574 /* if the line ends with a space, it means we want to complete the
3575 next arg */
3576 len = strlen(cmdline);
3577 if (len > 0 && qemu_isspace(cmdline[len - 1])) {
3578 if (nb_args >= MAX_ARGS) {
3579 goto cleanup;
3581 args[nb_args++] = g_strdup("");
3584 /* 2. auto complete according to args */
3585 monitor_find_completion_by_table(mon, mon->cmd_table, args, nb_args);
3587 cleanup:
3588 free_cmdline_args(args, nb_args);
3591 static int monitor_can_read(void *opaque)
3593 Monitor *mon = opaque;
3595 return (mon->suspend_cnt == 0) ? 1 : 0;
3598 static bool invalid_qmp_mode(const Monitor *mon, const mon_cmd_t *cmd,
3599 Error **errp)
3601 bool is_cap = cmd->mhandler.cmd_new == qmp_capabilities;
3603 if (is_cap && mon->qmp.in_command_mode) {
3604 error_set(errp, ERROR_CLASS_COMMAND_NOT_FOUND,
3605 "Capabilities negotiation is already complete, command "
3606 "'%s' ignored", cmd->name);
3607 return true;
3609 if (!is_cap && !mon->qmp.in_command_mode) {
3610 error_set(errp, ERROR_CLASS_COMMAND_NOT_FOUND,
3611 "Expecting capabilities negotiation with "
3612 "'qmp_capabilities' before command '%s'", cmd->name);
3613 return true;
3615 return false;
3619 * Argument validation rules:
3621 * 1. The argument must exist in cmd_args qdict
3622 * 2. The argument type must be the expected one
3624 * Special case: If the argument doesn't exist in cmd_args and
3625 * the QMP_ACCEPT_UNKNOWNS flag is set, then the
3626 * checking is skipped for it.
3628 static void check_client_args_type(const QDict *client_args,
3629 const QDict *cmd_args, int flags,
3630 Error **errp)
3632 const QDictEntry *ent;
3634 for (ent = qdict_first(client_args); ent;ent = qdict_next(client_args,ent)){
3635 QObject *obj;
3636 QString *arg_type;
3637 const QObject *client_arg = qdict_entry_value(ent);
3638 const char *client_arg_name = qdict_entry_key(ent);
3640 obj = qdict_get(cmd_args, client_arg_name);
3641 if (!obj) {
3642 if (flags & QMP_ACCEPT_UNKNOWNS) {
3643 /* handler accepts unknowns */
3644 continue;
3646 /* client arg doesn't exist */
3647 error_setg(errp, QERR_INVALID_PARAMETER, client_arg_name);
3648 return;
3651 arg_type = qobject_to_qstring(obj);
3652 assert(arg_type != NULL);
3654 /* check if argument's type is correct */
3655 switch (qstring_get_str(arg_type)[0]) {
3656 case 'F':
3657 case 'B':
3658 case 's':
3659 if (qobject_type(client_arg) != QTYPE_QSTRING) {
3660 error_setg(errp, QERR_INVALID_PARAMETER_TYPE,
3661 client_arg_name, "string");
3662 return;
3664 break;
3665 case 'i':
3666 case 'l':
3667 case 'M':
3668 case 'o':
3669 if (qobject_type(client_arg) != QTYPE_QINT) {
3670 error_setg(errp, QERR_INVALID_PARAMETER_TYPE,
3671 client_arg_name, "int");
3672 return;
3674 break;
3675 case 'T':
3676 if (qobject_type(client_arg) != QTYPE_QINT &&
3677 qobject_type(client_arg) != QTYPE_QFLOAT) {
3678 error_setg(errp, QERR_INVALID_PARAMETER_TYPE,
3679 client_arg_name, "number");
3680 return;
3682 break;
3683 case 'b':
3684 case '-':
3685 if (qobject_type(client_arg) != QTYPE_QBOOL) {
3686 error_setg(errp, QERR_INVALID_PARAMETER_TYPE,
3687 client_arg_name, "bool");
3688 return;
3690 break;
3691 case 'O':
3692 assert(flags & QMP_ACCEPT_UNKNOWNS);
3693 break;
3694 case 'q':
3695 /* Any QObject can be passed. */
3696 break;
3697 case '/':
3698 case '.':
3700 * These types are not supported by QMP and thus are not
3701 * handled here. Fall through.
3703 default:
3704 abort();
3710 * - Check if the client has passed all mandatory args
3711 * - Set special flags for argument validation
3713 static void check_mandatory_args(const QDict *cmd_args,
3714 const QDict *client_args, int *flags,
3715 Error **errp)
3717 const QDictEntry *ent;
3719 for (ent = qdict_first(cmd_args); ent; ent = qdict_next(cmd_args, ent)) {
3720 const char *cmd_arg_name = qdict_entry_key(ent);
3721 QString *type = qobject_to_qstring(qdict_entry_value(ent));
3722 assert(type != NULL);
3724 if (qstring_get_str(type)[0] == 'O') {
3725 assert((*flags & QMP_ACCEPT_UNKNOWNS) == 0);
3726 *flags |= QMP_ACCEPT_UNKNOWNS;
3727 } else if (qstring_get_str(type)[0] != '-' &&
3728 qstring_get_str(type)[1] != '?' &&
3729 !qdict_haskey(client_args, cmd_arg_name)) {
3730 error_setg(errp, QERR_MISSING_PARAMETER, cmd_arg_name);
3731 return;
3736 static QDict *qdict_from_args_type(const char *args_type)
3738 int i;
3739 QDict *qdict;
3740 QString *key, *type, *cur_qs;
3742 assert(args_type != NULL);
3744 qdict = qdict_new();
3746 if (args_type == NULL || args_type[0] == '\0') {
3747 /* no args, empty qdict */
3748 goto out;
3751 key = qstring_new();
3752 type = qstring_new();
3754 cur_qs = key;
3756 for (i = 0;; i++) {
3757 switch (args_type[i]) {
3758 case ',':
3759 case '\0':
3760 qdict_put(qdict, qstring_get_str(key), type);
3761 QDECREF(key);
3762 if (args_type[i] == '\0') {
3763 goto out;
3765 type = qstring_new(); /* qdict has ref */
3766 cur_qs = key = qstring_new();
3767 break;
3768 case ':':
3769 cur_qs = type;
3770 break;
3771 default:
3772 qstring_append_chr(cur_qs, args_type[i]);
3773 break;
3777 out:
3778 return qdict;
3782 * Client argument checking rules:
3784 * 1. Client must provide all mandatory arguments
3785 * 2. Each argument provided by the client must be expected
3786 * 3. Each argument provided by the client must have the type expected
3787 * by the command
3789 static void qmp_check_client_args(const mon_cmd_t *cmd, QDict *client_args,
3790 Error **errp)
3792 Error *err = NULL;
3793 int flags;
3794 QDict *cmd_args;
3796 cmd_args = qdict_from_args_type(cmd->args_type);
3798 flags = 0;
3799 check_mandatory_args(cmd_args, client_args, &flags, &err);
3800 if (err) {
3801 goto out;
3804 check_client_args_type(client_args, cmd_args, flags, &err);
3806 out:
3807 error_propagate(errp, err);
3808 QDECREF(cmd_args);
3812 * Input object checking rules
3814 * 1. Input object must be a dict
3815 * 2. The "execute" key must exist
3816 * 3. The "execute" key must be a string
3817 * 4. If the "arguments" key exists, it must be a dict
3818 * 5. If the "id" key exists, it can be anything (ie. json-value)
3819 * 6. Any argument not listed above is considered invalid
3821 static QDict *qmp_check_input_obj(QObject *input_obj, Error **errp)
3823 const QDictEntry *ent;
3824 int has_exec_key = 0;
3825 QDict *input_dict;
3827 if (qobject_type(input_obj) != QTYPE_QDICT) {
3828 error_setg(errp, QERR_QMP_BAD_INPUT_OBJECT, "object");
3829 return NULL;
3832 input_dict = qobject_to_qdict(input_obj);
3834 for (ent = qdict_first(input_dict); ent; ent = qdict_next(input_dict, ent)){
3835 const char *arg_name = qdict_entry_key(ent);
3836 const QObject *arg_obj = qdict_entry_value(ent);
3838 if (!strcmp(arg_name, "execute")) {
3839 if (qobject_type(arg_obj) != QTYPE_QSTRING) {
3840 error_setg(errp, QERR_QMP_BAD_INPUT_OBJECT_MEMBER,
3841 "execute", "string");
3842 return NULL;
3844 has_exec_key = 1;
3845 } else if (!strcmp(arg_name, "arguments")) {
3846 if (qobject_type(arg_obj) != QTYPE_QDICT) {
3847 error_setg(errp, QERR_QMP_BAD_INPUT_OBJECT_MEMBER,
3848 "arguments", "object");
3849 return NULL;
3851 } else if (!strcmp(arg_name, "id")) {
3852 /* Any string is acceptable as "id", so nothing to check */
3853 } else {
3854 error_setg(errp, QERR_QMP_EXTRA_MEMBER, arg_name);
3855 return NULL;
3859 if (!has_exec_key) {
3860 error_setg(errp, QERR_QMP_BAD_INPUT_OBJECT, "execute");
3861 return NULL;
3864 return input_dict;
3867 static void handle_qmp_command(JSONMessageParser *parser, GQueue *tokens)
3869 Error *local_err = NULL;
3870 QObject *obj, *data;
3871 QDict *input, *args;
3872 const mon_cmd_t *cmd;
3873 const char *cmd_name;
3874 Monitor *mon = cur_mon;
3876 args = input = NULL;
3877 data = NULL;
3879 obj = json_parser_parse(tokens, NULL);
3880 if (!obj) {
3881 // FIXME: should be triggered in json_parser_parse()
3882 error_setg(&local_err, QERR_JSON_PARSING);
3883 goto err_out;
3886 input = qmp_check_input_obj(obj, &local_err);
3887 if (!input) {
3888 qobject_decref(obj);
3889 goto err_out;
3892 mon->qmp.id = qdict_get(input, "id");
3893 qobject_incref(mon->qmp.id);
3895 cmd_name = qdict_get_str(input, "execute");
3896 trace_handle_qmp_command(mon, cmd_name);
3897 cmd = qmp_find_cmd(cmd_name);
3898 if (!cmd) {
3899 error_set(&local_err, ERROR_CLASS_COMMAND_NOT_FOUND,
3900 "The command %s has not been found", cmd_name);
3901 goto err_out;
3903 if (invalid_qmp_mode(mon, cmd, &local_err)) {
3904 goto err_out;
3907 obj = qdict_get(input, "arguments");
3908 if (!obj) {
3909 args = qdict_new();
3910 } else {
3911 args = qobject_to_qdict(obj);
3912 QINCREF(args);
3915 qmp_check_client_args(cmd, args, &local_err);
3916 if (local_err) {
3917 goto err_out;
3920 cmd->mhandler.cmd_new(args, &data, &local_err);
3922 err_out:
3923 monitor_protocol_emitter(mon, data, local_err);
3924 qobject_decref(data);
3925 error_free(local_err);
3926 QDECREF(input);
3927 QDECREF(args);
3930 static void monitor_qmp_read(void *opaque, const uint8_t *buf, int size)
3932 Monitor *old_mon = cur_mon;
3934 cur_mon = opaque;
3936 json_message_parser_feed(&cur_mon->qmp.parser, (const char *) buf, size);
3938 cur_mon = old_mon;
3941 static void monitor_read(void *opaque, const uint8_t *buf, int size)
3943 Monitor *old_mon = cur_mon;
3944 int i;
3946 cur_mon = opaque;
3948 if (cur_mon->rs) {
3949 for (i = 0; i < size; i++)
3950 readline_handle_byte(cur_mon->rs, buf[i]);
3951 } else {
3952 if (size == 0 || buf[size - 1] != 0)
3953 monitor_printf(cur_mon, "corrupted command\n");
3954 else
3955 handle_hmp_command(cur_mon, (char *)buf);
3958 cur_mon = old_mon;
3961 static void monitor_command_cb(void *opaque, const char *cmdline,
3962 void *readline_opaque)
3964 Monitor *mon = opaque;
3966 monitor_suspend(mon);
3967 handle_hmp_command(mon, cmdline);
3968 monitor_resume(mon);
3971 int monitor_suspend(Monitor *mon)
3973 if (!mon->rs)
3974 return -ENOTTY;
3975 mon->suspend_cnt++;
3976 return 0;
3979 void monitor_resume(Monitor *mon)
3981 if (!mon->rs)
3982 return;
3983 if (--mon->suspend_cnt == 0)
3984 readline_show_prompt(mon->rs);
3987 static QObject *get_qmp_greeting(void)
3989 QObject *ver = NULL;
3991 qmp_marshal_query_version(NULL, &ver, NULL);
3992 return qobject_from_jsonf("{'QMP':{'version': %p,'capabilities': []}}",ver);
3995 static void monitor_qmp_event(void *opaque, int event)
3997 QObject *data;
3998 Monitor *mon = opaque;
4000 switch (event) {
4001 case CHR_EVENT_OPENED:
4002 mon->qmp.in_command_mode = false;
4003 data = get_qmp_greeting();
4004 monitor_json_emitter(mon, data);
4005 qobject_decref(data);
4006 mon_refcount++;
4007 break;
4008 case CHR_EVENT_CLOSED:
4009 json_message_parser_destroy(&mon->qmp.parser);
4010 json_message_parser_init(&mon->qmp.parser, handle_qmp_command);
4011 mon_refcount--;
4012 monitor_fdsets_cleanup();
4013 break;
4017 static void monitor_event(void *opaque, int event)
4019 Monitor *mon = opaque;
4021 switch (event) {
4022 case CHR_EVENT_MUX_IN:
4023 qemu_mutex_lock(&mon->out_lock);
4024 mon->mux_out = 0;
4025 qemu_mutex_unlock(&mon->out_lock);
4026 if (mon->reset_seen) {
4027 readline_restart(mon->rs);
4028 monitor_resume(mon);
4029 monitor_flush(mon);
4030 } else {
4031 mon->suspend_cnt = 0;
4033 break;
4035 case CHR_EVENT_MUX_OUT:
4036 if (mon->reset_seen) {
4037 if (mon->suspend_cnt == 0) {
4038 monitor_printf(mon, "\n");
4040 monitor_flush(mon);
4041 monitor_suspend(mon);
4042 } else {
4043 mon->suspend_cnt++;
4045 qemu_mutex_lock(&mon->out_lock);
4046 mon->mux_out = 1;
4047 qemu_mutex_unlock(&mon->out_lock);
4048 break;
4050 case CHR_EVENT_OPENED:
4051 monitor_printf(mon, "QEMU %s monitor - type 'help' for more "
4052 "information\n", QEMU_VERSION);
4053 if (!mon->mux_out) {
4054 readline_restart(mon->rs);
4055 readline_show_prompt(mon->rs);
4057 mon->reset_seen = 1;
4058 mon_refcount++;
4059 break;
4061 case CHR_EVENT_CLOSED:
4062 mon_refcount--;
4063 monitor_fdsets_cleanup();
4064 break;
4068 static int
4069 compare_mon_cmd(const void *a, const void *b)
4071 return strcmp(((const mon_cmd_t *)a)->name,
4072 ((const mon_cmd_t *)b)->name);
4075 static void sortcmdlist(void)
4077 int array_num;
4078 int elem_size = sizeof(mon_cmd_t);
4080 array_num = sizeof(mon_cmds)/elem_size-1;
4081 qsort((void *)mon_cmds, array_num, elem_size, compare_mon_cmd);
4083 array_num = sizeof(info_cmds)/elem_size-1;
4084 qsort((void *)info_cmds, array_num, elem_size, compare_mon_cmd);
4089 * Local variables:
4090 * c-indent-level: 4
4091 * c-basic-offset: 4
4092 * tab-width: 8
4093 * End:
4096 /* These functions just adapt the readline interface in a typesafe way. We
4097 * could cast function pointers but that discards compiler checks.
4099 static void GCC_FMT_ATTR(2, 3) monitor_readline_printf(void *opaque,
4100 const char *fmt, ...)
4102 va_list ap;
4103 va_start(ap, fmt);
4104 monitor_vprintf(opaque, fmt, ap);
4105 va_end(ap);
4108 static void monitor_readline_flush(void *opaque)
4110 monitor_flush(opaque);
4113 static void __attribute__((constructor)) monitor_lock_init(void)
4115 qemu_mutex_init(&monitor_lock);
4118 void monitor_init(CharDriverState *chr, int flags)
4120 static int is_first_init = 1;
4121 Monitor *mon;
4123 if (is_first_init) {
4124 monitor_qapi_event_init();
4125 sortcmdlist();
4126 is_first_init = 0;
4129 mon = g_malloc(sizeof(*mon));
4130 monitor_data_init(mon);
4132 mon->chr = chr;
4133 mon->flags = flags;
4134 if (flags & MONITOR_USE_READLINE) {
4135 mon->rs = readline_init(monitor_readline_printf,
4136 monitor_readline_flush,
4137 mon,
4138 monitor_find_completion);
4139 monitor_read_command(mon, 0);
4142 if (monitor_is_qmp(mon)) {
4143 qemu_chr_add_handlers(chr, monitor_can_read, monitor_qmp_read,
4144 monitor_qmp_event, mon);
4145 qemu_chr_fe_set_echo(chr, true);
4146 json_message_parser_init(&mon->qmp.parser, handle_qmp_command);
4147 } else {
4148 qemu_chr_add_handlers(chr, monitor_can_read, monitor_read,
4149 monitor_event, mon);
4152 qemu_mutex_lock(&monitor_lock);
4153 QLIST_INSERT_HEAD(&mon_list, mon, entry);
4154 qemu_mutex_unlock(&monitor_lock);
4157 static void bdrv_password_cb(void *opaque, const char *password,
4158 void *readline_opaque)
4160 Monitor *mon = opaque;
4161 BlockDriverState *bs = readline_opaque;
4162 int ret = 0;
4163 Error *local_err = NULL;
4165 bdrv_add_key(bs, password, &local_err);
4166 if (local_err) {
4167 error_report_err(local_err);
4168 ret = -EPERM;
4170 if (mon->password_completion_cb)
4171 mon->password_completion_cb(mon->password_opaque, ret);
4173 monitor_read_command(mon, 1);
4176 int monitor_read_bdrv_key_start(Monitor *mon, BlockDriverState *bs,
4177 BlockCompletionFunc *completion_cb,
4178 void *opaque)
4180 int err;
4182 monitor_printf(mon, "%s (%s) is encrypted.\n", bdrv_get_device_name(bs),
4183 bdrv_get_encrypted_filename(bs));
4185 mon->password_completion_cb = completion_cb;
4186 mon->password_opaque = opaque;
4188 err = monitor_read_password(mon, bdrv_password_cb, bs);
4190 if (err && completion_cb)
4191 completion_cb(opaque, err);
4193 return err;
4196 int monitor_read_block_device_key(Monitor *mon, const char *device,
4197 BlockCompletionFunc *completion_cb,
4198 void *opaque)
4200 Error *err = NULL;
4201 BlockBackend *blk;
4203 blk = blk_by_name(device);
4204 if (!blk) {
4205 monitor_printf(mon, "Device not found %s\n", device);
4206 return -1;
4208 if (!blk_bs(blk)) {
4209 monitor_printf(mon, "Device '%s' has no medium\n", device);
4210 return -1;
4213 bdrv_add_key(blk_bs(blk), NULL, &err);
4214 if (err) {
4215 error_free(err);
4216 return monitor_read_bdrv_key_start(mon, blk_bs(blk), completion_cb, opaque);
4219 if (completion_cb) {
4220 completion_cb(opaque, 0);
4222 return 0;
4225 QemuOptsList qemu_mon_opts = {
4226 .name = "mon",
4227 .implied_opt_name = "chardev",
4228 .head = QTAILQ_HEAD_INITIALIZER(qemu_mon_opts.head),
4229 .desc = {
4231 .name = "mode",
4232 .type = QEMU_OPT_STRING,
4234 .name = "chardev",
4235 .type = QEMU_OPT_STRING,
4237 .name = "default",
4238 .type = QEMU_OPT_BOOL,
4240 .name = "pretty",
4241 .type = QEMU_OPT_BOOL,
4243 { /* end of list */ }
4247 #ifndef TARGET_I386
4248 void qmp_rtc_reset_reinjection(Error **errp)
4250 error_setg(errp, QERR_FEATURE_DISABLED, "rtc-reset-reinjection");
4252 #endif
4254 #ifndef TARGET_S390X
4255 void qmp_dump_skeys(const char *filename, Error **errp)
4257 error_setg(errp, QERR_FEATURE_DISABLED, "dump-skeys");
4259 #endif