util: Use g_malloc/g_free in envlist.c
[qemu.git] / monitor.c
blob62c9f81e8e0092d04a34a44ab6f85fe2119f7228
1 /*
2 * QEMU monitor
4 * Copyright (c) 2003-2004 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
24 #include "qemu/osdep.h"
25 #include <dirent.h>
26 #include "qemu-common.h"
27 #include "cpu.h"
28 #include "hw/hw.h"
29 #include "monitor/qdev.h"
30 #include "hw/usb.h"
31 #include "hw/i386/pc.h"
32 #include "hw/pci/pci.h"
33 #include "sysemu/watchdog.h"
34 #include "hw/loader.h"
35 #include "exec/gdbstub.h"
36 #include "net/net.h"
37 #include "net/slirp.h"
38 #include "sysemu/char.h"
39 #include "ui/qemu-spice.h"
40 #include "sysemu/sysemu.h"
41 #include "sysemu/numa.h"
42 #include "monitor/monitor.h"
43 #include "qemu/config-file.h"
44 #include "qemu/readline.h"
45 #include "ui/console.h"
46 #include "ui/input.h"
47 #include "sysemu/blockdev.h"
48 #include "sysemu/block-backend.h"
49 #include "audio/audio.h"
50 #include "disas/disas.h"
51 #include "sysemu/balloon.h"
52 #include "qemu/timer.h"
53 #include "migration/migration.h"
54 #include "sysemu/hw_accel.h"
55 #include "qemu/acl.h"
56 #include "sysemu/tpm.h"
57 #include "qapi/qmp/qerror.h"
58 #include "qapi/qmp/types.h"
59 #include "qapi/qmp/qjson.h"
60 #include "qapi/qmp/json-streamer.h"
61 #include "qapi/qmp/json-parser.h"
62 #include "qom/object_interfaces.h"
63 #include "trace-root.h"
64 #include "trace/control.h"
65 #include "monitor/hmp-target.h"
66 #ifdef CONFIG_TRACE_SIMPLE
67 #include "trace/simple.h"
68 #endif
69 #include "exec/memory.h"
70 #include "exec/exec-all.h"
71 #include "qemu/log.h"
72 #include "qmp-commands.h"
73 #include "hmp.h"
74 #include "qemu/thread.h"
75 #include "block/qapi.h"
76 #include "qapi/qmp-event.h"
77 #include "qapi-event.h"
78 #include "qmp-introspect.h"
79 #include "sysemu/qtest.h"
80 #include "sysemu/cpus.h"
81 #include "qemu/cutils.h"
82 #include "qapi/qmp/dispatch.h"
84 #if defined(TARGET_S390X)
85 #include "hw/s390x/storage-keys.h"
86 #endif
89 * Supported types:
91 * 'F' filename
92 * 'B' block device name
93 * 's' string (accept optional quote)
94 * 'S' it just appends the rest of the string (accept optional quote)
95 * 'O' option string of the form NAME=VALUE,...
96 * parsed according to QemuOptsList given by its name
97 * Example: 'device:O' uses qemu_device_opts.
98 * Restriction: only lists with empty desc are supported
99 * TODO lift the restriction
100 * 'i' 32 bit integer
101 * 'l' target long (32 or 64 bit)
102 * 'M' Non-negative target long (32 or 64 bit), in user mode the
103 * value is multiplied by 2^20 (think Mebibyte)
104 * 'o' octets (aka bytes)
105 * user mode accepts an optional E, e, P, p, T, t, G, g, M, m,
106 * K, k suffix, which multiplies the value by 2^60 for suffixes E
107 * and e, 2^50 for suffixes P and p, 2^40 for suffixes T and t,
108 * 2^30 for suffixes G and g, 2^20 for M and m, 2^10 for K and k
109 * 'T' double
110 * user mode accepts an optional ms, us, ns suffix,
111 * which divides the value by 1e3, 1e6, 1e9, respectively
112 * '/' optional gdb-like print format (like "/10x")
114 * '?' optional type (for all types, except '/')
115 * '.' other form of optional type (for 'i' and 'l')
116 * 'b' boolean
117 * user mode accepts "on" or "off"
118 * '-' optional parameter (eg. '-f')
122 typedef struct mon_cmd_t {
123 const char *name;
124 const char *args_type;
125 const char *params;
126 const char *help;
127 void (*cmd)(Monitor *mon, const QDict *qdict);
128 /* @sub_table is a list of 2nd level of commands. If it does not exist,
129 * cmd should be used. If it exists, sub_table[?].cmd should be
130 * used, and cmd of 1st level plays the role of help function.
132 struct mon_cmd_t *sub_table;
133 void (*command_completion)(ReadLineState *rs, int nb_args, const char *str);
134 } mon_cmd_t;
136 /* file descriptors passed via SCM_RIGHTS */
137 typedef struct mon_fd_t mon_fd_t;
138 struct mon_fd_t {
139 char *name;
140 int fd;
141 QLIST_ENTRY(mon_fd_t) next;
144 /* file descriptor associated with a file descriptor set */
145 typedef struct MonFdsetFd MonFdsetFd;
146 struct MonFdsetFd {
147 int fd;
148 bool removed;
149 char *opaque;
150 QLIST_ENTRY(MonFdsetFd) next;
153 /* file descriptor set containing fds passed via SCM_RIGHTS */
154 typedef struct MonFdset MonFdset;
155 struct MonFdset {
156 int64_t id;
157 QLIST_HEAD(, MonFdsetFd) fds;
158 QLIST_HEAD(, MonFdsetFd) dup_fds;
159 QLIST_ENTRY(MonFdset) next;
162 typedef struct {
163 JSONMessageParser parser;
165 * When a client connects, we're in capabilities negotiation mode.
166 * When command qmp_capabilities succeeds, we go into command
167 * mode.
169 QmpCommandList *commands;
170 } MonitorQMP;
173 * To prevent flooding clients, events can be throttled. The
174 * throttling is calculated globally, rather than per-Monitor
175 * instance.
177 typedef struct MonitorQAPIEventState {
178 QAPIEvent event; /* Throttling state for this event type and... */
179 QDict *data; /* ... data, see qapi_event_throttle_equal() */
180 QEMUTimer *timer; /* Timer for handling delayed events */
181 QDict *qdict; /* Delayed event (if any) */
182 } MonitorQAPIEventState;
184 typedef struct {
185 int64_t rate; /* Minimum time (in ns) between two events */
186 } MonitorQAPIEventConf;
188 struct Monitor {
189 CharBackend chr;
190 int reset_seen;
191 int flags;
192 int suspend_cnt;
193 bool skip_flush;
195 QemuMutex out_lock;
196 QString *outbuf;
197 guint out_watch;
199 /* Read under either BQL or out_lock, written with BQL+out_lock. */
200 int mux_out;
202 ReadLineState *rs;
203 MonitorQMP qmp;
204 CPUState *mon_cpu;
205 BlockCompletionFunc *password_completion_cb;
206 void *password_opaque;
207 mon_cmd_t *cmd_table;
208 QLIST_HEAD(,mon_fd_t) fds;
209 QLIST_ENTRY(Monitor) entry;
212 /* QMP checker flags */
213 #define QMP_ACCEPT_UNKNOWNS 1
215 /* Protects mon_list, monitor_event_state. */
216 static QemuMutex monitor_lock;
218 static QLIST_HEAD(mon_list, Monitor) mon_list;
219 static QLIST_HEAD(mon_fdsets, MonFdset) mon_fdsets;
220 static int mon_refcount;
222 static mon_cmd_t mon_cmds[];
223 static mon_cmd_t info_cmds[];
225 QmpCommandList qmp_commands, qmp_cap_negotiation_commands;
227 Monitor *cur_mon;
229 static QEMUClockType event_clock_type = QEMU_CLOCK_REALTIME;
231 static void monitor_command_cb(void *opaque, const char *cmdline,
232 void *readline_opaque);
235 * Is @mon a QMP monitor?
237 static inline bool monitor_is_qmp(const Monitor *mon)
239 return (mon->flags & MONITOR_USE_CONTROL);
243 * Is the current monitor, if any, a QMP monitor?
245 bool monitor_cur_is_qmp(void)
247 return cur_mon && monitor_is_qmp(cur_mon);
250 void monitor_read_command(Monitor *mon, int show_prompt)
252 if (!mon->rs)
253 return;
255 readline_start(mon->rs, "(qemu) ", 0, monitor_command_cb, NULL);
256 if (show_prompt)
257 readline_show_prompt(mon->rs);
260 int monitor_read_password(Monitor *mon, ReadLineFunc *readline_func,
261 void *opaque)
263 if (mon->rs) {
264 readline_start(mon->rs, "Password: ", 1, readline_func, opaque);
265 /* prompt is printed on return from the command handler */
266 return 0;
267 } else {
268 monitor_printf(mon, "terminal does not support password prompting\n");
269 return -ENOTTY;
273 static void monitor_flush_locked(Monitor *mon);
275 static gboolean monitor_unblocked(GIOChannel *chan, GIOCondition cond,
276 void *opaque)
278 Monitor *mon = opaque;
280 qemu_mutex_lock(&mon->out_lock);
281 mon->out_watch = 0;
282 monitor_flush_locked(mon);
283 qemu_mutex_unlock(&mon->out_lock);
284 return FALSE;
287 /* Called with mon->out_lock held. */
288 static void monitor_flush_locked(Monitor *mon)
290 int rc;
291 size_t len;
292 const char *buf;
294 if (mon->skip_flush) {
295 return;
298 buf = qstring_get_str(mon->outbuf);
299 len = qstring_get_length(mon->outbuf);
301 if (len && !mon->mux_out) {
302 rc = qemu_chr_fe_write(&mon->chr, (const uint8_t *) buf, len);
303 if ((rc < 0 && errno != EAGAIN) || (rc == len)) {
304 /* all flushed or error */
305 QDECREF(mon->outbuf);
306 mon->outbuf = qstring_new();
307 return;
309 if (rc > 0) {
310 /* partial write */
311 QString *tmp = qstring_from_str(buf + rc);
312 QDECREF(mon->outbuf);
313 mon->outbuf = tmp;
315 if (mon->out_watch == 0) {
316 mon->out_watch =
317 qemu_chr_fe_add_watch(&mon->chr, G_IO_OUT | G_IO_HUP,
318 monitor_unblocked, mon);
323 void monitor_flush(Monitor *mon)
325 qemu_mutex_lock(&mon->out_lock);
326 monitor_flush_locked(mon);
327 qemu_mutex_unlock(&mon->out_lock);
330 /* flush at every end of line */
331 static void monitor_puts(Monitor *mon, const char *str)
333 char c;
335 qemu_mutex_lock(&mon->out_lock);
336 for(;;) {
337 c = *str++;
338 if (c == '\0')
339 break;
340 if (c == '\n') {
341 qstring_append_chr(mon->outbuf, '\r');
343 qstring_append_chr(mon->outbuf, c);
344 if (c == '\n') {
345 monitor_flush_locked(mon);
348 qemu_mutex_unlock(&mon->out_lock);
351 void monitor_vprintf(Monitor *mon, const char *fmt, va_list ap)
353 char *buf;
355 if (!mon)
356 return;
358 if (monitor_is_qmp(mon)) {
359 return;
362 buf = g_strdup_vprintf(fmt, ap);
363 monitor_puts(mon, buf);
364 g_free(buf);
367 void monitor_printf(Monitor *mon, const char *fmt, ...)
369 va_list ap;
370 va_start(ap, fmt);
371 monitor_vprintf(mon, fmt, ap);
372 va_end(ap);
375 int monitor_fprintf(FILE *stream, const char *fmt, ...)
377 va_list ap;
378 va_start(ap, fmt);
379 monitor_vprintf((Monitor *)stream, fmt, ap);
380 va_end(ap);
381 return 0;
384 static void monitor_json_emitter(Monitor *mon, const QObject *data)
386 QString *json;
388 json = mon->flags & MONITOR_USE_PRETTY ? qobject_to_json_pretty(data) :
389 qobject_to_json(data);
390 assert(json != NULL);
392 qstring_append_chr(json, '\n');
393 monitor_puts(mon, qstring_get_str(json));
395 QDECREF(json);
398 static MonitorQAPIEventConf monitor_qapi_event_conf[QAPI_EVENT__MAX] = {
399 /* Limit guest-triggerable events to 1 per second */
400 [QAPI_EVENT_RTC_CHANGE] = { 1000 * SCALE_MS },
401 [QAPI_EVENT_WATCHDOG] = { 1000 * SCALE_MS },
402 [QAPI_EVENT_BALLOON_CHANGE] = { 1000 * SCALE_MS },
403 [QAPI_EVENT_QUORUM_REPORT_BAD] = { 1000 * SCALE_MS },
404 [QAPI_EVENT_QUORUM_FAILURE] = { 1000 * SCALE_MS },
405 [QAPI_EVENT_VSERPORT_CHANGE] = { 1000 * SCALE_MS },
408 GHashTable *monitor_qapi_event_state;
411 * Emits the event to every monitor instance, @event is only used for trace
412 * Called with monitor_lock held.
414 static void monitor_qapi_event_emit(QAPIEvent event, QDict *qdict)
416 Monitor *mon;
418 trace_monitor_protocol_event_emit(event, qdict);
419 QLIST_FOREACH(mon, &mon_list, entry) {
420 if (monitor_is_qmp(mon)
421 && mon->qmp.commands != &qmp_cap_negotiation_commands) {
422 monitor_json_emitter(mon, QOBJECT(qdict));
427 static void monitor_qapi_event_handler(void *opaque);
430 * Queue a new event for emission to Monitor instances,
431 * applying any rate limiting if required.
433 static void
434 monitor_qapi_event_queue(QAPIEvent event, QDict *qdict, Error **errp)
436 MonitorQAPIEventConf *evconf;
437 MonitorQAPIEventState *evstate;
439 assert(event < QAPI_EVENT__MAX);
440 evconf = &monitor_qapi_event_conf[event];
441 trace_monitor_protocol_event_queue(event, qdict, evconf->rate);
443 qemu_mutex_lock(&monitor_lock);
445 if (!evconf->rate) {
446 /* Unthrottled event */
447 monitor_qapi_event_emit(event, qdict);
448 } else {
449 QDict *data = qobject_to_qdict(qdict_get(qdict, "data"));
450 MonitorQAPIEventState key = { .event = event, .data = data };
452 evstate = g_hash_table_lookup(monitor_qapi_event_state, &key);
453 assert(!evstate || timer_pending(evstate->timer));
455 if (evstate) {
457 * Timer is pending for (at least) evconf->rate ns after
458 * last send. Store event for sending when timer fires,
459 * replacing a prior stored event if any.
461 QDECREF(evstate->qdict);
462 evstate->qdict = qdict;
463 QINCREF(evstate->qdict);
464 } else {
466 * Last send was (at least) evconf->rate ns ago.
467 * Send immediately, and arm the timer to call
468 * monitor_qapi_event_handler() in evconf->rate ns. Any
469 * events arriving before then will be delayed until then.
471 int64_t now = qemu_clock_get_ns(event_clock_type);
473 monitor_qapi_event_emit(event, qdict);
475 evstate = g_new(MonitorQAPIEventState, 1);
476 evstate->event = event;
477 evstate->data = data;
478 QINCREF(evstate->data);
479 evstate->qdict = NULL;
480 evstate->timer = timer_new_ns(event_clock_type,
481 monitor_qapi_event_handler,
482 evstate);
483 g_hash_table_add(monitor_qapi_event_state, evstate);
484 timer_mod_ns(evstate->timer, now + evconf->rate);
488 qemu_mutex_unlock(&monitor_lock);
492 * This function runs evconf->rate ns after sending a throttled
493 * event.
494 * If another event has since been stored, send it.
496 static void monitor_qapi_event_handler(void *opaque)
498 MonitorQAPIEventState *evstate = opaque;
499 MonitorQAPIEventConf *evconf = &monitor_qapi_event_conf[evstate->event];
501 trace_monitor_protocol_event_handler(evstate->event, evstate->qdict);
502 qemu_mutex_lock(&monitor_lock);
504 if (evstate->qdict) {
505 int64_t now = qemu_clock_get_ns(event_clock_type);
507 monitor_qapi_event_emit(evstate->event, evstate->qdict);
508 QDECREF(evstate->qdict);
509 evstate->qdict = NULL;
510 timer_mod_ns(evstate->timer, now + evconf->rate);
511 } else {
512 g_hash_table_remove(monitor_qapi_event_state, evstate);
513 QDECREF(evstate->data);
514 timer_free(evstate->timer);
515 g_free(evstate);
518 qemu_mutex_unlock(&monitor_lock);
521 static unsigned int qapi_event_throttle_hash(const void *key)
523 const MonitorQAPIEventState *evstate = key;
524 unsigned int hash = evstate->event * 255;
526 if (evstate->event == QAPI_EVENT_VSERPORT_CHANGE) {
527 hash += g_str_hash(qdict_get_str(evstate->data, "id"));
530 if (evstate->event == QAPI_EVENT_QUORUM_REPORT_BAD) {
531 hash += g_str_hash(qdict_get_str(evstate->data, "node-name"));
534 return hash;
537 static gboolean qapi_event_throttle_equal(const void *a, const void *b)
539 const MonitorQAPIEventState *eva = a;
540 const MonitorQAPIEventState *evb = b;
542 if (eva->event != evb->event) {
543 return FALSE;
546 if (eva->event == QAPI_EVENT_VSERPORT_CHANGE) {
547 return !strcmp(qdict_get_str(eva->data, "id"),
548 qdict_get_str(evb->data, "id"));
551 if (eva->event == QAPI_EVENT_QUORUM_REPORT_BAD) {
552 return !strcmp(qdict_get_str(eva->data, "node-name"),
553 qdict_get_str(evb->data, "node-name"));
556 return TRUE;
559 static void monitor_qapi_event_init(void)
561 if (qtest_enabled()) {
562 event_clock_type = QEMU_CLOCK_VIRTUAL;
565 monitor_qapi_event_state = g_hash_table_new(qapi_event_throttle_hash,
566 qapi_event_throttle_equal);
567 qmp_event_set_func_emit(monitor_qapi_event_queue);
570 static void handle_hmp_command(Monitor *mon, const char *cmdline);
572 static void monitor_data_init(Monitor *mon)
574 memset(mon, 0, sizeof(Monitor));
575 qemu_mutex_init(&mon->out_lock);
576 mon->outbuf = qstring_new();
577 /* Use *mon_cmds by default. */
578 mon->cmd_table = mon_cmds;
581 static void monitor_data_destroy(Monitor *mon)
583 qemu_chr_fe_deinit(&mon->chr);
584 if (monitor_is_qmp(mon)) {
585 json_message_parser_destroy(&mon->qmp.parser);
587 g_free(mon->rs);
588 QDECREF(mon->outbuf);
589 qemu_mutex_destroy(&mon->out_lock);
592 char *qmp_human_monitor_command(const char *command_line, bool has_cpu_index,
593 int64_t cpu_index, Error **errp)
595 char *output = NULL;
596 Monitor *old_mon, hmp;
598 monitor_data_init(&hmp);
599 hmp.skip_flush = true;
601 old_mon = cur_mon;
602 cur_mon = &hmp;
604 if (has_cpu_index) {
605 int ret = monitor_set_cpu(cpu_index);
606 if (ret < 0) {
607 cur_mon = old_mon;
608 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cpu-index",
609 "a CPU number");
610 goto out;
614 handle_hmp_command(&hmp, command_line);
615 cur_mon = old_mon;
617 qemu_mutex_lock(&hmp.out_lock);
618 if (qstring_get_length(hmp.outbuf) > 0) {
619 output = g_strdup(qstring_get_str(hmp.outbuf));
620 } else {
621 output = g_strdup("");
623 qemu_mutex_unlock(&hmp.out_lock);
625 out:
626 monitor_data_destroy(&hmp);
627 return output;
630 static int compare_cmd(const char *name, const char *list)
632 const char *p, *pstart;
633 int len;
634 len = strlen(name);
635 p = list;
636 for(;;) {
637 pstart = p;
638 p = strchr(p, '|');
639 if (!p)
640 p = pstart + strlen(pstart);
641 if ((p - pstart) == len && !memcmp(pstart, name, len))
642 return 1;
643 if (*p == '\0')
644 break;
645 p++;
647 return 0;
650 static int get_str(char *buf, int buf_size, const char **pp)
652 const char *p;
653 char *q;
654 int c;
656 q = buf;
657 p = *pp;
658 while (qemu_isspace(*p)) {
659 p++;
661 if (*p == '\0') {
662 fail:
663 *q = '\0';
664 *pp = p;
665 return -1;
667 if (*p == '\"') {
668 p++;
669 while (*p != '\0' && *p != '\"') {
670 if (*p == '\\') {
671 p++;
672 c = *p++;
673 switch (c) {
674 case 'n':
675 c = '\n';
676 break;
677 case 'r':
678 c = '\r';
679 break;
680 case '\\':
681 case '\'':
682 case '\"':
683 break;
684 default:
685 printf("unsupported escape code: '\\%c'\n", c);
686 goto fail;
688 if ((q - buf) < buf_size - 1) {
689 *q++ = c;
691 } else {
692 if ((q - buf) < buf_size - 1) {
693 *q++ = *p;
695 p++;
698 if (*p != '\"') {
699 printf("unterminated string\n");
700 goto fail;
702 p++;
703 } else {
704 while (*p != '\0' && !qemu_isspace(*p)) {
705 if ((q - buf) < buf_size - 1) {
706 *q++ = *p;
708 p++;
711 *q = '\0';
712 *pp = p;
713 return 0;
716 #define MAX_ARGS 16
718 static void free_cmdline_args(char **args, int nb_args)
720 int i;
722 assert(nb_args <= MAX_ARGS);
724 for (i = 0; i < nb_args; i++) {
725 g_free(args[i]);
731 * Parse the command line to get valid args.
732 * @cmdline: command line to be parsed.
733 * @pnb_args: location to store the number of args, must NOT be NULL.
734 * @args: location to store the args, which should be freed by caller, must
735 * NOT be NULL.
737 * Returns 0 on success, negative on failure.
739 * NOTE: this parser is an approximate form of the real command parser. Number
740 * of args have a limit of MAX_ARGS. If cmdline contains more, it will
741 * return with failure.
743 static int parse_cmdline(const char *cmdline,
744 int *pnb_args, char **args)
746 const char *p;
747 int nb_args, ret;
748 char buf[1024];
750 p = cmdline;
751 nb_args = 0;
752 for (;;) {
753 while (qemu_isspace(*p)) {
754 p++;
756 if (*p == '\0') {
757 break;
759 if (nb_args >= MAX_ARGS) {
760 goto fail;
762 ret = get_str(buf, sizeof(buf), &p);
763 if (ret < 0) {
764 goto fail;
766 args[nb_args] = g_strdup(buf);
767 nb_args++;
769 *pnb_args = nb_args;
770 return 0;
772 fail:
773 free_cmdline_args(args, nb_args);
774 return -1;
777 static void help_cmd_dump_one(Monitor *mon,
778 const mon_cmd_t *cmd,
779 char **prefix_args,
780 int prefix_args_nb)
782 int i;
784 for (i = 0; i < prefix_args_nb; i++) {
785 monitor_printf(mon, "%s ", prefix_args[i]);
787 monitor_printf(mon, "%s %s -- %s\n", cmd->name, cmd->params, cmd->help);
790 /* @args[@arg_index] is the valid command need to find in @cmds */
791 static void help_cmd_dump(Monitor *mon, const mon_cmd_t *cmds,
792 char **args, int nb_args, int arg_index)
794 const mon_cmd_t *cmd;
796 /* No valid arg need to compare with, dump all in *cmds */
797 if (arg_index >= nb_args) {
798 for (cmd = cmds; cmd->name != NULL; cmd++) {
799 help_cmd_dump_one(mon, cmd, args, arg_index);
801 return;
804 /* Find one entry to dump */
805 for (cmd = cmds; cmd->name != NULL; cmd++) {
806 if (compare_cmd(args[arg_index], cmd->name)) {
807 if (cmd->sub_table) {
808 /* continue with next arg */
809 help_cmd_dump(mon, cmd->sub_table,
810 args, nb_args, arg_index + 1);
811 } else {
812 help_cmd_dump_one(mon, cmd, args, arg_index);
814 break;
819 static void help_cmd(Monitor *mon, const char *name)
821 char *args[MAX_ARGS];
822 int nb_args = 0;
824 /* 1. parse user input */
825 if (name) {
826 /* special case for log, directly dump and return */
827 if (!strcmp(name, "log")) {
828 const QEMULogItem *item;
829 monitor_printf(mon, "Log items (comma separated):\n");
830 monitor_printf(mon, "%-10s %s\n", "none", "remove all logs");
831 for (item = qemu_log_items; item->mask != 0; item++) {
832 monitor_printf(mon, "%-10s %s\n", item->name, item->help);
834 return;
837 if (parse_cmdline(name, &nb_args, args) < 0) {
838 return;
842 /* 2. dump the contents according to parsed args */
843 help_cmd_dump(mon, mon->cmd_table, args, nb_args, 0);
845 free_cmdline_args(args, nb_args);
848 static void do_help_cmd(Monitor *mon, const QDict *qdict)
850 help_cmd(mon, qdict_get_try_str(qdict, "name"));
853 static void hmp_trace_event(Monitor *mon, const QDict *qdict)
855 const char *tp_name = qdict_get_str(qdict, "name");
856 bool new_state = qdict_get_bool(qdict, "option");
857 bool has_vcpu = qdict_haskey(qdict, "vcpu");
858 int vcpu = qdict_get_try_int(qdict, "vcpu", 0);
859 Error *local_err = NULL;
861 if (vcpu < 0) {
862 monitor_printf(mon, "argument vcpu must be positive");
863 return;
866 qmp_trace_event_set_state(tp_name, new_state, true, true, has_vcpu, vcpu, &local_err);
867 if (local_err) {
868 error_report_err(local_err);
872 #ifdef CONFIG_TRACE_SIMPLE
873 static void hmp_trace_file(Monitor *mon, const QDict *qdict)
875 const char *op = qdict_get_try_str(qdict, "op");
876 const char *arg = qdict_get_try_str(qdict, "arg");
878 if (!op) {
879 st_print_trace_file_status((FILE *)mon, &monitor_fprintf);
880 } else if (!strcmp(op, "on")) {
881 st_set_trace_file_enabled(true);
882 } else if (!strcmp(op, "off")) {
883 st_set_trace_file_enabled(false);
884 } else if (!strcmp(op, "flush")) {
885 st_flush_trace_buffer();
886 } else if (!strcmp(op, "set")) {
887 if (arg) {
888 st_set_trace_file(arg);
890 } else {
891 monitor_printf(mon, "unexpected argument \"%s\"\n", op);
892 help_cmd(mon, "trace-file");
895 #endif
897 static void hmp_info_help(Monitor *mon, const QDict *qdict)
899 help_cmd(mon, "info");
902 static void query_commands_cb(QmpCommand *cmd, void *opaque)
904 CommandInfoList *info, **list = opaque;
906 if (!cmd->enabled) {
907 return;
910 info = g_malloc0(sizeof(*info));
911 info->value = g_malloc0(sizeof(*info->value));
912 info->value->name = g_strdup(cmd->name);
913 info->next = *list;
914 *list = info;
917 CommandInfoList *qmp_query_commands(Error **errp)
919 CommandInfoList *list = NULL;
921 qmp_for_each_command(cur_mon->qmp.commands, query_commands_cb, &list);
923 return list;
926 EventInfoList *qmp_query_events(Error **errp)
928 EventInfoList *info, *ev_list = NULL;
929 QAPIEvent e;
931 for (e = 0 ; e < QAPI_EVENT__MAX ; e++) {
932 const char *event_name = QAPIEvent_lookup[e];
933 assert(event_name != NULL);
934 info = g_malloc0(sizeof(*info));
935 info->value = g_malloc0(sizeof(*info->value));
936 info->value->name = g_strdup(event_name);
938 info->next = ev_list;
939 ev_list = info;
942 return ev_list;
946 * Minor hack: generated marshalling suppressed for this command
947 * ('gen': false in the schema) so we can parse the JSON string
948 * directly into QObject instead of first parsing it with
949 * visit_type_SchemaInfoList() into a SchemaInfoList, then marshal it
950 * to QObject with generated output marshallers, every time. Instead,
951 * we do it in test-qobject-input-visitor.c, just to make sure
952 * qapi-introspect.py's output actually conforms to the schema.
954 static void qmp_query_qmp_schema(QDict *qdict, QObject **ret_data,
955 Error **errp)
957 *ret_data = qobject_from_json(qmp_schema_json, &error_abort);
961 * We used to define commands in qmp-commands.hx in addition to the
962 * QAPI schema. This permitted defining some of them only in certain
963 * configurations. query-commands has always reflected that (good,
964 * because it lets QMP clients figure out what's actually available),
965 * while query-qmp-schema never did (not so good). This function is a
966 * hack to keep the configuration-specific commands defined exactly as
967 * before, even though qmp-commands.hx is gone.
969 * FIXME Educate the QAPI schema on configuration-specific commands,
970 * and drop this hack.
972 static void qmp_unregister_commands_hack(void)
974 #ifndef CONFIG_SPICE
975 qmp_unregister_command(&qmp_commands, "query-spice");
976 #endif
977 #ifndef CONFIG_REPLICATION
978 qmp_unregister_command(&qmp_commands, "xen-set-replication");
979 qmp_unregister_command(&qmp_commands, "query-xen-replication-status");
980 qmp_unregister_command(&qmp_commands, "xen-colo-do-checkpoint");
981 #endif
982 #ifndef TARGET_I386
983 qmp_unregister_command(&qmp_commands, "rtc-reset-reinjection");
984 #endif
985 #ifndef TARGET_S390X
986 qmp_unregister_command(&qmp_commands, "dump-skeys");
987 #endif
988 #ifndef TARGET_ARM
989 qmp_unregister_command(&qmp_commands, "query-gic-capabilities");
990 #endif
991 #if !defined(TARGET_S390X) && !defined(TARGET_I386)
992 qmp_unregister_command(&qmp_commands, "query-cpu-model-expansion");
993 #endif
994 #if !defined(TARGET_S390X)
995 qmp_unregister_command(&qmp_commands, "query-cpu-model-baseline");
996 qmp_unregister_command(&qmp_commands, "query-cpu-model-comparison");
997 #endif
998 #if !defined(TARGET_PPC) && !defined(TARGET_ARM) && !defined(TARGET_I386) \
999 && !defined(TARGET_S390X)
1000 qmp_unregister_command(&qmp_commands, "query-cpu-definitions");
1001 #endif
1004 void monitor_init_qmp_commands(void)
1007 * Two command lists:
1008 * - qmp_commands contains all QMP commands
1009 * - qmp_cap_negotiation_commands contains just
1010 * "qmp_capabilities", to enforce capability negotiation
1013 qmp_init_marshal(&qmp_commands);
1015 qmp_register_command(&qmp_commands, "query-qmp-schema",
1016 qmp_query_qmp_schema,
1017 QCO_NO_OPTIONS);
1018 qmp_register_command(&qmp_commands, "device_add", qmp_device_add,
1019 QCO_NO_OPTIONS);
1020 qmp_register_command(&qmp_commands, "netdev_add", qmp_netdev_add,
1021 QCO_NO_OPTIONS);
1023 qmp_unregister_commands_hack();
1025 QTAILQ_INIT(&qmp_cap_negotiation_commands);
1026 qmp_register_command(&qmp_cap_negotiation_commands, "qmp_capabilities",
1027 qmp_marshal_qmp_capabilities, QCO_NO_OPTIONS);
1030 void qmp_qmp_capabilities(Error **errp)
1032 if (cur_mon->qmp.commands == &qmp_commands) {
1033 error_set(errp, ERROR_CLASS_COMMAND_NOT_FOUND,
1034 "Capabilities negotiation is already complete, command "
1035 "ignored");
1036 return;
1039 cur_mon->qmp.commands = &qmp_commands;
1042 /* set the current CPU defined by the user */
1043 int monitor_set_cpu(int cpu_index)
1045 CPUState *cpu;
1047 cpu = qemu_get_cpu(cpu_index);
1048 if (cpu == NULL) {
1049 return -1;
1051 cur_mon->mon_cpu = cpu;
1052 return 0;
1055 CPUState *mon_get_cpu(void)
1057 if (!cur_mon->mon_cpu) {
1058 if (!first_cpu) {
1059 return NULL;
1061 monitor_set_cpu(first_cpu->cpu_index);
1063 cpu_synchronize_state(cur_mon->mon_cpu);
1064 return cur_mon->mon_cpu;
1067 CPUArchState *mon_get_cpu_env(void)
1069 CPUState *cs = mon_get_cpu();
1071 return cs ? cs->env_ptr : NULL;
1074 int monitor_get_cpu_index(void)
1076 CPUState *cs = mon_get_cpu();
1078 return cs ? cs->cpu_index : UNASSIGNED_CPU_INDEX;
1081 static void hmp_info_registers(Monitor *mon, const QDict *qdict)
1083 CPUState *cs = mon_get_cpu();
1085 if (!cs) {
1086 monitor_printf(mon, "No CPU available\n");
1087 return;
1089 cpu_dump_state(cs, (FILE *)mon, monitor_fprintf, CPU_DUMP_FPU);
1092 static void hmp_info_jit(Monitor *mon, const QDict *qdict)
1094 if (!tcg_enabled()) {
1095 error_report("JIT information is only available with accel=tcg");
1096 return;
1099 dump_exec_info((FILE *)mon, monitor_fprintf);
1100 dump_drift_info((FILE *)mon, monitor_fprintf);
1103 static void hmp_info_opcount(Monitor *mon, const QDict *qdict)
1105 dump_opcount_info((FILE *)mon, monitor_fprintf);
1108 static void hmp_info_history(Monitor *mon, const QDict *qdict)
1110 int i;
1111 const char *str;
1113 if (!mon->rs)
1114 return;
1115 i = 0;
1116 for(;;) {
1117 str = readline_get_history(mon->rs, i);
1118 if (!str)
1119 break;
1120 monitor_printf(mon, "%d: '%s'\n", i, str);
1121 i++;
1125 static void hmp_info_cpustats(Monitor *mon, const QDict *qdict)
1127 CPUState *cs = mon_get_cpu();
1129 if (!cs) {
1130 monitor_printf(mon, "No CPU available\n");
1131 return;
1133 cpu_dump_statistics(cs, (FILE *)mon, &monitor_fprintf, 0);
1136 static void hmp_info_trace_events(Monitor *mon, const QDict *qdict)
1138 const char *name = qdict_get_try_str(qdict, "name");
1139 bool has_vcpu = qdict_haskey(qdict, "vcpu");
1140 int vcpu = qdict_get_try_int(qdict, "vcpu", 0);
1141 TraceEventInfoList *events;
1142 TraceEventInfoList *elem;
1143 Error *local_err = NULL;
1145 if (name == NULL) {
1146 name = "*";
1148 if (vcpu < 0) {
1149 monitor_printf(mon, "argument vcpu must be positive");
1150 return;
1153 events = qmp_trace_event_get_state(name, has_vcpu, vcpu, &local_err);
1154 if (local_err) {
1155 error_report_err(local_err);
1156 return;
1159 for (elem = events; elem != NULL; elem = elem->next) {
1160 monitor_printf(mon, "%s : state %u\n",
1161 elem->value->name,
1162 elem->value->state == TRACE_EVENT_STATE_ENABLED ? 1 : 0);
1164 qapi_free_TraceEventInfoList(events);
1167 void qmp_client_migrate_info(const char *protocol, const char *hostname,
1168 bool has_port, int64_t port,
1169 bool has_tls_port, int64_t tls_port,
1170 bool has_cert_subject, const char *cert_subject,
1171 Error **errp)
1173 if (strcmp(protocol, "spice") == 0) {
1174 if (!qemu_using_spice(errp)) {
1175 return;
1178 if (!has_port && !has_tls_port) {
1179 error_setg(errp, QERR_MISSING_PARAMETER, "port/tls-port");
1180 return;
1183 if (qemu_spice_migrate_info(hostname,
1184 has_port ? port : -1,
1185 has_tls_port ? tls_port : -1,
1186 cert_subject)) {
1187 error_setg(errp, QERR_UNDEFINED_ERROR);
1188 return;
1190 return;
1193 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "protocol", "spice");
1196 static void hmp_logfile(Monitor *mon, const QDict *qdict)
1198 Error *err = NULL;
1200 qemu_set_log_filename(qdict_get_str(qdict, "filename"), &err);
1201 if (err) {
1202 error_report_err(err);
1206 static void hmp_log(Monitor *mon, const QDict *qdict)
1208 int mask;
1209 const char *items = qdict_get_str(qdict, "items");
1211 if (!strcmp(items, "none")) {
1212 mask = 0;
1213 } else {
1214 mask = qemu_str_to_log_mask(items);
1215 if (!mask) {
1216 help_cmd(mon, "log");
1217 return;
1220 qemu_set_log(mask);
1223 static void hmp_singlestep(Monitor *mon, const QDict *qdict)
1225 const char *option = qdict_get_try_str(qdict, "option");
1226 if (!option || !strcmp(option, "on")) {
1227 singlestep = 1;
1228 } else if (!strcmp(option, "off")) {
1229 singlestep = 0;
1230 } else {
1231 monitor_printf(mon, "unexpected option %s\n", option);
1235 static void hmp_gdbserver(Monitor *mon, const QDict *qdict)
1237 const char *device = qdict_get_try_str(qdict, "device");
1238 if (!device)
1239 device = "tcp::" DEFAULT_GDBSTUB_PORT;
1240 if (gdbserver_start(device) < 0) {
1241 monitor_printf(mon, "Could not open gdbserver on device '%s'\n",
1242 device);
1243 } else if (strcmp(device, "none") == 0) {
1244 monitor_printf(mon, "Disabled gdbserver\n");
1245 } else {
1246 monitor_printf(mon, "Waiting for gdb connection on device '%s'\n",
1247 device);
1251 static void hmp_watchdog_action(Monitor *mon, const QDict *qdict)
1253 const char *action = qdict_get_str(qdict, "action");
1254 if (select_watchdog_action(action) == -1) {
1255 monitor_printf(mon, "Unknown watchdog action '%s'\n", action);
1259 static void monitor_printc(Monitor *mon, int c)
1261 monitor_printf(mon, "'");
1262 switch(c) {
1263 case '\'':
1264 monitor_printf(mon, "\\'");
1265 break;
1266 case '\\':
1267 monitor_printf(mon, "\\\\");
1268 break;
1269 case '\n':
1270 monitor_printf(mon, "\\n");
1271 break;
1272 case '\r':
1273 monitor_printf(mon, "\\r");
1274 break;
1275 default:
1276 if (c >= 32 && c <= 126) {
1277 monitor_printf(mon, "%c", c);
1278 } else {
1279 monitor_printf(mon, "\\x%02x", c);
1281 break;
1283 monitor_printf(mon, "'");
1286 static void memory_dump(Monitor *mon, int count, int format, int wsize,
1287 hwaddr addr, int is_physical)
1289 int l, line_size, i, max_digits, len;
1290 uint8_t buf[16];
1291 uint64_t v;
1292 CPUState *cs = mon_get_cpu();
1294 if (!cs && (format == 'i' || !is_physical)) {
1295 monitor_printf(mon, "Can not dump without CPU\n");
1296 return;
1299 if (format == 'i') {
1300 int flags = 0;
1301 #ifdef TARGET_I386
1302 CPUArchState *env = mon_get_cpu_env();
1303 if (wsize == 2) {
1304 flags = 1;
1305 } else if (wsize == 4) {
1306 flags = 0;
1307 } else {
1308 /* as default we use the current CS size */
1309 flags = 0;
1310 if (env) {
1311 #ifdef TARGET_X86_64
1312 if ((env->efer & MSR_EFER_LMA) &&
1313 (env->segs[R_CS].flags & DESC_L_MASK))
1314 flags = 2;
1315 else
1316 #endif
1317 if (!(env->segs[R_CS].flags & DESC_B_MASK))
1318 flags = 1;
1321 #endif
1322 #ifdef TARGET_PPC
1323 CPUArchState *env = mon_get_cpu_env();
1324 flags = msr_le << 16;
1325 flags |= env->bfd_mach;
1326 #endif
1327 monitor_disas(mon, cs, addr, count, is_physical, flags);
1328 return;
1331 len = wsize * count;
1332 if (wsize == 1)
1333 line_size = 8;
1334 else
1335 line_size = 16;
1336 max_digits = 0;
1338 switch(format) {
1339 case 'o':
1340 max_digits = (wsize * 8 + 2) / 3;
1341 break;
1342 default:
1343 case 'x':
1344 max_digits = (wsize * 8) / 4;
1345 break;
1346 case 'u':
1347 case 'd':
1348 max_digits = (wsize * 8 * 10 + 32) / 33;
1349 break;
1350 case 'c':
1351 wsize = 1;
1352 break;
1355 while (len > 0) {
1356 if (is_physical)
1357 monitor_printf(mon, TARGET_FMT_plx ":", addr);
1358 else
1359 monitor_printf(mon, TARGET_FMT_lx ":", (target_ulong)addr);
1360 l = len;
1361 if (l > line_size)
1362 l = line_size;
1363 if (is_physical) {
1364 cpu_physical_memory_read(addr, buf, l);
1365 } else {
1366 if (cpu_memory_rw_debug(cs, addr, buf, l, 0) < 0) {
1367 monitor_printf(mon, " Cannot access memory\n");
1368 break;
1371 i = 0;
1372 while (i < l) {
1373 switch(wsize) {
1374 default:
1375 case 1:
1376 v = ldub_p(buf + i);
1377 break;
1378 case 2:
1379 v = lduw_p(buf + i);
1380 break;
1381 case 4:
1382 v = (uint32_t)ldl_p(buf + i);
1383 break;
1384 case 8:
1385 v = ldq_p(buf + i);
1386 break;
1388 monitor_printf(mon, " ");
1389 switch(format) {
1390 case 'o':
1391 monitor_printf(mon, "%#*" PRIo64, max_digits, v);
1392 break;
1393 case 'x':
1394 monitor_printf(mon, "0x%0*" PRIx64, max_digits, v);
1395 break;
1396 case 'u':
1397 monitor_printf(mon, "%*" PRIu64, max_digits, v);
1398 break;
1399 case 'd':
1400 monitor_printf(mon, "%*" PRId64, max_digits, v);
1401 break;
1402 case 'c':
1403 monitor_printc(mon, v);
1404 break;
1406 i += wsize;
1408 monitor_printf(mon, "\n");
1409 addr += l;
1410 len -= l;
1414 static void hmp_memory_dump(Monitor *mon, const QDict *qdict)
1416 int count = qdict_get_int(qdict, "count");
1417 int format = qdict_get_int(qdict, "format");
1418 int size = qdict_get_int(qdict, "size");
1419 target_long addr = qdict_get_int(qdict, "addr");
1421 memory_dump(mon, count, format, size, addr, 0);
1424 static void hmp_physical_memory_dump(Monitor *mon, const QDict *qdict)
1426 int count = qdict_get_int(qdict, "count");
1427 int format = qdict_get_int(qdict, "format");
1428 int size = qdict_get_int(qdict, "size");
1429 hwaddr addr = qdict_get_int(qdict, "addr");
1431 memory_dump(mon, count, format, size, addr, 1);
1434 static void *gpa2hva(MemoryRegion **p_mr, hwaddr addr, Error **errp)
1436 MemoryRegionSection mrs = memory_region_find(get_system_memory(),
1437 addr, 1);
1439 if (!mrs.mr) {
1440 error_setg(errp, "No memory is mapped at address 0x%" HWADDR_PRIx, addr);
1441 return NULL;
1444 if (!memory_region_is_ram(mrs.mr) && !memory_region_is_romd(mrs.mr)) {
1445 error_setg(errp, "Memory at address 0x%" HWADDR_PRIx "is not RAM", addr);
1446 memory_region_unref(mrs.mr);
1447 return NULL;
1450 *p_mr = mrs.mr;
1451 return qemu_map_ram_ptr(mrs.mr->ram_block, mrs.offset_within_region);
1454 static void hmp_gpa2hva(Monitor *mon, const QDict *qdict)
1456 hwaddr addr = qdict_get_int(qdict, "addr");
1457 Error *local_err = NULL;
1458 MemoryRegion *mr = NULL;
1459 void *ptr;
1461 ptr = gpa2hva(&mr, addr, &local_err);
1462 if (local_err) {
1463 error_report_err(local_err);
1464 return;
1467 monitor_printf(mon, "Host virtual address for 0x%" HWADDR_PRIx
1468 " (%s) is %p\n",
1469 addr, mr->name, ptr);
1471 memory_region_unref(mr);
1474 #ifdef CONFIG_LINUX
1475 static uint64_t vtop(void *ptr, Error **errp)
1477 uint64_t pinfo;
1478 uint64_t ret = -1;
1479 uintptr_t addr = (uintptr_t) ptr;
1480 uintptr_t pagesize = getpagesize();
1481 off_t offset = addr / pagesize * sizeof(pinfo);
1482 int fd;
1484 fd = open("/proc/self/pagemap", O_RDONLY);
1485 if (fd == -1) {
1486 error_setg_errno(errp, errno, "Cannot open /proc/self/pagemap");
1487 return -1;
1490 /* Force copy-on-write if necessary. */
1491 atomic_add((uint8_t *)ptr, 0);
1493 if (pread(fd, &pinfo, sizeof(pinfo), offset) != sizeof(pinfo)) {
1494 error_setg_errno(errp, errno, "Cannot read pagemap");
1495 goto out;
1497 if ((pinfo & (1ull << 63)) == 0) {
1498 error_setg(errp, "Page not present");
1499 goto out;
1501 ret = ((pinfo & 0x007fffffffffffffull) * pagesize) | (addr & (pagesize - 1));
1503 out:
1504 close(fd);
1505 return ret;
1508 static void hmp_gpa2hpa(Monitor *mon, const QDict *qdict)
1510 hwaddr addr = qdict_get_int(qdict, "addr");
1511 Error *local_err = NULL;
1512 MemoryRegion *mr = NULL;
1513 void *ptr;
1514 uint64_t physaddr;
1516 ptr = gpa2hva(&mr, addr, &local_err);
1517 if (local_err) {
1518 error_report_err(local_err);
1519 return;
1522 physaddr = vtop(ptr, &local_err);
1523 if (local_err) {
1524 error_report_err(local_err);
1525 } else {
1526 monitor_printf(mon, "Host physical address for 0x%" HWADDR_PRIx
1527 " (%s) is 0x%" PRIx64 "\n",
1528 addr, mr->name, (uint64_t) physaddr);
1531 memory_region_unref(mr);
1533 #endif
1535 static void do_print(Monitor *mon, const QDict *qdict)
1537 int format = qdict_get_int(qdict, "format");
1538 hwaddr val = qdict_get_int(qdict, "val");
1540 switch(format) {
1541 case 'o':
1542 monitor_printf(mon, "%#" HWADDR_PRIo, val);
1543 break;
1544 case 'x':
1545 monitor_printf(mon, "%#" HWADDR_PRIx, val);
1546 break;
1547 case 'u':
1548 monitor_printf(mon, "%" HWADDR_PRIu, val);
1549 break;
1550 default:
1551 case 'd':
1552 monitor_printf(mon, "%" HWADDR_PRId, val);
1553 break;
1554 case 'c':
1555 monitor_printc(mon, val);
1556 break;
1558 monitor_printf(mon, "\n");
1561 static void hmp_sum(Monitor *mon, const QDict *qdict)
1563 uint32_t addr;
1564 uint16_t sum;
1565 uint32_t start = qdict_get_int(qdict, "start");
1566 uint32_t size = qdict_get_int(qdict, "size");
1568 sum = 0;
1569 for(addr = start; addr < (start + size); addr++) {
1570 uint8_t val = address_space_ldub(&address_space_memory, addr,
1571 MEMTXATTRS_UNSPECIFIED, NULL);
1572 /* BSD sum algorithm ('sum' Unix command) */
1573 sum = (sum >> 1) | (sum << 15);
1574 sum += val;
1576 monitor_printf(mon, "%05d\n", sum);
1579 static int mouse_button_state;
1581 static void hmp_mouse_move(Monitor *mon, const QDict *qdict)
1583 int dx, dy, dz, button;
1584 const char *dx_str = qdict_get_str(qdict, "dx_str");
1585 const char *dy_str = qdict_get_str(qdict, "dy_str");
1586 const char *dz_str = qdict_get_try_str(qdict, "dz_str");
1588 dx = strtol(dx_str, NULL, 0);
1589 dy = strtol(dy_str, NULL, 0);
1590 qemu_input_queue_rel(NULL, INPUT_AXIS_X, dx);
1591 qemu_input_queue_rel(NULL, INPUT_AXIS_Y, dy);
1593 if (dz_str) {
1594 dz = strtol(dz_str, NULL, 0);
1595 if (dz != 0) {
1596 button = (dz > 0) ? INPUT_BUTTON_WHEEL_UP : INPUT_BUTTON_WHEEL_DOWN;
1597 qemu_input_queue_btn(NULL, button, true);
1598 qemu_input_event_sync();
1599 qemu_input_queue_btn(NULL, button, false);
1602 qemu_input_event_sync();
1605 static void hmp_mouse_button(Monitor *mon, const QDict *qdict)
1607 static uint32_t bmap[INPUT_BUTTON__MAX] = {
1608 [INPUT_BUTTON_LEFT] = MOUSE_EVENT_LBUTTON,
1609 [INPUT_BUTTON_MIDDLE] = MOUSE_EVENT_MBUTTON,
1610 [INPUT_BUTTON_RIGHT] = MOUSE_EVENT_RBUTTON,
1612 int button_state = qdict_get_int(qdict, "button_state");
1614 if (mouse_button_state == button_state) {
1615 return;
1617 qemu_input_update_buttons(NULL, bmap, mouse_button_state, button_state);
1618 qemu_input_event_sync();
1619 mouse_button_state = button_state;
1622 static void hmp_ioport_read(Monitor *mon, const QDict *qdict)
1624 int size = qdict_get_int(qdict, "size");
1625 int addr = qdict_get_int(qdict, "addr");
1626 int has_index = qdict_haskey(qdict, "index");
1627 uint32_t val;
1628 int suffix;
1630 if (has_index) {
1631 int index = qdict_get_int(qdict, "index");
1632 cpu_outb(addr & IOPORTS_MASK, index & 0xff);
1633 addr++;
1635 addr &= 0xffff;
1637 switch(size) {
1638 default:
1639 case 1:
1640 val = cpu_inb(addr);
1641 suffix = 'b';
1642 break;
1643 case 2:
1644 val = cpu_inw(addr);
1645 suffix = 'w';
1646 break;
1647 case 4:
1648 val = cpu_inl(addr);
1649 suffix = 'l';
1650 break;
1652 monitor_printf(mon, "port%c[0x%04x] = %#0*x\n",
1653 suffix, addr, size * 2, val);
1656 static void hmp_ioport_write(Monitor *mon, const QDict *qdict)
1658 int size = qdict_get_int(qdict, "size");
1659 int addr = qdict_get_int(qdict, "addr");
1660 int val = qdict_get_int(qdict, "val");
1662 addr &= IOPORTS_MASK;
1664 switch (size) {
1665 default:
1666 case 1:
1667 cpu_outb(addr, val);
1668 break;
1669 case 2:
1670 cpu_outw(addr, val);
1671 break;
1672 case 4:
1673 cpu_outl(addr, val);
1674 break;
1678 static void hmp_boot_set(Monitor *mon, const QDict *qdict)
1680 Error *local_err = NULL;
1681 const char *bootdevice = qdict_get_str(qdict, "bootdevice");
1683 qemu_boot_set(bootdevice, &local_err);
1684 if (local_err) {
1685 error_report_err(local_err);
1686 } else {
1687 monitor_printf(mon, "boot device list now set to %s\n", bootdevice);
1691 static void hmp_info_mtree(Monitor *mon, const QDict *qdict)
1693 bool flatview = qdict_get_try_bool(qdict, "flatview", false);
1695 mtree_info((fprintf_function)monitor_printf, mon, flatview);
1698 static void hmp_info_numa(Monitor *mon, const QDict *qdict)
1700 int i;
1701 CPUState *cpu;
1702 uint64_t *node_mem;
1704 node_mem = g_new0(uint64_t, nb_numa_nodes);
1705 query_numa_node_mem(node_mem);
1706 monitor_printf(mon, "%d nodes\n", nb_numa_nodes);
1707 for (i = 0; i < nb_numa_nodes; i++) {
1708 monitor_printf(mon, "node %d cpus:", i);
1709 CPU_FOREACH(cpu) {
1710 if (cpu->numa_node == i) {
1711 monitor_printf(mon, " %d", cpu->cpu_index);
1714 monitor_printf(mon, "\n");
1715 monitor_printf(mon, "node %d size: %" PRId64 " MB\n", i,
1716 node_mem[i] >> 20);
1718 g_free(node_mem);
1721 #ifdef CONFIG_PROFILER
1723 int64_t tcg_time;
1724 int64_t dev_time;
1726 static void hmp_info_profile(Monitor *mon, const QDict *qdict)
1728 monitor_printf(mon, "async time %" PRId64 " (%0.3f)\n",
1729 dev_time, dev_time / (double)NANOSECONDS_PER_SECOND);
1730 monitor_printf(mon, "qemu time %" PRId64 " (%0.3f)\n",
1731 tcg_time, tcg_time / (double)NANOSECONDS_PER_SECOND);
1732 tcg_time = 0;
1733 dev_time = 0;
1735 #else
1736 static void hmp_info_profile(Monitor *mon, const QDict *qdict)
1738 monitor_printf(mon, "Internal profiler not compiled\n");
1740 #endif
1742 /* Capture support */
1743 static QLIST_HEAD (capture_list_head, CaptureState) capture_head;
1745 static void hmp_info_capture(Monitor *mon, const QDict *qdict)
1747 int i;
1748 CaptureState *s;
1750 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
1751 monitor_printf(mon, "[%d]: ", i);
1752 s->ops.info (s->opaque);
1756 static void hmp_stopcapture(Monitor *mon, const QDict *qdict)
1758 int i;
1759 int n = qdict_get_int(qdict, "n");
1760 CaptureState *s;
1762 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
1763 if (i == n) {
1764 s->ops.destroy (s->opaque);
1765 QLIST_REMOVE (s, entries);
1766 g_free (s);
1767 return;
1772 static void hmp_wavcapture(Monitor *mon, const QDict *qdict)
1774 const char *path = qdict_get_str(qdict, "path");
1775 int has_freq = qdict_haskey(qdict, "freq");
1776 int freq = qdict_get_try_int(qdict, "freq", -1);
1777 int has_bits = qdict_haskey(qdict, "bits");
1778 int bits = qdict_get_try_int(qdict, "bits", -1);
1779 int has_channels = qdict_haskey(qdict, "nchannels");
1780 int nchannels = qdict_get_try_int(qdict, "nchannels", -1);
1781 CaptureState *s;
1783 s = g_malloc0 (sizeof (*s));
1785 freq = has_freq ? freq : 44100;
1786 bits = has_bits ? bits : 16;
1787 nchannels = has_channels ? nchannels : 2;
1789 if (wav_start_capture (s, path, freq, bits, nchannels)) {
1790 monitor_printf(mon, "Failed to add wave capture\n");
1791 g_free (s);
1792 return;
1794 QLIST_INSERT_HEAD (&capture_head, s, entries);
1797 static qemu_acl *find_acl(Monitor *mon, const char *name)
1799 qemu_acl *acl = qemu_acl_find(name);
1801 if (!acl) {
1802 monitor_printf(mon, "acl: unknown list '%s'\n", name);
1804 return acl;
1807 static void hmp_acl_show(Monitor *mon, const QDict *qdict)
1809 const char *aclname = qdict_get_str(qdict, "aclname");
1810 qemu_acl *acl = find_acl(mon, aclname);
1811 qemu_acl_entry *entry;
1812 int i = 0;
1814 if (acl) {
1815 monitor_printf(mon, "policy: %s\n",
1816 acl->defaultDeny ? "deny" : "allow");
1817 QTAILQ_FOREACH(entry, &acl->entries, next) {
1818 i++;
1819 monitor_printf(mon, "%d: %s %s\n", i,
1820 entry->deny ? "deny" : "allow", entry->match);
1825 static void hmp_acl_reset(Monitor *mon, const QDict *qdict)
1827 const char *aclname = qdict_get_str(qdict, "aclname");
1828 qemu_acl *acl = find_acl(mon, aclname);
1830 if (acl) {
1831 qemu_acl_reset(acl);
1832 monitor_printf(mon, "acl: removed all rules\n");
1836 static void hmp_acl_policy(Monitor *mon, const QDict *qdict)
1838 const char *aclname = qdict_get_str(qdict, "aclname");
1839 const char *policy = qdict_get_str(qdict, "policy");
1840 qemu_acl *acl = find_acl(mon, aclname);
1842 if (acl) {
1843 if (strcmp(policy, "allow") == 0) {
1844 acl->defaultDeny = 0;
1845 monitor_printf(mon, "acl: policy set to 'allow'\n");
1846 } else if (strcmp(policy, "deny") == 0) {
1847 acl->defaultDeny = 1;
1848 monitor_printf(mon, "acl: policy set to 'deny'\n");
1849 } else {
1850 monitor_printf(mon, "acl: unknown policy '%s', "
1851 "expected 'deny' or 'allow'\n", policy);
1856 static void hmp_acl_add(Monitor *mon, const QDict *qdict)
1858 const char *aclname = qdict_get_str(qdict, "aclname");
1859 const char *match = qdict_get_str(qdict, "match");
1860 const char *policy = qdict_get_str(qdict, "policy");
1861 int has_index = qdict_haskey(qdict, "index");
1862 int index = qdict_get_try_int(qdict, "index", -1);
1863 qemu_acl *acl = find_acl(mon, aclname);
1864 int deny, ret;
1866 if (acl) {
1867 if (strcmp(policy, "allow") == 0) {
1868 deny = 0;
1869 } else if (strcmp(policy, "deny") == 0) {
1870 deny = 1;
1871 } else {
1872 monitor_printf(mon, "acl: unknown policy '%s', "
1873 "expected 'deny' or 'allow'\n", policy);
1874 return;
1876 if (has_index)
1877 ret = qemu_acl_insert(acl, deny, match, index);
1878 else
1879 ret = qemu_acl_append(acl, deny, match);
1880 if (ret < 0)
1881 monitor_printf(mon, "acl: unable to add acl entry\n");
1882 else
1883 monitor_printf(mon, "acl: added rule at position %d\n", ret);
1887 static void hmp_acl_remove(Monitor *mon, const QDict *qdict)
1889 const char *aclname = qdict_get_str(qdict, "aclname");
1890 const char *match = qdict_get_str(qdict, "match");
1891 qemu_acl *acl = find_acl(mon, aclname);
1892 int ret;
1894 if (acl) {
1895 ret = qemu_acl_remove(acl, match);
1896 if (ret < 0)
1897 monitor_printf(mon, "acl: no matching acl entry\n");
1898 else
1899 monitor_printf(mon, "acl: removed rule at position %d\n", ret);
1903 void qmp_getfd(const char *fdname, Error **errp)
1905 mon_fd_t *monfd;
1906 int fd;
1908 fd = qemu_chr_fe_get_msgfd(&cur_mon->chr);
1909 if (fd == -1) {
1910 error_setg(errp, QERR_FD_NOT_SUPPLIED);
1911 return;
1914 if (qemu_isdigit(fdname[0])) {
1915 close(fd);
1916 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "fdname",
1917 "a name not starting with a digit");
1918 return;
1921 QLIST_FOREACH(monfd, &cur_mon->fds, next) {
1922 if (strcmp(monfd->name, fdname) != 0) {
1923 continue;
1926 close(monfd->fd);
1927 monfd->fd = fd;
1928 return;
1931 monfd = g_malloc0(sizeof(mon_fd_t));
1932 monfd->name = g_strdup(fdname);
1933 monfd->fd = fd;
1935 QLIST_INSERT_HEAD(&cur_mon->fds, monfd, next);
1938 void qmp_closefd(const char *fdname, Error **errp)
1940 mon_fd_t *monfd;
1942 QLIST_FOREACH(monfd, &cur_mon->fds, next) {
1943 if (strcmp(monfd->name, fdname) != 0) {
1944 continue;
1947 QLIST_REMOVE(monfd, next);
1948 close(monfd->fd);
1949 g_free(monfd->name);
1950 g_free(monfd);
1951 return;
1954 error_setg(errp, QERR_FD_NOT_FOUND, fdname);
1957 static void hmp_loadvm(Monitor *mon, const QDict *qdict)
1959 int saved_vm_running = runstate_is_running();
1960 const char *name = qdict_get_str(qdict, "name");
1962 vm_stop(RUN_STATE_RESTORE_VM);
1964 if (load_vmstate(name) == 0 && saved_vm_running) {
1965 vm_start();
1969 int monitor_get_fd(Monitor *mon, const char *fdname, Error **errp)
1971 mon_fd_t *monfd;
1973 QLIST_FOREACH(monfd, &mon->fds, next) {
1974 int fd;
1976 if (strcmp(monfd->name, fdname) != 0) {
1977 continue;
1980 fd = monfd->fd;
1982 /* caller takes ownership of fd */
1983 QLIST_REMOVE(monfd, next);
1984 g_free(monfd->name);
1985 g_free(monfd);
1987 return fd;
1990 error_setg(errp, "File descriptor named '%s' has not been found", fdname);
1991 return -1;
1994 static void monitor_fdset_cleanup(MonFdset *mon_fdset)
1996 MonFdsetFd *mon_fdset_fd;
1997 MonFdsetFd *mon_fdset_fd_next;
1999 QLIST_FOREACH_SAFE(mon_fdset_fd, &mon_fdset->fds, next, mon_fdset_fd_next) {
2000 if ((mon_fdset_fd->removed ||
2001 (QLIST_EMPTY(&mon_fdset->dup_fds) && mon_refcount == 0)) &&
2002 runstate_is_running()) {
2003 close(mon_fdset_fd->fd);
2004 g_free(mon_fdset_fd->opaque);
2005 QLIST_REMOVE(mon_fdset_fd, next);
2006 g_free(mon_fdset_fd);
2010 if (QLIST_EMPTY(&mon_fdset->fds) && QLIST_EMPTY(&mon_fdset->dup_fds)) {
2011 QLIST_REMOVE(mon_fdset, next);
2012 g_free(mon_fdset);
2016 static void monitor_fdsets_cleanup(void)
2018 MonFdset *mon_fdset;
2019 MonFdset *mon_fdset_next;
2021 QLIST_FOREACH_SAFE(mon_fdset, &mon_fdsets, next, mon_fdset_next) {
2022 monitor_fdset_cleanup(mon_fdset);
2026 AddfdInfo *qmp_add_fd(bool has_fdset_id, int64_t fdset_id, bool has_opaque,
2027 const char *opaque, Error **errp)
2029 int fd;
2030 Monitor *mon = cur_mon;
2031 AddfdInfo *fdinfo;
2033 fd = qemu_chr_fe_get_msgfd(&mon->chr);
2034 if (fd == -1) {
2035 error_setg(errp, QERR_FD_NOT_SUPPLIED);
2036 goto error;
2039 fdinfo = monitor_fdset_add_fd(fd, has_fdset_id, fdset_id,
2040 has_opaque, opaque, errp);
2041 if (fdinfo) {
2042 return fdinfo;
2045 error:
2046 if (fd != -1) {
2047 close(fd);
2049 return NULL;
2052 void qmp_remove_fd(int64_t fdset_id, bool has_fd, int64_t fd, Error **errp)
2054 MonFdset *mon_fdset;
2055 MonFdsetFd *mon_fdset_fd;
2056 char fd_str[60];
2058 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2059 if (mon_fdset->id != fdset_id) {
2060 continue;
2062 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2063 if (has_fd) {
2064 if (mon_fdset_fd->fd != fd) {
2065 continue;
2067 mon_fdset_fd->removed = true;
2068 break;
2069 } else {
2070 mon_fdset_fd->removed = true;
2073 if (has_fd && !mon_fdset_fd) {
2074 goto error;
2076 monitor_fdset_cleanup(mon_fdset);
2077 return;
2080 error:
2081 if (has_fd) {
2082 snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64 ", fd:%" PRId64,
2083 fdset_id, fd);
2084 } else {
2085 snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64, fdset_id);
2087 error_setg(errp, QERR_FD_NOT_FOUND, fd_str);
2090 FdsetInfoList *qmp_query_fdsets(Error **errp)
2092 MonFdset *mon_fdset;
2093 MonFdsetFd *mon_fdset_fd;
2094 FdsetInfoList *fdset_list = NULL;
2096 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2097 FdsetInfoList *fdset_info = g_malloc0(sizeof(*fdset_info));
2098 FdsetFdInfoList *fdsetfd_list = NULL;
2100 fdset_info->value = g_malloc0(sizeof(*fdset_info->value));
2101 fdset_info->value->fdset_id = mon_fdset->id;
2103 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2104 FdsetFdInfoList *fdsetfd_info;
2106 fdsetfd_info = g_malloc0(sizeof(*fdsetfd_info));
2107 fdsetfd_info->value = g_malloc0(sizeof(*fdsetfd_info->value));
2108 fdsetfd_info->value->fd = mon_fdset_fd->fd;
2109 if (mon_fdset_fd->opaque) {
2110 fdsetfd_info->value->has_opaque = true;
2111 fdsetfd_info->value->opaque = g_strdup(mon_fdset_fd->opaque);
2112 } else {
2113 fdsetfd_info->value->has_opaque = false;
2116 fdsetfd_info->next = fdsetfd_list;
2117 fdsetfd_list = fdsetfd_info;
2120 fdset_info->value->fds = fdsetfd_list;
2122 fdset_info->next = fdset_list;
2123 fdset_list = fdset_info;
2126 return fdset_list;
2129 AddfdInfo *monitor_fdset_add_fd(int fd, bool has_fdset_id, int64_t fdset_id,
2130 bool has_opaque, const char *opaque,
2131 Error **errp)
2133 MonFdset *mon_fdset = NULL;
2134 MonFdsetFd *mon_fdset_fd;
2135 AddfdInfo *fdinfo;
2137 if (has_fdset_id) {
2138 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2139 /* Break if match found or match impossible due to ordering by ID */
2140 if (fdset_id <= mon_fdset->id) {
2141 if (fdset_id < mon_fdset->id) {
2142 mon_fdset = NULL;
2144 break;
2149 if (mon_fdset == NULL) {
2150 int64_t fdset_id_prev = -1;
2151 MonFdset *mon_fdset_cur = QLIST_FIRST(&mon_fdsets);
2153 if (has_fdset_id) {
2154 if (fdset_id < 0) {
2155 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "fdset-id",
2156 "a non-negative value");
2157 return NULL;
2159 /* Use specified fdset ID */
2160 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2161 mon_fdset_cur = mon_fdset;
2162 if (fdset_id < mon_fdset_cur->id) {
2163 break;
2166 } else {
2167 /* Use first available fdset ID */
2168 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2169 mon_fdset_cur = mon_fdset;
2170 if (fdset_id_prev == mon_fdset_cur->id - 1) {
2171 fdset_id_prev = mon_fdset_cur->id;
2172 continue;
2174 break;
2178 mon_fdset = g_malloc0(sizeof(*mon_fdset));
2179 if (has_fdset_id) {
2180 mon_fdset->id = fdset_id;
2181 } else {
2182 mon_fdset->id = fdset_id_prev + 1;
2185 /* The fdset list is ordered by fdset ID */
2186 if (!mon_fdset_cur) {
2187 QLIST_INSERT_HEAD(&mon_fdsets, mon_fdset, next);
2188 } else if (mon_fdset->id < mon_fdset_cur->id) {
2189 QLIST_INSERT_BEFORE(mon_fdset_cur, mon_fdset, next);
2190 } else {
2191 QLIST_INSERT_AFTER(mon_fdset_cur, mon_fdset, next);
2195 mon_fdset_fd = g_malloc0(sizeof(*mon_fdset_fd));
2196 mon_fdset_fd->fd = fd;
2197 mon_fdset_fd->removed = false;
2198 if (has_opaque) {
2199 mon_fdset_fd->opaque = g_strdup(opaque);
2201 QLIST_INSERT_HEAD(&mon_fdset->fds, mon_fdset_fd, next);
2203 fdinfo = g_malloc0(sizeof(*fdinfo));
2204 fdinfo->fdset_id = mon_fdset->id;
2205 fdinfo->fd = mon_fdset_fd->fd;
2207 return fdinfo;
2210 int monitor_fdset_get_fd(int64_t fdset_id, int flags)
2212 #ifndef _WIN32
2213 MonFdset *mon_fdset;
2214 MonFdsetFd *mon_fdset_fd;
2215 int mon_fd_flags;
2217 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2218 if (mon_fdset->id != fdset_id) {
2219 continue;
2221 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2222 mon_fd_flags = fcntl(mon_fdset_fd->fd, F_GETFL);
2223 if (mon_fd_flags == -1) {
2224 return -1;
2227 if ((flags & O_ACCMODE) == (mon_fd_flags & O_ACCMODE)) {
2228 return mon_fdset_fd->fd;
2231 errno = EACCES;
2232 return -1;
2234 #endif
2236 errno = ENOENT;
2237 return -1;
2240 int monitor_fdset_dup_fd_add(int64_t fdset_id, int dup_fd)
2242 MonFdset *mon_fdset;
2243 MonFdsetFd *mon_fdset_fd_dup;
2245 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2246 if (mon_fdset->id != fdset_id) {
2247 continue;
2249 QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
2250 if (mon_fdset_fd_dup->fd == dup_fd) {
2251 return -1;
2254 mon_fdset_fd_dup = g_malloc0(sizeof(*mon_fdset_fd_dup));
2255 mon_fdset_fd_dup->fd = dup_fd;
2256 QLIST_INSERT_HEAD(&mon_fdset->dup_fds, mon_fdset_fd_dup, next);
2257 return 0;
2259 return -1;
2262 static int monitor_fdset_dup_fd_find_remove(int dup_fd, bool remove)
2264 MonFdset *mon_fdset;
2265 MonFdsetFd *mon_fdset_fd_dup;
2267 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2268 QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
2269 if (mon_fdset_fd_dup->fd == dup_fd) {
2270 if (remove) {
2271 QLIST_REMOVE(mon_fdset_fd_dup, next);
2272 if (QLIST_EMPTY(&mon_fdset->dup_fds)) {
2273 monitor_fdset_cleanup(mon_fdset);
2275 return -1;
2276 } else {
2277 return mon_fdset->id;
2282 return -1;
2285 int monitor_fdset_dup_fd_find(int dup_fd)
2287 return monitor_fdset_dup_fd_find_remove(dup_fd, false);
2290 void monitor_fdset_dup_fd_remove(int dup_fd)
2292 monitor_fdset_dup_fd_find_remove(dup_fd, true);
2295 int monitor_fd_param(Monitor *mon, const char *fdname, Error **errp)
2297 int fd;
2298 Error *local_err = NULL;
2300 if (!qemu_isdigit(fdname[0]) && mon) {
2301 fd = monitor_get_fd(mon, fdname, &local_err);
2302 } else {
2303 fd = qemu_parse_fd(fdname);
2304 if (fd == -1) {
2305 error_setg(&local_err, "Invalid file descriptor number '%s'",
2306 fdname);
2309 if (local_err) {
2310 error_propagate(errp, local_err);
2311 assert(fd == -1);
2312 } else {
2313 assert(fd != -1);
2316 return fd;
2319 /* Please update hmp-commands.hx when adding or changing commands */
2320 static mon_cmd_t info_cmds[] = {
2321 #include "hmp-commands-info.h"
2322 { NULL, NULL, },
2325 /* mon_cmds and info_cmds would be sorted at runtime */
2326 static mon_cmd_t mon_cmds[] = {
2327 #include "hmp-commands.h"
2328 { NULL, NULL, },
2331 /*******************************************************************/
2333 static const char *pch;
2334 static sigjmp_buf expr_env;
2337 static void GCC_FMT_ATTR(2, 3) QEMU_NORETURN
2338 expr_error(Monitor *mon, const char *fmt, ...)
2340 va_list ap;
2341 va_start(ap, fmt);
2342 monitor_vprintf(mon, fmt, ap);
2343 monitor_printf(mon, "\n");
2344 va_end(ap);
2345 siglongjmp(expr_env, 1);
2348 /* return 0 if OK, -1 if not found */
2349 static int get_monitor_def(target_long *pval, const char *name)
2351 const MonitorDef *md = target_monitor_defs();
2352 CPUState *cs = mon_get_cpu();
2353 void *ptr;
2354 uint64_t tmp = 0;
2355 int ret;
2357 if (cs == NULL || md == NULL) {
2358 return -1;
2361 for(; md->name != NULL; md++) {
2362 if (compare_cmd(name, md->name)) {
2363 if (md->get_value) {
2364 *pval = md->get_value(md, md->offset);
2365 } else {
2366 CPUArchState *env = mon_get_cpu_env();
2367 ptr = (uint8_t *)env + md->offset;
2368 switch(md->type) {
2369 case MD_I32:
2370 *pval = *(int32_t *)ptr;
2371 break;
2372 case MD_TLONG:
2373 *pval = *(target_long *)ptr;
2374 break;
2375 default:
2376 *pval = 0;
2377 break;
2380 return 0;
2384 ret = target_get_monitor_def(cs, name, &tmp);
2385 if (!ret) {
2386 *pval = (target_long) tmp;
2389 return ret;
2392 static void next(void)
2394 if (*pch != '\0') {
2395 pch++;
2396 while (qemu_isspace(*pch))
2397 pch++;
2401 static int64_t expr_sum(Monitor *mon);
2403 static int64_t expr_unary(Monitor *mon)
2405 int64_t n;
2406 char *p;
2407 int ret;
2409 switch(*pch) {
2410 case '+':
2411 next();
2412 n = expr_unary(mon);
2413 break;
2414 case '-':
2415 next();
2416 n = -expr_unary(mon);
2417 break;
2418 case '~':
2419 next();
2420 n = ~expr_unary(mon);
2421 break;
2422 case '(':
2423 next();
2424 n = expr_sum(mon);
2425 if (*pch != ')') {
2426 expr_error(mon, "')' expected");
2428 next();
2429 break;
2430 case '\'':
2431 pch++;
2432 if (*pch == '\0')
2433 expr_error(mon, "character constant expected");
2434 n = *pch;
2435 pch++;
2436 if (*pch != '\'')
2437 expr_error(mon, "missing terminating \' character");
2438 next();
2439 break;
2440 case '$':
2442 char buf[128], *q;
2443 target_long reg=0;
2445 pch++;
2446 q = buf;
2447 while ((*pch >= 'a' && *pch <= 'z') ||
2448 (*pch >= 'A' && *pch <= 'Z') ||
2449 (*pch >= '0' && *pch <= '9') ||
2450 *pch == '_' || *pch == '.') {
2451 if ((q - buf) < sizeof(buf) - 1)
2452 *q++ = *pch;
2453 pch++;
2455 while (qemu_isspace(*pch))
2456 pch++;
2457 *q = 0;
2458 ret = get_monitor_def(&reg, buf);
2459 if (ret < 0)
2460 expr_error(mon, "unknown register");
2461 n = reg;
2463 break;
2464 case '\0':
2465 expr_error(mon, "unexpected end of expression");
2466 n = 0;
2467 break;
2468 default:
2469 errno = 0;
2470 n = strtoull(pch, &p, 0);
2471 if (errno == ERANGE) {
2472 expr_error(mon, "number too large");
2474 if (pch == p) {
2475 expr_error(mon, "invalid char '%c' in expression", *p);
2477 pch = p;
2478 while (qemu_isspace(*pch))
2479 pch++;
2480 break;
2482 return n;
2486 static int64_t expr_prod(Monitor *mon)
2488 int64_t val, val2;
2489 int op;
2491 val = expr_unary(mon);
2492 for(;;) {
2493 op = *pch;
2494 if (op != '*' && op != '/' && op != '%')
2495 break;
2496 next();
2497 val2 = expr_unary(mon);
2498 switch(op) {
2499 default:
2500 case '*':
2501 val *= val2;
2502 break;
2503 case '/':
2504 case '%':
2505 if (val2 == 0)
2506 expr_error(mon, "division by zero");
2507 if (op == '/')
2508 val /= val2;
2509 else
2510 val %= val2;
2511 break;
2514 return val;
2517 static int64_t expr_logic(Monitor *mon)
2519 int64_t val, val2;
2520 int op;
2522 val = expr_prod(mon);
2523 for(;;) {
2524 op = *pch;
2525 if (op != '&' && op != '|' && op != '^')
2526 break;
2527 next();
2528 val2 = expr_prod(mon);
2529 switch(op) {
2530 default:
2531 case '&':
2532 val &= val2;
2533 break;
2534 case '|':
2535 val |= val2;
2536 break;
2537 case '^':
2538 val ^= val2;
2539 break;
2542 return val;
2545 static int64_t expr_sum(Monitor *mon)
2547 int64_t val, val2;
2548 int op;
2550 val = expr_logic(mon);
2551 for(;;) {
2552 op = *pch;
2553 if (op != '+' && op != '-')
2554 break;
2555 next();
2556 val2 = expr_logic(mon);
2557 if (op == '+')
2558 val += val2;
2559 else
2560 val -= val2;
2562 return val;
2565 static int get_expr(Monitor *mon, int64_t *pval, const char **pp)
2567 pch = *pp;
2568 if (sigsetjmp(expr_env, 0)) {
2569 *pp = pch;
2570 return -1;
2572 while (qemu_isspace(*pch))
2573 pch++;
2574 *pval = expr_sum(mon);
2575 *pp = pch;
2576 return 0;
2579 static int get_double(Monitor *mon, double *pval, const char **pp)
2581 const char *p = *pp;
2582 char *tailp;
2583 double d;
2585 d = strtod(p, &tailp);
2586 if (tailp == p) {
2587 monitor_printf(mon, "Number expected\n");
2588 return -1;
2590 if (d != d || d - d != 0) {
2591 /* NaN or infinity */
2592 monitor_printf(mon, "Bad number\n");
2593 return -1;
2595 *pval = d;
2596 *pp = tailp;
2597 return 0;
2601 * Store the command-name in cmdname, and return a pointer to
2602 * the remaining of the command string.
2604 static const char *get_command_name(const char *cmdline,
2605 char *cmdname, size_t nlen)
2607 size_t len;
2608 const char *p, *pstart;
2610 p = cmdline;
2611 while (qemu_isspace(*p))
2612 p++;
2613 if (*p == '\0')
2614 return NULL;
2615 pstart = p;
2616 while (*p != '\0' && *p != '/' && !qemu_isspace(*p))
2617 p++;
2618 len = p - pstart;
2619 if (len > nlen - 1)
2620 len = nlen - 1;
2621 memcpy(cmdname, pstart, len);
2622 cmdname[len] = '\0';
2623 return p;
2627 * Read key of 'type' into 'key' and return the current
2628 * 'type' pointer.
2630 static char *key_get_info(const char *type, char **key)
2632 size_t len;
2633 char *p, *str;
2635 if (*type == ',')
2636 type++;
2638 p = strchr(type, ':');
2639 if (!p) {
2640 *key = NULL;
2641 return NULL;
2643 len = p - type;
2645 str = g_malloc(len + 1);
2646 memcpy(str, type, len);
2647 str[len] = '\0';
2649 *key = str;
2650 return ++p;
2653 static int default_fmt_format = 'x';
2654 static int default_fmt_size = 4;
2656 static int is_valid_option(const char *c, const char *typestr)
2658 char option[3];
2660 option[0] = '-';
2661 option[1] = *c;
2662 option[2] = '\0';
2664 typestr = strstr(typestr, option);
2665 return (typestr != NULL);
2668 static const mon_cmd_t *search_dispatch_table(const mon_cmd_t *disp_table,
2669 const char *cmdname)
2671 const mon_cmd_t *cmd;
2673 for (cmd = disp_table; cmd->name != NULL; cmd++) {
2674 if (compare_cmd(cmdname, cmd->name)) {
2675 return cmd;
2679 return NULL;
2683 * Parse command name from @cmdp according to command table @table.
2684 * If blank, return NULL.
2685 * Else, if no valid command can be found, report to @mon, and return
2686 * NULL.
2687 * Else, change @cmdp to point right behind the name, and return its
2688 * command table entry.
2689 * Do not assume the return value points into @table! It doesn't when
2690 * the command is found in a sub-command table.
2692 static const mon_cmd_t *monitor_parse_command(Monitor *mon,
2693 const char **cmdp,
2694 mon_cmd_t *table)
2696 const char *p;
2697 const mon_cmd_t *cmd;
2698 char cmdname[256];
2700 /* extract the command name */
2701 p = get_command_name(*cmdp, cmdname, sizeof(cmdname));
2702 if (!p)
2703 return NULL;
2705 cmd = search_dispatch_table(table, cmdname);
2706 if (!cmd) {
2707 monitor_printf(mon, "unknown command: '%.*s'\n",
2708 (int)(p - *cmdp), *cmdp);
2709 return NULL;
2712 /* filter out following useless space */
2713 while (qemu_isspace(*p)) {
2714 p++;
2717 *cmdp = p;
2718 /* search sub command */
2719 if (cmd->sub_table != NULL && *p != '\0') {
2720 return monitor_parse_command(mon, cmdp, cmd->sub_table);
2723 return cmd;
2727 * Parse arguments for @cmd.
2728 * If it can't be parsed, report to @mon, and return NULL.
2729 * Else, insert command arguments into a QDict, and return it.
2730 * Note: On success, caller has to free the QDict structure.
2733 static QDict *monitor_parse_arguments(Monitor *mon,
2734 const char **endp,
2735 const mon_cmd_t *cmd)
2737 const char *typestr;
2738 char *key;
2739 int c;
2740 const char *p = *endp;
2741 char buf[1024];
2742 QDict *qdict = qdict_new();
2744 /* parse the parameters */
2745 typestr = cmd->args_type;
2746 for(;;) {
2747 typestr = key_get_info(typestr, &key);
2748 if (!typestr)
2749 break;
2750 c = *typestr;
2751 typestr++;
2752 switch(c) {
2753 case 'F':
2754 case 'B':
2755 case 's':
2757 int ret;
2759 while (qemu_isspace(*p))
2760 p++;
2761 if (*typestr == '?') {
2762 typestr++;
2763 if (*p == '\0') {
2764 /* no optional string: NULL argument */
2765 break;
2768 ret = get_str(buf, sizeof(buf), &p);
2769 if (ret < 0) {
2770 switch(c) {
2771 case 'F':
2772 monitor_printf(mon, "%s: filename expected\n",
2773 cmd->name);
2774 break;
2775 case 'B':
2776 monitor_printf(mon, "%s: block device name expected\n",
2777 cmd->name);
2778 break;
2779 default:
2780 monitor_printf(mon, "%s: string expected\n", cmd->name);
2781 break;
2783 goto fail;
2785 qdict_put(qdict, key, qstring_from_str(buf));
2787 break;
2788 case 'O':
2790 QemuOptsList *opts_list;
2791 QemuOpts *opts;
2793 opts_list = qemu_find_opts(key);
2794 if (!opts_list || opts_list->desc->name) {
2795 goto bad_type;
2797 while (qemu_isspace(*p)) {
2798 p++;
2800 if (!*p)
2801 break;
2802 if (get_str(buf, sizeof(buf), &p) < 0) {
2803 goto fail;
2805 opts = qemu_opts_parse_noisily(opts_list, buf, true);
2806 if (!opts) {
2807 goto fail;
2809 qemu_opts_to_qdict(opts, qdict);
2810 qemu_opts_del(opts);
2812 break;
2813 case '/':
2815 int count, format, size;
2817 while (qemu_isspace(*p))
2818 p++;
2819 if (*p == '/') {
2820 /* format found */
2821 p++;
2822 count = 1;
2823 if (qemu_isdigit(*p)) {
2824 count = 0;
2825 while (qemu_isdigit(*p)) {
2826 count = count * 10 + (*p - '0');
2827 p++;
2830 size = -1;
2831 format = -1;
2832 for(;;) {
2833 switch(*p) {
2834 case 'o':
2835 case 'd':
2836 case 'u':
2837 case 'x':
2838 case 'i':
2839 case 'c':
2840 format = *p++;
2841 break;
2842 case 'b':
2843 size = 1;
2844 p++;
2845 break;
2846 case 'h':
2847 size = 2;
2848 p++;
2849 break;
2850 case 'w':
2851 size = 4;
2852 p++;
2853 break;
2854 case 'g':
2855 case 'L':
2856 size = 8;
2857 p++;
2858 break;
2859 default:
2860 goto next;
2863 next:
2864 if (*p != '\0' && !qemu_isspace(*p)) {
2865 monitor_printf(mon, "invalid char in format: '%c'\n",
2866 *p);
2867 goto fail;
2869 if (format < 0)
2870 format = default_fmt_format;
2871 if (format != 'i') {
2872 /* for 'i', not specifying a size gives -1 as size */
2873 if (size < 0)
2874 size = default_fmt_size;
2875 default_fmt_size = size;
2877 default_fmt_format = format;
2878 } else {
2879 count = 1;
2880 format = default_fmt_format;
2881 if (format != 'i') {
2882 size = default_fmt_size;
2883 } else {
2884 size = -1;
2887 qdict_put(qdict, "count", qint_from_int(count));
2888 qdict_put(qdict, "format", qint_from_int(format));
2889 qdict_put(qdict, "size", qint_from_int(size));
2891 break;
2892 case 'i':
2893 case 'l':
2894 case 'M':
2896 int64_t val;
2898 while (qemu_isspace(*p))
2899 p++;
2900 if (*typestr == '?' || *typestr == '.') {
2901 if (*typestr == '?') {
2902 if (*p == '\0') {
2903 typestr++;
2904 break;
2906 } else {
2907 if (*p == '.') {
2908 p++;
2909 while (qemu_isspace(*p))
2910 p++;
2911 } else {
2912 typestr++;
2913 break;
2916 typestr++;
2918 if (get_expr(mon, &val, &p))
2919 goto fail;
2920 /* Check if 'i' is greater than 32-bit */
2921 if ((c == 'i') && ((val >> 32) & 0xffffffff)) {
2922 monitor_printf(mon, "\'%s\' has failed: ", cmd->name);
2923 monitor_printf(mon, "integer is for 32-bit values\n");
2924 goto fail;
2925 } else if (c == 'M') {
2926 if (val < 0) {
2927 monitor_printf(mon, "enter a positive value\n");
2928 goto fail;
2930 val <<= 20;
2932 qdict_put(qdict, key, qint_from_int(val));
2934 break;
2935 case 'o':
2937 int ret;
2938 uint64_t val;
2939 char *end;
2941 while (qemu_isspace(*p)) {
2942 p++;
2944 if (*typestr == '?') {
2945 typestr++;
2946 if (*p == '\0') {
2947 break;
2950 ret = qemu_strtosz_MiB(p, &end, &val);
2951 if (ret < 0 || val > INT64_MAX) {
2952 monitor_printf(mon, "invalid size\n");
2953 goto fail;
2955 qdict_put(qdict, key, qint_from_int(val));
2956 p = end;
2958 break;
2959 case 'T':
2961 double val;
2963 while (qemu_isspace(*p))
2964 p++;
2965 if (*typestr == '?') {
2966 typestr++;
2967 if (*p == '\0') {
2968 break;
2971 if (get_double(mon, &val, &p) < 0) {
2972 goto fail;
2974 if (p[0] && p[1] == 's') {
2975 switch (*p) {
2976 case 'm':
2977 val /= 1e3; p += 2; break;
2978 case 'u':
2979 val /= 1e6; p += 2; break;
2980 case 'n':
2981 val /= 1e9; p += 2; break;
2984 if (*p && !qemu_isspace(*p)) {
2985 monitor_printf(mon, "Unknown unit suffix\n");
2986 goto fail;
2988 qdict_put(qdict, key, qfloat_from_double(val));
2990 break;
2991 case 'b':
2993 const char *beg;
2994 bool val;
2996 while (qemu_isspace(*p)) {
2997 p++;
2999 beg = p;
3000 while (qemu_isgraph(*p)) {
3001 p++;
3003 if (p - beg == 2 && !memcmp(beg, "on", p - beg)) {
3004 val = true;
3005 } else if (p - beg == 3 && !memcmp(beg, "off", p - beg)) {
3006 val = false;
3007 } else {
3008 monitor_printf(mon, "Expected 'on' or 'off'\n");
3009 goto fail;
3011 qdict_put(qdict, key, qbool_from_bool(val));
3013 break;
3014 case '-':
3016 const char *tmp = p;
3017 int skip_key = 0;
3018 /* option */
3020 c = *typestr++;
3021 if (c == '\0')
3022 goto bad_type;
3023 while (qemu_isspace(*p))
3024 p++;
3025 if (*p == '-') {
3026 p++;
3027 if(c != *p) {
3028 if(!is_valid_option(p, typestr)) {
3030 monitor_printf(mon, "%s: unsupported option -%c\n",
3031 cmd->name, *p);
3032 goto fail;
3033 } else {
3034 skip_key = 1;
3037 if(skip_key) {
3038 p = tmp;
3039 } else {
3040 /* has option */
3041 p++;
3042 qdict_put(qdict, key, qbool_from_bool(true));
3046 break;
3047 case 'S':
3049 /* package all remaining string */
3050 int len;
3052 while (qemu_isspace(*p)) {
3053 p++;
3055 if (*typestr == '?') {
3056 typestr++;
3057 if (*p == '\0') {
3058 /* no remaining string: NULL argument */
3059 break;
3062 len = strlen(p);
3063 if (len <= 0) {
3064 monitor_printf(mon, "%s: string expected\n",
3065 cmd->name);
3066 goto fail;
3068 qdict_put(qdict, key, qstring_from_str(p));
3069 p += len;
3071 break;
3072 default:
3073 bad_type:
3074 monitor_printf(mon, "%s: unknown type '%c'\n", cmd->name, c);
3075 goto fail;
3077 g_free(key);
3078 key = NULL;
3080 /* check that all arguments were parsed */
3081 while (qemu_isspace(*p))
3082 p++;
3083 if (*p != '\0') {
3084 monitor_printf(mon, "%s: extraneous characters at the end of line\n",
3085 cmd->name);
3086 goto fail;
3089 return qdict;
3091 fail:
3092 QDECREF(qdict);
3093 g_free(key);
3094 return NULL;
3097 static void handle_hmp_command(Monitor *mon, const char *cmdline)
3099 QDict *qdict;
3100 const mon_cmd_t *cmd;
3102 cmd = monitor_parse_command(mon, &cmdline, mon->cmd_table);
3103 if (!cmd) {
3104 return;
3107 qdict = monitor_parse_arguments(mon, &cmdline, cmd);
3108 if (!qdict) {
3109 monitor_printf(mon, "Try \"help %s\" for more information\n",
3110 cmd->name);
3111 return;
3114 cmd->cmd(mon, qdict);
3115 QDECREF(qdict);
3118 static void cmd_completion(Monitor *mon, const char *name, const char *list)
3120 const char *p, *pstart;
3121 char cmd[128];
3122 int len;
3124 p = list;
3125 for(;;) {
3126 pstart = p;
3127 p = strchr(p, '|');
3128 if (!p)
3129 p = pstart + strlen(pstart);
3130 len = p - pstart;
3131 if (len > sizeof(cmd) - 2)
3132 len = sizeof(cmd) - 2;
3133 memcpy(cmd, pstart, len);
3134 cmd[len] = '\0';
3135 if (name[0] == '\0' || !strncmp(name, cmd, strlen(name))) {
3136 readline_add_completion(mon->rs, cmd);
3138 if (*p == '\0')
3139 break;
3140 p++;
3144 static void file_completion(Monitor *mon, const char *input)
3146 DIR *ffs;
3147 struct dirent *d;
3148 char path[1024];
3149 char file[1024], file_prefix[1024];
3150 int input_path_len;
3151 const char *p;
3153 p = strrchr(input, '/');
3154 if (!p) {
3155 input_path_len = 0;
3156 pstrcpy(file_prefix, sizeof(file_prefix), input);
3157 pstrcpy(path, sizeof(path), ".");
3158 } else {
3159 input_path_len = p - input + 1;
3160 memcpy(path, input, input_path_len);
3161 if (input_path_len > sizeof(path) - 1)
3162 input_path_len = sizeof(path) - 1;
3163 path[input_path_len] = '\0';
3164 pstrcpy(file_prefix, sizeof(file_prefix), p + 1);
3167 ffs = opendir(path);
3168 if (!ffs)
3169 return;
3170 for(;;) {
3171 struct stat sb;
3172 d = readdir(ffs);
3173 if (!d)
3174 break;
3176 if (strcmp(d->d_name, ".") == 0 || strcmp(d->d_name, "..") == 0) {
3177 continue;
3180 if (strstart(d->d_name, file_prefix, NULL)) {
3181 memcpy(file, input, input_path_len);
3182 if (input_path_len < sizeof(file))
3183 pstrcpy(file + input_path_len, sizeof(file) - input_path_len,
3184 d->d_name);
3185 /* stat the file to find out if it's a directory.
3186 * In that case add a slash to speed up typing long paths
3188 if (stat(file, &sb) == 0 && S_ISDIR(sb.st_mode)) {
3189 pstrcat(file, sizeof(file), "/");
3191 readline_add_completion(mon->rs, file);
3194 closedir(ffs);
3197 static const char *next_arg_type(const char *typestr)
3199 const char *p = strchr(typestr, ':');
3200 return (p != NULL ? ++p : typestr);
3203 static void add_completion_option(ReadLineState *rs, const char *str,
3204 const char *option)
3206 if (!str || !option) {
3207 return;
3209 if (!strncmp(option, str, strlen(str))) {
3210 readline_add_completion(rs, option);
3214 void chardev_add_completion(ReadLineState *rs, int nb_args, const char *str)
3216 size_t len;
3217 ChardevBackendInfoList *list, *start;
3219 if (nb_args != 2) {
3220 return;
3222 len = strlen(str);
3223 readline_set_completion_index(rs, len);
3225 start = list = qmp_query_chardev_backends(NULL);
3226 while (list) {
3227 const char *chr_name = list->value->name;
3229 if (!strncmp(chr_name, str, len)) {
3230 readline_add_completion(rs, chr_name);
3232 list = list->next;
3234 qapi_free_ChardevBackendInfoList(start);
3237 void netdev_add_completion(ReadLineState *rs, int nb_args, const char *str)
3239 size_t len;
3240 int i;
3242 if (nb_args != 2) {
3243 return;
3245 len = strlen(str);
3246 readline_set_completion_index(rs, len);
3247 for (i = 0; NetClientDriver_lookup[i]; i++) {
3248 add_completion_option(rs, str, NetClientDriver_lookup[i]);
3252 void device_add_completion(ReadLineState *rs, int nb_args, const char *str)
3254 GSList *list, *elt;
3255 size_t len;
3257 if (nb_args != 2) {
3258 return;
3261 len = strlen(str);
3262 readline_set_completion_index(rs, len);
3263 list = elt = object_class_get_list(TYPE_DEVICE, false);
3264 while (elt) {
3265 const char *name;
3266 DeviceClass *dc = OBJECT_CLASS_CHECK(DeviceClass, elt->data,
3267 TYPE_DEVICE);
3268 name = object_class_get_name(OBJECT_CLASS(dc));
3270 if (!dc->cannot_instantiate_with_device_add_yet
3271 && !strncmp(name, str, len)) {
3272 readline_add_completion(rs, name);
3274 elt = elt->next;
3276 g_slist_free(list);
3279 void object_add_completion(ReadLineState *rs, int nb_args, const char *str)
3281 GSList *list, *elt;
3282 size_t len;
3284 if (nb_args != 2) {
3285 return;
3288 len = strlen(str);
3289 readline_set_completion_index(rs, len);
3290 list = elt = object_class_get_list(TYPE_USER_CREATABLE, false);
3291 while (elt) {
3292 const char *name;
3294 name = object_class_get_name(OBJECT_CLASS(elt->data));
3295 if (!strncmp(name, str, len) && strcmp(name, TYPE_USER_CREATABLE)) {
3296 readline_add_completion(rs, name);
3298 elt = elt->next;
3300 g_slist_free(list);
3303 static void peripheral_device_del_completion(ReadLineState *rs,
3304 const char *str, size_t len)
3306 Object *peripheral = container_get(qdev_get_machine(), "/peripheral");
3307 GSList *list, *item;
3309 list = qdev_build_hotpluggable_device_list(peripheral);
3310 if (!list) {
3311 return;
3314 for (item = list; item; item = g_slist_next(item)) {
3315 DeviceState *dev = item->data;
3317 if (dev->id && !strncmp(str, dev->id, len)) {
3318 readline_add_completion(rs, dev->id);
3322 g_slist_free(list);
3325 void chardev_remove_completion(ReadLineState *rs, int nb_args, const char *str)
3327 size_t len;
3328 ChardevInfoList *list, *start;
3330 if (nb_args != 2) {
3331 return;
3333 len = strlen(str);
3334 readline_set_completion_index(rs, len);
3336 start = list = qmp_query_chardev(NULL);
3337 while (list) {
3338 ChardevInfo *chr = list->value;
3340 if (!strncmp(chr->label, str, len)) {
3341 readline_add_completion(rs, chr->label);
3343 list = list->next;
3345 qapi_free_ChardevInfoList(start);
3348 static void ringbuf_completion(ReadLineState *rs, const char *str)
3350 size_t len;
3351 ChardevInfoList *list, *start;
3353 len = strlen(str);
3354 readline_set_completion_index(rs, len);
3356 start = list = qmp_query_chardev(NULL);
3357 while (list) {
3358 ChardevInfo *chr_info = list->value;
3360 if (!strncmp(chr_info->label, str, len)) {
3361 Chardev *chr = qemu_chr_find(chr_info->label);
3362 if (chr && CHARDEV_IS_RINGBUF(chr)) {
3363 readline_add_completion(rs, chr_info->label);
3366 list = list->next;
3368 qapi_free_ChardevInfoList(start);
3371 void ringbuf_write_completion(ReadLineState *rs, int nb_args, const char *str)
3373 if (nb_args != 2) {
3374 return;
3376 ringbuf_completion(rs, str);
3379 void device_del_completion(ReadLineState *rs, int nb_args, const char *str)
3381 size_t len;
3383 if (nb_args != 2) {
3384 return;
3387 len = strlen(str);
3388 readline_set_completion_index(rs, len);
3389 peripheral_device_del_completion(rs, str, len);
3392 void object_del_completion(ReadLineState *rs, int nb_args, const char *str)
3394 ObjectPropertyInfoList *list, *start;
3395 size_t len;
3397 if (nb_args != 2) {
3398 return;
3400 len = strlen(str);
3401 readline_set_completion_index(rs, len);
3403 start = list = qmp_qom_list("/objects", NULL);
3404 while (list) {
3405 ObjectPropertyInfo *info = list->value;
3407 if (!strncmp(info->type, "child<", 5)
3408 && !strncmp(info->name, str, len)) {
3409 readline_add_completion(rs, info->name);
3411 list = list->next;
3413 qapi_free_ObjectPropertyInfoList(start);
3416 void sendkey_completion(ReadLineState *rs, int nb_args, const char *str)
3418 int i;
3419 char *sep;
3420 size_t len;
3422 if (nb_args != 2) {
3423 return;
3425 sep = strrchr(str, '-');
3426 if (sep) {
3427 str = sep + 1;
3429 len = strlen(str);
3430 readline_set_completion_index(rs, len);
3431 for (i = 0; i < Q_KEY_CODE__MAX; i++) {
3432 if (!strncmp(str, QKeyCode_lookup[i], len)) {
3433 readline_add_completion(rs, QKeyCode_lookup[i]);
3438 void set_link_completion(ReadLineState *rs, int nb_args, const char *str)
3440 size_t len;
3442 len = strlen(str);
3443 readline_set_completion_index(rs, len);
3444 if (nb_args == 2) {
3445 NetClientState *ncs[MAX_QUEUE_NUM];
3446 int count, i;
3447 count = qemu_find_net_clients_except(NULL, ncs,
3448 NET_CLIENT_DRIVER_NONE,
3449 MAX_QUEUE_NUM);
3450 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3451 const char *name = ncs[i]->name;
3452 if (!strncmp(str, name, len)) {
3453 readline_add_completion(rs, name);
3456 } else if (nb_args == 3) {
3457 add_completion_option(rs, str, "on");
3458 add_completion_option(rs, str, "off");
3462 void netdev_del_completion(ReadLineState *rs, int nb_args, const char *str)
3464 int len, count, i;
3465 NetClientState *ncs[MAX_QUEUE_NUM];
3467 if (nb_args != 2) {
3468 return;
3471 len = strlen(str);
3472 readline_set_completion_index(rs, len);
3473 count = qemu_find_net_clients_except(NULL, ncs, NET_CLIENT_DRIVER_NIC,
3474 MAX_QUEUE_NUM);
3475 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3476 QemuOpts *opts;
3477 const char *name = ncs[i]->name;
3478 if (strncmp(str, name, len)) {
3479 continue;
3481 opts = qemu_opts_find(qemu_find_opts_err("netdev", NULL), name);
3482 if (opts) {
3483 readline_add_completion(rs, name);
3488 void info_trace_events_completion(ReadLineState *rs, int nb_args, const char *str)
3490 size_t len;
3492 len = strlen(str);
3493 readline_set_completion_index(rs, len);
3494 if (nb_args == 2) {
3495 TraceEventIter iter;
3496 TraceEvent *ev;
3497 char *pattern = g_strdup_printf("%s*", str);
3498 trace_event_iter_init(&iter, pattern);
3499 while ((ev = trace_event_iter_next(&iter)) != NULL) {
3500 readline_add_completion(rs, trace_event_get_name(ev));
3502 g_free(pattern);
3506 void trace_event_completion(ReadLineState *rs, int nb_args, const char *str)
3508 size_t len;
3510 len = strlen(str);
3511 readline_set_completion_index(rs, len);
3512 if (nb_args == 2) {
3513 TraceEventIter iter;
3514 TraceEvent *ev;
3515 char *pattern = g_strdup_printf("%s*", str);
3516 trace_event_iter_init(&iter, pattern);
3517 while ((ev = trace_event_iter_next(&iter)) != NULL) {
3518 readline_add_completion(rs, trace_event_get_name(ev));
3520 g_free(pattern);
3521 } else if (nb_args == 3) {
3522 add_completion_option(rs, str, "on");
3523 add_completion_option(rs, str, "off");
3527 void watchdog_action_completion(ReadLineState *rs, int nb_args, const char *str)
3529 int i;
3531 if (nb_args != 2) {
3532 return;
3534 readline_set_completion_index(rs, strlen(str));
3535 for (i = 0; WatchdogExpirationAction_lookup[i]; i++) {
3536 add_completion_option(rs, str, WatchdogExpirationAction_lookup[i]);
3540 void migrate_set_capability_completion(ReadLineState *rs, int nb_args,
3541 const char *str)
3543 size_t len;
3545 len = strlen(str);
3546 readline_set_completion_index(rs, len);
3547 if (nb_args == 2) {
3548 int i;
3549 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
3550 const char *name = MigrationCapability_lookup[i];
3551 if (!strncmp(str, name, len)) {
3552 readline_add_completion(rs, name);
3555 } else if (nb_args == 3) {
3556 add_completion_option(rs, str, "on");
3557 add_completion_option(rs, str, "off");
3561 void migrate_set_parameter_completion(ReadLineState *rs, int nb_args,
3562 const char *str)
3564 size_t len;
3566 len = strlen(str);
3567 readline_set_completion_index(rs, len);
3568 if (nb_args == 2) {
3569 int i;
3570 for (i = 0; i < MIGRATION_PARAMETER__MAX; i++) {
3571 const char *name = MigrationParameter_lookup[i];
3572 if (!strncmp(str, name, len)) {
3573 readline_add_completion(rs, name);
3579 void host_net_add_completion(ReadLineState *rs, int nb_args, const char *str)
3581 int i;
3582 size_t len;
3583 if (nb_args != 2) {
3584 return;
3586 len = strlen(str);
3587 readline_set_completion_index(rs, len);
3588 for (i = 0; host_net_devices[i]; i++) {
3589 if (!strncmp(host_net_devices[i], str, len)) {
3590 readline_add_completion(rs, host_net_devices[i]);
3595 void host_net_remove_completion(ReadLineState *rs, int nb_args, const char *str)
3597 NetClientState *ncs[MAX_QUEUE_NUM];
3598 int count, i, len;
3600 len = strlen(str);
3601 readline_set_completion_index(rs, len);
3602 if (nb_args == 2) {
3603 count = qemu_find_net_clients_except(NULL, ncs,
3604 NET_CLIENT_DRIVER_NONE,
3605 MAX_QUEUE_NUM);
3606 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3607 int id;
3608 char name[16];
3610 if (net_hub_id_for_client(ncs[i], &id)) {
3611 continue;
3613 snprintf(name, sizeof(name), "%d", id);
3614 if (!strncmp(str, name, len)) {
3615 readline_add_completion(rs, name);
3618 return;
3619 } else if (nb_args == 3) {
3620 count = qemu_find_net_clients_except(NULL, ncs,
3621 NET_CLIENT_DRIVER_NIC,
3622 MAX_QUEUE_NUM);
3623 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3624 int id;
3625 const char *name;
3627 if (ncs[i]->info->type == NET_CLIENT_DRIVER_HUBPORT ||
3628 net_hub_id_for_client(ncs[i], &id)) {
3629 continue;
3631 name = ncs[i]->name;
3632 if (!strncmp(str, name, len)) {
3633 readline_add_completion(rs, name);
3636 return;
3640 static void vm_completion(ReadLineState *rs, const char *str)
3642 size_t len;
3643 BlockDriverState *bs;
3644 BdrvNextIterator it;
3646 len = strlen(str);
3647 readline_set_completion_index(rs, len);
3649 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
3650 SnapshotInfoList *snapshots, *snapshot;
3651 AioContext *ctx = bdrv_get_aio_context(bs);
3652 bool ok = false;
3654 aio_context_acquire(ctx);
3655 if (bdrv_can_snapshot(bs)) {
3656 ok = bdrv_query_snapshot_info_list(bs, &snapshots, NULL) == 0;
3658 aio_context_release(ctx);
3659 if (!ok) {
3660 continue;
3663 snapshot = snapshots;
3664 while (snapshot) {
3665 char *completion = snapshot->value->name;
3666 if (!strncmp(str, completion, len)) {
3667 readline_add_completion(rs, completion);
3669 completion = snapshot->value->id;
3670 if (!strncmp(str, completion, len)) {
3671 readline_add_completion(rs, completion);
3673 snapshot = snapshot->next;
3675 qapi_free_SnapshotInfoList(snapshots);
3680 void delvm_completion(ReadLineState *rs, int nb_args, const char *str)
3682 if (nb_args == 2) {
3683 vm_completion(rs, str);
3687 void loadvm_completion(ReadLineState *rs, int nb_args, const char *str)
3689 if (nb_args == 2) {
3690 vm_completion(rs, str);
3694 static void monitor_find_completion_by_table(Monitor *mon,
3695 const mon_cmd_t *cmd_table,
3696 char **args,
3697 int nb_args)
3699 const char *cmdname;
3700 int i;
3701 const char *ptype, *str, *name;
3702 const mon_cmd_t *cmd;
3703 BlockBackend *blk = NULL;
3705 if (nb_args <= 1) {
3706 /* command completion */
3707 if (nb_args == 0)
3708 cmdname = "";
3709 else
3710 cmdname = args[0];
3711 readline_set_completion_index(mon->rs, strlen(cmdname));
3712 for (cmd = cmd_table; cmd->name != NULL; cmd++) {
3713 cmd_completion(mon, cmdname, cmd->name);
3715 } else {
3716 /* find the command */
3717 for (cmd = cmd_table; cmd->name != NULL; cmd++) {
3718 if (compare_cmd(args[0], cmd->name)) {
3719 break;
3722 if (!cmd->name) {
3723 return;
3726 if (cmd->sub_table) {
3727 /* do the job again */
3728 monitor_find_completion_by_table(mon, cmd->sub_table,
3729 &args[1], nb_args - 1);
3730 return;
3732 if (cmd->command_completion) {
3733 cmd->command_completion(mon->rs, nb_args, args[nb_args - 1]);
3734 return;
3737 ptype = next_arg_type(cmd->args_type);
3738 for(i = 0; i < nb_args - 2; i++) {
3739 if (*ptype != '\0') {
3740 ptype = next_arg_type(ptype);
3741 while (*ptype == '?')
3742 ptype = next_arg_type(ptype);
3745 str = args[nb_args - 1];
3746 while (*ptype == '-' && ptype[1] != '\0') {
3747 ptype = next_arg_type(ptype);
3749 switch(*ptype) {
3750 case 'F':
3751 /* file completion */
3752 readline_set_completion_index(mon->rs, strlen(str));
3753 file_completion(mon, str);
3754 break;
3755 case 'B':
3756 /* block device name completion */
3757 readline_set_completion_index(mon->rs, strlen(str));
3758 while ((blk = blk_next(blk)) != NULL) {
3759 name = blk_name(blk);
3760 if (str[0] == '\0' ||
3761 !strncmp(name, str, strlen(str))) {
3762 readline_add_completion(mon->rs, name);
3765 break;
3766 case 's':
3767 case 'S':
3768 if (!strcmp(cmd->name, "help|?")) {
3769 monitor_find_completion_by_table(mon, cmd_table,
3770 &args[1], nb_args - 1);
3772 break;
3773 default:
3774 break;
3779 static void monitor_find_completion(void *opaque,
3780 const char *cmdline)
3782 Monitor *mon = opaque;
3783 char *args[MAX_ARGS];
3784 int nb_args, len;
3786 /* 1. parse the cmdline */
3787 if (parse_cmdline(cmdline, &nb_args, args) < 0) {
3788 return;
3791 /* if the line ends with a space, it means we want to complete the
3792 next arg */
3793 len = strlen(cmdline);
3794 if (len > 0 && qemu_isspace(cmdline[len - 1])) {
3795 if (nb_args >= MAX_ARGS) {
3796 goto cleanup;
3798 args[nb_args++] = g_strdup("");
3801 /* 2. auto complete according to args */
3802 monitor_find_completion_by_table(mon, mon->cmd_table, args, nb_args);
3804 cleanup:
3805 free_cmdline_args(args, nb_args);
3808 static int monitor_can_read(void *opaque)
3810 Monitor *mon = opaque;
3812 return (mon->suspend_cnt == 0) ? 1 : 0;
3815 static void handle_qmp_command(JSONMessageParser *parser, GQueue *tokens)
3817 QObject *req, *rsp = NULL, *id = NULL;
3818 QDict *qdict = NULL;
3819 Monitor *mon = cur_mon;
3820 Error *err = NULL;
3822 req = json_parser_parse_err(tokens, NULL, &err);
3823 if (!req && !err) {
3824 /* json_parser_parse_err() sucks: can fail without setting @err */
3825 error_setg(&err, QERR_JSON_PARSING);
3827 if (err) {
3828 goto err_out;
3831 qdict = qobject_to_qdict(req);
3832 if (qdict) {
3833 id = qdict_get(qdict, "id");
3834 qobject_incref(id);
3835 qdict_del(qdict, "id");
3836 } /* else will fail qmp_dispatch() */
3838 rsp = qmp_dispatch(cur_mon->qmp.commands, req);
3840 if (mon->qmp.commands == &qmp_cap_negotiation_commands) {
3841 qdict = qdict_get_qdict(qobject_to_qdict(rsp), "error");
3842 if (qdict
3843 && !g_strcmp0(qdict_get_try_str(qdict, "class"),
3844 QapiErrorClass_lookup[ERROR_CLASS_COMMAND_NOT_FOUND])) {
3845 /* Provide a more useful error message */
3846 qdict_del(qdict, "desc");
3847 qdict_put(qdict, "desc",
3848 qstring_from_str("Expecting capabilities negotiation"
3849 " with 'qmp_capabilities'"));
3853 err_out:
3854 if (err) {
3855 qdict = qdict_new();
3856 qdict_put_obj(qdict, "error", qmp_build_error_object(err));
3857 error_free(err);
3858 rsp = QOBJECT(qdict);
3861 if (rsp) {
3862 if (id) {
3863 qdict_put_obj(qobject_to_qdict(rsp), "id", id);
3864 id = NULL;
3867 monitor_json_emitter(mon, rsp);
3870 qobject_decref(id);
3871 qobject_decref(rsp);
3872 qobject_decref(req);
3875 static void monitor_qmp_read(void *opaque, const uint8_t *buf, int size)
3877 Monitor *old_mon = cur_mon;
3879 cur_mon = opaque;
3881 json_message_parser_feed(&cur_mon->qmp.parser, (const char *) buf, size);
3883 cur_mon = old_mon;
3886 static void monitor_read(void *opaque, const uint8_t *buf, int size)
3888 Monitor *old_mon = cur_mon;
3889 int i;
3891 cur_mon = opaque;
3893 if (cur_mon->rs) {
3894 for (i = 0; i < size; i++)
3895 readline_handle_byte(cur_mon->rs, buf[i]);
3896 } else {
3897 if (size == 0 || buf[size - 1] != 0)
3898 monitor_printf(cur_mon, "corrupted command\n");
3899 else
3900 handle_hmp_command(cur_mon, (char *)buf);
3903 cur_mon = old_mon;
3906 static void monitor_command_cb(void *opaque, const char *cmdline,
3907 void *readline_opaque)
3909 Monitor *mon = opaque;
3911 monitor_suspend(mon);
3912 handle_hmp_command(mon, cmdline);
3913 monitor_resume(mon);
3916 int monitor_suspend(Monitor *mon)
3918 if (!mon->rs)
3919 return -ENOTTY;
3920 mon->suspend_cnt++;
3921 return 0;
3924 void monitor_resume(Monitor *mon)
3926 if (!mon->rs)
3927 return;
3928 if (--mon->suspend_cnt == 0)
3929 readline_show_prompt(mon->rs);
3932 static QObject *get_qmp_greeting(void)
3934 QObject *ver = NULL;
3936 qmp_marshal_query_version(NULL, &ver, NULL);
3938 return qobject_from_jsonf("{'QMP': {'version': %p, 'capabilities': []}}",
3939 ver);
3942 static void monitor_qmp_event(void *opaque, int event)
3944 QObject *data;
3945 Monitor *mon = opaque;
3947 switch (event) {
3948 case CHR_EVENT_OPENED:
3949 mon->qmp.commands = &qmp_cap_negotiation_commands;
3950 data = get_qmp_greeting();
3951 monitor_json_emitter(mon, data);
3952 qobject_decref(data);
3953 mon_refcount++;
3954 break;
3955 case CHR_EVENT_CLOSED:
3956 json_message_parser_destroy(&mon->qmp.parser);
3957 json_message_parser_init(&mon->qmp.parser, handle_qmp_command);
3958 mon_refcount--;
3959 monitor_fdsets_cleanup();
3960 break;
3964 static void monitor_event(void *opaque, int event)
3966 Monitor *mon = opaque;
3968 switch (event) {
3969 case CHR_EVENT_MUX_IN:
3970 qemu_mutex_lock(&mon->out_lock);
3971 mon->mux_out = 0;
3972 qemu_mutex_unlock(&mon->out_lock);
3973 if (mon->reset_seen) {
3974 readline_restart(mon->rs);
3975 monitor_resume(mon);
3976 monitor_flush(mon);
3977 } else {
3978 mon->suspend_cnt = 0;
3980 break;
3982 case CHR_EVENT_MUX_OUT:
3983 if (mon->reset_seen) {
3984 if (mon->suspend_cnt == 0) {
3985 monitor_printf(mon, "\n");
3987 monitor_flush(mon);
3988 monitor_suspend(mon);
3989 } else {
3990 mon->suspend_cnt++;
3992 qemu_mutex_lock(&mon->out_lock);
3993 mon->mux_out = 1;
3994 qemu_mutex_unlock(&mon->out_lock);
3995 break;
3997 case CHR_EVENT_OPENED:
3998 monitor_printf(mon, "QEMU %s monitor - type 'help' for more "
3999 "information\n", QEMU_VERSION);
4000 if (!mon->mux_out) {
4001 readline_restart(mon->rs);
4002 readline_show_prompt(mon->rs);
4004 mon->reset_seen = 1;
4005 mon_refcount++;
4006 break;
4008 case CHR_EVENT_CLOSED:
4009 mon_refcount--;
4010 monitor_fdsets_cleanup();
4011 break;
4015 static int
4016 compare_mon_cmd(const void *a, const void *b)
4018 return strcmp(((const mon_cmd_t *)a)->name,
4019 ((const mon_cmd_t *)b)->name);
4022 static void sortcmdlist(void)
4024 int array_num;
4025 int elem_size = sizeof(mon_cmd_t);
4027 array_num = sizeof(mon_cmds)/elem_size-1;
4028 qsort((void *)mon_cmds, array_num, elem_size, compare_mon_cmd);
4030 array_num = sizeof(info_cmds)/elem_size-1;
4031 qsort((void *)info_cmds, array_num, elem_size, compare_mon_cmd);
4034 /* These functions just adapt the readline interface in a typesafe way. We
4035 * could cast function pointers but that discards compiler checks.
4037 static void GCC_FMT_ATTR(2, 3) monitor_readline_printf(void *opaque,
4038 const char *fmt, ...)
4040 va_list ap;
4041 va_start(ap, fmt);
4042 monitor_vprintf(opaque, fmt, ap);
4043 va_end(ap);
4046 static void monitor_readline_flush(void *opaque)
4048 monitor_flush(opaque);
4052 * Print to current monitor if we have one, else to stderr.
4053 * TODO should return int, so callers can calculate width, but that
4054 * requires surgery to monitor_vprintf(). Left for another day.
4056 void error_vprintf(const char *fmt, va_list ap)
4058 if (cur_mon && !monitor_cur_is_qmp()) {
4059 monitor_vprintf(cur_mon, fmt, ap);
4060 } else {
4061 vfprintf(stderr, fmt, ap);
4065 void error_vprintf_unless_qmp(const char *fmt, va_list ap)
4067 if (cur_mon && !monitor_cur_is_qmp()) {
4068 monitor_vprintf(cur_mon, fmt, ap);
4069 } else if (!cur_mon) {
4070 vfprintf(stderr, fmt, ap);
4074 static void __attribute__((constructor)) monitor_lock_init(void)
4076 qemu_mutex_init(&monitor_lock);
4079 void monitor_init(Chardev *chr, int flags)
4081 static int is_first_init = 1;
4082 Monitor *mon;
4084 if (is_first_init) {
4085 monitor_qapi_event_init();
4086 sortcmdlist();
4087 is_first_init = 0;
4090 mon = g_malloc(sizeof(*mon));
4091 monitor_data_init(mon);
4093 qemu_chr_fe_init(&mon->chr, chr, &error_abort);
4094 mon->flags = flags;
4095 if (flags & MONITOR_USE_READLINE) {
4096 mon->rs = readline_init(monitor_readline_printf,
4097 monitor_readline_flush,
4098 mon,
4099 monitor_find_completion);
4100 monitor_read_command(mon, 0);
4103 if (monitor_is_qmp(mon)) {
4104 qemu_chr_fe_set_handlers(&mon->chr, monitor_can_read, monitor_qmp_read,
4105 monitor_qmp_event, mon, NULL, true);
4106 qemu_chr_fe_set_echo(&mon->chr, true);
4107 json_message_parser_init(&mon->qmp.parser, handle_qmp_command);
4108 } else {
4109 qemu_chr_fe_set_handlers(&mon->chr, monitor_can_read, monitor_read,
4110 monitor_event, mon, NULL, true);
4113 qemu_mutex_lock(&monitor_lock);
4114 QLIST_INSERT_HEAD(&mon_list, mon, entry);
4115 qemu_mutex_unlock(&monitor_lock);
4118 void monitor_cleanup(void)
4120 Monitor *mon, *next;
4122 qemu_mutex_lock(&monitor_lock);
4123 QLIST_FOREACH_SAFE(mon, &mon_list, entry, next) {
4124 QLIST_REMOVE(mon, entry);
4125 monitor_data_destroy(mon);
4126 g_free(mon);
4128 qemu_mutex_unlock(&monitor_lock);
4131 static void bdrv_password_cb(void *opaque, const char *password,
4132 void *readline_opaque)
4134 Monitor *mon = opaque;
4135 BlockDriverState *bs = readline_opaque;
4136 int ret = 0;
4137 Error *local_err = NULL;
4139 bdrv_add_key(bs, password, &local_err);
4140 if (local_err) {
4141 error_report_err(local_err);
4142 ret = -EPERM;
4144 if (mon->password_completion_cb)
4145 mon->password_completion_cb(mon->password_opaque, ret);
4147 monitor_read_command(mon, 1);
4150 int monitor_read_bdrv_key_start(Monitor *mon, BlockDriverState *bs,
4151 BlockCompletionFunc *completion_cb,
4152 void *opaque)
4154 int err;
4156 monitor_printf(mon, "%s (%s) is encrypted.\n", bdrv_get_device_name(bs),
4157 bdrv_get_encrypted_filename(bs));
4159 mon->password_completion_cb = completion_cb;
4160 mon->password_opaque = opaque;
4162 err = monitor_read_password(mon, bdrv_password_cb, bs);
4164 if (err && completion_cb)
4165 completion_cb(opaque, err);
4167 return err;
4170 int monitor_read_block_device_key(Monitor *mon, const char *device,
4171 BlockCompletionFunc *completion_cb,
4172 void *opaque)
4174 Error *err = NULL;
4175 BlockBackend *blk;
4177 blk = blk_by_name(device);
4178 if (!blk) {
4179 monitor_printf(mon, "Device not found %s\n", device);
4180 return -1;
4182 if (!blk_bs(blk)) {
4183 monitor_printf(mon, "Device '%s' has no medium\n", device);
4184 return -1;
4187 bdrv_add_key(blk_bs(blk), NULL, &err);
4188 if (err) {
4189 error_free(err);
4190 return monitor_read_bdrv_key_start(mon, blk_bs(blk), completion_cb, opaque);
4193 if (completion_cb) {
4194 completion_cb(opaque, 0);
4196 return 0;
4199 QemuOptsList qemu_mon_opts = {
4200 .name = "mon",
4201 .implied_opt_name = "chardev",
4202 .head = QTAILQ_HEAD_INITIALIZER(qemu_mon_opts.head),
4203 .desc = {
4205 .name = "mode",
4206 .type = QEMU_OPT_STRING,
4208 .name = "chardev",
4209 .type = QEMU_OPT_STRING,
4211 .name = "default", /* deprecated */
4212 .type = QEMU_OPT_BOOL,
4214 .name = "pretty",
4215 .type = QEMU_OPT_BOOL,
4217 { /* end of list */ }
4221 #ifndef TARGET_I386
4222 void qmp_rtc_reset_reinjection(Error **errp)
4224 error_setg(errp, QERR_FEATURE_DISABLED, "rtc-reset-reinjection");
4226 #endif
4228 #ifndef TARGET_S390X
4229 void qmp_dump_skeys(const char *filename, Error **errp)
4231 error_setg(errp, QERR_FEATURE_DISABLED, "dump-skeys");
4233 #endif
4235 #ifndef TARGET_ARM
4236 GICCapabilityList *qmp_query_gic_capabilities(Error **errp)
4238 error_setg(errp, QERR_FEATURE_DISABLED, "query-gic-capabilities");
4239 return NULL;
4241 #endif
4243 HotpluggableCPUList *qmp_query_hotpluggable_cpus(Error **errp)
4245 MachineState *ms = MACHINE(qdev_get_machine());
4246 MachineClass *mc = MACHINE_GET_CLASS(ms);
4248 if (!mc->has_hotpluggable_cpus) {
4249 error_setg(errp, QERR_FEATURE_DISABLED, "query-hotpluggable-cpus");
4250 return NULL;
4253 return machine_query_hotpluggable_cpus(ms);