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/types.h"
58 #include "qapi/qmp/qjson.h"
59 #include "qapi/qmp/json-streamer.h"
60 #include "qapi/qmp/json-parser.h"
61 #include "qom/object_interfaces.h"
64 #include "trace/control.h"
65 #include "monitor/hmp-target.h"
66 #ifdef CONFIG_TRACE_SIMPLE
67 #include "trace/simple.h"
69 #include "exec/memory.h"
70 #include "exec/exec-all.h"
72 #include "qmp-commands.h"
74 #include "qemu/thread.h"
75 #include "block/qapi.h"
76 #include "qapi/qmp-event.h"
77 #include "qapi-event.h"
78 #include "qmp-introspect.h"
79 #include "sysemu/block-backend.h"
80 #include "sysemu/qtest.h"
81 #include "qemu/cutils.h"
82 #include "qapi/qmp/dispatch.h"
84 #if defined(TARGET_S390X)
85 #include "hw/s390x/storage-keys.h"
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
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
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')
117 * user mode accepts "on" or "off"
118 * '-' optional parameter (eg. '-f')
122 typedef struct mon_cmd_t {
124 const char *args_type;
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);
136 /* file descriptors passed via SCM_RIGHTS */
137 typedef struct mon_fd_t mon_fd_t;
141 QLIST_ENTRY(mon_fd_t) next;
144 /* file descriptor associated with a file descriptor set */
145 typedef struct MonFdsetFd MonFdsetFd;
150 QLIST_ENTRY(MonFdsetFd) next;
153 /* file descriptor set containing fds passed via SCM_RIGHTS */
154 typedef struct MonFdset MonFdset;
157 QLIST_HEAD(, MonFdsetFd) fds;
158 QLIST_HEAD(, MonFdsetFd) dup_fds;
159 QLIST_ENTRY(MonFdset) next;
163 JSONMessageParser parser;
165 * When a client connects, we're in capabilities negotiation mode.
166 * When command qmp_capabilities succeeds, we go into command
169 bool in_command_mode; /* are we in command mode? */
173 * To prevent flooding clients, events can be throttled. The
174 * throttling is calculated globally, rather than per-Monitor
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;
185 int64_t rate; /* Minimum time (in ns) between two events */
186 } MonitorQAPIEventConf;
189 CharDriverState *chr;
199 /* Read under either BQL or out_lock, written with BQL+out_lock. */
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[];
227 static QEMUClockType event_clock_type = QEMU_CLOCK_REALTIME;
229 static void monitor_command_cb(void *opaque, const char *cmdline,
230 void *readline_opaque);
233 * Is @mon a QMP monitor?
235 static inline bool monitor_is_qmp(const Monitor *mon)
237 return (mon->flags & MONITOR_USE_CONTROL);
241 * Is the current monitor, if any, a QMP monitor?
243 bool monitor_cur_is_qmp(void)
245 return cur_mon && monitor_is_qmp(cur_mon);
248 void monitor_read_command(Monitor *mon, int show_prompt)
253 readline_start(mon->rs, "(qemu) ", 0, monitor_command_cb, NULL);
255 readline_show_prompt(mon->rs);
258 int monitor_read_password(Monitor *mon, ReadLineFunc *readline_func,
262 readline_start(mon->rs, "Password: ", 1, readline_func, opaque);
263 /* prompt is printed on return from the command handler */
266 monitor_printf(mon, "terminal does not support password prompting\n");
271 static void monitor_flush_locked(Monitor *mon);
273 static gboolean monitor_unblocked(GIOChannel *chan, GIOCondition cond,
276 Monitor *mon = opaque;
278 qemu_mutex_lock(&mon->out_lock);
280 monitor_flush_locked(mon);
281 qemu_mutex_unlock(&mon->out_lock);
285 /* Called with mon->out_lock held. */
286 static void monitor_flush_locked(Monitor *mon)
292 if (mon->skip_flush) {
296 buf = qstring_get_str(mon->outbuf);
297 len = qstring_get_length(mon->outbuf);
299 if (len && !mon->mux_out) {
300 rc = qemu_chr_fe_write(mon->chr, (const uint8_t *) buf, len);
301 if ((rc < 0 && errno != EAGAIN) || (rc == len)) {
302 /* all flushed or error */
303 QDECREF(mon->outbuf);
304 mon->outbuf = qstring_new();
309 QString *tmp = qstring_from_str(buf + rc);
310 QDECREF(mon->outbuf);
313 if (mon->out_watch == 0) {
314 mon->out_watch = qemu_chr_fe_add_watch(mon->chr, G_IO_OUT|G_IO_HUP,
315 monitor_unblocked, mon);
320 void monitor_flush(Monitor *mon)
322 qemu_mutex_lock(&mon->out_lock);
323 monitor_flush_locked(mon);
324 qemu_mutex_unlock(&mon->out_lock);
327 /* flush at every end of line */
328 static void monitor_puts(Monitor *mon, const char *str)
332 qemu_mutex_lock(&mon->out_lock);
338 qstring_append_chr(mon->outbuf, '\r');
340 qstring_append_chr(mon->outbuf, c);
342 monitor_flush_locked(mon);
345 qemu_mutex_unlock(&mon->out_lock);
348 void monitor_vprintf(Monitor *mon, const char *fmt, va_list ap)
355 if (monitor_is_qmp(mon)) {
359 buf = g_strdup_vprintf(fmt, ap);
360 monitor_puts(mon, buf);
364 void monitor_printf(Monitor *mon, const char *fmt, ...)
368 monitor_vprintf(mon, fmt, ap);
372 int monitor_fprintf(FILE *stream, const char *fmt, ...)
376 monitor_vprintf((Monitor *)stream, fmt, ap);
381 static void monitor_json_emitter(Monitor *mon, const QObject *data)
385 json = mon->flags & MONITOR_USE_PRETTY ? qobject_to_json_pretty(data) :
386 qobject_to_json(data);
387 assert(json != NULL);
389 qstring_append_chr(json, '\n');
390 monitor_puts(mon, qstring_get_str(json));
395 static MonitorQAPIEventConf monitor_qapi_event_conf[QAPI_EVENT__MAX] = {
396 /* Limit guest-triggerable events to 1 per second */
397 [QAPI_EVENT_RTC_CHANGE] = { 1000 * SCALE_MS },
398 [QAPI_EVENT_WATCHDOG] = { 1000 * SCALE_MS },
399 [QAPI_EVENT_BALLOON_CHANGE] = { 1000 * SCALE_MS },
400 [QAPI_EVENT_QUORUM_REPORT_BAD] = { 1000 * SCALE_MS },
401 [QAPI_EVENT_QUORUM_FAILURE] = { 1000 * SCALE_MS },
402 [QAPI_EVENT_VSERPORT_CHANGE] = { 1000 * SCALE_MS },
405 GHashTable *monitor_qapi_event_state;
408 * Emits the event to every monitor instance, @event is only used for trace
409 * Called with monitor_lock held.
411 static void monitor_qapi_event_emit(QAPIEvent event, QDict *qdict)
415 trace_monitor_protocol_event_emit(event, qdict);
416 QLIST_FOREACH(mon, &mon_list, entry) {
417 if (monitor_is_qmp(mon) && mon->qmp.in_command_mode) {
418 monitor_json_emitter(mon, QOBJECT(qdict));
423 static void monitor_qapi_event_handler(void *opaque);
426 * Queue a new event for emission to Monitor instances,
427 * applying any rate limiting if required.
430 monitor_qapi_event_queue(QAPIEvent event, QDict *qdict, Error **errp)
432 MonitorQAPIEventConf *evconf;
433 MonitorQAPIEventState *evstate;
435 assert(event < QAPI_EVENT__MAX);
436 evconf = &monitor_qapi_event_conf[event];
437 trace_monitor_protocol_event_queue(event, qdict, evconf->rate);
439 qemu_mutex_lock(&monitor_lock);
442 /* Unthrottled event */
443 monitor_qapi_event_emit(event, qdict);
445 QDict *data = qobject_to_qdict(qdict_get(qdict, "data"));
446 MonitorQAPIEventState key = { .event = event, .data = data };
448 evstate = g_hash_table_lookup(monitor_qapi_event_state, &key);
449 assert(!evstate || timer_pending(evstate->timer));
453 * Timer is pending for (at least) evconf->rate ns after
454 * last send. Store event for sending when timer fires,
455 * replacing a prior stored event if any.
457 QDECREF(evstate->qdict);
458 evstate->qdict = qdict;
459 QINCREF(evstate->qdict);
462 * Last send was (at least) evconf->rate ns ago.
463 * Send immediately, and arm the timer to call
464 * monitor_qapi_event_handler() in evconf->rate ns. Any
465 * events arriving before then will be delayed until then.
467 int64_t now = qemu_clock_get_ns(event_clock_type);
469 monitor_qapi_event_emit(event, qdict);
471 evstate = g_new(MonitorQAPIEventState, 1);
472 evstate->event = event;
473 evstate->data = data;
474 QINCREF(evstate->data);
475 evstate->qdict = NULL;
476 evstate->timer = timer_new_ns(event_clock_type,
477 monitor_qapi_event_handler,
479 g_hash_table_add(monitor_qapi_event_state, evstate);
480 timer_mod_ns(evstate->timer, now + evconf->rate);
484 qemu_mutex_unlock(&monitor_lock);
488 * This function runs evconf->rate ns after sending a throttled
490 * If another event has since been stored, send it.
492 static void monitor_qapi_event_handler(void *opaque)
494 MonitorQAPIEventState *evstate = opaque;
495 MonitorQAPIEventConf *evconf = &monitor_qapi_event_conf[evstate->event];
497 trace_monitor_protocol_event_handler(evstate->event, evstate->qdict);
498 qemu_mutex_lock(&monitor_lock);
500 if (evstate->qdict) {
501 int64_t now = qemu_clock_get_ns(event_clock_type);
503 monitor_qapi_event_emit(evstate->event, evstate->qdict);
504 QDECREF(evstate->qdict);
505 evstate->qdict = NULL;
506 timer_mod_ns(evstate->timer, now + evconf->rate);
508 g_hash_table_remove(monitor_qapi_event_state, evstate);
509 QDECREF(evstate->data);
510 timer_free(evstate->timer);
514 qemu_mutex_unlock(&monitor_lock);
517 static unsigned int qapi_event_throttle_hash(const void *key)
519 const MonitorQAPIEventState *evstate = key;
520 unsigned int hash = evstate->event * 255;
522 if (evstate->event == QAPI_EVENT_VSERPORT_CHANGE) {
523 hash += g_str_hash(qdict_get_str(evstate->data, "id"));
526 if (evstate->event == QAPI_EVENT_QUORUM_REPORT_BAD) {
527 hash += g_str_hash(qdict_get_str(evstate->data, "node-name"));
533 static gboolean qapi_event_throttle_equal(const void *a, const void *b)
535 const MonitorQAPIEventState *eva = a;
536 const MonitorQAPIEventState *evb = b;
538 if (eva->event != evb->event) {
542 if (eva->event == QAPI_EVENT_VSERPORT_CHANGE) {
543 return !strcmp(qdict_get_str(eva->data, "id"),
544 qdict_get_str(evb->data, "id"));
547 if (eva->event == QAPI_EVENT_QUORUM_REPORT_BAD) {
548 return !strcmp(qdict_get_str(eva->data, "node-name"),
549 qdict_get_str(evb->data, "node-name"));
555 static void monitor_qapi_event_init(void)
557 if (qtest_enabled()) {
558 event_clock_type = QEMU_CLOCK_VIRTUAL;
561 monitor_qapi_event_state = g_hash_table_new(qapi_event_throttle_hash,
562 qapi_event_throttle_equal);
563 qmp_event_set_func_emit(monitor_qapi_event_queue);
566 void qmp_qmp_capabilities(Error **errp)
568 cur_mon->qmp.in_command_mode = true;
571 static void handle_hmp_command(Monitor *mon, const char *cmdline);
573 static void monitor_data_init(Monitor *mon)
575 memset(mon, 0, sizeof(Monitor));
576 qemu_mutex_init(&mon->out_lock);
577 mon->outbuf = qstring_new();
578 /* Use *mon_cmds by default. */
579 mon->cmd_table = mon_cmds;
582 static void monitor_data_destroy(Monitor *mon)
585 qemu_chr_add_handlers(mon->chr, NULL, NULL, NULL, NULL);
587 if (monitor_is_qmp(mon)) {
588 json_message_parser_destroy(&mon->qmp.parser);
591 QDECREF(mon->outbuf);
592 qemu_mutex_destroy(&mon->out_lock);
595 char *qmp_human_monitor_command(const char *command_line, bool has_cpu_index,
596 int64_t cpu_index, Error **errp)
599 Monitor *old_mon, hmp;
601 monitor_data_init(&hmp);
602 hmp.skip_flush = true;
608 int ret = monitor_set_cpu(cpu_index);
611 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cpu-index",
617 handle_hmp_command(&hmp, command_line);
620 qemu_mutex_lock(&hmp.out_lock);
621 if (qstring_get_length(hmp.outbuf) > 0) {
622 output = g_strdup(qstring_get_str(hmp.outbuf));
624 output = g_strdup("");
626 qemu_mutex_unlock(&hmp.out_lock);
629 monitor_data_destroy(&hmp);
633 static int compare_cmd(const char *name, const char *list)
635 const char *p, *pstart;
643 p = pstart + strlen(pstart);
644 if ((p - pstart) == len && !memcmp(pstart, name, len))
653 static int get_str(char *buf, int buf_size, const char **pp)
661 while (qemu_isspace(*p)) {
672 while (*p != '\0' && *p != '\"') {
688 printf("unsupported escape code: '\\%c'\n", c);
691 if ((q - buf) < buf_size - 1) {
695 if ((q - buf) < buf_size - 1) {
702 printf("unterminated string\n");
707 while (*p != '\0' && !qemu_isspace(*p)) {
708 if ((q - buf) < buf_size - 1) {
721 static void free_cmdline_args(char **args, int nb_args)
725 assert(nb_args <= MAX_ARGS);
727 for (i = 0; i < nb_args; i++) {
734 * Parse the command line to get valid args.
735 * @cmdline: command line to be parsed.
736 * @pnb_args: location to store the number of args, must NOT be NULL.
737 * @args: location to store the args, which should be freed by caller, must
740 * Returns 0 on success, negative on failure.
742 * NOTE: this parser is an approximate form of the real command parser. Number
743 * of args have a limit of MAX_ARGS. If cmdline contains more, it will
744 * return with failure.
746 static int parse_cmdline(const char *cmdline,
747 int *pnb_args, char **args)
756 while (qemu_isspace(*p)) {
762 if (nb_args >= MAX_ARGS) {
765 ret = get_str(buf, sizeof(buf), &p);
769 args[nb_args] = g_strdup(buf);
776 free_cmdline_args(args, nb_args);
780 static void help_cmd_dump_one(Monitor *mon,
781 const mon_cmd_t *cmd,
787 for (i = 0; i < prefix_args_nb; i++) {
788 monitor_printf(mon, "%s ", prefix_args[i]);
790 monitor_printf(mon, "%s %s -- %s\n", cmd->name, cmd->params, cmd->help);
793 /* @args[@arg_index] is the valid command need to find in @cmds */
794 static void help_cmd_dump(Monitor *mon, const mon_cmd_t *cmds,
795 char **args, int nb_args, int arg_index)
797 const mon_cmd_t *cmd;
799 /* No valid arg need to compare with, dump all in *cmds */
800 if (arg_index >= nb_args) {
801 for (cmd = cmds; cmd->name != NULL; cmd++) {
802 help_cmd_dump_one(mon, cmd, args, arg_index);
807 /* Find one entry to dump */
808 for (cmd = cmds; cmd->name != NULL; cmd++) {
809 if (compare_cmd(args[arg_index], cmd->name)) {
810 if (cmd->sub_table) {
811 /* continue with next arg */
812 help_cmd_dump(mon, cmd->sub_table,
813 args, nb_args, arg_index + 1);
815 help_cmd_dump_one(mon, cmd, args, arg_index);
822 static void help_cmd(Monitor *mon, const char *name)
824 char *args[MAX_ARGS];
827 /* 1. parse user input */
829 /* special case for log, directly dump and return */
830 if (!strcmp(name, "log")) {
831 const QEMULogItem *item;
832 monitor_printf(mon, "Log items (comma separated):\n");
833 monitor_printf(mon, "%-10s %s\n", "none", "remove all logs");
834 for (item = qemu_log_items; item->mask != 0; item++) {
835 monitor_printf(mon, "%-10s %s\n", item->name, item->help);
840 if (parse_cmdline(name, &nb_args, args) < 0) {
845 /* 2. dump the contents according to parsed args */
846 help_cmd_dump(mon, mon->cmd_table, args, nb_args, 0);
848 free_cmdline_args(args, nb_args);
851 static void do_help_cmd(Monitor *mon, const QDict *qdict)
853 help_cmd(mon, qdict_get_try_str(qdict, "name"));
856 static void hmp_trace_event(Monitor *mon, const QDict *qdict)
858 const char *tp_name = qdict_get_str(qdict, "name");
859 bool new_state = qdict_get_bool(qdict, "option");
860 bool has_vcpu = qdict_haskey(qdict, "vcpu");
861 int vcpu = qdict_get_try_int(qdict, "vcpu", 0);
862 Error *local_err = NULL;
865 monitor_printf(mon, "argument vcpu must be positive");
869 qmp_trace_event_set_state(tp_name, new_state, true, true, has_vcpu, vcpu, &local_err);
871 error_report_err(local_err);
875 #ifdef CONFIG_TRACE_SIMPLE
876 static void hmp_trace_file(Monitor *mon, const QDict *qdict)
878 const char *op = qdict_get_try_str(qdict, "op");
879 const char *arg = qdict_get_try_str(qdict, "arg");
882 st_print_trace_file_status((FILE *)mon, &monitor_fprintf);
883 } else if (!strcmp(op, "on")) {
884 st_set_trace_file_enabled(true);
885 } else if (!strcmp(op, "off")) {
886 st_set_trace_file_enabled(false);
887 } else if (!strcmp(op, "flush")) {
888 st_flush_trace_buffer();
889 } else if (!strcmp(op, "set")) {
891 st_set_trace_file(arg);
894 monitor_printf(mon, "unexpected argument \"%s\"\n", op);
895 help_cmd(mon, "trace-file");
900 static void hmp_info_help(Monitor *mon, const QDict *qdict)
902 help_cmd(mon, "info");
905 static void query_commands_cb(QmpCommand *cmd, void *opaque)
907 CommandInfoList *info, **list = opaque;
913 info = g_malloc0(sizeof(*info));
914 info->value = g_malloc0(sizeof(*info->value));
915 info->value->name = g_strdup(cmd->name);
920 CommandInfoList *qmp_query_commands(Error **errp)
922 CommandInfoList *list = NULL;
924 qmp_for_each_command(query_commands_cb, &list);
929 EventInfoList *qmp_query_events(Error **errp)
931 EventInfoList *info, *ev_list = NULL;
934 for (e = 0 ; e < QAPI_EVENT__MAX ; e++) {
935 const char *event_name = QAPIEvent_lookup[e];
936 assert(event_name != NULL);
937 info = g_malloc0(sizeof(*info));
938 info->value = g_malloc0(sizeof(*info->value));
939 info->value->name = g_strdup(event_name);
941 info->next = ev_list;
949 * Minor hack: generated marshalling suppressed for this command
950 * ('gen': false in the schema) so we can parse the JSON string
951 * directly into QObject instead of first parsing it with
952 * visit_type_SchemaInfoList() into a SchemaInfoList, then marshal it
953 * to QObject with generated output marshallers, every time. Instead,
954 * we do it in test-qmp-input-visitor.c, just to make sure
955 * qapi-introspect.py's output actually conforms to the schema.
957 static void qmp_query_qmp_schema(QDict *qdict, QObject **ret_data,
960 *ret_data = qobject_from_json(qmp_schema_json);
964 * We used to define commands in qmp-commands.hx in addition to the
965 * QAPI schema. This permitted defining some of them only in certain
966 * configurations. query-commands has always reflected that (good,
967 * because it lets QMP clients figure out what's actually available),
968 * while query-qmp-schema never did (not so good). This function is a
969 * hack to keep the configuration-specific commands defined exactly as
970 * before, even though qmp-commands.hx is gone.
972 * FIXME Educate the QAPI schema on configuration-specific commands,
973 * and drop this hack.
975 static void qmp_unregister_commands_hack(void)
978 qmp_unregister_command("query-spice");
981 qmp_unregister_command("rtc-reset-reinjection");
984 qmp_unregister_command("dump-skeys");
987 qmp_unregister_command("query-gic-capabilities");
989 #if !defined(TARGET_S390X)
990 qmp_unregister_command("query-cpu-model-expansion");
991 qmp_unregister_command("query-cpu-model-baseline");
992 qmp_unregister_command("query-cpu-model-comparison");
994 #if !defined(TARGET_PPC) && !defined(TARGET_ARM) && !defined(TARGET_I386) \
995 && !defined(TARGET_S390X)
996 qmp_unregister_command("query-cpu-definitions");
1000 static void qmp_init_marshal(void)
1002 qmp_register_command("query-qmp-schema", qmp_query_qmp_schema,
1004 qmp_register_command("device_add", qmp_device_add,
1006 qmp_register_command("netdev_add", qmp_netdev_add,
1009 /* call it after the rest of qapi_init() */
1010 register_module_init(qmp_unregister_commands_hack, MODULE_INIT_QAPI);
1013 qapi_init(qmp_init_marshal);
1015 /* set the current CPU defined by the user */
1016 int monitor_set_cpu(int cpu_index)
1020 cpu = qemu_get_cpu(cpu_index);
1024 cur_mon->mon_cpu = cpu;
1028 CPUState *mon_get_cpu(void)
1030 if (!cur_mon->mon_cpu) {
1031 monitor_set_cpu(first_cpu->cpu_index);
1033 cpu_synchronize_state(cur_mon->mon_cpu);
1034 return cur_mon->mon_cpu;
1037 CPUArchState *mon_get_cpu_env(void)
1039 return mon_get_cpu()->env_ptr;
1042 int monitor_get_cpu_index(void)
1044 return mon_get_cpu()->cpu_index;
1047 static void hmp_info_registers(Monitor *mon, const QDict *qdict)
1049 cpu_dump_state(mon_get_cpu(), (FILE *)mon, monitor_fprintf, CPU_DUMP_FPU);
1052 static void hmp_info_jit(Monitor *mon, const QDict *qdict)
1054 dump_exec_info((FILE *)mon, monitor_fprintf);
1055 dump_drift_info((FILE *)mon, monitor_fprintf);
1058 static void hmp_info_opcount(Monitor *mon, const QDict *qdict)
1060 dump_opcount_info((FILE *)mon, monitor_fprintf);
1063 static void hmp_info_history(Monitor *mon, const QDict *qdict)
1072 str = readline_get_history(mon->rs, i);
1075 monitor_printf(mon, "%d: '%s'\n", i, str);
1080 static void hmp_info_cpustats(Monitor *mon, const QDict *qdict)
1082 cpu_dump_statistics(mon_get_cpu(), (FILE *)mon, &monitor_fprintf, 0);
1085 static void hmp_info_trace_events(Monitor *mon, const QDict *qdict)
1087 const char *name = qdict_get_try_str(qdict, "name");
1088 bool has_vcpu = qdict_haskey(qdict, "vcpu");
1089 int vcpu = qdict_get_try_int(qdict, "vcpu", 0);
1090 TraceEventInfoList *events;
1091 TraceEventInfoList *elem;
1092 Error *local_err = NULL;
1098 monitor_printf(mon, "argument vcpu must be positive");
1102 events = qmp_trace_event_get_state(name, has_vcpu, vcpu, &local_err);
1104 error_report_err(local_err);
1108 for (elem = events; elem != NULL; elem = elem->next) {
1109 monitor_printf(mon, "%s : state %u\n",
1111 elem->value->state == TRACE_EVENT_STATE_ENABLED ? 1 : 0);
1113 qapi_free_TraceEventInfoList(events);
1116 void qmp_client_migrate_info(const char *protocol, const char *hostname,
1117 bool has_port, int64_t port,
1118 bool has_tls_port, int64_t tls_port,
1119 bool has_cert_subject, const char *cert_subject,
1122 if (strcmp(protocol, "spice") == 0) {
1123 if (!qemu_using_spice(errp)) {
1127 if (!has_port && !has_tls_port) {
1128 error_setg(errp, QERR_MISSING_PARAMETER, "port/tls-port");
1132 if (qemu_spice_migrate_info(hostname,
1133 has_port ? port : -1,
1134 has_tls_port ? tls_port : -1,
1136 error_setg(errp, QERR_UNDEFINED_ERROR);
1142 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "protocol", "spice");
1145 static void hmp_logfile(Monitor *mon, const QDict *qdict)
1149 qemu_set_log_filename(qdict_get_str(qdict, "filename"), &err);
1151 error_report_err(err);
1155 static void hmp_log(Monitor *mon, const QDict *qdict)
1158 const char *items = qdict_get_str(qdict, "items");
1160 if (!strcmp(items, "none")) {
1163 mask = qemu_str_to_log_mask(items);
1165 help_cmd(mon, "log");
1172 static void hmp_singlestep(Monitor *mon, const QDict *qdict)
1174 const char *option = qdict_get_try_str(qdict, "option");
1175 if (!option || !strcmp(option, "on")) {
1177 } else if (!strcmp(option, "off")) {
1180 monitor_printf(mon, "unexpected option %s\n", option);
1184 static void hmp_gdbserver(Monitor *mon, const QDict *qdict)
1186 const char *device = qdict_get_try_str(qdict, "device");
1188 device = "tcp::" DEFAULT_GDBSTUB_PORT;
1189 if (gdbserver_start(device) < 0) {
1190 monitor_printf(mon, "Could not open gdbserver on device '%s'\n",
1192 } else if (strcmp(device, "none") == 0) {
1193 monitor_printf(mon, "Disabled gdbserver\n");
1195 monitor_printf(mon, "Waiting for gdb connection on device '%s'\n",
1200 static void hmp_watchdog_action(Monitor *mon, const QDict *qdict)
1202 const char *action = qdict_get_str(qdict, "action");
1203 if (select_watchdog_action(action) == -1) {
1204 monitor_printf(mon, "Unknown watchdog action '%s'\n", action);
1208 static void monitor_printc(Monitor *mon, int c)
1210 monitor_printf(mon, "'");
1213 monitor_printf(mon, "\\'");
1216 monitor_printf(mon, "\\\\");
1219 monitor_printf(mon, "\\n");
1222 monitor_printf(mon, "\\r");
1225 if (c >= 32 && c <= 126) {
1226 monitor_printf(mon, "%c", c);
1228 monitor_printf(mon, "\\x%02x", c);
1232 monitor_printf(mon, "'");
1235 static void memory_dump(Monitor *mon, int count, int format, int wsize,
1236 hwaddr addr, int is_physical)
1238 int l, line_size, i, max_digits, len;
1242 if (format == 'i') {
1245 CPUArchState *env = mon_get_cpu_env();
1248 } else if (wsize == 4) {
1251 /* as default we use the current CS size */
1254 #ifdef TARGET_X86_64
1255 if ((env->efer & MSR_EFER_LMA) &&
1256 (env->segs[R_CS].flags & DESC_L_MASK))
1260 if (!(env->segs[R_CS].flags & DESC_B_MASK))
1266 CPUArchState *env = mon_get_cpu_env();
1267 flags = msr_le << 16;
1268 flags |= env->bfd_mach;
1270 monitor_disas(mon, mon_get_cpu(), addr, count, is_physical, flags);
1274 len = wsize * count;
1283 max_digits = (wsize * 8 + 2) / 3;
1287 max_digits = (wsize * 8) / 4;
1291 max_digits = (wsize * 8 * 10 + 32) / 33;
1300 monitor_printf(mon, TARGET_FMT_plx ":", addr);
1302 monitor_printf(mon, TARGET_FMT_lx ":", (target_ulong)addr);
1307 cpu_physical_memory_read(addr, buf, l);
1309 if (cpu_memory_rw_debug(mon_get_cpu(), addr, buf, l, 0) < 0) {
1310 monitor_printf(mon, " Cannot access memory\n");
1319 v = ldub_p(buf + i);
1322 v = lduw_p(buf + i);
1325 v = (uint32_t)ldl_p(buf + i);
1331 monitor_printf(mon, " ");
1334 monitor_printf(mon, "%#*" PRIo64, max_digits, v);
1337 monitor_printf(mon, "0x%0*" PRIx64, max_digits, v);
1340 monitor_printf(mon, "%*" PRIu64, max_digits, v);
1343 monitor_printf(mon, "%*" PRId64, max_digits, v);
1346 monitor_printc(mon, v);
1351 monitor_printf(mon, "\n");
1357 static void hmp_memory_dump(Monitor *mon, const QDict *qdict)
1359 int count = qdict_get_int(qdict, "count");
1360 int format = qdict_get_int(qdict, "format");
1361 int size = qdict_get_int(qdict, "size");
1362 target_long addr = qdict_get_int(qdict, "addr");
1364 memory_dump(mon, count, format, size, addr, 0);
1367 static void hmp_physical_memory_dump(Monitor *mon, const QDict *qdict)
1369 int count = qdict_get_int(qdict, "count");
1370 int format = qdict_get_int(qdict, "format");
1371 int size = qdict_get_int(qdict, "size");
1372 hwaddr addr = qdict_get_int(qdict, "addr");
1374 memory_dump(mon, count, format, size, addr, 1);
1377 static void do_print(Monitor *mon, const QDict *qdict)
1379 int format = qdict_get_int(qdict, "format");
1380 hwaddr val = qdict_get_int(qdict, "val");
1384 monitor_printf(mon, "%#" HWADDR_PRIo, val);
1387 monitor_printf(mon, "%#" HWADDR_PRIx, val);
1390 monitor_printf(mon, "%" HWADDR_PRIu, val);
1394 monitor_printf(mon, "%" HWADDR_PRId, val);
1397 monitor_printc(mon, val);
1400 monitor_printf(mon, "\n");
1403 static void hmp_sum(Monitor *mon, const QDict *qdict)
1407 uint32_t start = qdict_get_int(qdict, "start");
1408 uint32_t size = qdict_get_int(qdict, "size");
1411 for(addr = start; addr < (start + size); addr++) {
1412 uint8_t val = address_space_ldub(&address_space_memory, addr,
1413 MEMTXATTRS_UNSPECIFIED, NULL);
1414 /* BSD sum algorithm ('sum' Unix command) */
1415 sum = (sum >> 1) | (sum << 15);
1418 monitor_printf(mon, "%05d\n", sum);
1421 static int mouse_button_state;
1423 static void hmp_mouse_move(Monitor *mon, const QDict *qdict)
1425 int dx, dy, dz, button;
1426 const char *dx_str = qdict_get_str(qdict, "dx_str");
1427 const char *dy_str = qdict_get_str(qdict, "dy_str");
1428 const char *dz_str = qdict_get_try_str(qdict, "dz_str");
1430 dx = strtol(dx_str, NULL, 0);
1431 dy = strtol(dy_str, NULL, 0);
1432 qemu_input_queue_rel(NULL, INPUT_AXIS_X, dx);
1433 qemu_input_queue_rel(NULL, INPUT_AXIS_Y, dy);
1436 dz = strtol(dz_str, NULL, 0);
1438 button = (dz > 0) ? INPUT_BUTTON_WHEEL_UP : INPUT_BUTTON_WHEEL_DOWN;
1439 qemu_input_queue_btn(NULL, button, true);
1440 qemu_input_event_sync();
1441 qemu_input_queue_btn(NULL, button, false);
1444 qemu_input_event_sync();
1447 static void hmp_mouse_button(Monitor *mon, const QDict *qdict)
1449 static uint32_t bmap[INPUT_BUTTON__MAX] = {
1450 [INPUT_BUTTON_LEFT] = MOUSE_EVENT_LBUTTON,
1451 [INPUT_BUTTON_MIDDLE] = MOUSE_EVENT_MBUTTON,
1452 [INPUT_BUTTON_RIGHT] = MOUSE_EVENT_RBUTTON,
1454 int button_state = qdict_get_int(qdict, "button_state");
1456 if (mouse_button_state == button_state) {
1459 qemu_input_update_buttons(NULL, bmap, mouse_button_state, button_state);
1460 qemu_input_event_sync();
1461 mouse_button_state = button_state;
1464 static void hmp_ioport_read(Monitor *mon, const QDict *qdict)
1466 int size = qdict_get_int(qdict, "size");
1467 int addr = qdict_get_int(qdict, "addr");
1468 int has_index = qdict_haskey(qdict, "index");
1473 int index = qdict_get_int(qdict, "index");
1474 cpu_outb(addr & IOPORTS_MASK, index & 0xff);
1482 val = cpu_inb(addr);
1486 val = cpu_inw(addr);
1490 val = cpu_inl(addr);
1494 monitor_printf(mon, "port%c[0x%04x] = %#0*x\n",
1495 suffix, addr, size * 2, val);
1498 static void hmp_ioport_write(Monitor *mon, const QDict *qdict)
1500 int size = qdict_get_int(qdict, "size");
1501 int addr = qdict_get_int(qdict, "addr");
1502 int val = qdict_get_int(qdict, "val");
1504 addr &= IOPORTS_MASK;
1509 cpu_outb(addr, val);
1512 cpu_outw(addr, val);
1515 cpu_outl(addr, val);
1520 static void hmp_boot_set(Monitor *mon, const QDict *qdict)
1522 Error *local_err = NULL;
1523 const char *bootdevice = qdict_get_str(qdict, "bootdevice");
1525 qemu_boot_set(bootdevice, &local_err);
1527 error_report_err(local_err);
1529 monitor_printf(mon, "boot device list now set to %s\n", bootdevice);
1533 static void hmp_info_mtree(Monitor *mon, const QDict *qdict)
1535 mtree_info((fprintf_function)monitor_printf, mon);
1538 static void hmp_info_numa(Monitor *mon, const QDict *qdict)
1544 node_mem = g_new0(uint64_t, nb_numa_nodes);
1545 query_numa_node_mem(node_mem);
1546 monitor_printf(mon, "%d nodes\n", nb_numa_nodes);
1547 for (i = 0; i < nb_numa_nodes; i++) {
1548 monitor_printf(mon, "node %d cpus:", i);
1550 if (cpu->numa_node == i) {
1551 monitor_printf(mon, " %d", cpu->cpu_index);
1554 monitor_printf(mon, "\n");
1555 monitor_printf(mon, "node %d size: %" PRId64 " MB\n", i,
1561 #ifdef CONFIG_PROFILER
1566 static void hmp_info_profile(Monitor *mon, const QDict *qdict)
1568 monitor_printf(mon, "async time %" PRId64 " (%0.3f)\n",
1569 dev_time, dev_time / (double)NANOSECONDS_PER_SECOND);
1570 monitor_printf(mon, "qemu time %" PRId64 " (%0.3f)\n",
1571 tcg_time, tcg_time / (double)NANOSECONDS_PER_SECOND);
1576 static void hmp_info_profile(Monitor *mon, const QDict *qdict)
1578 monitor_printf(mon, "Internal profiler not compiled\n");
1582 /* Capture support */
1583 static QLIST_HEAD (capture_list_head, CaptureState) capture_head;
1585 static void hmp_info_capture(Monitor *mon, const QDict *qdict)
1590 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
1591 monitor_printf(mon, "[%d]: ", i);
1592 s->ops.info (s->opaque);
1596 static void hmp_stopcapture(Monitor *mon, const QDict *qdict)
1599 int n = qdict_get_int(qdict, "n");
1602 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
1604 s->ops.destroy (s->opaque);
1605 QLIST_REMOVE (s, entries);
1612 static void hmp_wavcapture(Monitor *mon, const QDict *qdict)
1614 const char *path = qdict_get_str(qdict, "path");
1615 int has_freq = qdict_haskey(qdict, "freq");
1616 int freq = qdict_get_try_int(qdict, "freq", -1);
1617 int has_bits = qdict_haskey(qdict, "bits");
1618 int bits = qdict_get_try_int(qdict, "bits", -1);
1619 int has_channels = qdict_haskey(qdict, "nchannels");
1620 int nchannels = qdict_get_try_int(qdict, "nchannels", -1);
1623 s = g_malloc0 (sizeof (*s));
1625 freq = has_freq ? freq : 44100;
1626 bits = has_bits ? bits : 16;
1627 nchannels = has_channels ? nchannels : 2;
1629 if (wav_start_capture (s, path, freq, bits, nchannels)) {
1630 monitor_printf(mon, "Failed to add wave capture\n");
1634 QLIST_INSERT_HEAD (&capture_head, s, entries);
1637 static qemu_acl *find_acl(Monitor *mon, const char *name)
1639 qemu_acl *acl = qemu_acl_find(name);
1642 monitor_printf(mon, "acl: unknown list '%s'\n", name);
1647 static void hmp_acl_show(Monitor *mon, const QDict *qdict)
1649 const char *aclname = qdict_get_str(qdict, "aclname");
1650 qemu_acl *acl = find_acl(mon, aclname);
1651 qemu_acl_entry *entry;
1655 monitor_printf(mon, "policy: %s\n",
1656 acl->defaultDeny ? "deny" : "allow");
1657 QTAILQ_FOREACH(entry, &acl->entries, next) {
1659 monitor_printf(mon, "%d: %s %s\n", i,
1660 entry->deny ? "deny" : "allow", entry->match);
1665 static void hmp_acl_reset(Monitor *mon, const QDict *qdict)
1667 const char *aclname = qdict_get_str(qdict, "aclname");
1668 qemu_acl *acl = find_acl(mon, aclname);
1671 qemu_acl_reset(acl);
1672 monitor_printf(mon, "acl: removed all rules\n");
1676 static void hmp_acl_policy(Monitor *mon, const QDict *qdict)
1678 const char *aclname = qdict_get_str(qdict, "aclname");
1679 const char *policy = qdict_get_str(qdict, "policy");
1680 qemu_acl *acl = find_acl(mon, aclname);
1683 if (strcmp(policy, "allow") == 0) {
1684 acl->defaultDeny = 0;
1685 monitor_printf(mon, "acl: policy set to 'allow'\n");
1686 } else if (strcmp(policy, "deny") == 0) {
1687 acl->defaultDeny = 1;
1688 monitor_printf(mon, "acl: policy set to 'deny'\n");
1690 monitor_printf(mon, "acl: unknown policy '%s', "
1691 "expected 'deny' or 'allow'\n", policy);
1696 static void hmp_acl_add(Monitor *mon, const QDict *qdict)
1698 const char *aclname = qdict_get_str(qdict, "aclname");
1699 const char *match = qdict_get_str(qdict, "match");
1700 const char *policy = qdict_get_str(qdict, "policy");
1701 int has_index = qdict_haskey(qdict, "index");
1702 int index = qdict_get_try_int(qdict, "index", -1);
1703 qemu_acl *acl = find_acl(mon, aclname);
1707 if (strcmp(policy, "allow") == 0) {
1709 } else if (strcmp(policy, "deny") == 0) {
1712 monitor_printf(mon, "acl: unknown policy '%s', "
1713 "expected 'deny' or 'allow'\n", policy);
1717 ret = qemu_acl_insert(acl, deny, match, index);
1719 ret = qemu_acl_append(acl, deny, match);
1721 monitor_printf(mon, "acl: unable to add acl entry\n");
1723 monitor_printf(mon, "acl: added rule at position %d\n", ret);
1727 static void hmp_acl_remove(Monitor *mon, const QDict *qdict)
1729 const char *aclname = qdict_get_str(qdict, "aclname");
1730 const char *match = qdict_get_str(qdict, "match");
1731 qemu_acl *acl = find_acl(mon, aclname);
1735 ret = qemu_acl_remove(acl, match);
1737 monitor_printf(mon, "acl: no matching acl entry\n");
1739 monitor_printf(mon, "acl: removed rule at position %d\n", ret);
1743 void qmp_getfd(const char *fdname, Error **errp)
1748 fd = qemu_chr_fe_get_msgfd(cur_mon->chr);
1750 error_setg(errp, QERR_FD_NOT_SUPPLIED);
1754 if (qemu_isdigit(fdname[0])) {
1756 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "fdname",
1757 "a name not starting with a digit");
1761 QLIST_FOREACH(monfd, &cur_mon->fds, next) {
1762 if (strcmp(monfd->name, fdname) != 0) {
1771 monfd = g_malloc0(sizeof(mon_fd_t));
1772 monfd->name = g_strdup(fdname);
1775 QLIST_INSERT_HEAD(&cur_mon->fds, monfd, next);
1778 void qmp_closefd(const char *fdname, Error **errp)
1782 QLIST_FOREACH(monfd, &cur_mon->fds, next) {
1783 if (strcmp(monfd->name, fdname) != 0) {
1787 QLIST_REMOVE(monfd, next);
1789 g_free(monfd->name);
1794 error_setg(errp, QERR_FD_NOT_FOUND, fdname);
1797 static void hmp_loadvm(Monitor *mon, const QDict *qdict)
1799 int saved_vm_running = runstate_is_running();
1800 const char *name = qdict_get_str(qdict, "name");
1802 vm_stop(RUN_STATE_RESTORE_VM);
1804 if (load_vmstate(name) == 0 && saved_vm_running) {
1809 int monitor_get_fd(Monitor *mon, const char *fdname, Error **errp)
1813 QLIST_FOREACH(monfd, &mon->fds, next) {
1816 if (strcmp(monfd->name, fdname) != 0) {
1822 /* caller takes ownership of fd */
1823 QLIST_REMOVE(monfd, next);
1824 g_free(monfd->name);
1830 error_setg(errp, "File descriptor named '%s' has not been found", fdname);
1834 static void monitor_fdset_cleanup(MonFdset *mon_fdset)
1836 MonFdsetFd *mon_fdset_fd;
1837 MonFdsetFd *mon_fdset_fd_next;
1839 QLIST_FOREACH_SAFE(mon_fdset_fd, &mon_fdset->fds, next, mon_fdset_fd_next) {
1840 if ((mon_fdset_fd->removed ||
1841 (QLIST_EMPTY(&mon_fdset->dup_fds) && mon_refcount == 0)) &&
1842 runstate_is_running()) {
1843 close(mon_fdset_fd->fd);
1844 g_free(mon_fdset_fd->opaque);
1845 QLIST_REMOVE(mon_fdset_fd, next);
1846 g_free(mon_fdset_fd);
1850 if (QLIST_EMPTY(&mon_fdset->fds) && QLIST_EMPTY(&mon_fdset->dup_fds)) {
1851 QLIST_REMOVE(mon_fdset, next);
1856 static void monitor_fdsets_cleanup(void)
1858 MonFdset *mon_fdset;
1859 MonFdset *mon_fdset_next;
1861 QLIST_FOREACH_SAFE(mon_fdset, &mon_fdsets, next, mon_fdset_next) {
1862 monitor_fdset_cleanup(mon_fdset);
1866 AddfdInfo *qmp_add_fd(bool has_fdset_id, int64_t fdset_id, bool has_opaque,
1867 const char *opaque, Error **errp)
1870 Monitor *mon = cur_mon;
1873 fd = qemu_chr_fe_get_msgfd(mon->chr);
1875 error_setg(errp, QERR_FD_NOT_SUPPLIED);
1879 fdinfo = monitor_fdset_add_fd(fd, has_fdset_id, fdset_id,
1880 has_opaque, opaque, errp);
1892 void qmp_remove_fd(int64_t fdset_id, bool has_fd, int64_t fd, Error **errp)
1894 MonFdset *mon_fdset;
1895 MonFdsetFd *mon_fdset_fd;
1898 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
1899 if (mon_fdset->id != fdset_id) {
1902 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
1904 if (mon_fdset_fd->fd != fd) {
1907 mon_fdset_fd->removed = true;
1910 mon_fdset_fd->removed = true;
1913 if (has_fd && !mon_fdset_fd) {
1916 monitor_fdset_cleanup(mon_fdset);
1922 snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64 ", fd:%" PRId64,
1925 snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64, fdset_id);
1927 error_setg(errp, QERR_FD_NOT_FOUND, fd_str);
1930 FdsetInfoList *qmp_query_fdsets(Error **errp)
1932 MonFdset *mon_fdset;
1933 MonFdsetFd *mon_fdset_fd;
1934 FdsetInfoList *fdset_list = NULL;
1936 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
1937 FdsetInfoList *fdset_info = g_malloc0(sizeof(*fdset_info));
1938 FdsetFdInfoList *fdsetfd_list = NULL;
1940 fdset_info->value = g_malloc0(sizeof(*fdset_info->value));
1941 fdset_info->value->fdset_id = mon_fdset->id;
1943 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
1944 FdsetFdInfoList *fdsetfd_info;
1946 fdsetfd_info = g_malloc0(sizeof(*fdsetfd_info));
1947 fdsetfd_info->value = g_malloc0(sizeof(*fdsetfd_info->value));
1948 fdsetfd_info->value->fd = mon_fdset_fd->fd;
1949 if (mon_fdset_fd->opaque) {
1950 fdsetfd_info->value->has_opaque = true;
1951 fdsetfd_info->value->opaque = g_strdup(mon_fdset_fd->opaque);
1953 fdsetfd_info->value->has_opaque = false;
1956 fdsetfd_info->next = fdsetfd_list;
1957 fdsetfd_list = fdsetfd_info;
1960 fdset_info->value->fds = fdsetfd_list;
1962 fdset_info->next = fdset_list;
1963 fdset_list = fdset_info;
1969 AddfdInfo *monitor_fdset_add_fd(int fd, bool has_fdset_id, int64_t fdset_id,
1970 bool has_opaque, const char *opaque,
1973 MonFdset *mon_fdset = NULL;
1974 MonFdsetFd *mon_fdset_fd;
1978 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
1979 /* Break if match found or match impossible due to ordering by ID */
1980 if (fdset_id <= mon_fdset->id) {
1981 if (fdset_id < mon_fdset->id) {
1989 if (mon_fdset == NULL) {
1990 int64_t fdset_id_prev = -1;
1991 MonFdset *mon_fdset_cur = QLIST_FIRST(&mon_fdsets);
1995 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "fdset-id",
1996 "a non-negative value");
1999 /* Use specified fdset ID */
2000 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2001 mon_fdset_cur = mon_fdset;
2002 if (fdset_id < mon_fdset_cur->id) {
2007 /* Use first available fdset ID */
2008 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2009 mon_fdset_cur = mon_fdset;
2010 if (fdset_id_prev == mon_fdset_cur->id - 1) {
2011 fdset_id_prev = mon_fdset_cur->id;
2018 mon_fdset = g_malloc0(sizeof(*mon_fdset));
2020 mon_fdset->id = fdset_id;
2022 mon_fdset->id = fdset_id_prev + 1;
2025 /* The fdset list is ordered by fdset ID */
2026 if (!mon_fdset_cur) {
2027 QLIST_INSERT_HEAD(&mon_fdsets, mon_fdset, next);
2028 } else if (mon_fdset->id < mon_fdset_cur->id) {
2029 QLIST_INSERT_BEFORE(mon_fdset_cur, mon_fdset, next);
2031 QLIST_INSERT_AFTER(mon_fdset_cur, mon_fdset, next);
2035 mon_fdset_fd = g_malloc0(sizeof(*mon_fdset_fd));
2036 mon_fdset_fd->fd = fd;
2037 mon_fdset_fd->removed = false;
2039 mon_fdset_fd->opaque = g_strdup(opaque);
2041 QLIST_INSERT_HEAD(&mon_fdset->fds, mon_fdset_fd, next);
2043 fdinfo = g_malloc0(sizeof(*fdinfo));
2044 fdinfo->fdset_id = mon_fdset->id;
2045 fdinfo->fd = mon_fdset_fd->fd;
2050 int monitor_fdset_get_fd(int64_t fdset_id, int flags)
2053 MonFdset *mon_fdset;
2054 MonFdsetFd *mon_fdset_fd;
2057 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2058 if (mon_fdset->id != fdset_id) {
2061 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2062 mon_fd_flags = fcntl(mon_fdset_fd->fd, F_GETFL);
2063 if (mon_fd_flags == -1) {
2067 if ((flags & O_ACCMODE) == (mon_fd_flags & O_ACCMODE)) {
2068 return mon_fdset_fd->fd;
2080 int monitor_fdset_dup_fd_add(int64_t fdset_id, int dup_fd)
2082 MonFdset *mon_fdset;
2083 MonFdsetFd *mon_fdset_fd_dup;
2085 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2086 if (mon_fdset->id != fdset_id) {
2089 QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
2090 if (mon_fdset_fd_dup->fd == dup_fd) {
2094 mon_fdset_fd_dup = g_malloc0(sizeof(*mon_fdset_fd_dup));
2095 mon_fdset_fd_dup->fd = dup_fd;
2096 QLIST_INSERT_HEAD(&mon_fdset->dup_fds, mon_fdset_fd_dup, next);
2102 static int monitor_fdset_dup_fd_find_remove(int dup_fd, bool remove)
2104 MonFdset *mon_fdset;
2105 MonFdsetFd *mon_fdset_fd_dup;
2107 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2108 QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
2109 if (mon_fdset_fd_dup->fd == dup_fd) {
2111 QLIST_REMOVE(mon_fdset_fd_dup, next);
2112 if (QLIST_EMPTY(&mon_fdset->dup_fds)) {
2113 monitor_fdset_cleanup(mon_fdset);
2117 return mon_fdset->id;
2125 int monitor_fdset_dup_fd_find(int dup_fd)
2127 return monitor_fdset_dup_fd_find_remove(dup_fd, false);
2130 void monitor_fdset_dup_fd_remove(int dup_fd)
2132 monitor_fdset_dup_fd_find_remove(dup_fd, true);
2135 int monitor_fd_param(Monitor *mon, const char *fdname, Error **errp)
2138 Error *local_err = NULL;
2140 if (!qemu_isdigit(fdname[0]) && mon) {
2141 fd = monitor_get_fd(mon, fdname, &local_err);
2143 fd = qemu_parse_fd(fdname);
2145 error_setg(&local_err, "Invalid file descriptor number '%s'",
2150 error_propagate(errp, local_err);
2159 /* Please update hmp-commands.hx when adding or changing commands */
2160 static mon_cmd_t info_cmds[] = {
2161 #include "hmp-commands-info.h"
2165 /* mon_cmds and info_cmds would be sorted at runtime */
2166 static mon_cmd_t mon_cmds[] = {
2167 #include "hmp-commands.h"
2171 /*******************************************************************/
2173 static const char *pch;
2174 static sigjmp_buf expr_env;
2177 static void GCC_FMT_ATTR(2, 3) QEMU_NORETURN
2178 expr_error(Monitor *mon, const char *fmt, ...)
2182 monitor_vprintf(mon, fmt, ap);
2183 monitor_printf(mon, "\n");
2185 siglongjmp(expr_env, 1);
2188 /* return 0 if OK, -1 if not found */
2189 static int get_monitor_def(target_long *pval, const char *name)
2191 const MonitorDef *md = target_monitor_defs();
2200 for(; md->name != NULL; md++) {
2201 if (compare_cmd(name, md->name)) {
2202 if (md->get_value) {
2203 *pval = md->get_value(md, md->offset);
2205 CPUArchState *env = mon_get_cpu_env();
2206 ptr = (uint8_t *)env + md->offset;
2209 *pval = *(int32_t *)ptr;
2212 *pval = *(target_long *)ptr;
2223 ret = target_get_monitor_def(mon_get_cpu(), name, &tmp);
2225 *pval = (target_long) tmp;
2231 static void next(void)
2235 while (qemu_isspace(*pch))
2240 static int64_t expr_sum(Monitor *mon);
2242 static int64_t expr_unary(Monitor *mon)
2251 n = expr_unary(mon);
2255 n = -expr_unary(mon);
2259 n = ~expr_unary(mon);
2265 expr_error(mon, "')' expected");
2272 expr_error(mon, "character constant expected");
2276 expr_error(mon, "missing terminating \' character");
2286 while ((*pch >= 'a' && *pch <= 'z') ||
2287 (*pch >= 'A' && *pch <= 'Z') ||
2288 (*pch >= '0' && *pch <= '9') ||
2289 *pch == '_' || *pch == '.') {
2290 if ((q - buf) < sizeof(buf) - 1)
2294 while (qemu_isspace(*pch))
2297 ret = get_monitor_def(®, buf);
2299 expr_error(mon, "unknown register");
2304 expr_error(mon, "unexpected end of expression");
2309 n = strtoull(pch, &p, 0);
2310 if (errno == ERANGE) {
2311 expr_error(mon, "number too large");
2314 expr_error(mon, "invalid char '%c' in expression", *p);
2317 while (qemu_isspace(*pch))
2325 static int64_t expr_prod(Monitor *mon)
2330 val = expr_unary(mon);
2333 if (op != '*' && op != '/' && op != '%')
2336 val2 = expr_unary(mon);
2345 expr_error(mon, "division by zero");
2356 static int64_t expr_logic(Monitor *mon)
2361 val = expr_prod(mon);
2364 if (op != '&' && op != '|' && op != '^')
2367 val2 = expr_prod(mon);
2384 static int64_t expr_sum(Monitor *mon)
2389 val = expr_logic(mon);
2392 if (op != '+' && op != '-')
2395 val2 = expr_logic(mon);
2404 static int get_expr(Monitor *mon, int64_t *pval, const char **pp)
2407 if (sigsetjmp(expr_env, 0)) {
2411 while (qemu_isspace(*pch))
2413 *pval = expr_sum(mon);
2418 static int get_double(Monitor *mon, double *pval, const char **pp)
2420 const char *p = *pp;
2424 d = strtod(p, &tailp);
2426 monitor_printf(mon, "Number expected\n");
2429 if (d != d || d - d != 0) {
2430 /* NaN or infinity */
2431 monitor_printf(mon, "Bad number\n");
2440 * Store the command-name in cmdname, and return a pointer to
2441 * the remaining of the command string.
2443 static const char *get_command_name(const char *cmdline,
2444 char *cmdname, size_t nlen)
2447 const char *p, *pstart;
2450 while (qemu_isspace(*p))
2455 while (*p != '\0' && *p != '/' && !qemu_isspace(*p))
2460 memcpy(cmdname, pstart, len);
2461 cmdname[len] = '\0';
2466 * Read key of 'type' into 'key' and return the current
2469 static char *key_get_info(const char *type, char **key)
2477 p = strchr(type, ':');
2484 str = g_malloc(len + 1);
2485 memcpy(str, type, len);
2492 static int default_fmt_format = 'x';
2493 static int default_fmt_size = 4;
2495 static int is_valid_option(const char *c, const char *typestr)
2503 typestr = strstr(typestr, option);
2504 return (typestr != NULL);
2507 static const mon_cmd_t *search_dispatch_table(const mon_cmd_t *disp_table,
2508 const char *cmdname)
2510 const mon_cmd_t *cmd;
2512 for (cmd = disp_table; cmd->name != NULL; cmd++) {
2513 if (compare_cmd(cmdname, cmd->name)) {
2522 * Parse command name from @cmdp according to command table @table.
2523 * If blank, return NULL.
2524 * Else, if no valid command can be found, report to @mon, and return
2526 * Else, change @cmdp to point right behind the name, and return its
2527 * command table entry.
2528 * Do not assume the return value points into @table! It doesn't when
2529 * the command is found in a sub-command table.
2531 static const mon_cmd_t *monitor_parse_command(Monitor *mon,
2536 const mon_cmd_t *cmd;
2539 /* extract the command name */
2540 p = get_command_name(*cmdp, cmdname, sizeof(cmdname));
2544 cmd = search_dispatch_table(table, cmdname);
2546 monitor_printf(mon, "unknown command: '%.*s'\n",
2547 (int)(p - *cmdp), *cmdp);
2551 /* filter out following useless space */
2552 while (qemu_isspace(*p)) {
2557 /* search sub command */
2558 if (cmd->sub_table != NULL && *p != '\0') {
2559 return monitor_parse_command(mon, cmdp, cmd->sub_table);
2566 * Parse arguments for @cmd.
2567 * If it can't be parsed, report to @mon, and return NULL.
2568 * Else, insert command arguments into a QDict, and return it.
2569 * Note: On success, caller has to free the QDict structure.
2572 static QDict *monitor_parse_arguments(Monitor *mon,
2574 const mon_cmd_t *cmd)
2576 const char *typestr;
2579 const char *p = *endp;
2581 QDict *qdict = qdict_new();
2583 /* parse the parameters */
2584 typestr = cmd->args_type;
2586 typestr = key_get_info(typestr, &key);
2598 while (qemu_isspace(*p))
2600 if (*typestr == '?') {
2603 /* no optional string: NULL argument */
2607 ret = get_str(buf, sizeof(buf), &p);
2611 monitor_printf(mon, "%s: filename expected\n",
2615 monitor_printf(mon, "%s: block device name expected\n",
2619 monitor_printf(mon, "%s: string expected\n", cmd->name);
2624 qdict_put(qdict, key, qstring_from_str(buf));
2629 QemuOptsList *opts_list;
2632 opts_list = qemu_find_opts(key);
2633 if (!opts_list || opts_list->desc->name) {
2636 while (qemu_isspace(*p)) {
2641 if (get_str(buf, sizeof(buf), &p) < 0) {
2644 opts = qemu_opts_parse_noisily(opts_list, buf, true);
2648 qemu_opts_to_qdict(opts, qdict);
2649 qemu_opts_del(opts);
2654 int count, format, size;
2656 while (qemu_isspace(*p))
2662 if (qemu_isdigit(*p)) {
2664 while (qemu_isdigit(*p)) {
2665 count = count * 10 + (*p - '0');
2703 if (*p != '\0' && !qemu_isspace(*p)) {
2704 monitor_printf(mon, "invalid char in format: '%c'\n",
2709 format = default_fmt_format;
2710 if (format != 'i') {
2711 /* for 'i', not specifying a size gives -1 as size */
2713 size = default_fmt_size;
2714 default_fmt_size = size;
2716 default_fmt_format = format;
2719 format = default_fmt_format;
2720 if (format != 'i') {
2721 size = default_fmt_size;
2726 qdict_put(qdict, "count", qint_from_int(count));
2727 qdict_put(qdict, "format", qint_from_int(format));
2728 qdict_put(qdict, "size", qint_from_int(size));
2737 while (qemu_isspace(*p))
2739 if (*typestr == '?' || *typestr == '.') {
2740 if (*typestr == '?') {
2748 while (qemu_isspace(*p))
2757 if (get_expr(mon, &val, &p))
2759 /* Check if 'i' is greater than 32-bit */
2760 if ((c == 'i') && ((val >> 32) & 0xffffffff)) {
2761 monitor_printf(mon, "\'%s\' has failed: ", cmd->name);
2762 monitor_printf(mon, "integer is for 32-bit values\n");
2764 } else if (c == 'M') {
2766 monitor_printf(mon, "enter a positive value\n");
2771 qdict_put(qdict, key, qint_from_int(val));
2779 while (qemu_isspace(*p)) {
2782 if (*typestr == '?') {
2788 val = qemu_strtosz(p, &end);
2790 monitor_printf(mon, "invalid size\n");
2793 qdict_put(qdict, key, qint_from_int(val));
2801 while (qemu_isspace(*p))
2803 if (*typestr == '?') {
2809 if (get_double(mon, &val, &p) < 0) {
2812 if (p[0] && p[1] == 's') {
2815 val /= 1e3; p += 2; break;
2817 val /= 1e6; p += 2; break;
2819 val /= 1e9; p += 2; break;
2822 if (*p && !qemu_isspace(*p)) {
2823 monitor_printf(mon, "Unknown unit suffix\n");
2826 qdict_put(qdict, key, qfloat_from_double(val));
2834 while (qemu_isspace(*p)) {
2838 while (qemu_isgraph(*p)) {
2841 if (p - beg == 2 && !memcmp(beg, "on", p - beg)) {
2843 } else if (p - beg == 3 && !memcmp(beg, "off", p - beg)) {
2846 monitor_printf(mon, "Expected 'on' or 'off'\n");
2849 qdict_put(qdict, key, qbool_from_bool(val));
2854 const char *tmp = p;
2861 while (qemu_isspace(*p))
2866 if(!is_valid_option(p, typestr)) {
2868 monitor_printf(mon, "%s: unsupported option -%c\n",
2880 qdict_put(qdict, key, qbool_from_bool(true));
2887 /* package all remaining string */
2890 while (qemu_isspace(*p)) {
2893 if (*typestr == '?') {
2896 /* no remaining string: NULL argument */
2902 monitor_printf(mon, "%s: string expected\n",
2906 qdict_put(qdict, key, qstring_from_str(p));
2912 monitor_printf(mon, "%s: unknown type '%c'\n", cmd->name, c);
2918 /* check that all arguments were parsed */
2919 while (qemu_isspace(*p))
2922 monitor_printf(mon, "%s: extraneous characters at the end of line\n",
2935 static void handle_hmp_command(Monitor *mon, const char *cmdline)
2938 const mon_cmd_t *cmd;
2940 cmd = monitor_parse_command(mon, &cmdline, mon->cmd_table);
2945 qdict = monitor_parse_arguments(mon, &cmdline, cmd);
2947 monitor_printf(mon, "Try \"help %s\" for more information\n",
2952 cmd->cmd(mon, qdict);
2956 static void cmd_completion(Monitor *mon, const char *name, const char *list)
2958 const char *p, *pstart;
2967 p = pstart + strlen(pstart);
2969 if (len > sizeof(cmd) - 2)
2970 len = sizeof(cmd) - 2;
2971 memcpy(cmd, pstart, len);
2973 if (name[0] == '\0' || !strncmp(name, cmd, strlen(name))) {
2974 readline_add_completion(mon->rs, cmd);
2982 static void file_completion(Monitor *mon, const char *input)
2987 char file[1024], file_prefix[1024];
2991 p = strrchr(input, '/');
2994 pstrcpy(file_prefix, sizeof(file_prefix), input);
2995 pstrcpy(path, sizeof(path), ".");
2997 input_path_len = p - input + 1;
2998 memcpy(path, input, input_path_len);
2999 if (input_path_len > sizeof(path) - 1)
3000 input_path_len = sizeof(path) - 1;
3001 path[input_path_len] = '\0';
3002 pstrcpy(file_prefix, sizeof(file_prefix), p + 1);
3005 ffs = opendir(path);
3014 if (strcmp(d->d_name, ".") == 0 || strcmp(d->d_name, "..") == 0) {
3018 if (strstart(d->d_name, file_prefix, NULL)) {
3019 memcpy(file, input, input_path_len);
3020 if (input_path_len < sizeof(file))
3021 pstrcpy(file + input_path_len, sizeof(file) - input_path_len,
3023 /* stat the file to find out if it's a directory.
3024 * In that case add a slash to speed up typing long paths
3026 if (stat(file, &sb) == 0 && S_ISDIR(sb.st_mode)) {
3027 pstrcat(file, sizeof(file), "/");
3029 readline_add_completion(mon->rs, file);
3035 static const char *next_arg_type(const char *typestr)
3037 const char *p = strchr(typestr, ':');
3038 return (p != NULL ? ++p : typestr);
3041 static void add_completion_option(ReadLineState *rs, const char *str,
3044 if (!str || !option) {
3047 if (!strncmp(option, str, strlen(str))) {
3048 readline_add_completion(rs, option);
3052 void chardev_add_completion(ReadLineState *rs, int nb_args, const char *str)
3055 ChardevBackendInfoList *list, *start;
3061 readline_set_completion_index(rs, len);
3063 start = list = qmp_query_chardev_backends(NULL);
3065 const char *chr_name = list->value->name;
3067 if (!strncmp(chr_name, str, len)) {
3068 readline_add_completion(rs, chr_name);
3072 qapi_free_ChardevBackendInfoList(start);
3075 void netdev_add_completion(ReadLineState *rs, int nb_args, const char *str)
3084 readline_set_completion_index(rs, len);
3085 for (i = 0; NetClientDriver_lookup[i]; i++) {
3086 add_completion_option(rs, str, NetClientDriver_lookup[i]);
3090 void device_add_completion(ReadLineState *rs, int nb_args, const char *str)
3100 readline_set_completion_index(rs, len);
3101 list = elt = object_class_get_list(TYPE_DEVICE, false);
3104 DeviceClass *dc = OBJECT_CLASS_CHECK(DeviceClass, elt->data,
3106 name = object_class_get_name(OBJECT_CLASS(dc));
3108 if (!dc->cannot_instantiate_with_device_add_yet
3109 && !strncmp(name, str, len)) {
3110 readline_add_completion(rs, name);
3117 void object_add_completion(ReadLineState *rs, int nb_args, const char *str)
3127 readline_set_completion_index(rs, len);
3128 list = elt = object_class_get_list(TYPE_USER_CREATABLE, false);
3132 name = object_class_get_name(OBJECT_CLASS(elt->data));
3133 if (!strncmp(name, str, len) && strcmp(name, TYPE_USER_CREATABLE)) {
3134 readline_add_completion(rs, name);
3141 static void peripheral_device_del_completion(ReadLineState *rs,
3142 const char *str, size_t len)
3144 Object *peripheral = container_get(qdev_get_machine(), "/peripheral");
3145 GSList *list, *item;
3147 list = qdev_build_hotpluggable_device_list(peripheral);
3152 for (item = list; item; item = g_slist_next(item)) {
3153 DeviceState *dev = item->data;
3155 if (dev->id && !strncmp(str, dev->id, len)) {
3156 readline_add_completion(rs, dev->id);
3163 void chardev_remove_completion(ReadLineState *rs, int nb_args, const char *str)
3166 ChardevInfoList *list, *start;
3172 readline_set_completion_index(rs, len);
3174 start = list = qmp_query_chardev(NULL);
3176 ChardevInfo *chr = list->value;
3178 if (!strncmp(chr->label, str, len)) {
3179 readline_add_completion(rs, chr->label);
3183 qapi_free_ChardevInfoList(start);
3186 static void ringbuf_completion(ReadLineState *rs, const char *str)
3189 ChardevInfoList *list, *start;
3192 readline_set_completion_index(rs, len);
3194 start = list = qmp_query_chardev(NULL);
3196 ChardevInfo *chr_info = list->value;
3198 if (!strncmp(chr_info->label, str, len)) {
3199 CharDriverState *chr = qemu_chr_find(chr_info->label);
3200 if (chr && chr_is_ringbuf(chr)) {
3201 readline_add_completion(rs, chr_info->label);
3206 qapi_free_ChardevInfoList(start);
3209 void ringbuf_write_completion(ReadLineState *rs, int nb_args, const char *str)
3214 ringbuf_completion(rs, str);
3217 void device_del_completion(ReadLineState *rs, int nb_args, const char *str)
3226 readline_set_completion_index(rs, len);
3227 peripheral_device_del_completion(rs, str, len);
3230 void object_del_completion(ReadLineState *rs, int nb_args, const char *str)
3232 ObjectPropertyInfoList *list, *start;
3239 readline_set_completion_index(rs, len);
3241 start = list = qmp_qom_list("/objects", NULL);
3243 ObjectPropertyInfo *info = list->value;
3245 if (!strncmp(info->type, "child<", 5)
3246 && !strncmp(info->name, str, len)) {
3247 readline_add_completion(rs, info->name);
3251 qapi_free_ObjectPropertyInfoList(start);
3254 void sendkey_completion(ReadLineState *rs, int nb_args, const char *str)
3263 sep = strrchr(str, '-');
3268 readline_set_completion_index(rs, len);
3269 for (i = 0; i < Q_KEY_CODE__MAX; i++) {
3270 if (!strncmp(str, QKeyCode_lookup[i], len)) {
3271 readline_add_completion(rs, QKeyCode_lookup[i]);
3276 void set_link_completion(ReadLineState *rs, int nb_args, const char *str)
3281 readline_set_completion_index(rs, len);
3283 NetClientState *ncs[MAX_QUEUE_NUM];
3285 count = qemu_find_net_clients_except(NULL, ncs,
3286 NET_CLIENT_DRIVER_NONE,
3288 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3289 const char *name = ncs[i]->name;
3290 if (!strncmp(str, name, len)) {
3291 readline_add_completion(rs, name);
3294 } else if (nb_args == 3) {
3295 add_completion_option(rs, str, "on");
3296 add_completion_option(rs, str, "off");
3300 void netdev_del_completion(ReadLineState *rs, int nb_args, const char *str)
3303 NetClientState *ncs[MAX_QUEUE_NUM];
3310 readline_set_completion_index(rs, len);
3311 count = qemu_find_net_clients_except(NULL, ncs, NET_CLIENT_DRIVER_NIC,
3313 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3315 const char *name = ncs[i]->name;
3316 if (strncmp(str, name, len)) {
3319 opts = qemu_opts_find(qemu_find_opts_err("netdev", NULL), name);
3321 readline_add_completion(rs, name);
3326 void info_trace_events_completion(ReadLineState *rs, int nb_args, const char *str)
3331 readline_set_completion_index(rs, len);
3334 for (id = 0; id < trace_event_count(); id++) {
3335 const char *event_name = trace_event_get_name(trace_event_id(id));
3336 if (!strncmp(str, event_name, len)) {
3337 readline_add_completion(rs, event_name);
3343 void trace_event_completion(ReadLineState *rs, int nb_args, const char *str)
3348 readline_set_completion_index(rs, len);
3351 for (id = 0; id < trace_event_count(); id++) {
3352 const char *event_name = trace_event_get_name(trace_event_id(id));
3353 if (!strncmp(str, event_name, len)) {
3354 readline_add_completion(rs, event_name);
3357 } else if (nb_args == 3) {
3358 add_completion_option(rs, str, "on");
3359 add_completion_option(rs, str, "off");
3363 void watchdog_action_completion(ReadLineState *rs, int nb_args, const char *str)
3370 readline_set_completion_index(rs, strlen(str));
3371 for (i = 0; WatchdogExpirationAction_lookup[i]; i++) {
3372 add_completion_option(rs, str, WatchdogExpirationAction_lookup[i]);
3376 void migrate_set_capability_completion(ReadLineState *rs, int nb_args,
3382 readline_set_completion_index(rs, len);
3385 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
3386 const char *name = MigrationCapability_lookup[i];
3387 if (!strncmp(str, name, len)) {
3388 readline_add_completion(rs, name);
3391 } else if (nb_args == 3) {
3392 add_completion_option(rs, str, "on");
3393 add_completion_option(rs, str, "off");
3397 void migrate_set_parameter_completion(ReadLineState *rs, int nb_args,
3403 readline_set_completion_index(rs, len);
3406 for (i = 0; i < MIGRATION_PARAMETER__MAX; i++) {
3407 const char *name = MigrationParameter_lookup[i];
3408 if (!strncmp(str, name, len)) {
3409 readline_add_completion(rs, name);
3415 void host_net_add_completion(ReadLineState *rs, int nb_args, const char *str)
3423 readline_set_completion_index(rs, len);
3424 for (i = 0; host_net_devices[i]; i++) {
3425 if (!strncmp(host_net_devices[i], str, len)) {
3426 readline_add_completion(rs, host_net_devices[i]);
3431 void host_net_remove_completion(ReadLineState *rs, int nb_args, const char *str)
3433 NetClientState *ncs[MAX_QUEUE_NUM];
3437 readline_set_completion_index(rs, len);
3439 count = qemu_find_net_clients_except(NULL, ncs,
3440 NET_CLIENT_DRIVER_NONE,
3442 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3446 if (net_hub_id_for_client(ncs[i], &id)) {
3449 snprintf(name, sizeof(name), "%d", id);
3450 if (!strncmp(str, name, len)) {
3451 readline_add_completion(rs, name);
3455 } else if (nb_args == 3) {
3456 count = qemu_find_net_clients_except(NULL, ncs,
3457 NET_CLIENT_DRIVER_NIC,
3459 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3463 if (ncs[i]->info->type == NET_CLIENT_DRIVER_HUBPORT ||
3464 net_hub_id_for_client(ncs[i], &id)) {
3467 name = ncs[i]->name;
3468 if (!strncmp(str, name, len)) {
3469 readline_add_completion(rs, name);
3476 static void vm_completion(ReadLineState *rs, const char *str)
3479 BlockDriverState *bs;
3480 BdrvNextIterator it;
3483 readline_set_completion_index(rs, len);
3485 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
3486 SnapshotInfoList *snapshots, *snapshot;
3487 AioContext *ctx = bdrv_get_aio_context(bs);
3490 aio_context_acquire(ctx);
3491 if (bdrv_can_snapshot(bs)) {
3492 ok = bdrv_query_snapshot_info_list(bs, &snapshots, NULL) == 0;
3494 aio_context_release(ctx);
3499 snapshot = snapshots;
3501 char *completion = snapshot->value->name;
3502 if (!strncmp(str, completion, len)) {
3503 readline_add_completion(rs, completion);
3505 completion = snapshot->value->id;
3506 if (!strncmp(str, completion, len)) {
3507 readline_add_completion(rs, completion);
3509 snapshot = snapshot->next;
3511 qapi_free_SnapshotInfoList(snapshots);
3516 void delvm_completion(ReadLineState *rs, int nb_args, const char *str)
3519 vm_completion(rs, str);
3523 void loadvm_completion(ReadLineState *rs, int nb_args, const char *str)
3526 vm_completion(rs, str);
3530 static void monitor_find_completion_by_table(Monitor *mon,
3531 const mon_cmd_t *cmd_table,
3535 const char *cmdname;
3537 const char *ptype, *str, *name;
3538 const mon_cmd_t *cmd;
3539 BlockBackend *blk = NULL;
3542 /* command completion */
3547 readline_set_completion_index(mon->rs, strlen(cmdname));
3548 for (cmd = cmd_table; cmd->name != NULL; cmd++) {
3549 cmd_completion(mon, cmdname, cmd->name);
3552 /* find the command */
3553 for (cmd = cmd_table; cmd->name != NULL; cmd++) {
3554 if (compare_cmd(args[0], cmd->name)) {
3562 if (cmd->sub_table) {
3563 /* do the job again */
3564 monitor_find_completion_by_table(mon, cmd->sub_table,
3565 &args[1], nb_args - 1);
3568 if (cmd->command_completion) {
3569 cmd->command_completion(mon->rs, nb_args, args[nb_args - 1]);
3573 ptype = next_arg_type(cmd->args_type);
3574 for(i = 0; i < nb_args - 2; i++) {
3575 if (*ptype != '\0') {
3576 ptype = next_arg_type(ptype);
3577 while (*ptype == '?')
3578 ptype = next_arg_type(ptype);
3581 str = args[nb_args - 1];
3582 while (*ptype == '-' && ptype[1] != '\0') {
3583 ptype = next_arg_type(ptype);
3587 /* file completion */
3588 readline_set_completion_index(mon->rs, strlen(str));
3589 file_completion(mon, str);
3592 /* block device name completion */
3593 readline_set_completion_index(mon->rs, strlen(str));
3594 while ((blk = blk_next(blk)) != NULL) {
3595 name = blk_name(blk);
3596 if (str[0] == '\0' ||
3597 !strncmp(name, str, strlen(str))) {
3598 readline_add_completion(mon->rs, name);
3604 if (!strcmp(cmd->name, "help|?")) {
3605 monitor_find_completion_by_table(mon, cmd_table,
3606 &args[1], nb_args - 1);
3615 static void monitor_find_completion(void *opaque,
3616 const char *cmdline)
3618 Monitor *mon = opaque;
3619 char *args[MAX_ARGS];
3622 /* 1. parse the cmdline */
3623 if (parse_cmdline(cmdline, &nb_args, args) < 0) {
3627 /* if the line ends with a space, it means we want to complete the
3629 len = strlen(cmdline);
3630 if (len > 0 && qemu_isspace(cmdline[len - 1])) {
3631 if (nb_args >= MAX_ARGS) {
3634 args[nb_args++] = g_strdup("");
3637 /* 2. auto complete according to args */
3638 monitor_find_completion_by_table(mon, mon->cmd_table, args, nb_args);
3641 free_cmdline_args(args, nb_args);
3644 static int monitor_can_read(void *opaque)
3646 Monitor *mon = opaque;
3648 return (mon->suspend_cnt == 0) ? 1 : 0;
3651 static bool invalid_qmp_mode(const Monitor *mon, const char *cmd,
3654 bool is_cap = g_str_equal(cmd, "qmp_capabilities");
3656 if (is_cap && mon->qmp.in_command_mode) {
3657 error_set(errp, ERROR_CLASS_COMMAND_NOT_FOUND,
3658 "Capabilities negotiation is already complete, command "
3659 "'%s' ignored", cmd);
3662 if (!is_cap && !mon->qmp.in_command_mode) {
3663 error_set(errp, ERROR_CLASS_COMMAND_NOT_FOUND,
3664 "Expecting capabilities negotiation with "
3665 "'qmp_capabilities' before command '%s'", cmd);
3672 * Input object checking rules
3674 * 1. Input object must be a dict
3675 * 2. The "execute" key must exist
3676 * 3. The "execute" key must be a string
3677 * 4. If the "arguments" key exists, it must be a dict
3678 * 5. If the "id" key exists, it can be anything (ie. json-value)
3679 * 6. Any argument not listed above is considered invalid
3681 static QDict *qmp_check_input_obj(QObject *input_obj, Error **errp)
3683 const QDictEntry *ent;
3684 int has_exec_key = 0;
3687 if (qobject_type(input_obj) != QTYPE_QDICT) {
3688 error_setg(errp, QERR_QMP_BAD_INPUT_OBJECT, "object");
3692 input_dict = qobject_to_qdict(input_obj);
3694 for (ent = qdict_first(input_dict); ent; ent = qdict_next(input_dict, ent)){
3695 const char *arg_name = qdict_entry_key(ent);
3696 const QObject *arg_obj = qdict_entry_value(ent);
3698 if (!strcmp(arg_name, "execute")) {
3699 if (qobject_type(arg_obj) != QTYPE_QSTRING) {
3700 error_setg(errp, QERR_QMP_BAD_INPUT_OBJECT_MEMBER,
3701 "execute", "string");
3705 } else if (!strcmp(arg_name, "arguments")) {
3706 if (qobject_type(arg_obj) != QTYPE_QDICT) {
3707 error_setg(errp, QERR_QMP_BAD_INPUT_OBJECT_MEMBER,
3708 "arguments", "object");
3711 } else if (!strcmp(arg_name, "id")) {
3712 /* Any string is acceptable as "id", so nothing to check */
3714 error_setg(errp, QERR_QMP_EXTRA_MEMBER, arg_name);
3719 if (!has_exec_key) {
3720 error_setg(errp, QERR_QMP_BAD_INPUT_OBJECT, "execute");
3727 static void handle_qmp_command(JSONMessageParser *parser, GQueue *tokens)
3729 QObject *req, *rsp = NULL, *id = NULL;
3730 QDict *qdict = NULL;
3731 const char *cmd_name;
3732 Monitor *mon = cur_mon;
3735 req = json_parser_parse_err(tokens, NULL, &err);
3736 if (err || !req || qobject_type(req) != QTYPE_QDICT) {
3738 error_setg(&err, QERR_JSON_PARSING);
3743 qdict = qmp_check_input_obj(req, &err);
3748 id = qdict_get(qdict, "id");
3750 qdict_del(qdict, "id");
3752 cmd_name = qdict_get_str(qdict, "execute");
3753 trace_handle_qmp_command(mon, cmd_name);
3755 if (invalid_qmp_mode(mon, cmd_name, &err)) {
3759 rsp = qmp_dispatch(req);
3763 qdict = qdict_new();
3764 qdict_put_obj(qdict, "error", qmp_build_error_object(err));
3766 rsp = QOBJECT(qdict);
3771 qdict_put_obj(qobject_to_qdict(rsp), "id", id);
3775 monitor_json_emitter(mon, rsp);
3779 qobject_decref(rsp);
3780 qobject_decref(req);
3783 static void monitor_qmp_read(void *opaque, const uint8_t *buf, int size)
3785 Monitor *old_mon = cur_mon;
3789 json_message_parser_feed(&cur_mon->qmp.parser, (const char *) buf, size);
3794 static void monitor_read(void *opaque, const uint8_t *buf, int size)
3796 Monitor *old_mon = cur_mon;
3802 for (i = 0; i < size; i++)
3803 readline_handle_byte(cur_mon->rs, buf[i]);
3805 if (size == 0 || buf[size - 1] != 0)
3806 monitor_printf(cur_mon, "corrupted command\n");
3808 handle_hmp_command(cur_mon, (char *)buf);
3814 static void monitor_command_cb(void *opaque, const char *cmdline,
3815 void *readline_opaque)
3817 Monitor *mon = opaque;
3819 monitor_suspend(mon);
3820 handle_hmp_command(mon, cmdline);
3821 monitor_resume(mon);
3824 int monitor_suspend(Monitor *mon)
3832 void monitor_resume(Monitor *mon)
3836 if (--mon->suspend_cnt == 0)
3837 readline_show_prompt(mon->rs);
3840 static QObject *get_qmp_greeting(void)
3842 QObject *ver = NULL;
3844 qmp_marshal_query_version(NULL, &ver, NULL);
3846 return qobject_from_jsonf("{'QMP': {'version': %p, 'capabilities': []}}",
3850 static void monitor_qmp_event(void *opaque, int event)
3853 Monitor *mon = opaque;
3856 case CHR_EVENT_OPENED:
3857 mon->qmp.in_command_mode = false;
3858 data = get_qmp_greeting();
3859 monitor_json_emitter(mon, data);
3860 qobject_decref(data);
3863 case CHR_EVENT_CLOSED:
3864 json_message_parser_destroy(&mon->qmp.parser);
3865 json_message_parser_init(&mon->qmp.parser, handle_qmp_command);
3867 monitor_fdsets_cleanup();
3872 static void monitor_event(void *opaque, int event)
3874 Monitor *mon = opaque;
3877 case CHR_EVENT_MUX_IN:
3878 qemu_mutex_lock(&mon->out_lock);
3880 qemu_mutex_unlock(&mon->out_lock);
3881 if (mon->reset_seen) {
3882 readline_restart(mon->rs);
3883 monitor_resume(mon);
3886 mon->suspend_cnt = 0;
3890 case CHR_EVENT_MUX_OUT:
3891 if (mon->reset_seen) {
3892 if (mon->suspend_cnt == 0) {
3893 monitor_printf(mon, "\n");
3896 monitor_suspend(mon);
3900 qemu_mutex_lock(&mon->out_lock);
3902 qemu_mutex_unlock(&mon->out_lock);
3905 case CHR_EVENT_OPENED:
3906 monitor_printf(mon, "QEMU %s monitor - type 'help' for more "
3907 "information\n", QEMU_VERSION);
3908 if (!mon->mux_out) {
3909 readline_restart(mon->rs);
3910 readline_show_prompt(mon->rs);
3912 mon->reset_seen = 1;
3916 case CHR_EVENT_CLOSED:
3918 monitor_fdsets_cleanup();
3924 compare_mon_cmd(const void *a, const void *b)
3926 return strcmp(((const mon_cmd_t *)a)->name,
3927 ((const mon_cmd_t *)b)->name);
3930 static void sortcmdlist(void)
3933 int elem_size = sizeof(mon_cmd_t);
3935 array_num = sizeof(mon_cmds)/elem_size-1;
3936 qsort((void *)mon_cmds, array_num, elem_size, compare_mon_cmd);
3938 array_num = sizeof(info_cmds)/elem_size-1;
3939 qsort((void *)info_cmds, array_num, elem_size, compare_mon_cmd);
3942 /* These functions just adapt the readline interface in a typesafe way. We
3943 * could cast function pointers but that discards compiler checks.
3945 static void GCC_FMT_ATTR(2, 3) monitor_readline_printf(void *opaque,
3946 const char *fmt, ...)
3950 monitor_vprintf(opaque, fmt, ap);
3954 static void monitor_readline_flush(void *opaque)
3956 monitor_flush(opaque);
3959 static void __attribute__((constructor)) monitor_lock_init(void)
3961 qemu_mutex_init(&monitor_lock);
3964 void monitor_init(CharDriverState *chr, int flags)
3966 static int is_first_init = 1;
3969 if (is_first_init) {
3970 monitor_qapi_event_init();
3975 mon = g_malloc(sizeof(*mon));
3976 monitor_data_init(mon);
3980 if (flags & MONITOR_USE_READLINE) {
3981 mon->rs = readline_init(monitor_readline_printf,
3982 monitor_readline_flush,
3984 monitor_find_completion);
3985 monitor_read_command(mon, 0);
3988 if (monitor_is_qmp(mon)) {
3989 qemu_chr_add_handlers(chr, monitor_can_read, monitor_qmp_read,
3990 monitor_qmp_event, mon);
3991 qemu_chr_fe_set_echo(chr, true);
3992 json_message_parser_init(&mon->qmp.parser, handle_qmp_command);
3994 qemu_chr_add_handlers(chr, monitor_can_read, monitor_read,
3995 monitor_event, mon);
3998 qemu_mutex_lock(&monitor_lock);
3999 QLIST_INSERT_HEAD(&mon_list, mon, entry);
4000 qemu_mutex_unlock(&monitor_lock);
4003 void monitor_cleanup(void)
4005 Monitor *mon, *next;
4007 qemu_mutex_lock(&monitor_lock);
4008 QLIST_FOREACH_SAFE(mon, &mon_list, entry, next) {
4009 QLIST_REMOVE(mon, entry);
4010 monitor_data_destroy(mon);
4013 qemu_mutex_unlock(&monitor_lock);
4016 static void bdrv_password_cb(void *opaque, const char *password,
4017 void *readline_opaque)
4019 Monitor *mon = opaque;
4020 BlockDriverState *bs = readline_opaque;
4022 Error *local_err = NULL;
4024 bdrv_add_key(bs, password, &local_err);
4026 error_report_err(local_err);
4029 if (mon->password_completion_cb)
4030 mon->password_completion_cb(mon->password_opaque, ret);
4032 monitor_read_command(mon, 1);
4035 int monitor_read_bdrv_key_start(Monitor *mon, BlockDriverState *bs,
4036 BlockCompletionFunc *completion_cb,
4041 monitor_printf(mon, "%s (%s) is encrypted.\n", bdrv_get_device_name(bs),
4042 bdrv_get_encrypted_filename(bs));
4044 mon->password_completion_cb = completion_cb;
4045 mon->password_opaque = opaque;
4047 err = monitor_read_password(mon, bdrv_password_cb, bs);
4049 if (err && completion_cb)
4050 completion_cb(opaque, err);
4055 int monitor_read_block_device_key(Monitor *mon, const char *device,
4056 BlockCompletionFunc *completion_cb,
4062 blk = blk_by_name(device);
4064 monitor_printf(mon, "Device not found %s\n", device);
4068 monitor_printf(mon, "Device '%s' has no medium\n", device);
4072 bdrv_add_key(blk_bs(blk), NULL, &err);
4075 return monitor_read_bdrv_key_start(mon, blk_bs(blk), completion_cb, opaque);
4078 if (completion_cb) {
4079 completion_cb(opaque, 0);
4084 QemuOptsList qemu_mon_opts = {
4086 .implied_opt_name = "chardev",
4087 .head = QTAILQ_HEAD_INITIALIZER(qemu_mon_opts.head),
4091 .type = QEMU_OPT_STRING,
4094 .type = QEMU_OPT_STRING,
4097 .type = QEMU_OPT_BOOL,
4100 .type = QEMU_OPT_BOOL,
4102 { /* end of list */ }
4107 void qmp_rtc_reset_reinjection(Error **errp)
4109 error_setg(errp, QERR_FEATURE_DISABLED, "rtc-reset-reinjection");
4113 #ifndef TARGET_S390X
4114 void qmp_dump_skeys(const char *filename, Error **errp)
4116 error_setg(errp, QERR_FEATURE_DISABLED, "dump-skeys");
4121 GICCapabilityList *qmp_query_gic_capabilities(Error **errp)
4123 error_setg(errp, QERR_FEATURE_DISABLED, "query-gic-capabilities");
4128 HotpluggableCPUList *qmp_query_hotpluggable_cpus(Error **errp)
4130 MachineState *ms = MACHINE(qdev_get_machine());
4131 MachineClass *mc = MACHINE_GET_CLASS(ms);
4133 if (!mc->query_hotpluggable_cpus) {
4134 error_setg(errp, QERR_FEATURE_DISABLED, "query-hotpluggable-cpus");
4138 return mc->query_hotpluggable_cpus(ms);