vnc-enc-tight: fix off-by-one bug
[qemu/kevin.git] / monitor.c
blobd0ff246a163cbfe2f21a6f173b68981bf4649d38
1 /*
2 * QEMU monitor
4 * Copyright (c) 2003-2004 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
24 #include "qemu/osdep.h"
25 #include <dirent.h>
26 #include "qemu-common.h"
27 #include "cpu.h"
28 #include "hw/hw.h"
29 #include "monitor/qdev.h"
30 #include "hw/usb.h"
31 #include "hw/i386/pc.h"
32 #include "hw/pci/pci.h"
33 #include "sysemu/watchdog.h"
34 #include "hw/loader.h"
35 #include "exec/gdbstub.h"
36 #include "net/net.h"
37 #include "net/slirp.h"
38 #include "sysemu/char.h"
39 #include "ui/qemu-spice.h"
40 #include "sysemu/sysemu.h"
41 #include "sysemu/numa.h"
42 #include "monitor/monitor.h"
43 #include "qemu/readline.h"
44 #include "ui/console.h"
45 #include "ui/input.h"
46 #include "sysemu/blockdev.h"
47 #include "sysemu/block-backend.h"
48 #include "audio/audio.h"
49 #include "disas/disas.h"
50 #include "sysemu/balloon.h"
51 #include "qemu/timer.h"
52 #include "migration/migration.h"
53 #include "sysemu/kvm.h"
54 #include "qemu/acl.h"
55 #include "sysemu/tpm.h"
56 #include "qapi/qmp/qerror.h"
57 #include "qapi/qmp/types.h"
58 #include "qapi/qmp/qjson.h"
59 #include "qapi/qmp/json-streamer.h"
60 #include "qapi/qmp/json-parser.h"
61 #include "qom/object_interfaces.h"
62 #include "cpu.h"
63 #include "trace.h"
64 #include "trace/control.h"
65 #include "monitor/hmp-target.h"
66 #ifdef CONFIG_TRACE_SIMPLE
67 #include "trace/simple.h"
68 #endif
69 #include "exec/memory.h"
70 #include "exec/exec-all.h"
71 #include "qemu/log.h"
72 #include "qmp-commands.h"
73 #include "hmp.h"
74 #include "qemu/thread.h"
75 #include "block/qapi.h"
76 #include "qapi/qmp-event.h"
77 #include "qapi-event.h"
78 #include "qmp-introspect.h"
79 #include "sysemu/block-backend.h"
80 #include "sysemu/qtest.h"
81 #include "qemu/cutils.h"
83 /* for hmp_info_irq/pic */
84 #if defined(TARGET_SPARC)
85 #include "hw/sparc/sun4m.h"
86 #endif
87 #include "hw/lm32/lm32_pic.h"
89 #if defined(TARGET_S390X)
90 #include "hw/s390x/storage-keys.h"
91 #endif
94 * Supported types:
96 * 'F' filename
97 * 'B' block device name
98 * 's' string (accept optional quote)
99 * 'S' it just appends the rest of the string (accept optional quote)
100 * 'O' option string of the form NAME=VALUE,...
101 * parsed according to QemuOptsList given by its name
102 * Example: 'device:O' uses qemu_device_opts.
103 * Restriction: only lists with empty desc are supported
104 * TODO lift the restriction
105 * 'i' 32 bit integer
106 * 'l' target long (32 or 64 bit)
107 * 'M' Non-negative target long (32 or 64 bit), in user mode the
108 * value is multiplied by 2^20 (think Mebibyte)
109 * 'o' octets (aka bytes)
110 * user mode accepts an optional E, e, P, p, T, t, G, g, M, m,
111 * K, k suffix, which multiplies the value by 2^60 for suffixes E
112 * and e, 2^50 for suffixes P and p, 2^40 for suffixes T and t,
113 * 2^30 for suffixes G and g, 2^20 for M and m, 2^10 for K and k
114 * 'T' double
115 * user mode accepts an optional ms, us, ns suffix,
116 * which divides the value by 1e3, 1e6, 1e9, respectively
117 * '/' optional gdb-like print format (like "/10x")
119 * '?' optional type (for all types, except '/')
120 * '.' other form of optional type (for 'i' and 'l')
121 * 'b' boolean
122 * user mode accepts "on" or "off"
123 * '-' optional parameter (eg. '-f')
127 typedef struct mon_cmd_t {
128 const char *name;
129 const char *args_type;
130 const char *params;
131 const char *help;
132 union {
133 void (*cmd)(Monitor *mon, const QDict *qdict);
134 void (*cmd_new)(QDict *params, QObject **ret_data, Error **errp);
135 } mhandler;
136 /* @sub_table is a list of 2nd level of commands. If it do not exist,
137 * mhandler should be used. If it exist, sub_table[?].mhandler should be
138 * used, and mhandler of 1st level plays the role of help function.
140 struct mon_cmd_t *sub_table;
141 void (*command_completion)(ReadLineState *rs, int nb_args, const char *str);
142 } mon_cmd_t;
144 /* file descriptors passed via SCM_RIGHTS */
145 typedef struct mon_fd_t mon_fd_t;
146 struct mon_fd_t {
147 char *name;
148 int fd;
149 QLIST_ENTRY(mon_fd_t) next;
152 /* file descriptor associated with a file descriptor set */
153 typedef struct MonFdsetFd MonFdsetFd;
154 struct MonFdsetFd {
155 int fd;
156 bool removed;
157 char *opaque;
158 QLIST_ENTRY(MonFdsetFd) next;
161 /* file descriptor set containing fds passed via SCM_RIGHTS */
162 typedef struct MonFdset MonFdset;
163 struct MonFdset {
164 int64_t id;
165 QLIST_HEAD(, MonFdsetFd) fds;
166 QLIST_HEAD(, MonFdsetFd) dup_fds;
167 QLIST_ENTRY(MonFdset) next;
170 typedef struct {
171 QObject *id;
172 JSONMessageParser parser;
174 * When a client connects, we're in capabilities negotiation mode.
175 * When command qmp_capabilities succeeds, we go into command
176 * mode.
178 bool in_command_mode; /* are we in command mode? */
179 } MonitorQMP;
182 * To prevent flooding clients, events can be throttled. The
183 * throttling is calculated globally, rather than per-Monitor
184 * instance.
186 typedef struct MonitorQAPIEventState {
187 QAPIEvent event; /* Throttling state for this event type and... */
188 QDict *data; /* ... data, see qapi_event_throttle_equal() */
189 QEMUTimer *timer; /* Timer for handling delayed events */
190 QDict *qdict; /* Delayed event (if any) */
191 } MonitorQAPIEventState;
193 typedef struct {
194 int64_t rate; /* Minimum time (in ns) between two events */
195 } MonitorQAPIEventConf;
197 struct Monitor {
198 CharDriverState *chr;
199 int reset_seen;
200 int flags;
201 int suspend_cnt;
202 bool skip_flush;
204 QemuMutex out_lock;
205 QString *outbuf;
206 guint out_watch;
208 /* Read under either BQL or out_lock, written with BQL+out_lock. */
209 int mux_out;
211 ReadLineState *rs;
212 MonitorQMP qmp;
213 CPUState *mon_cpu;
214 BlockCompletionFunc *password_completion_cb;
215 void *password_opaque;
216 mon_cmd_t *cmd_table;
217 QLIST_HEAD(,mon_fd_t) fds;
218 QLIST_ENTRY(Monitor) entry;
221 /* QMP checker flags */
222 #define QMP_ACCEPT_UNKNOWNS 1
224 /* Protects mon_list, monitor_event_state. */
225 static QemuMutex monitor_lock;
227 static QLIST_HEAD(mon_list, Monitor) mon_list;
228 static QLIST_HEAD(mon_fdsets, MonFdset) mon_fdsets;
229 static int mon_refcount;
231 static mon_cmd_t mon_cmds[];
232 static mon_cmd_t info_cmds[];
234 static const mon_cmd_t qmp_cmds[];
236 Monitor *cur_mon;
238 static QEMUClockType event_clock_type = QEMU_CLOCK_REALTIME;
240 static void monitor_command_cb(void *opaque, const char *cmdline,
241 void *readline_opaque);
244 * Is @mon a QMP monitor?
246 static inline bool monitor_is_qmp(const Monitor *mon)
248 return (mon->flags & MONITOR_USE_CONTROL);
252 * Is the current monitor, if any, a QMP monitor?
254 bool monitor_cur_is_qmp(void)
256 return cur_mon && monitor_is_qmp(cur_mon);
259 void monitor_read_command(Monitor *mon, int show_prompt)
261 if (!mon->rs)
262 return;
264 readline_start(mon->rs, "(qemu) ", 0, monitor_command_cb, NULL);
265 if (show_prompt)
266 readline_show_prompt(mon->rs);
269 int monitor_read_password(Monitor *mon, ReadLineFunc *readline_func,
270 void *opaque)
272 if (mon->rs) {
273 readline_start(mon->rs, "Password: ", 1, readline_func, opaque);
274 /* prompt is printed on return from the command handler */
275 return 0;
276 } else {
277 monitor_printf(mon, "terminal does not support password prompting\n");
278 return -ENOTTY;
282 static void monitor_flush_locked(Monitor *mon);
284 static gboolean monitor_unblocked(GIOChannel *chan, GIOCondition cond,
285 void *opaque)
287 Monitor *mon = opaque;
289 qemu_mutex_lock(&mon->out_lock);
290 mon->out_watch = 0;
291 monitor_flush_locked(mon);
292 qemu_mutex_unlock(&mon->out_lock);
293 return FALSE;
296 /* Called with mon->out_lock held. */
297 static void monitor_flush_locked(Monitor *mon)
299 int rc;
300 size_t len;
301 const char *buf;
303 if (mon->skip_flush) {
304 return;
307 buf = qstring_get_str(mon->outbuf);
308 len = qstring_get_length(mon->outbuf);
310 if (len && !mon->mux_out) {
311 rc = qemu_chr_fe_write(mon->chr, (const uint8_t *) buf, len);
312 if ((rc < 0 && errno != EAGAIN) || (rc == len)) {
313 /* all flushed or error */
314 QDECREF(mon->outbuf);
315 mon->outbuf = qstring_new();
316 return;
318 if (rc > 0) {
319 /* partial write */
320 QString *tmp = qstring_from_str(buf + rc);
321 QDECREF(mon->outbuf);
322 mon->outbuf = tmp;
324 if (mon->out_watch == 0) {
325 mon->out_watch = qemu_chr_fe_add_watch(mon->chr, G_IO_OUT|G_IO_HUP,
326 monitor_unblocked, mon);
331 void monitor_flush(Monitor *mon)
333 qemu_mutex_lock(&mon->out_lock);
334 monitor_flush_locked(mon);
335 qemu_mutex_unlock(&mon->out_lock);
338 /* flush at every end of line */
339 static void monitor_puts(Monitor *mon, const char *str)
341 char c;
343 qemu_mutex_lock(&mon->out_lock);
344 for(;;) {
345 c = *str++;
346 if (c == '\0')
347 break;
348 if (c == '\n') {
349 qstring_append_chr(mon->outbuf, '\r');
351 qstring_append_chr(mon->outbuf, c);
352 if (c == '\n') {
353 monitor_flush_locked(mon);
356 qemu_mutex_unlock(&mon->out_lock);
359 void monitor_vprintf(Monitor *mon, const char *fmt, va_list ap)
361 char *buf;
363 if (!mon)
364 return;
366 if (monitor_is_qmp(mon)) {
367 return;
370 buf = g_strdup_vprintf(fmt, ap);
371 monitor_puts(mon, buf);
372 g_free(buf);
375 void monitor_printf(Monitor *mon, const char *fmt, ...)
377 va_list ap;
378 va_start(ap, fmt);
379 monitor_vprintf(mon, fmt, ap);
380 va_end(ap);
383 int monitor_fprintf(FILE *stream, const char *fmt, ...)
385 va_list ap;
386 va_start(ap, fmt);
387 monitor_vprintf((Monitor *)stream, fmt, ap);
388 va_end(ap);
389 return 0;
392 static void monitor_json_emitter(Monitor *mon, const QObject *data)
394 QString *json;
396 json = mon->flags & MONITOR_USE_PRETTY ? qobject_to_json_pretty(data) :
397 qobject_to_json(data);
398 assert(json != NULL);
400 qstring_append_chr(json, '\n');
401 monitor_puts(mon, qstring_get_str(json));
403 QDECREF(json);
406 static QDict *build_qmp_error_dict(Error *err)
408 QObject *obj;
410 obj = qobject_from_jsonf("{ 'error': { 'class': %s, 'desc': %s } }",
411 QapiErrorClass_lookup[error_get_class(err)],
412 error_get_pretty(err));
414 return qobject_to_qdict(obj);
417 static void monitor_protocol_emitter(Monitor *mon, QObject *data,
418 Error *err)
420 QDict *qmp;
422 trace_monitor_protocol_emitter(mon);
424 if (!err) {
425 /* success response */
426 qmp = qdict_new();
427 if (data) {
428 qobject_incref(data);
429 qdict_put_obj(qmp, "return", data);
430 } else {
431 /* return an empty QDict by default */
432 qdict_put(qmp, "return", qdict_new());
434 } else {
435 /* error response */
436 qmp = build_qmp_error_dict(err);
439 if (mon->qmp.id) {
440 qdict_put_obj(qmp, "id", mon->qmp.id);
441 mon->qmp.id = NULL;
444 monitor_json_emitter(mon, QOBJECT(qmp));
445 QDECREF(qmp);
449 static MonitorQAPIEventConf monitor_qapi_event_conf[QAPI_EVENT__MAX] = {
450 /* Limit guest-triggerable events to 1 per second */
451 [QAPI_EVENT_RTC_CHANGE] = { 1000 * SCALE_MS },
452 [QAPI_EVENT_WATCHDOG] = { 1000 * SCALE_MS },
453 [QAPI_EVENT_BALLOON_CHANGE] = { 1000 * SCALE_MS },
454 [QAPI_EVENT_QUORUM_REPORT_BAD] = { 1000 * SCALE_MS },
455 [QAPI_EVENT_QUORUM_FAILURE] = { 1000 * SCALE_MS },
456 [QAPI_EVENT_VSERPORT_CHANGE] = { 1000 * SCALE_MS },
459 GHashTable *monitor_qapi_event_state;
462 * Emits the event to every monitor instance, @event is only used for trace
463 * Called with monitor_lock held.
465 static void monitor_qapi_event_emit(QAPIEvent event, QDict *qdict)
467 Monitor *mon;
469 trace_monitor_protocol_event_emit(event, qdict);
470 QLIST_FOREACH(mon, &mon_list, entry) {
471 if (monitor_is_qmp(mon) && mon->qmp.in_command_mode) {
472 monitor_json_emitter(mon, QOBJECT(qdict));
477 static void monitor_qapi_event_handler(void *opaque);
480 * Queue a new event for emission to Monitor instances,
481 * applying any rate limiting if required.
483 static void
484 monitor_qapi_event_queue(QAPIEvent event, QDict *qdict, Error **errp)
486 MonitorQAPIEventConf *evconf;
487 MonitorQAPIEventState *evstate;
489 assert(event < QAPI_EVENT__MAX);
490 evconf = &monitor_qapi_event_conf[event];
491 trace_monitor_protocol_event_queue(event, qdict, evconf->rate);
493 qemu_mutex_lock(&monitor_lock);
495 if (!evconf->rate) {
496 /* Unthrottled event */
497 monitor_qapi_event_emit(event, qdict);
498 } else {
499 QDict *data = qobject_to_qdict(qdict_get(qdict, "data"));
500 MonitorQAPIEventState key = { .event = event, .data = data };
502 evstate = g_hash_table_lookup(monitor_qapi_event_state, &key);
503 assert(!evstate || timer_pending(evstate->timer));
505 if (evstate) {
507 * Timer is pending for (at least) evconf->rate ns after
508 * last send. Store event for sending when timer fires,
509 * replacing a prior stored event if any.
511 QDECREF(evstate->qdict);
512 evstate->qdict = qdict;
513 QINCREF(evstate->qdict);
514 } else {
516 * Last send was (at least) evconf->rate ns ago.
517 * Send immediately, and arm the timer to call
518 * monitor_qapi_event_handler() in evconf->rate ns. Any
519 * events arriving before then will be delayed until then.
521 int64_t now = qemu_clock_get_ns(event_clock_type);
523 monitor_qapi_event_emit(event, qdict);
525 evstate = g_new(MonitorQAPIEventState, 1);
526 evstate->event = event;
527 evstate->data = data;
528 QINCREF(evstate->data);
529 evstate->qdict = NULL;
530 evstate->timer = timer_new_ns(event_clock_type,
531 monitor_qapi_event_handler,
532 evstate);
533 g_hash_table_add(monitor_qapi_event_state, evstate);
534 timer_mod_ns(evstate->timer, now + evconf->rate);
538 qemu_mutex_unlock(&monitor_lock);
542 * This function runs evconf->rate ns after sending a throttled
543 * event.
544 * If another event has since been stored, send it.
546 static void monitor_qapi_event_handler(void *opaque)
548 MonitorQAPIEventState *evstate = opaque;
549 MonitorQAPIEventConf *evconf = &monitor_qapi_event_conf[evstate->event];
551 trace_monitor_protocol_event_handler(evstate->event, evstate->qdict);
552 qemu_mutex_lock(&monitor_lock);
554 if (evstate->qdict) {
555 int64_t now = qemu_clock_get_ns(event_clock_type);
557 monitor_qapi_event_emit(evstate->event, evstate->qdict);
558 QDECREF(evstate->qdict);
559 evstate->qdict = NULL;
560 timer_mod_ns(evstate->timer, now + evconf->rate);
561 } else {
562 g_hash_table_remove(monitor_qapi_event_state, evstate);
563 QDECREF(evstate->data);
564 timer_free(evstate->timer);
565 g_free(evstate);
568 qemu_mutex_unlock(&monitor_lock);
571 static unsigned int qapi_event_throttle_hash(const void *key)
573 const MonitorQAPIEventState *evstate = key;
574 unsigned int hash = evstate->event * 255;
576 if (evstate->event == QAPI_EVENT_VSERPORT_CHANGE) {
577 hash += g_str_hash(qdict_get_str(evstate->data, "id"));
580 if (evstate->event == QAPI_EVENT_QUORUM_REPORT_BAD) {
581 hash += g_str_hash(qdict_get_str(evstate->data, "node-name"));
584 return hash;
587 static gboolean qapi_event_throttle_equal(const void *a, const void *b)
589 const MonitorQAPIEventState *eva = a;
590 const MonitorQAPIEventState *evb = b;
592 if (eva->event != evb->event) {
593 return FALSE;
596 if (eva->event == QAPI_EVENT_VSERPORT_CHANGE) {
597 return !strcmp(qdict_get_str(eva->data, "id"),
598 qdict_get_str(evb->data, "id"));
601 if (eva->event == QAPI_EVENT_QUORUM_REPORT_BAD) {
602 return !strcmp(qdict_get_str(eva->data, "node-name"),
603 qdict_get_str(evb->data, "node-name"));
606 return TRUE;
609 static void monitor_qapi_event_init(void)
611 if (qtest_enabled()) {
612 event_clock_type = QEMU_CLOCK_VIRTUAL;
615 monitor_qapi_event_state = g_hash_table_new(qapi_event_throttle_hash,
616 qapi_event_throttle_equal);
617 qmp_event_set_func_emit(monitor_qapi_event_queue);
620 static void qmp_capabilities(QDict *params, QObject **ret_data, Error **errp)
622 cur_mon->qmp.in_command_mode = true;
625 static void handle_hmp_command(Monitor *mon, const char *cmdline);
627 static void monitor_data_init(Monitor *mon)
629 memset(mon, 0, sizeof(Monitor));
630 qemu_mutex_init(&mon->out_lock);
631 mon->outbuf = qstring_new();
632 /* Use *mon_cmds by default. */
633 mon->cmd_table = mon_cmds;
636 static void monitor_data_destroy(Monitor *mon)
638 QDECREF(mon->outbuf);
639 qemu_mutex_destroy(&mon->out_lock);
642 char *qmp_human_monitor_command(const char *command_line, bool has_cpu_index,
643 int64_t cpu_index, Error **errp)
645 char *output = NULL;
646 Monitor *old_mon, hmp;
648 monitor_data_init(&hmp);
649 hmp.skip_flush = true;
651 old_mon = cur_mon;
652 cur_mon = &hmp;
654 if (has_cpu_index) {
655 int ret = monitor_set_cpu(cpu_index);
656 if (ret < 0) {
657 cur_mon = old_mon;
658 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cpu-index",
659 "a CPU number");
660 goto out;
664 handle_hmp_command(&hmp, command_line);
665 cur_mon = old_mon;
667 qemu_mutex_lock(&hmp.out_lock);
668 if (qstring_get_length(hmp.outbuf) > 0) {
669 output = g_strdup(qstring_get_str(hmp.outbuf));
670 } else {
671 output = g_strdup("");
673 qemu_mutex_unlock(&hmp.out_lock);
675 out:
676 monitor_data_destroy(&hmp);
677 return output;
680 static int compare_cmd(const char *name, const char *list)
682 const char *p, *pstart;
683 int len;
684 len = strlen(name);
685 p = list;
686 for(;;) {
687 pstart = p;
688 p = strchr(p, '|');
689 if (!p)
690 p = pstart + strlen(pstart);
691 if ((p - pstart) == len && !memcmp(pstart, name, len))
692 return 1;
693 if (*p == '\0')
694 break;
695 p++;
697 return 0;
700 static int get_str(char *buf, int buf_size, const char **pp)
702 const char *p;
703 char *q;
704 int c;
706 q = buf;
707 p = *pp;
708 while (qemu_isspace(*p)) {
709 p++;
711 if (*p == '\0') {
712 fail:
713 *q = '\0';
714 *pp = p;
715 return -1;
717 if (*p == '\"') {
718 p++;
719 while (*p != '\0' && *p != '\"') {
720 if (*p == '\\') {
721 p++;
722 c = *p++;
723 switch (c) {
724 case 'n':
725 c = '\n';
726 break;
727 case 'r':
728 c = '\r';
729 break;
730 case '\\':
731 case '\'':
732 case '\"':
733 break;
734 default:
735 printf("unsupported escape code: '\\%c'\n", c);
736 goto fail;
738 if ((q - buf) < buf_size - 1) {
739 *q++ = c;
741 } else {
742 if ((q - buf) < buf_size - 1) {
743 *q++ = *p;
745 p++;
748 if (*p != '\"') {
749 printf("unterminated string\n");
750 goto fail;
752 p++;
753 } else {
754 while (*p != '\0' && !qemu_isspace(*p)) {
755 if ((q - buf) < buf_size - 1) {
756 *q++ = *p;
758 p++;
761 *q = '\0';
762 *pp = p;
763 return 0;
766 #define MAX_ARGS 16
768 static void free_cmdline_args(char **args, int nb_args)
770 int i;
772 assert(nb_args <= MAX_ARGS);
774 for (i = 0; i < nb_args; i++) {
775 g_free(args[i]);
781 * Parse the command line to get valid args.
782 * @cmdline: command line to be parsed.
783 * @pnb_args: location to store the number of args, must NOT be NULL.
784 * @args: location to store the args, which should be freed by caller, must
785 * NOT be NULL.
787 * Returns 0 on success, negative on failure.
789 * NOTE: this parser is an approximate form of the real command parser. Number
790 * of args have a limit of MAX_ARGS. If cmdline contains more, it will
791 * return with failure.
793 static int parse_cmdline(const char *cmdline,
794 int *pnb_args, char **args)
796 const char *p;
797 int nb_args, ret;
798 char buf[1024];
800 p = cmdline;
801 nb_args = 0;
802 for (;;) {
803 while (qemu_isspace(*p)) {
804 p++;
806 if (*p == '\0') {
807 break;
809 if (nb_args >= MAX_ARGS) {
810 goto fail;
812 ret = get_str(buf, sizeof(buf), &p);
813 if (ret < 0) {
814 goto fail;
816 args[nb_args] = g_strdup(buf);
817 nb_args++;
819 *pnb_args = nb_args;
820 return 0;
822 fail:
823 free_cmdline_args(args, nb_args);
824 return -1;
827 static void help_cmd_dump_one(Monitor *mon,
828 const mon_cmd_t *cmd,
829 char **prefix_args,
830 int prefix_args_nb)
832 int i;
834 for (i = 0; i < prefix_args_nb; i++) {
835 monitor_printf(mon, "%s ", prefix_args[i]);
837 monitor_printf(mon, "%s %s -- %s\n", cmd->name, cmd->params, cmd->help);
840 /* @args[@arg_index] is the valid command need to find in @cmds */
841 static void help_cmd_dump(Monitor *mon, const mon_cmd_t *cmds,
842 char **args, int nb_args, int arg_index)
844 const mon_cmd_t *cmd;
846 /* No valid arg need to compare with, dump all in *cmds */
847 if (arg_index >= nb_args) {
848 for (cmd = cmds; cmd->name != NULL; cmd++) {
849 help_cmd_dump_one(mon, cmd, args, arg_index);
851 return;
854 /* Find one entry to dump */
855 for (cmd = cmds; cmd->name != NULL; cmd++) {
856 if (compare_cmd(args[arg_index], cmd->name)) {
857 if (cmd->sub_table) {
858 /* continue with next arg */
859 help_cmd_dump(mon, cmd->sub_table,
860 args, nb_args, arg_index + 1);
861 } else {
862 help_cmd_dump_one(mon, cmd, args, arg_index);
864 break;
869 static void help_cmd(Monitor *mon, const char *name)
871 char *args[MAX_ARGS];
872 int nb_args = 0;
874 /* 1. parse user input */
875 if (name) {
876 /* special case for log, directly dump and return */
877 if (!strcmp(name, "log")) {
878 const QEMULogItem *item;
879 monitor_printf(mon, "Log items (comma separated):\n");
880 monitor_printf(mon, "%-10s %s\n", "none", "remove all logs");
881 for (item = qemu_log_items; item->mask != 0; item++) {
882 monitor_printf(mon, "%-10s %s\n", item->name, item->help);
884 return;
887 if (parse_cmdline(name, &nb_args, args) < 0) {
888 return;
892 /* 2. dump the contents according to parsed args */
893 help_cmd_dump(mon, mon->cmd_table, args, nb_args, 0);
895 free_cmdline_args(args, nb_args);
898 static void do_help_cmd(Monitor *mon, const QDict *qdict)
900 help_cmd(mon, qdict_get_try_str(qdict, "name"));
903 static void hmp_trace_event(Monitor *mon, const QDict *qdict)
905 const char *tp_name = qdict_get_str(qdict, "name");
906 bool new_state = qdict_get_bool(qdict, "option");
907 Error *local_err = NULL;
909 qmp_trace_event_set_state(tp_name, new_state, true, true, &local_err);
910 if (local_err) {
911 error_report_err(local_err);
915 #ifdef CONFIG_TRACE_SIMPLE
916 static void hmp_trace_file(Monitor *mon, const QDict *qdict)
918 const char *op = qdict_get_try_str(qdict, "op");
919 const char *arg = qdict_get_try_str(qdict, "arg");
921 if (!op) {
922 st_print_trace_file_status((FILE *)mon, &monitor_fprintf);
923 } else if (!strcmp(op, "on")) {
924 st_set_trace_file_enabled(true);
925 } else if (!strcmp(op, "off")) {
926 st_set_trace_file_enabled(false);
927 } else if (!strcmp(op, "flush")) {
928 st_flush_trace_buffer();
929 } else if (!strcmp(op, "set")) {
930 if (arg) {
931 st_set_trace_file(arg);
933 } else {
934 monitor_printf(mon, "unexpected argument \"%s\"\n", op);
935 help_cmd(mon, "trace-file");
938 #endif
940 static void hmp_info_help(Monitor *mon, const QDict *qdict)
942 help_cmd(mon, "info");
945 CommandInfoList *qmp_query_commands(Error **errp)
947 CommandInfoList *info, *cmd_list = NULL;
948 const mon_cmd_t *cmd;
950 for (cmd = qmp_cmds; cmd->name != NULL; cmd++) {
951 info = g_malloc0(sizeof(*info));
952 info->value = g_malloc0(sizeof(*info->value));
953 info->value->name = g_strdup(cmd->name);
955 info->next = cmd_list;
956 cmd_list = info;
959 return cmd_list;
962 EventInfoList *qmp_query_events(Error **errp)
964 EventInfoList *info, *ev_list = NULL;
965 QAPIEvent e;
967 for (e = 0 ; e < QAPI_EVENT__MAX ; e++) {
968 const char *event_name = QAPIEvent_lookup[e];
969 assert(event_name != NULL);
970 info = g_malloc0(sizeof(*info));
971 info->value = g_malloc0(sizeof(*info->value));
972 info->value->name = g_strdup(event_name);
974 info->next = ev_list;
975 ev_list = info;
978 return ev_list;
982 * Minor hack: generated marshalling suppressed for this command
983 * ('gen': false in the schema) so we can parse the JSON string
984 * directly into QObject instead of first parsing it with
985 * visit_type_SchemaInfoList() into a SchemaInfoList, then marshal it
986 * to QObject with generated output marshallers, every time. Instead,
987 * we do it in test-qmp-input-visitor.c, just to make sure
988 * qapi-introspect.py's output actually conforms to the schema.
990 static void qmp_query_qmp_schema(QDict *qdict, QObject **ret_data,
991 Error **errp)
993 *ret_data = qobject_from_json(qmp_schema_json);
996 /* set the current CPU defined by the user */
997 int monitor_set_cpu(int cpu_index)
999 CPUState *cpu;
1001 cpu = qemu_get_cpu(cpu_index);
1002 if (cpu == NULL) {
1003 return -1;
1005 cur_mon->mon_cpu = cpu;
1006 return 0;
1009 CPUState *mon_get_cpu(void)
1011 if (!cur_mon->mon_cpu) {
1012 monitor_set_cpu(0);
1014 cpu_synchronize_state(cur_mon->mon_cpu);
1015 return cur_mon->mon_cpu;
1018 CPUArchState *mon_get_cpu_env(void)
1020 return mon_get_cpu()->env_ptr;
1023 int monitor_get_cpu_index(void)
1025 return mon_get_cpu()->cpu_index;
1028 static void hmp_info_registers(Monitor *mon, const QDict *qdict)
1030 cpu_dump_state(mon_get_cpu(), (FILE *)mon, monitor_fprintf, CPU_DUMP_FPU);
1033 static void hmp_info_jit(Monitor *mon, const QDict *qdict)
1035 dump_exec_info((FILE *)mon, monitor_fprintf);
1036 dump_drift_info((FILE *)mon, monitor_fprintf);
1039 static void hmp_info_opcount(Monitor *mon, const QDict *qdict)
1041 dump_opcount_info((FILE *)mon, monitor_fprintf);
1044 static void hmp_info_history(Monitor *mon, const QDict *qdict)
1046 int i;
1047 const char *str;
1049 if (!mon->rs)
1050 return;
1051 i = 0;
1052 for(;;) {
1053 str = readline_get_history(mon->rs, i);
1054 if (!str)
1055 break;
1056 monitor_printf(mon, "%d: '%s'\n", i, str);
1057 i++;
1061 static void hmp_info_cpustats(Monitor *mon, const QDict *qdict)
1063 cpu_dump_statistics(mon_get_cpu(), (FILE *)mon, &monitor_fprintf, 0);
1066 static void hmp_info_trace_events(Monitor *mon, const QDict *qdict)
1068 TraceEventInfoList *events = qmp_trace_event_get_state("*", NULL);
1069 TraceEventInfoList *elem;
1071 for (elem = events; elem != NULL; elem = elem->next) {
1072 monitor_printf(mon, "%s : state %u\n",
1073 elem->value->name,
1074 elem->value->state == TRACE_EVENT_STATE_ENABLED ? 1 : 0);
1076 qapi_free_TraceEventInfoList(events);
1079 void qmp_client_migrate_info(const char *protocol, const char *hostname,
1080 bool has_port, int64_t port,
1081 bool has_tls_port, int64_t tls_port,
1082 bool has_cert_subject, const char *cert_subject,
1083 Error **errp)
1085 if (strcmp(protocol, "spice") == 0) {
1086 if (!qemu_using_spice(errp)) {
1087 return;
1090 if (!has_port && !has_tls_port) {
1091 error_setg(errp, QERR_MISSING_PARAMETER, "port/tls-port");
1092 return;
1095 if (qemu_spice_migrate_info(hostname,
1096 has_port ? port : -1,
1097 has_tls_port ? tls_port : -1,
1098 cert_subject)) {
1099 error_setg(errp, QERR_UNDEFINED_ERROR);
1100 return;
1102 return;
1105 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "protocol", "spice");
1108 static void hmp_logfile(Monitor *mon, const QDict *qdict)
1110 Error *err = NULL;
1112 qemu_set_log_filename(qdict_get_str(qdict, "filename"), &err);
1113 if (err) {
1114 error_report_err(err);
1118 static void hmp_log(Monitor *mon, const QDict *qdict)
1120 int mask;
1121 const char *items = qdict_get_str(qdict, "items");
1123 if (!strcmp(items, "none")) {
1124 mask = 0;
1125 } else {
1126 mask = qemu_str_to_log_mask(items);
1127 if (!mask) {
1128 help_cmd(mon, "log");
1129 return;
1132 qemu_set_log(mask);
1135 static void hmp_singlestep(Monitor *mon, const QDict *qdict)
1137 const char *option = qdict_get_try_str(qdict, "option");
1138 if (!option || !strcmp(option, "on")) {
1139 singlestep = 1;
1140 } else if (!strcmp(option, "off")) {
1141 singlestep = 0;
1142 } else {
1143 monitor_printf(mon, "unexpected option %s\n", option);
1147 static void hmp_gdbserver(Monitor *mon, const QDict *qdict)
1149 const char *device = qdict_get_try_str(qdict, "device");
1150 if (!device)
1151 device = "tcp::" DEFAULT_GDBSTUB_PORT;
1152 if (gdbserver_start(device) < 0) {
1153 monitor_printf(mon, "Could not open gdbserver on device '%s'\n",
1154 device);
1155 } else if (strcmp(device, "none") == 0) {
1156 monitor_printf(mon, "Disabled gdbserver\n");
1157 } else {
1158 monitor_printf(mon, "Waiting for gdb connection on device '%s'\n",
1159 device);
1163 static void hmp_watchdog_action(Monitor *mon, const QDict *qdict)
1165 const char *action = qdict_get_str(qdict, "action");
1166 if (select_watchdog_action(action) == -1) {
1167 monitor_printf(mon, "Unknown watchdog action '%s'\n", action);
1171 static void monitor_printc(Monitor *mon, int c)
1173 monitor_printf(mon, "'");
1174 switch(c) {
1175 case '\'':
1176 monitor_printf(mon, "\\'");
1177 break;
1178 case '\\':
1179 monitor_printf(mon, "\\\\");
1180 break;
1181 case '\n':
1182 monitor_printf(mon, "\\n");
1183 break;
1184 case '\r':
1185 monitor_printf(mon, "\\r");
1186 break;
1187 default:
1188 if (c >= 32 && c <= 126) {
1189 monitor_printf(mon, "%c", c);
1190 } else {
1191 monitor_printf(mon, "\\x%02x", c);
1193 break;
1195 monitor_printf(mon, "'");
1198 static void memory_dump(Monitor *mon, int count, int format, int wsize,
1199 hwaddr addr, int is_physical)
1201 int l, line_size, i, max_digits, len;
1202 uint8_t buf[16];
1203 uint64_t v;
1205 if (format == 'i') {
1206 int flags = 0;
1207 #ifdef TARGET_I386
1208 CPUArchState *env = mon_get_cpu_env();
1209 if (wsize == 2) {
1210 flags = 1;
1211 } else if (wsize == 4) {
1212 flags = 0;
1213 } else {
1214 /* as default we use the current CS size */
1215 flags = 0;
1216 if (env) {
1217 #ifdef TARGET_X86_64
1218 if ((env->efer & MSR_EFER_LMA) &&
1219 (env->segs[R_CS].flags & DESC_L_MASK))
1220 flags = 2;
1221 else
1222 #endif
1223 if (!(env->segs[R_CS].flags & DESC_B_MASK))
1224 flags = 1;
1227 #endif
1228 #ifdef TARGET_PPC
1229 CPUArchState *env = mon_get_cpu_env();
1230 flags = msr_le << 16;
1231 flags |= env->bfd_mach;
1232 #endif
1233 monitor_disas(mon, mon_get_cpu(), addr, count, is_physical, flags);
1234 return;
1237 len = wsize * count;
1238 if (wsize == 1)
1239 line_size = 8;
1240 else
1241 line_size = 16;
1242 max_digits = 0;
1244 switch(format) {
1245 case 'o':
1246 max_digits = (wsize * 8 + 2) / 3;
1247 break;
1248 default:
1249 case 'x':
1250 max_digits = (wsize * 8) / 4;
1251 break;
1252 case 'u':
1253 case 'd':
1254 max_digits = (wsize * 8 * 10 + 32) / 33;
1255 break;
1256 case 'c':
1257 wsize = 1;
1258 break;
1261 while (len > 0) {
1262 if (is_physical)
1263 monitor_printf(mon, TARGET_FMT_plx ":", addr);
1264 else
1265 monitor_printf(mon, TARGET_FMT_lx ":", (target_ulong)addr);
1266 l = len;
1267 if (l > line_size)
1268 l = line_size;
1269 if (is_physical) {
1270 cpu_physical_memory_read(addr, buf, l);
1271 } else {
1272 if (cpu_memory_rw_debug(mon_get_cpu(), addr, buf, l, 0) < 0) {
1273 monitor_printf(mon, " Cannot access memory\n");
1274 break;
1277 i = 0;
1278 while (i < l) {
1279 switch(wsize) {
1280 default:
1281 case 1:
1282 v = ldub_p(buf + i);
1283 break;
1284 case 2:
1285 v = lduw_p(buf + i);
1286 break;
1287 case 4:
1288 v = (uint32_t)ldl_p(buf + i);
1289 break;
1290 case 8:
1291 v = ldq_p(buf + i);
1292 break;
1294 monitor_printf(mon, " ");
1295 switch(format) {
1296 case 'o':
1297 monitor_printf(mon, "%#*" PRIo64, max_digits, v);
1298 break;
1299 case 'x':
1300 monitor_printf(mon, "0x%0*" PRIx64, max_digits, v);
1301 break;
1302 case 'u':
1303 monitor_printf(mon, "%*" PRIu64, max_digits, v);
1304 break;
1305 case 'd':
1306 monitor_printf(mon, "%*" PRId64, max_digits, v);
1307 break;
1308 case 'c':
1309 monitor_printc(mon, v);
1310 break;
1312 i += wsize;
1314 monitor_printf(mon, "\n");
1315 addr += l;
1316 len -= l;
1320 static void hmp_memory_dump(Monitor *mon, const QDict *qdict)
1322 int count = qdict_get_int(qdict, "count");
1323 int format = qdict_get_int(qdict, "format");
1324 int size = qdict_get_int(qdict, "size");
1325 target_long addr = qdict_get_int(qdict, "addr");
1327 memory_dump(mon, count, format, size, addr, 0);
1330 static void hmp_physical_memory_dump(Monitor *mon, const QDict *qdict)
1332 int count = qdict_get_int(qdict, "count");
1333 int format = qdict_get_int(qdict, "format");
1334 int size = qdict_get_int(qdict, "size");
1335 hwaddr addr = qdict_get_int(qdict, "addr");
1337 memory_dump(mon, count, format, size, addr, 1);
1340 static void do_print(Monitor *mon, const QDict *qdict)
1342 int format = qdict_get_int(qdict, "format");
1343 hwaddr val = qdict_get_int(qdict, "val");
1345 switch(format) {
1346 case 'o':
1347 monitor_printf(mon, "%#" HWADDR_PRIo, val);
1348 break;
1349 case 'x':
1350 monitor_printf(mon, "%#" HWADDR_PRIx, val);
1351 break;
1352 case 'u':
1353 monitor_printf(mon, "%" HWADDR_PRIu, val);
1354 break;
1355 default:
1356 case 'd':
1357 monitor_printf(mon, "%" HWADDR_PRId, val);
1358 break;
1359 case 'c':
1360 monitor_printc(mon, val);
1361 break;
1363 monitor_printf(mon, "\n");
1366 static void hmp_sum(Monitor *mon, const QDict *qdict)
1368 uint32_t addr;
1369 uint16_t sum;
1370 uint32_t start = qdict_get_int(qdict, "start");
1371 uint32_t size = qdict_get_int(qdict, "size");
1373 sum = 0;
1374 for(addr = start; addr < (start + size); addr++) {
1375 uint8_t val = address_space_ldub(&address_space_memory, addr,
1376 MEMTXATTRS_UNSPECIFIED, NULL);
1377 /* BSD sum algorithm ('sum' Unix command) */
1378 sum = (sum >> 1) | (sum << 15);
1379 sum += val;
1381 monitor_printf(mon, "%05d\n", sum);
1384 static int mouse_button_state;
1386 static void hmp_mouse_move(Monitor *mon, const QDict *qdict)
1388 int dx, dy, dz, button;
1389 const char *dx_str = qdict_get_str(qdict, "dx_str");
1390 const char *dy_str = qdict_get_str(qdict, "dy_str");
1391 const char *dz_str = qdict_get_try_str(qdict, "dz_str");
1393 dx = strtol(dx_str, NULL, 0);
1394 dy = strtol(dy_str, NULL, 0);
1395 qemu_input_queue_rel(NULL, INPUT_AXIS_X, dx);
1396 qemu_input_queue_rel(NULL, INPUT_AXIS_Y, dy);
1398 if (dz_str) {
1399 dz = strtol(dz_str, NULL, 0);
1400 if (dz != 0) {
1401 button = (dz > 0) ? INPUT_BUTTON_WHEEL_UP : INPUT_BUTTON_WHEEL_DOWN;
1402 qemu_input_queue_btn(NULL, button, true);
1403 qemu_input_event_sync();
1404 qemu_input_queue_btn(NULL, button, false);
1407 qemu_input_event_sync();
1410 static void hmp_mouse_button(Monitor *mon, const QDict *qdict)
1412 static uint32_t bmap[INPUT_BUTTON__MAX] = {
1413 [INPUT_BUTTON_LEFT] = MOUSE_EVENT_LBUTTON,
1414 [INPUT_BUTTON_MIDDLE] = MOUSE_EVENT_MBUTTON,
1415 [INPUT_BUTTON_RIGHT] = MOUSE_EVENT_RBUTTON,
1417 int button_state = qdict_get_int(qdict, "button_state");
1419 if (mouse_button_state == button_state) {
1420 return;
1422 qemu_input_update_buttons(NULL, bmap, mouse_button_state, button_state);
1423 qemu_input_event_sync();
1424 mouse_button_state = button_state;
1427 static void hmp_ioport_read(Monitor *mon, const QDict *qdict)
1429 int size = qdict_get_int(qdict, "size");
1430 int addr = qdict_get_int(qdict, "addr");
1431 int has_index = qdict_haskey(qdict, "index");
1432 uint32_t val;
1433 int suffix;
1435 if (has_index) {
1436 int index = qdict_get_int(qdict, "index");
1437 cpu_outb(addr & IOPORTS_MASK, index & 0xff);
1438 addr++;
1440 addr &= 0xffff;
1442 switch(size) {
1443 default:
1444 case 1:
1445 val = cpu_inb(addr);
1446 suffix = 'b';
1447 break;
1448 case 2:
1449 val = cpu_inw(addr);
1450 suffix = 'w';
1451 break;
1452 case 4:
1453 val = cpu_inl(addr);
1454 suffix = 'l';
1455 break;
1457 monitor_printf(mon, "port%c[0x%04x] = %#0*x\n",
1458 suffix, addr, size * 2, val);
1461 static void hmp_ioport_write(Monitor *mon, const QDict *qdict)
1463 int size = qdict_get_int(qdict, "size");
1464 int addr = qdict_get_int(qdict, "addr");
1465 int val = qdict_get_int(qdict, "val");
1467 addr &= IOPORTS_MASK;
1469 switch (size) {
1470 default:
1471 case 1:
1472 cpu_outb(addr, val);
1473 break;
1474 case 2:
1475 cpu_outw(addr, val);
1476 break;
1477 case 4:
1478 cpu_outl(addr, val);
1479 break;
1483 static void hmp_boot_set(Monitor *mon, const QDict *qdict)
1485 Error *local_err = NULL;
1486 const char *bootdevice = qdict_get_str(qdict, "bootdevice");
1488 qemu_boot_set(bootdevice, &local_err);
1489 if (local_err) {
1490 error_report_err(local_err);
1491 } else {
1492 monitor_printf(mon, "boot device list now set to %s\n", bootdevice);
1496 static void hmp_info_mtree(Monitor *mon, const QDict *qdict)
1498 mtree_info((fprintf_function)monitor_printf, mon);
1501 static void hmp_info_numa(Monitor *mon, const QDict *qdict)
1503 int i;
1504 CPUState *cpu;
1505 uint64_t *node_mem;
1507 node_mem = g_new0(uint64_t, nb_numa_nodes);
1508 query_numa_node_mem(node_mem);
1509 monitor_printf(mon, "%d nodes\n", nb_numa_nodes);
1510 for (i = 0; i < nb_numa_nodes; i++) {
1511 monitor_printf(mon, "node %d cpus:", i);
1512 CPU_FOREACH(cpu) {
1513 if (cpu->numa_node == i) {
1514 monitor_printf(mon, " %d", cpu->cpu_index);
1517 monitor_printf(mon, "\n");
1518 monitor_printf(mon, "node %d size: %" PRId64 " MB\n", i,
1519 node_mem[i] >> 20);
1521 g_free(node_mem);
1524 #ifdef CONFIG_PROFILER
1526 int64_t tcg_time;
1527 int64_t dev_time;
1529 static void hmp_info_profile(Monitor *mon, const QDict *qdict)
1531 monitor_printf(mon, "async time %" PRId64 " (%0.3f)\n",
1532 dev_time, dev_time / (double)NANOSECONDS_PER_SECOND);
1533 monitor_printf(mon, "qemu time %" PRId64 " (%0.3f)\n",
1534 tcg_time, tcg_time / (double)NANOSECONDS_PER_SECOND);
1535 tcg_time = 0;
1536 dev_time = 0;
1538 #else
1539 static void hmp_info_profile(Monitor *mon, const QDict *qdict)
1541 monitor_printf(mon, "Internal profiler not compiled\n");
1543 #endif
1545 /* Capture support */
1546 static QLIST_HEAD (capture_list_head, CaptureState) capture_head;
1548 static void hmp_info_capture(Monitor *mon, const QDict *qdict)
1550 int i;
1551 CaptureState *s;
1553 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
1554 monitor_printf(mon, "[%d]: ", i);
1555 s->ops.info (s->opaque);
1559 static void hmp_stopcapture(Monitor *mon, const QDict *qdict)
1561 int i;
1562 int n = qdict_get_int(qdict, "n");
1563 CaptureState *s;
1565 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
1566 if (i == n) {
1567 s->ops.destroy (s->opaque);
1568 QLIST_REMOVE (s, entries);
1569 g_free (s);
1570 return;
1575 static void hmp_wavcapture(Monitor *mon, const QDict *qdict)
1577 const char *path = qdict_get_str(qdict, "path");
1578 int has_freq = qdict_haskey(qdict, "freq");
1579 int freq = qdict_get_try_int(qdict, "freq", -1);
1580 int has_bits = qdict_haskey(qdict, "bits");
1581 int bits = qdict_get_try_int(qdict, "bits", -1);
1582 int has_channels = qdict_haskey(qdict, "nchannels");
1583 int nchannels = qdict_get_try_int(qdict, "nchannels", -1);
1584 CaptureState *s;
1586 s = g_malloc0 (sizeof (*s));
1588 freq = has_freq ? freq : 44100;
1589 bits = has_bits ? bits : 16;
1590 nchannels = has_channels ? nchannels : 2;
1592 if (wav_start_capture (s, path, freq, bits, nchannels)) {
1593 monitor_printf(mon, "Failed to add wave capture\n");
1594 g_free (s);
1595 return;
1597 QLIST_INSERT_HEAD (&capture_head, s, entries);
1600 static qemu_acl *find_acl(Monitor *mon, const char *name)
1602 qemu_acl *acl = qemu_acl_find(name);
1604 if (!acl) {
1605 monitor_printf(mon, "acl: unknown list '%s'\n", name);
1607 return acl;
1610 static void hmp_acl_show(Monitor *mon, const QDict *qdict)
1612 const char *aclname = qdict_get_str(qdict, "aclname");
1613 qemu_acl *acl = find_acl(mon, aclname);
1614 qemu_acl_entry *entry;
1615 int i = 0;
1617 if (acl) {
1618 monitor_printf(mon, "policy: %s\n",
1619 acl->defaultDeny ? "deny" : "allow");
1620 QTAILQ_FOREACH(entry, &acl->entries, next) {
1621 i++;
1622 monitor_printf(mon, "%d: %s %s\n", i,
1623 entry->deny ? "deny" : "allow", entry->match);
1628 static void hmp_acl_reset(Monitor *mon, const QDict *qdict)
1630 const char *aclname = qdict_get_str(qdict, "aclname");
1631 qemu_acl *acl = find_acl(mon, aclname);
1633 if (acl) {
1634 qemu_acl_reset(acl);
1635 monitor_printf(mon, "acl: removed all rules\n");
1639 static void hmp_acl_policy(Monitor *mon, const QDict *qdict)
1641 const char *aclname = qdict_get_str(qdict, "aclname");
1642 const char *policy = qdict_get_str(qdict, "policy");
1643 qemu_acl *acl = find_acl(mon, aclname);
1645 if (acl) {
1646 if (strcmp(policy, "allow") == 0) {
1647 acl->defaultDeny = 0;
1648 monitor_printf(mon, "acl: policy set to 'allow'\n");
1649 } else if (strcmp(policy, "deny") == 0) {
1650 acl->defaultDeny = 1;
1651 monitor_printf(mon, "acl: policy set to 'deny'\n");
1652 } else {
1653 monitor_printf(mon, "acl: unknown policy '%s', "
1654 "expected 'deny' or 'allow'\n", policy);
1659 static void hmp_acl_add(Monitor *mon, const QDict *qdict)
1661 const char *aclname = qdict_get_str(qdict, "aclname");
1662 const char *match = qdict_get_str(qdict, "match");
1663 const char *policy = qdict_get_str(qdict, "policy");
1664 int has_index = qdict_haskey(qdict, "index");
1665 int index = qdict_get_try_int(qdict, "index", -1);
1666 qemu_acl *acl = find_acl(mon, aclname);
1667 int deny, ret;
1669 if (acl) {
1670 if (strcmp(policy, "allow") == 0) {
1671 deny = 0;
1672 } else if (strcmp(policy, "deny") == 0) {
1673 deny = 1;
1674 } else {
1675 monitor_printf(mon, "acl: unknown policy '%s', "
1676 "expected 'deny' or 'allow'\n", policy);
1677 return;
1679 if (has_index)
1680 ret = qemu_acl_insert(acl, deny, match, index);
1681 else
1682 ret = qemu_acl_append(acl, deny, match);
1683 if (ret < 0)
1684 monitor_printf(mon, "acl: unable to add acl entry\n");
1685 else
1686 monitor_printf(mon, "acl: added rule at position %d\n", ret);
1690 static void hmp_acl_remove(Monitor *mon, const QDict *qdict)
1692 const char *aclname = qdict_get_str(qdict, "aclname");
1693 const char *match = qdict_get_str(qdict, "match");
1694 qemu_acl *acl = find_acl(mon, aclname);
1695 int ret;
1697 if (acl) {
1698 ret = qemu_acl_remove(acl, match);
1699 if (ret < 0)
1700 monitor_printf(mon, "acl: no matching acl entry\n");
1701 else
1702 monitor_printf(mon, "acl: removed rule at position %d\n", ret);
1706 void qmp_getfd(const char *fdname, Error **errp)
1708 mon_fd_t *monfd;
1709 int fd;
1711 fd = qemu_chr_fe_get_msgfd(cur_mon->chr);
1712 if (fd == -1) {
1713 error_setg(errp, QERR_FD_NOT_SUPPLIED);
1714 return;
1717 if (qemu_isdigit(fdname[0])) {
1718 close(fd);
1719 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "fdname",
1720 "a name not starting with a digit");
1721 return;
1724 QLIST_FOREACH(monfd, &cur_mon->fds, next) {
1725 if (strcmp(monfd->name, fdname) != 0) {
1726 continue;
1729 close(monfd->fd);
1730 monfd->fd = fd;
1731 return;
1734 monfd = g_malloc0(sizeof(mon_fd_t));
1735 monfd->name = g_strdup(fdname);
1736 monfd->fd = fd;
1738 QLIST_INSERT_HEAD(&cur_mon->fds, monfd, next);
1741 void qmp_closefd(const char *fdname, Error **errp)
1743 mon_fd_t *monfd;
1745 QLIST_FOREACH(monfd, &cur_mon->fds, next) {
1746 if (strcmp(monfd->name, fdname) != 0) {
1747 continue;
1750 QLIST_REMOVE(monfd, next);
1751 close(monfd->fd);
1752 g_free(monfd->name);
1753 g_free(monfd);
1754 return;
1757 error_setg(errp, QERR_FD_NOT_FOUND, fdname);
1760 static void hmp_loadvm(Monitor *mon, const QDict *qdict)
1762 int saved_vm_running = runstate_is_running();
1763 const char *name = qdict_get_str(qdict, "name");
1765 vm_stop(RUN_STATE_RESTORE_VM);
1767 if (load_vmstate(name) == 0 && saved_vm_running) {
1768 vm_start();
1772 int monitor_get_fd(Monitor *mon, const char *fdname, Error **errp)
1774 mon_fd_t *monfd;
1776 QLIST_FOREACH(monfd, &mon->fds, next) {
1777 int fd;
1779 if (strcmp(monfd->name, fdname) != 0) {
1780 continue;
1783 fd = monfd->fd;
1785 /* caller takes ownership of fd */
1786 QLIST_REMOVE(monfd, next);
1787 g_free(monfd->name);
1788 g_free(monfd);
1790 return fd;
1793 error_setg(errp, "File descriptor named '%s' has not been found", fdname);
1794 return -1;
1797 static void monitor_fdset_cleanup(MonFdset *mon_fdset)
1799 MonFdsetFd *mon_fdset_fd;
1800 MonFdsetFd *mon_fdset_fd_next;
1802 QLIST_FOREACH_SAFE(mon_fdset_fd, &mon_fdset->fds, next, mon_fdset_fd_next) {
1803 if ((mon_fdset_fd->removed ||
1804 (QLIST_EMPTY(&mon_fdset->dup_fds) && mon_refcount == 0)) &&
1805 runstate_is_running()) {
1806 close(mon_fdset_fd->fd);
1807 g_free(mon_fdset_fd->opaque);
1808 QLIST_REMOVE(mon_fdset_fd, next);
1809 g_free(mon_fdset_fd);
1813 if (QLIST_EMPTY(&mon_fdset->fds) && QLIST_EMPTY(&mon_fdset->dup_fds)) {
1814 QLIST_REMOVE(mon_fdset, next);
1815 g_free(mon_fdset);
1819 static void monitor_fdsets_cleanup(void)
1821 MonFdset *mon_fdset;
1822 MonFdset *mon_fdset_next;
1824 QLIST_FOREACH_SAFE(mon_fdset, &mon_fdsets, next, mon_fdset_next) {
1825 monitor_fdset_cleanup(mon_fdset);
1829 AddfdInfo *qmp_add_fd(bool has_fdset_id, int64_t fdset_id, bool has_opaque,
1830 const char *opaque, Error **errp)
1832 int fd;
1833 Monitor *mon = cur_mon;
1834 AddfdInfo *fdinfo;
1836 fd = qemu_chr_fe_get_msgfd(mon->chr);
1837 if (fd == -1) {
1838 error_setg(errp, QERR_FD_NOT_SUPPLIED);
1839 goto error;
1842 fdinfo = monitor_fdset_add_fd(fd, has_fdset_id, fdset_id,
1843 has_opaque, opaque, errp);
1844 if (fdinfo) {
1845 return fdinfo;
1848 error:
1849 if (fd != -1) {
1850 close(fd);
1852 return NULL;
1855 void qmp_remove_fd(int64_t fdset_id, bool has_fd, int64_t fd, Error **errp)
1857 MonFdset *mon_fdset;
1858 MonFdsetFd *mon_fdset_fd;
1859 char fd_str[60];
1861 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
1862 if (mon_fdset->id != fdset_id) {
1863 continue;
1865 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
1866 if (has_fd) {
1867 if (mon_fdset_fd->fd != fd) {
1868 continue;
1870 mon_fdset_fd->removed = true;
1871 break;
1872 } else {
1873 mon_fdset_fd->removed = true;
1876 if (has_fd && !mon_fdset_fd) {
1877 goto error;
1879 monitor_fdset_cleanup(mon_fdset);
1880 return;
1883 error:
1884 if (has_fd) {
1885 snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64 ", fd:%" PRId64,
1886 fdset_id, fd);
1887 } else {
1888 snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64, fdset_id);
1890 error_setg(errp, QERR_FD_NOT_FOUND, fd_str);
1893 FdsetInfoList *qmp_query_fdsets(Error **errp)
1895 MonFdset *mon_fdset;
1896 MonFdsetFd *mon_fdset_fd;
1897 FdsetInfoList *fdset_list = NULL;
1899 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
1900 FdsetInfoList *fdset_info = g_malloc0(sizeof(*fdset_info));
1901 FdsetFdInfoList *fdsetfd_list = NULL;
1903 fdset_info->value = g_malloc0(sizeof(*fdset_info->value));
1904 fdset_info->value->fdset_id = mon_fdset->id;
1906 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
1907 FdsetFdInfoList *fdsetfd_info;
1909 fdsetfd_info = g_malloc0(sizeof(*fdsetfd_info));
1910 fdsetfd_info->value = g_malloc0(sizeof(*fdsetfd_info->value));
1911 fdsetfd_info->value->fd = mon_fdset_fd->fd;
1912 if (mon_fdset_fd->opaque) {
1913 fdsetfd_info->value->has_opaque = true;
1914 fdsetfd_info->value->opaque = g_strdup(mon_fdset_fd->opaque);
1915 } else {
1916 fdsetfd_info->value->has_opaque = false;
1919 fdsetfd_info->next = fdsetfd_list;
1920 fdsetfd_list = fdsetfd_info;
1923 fdset_info->value->fds = fdsetfd_list;
1925 fdset_info->next = fdset_list;
1926 fdset_list = fdset_info;
1929 return fdset_list;
1932 AddfdInfo *monitor_fdset_add_fd(int fd, bool has_fdset_id, int64_t fdset_id,
1933 bool has_opaque, const char *opaque,
1934 Error **errp)
1936 MonFdset *mon_fdset = NULL;
1937 MonFdsetFd *mon_fdset_fd;
1938 AddfdInfo *fdinfo;
1940 if (has_fdset_id) {
1941 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
1942 /* Break if match found or match impossible due to ordering by ID */
1943 if (fdset_id <= mon_fdset->id) {
1944 if (fdset_id < mon_fdset->id) {
1945 mon_fdset = NULL;
1947 break;
1952 if (mon_fdset == NULL) {
1953 int64_t fdset_id_prev = -1;
1954 MonFdset *mon_fdset_cur = QLIST_FIRST(&mon_fdsets);
1956 if (has_fdset_id) {
1957 if (fdset_id < 0) {
1958 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "fdset-id",
1959 "a non-negative value");
1960 return NULL;
1962 /* Use specified fdset ID */
1963 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
1964 mon_fdset_cur = mon_fdset;
1965 if (fdset_id < mon_fdset_cur->id) {
1966 break;
1969 } else {
1970 /* Use first available fdset ID */
1971 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
1972 mon_fdset_cur = mon_fdset;
1973 if (fdset_id_prev == mon_fdset_cur->id - 1) {
1974 fdset_id_prev = mon_fdset_cur->id;
1975 continue;
1977 break;
1981 mon_fdset = g_malloc0(sizeof(*mon_fdset));
1982 if (has_fdset_id) {
1983 mon_fdset->id = fdset_id;
1984 } else {
1985 mon_fdset->id = fdset_id_prev + 1;
1988 /* The fdset list is ordered by fdset ID */
1989 if (!mon_fdset_cur) {
1990 QLIST_INSERT_HEAD(&mon_fdsets, mon_fdset, next);
1991 } else if (mon_fdset->id < mon_fdset_cur->id) {
1992 QLIST_INSERT_BEFORE(mon_fdset_cur, mon_fdset, next);
1993 } else {
1994 QLIST_INSERT_AFTER(mon_fdset_cur, mon_fdset, next);
1998 mon_fdset_fd = g_malloc0(sizeof(*mon_fdset_fd));
1999 mon_fdset_fd->fd = fd;
2000 mon_fdset_fd->removed = false;
2001 if (has_opaque) {
2002 mon_fdset_fd->opaque = g_strdup(opaque);
2004 QLIST_INSERT_HEAD(&mon_fdset->fds, mon_fdset_fd, next);
2006 fdinfo = g_malloc0(sizeof(*fdinfo));
2007 fdinfo->fdset_id = mon_fdset->id;
2008 fdinfo->fd = mon_fdset_fd->fd;
2010 return fdinfo;
2013 int monitor_fdset_get_fd(int64_t fdset_id, int flags)
2015 #ifndef _WIN32
2016 MonFdset *mon_fdset;
2017 MonFdsetFd *mon_fdset_fd;
2018 int mon_fd_flags;
2020 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2021 if (mon_fdset->id != fdset_id) {
2022 continue;
2024 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2025 mon_fd_flags = fcntl(mon_fdset_fd->fd, F_GETFL);
2026 if (mon_fd_flags == -1) {
2027 return -1;
2030 if ((flags & O_ACCMODE) == (mon_fd_flags & O_ACCMODE)) {
2031 return mon_fdset_fd->fd;
2034 errno = EACCES;
2035 return -1;
2037 #endif
2039 errno = ENOENT;
2040 return -1;
2043 int monitor_fdset_dup_fd_add(int64_t fdset_id, int dup_fd)
2045 MonFdset *mon_fdset;
2046 MonFdsetFd *mon_fdset_fd_dup;
2048 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2049 if (mon_fdset->id != fdset_id) {
2050 continue;
2052 QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
2053 if (mon_fdset_fd_dup->fd == dup_fd) {
2054 return -1;
2057 mon_fdset_fd_dup = g_malloc0(sizeof(*mon_fdset_fd_dup));
2058 mon_fdset_fd_dup->fd = dup_fd;
2059 QLIST_INSERT_HEAD(&mon_fdset->dup_fds, mon_fdset_fd_dup, next);
2060 return 0;
2062 return -1;
2065 static int monitor_fdset_dup_fd_find_remove(int dup_fd, bool remove)
2067 MonFdset *mon_fdset;
2068 MonFdsetFd *mon_fdset_fd_dup;
2070 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2071 QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
2072 if (mon_fdset_fd_dup->fd == dup_fd) {
2073 if (remove) {
2074 QLIST_REMOVE(mon_fdset_fd_dup, next);
2075 if (QLIST_EMPTY(&mon_fdset->dup_fds)) {
2076 monitor_fdset_cleanup(mon_fdset);
2078 return -1;
2079 } else {
2080 return mon_fdset->id;
2085 return -1;
2088 int monitor_fdset_dup_fd_find(int dup_fd)
2090 return monitor_fdset_dup_fd_find_remove(dup_fd, false);
2093 void monitor_fdset_dup_fd_remove(int dup_fd)
2095 monitor_fdset_dup_fd_find_remove(dup_fd, true);
2098 int monitor_fd_param(Monitor *mon, const char *fdname, Error **errp)
2100 int fd;
2101 Error *local_err = NULL;
2103 if (!qemu_isdigit(fdname[0]) && mon) {
2104 fd = monitor_get_fd(mon, fdname, &local_err);
2105 } else {
2106 fd = qemu_parse_fd(fdname);
2107 if (fd == -1) {
2108 error_setg(&local_err, "Invalid file descriptor number '%s'",
2109 fdname);
2112 if (local_err) {
2113 error_propagate(errp, local_err);
2114 assert(fd == -1);
2115 } else {
2116 assert(fd != -1);
2119 return fd;
2122 /* Please update hmp-commands.hx when adding or changing commands */
2123 static mon_cmd_t info_cmds[] = {
2124 #include "hmp-commands-info.h"
2125 { NULL, NULL, },
2128 /* mon_cmds and info_cmds would be sorted at runtime */
2129 static mon_cmd_t mon_cmds[] = {
2130 #include "hmp-commands.h"
2131 { NULL, NULL, },
2134 static const mon_cmd_t qmp_cmds[] = {
2135 #include "qmp-commands-old.h"
2136 { /* NULL */ },
2139 /*******************************************************************/
2141 static const char *pch;
2142 static sigjmp_buf expr_env;
2145 static void GCC_FMT_ATTR(2, 3) QEMU_NORETURN
2146 expr_error(Monitor *mon, const char *fmt, ...)
2148 va_list ap;
2149 va_start(ap, fmt);
2150 monitor_vprintf(mon, fmt, ap);
2151 monitor_printf(mon, "\n");
2152 va_end(ap);
2153 siglongjmp(expr_env, 1);
2156 /* return 0 if OK, -1 if not found */
2157 static int get_monitor_def(target_long *pval, const char *name)
2159 const MonitorDef *md = target_monitor_defs();
2160 void *ptr;
2161 uint64_t tmp = 0;
2162 int ret;
2164 if (md == NULL) {
2165 return -1;
2168 for(; md->name != NULL; md++) {
2169 if (compare_cmd(name, md->name)) {
2170 if (md->get_value) {
2171 *pval = md->get_value(md, md->offset);
2172 } else {
2173 CPUArchState *env = mon_get_cpu_env();
2174 ptr = (uint8_t *)env + md->offset;
2175 switch(md->type) {
2176 case MD_I32:
2177 *pval = *(int32_t *)ptr;
2178 break;
2179 case MD_TLONG:
2180 *pval = *(target_long *)ptr;
2181 break;
2182 default:
2183 *pval = 0;
2184 break;
2187 return 0;
2191 ret = target_get_monitor_def(mon_get_cpu(), name, &tmp);
2192 if (!ret) {
2193 *pval = (target_long) tmp;
2196 return ret;
2199 static void next(void)
2201 if (*pch != '\0') {
2202 pch++;
2203 while (qemu_isspace(*pch))
2204 pch++;
2208 static int64_t expr_sum(Monitor *mon);
2210 static int64_t expr_unary(Monitor *mon)
2212 int64_t n;
2213 char *p;
2214 int ret;
2216 switch(*pch) {
2217 case '+':
2218 next();
2219 n = expr_unary(mon);
2220 break;
2221 case '-':
2222 next();
2223 n = -expr_unary(mon);
2224 break;
2225 case '~':
2226 next();
2227 n = ~expr_unary(mon);
2228 break;
2229 case '(':
2230 next();
2231 n = expr_sum(mon);
2232 if (*pch != ')') {
2233 expr_error(mon, "')' expected");
2235 next();
2236 break;
2237 case '\'':
2238 pch++;
2239 if (*pch == '\0')
2240 expr_error(mon, "character constant expected");
2241 n = *pch;
2242 pch++;
2243 if (*pch != '\'')
2244 expr_error(mon, "missing terminating \' character");
2245 next();
2246 break;
2247 case '$':
2249 char buf[128], *q;
2250 target_long reg=0;
2252 pch++;
2253 q = buf;
2254 while ((*pch >= 'a' && *pch <= 'z') ||
2255 (*pch >= 'A' && *pch <= 'Z') ||
2256 (*pch >= '0' && *pch <= '9') ||
2257 *pch == '_' || *pch == '.') {
2258 if ((q - buf) < sizeof(buf) - 1)
2259 *q++ = *pch;
2260 pch++;
2262 while (qemu_isspace(*pch))
2263 pch++;
2264 *q = 0;
2265 ret = get_monitor_def(&reg, buf);
2266 if (ret < 0)
2267 expr_error(mon, "unknown register");
2268 n = reg;
2270 break;
2271 case '\0':
2272 expr_error(mon, "unexpected end of expression");
2273 n = 0;
2274 break;
2275 default:
2276 errno = 0;
2277 n = strtoull(pch, &p, 0);
2278 if (errno == ERANGE) {
2279 expr_error(mon, "number too large");
2281 if (pch == p) {
2282 expr_error(mon, "invalid char '%c' in expression", *p);
2284 pch = p;
2285 while (qemu_isspace(*pch))
2286 pch++;
2287 break;
2289 return n;
2293 static int64_t expr_prod(Monitor *mon)
2295 int64_t val, val2;
2296 int op;
2298 val = expr_unary(mon);
2299 for(;;) {
2300 op = *pch;
2301 if (op != '*' && op != '/' && op != '%')
2302 break;
2303 next();
2304 val2 = expr_unary(mon);
2305 switch(op) {
2306 default:
2307 case '*':
2308 val *= val2;
2309 break;
2310 case '/':
2311 case '%':
2312 if (val2 == 0)
2313 expr_error(mon, "division by zero");
2314 if (op == '/')
2315 val /= val2;
2316 else
2317 val %= val2;
2318 break;
2321 return val;
2324 static int64_t expr_logic(Monitor *mon)
2326 int64_t val, val2;
2327 int op;
2329 val = expr_prod(mon);
2330 for(;;) {
2331 op = *pch;
2332 if (op != '&' && op != '|' && op != '^')
2333 break;
2334 next();
2335 val2 = expr_prod(mon);
2336 switch(op) {
2337 default:
2338 case '&':
2339 val &= val2;
2340 break;
2341 case '|':
2342 val |= val2;
2343 break;
2344 case '^':
2345 val ^= val2;
2346 break;
2349 return val;
2352 static int64_t expr_sum(Monitor *mon)
2354 int64_t val, val2;
2355 int op;
2357 val = expr_logic(mon);
2358 for(;;) {
2359 op = *pch;
2360 if (op != '+' && op != '-')
2361 break;
2362 next();
2363 val2 = expr_logic(mon);
2364 if (op == '+')
2365 val += val2;
2366 else
2367 val -= val2;
2369 return val;
2372 static int get_expr(Monitor *mon, int64_t *pval, const char **pp)
2374 pch = *pp;
2375 if (sigsetjmp(expr_env, 0)) {
2376 *pp = pch;
2377 return -1;
2379 while (qemu_isspace(*pch))
2380 pch++;
2381 *pval = expr_sum(mon);
2382 *pp = pch;
2383 return 0;
2386 static int get_double(Monitor *mon, double *pval, const char **pp)
2388 const char *p = *pp;
2389 char *tailp;
2390 double d;
2392 d = strtod(p, &tailp);
2393 if (tailp == p) {
2394 monitor_printf(mon, "Number expected\n");
2395 return -1;
2397 if (d != d || d - d != 0) {
2398 /* NaN or infinity */
2399 monitor_printf(mon, "Bad number\n");
2400 return -1;
2402 *pval = d;
2403 *pp = tailp;
2404 return 0;
2408 * Store the command-name in cmdname, and return a pointer to
2409 * the remaining of the command string.
2411 static const char *get_command_name(const char *cmdline,
2412 char *cmdname, size_t nlen)
2414 size_t len;
2415 const char *p, *pstart;
2417 p = cmdline;
2418 while (qemu_isspace(*p))
2419 p++;
2420 if (*p == '\0')
2421 return NULL;
2422 pstart = p;
2423 while (*p != '\0' && *p != '/' && !qemu_isspace(*p))
2424 p++;
2425 len = p - pstart;
2426 if (len > nlen - 1)
2427 len = nlen - 1;
2428 memcpy(cmdname, pstart, len);
2429 cmdname[len] = '\0';
2430 return p;
2434 * Read key of 'type' into 'key' and return the current
2435 * 'type' pointer.
2437 static char *key_get_info(const char *type, char **key)
2439 size_t len;
2440 char *p, *str;
2442 if (*type == ',')
2443 type++;
2445 p = strchr(type, ':');
2446 if (!p) {
2447 *key = NULL;
2448 return NULL;
2450 len = p - type;
2452 str = g_malloc(len + 1);
2453 memcpy(str, type, len);
2454 str[len] = '\0';
2456 *key = str;
2457 return ++p;
2460 static int default_fmt_format = 'x';
2461 static int default_fmt_size = 4;
2463 static int is_valid_option(const char *c, const char *typestr)
2465 char option[3];
2467 option[0] = '-';
2468 option[1] = *c;
2469 option[2] = '\0';
2471 typestr = strstr(typestr, option);
2472 return (typestr != NULL);
2475 static const mon_cmd_t *search_dispatch_table(const mon_cmd_t *disp_table,
2476 const char *cmdname)
2478 const mon_cmd_t *cmd;
2480 for (cmd = disp_table; cmd->name != NULL; cmd++) {
2481 if (compare_cmd(cmdname, cmd->name)) {
2482 return cmd;
2486 return NULL;
2489 static const mon_cmd_t *qmp_find_cmd(const char *cmdname)
2491 return search_dispatch_table(qmp_cmds, cmdname);
2495 * Parse command name from @cmdp according to command table @table.
2496 * If blank, return NULL.
2497 * Else, if no valid command can be found, report to @mon, and return
2498 * NULL.
2499 * Else, change @cmdp to point right behind the name, and return its
2500 * command table entry.
2501 * Do not assume the return value points into @table! It doesn't when
2502 * the command is found in a sub-command table.
2504 static const mon_cmd_t *monitor_parse_command(Monitor *mon,
2505 const char **cmdp,
2506 mon_cmd_t *table)
2508 const char *p;
2509 const mon_cmd_t *cmd;
2510 char cmdname[256];
2512 /* extract the command name */
2513 p = get_command_name(*cmdp, cmdname, sizeof(cmdname));
2514 if (!p)
2515 return NULL;
2517 cmd = search_dispatch_table(table, cmdname);
2518 if (!cmd) {
2519 monitor_printf(mon, "unknown command: '%.*s'\n",
2520 (int)(p - *cmdp), *cmdp);
2521 return NULL;
2524 /* filter out following useless space */
2525 while (qemu_isspace(*p)) {
2526 p++;
2529 *cmdp = p;
2530 /* search sub command */
2531 if (cmd->sub_table != NULL && *p != '\0') {
2532 return monitor_parse_command(mon, cmdp, cmd->sub_table);
2535 return cmd;
2539 * Parse arguments for @cmd.
2540 * If it can't be parsed, report to @mon, and return NULL.
2541 * Else, insert command arguments into a QDict, and return it.
2542 * Note: On success, caller has to free the QDict structure.
2545 static QDict *monitor_parse_arguments(Monitor *mon,
2546 const char **endp,
2547 const mon_cmd_t *cmd)
2549 const char *typestr;
2550 char *key;
2551 int c;
2552 const char *p = *endp;
2553 char buf[1024];
2554 QDict *qdict = qdict_new();
2556 /* parse the parameters */
2557 typestr = cmd->args_type;
2558 for(;;) {
2559 typestr = key_get_info(typestr, &key);
2560 if (!typestr)
2561 break;
2562 c = *typestr;
2563 typestr++;
2564 switch(c) {
2565 case 'F':
2566 case 'B':
2567 case 's':
2569 int ret;
2571 while (qemu_isspace(*p))
2572 p++;
2573 if (*typestr == '?') {
2574 typestr++;
2575 if (*p == '\0') {
2576 /* no optional string: NULL argument */
2577 break;
2580 ret = get_str(buf, sizeof(buf), &p);
2581 if (ret < 0) {
2582 switch(c) {
2583 case 'F':
2584 monitor_printf(mon, "%s: filename expected\n",
2585 cmd->name);
2586 break;
2587 case 'B':
2588 monitor_printf(mon, "%s: block device name expected\n",
2589 cmd->name);
2590 break;
2591 default:
2592 monitor_printf(mon, "%s: string expected\n", cmd->name);
2593 break;
2595 goto fail;
2597 qdict_put(qdict, key, qstring_from_str(buf));
2599 break;
2600 case 'O':
2602 QemuOptsList *opts_list;
2603 QemuOpts *opts;
2605 opts_list = qemu_find_opts(key);
2606 if (!opts_list || opts_list->desc->name) {
2607 goto bad_type;
2609 while (qemu_isspace(*p)) {
2610 p++;
2612 if (!*p)
2613 break;
2614 if (get_str(buf, sizeof(buf), &p) < 0) {
2615 goto fail;
2617 opts = qemu_opts_parse_noisily(opts_list, buf, true);
2618 if (!opts) {
2619 goto fail;
2621 qemu_opts_to_qdict(opts, qdict);
2622 qemu_opts_del(opts);
2624 break;
2625 case '/':
2627 int count, format, size;
2629 while (qemu_isspace(*p))
2630 p++;
2631 if (*p == '/') {
2632 /* format found */
2633 p++;
2634 count = 1;
2635 if (qemu_isdigit(*p)) {
2636 count = 0;
2637 while (qemu_isdigit(*p)) {
2638 count = count * 10 + (*p - '0');
2639 p++;
2642 size = -1;
2643 format = -1;
2644 for(;;) {
2645 switch(*p) {
2646 case 'o':
2647 case 'd':
2648 case 'u':
2649 case 'x':
2650 case 'i':
2651 case 'c':
2652 format = *p++;
2653 break;
2654 case 'b':
2655 size = 1;
2656 p++;
2657 break;
2658 case 'h':
2659 size = 2;
2660 p++;
2661 break;
2662 case 'w':
2663 size = 4;
2664 p++;
2665 break;
2666 case 'g':
2667 case 'L':
2668 size = 8;
2669 p++;
2670 break;
2671 default:
2672 goto next;
2675 next:
2676 if (*p != '\0' && !qemu_isspace(*p)) {
2677 monitor_printf(mon, "invalid char in format: '%c'\n",
2678 *p);
2679 goto fail;
2681 if (format < 0)
2682 format = default_fmt_format;
2683 if (format != 'i') {
2684 /* for 'i', not specifying a size gives -1 as size */
2685 if (size < 0)
2686 size = default_fmt_size;
2687 default_fmt_size = size;
2689 default_fmt_format = format;
2690 } else {
2691 count = 1;
2692 format = default_fmt_format;
2693 if (format != 'i') {
2694 size = default_fmt_size;
2695 } else {
2696 size = -1;
2699 qdict_put(qdict, "count", qint_from_int(count));
2700 qdict_put(qdict, "format", qint_from_int(format));
2701 qdict_put(qdict, "size", qint_from_int(size));
2703 break;
2704 case 'i':
2705 case 'l':
2706 case 'M':
2708 int64_t val;
2710 while (qemu_isspace(*p))
2711 p++;
2712 if (*typestr == '?' || *typestr == '.') {
2713 if (*typestr == '?') {
2714 if (*p == '\0') {
2715 typestr++;
2716 break;
2718 } else {
2719 if (*p == '.') {
2720 p++;
2721 while (qemu_isspace(*p))
2722 p++;
2723 } else {
2724 typestr++;
2725 break;
2728 typestr++;
2730 if (get_expr(mon, &val, &p))
2731 goto fail;
2732 /* Check if 'i' is greater than 32-bit */
2733 if ((c == 'i') && ((val >> 32) & 0xffffffff)) {
2734 monitor_printf(mon, "\'%s\' has failed: ", cmd->name);
2735 monitor_printf(mon, "integer is for 32-bit values\n");
2736 goto fail;
2737 } else if (c == 'M') {
2738 if (val < 0) {
2739 monitor_printf(mon, "enter a positive value\n");
2740 goto fail;
2742 val <<= 20;
2744 qdict_put(qdict, key, qint_from_int(val));
2746 break;
2747 case 'o':
2749 int64_t val;
2750 char *end;
2752 while (qemu_isspace(*p)) {
2753 p++;
2755 if (*typestr == '?') {
2756 typestr++;
2757 if (*p == '\0') {
2758 break;
2761 val = qemu_strtosz(p, &end);
2762 if (val < 0) {
2763 monitor_printf(mon, "invalid size\n");
2764 goto fail;
2766 qdict_put(qdict, key, qint_from_int(val));
2767 p = end;
2769 break;
2770 case 'T':
2772 double val;
2774 while (qemu_isspace(*p))
2775 p++;
2776 if (*typestr == '?') {
2777 typestr++;
2778 if (*p == '\0') {
2779 break;
2782 if (get_double(mon, &val, &p) < 0) {
2783 goto fail;
2785 if (p[0] && p[1] == 's') {
2786 switch (*p) {
2787 case 'm':
2788 val /= 1e3; p += 2; break;
2789 case 'u':
2790 val /= 1e6; p += 2; break;
2791 case 'n':
2792 val /= 1e9; p += 2; break;
2795 if (*p && !qemu_isspace(*p)) {
2796 monitor_printf(mon, "Unknown unit suffix\n");
2797 goto fail;
2799 qdict_put(qdict, key, qfloat_from_double(val));
2801 break;
2802 case 'b':
2804 const char *beg;
2805 bool val;
2807 while (qemu_isspace(*p)) {
2808 p++;
2810 beg = p;
2811 while (qemu_isgraph(*p)) {
2812 p++;
2814 if (p - beg == 2 && !memcmp(beg, "on", p - beg)) {
2815 val = true;
2816 } else if (p - beg == 3 && !memcmp(beg, "off", p - beg)) {
2817 val = false;
2818 } else {
2819 monitor_printf(mon, "Expected 'on' or 'off'\n");
2820 goto fail;
2822 qdict_put(qdict, key, qbool_from_bool(val));
2824 break;
2825 case '-':
2827 const char *tmp = p;
2828 int skip_key = 0;
2829 /* option */
2831 c = *typestr++;
2832 if (c == '\0')
2833 goto bad_type;
2834 while (qemu_isspace(*p))
2835 p++;
2836 if (*p == '-') {
2837 p++;
2838 if(c != *p) {
2839 if(!is_valid_option(p, typestr)) {
2841 monitor_printf(mon, "%s: unsupported option -%c\n",
2842 cmd->name, *p);
2843 goto fail;
2844 } else {
2845 skip_key = 1;
2848 if(skip_key) {
2849 p = tmp;
2850 } else {
2851 /* has option */
2852 p++;
2853 qdict_put(qdict, key, qbool_from_bool(true));
2857 break;
2858 case 'S':
2860 /* package all remaining string */
2861 int len;
2863 while (qemu_isspace(*p)) {
2864 p++;
2866 if (*typestr == '?') {
2867 typestr++;
2868 if (*p == '\0') {
2869 /* no remaining string: NULL argument */
2870 break;
2873 len = strlen(p);
2874 if (len <= 0) {
2875 monitor_printf(mon, "%s: string expected\n",
2876 cmd->name);
2877 goto fail;
2879 qdict_put(qdict, key, qstring_from_str(p));
2880 p += len;
2882 break;
2883 default:
2884 bad_type:
2885 monitor_printf(mon, "%s: unknown type '%c'\n", cmd->name, c);
2886 goto fail;
2888 g_free(key);
2889 key = NULL;
2891 /* check that all arguments were parsed */
2892 while (qemu_isspace(*p))
2893 p++;
2894 if (*p != '\0') {
2895 monitor_printf(mon, "%s: extraneous characters at the end of line\n",
2896 cmd->name);
2897 goto fail;
2900 return qdict;
2902 fail:
2903 QDECREF(qdict);
2904 g_free(key);
2905 return NULL;
2908 static void handle_hmp_command(Monitor *mon, const char *cmdline)
2910 QDict *qdict;
2911 const mon_cmd_t *cmd;
2913 cmd = monitor_parse_command(mon, &cmdline, mon->cmd_table);
2914 if (!cmd) {
2915 return;
2918 qdict = monitor_parse_arguments(mon, &cmdline, cmd);
2919 if (!qdict) {
2920 monitor_printf(mon, "Try \"help %s\" for more information\n",
2921 cmd->name);
2922 return;
2925 cmd->mhandler.cmd(mon, qdict);
2926 QDECREF(qdict);
2929 static void cmd_completion(Monitor *mon, const char *name, const char *list)
2931 const char *p, *pstart;
2932 char cmd[128];
2933 int len;
2935 p = list;
2936 for(;;) {
2937 pstart = p;
2938 p = strchr(p, '|');
2939 if (!p)
2940 p = pstart + strlen(pstart);
2941 len = p - pstart;
2942 if (len > sizeof(cmd) - 2)
2943 len = sizeof(cmd) - 2;
2944 memcpy(cmd, pstart, len);
2945 cmd[len] = '\0';
2946 if (name[0] == '\0' || !strncmp(name, cmd, strlen(name))) {
2947 readline_add_completion(mon->rs, cmd);
2949 if (*p == '\0')
2950 break;
2951 p++;
2955 static void file_completion(Monitor *mon, const char *input)
2957 DIR *ffs;
2958 struct dirent *d;
2959 char path[1024];
2960 char file[1024], file_prefix[1024];
2961 int input_path_len;
2962 const char *p;
2964 p = strrchr(input, '/');
2965 if (!p) {
2966 input_path_len = 0;
2967 pstrcpy(file_prefix, sizeof(file_prefix), input);
2968 pstrcpy(path, sizeof(path), ".");
2969 } else {
2970 input_path_len = p - input + 1;
2971 memcpy(path, input, input_path_len);
2972 if (input_path_len > sizeof(path) - 1)
2973 input_path_len = sizeof(path) - 1;
2974 path[input_path_len] = '\0';
2975 pstrcpy(file_prefix, sizeof(file_prefix), p + 1);
2978 ffs = opendir(path);
2979 if (!ffs)
2980 return;
2981 for(;;) {
2982 struct stat sb;
2983 d = readdir(ffs);
2984 if (!d)
2985 break;
2987 if (strcmp(d->d_name, ".") == 0 || strcmp(d->d_name, "..") == 0) {
2988 continue;
2991 if (strstart(d->d_name, file_prefix, NULL)) {
2992 memcpy(file, input, input_path_len);
2993 if (input_path_len < sizeof(file))
2994 pstrcpy(file + input_path_len, sizeof(file) - input_path_len,
2995 d->d_name);
2996 /* stat the file to find out if it's a directory.
2997 * In that case add a slash to speed up typing long paths
2999 if (stat(file, &sb) == 0 && S_ISDIR(sb.st_mode)) {
3000 pstrcat(file, sizeof(file), "/");
3002 readline_add_completion(mon->rs, file);
3005 closedir(ffs);
3008 static const char *next_arg_type(const char *typestr)
3010 const char *p = strchr(typestr, ':');
3011 return (p != NULL ? ++p : typestr);
3014 static void add_completion_option(ReadLineState *rs, const char *str,
3015 const char *option)
3017 if (!str || !option) {
3018 return;
3020 if (!strncmp(option, str, strlen(str))) {
3021 readline_add_completion(rs, option);
3025 void chardev_add_completion(ReadLineState *rs, int nb_args, const char *str)
3027 size_t len;
3028 ChardevBackendInfoList *list, *start;
3030 if (nb_args != 2) {
3031 return;
3033 len = strlen(str);
3034 readline_set_completion_index(rs, len);
3036 start = list = qmp_query_chardev_backends(NULL);
3037 while (list) {
3038 const char *chr_name = list->value->name;
3040 if (!strncmp(chr_name, str, len)) {
3041 readline_add_completion(rs, chr_name);
3043 list = list->next;
3045 qapi_free_ChardevBackendInfoList(start);
3048 void netdev_add_completion(ReadLineState *rs, int nb_args, const char *str)
3050 size_t len;
3051 int i;
3053 if (nb_args != 2) {
3054 return;
3056 len = strlen(str);
3057 readline_set_completion_index(rs, len);
3058 for (i = 0; NetClientOptionsKind_lookup[i]; i++) {
3059 add_completion_option(rs, str, NetClientOptionsKind_lookup[i]);
3063 void device_add_completion(ReadLineState *rs, int nb_args, const char *str)
3065 GSList *list, *elt;
3066 size_t len;
3068 if (nb_args != 2) {
3069 return;
3072 len = strlen(str);
3073 readline_set_completion_index(rs, len);
3074 list = elt = object_class_get_list(TYPE_DEVICE, false);
3075 while (elt) {
3076 const char *name;
3077 DeviceClass *dc = OBJECT_CLASS_CHECK(DeviceClass, elt->data,
3078 TYPE_DEVICE);
3079 name = object_class_get_name(OBJECT_CLASS(dc));
3081 if (!dc->cannot_instantiate_with_device_add_yet
3082 && !strncmp(name, str, len)) {
3083 readline_add_completion(rs, name);
3085 elt = elt->next;
3087 g_slist_free(list);
3090 void object_add_completion(ReadLineState *rs, int nb_args, const char *str)
3092 GSList *list, *elt;
3093 size_t len;
3095 if (nb_args != 2) {
3096 return;
3099 len = strlen(str);
3100 readline_set_completion_index(rs, len);
3101 list = elt = object_class_get_list(TYPE_USER_CREATABLE, false);
3102 while (elt) {
3103 const char *name;
3105 name = object_class_get_name(OBJECT_CLASS(elt->data));
3106 if (!strncmp(name, str, len) && strcmp(name, TYPE_USER_CREATABLE)) {
3107 readline_add_completion(rs, name);
3109 elt = elt->next;
3111 g_slist_free(list);
3114 static void peripheral_device_del_completion(ReadLineState *rs,
3115 const char *str, size_t len)
3117 Object *peripheral = container_get(qdev_get_machine(), "/peripheral");
3118 GSList *list, *item;
3120 list = qdev_build_hotpluggable_device_list(peripheral);
3121 if (!list) {
3122 return;
3125 for (item = list; item; item = g_slist_next(item)) {
3126 DeviceState *dev = item->data;
3128 if (dev->id && !strncmp(str, dev->id, len)) {
3129 readline_add_completion(rs, dev->id);
3133 g_slist_free(list);
3136 void chardev_remove_completion(ReadLineState *rs, int nb_args, const char *str)
3138 size_t len;
3139 ChardevInfoList *list, *start;
3141 if (nb_args != 2) {
3142 return;
3144 len = strlen(str);
3145 readline_set_completion_index(rs, len);
3147 start = list = qmp_query_chardev(NULL);
3148 while (list) {
3149 ChardevInfo *chr = list->value;
3151 if (!strncmp(chr->label, str, len)) {
3152 readline_add_completion(rs, chr->label);
3154 list = list->next;
3156 qapi_free_ChardevInfoList(start);
3159 static void ringbuf_completion(ReadLineState *rs, const char *str)
3161 size_t len;
3162 ChardevInfoList *list, *start;
3164 len = strlen(str);
3165 readline_set_completion_index(rs, len);
3167 start = list = qmp_query_chardev(NULL);
3168 while (list) {
3169 ChardevInfo *chr_info = list->value;
3171 if (!strncmp(chr_info->label, str, len)) {
3172 CharDriverState *chr = qemu_chr_find(chr_info->label);
3173 if (chr && chr_is_ringbuf(chr)) {
3174 readline_add_completion(rs, chr_info->label);
3177 list = list->next;
3179 qapi_free_ChardevInfoList(start);
3182 void ringbuf_write_completion(ReadLineState *rs, int nb_args, const char *str)
3184 if (nb_args != 2) {
3185 return;
3187 ringbuf_completion(rs, str);
3190 void device_del_completion(ReadLineState *rs, int nb_args, const char *str)
3192 size_t len;
3194 if (nb_args != 2) {
3195 return;
3198 len = strlen(str);
3199 readline_set_completion_index(rs, len);
3200 peripheral_device_del_completion(rs, str, len);
3203 void object_del_completion(ReadLineState *rs, int nb_args, const char *str)
3205 ObjectPropertyInfoList *list, *start;
3206 size_t len;
3208 if (nb_args != 2) {
3209 return;
3211 len = strlen(str);
3212 readline_set_completion_index(rs, len);
3214 start = list = qmp_qom_list("/objects", NULL);
3215 while (list) {
3216 ObjectPropertyInfo *info = list->value;
3218 if (!strncmp(info->type, "child<", 5)
3219 && !strncmp(info->name, str, len)) {
3220 readline_add_completion(rs, info->name);
3222 list = list->next;
3224 qapi_free_ObjectPropertyInfoList(start);
3227 void sendkey_completion(ReadLineState *rs, int nb_args, const char *str)
3229 int i;
3230 char *sep;
3231 size_t len;
3233 if (nb_args != 2) {
3234 return;
3236 sep = strrchr(str, '-');
3237 if (sep) {
3238 str = sep + 1;
3240 len = strlen(str);
3241 readline_set_completion_index(rs, len);
3242 for (i = 0; i < Q_KEY_CODE__MAX; i++) {
3243 if (!strncmp(str, QKeyCode_lookup[i], len)) {
3244 readline_add_completion(rs, QKeyCode_lookup[i]);
3249 void set_link_completion(ReadLineState *rs, int nb_args, const char *str)
3251 size_t len;
3253 len = strlen(str);
3254 readline_set_completion_index(rs, len);
3255 if (nb_args == 2) {
3256 NetClientState *ncs[MAX_QUEUE_NUM];
3257 int count, i;
3258 count = qemu_find_net_clients_except(NULL, ncs,
3259 NET_CLIENT_OPTIONS_KIND_NONE,
3260 MAX_QUEUE_NUM);
3261 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3262 const char *name = ncs[i]->name;
3263 if (!strncmp(str, name, len)) {
3264 readline_add_completion(rs, name);
3267 } else if (nb_args == 3) {
3268 add_completion_option(rs, str, "on");
3269 add_completion_option(rs, str, "off");
3273 void netdev_del_completion(ReadLineState *rs, int nb_args, const char *str)
3275 int len, count, i;
3276 NetClientState *ncs[MAX_QUEUE_NUM];
3278 if (nb_args != 2) {
3279 return;
3282 len = strlen(str);
3283 readline_set_completion_index(rs, len);
3284 count = qemu_find_net_clients_except(NULL, ncs, NET_CLIENT_OPTIONS_KIND_NIC,
3285 MAX_QUEUE_NUM);
3286 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3287 QemuOpts *opts;
3288 const char *name = ncs[i]->name;
3289 if (strncmp(str, name, len)) {
3290 continue;
3292 opts = qemu_opts_find(qemu_find_opts_err("netdev", NULL), name);
3293 if (opts) {
3294 readline_add_completion(rs, name);
3299 void trace_event_completion(ReadLineState *rs, int nb_args, const char *str)
3301 size_t len;
3303 len = strlen(str);
3304 readline_set_completion_index(rs, len);
3305 if (nb_args == 2) {
3306 TraceEventID id;
3307 for (id = 0; id < trace_event_count(); id++) {
3308 const char *event_name = trace_event_get_name(trace_event_id(id));
3309 if (!strncmp(str, event_name, len)) {
3310 readline_add_completion(rs, event_name);
3313 } else if (nb_args == 3) {
3314 add_completion_option(rs, str, "on");
3315 add_completion_option(rs, str, "off");
3319 void watchdog_action_completion(ReadLineState *rs, int nb_args, const char *str)
3321 int i;
3323 if (nb_args != 2) {
3324 return;
3326 readline_set_completion_index(rs, strlen(str));
3327 for (i = 0; WatchdogExpirationAction_lookup[i]; i++) {
3328 add_completion_option(rs, str, WatchdogExpirationAction_lookup[i]);
3332 void migrate_set_capability_completion(ReadLineState *rs, int nb_args,
3333 const char *str)
3335 size_t len;
3337 len = strlen(str);
3338 readline_set_completion_index(rs, len);
3339 if (nb_args == 2) {
3340 int i;
3341 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
3342 const char *name = MigrationCapability_lookup[i];
3343 if (!strncmp(str, name, len)) {
3344 readline_add_completion(rs, name);
3347 } else if (nb_args == 3) {
3348 add_completion_option(rs, str, "on");
3349 add_completion_option(rs, str, "off");
3353 void migrate_set_parameter_completion(ReadLineState *rs, int nb_args,
3354 const char *str)
3356 size_t len;
3358 len = strlen(str);
3359 readline_set_completion_index(rs, len);
3360 if (nb_args == 2) {
3361 int i;
3362 for (i = 0; i < MIGRATION_PARAMETER__MAX; i++) {
3363 const char *name = MigrationParameter_lookup[i];
3364 if (!strncmp(str, name, len)) {
3365 readline_add_completion(rs, name);
3371 void host_net_add_completion(ReadLineState *rs, int nb_args, const char *str)
3373 int i;
3374 size_t len;
3375 if (nb_args != 2) {
3376 return;
3378 len = strlen(str);
3379 readline_set_completion_index(rs, len);
3380 for (i = 0; host_net_devices[i]; i++) {
3381 if (!strncmp(host_net_devices[i], str, len)) {
3382 readline_add_completion(rs, host_net_devices[i]);
3387 void host_net_remove_completion(ReadLineState *rs, int nb_args, const char *str)
3389 NetClientState *ncs[MAX_QUEUE_NUM];
3390 int count, i, len;
3392 len = strlen(str);
3393 readline_set_completion_index(rs, len);
3394 if (nb_args == 2) {
3395 count = qemu_find_net_clients_except(NULL, ncs,
3396 NET_CLIENT_OPTIONS_KIND_NONE,
3397 MAX_QUEUE_NUM);
3398 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3399 int id;
3400 char name[16];
3402 if (net_hub_id_for_client(ncs[i], &id)) {
3403 continue;
3405 snprintf(name, sizeof(name), "%d", id);
3406 if (!strncmp(str, name, len)) {
3407 readline_add_completion(rs, name);
3410 return;
3411 } else if (nb_args == 3) {
3412 count = qemu_find_net_clients_except(NULL, ncs,
3413 NET_CLIENT_OPTIONS_KIND_NIC,
3414 MAX_QUEUE_NUM);
3415 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3416 int id;
3417 const char *name;
3419 if (ncs[i]->info->type == NET_CLIENT_OPTIONS_KIND_HUBPORT ||
3420 net_hub_id_for_client(ncs[i], &id)) {
3421 continue;
3423 name = ncs[i]->name;
3424 if (!strncmp(str, name, len)) {
3425 readline_add_completion(rs, name);
3428 return;
3432 static void vm_completion(ReadLineState *rs, const char *str)
3434 size_t len;
3435 BlockDriverState *bs;
3436 BdrvNextIterator it;
3438 len = strlen(str);
3439 readline_set_completion_index(rs, len);
3441 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
3442 SnapshotInfoList *snapshots, *snapshot;
3443 AioContext *ctx = bdrv_get_aio_context(bs);
3444 bool ok = false;
3446 aio_context_acquire(ctx);
3447 if (bdrv_can_snapshot(bs)) {
3448 ok = bdrv_query_snapshot_info_list(bs, &snapshots, NULL) == 0;
3450 aio_context_release(ctx);
3451 if (!ok) {
3452 continue;
3455 snapshot = snapshots;
3456 while (snapshot) {
3457 char *completion = snapshot->value->name;
3458 if (!strncmp(str, completion, len)) {
3459 readline_add_completion(rs, completion);
3461 completion = snapshot->value->id;
3462 if (!strncmp(str, completion, len)) {
3463 readline_add_completion(rs, completion);
3465 snapshot = snapshot->next;
3467 qapi_free_SnapshotInfoList(snapshots);
3472 void delvm_completion(ReadLineState *rs, int nb_args, const char *str)
3474 if (nb_args == 2) {
3475 vm_completion(rs, str);
3479 void loadvm_completion(ReadLineState *rs, int nb_args, const char *str)
3481 if (nb_args == 2) {
3482 vm_completion(rs, str);
3486 static void monitor_find_completion_by_table(Monitor *mon,
3487 const mon_cmd_t *cmd_table,
3488 char **args,
3489 int nb_args)
3491 const char *cmdname;
3492 int i;
3493 const char *ptype, *str, *name;
3494 const mon_cmd_t *cmd;
3495 BlockBackend *blk = NULL;
3497 if (nb_args <= 1) {
3498 /* command completion */
3499 if (nb_args == 0)
3500 cmdname = "";
3501 else
3502 cmdname = args[0];
3503 readline_set_completion_index(mon->rs, strlen(cmdname));
3504 for (cmd = cmd_table; cmd->name != NULL; cmd++) {
3505 cmd_completion(mon, cmdname, cmd->name);
3507 } else {
3508 /* find the command */
3509 for (cmd = cmd_table; cmd->name != NULL; cmd++) {
3510 if (compare_cmd(args[0], cmd->name)) {
3511 break;
3514 if (!cmd->name) {
3515 return;
3518 if (cmd->sub_table) {
3519 /* do the job again */
3520 monitor_find_completion_by_table(mon, cmd->sub_table,
3521 &args[1], nb_args - 1);
3522 return;
3524 if (cmd->command_completion) {
3525 cmd->command_completion(mon->rs, nb_args, args[nb_args - 1]);
3526 return;
3529 ptype = next_arg_type(cmd->args_type);
3530 for(i = 0; i < nb_args - 2; i++) {
3531 if (*ptype != '\0') {
3532 ptype = next_arg_type(ptype);
3533 while (*ptype == '?')
3534 ptype = next_arg_type(ptype);
3537 str = args[nb_args - 1];
3538 while (*ptype == '-' && ptype[1] != '\0') {
3539 ptype = next_arg_type(ptype);
3541 switch(*ptype) {
3542 case 'F':
3543 /* file completion */
3544 readline_set_completion_index(mon->rs, strlen(str));
3545 file_completion(mon, str);
3546 break;
3547 case 'B':
3548 /* block device name completion */
3549 readline_set_completion_index(mon->rs, strlen(str));
3550 while ((blk = blk_next(blk)) != NULL) {
3551 name = blk_name(blk);
3552 if (str[0] == '\0' ||
3553 !strncmp(name, str, strlen(str))) {
3554 readline_add_completion(mon->rs, name);
3557 break;
3558 case 's':
3559 case 'S':
3560 if (!strcmp(cmd->name, "help|?")) {
3561 monitor_find_completion_by_table(mon, cmd_table,
3562 &args[1], nb_args - 1);
3564 break;
3565 default:
3566 break;
3571 static void monitor_find_completion(void *opaque,
3572 const char *cmdline)
3574 Monitor *mon = opaque;
3575 char *args[MAX_ARGS];
3576 int nb_args, len;
3578 /* 1. parse the cmdline */
3579 if (parse_cmdline(cmdline, &nb_args, args) < 0) {
3580 return;
3583 /* if the line ends with a space, it means we want to complete the
3584 next arg */
3585 len = strlen(cmdline);
3586 if (len > 0 && qemu_isspace(cmdline[len - 1])) {
3587 if (nb_args >= MAX_ARGS) {
3588 goto cleanup;
3590 args[nb_args++] = g_strdup("");
3593 /* 2. auto complete according to args */
3594 monitor_find_completion_by_table(mon, mon->cmd_table, args, nb_args);
3596 cleanup:
3597 free_cmdline_args(args, nb_args);
3600 static int monitor_can_read(void *opaque)
3602 Monitor *mon = opaque;
3604 return (mon->suspend_cnt == 0) ? 1 : 0;
3607 static bool invalid_qmp_mode(const Monitor *mon, const mon_cmd_t *cmd,
3608 Error **errp)
3610 bool is_cap = cmd->mhandler.cmd_new == qmp_capabilities;
3612 if (is_cap && mon->qmp.in_command_mode) {
3613 error_set(errp, ERROR_CLASS_COMMAND_NOT_FOUND,
3614 "Capabilities negotiation is already complete, command "
3615 "'%s' ignored", cmd->name);
3616 return true;
3618 if (!is_cap && !mon->qmp.in_command_mode) {
3619 error_set(errp, ERROR_CLASS_COMMAND_NOT_FOUND,
3620 "Expecting capabilities negotiation with "
3621 "'qmp_capabilities' before command '%s'", cmd->name);
3622 return true;
3624 return false;
3628 * Argument validation rules:
3630 * 1. The argument must exist in cmd_args qdict
3631 * 2. The argument type must be the expected one
3633 * Special case: If the argument doesn't exist in cmd_args and
3634 * the QMP_ACCEPT_UNKNOWNS flag is set, then the
3635 * checking is skipped for it.
3637 static void check_client_args_type(const QDict *client_args,
3638 const QDict *cmd_args, int flags,
3639 Error **errp)
3641 const QDictEntry *ent;
3643 for (ent = qdict_first(client_args); ent;ent = qdict_next(client_args,ent)){
3644 QObject *obj;
3645 QString *arg_type;
3646 const QObject *client_arg = qdict_entry_value(ent);
3647 const char *client_arg_name = qdict_entry_key(ent);
3649 obj = qdict_get(cmd_args, client_arg_name);
3650 if (!obj) {
3651 if (flags & QMP_ACCEPT_UNKNOWNS) {
3652 /* handler accepts unknowns */
3653 continue;
3655 /* client arg doesn't exist */
3656 error_setg(errp, QERR_INVALID_PARAMETER, client_arg_name);
3657 return;
3660 arg_type = qobject_to_qstring(obj);
3661 assert(arg_type != NULL);
3663 /* check if argument's type is correct */
3664 switch (qstring_get_str(arg_type)[0]) {
3665 case 'F':
3666 case 'B':
3667 case 's':
3668 if (qobject_type(client_arg) != QTYPE_QSTRING) {
3669 error_setg(errp, QERR_INVALID_PARAMETER_TYPE,
3670 client_arg_name, "string");
3671 return;
3673 break;
3674 case 'i':
3675 case 'l':
3676 case 'M':
3677 case 'o':
3678 if (qobject_type(client_arg) != QTYPE_QINT) {
3679 error_setg(errp, QERR_INVALID_PARAMETER_TYPE,
3680 client_arg_name, "int");
3681 return;
3683 break;
3684 case 'T':
3685 if (qobject_type(client_arg) != QTYPE_QINT &&
3686 qobject_type(client_arg) != QTYPE_QFLOAT) {
3687 error_setg(errp, QERR_INVALID_PARAMETER_TYPE,
3688 client_arg_name, "number");
3689 return;
3691 break;
3692 case 'b':
3693 case '-':
3694 if (qobject_type(client_arg) != QTYPE_QBOOL) {
3695 error_setg(errp, QERR_INVALID_PARAMETER_TYPE,
3696 client_arg_name, "bool");
3697 return;
3699 break;
3700 case 'O':
3701 assert(flags & QMP_ACCEPT_UNKNOWNS);
3702 break;
3703 case 'q':
3704 /* Any QObject can be passed. */
3705 break;
3706 case '/':
3707 case '.':
3709 * These types are not supported by QMP and thus are not
3710 * handled here. Fall through.
3712 default:
3713 abort();
3719 * - Check if the client has passed all mandatory args
3720 * - Set special flags for argument validation
3722 static void check_mandatory_args(const QDict *cmd_args,
3723 const QDict *client_args, int *flags,
3724 Error **errp)
3726 const QDictEntry *ent;
3728 for (ent = qdict_first(cmd_args); ent; ent = qdict_next(cmd_args, ent)) {
3729 const char *cmd_arg_name = qdict_entry_key(ent);
3730 QString *type = qobject_to_qstring(qdict_entry_value(ent));
3731 assert(type != NULL);
3733 if (qstring_get_str(type)[0] == 'O') {
3734 assert((*flags & QMP_ACCEPT_UNKNOWNS) == 0);
3735 *flags |= QMP_ACCEPT_UNKNOWNS;
3736 } else if (qstring_get_str(type)[0] != '-' &&
3737 qstring_get_str(type)[1] != '?' &&
3738 !qdict_haskey(client_args, cmd_arg_name)) {
3739 error_setg(errp, QERR_MISSING_PARAMETER, cmd_arg_name);
3740 return;
3745 static QDict *qdict_from_args_type(const char *args_type)
3747 int i;
3748 QDict *qdict;
3749 QString *key, *type, *cur_qs;
3751 assert(args_type != NULL);
3753 qdict = qdict_new();
3755 if (args_type == NULL || args_type[0] == '\0') {
3756 /* no args, empty qdict */
3757 goto out;
3760 key = qstring_new();
3761 type = qstring_new();
3763 cur_qs = key;
3765 for (i = 0;; i++) {
3766 switch (args_type[i]) {
3767 case ',':
3768 case '\0':
3769 qdict_put(qdict, qstring_get_str(key), type);
3770 QDECREF(key);
3771 if (args_type[i] == '\0') {
3772 goto out;
3774 type = qstring_new(); /* qdict has ref */
3775 cur_qs = key = qstring_new();
3776 break;
3777 case ':':
3778 cur_qs = type;
3779 break;
3780 default:
3781 qstring_append_chr(cur_qs, args_type[i]);
3782 break;
3786 out:
3787 return qdict;
3791 * Client argument checking rules:
3793 * 1. Client must provide all mandatory arguments
3794 * 2. Each argument provided by the client must be expected
3795 * 3. Each argument provided by the client must have the type expected
3796 * by the command
3798 static void qmp_check_client_args(const mon_cmd_t *cmd, QDict *client_args,
3799 Error **errp)
3801 Error *err = NULL;
3802 int flags;
3803 QDict *cmd_args;
3805 cmd_args = qdict_from_args_type(cmd->args_type);
3807 flags = 0;
3808 check_mandatory_args(cmd_args, client_args, &flags, &err);
3809 if (err) {
3810 goto out;
3813 check_client_args_type(client_args, cmd_args, flags, &err);
3815 out:
3816 error_propagate(errp, err);
3817 QDECREF(cmd_args);
3821 * Input object checking rules
3823 * 1. Input object must be a dict
3824 * 2. The "execute" key must exist
3825 * 3. The "execute" key must be a string
3826 * 4. If the "arguments" key exists, it must be a dict
3827 * 5. If the "id" key exists, it can be anything (ie. json-value)
3828 * 6. Any argument not listed above is considered invalid
3830 static QDict *qmp_check_input_obj(QObject *input_obj, Error **errp)
3832 const QDictEntry *ent;
3833 int has_exec_key = 0;
3834 QDict *input_dict;
3836 if (qobject_type(input_obj) != QTYPE_QDICT) {
3837 error_setg(errp, QERR_QMP_BAD_INPUT_OBJECT, "object");
3838 return NULL;
3841 input_dict = qobject_to_qdict(input_obj);
3843 for (ent = qdict_first(input_dict); ent; ent = qdict_next(input_dict, ent)){
3844 const char *arg_name = qdict_entry_key(ent);
3845 const QObject *arg_obj = qdict_entry_value(ent);
3847 if (!strcmp(arg_name, "execute")) {
3848 if (qobject_type(arg_obj) != QTYPE_QSTRING) {
3849 error_setg(errp, QERR_QMP_BAD_INPUT_OBJECT_MEMBER,
3850 "execute", "string");
3851 return NULL;
3853 has_exec_key = 1;
3854 } else if (!strcmp(arg_name, "arguments")) {
3855 if (qobject_type(arg_obj) != QTYPE_QDICT) {
3856 error_setg(errp, QERR_QMP_BAD_INPUT_OBJECT_MEMBER,
3857 "arguments", "object");
3858 return NULL;
3860 } else if (!strcmp(arg_name, "id")) {
3861 /* Any string is acceptable as "id", so nothing to check */
3862 } else {
3863 error_setg(errp, QERR_QMP_EXTRA_MEMBER, arg_name);
3864 return NULL;
3868 if (!has_exec_key) {
3869 error_setg(errp, QERR_QMP_BAD_INPUT_OBJECT, "execute");
3870 return NULL;
3873 return input_dict;
3876 static void handle_qmp_command(JSONMessageParser *parser, GQueue *tokens)
3878 Error *local_err = NULL;
3879 QObject *obj, *data;
3880 QDict *input, *args;
3881 const mon_cmd_t *cmd;
3882 const char *cmd_name;
3883 Monitor *mon = cur_mon;
3885 args = input = NULL;
3886 data = NULL;
3888 obj = json_parser_parse(tokens, NULL);
3889 if (!obj) {
3890 // FIXME: should be triggered in json_parser_parse()
3891 error_setg(&local_err, QERR_JSON_PARSING);
3892 goto err_out;
3895 input = qmp_check_input_obj(obj, &local_err);
3896 if (!input) {
3897 qobject_decref(obj);
3898 goto err_out;
3901 mon->qmp.id = qdict_get(input, "id");
3902 qobject_incref(mon->qmp.id);
3904 cmd_name = qdict_get_str(input, "execute");
3905 trace_handle_qmp_command(mon, cmd_name);
3906 cmd = qmp_find_cmd(cmd_name);
3907 if (!cmd) {
3908 error_set(&local_err, ERROR_CLASS_COMMAND_NOT_FOUND,
3909 "The command %s has not been found", cmd_name);
3910 goto err_out;
3912 if (invalid_qmp_mode(mon, cmd, &local_err)) {
3913 goto err_out;
3916 obj = qdict_get(input, "arguments");
3917 if (!obj) {
3918 args = qdict_new();
3919 } else {
3920 args = qobject_to_qdict(obj);
3921 QINCREF(args);
3924 qmp_check_client_args(cmd, args, &local_err);
3925 if (local_err) {
3926 goto err_out;
3929 cmd->mhandler.cmd_new(args, &data, &local_err);
3931 err_out:
3932 monitor_protocol_emitter(mon, data, local_err);
3933 qobject_decref(data);
3934 error_free(local_err);
3935 QDECREF(input);
3936 QDECREF(args);
3939 static void monitor_qmp_read(void *opaque, const uint8_t *buf, int size)
3941 Monitor *old_mon = cur_mon;
3943 cur_mon = opaque;
3945 json_message_parser_feed(&cur_mon->qmp.parser, (const char *) buf, size);
3947 cur_mon = old_mon;
3950 static void monitor_read(void *opaque, const uint8_t *buf, int size)
3952 Monitor *old_mon = cur_mon;
3953 int i;
3955 cur_mon = opaque;
3957 if (cur_mon->rs) {
3958 for (i = 0; i < size; i++)
3959 readline_handle_byte(cur_mon->rs, buf[i]);
3960 } else {
3961 if (size == 0 || buf[size - 1] != 0)
3962 monitor_printf(cur_mon, "corrupted command\n");
3963 else
3964 handle_hmp_command(cur_mon, (char *)buf);
3967 cur_mon = old_mon;
3970 static void monitor_command_cb(void *opaque, const char *cmdline,
3971 void *readline_opaque)
3973 Monitor *mon = opaque;
3975 monitor_suspend(mon);
3976 handle_hmp_command(mon, cmdline);
3977 monitor_resume(mon);
3980 int monitor_suspend(Monitor *mon)
3982 if (!mon->rs)
3983 return -ENOTTY;
3984 mon->suspend_cnt++;
3985 return 0;
3988 void monitor_resume(Monitor *mon)
3990 if (!mon->rs)
3991 return;
3992 if (--mon->suspend_cnt == 0)
3993 readline_show_prompt(mon->rs);
3996 static QObject *get_qmp_greeting(void)
3998 QObject *ver = NULL;
4000 qmp_marshal_query_version(NULL, &ver, NULL);
4001 return qobject_from_jsonf("{'QMP':{'version': %p,'capabilities': []}}",ver);
4004 static void monitor_qmp_event(void *opaque, int event)
4006 QObject *data;
4007 Monitor *mon = opaque;
4009 switch (event) {
4010 case CHR_EVENT_OPENED:
4011 mon->qmp.in_command_mode = false;
4012 data = get_qmp_greeting();
4013 monitor_json_emitter(mon, data);
4014 qobject_decref(data);
4015 mon_refcount++;
4016 break;
4017 case CHR_EVENT_CLOSED:
4018 json_message_parser_destroy(&mon->qmp.parser);
4019 json_message_parser_init(&mon->qmp.parser, handle_qmp_command);
4020 mon_refcount--;
4021 monitor_fdsets_cleanup();
4022 break;
4026 static void monitor_event(void *opaque, int event)
4028 Monitor *mon = opaque;
4030 switch (event) {
4031 case CHR_EVENT_MUX_IN:
4032 qemu_mutex_lock(&mon->out_lock);
4033 mon->mux_out = 0;
4034 qemu_mutex_unlock(&mon->out_lock);
4035 if (mon->reset_seen) {
4036 readline_restart(mon->rs);
4037 monitor_resume(mon);
4038 monitor_flush(mon);
4039 } else {
4040 mon->suspend_cnt = 0;
4042 break;
4044 case CHR_EVENT_MUX_OUT:
4045 if (mon->reset_seen) {
4046 if (mon->suspend_cnt == 0) {
4047 monitor_printf(mon, "\n");
4049 monitor_flush(mon);
4050 monitor_suspend(mon);
4051 } else {
4052 mon->suspend_cnt++;
4054 qemu_mutex_lock(&mon->out_lock);
4055 mon->mux_out = 1;
4056 qemu_mutex_unlock(&mon->out_lock);
4057 break;
4059 case CHR_EVENT_OPENED:
4060 monitor_printf(mon, "QEMU %s monitor - type 'help' for more "
4061 "information\n", QEMU_VERSION);
4062 if (!mon->mux_out) {
4063 readline_restart(mon->rs);
4064 readline_show_prompt(mon->rs);
4066 mon->reset_seen = 1;
4067 mon_refcount++;
4068 break;
4070 case CHR_EVENT_CLOSED:
4071 mon_refcount--;
4072 monitor_fdsets_cleanup();
4073 break;
4077 static int
4078 compare_mon_cmd(const void *a, const void *b)
4080 return strcmp(((const mon_cmd_t *)a)->name,
4081 ((const mon_cmd_t *)b)->name);
4084 static void sortcmdlist(void)
4086 int array_num;
4087 int elem_size = sizeof(mon_cmd_t);
4089 array_num = sizeof(mon_cmds)/elem_size-1;
4090 qsort((void *)mon_cmds, array_num, elem_size, compare_mon_cmd);
4092 array_num = sizeof(info_cmds)/elem_size-1;
4093 qsort((void *)info_cmds, array_num, elem_size, compare_mon_cmd);
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
4261 #ifndef TARGET_ARM
4262 GICCapabilityList *qmp_query_gic_capabilities(Error **errp)
4264 error_setg(errp, QERR_FEATURE_DISABLED, "query-gic-capabilities");
4265 return NULL;
4267 #endif
4269 HotpluggableCPUList *qmp_query_hotpluggable_cpus(Error **errp)
4271 MachineState *ms = MACHINE(qdev_get_machine());
4272 MachineClass *mc = MACHINE_GET_CLASS(ms);
4274 if (!mc->query_hotpluggable_cpus) {
4275 error_setg(errp, QERR_FEATURE_DISABLED, "query-hotpluggable-cpus");
4276 return NULL;
4279 return mc->query_hotpluggable_cpus(ms);