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
24 #include "qemu/osdep.h"
26 #include "qemu-common.h"
29 #include "monitor/qdev.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"
37 #include "net/slirp.h"
38 #include "sysemu/char.h"
39 #include "ui/qemu-spice.h"
40 #include "sysemu/sysemu.h"
41 #include "sysemu/numa.h"
42 #include "monitor/monitor.h"
43 #include "qemu/readline.h"
44 #include "ui/console.h"
46 #include "sysemu/blockdev.h"
47 #include "sysemu/block-backend.h"
48 #include "audio/audio.h"
49 #include "disas/disas.h"
50 #include "sysemu/balloon.h"
51 #include "qemu/timer.h"
52 #include "migration/migration.h"
53 #include "sysemu/kvm.h"
55 #include "sysemu/tpm.h"
56 #include "qapi/qmp/qerror.h"
57 #include "qapi/qmp/qint.h"
58 #include "qapi/qmp/qfloat.h"
59 #include "qapi/qmp/qlist.h"
60 #include "qapi/qmp/qbool.h"
61 #include "qapi/qmp/qstring.h"
62 #include "qapi/qmp/qjson.h"
63 #include "qapi/qmp/json-streamer.h"
64 #include "qapi/qmp/json-parser.h"
65 #include <qom/object_interfaces.h>
68 #include "trace/control.h"
69 #include "monitor/hmp-target.h"
70 #ifdef CONFIG_TRACE_SIMPLE
71 #include "trace/simple.h"
73 #include "exec/memory.h"
74 #include "exec/exec-all.h"
76 #include "qmp-commands.h"
78 #include "qemu/thread.h"
79 #include "block/qapi.h"
80 #include "qapi/qmp-event.h"
81 #include "qapi-event.h"
82 #include "qmp-introspect.h"
83 #include "sysemu/block-backend.h"
84 #include "sysemu/qtest.h"
85 #include "qemu/cutils.h"
87 /* for hmp_info_irq/pic */
88 #if defined(TARGET_SPARC)
89 #include "hw/sparc/sun4m.h"
91 #include "hw/lm32/lm32_pic.h"
93 #if defined(TARGET_S390X)
94 #include "hw/s390x/storage-keys.h"
101 * 'B' block device name
102 * 's' string (accept optional quote)
103 * 'S' it just appends the rest of the string (accept optional quote)
104 * 'O' option string of the form NAME=VALUE,...
105 * parsed according to QemuOptsList given by its name
106 * Example: 'device:O' uses qemu_device_opts.
107 * Restriction: only lists with empty desc are supported
108 * TODO lift the restriction
110 * 'l' target long (32 or 64 bit)
111 * 'M' Non-negative target long (32 or 64 bit), in user mode the
112 * value is multiplied by 2^20 (think Mebibyte)
113 * 'o' octets (aka bytes)
114 * user mode accepts an optional E, e, P, p, T, t, G, g, M, m,
115 * K, k suffix, which multiplies the value by 2^60 for suffixes E
116 * and e, 2^50 for suffixes P and p, 2^40 for suffixes T and t,
117 * 2^30 for suffixes G and g, 2^20 for M and m, 2^10 for K and k
119 * user mode accepts an optional ms, us, ns suffix,
120 * which divides the value by 1e3, 1e6, 1e9, respectively
121 * '/' optional gdb-like print format (like "/10x")
123 * '?' optional type (for all types, except '/')
124 * '.' other form of optional type (for 'i' and 'l')
126 * user mode accepts "on" or "off"
127 * '-' optional parameter (eg. '-f')
131 typedef struct mon_cmd_t {
133 const char *args_type;
137 void (*cmd)(Monitor *mon, const QDict *qdict);
138 void (*cmd_new)(QDict *params, QObject **ret_data, Error **errp);
140 /* @sub_table is a list of 2nd level of commands. If it do not exist,
141 * mhandler should be used. If it exist, sub_table[?].mhandler should be
142 * used, and mhandler of 1st level plays the role of help function.
144 struct mon_cmd_t *sub_table;
145 void (*command_completion)(ReadLineState *rs, int nb_args, const char *str);
148 /* file descriptors passed via SCM_RIGHTS */
149 typedef struct mon_fd_t mon_fd_t;
153 QLIST_ENTRY(mon_fd_t) next;
156 /* file descriptor associated with a file descriptor set */
157 typedef struct MonFdsetFd MonFdsetFd;
162 QLIST_ENTRY(MonFdsetFd) next;
165 /* file descriptor set containing fds passed via SCM_RIGHTS */
166 typedef struct MonFdset MonFdset;
169 QLIST_HEAD(, MonFdsetFd) fds;
170 QLIST_HEAD(, MonFdsetFd) dup_fds;
171 QLIST_ENTRY(MonFdset) next;
176 JSONMessageParser parser;
178 * When a client connects, we're in capabilities negotiation mode.
179 * When command qmp_capabilities succeeds, we go into command
182 bool in_command_mode; /* are we in command mode? */
186 * To prevent flooding clients, events can be throttled. The
187 * throttling is calculated globally, rather than per-Monitor
190 typedef struct MonitorQAPIEventState {
191 QAPIEvent event; /* Throttling state for this event type and... */
192 QDict *data; /* ... data, see qapi_event_throttle_equal() */
193 QEMUTimer *timer; /* Timer for handling delayed events */
194 QDict *qdict; /* Delayed event (if any) */
195 } MonitorQAPIEventState;
198 int64_t rate; /* Minimum time (in ns) between two events */
199 } MonitorQAPIEventConf;
202 CharDriverState *chr;
212 /* Read under either BQL or out_lock, written with BQL+out_lock. */
218 BlockCompletionFunc *password_completion_cb;
219 void *password_opaque;
220 mon_cmd_t *cmd_table;
221 QLIST_HEAD(,mon_fd_t) fds;
222 QLIST_ENTRY(Monitor) entry;
225 /* QMP checker flags */
226 #define QMP_ACCEPT_UNKNOWNS 1
228 /* Protects mon_list, monitor_event_state. */
229 static QemuMutex monitor_lock;
231 static QLIST_HEAD(mon_list, Monitor) mon_list;
232 static QLIST_HEAD(mon_fdsets, MonFdset) mon_fdsets;
233 static int mon_refcount;
235 static mon_cmd_t mon_cmds[];
236 static mon_cmd_t info_cmds[];
238 static const mon_cmd_t qmp_cmds[];
242 static QEMUClockType event_clock_type = QEMU_CLOCK_REALTIME;
244 static void monitor_command_cb(void *opaque, const char *cmdline,
245 void *readline_opaque);
248 * Is @mon a QMP monitor?
250 static inline bool monitor_is_qmp(const Monitor *mon)
252 return (mon->flags & MONITOR_USE_CONTROL);
256 * Is the current monitor, if any, a QMP monitor?
258 bool monitor_cur_is_qmp(void)
260 return cur_mon && monitor_is_qmp(cur_mon);
263 void monitor_read_command(Monitor *mon, int show_prompt)
268 readline_start(mon->rs, "(qemu) ", 0, monitor_command_cb, NULL);
270 readline_show_prompt(mon->rs);
273 int monitor_read_password(Monitor *mon, ReadLineFunc *readline_func,
277 readline_start(mon->rs, "Password: ", 1, readline_func, opaque);
278 /* prompt is printed on return from the command handler */
281 monitor_printf(mon, "terminal does not support password prompting\n");
286 static void monitor_flush_locked(Monitor *mon);
288 static gboolean monitor_unblocked(GIOChannel *chan, GIOCondition cond,
291 Monitor *mon = opaque;
293 qemu_mutex_lock(&mon->out_lock);
295 monitor_flush_locked(mon);
296 qemu_mutex_unlock(&mon->out_lock);
300 /* Called with mon->out_lock held. */
301 static void monitor_flush_locked(Monitor *mon)
307 if (mon->skip_flush) {
311 buf = qstring_get_str(mon->outbuf);
312 len = qstring_get_length(mon->outbuf);
314 if (len && !mon->mux_out) {
315 rc = qemu_chr_fe_write(mon->chr, (const uint8_t *) buf, len);
316 if ((rc < 0 && errno != EAGAIN) || (rc == len)) {
317 /* all flushed or error */
318 QDECREF(mon->outbuf);
319 mon->outbuf = qstring_new();
324 QString *tmp = qstring_from_str(buf + rc);
325 QDECREF(mon->outbuf);
328 if (mon->out_watch == 0) {
329 mon->out_watch = qemu_chr_fe_add_watch(mon->chr, G_IO_OUT|G_IO_HUP,
330 monitor_unblocked, mon);
335 void monitor_flush(Monitor *mon)
337 qemu_mutex_lock(&mon->out_lock);
338 monitor_flush_locked(mon);
339 qemu_mutex_unlock(&mon->out_lock);
342 /* flush at every end of line */
343 static void monitor_puts(Monitor *mon, const char *str)
347 qemu_mutex_lock(&mon->out_lock);
353 qstring_append_chr(mon->outbuf, '\r');
355 qstring_append_chr(mon->outbuf, c);
357 monitor_flush_locked(mon);
360 qemu_mutex_unlock(&mon->out_lock);
363 void monitor_vprintf(Monitor *mon, const char *fmt, va_list ap)
370 if (monitor_is_qmp(mon)) {
374 buf = g_strdup_vprintf(fmt, ap);
375 monitor_puts(mon, buf);
379 void monitor_printf(Monitor *mon, const char *fmt, ...)
383 monitor_vprintf(mon, fmt, ap);
387 int monitor_fprintf(FILE *stream, const char *fmt, ...)
391 monitor_vprintf((Monitor *)stream, fmt, ap);
396 static void monitor_json_emitter(Monitor *mon, const QObject *data)
400 json = mon->flags & MONITOR_USE_PRETTY ? qobject_to_json_pretty(data) :
401 qobject_to_json(data);
402 assert(json != NULL);
404 qstring_append_chr(json, '\n');
405 monitor_puts(mon, qstring_get_str(json));
410 static QDict *build_qmp_error_dict(Error *err)
414 obj = qobject_from_jsonf("{ 'error': { 'class': %s, 'desc': %s } }",
415 QapiErrorClass_lookup[error_get_class(err)],
416 error_get_pretty(err));
418 return qobject_to_qdict(obj);
421 static void monitor_protocol_emitter(Monitor *mon, QObject *data,
426 trace_monitor_protocol_emitter(mon);
429 /* success response */
432 qobject_incref(data);
433 qdict_put_obj(qmp, "return", data);
435 /* return an empty QDict by default */
436 qdict_put(qmp, "return", qdict_new());
440 qmp = build_qmp_error_dict(err);
444 qdict_put_obj(qmp, "id", mon->qmp.id);
448 monitor_json_emitter(mon, QOBJECT(qmp));
453 static MonitorQAPIEventConf monitor_qapi_event_conf[QAPI_EVENT__MAX] = {
454 /* Limit guest-triggerable events to 1 per second */
455 [QAPI_EVENT_RTC_CHANGE] = { 1000 * SCALE_MS },
456 [QAPI_EVENT_WATCHDOG] = { 1000 * SCALE_MS },
457 [QAPI_EVENT_BALLOON_CHANGE] = { 1000 * SCALE_MS },
458 [QAPI_EVENT_QUORUM_REPORT_BAD] = { 1000 * SCALE_MS },
459 [QAPI_EVENT_QUORUM_FAILURE] = { 1000 * SCALE_MS },
460 [QAPI_EVENT_VSERPORT_CHANGE] = { 1000 * SCALE_MS },
463 GHashTable *monitor_qapi_event_state;
466 * Emits the event to every monitor instance, @event is only used for trace
467 * Called with monitor_lock held.
469 static void monitor_qapi_event_emit(QAPIEvent event, QDict *qdict)
473 trace_monitor_protocol_event_emit(event, qdict);
474 QLIST_FOREACH(mon, &mon_list, entry) {
475 if (monitor_is_qmp(mon) && mon->qmp.in_command_mode) {
476 monitor_json_emitter(mon, QOBJECT(qdict));
481 static void monitor_qapi_event_handler(void *opaque);
484 * Queue a new event for emission to Monitor instances,
485 * applying any rate limiting if required.
488 monitor_qapi_event_queue(QAPIEvent event, QDict *qdict, Error **errp)
490 MonitorQAPIEventConf *evconf;
491 MonitorQAPIEventState *evstate;
493 assert(event < QAPI_EVENT__MAX);
494 evconf = &monitor_qapi_event_conf[event];
495 trace_monitor_protocol_event_queue(event, qdict, evconf->rate);
497 qemu_mutex_lock(&monitor_lock);
500 /* Unthrottled event */
501 monitor_qapi_event_emit(event, qdict);
503 QDict *data = qobject_to_qdict(qdict_get(qdict, "data"));
504 MonitorQAPIEventState key = { .event = event, .data = data };
506 evstate = g_hash_table_lookup(monitor_qapi_event_state, &key);
507 assert(!evstate || timer_pending(evstate->timer));
511 * Timer is pending for (at least) evconf->rate ns after
512 * last send. Store event for sending when timer fires,
513 * replacing a prior stored event if any.
515 QDECREF(evstate->qdict);
516 evstate->qdict = qdict;
517 QINCREF(evstate->qdict);
520 * Last send was (at least) evconf->rate ns ago.
521 * Send immediately, and arm the timer to call
522 * monitor_qapi_event_handler() in evconf->rate ns. Any
523 * events arriving before then will be delayed until then.
525 int64_t now = qemu_clock_get_ns(event_clock_type);
527 monitor_qapi_event_emit(event, qdict);
529 evstate = g_new(MonitorQAPIEventState, 1);
530 evstate->event = event;
531 evstate->data = data;
532 QINCREF(evstate->data);
533 evstate->qdict = NULL;
534 evstate->timer = timer_new_ns(event_clock_type,
535 monitor_qapi_event_handler,
537 g_hash_table_add(monitor_qapi_event_state, evstate);
538 timer_mod_ns(evstate->timer, now + evconf->rate);
542 qemu_mutex_unlock(&monitor_lock);
546 * This function runs evconf->rate ns after sending a throttled
548 * If another event has since been stored, send it.
550 static void monitor_qapi_event_handler(void *opaque)
552 MonitorQAPIEventState *evstate = opaque;
553 MonitorQAPIEventConf *evconf = &monitor_qapi_event_conf[evstate->event];
555 trace_monitor_protocol_event_handler(evstate->event, evstate->qdict);
556 qemu_mutex_lock(&monitor_lock);
558 if (evstate->qdict) {
559 int64_t now = qemu_clock_get_ns(event_clock_type);
561 monitor_qapi_event_emit(evstate->event, evstate->qdict);
562 QDECREF(evstate->qdict);
563 evstate->qdict = NULL;
564 timer_mod_ns(evstate->timer, now + evconf->rate);
566 g_hash_table_remove(monitor_qapi_event_state, evstate);
567 QDECREF(evstate->data);
568 timer_free(evstate->timer);
572 qemu_mutex_unlock(&monitor_lock);
575 static unsigned int qapi_event_throttle_hash(const void *key)
577 const MonitorQAPIEventState *evstate = key;
578 unsigned int hash = evstate->event * 255;
580 if (evstate->event == QAPI_EVENT_VSERPORT_CHANGE) {
581 hash += g_str_hash(qdict_get_str(evstate->data, "id"));
584 if (evstate->event == QAPI_EVENT_QUORUM_REPORT_BAD) {
585 hash += g_str_hash(qdict_get_str(evstate->data, "node-name"));
591 static gboolean qapi_event_throttle_equal(const void *a, const void *b)
593 const MonitorQAPIEventState *eva = a;
594 const MonitorQAPIEventState *evb = b;
596 if (eva->event != evb->event) {
600 if (eva->event == QAPI_EVENT_VSERPORT_CHANGE) {
601 return !strcmp(qdict_get_str(eva->data, "id"),
602 qdict_get_str(evb->data, "id"));
605 if (eva->event == QAPI_EVENT_QUORUM_REPORT_BAD) {
606 return !strcmp(qdict_get_str(eva->data, "node-name"),
607 qdict_get_str(evb->data, "node-name"));
613 static void monitor_qapi_event_init(void)
615 if (qtest_enabled()) {
616 event_clock_type = QEMU_CLOCK_VIRTUAL;
619 monitor_qapi_event_state = g_hash_table_new(qapi_event_throttle_hash,
620 qapi_event_throttle_equal);
621 qmp_event_set_func_emit(monitor_qapi_event_queue);
624 static void qmp_capabilities(QDict *params, QObject **ret_data, Error **errp)
626 cur_mon->qmp.in_command_mode = true;
629 static void handle_hmp_command(Monitor *mon, const char *cmdline);
631 static void monitor_data_init(Monitor *mon)
633 memset(mon, 0, sizeof(Monitor));
634 qemu_mutex_init(&mon->out_lock);
635 mon->outbuf = qstring_new();
636 /* Use *mon_cmds by default. */
637 mon->cmd_table = mon_cmds;
640 static void monitor_data_destroy(Monitor *mon)
642 QDECREF(mon->outbuf);
643 qemu_mutex_destroy(&mon->out_lock);
646 char *qmp_human_monitor_command(const char *command_line, bool has_cpu_index,
647 int64_t cpu_index, Error **errp)
650 Monitor *old_mon, hmp;
652 monitor_data_init(&hmp);
653 hmp.skip_flush = true;
659 int ret = monitor_set_cpu(cpu_index);
662 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cpu-index",
668 handle_hmp_command(&hmp, command_line);
671 qemu_mutex_lock(&hmp.out_lock);
672 if (qstring_get_length(hmp.outbuf) > 0) {
673 output = g_strdup(qstring_get_str(hmp.outbuf));
675 output = g_strdup("");
677 qemu_mutex_unlock(&hmp.out_lock);
680 monitor_data_destroy(&hmp);
684 static int compare_cmd(const char *name, const char *list)
686 const char *p, *pstart;
694 p = pstart + strlen(pstart);
695 if ((p - pstart) == len && !memcmp(pstart, name, len))
704 static int get_str(char *buf, int buf_size, const char **pp)
712 while (qemu_isspace(*p)) {
723 while (*p != '\0' && *p != '\"') {
739 printf("unsupported escape code: '\\%c'\n", c);
742 if ((q - buf) < buf_size - 1) {
746 if ((q - buf) < buf_size - 1) {
753 printf("unterminated string\n");
758 while (*p != '\0' && !qemu_isspace(*p)) {
759 if ((q - buf) < buf_size - 1) {
772 static void free_cmdline_args(char **args, int nb_args)
776 assert(nb_args <= MAX_ARGS);
778 for (i = 0; i < nb_args; i++) {
785 * Parse the command line to get valid args.
786 * @cmdline: command line to be parsed.
787 * @pnb_args: location to store the number of args, must NOT be NULL.
788 * @args: location to store the args, which should be freed by caller, must
791 * Returns 0 on success, negative on failure.
793 * NOTE: this parser is an approximate form of the real command parser. Number
794 * of args have a limit of MAX_ARGS. If cmdline contains more, it will
795 * return with failure.
797 static int parse_cmdline(const char *cmdline,
798 int *pnb_args, char **args)
807 while (qemu_isspace(*p)) {
813 if (nb_args >= MAX_ARGS) {
816 ret = get_str(buf, sizeof(buf), &p);
820 args[nb_args] = g_strdup(buf);
827 free_cmdline_args(args, nb_args);
831 static void help_cmd_dump_one(Monitor *mon,
832 const mon_cmd_t *cmd,
838 for (i = 0; i < prefix_args_nb; i++) {
839 monitor_printf(mon, "%s ", prefix_args[i]);
841 monitor_printf(mon, "%s %s -- %s\n", cmd->name, cmd->params, cmd->help);
844 /* @args[@arg_index] is the valid command need to find in @cmds */
845 static void help_cmd_dump(Monitor *mon, const mon_cmd_t *cmds,
846 char **args, int nb_args, int arg_index)
848 const mon_cmd_t *cmd;
850 /* No valid arg need to compare with, dump all in *cmds */
851 if (arg_index >= nb_args) {
852 for (cmd = cmds; cmd->name != NULL; cmd++) {
853 help_cmd_dump_one(mon, cmd, args, arg_index);
858 /* Find one entry to dump */
859 for (cmd = cmds; cmd->name != NULL; cmd++) {
860 if (compare_cmd(args[arg_index], cmd->name)) {
861 if (cmd->sub_table) {
862 /* continue with next arg */
863 help_cmd_dump(mon, cmd->sub_table,
864 args, nb_args, arg_index + 1);
866 help_cmd_dump_one(mon, cmd, args, arg_index);
873 static void help_cmd(Monitor *mon, const char *name)
875 char *args[MAX_ARGS];
878 /* 1. parse user input */
880 /* special case for log, directly dump and return */
881 if (!strcmp(name, "log")) {
882 const QEMULogItem *item;
883 monitor_printf(mon, "Log items (comma separated):\n");
884 monitor_printf(mon, "%-10s %s\n", "none", "remove all logs");
885 for (item = qemu_log_items; item->mask != 0; item++) {
886 monitor_printf(mon, "%-10s %s\n", item->name, item->help);
891 if (parse_cmdline(name, &nb_args, args) < 0) {
896 /* 2. dump the contents according to parsed args */
897 help_cmd_dump(mon, mon->cmd_table, args, nb_args, 0);
899 free_cmdline_args(args, nb_args);
902 static void do_help_cmd(Monitor *mon, const QDict *qdict)
904 help_cmd(mon, qdict_get_try_str(qdict, "name"));
907 static void hmp_trace_event(Monitor *mon, const QDict *qdict)
909 const char *tp_name = qdict_get_str(qdict, "name");
910 bool new_state = qdict_get_bool(qdict, "option");
911 Error *local_err = NULL;
913 qmp_trace_event_set_state(tp_name, new_state, true, true, &local_err);
915 error_report_err(local_err);
919 #ifdef CONFIG_TRACE_SIMPLE
920 static void hmp_trace_file(Monitor *mon, const QDict *qdict)
922 const char *op = qdict_get_try_str(qdict, "op");
923 const char *arg = qdict_get_try_str(qdict, "arg");
926 st_print_trace_file_status((FILE *)mon, &monitor_fprintf);
927 } else if (!strcmp(op, "on")) {
928 st_set_trace_file_enabled(true);
929 } else if (!strcmp(op, "off")) {
930 st_set_trace_file_enabled(false);
931 } else if (!strcmp(op, "flush")) {
932 st_flush_trace_buffer();
933 } else if (!strcmp(op, "set")) {
935 st_set_trace_file(arg);
938 monitor_printf(mon, "unexpected argument \"%s\"\n", op);
939 help_cmd(mon, "trace-file");
944 static void hmp_info_help(Monitor *mon, const QDict *qdict)
946 help_cmd(mon, "info");
949 CommandInfoList *qmp_query_commands(Error **errp)
951 CommandInfoList *info, *cmd_list = NULL;
952 const mon_cmd_t *cmd;
954 for (cmd = qmp_cmds; cmd->name != NULL; cmd++) {
955 info = g_malloc0(sizeof(*info));
956 info->value = g_malloc0(sizeof(*info->value));
957 info->value->name = g_strdup(cmd->name);
959 info->next = cmd_list;
966 EventInfoList *qmp_query_events(Error **errp)
968 EventInfoList *info, *ev_list = NULL;
971 for (e = 0 ; e < QAPI_EVENT__MAX ; e++) {
972 const char *event_name = QAPIEvent_lookup[e];
973 assert(event_name != NULL);
974 info = g_malloc0(sizeof(*info));
975 info->value = g_malloc0(sizeof(*info->value));
976 info->value->name = g_strdup(event_name);
978 info->next = ev_list;
986 * Minor hack: generated marshalling suppressed for this command
987 * ('gen': false in the schema) so we can parse the JSON string
988 * directly into QObject instead of first parsing it with
989 * visit_type_SchemaInfoList() into a SchemaInfoList, then marshal it
990 * to QObject with generated output marshallers, every time. Instead,
991 * we do it in test-qmp-input-visitor.c, just to make sure
992 * qapi-introspect.py's output actually conforms to the schema.
994 static void qmp_query_qmp_schema(QDict *qdict, QObject **ret_data,
997 *ret_data = qobject_from_json(qmp_schema_json);
1000 /* set the current CPU defined by the user */
1001 int monitor_set_cpu(int cpu_index)
1005 cpu = qemu_get_cpu(cpu_index);
1009 cur_mon->mon_cpu = cpu;
1013 CPUState *mon_get_cpu(void)
1015 if (!cur_mon->mon_cpu) {
1018 cpu_synchronize_state(cur_mon->mon_cpu);
1019 return cur_mon->mon_cpu;
1022 CPUArchState *mon_get_cpu_env(void)
1024 return mon_get_cpu()->env_ptr;
1027 int monitor_get_cpu_index(void)
1029 return mon_get_cpu()->cpu_index;
1032 static void hmp_info_registers(Monitor *mon, const QDict *qdict)
1034 cpu_dump_state(mon_get_cpu(), (FILE *)mon, monitor_fprintf, CPU_DUMP_FPU);
1037 static void hmp_info_jit(Monitor *mon, const QDict *qdict)
1039 dump_exec_info((FILE *)mon, monitor_fprintf);
1040 dump_drift_info((FILE *)mon, monitor_fprintf);
1043 static void hmp_info_opcount(Monitor *mon, const QDict *qdict)
1045 dump_opcount_info((FILE *)mon, monitor_fprintf);
1048 static void hmp_info_history(Monitor *mon, const QDict *qdict)
1057 str = readline_get_history(mon->rs, i);
1060 monitor_printf(mon, "%d: '%s'\n", i, str);
1065 static void hmp_info_cpustats(Monitor *mon, const QDict *qdict)
1067 cpu_dump_statistics(mon_get_cpu(), (FILE *)mon, &monitor_fprintf, 0);
1070 static void hmp_info_trace_events(Monitor *mon, const QDict *qdict)
1072 TraceEventInfoList *events = qmp_trace_event_get_state("*", NULL);
1073 TraceEventInfoList *elem;
1075 for (elem = events; elem != NULL; elem = elem->next) {
1076 monitor_printf(mon, "%s : state %u\n",
1078 elem->value->state == TRACE_EVENT_STATE_ENABLED ? 1 : 0);
1080 qapi_free_TraceEventInfoList(events);
1083 void qmp_client_migrate_info(const char *protocol, const char *hostname,
1084 bool has_port, int64_t port,
1085 bool has_tls_port, int64_t tls_port,
1086 bool has_cert_subject, const char *cert_subject,
1089 if (strcmp(protocol, "spice") == 0) {
1090 if (!qemu_using_spice(errp)) {
1094 if (!has_port && !has_tls_port) {
1095 error_setg(errp, QERR_MISSING_PARAMETER, "port/tls-port");
1099 if (qemu_spice_migrate_info(hostname,
1100 has_port ? port : -1,
1101 has_tls_port ? tls_port : -1,
1103 error_setg(errp, QERR_UNDEFINED_ERROR);
1109 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "protocol", "spice");
1112 static void hmp_logfile(Monitor *mon, const QDict *qdict)
1116 qemu_set_log_filename(qdict_get_str(qdict, "filename"), &err);
1118 error_report_err(err);
1122 static void hmp_log(Monitor *mon, const QDict *qdict)
1125 const char *items = qdict_get_str(qdict, "items");
1127 if (!strcmp(items, "none")) {
1130 mask = qemu_str_to_log_mask(items);
1132 help_cmd(mon, "log");
1139 static void hmp_singlestep(Monitor *mon, const QDict *qdict)
1141 const char *option = qdict_get_try_str(qdict, "option");
1142 if (!option || !strcmp(option, "on")) {
1144 } else if (!strcmp(option, "off")) {
1147 monitor_printf(mon, "unexpected option %s\n", option);
1151 static void hmp_gdbserver(Monitor *mon, const QDict *qdict)
1153 const char *device = qdict_get_try_str(qdict, "device");
1155 device = "tcp::" DEFAULT_GDBSTUB_PORT;
1156 if (gdbserver_start(device) < 0) {
1157 monitor_printf(mon, "Could not open gdbserver on device '%s'\n",
1159 } else if (strcmp(device, "none") == 0) {
1160 monitor_printf(mon, "Disabled gdbserver\n");
1162 monitor_printf(mon, "Waiting for gdb connection on device '%s'\n",
1167 static void hmp_watchdog_action(Monitor *mon, const QDict *qdict)
1169 const char *action = qdict_get_str(qdict, "action");
1170 if (select_watchdog_action(action) == -1) {
1171 monitor_printf(mon, "Unknown watchdog action '%s'\n", action);
1175 static void monitor_printc(Monitor *mon, int c)
1177 monitor_printf(mon, "'");
1180 monitor_printf(mon, "\\'");
1183 monitor_printf(mon, "\\\\");
1186 monitor_printf(mon, "\\n");
1189 monitor_printf(mon, "\\r");
1192 if (c >= 32 && c <= 126) {
1193 monitor_printf(mon, "%c", c);
1195 monitor_printf(mon, "\\x%02x", c);
1199 monitor_printf(mon, "'");
1202 static void memory_dump(Monitor *mon, int count, int format, int wsize,
1203 hwaddr addr, int is_physical)
1205 int l, line_size, i, max_digits, len;
1209 if (format == 'i') {
1212 CPUArchState *env = mon_get_cpu_env();
1215 } else if (wsize == 4) {
1218 /* as default we use the current CS size */
1221 #ifdef TARGET_X86_64
1222 if ((env->efer & MSR_EFER_LMA) &&
1223 (env->segs[R_CS].flags & DESC_L_MASK))
1227 if (!(env->segs[R_CS].flags & DESC_B_MASK))
1233 CPUArchState *env = mon_get_cpu_env();
1234 flags = msr_le << 16;
1235 flags |= env->bfd_mach;
1237 monitor_disas(mon, mon_get_cpu(), addr, count, is_physical, flags);
1241 len = wsize * count;
1250 max_digits = (wsize * 8 + 2) / 3;
1254 max_digits = (wsize * 8) / 4;
1258 max_digits = (wsize * 8 * 10 + 32) / 33;
1267 monitor_printf(mon, TARGET_FMT_plx ":", addr);
1269 monitor_printf(mon, TARGET_FMT_lx ":", (target_ulong)addr);
1274 cpu_physical_memory_read(addr, buf, l);
1276 if (cpu_memory_rw_debug(mon_get_cpu(), addr, buf, l, 0) < 0) {
1277 monitor_printf(mon, " Cannot access memory\n");
1286 v = ldub_p(buf + i);
1289 v = lduw_p(buf + i);
1292 v = (uint32_t)ldl_p(buf + i);
1298 monitor_printf(mon, " ");
1301 monitor_printf(mon, "%#*" PRIo64, max_digits, v);
1304 monitor_printf(mon, "0x%0*" PRIx64, max_digits, v);
1307 monitor_printf(mon, "%*" PRIu64, max_digits, v);
1310 monitor_printf(mon, "%*" PRId64, max_digits, v);
1313 monitor_printc(mon, v);
1318 monitor_printf(mon, "\n");
1324 static void hmp_memory_dump(Monitor *mon, const QDict *qdict)
1326 int count = qdict_get_int(qdict, "count");
1327 int format = qdict_get_int(qdict, "format");
1328 int size = qdict_get_int(qdict, "size");
1329 target_long addr = qdict_get_int(qdict, "addr");
1331 memory_dump(mon, count, format, size, addr, 0);
1334 static void hmp_physical_memory_dump(Monitor *mon, const QDict *qdict)
1336 int count = qdict_get_int(qdict, "count");
1337 int format = qdict_get_int(qdict, "format");
1338 int size = qdict_get_int(qdict, "size");
1339 hwaddr addr = qdict_get_int(qdict, "addr");
1341 memory_dump(mon, count, format, size, addr, 1);
1344 static void do_print(Monitor *mon, const QDict *qdict)
1346 int format = qdict_get_int(qdict, "format");
1347 hwaddr val = qdict_get_int(qdict, "val");
1351 monitor_printf(mon, "%#" HWADDR_PRIo, val);
1354 monitor_printf(mon, "%#" HWADDR_PRIx, val);
1357 monitor_printf(mon, "%" HWADDR_PRIu, val);
1361 monitor_printf(mon, "%" HWADDR_PRId, val);
1364 monitor_printc(mon, val);
1367 monitor_printf(mon, "\n");
1370 static void hmp_sum(Monitor *mon, const QDict *qdict)
1374 uint32_t start = qdict_get_int(qdict, "start");
1375 uint32_t size = qdict_get_int(qdict, "size");
1378 for(addr = start; addr < (start + size); addr++) {
1379 uint8_t val = address_space_ldub(&address_space_memory, addr,
1380 MEMTXATTRS_UNSPECIFIED, NULL);
1381 /* BSD sum algorithm ('sum' Unix command) */
1382 sum = (sum >> 1) | (sum << 15);
1385 monitor_printf(mon, "%05d\n", sum);
1388 static int mouse_button_state;
1390 static void hmp_mouse_move(Monitor *mon, const QDict *qdict)
1392 int dx, dy, dz, button;
1393 const char *dx_str = qdict_get_str(qdict, "dx_str");
1394 const char *dy_str = qdict_get_str(qdict, "dy_str");
1395 const char *dz_str = qdict_get_try_str(qdict, "dz_str");
1397 dx = strtol(dx_str, NULL, 0);
1398 dy = strtol(dy_str, NULL, 0);
1399 qemu_input_queue_rel(NULL, INPUT_AXIS_X, dx);
1400 qemu_input_queue_rel(NULL, INPUT_AXIS_Y, dy);
1403 dz = strtol(dz_str, NULL, 0);
1405 button = (dz > 0) ? INPUT_BUTTON_WHEEL_UP : INPUT_BUTTON_WHEEL_DOWN;
1406 qemu_input_queue_btn(NULL, button, true);
1407 qemu_input_event_sync();
1408 qemu_input_queue_btn(NULL, button, false);
1411 qemu_input_event_sync();
1414 static void hmp_mouse_button(Monitor *mon, const QDict *qdict)
1416 static uint32_t bmap[INPUT_BUTTON__MAX] = {
1417 [INPUT_BUTTON_LEFT] = MOUSE_EVENT_LBUTTON,
1418 [INPUT_BUTTON_MIDDLE] = MOUSE_EVENT_MBUTTON,
1419 [INPUT_BUTTON_RIGHT] = MOUSE_EVENT_RBUTTON,
1421 int button_state = qdict_get_int(qdict, "button_state");
1423 if (mouse_button_state == button_state) {
1426 qemu_input_update_buttons(NULL, bmap, mouse_button_state, button_state);
1427 qemu_input_event_sync();
1428 mouse_button_state = button_state;
1431 static void hmp_ioport_read(Monitor *mon, const QDict *qdict)
1433 int size = qdict_get_int(qdict, "size");
1434 int addr = qdict_get_int(qdict, "addr");
1435 int has_index = qdict_haskey(qdict, "index");
1440 int index = qdict_get_int(qdict, "index");
1441 cpu_outb(addr & IOPORTS_MASK, index & 0xff);
1449 val = cpu_inb(addr);
1453 val = cpu_inw(addr);
1457 val = cpu_inl(addr);
1461 monitor_printf(mon, "port%c[0x%04x] = %#0*x\n",
1462 suffix, addr, size * 2, val);
1465 static void hmp_ioport_write(Monitor *mon, const QDict *qdict)
1467 int size = qdict_get_int(qdict, "size");
1468 int addr = qdict_get_int(qdict, "addr");
1469 int val = qdict_get_int(qdict, "val");
1471 addr &= IOPORTS_MASK;
1476 cpu_outb(addr, val);
1479 cpu_outw(addr, val);
1482 cpu_outl(addr, val);
1487 static void hmp_boot_set(Monitor *mon, const QDict *qdict)
1489 Error *local_err = NULL;
1490 const char *bootdevice = qdict_get_str(qdict, "bootdevice");
1492 qemu_boot_set(bootdevice, &local_err);
1494 error_report_err(local_err);
1496 monitor_printf(mon, "boot device list now set to %s\n", bootdevice);
1500 static void hmp_info_mtree(Monitor *mon, const QDict *qdict)
1502 mtree_info((fprintf_function)monitor_printf, mon);
1505 static void hmp_info_numa(Monitor *mon, const QDict *qdict)
1511 node_mem = g_new0(uint64_t, nb_numa_nodes);
1512 query_numa_node_mem(node_mem);
1513 monitor_printf(mon, "%d nodes\n", nb_numa_nodes);
1514 for (i = 0; i < nb_numa_nodes; i++) {
1515 monitor_printf(mon, "node %d cpus:", i);
1517 if (cpu->numa_node == i) {
1518 monitor_printf(mon, " %d", cpu->cpu_index);
1521 monitor_printf(mon, "\n");
1522 monitor_printf(mon, "node %d size: %" PRId64 " MB\n", i,
1528 #ifdef CONFIG_PROFILER
1533 static void hmp_info_profile(Monitor *mon, const QDict *qdict)
1535 monitor_printf(mon, "async time %" PRId64 " (%0.3f)\n",
1536 dev_time, dev_time / (double)NANOSECONDS_PER_SECOND);
1537 monitor_printf(mon, "qemu time %" PRId64 " (%0.3f)\n",
1538 tcg_time, tcg_time / (double)NANOSECONDS_PER_SECOND);
1543 static void hmp_info_profile(Monitor *mon, const QDict *qdict)
1545 monitor_printf(mon, "Internal profiler not compiled\n");
1549 /* Capture support */
1550 static QLIST_HEAD (capture_list_head, CaptureState) capture_head;
1552 static void hmp_info_capture(Monitor *mon, const QDict *qdict)
1557 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
1558 monitor_printf(mon, "[%d]: ", i);
1559 s->ops.info (s->opaque);
1563 static void hmp_stopcapture(Monitor *mon, const QDict *qdict)
1566 int n = qdict_get_int(qdict, "n");
1569 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
1571 s->ops.destroy (s->opaque);
1572 QLIST_REMOVE (s, entries);
1579 static void hmp_wavcapture(Monitor *mon, const QDict *qdict)
1581 const char *path = qdict_get_str(qdict, "path");
1582 int has_freq = qdict_haskey(qdict, "freq");
1583 int freq = qdict_get_try_int(qdict, "freq", -1);
1584 int has_bits = qdict_haskey(qdict, "bits");
1585 int bits = qdict_get_try_int(qdict, "bits", -1);
1586 int has_channels = qdict_haskey(qdict, "nchannels");
1587 int nchannels = qdict_get_try_int(qdict, "nchannels", -1);
1590 s = g_malloc0 (sizeof (*s));
1592 freq = has_freq ? freq : 44100;
1593 bits = has_bits ? bits : 16;
1594 nchannels = has_channels ? nchannels : 2;
1596 if (wav_start_capture (s, path, freq, bits, nchannels)) {
1597 monitor_printf(mon, "Failed to add wave capture\n");
1601 QLIST_INSERT_HEAD (&capture_head, s, entries);
1604 static qemu_acl *find_acl(Monitor *mon, const char *name)
1606 qemu_acl *acl = qemu_acl_find(name);
1609 monitor_printf(mon, "acl: unknown list '%s'\n", name);
1614 static void hmp_acl_show(Monitor *mon, const QDict *qdict)
1616 const char *aclname = qdict_get_str(qdict, "aclname");
1617 qemu_acl *acl = find_acl(mon, aclname);
1618 qemu_acl_entry *entry;
1622 monitor_printf(mon, "policy: %s\n",
1623 acl->defaultDeny ? "deny" : "allow");
1624 QTAILQ_FOREACH(entry, &acl->entries, next) {
1626 monitor_printf(mon, "%d: %s %s\n", i,
1627 entry->deny ? "deny" : "allow", entry->match);
1632 static void hmp_acl_reset(Monitor *mon, const QDict *qdict)
1634 const char *aclname = qdict_get_str(qdict, "aclname");
1635 qemu_acl *acl = find_acl(mon, aclname);
1638 qemu_acl_reset(acl);
1639 monitor_printf(mon, "acl: removed all rules\n");
1643 static void hmp_acl_policy(Monitor *mon, const QDict *qdict)
1645 const char *aclname = qdict_get_str(qdict, "aclname");
1646 const char *policy = qdict_get_str(qdict, "policy");
1647 qemu_acl *acl = find_acl(mon, aclname);
1650 if (strcmp(policy, "allow") == 0) {
1651 acl->defaultDeny = 0;
1652 monitor_printf(mon, "acl: policy set to 'allow'\n");
1653 } else if (strcmp(policy, "deny") == 0) {
1654 acl->defaultDeny = 1;
1655 monitor_printf(mon, "acl: policy set to 'deny'\n");
1657 monitor_printf(mon, "acl: unknown policy '%s', "
1658 "expected 'deny' or 'allow'\n", policy);
1663 static void hmp_acl_add(Monitor *mon, const QDict *qdict)
1665 const char *aclname = qdict_get_str(qdict, "aclname");
1666 const char *match = qdict_get_str(qdict, "match");
1667 const char *policy = qdict_get_str(qdict, "policy");
1668 int has_index = qdict_haskey(qdict, "index");
1669 int index = qdict_get_try_int(qdict, "index", -1);
1670 qemu_acl *acl = find_acl(mon, aclname);
1674 if (strcmp(policy, "allow") == 0) {
1676 } else if (strcmp(policy, "deny") == 0) {
1679 monitor_printf(mon, "acl: unknown policy '%s', "
1680 "expected 'deny' or 'allow'\n", policy);
1684 ret = qemu_acl_insert(acl, deny, match, index);
1686 ret = qemu_acl_append(acl, deny, match);
1688 monitor_printf(mon, "acl: unable to add acl entry\n");
1690 monitor_printf(mon, "acl: added rule at position %d\n", ret);
1694 static void hmp_acl_remove(Monitor *mon, const QDict *qdict)
1696 const char *aclname = qdict_get_str(qdict, "aclname");
1697 const char *match = qdict_get_str(qdict, "match");
1698 qemu_acl *acl = find_acl(mon, aclname);
1702 ret = qemu_acl_remove(acl, match);
1704 monitor_printf(mon, "acl: no matching acl entry\n");
1706 monitor_printf(mon, "acl: removed rule at position %d\n", ret);
1710 void qmp_getfd(const char *fdname, Error **errp)
1715 fd = qemu_chr_fe_get_msgfd(cur_mon->chr);
1717 error_setg(errp, QERR_FD_NOT_SUPPLIED);
1721 if (qemu_isdigit(fdname[0])) {
1723 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "fdname",
1724 "a name not starting with a digit");
1728 QLIST_FOREACH(monfd, &cur_mon->fds, next) {
1729 if (strcmp(monfd->name, fdname) != 0) {
1738 monfd = g_malloc0(sizeof(mon_fd_t));
1739 monfd->name = g_strdup(fdname);
1742 QLIST_INSERT_HEAD(&cur_mon->fds, monfd, next);
1745 void qmp_closefd(const char *fdname, Error **errp)
1749 QLIST_FOREACH(monfd, &cur_mon->fds, next) {
1750 if (strcmp(monfd->name, fdname) != 0) {
1754 QLIST_REMOVE(monfd, next);
1756 g_free(monfd->name);
1761 error_setg(errp, QERR_FD_NOT_FOUND, fdname);
1764 static void hmp_loadvm(Monitor *mon, const QDict *qdict)
1766 int saved_vm_running = runstate_is_running();
1767 const char *name = qdict_get_str(qdict, "name");
1769 vm_stop(RUN_STATE_RESTORE_VM);
1771 if (load_vmstate(name) == 0 && saved_vm_running) {
1776 int monitor_get_fd(Monitor *mon, const char *fdname, Error **errp)
1780 QLIST_FOREACH(monfd, &mon->fds, next) {
1783 if (strcmp(monfd->name, fdname) != 0) {
1789 /* caller takes ownership of fd */
1790 QLIST_REMOVE(monfd, next);
1791 g_free(monfd->name);
1797 error_setg(errp, "File descriptor named '%s' has not been found", fdname);
1801 static void monitor_fdset_cleanup(MonFdset *mon_fdset)
1803 MonFdsetFd *mon_fdset_fd;
1804 MonFdsetFd *mon_fdset_fd_next;
1806 QLIST_FOREACH_SAFE(mon_fdset_fd, &mon_fdset->fds, next, mon_fdset_fd_next) {
1807 if ((mon_fdset_fd->removed ||
1808 (QLIST_EMPTY(&mon_fdset->dup_fds) && mon_refcount == 0)) &&
1809 runstate_is_running()) {
1810 close(mon_fdset_fd->fd);
1811 g_free(mon_fdset_fd->opaque);
1812 QLIST_REMOVE(mon_fdset_fd, next);
1813 g_free(mon_fdset_fd);
1817 if (QLIST_EMPTY(&mon_fdset->fds) && QLIST_EMPTY(&mon_fdset->dup_fds)) {
1818 QLIST_REMOVE(mon_fdset, next);
1823 static void monitor_fdsets_cleanup(void)
1825 MonFdset *mon_fdset;
1826 MonFdset *mon_fdset_next;
1828 QLIST_FOREACH_SAFE(mon_fdset, &mon_fdsets, next, mon_fdset_next) {
1829 monitor_fdset_cleanup(mon_fdset);
1833 AddfdInfo *qmp_add_fd(bool has_fdset_id, int64_t fdset_id, bool has_opaque,
1834 const char *opaque, Error **errp)
1837 Monitor *mon = cur_mon;
1840 fd = qemu_chr_fe_get_msgfd(mon->chr);
1842 error_setg(errp, QERR_FD_NOT_SUPPLIED);
1846 fdinfo = monitor_fdset_add_fd(fd, has_fdset_id, fdset_id,
1847 has_opaque, opaque, errp);
1859 void qmp_remove_fd(int64_t fdset_id, bool has_fd, int64_t fd, Error **errp)
1861 MonFdset *mon_fdset;
1862 MonFdsetFd *mon_fdset_fd;
1865 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
1866 if (mon_fdset->id != fdset_id) {
1869 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
1871 if (mon_fdset_fd->fd != fd) {
1874 mon_fdset_fd->removed = true;
1877 mon_fdset_fd->removed = true;
1880 if (has_fd && !mon_fdset_fd) {
1883 monitor_fdset_cleanup(mon_fdset);
1889 snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64 ", fd:%" PRId64,
1892 snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64, fdset_id);
1894 error_setg(errp, QERR_FD_NOT_FOUND, fd_str);
1897 FdsetInfoList *qmp_query_fdsets(Error **errp)
1899 MonFdset *mon_fdset;
1900 MonFdsetFd *mon_fdset_fd;
1901 FdsetInfoList *fdset_list = NULL;
1903 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
1904 FdsetInfoList *fdset_info = g_malloc0(sizeof(*fdset_info));
1905 FdsetFdInfoList *fdsetfd_list = NULL;
1907 fdset_info->value = g_malloc0(sizeof(*fdset_info->value));
1908 fdset_info->value->fdset_id = mon_fdset->id;
1910 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
1911 FdsetFdInfoList *fdsetfd_info;
1913 fdsetfd_info = g_malloc0(sizeof(*fdsetfd_info));
1914 fdsetfd_info->value = g_malloc0(sizeof(*fdsetfd_info->value));
1915 fdsetfd_info->value->fd = mon_fdset_fd->fd;
1916 if (mon_fdset_fd->opaque) {
1917 fdsetfd_info->value->has_opaque = true;
1918 fdsetfd_info->value->opaque = g_strdup(mon_fdset_fd->opaque);
1920 fdsetfd_info->value->has_opaque = false;
1923 fdsetfd_info->next = fdsetfd_list;
1924 fdsetfd_list = fdsetfd_info;
1927 fdset_info->value->fds = fdsetfd_list;
1929 fdset_info->next = fdset_list;
1930 fdset_list = fdset_info;
1936 AddfdInfo *monitor_fdset_add_fd(int fd, bool has_fdset_id, int64_t fdset_id,
1937 bool has_opaque, const char *opaque,
1940 MonFdset *mon_fdset = NULL;
1941 MonFdsetFd *mon_fdset_fd;
1945 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
1946 /* Break if match found or match impossible due to ordering by ID */
1947 if (fdset_id <= mon_fdset->id) {
1948 if (fdset_id < mon_fdset->id) {
1956 if (mon_fdset == NULL) {
1957 int64_t fdset_id_prev = -1;
1958 MonFdset *mon_fdset_cur = QLIST_FIRST(&mon_fdsets);
1962 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "fdset-id",
1963 "a non-negative value");
1966 /* Use specified fdset ID */
1967 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
1968 mon_fdset_cur = mon_fdset;
1969 if (fdset_id < mon_fdset_cur->id) {
1974 /* Use first available fdset ID */
1975 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
1976 mon_fdset_cur = mon_fdset;
1977 if (fdset_id_prev == mon_fdset_cur->id - 1) {
1978 fdset_id_prev = mon_fdset_cur->id;
1985 mon_fdset = g_malloc0(sizeof(*mon_fdset));
1987 mon_fdset->id = fdset_id;
1989 mon_fdset->id = fdset_id_prev + 1;
1992 /* The fdset list is ordered by fdset ID */
1993 if (!mon_fdset_cur) {
1994 QLIST_INSERT_HEAD(&mon_fdsets, mon_fdset, next);
1995 } else if (mon_fdset->id < mon_fdset_cur->id) {
1996 QLIST_INSERT_BEFORE(mon_fdset_cur, mon_fdset, next);
1998 QLIST_INSERT_AFTER(mon_fdset_cur, mon_fdset, next);
2002 mon_fdset_fd = g_malloc0(sizeof(*mon_fdset_fd));
2003 mon_fdset_fd->fd = fd;
2004 mon_fdset_fd->removed = false;
2006 mon_fdset_fd->opaque = g_strdup(opaque);
2008 QLIST_INSERT_HEAD(&mon_fdset->fds, mon_fdset_fd, next);
2010 fdinfo = g_malloc0(sizeof(*fdinfo));
2011 fdinfo->fdset_id = mon_fdset->id;
2012 fdinfo->fd = mon_fdset_fd->fd;
2017 int monitor_fdset_get_fd(int64_t fdset_id, int flags)
2020 MonFdset *mon_fdset;
2021 MonFdsetFd *mon_fdset_fd;
2024 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2025 if (mon_fdset->id != fdset_id) {
2028 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2029 mon_fd_flags = fcntl(mon_fdset_fd->fd, F_GETFL);
2030 if (mon_fd_flags == -1) {
2034 if ((flags & O_ACCMODE) == (mon_fd_flags & O_ACCMODE)) {
2035 return mon_fdset_fd->fd;
2047 int monitor_fdset_dup_fd_add(int64_t fdset_id, int dup_fd)
2049 MonFdset *mon_fdset;
2050 MonFdsetFd *mon_fdset_fd_dup;
2052 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2053 if (mon_fdset->id != fdset_id) {
2056 QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
2057 if (mon_fdset_fd_dup->fd == dup_fd) {
2061 mon_fdset_fd_dup = g_malloc0(sizeof(*mon_fdset_fd_dup));
2062 mon_fdset_fd_dup->fd = dup_fd;
2063 QLIST_INSERT_HEAD(&mon_fdset->dup_fds, mon_fdset_fd_dup, next);
2069 static int monitor_fdset_dup_fd_find_remove(int dup_fd, bool remove)
2071 MonFdset *mon_fdset;
2072 MonFdsetFd *mon_fdset_fd_dup;
2074 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2075 QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
2076 if (mon_fdset_fd_dup->fd == dup_fd) {
2078 QLIST_REMOVE(mon_fdset_fd_dup, next);
2079 if (QLIST_EMPTY(&mon_fdset->dup_fds)) {
2080 monitor_fdset_cleanup(mon_fdset);
2084 return mon_fdset->id;
2092 int monitor_fdset_dup_fd_find(int dup_fd)
2094 return monitor_fdset_dup_fd_find_remove(dup_fd, false);
2097 void monitor_fdset_dup_fd_remove(int dup_fd)
2099 monitor_fdset_dup_fd_find_remove(dup_fd, true);
2102 int monitor_fd_param(Monitor *mon, const char *fdname, Error **errp)
2105 Error *local_err = NULL;
2107 if (!qemu_isdigit(fdname[0]) && mon) {
2108 fd = monitor_get_fd(mon, fdname, &local_err);
2110 fd = qemu_parse_fd(fdname);
2112 error_setg(&local_err, "Invalid file descriptor number '%s'",
2117 error_propagate(errp, local_err);
2126 /* Please update hmp-commands.hx when adding or changing commands */
2127 static mon_cmd_t info_cmds[] = {
2128 #include "hmp-commands-info.h"
2132 /* mon_cmds and info_cmds would be sorted at runtime */
2133 static mon_cmd_t mon_cmds[] = {
2134 #include "hmp-commands.h"
2138 static const mon_cmd_t qmp_cmds[] = {
2139 #include "qmp-commands-old.h"
2143 /*******************************************************************/
2145 static const char *pch;
2146 static sigjmp_buf expr_env;
2149 static void GCC_FMT_ATTR(2, 3) QEMU_NORETURN
2150 expr_error(Monitor *mon, const char *fmt, ...)
2154 monitor_vprintf(mon, fmt, ap);
2155 monitor_printf(mon, "\n");
2157 siglongjmp(expr_env, 1);
2160 /* return 0 if OK, -1 if not found */
2161 static int get_monitor_def(target_long *pval, const char *name)
2163 const MonitorDef *md = target_monitor_defs();
2172 for(; md->name != NULL; md++) {
2173 if (compare_cmd(name, md->name)) {
2174 if (md->get_value) {
2175 *pval = md->get_value(md, md->offset);
2177 CPUArchState *env = mon_get_cpu_env();
2178 ptr = (uint8_t *)env + md->offset;
2181 *pval = *(int32_t *)ptr;
2184 *pval = *(target_long *)ptr;
2195 ret = target_get_monitor_def(mon_get_cpu(), name, &tmp);
2197 *pval = (target_long) tmp;
2203 static void next(void)
2207 while (qemu_isspace(*pch))
2212 static int64_t expr_sum(Monitor *mon);
2214 static int64_t expr_unary(Monitor *mon)
2223 n = expr_unary(mon);
2227 n = -expr_unary(mon);
2231 n = ~expr_unary(mon);
2237 expr_error(mon, "')' expected");
2244 expr_error(mon, "character constant expected");
2248 expr_error(mon, "missing terminating \' character");
2258 while ((*pch >= 'a' && *pch <= 'z') ||
2259 (*pch >= 'A' && *pch <= 'Z') ||
2260 (*pch >= '0' && *pch <= '9') ||
2261 *pch == '_' || *pch == '.') {
2262 if ((q - buf) < sizeof(buf) - 1)
2266 while (qemu_isspace(*pch))
2269 ret = get_monitor_def(®, buf);
2271 expr_error(mon, "unknown register");
2276 expr_error(mon, "unexpected end of expression");
2281 n = strtoull(pch, &p, 0);
2282 if (errno == ERANGE) {
2283 expr_error(mon, "number too large");
2286 expr_error(mon, "invalid char '%c' in expression", *p);
2289 while (qemu_isspace(*pch))
2297 static int64_t expr_prod(Monitor *mon)
2302 val = expr_unary(mon);
2305 if (op != '*' && op != '/' && op != '%')
2308 val2 = expr_unary(mon);
2317 expr_error(mon, "division by zero");
2328 static int64_t expr_logic(Monitor *mon)
2333 val = expr_prod(mon);
2336 if (op != '&' && op != '|' && op != '^')
2339 val2 = expr_prod(mon);
2356 static int64_t expr_sum(Monitor *mon)
2361 val = expr_logic(mon);
2364 if (op != '+' && op != '-')
2367 val2 = expr_logic(mon);
2376 static int get_expr(Monitor *mon, int64_t *pval, const char **pp)
2379 if (sigsetjmp(expr_env, 0)) {
2383 while (qemu_isspace(*pch))
2385 *pval = expr_sum(mon);
2390 static int get_double(Monitor *mon, double *pval, const char **pp)
2392 const char *p = *pp;
2396 d = strtod(p, &tailp);
2398 monitor_printf(mon, "Number expected\n");
2401 if (d != d || d - d != 0) {
2402 /* NaN or infinity */
2403 monitor_printf(mon, "Bad number\n");
2412 * Store the command-name in cmdname, and return a pointer to
2413 * the remaining of the command string.
2415 static const char *get_command_name(const char *cmdline,
2416 char *cmdname, size_t nlen)
2419 const char *p, *pstart;
2422 while (qemu_isspace(*p))
2427 while (*p != '\0' && *p != '/' && !qemu_isspace(*p))
2432 memcpy(cmdname, pstart, len);
2433 cmdname[len] = '\0';
2438 * Read key of 'type' into 'key' and return the current
2441 static char *key_get_info(const char *type, char **key)
2449 p = strchr(type, ':');
2456 str = g_malloc(len + 1);
2457 memcpy(str, type, len);
2464 static int default_fmt_format = 'x';
2465 static int default_fmt_size = 4;
2467 static int is_valid_option(const char *c, const char *typestr)
2475 typestr = strstr(typestr, option);
2476 return (typestr != NULL);
2479 static const mon_cmd_t *search_dispatch_table(const mon_cmd_t *disp_table,
2480 const char *cmdname)
2482 const mon_cmd_t *cmd;
2484 for (cmd = disp_table; cmd->name != NULL; cmd++) {
2485 if (compare_cmd(cmdname, cmd->name)) {
2493 static const mon_cmd_t *qmp_find_cmd(const char *cmdname)
2495 return search_dispatch_table(qmp_cmds, cmdname);
2499 * Parse command name from @cmdp according to command table @table.
2500 * If blank, return NULL.
2501 * Else, if no valid command can be found, report to @mon, and return
2503 * Else, change @cmdp to point right behind the name, and return its
2504 * command table entry.
2505 * Do not assume the return value points into @table! It doesn't when
2506 * the command is found in a sub-command table.
2508 static const mon_cmd_t *monitor_parse_command(Monitor *mon,
2513 const mon_cmd_t *cmd;
2516 /* extract the command name */
2517 p = get_command_name(*cmdp, cmdname, sizeof(cmdname));
2521 cmd = search_dispatch_table(table, cmdname);
2523 monitor_printf(mon, "unknown command: '%.*s'\n",
2524 (int)(p - *cmdp), *cmdp);
2528 /* filter out following useless space */
2529 while (qemu_isspace(*p)) {
2534 /* search sub command */
2535 if (cmd->sub_table != NULL && *p != '\0') {
2536 return monitor_parse_command(mon, cmdp, cmd->sub_table);
2543 * Parse arguments for @cmd.
2544 * If it can't be parsed, report to @mon, and return NULL.
2545 * Else, insert command arguments into a QDict, and return it.
2546 * Note: On success, caller has to free the QDict structure.
2549 static QDict *monitor_parse_arguments(Monitor *mon,
2551 const mon_cmd_t *cmd)
2553 const char *typestr;
2556 const char *p = *endp;
2558 QDict *qdict = qdict_new();
2560 /* parse the parameters */
2561 typestr = cmd->args_type;
2563 typestr = key_get_info(typestr, &key);
2575 while (qemu_isspace(*p))
2577 if (*typestr == '?') {
2580 /* no optional string: NULL argument */
2584 ret = get_str(buf, sizeof(buf), &p);
2588 monitor_printf(mon, "%s: filename expected\n",
2592 monitor_printf(mon, "%s: block device name expected\n",
2596 monitor_printf(mon, "%s: string expected\n", cmd->name);
2601 qdict_put(qdict, key, qstring_from_str(buf));
2606 QemuOptsList *opts_list;
2609 opts_list = qemu_find_opts(key);
2610 if (!opts_list || opts_list->desc->name) {
2613 while (qemu_isspace(*p)) {
2618 if (get_str(buf, sizeof(buf), &p) < 0) {
2621 opts = qemu_opts_parse_noisily(opts_list, buf, true);
2625 qemu_opts_to_qdict(opts, qdict);
2626 qemu_opts_del(opts);
2631 int count, format, size;
2633 while (qemu_isspace(*p))
2639 if (qemu_isdigit(*p)) {
2641 while (qemu_isdigit(*p)) {
2642 count = count * 10 + (*p - '0');
2680 if (*p != '\0' && !qemu_isspace(*p)) {
2681 monitor_printf(mon, "invalid char in format: '%c'\n",
2686 format = default_fmt_format;
2687 if (format != 'i') {
2688 /* for 'i', not specifying a size gives -1 as size */
2690 size = default_fmt_size;
2691 default_fmt_size = size;
2693 default_fmt_format = format;
2696 format = default_fmt_format;
2697 if (format != 'i') {
2698 size = default_fmt_size;
2703 qdict_put(qdict, "count", qint_from_int(count));
2704 qdict_put(qdict, "format", qint_from_int(format));
2705 qdict_put(qdict, "size", qint_from_int(size));
2714 while (qemu_isspace(*p))
2716 if (*typestr == '?' || *typestr == '.') {
2717 if (*typestr == '?') {
2725 while (qemu_isspace(*p))
2734 if (get_expr(mon, &val, &p))
2736 /* Check if 'i' is greater than 32-bit */
2737 if ((c == 'i') && ((val >> 32) & 0xffffffff)) {
2738 monitor_printf(mon, "\'%s\' has failed: ", cmd->name);
2739 monitor_printf(mon, "integer is for 32-bit values\n");
2741 } else if (c == 'M') {
2743 monitor_printf(mon, "enter a positive value\n");
2748 qdict_put(qdict, key, qint_from_int(val));
2756 while (qemu_isspace(*p)) {
2759 if (*typestr == '?') {
2765 val = qemu_strtosz(p, &end);
2767 monitor_printf(mon, "invalid size\n");
2770 qdict_put(qdict, key, qint_from_int(val));
2778 while (qemu_isspace(*p))
2780 if (*typestr == '?') {
2786 if (get_double(mon, &val, &p) < 0) {
2789 if (p[0] && p[1] == 's') {
2792 val /= 1e3; p += 2; break;
2794 val /= 1e6; p += 2; break;
2796 val /= 1e9; p += 2; break;
2799 if (*p && !qemu_isspace(*p)) {
2800 monitor_printf(mon, "Unknown unit suffix\n");
2803 qdict_put(qdict, key, qfloat_from_double(val));
2811 while (qemu_isspace(*p)) {
2815 while (qemu_isgraph(*p)) {
2818 if (p - beg == 2 && !memcmp(beg, "on", p - beg)) {
2820 } else if (p - beg == 3 && !memcmp(beg, "off", p - beg)) {
2823 monitor_printf(mon, "Expected 'on' or 'off'\n");
2826 qdict_put(qdict, key, qbool_from_bool(val));
2831 const char *tmp = p;
2838 while (qemu_isspace(*p))
2843 if(!is_valid_option(p, typestr)) {
2845 monitor_printf(mon, "%s: unsupported option -%c\n",
2857 qdict_put(qdict, key, qbool_from_bool(true));
2864 /* package all remaining string */
2867 while (qemu_isspace(*p)) {
2870 if (*typestr == '?') {
2873 /* no remaining string: NULL argument */
2879 monitor_printf(mon, "%s: string expected\n",
2883 qdict_put(qdict, key, qstring_from_str(p));
2889 monitor_printf(mon, "%s: unknown type '%c'\n", cmd->name, c);
2895 /* check that all arguments were parsed */
2896 while (qemu_isspace(*p))
2899 monitor_printf(mon, "%s: extraneous characters at the end of line\n",
2912 static void handle_hmp_command(Monitor *mon, const char *cmdline)
2915 const mon_cmd_t *cmd;
2917 cmd = monitor_parse_command(mon, &cmdline, mon->cmd_table);
2922 qdict = monitor_parse_arguments(mon, &cmdline, cmd);
2924 monitor_printf(mon, "Try \"help %s\" for more information\n",
2929 cmd->mhandler.cmd(mon, qdict);
2933 static void cmd_completion(Monitor *mon, const char *name, const char *list)
2935 const char *p, *pstart;
2944 p = pstart + strlen(pstart);
2946 if (len > sizeof(cmd) - 2)
2947 len = sizeof(cmd) - 2;
2948 memcpy(cmd, pstart, len);
2950 if (name[0] == '\0' || !strncmp(name, cmd, strlen(name))) {
2951 readline_add_completion(mon->rs, cmd);
2959 static void file_completion(Monitor *mon, const char *input)
2964 char file[1024], file_prefix[1024];
2968 p = strrchr(input, '/');
2971 pstrcpy(file_prefix, sizeof(file_prefix), input);
2972 pstrcpy(path, sizeof(path), ".");
2974 input_path_len = p - input + 1;
2975 memcpy(path, input, input_path_len);
2976 if (input_path_len > sizeof(path) - 1)
2977 input_path_len = sizeof(path) - 1;
2978 path[input_path_len] = '\0';
2979 pstrcpy(file_prefix, sizeof(file_prefix), p + 1);
2982 ffs = opendir(path);
2991 if (strcmp(d->d_name, ".") == 0 || strcmp(d->d_name, "..") == 0) {
2995 if (strstart(d->d_name, file_prefix, NULL)) {
2996 memcpy(file, input, input_path_len);
2997 if (input_path_len < sizeof(file))
2998 pstrcpy(file + input_path_len, sizeof(file) - input_path_len,
3000 /* stat the file to find out if it's a directory.
3001 * In that case add a slash to speed up typing long paths
3003 if (stat(file, &sb) == 0 && S_ISDIR(sb.st_mode)) {
3004 pstrcat(file, sizeof(file), "/");
3006 readline_add_completion(mon->rs, file);
3012 static const char *next_arg_type(const char *typestr)
3014 const char *p = strchr(typestr, ':');
3015 return (p != NULL ? ++p : typestr);
3018 static void add_completion_option(ReadLineState *rs, const char *str,
3021 if (!str || !option) {
3024 if (!strncmp(option, str, strlen(str))) {
3025 readline_add_completion(rs, option);
3029 void chardev_add_completion(ReadLineState *rs, int nb_args, const char *str)
3032 ChardevBackendInfoList *list, *start;
3038 readline_set_completion_index(rs, len);
3040 start = list = qmp_query_chardev_backends(NULL);
3042 const char *chr_name = list->value->name;
3044 if (!strncmp(chr_name, str, len)) {
3045 readline_add_completion(rs, chr_name);
3049 qapi_free_ChardevBackendInfoList(start);
3052 void netdev_add_completion(ReadLineState *rs, int nb_args, const char *str)
3061 readline_set_completion_index(rs, len);
3062 for (i = 0; NetClientOptionsKind_lookup[i]; i++) {
3063 add_completion_option(rs, str, NetClientOptionsKind_lookup[i]);
3067 void device_add_completion(ReadLineState *rs, int nb_args, const char *str)
3077 readline_set_completion_index(rs, len);
3078 list = elt = object_class_get_list(TYPE_DEVICE, false);
3081 DeviceClass *dc = OBJECT_CLASS_CHECK(DeviceClass, elt->data,
3083 name = object_class_get_name(OBJECT_CLASS(dc));
3085 if (!dc->cannot_instantiate_with_device_add_yet
3086 && !strncmp(name, str, len)) {
3087 readline_add_completion(rs, name);
3094 void object_add_completion(ReadLineState *rs, int nb_args, const char *str)
3104 readline_set_completion_index(rs, len);
3105 list = elt = object_class_get_list(TYPE_USER_CREATABLE, false);
3109 name = object_class_get_name(OBJECT_CLASS(elt->data));
3110 if (!strncmp(name, str, len) && strcmp(name, TYPE_USER_CREATABLE)) {
3111 readline_add_completion(rs, name);
3118 static void peripheral_device_del_completion(ReadLineState *rs,
3119 const char *str, size_t len)
3121 Object *peripheral = container_get(qdev_get_machine(), "/peripheral");
3122 GSList *list, *item;
3124 list = qdev_build_hotpluggable_device_list(peripheral);
3129 for (item = list; item; item = g_slist_next(item)) {
3130 DeviceState *dev = item->data;
3132 if (dev->id && !strncmp(str, dev->id, len)) {
3133 readline_add_completion(rs, dev->id);
3140 void chardev_remove_completion(ReadLineState *rs, int nb_args, const char *str)
3143 ChardevInfoList *list, *start;
3149 readline_set_completion_index(rs, len);
3151 start = list = qmp_query_chardev(NULL);
3153 ChardevInfo *chr = list->value;
3155 if (!strncmp(chr->label, str, len)) {
3156 readline_add_completion(rs, chr->label);
3160 qapi_free_ChardevInfoList(start);
3163 static void ringbuf_completion(ReadLineState *rs, const char *str)
3166 ChardevInfoList *list, *start;
3169 readline_set_completion_index(rs, len);
3171 start = list = qmp_query_chardev(NULL);
3173 ChardevInfo *chr_info = list->value;
3175 if (!strncmp(chr_info->label, str, len)) {
3176 CharDriverState *chr = qemu_chr_find(chr_info->label);
3177 if (chr && chr_is_ringbuf(chr)) {
3178 readline_add_completion(rs, chr_info->label);
3183 qapi_free_ChardevInfoList(start);
3186 void ringbuf_write_completion(ReadLineState *rs, int nb_args, const char *str)
3191 ringbuf_completion(rs, str);
3194 void device_del_completion(ReadLineState *rs, int nb_args, const char *str)
3203 readline_set_completion_index(rs, len);
3204 peripheral_device_del_completion(rs, str, len);
3207 void object_del_completion(ReadLineState *rs, int nb_args, const char *str)
3209 ObjectPropertyInfoList *list, *start;
3216 readline_set_completion_index(rs, len);
3218 start = list = qmp_qom_list("/objects", NULL);
3220 ObjectPropertyInfo *info = list->value;
3222 if (!strncmp(info->type, "child<", 5)
3223 && !strncmp(info->name, str, len)) {
3224 readline_add_completion(rs, info->name);
3228 qapi_free_ObjectPropertyInfoList(start);
3231 void sendkey_completion(ReadLineState *rs, int nb_args, const char *str)
3240 sep = strrchr(str, '-');
3245 readline_set_completion_index(rs, len);
3246 for (i = 0; i < Q_KEY_CODE__MAX; i++) {
3247 if (!strncmp(str, QKeyCode_lookup[i], len)) {
3248 readline_add_completion(rs, QKeyCode_lookup[i]);
3253 void set_link_completion(ReadLineState *rs, int nb_args, const char *str)
3258 readline_set_completion_index(rs, len);
3260 NetClientState *ncs[MAX_QUEUE_NUM];
3262 count = qemu_find_net_clients_except(NULL, ncs,
3263 NET_CLIENT_OPTIONS_KIND_NONE,
3265 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3266 const char *name = ncs[i]->name;
3267 if (!strncmp(str, name, len)) {
3268 readline_add_completion(rs, name);
3271 } else if (nb_args == 3) {
3272 add_completion_option(rs, str, "on");
3273 add_completion_option(rs, str, "off");
3277 void netdev_del_completion(ReadLineState *rs, int nb_args, const char *str)
3280 NetClientState *ncs[MAX_QUEUE_NUM];
3287 readline_set_completion_index(rs, len);
3288 count = qemu_find_net_clients_except(NULL, ncs, NET_CLIENT_OPTIONS_KIND_NIC,
3290 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3292 const char *name = ncs[i]->name;
3293 if (strncmp(str, name, len)) {
3296 opts = qemu_opts_find(qemu_find_opts_err("netdev", NULL), name);
3298 readline_add_completion(rs, name);
3303 void trace_event_completion(ReadLineState *rs, int nb_args, const char *str)
3308 readline_set_completion_index(rs, len);
3311 for (id = 0; id < trace_event_count(); id++) {
3312 const char *event_name = trace_event_get_name(trace_event_id(id));
3313 if (!strncmp(str, event_name, len)) {
3314 readline_add_completion(rs, event_name);
3317 } else if (nb_args == 3) {
3318 add_completion_option(rs, str, "on");
3319 add_completion_option(rs, str, "off");
3323 void watchdog_action_completion(ReadLineState *rs, int nb_args, const char *str)
3330 readline_set_completion_index(rs, strlen(str));
3331 for (i = 0; WatchdogExpirationAction_lookup[i]; i++) {
3332 add_completion_option(rs, str, WatchdogExpirationAction_lookup[i]);
3336 void migrate_set_capability_completion(ReadLineState *rs, int nb_args,
3342 readline_set_completion_index(rs, len);
3345 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
3346 const char *name = MigrationCapability_lookup[i];
3347 if (!strncmp(str, name, len)) {
3348 readline_add_completion(rs, name);
3351 } else if (nb_args == 3) {
3352 add_completion_option(rs, str, "on");
3353 add_completion_option(rs, str, "off");
3357 void migrate_set_parameter_completion(ReadLineState *rs, int nb_args,
3363 readline_set_completion_index(rs, len);
3366 for (i = 0; i < MIGRATION_PARAMETER__MAX; i++) {
3367 const char *name = MigrationParameter_lookup[i];
3368 if (!strncmp(str, name, len)) {
3369 readline_add_completion(rs, name);
3375 void host_net_add_completion(ReadLineState *rs, int nb_args, const char *str)
3383 readline_set_completion_index(rs, len);
3384 for (i = 0; host_net_devices[i]; i++) {
3385 if (!strncmp(host_net_devices[i], str, len)) {
3386 readline_add_completion(rs, host_net_devices[i]);
3391 void host_net_remove_completion(ReadLineState *rs, int nb_args, const char *str)
3393 NetClientState *ncs[MAX_QUEUE_NUM];
3397 readline_set_completion_index(rs, len);
3399 count = qemu_find_net_clients_except(NULL, ncs,
3400 NET_CLIENT_OPTIONS_KIND_NONE,
3402 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3406 if (net_hub_id_for_client(ncs[i], &id)) {
3409 snprintf(name, sizeof(name), "%d", id);
3410 if (!strncmp(str, name, len)) {
3411 readline_add_completion(rs, name);
3415 } else if (nb_args == 3) {
3416 count = qemu_find_net_clients_except(NULL, ncs,
3417 NET_CLIENT_OPTIONS_KIND_NIC,
3419 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3423 if (ncs[i]->info->type == NET_CLIENT_OPTIONS_KIND_HUBPORT ||
3424 net_hub_id_for_client(ncs[i], &id)) {
3427 name = ncs[i]->name;
3428 if (!strncmp(str, name, len)) {
3429 readline_add_completion(rs, name);
3436 static void vm_completion(ReadLineState *rs, const char *str)
3439 BlockDriverState *bs;
3440 BdrvNextIterator it;
3443 readline_set_completion_index(rs, len);
3445 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
3446 SnapshotInfoList *snapshots, *snapshot;
3447 AioContext *ctx = bdrv_get_aio_context(bs);
3450 aio_context_acquire(ctx);
3451 if (bdrv_can_snapshot(bs)) {
3452 ok = bdrv_query_snapshot_info_list(bs, &snapshots, NULL) == 0;
3454 aio_context_release(ctx);
3459 snapshot = snapshots;
3461 char *completion = snapshot->value->name;
3462 if (!strncmp(str, completion, len)) {
3463 readline_add_completion(rs, completion);
3465 completion = snapshot->value->id;
3466 if (!strncmp(str, completion, len)) {
3467 readline_add_completion(rs, completion);
3469 snapshot = snapshot->next;
3471 qapi_free_SnapshotInfoList(snapshots);
3476 void delvm_completion(ReadLineState *rs, int nb_args, const char *str)
3479 vm_completion(rs, str);
3483 void loadvm_completion(ReadLineState *rs, int nb_args, const char *str)
3486 vm_completion(rs, str);
3490 static void monitor_find_completion_by_table(Monitor *mon,
3491 const mon_cmd_t *cmd_table,
3495 const char *cmdname;
3497 const char *ptype, *str, *name;
3498 const mon_cmd_t *cmd;
3499 BlockBackend *blk = NULL;
3502 /* command completion */
3507 readline_set_completion_index(mon->rs, strlen(cmdname));
3508 for (cmd = cmd_table; cmd->name != NULL; cmd++) {
3509 cmd_completion(mon, cmdname, cmd->name);
3512 /* find the command */
3513 for (cmd = cmd_table; cmd->name != NULL; cmd++) {
3514 if (compare_cmd(args[0], cmd->name)) {
3522 if (cmd->sub_table) {
3523 /* do the job again */
3524 monitor_find_completion_by_table(mon, cmd->sub_table,
3525 &args[1], nb_args - 1);
3528 if (cmd->command_completion) {
3529 cmd->command_completion(mon->rs, nb_args, args[nb_args - 1]);
3533 ptype = next_arg_type(cmd->args_type);
3534 for(i = 0; i < nb_args - 2; i++) {
3535 if (*ptype != '\0') {
3536 ptype = next_arg_type(ptype);
3537 while (*ptype == '?')
3538 ptype = next_arg_type(ptype);
3541 str = args[nb_args - 1];
3542 while (*ptype == '-' && ptype[1] != '\0') {
3543 ptype = next_arg_type(ptype);
3547 /* file completion */
3548 readline_set_completion_index(mon->rs, strlen(str));
3549 file_completion(mon, str);
3552 /* block device name completion */
3553 readline_set_completion_index(mon->rs, strlen(str));
3554 while ((blk = blk_next(blk)) != NULL) {
3555 name = blk_name(blk);
3556 if (str[0] == '\0' ||
3557 !strncmp(name, str, strlen(str))) {
3558 readline_add_completion(mon->rs, name);
3564 if (!strcmp(cmd->name, "help|?")) {
3565 monitor_find_completion_by_table(mon, cmd_table,
3566 &args[1], nb_args - 1);
3575 static void monitor_find_completion(void *opaque,
3576 const char *cmdline)
3578 Monitor *mon = opaque;
3579 char *args[MAX_ARGS];
3582 /* 1. parse the cmdline */
3583 if (parse_cmdline(cmdline, &nb_args, args) < 0) {
3587 /* if the line ends with a space, it means we want to complete the
3589 len = strlen(cmdline);
3590 if (len > 0 && qemu_isspace(cmdline[len - 1])) {
3591 if (nb_args >= MAX_ARGS) {
3594 args[nb_args++] = g_strdup("");
3597 /* 2. auto complete according to args */
3598 monitor_find_completion_by_table(mon, mon->cmd_table, args, nb_args);
3601 free_cmdline_args(args, nb_args);
3604 static int monitor_can_read(void *opaque)
3606 Monitor *mon = opaque;
3608 return (mon->suspend_cnt == 0) ? 1 : 0;
3611 static bool invalid_qmp_mode(const Monitor *mon, const mon_cmd_t *cmd,
3614 bool is_cap = cmd->mhandler.cmd_new == qmp_capabilities;
3616 if (is_cap && mon->qmp.in_command_mode) {
3617 error_set(errp, ERROR_CLASS_COMMAND_NOT_FOUND,
3618 "Capabilities negotiation is already complete, command "
3619 "'%s' ignored", cmd->name);
3622 if (!is_cap && !mon->qmp.in_command_mode) {
3623 error_set(errp, ERROR_CLASS_COMMAND_NOT_FOUND,
3624 "Expecting capabilities negotiation with "
3625 "'qmp_capabilities' before command '%s'", cmd->name);
3632 * Argument validation rules:
3634 * 1. The argument must exist in cmd_args qdict
3635 * 2. The argument type must be the expected one
3637 * Special case: If the argument doesn't exist in cmd_args and
3638 * the QMP_ACCEPT_UNKNOWNS flag is set, then the
3639 * checking is skipped for it.
3641 static void check_client_args_type(const QDict *client_args,
3642 const QDict *cmd_args, int flags,
3645 const QDictEntry *ent;
3647 for (ent = qdict_first(client_args); ent;ent = qdict_next(client_args,ent)){
3650 const QObject *client_arg = qdict_entry_value(ent);
3651 const char *client_arg_name = qdict_entry_key(ent);
3653 obj = qdict_get(cmd_args, client_arg_name);
3655 if (flags & QMP_ACCEPT_UNKNOWNS) {
3656 /* handler accepts unknowns */
3659 /* client arg doesn't exist */
3660 error_setg(errp, QERR_INVALID_PARAMETER, client_arg_name);
3664 arg_type = qobject_to_qstring(obj);
3665 assert(arg_type != NULL);
3667 /* check if argument's type is correct */
3668 switch (qstring_get_str(arg_type)[0]) {
3672 if (qobject_type(client_arg) != QTYPE_QSTRING) {
3673 error_setg(errp, QERR_INVALID_PARAMETER_TYPE,
3674 client_arg_name, "string");
3682 if (qobject_type(client_arg) != QTYPE_QINT) {
3683 error_setg(errp, QERR_INVALID_PARAMETER_TYPE,
3684 client_arg_name, "int");
3689 if (qobject_type(client_arg) != QTYPE_QINT &&
3690 qobject_type(client_arg) != QTYPE_QFLOAT) {
3691 error_setg(errp, QERR_INVALID_PARAMETER_TYPE,
3692 client_arg_name, "number");
3698 if (qobject_type(client_arg) != QTYPE_QBOOL) {
3699 error_setg(errp, QERR_INVALID_PARAMETER_TYPE,
3700 client_arg_name, "bool");
3705 assert(flags & QMP_ACCEPT_UNKNOWNS);
3708 /* Any QObject can be passed. */
3713 * These types are not supported by QMP and thus are not
3714 * handled here. Fall through.
3723 * - Check if the client has passed all mandatory args
3724 * - Set special flags for argument validation
3726 static void check_mandatory_args(const QDict *cmd_args,
3727 const QDict *client_args, int *flags,
3730 const QDictEntry *ent;
3732 for (ent = qdict_first(cmd_args); ent; ent = qdict_next(cmd_args, ent)) {
3733 const char *cmd_arg_name = qdict_entry_key(ent);
3734 QString *type = qobject_to_qstring(qdict_entry_value(ent));
3735 assert(type != NULL);
3737 if (qstring_get_str(type)[0] == 'O') {
3738 assert((*flags & QMP_ACCEPT_UNKNOWNS) == 0);
3739 *flags |= QMP_ACCEPT_UNKNOWNS;
3740 } else if (qstring_get_str(type)[0] != '-' &&
3741 qstring_get_str(type)[1] != '?' &&
3742 !qdict_haskey(client_args, cmd_arg_name)) {
3743 error_setg(errp, QERR_MISSING_PARAMETER, cmd_arg_name);
3749 static QDict *qdict_from_args_type(const char *args_type)
3753 QString *key, *type, *cur_qs;
3755 assert(args_type != NULL);
3757 qdict = qdict_new();
3759 if (args_type == NULL || args_type[0] == '\0') {
3760 /* no args, empty qdict */
3764 key = qstring_new();
3765 type = qstring_new();
3770 switch (args_type[i]) {
3773 qdict_put(qdict, qstring_get_str(key), type);
3775 if (args_type[i] == '\0') {
3778 type = qstring_new(); /* qdict has ref */
3779 cur_qs = key = qstring_new();
3785 qstring_append_chr(cur_qs, args_type[i]);
3795 * Client argument checking rules:
3797 * 1. Client must provide all mandatory arguments
3798 * 2. Each argument provided by the client must be expected
3799 * 3. Each argument provided by the client must have the type expected
3802 static void qmp_check_client_args(const mon_cmd_t *cmd, QDict *client_args,
3809 cmd_args = qdict_from_args_type(cmd->args_type);
3812 check_mandatory_args(cmd_args, client_args, &flags, &err);
3817 check_client_args_type(client_args, cmd_args, flags, &err);
3820 error_propagate(errp, err);
3825 * Input object checking rules
3827 * 1. Input object must be a dict
3828 * 2. The "execute" key must exist
3829 * 3. The "execute" key must be a string
3830 * 4. If the "arguments" key exists, it must be a dict
3831 * 5. If the "id" key exists, it can be anything (ie. json-value)
3832 * 6. Any argument not listed above is considered invalid
3834 static QDict *qmp_check_input_obj(QObject *input_obj, Error **errp)
3836 const QDictEntry *ent;
3837 int has_exec_key = 0;
3840 if (qobject_type(input_obj) != QTYPE_QDICT) {
3841 error_setg(errp, QERR_QMP_BAD_INPUT_OBJECT, "object");
3845 input_dict = qobject_to_qdict(input_obj);
3847 for (ent = qdict_first(input_dict); ent; ent = qdict_next(input_dict, ent)){
3848 const char *arg_name = qdict_entry_key(ent);
3849 const QObject *arg_obj = qdict_entry_value(ent);
3851 if (!strcmp(arg_name, "execute")) {
3852 if (qobject_type(arg_obj) != QTYPE_QSTRING) {
3853 error_setg(errp, QERR_QMP_BAD_INPUT_OBJECT_MEMBER,
3854 "execute", "string");
3858 } else if (!strcmp(arg_name, "arguments")) {
3859 if (qobject_type(arg_obj) != QTYPE_QDICT) {
3860 error_setg(errp, QERR_QMP_BAD_INPUT_OBJECT_MEMBER,
3861 "arguments", "object");
3864 } else if (!strcmp(arg_name, "id")) {
3865 /* Any string is acceptable as "id", so nothing to check */
3867 error_setg(errp, QERR_QMP_EXTRA_MEMBER, arg_name);
3872 if (!has_exec_key) {
3873 error_setg(errp, QERR_QMP_BAD_INPUT_OBJECT, "execute");
3880 static void handle_qmp_command(JSONMessageParser *parser, GQueue *tokens)
3882 Error *local_err = NULL;
3883 QObject *obj, *data;
3884 QDict *input, *args;
3885 const mon_cmd_t *cmd;
3886 const char *cmd_name;
3887 Monitor *mon = cur_mon;
3889 args = input = NULL;
3892 obj = json_parser_parse(tokens, NULL);
3894 // FIXME: should be triggered in json_parser_parse()
3895 error_setg(&local_err, QERR_JSON_PARSING);
3899 input = qmp_check_input_obj(obj, &local_err);
3901 qobject_decref(obj);
3905 mon->qmp.id = qdict_get(input, "id");
3906 qobject_incref(mon->qmp.id);
3908 cmd_name = qdict_get_str(input, "execute");
3909 trace_handle_qmp_command(mon, cmd_name);
3910 cmd = qmp_find_cmd(cmd_name);
3912 error_set(&local_err, ERROR_CLASS_COMMAND_NOT_FOUND,
3913 "The command %s has not been found", cmd_name);
3916 if (invalid_qmp_mode(mon, cmd, &local_err)) {
3920 obj = qdict_get(input, "arguments");
3924 args = qobject_to_qdict(obj);
3928 qmp_check_client_args(cmd, args, &local_err);
3933 cmd->mhandler.cmd_new(args, &data, &local_err);
3936 monitor_protocol_emitter(mon, data, local_err);
3937 qobject_decref(data);
3938 error_free(local_err);
3943 static void monitor_qmp_read(void *opaque, const uint8_t *buf, int size)
3945 Monitor *old_mon = cur_mon;
3949 json_message_parser_feed(&cur_mon->qmp.parser, (const char *) buf, size);
3954 static void monitor_read(void *opaque, const uint8_t *buf, int size)
3956 Monitor *old_mon = cur_mon;
3962 for (i = 0; i < size; i++)
3963 readline_handle_byte(cur_mon->rs, buf[i]);
3965 if (size == 0 || buf[size - 1] != 0)
3966 monitor_printf(cur_mon, "corrupted command\n");
3968 handle_hmp_command(cur_mon, (char *)buf);
3974 static void monitor_command_cb(void *opaque, const char *cmdline,
3975 void *readline_opaque)
3977 Monitor *mon = opaque;
3979 monitor_suspend(mon);
3980 handle_hmp_command(mon, cmdline);
3981 monitor_resume(mon);
3984 int monitor_suspend(Monitor *mon)
3992 void monitor_resume(Monitor *mon)
3996 if (--mon->suspend_cnt == 0)
3997 readline_show_prompt(mon->rs);
4000 static QObject *get_qmp_greeting(void)
4002 QObject *ver = NULL;
4004 qmp_marshal_query_version(NULL, &ver, NULL);
4005 return qobject_from_jsonf("{'QMP':{'version': %p,'capabilities': []}}",ver);
4008 static void monitor_qmp_event(void *opaque, int event)
4011 Monitor *mon = opaque;
4014 case CHR_EVENT_OPENED:
4015 mon->qmp.in_command_mode = false;
4016 data = get_qmp_greeting();
4017 monitor_json_emitter(mon, data);
4018 qobject_decref(data);
4021 case CHR_EVENT_CLOSED:
4022 json_message_parser_destroy(&mon->qmp.parser);
4023 json_message_parser_init(&mon->qmp.parser, handle_qmp_command);
4025 monitor_fdsets_cleanup();
4030 static void monitor_event(void *opaque, int event)
4032 Monitor *mon = opaque;
4035 case CHR_EVENT_MUX_IN:
4036 qemu_mutex_lock(&mon->out_lock);
4038 qemu_mutex_unlock(&mon->out_lock);
4039 if (mon->reset_seen) {
4040 readline_restart(mon->rs);
4041 monitor_resume(mon);
4044 mon->suspend_cnt = 0;
4048 case CHR_EVENT_MUX_OUT:
4049 if (mon->reset_seen) {
4050 if (mon->suspend_cnt == 0) {
4051 monitor_printf(mon, "\n");
4054 monitor_suspend(mon);
4058 qemu_mutex_lock(&mon->out_lock);
4060 qemu_mutex_unlock(&mon->out_lock);
4063 case CHR_EVENT_OPENED:
4064 monitor_printf(mon, "QEMU %s monitor - type 'help' for more "
4065 "information\n", QEMU_VERSION);
4066 if (!mon->mux_out) {
4067 readline_restart(mon->rs);
4068 readline_show_prompt(mon->rs);
4070 mon->reset_seen = 1;
4074 case CHR_EVENT_CLOSED:
4076 monitor_fdsets_cleanup();
4082 compare_mon_cmd(const void *a, const void *b)
4084 return strcmp(((const mon_cmd_t *)a)->name,
4085 ((const mon_cmd_t *)b)->name);
4088 static void sortcmdlist(void)
4091 int elem_size = sizeof(mon_cmd_t);
4093 array_num = sizeof(mon_cmds)/elem_size-1;
4094 qsort((void *)mon_cmds, array_num, elem_size, compare_mon_cmd);
4096 array_num = sizeof(info_cmds)/elem_size-1;
4097 qsort((void *)info_cmds, array_num, elem_size, compare_mon_cmd);
4109 /* These functions just adapt the readline interface in a typesafe way. We
4110 * could cast function pointers but that discards compiler checks.
4112 static void GCC_FMT_ATTR(2, 3) monitor_readline_printf(void *opaque,
4113 const char *fmt, ...)
4117 monitor_vprintf(opaque, fmt, ap);
4121 static void monitor_readline_flush(void *opaque)
4123 monitor_flush(opaque);
4126 static void __attribute__((constructor)) monitor_lock_init(void)
4128 qemu_mutex_init(&monitor_lock);
4131 void monitor_init(CharDriverState *chr, int flags)
4133 static int is_first_init = 1;
4136 if (is_first_init) {
4137 monitor_qapi_event_init();
4142 mon = g_malloc(sizeof(*mon));
4143 monitor_data_init(mon);
4147 if (flags & MONITOR_USE_READLINE) {
4148 mon->rs = readline_init(monitor_readline_printf,
4149 monitor_readline_flush,
4151 monitor_find_completion);
4152 monitor_read_command(mon, 0);
4155 if (monitor_is_qmp(mon)) {
4156 qemu_chr_add_handlers(chr, monitor_can_read, monitor_qmp_read,
4157 monitor_qmp_event, mon);
4158 qemu_chr_fe_set_echo(chr, true);
4159 json_message_parser_init(&mon->qmp.parser, handle_qmp_command);
4161 qemu_chr_add_handlers(chr, monitor_can_read, monitor_read,
4162 monitor_event, mon);
4165 qemu_mutex_lock(&monitor_lock);
4166 QLIST_INSERT_HEAD(&mon_list, mon, entry);
4167 qemu_mutex_unlock(&monitor_lock);
4170 static void bdrv_password_cb(void *opaque, const char *password,
4171 void *readline_opaque)
4173 Monitor *mon = opaque;
4174 BlockDriverState *bs = readline_opaque;
4176 Error *local_err = NULL;
4178 bdrv_add_key(bs, password, &local_err);
4180 error_report_err(local_err);
4183 if (mon->password_completion_cb)
4184 mon->password_completion_cb(mon->password_opaque, ret);
4186 monitor_read_command(mon, 1);
4189 int monitor_read_bdrv_key_start(Monitor *mon, BlockDriverState *bs,
4190 BlockCompletionFunc *completion_cb,
4195 monitor_printf(mon, "%s (%s) is encrypted.\n", bdrv_get_device_name(bs),
4196 bdrv_get_encrypted_filename(bs));
4198 mon->password_completion_cb = completion_cb;
4199 mon->password_opaque = opaque;
4201 err = monitor_read_password(mon, bdrv_password_cb, bs);
4203 if (err && completion_cb)
4204 completion_cb(opaque, err);
4209 int monitor_read_block_device_key(Monitor *mon, const char *device,
4210 BlockCompletionFunc *completion_cb,
4216 blk = blk_by_name(device);
4218 monitor_printf(mon, "Device not found %s\n", device);
4222 monitor_printf(mon, "Device '%s' has no medium\n", device);
4226 bdrv_add_key(blk_bs(blk), NULL, &err);
4229 return monitor_read_bdrv_key_start(mon, blk_bs(blk), completion_cb, opaque);
4232 if (completion_cb) {
4233 completion_cb(opaque, 0);
4238 QemuOptsList qemu_mon_opts = {
4240 .implied_opt_name = "chardev",
4241 .head = QTAILQ_HEAD_INITIALIZER(qemu_mon_opts.head),
4245 .type = QEMU_OPT_STRING,
4248 .type = QEMU_OPT_STRING,
4251 .type = QEMU_OPT_BOOL,
4254 .type = QEMU_OPT_BOOL,
4256 { /* end of list */ }
4261 void qmp_rtc_reset_reinjection(Error **errp)
4263 error_setg(errp, QERR_FEATURE_DISABLED, "rtc-reset-reinjection");
4267 #ifndef TARGET_S390X
4268 void qmp_dump_skeys(const char *filename, Error **errp)
4270 error_setg(errp, QERR_FEATURE_DISABLED, "dump-skeys");
4275 GICCapabilityList *qmp_query_gic_capabilities(Error **errp)
4277 error_setg(errp, QERR_FEATURE_DISABLED, "query-gic-capabilities");
4282 HotpluggableCPUList *qmp_query_hotpluggable_cpus(Error **errp)
4284 MachineState *ms = MACHINE(qdev_get_machine());
4285 MachineClass *mc = MACHINE_GET_CLASS(ms);
4287 if (!mc->query_hotpluggable_cpus) {
4288 error_setg(errp, QERR_FEATURE_DISABLED, "query-hotpluggable-cpus");
4292 return mc->query_hotpluggable_cpus(ms);