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 "sysemu/block-backend.h"
79 /* for hmp_info_irq/pic */
80 #if defined(TARGET_SPARC)
81 #include "hw/sparc/sun4m.h"
83 #include "hw/lm32/lm32_pic.h"
85 #if defined(TARGET_S390X)
86 #include "hw/s390x/storage-keys.h"
93 * 'B' block device name
94 * 's' string (accept optional quote)
95 * 'S' it just appends the rest of the string (accept optional quote)
96 * 'O' option string of the form NAME=VALUE,...
97 * parsed according to QemuOptsList given by its name
98 * Example: 'device:O' uses qemu_device_opts.
99 * Restriction: only lists with empty desc are supported
100 * TODO lift the restriction
102 * 'l' target long (32 or 64 bit)
103 * 'M' Non-negative target long (32 or 64 bit), in user mode the
104 * value is multiplied by 2^20 (think Mebibyte)
105 * 'o' octets (aka bytes)
106 * user mode accepts an optional E, e, P, p, T, t, G, g, M, m,
107 * K, k suffix, which multiplies the value by 2^60 for suffixes E
108 * and e, 2^50 for suffixes P and p, 2^40 for suffixes T and t,
109 * 2^30 for suffixes G and g, 2^20 for M and m, 2^10 for K and k
111 * user mode accepts an optional ms, us, ns suffix,
112 * which divides the value by 1e3, 1e6, 1e9, respectively
113 * '/' optional gdb-like print format (like "/10x")
115 * '?' optional type (for all types, except '/')
116 * '.' other form of optional type (for 'i' and 'l')
118 * user mode accepts "on" or "off"
119 * '-' optional parameter (eg. '-f')
123 typedef struct mon_cmd_t {
125 const char *args_type;
129 void (*cmd)(Monitor *mon, const QDict *qdict);
130 void (*cmd_new)(QDict *params, QObject **ret_data, Error **errp);
132 /* @sub_table is a list of 2nd level of commands. If it do not exist,
133 * mhandler should be used. If it exist, sub_table[?].mhandler should be
134 * used, and mhandler of 1st level plays the role of help function.
136 struct mon_cmd_t *sub_table;
137 void (*command_completion)(ReadLineState *rs, int nb_args, const char *str);
140 /* file descriptors passed via SCM_RIGHTS */
141 typedef struct mon_fd_t mon_fd_t;
145 QLIST_ENTRY(mon_fd_t) next;
148 /* file descriptor associated with a file descriptor set */
149 typedef struct MonFdsetFd MonFdsetFd;
154 QLIST_ENTRY(MonFdsetFd) next;
157 /* file descriptor set containing fds passed via SCM_RIGHTS */
158 typedef struct MonFdset MonFdset;
161 QLIST_HEAD(, MonFdsetFd) fds;
162 QLIST_HEAD(, MonFdsetFd) dup_fds;
163 QLIST_ENTRY(MonFdset) next;
168 JSONMessageParser parser;
170 * When a client connects, we're in capabilities negotiation mode.
171 * When command qmp_capabilities succeeds, we go into command
174 bool in_command_mode; /* are we in command mode? */
178 * To prevent flooding clients, events can be throttled. The
179 * throttling is calculated globally, rather than per-Monitor
182 typedef struct MonitorQAPIEventState {
183 QAPIEvent event; /* Event being tracked */
184 int64_t rate; /* Minimum time (in ns) between two events */
185 int64_t last; /* QEMU_CLOCK_REALTIME value at last emission */
186 QEMUTimer *timer; /* Timer for handling delayed events */
187 QObject *data; /* Event pending delayed dispatch */
188 } MonitorQAPIEventState;
191 CharDriverState *chr;
201 /* Read under either BQL or out_lock, written with BQL+out_lock. */
207 BlockCompletionFunc *password_completion_cb;
208 void *password_opaque;
209 mon_cmd_t *cmd_table;
210 QLIST_HEAD(,mon_fd_t) fds;
211 QLIST_ENTRY(Monitor) entry;
214 /* QMP checker flags */
215 #define QMP_ACCEPT_UNKNOWNS 1
217 /* Protects mon_list, monitor_event_state. */
218 static QemuMutex monitor_lock;
220 static QLIST_HEAD(mon_list, Monitor) mon_list;
221 static QLIST_HEAD(mon_fdsets, MonFdset) mon_fdsets;
222 static int mon_refcount;
224 static mon_cmd_t mon_cmds[];
225 static mon_cmd_t info_cmds[];
227 static const mon_cmd_t qmp_cmds[];
231 static void monitor_command_cb(void *opaque, const char *cmdline,
232 void *readline_opaque);
235 * Is @mon a QMP monitor?
237 static inline bool monitor_is_qmp(const Monitor *mon)
239 return (mon->flags & MONITOR_USE_CONTROL);
243 * Is the current monitor, if any, a QMP monitor?
245 bool monitor_cur_is_qmp(void)
247 return cur_mon && monitor_is_qmp(cur_mon);
250 void monitor_read_command(Monitor *mon, int show_prompt)
255 readline_start(mon->rs, "(qemu) ", 0, monitor_command_cb, NULL);
257 readline_show_prompt(mon->rs);
260 int monitor_read_password(Monitor *mon, ReadLineFunc *readline_func,
264 readline_start(mon->rs, "Password: ", 1, readline_func, opaque);
265 /* prompt is printed on return from the command handler */
268 monitor_printf(mon, "terminal does not support password prompting\n");
273 static void monitor_flush_locked(Monitor *mon);
275 static gboolean monitor_unblocked(GIOChannel *chan, GIOCondition cond,
278 Monitor *mon = opaque;
280 qemu_mutex_lock(&mon->out_lock);
282 monitor_flush_locked(mon);
283 qemu_mutex_unlock(&mon->out_lock);
287 /* Called with mon->out_lock held. */
288 static void monitor_flush_locked(Monitor *mon)
294 if (mon->skip_flush) {
298 buf = qstring_get_str(mon->outbuf);
299 len = qstring_get_length(mon->outbuf);
301 if (len && !mon->mux_out) {
302 rc = qemu_chr_fe_write(mon->chr, (const uint8_t *) buf, len);
303 if ((rc < 0 && errno != EAGAIN) || (rc == len)) {
304 /* all flushed or error */
305 QDECREF(mon->outbuf);
306 mon->outbuf = qstring_new();
311 QString *tmp = qstring_from_str(buf + rc);
312 QDECREF(mon->outbuf);
315 if (mon->out_watch == 0) {
316 mon->out_watch = qemu_chr_fe_add_watch(mon->chr, G_IO_OUT|G_IO_HUP,
317 monitor_unblocked, mon);
322 void monitor_flush(Monitor *mon)
324 qemu_mutex_lock(&mon->out_lock);
325 monitor_flush_locked(mon);
326 qemu_mutex_unlock(&mon->out_lock);
329 /* flush at every end of line */
330 static void monitor_puts(Monitor *mon, const char *str)
334 qemu_mutex_lock(&mon->out_lock);
340 qstring_append_chr(mon->outbuf, '\r');
342 qstring_append_chr(mon->outbuf, c);
344 monitor_flush_locked(mon);
347 qemu_mutex_unlock(&mon->out_lock);
350 void monitor_vprintf(Monitor *mon, const char *fmt, va_list ap)
357 if (monitor_is_qmp(mon)) {
361 buf = g_strdup_vprintf(fmt, ap);
362 monitor_puts(mon, buf);
366 void monitor_printf(Monitor *mon, const char *fmt, ...)
370 monitor_vprintf(mon, fmt, ap);
374 static int GCC_FMT_ATTR(2, 3) monitor_fprintf(FILE *stream,
375 const char *fmt, ...)
379 monitor_vprintf((Monitor *)stream, fmt, ap);
384 static void monitor_json_emitter(Monitor *mon, const QObject *data)
388 json = mon->flags & MONITOR_USE_PRETTY ? qobject_to_json_pretty(data) :
389 qobject_to_json(data);
390 assert(json != NULL);
392 qstring_append_chr(json, '\n');
393 monitor_puts(mon, qstring_get_str(json));
398 static QDict *build_qmp_error_dict(Error *err)
402 obj = qobject_from_jsonf("{ 'error': { 'class': %s, 'desc': %s } }",
403 ErrorClass_lookup[error_get_class(err)],
404 error_get_pretty(err));
406 return qobject_to_qdict(obj);
409 static void monitor_protocol_emitter(Monitor *mon, QObject *data,
414 trace_monitor_protocol_emitter(mon);
417 /* success response */
420 qobject_incref(data);
421 qdict_put_obj(qmp, "return", data);
423 /* return an empty QDict by default */
424 qdict_put(qmp, "return", qdict_new());
428 qmp = build_qmp_error_dict(err);
432 qdict_put_obj(qmp, "id", mon->qmp.id);
436 monitor_json_emitter(mon, QOBJECT(qmp));
441 static MonitorQAPIEventState monitor_qapi_event_state[QAPI_EVENT_MAX];
444 * Emits the event to every monitor instance, @event is only used for trace
445 * Called with monitor_lock held.
447 static void monitor_qapi_event_emit(QAPIEvent event, QObject *data)
451 trace_monitor_protocol_event_emit(event, data);
452 QLIST_FOREACH(mon, &mon_list, entry) {
453 if (monitor_is_qmp(mon) && mon->qmp.in_command_mode) {
454 monitor_json_emitter(mon, data);
460 * Queue a new event for emission to Monitor instances,
461 * applying any rate limiting if required.
464 monitor_qapi_event_queue(QAPIEvent event, QDict *data, Error **errp)
466 MonitorQAPIEventState *evstate;
467 assert(event < QAPI_EVENT_MAX);
468 int64_t now = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
470 evstate = &(monitor_qapi_event_state[event]);
471 trace_monitor_protocol_event_queue(event,
477 /* Rate limit of 0 indicates no throttling */
478 qemu_mutex_lock(&monitor_lock);
479 if (!evstate->rate) {
480 monitor_qapi_event_emit(event, QOBJECT(data));
483 int64_t delta = now - evstate->last;
485 delta < evstate->rate) {
486 /* If there's an existing event pending, replace
487 * it with the new event, otherwise schedule a
488 * timer for delayed emission
491 qobject_decref(evstate->data);
493 int64_t then = evstate->last + evstate->rate;
494 timer_mod_ns(evstate->timer, then);
496 evstate->data = QOBJECT(data);
497 qobject_incref(evstate->data);
499 monitor_qapi_event_emit(event, QOBJECT(data));
503 qemu_mutex_unlock(&monitor_lock);
507 * The callback invoked by QemuTimer when a delayed
508 * event is ready to be emitted
510 static void monitor_qapi_event_handler(void *opaque)
512 MonitorQAPIEventState *evstate = opaque;
513 int64_t now = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
515 trace_monitor_protocol_event_handler(evstate->event,
519 qemu_mutex_lock(&monitor_lock);
521 monitor_qapi_event_emit(evstate->event, evstate->data);
522 qobject_decref(evstate->data);
523 evstate->data = NULL;
526 qemu_mutex_unlock(&monitor_lock);
530 * @event: the event ID to be limited
531 * @rate: the rate limit in milliseconds
533 * Sets a rate limit on a particular event, so no
534 * more than 1 event will be emitted within @rate
538 monitor_qapi_event_throttle(QAPIEvent event, int64_t rate)
540 MonitorQAPIEventState *evstate;
541 assert(event < QAPI_EVENT_MAX);
543 evstate = &(monitor_qapi_event_state[event]);
545 trace_monitor_protocol_event_throttle(event, rate);
546 evstate->event = event;
547 assert(rate * SCALE_MS <= INT64_MAX);
548 evstate->rate = rate * SCALE_MS;
550 evstate->data = NULL;
551 evstate->timer = timer_new(QEMU_CLOCK_REALTIME,
553 monitor_qapi_event_handler,
557 static void monitor_qapi_event_init(void)
559 /* Limit guest-triggerable events to 1 per second */
560 monitor_qapi_event_throttle(QAPI_EVENT_RTC_CHANGE, 1000);
561 monitor_qapi_event_throttle(QAPI_EVENT_WATCHDOG, 1000);
562 monitor_qapi_event_throttle(QAPI_EVENT_BALLOON_CHANGE, 1000);
563 monitor_qapi_event_throttle(QAPI_EVENT_QUORUM_REPORT_BAD, 1000);
564 monitor_qapi_event_throttle(QAPI_EVENT_QUORUM_FAILURE, 1000);
565 monitor_qapi_event_throttle(QAPI_EVENT_VSERPORT_CHANGE, 1000);
567 qmp_event_set_func_emit(monitor_qapi_event_queue);
570 static void qmp_capabilities(QDict *params, QObject **ret_data, Error **errp)
572 cur_mon->qmp.in_command_mode = true;
575 static void handle_hmp_command(Monitor *mon, const char *cmdline);
577 static void monitor_data_init(Monitor *mon)
579 memset(mon, 0, sizeof(Monitor));
580 qemu_mutex_init(&mon->out_lock);
581 mon->outbuf = qstring_new();
582 /* Use *mon_cmds by default. */
583 mon->cmd_table = mon_cmds;
586 static void monitor_data_destroy(Monitor *mon)
588 QDECREF(mon->outbuf);
589 qemu_mutex_destroy(&mon->out_lock);
592 char *qmp_human_monitor_command(const char *command_line, bool has_cpu_index,
593 int64_t cpu_index, Error **errp)
596 Monitor *old_mon, hmp;
598 monitor_data_init(&hmp);
599 hmp.skip_flush = true;
605 int ret = monitor_set_cpu(cpu_index);
608 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cpu-index",
614 handle_hmp_command(&hmp, command_line);
617 qemu_mutex_lock(&hmp.out_lock);
618 if (qstring_get_length(hmp.outbuf) > 0) {
619 output = g_strdup(qstring_get_str(hmp.outbuf));
621 output = g_strdup("");
623 qemu_mutex_unlock(&hmp.out_lock);
626 monitor_data_destroy(&hmp);
630 static int compare_cmd(const char *name, const char *list)
632 const char *p, *pstart;
640 p = pstart + strlen(pstart);
641 if ((p - pstart) == len && !memcmp(pstart, name, len))
650 static int get_str(char *buf, int buf_size, const char **pp)
658 while (qemu_isspace(*p)) {
669 while (*p != '\0' && *p != '\"') {
685 printf("unsupported escape code: '\\%c'\n", c);
688 if ((q - buf) < buf_size - 1) {
692 if ((q - buf) < buf_size - 1) {
699 printf("unterminated string\n");
704 while (*p != '\0' && !qemu_isspace(*p)) {
705 if ((q - buf) < buf_size - 1) {
718 static void free_cmdline_args(char **args, int nb_args)
722 assert(nb_args <= MAX_ARGS);
724 for (i = 0; i < nb_args; i++) {
731 * Parse the command line to get valid args.
732 * @cmdline: command line to be parsed.
733 * @pnb_args: location to store the number of args, must NOT be NULL.
734 * @args: location to store the args, which should be freed by caller, must
737 * Returns 0 on success, negative on failure.
739 * NOTE: this parser is an approximate form of the real command parser. Number
740 * of args have a limit of MAX_ARGS. If cmdline contains more, it will
741 * return with failure.
743 static int parse_cmdline(const char *cmdline,
744 int *pnb_args, char **args)
753 while (qemu_isspace(*p)) {
759 if (nb_args >= MAX_ARGS) {
762 ret = get_str(buf, sizeof(buf), &p);
766 args[nb_args] = g_strdup(buf);
773 free_cmdline_args(args, nb_args);
777 static void help_cmd_dump_one(Monitor *mon,
778 const mon_cmd_t *cmd,
784 for (i = 0; i < prefix_args_nb; i++) {
785 monitor_printf(mon, "%s ", prefix_args[i]);
787 monitor_printf(mon, "%s %s -- %s\n", cmd->name, cmd->params, cmd->help);
790 /* @args[@arg_index] is the valid command need to find in @cmds */
791 static void help_cmd_dump(Monitor *mon, const mon_cmd_t *cmds,
792 char **args, int nb_args, int arg_index)
794 const mon_cmd_t *cmd;
796 /* No valid arg need to compare with, dump all in *cmds */
797 if (arg_index >= nb_args) {
798 for (cmd = cmds; cmd->name != NULL; cmd++) {
799 help_cmd_dump_one(mon, cmd, args, arg_index);
804 /* Find one entry to dump */
805 for (cmd = cmds; cmd->name != NULL; cmd++) {
806 if (compare_cmd(args[arg_index], cmd->name)) {
807 if (cmd->sub_table) {
808 /* continue with next arg */
809 help_cmd_dump(mon, cmd->sub_table,
810 args, nb_args, arg_index + 1);
812 help_cmd_dump_one(mon, cmd, args, arg_index);
819 static void help_cmd(Monitor *mon, const char *name)
821 char *args[MAX_ARGS];
824 /* 1. parse user input */
826 /* special case for log, directly dump and return */
827 if (!strcmp(name, "log")) {
828 const QEMULogItem *item;
829 monitor_printf(mon, "Log items (comma separated):\n");
830 monitor_printf(mon, "%-10s %s\n", "none", "remove all logs");
831 for (item = qemu_log_items; item->mask != 0; item++) {
832 monitor_printf(mon, "%-10s %s\n", item->name, item->help);
837 if (parse_cmdline(name, &nb_args, args) < 0) {
842 /* 2. dump the contents according to parsed args */
843 help_cmd_dump(mon, mon->cmd_table, args, nb_args, 0);
845 free_cmdline_args(args, nb_args);
848 static void do_help_cmd(Monitor *mon, const QDict *qdict)
850 help_cmd(mon, qdict_get_try_str(qdict, "name"));
853 static void hmp_trace_event(Monitor *mon, const QDict *qdict)
855 const char *tp_name = qdict_get_str(qdict, "name");
856 bool new_state = qdict_get_bool(qdict, "option");
857 Error *local_err = NULL;
859 qmp_trace_event_set_state(tp_name, new_state, true, true, &local_err);
861 error_report_err(local_err);
865 #ifdef CONFIG_TRACE_SIMPLE
866 static void hmp_trace_file(Monitor *mon, const QDict *qdict)
868 const char *op = qdict_get_try_str(qdict, "op");
869 const char *arg = qdict_get_try_str(qdict, "arg");
872 st_print_trace_file_status((FILE *)mon, &monitor_fprintf);
873 } else if (!strcmp(op, "on")) {
874 st_set_trace_file_enabled(true);
875 } else if (!strcmp(op, "off")) {
876 st_set_trace_file_enabled(false);
877 } else if (!strcmp(op, "flush")) {
878 st_flush_trace_buffer();
879 } else if (!strcmp(op, "set")) {
881 st_set_trace_file(arg);
884 monitor_printf(mon, "unexpected argument \"%s\"\n", op);
885 help_cmd(mon, "trace-file");
890 static void hmp_info_help(Monitor *mon, const QDict *qdict)
892 help_cmd(mon, "info");
895 CommandInfoList *qmp_query_commands(Error **errp)
897 CommandInfoList *info, *cmd_list = NULL;
898 const mon_cmd_t *cmd;
900 for (cmd = qmp_cmds; cmd->name != NULL; cmd++) {
901 info = g_malloc0(sizeof(*info));
902 info->value = g_malloc0(sizeof(*info->value));
903 info->value->name = g_strdup(cmd->name);
905 info->next = cmd_list;
912 EventInfoList *qmp_query_events(Error **errp)
914 EventInfoList *info, *ev_list = NULL;
917 for (e = 0 ; e < QAPI_EVENT_MAX ; e++) {
918 const char *event_name = QAPIEvent_lookup[e];
919 assert(event_name != NULL);
920 info = g_malloc0(sizeof(*info));
921 info->value = g_malloc0(sizeof(*info->value));
922 info->value->name = g_strdup(event_name);
924 info->next = ev_list;
931 /* set the current CPU defined by the user */
932 int monitor_set_cpu(int cpu_index)
936 cpu = qemu_get_cpu(cpu_index);
940 cur_mon->mon_cpu = cpu;
944 static CPUState *mon_get_cpu(void)
946 if (!cur_mon->mon_cpu) {
949 cpu_synchronize_state(cur_mon->mon_cpu);
950 return cur_mon->mon_cpu;
953 CPUArchState *mon_get_cpu_env(void)
955 return mon_get_cpu()->env_ptr;
958 int monitor_get_cpu_index(void)
960 return mon_get_cpu()->cpu_index;
963 static void hmp_info_registers(Monitor *mon, const QDict *qdict)
965 cpu_dump_state(mon_get_cpu(), (FILE *)mon, monitor_fprintf, CPU_DUMP_FPU);
968 static void hmp_info_jit(Monitor *mon, const QDict *qdict)
970 dump_exec_info((FILE *)mon, monitor_fprintf);
971 dump_drift_info((FILE *)mon, monitor_fprintf);
974 static void hmp_info_opcount(Monitor *mon, const QDict *qdict)
976 dump_opcount_info((FILE *)mon, monitor_fprintf);
979 static void hmp_info_history(Monitor *mon, const QDict *qdict)
988 str = readline_get_history(mon->rs, i);
991 monitor_printf(mon, "%d: '%s'\n", i, str);
996 static void hmp_info_cpustats(Monitor *mon, const QDict *qdict)
998 cpu_dump_statistics(mon_get_cpu(), (FILE *)mon, &monitor_fprintf, 0);
1001 static void hmp_info_trace_events(Monitor *mon, const QDict *qdict)
1003 TraceEventInfoList *events = qmp_trace_event_get_state("*", NULL);
1004 TraceEventInfoList *elem;
1006 for (elem = events; elem != NULL; elem = elem->next) {
1007 monitor_printf(mon, "%s : state %u\n",
1009 elem->value->state == TRACE_EVENT_STATE_ENABLED ? 1 : 0);
1011 qapi_free_TraceEventInfoList(events);
1014 void qmp_client_migrate_info(const char *protocol, const char *hostname,
1015 bool has_port, int64_t port,
1016 bool has_tls_port, int64_t tls_port,
1017 bool has_cert_subject, const char *cert_subject,
1020 if (strcmp(protocol, "spice") == 0) {
1021 if (!qemu_using_spice(errp)) {
1025 if (!has_port && !has_tls_port) {
1026 error_setg(errp, QERR_MISSING_PARAMETER, "port/tls-port");
1030 if (qemu_spice_migrate_info(hostname,
1031 has_port ? port : -1,
1032 has_tls_port ? tls_port : -1,
1034 error_setg(errp, QERR_UNDEFINED_ERROR);
1040 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "protocol", "spice");
1043 static void hmp_logfile(Monitor *mon, const QDict *qdict)
1045 qemu_set_log_filename(qdict_get_str(qdict, "filename"));
1048 static void hmp_log(Monitor *mon, const QDict *qdict)
1051 const char *items = qdict_get_str(qdict, "items");
1053 if (!strcmp(items, "none")) {
1056 mask = qemu_str_to_log_mask(items);
1058 help_cmd(mon, "log");
1065 static void hmp_singlestep(Monitor *mon, const QDict *qdict)
1067 const char *option = qdict_get_try_str(qdict, "option");
1068 if (!option || !strcmp(option, "on")) {
1070 } else if (!strcmp(option, "off")) {
1073 monitor_printf(mon, "unexpected option %s\n", option);
1077 static void hmp_gdbserver(Monitor *mon, const QDict *qdict)
1079 const char *device = qdict_get_try_str(qdict, "device");
1081 device = "tcp::" DEFAULT_GDBSTUB_PORT;
1082 if (gdbserver_start(device) < 0) {
1083 monitor_printf(mon, "Could not open gdbserver on device '%s'\n",
1085 } else if (strcmp(device, "none") == 0) {
1086 monitor_printf(mon, "Disabled gdbserver\n");
1088 monitor_printf(mon, "Waiting for gdb connection on device '%s'\n",
1093 static void hmp_watchdog_action(Monitor *mon, const QDict *qdict)
1095 const char *action = qdict_get_str(qdict, "action");
1096 if (select_watchdog_action(action) == -1) {
1097 monitor_printf(mon, "Unknown watchdog action '%s'\n", action);
1101 static void monitor_printc(Monitor *mon, int c)
1103 monitor_printf(mon, "'");
1106 monitor_printf(mon, "\\'");
1109 monitor_printf(mon, "\\\\");
1112 monitor_printf(mon, "\\n");
1115 monitor_printf(mon, "\\r");
1118 if (c >= 32 && c <= 126) {
1119 monitor_printf(mon, "%c", c);
1121 monitor_printf(mon, "\\x%02x", c);
1125 monitor_printf(mon, "'");
1128 static void memory_dump(Monitor *mon, int count, int format, int wsize,
1129 hwaddr addr, int is_physical)
1131 int l, line_size, i, max_digits, len;
1135 if (format == 'i') {
1138 CPUArchState *env = mon_get_cpu_env();
1141 } else if (wsize == 4) {
1144 /* as default we use the current CS size */
1147 #ifdef TARGET_X86_64
1148 if ((env->efer & MSR_EFER_LMA) &&
1149 (env->segs[R_CS].flags & DESC_L_MASK))
1153 if (!(env->segs[R_CS].flags & DESC_B_MASK))
1159 CPUArchState *env = mon_get_cpu_env();
1160 flags = msr_le << 16;
1161 flags |= env->bfd_mach;
1163 monitor_disas(mon, mon_get_cpu(), addr, count, is_physical, flags);
1167 len = wsize * count;
1176 max_digits = (wsize * 8 + 2) / 3;
1180 max_digits = (wsize * 8) / 4;
1184 max_digits = (wsize * 8 * 10 + 32) / 33;
1193 monitor_printf(mon, TARGET_FMT_plx ":", addr);
1195 monitor_printf(mon, TARGET_FMT_lx ":", (target_ulong)addr);
1200 cpu_physical_memory_read(addr, buf, l);
1202 if (cpu_memory_rw_debug(mon_get_cpu(), addr, buf, l, 0) < 0) {
1203 monitor_printf(mon, " Cannot access memory\n");
1212 v = ldub_p(buf + i);
1215 v = lduw_p(buf + i);
1218 v = (uint32_t)ldl_p(buf + i);
1224 monitor_printf(mon, " ");
1227 monitor_printf(mon, "%#*" PRIo64, max_digits, v);
1230 monitor_printf(mon, "0x%0*" PRIx64, max_digits, v);
1233 monitor_printf(mon, "%*" PRIu64, max_digits, v);
1236 monitor_printf(mon, "%*" PRId64, max_digits, v);
1239 monitor_printc(mon, v);
1244 monitor_printf(mon, "\n");
1250 static void hmp_memory_dump(Monitor *mon, const QDict *qdict)
1252 int count = qdict_get_int(qdict, "count");
1253 int format = qdict_get_int(qdict, "format");
1254 int size = qdict_get_int(qdict, "size");
1255 target_long addr = qdict_get_int(qdict, "addr");
1257 memory_dump(mon, count, format, size, addr, 0);
1260 static void hmp_physical_memory_dump(Monitor *mon, const QDict *qdict)
1262 int count = qdict_get_int(qdict, "count");
1263 int format = qdict_get_int(qdict, "format");
1264 int size = qdict_get_int(qdict, "size");
1265 hwaddr addr = qdict_get_int(qdict, "addr");
1267 memory_dump(mon, count, format, size, addr, 1);
1270 static void do_print(Monitor *mon, const QDict *qdict)
1272 int format = qdict_get_int(qdict, "format");
1273 hwaddr val = qdict_get_int(qdict, "val");
1277 monitor_printf(mon, "%#" HWADDR_PRIo, val);
1280 monitor_printf(mon, "%#" HWADDR_PRIx, val);
1283 monitor_printf(mon, "%" HWADDR_PRIu, val);
1287 monitor_printf(mon, "%" HWADDR_PRId, val);
1290 monitor_printc(mon, val);
1293 monitor_printf(mon, "\n");
1296 static void hmp_sum(Monitor *mon, const QDict *qdict)
1300 uint32_t start = qdict_get_int(qdict, "start");
1301 uint32_t size = qdict_get_int(qdict, "size");
1304 for(addr = start; addr < (start + size); addr++) {
1305 uint8_t val = address_space_ldub(&address_space_memory, addr,
1306 MEMTXATTRS_UNSPECIFIED, NULL);
1307 /* BSD sum algorithm ('sum' Unix command) */
1308 sum = (sum >> 1) | (sum << 15);
1311 monitor_printf(mon, "%05d\n", sum);
1314 static int mouse_button_state;
1316 static void hmp_mouse_move(Monitor *mon, const QDict *qdict)
1318 int dx, dy, dz, button;
1319 const char *dx_str = qdict_get_str(qdict, "dx_str");
1320 const char *dy_str = qdict_get_str(qdict, "dy_str");
1321 const char *dz_str = qdict_get_try_str(qdict, "dz_str");
1323 dx = strtol(dx_str, NULL, 0);
1324 dy = strtol(dy_str, NULL, 0);
1325 qemu_input_queue_rel(NULL, INPUT_AXIS_X, dx);
1326 qemu_input_queue_rel(NULL, INPUT_AXIS_Y, dy);
1329 dz = strtol(dz_str, NULL, 0);
1331 button = (dz > 0) ? INPUT_BUTTON_WHEEL_UP : INPUT_BUTTON_WHEEL_DOWN;
1332 qemu_input_queue_btn(NULL, button, true);
1333 qemu_input_event_sync();
1334 qemu_input_queue_btn(NULL, button, false);
1337 qemu_input_event_sync();
1340 static void hmp_mouse_button(Monitor *mon, const QDict *qdict)
1342 static uint32_t bmap[INPUT_BUTTON_MAX] = {
1343 [INPUT_BUTTON_LEFT] = MOUSE_EVENT_LBUTTON,
1344 [INPUT_BUTTON_MIDDLE] = MOUSE_EVENT_MBUTTON,
1345 [INPUT_BUTTON_RIGHT] = MOUSE_EVENT_RBUTTON,
1347 int button_state = qdict_get_int(qdict, "button_state");
1349 if (mouse_button_state == button_state) {
1352 qemu_input_update_buttons(NULL, bmap, mouse_button_state, button_state);
1353 qemu_input_event_sync();
1354 mouse_button_state = button_state;
1357 static void hmp_ioport_read(Monitor *mon, const QDict *qdict)
1359 int size = qdict_get_int(qdict, "size");
1360 int addr = qdict_get_int(qdict, "addr");
1361 int has_index = qdict_haskey(qdict, "index");
1366 int index = qdict_get_int(qdict, "index");
1367 cpu_outb(addr & IOPORTS_MASK, index & 0xff);
1375 val = cpu_inb(addr);
1379 val = cpu_inw(addr);
1383 val = cpu_inl(addr);
1387 monitor_printf(mon, "port%c[0x%04x] = %#0*x\n",
1388 suffix, addr, size * 2, val);
1391 static void hmp_ioport_write(Monitor *mon, const QDict *qdict)
1393 int size = qdict_get_int(qdict, "size");
1394 int addr = qdict_get_int(qdict, "addr");
1395 int val = qdict_get_int(qdict, "val");
1397 addr &= IOPORTS_MASK;
1402 cpu_outb(addr, val);
1405 cpu_outw(addr, val);
1408 cpu_outl(addr, val);
1413 static void hmp_boot_set(Monitor *mon, const QDict *qdict)
1415 Error *local_err = NULL;
1416 const char *bootdevice = qdict_get_str(qdict, "bootdevice");
1418 qemu_boot_set(bootdevice, &local_err);
1420 monitor_printf(mon, "%s\n", error_get_pretty(local_err));
1421 error_free(local_err);
1423 monitor_printf(mon, "boot device list now set to %s\n", bootdevice);
1427 static void hmp_info_mtree(Monitor *mon, const QDict *qdict)
1429 mtree_info((fprintf_function)monitor_printf, mon);
1432 static void hmp_info_numa(Monitor *mon, const QDict *qdict)
1438 node_mem = g_new0(uint64_t, nb_numa_nodes);
1439 query_numa_node_mem(node_mem);
1440 monitor_printf(mon, "%d nodes\n", nb_numa_nodes);
1441 for (i = 0; i < nb_numa_nodes; i++) {
1442 monitor_printf(mon, "node %d cpus:", i);
1444 if (cpu->numa_node == i) {
1445 monitor_printf(mon, " %d", cpu->cpu_index);
1448 monitor_printf(mon, "\n");
1449 monitor_printf(mon, "node %d size: %" PRId64 " MB\n", i,
1455 #ifdef CONFIG_PROFILER
1460 static void hmp_info_profile(Monitor *mon, const QDict *qdict)
1462 monitor_printf(mon, "async time %" PRId64 " (%0.3f)\n",
1463 dev_time, dev_time / (double)get_ticks_per_sec());
1464 monitor_printf(mon, "qemu time %" PRId64 " (%0.3f)\n",
1465 tcg_time, tcg_time / (double)get_ticks_per_sec());
1470 static void hmp_info_profile(Monitor *mon, const QDict *qdict)
1472 monitor_printf(mon, "Internal profiler not compiled\n");
1476 /* Capture support */
1477 static QLIST_HEAD (capture_list_head, CaptureState) capture_head;
1479 static void hmp_info_capture(Monitor *mon, const QDict *qdict)
1484 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
1485 monitor_printf(mon, "[%d]: ", i);
1486 s->ops.info (s->opaque);
1490 static void hmp_stopcapture(Monitor *mon, const QDict *qdict)
1493 int n = qdict_get_int(qdict, "n");
1496 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
1498 s->ops.destroy (s->opaque);
1499 QLIST_REMOVE (s, entries);
1506 static void hmp_wavcapture(Monitor *mon, const QDict *qdict)
1508 const char *path = qdict_get_str(qdict, "path");
1509 int has_freq = qdict_haskey(qdict, "freq");
1510 int freq = qdict_get_try_int(qdict, "freq", -1);
1511 int has_bits = qdict_haskey(qdict, "bits");
1512 int bits = qdict_get_try_int(qdict, "bits", -1);
1513 int has_channels = qdict_haskey(qdict, "nchannels");
1514 int nchannels = qdict_get_try_int(qdict, "nchannels", -1);
1517 s = g_malloc0 (sizeof (*s));
1519 freq = has_freq ? freq : 44100;
1520 bits = has_bits ? bits : 16;
1521 nchannels = has_channels ? nchannels : 2;
1523 if (wav_start_capture (s, path, freq, bits, nchannels)) {
1524 monitor_printf(mon, "Failed to add wave capture\n");
1528 QLIST_INSERT_HEAD (&capture_head, s, entries);
1531 static qemu_acl *find_acl(Monitor *mon, const char *name)
1533 qemu_acl *acl = qemu_acl_find(name);
1536 monitor_printf(mon, "acl: unknown list '%s'\n", name);
1541 static void hmp_acl_show(Monitor *mon, const QDict *qdict)
1543 const char *aclname = qdict_get_str(qdict, "aclname");
1544 qemu_acl *acl = find_acl(mon, aclname);
1545 qemu_acl_entry *entry;
1549 monitor_printf(mon, "policy: %s\n",
1550 acl->defaultDeny ? "deny" : "allow");
1551 QTAILQ_FOREACH(entry, &acl->entries, next) {
1553 monitor_printf(mon, "%d: %s %s\n", i,
1554 entry->deny ? "deny" : "allow", entry->match);
1559 static void hmp_acl_reset(Monitor *mon, const QDict *qdict)
1561 const char *aclname = qdict_get_str(qdict, "aclname");
1562 qemu_acl *acl = find_acl(mon, aclname);
1565 qemu_acl_reset(acl);
1566 monitor_printf(mon, "acl: removed all rules\n");
1570 static void hmp_acl_policy(Monitor *mon, const QDict *qdict)
1572 const char *aclname = qdict_get_str(qdict, "aclname");
1573 const char *policy = qdict_get_str(qdict, "policy");
1574 qemu_acl *acl = find_acl(mon, aclname);
1577 if (strcmp(policy, "allow") == 0) {
1578 acl->defaultDeny = 0;
1579 monitor_printf(mon, "acl: policy set to 'allow'\n");
1580 } else if (strcmp(policy, "deny") == 0) {
1581 acl->defaultDeny = 1;
1582 monitor_printf(mon, "acl: policy set to 'deny'\n");
1584 monitor_printf(mon, "acl: unknown policy '%s', "
1585 "expected 'deny' or 'allow'\n", policy);
1590 static void hmp_acl_add(Monitor *mon, const QDict *qdict)
1592 const char *aclname = qdict_get_str(qdict, "aclname");
1593 const char *match = qdict_get_str(qdict, "match");
1594 const char *policy = qdict_get_str(qdict, "policy");
1595 int has_index = qdict_haskey(qdict, "index");
1596 int index = qdict_get_try_int(qdict, "index", -1);
1597 qemu_acl *acl = find_acl(mon, aclname);
1601 if (strcmp(policy, "allow") == 0) {
1603 } else if (strcmp(policy, "deny") == 0) {
1606 monitor_printf(mon, "acl: unknown policy '%s', "
1607 "expected 'deny' or 'allow'\n", policy);
1611 ret = qemu_acl_insert(acl, deny, match, index);
1613 ret = qemu_acl_append(acl, deny, match);
1615 monitor_printf(mon, "acl: unable to add acl entry\n");
1617 monitor_printf(mon, "acl: added rule at position %d\n", ret);
1621 static void hmp_acl_remove(Monitor *mon, const QDict *qdict)
1623 const char *aclname = qdict_get_str(qdict, "aclname");
1624 const char *match = qdict_get_str(qdict, "match");
1625 qemu_acl *acl = find_acl(mon, aclname);
1629 ret = qemu_acl_remove(acl, match);
1631 monitor_printf(mon, "acl: no matching acl entry\n");
1633 monitor_printf(mon, "acl: removed rule at position %d\n", ret);
1637 void qmp_getfd(const char *fdname, Error **errp)
1642 fd = qemu_chr_fe_get_msgfd(cur_mon->chr);
1644 error_setg(errp, QERR_FD_NOT_SUPPLIED);
1648 if (qemu_isdigit(fdname[0])) {
1650 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "fdname",
1651 "a name not starting with a digit");
1655 QLIST_FOREACH(monfd, &cur_mon->fds, next) {
1656 if (strcmp(monfd->name, fdname) != 0) {
1665 monfd = g_malloc0(sizeof(mon_fd_t));
1666 monfd->name = g_strdup(fdname);
1669 QLIST_INSERT_HEAD(&cur_mon->fds, monfd, next);
1672 void qmp_closefd(const char *fdname, Error **errp)
1676 QLIST_FOREACH(monfd, &cur_mon->fds, next) {
1677 if (strcmp(monfd->name, fdname) != 0) {
1681 QLIST_REMOVE(monfd, next);
1683 g_free(monfd->name);
1688 error_setg(errp, QERR_FD_NOT_FOUND, fdname);
1691 static void hmp_loadvm(Monitor *mon, const QDict *qdict)
1693 int saved_vm_running = runstate_is_running();
1694 const char *name = qdict_get_str(qdict, "name");
1696 vm_stop(RUN_STATE_RESTORE_VM);
1698 if (load_vmstate(name) == 0 && saved_vm_running) {
1703 int monitor_get_fd(Monitor *mon, const char *fdname, Error **errp)
1707 QLIST_FOREACH(monfd, &mon->fds, next) {
1710 if (strcmp(monfd->name, fdname) != 0) {
1716 /* caller takes ownership of fd */
1717 QLIST_REMOVE(monfd, next);
1718 g_free(monfd->name);
1724 error_setg(errp, "File descriptor named '%s' has not been found", fdname);
1728 static void monitor_fdset_cleanup(MonFdset *mon_fdset)
1730 MonFdsetFd *mon_fdset_fd;
1731 MonFdsetFd *mon_fdset_fd_next;
1733 QLIST_FOREACH_SAFE(mon_fdset_fd, &mon_fdset->fds, next, mon_fdset_fd_next) {
1734 if ((mon_fdset_fd->removed ||
1735 (QLIST_EMPTY(&mon_fdset->dup_fds) && mon_refcount == 0)) &&
1736 runstate_is_running()) {
1737 close(mon_fdset_fd->fd);
1738 g_free(mon_fdset_fd->opaque);
1739 QLIST_REMOVE(mon_fdset_fd, next);
1740 g_free(mon_fdset_fd);
1744 if (QLIST_EMPTY(&mon_fdset->fds) && QLIST_EMPTY(&mon_fdset->dup_fds)) {
1745 QLIST_REMOVE(mon_fdset, next);
1750 static void monitor_fdsets_cleanup(void)
1752 MonFdset *mon_fdset;
1753 MonFdset *mon_fdset_next;
1755 QLIST_FOREACH_SAFE(mon_fdset, &mon_fdsets, next, mon_fdset_next) {
1756 monitor_fdset_cleanup(mon_fdset);
1760 AddfdInfo *qmp_add_fd(bool has_fdset_id, int64_t fdset_id, bool has_opaque,
1761 const char *opaque, Error **errp)
1764 Monitor *mon = cur_mon;
1767 fd = qemu_chr_fe_get_msgfd(mon->chr);
1769 error_setg(errp, QERR_FD_NOT_SUPPLIED);
1773 fdinfo = monitor_fdset_add_fd(fd, has_fdset_id, fdset_id,
1774 has_opaque, opaque, errp);
1786 void qmp_remove_fd(int64_t fdset_id, bool has_fd, int64_t fd, Error **errp)
1788 MonFdset *mon_fdset;
1789 MonFdsetFd *mon_fdset_fd;
1792 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
1793 if (mon_fdset->id != fdset_id) {
1796 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
1798 if (mon_fdset_fd->fd != fd) {
1801 mon_fdset_fd->removed = true;
1804 mon_fdset_fd->removed = true;
1807 if (has_fd && !mon_fdset_fd) {
1810 monitor_fdset_cleanup(mon_fdset);
1816 snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64 ", fd:%" PRId64,
1819 snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64, fdset_id);
1821 error_setg(errp, QERR_FD_NOT_FOUND, fd_str);
1824 FdsetInfoList *qmp_query_fdsets(Error **errp)
1826 MonFdset *mon_fdset;
1827 MonFdsetFd *mon_fdset_fd;
1828 FdsetInfoList *fdset_list = NULL;
1830 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
1831 FdsetInfoList *fdset_info = g_malloc0(sizeof(*fdset_info));
1832 FdsetFdInfoList *fdsetfd_list = NULL;
1834 fdset_info->value = g_malloc0(sizeof(*fdset_info->value));
1835 fdset_info->value->fdset_id = mon_fdset->id;
1837 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
1838 FdsetFdInfoList *fdsetfd_info;
1840 fdsetfd_info = g_malloc0(sizeof(*fdsetfd_info));
1841 fdsetfd_info->value = g_malloc0(sizeof(*fdsetfd_info->value));
1842 fdsetfd_info->value->fd = mon_fdset_fd->fd;
1843 if (mon_fdset_fd->opaque) {
1844 fdsetfd_info->value->has_opaque = true;
1845 fdsetfd_info->value->opaque = g_strdup(mon_fdset_fd->opaque);
1847 fdsetfd_info->value->has_opaque = false;
1850 fdsetfd_info->next = fdsetfd_list;
1851 fdsetfd_list = fdsetfd_info;
1854 fdset_info->value->fds = fdsetfd_list;
1856 fdset_info->next = fdset_list;
1857 fdset_list = fdset_info;
1863 AddfdInfo *monitor_fdset_add_fd(int fd, bool has_fdset_id, int64_t fdset_id,
1864 bool has_opaque, const char *opaque,
1867 MonFdset *mon_fdset = NULL;
1868 MonFdsetFd *mon_fdset_fd;
1872 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
1873 /* Break if match found or match impossible due to ordering by ID */
1874 if (fdset_id <= mon_fdset->id) {
1875 if (fdset_id < mon_fdset->id) {
1883 if (mon_fdset == NULL) {
1884 int64_t fdset_id_prev = -1;
1885 MonFdset *mon_fdset_cur = QLIST_FIRST(&mon_fdsets);
1889 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "fdset-id",
1890 "a non-negative value");
1893 /* Use specified fdset ID */
1894 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
1895 mon_fdset_cur = mon_fdset;
1896 if (fdset_id < mon_fdset_cur->id) {
1901 /* Use first available fdset ID */
1902 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
1903 mon_fdset_cur = mon_fdset;
1904 if (fdset_id_prev == mon_fdset_cur->id - 1) {
1905 fdset_id_prev = mon_fdset_cur->id;
1912 mon_fdset = g_malloc0(sizeof(*mon_fdset));
1914 mon_fdset->id = fdset_id;
1916 mon_fdset->id = fdset_id_prev + 1;
1919 /* The fdset list is ordered by fdset ID */
1920 if (!mon_fdset_cur) {
1921 QLIST_INSERT_HEAD(&mon_fdsets, mon_fdset, next);
1922 } else if (mon_fdset->id < mon_fdset_cur->id) {
1923 QLIST_INSERT_BEFORE(mon_fdset_cur, mon_fdset, next);
1925 QLIST_INSERT_AFTER(mon_fdset_cur, mon_fdset, next);
1929 mon_fdset_fd = g_malloc0(sizeof(*mon_fdset_fd));
1930 mon_fdset_fd->fd = fd;
1931 mon_fdset_fd->removed = false;
1933 mon_fdset_fd->opaque = g_strdup(opaque);
1935 QLIST_INSERT_HEAD(&mon_fdset->fds, mon_fdset_fd, next);
1937 fdinfo = g_malloc0(sizeof(*fdinfo));
1938 fdinfo->fdset_id = mon_fdset->id;
1939 fdinfo->fd = mon_fdset_fd->fd;
1944 int monitor_fdset_get_fd(int64_t fdset_id, int flags)
1947 MonFdset *mon_fdset;
1948 MonFdsetFd *mon_fdset_fd;
1951 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
1952 if (mon_fdset->id != fdset_id) {
1955 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
1956 mon_fd_flags = fcntl(mon_fdset_fd->fd, F_GETFL);
1957 if (mon_fd_flags == -1) {
1961 if ((flags & O_ACCMODE) == (mon_fd_flags & O_ACCMODE)) {
1962 return mon_fdset_fd->fd;
1974 int monitor_fdset_dup_fd_add(int64_t fdset_id, int dup_fd)
1976 MonFdset *mon_fdset;
1977 MonFdsetFd *mon_fdset_fd_dup;
1979 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
1980 if (mon_fdset->id != fdset_id) {
1983 QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
1984 if (mon_fdset_fd_dup->fd == dup_fd) {
1988 mon_fdset_fd_dup = g_malloc0(sizeof(*mon_fdset_fd_dup));
1989 mon_fdset_fd_dup->fd = dup_fd;
1990 QLIST_INSERT_HEAD(&mon_fdset->dup_fds, mon_fdset_fd_dup, next);
1996 static int monitor_fdset_dup_fd_find_remove(int dup_fd, bool remove)
1998 MonFdset *mon_fdset;
1999 MonFdsetFd *mon_fdset_fd_dup;
2001 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2002 QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
2003 if (mon_fdset_fd_dup->fd == dup_fd) {
2005 QLIST_REMOVE(mon_fdset_fd_dup, next);
2006 if (QLIST_EMPTY(&mon_fdset->dup_fds)) {
2007 monitor_fdset_cleanup(mon_fdset);
2011 return mon_fdset->id;
2019 int monitor_fdset_dup_fd_find(int dup_fd)
2021 return monitor_fdset_dup_fd_find_remove(dup_fd, false);
2024 void monitor_fdset_dup_fd_remove(int dup_fd)
2026 monitor_fdset_dup_fd_find_remove(dup_fd, true);
2029 int monitor_fd_param(Monitor *mon, const char *fdname, Error **errp)
2032 Error *local_err = NULL;
2034 if (!qemu_isdigit(fdname[0]) && mon) {
2035 fd = monitor_get_fd(mon, fdname, &local_err);
2037 fd = qemu_parse_fd(fdname);
2039 error_setg(&local_err, "Invalid file descriptor number '%s'",
2044 error_propagate(errp, local_err);
2053 /* Please update hmp-commands.hx when adding or changing commands */
2054 static mon_cmd_t info_cmds[] = {
2055 #include "hmp-commands-info.h"
2059 /* mon_cmds and info_cmds would be sorted at runtime */
2060 static mon_cmd_t mon_cmds[] = {
2061 #include "hmp-commands.h"
2065 static const mon_cmd_t qmp_cmds[] = {
2066 #include "qmp-commands-old.h"
2070 /*******************************************************************/
2072 static const char *pch;
2073 static sigjmp_buf expr_env;
2076 static void GCC_FMT_ATTR(2, 3) QEMU_NORETURN
2077 expr_error(Monitor *mon, const char *fmt, ...)
2081 monitor_vprintf(mon, fmt, ap);
2082 monitor_printf(mon, "\n");
2084 siglongjmp(expr_env, 1);
2087 /* return 0 if OK, -1 if not found */
2088 static int get_monitor_def(target_long *pval, const char *name)
2090 const MonitorDef *md = target_monitor_defs();
2097 for(; md->name != NULL; md++) {
2098 if (compare_cmd(name, md->name)) {
2099 if (md->get_value) {
2100 *pval = md->get_value(md, md->offset);
2102 CPUArchState *env = mon_get_cpu_env();
2103 ptr = (uint8_t *)env + md->offset;
2106 *pval = *(int32_t *)ptr;
2109 *pval = *(target_long *)ptr;
2122 static void next(void)
2126 while (qemu_isspace(*pch))
2131 static int64_t expr_sum(Monitor *mon);
2133 static int64_t expr_unary(Monitor *mon)
2142 n = expr_unary(mon);
2146 n = -expr_unary(mon);
2150 n = ~expr_unary(mon);
2156 expr_error(mon, "')' expected");
2163 expr_error(mon, "character constant expected");
2167 expr_error(mon, "missing terminating \' character");
2177 while ((*pch >= 'a' && *pch <= 'z') ||
2178 (*pch >= 'A' && *pch <= 'Z') ||
2179 (*pch >= '0' && *pch <= '9') ||
2180 *pch == '_' || *pch == '.') {
2181 if ((q - buf) < sizeof(buf) - 1)
2185 while (qemu_isspace(*pch))
2188 ret = get_monitor_def(®, buf);
2190 expr_error(mon, "unknown register");
2195 expr_error(mon, "unexpected end of expression");
2200 n = strtoull(pch, &p, 0);
2201 if (errno == ERANGE) {
2202 expr_error(mon, "number too large");
2205 expr_error(mon, "invalid char '%c' in expression", *p);
2208 while (qemu_isspace(*pch))
2216 static int64_t expr_prod(Monitor *mon)
2221 val = expr_unary(mon);
2224 if (op != '*' && op != '/' && op != '%')
2227 val2 = expr_unary(mon);
2236 expr_error(mon, "division by zero");
2247 static int64_t expr_logic(Monitor *mon)
2252 val = expr_prod(mon);
2255 if (op != '&' && op != '|' && op != '^')
2258 val2 = expr_prod(mon);
2275 static int64_t expr_sum(Monitor *mon)
2280 val = expr_logic(mon);
2283 if (op != '+' && op != '-')
2286 val2 = expr_logic(mon);
2295 static int get_expr(Monitor *mon, int64_t *pval, const char **pp)
2298 if (sigsetjmp(expr_env, 0)) {
2302 while (qemu_isspace(*pch))
2304 *pval = expr_sum(mon);
2309 static int get_double(Monitor *mon, double *pval, const char **pp)
2311 const char *p = *pp;
2315 d = strtod(p, &tailp);
2317 monitor_printf(mon, "Number expected\n");
2320 if (d != d || d - d != 0) {
2321 /* NaN or infinity */
2322 monitor_printf(mon, "Bad number\n");
2331 * Store the command-name in cmdname, and return a pointer to
2332 * the remaining of the command string.
2334 static const char *get_command_name(const char *cmdline,
2335 char *cmdname, size_t nlen)
2338 const char *p, *pstart;
2341 while (qemu_isspace(*p))
2346 while (*p != '\0' && *p != '/' && !qemu_isspace(*p))
2351 memcpy(cmdname, pstart, len);
2352 cmdname[len] = '\0';
2357 * Read key of 'type' into 'key' and return the current
2360 static char *key_get_info(const char *type, char **key)
2368 p = strchr(type, ':');
2375 str = g_malloc(len + 1);
2376 memcpy(str, type, len);
2383 static int default_fmt_format = 'x';
2384 static int default_fmt_size = 4;
2386 static int is_valid_option(const char *c, const char *typestr)
2394 typestr = strstr(typestr, option);
2395 return (typestr != NULL);
2398 static const mon_cmd_t *search_dispatch_table(const mon_cmd_t *disp_table,
2399 const char *cmdname)
2401 const mon_cmd_t *cmd;
2403 for (cmd = disp_table; cmd->name != NULL; cmd++) {
2404 if (compare_cmd(cmdname, cmd->name)) {
2412 static const mon_cmd_t *qmp_find_cmd(const char *cmdname)
2414 return search_dispatch_table(qmp_cmds, cmdname);
2418 * Parse command name from @cmdp according to command table @table.
2419 * If blank, return NULL.
2420 * Else, if no valid command can be found, report to @mon, and return
2422 * Else, change @cmdp to point right behind the name, and return its
2423 * command table entry.
2424 * Do not assume the return value points into @table! It doesn't when
2425 * the command is found in a sub-command table.
2427 static const mon_cmd_t *monitor_parse_command(Monitor *mon,
2432 const mon_cmd_t *cmd;
2435 /* extract the command name */
2436 p = get_command_name(*cmdp, cmdname, sizeof(cmdname));
2440 cmd = search_dispatch_table(table, cmdname);
2442 monitor_printf(mon, "unknown command: '%.*s'\n",
2443 (int)(p - *cmdp), *cmdp);
2447 /* filter out following useless space */
2448 while (qemu_isspace(*p)) {
2453 /* search sub command */
2454 if (cmd->sub_table != NULL && *p != '\0') {
2455 return monitor_parse_command(mon, cmdp, cmd->sub_table);
2462 * Parse arguments for @cmd.
2463 * If it can't be parsed, report to @mon, and return NULL.
2464 * Else, insert command arguments into a QDict, and return it.
2465 * Note: On success, caller has to free the QDict structure.
2468 static QDict *monitor_parse_arguments(Monitor *mon,
2470 const mon_cmd_t *cmd)
2472 const char *typestr;
2475 const char *p = *endp;
2477 QDict *qdict = qdict_new();
2479 /* parse the parameters */
2480 typestr = cmd->args_type;
2482 typestr = key_get_info(typestr, &key);
2494 while (qemu_isspace(*p))
2496 if (*typestr == '?') {
2499 /* no optional string: NULL argument */
2503 ret = get_str(buf, sizeof(buf), &p);
2507 monitor_printf(mon, "%s: filename expected\n",
2511 monitor_printf(mon, "%s: block device name expected\n",
2515 monitor_printf(mon, "%s: string expected\n", cmd->name);
2520 qdict_put(qdict, key, qstring_from_str(buf));
2525 QemuOptsList *opts_list;
2528 opts_list = qemu_find_opts(key);
2529 if (!opts_list || opts_list->desc->name) {
2532 while (qemu_isspace(*p)) {
2537 if (get_str(buf, sizeof(buf), &p) < 0) {
2540 opts = qemu_opts_parse_noisily(opts_list, buf, true);
2544 qemu_opts_to_qdict(opts, qdict);
2545 qemu_opts_del(opts);
2550 int count, format, size;
2552 while (qemu_isspace(*p))
2558 if (qemu_isdigit(*p)) {
2560 while (qemu_isdigit(*p)) {
2561 count = count * 10 + (*p - '0');
2599 if (*p != '\0' && !qemu_isspace(*p)) {
2600 monitor_printf(mon, "invalid char in format: '%c'\n",
2605 format = default_fmt_format;
2606 if (format != 'i') {
2607 /* for 'i', not specifying a size gives -1 as size */
2609 size = default_fmt_size;
2610 default_fmt_size = size;
2612 default_fmt_format = format;
2615 format = default_fmt_format;
2616 if (format != 'i') {
2617 size = default_fmt_size;
2622 qdict_put(qdict, "count", qint_from_int(count));
2623 qdict_put(qdict, "format", qint_from_int(format));
2624 qdict_put(qdict, "size", qint_from_int(size));
2633 while (qemu_isspace(*p))
2635 if (*typestr == '?' || *typestr == '.') {
2636 if (*typestr == '?') {
2644 while (qemu_isspace(*p))
2653 if (get_expr(mon, &val, &p))
2655 /* Check if 'i' is greater than 32-bit */
2656 if ((c == 'i') && ((val >> 32) & 0xffffffff)) {
2657 monitor_printf(mon, "\'%s\' has failed: ", cmd->name);
2658 monitor_printf(mon, "integer is for 32-bit values\n");
2660 } else if (c == 'M') {
2662 monitor_printf(mon, "enter a positive value\n");
2667 qdict_put(qdict, key, qint_from_int(val));
2675 while (qemu_isspace(*p)) {
2678 if (*typestr == '?') {
2684 val = strtosz(p, &end);
2686 monitor_printf(mon, "invalid size\n");
2689 qdict_put(qdict, key, qint_from_int(val));
2697 while (qemu_isspace(*p))
2699 if (*typestr == '?') {
2705 if (get_double(mon, &val, &p) < 0) {
2708 if (p[0] && p[1] == 's') {
2711 val /= 1e3; p += 2; break;
2713 val /= 1e6; p += 2; break;
2715 val /= 1e9; p += 2; break;
2718 if (*p && !qemu_isspace(*p)) {
2719 monitor_printf(mon, "Unknown unit suffix\n");
2722 qdict_put(qdict, key, qfloat_from_double(val));
2730 while (qemu_isspace(*p)) {
2734 while (qemu_isgraph(*p)) {
2737 if (p - beg == 2 && !memcmp(beg, "on", p - beg)) {
2739 } else if (p - beg == 3 && !memcmp(beg, "off", p - beg)) {
2742 monitor_printf(mon, "Expected 'on' or 'off'\n");
2745 qdict_put(qdict, key, qbool_from_bool(val));
2750 const char *tmp = p;
2757 while (qemu_isspace(*p))
2762 if(!is_valid_option(p, typestr)) {
2764 monitor_printf(mon, "%s: unsupported option -%c\n",
2776 qdict_put(qdict, key, qbool_from_bool(true));
2783 /* package all remaining string */
2786 while (qemu_isspace(*p)) {
2789 if (*typestr == '?') {
2792 /* no remaining string: NULL argument */
2798 monitor_printf(mon, "%s: string expected\n",
2802 qdict_put(qdict, key, qstring_from_str(p));
2808 monitor_printf(mon, "%s: unknown type '%c'\n", cmd->name, c);
2814 /* check that all arguments were parsed */
2815 while (qemu_isspace(*p))
2818 monitor_printf(mon, "%s: extraneous characters at the end of line\n",
2831 static void handle_hmp_command(Monitor *mon, const char *cmdline)
2834 const mon_cmd_t *cmd;
2836 cmd = monitor_parse_command(mon, &cmdline, mon->cmd_table);
2841 qdict = monitor_parse_arguments(mon, &cmdline, cmd);
2843 monitor_printf(mon, "Try \"help %s\" for more information\n",
2848 cmd->mhandler.cmd(mon, qdict);
2852 static void cmd_completion(Monitor *mon, const char *name, const char *list)
2854 const char *p, *pstart;
2863 p = pstart + strlen(pstart);
2865 if (len > sizeof(cmd) - 2)
2866 len = sizeof(cmd) - 2;
2867 memcpy(cmd, pstart, len);
2869 if (name[0] == '\0' || !strncmp(name, cmd, strlen(name))) {
2870 readline_add_completion(mon->rs, cmd);
2878 static void file_completion(Monitor *mon, const char *input)
2883 char file[1024], file_prefix[1024];
2887 p = strrchr(input, '/');
2890 pstrcpy(file_prefix, sizeof(file_prefix), input);
2891 pstrcpy(path, sizeof(path), ".");
2893 input_path_len = p - input + 1;
2894 memcpy(path, input, input_path_len);
2895 if (input_path_len > sizeof(path) - 1)
2896 input_path_len = sizeof(path) - 1;
2897 path[input_path_len] = '\0';
2898 pstrcpy(file_prefix, sizeof(file_prefix), p + 1);
2901 ffs = opendir(path);
2910 if (strcmp(d->d_name, ".") == 0 || strcmp(d->d_name, "..") == 0) {
2914 if (strstart(d->d_name, file_prefix, NULL)) {
2915 memcpy(file, input, input_path_len);
2916 if (input_path_len < sizeof(file))
2917 pstrcpy(file + input_path_len, sizeof(file) - input_path_len,
2919 /* stat the file to find out if it's a directory.
2920 * In that case add a slash to speed up typing long paths
2922 if (stat(file, &sb) == 0 && S_ISDIR(sb.st_mode)) {
2923 pstrcat(file, sizeof(file), "/");
2925 readline_add_completion(mon->rs, file);
2931 static const char *next_arg_type(const char *typestr)
2933 const char *p = strchr(typestr, ':');
2934 return (p != NULL ? ++p : typestr);
2937 static void add_completion_option(ReadLineState *rs, const char *str,
2940 if (!str || !option) {
2943 if (!strncmp(option, str, strlen(str))) {
2944 readline_add_completion(rs, option);
2948 void chardev_add_completion(ReadLineState *rs, int nb_args, const char *str)
2951 ChardevBackendInfoList *list, *start;
2957 readline_set_completion_index(rs, len);
2959 start = list = qmp_query_chardev_backends(NULL);
2961 const char *chr_name = list->value->name;
2963 if (!strncmp(chr_name, str, len)) {
2964 readline_add_completion(rs, chr_name);
2968 qapi_free_ChardevBackendInfoList(start);
2971 void netdev_add_completion(ReadLineState *rs, int nb_args, const char *str)
2980 readline_set_completion_index(rs, len);
2981 for (i = 0; NetClientOptionsKind_lookup[i]; i++) {
2982 add_completion_option(rs, str, NetClientOptionsKind_lookup[i]);
2986 void device_add_completion(ReadLineState *rs, int nb_args, const char *str)
2996 readline_set_completion_index(rs, len);
2997 list = elt = object_class_get_list(TYPE_DEVICE, false);
3000 DeviceClass *dc = OBJECT_CLASS_CHECK(DeviceClass, elt->data,
3002 name = object_class_get_name(OBJECT_CLASS(dc));
3004 if (!dc->cannot_instantiate_with_device_add_yet
3005 && !strncmp(name, str, len)) {
3006 readline_add_completion(rs, name);
3013 void object_add_completion(ReadLineState *rs, int nb_args, const char *str)
3023 readline_set_completion_index(rs, len);
3024 list = elt = object_class_get_list(TYPE_USER_CREATABLE, false);
3028 name = object_class_get_name(OBJECT_CLASS(elt->data));
3029 if (!strncmp(name, str, len) && strcmp(name, TYPE_USER_CREATABLE)) {
3030 readline_add_completion(rs, name);
3037 static void peripheral_device_del_completion(ReadLineState *rs,
3038 const char *str, size_t len)
3040 Object *peripheral = container_get(qdev_get_machine(), "/peripheral");
3041 GSList *list, *item;
3043 list = qdev_build_hotpluggable_device_list(peripheral);
3048 for (item = list; item; item = g_slist_next(item)) {
3049 DeviceState *dev = item->data;
3051 if (dev->id && !strncmp(str, dev->id, len)) {
3052 readline_add_completion(rs, dev->id);
3059 void chardev_remove_completion(ReadLineState *rs, int nb_args, const char *str)
3062 ChardevInfoList *list, *start;
3068 readline_set_completion_index(rs, len);
3070 start = list = qmp_query_chardev(NULL);
3072 ChardevInfo *chr = list->value;
3074 if (!strncmp(chr->label, str, len)) {
3075 readline_add_completion(rs, chr->label);
3079 qapi_free_ChardevInfoList(start);
3082 static void ringbuf_completion(ReadLineState *rs, const char *str)
3085 ChardevInfoList *list, *start;
3088 readline_set_completion_index(rs, len);
3090 start = list = qmp_query_chardev(NULL);
3092 ChardevInfo *chr_info = list->value;
3094 if (!strncmp(chr_info->label, str, len)) {
3095 CharDriverState *chr = qemu_chr_find(chr_info->label);
3096 if (chr && chr_is_ringbuf(chr)) {
3097 readline_add_completion(rs, chr_info->label);
3102 qapi_free_ChardevInfoList(start);
3105 void ringbuf_write_completion(ReadLineState *rs, int nb_args, const char *str)
3110 ringbuf_completion(rs, str);
3113 void device_del_completion(ReadLineState *rs, int nb_args, const char *str)
3122 readline_set_completion_index(rs, len);
3123 peripheral_device_del_completion(rs, str, len);
3126 void object_del_completion(ReadLineState *rs, int nb_args, const char *str)
3128 ObjectPropertyInfoList *list, *start;
3135 readline_set_completion_index(rs, len);
3137 start = list = qmp_qom_list("/objects", NULL);
3139 ObjectPropertyInfo *info = list->value;
3141 if (!strncmp(info->type, "child<", 5)
3142 && !strncmp(info->name, str, len)) {
3143 readline_add_completion(rs, info->name);
3147 qapi_free_ObjectPropertyInfoList(start);
3150 void sendkey_completion(ReadLineState *rs, int nb_args, const char *str)
3159 sep = strrchr(str, '-');
3164 readline_set_completion_index(rs, len);
3165 for (i = 0; i < Q_KEY_CODE_MAX; i++) {
3166 if (!strncmp(str, QKeyCode_lookup[i], len)) {
3167 readline_add_completion(rs, QKeyCode_lookup[i]);
3172 void set_link_completion(ReadLineState *rs, int nb_args, const char *str)
3177 readline_set_completion_index(rs, len);
3179 NetClientState *ncs[MAX_QUEUE_NUM];
3181 count = qemu_find_net_clients_except(NULL, ncs,
3182 NET_CLIENT_OPTIONS_KIND_NONE,
3184 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3185 const char *name = ncs[i]->name;
3186 if (!strncmp(str, name, len)) {
3187 readline_add_completion(rs, name);
3190 } else if (nb_args == 3) {
3191 add_completion_option(rs, str, "on");
3192 add_completion_option(rs, str, "off");
3196 void netdev_del_completion(ReadLineState *rs, int nb_args, const char *str)
3199 NetClientState *ncs[MAX_QUEUE_NUM];
3206 readline_set_completion_index(rs, len);
3207 count = qemu_find_net_clients_except(NULL, ncs, NET_CLIENT_OPTIONS_KIND_NIC,
3209 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3211 const char *name = ncs[i]->name;
3212 if (strncmp(str, name, len)) {
3215 opts = qemu_opts_find(qemu_find_opts_err("netdev", NULL), name);
3217 readline_add_completion(rs, name);
3222 void trace_event_completion(ReadLineState *rs, int nb_args, const char *str)
3227 readline_set_completion_index(rs, len);
3230 for (id = 0; id < trace_event_count(); id++) {
3231 const char *event_name = trace_event_get_name(trace_event_id(id));
3232 if (!strncmp(str, event_name, len)) {
3233 readline_add_completion(rs, event_name);
3236 } else if (nb_args == 3) {
3237 add_completion_option(rs, str, "on");
3238 add_completion_option(rs, str, "off");
3242 void watchdog_action_completion(ReadLineState *rs, int nb_args, const char *str)
3249 readline_set_completion_index(rs, strlen(str));
3250 for (i = 0; WatchdogExpirationAction_lookup[i]; i++) {
3251 add_completion_option(rs, str, WatchdogExpirationAction_lookup[i]);
3255 void migrate_set_capability_completion(ReadLineState *rs, int nb_args,
3261 readline_set_completion_index(rs, len);
3264 for (i = 0; i < MIGRATION_CAPABILITY_MAX; i++) {
3265 const char *name = MigrationCapability_lookup[i];
3266 if (!strncmp(str, name, len)) {
3267 readline_add_completion(rs, name);
3270 } else if (nb_args == 3) {
3271 add_completion_option(rs, str, "on");
3272 add_completion_option(rs, str, "off");
3276 void migrate_set_parameter_completion(ReadLineState *rs, int nb_args,
3282 readline_set_completion_index(rs, len);
3285 for (i = 0; i < MIGRATION_PARAMETER_MAX; i++) {
3286 const char *name = MigrationParameter_lookup[i];
3287 if (!strncmp(str, name, len)) {
3288 readline_add_completion(rs, name);
3294 void host_net_add_completion(ReadLineState *rs, int nb_args, const char *str)
3302 readline_set_completion_index(rs, len);
3303 for (i = 0; host_net_devices[i]; i++) {
3304 if (!strncmp(host_net_devices[i], str, len)) {
3305 readline_add_completion(rs, host_net_devices[i]);
3310 void host_net_remove_completion(ReadLineState *rs, int nb_args, const char *str)
3312 NetClientState *ncs[MAX_QUEUE_NUM];
3316 readline_set_completion_index(rs, len);
3318 count = qemu_find_net_clients_except(NULL, ncs,
3319 NET_CLIENT_OPTIONS_KIND_NONE,
3321 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3325 if (net_hub_id_for_client(ncs[i], &id)) {
3328 snprintf(name, sizeof(name), "%d", id);
3329 if (!strncmp(str, name, len)) {
3330 readline_add_completion(rs, name);
3334 } else if (nb_args == 3) {
3335 count = qemu_find_net_clients_except(NULL, ncs,
3336 NET_CLIENT_OPTIONS_KIND_NIC,
3338 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3342 if (ncs[i]->info->type == NET_CLIENT_OPTIONS_KIND_HUBPORT ||
3343 net_hub_id_for_client(ncs[i], &id)) {
3346 name = ncs[i]->name;
3347 if (!strncmp(str, name, len)) {
3348 readline_add_completion(rs, name);
3355 static void vm_completion(ReadLineState *rs, const char *str)
3358 BlockDriverState *bs = NULL;
3361 readline_set_completion_index(rs, len);
3362 while ((bs = bdrv_next(bs))) {
3363 SnapshotInfoList *snapshots, *snapshot;
3365 if (!bdrv_can_snapshot(bs)) {
3368 if (bdrv_query_snapshot_info_list(bs, &snapshots, NULL)) {
3371 snapshot = snapshots;
3373 char *completion = snapshot->value->name;
3374 if (!strncmp(str, completion, len)) {
3375 readline_add_completion(rs, completion);
3377 completion = snapshot->value->id;
3378 if (!strncmp(str, completion, len)) {
3379 readline_add_completion(rs, completion);
3381 snapshot = snapshot->next;
3383 qapi_free_SnapshotInfoList(snapshots);
3388 void delvm_completion(ReadLineState *rs, int nb_args, const char *str)
3391 vm_completion(rs, str);
3395 void loadvm_completion(ReadLineState *rs, int nb_args, const char *str)
3398 vm_completion(rs, str);
3402 static void monitor_find_completion_by_table(Monitor *mon,
3403 const mon_cmd_t *cmd_table,
3407 const char *cmdname;
3409 const char *ptype, *str, *name;
3410 const mon_cmd_t *cmd;
3411 BlockDriverState *bs;
3414 /* command completion */
3419 readline_set_completion_index(mon->rs, strlen(cmdname));
3420 for (cmd = cmd_table; cmd->name != NULL; cmd++) {
3421 cmd_completion(mon, cmdname, cmd->name);
3424 /* find the command */
3425 for (cmd = cmd_table; cmd->name != NULL; cmd++) {
3426 if (compare_cmd(args[0], cmd->name)) {
3434 if (cmd->sub_table) {
3435 /* do the job again */
3436 monitor_find_completion_by_table(mon, cmd->sub_table,
3437 &args[1], nb_args - 1);
3440 if (cmd->command_completion) {
3441 cmd->command_completion(mon->rs, nb_args, args[nb_args - 1]);
3445 ptype = next_arg_type(cmd->args_type);
3446 for(i = 0; i < nb_args - 2; i++) {
3447 if (*ptype != '\0') {
3448 ptype = next_arg_type(ptype);
3449 while (*ptype == '?')
3450 ptype = next_arg_type(ptype);
3453 str = args[nb_args - 1];
3454 while (*ptype == '-' && ptype[1] != '\0') {
3455 ptype = next_arg_type(ptype);
3459 /* file completion */
3460 readline_set_completion_index(mon->rs, strlen(str));
3461 file_completion(mon, str);
3464 /* block device name completion */
3465 readline_set_completion_index(mon->rs, strlen(str));
3466 for (bs = bdrv_next(NULL); bs; bs = bdrv_next(bs)) {
3467 name = bdrv_get_device_name(bs);
3468 if (str[0] == '\0' ||
3469 !strncmp(name, str, strlen(str))) {
3470 readline_add_completion(mon->rs, name);
3476 if (!strcmp(cmd->name, "help|?")) {
3477 monitor_find_completion_by_table(mon, cmd_table,
3478 &args[1], nb_args - 1);
3487 static void monitor_find_completion(void *opaque,
3488 const char *cmdline)
3490 Monitor *mon = opaque;
3491 char *args[MAX_ARGS];
3494 /* 1. parse the cmdline */
3495 if (parse_cmdline(cmdline, &nb_args, args) < 0) {
3499 /* if the line ends with a space, it means we want to complete the
3501 len = strlen(cmdline);
3502 if (len > 0 && qemu_isspace(cmdline[len - 1])) {
3503 if (nb_args >= MAX_ARGS) {
3506 args[nb_args++] = g_strdup("");
3509 /* 2. auto complete according to args */
3510 monitor_find_completion_by_table(mon, mon->cmd_table, args, nb_args);
3513 free_cmdline_args(args, nb_args);
3516 static int monitor_can_read(void *opaque)
3518 Monitor *mon = opaque;
3520 return (mon->suspend_cnt == 0) ? 1 : 0;
3523 static bool invalid_qmp_mode(const Monitor *mon, const mon_cmd_t *cmd,
3526 bool is_cap = cmd->mhandler.cmd_new == qmp_capabilities;
3528 if (is_cap && mon->qmp.in_command_mode) {
3529 error_set(errp, ERROR_CLASS_COMMAND_NOT_FOUND,
3530 "Capabilities negotiation is already complete, command "
3531 "'%s' ignored", cmd->name);
3534 if (!is_cap && !mon->qmp.in_command_mode) {
3535 error_set(errp, ERROR_CLASS_COMMAND_NOT_FOUND,
3536 "Expecting capabilities negotiation with "
3537 "'qmp_capabilities' before command '%s'", cmd->name);
3544 * Argument validation rules:
3546 * 1. The argument must exist in cmd_args qdict
3547 * 2. The argument type must be the expected one
3549 * Special case: If the argument doesn't exist in cmd_args and
3550 * the QMP_ACCEPT_UNKNOWNS flag is set, then the
3551 * checking is skipped for it.
3553 static void check_client_args_type(const QDict *client_args,
3554 const QDict *cmd_args, int flags,
3557 const QDictEntry *ent;
3559 for (ent = qdict_first(client_args); ent;ent = qdict_next(client_args,ent)){
3562 const QObject *client_arg = qdict_entry_value(ent);
3563 const char *client_arg_name = qdict_entry_key(ent);
3565 obj = qdict_get(cmd_args, client_arg_name);
3567 if (flags & QMP_ACCEPT_UNKNOWNS) {
3568 /* handler accepts unknowns */
3571 /* client arg doesn't exist */
3572 error_setg(errp, QERR_INVALID_PARAMETER, client_arg_name);
3576 arg_type = qobject_to_qstring(obj);
3577 assert(arg_type != NULL);
3579 /* check if argument's type is correct */
3580 switch (qstring_get_str(arg_type)[0]) {
3584 if (qobject_type(client_arg) != QTYPE_QSTRING) {
3585 error_setg(errp, QERR_INVALID_PARAMETER_TYPE,
3586 client_arg_name, "string");
3594 if (qobject_type(client_arg) != QTYPE_QINT) {
3595 error_setg(errp, QERR_INVALID_PARAMETER_TYPE,
3596 client_arg_name, "int");
3601 if (qobject_type(client_arg) != QTYPE_QINT &&
3602 qobject_type(client_arg) != QTYPE_QFLOAT) {
3603 error_setg(errp, QERR_INVALID_PARAMETER_TYPE,
3604 client_arg_name, "number");
3610 if (qobject_type(client_arg) != QTYPE_QBOOL) {
3611 error_setg(errp, QERR_INVALID_PARAMETER_TYPE,
3612 client_arg_name, "bool");
3617 assert(flags & QMP_ACCEPT_UNKNOWNS);
3620 /* Any QObject can be passed. */
3625 * These types are not supported by QMP and thus are not
3626 * handled here. Fall through.
3635 * - Check if the client has passed all mandatory args
3636 * - Set special flags for argument validation
3638 static void check_mandatory_args(const QDict *cmd_args,
3639 const QDict *client_args, int *flags,
3642 const QDictEntry *ent;
3644 for (ent = qdict_first(cmd_args); ent; ent = qdict_next(cmd_args, ent)) {
3645 const char *cmd_arg_name = qdict_entry_key(ent);
3646 QString *type = qobject_to_qstring(qdict_entry_value(ent));
3647 assert(type != NULL);
3649 if (qstring_get_str(type)[0] == 'O') {
3650 assert((*flags & QMP_ACCEPT_UNKNOWNS) == 0);
3651 *flags |= QMP_ACCEPT_UNKNOWNS;
3652 } else if (qstring_get_str(type)[0] != '-' &&
3653 qstring_get_str(type)[1] != '?' &&
3654 !qdict_haskey(client_args, cmd_arg_name)) {
3655 error_setg(errp, QERR_MISSING_PARAMETER, cmd_arg_name);
3661 static QDict *qdict_from_args_type(const char *args_type)
3665 QString *key, *type, *cur_qs;
3667 assert(args_type != NULL);
3669 qdict = qdict_new();
3671 if (args_type == NULL || args_type[0] == '\0') {
3672 /* no args, empty qdict */
3676 key = qstring_new();
3677 type = qstring_new();
3682 switch (args_type[i]) {
3685 qdict_put(qdict, qstring_get_str(key), type);
3687 if (args_type[i] == '\0') {
3690 type = qstring_new(); /* qdict has ref */
3691 cur_qs = key = qstring_new();
3697 qstring_append_chr(cur_qs, args_type[i]);
3707 * Client argument checking rules:
3709 * 1. Client must provide all mandatory arguments
3710 * 2. Each argument provided by the client must be expected
3711 * 3. Each argument provided by the client must have the type expected
3714 static void qmp_check_client_args(const mon_cmd_t *cmd, QDict *client_args,
3721 cmd_args = qdict_from_args_type(cmd->args_type);
3724 check_mandatory_args(cmd_args, client_args, &flags, &err);
3729 check_client_args_type(client_args, cmd_args, flags, &err);
3732 error_propagate(errp, err);
3737 * Input object checking rules
3739 * 1. Input object must be a dict
3740 * 2. The "execute" key must exist
3741 * 3. The "execute" key must be a string
3742 * 4. If the "arguments" key exists, it must be a dict
3743 * 5. If the "id" key exists, it can be anything (ie. json-value)
3744 * 6. Any argument not listed above is considered invalid
3746 static QDict *qmp_check_input_obj(QObject *input_obj, Error **errp)
3748 const QDictEntry *ent;
3749 int has_exec_key = 0;
3752 if (qobject_type(input_obj) != QTYPE_QDICT) {
3753 error_setg(errp, QERR_QMP_BAD_INPUT_OBJECT, "object");
3757 input_dict = qobject_to_qdict(input_obj);
3759 for (ent = qdict_first(input_dict); ent; ent = qdict_next(input_dict, ent)){
3760 const char *arg_name = qdict_entry_key(ent);
3761 const QObject *arg_obj = qdict_entry_value(ent);
3763 if (!strcmp(arg_name, "execute")) {
3764 if (qobject_type(arg_obj) != QTYPE_QSTRING) {
3765 error_setg(errp, QERR_QMP_BAD_INPUT_OBJECT_MEMBER,
3766 "execute", "string");
3770 } else if (!strcmp(arg_name, "arguments")) {
3771 if (qobject_type(arg_obj) != QTYPE_QDICT) {
3772 error_setg(errp, QERR_QMP_BAD_INPUT_OBJECT_MEMBER,
3773 "arguments", "object");
3776 } else if (!strcmp(arg_name, "id")) {
3777 /* Any string is acceptable as "id", so nothing to check */
3779 error_setg(errp, QERR_QMP_EXTRA_MEMBER, arg_name);
3784 if (!has_exec_key) {
3785 error_setg(errp, QERR_QMP_BAD_INPUT_OBJECT, "execute");
3792 static void handle_qmp_command(JSONMessageParser *parser, QList *tokens)
3794 Error *local_err = NULL;
3795 QObject *obj, *data;
3796 QDict *input, *args;
3797 const mon_cmd_t *cmd;
3798 const char *cmd_name;
3799 Monitor *mon = cur_mon;
3801 args = input = NULL;
3804 obj = json_parser_parse(tokens, NULL);
3806 // FIXME: should be triggered in json_parser_parse()
3807 error_setg(&local_err, QERR_JSON_PARSING);
3811 input = qmp_check_input_obj(obj, &local_err);
3813 qobject_decref(obj);
3817 mon->qmp.id = qdict_get(input, "id");
3818 qobject_incref(mon->qmp.id);
3820 cmd_name = qdict_get_str(input, "execute");
3821 trace_handle_qmp_command(mon, cmd_name);
3822 cmd = qmp_find_cmd(cmd_name);
3824 error_set(&local_err, ERROR_CLASS_COMMAND_NOT_FOUND,
3825 "The command %s has not been found", cmd_name);
3828 if (invalid_qmp_mode(mon, cmd, &local_err)) {
3832 obj = qdict_get(input, "arguments");
3836 args = qobject_to_qdict(obj);
3840 qmp_check_client_args(cmd, args, &local_err);
3845 cmd->mhandler.cmd_new(args, &data, &local_err);
3848 monitor_protocol_emitter(mon, data, local_err);
3849 qobject_decref(data);
3854 static void monitor_qmp_read(void *opaque, const uint8_t *buf, int size)
3856 Monitor *old_mon = cur_mon;
3860 json_message_parser_feed(&cur_mon->qmp.parser, (const char *) buf, size);
3865 static void monitor_read(void *opaque, const uint8_t *buf, int size)
3867 Monitor *old_mon = cur_mon;
3873 for (i = 0; i < size; i++)
3874 readline_handle_byte(cur_mon->rs, buf[i]);
3876 if (size == 0 || buf[size - 1] != 0)
3877 monitor_printf(cur_mon, "corrupted command\n");
3879 handle_hmp_command(cur_mon, (char *)buf);
3885 static void monitor_command_cb(void *opaque, const char *cmdline,
3886 void *readline_opaque)
3888 Monitor *mon = opaque;
3890 monitor_suspend(mon);
3891 handle_hmp_command(mon, cmdline);
3892 monitor_resume(mon);
3895 int monitor_suspend(Monitor *mon)
3903 void monitor_resume(Monitor *mon)
3907 if (--mon->suspend_cnt == 0)
3908 readline_show_prompt(mon->rs);
3911 static QObject *get_qmp_greeting(void)
3913 QObject *ver = NULL;
3915 qmp_marshal_query_version(NULL, &ver, NULL);
3916 return qobject_from_jsonf("{'QMP':{'version': %p,'capabilities': []}}",ver);
3919 static void monitor_qmp_event(void *opaque, int event)
3922 Monitor *mon = opaque;
3925 case CHR_EVENT_OPENED:
3926 mon->qmp.in_command_mode = false;
3927 data = get_qmp_greeting();
3928 monitor_json_emitter(mon, data);
3929 qobject_decref(data);
3932 case CHR_EVENT_CLOSED:
3933 json_message_parser_destroy(&mon->qmp.parser);
3934 json_message_parser_init(&mon->qmp.parser, handle_qmp_command);
3936 monitor_fdsets_cleanup();
3941 static void monitor_event(void *opaque, int event)
3943 Monitor *mon = opaque;
3946 case CHR_EVENT_MUX_IN:
3947 qemu_mutex_lock(&mon->out_lock);
3949 qemu_mutex_unlock(&mon->out_lock);
3950 if (mon->reset_seen) {
3951 readline_restart(mon->rs);
3952 monitor_resume(mon);
3955 mon->suspend_cnt = 0;
3959 case CHR_EVENT_MUX_OUT:
3960 if (mon->reset_seen) {
3961 if (mon->suspend_cnt == 0) {
3962 monitor_printf(mon, "\n");
3965 monitor_suspend(mon);
3969 qemu_mutex_lock(&mon->out_lock);
3971 qemu_mutex_unlock(&mon->out_lock);
3974 case CHR_EVENT_OPENED:
3975 monitor_printf(mon, "QEMU %s monitor - type 'help' for more "
3976 "information\n", QEMU_VERSION);
3977 if (!mon->mux_out) {
3978 readline_restart(mon->rs);
3979 readline_show_prompt(mon->rs);
3981 mon->reset_seen = 1;
3985 case CHR_EVENT_CLOSED:
3987 monitor_fdsets_cleanup();
3993 compare_mon_cmd(const void *a, const void *b)
3995 return strcmp(((const mon_cmd_t *)a)->name,
3996 ((const mon_cmd_t *)b)->name);
3999 static void sortcmdlist(void)
4002 int elem_size = sizeof(mon_cmd_t);
4004 array_num = sizeof(mon_cmds)/elem_size-1;
4005 qsort((void *)mon_cmds, array_num, elem_size, compare_mon_cmd);
4007 array_num = sizeof(info_cmds)/elem_size-1;
4008 qsort((void *)info_cmds, array_num, elem_size, compare_mon_cmd);
4020 /* These functions just adapt the readline interface in a typesafe way. We
4021 * could cast function pointers but that discards compiler checks.
4023 static void GCC_FMT_ATTR(2, 3) monitor_readline_printf(void *opaque,
4024 const char *fmt, ...)
4028 monitor_vprintf(opaque, fmt, ap);
4032 static void monitor_readline_flush(void *opaque)
4034 monitor_flush(opaque);
4037 static void __attribute__((constructor)) monitor_lock_init(void)
4039 qemu_mutex_init(&monitor_lock);
4042 void monitor_init(CharDriverState *chr, int flags)
4044 static int is_first_init = 1;
4047 if (is_first_init) {
4048 monitor_qapi_event_init();
4053 mon = g_malloc(sizeof(*mon));
4054 monitor_data_init(mon);
4058 if (flags & MONITOR_USE_READLINE) {
4059 mon->rs = readline_init(monitor_readline_printf,
4060 monitor_readline_flush,
4062 monitor_find_completion);
4063 monitor_read_command(mon, 0);
4066 if (monitor_is_qmp(mon)) {
4067 qemu_chr_add_handlers(chr, monitor_can_read, monitor_qmp_read,
4068 monitor_qmp_event, mon);
4069 qemu_chr_fe_set_echo(chr, true);
4070 json_message_parser_init(&mon->qmp.parser, handle_qmp_command);
4072 qemu_chr_add_handlers(chr, monitor_can_read, monitor_read,
4073 monitor_event, mon);
4076 qemu_mutex_lock(&monitor_lock);
4077 QLIST_INSERT_HEAD(&mon_list, mon, entry);
4078 qemu_mutex_unlock(&monitor_lock);
4081 static void bdrv_password_cb(void *opaque, const char *password,
4082 void *readline_opaque)
4084 Monitor *mon = opaque;
4085 BlockDriverState *bs = readline_opaque;
4087 Error *local_err = NULL;
4089 bdrv_add_key(bs, password, &local_err);
4091 monitor_printf(mon, "%s\n", error_get_pretty(local_err));
4092 error_free(local_err);
4095 if (mon->password_completion_cb)
4096 mon->password_completion_cb(mon->password_opaque, ret);
4098 monitor_read_command(mon, 1);
4101 int monitor_read_bdrv_key_start(Monitor *mon, BlockDriverState *bs,
4102 BlockCompletionFunc *completion_cb,
4107 monitor_printf(mon, "%s (%s) is encrypted.\n", bdrv_get_device_name(bs),
4108 bdrv_get_encrypted_filename(bs));
4110 mon->password_completion_cb = completion_cb;
4111 mon->password_opaque = opaque;
4113 err = monitor_read_password(mon, bdrv_password_cb, bs);
4115 if (err && completion_cb)
4116 completion_cb(opaque, err);
4121 int monitor_read_block_device_key(Monitor *mon, const char *device,
4122 BlockCompletionFunc *completion_cb,
4128 blk = blk_by_name(device);
4130 monitor_printf(mon, "Device not found %s\n", device);
4134 bdrv_add_key(blk_bs(blk), NULL, &err);
4137 return monitor_read_bdrv_key_start(mon, blk_bs(blk), completion_cb, opaque);
4140 if (completion_cb) {
4141 completion_cb(opaque, 0);
4146 QemuOptsList qemu_mon_opts = {
4148 .implied_opt_name = "chardev",
4149 .head = QTAILQ_HEAD_INITIALIZER(qemu_mon_opts.head),
4153 .type = QEMU_OPT_STRING,
4156 .type = QEMU_OPT_STRING,
4159 .type = QEMU_OPT_BOOL,
4162 .type = QEMU_OPT_BOOL,
4164 { /* end of list */ }
4169 void qmp_rtc_reset_reinjection(Error **errp)
4171 error_setg(errp, QERR_FEATURE_DISABLED, "rtc-reset-reinjection");
4175 #ifndef TARGET_S390X
4176 void qmp_dump_skeys(const char *filename, Error **errp)
4178 error_setg(errp, QERR_FEATURE_DISABLED, "dump-skeys");