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
26 #include "monitor/qdev.h"
28 #include "hw/i386/pc.h"
29 #include "hw/pci/pci.h"
30 #include "sysemu/watchdog.h"
31 #include "hw/loader.h"
32 #include "exec/gdbstub.h"
34 #include "net/slirp.h"
35 #include "sysemu/char.h"
36 #include "ui/qemu-spice.h"
37 #include "sysemu/sysemu.h"
38 #include "sysemu/numa.h"
39 #include "monitor/monitor.h"
40 #include "qemu/readline.h"
41 #include "ui/console.h"
43 #include "sysemu/blockdev.h"
44 #include "audio/audio.h"
45 #include "disas/disas.h"
46 #include "sysemu/balloon.h"
47 #include "qemu/timer.h"
48 #include "migration/migration.h"
49 #include "sysemu/kvm.h"
51 #include "sysemu/tpm.h"
52 #include "qapi/qmp/qerror.h"
53 #include "qapi/qmp/qint.h"
54 #include "qapi/qmp/qfloat.h"
55 #include "qapi/qmp/qlist.h"
56 #include "qapi/qmp/qbool.h"
57 #include "qapi/qmp/qstring.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>
62 #include "qemu/osdep.h"
65 #include "trace/control.h"
66 #include "monitor/hmp-target.h"
67 #ifdef CONFIG_TRACE_SIMPLE
68 #include "trace/simple.h"
70 #include "exec/memory.h"
71 #include "qmp-commands.h"
73 #include "qemu/thread.h"
74 #include "block/qapi.h"
75 #include "qapi/qmp-event.h"
76 #include "qapi-event.h"
77 #include "qmp-introspect.h"
78 #include "sysemu/block-backend.h"
80 /* for hmp_info_irq/pic */
81 #if defined(TARGET_SPARC)
82 #include "hw/sparc/sun4m.h"
84 #include "hw/lm32/lm32_pic.h"
86 #if defined(TARGET_S390X)
87 #include "hw/s390x/storage-keys.h"
94 * 'B' block device name
95 * 's' string (accept optional quote)
96 * 'S' it just appends the rest of the string (accept optional quote)
97 * 'O' option string of the form NAME=VALUE,...
98 * parsed according to QemuOptsList given by its name
99 * Example: 'device:O' uses qemu_device_opts.
100 * Restriction: only lists with empty desc are supported
101 * TODO lift the restriction
103 * 'l' target long (32 or 64 bit)
104 * 'M' Non-negative target long (32 or 64 bit), in user mode the
105 * value is multiplied by 2^20 (think Mebibyte)
106 * 'o' octets (aka bytes)
107 * user mode accepts an optional E, e, P, p, T, t, G, g, M, m,
108 * K, k suffix, which multiplies the value by 2^60 for suffixes E
109 * and e, 2^50 for suffixes P and p, 2^40 for suffixes T and t,
110 * 2^30 for suffixes G and g, 2^20 for M and m, 2^10 for K and k
112 * user mode accepts an optional ms, us, ns suffix,
113 * which divides the value by 1e3, 1e6, 1e9, respectively
114 * '/' optional gdb-like print format (like "/10x")
116 * '?' optional type (for all types, except '/')
117 * '.' other form of optional type (for 'i' and 'l')
119 * user mode accepts "on" or "off"
120 * '-' optional parameter (eg. '-f')
124 typedef struct mon_cmd_t {
126 const char *args_type;
130 void (*cmd)(Monitor *mon, const QDict *qdict);
131 void (*cmd_new)(QDict *params, QObject **ret_data, Error **errp);
133 /* @sub_table is a list of 2nd level of commands. If it do not exist,
134 * mhandler should be used. If it exist, sub_table[?].mhandler should be
135 * used, and mhandler of 1st level plays the role of help function.
137 struct mon_cmd_t *sub_table;
138 void (*command_completion)(ReadLineState *rs, int nb_args, const char *str);
141 /* file descriptors passed via SCM_RIGHTS */
142 typedef struct mon_fd_t mon_fd_t;
146 QLIST_ENTRY(mon_fd_t) next;
149 /* file descriptor associated with a file descriptor set */
150 typedef struct MonFdsetFd MonFdsetFd;
155 QLIST_ENTRY(MonFdsetFd) next;
158 /* file descriptor set containing fds passed via SCM_RIGHTS */
159 typedef struct MonFdset MonFdset;
162 QLIST_HEAD(, MonFdsetFd) fds;
163 QLIST_HEAD(, MonFdsetFd) dup_fds;
164 QLIST_ENTRY(MonFdset) next;
169 JSONMessageParser parser;
171 * When a client connects, we're in capabilities negotiation mode.
172 * When command qmp_capabilities succeeds, we go into command
175 bool in_command_mode; /* are we in command mode? */
179 * To prevent flooding clients, events can be throttled. The
180 * throttling is calculated globally, rather than per-Monitor
183 typedef struct MonitorQAPIEventState {
184 QAPIEvent event; /* Event being tracked */
185 QEMUTimer *timer; /* Timer for handling delayed events */
186 QDict *qdict; /* Delayed event (if any) */
187 } MonitorQAPIEventState;
190 int64_t rate; /* Minimum time (in ns) between two events */
191 } MonitorQAPIEventConf;
194 CharDriverState *chr;
204 /* Read under either BQL or out_lock, written with BQL+out_lock. */
210 BlockCompletionFunc *password_completion_cb;
211 void *password_opaque;
212 mon_cmd_t *cmd_table;
213 QLIST_HEAD(,mon_fd_t) fds;
214 QLIST_ENTRY(Monitor) entry;
217 /* QMP checker flags */
218 #define QMP_ACCEPT_UNKNOWNS 1
220 /* Protects mon_list, monitor_event_state. */
221 static QemuMutex monitor_lock;
223 static QLIST_HEAD(mon_list, Monitor) mon_list;
224 static QLIST_HEAD(mon_fdsets, MonFdset) mon_fdsets;
225 static int mon_refcount;
227 static mon_cmd_t mon_cmds[];
228 static mon_cmd_t info_cmds[];
230 static const mon_cmd_t qmp_cmds[];
234 static void monitor_command_cb(void *opaque, const char *cmdline,
235 void *readline_opaque);
238 * Is @mon a QMP monitor?
240 static inline bool monitor_is_qmp(const Monitor *mon)
242 return (mon->flags & MONITOR_USE_CONTROL);
246 * Is the current monitor, if any, a QMP monitor?
248 bool monitor_cur_is_qmp(void)
250 return cur_mon && monitor_is_qmp(cur_mon);
253 void monitor_read_command(Monitor *mon, int show_prompt)
258 readline_start(mon->rs, "(qemu) ", 0, monitor_command_cb, NULL);
260 readline_show_prompt(mon->rs);
263 int monitor_read_password(Monitor *mon, ReadLineFunc *readline_func,
267 readline_start(mon->rs, "Password: ", 1, readline_func, opaque);
268 /* prompt is printed on return from the command handler */
271 monitor_printf(mon, "terminal does not support password prompting\n");
276 static void monitor_flush_locked(Monitor *mon);
278 static gboolean monitor_unblocked(GIOChannel *chan, GIOCondition cond,
281 Monitor *mon = opaque;
283 qemu_mutex_lock(&mon->out_lock);
285 monitor_flush_locked(mon);
286 qemu_mutex_unlock(&mon->out_lock);
290 /* Called with mon->out_lock held. */
291 static void monitor_flush_locked(Monitor *mon)
297 if (mon->skip_flush) {
301 buf = qstring_get_str(mon->outbuf);
302 len = qstring_get_length(mon->outbuf);
304 if (len && !mon->mux_out) {
305 rc = qemu_chr_fe_write(mon->chr, (const uint8_t *) buf, len);
306 if ((rc < 0 && errno != EAGAIN) || (rc == len)) {
307 /* all flushed or error */
308 QDECREF(mon->outbuf);
309 mon->outbuf = qstring_new();
314 QString *tmp = qstring_from_str(buf + rc);
315 QDECREF(mon->outbuf);
318 if (mon->out_watch == 0) {
319 mon->out_watch = qemu_chr_fe_add_watch(mon->chr, G_IO_OUT|G_IO_HUP,
320 monitor_unblocked, mon);
325 void monitor_flush(Monitor *mon)
327 qemu_mutex_lock(&mon->out_lock);
328 monitor_flush_locked(mon);
329 qemu_mutex_unlock(&mon->out_lock);
332 /* flush at every end of line */
333 static void monitor_puts(Monitor *mon, const char *str)
337 qemu_mutex_lock(&mon->out_lock);
343 qstring_append_chr(mon->outbuf, '\r');
345 qstring_append_chr(mon->outbuf, c);
347 monitor_flush_locked(mon);
350 qemu_mutex_unlock(&mon->out_lock);
353 void monitor_vprintf(Monitor *mon, const char *fmt, va_list ap)
360 if (monitor_is_qmp(mon)) {
364 buf = g_strdup_vprintf(fmt, ap);
365 monitor_puts(mon, buf);
369 void monitor_printf(Monitor *mon, const char *fmt, ...)
373 monitor_vprintf(mon, fmt, ap);
377 int monitor_fprintf(FILE *stream, const char *fmt, ...)
381 monitor_vprintf((Monitor *)stream, fmt, ap);
386 static void monitor_json_emitter(Monitor *mon, const QObject *data)
390 json = mon->flags & MONITOR_USE_PRETTY ? qobject_to_json_pretty(data) :
391 qobject_to_json(data);
392 assert(json != NULL);
394 qstring_append_chr(json, '\n');
395 monitor_puts(mon, qstring_get_str(json));
400 static QDict *build_qmp_error_dict(Error *err)
404 obj = qobject_from_jsonf("{ 'error': { 'class': %s, 'desc': %s } }",
405 ErrorClass_lookup[error_get_class(err)],
406 error_get_pretty(err));
408 return qobject_to_qdict(obj);
411 static void monitor_protocol_emitter(Monitor *mon, QObject *data,
416 trace_monitor_protocol_emitter(mon);
419 /* success response */
422 qobject_incref(data);
423 qdict_put_obj(qmp, "return", data);
425 /* return an empty QDict by default */
426 qdict_put(qmp, "return", qdict_new());
430 qmp = build_qmp_error_dict(err);
434 qdict_put_obj(qmp, "id", mon->qmp.id);
438 monitor_json_emitter(mon, QOBJECT(qmp));
443 static MonitorQAPIEventConf monitor_qapi_event_conf[QAPI_EVENT_MAX] = {
444 /* Limit guest-triggerable events to 1 per second */
445 [QAPI_EVENT_RTC_CHANGE] = { 1000 * SCALE_MS },
446 [QAPI_EVENT_WATCHDOG] = { 1000 * SCALE_MS },
447 [QAPI_EVENT_BALLOON_CHANGE] = { 1000 * SCALE_MS },
448 [QAPI_EVENT_QUORUM_REPORT_BAD] = { 1000 * SCALE_MS },
449 [QAPI_EVENT_QUORUM_FAILURE] = { 1000 * SCALE_MS },
450 [QAPI_EVENT_VSERPORT_CHANGE] = { 1000 * SCALE_MS },
453 GHashTable *monitor_qapi_event_state;
456 * Emits the event to every monitor instance, @event is only used for trace
457 * Called with monitor_lock held.
459 static void monitor_qapi_event_emit(QAPIEvent event, QDict *qdict)
463 trace_monitor_protocol_event_emit(event, qdict);
464 QLIST_FOREACH(mon, &mon_list, entry) {
465 if (monitor_is_qmp(mon) && mon->qmp.in_command_mode) {
466 monitor_json_emitter(mon, QOBJECT(qdict));
471 static void monitor_qapi_event_handler(void *opaque);
474 * Queue a new event for emission to Monitor instances,
475 * applying any rate limiting if required.
478 monitor_qapi_event_queue(QAPIEvent event, QDict *qdict, Error **errp)
480 MonitorQAPIEventConf *evconf;
481 MonitorQAPIEventState *evstate;
483 assert(event < QAPI_EVENT_MAX);
484 evconf = &monitor_qapi_event_conf[event];
485 trace_monitor_protocol_event_queue(event, qdict, evconf->rate);
487 qemu_mutex_lock(&monitor_lock);
490 /* Unthrottled event */
491 monitor_qapi_event_emit(event, qdict);
493 MonitorQAPIEventState key = { .event = event };
495 evstate = g_hash_table_lookup(monitor_qapi_event_state, &key);
496 assert(!evstate || timer_pending(evstate->timer));
500 * Timer is pending for (at least) evconf->rate ns after
501 * last send. Store event for sending when timer fires,
502 * replacing a prior stored event if any.
504 QDECREF(evstate->qdict);
505 evstate->qdict = qdict;
506 QINCREF(evstate->qdict);
509 * Last send was (at least) evconf->rate ns ago.
510 * Send immediately, and arm the timer to call
511 * monitor_qapi_event_handler() in evconf->rate ns. Any
512 * events arriving before then will be delayed until then.
514 int64_t now = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
516 monitor_qapi_event_emit(event, qdict);
518 evstate = g_new(MonitorQAPIEventState, 1);
519 evstate->event = event;
520 evstate->qdict = NULL;
521 evstate->timer = timer_new_ns(QEMU_CLOCK_REALTIME,
522 monitor_qapi_event_handler,
524 g_hash_table_add(monitor_qapi_event_state, evstate);
525 timer_mod_ns(evstate->timer, now + evconf->rate);
529 qemu_mutex_unlock(&monitor_lock);
533 * This function runs evconf->rate ns after sending a throttled
535 * If another event has since been stored, send it.
537 static void monitor_qapi_event_handler(void *opaque)
539 MonitorQAPIEventState *evstate = opaque;
540 MonitorQAPIEventConf *evconf = &monitor_qapi_event_conf[evstate->event];
542 trace_monitor_protocol_event_handler(evstate->event, evstate->qdict);
543 qemu_mutex_lock(&monitor_lock);
545 if (evstate->qdict) {
546 int64_t now = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
548 monitor_qapi_event_emit(evstate->event, evstate->qdict);
549 QDECREF(evstate->qdict);
550 evstate->qdict = NULL;
551 timer_mod_ns(evstate->timer, now + evconf->rate);
553 g_hash_table_remove(monitor_qapi_event_state, evstate);
554 timer_free(evstate->timer);
558 qemu_mutex_unlock(&monitor_lock);
561 static unsigned int qapi_event_throttle_hash(const void *key)
563 const MonitorQAPIEventState *evstate = key;
565 return evstate->event * 255;
568 static gboolean qapi_event_throttle_equal(const void *a, const void *b)
570 const MonitorQAPIEventState *eva = a;
571 const MonitorQAPIEventState *evb = b;
573 return eva->event == evb->event;
576 static void monitor_qapi_event_init(void)
578 monitor_qapi_event_state = g_hash_table_new(qapi_event_throttle_hash,
579 qapi_event_throttle_equal);
580 qmp_event_set_func_emit(monitor_qapi_event_queue);
583 static void qmp_capabilities(QDict *params, QObject **ret_data, Error **errp)
585 cur_mon->qmp.in_command_mode = true;
588 static void handle_hmp_command(Monitor *mon, const char *cmdline);
590 static void monitor_data_init(Monitor *mon)
592 memset(mon, 0, sizeof(Monitor));
593 qemu_mutex_init(&mon->out_lock);
594 mon->outbuf = qstring_new();
595 /* Use *mon_cmds by default. */
596 mon->cmd_table = mon_cmds;
599 static void monitor_data_destroy(Monitor *mon)
601 QDECREF(mon->outbuf);
602 qemu_mutex_destroy(&mon->out_lock);
605 char *qmp_human_monitor_command(const char *command_line, bool has_cpu_index,
606 int64_t cpu_index, Error **errp)
609 Monitor *old_mon, hmp;
611 monitor_data_init(&hmp);
612 hmp.skip_flush = true;
618 int ret = monitor_set_cpu(cpu_index);
621 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cpu-index",
627 handle_hmp_command(&hmp, command_line);
630 qemu_mutex_lock(&hmp.out_lock);
631 if (qstring_get_length(hmp.outbuf) > 0) {
632 output = g_strdup(qstring_get_str(hmp.outbuf));
634 output = g_strdup("");
636 qemu_mutex_unlock(&hmp.out_lock);
639 monitor_data_destroy(&hmp);
643 static int compare_cmd(const char *name, const char *list)
645 const char *p, *pstart;
653 p = pstart + strlen(pstart);
654 if ((p - pstart) == len && !memcmp(pstart, name, len))
663 static int get_str(char *buf, int buf_size, const char **pp)
671 while (qemu_isspace(*p)) {
682 while (*p != '\0' && *p != '\"') {
698 printf("unsupported escape code: '\\%c'\n", c);
701 if ((q - buf) < buf_size - 1) {
705 if ((q - buf) < buf_size - 1) {
712 printf("unterminated string\n");
717 while (*p != '\0' && !qemu_isspace(*p)) {
718 if ((q - buf) < buf_size - 1) {
731 static void free_cmdline_args(char **args, int nb_args)
735 assert(nb_args <= MAX_ARGS);
737 for (i = 0; i < nb_args; i++) {
744 * Parse the command line to get valid args.
745 * @cmdline: command line to be parsed.
746 * @pnb_args: location to store the number of args, must NOT be NULL.
747 * @args: location to store the args, which should be freed by caller, must
750 * Returns 0 on success, negative on failure.
752 * NOTE: this parser is an approximate form of the real command parser. Number
753 * of args have a limit of MAX_ARGS. If cmdline contains more, it will
754 * return with failure.
756 static int parse_cmdline(const char *cmdline,
757 int *pnb_args, char **args)
766 while (qemu_isspace(*p)) {
772 if (nb_args >= MAX_ARGS) {
775 ret = get_str(buf, sizeof(buf), &p);
779 args[nb_args] = g_strdup(buf);
786 free_cmdline_args(args, nb_args);
790 static void help_cmd_dump_one(Monitor *mon,
791 const mon_cmd_t *cmd,
797 for (i = 0; i < prefix_args_nb; i++) {
798 monitor_printf(mon, "%s ", prefix_args[i]);
800 monitor_printf(mon, "%s %s -- %s\n", cmd->name, cmd->params, cmd->help);
803 /* @args[@arg_index] is the valid command need to find in @cmds */
804 static void help_cmd_dump(Monitor *mon, const mon_cmd_t *cmds,
805 char **args, int nb_args, int arg_index)
807 const mon_cmd_t *cmd;
809 /* No valid arg need to compare with, dump all in *cmds */
810 if (arg_index >= nb_args) {
811 for (cmd = cmds; cmd->name != NULL; cmd++) {
812 help_cmd_dump_one(mon, cmd, args, arg_index);
817 /* Find one entry to dump */
818 for (cmd = cmds; cmd->name != NULL; cmd++) {
819 if (compare_cmd(args[arg_index], cmd->name)) {
820 if (cmd->sub_table) {
821 /* continue with next arg */
822 help_cmd_dump(mon, cmd->sub_table,
823 args, nb_args, arg_index + 1);
825 help_cmd_dump_one(mon, cmd, args, arg_index);
832 static void help_cmd(Monitor *mon, const char *name)
834 char *args[MAX_ARGS];
837 /* 1. parse user input */
839 /* special case for log, directly dump and return */
840 if (!strcmp(name, "log")) {
841 const QEMULogItem *item;
842 monitor_printf(mon, "Log items (comma separated):\n");
843 monitor_printf(mon, "%-10s %s\n", "none", "remove all logs");
844 for (item = qemu_log_items; item->mask != 0; item++) {
845 monitor_printf(mon, "%-10s %s\n", item->name, item->help);
850 if (parse_cmdline(name, &nb_args, args) < 0) {
855 /* 2. dump the contents according to parsed args */
856 help_cmd_dump(mon, mon->cmd_table, args, nb_args, 0);
858 free_cmdline_args(args, nb_args);
861 static void do_help_cmd(Monitor *mon, const QDict *qdict)
863 help_cmd(mon, qdict_get_try_str(qdict, "name"));
866 static void hmp_trace_event(Monitor *mon, const QDict *qdict)
868 const char *tp_name = qdict_get_str(qdict, "name");
869 bool new_state = qdict_get_bool(qdict, "option");
870 Error *local_err = NULL;
872 qmp_trace_event_set_state(tp_name, new_state, true, true, &local_err);
874 error_report_err(local_err);
878 #ifdef CONFIG_TRACE_SIMPLE
879 static void hmp_trace_file(Monitor *mon, const QDict *qdict)
881 const char *op = qdict_get_try_str(qdict, "op");
882 const char *arg = qdict_get_try_str(qdict, "arg");
885 st_print_trace_file_status((FILE *)mon, &monitor_fprintf);
886 } else if (!strcmp(op, "on")) {
887 st_set_trace_file_enabled(true);
888 } else if (!strcmp(op, "off")) {
889 st_set_trace_file_enabled(false);
890 } else if (!strcmp(op, "flush")) {
891 st_flush_trace_buffer();
892 } else if (!strcmp(op, "set")) {
894 st_set_trace_file(arg);
897 monitor_printf(mon, "unexpected argument \"%s\"\n", op);
898 help_cmd(mon, "trace-file");
903 static void hmp_info_help(Monitor *mon, const QDict *qdict)
905 help_cmd(mon, "info");
908 CommandInfoList *qmp_query_commands(Error **errp)
910 CommandInfoList *info, *cmd_list = NULL;
911 const mon_cmd_t *cmd;
913 for (cmd = qmp_cmds; cmd->name != NULL; cmd++) {
914 info = g_malloc0(sizeof(*info));
915 info->value = g_malloc0(sizeof(*info->value));
916 info->value->name = g_strdup(cmd->name);
918 info->next = cmd_list;
925 EventInfoList *qmp_query_events(Error **errp)
927 EventInfoList *info, *ev_list = NULL;
930 for (e = 0 ; e < QAPI_EVENT_MAX ; e++) {
931 const char *event_name = QAPIEvent_lookup[e];
932 assert(event_name != NULL);
933 info = g_malloc0(sizeof(*info));
934 info->value = g_malloc0(sizeof(*info->value));
935 info->value->name = g_strdup(event_name);
937 info->next = ev_list;
945 * Minor hack: generated marshalling suppressed for this command
946 * ('gen': false in the schema) so we can parse the JSON string
947 * directly into QObject instead of first parsing it with
948 * visit_type_SchemaInfoList() into a SchemaInfoList, then marshal it
949 * to QObject with generated output marshallers, every time. Instead,
950 * we do it in test-qmp-input-visitor.c, just to make sure
951 * qapi-introspect.py's output actually conforms to the schema.
953 static void qmp_query_qmp_schema(QDict *qdict, QObject **ret_data,
956 *ret_data = qobject_from_json(qmp_schema_json);
959 /* set the current CPU defined by the user */
960 int monitor_set_cpu(int cpu_index)
964 cpu = qemu_get_cpu(cpu_index);
968 cur_mon->mon_cpu = cpu;
972 CPUState *mon_get_cpu(void)
974 if (!cur_mon->mon_cpu) {
977 cpu_synchronize_state(cur_mon->mon_cpu);
978 return cur_mon->mon_cpu;
981 CPUArchState *mon_get_cpu_env(void)
983 return mon_get_cpu()->env_ptr;
986 int monitor_get_cpu_index(void)
988 return mon_get_cpu()->cpu_index;
991 static void hmp_info_registers(Monitor *mon, const QDict *qdict)
993 cpu_dump_state(mon_get_cpu(), (FILE *)mon, monitor_fprintf, CPU_DUMP_FPU);
996 static void hmp_info_jit(Monitor *mon, const QDict *qdict)
998 dump_exec_info((FILE *)mon, monitor_fprintf);
999 dump_drift_info((FILE *)mon, monitor_fprintf);
1002 static void hmp_info_opcount(Monitor *mon, const QDict *qdict)
1004 dump_opcount_info((FILE *)mon, monitor_fprintf);
1007 static void hmp_info_history(Monitor *mon, const QDict *qdict)
1016 str = readline_get_history(mon->rs, i);
1019 monitor_printf(mon, "%d: '%s'\n", i, str);
1024 static void hmp_info_cpustats(Monitor *mon, const QDict *qdict)
1026 cpu_dump_statistics(mon_get_cpu(), (FILE *)mon, &monitor_fprintf, 0);
1029 static void hmp_info_trace_events(Monitor *mon, const QDict *qdict)
1031 TraceEventInfoList *events = qmp_trace_event_get_state("*", NULL);
1032 TraceEventInfoList *elem;
1034 for (elem = events; elem != NULL; elem = elem->next) {
1035 monitor_printf(mon, "%s : state %u\n",
1037 elem->value->state == TRACE_EVENT_STATE_ENABLED ? 1 : 0);
1039 qapi_free_TraceEventInfoList(events);
1042 void qmp_client_migrate_info(const char *protocol, const char *hostname,
1043 bool has_port, int64_t port,
1044 bool has_tls_port, int64_t tls_port,
1045 bool has_cert_subject, const char *cert_subject,
1048 if (strcmp(protocol, "spice") == 0) {
1049 if (!qemu_using_spice(errp)) {
1053 if (!has_port && !has_tls_port) {
1054 error_setg(errp, QERR_MISSING_PARAMETER, "port/tls-port");
1058 if (qemu_spice_migrate_info(hostname,
1059 has_port ? port : -1,
1060 has_tls_port ? tls_port : -1,
1062 error_setg(errp, QERR_UNDEFINED_ERROR);
1068 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "protocol", "spice");
1071 static void hmp_logfile(Monitor *mon, const QDict *qdict)
1073 qemu_set_log_filename(qdict_get_str(qdict, "filename"));
1076 static void hmp_log(Monitor *mon, const QDict *qdict)
1079 const char *items = qdict_get_str(qdict, "items");
1081 if (!strcmp(items, "none")) {
1084 mask = qemu_str_to_log_mask(items);
1086 help_cmd(mon, "log");
1093 static void hmp_singlestep(Monitor *mon, const QDict *qdict)
1095 const char *option = qdict_get_try_str(qdict, "option");
1096 if (!option || !strcmp(option, "on")) {
1098 } else if (!strcmp(option, "off")) {
1101 monitor_printf(mon, "unexpected option %s\n", option);
1105 static void hmp_gdbserver(Monitor *mon, const QDict *qdict)
1107 const char *device = qdict_get_try_str(qdict, "device");
1109 device = "tcp::" DEFAULT_GDBSTUB_PORT;
1110 if (gdbserver_start(device) < 0) {
1111 monitor_printf(mon, "Could not open gdbserver on device '%s'\n",
1113 } else if (strcmp(device, "none") == 0) {
1114 monitor_printf(mon, "Disabled gdbserver\n");
1116 monitor_printf(mon, "Waiting for gdb connection on device '%s'\n",
1121 static void hmp_watchdog_action(Monitor *mon, const QDict *qdict)
1123 const char *action = qdict_get_str(qdict, "action");
1124 if (select_watchdog_action(action) == -1) {
1125 monitor_printf(mon, "Unknown watchdog action '%s'\n", action);
1129 static void monitor_printc(Monitor *mon, int c)
1131 monitor_printf(mon, "'");
1134 monitor_printf(mon, "\\'");
1137 monitor_printf(mon, "\\\\");
1140 monitor_printf(mon, "\\n");
1143 monitor_printf(mon, "\\r");
1146 if (c >= 32 && c <= 126) {
1147 monitor_printf(mon, "%c", c);
1149 monitor_printf(mon, "\\x%02x", c);
1153 monitor_printf(mon, "'");
1156 static void memory_dump(Monitor *mon, int count, int format, int wsize,
1157 hwaddr addr, int is_physical)
1159 int l, line_size, i, max_digits, len;
1163 if (format == 'i') {
1166 CPUArchState *env = mon_get_cpu_env();
1169 } else if (wsize == 4) {
1172 /* as default we use the current CS size */
1175 #ifdef TARGET_X86_64
1176 if ((env->efer & MSR_EFER_LMA) &&
1177 (env->segs[R_CS].flags & DESC_L_MASK))
1181 if (!(env->segs[R_CS].flags & DESC_B_MASK))
1187 CPUArchState *env = mon_get_cpu_env();
1188 flags = msr_le << 16;
1189 flags |= env->bfd_mach;
1191 monitor_disas(mon, mon_get_cpu(), addr, count, is_physical, flags);
1195 len = wsize * count;
1204 max_digits = (wsize * 8 + 2) / 3;
1208 max_digits = (wsize * 8) / 4;
1212 max_digits = (wsize * 8 * 10 + 32) / 33;
1221 monitor_printf(mon, TARGET_FMT_plx ":", addr);
1223 monitor_printf(mon, TARGET_FMT_lx ":", (target_ulong)addr);
1228 cpu_physical_memory_read(addr, buf, l);
1230 if (cpu_memory_rw_debug(mon_get_cpu(), addr, buf, l, 0) < 0) {
1231 monitor_printf(mon, " Cannot access memory\n");
1240 v = ldub_p(buf + i);
1243 v = lduw_p(buf + i);
1246 v = (uint32_t)ldl_p(buf + i);
1252 monitor_printf(mon, " ");
1255 monitor_printf(mon, "%#*" PRIo64, max_digits, v);
1258 monitor_printf(mon, "0x%0*" PRIx64, max_digits, v);
1261 monitor_printf(mon, "%*" PRIu64, max_digits, v);
1264 monitor_printf(mon, "%*" PRId64, max_digits, v);
1267 monitor_printc(mon, v);
1272 monitor_printf(mon, "\n");
1278 static void hmp_memory_dump(Monitor *mon, const QDict *qdict)
1280 int count = qdict_get_int(qdict, "count");
1281 int format = qdict_get_int(qdict, "format");
1282 int size = qdict_get_int(qdict, "size");
1283 target_long addr = qdict_get_int(qdict, "addr");
1285 memory_dump(mon, count, format, size, addr, 0);
1288 static void hmp_physical_memory_dump(Monitor *mon, const QDict *qdict)
1290 int count = qdict_get_int(qdict, "count");
1291 int format = qdict_get_int(qdict, "format");
1292 int size = qdict_get_int(qdict, "size");
1293 hwaddr addr = qdict_get_int(qdict, "addr");
1295 memory_dump(mon, count, format, size, addr, 1);
1298 static void do_print(Monitor *mon, const QDict *qdict)
1300 int format = qdict_get_int(qdict, "format");
1301 hwaddr val = qdict_get_int(qdict, "val");
1305 monitor_printf(mon, "%#" HWADDR_PRIo, val);
1308 monitor_printf(mon, "%#" HWADDR_PRIx, val);
1311 monitor_printf(mon, "%" HWADDR_PRIu, val);
1315 monitor_printf(mon, "%" HWADDR_PRId, val);
1318 monitor_printc(mon, val);
1321 monitor_printf(mon, "\n");
1324 static void hmp_sum(Monitor *mon, const QDict *qdict)
1328 uint32_t start = qdict_get_int(qdict, "start");
1329 uint32_t size = qdict_get_int(qdict, "size");
1332 for(addr = start; addr < (start + size); addr++) {
1333 uint8_t val = address_space_ldub(&address_space_memory, addr,
1334 MEMTXATTRS_UNSPECIFIED, NULL);
1335 /* BSD sum algorithm ('sum' Unix command) */
1336 sum = (sum >> 1) | (sum << 15);
1339 monitor_printf(mon, "%05d\n", sum);
1342 static int mouse_button_state;
1344 static void hmp_mouse_move(Monitor *mon, const QDict *qdict)
1346 int dx, dy, dz, button;
1347 const char *dx_str = qdict_get_str(qdict, "dx_str");
1348 const char *dy_str = qdict_get_str(qdict, "dy_str");
1349 const char *dz_str = qdict_get_try_str(qdict, "dz_str");
1351 dx = strtol(dx_str, NULL, 0);
1352 dy = strtol(dy_str, NULL, 0);
1353 qemu_input_queue_rel(NULL, INPUT_AXIS_X, dx);
1354 qemu_input_queue_rel(NULL, INPUT_AXIS_Y, dy);
1357 dz = strtol(dz_str, NULL, 0);
1359 button = (dz > 0) ? INPUT_BUTTON_WHEEL_UP : INPUT_BUTTON_WHEEL_DOWN;
1360 qemu_input_queue_btn(NULL, button, true);
1361 qemu_input_event_sync();
1362 qemu_input_queue_btn(NULL, button, false);
1365 qemu_input_event_sync();
1368 static void hmp_mouse_button(Monitor *mon, const QDict *qdict)
1370 static uint32_t bmap[INPUT_BUTTON_MAX] = {
1371 [INPUT_BUTTON_LEFT] = MOUSE_EVENT_LBUTTON,
1372 [INPUT_BUTTON_MIDDLE] = MOUSE_EVENT_MBUTTON,
1373 [INPUT_BUTTON_RIGHT] = MOUSE_EVENT_RBUTTON,
1375 int button_state = qdict_get_int(qdict, "button_state");
1377 if (mouse_button_state == button_state) {
1380 qemu_input_update_buttons(NULL, bmap, mouse_button_state, button_state);
1381 qemu_input_event_sync();
1382 mouse_button_state = button_state;
1385 static void hmp_ioport_read(Monitor *mon, const QDict *qdict)
1387 int size = qdict_get_int(qdict, "size");
1388 int addr = qdict_get_int(qdict, "addr");
1389 int has_index = qdict_haskey(qdict, "index");
1394 int index = qdict_get_int(qdict, "index");
1395 cpu_outb(addr & IOPORTS_MASK, index & 0xff);
1403 val = cpu_inb(addr);
1407 val = cpu_inw(addr);
1411 val = cpu_inl(addr);
1415 monitor_printf(mon, "port%c[0x%04x] = %#0*x\n",
1416 suffix, addr, size * 2, val);
1419 static void hmp_ioport_write(Monitor *mon, const QDict *qdict)
1421 int size = qdict_get_int(qdict, "size");
1422 int addr = qdict_get_int(qdict, "addr");
1423 int val = qdict_get_int(qdict, "val");
1425 addr &= IOPORTS_MASK;
1430 cpu_outb(addr, val);
1433 cpu_outw(addr, val);
1436 cpu_outl(addr, val);
1441 static void hmp_boot_set(Monitor *mon, const QDict *qdict)
1443 Error *local_err = NULL;
1444 const char *bootdevice = qdict_get_str(qdict, "bootdevice");
1446 qemu_boot_set(bootdevice, &local_err);
1448 monitor_printf(mon, "%s\n", error_get_pretty(local_err));
1449 error_free(local_err);
1451 monitor_printf(mon, "boot device list now set to %s\n", bootdevice);
1455 static void hmp_info_mtree(Monitor *mon, const QDict *qdict)
1457 mtree_info((fprintf_function)monitor_printf, mon);
1460 static void hmp_info_numa(Monitor *mon, const QDict *qdict)
1466 node_mem = g_new0(uint64_t, nb_numa_nodes);
1467 query_numa_node_mem(node_mem);
1468 monitor_printf(mon, "%d nodes\n", nb_numa_nodes);
1469 for (i = 0; i < nb_numa_nodes; i++) {
1470 monitor_printf(mon, "node %d cpus:", i);
1472 if (cpu->numa_node == i) {
1473 monitor_printf(mon, " %d", cpu->cpu_index);
1476 monitor_printf(mon, "\n");
1477 monitor_printf(mon, "node %d size: %" PRId64 " MB\n", i,
1483 #ifdef CONFIG_PROFILER
1488 static void hmp_info_profile(Monitor *mon, const QDict *qdict)
1490 monitor_printf(mon, "async time %" PRId64 " (%0.3f)\n",
1491 dev_time, dev_time / (double)get_ticks_per_sec());
1492 monitor_printf(mon, "qemu time %" PRId64 " (%0.3f)\n",
1493 tcg_time, tcg_time / (double)get_ticks_per_sec());
1498 static void hmp_info_profile(Monitor *mon, const QDict *qdict)
1500 monitor_printf(mon, "Internal profiler not compiled\n");
1504 /* Capture support */
1505 static QLIST_HEAD (capture_list_head, CaptureState) capture_head;
1507 static void hmp_info_capture(Monitor *mon, const QDict *qdict)
1512 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
1513 monitor_printf(mon, "[%d]: ", i);
1514 s->ops.info (s->opaque);
1518 static void hmp_stopcapture(Monitor *mon, const QDict *qdict)
1521 int n = qdict_get_int(qdict, "n");
1524 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
1526 s->ops.destroy (s->opaque);
1527 QLIST_REMOVE (s, entries);
1534 static void hmp_wavcapture(Monitor *mon, const QDict *qdict)
1536 const char *path = qdict_get_str(qdict, "path");
1537 int has_freq = qdict_haskey(qdict, "freq");
1538 int freq = qdict_get_try_int(qdict, "freq", -1);
1539 int has_bits = qdict_haskey(qdict, "bits");
1540 int bits = qdict_get_try_int(qdict, "bits", -1);
1541 int has_channels = qdict_haskey(qdict, "nchannels");
1542 int nchannels = qdict_get_try_int(qdict, "nchannels", -1);
1545 s = g_malloc0 (sizeof (*s));
1547 freq = has_freq ? freq : 44100;
1548 bits = has_bits ? bits : 16;
1549 nchannels = has_channels ? nchannels : 2;
1551 if (wav_start_capture (s, path, freq, bits, nchannels)) {
1552 monitor_printf(mon, "Failed to add wave capture\n");
1556 QLIST_INSERT_HEAD (&capture_head, s, entries);
1559 static qemu_acl *find_acl(Monitor *mon, const char *name)
1561 qemu_acl *acl = qemu_acl_find(name);
1564 monitor_printf(mon, "acl: unknown list '%s'\n", name);
1569 static void hmp_acl_show(Monitor *mon, const QDict *qdict)
1571 const char *aclname = qdict_get_str(qdict, "aclname");
1572 qemu_acl *acl = find_acl(mon, aclname);
1573 qemu_acl_entry *entry;
1577 monitor_printf(mon, "policy: %s\n",
1578 acl->defaultDeny ? "deny" : "allow");
1579 QTAILQ_FOREACH(entry, &acl->entries, next) {
1581 monitor_printf(mon, "%d: %s %s\n", i,
1582 entry->deny ? "deny" : "allow", entry->match);
1587 static void hmp_acl_reset(Monitor *mon, const QDict *qdict)
1589 const char *aclname = qdict_get_str(qdict, "aclname");
1590 qemu_acl *acl = find_acl(mon, aclname);
1593 qemu_acl_reset(acl);
1594 monitor_printf(mon, "acl: removed all rules\n");
1598 static void hmp_acl_policy(Monitor *mon, const QDict *qdict)
1600 const char *aclname = qdict_get_str(qdict, "aclname");
1601 const char *policy = qdict_get_str(qdict, "policy");
1602 qemu_acl *acl = find_acl(mon, aclname);
1605 if (strcmp(policy, "allow") == 0) {
1606 acl->defaultDeny = 0;
1607 monitor_printf(mon, "acl: policy set to 'allow'\n");
1608 } else if (strcmp(policy, "deny") == 0) {
1609 acl->defaultDeny = 1;
1610 monitor_printf(mon, "acl: policy set to 'deny'\n");
1612 monitor_printf(mon, "acl: unknown policy '%s', "
1613 "expected 'deny' or 'allow'\n", policy);
1618 static void hmp_acl_add(Monitor *mon, const QDict *qdict)
1620 const char *aclname = qdict_get_str(qdict, "aclname");
1621 const char *match = qdict_get_str(qdict, "match");
1622 const char *policy = qdict_get_str(qdict, "policy");
1623 int has_index = qdict_haskey(qdict, "index");
1624 int index = qdict_get_try_int(qdict, "index", -1);
1625 qemu_acl *acl = find_acl(mon, aclname);
1629 if (strcmp(policy, "allow") == 0) {
1631 } else if (strcmp(policy, "deny") == 0) {
1634 monitor_printf(mon, "acl: unknown policy '%s', "
1635 "expected 'deny' or 'allow'\n", policy);
1639 ret = qemu_acl_insert(acl, deny, match, index);
1641 ret = qemu_acl_append(acl, deny, match);
1643 monitor_printf(mon, "acl: unable to add acl entry\n");
1645 monitor_printf(mon, "acl: added rule at position %d\n", ret);
1649 static void hmp_acl_remove(Monitor *mon, const QDict *qdict)
1651 const char *aclname = qdict_get_str(qdict, "aclname");
1652 const char *match = qdict_get_str(qdict, "match");
1653 qemu_acl *acl = find_acl(mon, aclname);
1657 ret = qemu_acl_remove(acl, match);
1659 monitor_printf(mon, "acl: no matching acl entry\n");
1661 monitor_printf(mon, "acl: removed rule at position %d\n", ret);
1665 void qmp_getfd(const char *fdname, Error **errp)
1670 fd = qemu_chr_fe_get_msgfd(cur_mon->chr);
1672 error_setg(errp, QERR_FD_NOT_SUPPLIED);
1676 if (qemu_isdigit(fdname[0])) {
1678 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "fdname",
1679 "a name not starting with a digit");
1683 QLIST_FOREACH(monfd, &cur_mon->fds, next) {
1684 if (strcmp(monfd->name, fdname) != 0) {
1693 monfd = g_malloc0(sizeof(mon_fd_t));
1694 monfd->name = g_strdup(fdname);
1697 QLIST_INSERT_HEAD(&cur_mon->fds, monfd, next);
1700 void qmp_closefd(const char *fdname, Error **errp)
1704 QLIST_FOREACH(monfd, &cur_mon->fds, next) {
1705 if (strcmp(monfd->name, fdname) != 0) {
1709 QLIST_REMOVE(monfd, next);
1711 g_free(monfd->name);
1716 error_setg(errp, QERR_FD_NOT_FOUND, fdname);
1719 static void hmp_loadvm(Monitor *mon, const QDict *qdict)
1721 int saved_vm_running = runstate_is_running();
1722 const char *name = qdict_get_str(qdict, "name");
1724 vm_stop(RUN_STATE_RESTORE_VM);
1726 if (load_vmstate(name) == 0 && saved_vm_running) {
1731 int monitor_get_fd(Monitor *mon, const char *fdname, Error **errp)
1735 QLIST_FOREACH(monfd, &mon->fds, next) {
1738 if (strcmp(monfd->name, fdname) != 0) {
1744 /* caller takes ownership of fd */
1745 QLIST_REMOVE(monfd, next);
1746 g_free(monfd->name);
1752 error_setg(errp, "File descriptor named '%s' has not been found", fdname);
1756 static void monitor_fdset_cleanup(MonFdset *mon_fdset)
1758 MonFdsetFd *mon_fdset_fd;
1759 MonFdsetFd *mon_fdset_fd_next;
1761 QLIST_FOREACH_SAFE(mon_fdset_fd, &mon_fdset->fds, next, mon_fdset_fd_next) {
1762 if ((mon_fdset_fd->removed ||
1763 (QLIST_EMPTY(&mon_fdset->dup_fds) && mon_refcount == 0)) &&
1764 runstate_is_running()) {
1765 close(mon_fdset_fd->fd);
1766 g_free(mon_fdset_fd->opaque);
1767 QLIST_REMOVE(mon_fdset_fd, next);
1768 g_free(mon_fdset_fd);
1772 if (QLIST_EMPTY(&mon_fdset->fds) && QLIST_EMPTY(&mon_fdset->dup_fds)) {
1773 QLIST_REMOVE(mon_fdset, next);
1778 static void monitor_fdsets_cleanup(void)
1780 MonFdset *mon_fdset;
1781 MonFdset *mon_fdset_next;
1783 QLIST_FOREACH_SAFE(mon_fdset, &mon_fdsets, next, mon_fdset_next) {
1784 monitor_fdset_cleanup(mon_fdset);
1788 AddfdInfo *qmp_add_fd(bool has_fdset_id, int64_t fdset_id, bool has_opaque,
1789 const char *opaque, Error **errp)
1792 Monitor *mon = cur_mon;
1795 fd = qemu_chr_fe_get_msgfd(mon->chr);
1797 error_setg(errp, QERR_FD_NOT_SUPPLIED);
1801 fdinfo = monitor_fdset_add_fd(fd, has_fdset_id, fdset_id,
1802 has_opaque, opaque, errp);
1814 void qmp_remove_fd(int64_t fdset_id, bool has_fd, int64_t fd, Error **errp)
1816 MonFdset *mon_fdset;
1817 MonFdsetFd *mon_fdset_fd;
1820 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
1821 if (mon_fdset->id != fdset_id) {
1824 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
1826 if (mon_fdset_fd->fd != fd) {
1829 mon_fdset_fd->removed = true;
1832 mon_fdset_fd->removed = true;
1835 if (has_fd && !mon_fdset_fd) {
1838 monitor_fdset_cleanup(mon_fdset);
1844 snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64 ", fd:%" PRId64,
1847 snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64, fdset_id);
1849 error_setg(errp, QERR_FD_NOT_FOUND, fd_str);
1852 FdsetInfoList *qmp_query_fdsets(Error **errp)
1854 MonFdset *mon_fdset;
1855 MonFdsetFd *mon_fdset_fd;
1856 FdsetInfoList *fdset_list = NULL;
1858 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
1859 FdsetInfoList *fdset_info = g_malloc0(sizeof(*fdset_info));
1860 FdsetFdInfoList *fdsetfd_list = NULL;
1862 fdset_info->value = g_malloc0(sizeof(*fdset_info->value));
1863 fdset_info->value->fdset_id = mon_fdset->id;
1865 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
1866 FdsetFdInfoList *fdsetfd_info;
1868 fdsetfd_info = g_malloc0(sizeof(*fdsetfd_info));
1869 fdsetfd_info->value = g_malloc0(sizeof(*fdsetfd_info->value));
1870 fdsetfd_info->value->fd = mon_fdset_fd->fd;
1871 if (mon_fdset_fd->opaque) {
1872 fdsetfd_info->value->has_opaque = true;
1873 fdsetfd_info->value->opaque = g_strdup(mon_fdset_fd->opaque);
1875 fdsetfd_info->value->has_opaque = false;
1878 fdsetfd_info->next = fdsetfd_list;
1879 fdsetfd_list = fdsetfd_info;
1882 fdset_info->value->fds = fdsetfd_list;
1884 fdset_info->next = fdset_list;
1885 fdset_list = fdset_info;
1891 AddfdInfo *monitor_fdset_add_fd(int fd, bool has_fdset_id, int64_t fdset_id,
1892 bool has_opaque, const char *opaque,
1895 MonFdset *mon_fdset = NULL;
1896 MonFdsetFd *mon_fdset_fd;
1900 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
1901 /* Break if match found or match impossible due to ordering by ID */
1902 if (fdset_id <= mon_fdset->id) {
1903 if (fdset_id < mon_fdset->id) {
1911 if (mon_fdset == NULL) {
1912 int64_t fdset_id_prev = -1;
1913 MonFdset *mon_fdset_cur = QLIST_FIRST(&mon_fdsets);
1917 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "fdset-id",
1918 "a non-negative value");
1921 /* Use specified fdset ID */
1922 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
1923 mon_fdset_cur = mon_fdset;
1924 if (fdset_id < mon_fdset_cur->id) {
1929 /* Use first available fdset ID */
1930 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
1931 mon_fdset_cur = mon_fdset;
1932 if (fdset_id_prev == mon_fdset_cur->id - 1) {
1933 fdset_id_prev = mon_fdset_cur->id;
1940 mon_fdset = g_malloc0(sizeof(*mon_fdset));
1942 mon_fdset->id = fdset_id;
1944 mon_fdset->id = fdset_id_prev + 1;
1947 /* The fdset list is ordered by fdset ID */
1948 if (!mon_fdset_cur) {
1949 QLIST_INSERT_HEAD(&mon_fdsets, mon_fdset, next);
1950 } else if (mon_fdset->id < mon_fdset_cur->id) {
1951 QLIST_INSERT_BEFORE(mon_fdset_cur, mon_fdset, next);
1953 QLIST_INSERT_AFTER(mon_fdset_cur, mon_fdset, next);
1957 mon_fdset_fd = g_malloc0(sizeof(*mon_fdset_fd));
1958 mon_fdset_fd->fd = fd;
1959 mon_fdset_fd->removed = false;
1961 mon_fdset_fd->opaque = g_strdup(opaque);
1963 QLIST_INSERT_HEAD(&mon_fdset->fds, mon_fdset_fd, next);
1965 fdinfo = g_malloc0(sizeof(*fdinfo));
1966 fdinfo->fdset_id = mon_fdset->id;
1967 fdinfo->fd = mon_fdset_fd->fd;
1972 int monitor_fdset_get_fd(int64_t fdset_id, int flags)
1975 MonFdset *mon_fdset;
1976 MonFdsetFd *mon_fdset_fd;
1979 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
1980 if (mon_fdset->id != fdset_id) {
1983 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
1984 mon_fd_flags = fcntl(mon_fdset_fd->fd, F_GETFL);
1985 if (mon_fd_flags == -1) {
1989 if ((flags & O_ACCMODE) == (mon_fd_flags & O_ACCMODE)) {
1990 return mon_fdset_fd->fd;
2002 int monitor_fdset_dup_fd_add(int64_t fdset_id, int dup_fd)
2004 MonFdset *mon_fdset;
2005 MonFdsetFd *mon_fdset_fd_dup;
2007 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2008 if (mon_fdset->id != fdset_id) {
2011 QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
2012 if (mon_fdset_fd_dup->fd == dup_fd) {
2016 mon_fdset_fd_dup = g_malloc0(sizeof(*mon_fdset_fd_dup));
2017 mon_fdset_fd_dup->fd = dup_fd;
2018 QLIST_INSERT_HEAD(&mon_fdset->dup_fds, mon_fdset_fd_dup, next);
2024 static int monitor_fdset_dup_fd_find_remove(int dup_fd, bool remove)
2026 MonFdset *mon_fdset;
2027 MonFdsetFd *mon_fdset_fd_dup;
2029 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2030 QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
2031 if (mon_fdset_fd_dup->fd == dup_fd) {
2033 QLIST_REMOVE(mon_fdset_fd_dup, next);
2034 if (QLIST_EMPTY(&mon_fdset->dup_fds)) {
2035 monitor_fdset_cleanup(mon_fdset);
2039 return mon_fdset->id;
2047 int monitor_fdset_dup_fd_find(int dup_fd)
2049 return monitor_fdset_dup_fd_find_remove(dup_fd, false);
2052 void monitor_fdset_dup_fd_remove(int dup_fd)
2054 monitor_fdset_dup_fd_find_remove(dup_fd, true);
2057 int monitor_fd_param(Monitor *mon, const char *fdname, Error **errp)
2060 Error *local_err = NULL;
2062 if (!qemu_isdigit(fdname[0]) && mon) {
2063 fd = monitor_get_fd(mon, fdname, &local_err);
2065 fd = qemu_parse_fd(fdname);
2067 error_setg(&local_err, "Invalid file descriptor number '%s'",
2072 error_propagate(errp, local_err);
2081 /* Please update hmp-commands.hx when adding or changing commands */
2082 static mon_cmd_t info_cmds[] = {
2083 #include "hmp-commands-info.h"
2087 /* mon_cmds and info_cmds would be sorted at runtime */
2088 static mon_cmd_t mon_cmds[] = {
2089 #include "hmp-commands.h"
2093 static const mon_cmd_t qmp_cmds[] = {
2094 #include "qmp-commands-old.h"
2098 /*******************************************************************/
2100 static const char *pch;
2101 static sigjmp_buf expr_env;
2104 static void GCC_FMT_ATTR(2, 3) QEMU_NORETURN
2105 expr_error(Monitor *mon, const char *fmt, ...)
2109 monitor_vprintf(mon, fmt, ap);
2110 monitor_printf(mon, "\n");
2112 siglongjmp(expr_env, 1);
2115 /* return 0 if OK, -1 if not found */
2116 static int get_monitor_def(target_long *pval, const char *name)
2118 const MonitorDef *md = target_monitor_defs();
2125 for(; md->name != NULL; md++) {
2126 if (compare_cmd(name, md->name)) {
2127 if (md->get_value) {
2128 *pval = md->get_value(md, md->offset);
2130 CPUArchState *env = mon_get_cpu_env();
2131 ptr = (uint8_t *)env + md->offset;
2134 *pval = *(int32_t *)ptr;
2137 *pval = *(target_long *)ptr;
2150 static void next(void)
2154 while (qemu_isspace(*pch))
2159 static int64_t expr_sum(Monitor *mon);
2161 static int64_t expr_unary(Monitor *mon)
2170 n = expr_unary(mon);
2174 n = -expr_unary(mon);
2178 n = ~expr_unary(mon);
2184 expr_error(mon, "')' expected");
2191 expr_error(mon, "character constant expected");
2195 expr_error(mon, "missing terminating \' character");
2205 while ((*pch >= 'a' && *pch <= 'z') ||
2206 (*pch >= 'A' && *pch <= 'Z') ||
2207 (*pch >= '0' && *pch <= '9') ||
2208 *pch == '_' || *pch == '.') {
2209 if ((q - buf) < sizeof(buf) - 1)
2213 while (qemu_isspace(*pch))
2216 ret = get_monitor_def(®, buf);
2218 expr_error(mon, "unknown register");
2223 expr_error(mon, "unexpected end of expression");
2228 n = strtoull(pch, &p, 0);
2229 if (errno == ERANGE) {
2230 expr_error(mon, "number too large");
2233 expr_error(mon, "invalid char '%c' in expression", *p);
2236 while (qemu_isspace(*pch))
2244 static int64_t expr_prod(Monitor *mon)
2249 val = expr_unary(mon);
2252 if (op != '*' && op != '/' && op != '%')
2255 val2 = expr_unary(mon);
2264 expr_error(mon, "division by zero");
2275 static int64_t expr_logic(Monitor *mon)
2280 val = expr_prod(mon);
2283 if (op != '&' && op != '|' && op != '^')
2286 val2 = expr_prod(mon);
2303 static int64_t expr_sum(Monitor *mon)
2308 val = expr_logic(mon);
2311 if (op != '+' && op != '-')
2314 val2 = expr_logic(mon);
2323 static int get_expr(Monitor *mon, int64_t *pval, const char **pp)
2326 if (sigsetjmp(expr_env, 0)) {
2330 while (qemu_isspace(*pch))
2332 *pval = expr_sum(mon);
2337 static int get_double(Monitor *mon, double *pval, const char **pp)
2339 const char *p = *pp;
2343 d = strtod(p, &tailp);
2345 monitor_printf(mon, "Number expected\n");
2348 if (d != d || d - d != 0) {
2349 /* NaN or infinity */
2350 monitor_printf(mon, "Bad number\n");
2359 * Store the command-name in cmdname, and return a pointer to
2360 * the remaining of the command string.
2362 static const char *get_command_name(const char *cmdline,
2363 char *cmdname, size_t nlen)
2366 const char *p, *pstart;
2369 while (qemu_isspace(*p))
2374 while (*p != '\0' && *p != '/' && !qemu_isspace(*p))
2379 memcpy(cmdname, pstart, len);
2380 cmdname[len] = '\0';
2385 * Read key of 'type' into 'key' and return the current
2388 static char *key_get_info(const char *type, char **key)
2396 p = strchr(type, ':');
2403 str = g_malloc(len + 1);
2404 memcpy(str, type, len);
2411 static int default_fmt_format = 'x';
2412 static int default_fmt_size = 4;
2414 static int is_valid_option(const char *c, const char *typestr)
2422 typestr = strstr(typestr, option);
2423 return (typestr != NULL);
2426 static const mon_cmd_t *search_dispatch_table(const mon_cmd_t *disp_table,
2427 const char *cmdname)
2429 const mon_cmd_t *cmd;
2431 for (cmd = disp_table; cmd->name != NULL; cmd++) {
2432 if (compare_cmd(cmdname, cmd->name)) {
2440 static const mon_cmd_t *qmp_find_cmd(const char *cmdname)
2442 return search_dispatch_table(qmp_cmds, cmdname);
2446 * Parse command name from @cmdp according to command table @table.
2447 * If blank, return NULL.
2448 * Else, if no valid command can be found, report to @mon, and return
2450 * Else, change @cmdp to point right behind the name, and return its
2451 * command table entry.
2452 * Do not assume the return value points into @table! It doesn't when
2453 * the command is found in a sub-command table.
2455 static const mon_cmd_t *monitor_parse_command(Monitor *mon,
2460 const mon_cmd_t *cmd;
2463 /* extract the command name */
2464 p = get_command_name(*cmdp, cmdname, sizeof(cmdname));
2468 cmd = search_dispatch_table(table, cmdname);
2470 monitor_printf(mon, "unknown command: '%.*s'\n",
2471 (int)(p - *cmdp), *cmdp);
2475 /* filter out following useless space */
2476 while (qemu_isspace(*p)) {
2481 /* search sub command */
2482 if (cmd->sub_table != NULL && *p != '\0') {
2483 return monitor_parse_command(mon, cmdp, cmd->sub_table);
2490 * Parse arguments for @cmd.
2491 * If it can't be parsed, report to @mon, and return NULL.
2492 * Else, insert command arguments into a QDict, and return it.
2493 * Note: On success, caller has to free the QDict structure.
2496 static QDict *monitor_parse_arguments(Monitor *mon,
2498 const mon_cmd_t *cmd)
2500 const char *typestr;
2503 const char *p = *endp;
2505 QDict *qdict = qdict_new();
2507 /* parse the parameters */
2508 typestr = cmd->args_type;
2510 typestr = key_get_info(typestr, &key);
2522 while (qemu_isspace(*p))
2524 if (*typestr == '?') {
2527 /* no optional string: NULL argument */
2531 ret = get_str(buf, sizeof(buf), &p);
2535 monitor_printf(mon, "%s: filename expected\n",
2539 monitor_printf(mon, "%s: block device name expected\n",
2543 monitor_printf(mon, "%s: string expected\n", cmd->name);
2548 qdict_put(qdict, key, qstring_from_str(buf));
2553 QemuOptsList *opts_list;
2556 opts_list = qemu_find_opts(key);
2557 if (!opts_list || opts_list->desc->name) {
2560 while (qemu_isspace(*p)) {
2565 if (get_str(buf, sizeof(buf), &p) < 0) {
2568 opts = qemu_opts_parse_noisily(opts_list, buf, true);
2572 qemu_opts_to_qdict(opts, qdict);
2573 qemu_opts_del(opts);
2578 int count, format, size;
2580 while (qemu_isspace(*p))
2586 if (qemu_isdigit(*p)) {
2588 while (qemu_isdigit(*p)) {
2589 count = count * 10 + (*p - '0');
2627 if (*p != '\0' && !qemu_isspace(*p)) {
2628 monitor_printf(mon, "invalid char in format: '%c'\n",
2633 format = default_fmt_format;
2634 if (format != 'i') {
2635 /* for 'i', not specifying a size gives -1 as size */
2637 size = default_fmt_size;
2638 default_fmt_size = size;
2640 default_fmt_format = format;
2643 format = default_fmt_format;
2644 if (format != 'i') {
2645 size = default_fmt_size;
2650 qdict_put(qdict, "count", qint_from_int(count));
2651 qdict_put(qdict, "format", qint_from_int(format));
2652 qdict_put(qdict, "size", qint_from_int(size));
2661 while (qemu_isspace(*p))
2663 if (*typestr == '?' || *typestr == '.') {
2664 if (*typestr == '?') {
2672 while (qemu_isspace(*p))
2681 if (get_expr(mon, &val, &p))
2683 /* Check if 'i' is greater than 32-bit */
2684 if ((c == 'i') && ((val >> 32) & 0xffffffff)) {
2685 monitor_printf(mon, "\'%s\' has failed: ", cmd->name);
2686 monitor_printf(mon, "integer is for 32-bit values\n");
2688 } else if (c == 'M') {
2690 monitor_printf(mon, "enter a positive value\n");
2695 qdict_put(qdict, key, qint_from_int(val));
2703 while (qemu_isspace(*p)) {
2706 if (*typestr == '?') {
2712 val = qemu_strtosz(p, &end);
2714 monitor_printf(mon, "invalid size\n");
2717 qdict_put(qdict, key, qint_from_int(val));
2725 while (qemu_isspace(*p))
2727 if (*typestr == '?') {
2733 if (get_double(mon, &val, &p) < 0) {
2736 if (p[0] && p[1] == 's') {
2739 val /= 1e3; p += 2; break;
2741 val /= 1e6; p += 2; break;
2743 val /= 1e9; p += 2; break;
2746 if (*p && !qemu_isspace(*p)) {
2747 monitor_printf(mon, "Unknown unit suffix\n");
2750 qdict_put(qdict, key, qfloat_from_double(val));
2758 while (qemu_isspace(*p)) {
2762 while (qemu_isgraph(*p)) {
2765 if (p - beg == 2 && !memcmp(beg, "on", p - beg)) {
2767 } else if (p - beg == 3 && !memcmp(beg, "off", p - beg)) {
2770 monitor_printf(mon, "Expected 'on' or 'off'\n");
2773 qdict_put(qdict, key, qbool_from_bool(val));
2778 const char *tmp = p;
2785 while (qemu_isspace(*p))
2790 if(!is_valid_option(p, typestr)) {
2792 monitor_printf(mon, "%s: unsupported option -%c\n",
2804 qdict_put(qdict, key, qbool_from_bool(true));
2811 /* package all remaining string */
2814 while (qemu_isspace(*p)) {
2817 if (*typestr == '?') {
2820 /* no remaining string: NULL argument */
2826 monitor_printf(mon, "%s: string expected\n",
2830 qdict_put(qdict, key, qstring_from_str(p));
2836 monitor_printf(mon, "%s: unknown type '%c'\n", cmd->name, c);
2842 /* check that all arguments were parsed */
2843 while (qemu_isspace(*p))
2846 monitor_printf(mon, "%s: extraneous characters at the end of line\n",
2859 static void handle_hmp_command(Monitor *mon, const char *cmdline)
2862 const mon_cmd_t *cmd;
2864 cmd = monitor_parse_command(mon, &cmdline, mon->cmd_table);
2869 qdict = monitor_parse_arguments(mon, &cmdline, cmd);
2871 monitor_printf(mon, "Try \"help %s\" for more information\n",
2876 cmd->mhandler.cmd(mon, qdict);
2880 static void cmd_completion(Monitor *mon, const char *name, const char *list)
2882 const char *p, *pstart;
2891 p = pstart + strlen(pstart);
2893 if (len > sizeof(cmd) - 2)
2894 len = sizeof(cmd) - 2;
2895 memcpy(cmd, pstart, len);
2897 if (name[0] == '\0' || !strncmp(name, cmd, strlen(name))) {
2898 readline_add_completion(mon->rs, cmd);
2906 static void file_completion(Monitor *mon, const char *input)
2911 char file[1024], file_prefix[1024];
2915 p = strrchr(input, '/');
2918 pstrcpy(file_prefix, sizeof(file_prefix), input);
2919 pstrcpy(path, sizeof(path), ".");
2921 input_path_len = p - input + 1;
2922 memcpy(path, input, input_path_len);
2923 if (input_path_len > sizeof(path) - 1)
2924 input_path_len = sizeof(path) - 1;
2925 path[input_path_len] = '\0';
2926 pstrcpy(file_prefix, sizeof(file_prefix), p + 1);
2929 ffs = opendir(path);
2938 if (strcmp(d->d_name, ".") == 0 || strcmp(d->d_name, "..") == 0) {
2942 if (strstart(d->d_name, file_prefix, NULL)) {
2943 memcpy(file, input, input_path_len);
2944 if (input_path_len < sizeof(file))
2945 pstrcpy(file + input_path_len, sizeof(file) - input_path_len,
2947 /* stat the file to find out if it's a directory.
2948 * In that case add a slash to speed up typing long paths
2950 if (stat(file, &sb) == 0 && S_ISDIR(sb.st_mode)) {
2951 pstrcat(file, sizeof(file), "/");
2953 readline_add_completion(mon->rs, file);
2959 static const char *next_arg_type(const char *typestr)
2961 const char *p = strchr(typestr, ':');
2962 return (p != NULL ? ++p : typestr);
2965 static void add_completion_option(ReadLineState *rs, const char *str,
2968 if (!str || !option) {
2971 if (!strncmp(option, str, strlen(str))) {
2972 readline_add_completion(rs, option);
2976 void chardev_add_completion(ReadLineState *rs, int nb_args, const char *str)
2979 ChardevBackendInfoList *list, *start;
2985 readline_set_completion_index(rs, len);
2987 start = list = qmp_query_chardev_backends(NULL);
2989 const char *chr_name = list->value->name;
2991 if (!strncmp(chr_name, str, len)) {
2992 readline_add_completion(rs, chr_name);
2996 qapi_free_ChardevBackendInfoList(start);
2999 void netdev_add_completion(ReadLineState *rs, int nb_args, const char *str)
3008 readline_set_completion_index(rs, len);
3009 for (i = 0; NetClientOptionsKind_lookup[i]; i++) {
3010 add_completion_option(rs, str, NetClientOptionsKind_lookup[i]);
3014 void device_add_completion(ReadLineState *rs, int nb_args, const char *str)
3024 readline_set_completion_index(rs, len);
3025 list = elt = object_class_get_list(TYPE_DEVICE, false);
3028 DeviceClass *dc = OBJECT_CLASS_CHECK(DeviceClass, elt->data,
3030 name = object_class_get_name(OBJECT_CLASS(dc));
3032 if (!dc->cannot_instantiate_with_device_add_yet
3033 && !strncmp(name, str, len)) {
3034 readline_add_completion(rs, name);
3041 void object_add_completion(ReadLineState *rs, int nb_args, const char *str)
3051 readline_set_completion_index(rs, len);
3052 list = elt = object_class_get_list(TYPE_USER_CREATABLE, false);
3056 name = object_class_get_name(OBJECT_CLASS(elt->data));
3057 if (!strncmp(name, str, len) && strcmp(name, TYPE_USER_CREATABLE)) {
3058 readline_add_completion(rs, name);
3065 static void peripheral_device_del_completion(ReadLineState *rs,
3066 const char *str, size_t len)
3068 Object *peripheral = container_get(qdev_get_machine(), "/peripheral");
3069 GSList *list, *item;
3071 list = qdev_build_hotpluggable_device_list(peripheral);
3076 for (item = list; item; item = g_slist_next(item)) {
3077 DeviceState *dev = item->data;
3079 if (dev->id && !strncmp(str, dev->id, len)) {
3080 readline_add_completion(rs, dev->id);
3087 void chardev_remove_completion(ReadLineState *rs, int nb_args, const char *str)
3090 ChardevInfoList *list, *start;
3096 readline_set_completion_index(rs, len);
3098 start = list = qmp_query_chardev(NULL);
3100 ChardevInfo *chr = list->value;
3102 if (!strncmp(chr->label, str, len)) {
3103 readline_add_completion(rs, chr->label);
3107 qapi_free_ChardevInfoList(start);
3110 static void ringbuf_completion(ReadLineState *rs, const char *str)
3113 ChardevInfoList *list, *start;
3116 readline_set_completion_index(rs, len);
3118 start = list = qmp_query_chardev(NULL);
3120 ChardevInfo *chr_info = list->value;
3122 if (!strncmp(chr_info->label, str, len)) {
3123 CharDriverState *chr = qemu_chr_find(chr_info->label);
3124 if (chr && chr_is_ringbuf(chr)) {
3125 readline_add_completion(rs, chr_info->label);
3130 qapi_free_ChardevInfoList(start);
3133 void ringbuf_write_completion(ReadLineState *rs, int nb_args, const char *str)
3138 ringbuf_completion(rs, str);
3141 void device_del_completion(ReadLineState *rs, int nb_args, const char *str)
3150 readline_set_completion_index(rs, len);
3151 peripheral_device_del_completion(rs, str, len);
3154 void object_del_completion(ReadLineState *rs, int nb_args, const char *str)
3156 ObjectPropertyInfoList *list, *start;
3163 readline_set_completion_index(rs, len);
3165 start = list = qmp_qom_list("/objects", NULL);
3167 ObjectPropertyInfo *info = list->value;
3169 if (!strncmp(info->type, "child<", 5)
3170 && !strncmp(info->name, str, len)) {
3171 readline_add_completion(rs, info->name);
3175 qapi_free_ObjectPropertyInfoList(start);
3178 void sendkey_completion(ReadLineState *rs, int nb_args, const char *str)
3187 sep = strrchr(str, '-');
3192 readline_set_completion_index(rs, len);
3193 for (i = 0; i < Q_KEY_CODE_MAX; i++) {
3194 if (!strncmp(str, QKeyCode_lookup[i], len)) {
3195 readline_add_completion(rs, QKeyCode_lookup[i]);
3200 void set_link_completion(ReadLineState *rs, int nb_args, const char *str)
3205 readline_set_completion_index(rs, len);
3207 NetClientState *ncs[MAX_QUEUE_NUM];
3209 count = qemu_find_net_clients_except(NULL, ncs,
3210 NET_CLIENT_OPTIONS_KIND_NONE,
3212 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3213 const char *name = ncs[i]->name;
3214 if (!strncmp(str, name, len)) {
3215 readline_add_completion(rs, name);
3218 } else if (nb_args == 3) {
3219 add_completion_option(rs, str, "on");
3220 add_completion_option(rs, str, "off");
3224 void netdev_del_completion(ReadLineState *rs, int nb_args, const char *str)
3227 NetClientState *ncs[MAX_QUEUE_NUM];
3234 readline_set_completion_index(rs, len);
3235 count = qemu_find_net_clients_except(NULL, ncs, NET_CLIENT_OPTIONS_KIND_NIC,
3237 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3239 const char *name = ncs[i]->name;
3240 if (strncmp(str, name, len)) {
3243 opts = qemu_opts_find(qemu_find_opts_err("netdev", NULL), name);
3245 readline_add_completion(rs, name);
3250 void trace_event_completion(ReadLineState *rs, int nb_args, const char *str)
3255 readline_set_completion_index(rs, len);
3258 for (id = 0; id < trace_event_count(); id++) {
3259 const char *event_name = trace_event_get_name(trace_event_id(id));
3260 if (!strncmp(str, event_name, len)) {
3261 readline_add_completion(rs, event_name);
3264 } else if (nb_args == 3) {
3265 add_completion_option(rs, str, "on");
3266 add_completion_option(rs, str, "off");
3270 void watchdog_action_completion(ReadLineState *rs, int nb_args, const char *str)
3277 readline_set_completion_index(rs, strlen(str));
3278 for (i = 0; WatchdogExpirationAction_lookup[i]; i++) {
3279 add_completion_option(rs, str, WatchdogExpirationAction_lookup[i]);
3283 void migrate_set_capability_completion(ReadLineState *rs, int nb_args,
3289 readline_set_completion_index(rs, len);
3292 for (i = 0; i < MIGRATION_CAPABILITY_MAX; i++) {
3293 const char *name = MigrationCapability_lookup[i];
3294 if (!strncmp(str, name, len)) {
3295 readline_add_completion(rs, name);
3298 } else if (nb_args == 3) {
3299 add_completion_option(rs, str, "on");
3300 add_completion_option(rs, str, "off");
3304 void migrate_set_parameter_completion(ReadLineState *rs, int nb_args,
3310 readline_set_completion_index(rs, len);
3313 for (i = 0; i < MIGRATION_PARAMETER_MAX; i++) {
3314 const char *name = MigrationParameter_lookup[i];
3315 if (!strncmp(str, name, len)) {
3316 readline_add_completion(rs, name);
3322 void host_net_add_completion(ReadLineState *rs, int nb_args, const char *str)
3330 readline_set_completion_index(rs, len);
3331 for (i = 0; host_net_devices[i]; i++) {
3332 if (!strncmp(host_net_devices[i], str, len)) {
3333 readline_add_completion(rs, host_net_devices[i]);
3338 void host_net_remove_completion(ReadLineState *rs, int nb_args, const char *str)
3340 NetClientState *ncs[MAX_QUEUE_NUM];
3344 readline_set_completion_index(rs, len);
3346 count = qemu_find_net_clients_except(NULL, ncs,
3347 NET_CLIENT_OPTIONS_KIND_NONE,
3349 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3353 if (net_hub_id_for_client(ncs[i], &id)) {
3356 snprintf(name, sizeof(name), "%d", id);
3357 if (!strncmp(str, name, len)) {
3358 readline_add_completion(rs, name);
3362 } else if (nb_args == 3) {
3363 count = qemu_find_net_clients_except(NULL, ncs,
3364 NET_CLIENT_OPTIONS_KIND_NIC,
3366 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3370 if (ncs[i]->info->type == NET_CLIENT_OPTIONS_KIND_HUBPORT ||
3371 net_hub_id_for_client(ncs[i], &id)) {
3374 name = ncs[i]->name;
3375 if (!strncmp(str, name, len)) {
3376 readline_add_completion(rs, name);
3383 static void vm_completion(ReadLineState *rs, const char *str)
3386 BlockDriverState *bs = NULL;
3389 readline_set_completion_index(rs, len);
3390 while ((bs = bdrv_next(bs))) {
3391 SnapshotInfoList *snapshots, *snapshot;
3393 if (!bdrv_can_snapshot(bs)) {
3396 if (bdrv_query_snapshot_info_list(bs, &snapshots, NULL)) {
3399 snapshot = snapshots;
3401 char *completion = snapshot->value->name;
3402 if (!strncmp(str, completion, len)) {
3403 readline_add_completion(rs, completion);
3405 completion = snapshot->value->id;
3406 if (!strncmp(str, completion, len)) {
3407 readline_add_completion(rs, completion);
3409 snapshot = snapshot->next;
3411 qapi_free_SnapshotInfoList(snapshots);
3416 void delvm_completion(ReadLineState *rs, int nb_args, const char *str)
3419 vm_completion(rs, str);
3423 void loadvm_completion(ReadLineState *rs, int nb_args, const char *str)
3426 vm_completion(rs, str);
3430 static void monitor_find_completion_by_table(Monitor *mon,
3431 const mon_cmd_t *cmd_table,
3435 const char *cmdname;
3437 const char *ptype, *str, *name;
3438 const mon_cmd_t *cmd;
3439 BlockDriverState *bs;
3442 /* command completion */
3447 readline_set_completion_index(mon->rs, strlen(cmdname));
3448 for (cmd = cmd_table; cmd->name != NULL; cmd++) {
3449 cmd_completion(mon, cmdname, cmd->name);
3452 /* find the command */
3453 for (cmd = cmd_table; cmd->name != NULL; cmd++) {
3454 if (compare_cmd(args[0], cmd->name)) {
3462 if (cmd->sub_table) {
3463 /* do the job again */
3464 monitor_find_completion_by_table(mon, cmd->sub_table,
3465 &args[1], nb_args - 1);
3468 if (cmd->command_completion) {
3469 cmd->command_completion(mon->rs, nb_args, args[nb_args - 1]);
3473 ptype = next_arg_type(cmd->args_type);
3474 for(i = 0; i < nb_args - 2; i++) {
3475 if (*ptype != '\0') {
3476 ptype = next_arg_type(ptype);
3477 while (*ptype == '?')
3478 ptype = next_arg_type(ptype);
3481 str = args[nb_args - 1];
3482 while (*ptype == '-' && ptype[1] != '\0') {
3483 ptype = next_arg_type(ptype);
3487 /* file completion */
3488 readline_set_completion_index(mon->rs, strlen(str));
3489 file_completion(mon, str);
3492 /* block device name completion */
3493 readline_set_completion_index(mon->rs, strlen(str));
3494 for (bs = bdrv_next(NULL); bs; bs = bdrv_next(bs)) {
3495 name = bdrv_get_device_name(bs);
3496 if (str[0] == '\0' ||
3497 !strncmp(name, str, strlen(str))) {
3498 readline_add_completion(mon->rs, name);
3504 if (!strcmp(cmd->name, "help|?")) {
3505 monitor_find_completion_by_table(mon, cmd_table,
3506 &args[1], nb_args - 1);
3515 static void monitor_find_completion(void *opaque,
3516 const char *cmdline)
3518 Monitor *mon = opaque;
3519 char *args[MAX_ARGS];
3522 /* 1. parse the cmdline */
3523 if (parse_cmdline(cmdline, &nb_args, args) < 0) {
3527 /* if the line ends with a space, it means we want to complete the
3529 len = strlen(cmdline);
3530 if (len > 0 && qemu_isspace(cmdline[len - 1])) {
3531 if (nb_args >= MAX_ARGS) {
3534 args[nb_args++] = g_strdup("");
3537 /* 2. auto complete according to args */
3538 monitor_find_completion_by_table(mon, mon->cmd_table, args, nb_args);
3541 free_cmdline_args(args, nb_args);
3544 static int monitor_can_read(void *opaque)
3546 Monitor *mon = opaque;
3548 return (mon->suspend_cnt == 0) ? 1 : 0;
3551 static bool invalid_qmp_mode(const Monitor *mon, const mon_cmd_t *cmd,
3554 bool is_cap = cmd->mhandler.cmd_new == qmp_capabilities;
3556 if (is_cap && mon->qmp.in_command_mode) {
3557 error_set(errp, ERROR_CLASS_COMMAND_NOT_FOUND,
3558 "Capabilities negotiation is already complete, command "
3559 "'%s' ignored", cmd->name);
3562 if (!is_cap && !mon->qmp.in_command_mode) {
3563 error_set(errp, ERROR_CLASS_COMMAND_NOT_FOUND,
3564 "Expecting capabilities negotiation with "
3565 "'qmp_capabilities' before command '%s'", cmd->name);
3572 * Argument validation rules:
3574 * 1. The argument must exist in cmd_args qdict
3575 * 2. The argument type must be the expected one
3577 * Special case: If the argument doesn't exist in cmd_args and
3578 * the QMP_ACCEPT_UNKNOWNS flag is set, then the
3579 * checking is skipped for it.
3581 static void check_client_args_type(const QDict *client_args,
3582 const QDict *cmd_args, int flags,
3585 const QDictEntry *ent;
3587 for (ent = qdict_first(client_args); ent;ent = qdict_next(client_args,ent)){
3590 const QObject *client_arg = qdict_entry_value(ent);
3591 const char *client_arg_name = qdict_entry_key(ent);
3593 obj = qdict_get(cmd_args, client_arg_name);
3595 if (flags & QMP_ACCEPT_UNKNOWNS) {
3596 /* handler accepts unknowns */
3599 /* client arg doesn't exist */
3600 error_setg(errp, QERR_INVALID_PARAMETER, client_arg_name);
3604 arg_type = qobject_to_qstring(obj);
3605 assert(arg_type != NULL);
3607 /* check if argument's type is correct */
3608 switch (qstring_get_str(arg_type)[0]) {
3612 if (qobject_type(client_arg) != QTYPE_QSTRING) {
3613 error_setg(errp, QERR_INVALID_PARAMETER_TYPE,
3614 client_arg_name, "string");
3622 if (qobject_type(client_arg) != QTYPE_QINT) {
3623 error_setg(errp, QERR_INVALID_PARAMETER_TYPE,
3624 client_arg_name, "int");
3629 if (qobject_type(client_arg) != QTYPE_QINT &&
3630 qobject_type(client_arg) != QTYPE_QFLOAT) {
3631 error_setg(errp, QERR_INVALID_PARAMETER_TYPE,
3632 client_arg_name, "number");
3638 if (qobject_type(client_arg) != QTYPE_QBOOL) {
3639 error_setg(errp, QERR_INVALID_PARAMETER_TYPE,
3640 client_arg_name, "bool");
3645 assert(flags & QMP_ACCEPT_UNKNOWNS);
3648 /* Any QObject can be passed. */
3653 * These types are not supported by QMP and thus are not
3654 * handled here. Fall through.
3663 * - Check if the client has passed all mandatory args
3664 * - Set special flags for argument validation
3666 static void check_mandatory_args(const QDict *cmd_args,
3667 const QDict *client_args, int *flags,
3670 const QDictEntry *ent;
3672 for (ent = qdict_first(cmd_args); ent; ent = qdict_next(cmd_args, ent)) {
3673 const char *cmd_arg_name = qdict_entry_key(ent);
3674 QString *type = qobject_to_qstring(qdict_entry_value(ent));
3675 assert(type != NULL);
3677 if (qstring_get_str(type)[0] == 'O') {
3678 assert((*flags & QMP_ACCEPT_UNKNOWNS) == 0);
3679 *flags |= QMP_ACCEPT_UNKNOWNS;
3680 } else if (qstring_get_str(type)[0] != '-' &&
3681 qstring_get_str(type)[1] != '?' &&
3682 !qdict_haskey(client_args, cmd_arg_name)) {
3683 error_setg(errp, QERR_MISSING_PARAMETER, cmd_arg_name);
3689 static QDict *qdict_from_args_type(const char *args_type)
3693 QString *key, *type, *cur_qs;
3695 assert(args_type != NULL);
3697 qdict = qdict_new();
3699 if (args_type == NULL || args_type[0] == '\0') {
3700 /* no args, empty qdict */
3704 key = qstring_new();
3705 type = qstring_new();
3710 switch (args_type[i]) {
3713 qdict_put(qdict, qstring_get_str(key), type);
3715 if (args_type[i] == '\0') {
3718 type = qstring_new(); /* qdict has ref */
3719 cur_qs = key = qstring_new();
3725 qstring_append_chr(cur_qs, args_type[i]);
3735 * Client argument checking rules:
3737 * 1. Client must provide all mandatory arguments
3738 * 2. Each argument provided by the client must be expected
3739 * 3. Each argument provided by the client must have the type expected
3742 static void qmp_check_client_args(const mon_cmd_t *cmd, QDict *client_args,
3749 cmd_args = qdict_from_args_type(cmd->args_type);
3752 check_mandatory_args(cmd_args, client_args, &flags, &err);
3757 check_client_args_type(client_args, cmd_args, flags, &err);
3760 error_propagate(errp, err);
3765 * Input object checking rules
3767 * 1. Input object must be a dict
3768 * 2. The "execute" key must exist
3769 * 3. The "execute" key must be a string
3770 * 4. If the "arguments" key exists, it must be a dict
3771 * 5. If the "id" key exists, it can be anything (ie. json-value)
3772 * 6. Any argument not listed above is considered invalid
3774 static QDict *qmp_check_input_obj(QObject *input_obj, Error **errp)
3776 const QDictEntry *ent;
3777 int has_exec_key = 0;
3780 if (qobject_type(input_obj) != QTYPE_QDICT) {
3781 error_setg(errp, QERR_QMP_BAD_INPUT_OBJECT, "object");
3785 input_dict = qobject_to_qdict(input_obj);
3787 for (ent = qdict_first(input_dict); ent; ent = qdict_next(input_dict, ent)){
3788 const char *arg_name = qdict_entry_key(ent);
3789 const QObject *arg_obj = qdict_entry_value(ent);
3791 if (!strcmp(arg_name, "execute")) {
3792 if (qobject_type(arg_obj) != QTYPE_QSTRING) {
3793 error_setg(errp, QERR_QMP_BAD_INPUT_OBJECT_MEMBER,
3794 "execute", "string");
3798 } else if (!strcmp(arg_name, "arguments")) {
3799 if (qobject_type(arg_obj) != QTYPE_QDICT) {
3800 error_setg(errp, QERR_QMP_BAD_INPUT_OBJECT_MEMBER,
3801 "arguments", "object");
3804 } else if (!strcmp(arg_name, "id")) {
3805 /* Any string is acceptable as "id", so nothing to check */
3807 error_setg(errp, QERR_QMP_EXTRA_MEMBER, arg_name);
3812 if (!has_exec_key) {
3813 error_setg(errp, QERR_QMP_BAD_INPUT_OBJECT, "execute");
3820 static void handle_qmp_command(JSONMessageParser *parser, QList *tokens)
3822 Error *local_err = NULL;
3823 QObject *obj, *data;
3824 QDict *input, *args;
3825 const mon_cmd_t *cmd;
3826 const char *cmd_name;
3827 Monitor *mon = cur_mon;
3829 args = input = NULL;
3832 obj = json_parser_parse(tokens, NULL);
3834 // FIXME: should be triggered in json_parser_parse()
3835 error_setg(&local_err, QERR_JSON_PARSING);
3839 input = qmp_check_input_obj(obj, &local_err);
3841 qobject_decref(obj);
3845 mon->qmp.id = qdict_get(input, "id");
3846 qobject_incref(mon->qmp.id);
3848 cmd_name = qdict_get_str(input, "execute");
3849 trace_handle_qmp_command(mon, cmd_name);
3850 cmd = qmp_find_cmd(cmd_name);
3852 error_set(&local_err, ERROR_CLASS_COMMAND_NOT_FOUND,
3853 "The command %s has not been found", cmd_name);
3856 if (invalid_qmp_mode(mon, cmd, &local_err)) {
3860 obj = qdict_get(input, "arguments");
3864 args = qobject_to_qdict(obj);
3868 qmp_check_client_args(cmd, args, &local_err);
3873 cmd->mhandler.cmd_new(args, &data, &local_err);
3876 monitor_protocol_emitter(mon, data, local_err);
3877 qobject_decref(data);
3882 static void monitor_qmp_read(void *opaque, const uint8_t *buf, int size)
3884 Monitor *old_mon = cur_mon;
3888 json_message_parser_feed(&cur_mon->qmp.parser, (const char *) buf, size);
3893 static void monitor_read(void *opaque, const uint8_t *buf, int size)
3895 Monitor *old_mon = cur_mon;
3901 for (i = 0; i < size; i++)
3902 readline_handle_byte(cur_mon->rs, buf[i]);
3904 if (size == 0 || buf[size - 1] != 0)
3905 monitor_printf(cur_mon, "corrupted command\n");
3907 handle_hmp_command(cur_mon, (char *)buf);
3913 static void monitor_command_cb(void *opaque, const char *cmdline,
3914 void *readline_opaque)
3916 Monitor *mon = opaque;
3918 monitor_suspend(mon);
3919 handle_hmp_command(mon, cmdline);
3920 monitor_resume(mon);
3923 int monitor_suspend(Monitor *mon)
3931 void monitor_resume(Monitor *mon)
3935 if (--mon->suspend_cnt == 0)
3936 readline_show_prompt(mon->rs);
3939 static QObject *get_qmp_greeting(void)
3941 QObject *ver = NULL;
3943 qmp_marshal_query_version(NULL, &ver, NULL);
3944 return qobject_from_jsonf("{'QMP':{'version': %p,'capabilities': []}}",ver);
3947 static void monitor_qmp_event(void *opaque, int event)
3950 Monitor *mon = opaque;
3953 case CHR_EVENT_OPENED:
3954 mon->qmp.in_command_mode = false;
3955 data = get_qmp_greeting();
3956 monitor_json_emitter(mon, data);
3957 qobject_decref(data);
3960 case CHR_EVENT_CLOSED:
3961 json_message_parser_destroy(&mon->qmp.parser);
3962 json_message_parser_init(&mon->qmp.parser, handle_qmp_command);
3964 monitor_fdsets_cleanup();
3969 static void monitor_event(void *opaque, int event)
3971 Monitor *mon = opaque;
3974 case CHR_EVENT_MUX_IN:
3975 qemu_mutex_lock(&mon->out_lock);
3977 qemu_mutex_unlock(&mon->out_lock);
3978 if (mon->reset_seen) {
3979 readline_restart(mon->rs);
3980 monitor_resume(mon);
3983 mon->suspend_cnt = 0;
3987 case CHR_EVENT_MUX_OUT:
3988 if (mon->reset_seen) {
3989 if (mon->suspend_cnt == 0) {
3990 monitor_printf(mon, "\n");
3993 monitor_suspend(mon);
3997 qemu_mutex_lock(&mon->out_lock);
3999 qemu_mutex_unlock(&mon->out_lock);
4002 case CHR_EVENT_OPENED:
4003 monitor_printf(mon, "QEMU %s monitor - type 'help' for more "
4004 "information\n", QEMU_VERSION);
4005 if (!mon->mux_out) {
4006 readline_restart(mon->rs);
4007 readline_show_prompt(mon->rs);
4009 mon->reset_seen = 1;
4013 case CHR_EVENT_CLOSED:
4015 monitor_fdsets_cleanup();
4021 compare_mon_cmd(const void *a, const void *b)
4023 return strcmp(((const mon_cmd_t *)a)->name,
4024 ((const mon_cmd_t *)b)->name);
4027 static void sortcmdlist(void)
4030 int elem_size = sizeof(mon_cmd_t);
4032 array_num = sizeof(mon_cmds)/elem_size-1;
4033 qsort((void *)mon_cmds, array_num, elem_size, compare_mon_cmd);
4035 array_num = sizeof(info_cmds)/elem_size-1;
4036 qsort((void *)info_cmds, array_num, elem_size, compare_mon_cmd);
4048 /* These functions just adapt the readline interface in a typesafe way. We
4049 * could cast function pointers but that discards compiler checks.
4051 static void GCC_FMT_ATTR(2, 3) monitor_readline_printf(void *opaque,
4052 const char *fmt, ...)
4056 monitor_vprintf(opaque, fmt, ap);
4060 static void monitor_readline_flush(void *opaque)
4062 monitor_flush(opaque);
4065 static void __attribute__((constructor)) monitor_lock_init(void)
4067 qemu_mutex_init(&monitor_lock);
4070 void monitor_init(CharDriverState *chr, int flags)
4072 static int is_first_init = 1;
4075 if (is_first_init) {
4076 monitor_qapi_event_init();
4081 mon = g_malloc(sizeof(*mon));
4082 monitor_data_init(mon);
4086 if (flags & MONITOR_USE_READLINE) {
4087 mon->rs = readline_init(monitor_readline_printf,
4088 monitor_readline_flush,
4090 monitor_find_completion);
4091 monitor_read_command(mon, 0);
4094 if (monitor_is_qmp(mon)) {
4095 qemu_chr_add_handlers(chr, monitor_can_read, monitor_qmp_read,
4096 monitor_qmp_event, mon);
4097 qemu_chr_fe_set_echo(chr, true);
4098 json_message_parser_init(&mon->qmp.parser, handle_qmp_command);
4100 qemu_chr_add_handlers(chr, monitor_can_read, monitor_read,
4101 monitor_event, mon);
4104 qemu_mutex_lock(&monitor_lock);
4105 QLIST_INSERT_HEAD(&mon_list, mon, entry);
4106 qemu_mutex_unlock(&monitor_lock);
4109 static void bdrv_password_cb(void *opaque, const char *password,
4110 void *readline_opaque)
4112 Monitor *mon = opaque;
4113 BlockDriverState *bs = readline_opaque;
4115 Error *local_err = NULL;
4117 bdrv_add_key(bs, password, &local_err);
4119 monitor_printf(mon, "%s\n", error_get_pretty(local_err));
4120 error_free(local_err);
4123 if (mon->password_completion_cb)
4124 mon->password_completion_cb(mon->password_opaque, ret);
4126 monitor_read_command(mon, 1);
4129 int monitor_read_bdrv_key_start(Monitor *mon, BlockDriverState *bs,
4130 BlockCompletionFunc *completion_cb,
4135 monitor_printf(mon, "%s (%s) is encrypted.\n", bdrv_get_device_name(bs),
4136 bdrv_get_encrypted_filename(bs));
4138 mon->password_completion_cb = completion_cb;
4139 mon->password_opaque = opaque;
4141 err = monitor_read_password(mon, bdrv_password_cb, bs);
4143 if (err && completion_cb)
4144 completion_cb(opaque, err);
4149 int monitor_read_block_device_key(Monitor *mon, const char *device,
4150 BlockCompletionFunc *completion_cb,
4156 blk = blk_by_name(device);
4158 monitor_printf(mon, "Device not found %s\n", device);
4162 monitor_printf(mon, "Device '%s' has no medium\n", device);
4166 bdrv_add_key(blk_bs(blk), NULL, &err);
4169 return monitor_read_bdrv_key_start(mon, blk_bs(blk), completion_cb, opaque);
4172 if (completion_cb) {
4173 completion_cb(opaque, 0);
4178 QemuOptsList qemu_mon_opts = {
4180 .implied_opt_name = "chardev",
4181 .head = QTAILQ_HEAD_INITIALIZER(qemu_mon_opts.head),
4185 .type = QEMU_OPT_STRING,
4188 .type = QEMU_OPT_STRING,
4191 .type = QEMU_OPT_BOOL,
4194 .type = QEMU_OPT_BOOL,
4196 { /* end of list */ }
4201 void qmp_rtc_reset_reinjection(Error **errp)
4203 error_setg(errp, QERR_FEATURE_DISABLED, "rtc-reset-reinjection");
4207 #ifndef TARGET_S390X
4208 void qmp_dump_skeys(const char *filename, Error **errp)
4210 error_setg(errp, QERR_FEATURE_DISABLED, "dump-skeys");