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/config-file.h"
44 #include "qemu/readline.h"
45 #include "ui/console.h"
47 #include "sysemu/blockdev.h"
48 #include "sysemu/block-backend.h"
49 #include "audio/audio.h"
50 #include "disas/disas.h"
51 #include "sysemu/balloon.h"
52 #include "qemu/timer.h"
53 #include "migration/migration.h"
54 #include "sysemu/hw_accel.h"
56 #include "sysemu/tpm.h"
57 #include "qapi/qmp/qerror.h"
58 #include "qapi/qmp/types.h"
59 #include "qapi/qmp/qjson.h"
60 #include "qapi/qmp/json-streamer.h"
61 #include "qapi/qmp/json-parser.h"
62 #include "qom/object_interfaces.h"
63 #include "trace-root.h"
64 #include "trace/control.h"
65 #include "monitor/hmp-target.h"
66 #ifdef CONFIG_TRACE_SIMPLE
67 #include "trace/simple.h"
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/qtest.h"
80 #include "qemu/cutils.h"
81 #include "qapi/qmp/dispatch.h"
83 #if defined(TARGET_S390X)
84 #include "hw/s390x/storage-keys.h"
91 * 'B' block device name
92 * 's' string (accept optional quote)
93 * 'S' it just appends the rest of the string (accept optional quote)
94 * 'O' option string of the form NAME=VALUE,...
95 * parsed according to QemuOptsList given by its name
96 * Example: 'device:O' uses qemu_device_opts.
97 * Restriction: only lists with empty desc are supported
98 * TODO lift the restriction
100 * 'l' target long (32 or 64 bit)
101 * 'M' Non-negative target long (32 or 64 bit), in user mode the
102 * value is multiplied by 2^20 (think Mebibyte)
103 * 'o' octets (aka bytes)
104 * user mode accepts an optional E, e, P, p, T, t, G, g, M, m,
105 * K, k suffix, which multiplies the value by 2^60 for suffixes E
106 * and e, 2^50 for suffixes P and p, 2^40 for suffixes T and t,
107 * 2^30 for suffixes G and g, 2^20 for M and m, 2^10 for K and k
109 * user mode accepts an optional ms, us, ns suffix,
110 * which divides the value by 1e3, 1e6, 1e9, respectively
111 * '/' optional gdb-like print format (like "/10x")
113 * '?' optional type (for all types, except '/')
114 * '.' other form of optional type (for 'i' and 'l')
116 * user mode accepts "on" or "off"
117 * '-' optional parameter (eg. '-f')
121 typedef struct mon_cmd_t {
123 const char *args_type;
126 void (*cmd)(Monitor *mon, const QDict *qdict);
127 /* @sub_table is a list of 2nd level of commands. If it does not exist,
128 * cmd should be used. If it exists, sub_table[?].cmd should be
129 * used, and cmd of 1st level plays the role of help function.
131 struct mon_cmd_t *sub_table;
132 void (*command_completion)(ReadLineState *rs, int nb_args, const char *str);
135 /* file descriptors passed via SCM_RIGHTS */
136 typedef struct mon_fd_t mon_fd_t;
140 QLIST_ENTRY(mon_fd_t) next;
143 /* file descriptor associated with a file descriptor set */
144 typedef struct MonFdsetFd MonFdsetFd;
149 QLIST_ENTRY(MonFdsetFd) next;
152 /* file descriptor set containing fds passed via SCM_RIGHTS */
153 typedef struct MonFdset MonFdset;
156 QLIST_HEAD(, MonFdsetFd) fds;
157 QLIST_HEAD(, MonFdsetFd) dup_fds;
158 QLIST_ENTRY(MonFdset) next;
162 JSONMessageParser parser;
164 * When a client connects, we're in capabilities negotiation mode.
165 * When command qmp_capabilities succeeds, we go into command
168 bool in_command_mode; /* are we in command mode? */
172 * To prevent flooding clients, events can be throttled. The
173 * throttling is calculated globally, rather than per-Monitor
176 typedef struct MonitorQAPIEventState {
177 QAPIEvent event; /* Throttling state for this event type and... */
178 QDict *data; /* ... data, see qapi_event_throttle_equal() */
179 QEMUTimer *timer; /* Timer for handling delayed events */
180 QDict *qdict; /* Delayed event (if any) */
181 } MonitorQAPIEventState;
184 int64_t rate; /* Minimum time (in ns) between two events */
185 } MonitorQAPIEventConf;
198 /* Read under either BQL or out_lock, written with BQL+out_lock. */
204 BlockCompletionFunc *password_completion_cb;
205 void *password_opaque;
206 mon_cmd_t *cmd_table;
207 QLIST_HEAD(,mon_fd_t) fds;
208 QLIST_ENTRY(Monitor) entry;
211 /* QMP checker flags */
212 #define QMP_ACCEPT_UNKNOWNS 1
214 /* Protects mon_list, monitor_event_state. */
215 static QemuMutex monitor_lock;
217 static QLIST_HEAD(mon_list, Monitor) mon_list;
218 static QLIST_HEAD(mon_fdsets, MonFdset) mon_fdsets;
219 static int mon_refcount;
221 static mon_cmd_t mon_cmds[];
222 static mon_cmd_t info_cmds[];
226 static QEMUClockType event_clock_type = QEMU_CLOCK_REALTIME;
228 static void monitor_command_cb(void *opaque, const char *cmdline,
229 void *readline_opaque);
232 * Is @mon a QMP monitor?
234 static inline bool monitor_is_qmp(const Monitor *mon)
236 return (mon->flags & MONITOR_USE_CONTROL);
240 * Is the current monitor, if any, a QMP monitor?
242 bool monitor_cur_is_qmp(void)
244 return cur_mon && monitor_is_qmp(cur_mon);
247 void monitor_read_command(Monitor *mon, int show_prompt)
252 readline_start(mon->rs, "(qemu) ", 0, monitor_command_cb, NULL);
254 readline_show_prompt(mon->rs);
257 int monitor_read_password(Monitor *mon, ReadLineFunc *readline_func,
261 readline_start(mon->rs, "Password: ", 1, readline_func, opaque);
262 /* prompt is printed on return from the command handler */
265 monitor_printf(mon, "terminal does not support password prompting\n");
270 static void monitor_flush_locked(Monitor *mon);
272 static gboolean monitor_unblocked(GIOChannel *chan, GIOCondition cond,
275 Monitor *mon = opaque;
277 qemu_mutex_lock(&mon->out_lock);
279 monitor_flush_locked(mon);
280 qemu_mutex_unlock(&mon->out_lock);
284 /* Called with mon->out_lock held. */
285 static void monitor_flush_locked(Monitor *mon)
291 if (mon->skip_flush) {
295 buf = qstring_get_str(mon->outbuf);
296 len = qstring_get_length(mon->outbuf);
298 if (len && !mon->mux_out) {
299 rc = qemu_chr_fe_write(&mon->chr, (const uint8_t *) buf, len);
300 if ((rc < 0 && errno != EAGAIN) || (rc == len)) {
301 /* all flushed or error */
302 QDECREF(mon->outbuf);
303 mon->outbuf = qstring_new();
308 QString *tmp = qstring_from_str(buf + rc);
309 QDECREF(mon->outbuf);
312 if (mon->out_watch == 0) {
314 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)
584 qemu_chr_fe_deinit(&mon->chr);
585 if (monitor_is_qmp(mon)) {
586 json_message_parser_destroy(&mon->qmp.parser);
589 QDECREF(mon->outbuf);
590 qemu_mutex_destroy(&mon->out_lock);
593 char *qmp_human_monitor_command(const char *command_line, bool has_cpu_index,
594 int64_t cpu_index, Error **errp)
597 Monitor *old_mon, hmp;
599 monitor_data_init(&hmp);
600 hmp.skip_flush = true;
606 int ret = monitor_set_cpu(cpu_index);
609 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cpu-index",
615 handle_hmp_command(&hmp, command_line);
618 qemu_mutex_lock(&hmp.out_lock);
619 if (qstring_get_length(hmp.outbuf) > 0) {
620 output = g_strdup(qstring_get_str(hmp.outbuf));
622 output = g_strdup("");
624 qemu_mutex_unlock(&hmp.out_lock);
627 monitor_data_destroy(&hmp);
631 static int compare_cmd(const char *name, const char *list)
633 const char *p, *pstart;
641 p = pstart + strlen(pstart);
642 if ((p - pstart) == len && !memcmp(pstart, name, len))
651 static int get_str(char *buf, int buf_size, const char **pp)
659 while (qemu_isspace(*p)) {
670 while (*p != '\0' && *p != '\"') {
686 printf("unsupported escape code: '\\%c'\n", c);
689 if ((q - buf) < buf_size - 1) {
693 if ((q - buf) < buf_size - 1) {
700 printf("unterminated string\n");
705 while (*p != '\0' && !qemu_isspace(*p)) {
706 if ((q - buf) < buf_size - 1) {
719 static void free_cmdline_args(char **args, int nb_args)
723 assert(nb_args <= MAX_ARGS);
725 for (i = 0; i < nb_args; i++) {
732 * Parse the command line to get valid args.
733 * @cmdline: command line to be parsed.
734 * @pnb_args: location to store the number of args, must NOT be NULL.
735 * @args: location to store the args, which should be freed by caller, must
738 * Returns 0 on success, negative on failure.
740 * NOTE: this parser is an approximate form of the real command parser. Number
741 * of args have a limit of MAX_ARGS. If cmdline contains more, it will
742 * return with failure.
744 static int parse_cmdline(const char *cmdline,
745 int *pnb_args, char **args)
754 while (qemu_isspace(*p)) {
760 if (nb_args >= MAX_ARGS) {
763 ret = get_str(buf, sizeof(buf), &p);
767 args[nb_args] = g_strdup(buf);
774 free_cmdline_args(args, nb_args);
778 static void help_cmd_dump_one(Monitor *mon,
779 const mon_cmd_t *cmd,
785 for (i = 0; i < prefix_args_nb; i++) {
786 monitor_printf(mon, "%s ", prefix_args[i]);
788 monitor_printf(mon, "%s %s -- %s\n", cmd->name, cmd->params, cmd->help);
791 /* @args[@arg_index] is the valid command need to find in @cmds */
792 static void help_cmd_dump(Monitor *mon, const mon_cmd_t *cmds,
793 char **args, int nb_args, int arg_index)
795 const mon_cmd_t *cmd;
797 /* No valid arg need to compare with, dump all in *cmds */
798 if (arg_index >= nb_args) {
799 for (cmd = cmds; cmd->name != NULL; cmd++) {
800 help_cmd_dump_one(mon, cmd, args, arg_index);
805 /* Find one entry to dump */
806 for (cmd = cmds; cmd->name != NULL; cmd++) {
807 if (compare_cmd(args[arg_index], cmd->name)) {
808 if (cmd->sub_table) {
809 /* continue with next arg */
810 help_cmd_dump(mon, cmd->sub_table,
811 args, nb_args, arg_index + 1);
813 help_cmd_dump_one(mon, cmd, args, arg_index);
820 static void help_cmd(Monitor *mon, const char *name)
822 char *args[MAX_ARGS];
825 /* 1. parse user input */
827 /* special case for log, directly dump and return */
828 if (!strcmp(name, "log")) {
829 const QEMULogItem *item;
830 monitor_printf(mon, "Log items (comma separated):\n");
831 monitor_printf(mon, "%-10s %s\n", "none", "remove all logs");
832 for (item = qemu_log_items; item->mask != 0; item++) {
833 monitor_printf(mon, "%-10s %s\n", item->name, item->help);
838 if (parse_cmdline(name, &nb_args, args) < 0) {
843 /* 2. dump the contents according to parsed args */
844 help_cmd_dump(mon, mon->cmd_table, args, nb_args, 0);
846 free_cmdline_args(args, nb_args);
849 static void do_help_cmd(Monitor *mon, const QDict *qdict)
851 help_cmd(mon, qdict_get_try_str(qdict, "name"));
854 static void hmp_trace_event(Monitor *mon, const QDict *qdict)
856 const char *tp_name = qdict_get_str(qdict, "name");
857 bool new_state = qdict_get_bool(qdict, "option");
858 bool has_vcpu = qdict_haskey(qdict, "vcpu");
859 int vcpu = qdict_get_try_int(qdict, "vcpu", 0);
860 Error *local_err = NULL;
863 monitor_printf(mon, "argument vcpu must be positive");
867 qmp_trace_event_set_state(tp_name, new_state, true, true, has_vcpu, vcpu, &local_err);
869 error_report_err(local_err);
873 #ifdef CONFIG_TRACE_SIMPLE
874 static void hmp_trace_file(Monitor *mon, const QDict *qdict)
876 const char *op = qdict_get_try_str(qdict, "op");
877 const char *arg = qdict_get_try_str(qdict, "arg");
880 st_print_trace_file_status((FILE *)mon, &monitor_fprintf);
881 } else if (!strcmp(op, "on")) {
882 st_set_trace_file_enabled(true);
883 } else if (!strcmp(op, "off")) {
884 st_set_trace_file_enabled(false);
885 } else if (!strcmp(op, "flush")) {
886 st_flush_trace_buffer();
887 } else if (!strcmp(op, "set")) {
889 st_set_trace_file(arg);
892 monitor_printf(mon, "unexpected argument \"%s\"\n", op);
893 help_cmd(mon, "trace-file");
898 static void hmp_info_help(Monitor *mon, const QDict *qdict)
900 help_cmd(mon, "info");
903 static void query_commands_cb(QmpCommand *cmd, void *opaque)
905 CommandInfoList *info, **list = opaque;
911 info = g_malloc0(sizeof(*info));
912 info->value = g_malloc0(sizeof(*info->value));
913 info->value->name = g_strdup(cmd->name);
918 CommandInfoList *qmp_query_commands(Error **errp)
920 CommandInfoList *list = NULL;
922 qmp_for_each_command(query_commands_cb, &list);
927 EventInfoList *qmp_query_events(Error **errp)
929 EventInfoList *info, *ev_list = NULL;
932 for (e = 0 ; e < QAPI_EVENT__MAX ; e++) {
933 const char *event_name = QAPIEvent_lookup[e];
934 assert(event_name != NULL);
935 info = g_malloc0(sizeof(*info));
936 info->value = g_malloc0(sizeof(*info->value));
937 info->value->name = g_strdup(event_name);
939 info->next = ev_list;
947 * Minor hack: generated marshalling suppressed for this command
948 * ('gen': false in the schema) so we can parse the JSON string
949 * directly into QObject instead of first parsing it with
950 * visit_type_SchemaInfoList() into a SchemaInfoList, then marshal it
951 * to QObject with generated output marshallers, every time. Instead,
952 * we do it in test-qobject-input-visitor.c, just to make sure
953 * qapi-introspect.py's output actually conforms to the schema.
955 static void qmp_query_qmp_schema(QDict *qdict, QObject **ret_data,
958 *ret_data = qobject_from_json(qmp_schema_json);
962 * We used to define commands in qmp-commands.hx in addition to the
963 * QAPI schema. This permitted defining some of them only in certain
964 * configurations. query-commands has always reflected that (good,
965 * because it lets QMP clients figure out what's actually available),
966 * while query-qmp-schema never did (not so good). This function is a
967 * hack to keep the configuration-specific commands defined exactly as
968 * before, even though qmp-commands.hx is gone.
970 * FIXME Educate the QAPI schema on configuration-specific commands,
971 * and drop this hack.
973 static void qmp_unregister_commands_hack(void)
976 qmp_unregister_command("query-spice");
979 qmp_unregister_command("rtc-reset-reinjection");
982 qmp_unregister_command("dump-skeys");
985 qmp_unregister_command("query-gic-capabilities");
987 #if !defined(TARGET_S390X) && !defined(TARGET_I386)
988 qmp_unregister_command("query-cpu-model-expansion");
990 #if !defined(TARGET_S390X)
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 void monitor_init_qmp_commands(void)
1004 qmp_register_command("query-qmp-schema", qmp_query_qmp_schema,
1006 qmp_register_command("device_add", qmp_device_add,
1008 qmp_register_command("netdev_add", qmp_netdev_add,
1011 qmp_unregister_commands_hack();
1014 /* set the current CPU defined by the user */
1015 int monitor_set_cpu(int cpu_index)
1019 cpu = qemu_get_cpu(cpu_index);
1023 cur_mon->mon_cpu = cpu;
1027 CPUState *mon_get_cpu(void)
1029 if (!cur_mon->mon_cpu) {
1033 monitor_set_cpu(first_cpu->cpu_index);
1035 cpu_synchronize_state(cur_mon->mon_cpu);
1036 return cur_mon->mon_cpu;
1039 CPUArchState *mon_get_cpu_env(void)
1041 CPUState *cs = mon_get_cpu();
1043 return cs ? cs->env_ptr : NULL;
1046 int monitor_get_cpu_index(void)
1048 CPUState *cs = mon_get_cpu();
1050 return cs ? cs->cpu_index : UNASSIGNED_CPU_INDEX;
1053 static void hmp_info_registers(Monitor *mon, const QDict *qdict)
1055 CPUState *cs = mon_get_cpu();
1058 monitor_printf(mon, "No CPU available\n");
1061 cpu_dump_state(cs, (FILE *)mon, monitor_fprintf, CPU_DUMP_FPU);
1064 static void hmp_info_jit(Monitor *mon, const QDict *qdict)
1066 dump_exec_info((FILE *)mon, monitor_fprintf);
1067 dump_drift_info((FILE *)mon, monitor_fprintf);
1070 static void hmp_info_opcount(Monitor *mon, const QDict *qdict)
1072 dump_opcount_info((FILE *)mon, monitor_fprintf);
1075 static void hmp_info_history(Monitor *mon, const QDict *qdict)
1084 str = readline_get_history(mon->rs, i);
1087 monitor_printf(mon, "%d: '%s'\n", i, str);
1092 static void hmp_info_cpustats(Monitor *mon, const QDict *qdict)
1094 CPUState *cs = mon_get_cpu();
1097 monitor_printf(mon, "No CPU available\n");
1100 cpu_dump_statistics(cs, (FILE *)mon, &monitor_fprintf, 0);
1103 static void hmp_info_trace_events(Monitor *mon, const QDict *qdict)
1105 const char *name = qdict_get_try_str(qdict, "name");
1106 bool has_vcpu = qdict_haskey(qdict, "vcpu");
1107 int vcpu = qdict_get_try_int(qdict, "vcpu", 0);
1108 TraceEventInfoList *events;
1109 TraceEventInfoList *elem;
1110 Error *local_err = NULL;
1116 monitor_printf(mon, "argument vcpu must be positive");
1120 events = qmp_trace_event_get_state(name, has_vcpu, vcpu, &local_err);
1122 error_report_err(local_err);
1126 for (elem = events; elem != NULL; elem = elem->next) {
1127 monitor_printf(mon, "%s : state %u\n",
1129 elem->value->state == TRACE_EVENT_STATE_ENABLED ? 1 : 0);
1131 qapi_free_TraceEventInfoList(events);
1134 void qmp_client_migrate_info(const char *protocol, const char *hostname,
1135 bool has_port, int64_t port,
1136 bool has_tls_port, int64_t tls_port,
1137 bool has_cert_subject, const char *cert_subject,
1140 if (strcmp(protocol, "spice") == 0) {
1141 if (!qemu_using_spice(errp)) {
1145 if (!has_port && !has_tls_port) {
1146 error_setg(errp, QERR_MISSING_PARAMETER, "port/tls-port");
1150 if (qemu_spice_migrate_info(hostname,
1151 has_port ? port : -1,
1152 has_tls_port ? tls_port : -1,
1154 error_setg(errp, QERR_UNDEFINED_ERROR);
1160 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "protocol", "spice");
1163 static void hmp_logfile(Monitor *mon, const QDict *qdict)
1167 qemu_set_log_filename(qdict_get_str(qdict, "filename"), &err);
1169 error_report_err(err);
1173 static void hmp_log(Monitor *mon, const QDict *qdict)
1176 const char *items = qdict_get_str(qdict, "items");
1178 if (!strcmp(items, "none")) {
1181 mask = qemu_str_to_log_mask(items);
1183 help_cmd(mon, "log");
1190 static void hmp_singlestep(Monitor *mon, const QDict *qdict)
1192 const char *option = qdict_get_try_str(qdict, "option");
1193 if (!option || !strcmp(option, "on")) {
1195 } else if (!strcmp(option, "off")) {
1198 monitor_printf(mon, "unexpected option %s\n", option);
1202 static void hmp_gdbserver(Monitor *mon, const QDict *qdict)
1204 const char *device = qdict_get_try_str(qdict, "device");
1206 device = "tcp::" DEFAULT_GDBSTUB_PORT;
1207 if (gdbserver_start(device) < 0) {
1208 monitor_printf(mon, "Could not open gdbserver on device '%s'\n",
1210 } else if (strcmp(device, "none") == 0) {
1211 monitor_printf(mon, "Disabled gdbserver\n");
1213 monitor_printf(mon, "Waiting for gdb connection on device '%s'\n",
1218 static void hmp_watchdog_action(Monitor *mon, const QDict *qdict)
1220 const char *action = qdict_get_str(qdict, "action");
1221 if (select_watchdog_action(action) == -1) {
1222 monitor_printf(mon, "Unknown watchdog action '%s'\n", action);
1226 static void monitor_printc(Monitor *mon, int c)
1228 monitor_printf(mon, "'");
1231 monitor_printf(mon, "\\'");
1234 monitor_printf(mon, "\\\\");
1237 monitor_printf(mon, "\\n");
1240 monitor_printf(mon, "\\r");
1243 if (c >= 32 && c <= 126) {
1244 monitor_printf(mon, "%c", c);
1246 monitor_printf(mon, "\\x%02x", c);
1250 monitor_printf(mon, "'");
1253 static void memory_dump(Monitor *mon, int count, int format, int wsize,
1254 hwaddr addr, int is_physical)
1256 int l, line_size, i, max_digits, len;
1259 CPUState *cs = mon_get_cpu();
1261 if (!cs && (format == 'i' || !is_physical)) {
1262 monitor_printf(mon, "Can not dump without CPU\n");
1266 if (format == 'i') {
1269 CPUArchState *env = mon_get_cpu_env();
1272 } else if (wsize == 4) {
1275 /* as default we use the current CS size */
1278 #ifdef TARGET_X86_64
1279 if ((env->efer & MSR_EFER_LMA) &&
1280 (env->segs[R_CS].flags & DESC_L_MASK))
1284 if (!(env->segs[R_CS].flags & DESC_B_MASK))
1290 CPUArchState *env = mon_get_cpu_env();
1291 flags = msr_le << 16;
1292 flags |= env->bfd_mach;
1294 monitor_disas(mon, cs, addr, count, is_physical, flags);
1298 len = wsize * count;
1307 max_digits = (wsize * 8 + 2) / 3;
1311 max_digits = (wsize * 8) / 4;
1315 max_digits = (wsize * 8 * 10 + 32) / 33;
1324 monitor_printf(mon, TARGET_FMT_plx ":", addr);
1326 monitor_printf(mon, TARGET_FMT_lx ":", (target_ulong)addr);
1331 cpu_physical_memory_read(addr, buf, l);
1333 if (cpu_memory_rw_debug(cs, addr, buf, l, 0) < 0) {
1334 monitor_printf(mon, " Cannot access memory\n");
1343 v = ldub_p(buf + i);
1346 v = lduw_p(buf + i);
1349 v = (uint32_t)ldl_p(buf + i);
1355 monitor_printf(mon, " ");
1358 monitor_printf(mon, "%#*" PRIo64, max_digits, v);
1361 monitor_printf(mon, "0x%0*" PRIx64, max_digits, v);
1364 monitor_printf(mon, "%*" PRIu64, max_digits, v);
1367 monitor_printf(mon, "%*" PRId64, max_digits, v);
1370 monitor_printc(mon, v);
1375 monitor_printf(mon, "\n");
1381 static void hmp_memory_dump(Monitor *mon, const QDict *qdict)
1383 int count = qdict_get_int(qdict, "count");
1384 int format = qdict_get_int(qdict, "format");
1385 int size = qdict_get_int(qdict, "size");
1386 target_long addr = qdict_get_int(qdict, "addr");
1388 memory_dump(mon, count, format, size, addr, 0);
1391 static void hmp_physical_memory_dump(Monitor *mon, const QDict *qdict)
1393 int count = qdict_get_int(qdict, "count");
1394 int format = qdict_get_int(qdict, "format");
1395 int size = qdict_get_int(qdict, "size");
1396 hwaddr addr = qdict_get_int(qdict, "addr");
1398 memory_dump(mon, count, format, size, addr, 1);
1401 static void do_print(Monitor *mon, const QDict *qdict)
1403 int format = qdict_get_int(qdict, "format");
1404 hwaddr val = qdict_get_int(qdict, "val");
1408 monitor_printf(mon, "%#" HWADDR_PRIo, val);
1411 monitor_printf(mon, "%#" HWADDR_PRIx, val);
1414 monitor_printf(mon, "%" HWADDR_PRIu, val);
1418 monitor_printf(mon, "%" HWADDR_PRId, val);
1421 monitor_printc(mon, val);
1424 monitor_printf(mon, "\n");
1427 static void hmp_sum(Monitor *mon, const QDict *qdict)
1431 uint32_t start = qdict_get_int(qdict, "start");
1432 uint32_t size = qdict_get_int(qdict, "size");
1435 for(addr = start; addr < (start + size); addr++) {
1436 uint8_t val = address_space_ldub(&address_space_memory, addr,
1437 MEMTXATTRS_UNSPECIFIED, NULL);
1438 /* BSD sum algorithm ('sum' Unix command) */
1439 sum = (sum >> 1) | (sum << 15);
1442 monitor_printf(mon, "%05d\n", sum);
1445 static int mouse_button_state;
1447 static void hmp_mouse_move(Monitor *mon, const QDict *qdict)
1449 int dx, dy, dz, button;
1450 const char *dx_str = qdict_get_str(qdict, "dx_str");
1451 const char *dy_str = qdict_get_str(qdict, "dy_str");
1452 const char *dz_str = qdict_get_try_str(qdict, "dz_str");
1454 dx = strtol(dx_str, NULL, 0);
1455 dy = strtol(dy_str, NULL, 0);
1456 qemu_input_queue_rel(NULL, INPUT_AXIS_X, dx);
1457 qemu_input_queue_rel(NULL, INPUT_AXIS_Y, dy);
1460 dz = strtol(dz_str, NULL, 0);
1462 button = (dz > 0) ? INPUT_BUTTON_WHEEL_UP : INPUT_BUTTON_WHEEL_DOWN;
1463 qemu_input_queue_btn(NULL, button, true);
1464 qemu_input_event_sync();
1465 qemu_input_queue_btn(NULL, button, false);
1468 qemu_input_event_sync();
1471 static void hmp_mouse_button(Monitor *mon, const QDict *qdict)
1473 static uint32_t bmap[INPUT_BUTTON__MAX] = {
1474 [INPUT_BUTTON_LEFT] = MOUSE_EVENT_LBUTTON,
1475 [INPUT_BUTTON_MIDDLE] = MOUSE_EVENT_MBUTTON,
1476 [INPUT_BUTTON_RIGHT] = MOUSE_EVENT_RBUTTON,
1478 int button_state = qdict_get_int(qdict, "button_state");
1480 if (mouse_button_state == button_state) {
1483 qemu_input_update_buttons(NULL, bmap, mouse_button_state, button_state);
1484 qemu_input_event_sync();
1485 mouse_button_state = button_state;
1488 static void hmp_ioport_read(Monitor *mon, const QDict *qdict)
1490 int size = qdict_get_int(qdict, "size");
1491 int addr = qdict_get_int(qdict, "addr");
1492 int has_index = qdict_haskey(qdict, "index");
1497 int index = qdict_get_int(qdict, "index");
1498 cpu_outb(addr & IOPORTS_MASK, index & 0xff);
1506 val = cpu_inb(addr);
1510 val = cpu_inw(addr);
1514 val = cpu_inl(addr);
1518 monitor_printf(mon, "port%c[0x%04x] = %#0*x\n",
1519 suffix, addr, size * 2, val);
1522 static void hmp_ioport_write(Monitor *mon, const QDict *qdict)
1524 int size = qdict_get_int(qdict, "size");
1525 int addr = qdict_get_int(qdict, "addr");
1526 int val = qdict_get_int(qdict, "val");
1528 addr &= IOPORTS_MASK;
1533 cpu_outb(addr, val);
1536 cpu_outw(addr, val);
1539 cpu_outl(addr, val);
1544 static void hmp_boot_set(Monitor *mon, const QDict *qdict)
1546 Error *local_err = NULL;
1547 const char *bootdevice = qdict_get_str(qdict, "bootdevice");
1549 qemu_boot_set(bootdevice, &local_err);
1551 error_report_err(local_err);
1553 monitor_printf(mon, "boot device list now set to %s\n", bootdevice);
1557 static void hmp_info_mtree(Monitor *mon, const QDict *qdict)
1559 bool flatview = qdict_get_try_bool(qdict, "flatview", false);
1561 mtree_info((fprintf_function)monitor_printf, mon, flatview);
1564 static void hmp_info_numa(Monitor *mon, const QDict *qdict)
1570 node_mem = g_new0(uint64_t, nb_numa_nodes);
1571 query_numa_node_mem(node_mem);
1572 monitor_printf(mon, "%d nodes\n", nb_numa_nodes);
1573 for (i = 0; i < nb_numa_nodes; i++) {
1574 monitor_printf(mon, "node %d cpus:", i);
1576 if (cpu->numa_node == i) {
1577 monitor_printf(mon, " %d", cpu->cpu_index);
1580 monitor_printf(mon, "\n");
1581 monitor_printf(mon, "node %d size: %" PRId64 " MB\n", i,
1587 #ifdef CONFIG_PROFILER
1592 static void hmp_info_profile(Monitor *mon, const QDict *qdict)
1594 monitor_printf(mon, "async time %" PRId64 " (%0.3f)\n",
1595 dev_time, dev_time / (double)NANOSECONDS_PER_SECOND);
1596 monitor_printf(mon, "qemu time %" PRId64 " (%0.3f)\n",
1597 tcg_time, tcg_time / (double)NANOSECONDS_PER_SECOND);
1602 static void hmp_info_profile(Monitor *mon, const QDict *qdict)
1604 monitor_printf(mon, "Internal profiler not compiled\n");
1608 /* Capture support */
1609 static QLIST_HEAD (capture_list_head, CaptureState) capture_head;
1611 static void hmp_info_capture(Monitor *mon, const QDict *qdict)
1616 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
1617 monitor_printf(mon, "[%d]: ", i);
1618 s->ops.info (s->opaque);
1622 static void hmp_stopcapture(Monitor *mon, const QDict *qdict)
1625 int n = qdict_get_int(qdict, "n");
1628 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
1630 s->ops.destroy (s->opaque);
1631 QLIST_REMOVE (s, entries);
1638 static void hmp_wavcapture(Monitor *mon, const QDict *qdict)
1640 const char *path = qdict_get_str(qdict, "path");
1641 int has_freq = qdict_haskey(qdict, "freq");
1642 int freq = qdict_get_try_int(qdict, "freq", -1);
1643 int has_bits = qdict_haskey(qdict, "bits");
1644 int bits = qdict_get_try_int(qdict, "bits", -1);
1645 int has_channels = qdict_haskey(qdict, "nchannels");
1646 int nchannels = qdict_get_try_int(qdict, "nchannels", -1);
1649 s = g_malloc0 (sizeof (*s));
1651 freq = has_freq ? freq : 44100;
1652 bits = has_bits ? bits : 16;
1653 nchannels = has_channels ? nchannels : 2;
1655 if (wav_start_capture (s, path, freq, bits, nchannels)) {
1656 monitor_printf(mon, "Failed to add wave capture\n");
1660 QLIST_INSERT_HEAD (&capture_head, s, entries);
1663 static qemu_acl *find_acl(Monitor *mon, const char *name)
1665 qemu_acl *acl = qemu_acl_find(name);
1668 monitor_printf(mon, "acl: unknown list '%s'\n", name);
1673 static void hmp_acl_show(Monitor *mon, const QDict *qdict)
1675 const char *aclname = qdict_get_str(qdict, "aclname");
1676 qemu_acl *acl = find_acl(mon, aclname);
1677 qemu_acl_entry *entry;
1681 monitor_printf(mon, "policy: %s\n",
1682 acl->defaultDeny ? "deny" : "allow");
1683 QTAILQ_FOREACH(entry, &acl->entries, next) {
1685 monitor_printf(mon, "%d: %s %s\n", i,
1686 entry->deny ? "deny" : "allow", entry->match);
1691 static void hmp_acl_reset(Monitor *mon, const QDict *qdict)
1693 const char *aclname = qdict_get_str(qdict, "aclname");
1694 qemu_acl *acl = find_acl(mon, aclname);
1697 qemu_acl_reset(acl);
1698 monitor_printf(mon, "acl: removed all rules\n");
1702 static void hmp_acl_policy(Monitor *mon, const QDict *qdict)
1704 const char *aclname = qdict_get_str(qdict, "aclname");
1705 const char *policy = qdict_get_str(qdict, "policy");
1706 qemu_acl *acl = find_acl(mon, aclname);
1709 if (strcmp(policy, "allow") == 0) {
1710 acl->defaultDeny = 0;
1711 monitor_printf(mon, "acl: policy set to 'allow'\n");
1712 } else if (strcmp(policy, "deny") == 0) {
1713 acl->defaultDeny = 1;
1714 monitor_printf(mon, "acl: policy set to 'deny'\n");
1716 monitor_printf(mon, "acl: unknown policy '%s', "
1717 "expected 'deny' or 'allow'\n", policy);
1722 static void hmp_acl_add(Monitor *mon, const QDict *qdict)
1724 const char *aclname = qdict_get_str(qdict, "aclname");
1725 const char *match = qdict_get_str(qdict, "match");
1726 const char *policy = qdict_get_str(qdict, "policy");
1727 int has_index = qdict_haskey(qdict, "index");
1728 int index = qdict_get_try_int(qdict, "index", -1);
1729 qemu_acl *acl = find_acl(mon, aclname);
1733 if (strcmp(policy, "allow") == 0) {
1735 } else if (strcmp(policy, "deny") == 0) {
1738 monitor_printf(mon, "acl: unknown policy '%s', "
1739 "expected 'deny' or 'allow'\n", policy);
1743 ret = qemu_acl_insert(acl, deny, match, index);
1745 ret = qemu_acl_append(acl, deny, match);
1747 monitor_printf(mon, "acl: unable to add acl entry\n");
1749 monitor_printf(mon, "acl: added rule at position %d\n", ret);
1753 static void hmp_acl_remove(Monitor *mon, const QDict *qdict)
1755 const char *aclname = qdict_get_str(qdict, "aclname");
1756 const char *match = qdict_get_str(qdict, "match");
1757 qemu_acl *acl = find_acl(mon, aclname);
1761 ret = qemu_acl_remove(acl, match);
1763 monitor_printf(mon, "acl: no matching acl entry\n");
1765 monitor_printf(mon, "acl: removed rule at position %d\n", ret);
1769 void qmp_getfd(const char *fdname, Error **errp)
1774 fd = qemu_chr_fe_get_msgfd(&cur_mon->chr);
1776 error_setg(errp, QERR_FD_NOT_SUPPLIED);
1780 if (qemu_isdigit(fdname[0])) {
1782 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "fdname",
1783 "a name not starting with a digit");
1787 QLIST_FOREACH(monfd, &cur_mon->fds, next) {
1788 if (strcmp(monfd->name, fdname) != 0) {
1797 monfd = g_malloc0(sizeof(mon_fd_t));
1798 monfd->name = g_strdup(fdname);
1801 QLIST_INSERT_HEAD(&cur_mon->fds, monfd, next);
1804 void qmp_closefd(const char *fdname, Error **errp)
1808 QLIST_FOREACH(monfd, &cur_mon->fds, next) {
1809 if (strcmp(monfd->name, fdname) != 0) {
1813 QLIST_REMOVE(monfd, next);
1815 g_free(monfd->name);
1820 error_setg(errp, QERR_FD_NOT_FOUND, fdname);
1823 static void hmp_loadvm(Monitor *mon, const QDict *qdict)
1825 int saved_vm_running = runstate_is_running();
1826 const char *name = qdict_get_str(qdict, "name");
1828 vm_stop(RUN_STATE_RESTORE_VM);
1830 if (load_vmstate(name) == 0 && saved_vm_running) {
1835 int monitor_get_fd(Monitor *mon, const char *fdname, Error **errp)
1839 QLIST_FOREACH(monfd, &mon->fds, next) {
1842 if (strcmp(monfd->name, fdname) != 0) {
1848 /* caller takes ownership of fd */
1849 QLIST_REMOVE(monfd, next);
1850 g_free(monfd->name);
1856 error_setg(errp, "File descriptor named '%s' has not been found", fdname);
1860 static void monitor_fdset_cleanup(MonFdset *mon_fdset)
1862 MonFdsetFd *mon_fdset_fd;
1863 MonFdsetFd *mon_fdset_fd_next;
1865 QLIST_FOREACH_SAFE(mon_fdset_fd, &mon_fdset->fds, next, mon_fdset_fd_next) {
1866 if ((mon_fdset_fd->removed ||
1867 (QLIST_EMPTY(&mon_fdset->dup_fds) && mon_refcount == 0)) &&
1868 runstate_is_running()) {
1869 close(mon_fdset_fd->fd);
1870 g_free(mon_fdset_fd->opaque);
1871 QLIST_REMOVE(mon_fdset_fd, next);
1872 g_free(mon_fdset_fd);
1876 if (QLIST_EMPTY(&mon_fdset->fds) && QLIST_EMPTY(&mon_fdset->dup_fds)) {
1877 QLIST_REMOVE(mon_fdset, next);
1882 static void monitor_fdsets_cleanup(void)
1884 MonFdset *mon_fdset;
1885 MonFdset *mon_fdset_next;
1887 QLIST_FOREACH_SAFE(mon_fdset, &mon_fdsets, next, mon_fdset_next) {
1888 monitor_fdset_cleanup(mon_fdset);
1892 AddfdInfo *qmp_add_fd(bool has_fdset_id, int64_t fdset_id, bool has_opaque,
1893 const char *opaque, Error **errp)
1896 Monitor *mon = cur_mon;
1899 fd = qemu_chr_fe_get_msgfd(&mon->chr);
1901 error_setg(errp, QERR_FD_NOT_SUPPLIED);
1905 fdinfo = monitor_fdset_add_fd(fd, has_fdset_id, fdset_id,
1906 has_opaque, opaque, errp);
1918 void qmp_remove_fd(int64_t fdset_id, bool has_fd, int64_t fd, Error **errp)
1920 MonFdset *mon_fdset;
1921 MonFdsetFd *mon_fdset_fd;
1924 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
1925 if (mon_fdset->id != fdset_id) {
1928 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
1930 if (mon_fdset_fd->fd != fd) {
1933 mon_fdset_fd->removed = true;
1936 mon_fdset_fd->removed = true;
1939 if (has_fd && !mon_fdset_fd) {
1942 monitor_fdset_cleanup(mon_fdset);
1948 snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64 ", fd:%" PRId64,
1951 snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64, fdset_id);
1953 error_setg(errp, QERR_FD_NOT_FOUND, fd_str);
1956 FdsetInfoList *qmp_query_fdsets(Error **errp)
1958 MonFdset *mon_fdset;
1959 MonFdsetFd *mon_fdset_fd;
1960 FdsetInfoList *fdset_list = NULL;
1962 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
1963 FdsetInfoList *fdset_info = g_malloc0(sizeof(*fdset_info));
1964 FdsetFdInfoList *fdsetfd_list = NULL;
1966 fdset_info->value = g_malloc0(sizeof(*fdset_info->value));
1967 fdset_info->value->fdset_id = mon_fdset->id;
1969 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
1970 FdsetFdInfoList *fdsetfd_info;
1972 fdsetfd_info = g_malloc0(sizeof(*fdsetfd_info));
1973 fdsetfd_info->value = g_malloc0(sizeof(*fdsetfd_info->value));
1974 fdsetfd_info->value->fd = mon_fdset_fd->fd;
1975 if (mon_fdset_fd->opaque) {
1976 fdsetfd_info->value->has_opaque = true;
1977 fdsetfd_info->value->opaque = g_strdup(mon_fdset_fd->opaque);
1979 fdsetfd_info->value->has_opaque = false;
1982 fdsetfd_info->next = fdsetfd_list;
1983 fdsetfd_list = fdsetfd_info;
1986 fdset_info->value->fds = fdsetfd_list;
1988 fdset_info->next = fdset_list;
1989 fdset_list = fdset_info;
1995 AddfdInfo *monitor_fdset_add_fd(int fd, bool has_fdset_id, int64_t fdset_id,
1996 bool has_opaque, const char *opaque,
1999 MonFdset *mon_fdset = NULL;
2000 MonFdsetFd *mon_fdset_fd;
2004 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2005 /* Break if match found or match impossible due to ordering by ID */
2006 if (fdset_id <= mon_fdset->id) {
2007 if (fdset_id < mon_fdset->id) {
2015 if (mon_fdset == NULL) {
2016 int64_t fdset_id_prev = -1;
2017 MonFdset *mon_fdset_cur = QLIST_FIRST(&mon_fdsets);
2021 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "fdset-id",
2022 "a non-negative value");
2025 /* Use specified fdset ID */
2026 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2027 mon_fdset_cur = mon_fdset;
2028 if (fdset_id < mon_fdset_cur->id) {
2033 /* Use first available fdset ID */
2034 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2035 mon_fdset_cur = mon_fdset;
2036 if (fdset_id_prev == mon_fdset_cur->id - 1) {
2037 fdset_id_prev = mon_fdset_cur->id;
2044 mon_fdset = g_malloc0(sizeof(*mon_fdset));
2046 mon_fdset->id = fdset_id;
2048 mon_fdset->id = fdset_id_prev + 1;
2051 /* The fdset list is ordered by fdset ID */
2052 if (!mon_fdset_cur) {
2053 QLIST_INSERT_HEAD(&mon_fdsets, mon_fdset, next);
2054 } else if (mon_fdset->id < mon_fdset_cur->id) {
2055 QLIST_INSERT_BEFORE(mon_fdset_cur, mon_fdset, next);
2057 QLIST_INSERT_AFTER(mon_fdset_cur, mon_fdset, next);
2061 mon_fdset_fd = g_malloc0(sizeof(*mon_fdset_fd));
2062 mon_fdset_fd->fd = fd;
2063 mon_fdset_fd->removed = false;
2065 mon_fdset_fd->opaque = g_strdup(opaque);
2067 QLIST_INSERT_HEAD(&mon_fdset->fds, mon_fdset_fd, next);
2069 fdinfo = g_malloc0(sizeof(*fdinfo));
2070 fdinfo->fdset_id = mon_fdset->id;
2071 fdinfo->fd = mon_fdset_fd->fd;
2076 int monitor_fdset_get_fd(int64_t fdset_id, int flags)
2079 MonFdset *mon_fdset;
2080 MonFdsetFd *mon_fdset_fd;
2083 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2084 if (mon_fdset->id != fdset_id) {
2087 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2088 mon_fd_flags = fcntl(mon_fdset_fd->fd, F_GETFL);
2089 if (mon_fd_flags == -1) {
2093 if ((flags & O_ACCMODE) == (mon_fd_flags & O_ACCMODE)) {
2094 return mon_fdset_fd->fd;
2106 int monitor_fdset_dup_fd_add(int64_t fdset_id, int dup_fd)
2108 MonFdset *mon_fdset;
2109 MonFdsetFd *mon_fdset_fd_dup;
2111 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2112 if (mon_fdset->id != fdset_id) {
2115 QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
2116 if (mon_fdset_fd_dup->fd == dup_fd) {
2120 mon_fdset_fd_dup = g_malloc0(sizeof(*mon_fdset_fd_dup));
2121 mon_fdset_fd_dup->fd = dup_fd;
2122 QLIST_INSERT_HEAD(&mon_fdset->dup_fds, mon_fdset_fd_dup, next);
2128 static int monitor_fdset_dup_fd_find_remove(int dup_fd, bool remove)
2130 MonFdset *mon_fdset;
2131 MonFdsetFd *mon_fdset_fd_dup;
2133 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2134 QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
2135 if (mon_fdset_fd_dup->fd == dup_fd) {
2137 QLIST_REMOVE(mon_fdset_fd_dup, next);
2138 if (QLIST_EMPTY(&mon_fdset->dup_fds)) {
2139 monitor_fdset_cleanup(mon_fdset);
2143 return mon_fdset->id;
2151 int monitor_fdset_dup_fd_find(int dup_fd)
2153 return monitor_fdset_dup_fd_find_remove(dup_fd, false);
2156 void monitor_fdset_dup_fd_remove(int dup_fd)
2158 monitor_fdset_dup_fd_find_remove(dup_fd, true);
2161 int monitor_fd_param(Monitor *mon, const char *fdname, Error **errp)
2164 Error *local_err = NULL;
2166 if (!qemu_isdigit(fdname[0]) && mon) {
2167 fd = monitor_get_fd(mon, fdname, &local_err);
2169 fd = qemu_parse_fd(fdname);
2171 error_setg(&local_err, "Invalid file descriptor number '%s'",
2176 error_propagate(errp, local_err);
2185 /* Please update hmp-commands.hx when adding or changing commands */
2186 static mon_cmd_t info_cmds[] = {
2187 #include "hmp-commands-info.h"
2191 /* mon_cmds and info_cmds would be sorted at runtime */
2192 static mon_cmd_t mon_cmds[] = {
2193 #include "hmp-commands.h"
2197 /*******************************************************************/
2199 static const char *pch;
2200 static sigjmp_buf expr_env;
2203 static void GCC_FMT_ATTR(2, 3) QEMU_NORETURN
2204 expr_error(Monitor *mon, const char *fmt, ...)
2208 monitor_vprintf(mon, fmt, ap);
2209 monitor_printf(mon, "\n");
2211 siglongjmp(expr_env, 1);
2214 /* return 0 if OK, -1 if not found */
2215 static int get_monitor_def(target_long *pval, const char *name)
2217 const MonitorDef *md = target_monitor_defs();
2218 CPUState *cs = mon_get_cpu();
2223 if (cs == NULL || md == NULL) {
2227 for(; md->name != NULL; md++) {
2228 if (compare_cmd(name, md->name)) {
2229 if (md->get_value) {
2230 *pval = md->get_value(md, md->offset);
2232 CPUArchState *env = mon_get_cpu_env();
2233 ptr = (uint8_t *)env + md->offset;
2236 *pval = *(int32_t *)ptr;
2239 *pval = *(target_long *)ptr;
2250 ret = target_get_monitor_def(cs, name, &tmp);
2252 *pval = (target_long) tmp;
2258 static void next(void)
2262 while (qemu_isspace(*pch))
2267 static int64_t expr_sum(Monitor *mon);
2269 static int64_t expr_unary(Monitor *mon)
2278 n = expr_unary(mon);
2282 n = -expr_unary(mon);
2286 n = ~expr_unary(mon);
2292 expr_error(mon, "')' expected");
2299 expr_error(mon, "character constant expected");
2303 expr_error(mon, "missing terminating \' character");
2313 while ((*pch >= 'a' && *pch <= 'z') ||
2314 (*pch >= 'A' && *pch <= 'Z') ||
2315 (*pch >= '0' && *pch <= '9') ||
2316 *pch == '_' || *pch == '.') {
2317 if ((q - buf) < sizeof(buf) - 1)
2321 while (qemu_isspace(*pch))
2324 ret = get_monitor_def(®, buf);
2326 expr_error(mon, "unknown register");
2331 expr_error(mon, "unexpected end of expression");
2336 n = strtoull(pch, &p, 0);
2337 if (errno == ERANGE) {
2338 expr_error(mon, "number too large");
2341 expr_error(mon, "invalid char '%c' in expression", *p);
2344 while (qemu_isspace(*pch))
2352 static int64_t expr_prod(Monitor *mon)
2357 val = expr_unary(mon);
2360 if (op != '*' && op != '/' && op != '%')
2363 val2 = expr_unary(mon);
2372 expr_error(mon, "division by zero");
2383 static int64_t expr_logic(Monitor *mon)
2388 val = expr_prod(mon);
2391 if (op != '&' && op != '|' && op != '^')
2394 val2 = expr_prod(mon);
2411 static int64_t expr_sum(Monitor *mon)
2416 val = expr_logic(mon);
2419 if (op != '+' && op != '-')
2422 val2 = expr_logic(mon);
2431 static int get_expr(Monitor *mon, int64_t *pval, const char **pp)
2434 if (sigsetjmp(expr_env, 0)) {
2438 while (qemu_isspace(*pch))
2440 *pval = expr_sum(mon);
2445 static int get_double(Monitor *mon, double *pval, const char **pp)
2447 const char *p = *pp;
2451 d = strtod(p, &tailp);
2453 monitor_printf(mon, "Number expected\n");
2456 if (d != d || d - d != 0) {
2457 /* NaN or infinity */
2458 monitor_printf(mon, "Bad number\n");
2467 * Store the command-name in cmdname, and return a pointer to
2468 * the remaining of the command string.
2470 static const char *get_command_name(const char *cmdline,
2471 char *cmdname, size_t nlen)
2474 const char *p, *pstart;
2477 while (qemu_isspace(*p))
2482 while (*p != '\0' && *p != '/' && !qemu_isspace(*p))
2487 memcpy(cmdname, pstart, len);
2488 cmdname[len] = '\0';
2493 * Read key of 'type' into 'key' and return the current
2496 static char *key_get_info(const char *type, char **key)
2504 p = strchr(type, ':');
2511 str = g_malloc(len + 1);
2512 memcpy(str, type, len);
2519 static int default_fmt_format = 'x';
2520 static int default_fmt_size = 4;
2522 static int is_valid_option(const char *c, const char *typestr)
2530 typestr = strstr(typestr, option);
2531 return (typestr != NULL);
2534 static const mon_cmd_t *search_dispatch_table(const mon_cmd_t *disp_table,
2535 const char *cmdname)
2537 const mon_cmd_t *cmd;
2539 for (cmd = disp_table; cmd->name != NULL; cmd++) {
2540 if (compare_cmd(cmdname, cmd->name)) {
2549 * Parse command name from @cmdp according to command table @table.
2550 * If blank, return NULL.
2551 * Else, if no valid command can be found, report to @mon, and return
2553 * Else, change @cmdp to point right behind the name, and return its
2554 * command table entry.
2555 * Do not assume the return value points into @table! It doesn't when
2556 * the command is found in a sub-command table.
2558 static const mon_cmd_t *monitor_parse_command(Monitor *mon,
2563 const mon_cmd_t *cmd;
2566 /* extract the command name */
2567 p = get_command_name(*cmdp, cmdname, sizeof(cmdname));
2571 cmd = search_dispatch_table(table, cmdname);
2573 monitor_printf(mon, "unknown command: '%.*s'\n",
2574 (int)(p - *cmdp), *cmdp);
2578 /* filter out following useless space */
2579 while (qemu_isspace(*p)) {
2584 /* search sub command */
2585 if (cmd->sub_table != NULL && *p != '\0') {
2586 return monitor_parse_command(mon, cmdp, cmd->sub_table);
2593 * Parse arguments for @cmd.
2594 * If it can't be parsed, report to @mon, and return NULL.
2595 * Else, insert command arguments into a QDict, and return it.
2596 * Note: On success, caller has to free the QDict structure.
2599 static QDict *monitor_parse_arguments(Monitor *mon,
2601 const mon_cmd_t *cmd)
2603 const char *typestr;
2606 const char *p = *endp;
2608 QDict *qdict = qdict_new();
2610 /* parse the parameters */
2611 typestr = cmd->args_type;
2613 typestr = key_get_info(typestr, &key);
2625 while (qemu_isspace(*p))
2627 if (*typestr == '?') {
2630 /* no optional string: NULL argument */
2634 ret = get_str(buf, sizeof(buf), &p);
2638 monitor_printf(mon, "%s: filename expected\n",
2642 monitor_printf(mon, "%s: block device name expected\n",
2646 monitor_printf(mon, "%s: string expected\n", cmd->name);
2651 qdict_put(qdict, key, qstring_from_str(buf));
2656 QemuOptsList *opts_list;
2659 opts_list = qemu_find_opts(key);
2660 if (!opts_list || opts_list->desc->name) {
2663 while (qemu_isspace(*p)) {
2668 if (get_str(buf, sizeof(buf), &p) < 0) {
2671 opts = qemu_opts_parse_noisily(opts_list, buf, true);
2675 qemu_opts_to_qdict(opts, qdict);
2676 qemu_opts_del(opts);
2681 int count, format, size;
2683 while (qemu_isspace(*p))
2689 if (qemu_isdigit(*p)) {
2691 while (qemu_isdigit(*p)) {
2692 count = count * 10 + (*p - '0');
2730 if (*p != '\0' && !qemu_isspace(*p)) {
2731 monitor_printf(mon, "invalid char in format: '%c'\n",
2736 format = default_fmt_format;
2737 if (format != 'i') {
2738 /* for 'i', not specifying a size gives -1 as size */
2740 size = default_fmt_size;
2741 default_fmt_size = size;
2743 default_fmt_format = format;
2746 format = default_fmt_format;
2747 if (format != 'i') {
2748 size = default_fmt_size;
2753 qdict_put(qdict, "count", qint_from_int(count));
2754 qdict_put(qdict, "format", qint_from_int(format));
2755 qdict_put(qdict, "size", qint_from_int(size));
2764 while (qemu_isspace(*p))
2766 if (*typestr == '?' || *typestr == '.') {
2767 if (*typestr == '?') {
2775 while (qemu_isspace(*p))
2784 if (get_expr(mon, &val, &p))
2786 /* Check if 'i' is greater than 32-bit */
2787 if ((c == 'i') && ((val >> 32) & 0xffffffff)) {
2788 monitor_printf(mon, "\'%s\' has failed: ", cmd->name);
2789 monitor_printf(mon, "integer is for 32-bit values\n");
2791 } else if (c == 'M') {
2793 monitor_printf(mon, "enter a positive value\n");
2798 qdict_put(qdict, key, qint_from_int(val));
2807 while (qemu_isspace(*p)) {
2810 if (*typestr == '?') {
2816 ret = qemu_strtosz_MiB(p, &end, &val);
2817 if (ret < 0 || val > INT64_MAX) {
2818 monitor_printf(mon, "invalid size\n");
2821 qdict_put(qdict, key, qint_from_int(val));
2829 while (qemu_isspace(*p))
2831 if (*typestr == '?') {
2837 if (get_double(mon, &val, &p) < 0) {
2840 if (p[0] && p[1] == 's') {
2843 val /= 1e3; p += 2; break;
2845 val /= 1e6; p += 2; break;
2847 val /= 1e9; p += 2; break;
2850 if (*p && !qemu_isspace(*p)) {
2851 monitor_printf(mon, "Unknown unit suffix\n");
2854 qdict_put(qdict, key, qfloat_from_double(val));
2862 while (qemu_isspace(*p)) {
2866 while (qemu_isgraph(*p)) {
2869 if (p - beg == 2 && !memcmp(beg, "on", p - beg)) {
2871 } else if (p - beg == 3 && !memcmp(beg, "off", p - beg)) {
2874 monitor_printf(mon, "Expected 'on' or 'off'\n");
2877 qdict_put(qdict, key, qbool_from_bool(val));
2882 const char *tmp = p;
2889 while (qemu_isspace(*p))
2894 if(!is_valid_option(p, typestr)) {
2896 monitor_printf(mon, "%s: unsupported option -%c\n",
2908 qdict_put(qdict, key, qbool_from_bool(true));
2915 /* package all remaining string */
2918 while (qemu_isspace(*p)) {
2921 if (*typestr == '?') {
2924 /* no remaining string: NULL argument */
2930 monitor_printf(mon, "%s: string expected\n",
2934 qdict_put(qdict, key, qstring_from_str(p));
2940 monitor_printf(mon, "%s: unknown type '%c'\n", cmd->name, c);
2946 /* check that all arguments were parsed */
2947 while (qemu_isspace(*p))
2950 monitor_printf(mon, "%s: extraneous characters at the end of line\n",
2963 static void handle_hmp_command(Monitor *mon, const char *cmdline)
2966 const mon_cmd_t *cmd;
2968 cmd = monitor_parse_command(mon, &cmdline, mon->cmd_table);
2973 qdict = monitor_parse_arguments(mon, &cmdline, cmd);
2975 monitor_printf(mon, "Try \"help %s\" for more information\n",
2980 cmd->cmd(mon, qdict);
2984 static void cmd_completion(Monitor *mon, const char *name, const char *list)
2986 const char *p, *pstart;
2995 p = pstart + strlen(pstart);
2997 if (len > sizeof(cmd) - 2)
2998 len = sizeof(cmd) - 2;
2999 memcpy(cmd, pstart, len);
3001 if (name[0] == '\0' || !strncmp(name, cmd, strlen(name))) {
3002 readline_add_completion(mon->rs, cmd);
3010 static void file_completion(Monitor *mon, const char *input)
3015 char file[1024], file_prefix[1024];
3019 p = strrchr(input, '/');
3022 pstrcpy(file_prefix, sizeof(file_prefix), input);
3023 pstrcpy(path, sizeof(path), ".");
3025 input_path_len = p - input + 1;
3026 memcpy(path, input, input_path_len);
3027 if (input_path_len > sizeof(path) - 1)
3028 input_path_len = sizeof(path) - 1;
3029 path[input_path_len] = '\0';
3030 pstrcpy(file_prefix, sizeof(file_prefix), p + 1);
3033 ffs = opendir(path);
3042 if (strcmp(d->d_name, ".") == 0 || strcmp(d->d_name, "..") == 0) {
3046 if (strstart(d->d_name, file_prefix, NULL)) {
3047 memcpy(file, input, input_path_len);
3048 if (input_path_len < sizeof(file))
3049 pstrcpy(file + input_path_len, sizeof(file) - input_path_len,
3051 /* stat the file to find out if it's a directory.
3052 * In that case add a slash to speed up typing long paths
3054 if (stat(file, &sb) == 0 && S_ISDIR(sb.st_mode)) {
3055 pstrcat(file, sizeof(file), "/");
3057 readline_add_completion(mon->rs, file);
3063 static const char *next_arg_type(const char *typestr)
3065 const char *p = strchr(typestr, ':');
3066 return (p != NULL ? ++p : typestr);
3069 static void add_completion_option(ReadLineState *rs, const char *str,
3072 if (!str || !option) {
3075 if (!strncmp(option, str, strlen(str))) {
3076 readline_add_completion(rs, option);
3080 void chardev_add_completion(ReadLineState *rs, int nb_args, const char *str)
3083 ChardevBackendInfoList *list, *start;
3089 readline_set_completion_index(rs, len);
3091 start = list = qmp_query_chardev_backends(NULL);
3093 const char *chr_name = list->value->name;
3095 if (!strncmp(chr_name, str, len)) {
3096 readline_add_completion(rs, chr_name);
3100 qapi_free_ChardevBackendInfoList(start);
3103 void netdev_add_completion(ReadLineState *rs, int nb_args, const char *str)
3112 readline_set_completion_index(rs, len);
3113 for (i = 0; NetClientDriver_lookup[i]; i++) {
3114 add_completion_option(rs, str, NetClientDriver_lookup[i]);
3118 void device_add_completion(ReadLineState *rs, int nb_args, const char *str)
3128 readline_set_completion_index(rs, len);
3129 list = elt = object_class_get_list(TYPE_DEVICE, false);
3132 DeviceClass *dc = OBJECT_CLASS_CHECK(DeviceClass, elt->data,
3134 name = object_class_get_name(OBJECT_CLASS(dc));
3136 if (!dc->cannot_instantiate_with_device_add_yet
3137 && !strncmp(name, str, len)) {
3138 readline_add_completion(rs, name);
3145 void object_add_completion(ReadLineState *rs, int nb_args, const char *str)
3155 readline_set_completion_index(rs, len);
3156 list = elt = object_class_get_list(TYPE_USER_CREATABLE, false);
3160 name = object_class_get_name(OBJECT_CLASS(elt->data));
3161 if (!strncmp(name, str, len) && strcmp(name, TYPE_USER_CREATABLE)) {
3162 readline_add_completion(rs, name);
3169 static void peripheral_device_del_completion(ReadLineState *rs,
3170 const char *str, size_t len)
3172 Object *peripheral = container_get(qdev_get_machine(), "/peripheral");
3173 GSList *list, *item;
3175 list = qdev_build_hotpluggable_device_list(peripheral);
3180 for (item = list; item; item = g_slist_next(item)) {
3181 DeviceState *dev = item->data;
3183 if (dev->id && !strncmp(str, dev->id, len)) {
3184 readline_add_completion(rs, dev->id);
3191 void chardev_remove_completion(ReadLineState *rs, int nb_args, const char *str)
3194 ChardevInfoList *list, *start;
3200 readline_set_completion_index(rs, len);
3202 start = list = qmp_query_chardev(NULL);
3204 ChardevInfo *chr = list->value;
3206 if (!strncmp(chr->label, str, len)) {
3207 readline_add_completion(rs, chr->label);
3211 qapi_free_ChardevInfoList(start);
3214 static void ringbuf_completion(ReadLineState *rs, const char *str)
3217 ChardevInfoList *list, *start;
3220 readline_set_completion_index(rs, len);
3222 start = list = qmp_query_chardev(NULL);
3224 ChardevInfo *chr_info = list->value;
3226 if (!strncmp(chr_info->label, str, len)) {
3227 Chardev *chr = qemu_chr_find(chr_info->label);
3228 if (chr && CHARDEV_IS_RINGBUF(chr)) {
3229 readline_add_completion(rs, chr_info->label);
3234 qapi_free_ChardevInfoList(start);
3237 void ringbuf_write_completion(ReadLineState *rs, int nb_args, const char *str)
3242 ringbuf_completion(rs, str);
3245 void device_del_completion(ReadLineState *rs, int nb_args, const char *str)
3254 readline_set_completion_index(rs, len);
3255 peripheral_device_del_completion(rs, str, len);
3258 void object_del_completion(ReadLineState *rs, int nb_args, const char *str)
3260 ObjectPropertyInfoList *list, *start;
3267 readline_set_completion_index(rs, len);
3269 start = list = qmp_qom_list("/objects", NULL);
3271 ObjectPropertyInfo *info = list->value;
3273 if (!strncmp(info->type, "child<", 5)
3274 && !strncmp(info->name, str, len)) {
3275 readline_add_completion(rs, info->name);
3279 qapi_free_ObjectPropertyInfoList(start);
3282 void sendkey_completion(ReadLineState *rs, int nb_args, const char *str)
3291 sep = strrchr(str, '-');
3296 readline_set_completion_index(rs, len);
3297 for (i = 0; i < Q_KEY_CODE__MAX; i++) {
3298 if (!strncmp(str, QKeyCode_lookup[i], len)) {
3299 readline_add_completion(rs, QKeyCode_lookup[i]);
3304 void set_link_completion(ReadLineState *rs, int nb_args, const char *str)
3309 readline_set_completion_index(rs, len);
3311 NetClientState *ncs[MAX_QUEUE_NUM];
3313 count = qemu_find_net_clients_except(NULL, ncs,
3314 NET_CLIENT_DRIVER_NONE,
3316 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3317 const char *name = ncs[i]->name;
3318 if (!strncmp(str, name, len)) {
3319 readline_add_completion(rs, name);
3322 } else if (nb_args == 3) {
3323 add_completion_option(rs, str, "on");
3324 add_completion_option(rs, str, "off");
3328 void netdev_del_completion(ReadLineState *rs, int nb_args, const char *str)
3331 NetClientState *ncs[MAX_QUEUE_NUM];
3338 readline_set_completion_index(rs, len);
3339 count = qemu_find_net_clients_except(NULL, ncs, NET_CLIENT_DRIVER_NIC,
3341 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3343 const char *name = ncs[i]->name;
3344 if (strncmp(str, name, len)) {
3347 opts = qemu_opts_find(qemu_find_opts_err("netdev", NULL), name);
3349 readline_add_completion(rs, name);
3354 void info_trace_events_completion(ReadLineState *rs, int nb_args, const char *str)
3359 readline_set_completion_index(rs, len);
3361 TraceEventIter iter;
3363 char *pattern = g_strdup_printf("%s*", str);
3364 trace_event_iter_init(&iter, pattern);
3365 while ((ev = trace_event_iter_next(&iter)) != NULL) {
3366 readline_add_completion(rs, trace_event_get_name(ev));
3372 void trace_event_completion(ReadLineState *rs, int nb_args, const char *str)
3377 readline_set_completion_index(rs, len);
3379 TraceEventIter iter;
3381 char *pattern = g_strdup_printf("%s*", str);
3382 trace_event_iter_init(&iter, pattern);
3383 while ((ev = trace_event_iter_next(&iter)) != NULL) {
3384 readline_add_completion(rs, trace_event_get_name(ev));
3387 } else if (nb_args == 3) {
3388 add_completion_option(rs, str, "on");
3389 add_completion_option(rs, str, "off");
3393 void watchdog_action_completion(ReadLineState *rs, int nb_args, const char *str)
3400 readline_set_completion_index(rs, strlen(str));
3401 for (i = 0; WatchdogExpirationAction_lookup[i]; i++) {
3402 add_completion_option(rs, str, WatchdogExpirationAction_lookup[i]);
3406 void migrate_set_capability_completion(ReadLineState *rs, int nb_args,
3412 readline_set_completion_index(rs, len);
3415 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
3416 const char *name = MigrationCapability_lookup[i];
3417 if (!strncmp(str, name, len)) {
3418 readline_add_completion(rs, name);
3421 } else if (nb_args == 3) {
3422 add_completion_option(rs, str, "on");
3423 add_completion_option(rs, str, "off");
3427 void migrate_set_parameter_completion(ReadLineState *rs, int nb_args,
3433 readline_set_completion_index(rs, len);
3436 for (i = 0; i < MIGRATION_PARAMETER__MAX; i++) {
3437 const char *name = MigrationParameter_lookup[i];
3438 if (!strncmp(str, name, len)) {
3439 readline_add_completion(rs, name);
3445 void host_net_add_completion(ReadLineState *rs, int nb_args, const char *str)
3453 readline_set_completion_index(rs, len);
3454 for (i = 0; host_net_devices[i]; i++) {
3455 if (!strncmp(host_net_devices[i], str, len)) {
3456 readline_add_completion(rs, host_net_devices[i]);
3461 void host_net_remove_completion(ReadLineState *rs, int nb_args, const char *str)
3463 NetClientState *ncs[MAX_QUEUE_NUM];
3467 readline_set_completion_index(rs, len);
3469 count = qemu_find_net_clients_except(NULL, ncs,
3470 NET_CLIENT_DRIVER_NONE,
3472 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3476 if (net_hub_id_for_client(ncs[i], &id)) {
3479 snprintf(name, sizeof(name), "%d", id);
3480 if (!strncmp(str, name, len)) {
3481 readline_add_completion(rs, name);
3485 } else if (nb_args == 3) {
3486 count = qemu_find_net_clients_except(NULL, ncs,
3487 NET_CLIENT_DRIVER_NIC,
3489 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3493 if (ncs[i]->info->type == NET_CLIENT_DRIVER_HUBPORT ||
3494 net_hub_id_for_client(ncs[i], &id)) {
3497 name = ncs[i]->name;
3498 if (!strncmp(str, name, len)) {
3499 readline_add_completion(rs, name);
3506 static void vm_completion(ReadLineState *rs, const char *str)
3509 BlockDriverState *bs;
3510 BdrvNextIterator it;
3513 readline_set_completion_index(rs, len);
3515 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
3516 SnapshotInfoList *snapshots, *snapshot;
3517 AioContext *ctx = bdrv_get_aio_context(bs);
3520 aio_context_acquire(ctx);
3521 if (bdrv_can_snapshot(bs)) {
3522 ok = bdrv_query_snapshot_info_list(bs, &snapshots, NULL) == 0;
3524 aio_context_release(ctx);
3529 snapshot = snapshots;
3531 char *completion = snapshot->value->name;
3532 if (!strncmp(str, completion, len)) {
3533 readline_add_completion(rs, completion);
3535 completion = snapshot->value->id;
3536 if (!strncmp(str, completion, len)) {
3537 readline_add_completion(rs, completion);
3539 snapshot = snapshot->next;
3541 qapi_free_SnapshotInfoList(snapshots);
3546 void delvm_completion(ReadLineState *rs, int nb_args, const char *str)
3549 vm_completion(rs, str);
3553 void loadvm_completion(ReadLineState *rs, int nb_args, const char *str)
3556 vm_completion(rs, str);
3560 static void monitor_find_completion_by_table(Monitor *mon,
3561 const mon_cmd_t *cmd_table,
3565 const char *cmdname;
3567 const char *ptype, *str, *name;
3568 const mon_cmd_t *cmd;
3569 BlockBackend *blk = NULL;
3572 /* command completion */
3577 readline_set_completion_index(mon->rs, strlen(cmdname));
3578 for (cmd = cmd_table; cmd->name != NULL; cmd++) {
3579 cmd_completion(mon, cmdname, cmd->name);
3582 /* find the command */
3583 for (cmd = cmd_table; cmd->name != NULL; cmd++) {
3584 if (compare_cmd(args[0], cmd->name)) {
3592 if (cmd->sub_table) {
3593 /* do the job again */
3594 monitor_find_completion_by_table(mon, cmd->sub_table,
3595 &args[1], nb_args - 1);
3598 if (cmd->command_completion) {
3599 cmd->command_completion(mon->rs, nb_args, args[nb_args - 1]);
3603 ptype = next_arg_type(cmd->args_type);
3604 for(i = 0; i < nb_args - 2; i++) {
3605 if (*ptype != '\0') {
3606 ptype = next_arg_type(ptype);
3607 while (*ptype == '?')
3608 ptype = next_arg_type(ptype);
3611 str = args[nb_args - 1];
3612 while (*ptype == '-' && ptype[1] != '\0') {
3613 ptype = next_arg_type(ptype);
3617 /* file completion */
3618 readline_set_completion_index(mon->rs, strlen(str));
3619 file_completion(mon, str);
3622 /* block device name completion */
3623 readline_set_completion_index(mon->rs, strlen(str));
3624 while ((blk = blk_next(blk)) != NULL) {
3625 name = blk_name(blk);
3626 if (str[0] == '\0' ||
3627 !strncmp(name, str, strlen(str))) {
3628 readline_add_completion(mon->rs, name);
3634 if (!strcmp(cmd->name, "help|?")) {
3635 monitor_find_completion_by_table(mon, cmd_table,
3636 &args[1], nb_args - 1);
3645 static void monitor_find_completion(void *opaque,
3646 const char *cmdline)
3648 Monitor *mon = opaque;
3649 char *args[MAX_ARGS];
3652 /* 1. parse the cmdline */
3653 if (parse_cmdline(cmdline, &nb_args, args) < 0) {
3657 /* if the line ends with a space, it means we want to complete the
3659 len = strlen(cmdline);
3660 if (len > 0 && qemu_isspace(cmdline[len - 1])) {
3661 if (nb_args >= MAX_ARGS) {
3664 args[nb_args++] = g_strdup("");
3667 /* 2. auto complete according to args */
3668 monitor_find_completion_by_table(mon, mon->cmd_table, args, nb_args);
3671 free_cmdline_args(args, nb_args);
3674 static int monitor_can_read(void *opaque)
3676 Monitor *mon = opaque;
3678 return (mon->suspend_cnt == 0) ? 1 : 0;
3681 static bool invalid_qmp_mode(const Monitor *mon, const char *cmd,
3684 bool is_cap = g_str_equal(cmd, "qmp_capabilities");
3686 if (is_cap && mon->qmp.in_command_mode) {
3687 error_set(errp, ERROR_CLASS_COMMAND_NOT_FOUND,
3688 "Capabilities negotiation is already complete, command "
3689 "'%s' ignored", cmd);
3692 if (!is_cap && !mon->qmp.in_command_mode) {
3693 error_set(errp, ERROR_CLASS_COMMAND_NOT_FOUND,
3694 "Expecting capabilities negotiation with "
3695 "'qmp_capabilities' before command '%s'", cmd);
3702 * Input object checking rules
3704 * 1. Input object must be a dict
3705 * 2. The "execute" key must exist
3706 * 3. The "execute" key must be a string
3707 * 4. If the "arguments" key exists, it must be a dict
3708 * 5. If the "id" key exists, it can be anything (ie. json-value)
3709 * 6. Any argument not listed above is considered invalid
3711 static QDict *qmp_check_input_obj(QObject *input_obj, Error **errp)
3713 const QDictEntry *ent;
3714 int has_exec_key = 0;
3717 input_dict = qobject_to_qdict(input_obj);
3719 error_setg(errp, QERR_QMP_BAD_INPUT_OBJECT, "object");
3724 for (ent = qdict_first(input_dict); ent; ent = qdict_next(input_dict, ent)){
3725 const char *arg_name = qdict_entry_key(ent);
3726 const QObject *arg_obj = qdict_entry_value(ent);
3728 if (!strcmp(arg_name, "execute")) {
3729 if (qobject_type(arg_obj) != QTYPE_QSTRING) {
3730 error_setg(errp, QERR_QMP_BAD_INPUT_OBJECT_MEMBER,
3731 "execute", "string");
3735 } else if (!strcmp(arg_name, "arguments")) {
3736 if (qobject_type(arg_obj) != QTYPE_QDICT) {
3737 error_setg(errp, QERR_QMP_BAD_INPUT_OBJECT_MEMBER,
3738 "arguments", "object");
3741 } else if (!strcmp(arg_name, "id")) {
3742 /* Any string is acceptable as "id", so nothing to check */
3744 error_setg(errp, QERR_QMP_EXTRA_MEMBER, arg_name);
3749 if (!has_exec_key) {
3750 error_setg(errp, QERR_QMP_BAD_INPUT_OBJECT, "execute");
3757 static void handle_qmp_command(JSONMessageParser *parser, GQueue *tokens)
3759 QObject *req, *rsp = NULL, *id = NULL;
3760 QDict *qdict = NULL;
3761 const char *cmd_name;
3762 Monitor *mon = cur_mon;
3765 req = json_parser_parse_err(tokens, NULL, &err);
3767 /* json_parser_parse_err() sucks: can fail without setting @err */
3768 error_setg(&err, QERR_JSON_PARSING);
3774 qdict = qmp_check_input_obj(req, &err);
3779 id = qdict_get(qdict, "id");
3781 qdict_del(qdict, "id");
3783 cmd_name = qdict_get_str(qdict, "execute");
3784 trace_handle_qmp_command(mon, cmd_name);
3786 if (invalid_qmp_mode(mon, cmd_name, &err)) {
3790 rsp = qmp_dispatch(req);
3794 qdict = qdict_new();
3795 qdict_put_obj(qdict, "error", qmp_build_error_object(err));
3797 rsp = QOBJECT(qdict);
3802 qdict_put_obj(qobject_to_qdict(rsp), "id", id);
3806 monitor_json_emitter(mon, rsp);
3810 qobject_decref(rsp);
3811 qobject_decref(req);
3814 static void monitor_qmp_read(void *opaque, const uint8_t *buf, int size)
3816 Monitor *old_mon = cur_mon;
3820 json_message_parser_feed(&cur_mon->qmp.parser, (const char *) buf, size);
3825 static void monitor_read(void *opaque, const uint8_t *buf, int size)
3827 Monitor *old_mon = cur_mon;
3833 for (i = 0; i < size; i++)
3834 readline_handle_byte(cur_mon->rs, buf[i]);
3836 if (size == 0 || buf[size - 1] != 0)
3837 monitor_printf(cur_mon, "corrupted command\n");
3839 handle_hmp_command(cur_mon, (char *)buf);
3845 static void monitor_command_cb(void *opaque, const char *cmdline,
3846 void *readline_opaque)
3848 Monitor *mon = opaque;
3850 monitor_suspend(mon);
3851 handle_hmp_command(mon, cmdline);
3852 monitor_resume(mon);
3855 int monitor_suspend(Monitor *mon)
3863 void monitor_resume(Monitor *mon)
3867 if (--mon->suspend_cnt == 0)
3868 readline_show_prompt(mon->rs);
3871 static QObject *get_qmp_greeting(void)
3873 QObject *ver = NULL;
3875 qmp_marshal_query_version(NULL, &ver, NULL);
3877 return qobject_from_jsonf("{'QMP': {'version': %p, 'capabilities': []}}",
3881 static void monitor_qmp_event(void *opaque, int event)
3884 Monitor *mon = opaque;
3887 case CHR_EVENT_OPENED:
3888 mon->qmp.in_command_mode = false;
3889 data = get_qmp_greeting();
3890 monitor_json_emitter(mon, data);
3891 qobject_decref(data);
3894 case CHR_EVENT_CLOSED:
3895 json_message_parser_destroy(&mon->qmp.parser);
3896 json_message_parser_init(&mon->qmp.parser, handle_qmp_command);
3898 monitor_fdsets_cleanup();
3903 static void monitor_event(void *opaque, int event)
3905 Monitor *mon = opaque;
3908 case CHR_EVENT_MUX_IN:
3909 qemu_mutex_lock(&mon->out_lock);
3911 qemu_mutex_unlock(&mon->out_lock);
3912 if (mon->reset_seen) {
3913 readline_restart(mon->rs);
3914 monitor_resume(mon);
3917 mon->suspend_cnt = 0;
3921 case CHR_EVENT_MUX_OUT:
3922 if (mon->reset_seen) {
3923 if (mon->suspend_cnt == 0) {
3924 monitor_printf(mon, "\n");
3927 monitor_suspend(mon);
3931 qemu_mutex_lock(&mon->out_lock);
3933 qemu_mutex_unlock(&mon->out_lock);
3936 case CHR_EVENT_OPENED:
3937 monitor_printf(mon, "QEMU %s monitor - type 'help' for more "
3938 "information\n", QEMU_VERSION);
3939 if (!mon->mux_out) {
3940 readline_restart(mon->rs);
3941 readline_show_prompt(mon->rs);
3943 mon->reset_seen = 1;
3947 case CHR_EVENT_CLOSED:
3949 monitor_fdsets_cleanup();
3955 compare_mon_cmd(const void *a, const void *b)
3957 return strcmp(((const mon_cmd_t *)a)->name,
3958 ((const mon_cmd_t *)b)->name);
3961 static void sortcmdlist(void)
3964 int elem_size = sizeof(mon_cmd_t);
3966 array_num = sizeof(mon_cmds)/elem_size-1;
3967 qsort((void *)mon_cmds, array_num, elem_size, compare_mon_cmd);
3969 array_num = sizeof(info_cmds)/elem_size-1;
3970 qsort((void *)info_cmds, array_num, elem_size, compare_mon_cmd);
3973 /* These functions just adapt the readline interface in a typesafe way. We
3974 * could cast function pointers but that discards compiler checks.
3976 static void GCC_FMT_ATTR(2, 3) monitor_readline_printf(void *opaque,
3977 const char *fmt, ...)
3981 monitor_vprintf(opaque, fmt, ap);
3985 static void monitor_readline_flush(void *opaque)
3987 monitor_flush(opaque);
3991 * Print to current monitor if we have one, else to stderr.
3992 * TODO should return int, so callers can calculate width, but that
3993 * requires surgery to monitor_vprintf(). Left for another day.
3995 void error_vprintf(const char *fmt, va_list ap)
3997 if (cur_mon && !monitor_cur_is_qmp()) {
3998 monitor_vprintf(cur_mon, fmt, ap);
4000 vfprintf(stderr, fmt, ap);
4004 void error_vprintf_unless_qmp(const char *fmt, va_list ap)
4006 if (cur_mon && !monitor_cur_is_qmp()) {
4007 monitor_vprintf(cur_mon, fmt, ap);
4008 } else if (!cur_mon) {
4009 vfprintf(stderr, fmt, ap);
4013 static void __attribute__((constructor)) monitor_lock_init(void)
4015 qemu_mutex_init(&monitor_lock);
4018 void monitor_init(Chardev *chr, int flags)
4020 static int is_first_init = 1;
4023 if (is_first_init) {
4024 monitor_qapi_event_init();
4029 mon = g_malloc(sizeof(*mon));
4030 monitor_data_init(mon);
4032 qemu_chr_fe_init(&mon->chr, chr, &error_abort);
4034 if (flags & MONITOR_USE_READLINE) {
4035 mon->rs = readline_init(monitor_readline_printf,
4036 monitor_readline_flush,
4038 monitor_find_completion);
4039 monitor_read_command(mon, 0);
4042 if (monitor_is_qmp(mon)) {
4043 qemu_chr_fe_set_handlers(&mon->chr, monitor_can_read, monitor_qmp_read,
4044 monitor_qmp_event, mon, NULL, true);
4045 qemu_chr_fe_set_echo(&mon->chr, true);
4046 json_message_parser_init(&mon->qmp.parser, handle_qmp_command);
4048 qemu_chr_fe_set_handlers(&mon->chr, monitor_can_read, monitor_read,
4049 monitor_event, mon, NULL, true);
4052 qemu_mutex_lock(&monitor_lock);
4053 QLIST_INSERT_HEAD(&mon_list, mon, entry);
4054 qemu_mutex_unlock(&monitor_lock);
4057 void monitor_cleanup(void)
4059 Monitor *mon, *next;
4061 qemu_mutex_lock(&monitor_lock);
4062 QLIST_FOREACH_SAFE(mon, &mon_list, entry, next) {
4063 QLIST_REMOVE(mon, entry);
4064 monitor_data_destroy(mon);
4067 qemu_mutex_unlock(&monitor_lock);
4070 static void bdrv_password_cb(void *opaque, const char *password,
4071 void *readline_opaque)
4073 Monitor *mon = opaque;
4074 BlockDriverState *bs = readline_opaque;
4076 Error *local_err = NULL;
4078 bdrv_add_key(bs, password, &local_err);
4080 error_report_err(local_err);
4083 if (mon->password_completion_cb)
4084 mon->password_completion_cb(mon->password_opaque, ret);
4086 monitor_read_command(mon, 1);
4089 int monitor_read_bdrv_key_start(Monitor *mon, BlockDriverState *bs,
4090 BlockCompletionFunc *completion_cb,
4095 monitor_printf(mon, "%s (%s) is encrypted.\n", bdrv_get_device_name(bs),
4096 bdrv_get_encrypted_filename(bs));
4098 mon->password_completion_cb = completion_cb;
4099 mon->password_opaque = opaque;
4101 err = monitor_read_password(mon, bdrv_password_cb, bs);
4103 if (err && completion_cb)
4104 completion_cb(opaque, err);
4109 int monitor_read_block_device_key(Monitor *mon, const char *device,
4110 BlockCompletionFunc *completion_cb,
4116 blk = blk_by_name(device);
4118 monitor_printf(mon, "Device not found %s\n", device);
4122 monitor_printf(mon, "Device '%s' has no medium\n", device);
4126 bdrv_add_key(blk_bs(blk), NULL, &err);
4129 return monitor_read_bdrv_key_start(mon, blk_bs(blk), completion_cb, opaque);
4132 if (completion_cb) {
4133 completion_cb(opaque, 0);
4138 QemuOptsList qemu_mon_opts = {
4140 .implied_opt_name = "chardev",
4141 .head = QTAILQ_HEAD_INITIALIZER(qemu_mon_opts.head),
4145 .type = QEMU_OPT_STRING,
4148 .type = QEMU_OPT_STRING,
4150 .name = "default", /* deprecated */
4151 .type = QEMU_OPT_BOOL,
4154 .type = QEMU_OPT_BOOL,
4156 { /* end of list */ }
4161 void qmp_rtc_reset_reinjection(Error **errp)
4163 error_setg(errp, QERR_FEATURE_DISABLED, "rtc-reset-reinjection");
4167 #ifndef TARGET_S390X
4168 void qmp_dump_skeys(const char *filename, Error **errp)
4170 error_setg(errp, QERR_FEATURE_DISABLED, "dump-skeys");
4175 GICCapabilityList *qmp_query_gic_capabilities(Error **errp)
4177 error_setg(errp, QERR_FEATURE_DISABLED, "query-gic-capabilities");
4182 HotpluggableCPUList *qmp_query_hotpluggable_cpus(Error **errp)
4184 MachineState *ms = MACHINE(qdev_get_machine());
4185 MachineClass *mc = MACHINE_GET_CLASS(ms);
4187 if (!mc->has_hotpluggable_cpus) {
4188 error_setg(errp, QERR_FEATURE_DISABLED, "query-hotpluggable-cpus");
4192 return machine_query_hotpluggable_cpus(ms);