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;
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) {
315 qemu_chr_fe_add_watch(&mon->chr, G_IO_OUT | G_IO_HUP,
316 monitor_unblocked, mon);
321 void monitor_flush(Monitor *mon)
323 qemu_mutex_lock(&mon->out_lock);
324 monitor_flush_locked(mon);
325 qemu_mutex_unlock(&mon->out_lock);
328 /* flush at every end of line */
329 static void monitor_puts(Monitor *mon, const char *str)
333 qemu_mutex_lock(&mon->out_lock);
339 qstring_append_chr(mon->outbuf, '\r');
341 qstring_append_chr(mon->outbuf, c);
343 monitor_flush_locked(mon);
346 qemu_mutex_unlock(&mon->out_lock);
349 void monitor_vprintf(Monitor *mon, const char *fmt, va_list ap)
356 if (monitor_is_qmp(mon)) {
360 buf = g_strdup_vprintf(fmt, ap);
361 monitor_puts(mon, buf);
365 void monitor_printf(Monitor *mon, const char *fmt, ...)
369 monitor_vprintf(mon, fmt, ap);
373 int monitor_fprintf(FILE *stream, const char *fmt, ...)
377 monitor_vprintf((Monitor *)stream, fmt, ap);
382 static void monitor_json_emitter(Monitor *mon, const QObject *data)
386 json = mon->flags & MONITOR_USE_PRETTY ? qobject_to_json_pretty(data) :
387 qobject_to_json(data);
388 assert(json != NULL);
390 qstring_append_chr(json, '\n');
391 monitor_puts(mon, qstring_get_str(json));
396 static MonitorQAPIEventConf monitor_qapi_event_conf[QAPI_EVENT__MAX] = {
397 /* Limit guest-triggerable events to 1 per second */
398 [QAPI_EVENT_RTC_CHANGE] = { 1000 * SCALE_MS },
399 [QAPI_EVENT_WATCHDOG] = { 1000 * SCALE_MS },
400 [QAPI_EVENT_BALLOON_CHANGE] = { 1000 * SCALE_MS },
401 [QAPI_EVENT_QUORUM_REPORT_BAD] = { 1000 * SCALE_MS },
402 [QAPI_EVENT_QUORUM_FAILURE] = { 1000 * SCALE_MS },
403 [QAPI_EVENT_VSERPORT_CHANGE] = { 1000 * SCALE_MS },
406 GHashTable *monitor_qapi_event_state;
409 * Emits the event to every monitor instance, @event is only used for trace
410 * Called with monitor_lock held.
412 static void monitor_qapi_event_emit(QAPIEvent event, QDict *qdict)
416 trace_monitor_protocol_event_emit(event, qdict);
417 QLIST_FOREACH(mon, &mon_list, entry) {
418 if (monitor_is_qmp(mon) && mon->qmp.in_command_mode) {
419 monitor_json_emitter(mon, QOBJECT(qdict));
424 static void monitor_qapi_event_handler(void *opaque);
427 * Queue a new event for emission to Monitor instances,
428 * applying any rate limiting if required.
431 monitor_qapi_event_queue(QAPIEvent event, QDict *qdict, Error **errp)
433 MonitorQAPIEventConf *evconf;
434 MonitorQAPIEventState *evstate;
436 assert(event < QAPI_EVENT__MAX);
437 evconf = &monitor_qapi_event_conf[event];
438 trace_monitor_protocol_event_queue(event, qdict, evconf->rate);
440 qemu_mutex_lock(&monitor_lock);
443 /* Unthrottled event */
444 monitor_qapi_event_emit(event, qdict);
446 QDict *data = qobject_to_qdict(qdict_get(qdict, "data"));
447 MonitorQAPIEventState key = { .event = event, .data = data };
449 evstate = g_hash_table_lookup(monitor_qapi_event_state, &key);
450 assert(!evstate || timer_pending(evstate->timer));
454 * Timer is pending for (at least) evconf->rate ns after
455 * last send. Store event for sending when timer fires,
456 * replacing a prior stored event if any.
458 QDECREF(evstate->qdict);
459 evstate->qdict = qdict;
460 QINCREF(evstate->qdict);
463 * Last send was (at least) evconf->rate ns ago.
464 * Send immediately, and arm the timer to call
465 * monitor_qapi_event_handler() in evconf->rate ns. Any
466 * events arriving before then will be delayed until then.
468 int64_t now = qemu_clock_get_ns(event_clock_type);
470 monitor_qapi_event_emit(event, qdict);
472 evstate = g_new(MonitorQAPIEventState, 1);
473 evstate->event = event;
474 evstate->data = data;
475 QINCREF(evstate->data);
476 evstate->qdict = NULL;
477 evstate->timer = timer_new_ns(event_clock_type,
478 monitor_qapi_event_handler,
480 g_hash_table_add(monitor_qapi_event_state, evstate);
481 timer_mod_ns(evstate->timer, now + evconf->rate);
485 qemu_mutex_unlock(&monitor_lock);
489 * This function runs evconf->rate ns after sending a throttled
491 * If another event has since been stored, send it.
493 static void monitor_qapi_event_handler(void *opaque)
495 MonitorQAPIEventState *evstate = opaque;
496 MonitorQAPIEventConf *evconf = &monitor_qapi_event_conf[evstate->event];
498 trace_monitor_protocol_event_handler(evstate->event, evstate->qdict);
499 qemu_mutex_lock(&monitor_lock);
501 if (evstate->qdict) {
502 int64_t now = qemu_clock_get_ns(event_clock_type);
504 monitor_qapi_event_emit(evstate->event, evstate->qdict);
505 QDECREF(evstate->qdict);
506 evstate->qdict = NULL;
507 timer_mod_ns(evstate->timer, now + evconf->rate);
509 g_hash_table_remove(monitor_qapi_event_state, evstate);
510 QDECREF(evstate->data);
511 timer_free(evstate->timer);
515 qemu_mutex_unlock(&monitor_lock);
518 static unsigned int qapi_event_throttle_hash(const void *key)
520 const MonitorQAPIEventState *evstate = key;
521 unsigned int hash = evstate->event * 255;
523 if (evstate->event == QAPI_EVENT_VSERPORT_CHANGE) {
524 hash += g_str_hash(qdict_get_str(evstate->data, "id"));
527 if (evstate->event == QAPI_EVENT_QUORUM_REPORT_BAD) {
528 hash += g_str_hash(qdict_get_str(evstate->data, "node-name"));
534 static gboolean qapi_event_throttle_equal(const void *a, const void *b)
536 const MonitorQAPIEventState *eva = a;
537 const MonitorQAPIEventState *evb = b;
539 if (eva->event != evb->event) {
543 if (eva->event == QAPI_EVENT_VSERPORT_CHANGE) {
544 return !strcmp(qdict_get_str(eva->data, "id"),
545 qdict_get_str(evb->data, "id"));
548 if (eva->event == QAPI_EVENT_QUORUM_REPORT_BAD) {
549 return !strcmp(qdict_get_str(eva->data, "node-name"),
550 qdict_get_str(evb->data, "node-name"));
556 static void monitor_qapi_event_init(void)
558 if (qtest_enabled()) {
559 event_clock_type = QEMU_CLOCK_VIRTUAL;
562 monitor_qapi_event_state = g_hash_table_new(qapi_event_throttle_hash,
563 qapi_event_throttle_equal);
564 qmp_event_set_func_emit(monitor_qapi_event_queue);
567 void qmp_qmp_capabilities(Error **errp)
569 cur_mon->qmp.in_command_mode = true;
572 static void handle_hmp_command(Monitor *mon, const char *cmdline);
574 static void monitor_data_init(Monitor *mon)
576 memset(mon, 0, sizeof(Monitor));
577 qemu_mutex_init(&mon->out_lock);
578 mon->outbuf = qstring_new();
579 /* Use *mon_cmds by default. */
580 mon->cmd_table = mon_cmds;
583 static void monitor_data_destroy(Monitor *mon)
585 qemu_chr_fe_deinit(&mon->chr);
586 if (monitor_is_qmp(mon)) {
587 json_message_parser_destroy(&mon->qmp.parser);
590 QDECREF(mon->outbuf);
591 qemu_mutex_destroy(&mon->out_lock);
594 char *qmp_human_monitor_command(const char *command_line, bool has_cpu_index,
595 int64_t cpu_index, Error **errp)
598 Monitor *old_mon, hmp;
600 monitor_data_init(&hmp);
601 hmp.skip_flush = true;
607 int ret = monitor_set_cpu(cpu_index);
610 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cpu-index",
616 handle_hmp_command(&hmp, command_line);
619 qemu_mutex_lock(&hmp.out_lock);
620 if (qstring_get_length(hmp.outbuf) > 0) {
621 output = g_strdup(qstring_get_str(hmp.outbuf));
623 output = g_strdup("");
625 qemu_mutex_unlock(&hmp.out_lock);
628 monitor_data_destroy(&hmp);
632 static int compare_cmd(const char *name, const char *list)
634 const char *p, *pstart;
642 p = pstart + strlen(pstart);
643 if ((p - pstart) == len && !memcmp(pstart, name, len))
652 static int get_str(char *buf, int buf_size, const char **pp)
660 while (qemu_isspace(*p)) {
671 while (*p != '\0' && *p != '\"') {
687 printf("unsupported escape code: '\\%c'\n", c);
690 if ((q - buf) < buf_size - 1) {
694 if ((q - buf) < buf_size - 1) {
701 printf("unterminated string\n");
706 while (*p != '\0' && !qemu_isspace(*p)) {
707 if ((q - buf) < buf_size - 1) {
720 static void free_cmdline_args(char **args, int nb_args)
724 assert(nb_args <= MAX_ARGS);
726 for (i = 0; i < nb_args; i++) {
733 * Parse the command line to get valid args.
734 * @cmdline: command line to be parsed.
735 * @pnb_args: location to store the number of args, must NOT be NULL.
736 * @args: location to store the args, which should be freed by caller, must
739 * Returns 0 on success, negative on failure.
741 * NOTE: this parser is an approximate form of the real command parser. Number
742 * of args have a limit of MAX_ARGS. If cmdline contains more, it will
743 * return with failure.
745 static int parse_cmdline(const char *cmdline,
746 int *pnb_args, char **args)
755 while (qemu_isspace(*p)) {
761 if (nb_args >= MAX_ARGS) {
764 ret = get_str(buf, sizeof(buf), &p);
768 args[nb_args] = g_strdup(buf);
775 free_cmdline_args(args, nb_args);
779 static void help_cmd_dump_one(Monitor *mon,
780 const mon_cmd_t *cmd,
786 for (i = 0; i < prefix_args_nb; i++) {
787 monitor_printf(mon, "%s ", prefix_args[i]);
789 monitor_printf(mon, "%s %s -- %s\n", cmd->name, cmd->params, cmd->help);
792 /* @args[@arg_index] is the valid command need to find in @cmds */
793 static void help_cmd_dump(Monitor *mon, const mon_cmd_t *cmds,
794 char **args, int nb_args, int arg_index)
796 const mon_cmd_t *cmd;
798 /* No valid arg need to compare with, dump all in *cmds */
799 if (arg_index >= nb_args) {
800 for (cmd = cmds; cmd->name != NULL; cmd++) {
801 help_cmd_dump_one(mon, cmd, args, arg_index);
806 /* Find one entry to dump */
807 for (cmd = cmds; cmd->name != NULL; cmd++) {
808 if (compare_cmd(args[arg_index], cmd->name)) {
809 if (cmd->sub_table) {
810 /* continue with next arg */
811 help_cmd_dump(mon, cmd->sub_table,
812 args, nb_args, arg_index + 1);
814 help_cmd_dump_one(mon, cmd, args, arg_index);
821 static void help_cmd(Monitor *mon, const char *name)
823 char *args[MAX_ARGS];
826 /* 1. parse user input */
828 /* special case for log, directly dump and return */
829 if (!strcmp(name, "log")) {
830 const QEMULogItem *item;
831 monitor_printf(mon, "Log items (comma separated):\n");
832 monitor_printf(mon, "%-10s %s\n", "none", "remove all logs");
833 for (item = qemu_log_items; item->mask != 0; item++) {
834 monitor_printf(mon, "%-10s %s\n", item->name, item->help);
839 if (parse_cmdline(name, &nb_args, args) < 0) {
844 /* 2. dump the contents according to parsed args */
845 help_cmd_dump(mon, mon->cmd_table, args, nb_args, 0);
847 free_cmdline_args(args, nb_args);
850 static void do_help_cmd(Monitor *mon, const QDict *qdict)
852 help_cmd(mon, qdict_get_try_str(qdict, "name"));
855 static void hmp_trace_event(Monitor *mon, const QDict *qdict)
857 const char *tp_name = qdict_get_str(qdict, "name");
858 bool new_state = qdict_get_bool(qdict, "option");
859 bool has_vcpu = qdict_haskey(qdict, "vcpu");
860 int vcpu = qdict_get_try_int(qdict, "vcpu", 0);
861 Error *local_err = NULL;
864 monitor_printf(mon, "argument vcpu must be positive");
868 qmp_trace_event_set_state(tp_name, new_state, true, true, has_vcpu, vcpu, &local_err);
870 error_report_err(local_err);
874 #ifdef CONFIG_TRACE_SIMPLE
875 static void hmp_trace_file(Monitor *mon, const QDict *qdict)
877 const char *op = qdict_get_try_str(qdict, "op");
878 const char *arg = qdict_get_try_str(qdict, "arg");
881 st_print_trace_file_status((FILE *)mon, &monitor_fprintf);
882 } else if (!strcmp(op, "on")) {
883 st_set_trace_file_enabled(true);
884 } else if (!strcmp(op, "off")) {
885 st_set_trace_file_enabled(false);
886 } else if (!strcmp(op, "flush")) {
887 st_flush_trace_buffer();
888 } else if (!strcmp(op, "set")) {
890 st_set_trace_file(arg);
893 monitor_printf(mon, "unexpected argument \"%s\"\n", op);
894 help_cmd(mon, "trace-file");
899 static void hmp_info_help(Monitor *mon, const QDict *qdict)
901 help_cmd(mon, "info");
904 static void query_commands_cb(QmpCommand *cmd, void *opaque)
906 CommandInfoList *info, **list = opaque;
912 info = g_malloc0(sizeof(*info));
913 info->value = g_malloc0(sizeof(*info->value));
914 info->value->name = g_strdup(cmd->name);
919 CommandInfoList *qmp_query_commands(Error **errp)
921 CommandInfoList *list = NULL;
923 qmp_for_each_command(query_commands_cb, &list);
928 EventInfoList *qmp_query_events(Error **errp)
930 EventInfoList *info, *ev_list = NULL;
933 for (e = 0 ; e < QAPI_EVENT__MAX ; e++) {
934 const char *event_name = QAPIEvent_lookup[e];
935 assert(event_name != NULL);
936 info = g_malloc0(sizeof(*info));
937 info->value = g_malloc0(sizeof(*info->value));
938 info->value->name = g_strdup(event_name);
940 info->next = ev_list;
948 * Minor hack: generated marshalling suppressed for this command
949 * ('gen': false in the schema) so we can parse the JSON string
950 * directly into QObject instead of first parsing it with
951 * visit_type_SchemaInfoList() into a SchemaInfoList, then marshal it
952 * to QObject with generated output marshallers, every time. Instead,
953 * we do it in test-qobject-input-visitor.c, just to make sure
954 * qapi-introspect.py's output actually conforms to the schema.
956 static void qmp_query_qmp_schema(QDict *qdict, QObject **ret_data,
959 *ret_data = qobject_from_json(qmp_schema_json);
963 * We used to define commands in qmp-commands.hx in addition to the
964 * QAPI schema. This permitted defining some of them only in certain
965 * configurations. query-commands has always reflected that (good,
966 * because it lets QMP clients figure out what's actually available),
967 * while query-qmp-schema never did (not so good). This function is a
968 * hack to keep the configuration-specific commands defined exactly as
969 * before, even though qmp-commands.hx is gone.
971 * FIXME Educate the QAPI schema on configuration-specific commands,
972 * and drop this hack.
974 static void qmp_unregister_commands_hack(void)
977 qmp_unregister_command("query-spice");
980 qmp_unregister_command("rtc-reset-reinjection");
983 qmp_unregister_command("dump-skeys");
986 qmp_unregister_command("query-gic-capabilities");
988 #if !defined(TARGET_S390X)
989 qmp_unregister_command("query-cpu-model-expansion");
990 qmp_unregister_command("query-cpu-model-baseline");
991 qmp_unregister_command("query-cpu-model-comparison");
993 #if !defined(TARGET_PPC) && !defined(TARGET_ARM) && !defined(TARGET_I386) \
994 && !defined(TARGET_S390X)
995 qmp_unregister_command("query-cpu-definitions");
999 static void qmp_init_marshal(void)
1001 qmp_register_command("query-qmp-schema", qmp_query_qmp_schema,
1003 qmp_register_command("device_add", qmp_device_add,
1005 qmp_register_command("netdev_add", qmp_netdev_add,
1008 /* call it after the rest of qapi_init() */
1009 register_module_init(qmp_unregister_commands_hack, MODULE_INIT_QAPI);
1012 qapi_init(qmp_init_marshal);
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) {
1030 monitor_set_cpu(first_cpu->cpu_index);
1032 cpu_synchronize_state(cur_mon->mon_cpu);
1033 return cur_mon->mon_cpu;
1036 CPUArchState *mon_get_cpu_env(void)
1038 return mon_get_cpu()->env_ptr;
1041 int monitor_get_cpu_index(void)
1043 return mon_get_cpu()->cpu_index;
1046 static void hmp_info_registers(Monitor *mon, const QDict *qdict)
1048 cpu_dump_state(mon_get_cpu(), (FILE *)mon, monitor_fprintf, CPU_DUMP_FPU);
1051 static void hmp_info_jit(Monitor *mon, const QDict *qdict)
1053 dump_exec_info((FILE *)mon, monitor_fprintf);
1054 dump_drift_info((FILE *)mon, monitor_fprintf);
1057 static void hmp_info_opcount(Monitor *mon, const QDict *qdict)
1059 dump_opcount_info((FILE *)mon, monitor_fprintf);
1062 static void hmp_info_history(Monitor *mon, const QDict *qdict)
1071 str = readline_get_history(mon->rs, i);
1074 monitor_printf(mon, "%d: '%s'\n", i, str);
1079 static void hmp_info_cpustats(Monitor *mon, const QDict *qdict)
1081 cpu_dump_statistics(mon_get_cpu(), (FILE *)mon, &monitor_fprintf, 0);
1084 static void hmp_info_trace_events(Monitor *mon, const QDict *qdict)
1086 const char *name = qdict_get_try_str(qdict, "name");
1087 bool has_vcpu = qdict_haskey(qdict, "vcpu");
1088 int vcpu = qdict_get_try_int(qdict, "vcpu", 0);
1089 TraceEventInfoList *events;
1090 TraceEventInfoList *elem;
1091 Error *local_err = NULL;
1097 monitor_printf(mon, "argument vcpu must be positive");
1101 events = qmp_trace_event_get_state(name, has_vcpu, vcpu, &local_err);
1103 error_report_err(local_err);
1107 for (elem = events; elem != NULL; elem = elem->next) {
1108 monitor_printf(mon, "%s : state %u\n",
1110 elem->value->state == TRACE_EVENT_STATE_ENABLED ? 1 : 0);
1112 qapi_free_TraceEventInfoList(events);
1115 void qmp_client_migrate_info(const char *protocol, const char *hostname,
1116 bool has_port, int64_t port,
1117 bool has_tls_port, int64_t tls_port,
1118 bool has_cert_subject, const char *cert_subject,
1121 if (strcmp(protocol, "spice") == 0) {
1122 if (!qemu_using_spice(errp)) {
1126 if (!has_port && !has_tls_port) {
1127 error_setg(errp, QERR_MISSING_PARAMETER, "port/tls-port");
1131 if (qemu_spice_migrate_info(hostname,
1132 has_port ? port : -1,
1133 has_tls_port ? tls_port : -1,
1135 error_setg(errp, QERR_UNDEFINED_ERROR);
1141 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "protocol", "spice");
1144 static void hmp_logfile(Monitor *mon, const QDict *qdict)
1148 qemu_set_log_filename(qdict_get_str(qdict, "filename"), &err);
1150 error_report_err(err);
1154 static void hmp_log(Monitor *mon, const QDict *qdict)
1157 const char *items = qdict_get_str(qdict, "items");
1159 if (!strcmp(items, "none")) {
1162 mask = qemu_str_to_log_mask(items);
1164 help_cmd(mon, "log");
1171 static void hmp_singlestep(Monitor *mon, const QDict *qdict)
1173 const char *option = qdict_get_try_str(qdict, "option");
1174 if (!option || !strcmp(option, "on")) {
1176 } else if (!strcmp(option, "off")) {
1179 monitor_printf(mon, "unexpected option %s\n", option);
1183 static void hmp_gdbserver(Monitor *mon, const QDict *qdict)
1185 const char *device = qdict_get_try_str(qdict, "device");
1187 device = "tcp::" DEFAULT_GDBSTUB_PORT;
1188 if (gdbserver_start(device) < 0) {
1189 monitor_printf(mon, "Could not open gdbserver on device '%s'\n",
1191 } else if (strcmp(device, "none") == 0) {
1192 monitor_printf(mon, "Disabled gdbserver\n");
1194 monitor_printf(mon, "Waiting for gdb connection on device '%s'\n",
1199 static void hmp_watchdog_action(Monitor *mon, const QDict *qdict)
1201 const char *action = qdict_get_str(qdict, "action");
1202 if (select_watchdog_action(action) == -1) {
1203 monitor_printf(mon, "Unknown watchdog action '%s'\n", action);
1207 static void monitor_printc(Monitor *mon, int c)
1209 monitor_printf(mon, "'");
1212 monitor_printf(mon, "\\'");
1215 monitor_printf(mon, "\\\\");
1218 monitor_printf(mon, "\\n");
1221 monitor_printf(mon, "\\r");
1224 if (c >= 32 && c <= 126) {
1225 monitor_printf(mon, "%c", c);
1227 monitor_printf(mon, "\\x%02x", c);
1231 monitor_printf(mon, "'");
1234 static void memory_dump(Monitor *mon, int count, int format, int wsize,
1235 hwaddr addr, int is_physical)
1237 int l, line_size, i, max_digits, len;
1241 if (format == 'i') {
1244 CPUArchState *env = mon_get_cpu_env();
1247 } else if (wsize == 4) {
1250 /* as default we use the current CS size */
1253 #ifdef TARGET_X86_64
1254 if ((env->efer & MSR_EFER_LMA) &&
1255 (env->segs[R_CS].flags & DESC_L_MASK))
1259 if (!(env->segs[R_CS].flags & DESC_B_MASK))
1265 CPUArchState *env = mon_get_cpu_env();
1266 flags = msr_le << 16;
1267 flags |= env->bfd_mach;
1269 monitor_disas(mon, mon_get_cpu(), addr, count, is_physical, flags);
1273 len = wsize * count;
1282 max_digits = (wsize * 8 + 2) / 3;
1286 max_digits = (wsize * 8) / 4;
1290 max_digits = (wsize * 8 * 10 + 32) / 33;
1299 monitor_printf(mon, TARGET_FMT_plx ":", addr);
1301 monitor_printf(mon, TARGET_FMT_lx ":", (target_ulong)addr);
1306 cpu_physical_memory_read(addr, buf, l);
1308 if (cpu_memory_rw_debug(mon_get_cpu(), addr, buf, l, 0) < 0) {
1309 monitor_printf(mon, " Cannot access memory\n");
1318 v = ldub_p(buf + i);
1321 v = lduw_p(buf + i);
1324 v = (uint32_t)ldl_p(buf + i);
1330 monitor_printf(mon, " ");
1333 monitor_printf(mon, "%#*" PRIo64, max_digits, v);
1336 monitor_printf(mon, "0x%0*" PRIx64, max_digits, v);
1339 monitor_printf(mon, "%*" PRIu64, max_digits, v);
1342 monitor_printf(mon, "%*" PRId64, max_digits, v);
1345 monitor_printc(mon, v);
1350 monitor_printf(mon, "\n");
1356 static void hmp_memory_dump(Monitor *mon, const QDict *qdict)
1358 int count = qdict_get_int(qdict, "count");
1359 int format = qdict_get_int(qdict, "format");
1360 int size = qdict_get_int(qdict, "size");
1361 target_long addr = qdict_get_int(qdict, "addr");
1363 memory_dump(mon, count, format, size, addr, 0);
1366 static void hmp_physical_memory_dump(Monitor *mon, const QDict *qdict)
1368 int count = qdict_get_int(qdict, "count");
1369 int format = qdict_get_int(qdict, "format");
1370 int size = qdict_get_int(qdict, "size");
1371 hwaddr addr = qdict_get_int(qdict, "addr");
1373 memory_dump(mon, count, format, size, addr, 1);
1376 static void do_print(Monitor *mon, const QDict *qdict)
1378 int format = qdict_get_int(qdict, "format");
1379 hwaddr val = qdict_get_int(qdict, "val");
1383 monitor_printf(mon, "%#" HWADDR_PRIo, val);
1386 monitor_printf(mon, "%#" HWADDR_PRIx, val);
1389 monitor_printf(mon, "%" HWADDR_PRIu, val);
1393 monitor_printf(mon, "%" HWADDR_PRId, val);
1396 monitor_printc(mon, val);
1399 monitor_printf(mon, "\n");
1402 static void hmp_sum(Monitor *mon, const QDict *qdict)
1406 uint32_t start = qdict_get_int(qdict, "start");
1407 uint32_t size = qdict_get_int(qdict, "size");
1410 for(addr = start; addr < (start + size); addr++) {
1411 uint8_t val = address_space_ldub(&address_space_memory, addr,
1412 MEMTXATTRS_UNSPECIFIED, NULL);
1413 /* BSD sum algorithm ('sum' Unix command) */
1414 sum = (sum >> 1) | (sum << 15);
1417 monitor_printf(mon, "%05d\n", sum);
1420 static int mouse_button_state;
1422 static void hmp_mouse_move(Monitor *mon, const QDict *qdict)
1424 int dx, dy, dz, button;
1425 const char *dx_str = qdict_get_str(qdict, "dx_str");
1426 const char *dy_str = qdict_get_str(qdict, "dy_str");
1427 const char *dz_str = qdict_get_try_str(qdict, "dz_str");
1429 dx = strtol(dx_str, NULL, 0);
1430 dy = strtol(dy_str, NULL, 0);
1431 qemu_input_queue_rel(NULL, INPUT_AXIS_X, dx);
1432 qemu_input_queue_rel(NULL, INPUT_AXIS_Y, dy);
1435 dz = strtol(dz_str, NULL, 0);
1437 button = (dz > 0) ? INPUT_BUTTON_WHEEL_UP : INPUT_BUTTON_WHEEL_DOWN;
1438 qemu_input_queue_btn(NULL, button, true);
1439 qemu_input_event_sync();
1440 qemu_input_queue_btn(NULL, button, false);
1443 qemu_input_event_sync();
1446 static void hmp_mouse_button(Monitor *mon, const QDict *qdict)
1448 static uint32_t bmap[INPUT_BUTTON__MAX] = {
1449 [INPUT_BUTTON_LEFT] = MOUSE_EVENT_LBUTTON,
1450 [INPUT_BUTTON_MIDDLE] = MOUSE_EVENT_MBUTTON,
1451 [INPUT_BUTTON_RIGHT] = MOUSE_EVENT_RBUTTON,
1453 int button_state = qdict_get_int(qdict, "button_state");
1455 if (mouse_button_state == button_state) {
1458 qemu_input_update_buttons(NULL, bmap, mouse_button_state, button_state);
1459 qemu_input_event_sync();
1460 mouse_button_state = button_state;
1463 static void hmp_ioport_read(Monitor *mon, const QDict *qdict)
1465 int size = qdict_get_int(qdict, "size");
1466 int addr = qdict_get_int(qdict, "addr");
1467 int has_index = qdict_haskey(qdict, "index");
1472 int index = qdict_get_int(qdict, "index");
1473 cpu_outb(addr & IOPORTS_MASK, index & 0xff);
1481 val = cpu_inb(addr);
1485 val = cpu_inw(addr);
1489 val = cpu_inl(addr);
1493 monitor_printf(mon, "port%c[0x%04x] = %#0*x\n",
1494 suffix, addr, size * 2, val);
1497 static void hmp_ioport_write(Monitor *mon, const QDict *qdict)
1499 int size = qdict_get_int(qdict, "size");
1500 int addr = qdict_get_int(qdict, "addr");
1501 int val = qdict_get_int(qdict, "val");
1503 addr &= IOPORTS_MASK;
1508 cpu_outb(addr, val);
1511 cpu_outw(addr, val);
1514 cpu_outl(addr, val);
1519 static void hmp_boot_set(Monitor *mon, const QDict *qdict)
1521 Error *local_err = NULL;
1522 const char *bootdevice = qdict_get_str(qdict, "bootdevice");
1524 qemu_boot_set(bootdevice, &local_err);
1526 error_report_err(local_err);
1528 monitor_printf(mon, "boot device list now set to %s\n", bootdevice);
1532 static void hmp_info_mtree(Monitor *mon, const QDict *qdict)
1534 mtree_info((fprintf_function)monitor_printf, mon);
1537 static void hmp_info_numa(Monitor *mon, const QDict *qdict)
1543 node_mem = g_new0(uint64_t, nb_numa_nodes);
1544 query_numa_node_mem(node_mem);
1545 monitor_printf(mon, "%d nodes\n", nb_numa_nodes);
1546 for (i = 0; i < nb_numa_nodes; i++) {
1547 monitor_printf(mon, "node %d cpus:", i);
1549 if (cpu->numa_node == i) {
1550 monitor_printf(mon, " %d", cpu->cpu_index);
1553 monitor_printf(mon, "\n");
1554 monitor_printf(mon, "node %d size: %" PRId64 " MB\n", i,
1560 #ifdef CONFIG_PROFILER
1565 static void hmp_info_profile(Monitor *mon, const QDict *qdict)
1567 monitor_printf(mon, "async time %" PRId64 " (%0.3f)\n",
1568 dev_time, dev_time / (double)NANOSECONDS_PER_SECOND);
1569 monitor_printf(mon, "qemu time %" PRId64 " (%0.3f)\n",
1570 tcg_time, tcg_time / (double)NANOSECONDS_PER_SECOND);
1575 static void hmp_info_profile(Monitor *mon, const QDict *qdict)
1577 monitor_printf(mon, "Internal profiler not compiled\n");
1581 /* Capture support */
1582 static QLIST_HEAD (capture_list_head, CaptureState) capture_head;
1584 static void hmp_info_capture(Monitor *mon, const QDict *qdict)
1589 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
1590 monitor_printf(mon, "[%d]: ", i);
1591 s->ops.info (s->opaque);
1595 static void hmp_stopcapture(Monitor *mon, const QDict *qdict)
1598 int n = qdict_get_int(qdict, "n");
1601 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
1603 s->ops.destroy (s->opaque);
1604 QLIST_REMOVE (s, entries);
1611 static void hmp_wavcapture(Monitor *mon, const QDict *qdict)
1613 const char *path = qdict_get_str(qdict, "path");
1614 int has_freq = qdict_haskey(qdict, "freq");
1615 int freq = qdict_get_try_int(qdict, "freq", -1);
1616 int has_bits = qdict_haskey(qdict, "bits");
1617 int bits = qdict_get_try_int(qdict, "bits", -1);
1618 int has_channels = qdict_haskey(qdict, "nchannels");
1619 int nchannels = qdict_get_try_int(qdict, "nchannels", -1);
1622 s = g_malloc0 (sizeof (*s));
1624 freq = has_freq ? freq : 44100;
1625 bits = has_bits ? bits : 16;
1626 nchannels = has_channels ? nchannels : 2;
1628 if (wav_start_capture (s, path, freq, bits, nchannels)) {
1629 monitor_printf(mon, "Failed to add wave capture\n");
1633 QLIST_INSERT_HEAD (&capture_head, s, entries);
1636 static qemu_acl *find_acl(Monitor *mon, const char *name)
1638 qemu_acl *acl = qemu_acl_find(name);
1641 monitor_printf(mon, "acl: unknown list '%s'\n", name);
1646 static void hmp_acl_show(Monitor *mon, const QDict *qdict)
1648 const char *aclname = qdict_get_str(qdict, "aclname");
1649 qemu_acl *acl = find_acl(mon, aclname);
1650 qemu_acl_entry *entry;
1654 monitor_printf(mon, "policy: %s\n",
1655 acl->defaultDeny ? "deny" : "allow");
1656 QTAILQ_FOREACH(entry, &acl->entries, next) {
1658 monitor_printf(mon, "%d: %s %s\n", i,
1659 entry->deny ? "deny" : "allow", entry->match);
1664 static void hmp_acl_reset(Monitor *mon, const QDict *qdict)
1666 const char *aclname = qdict_get_str(qdict, "aclname");
1667 qemu_acl *acl = find_acl(mon, aclname);
1670 qemu_acl_reset(acl);
1671 monitor_printf(mon, "acl: removed all rules\n");
1675 static void hmp_acl_policy(Monitor *mon, const QDict *qdict)
1677 const char *aclname = qdict_get_str(qdict, "aclname");
1678 const char *policy = qdict_get_str(qdict, "policy");
1679 qemu_acl *acl = find_acl(mon, aclname);
1682 if (strcmp(policy, "allow") == 0) {
1683 acl->defaultDeny = 0;
1684 monitor_printf(mon, "acl: policy set to 'allow'\n");
1685 } else if (strcmp(policy, "deny") == 0) {
1686 acl->defaultDeny = 1;
1687 monitor_printf(mon, "acl: policy set to 'deny'\n");
1689 monitor_printf(mon, "acl: unknown policy '%s', "
1690 "expected 'deny' or 'allow'\n", policy);
1695 static void hmp_acl_add(Monitor *mon, const QDict *qdict)
1697 const char *aclname = qdict_get_str(qdict, "aclname");
1698 const char *match = qdict_get_str(qdict, "match");
1699 const char *policy = qdict_get_str(qdict, "policy");
1700 int has_index = qdict_haskey(qdict, "index");
1701 int index = qdict_get_try_int(qdict, "index", -1);
1702 qemu_acl *acl = find_acl(mon, aclname);
1706 if (strcmp(policy, "allow") == 0) {
1708 } else if (strcmp(policy, "deny") == 0) {
1711 monitor_printf(mon, "acl: unknown policy '%s', "
1712 "expected 'deny' or 'allow'\n", policy);
1716 ret = qemu_acl_insert(acl, deny, match, index);
1718 ret = qemu_acl_append(acl, deny, match);
1720 monitor_printf(mon, "acl: unable to add acl entry\n");
1722 monitor_printf(mon, "acl: added rule at position %d\n", ret);
1726 static void hmp_acl_remove(Monitor *mon, const QDict *qdict)
1728 const char *aclname = qdict_get_str(qdict, "aclname");
1729 const char *match = qdict_get_str(qdict, "match");
1730 qemu_acl *acl = find_acl(mon, aclname);
1734 ret = qemu_acl_remove(acl, match);
1736 monitor_printf(mon, "acl: no matching acl entry\n");
1738 monitor_printf(mon, "acl: removed rule at position %d\n", ret);
1742 void qmp_getfd(const char *fdname, Error **errp)
1747 fd = qemu_chr_fe_get_msgfd(&cur_mon->chr);
1749 error_setg(errp, QERR_FD_NOT_SUPPLIED);
1753 if (qemu_isdigit(fdname[0])) {
1755 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "fdname",
1756 "a name not starting with a digit");
1760 QLIST_FOREACH(monfd, &cur_mon->fds, next) {
1761 if (strcmp(monfd->name, fdname) != 0) {
1770 monfd = g_malloc0(sizeof(mon_fd_t));
1771 monfd->name = g_strdup(fdname);
1774 QLIST_INSERT_HEAD(&cur_mon->fds, monfd, next);
1777 void qmp_closefd(const char *fdname, Error **errp)
1781 QLIST_FOREACH(monfd, &cur_mon->fds, next) {
1782 if (strcmp(monfd->name, fdname) != 0) {
1786 QLIST_REMOVE(monfd, next);
1788 g_free(monfd->name);
1793 error_setg(errp, QERR_FD_NOT_FOUND, fdname);
1796 static void hmp_loadvm(Monitor *mon, const QDict *qdict)
1798 int saved_vm_running = runstate_is_running();
1799 const char *name = qdict_get_str(qdict, "name");
1801 vm_stop(RUN_STATE_RESTORE_VM);
1803 if (load_vmstate(name) == 0 && saved_vm_running) {
1808 int monitor_get_fd(Monitor *mon, const char *fdname, Error **errp)
1812 QLIST_FOREACH(monfd, &mon->fds, next) {
1815 if (strcmp(monfd->name, fdname) != 0) {
1821 /* caller takes ownership of fd */
1822 QLIST_REMOVE(monfd, next);
1823 g_free(monfd->name);
1829 error_setg(errp, "File descriptor named '%s' has not been found", fdname);
1833 static void monitor_fdset_cleanup(MonFdset *mon_fdset)
1835 MonFdsetFd *mon_fdset_fd;
1836 MonFdsetFd *mon_fdset_fd_next;
1838 QLIST_FOREACH_SAFE(mon_fdset_fd, &mon_fdset->fds, next, mon_fdset_fd_next) {
1839 if ((mon_fdset_fd->removed ||
1840 (QLIST_EMPTY(&mon_fdset->dup_fds) && mon_refcount == 0)) &&
1841 runstate_is_running()) {
1842 close(mon_fdset_fd->fd);
1843 g_free(mon_fdset_fd->opaque);
1844 QLIST_REMOVE(mon_fdset_fd, next);
1845 g_free(mon_fdset_fd);
1849 if (QLIST_EMPTY(&mon_fdset->fds) && QLIST_EMPTY(&mon_fdset->dup_fds)) {
1850 QLIST_REMOVE(mon_fdset, next);
1855 static void monitor_fdsets_cleanup(void)
1857 MonFdset *mon_fdset;
1858 MonFdset *mon_fdset_next;
1860 QLIST_FOREACH_SAFE(mon_fdset, &mon_fdsets, next, mon_fdset_next) {
1861 monitor_fdset_cleanup(mon_fdset);
1865 AddfdInfo *qmp_add_fd(bool has_fdset_id, int64_t fdset_id, bool has_opaque,
1866 const char *opaque, Error **errp)
1869 Monitor *mon = cur_mon;
1872 fd = qemu_chr_fe_get_msgfd(&mon->chr);
1874 error_setg(errp, QERR_FD_NOT_SUPPLIED);
1878 fdinfo = monitor_fdset_add_fd(fd, has_fdset_id, fdset_id,
1879 has_opaque, opaque, errp);
1891 void qmp_remove_fd(int64_t fdset_id, bool has_fd, int64_t fd, Error **errp)
1893 MonFdset *mon_fdset;
1894 MonFdsetFd *mon_fdset_fd;
1897 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
1898 if (mon_fdset->id != fdset_id) {
1901 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
1903 if (mon_fdset_fd->fd != fd) {
1906 mon_fdset_fd->removed = true;
1909 mon_fdset_fd->removed = true;
1912 if (has_fd && !mon_fdset_fd) {
1915 monitor_fdset_cleanup(mon_fdset);
1921 snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64 ", fd:%" PRId64,
1924 snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64, fdset_id);
1926 error_setg(errp, QERR_FD_NOT_FOUND, fd_str);
1929 FdsetInfoList *qmp_query_fdsets(Error **errp)
1931 MonFdset *mon_fdset;
1932 MonFdsetFd *mon_fdset_fd;
1933 FdsetInfoList *fdset_list = NULL;
1935 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
1936 FdsetInfoList *fdset_info = g_malloc0(sizeof(*fdset_info));
1937 FdsetFdInfoList *fdsetfd_list = NULL;
1939 fdset_info->value = g_malloc0(sizeof(*fdset_info->value));
1940 fdset_info->value->fdset_id = mon_fdset->id;
1942 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
1943 FdsetFdInfoList *fdsetfd_info;
1945 fdsetfd_info = g_malloc0(sizeof(*fdsetfd_info));
1946 fdsetfd_info->value = g_malloc0(sizeof(*fdsetfd_info->value));
1947 fdsetfd_info->value->fd = mon_fdset_fd->fd;
1948 if (mon_fdset_fd->opaque) {
1949 fdsetfd_info->value->has_opaque = true;
1950 fdsetfd_info->value->opaque = g_strdup(mon_fdset_fd->opaque);
1952 fdsetfd_info->value->has_opaque = false;
1955 fdsetfd_info->next = fdsetfd_list;
1956 fdsetfd_list = fdsetfd_info;
1959 fdset_info->value->fds = fdsetfd_list;
1961 fdset_info->next = fdset_list;
1962 fdset_list = fdset_info;
1968 AddfdInfo *monitor_fdset_add_fd(int fd, bool has_fdset_id, int64_t fdset_id,
1969 bool has_opaque, const char *opaque,
1972 MonFdset *mon_fdset = NULL;
1973 MonFdsetFd *mon_fdset_fd;
1977 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
1978 /* Break if match found or match impossible due to ordering by ID */
1979 if (fdset_id <= mon_fdset->id) {
1980 if (fdset_id < mon_fdset->id) {
1988 if (mon_fdset == NULL) {
1989 int64_t fdset_id_prev = -1;
1990 MonFdset *mon_fdset_cur = QLIST_FIRST(&mon_fdsets);
1994 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "fdset-id",
1995 "a non-negative value");
1998 /* Use specified fdset ID */
1999 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2000 mon_fdset_cur = mon_fdset;
2001 if (fdset_id < mon_fdset_cur->id) {
2006 /* Use first available fdset ID */
2007 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2008 mon_fdset_cur = mon_fdset;
2009 if (fdset_id_prev == mon_fdset_cur->id - 1) {
2010 fdset_id_prev = mon_fdset_cur->id;
2017 mon_fdset = g_malloc0(sizeof(*mon_fdset));
2019 mon_fdset->id = fdset_id;
2021 mon_fdset->id = fdset_id_prev + 1;
2024 /* The fdset list is ordered by fdset ID */
2025 if (!mon_fdset_cur) {
2026 QLIST_INSERT_HEAD(&mon_fdsets, mon_fdset, next);
2027 } else if (mon_fdset->id < mon_fdset_cur->id) {
2028 QLIST_INSERT_BEFORE(mon_fdset_cur, mon_fdset, next);
2030 QLIST_INSERT_AFTER(mon_fdset_cur, mon_fdset, next);
2034 mon_fdset_fd = g_malloc0(sizeof(*mon_fdset_fd));
2035 mon_fdset_fd->fd = fd;
2036 mon_fdset_fd->removed = false;
2038 mon_fdset_fd->opaque = g_strdup(opaque);
2040 QLIST_INSERT_HEAD(&mon_fdset->fds, mon_fdset_fd, next);
2042 fdinfo = g_malloc0(sizeof(*fdinfo));
2043 fdinfo->fdset_id = mon_fdset->id;
2044 fdinfo->fd = mon_fdset_fd->fd;
2049 int monitor_fdset_get_fd(int64_t fdset_id, int flags)
2052 MonFdset *mon_fdset;
2053 MonFdsetFd *mon_fdset_fd;
2056 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2057 if (mon_fdset->id != fdset_id) {
2060 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2061 mon_fd_flags = fcntl(mon_fdset_fd->fd, F_GETFL);
2062 if (mon_fd_flags == -1) {
2066 if ((flags & O_ACCMODE) == (mon_fd_flags & O_ACCMODE)) {
2067 return mon_fdset_fd->fd;
2079 int monitor_fdset_dup_fd_add(int64_t fdset_id, int dup_fd)
2081 MonFdset *mon_fdset;
2082 MonFdsetFd *mon_fdset_fd_dup;
2084 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2085 if (mon_fdset->id != fdset_id) {
2088 QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
2089 if (mon_fdset_fd_dup->fd == dup_fd) {
2093 mon_fdset_fd_dup = g_malloc0(sizeof(*mon_fdset_fd_dup));
2094 mon_fdset_fd_dup->fd = dup_fd;
2095 QLIST_INSERT_HEAD(&mon_fdset->dup_fds, mon_fdset_fd_dup, next);
2101 static int monitor_fdset_dup_fd_find_remove(int dup_fd, bool remove)
2103 MonFdset *mon_fdset;
2104 MonFdsetFd *mon_fdset_fd_dup;
2106 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2107 QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
2108 if (mon_fdset_fd_dup->fd == dup_fd) {
2110 QLIST_REMOVE(mon_fdset_fd_dup, next);
2111 if (QLIST_EMPTY(&mon_fdset->dup_fds)) {
2112 monitor_fdset_cleanup(mon_fdset);
2116 return mon_fdset->id;
2124 int monitor_fdset_dup_fd_find(int dup_fd)
2126 return monitor_fdset_dup_fd_find_remove(dup_fd, false);
2129 void monitor_fdset_dup_fd_remove(int dup_fd)
2131 monitor_fdset_dup_fd_find_remove(dup_fd, true);
2134 int monitor_fd_param(Monitor *mon, const char *fdname, Error **errp)
2137 Error *local_err = NULL;
2139 if (!qemu_isdigit(fdname[0]) && mon) {
2140 fd = monitor_get_fd(mon, fdname, &local_err);
2142 fd = qemu_parse_fd(fdname);
2144 error_setg(&local_err, "Invalid file descriptor number '%s'",
2149 error_propagate(errp, local_err);
2158 /* Please update hmp-commands.hx when adding or changing commands */
2159 static mon_cmd_t info_cmds[] = {
2160 #include "hmp-commands-info.h"
2164 /* mon_cmds and info_cmds would be sorted at runtime */
2165 static mon_cmd_t mon_cmds[] = {
2166 #include "hmp-commands.h"
2170 /*******************************************************************/
2172 static const char *pch;
2173 static sigjmp_buf expr_env;
2176 static void GCC_FMT_ATTR(2, 3) QEMU_NORETURN
2177 expr_error(Monitor *mon, const char *fmt, ...)
2181 monitor_vprintf(mon, fmt, ap);
2182 monitor_printf(mon, "\n");
2184 siglongjmp(expr_env, 1);
2187 /* return 0 if OK, -1 if not found */
2188 static int get_monitor_def(target_long *pval, const char *name)
2190 const MonitorDef *md = target_monitor_defs();
2199 for(; md->name != NULL; md++) {
2200 if (compare_cmd(name, md->name)) {
2201 if (md->get_value) {
2202 *pval = md->get_value(md, md->offset);
2204 CPUArchState *env = mon_get_cpu_env();
2205 ptr = (uint8_t *)env + md->offset;
2208 *pval = *(int32_t *)ptr;
2211 *pval = *(target_long *)ptr;
2222 ret = target_get_monitor_def(mon_get_cpu(), name, &tmp);
2224 *pval = (target_long) tmp;
2230 static void next(void)
2234 while (qemu_isspace(*pch))
2239 static int64_t expr_sum(Monitor *mon);
2241 static int64_t expr_unary(Monitor *mon)
2250 n = expr_unary(mon);
2254 n = -expr_unary(mon);
2258 n = ~expr_unary(mon);
2264 expr_error(mon, "')' expected");
2271 expr_error(mon, "character constant expected");
2275 expr_error(mon, "missing terminating \' character");
2285 while ((*pch >= 'a' && *pch <= 'z') ||
2286 (*pch >= 'A' && *pch <= 'Z') ||
2287 (*pch >= '0' && *pch <= '9') ||
2288 *pch == '_' || *pch == '.') {
2289 if ((q - buf) < sizeof(buf) - 1)
2293 while (qemu_isspace(*pch))
2296 ret = get_monitor_def(®, buf);
2298 expr_error(mon, "unknown register");
2303 expr_error(mon, "unexpected end of expression");
2308 n = strtoull(pch, &p, 0);
2309 if (errno == ERANGE) {
2310 expr_error(mon, "number too large");
2313 expr_error(mon, "invalid char '%c' in expression", *p);
2316 while (qemu_isspace(*pch))
2324 static int64_t expr_prod(Monitor *mon)
2329 val = expr_unary(mon);
2332 if (op != '*' && op != '/' && op != '%')
2335 val2 = expr_unary(mon);
2344 expr_error(mon, "division by zero");
2355 static int64_t expr_logic(Monitor *mon)
2360 val = expr_prod(mon);
2363 if (op != '&' && op != '|' && op != '^')
2366 val2 = expr_prod(mon);
2383 static int64_t expr_sum(Monitor *mon)
2388 val = expr_logic(mon);
2391 if (op != '+' && op != '-')
2394 val2 = expr_logic(mon);
2403 static int get_expr(Monitor *mon, int64_t *pval, const char **pp)
2406 if (sigsetjmp(expr_env, 0)) {
2410 while (qemu_isspace(*pch))
2412 *pval = expr_sum(mon);
2417 static int get_double(Monitor *mon, double *pval, const char **pp)
2419 const char *p = *pp;
2423 d = strtod(p, &tailp);
2425 monitor_printf(mon, "Number expected\n");
2428 if (d != d || d - d != 0) {
2429 /* NaN or infinity */
2430 monitor_printf(mon, "Bad number\n");
2439 * Store the command-name in cmdname, and return a pointer to
2440 * the remaining of the command string.
2442 static const char *get_command_name(const char *cmdline,
2443 char *cmdname, size_t nlen)
2446 const char *p, *pstart;
2449 while (qemu_isspace(*p))
2454 while (*p != '\0' && *p != '/' && !qemu_isspace(*p))
2459 memcpy(cmdname, pstart, len);
2460 cmdname[len] = '\0';
2465 * Read key of 'type' into 'key' and return the current
2468 static char *key_get_info(const char *type, char **key)
2476 p = strchr(type, ':');
2483 str = g_malloc(len + 1);
2484 memcpy(str, type, len);
2491 static int default_fmt_format = 'x';
2492 static int default_fmt_size = 4;
2494 static int is_valid_option(const char *c, const char *typestr)
2502 typestr = strstr(typestr, option);
2503 return (typestr != NULL);
2506 static const mon_cmd_t *search_dispatch_table(const mon_cmd_t *disp_table,
2507 const char *cmdname)
2509 const mon_cmd_t *cmd;
2511 for (cmd = disp_table; cmd->name != NULL; cmd++) {
2512 if (compare_cmd(cmdname, cmd->name)) {
2521 * Parse command name from @cmdp according to command table @table.
2522 * If blank, return NULL.
2523 * Else, if no valid command can be found, report to @mon, and return
2525 * Else, change @cmdp to point right behind the name, and return its
2526 * command table entry.
2527 * Do not assume the return value points into @table! It doesn't when
2528 * the command is found in a sub-command table.
2530 static const mon_cmd_t *monitor_parse_command(Monitor *mon,
2535 const mon_cmd_t *cmd;
2538 /* extract the command name */
2539 p = get_command_name(*cmdp, cmdname, sizeof(cmdname));
2543 cmd = search_dispatch_table(table, cmdname);
2545 monitor_printf(mon, "unknown command: '%.*s'\n",
2546 (int)(p - *cmdp), *cmdp);
2550 /* filter out following useless space */
2551 while (qemu_isspace(*p)) {
2556 /* search sub command */
2557 if (cmd->sub_table != NULL && *p != '\0') {
2558 return monitor_parse_command(mon, cmdp, cmd->sub_table);
2565 * Parse arguments for @cmd.
2566 * If it can't be parsed, report to @mon, and return NULL.
2567 * Else, insert command arguments into a QDict, and return it.
2568 * Note: On success, caller has to free the QDict structure.
2571 static QDict *monitor_parse_arguments(Monitor *mon,
2573 const mon_cmd_t *cmd)
2575 const char *typestr;
2578 const char *p = *endp;
2580 QDict *qdict = qdict_new();
2582 /* parse the parameters */
2583 typestr = cmd->args_type;
2585 typestr = key_get_info(typestr, &key);
2597 while (qemu_isspace(*p))
2599 if (*typestr == '?') {
2602 /* no optional string: NULL argument */
2606 ret = get_str(buf, sizeof(buf), &p);
2610 monitor_printf(mon, "%s: filename expected\n",
2614 monitor_printf(mon, "%s: block device name expected\n",
2618 monitor_printf(mon, "%s: string expected\n", cmd->name);
2623 qdict_put(qdict, key, qstring_from_str(buf));
2628 QemuOptsList *opts_list;
2631 opts_list = qemu_find_opts(key);
2632 if (!opts_list || opts_list->desc->name) {
2635 while (qemu_isspace(*p)) {
2640 if (get_str(buf, sizeof(buf), &p) < 0) {
2643 opts = qemu_opts_parse_noisily(opts_list, buf, true);
2647 qemu_opts_to_qdict(opts, qdict);
2648 qemu_opts_del(opts);
2653 int count, format, size;
2655 while (qemu_isspace(*p))
2661 if (qemu_isdigit(*p)) {
2663 while (qemu_isdigit(*p)) {
2664 count = count * 10 + (*p - '0');
2702 if (*p != '\0' && !qemu_isspace(*p)) {
2703 monitor_printf(mon, "invalid char in format: '%c'\n",
2708 format = default_fmt_format;
2709 if (format != 'i') {
2710 /* for 'i', not specifying a size gives -1 as size */
2712 size = default_fmt_size;
2713 default_fmt_size = size;
2715 default_fmt_format = format;
2718 format = default_fmt_format;
2719 if (format != 'i') {
2720 size = default_fmt_size;
2725 qdict_put(qdict, "count", qint_from_int(count));
2726 qdict_put(qdict, "format", qint_from_int(format));
2727 qdict_put(qdict, "size", qint_from_int(size));
2736 while (qemu_isspace(*p))
2738 if (*typestr == '?' || *typestr == '.') {
2739 if (*typestr == '?') {
2747 while (qemu_isspace(*p))
2756 if (get_expr(mon, &val, &p))
2758 /* Check if 'i' is greater than 32-bit */
2759 if ((c == 'i') && ((val >> 32) & 0xffffffff)) {
2760 monitor_printf(mon, "\'%s\' has failed: ", cmd->name);
2761 monitor_printf(mon, "integer is for 32-bit values\n");
2763 } else if (c == 'M') {
2765 monitor_printf(mon, "enter a positive value\n");
2770 qdict_put(qdict, key, qint_from_int(val));
2778 while (qemu_isspace(*p)) {
2781 if (*typestr == '?') {
2787 val = qemu_strtosz(p, &end);
2789 monitor_printf(mon, "invalid size\n");
2792 qdict_put(qdict, key, qint_from_int(val));
2800 while (qemu_isspace(*p))
2802 if (*typestr == '?') {
2808 if (get_double(mon, &val, &p) < 0) {
2811 if (p[0] && p[1] == 's') {
2814 val /= 1e3; p += 2; break;
2816 val /= 1e6; p += 2; break;
2818 val /= 1e9; p += 2; break;
2821 if (*p && !qemu_isspace(*p)) {
2822 monitor_printf(mon, "Unknown unit suffix\n");
2825 qdict_put(qdict, key, qfloat_from_double(val));
2833 while (qemu_isspace(*p)) {
2837 while (qemu_isgraph(*p)) {
2840 if (p - beg == 2 && !memcmp(beg, "on", p - beg)) {
2842 } else if (p - beg == 3 && !memcmp(beg, "off", p - beg)) {
2845 monitor_printf(mon, "Expected 'on' or 'off'\n");
2848 qdict_put(qdict, key, qbool_from_bool(val));
2853 const char *tmp = p;
2860 while (qemu_isspace(*p))
2865 if(!is_valid_option(p, typestr)) {
2867 monitor_printf(mon, "%s: unsupported option -%c\n",
2879 qdict_put(qdict, key, qbool_from_bool(true));
2886 /* package all remaining string */
2889 while (qemu_isspace(*p)) {
2892 if (*typestr == '?') {
2895 /* no remaining string: NULL argument */
2901 monitor_printf(mon, "%s: string expected\n",
2905 qdict_put(qdict, key, qstring_from_str(p));
2911 monitor_printf(mon, "%s: unknown type '%c'\n", cmd->name, c);
2917 /* check that all arguments were parsed */
2918 while (qemu_isspace(*p))
2921 monitor_printf(mon, "%s: extraneous characters at the end of line\n",
2934 static void handle_hmp_command(Monitor *mon, const char *cmdline)
2937 const mon_cmd_t *cmd;
2939 cmd = monitor_parse_command(mon, &cmdline, mon->cmd_table);
2944 qdict = monitor_parse_arguments(mon, &cmdline, cmd);
2946 monitor_printf(mon, "Try \"help %s\" for more information\n",
2951 cmd->cmd(mon, qdict);
2955 static void cmd_completion(Monitor *mon, const char *name, const char *list)
2957 const char *p, *pstart;
2966 p = pstart + strlen(pstart);
2968 if (len > sizeof(cmd) - 2)
2969 len = sizeof(cmd) - 2;
2970 memcpy(cmd, pstart, len);
2972 if (name[0] == '\0' || !strncmp(name, cmd, strlen(name))) {
2973 readline_add_completion(mon->rs, cmd);
2981 static void file_completion(Monitor *mon, const char *input)
2986 char file[1024], file_prefix[1024];
2990 p = strrchr(input, '/');
2993 pstrcpy(file_prefix, sizeof(file_prefix), input);
2994 pstrcpy(path, sizeof(path), ".");
2996 input_path_len = p - input + 1;
2997 memcpy(path, input, input_path_len);
2998 if (input_path_len > sizeof(path) - 1)
2999 input_path_len = sizeof(path) - 1;
3000 path[input_path_len] = '\0';
3001 pstrcpy(file_prefix, sizeof(file_prefix), p + 1);
3004 ffs = opendir(path);
3013 if (strcmp(d->d_name, ".") == 0 || strcmp(d->d_name, "..") == 0) {
3017 if (strstart(d->d_name, file_prefix, NULL)) {
3018 memcpy(file, input, input_path_len);
3019 if (input_path_len < sizeof(file))
3020 pstrcpy(file + input_path_len, sizeof(file) - input_path_len,
3022 /* stat the file to find out if it's a directory.
3023 * In that case add a slash to speed up typing long paths
3025 if (stat(file, &sb) == 0 && S_ISDIR(sb.st_mode)) {
3026 pstrcat(file, sizeof(file), "/");
3028 readline_add_completion(mon->rs, file);
3034 static const char *next_arg_type(const char *typestr)
3036 const char *p = strchr(typestr, ':');
3037 return (p != NULL ? ++p : typestr);
3040 static void add_completion_option(ReadLineState *rs, const char *str,
3043 if (!str || !option) {
3046 if (!strncmp(option, str, strlen(str))) {
3047 readline_add_completion(rs, option);
3051 void chardev_add_completion(ReadLineState *rs, int nb_args, const char *str)
3054 ChardevBackendInfoList *list, *start;
3060 readline_set_completion_index(rs, len);
3062 start = list = qmp_query_chardev_backends(NULL);
3064 const char *chr_name = list->value->name;
3066 if (!strncmp(chr_name, str, len)) {
3067 readline_add_completion(rs, chr_name);
3071 qapi_free_ChardevBackendInfoList(start);
3074 void netdev_add_completion(ReadLineState *rs, int nb_args, const char *str)
3083 readline_set_completion_index(rs, len);
3084 for (i = 0; NetClientDriver_lookup[i]; i++) {
3085 add_completion_option(rs, str, NetClientDriver_lookup[i]);
3089 void device_add_completion(ReadLineState *rs, int nb_args, const char *str)
3099 readline_set_completion_index(rs, len);
3100 list = elt = object_class_get_list(TYPE_DEVICE, false);
3103 DeviceClass *dc = OBJECT_CLASS_CHECK(DeviceClass, elt->data,
3105 name = object_class_get_name(OBJECT_CLASS(dc));
3107 if (!dc->cannot_instantiate_with_device_add_yet
3108 && !strncmp(name, str, len)) {
3109 readline_add_completion(rs, name);
3116 void object_add_completion(ReadLineState *rs, int nb_args, const char *str)
3126 readline_set_completion_index(rs, len);
3127 list = elt = object_class_get_list(TYPE_USER_CREATABLE, false);
3131 name = object_class_get_name(OBJECT_CLASS(elt->data));
3132 if (!strncmp(name, str, len) && strcmp(name, TYPE_USER_CREATABLE)) {
3133 readline_add_completion(rs, name);
3140 static void peripheral_device_del_completion(ReadLineState *rs,
3141 const char *str, size_t len)
3143 Object *peripheral = container_get(qdev_get_machine(), "/peripheral");
3144 GSList *list, *item;
3146 list = qdev_build_hotpluggable_device_list(peripheral);
3151 for (item = list; item; item = g_slist_next(item)) {
3152 DeviceState *dev = item->data;
3154 if (dev->id && !strncmp(str, dev->id, len)) {
3155 readline_add_completion(rs, dev->id);
3162 void chardev_remove_completion(ReadLineState *rs, int nb_args, const char *str)
3165 ChardevInfoList *list, *start;
3171 readline_set_completion_index(rs, len);
3173 start = list = qmp_query_chardev(NULL);
3175 ChardevInfo *chr = list->value;
3177 if (!strncmp(chr->label, str, len)) {
3178 readline_add_completion(rs, chr->label);
3182 qapi_free_ChardevInfoList(start);
3185 static void ringbuf_completion(ReadLineState *rs, const char *str)
3188 ChardevInfoList *list, *start;
3191 readline_set_completion_index(rs, len);
3193 start = list = qmp_query_chardev(NULL);
3195 ChardevInfo *chr_info = list->value;
3197 if (!strncmp(chr_info->label, str, len)) {
3198 CharDriverState *chr = qemu_chr_find(chr_info->label);
3199 if (chr && chr_is_ringbuf(chr)) {
3200 readline_add_completion(rs, chr_info->label);
3205 qapi_free_ChardevInfoList(start);
3208 void ringbuf_write_completion(ReadLineState *rs, int nb_args, const char *str)
3213 ringbuf_completion(rs, str);
3216 void device_del_completion(ReadLineState *rs, int nb_args, const char *str)
3225 readline_set_completion_index(rs, len);
3226 peripheral_device_del_completion(rs, str, len);
3229 void object_del_completion(ReadLineState *rs, int nb_args, const char *str)
3231 ObjectPropertyInfoList *list, *start;
3238 readline_set_completion_index(rs, len);
3240 start = list = qmp_qom_list("/objects", NULL);
3242 ObjectPropertyInfo *info = list->value;
3244 if (!strncmp(info->type, "child<", 5)
3245 && !strncmp(info->name, str, len)) {
3246 readline_add_completion(rs, info->name);
3250 qapi_free_ObjectPropertyInfoList(start);
3253 void sendkey_completion(ReadLineState *rs, int nb_args, const char *str)
3262 sep = strrchr(str, '-');
3267 readline_set_completion_index(rs, len);
3268 for (i = 0; i < Q_KEY_CODE__MAX; i++) {
3269 if (!strncmp(str, QKeyCode_lookup[i], len)) {
3270 readline_add_completion(rs, QKeyCode_lookup[i]);
3275 void set_link_completion(ReadLineState *rs, int nb_args, const char *str)
3280 readline_set_completion_index(rs, len);
3282 NetClientState *ncs[MAX_QUEUE_NUM];
3284 count = qemu_find_net_clients_except(NULL, ncs,
3285 NET_CLIENT_DRIVER_NONE,
3287 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3288 const char *name = ncs[i]->name;
3289 if (!strncmp(str, name, len)) {
3290 readline_add_completion(rs, name);
3293 } else if (nb_args == 3) {
3294 add_completion_option(rs, str, "on");
3295 add_completion_option(rs, str, "off");
3299 void netdev_del_completion(ReadLineState *rs, int nb_args, const char *str)
3302 NetClientState *ncs[MAX_QUEUE_NUM];
3309 readline_set_completion_index(rs, len);
3310 count = qemu_find_net_clients_except(NULL, ncs, NET_CLIENT_DRIVER_NIC,
3312 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3314 const char *name = ncs[i]->name;
3315 if (strncmp(str, name, len)) {
3318 opts = qemu_opts_find(qemu_find_opts_err("netdev", NULL), name);
3320 readline_add_completion(rs, name);
3325 void info_trace_events_completion(ReadLineState *rs, int nb_args, const char *str)
3330 readline_set_completion_index(rs, len);
3332 TraceEventIter iter;
3334 char *pattern = g_strdup_printf("%s*", str);
3335 trace_event_iter_init(&iter, pattern);
3336 while ((ev = trace_event_iter_next(&iter)) != NULL) {
3337 readline_add_completion(rs, trace_event_get_name(ev));
3343 void trace_event_completion(ReadLineState *rs, int nb_args, const char *str)
3348 readline_set_completion_index(rs, len);
3350 TraceEventIter iter;
3352 char *pattern = g_strdup_printf("%s*", str);
3353 trace_event_iter_init(&iter, pattern);
3354 while ((ev = trace_event_iter_next(&iter)) != NULL) {
3355 readline_add_completion(rs, trace_event_get_name(ev));
3358 } else if (nb_args == 3) {
3359 add_completion_option(rs, str, "on");
3360 add_completion_option(rs, str, "off");
3364 void watchdog_action_completion(ReadLineState *rs, int nb_args, const char *str)
3371 readline_set_completion_index(rs, strlen(str));
3372 for (i = 0; WatchdogExpirationAction_lookup[i]; i++) {
3373 add_completion_option(rs, str, WatchdogExpirationAction_lookup[i]);
3377 void migrate_set_capability_completion(ReadLineState *rs, int nb_args,
3383 readline_set_completion_index(rs, len);
3386 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
3387 const char *name = MigrationCapability_lookup[i];
3388 if (!strncmp(str, name, len)) {
3389 readline_add_completion(rs, name);
3392 } else if (nb_args == 3) {
3393 add_completion_option(rs, str, "on");
3394 add_completion_option(rs, str, "off");
3398 void migrate_set_parameter_completion(ReadLineState *rs, int nb_args,
3404 readline_set_completion_index(rs, len);
3407 for (i = 0; i < MIGRATION_PARAMETER__MAX; i++) {
3408 const char *name = MigrationParameter_lookup[i];
3409 if (!strncmp(str, name, len)) {
3410 readline_add_completion(rs, name);
3416 void host_net_add_completion(ReadLineState *rs, int nb_args, const char *str)
3424 readline_set_completion_index(rs, len);
3425 for (i = 0; host_net_devices[i]; i++) {
3426 if (!strncmp(host_net_devices[i], str, len)) {
3427 readline_add_completion(rs, host_net_devices[i]);
3432 void host_net_remove_completion(ReadLineState *rs, int nb_args, const char *str)
3434 NetClientState *ncs[MAX_QUEUE_NUM];
3438 readline_set_completion_index(rs, len);
3440 count = qemu_find_net_clients_except(NULL, ncs,
3441 NET_CLIENT_DRIVER_NONE,
3443 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3447 if (net_hub_id_for_client(ncs[i], &id)) {
3450 snprintf(name, sizeof(name), "%d", id);
3451 if (!strncmp(str, name, len)) {
3452 readline_add_completion(rs, name);
3456 } else if (nb_args == 3) {
3457 count = qemu_find_net_clients_except(NULL, ncs,
3458 NET_CLIENT_DRIVER_NIC,
3460 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3464 if (ncs[i]->info->type == NET_CLIENT_DRIVER_HUBPORT ||
3465 net_hub_id_for_client(ncs[i], &id)) {
3468 name = ncs[i]->name;
3469 if (!strncmp(str, name, len)) {
3470 readline_add_completion(rs, name);
3477 static void vm_completion(ReadLineState *rs, const char *str)
3480 BlockDriverState *bs;
3481 BdrvNextIterator it;
3484 readline_set_completion_index(rs, len);
3486 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
3487 SnapshotInfoList *snapshots, *snapshot;
3488 AioContext *ctx = bdrv_get_aio_context(bs);
3491 aio_context_acquire(ctx);
3492 if (bdrv_can_snapshot(bs)) {
3493 ok = bdrv_query_snapshot_info_list(bs, &snapshots, NULL) == 0;
3495 aio_context_release(ctx);
3500 snapshot = snapshots;
3502 char *completion = snapshot->value->name;
3503 if (!strncmp(str, completion, len)) {
3504 readline_add_completion(rs, completion);
3506 completion = snapshot->value->id;
3507 if (!strncmp(str, completion, len)) {
3508 readline_add_completion(rs, completion);
3510 snapshot = snapshot->next;
3512 qapi_free_SnapshotInfoList(snapshots);
3517 void delvm_completion(ReadLineState *rs, int nb_args, const char *str)
3520 vm_completion(rs, str);
3524 void loadvm_completion(ReadLineState *rs, int nb_args, const char *str)
3527 vm_completion(rs, str);
3531 static void monitor_find_completion_by_table(Monitor *mon,
3532 const mon_cmd_t *cmd_table,
3536 const char *cmdname;
3538 const char *ptype, *str, *name;
3539 const mon_cmd_t *cmd;
3540 BlockBackend *blk = NULL;
3543 /* command completion */
3548 readline_set_completion_index(mon->rs, strlen(cmdname));
3549 for (cmd = cmd_table; cmd->name != NULL; cmd++) {
3550 cmd_completion(mon, cmdname, cmd->name);
3553 /* find the command */
3554 for (cmd = cmd_table; cmd->name != NULL; cmd++) {
3555 if (compare_cmd(args[0], cmd->name)) {
3563 if (cmd->sub_table) {
3564 /* do the job again */
3565 monitor_find_completion_by_table(mon, cmd->sub_table,
3566 &args[1], nb_args - 1);
3569 if (cmd->command_completion) {
3570 cmd->command_completion(mon->rs, nb_args, args[nb_args - 1]);
3574 ptype = next_arg_type(cmd->args_type);
3575 for(i = 0; i < nb_args - 2; i++) {
3576 if (*ptype != '\0') {
3577 ptype = next_arg_type(ptype);
3578 while (*ptype == '?')
3579 ptype = next_arg_type(ptype);
3582 str = args[nb_args - 1];
3583 while (*ptype == '-' && ptype[1] != '\0') {
3584 ptype = next_arg_type(ptype);
3588 /* file completion */
3589 readline_set_completion_index(mon->rs, strlen(str));
3590 file_completion(mon, str);
3593 /* block device name completion */
3594 readline_set_completion_index(mon->rs, strlen(str));
3595 while ((blk = blk_next(blk)) != NULL) {
3596 name = blk_name(blk);
3597 if (str[0] == '\0' ||
3598 !strncmp(name, str, strlen(str))) {
3599 readline_add_completion(mon->rs, name);
3605 if (!strcmp(cmd->name, "help|?")) {
3606 monitor_find_completion_by_table(mon, cmd_table,
3607 &args[1], nb_args - 1);
3616 static void monitor_find_completion(void *opaque,
3617 const char *cmdline)
3619 Monitor *mon = opaque;
3620 char *args[MAX_ARGS];
3623 /* 1. parse the cmdline */
3624 if (parse_cmdline(cmdline, &nb_args, args) < 0) {
3628 /* if the line ends with a space, it means we want to complete the
3630 len = strlen(cmdline);
3631 if (len > 0 && qemu_isspace(cmdline[len - 1])) {
3632 if (nb_args >= MAX_ARGS) {
3635 args[nb_args++] = g_strdup("");
3638 /* 2. auto complete according to args */
3639 monitor_find_completion_by_table(mon, mon->cmd_table, args, nb_args);
3642 free_cmdline_args(args, nb_args);
3645 static int monitor_can_read(void *opaque)
3647 Monitor *mon = opaque;
3649 return (mon->suspend_cnt == 0) ? 1 : 0;
3652 static bool invalid_qmp_mode(const Monitor *mon, const char *cmd,
3655 bool is_cap = g_str_equal(cmd, "qmp_capabilities");
3657 if (is_cap && mon->qmp.in_command_mode) {
3658 error_set(errp, ERROR_CLASS_COMMAND_NOT_FOUND,
3659 "Capabilities negotiation is already complete, command "
3660 "'%s' ignored", cmd);
3663 if (!is_cap && !mon->qmp.in_command_mode) {
3664 error_set(errp, ERROR_CLASS_COMMAND_NOT_FOUND,
3665 "Expecting capabilities negotiation with "
3666 "'qmp_capabilities' before command '%s'", cmd);
3673 * Input object checking rules
3675 * 1. Input object must be a dict
3676 * 2. The "execute" key must exist
3677 * 3. The "execute" key must be a string
3678 * 4. If the "arguments" key exists, it must be a dict
3679 * 5. If the "id" key exists, it can be anything (ie. json-value)
3680 * 6. Any argument not listed above is considered invalid
3682 static QDict *qmp_check_input_obj(QObject *input_obj, Error **errp)
3684 const QDictEntry *ent;
3685 int has_exec_key = 0;
3688 if (qobject_type(input_obj) != QTYPE_QDICT) {
3689 error_setg(errp, QERR_QMP_BAD_INPUT_OBJECT, "object");
3693 input_dict = qobject_to_qdict(input_obj);
3695 for (ent = qdict_first(input_dict); ent; ent = qdict_next(input_dict, ent)){
3696 const char *arg_name = qdict_entry_key(ent);
3697 const QObject *arg_obj = qdict_entry_value(ent);
3699 if (!strcmp(arg_name, "execute")) {
3700 if (qobject_type(arg_obj) != QTYPE_QSTRING) {
3701 error_setg(errp, QERR_QMP_BAD_INPUT_OBJECT_MEMBER,
3702 "execute", "string");
3706 } else if (!strcmp(arg_name, "arguments")) {
3707 if (qobject_type(arg_obj) != QTYPE_QDICT) {
3708 error_setg(errp, QERR_QMP_BAD_INPUT_OBJECT_MEMBER,
3709 "arguments", "object");
3712 } else if (!strcmp(arg_name, "id")) {
3713 /* Any string is acceptable as "id", so nothing to check */
3715 error_setg(errp, QERR_QMP_EXTRA_MEMBER, arg_name);
3720 if (!has_exec_key) {
3721 error_setg(errp, QERR_QMP_BAD_INPUT_OBJECT, "execute");
3728 static void handle_qmp_command(JSONMessageParser *parser, GQueue *tokens)
3730 QObject *req, *rsp = NULL, *id = NULL;
3731 QDict *qdict = NULL;
3732 const char *cmd_name;
3733 Monitor *mon = cur_mon;
3736 req = json_parser_parse_err(tokens, NULL, &err);
3737 if (err || !req || qobject_type(req) != QTYPE_QDICT) {
3739 error_setg(&err, QERR_JSON_PARSING);
3744 qdict = qmp_check_input_obj(req, &err);
3749 id = qdict_get(qdict, "id");
3751 qdict_del(qdict, "id");
3753 cmd_name = qdict_get_str(qdict, "execute");
3754 trace_handle_qmp_command(mon, cmd_name);
3756 if (invalid_qmp_mode(mon, cmd_name, &err)) {
3760 rsp = qmp_dispatch(req);
3764 qdict = qdict_new();
3765 qdict_put_obj(qdict, "error", qmp_build_error_object(err));
3767 rsp = QOBJECT(qdict);
3772 qdict_put_obj(qobject_to_qdict(rsp), "id", id);
3776 monitor_json_emitter(mon, rsp);
3780 qobject_decref(rsp);
3781 qobject_decref(req);
3784 static void monitor_qmp_read(void *opaque, const uint8_t *buf, int size)
3786 Monitor *old_mon = cur_mon;
3790 json_message_parser_feed(&cur_mon->qmp.parser, (const char *) buf, size);
3795 static void monitor_read(void *opaque, const uint8_t *buf, int size)
3797 Monitor *old_mon = cur_mon;
3803 for (i = 0; i < size; i++)
3804 readline_handle_byte(cur_mon->rs, buf[i]);
3806 if (size == 0 || buf[size - 1] != 0)
3807 monitor_printf(cur_mon, "corrupted command\n");
3809 handle_hmp_command(cur_mon, (char *)buf);
3815 static void monitor_command_cb(void *opaque, const char *cmdline,
3816 void *readline_opaque)
3818 Monitor *mon = opaque;
3820 monitor_suspend(mon);
3821 handle_hmp_command(mon, cmdline);
3822 monitor_resume(mon);
3825 int monitor_suspend(Monitor *mon)
3833 void monitor_resume(Monitor *mon)
3837 if (--mon->suspend_cnt == 0)
3838 readline_show_prompt(mon->rs);
3841 static QObject *get_qmp_greeting(void)
3843 QObject *ver = NULL;
3845 qmp_marshal_query_version(NULL, &ver, NULL);
3847 return qobject_from_jsonf("{'QMP': {'version': %p, 'capabilities': []}}",
3851 static void monitor_qmp_event(void *opaque, int event)
3854 Monitor *mon = opaque;
3857 case CHR_EVENT_OPENED:
3858 mon->qmp.in_command_mode = false;
3859 data = get_qmp_greeting();
3860 monitor_json_emitter(mon, data);
3861 qobject_decref(data);
3864 case CHR_EVENT_CLOSED:
3865 json_message_parser_destroy(&mon->qmp.parser);
3866 json_message_parser_init(&mon->qmp.parser, handle_qmp_command);
3868 monitor_fdsets_cleanup();
3873 static void monitor_event(void *opaque, int event)
3875 Monitor *mon = opaque;
3878 case CHR_EVENT_MUX_IN:
3879 qemu_mutex_lock(&mon->out_lock);
3881 qemu_mutex_unlock(&mon->out_lock);
3882 if (mon->reset_seen) {
3883 readline_restart(mon->rs);
3884 monitor_resume(mon);
3887 mon->suspend_cnt = 0;
3891 case CHR_EVENT_MUX_OUT:
3892 if (mon->reset_seen) {
3893 if (mon->suspend_cnt == 0) {
3894 monitor_printf(mon, "\n");
3897 monitor_suspend(mon);
3901 qemu_mutex_lock(&mon->out_lock);
3903 qemu_mutex_unlock(&mon->out_lock);
3906 case CHR_EVENT_OPENED:
3907 monitor_printf(mon, "QEMU %s monitor - type 'help' for more "
3908 "information\n", QEMU_VERSION);
3909 if (!mon->mux_out) {
3910 readline_restart(mon->rs);
3911 readline_show_prompt(mon->rs);
3913 mon->reset_seen = 1;
3917 case CHR_EVENT_CLOSED:
3919 monitor_fdsets_cleanup();
3925 compare_mon_cmd(const void *a, const void *b)
3927 return strcmp(((const mon_cmd_t *)a)->name,
3928 ((const mon_cmd_t *)b)->name);
3931 static void sortcmdlist(void)
3934 int elem_size = sizeof(mon_cmd_t);
3936 array_num = sizeof(mon_cmds)/elem_size-1;
3937 qsort((void *)mon_cmds, array_num, elem_size, compare_mon_cmd);
3939 array_num = sizeof(info_cmds)/elem_size-1;
3940 qsort((void *)info_cmds, array_num, elem_size, compare_mon_cmd);
3943 /* These functions just adapt the readline interface in a typesafe way. We
3944 * could cast function pointers but that discards compiler checks.
3946 static void GCC_FMT_ATTR(2, 3) monitor_readline_printf(void *opaque,
3947 const char *fmt, ...)
3951 monitor_vprintf(opaque, fmt, ap);
3955 static void monitor_readline_flush(void *opaque)
3957 monitor_flush(opaque);
3960 static void __attribute__((constructor)) monitor_lock_init(void)
3962 qemu_mutex_init(&monitor_lock);
3965 void monitor_init(CharDriverState *chr, int flags)
3967 static int is_first_init = 1;
3970 if (is_first_init) {
3971 monitor_qapi_event_init();
3976 mon = g_malloc(sizeof(*mon));
3977 monitor_data_init(mon);
3979 qemu_chr_fe_init(&mon->chr, chr, &error_abort);
3981 if (flags & MONITOR_USE_READLINE) {
3982 mon->rs = readline_init(monitor_readline_printf,
3983 monitor_readline_flush,
3985 monitor_find_completion);
3986 monitor_read_command(mon, 0);
3989 if (monitor_is_qmp(mon)) {
3990 qemu_chr_fe_set_handlers(&mon->chr, monitor_can_read, monitor_qmp_read,
3991 monitor_qmp_event, mon, NULL, true);
3992 qemu_chr_fe_set_echo(&mon->chr, true);
3993 json_message_parser_init(&mon->qmp.parser, handle_qmp_command);
3995 qemu_chr_fe_set_handlers(&mon->chr, monitor_can_read, monitor_read,
3996 monitor_event, mon, NULL, true);
3999 qemu_mutex_lock(&monitor_lock);
4000 QLIST_INSERT_HEAD(&mon_list, mon, entry);
4001 qemu_mutex_unlock(&monitor_lock);
4004 void monitor_cleanup(void)
4006 Monitor *mon, *next;
4008 qemu_mutex_lock(&monitor_lock);
4009 QLIST_FOREACH_SAFE(mon, &mon_list, entry, next) {
4010 QLIST_REMOVE(mon, entry);
4011 monitor_data_destroy(mon);
4014 qemu_mutex_unlock(&monitor_lock);
4017 static void bdrv_password_cb(void *opaque, const char *password,
4018 void *readline_opaque)
4020 Monitor *mon = opaque;
4021 BlockDriverState *bs = readline_opaque;
4023 Error *local_err = NULL;
4025 bdrv_add_key(bs, password, &local_err);
4027 error_report_err(local_err);
4030 if (mon->password_completion_cb)
4031 mon->password_completion_cb(mon->password_opaque, ret);
4033 monitor_read_command(mon, 1);
4036 int monitor_read_bdrv_key_start(Monitor *mon, BlockDriverState *bs,
4037 BlockCompletionFunc *completion_cb,
4042 monitor_printf(mon, "%s (%s) is encrypted.\n", bdrv_get_device_name(bs),
4043 bdrv_get_encrypted_filename(bs));
4045 mon->password_completion_cb = completion_cb;
4046 mon->password_opaque = opaque;
4048 err = monitor_read_password(mon, bdrv_password_cb, bs);
4050 if (err && completion_cb)
4051 completion_cb(opaque, err);
4056 int monitor_read_block_device_key(Monitor *mon, const char *device,
4057 BlockCompletionFunc *completion_cb,
4063 blk = blk_by_name(device);
4065 monitor_printf(mon, "Device not found %s\n", device);
4069 monitor_printf(mon, "Device '%s' has no medium\n", device);
4073 bdrv_add_key(blk_bs(blk), NULL, &err);
4076 return monitor_read_bdrv_key_start(mon, blk_bs(blk), completion_cb, opaque);
4079 if (completion_cb) {
4080 completion_cb(opaque, 0);
4085 QemuOptsList qemu_mon_opts = {
4087 .implied_opt_name = "chardev",
4088 .head = QTAILQ_HEAD_INITIALIZER(qemu_mon_opts.head),
4092 .type = QEMU_OPT_STRING,
4095 .type = QEMU_OPT_STRING,
4098 .type = QEMU_OPT_BOOL,
4101 .type = QEMU_OPT_BOOL,
4103 { /* end of list */ }
4108 void qmp_rtc_reset_reinjection(Error **errp)
4110 error_setg(errp, QERR_FEATURE_DISABLED, "rtc-reset-reinjection");
4114 #ifndef TARGET_S390X
4115 void qmp_dump_skeys(const char *filename, Error **errp)
4117 error_setg(errp, QERR_FEATURE_DISABLED, "dump-skeys");
4122 GICCapabilityList *qmp_query_gic_capabilities(Error **errp)
4124 error_setg(errp, QERR_FEATURE_DISABLED, "query-gic-capabilities");
4129 HotpluggableCPUList *qmp_query_hotpluggable_cpus(Error **errp)
4131 MachineState *ms = MACHINE(qdev_get_machine());
4132 MachineClass *mc = MACHINE_GET_CLASS(ms);
4134 if (!mc->query_hotpluggable_cpus) {
4135 error_setg(errp, QERR_FEATURE_DISABLED, "query-hotpluggable-cpus");
4139 return mc->query_hotpluggable_cpus(ms);