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 "exec/cpu_ldst.h"
72 #include "qmp-commands.h"
74 #include "qemu/thread.h"
75 #include "block/qapi.h"
76 #include "qapi/qmp-event.h"
77 #include "qapi-event.h"
78 #include "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 int64_t rate; /* Minimum time (in ns) between two events */
186 int64_t last; /* QEMU_CLOCK_REALTIME value at last emission */
187 QEMUTimer *timer; /* Timer for handling delayed events */
188 QObject *data; /* Event pending delayed dispatch */
189 } MonitorQAPIEventState;
192 CharDriverState *chr;
202 /* Read under either BQL or out_lock, written with BQL+out_lock. */
208 BlockCompletionFunc *password_completion_cb;
209 void *password_opaque;
210 mon_cmd_t *cmd_table;
211 QLIST_HEAD(,mon_fd_t) fds;
212 QLIST_ENTRY(Monitor) entry;
215 /* QMP checker flags */
216 #define QMP_ACCEPT_UNKNOWNS 1
218 /* Protects mon_list, monitor_event_state. */
219 static QemuMutex monitor_lock;
221 static QLIST_HEAD(mon_list, Monitor) mon_list;
222 static QLIST_HEAD(mon_fdsets, MonFdset) mon_fdsets;
223 static int mon_refcount;
225 static mon_cmd_t mon_cmds[];
226 static mon_cmd_t info_cmds[];
228 static const mon_cmd_t qmp_cmds[];
232 static void monitor_command_cb(void *opaque, const char *cmdline,
233 void *readline_opaque);
236 * Is @mon a QMP monitor?
238 static inline bool monitor_is_qmp(const Monitor *mon)
240 return (mon->flags & MONITOR_USE_CONTROL);
244 * Is the current monitor, if any, a QMP monitor?
246 bool monitor_cur_is_qmp(void)
248 return cur_mon && monitor_is_qmp(cur_mon);
251 void monitor_read_command(Monitor *mon, int show_prompt)
256 readline_start(mon->rs, "(qemu) ", 0, monitor_command_cb, NULL);
258 readline_show_prompt(mon->rs);
261 int monitor_read_password(Monitor *mon, ReadLineFunc *readline_func,
265 readline_start(mon->rs, "Password: ", 1, readline_func, opaque);
266 /* prompt is printed on return from the command handler */
269 monitor_printf(mon, "terminal does not support password prompting\n");
274 static void monitor_flush_locked(Monitor *mon);
276 static gboolean monitor_unblocked(GIOChannel *chan, GIOCondition cond,
279 Monitor *mon = opaque;
281 qemu_mutex_lock(&mon->out_lock);
283 monitor_flush_locked(mon);
284 qemu_mutex_unlock(&mon->out_lock);
288 /* Called with mon->out_lock held. */
289 static void monitor_flush_locked(Monitor *mon)
295 if (mon->skip_flush) {
299 buf = qstring_get_str(mon->outbuf);
300 len = qstring_get_length(mon->outbuf);
302 if (len && !mon->mux_out) {
303 rc = qemu_chr_fe_write(mon->chr, (const uint8_t *) buf, len);
304 if ((rc < 0 && errno != EAGAIN) || (rc == len)) {
305 /* all flushed or error */
306 QDECREF(mon->outbuf);
307 mon->outbuf = qstring_new();
312 QString *tmp = qstring_from_str(buf + rc);
313 QDECREF(mon->outbuf);
316 if (mon->out_watch == 0) {
317 mon->out_watch = qemu_chr_fe_add_watch(mon->chr, G_IO_OUT|G_IO_HUP,
318 monitor_unblocked, mon);
323 void monitor_flush(Monitor *mon)
325 qemu_mutex_lock(&mon->out_lock);
326 monitor_flush_locked(mon);
327 qemu_mutex_unlock(&mon->out_lock);
330 /* flush at every end of line */
331 static void monitor_puts(Monitor *mon, const char *str)
335 qemu_mutex_lock(&mon->out_lock);
341 qstring_append_chr(mon->outbuf, '\r');
343 qstring_append_chr(mon->outbuf, c);
345 monitor_flush_locked(mon);
348 qemu_mutex_unlock(&mon->out_lock);
351 void monitor_vprintf(Monitor *mon, const char *fmt, va_list ap)
358 if (monitor_is_qmp(mon)) {
362 buf = g_strdup_vprintf(fmt, ap);
363 monitor_puts(mon, buf);
367 void monitor_printf(Monitor *mon, const char *fmt, ...)
371 monitor_vprintf(mon, fmt, ap);
375 static int GCC_FMT_ATTR(2, 3) monitor_fprintf(FILE *stream,
376 const char *fmt, ...)
380 monitor_vprintf((Monitor *)stream, fmt, ap);
385 static void monitor_json_emitter(Monitor *mon, const QObject *data)
389 json = mon->flags & MONITOR_USE_PRETTY ? qobject_to_json_pretty(data) :
390 qobject_to_json(data);
391 assert(json != NULL);
393 qstring_append_chr(json, '\n');
394 monitor_puts(mon, qstring_get_str(json));
399 static QDict *build_qmp_error_dict(Error *err)
403 obj = qobject_from_jsonf("{ 'error': { 'class': %s, 'desc': %s } }",
404 ErrorClass_lookup[error_get_class(err)],
405 error_get_pretty(err));
407 return qobject_to_qdict(obj);
410 static void monitor_protocol_emitter(Monitor *mon, QObject *data,
415 trace_monitor_protocol_emitter(mon);
418 /* success response */
421 qobject_incref(data);
422 qdict_put_obj(qmp, "return", data);
424 /* return an empty QDict by default */
425 qdict_put(qmp, "return", qdict_new());
429 qmp = build_qmp_error_dict(err);
433 qdict_put_obj(qmp, "id", mon->qmp.id);
437 monitor_json_emitter(mon, QOBJECT(qmp));
442 static MonitorQAPIEventState monitor_qapi_event_state[QAPI_EVENT_MAX];
445 * Emits the event to every monitor instance, @event is only used for trace
446 * Called with monitor_lock held.
448 static void monitor_qapi_event_emit(QAPIEvent event, QObject *data)
452 trace_monitor_protocol_event_emit(event, data);
453 QLIST_FOREACH(mon, &mon_list, entry) {
454 if (monitor_is_qmp(mon) && mon->qmp.in_command_mode) {
455 monitor_json_emitter(mon, data);
461 * Queue a new event for emission to Monitor instances,
462 * applying any rate limiting if required.
465 monitor_qapi_event_queue(QAPIEvent event, QDict *data, Error **errp)
467 MonitorQAPIEventState *evstate;
468 assert(event < QAPI_EVENT_MAX);
469 int64_t now = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
471 evstate = &(monitor_qapi_event_state[event]);
472 trace_monitor_protocol_event_queue(event,
478 /* Rate limit of 0 indicates no throttling */
479 qemu_mutex_lock(&monitor_lock);
480 if (!evstate->rate) {
481 monitor_qapi_event_emit(event, QOBJECT(data));
484 int64_t delta = now - evstate->last;
486 delta < evstate->rate) {
487 /* If there's an existing event pending, replace
488 * it with the new event, otherwise schedule a
489 * timer for delayed emission
492 qobject_decref(evstate->data);
494 int64_t then = evstate->last + evstate->rate;
495 timer_mod_ns(evstate->timer, then);
497 evstate->data = QOBJECT(data);
498 qobject_incref(evstate->data);
500 monitor_qapi_event_emit(event, QOBJECT(data));
504 qemu_mutex_unlock(&monitor_lock);
508 * The callback invoked by QemuTimer when a delayed
509 * event is ready to be emitted
511 static void monitor_qapi_event_handler(void *opaque)
513 MonitorQAPIEventState *evstate = opaque;
514 int64_t now = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
516 trace_monitor_protocol_event_handler(evstate->event,
520 qemu_mutex_lock(&monitor_lock);
522 monitor_qapi_event_emit(evstate->event, evstate->data);
523 qobject_decref(evstate->data);
524 evstate->data = NULL;
527 qemu_mutex_unlock(&monitor_lock);
531 * @event: the event ID to be limited
532 * @rate: the rate limit in milliseconds
534 * Sets a rate limit on a particular event, so no
535 * more than 1 event will be emitted within @rate
539 monitor_qapi_event_throttle(QAPIEvent event, int64_t rate)
541 MonitorQAPIEventState *evstate;
542 assert(event < QAPI_EVENT_MAX);
544 evstate = &(monitor_qapi_event_state[event]);
546 trace_monitor_protocol_event_throttle(event, rate);
547 evstate->event = event;
548 assert(rate * SCALE_MS <= INT64_MAX);
549 evstate->rate = rate * SCALE_MS;
551 evstate->data = NULL;
552 evstate->timer = timer_new(QEMU_CLOCK_REALTIME,
554 monitor_qapi_event_handler,
558 static void monitor_qapi_event_init(void)
560 /* Limit guest-triggerable events to 1 per second */
561 monitor_qapi_event_throttle(QAPI_EVENT_RTC_CHANGE, 1000);
562 monitor_qapi_event_throttle(QAPI_EVENT_WATCHDOG, 1000);
563 monitor_qapi_event_throttle(QAPI_EVENT_BALLOON_CHANGE, 1000);
564 monitor_qapi_event_throttle(QAPI_EVENT_QUORUM_REPORT_BAD, 1000);
565 monitor_qapi_event_throttle(QAPI_EVENT_QUORUM_FAILURE, 1000);
566 monitor_qapi_event_throttle(QAPI_EVENT_VSERPORT_CHANGE, 1000);
568 qmp_event_set_func_emit(monitor_qapi_event_queue);
571 static void qmp_capabilities(QDict *params, QObject **ret_data, Error **errp)
573 cur_mon->qmp.in_command_mode = true;
576 static void handle_hmp_command(Monitor *mon, const char *cmdline);
578 static void monitor_data_init(Monitor *mon)
580 memset(mon, 0, sizeof(Monitor));
581 qemu_mutex_init(&mon->out_lock);
582 mon->outbuf = qstring_new();
583 /* Use *mon_cmds by default. */
584 mon->cmd_table = mon_cmds;
587 static void monitor_data_destroy(Monitor *mon)
589 QDECREF(mon->outbuf);
590 qemu_mutex_destroy(&mon->out_lock);
593 char *qmp_human_monitor_command(const char *command_line, bool has_cpu_index,
594 int64_t cpu_index, Error **errp)
597 Monitor *old_mon, hmp;
599 monitor_data_init(&hmp);
600 hmp.skip_flush = true;
606 int ret = monitor_set_cpu(cpu_index);
609 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cpu-index",
615 handle_hmp_command(&hmp, command_line);
618 qemu_mutex_lock(&hmp.out_lock);
619 if (qstring_get_length(hmp.outbuf) > 0) {
620 output = g_strdup(qstring_get_str(hmp.outbuf));
622 output = g_strdup("");
624 qemu_mutex_unlock(&hmp.out_lock);
627 monitor_data_destroy(&hmp);
631 static int compare_cmd(const char *name, const char *list)
633 const char *p, *pstart;
641 p = pstart + strlen(pstart);
642 if ((p - pstart) == len && !memcmp(pstart, name, len))
651 static int get_str(char *buf, int buf_size, const char **pp)
659 while (qemu_isspace(*p)) {
670 while (*p != '\0' && *p != '\"') {
686 printf("unsupported escape code: '\\%c'\n", c);
689 if ((q - buf) < buf_size - 1) {
693 if ((q - buf) < buf_size - 1) {
700 printf("unterminated string\n");
705 while (*p != '\0' && !qemu_isspace(*p)) {
706 if ((q - buf) < buf_size - 1) {
719 static void free_cmdline_args(char **args, int nb_args)
723 assert(nb_args <= MAX_ARGS);
725 for (i = 0; i < nb_args; i++) {
732 * Parse the command line to get valid args.
733 * @cmdline: command line to be parsed.
734 * @pnb_args: location to store the number of args, must NOT be NULL.
735 * @args: location to store the args, which should be freed by caller, must
738 * Returns 0 on success, negative on failure.
740 * NOTE: this parser is an approximate form of the real command parser. Number
741 * of args have a limit of MAX_ARGS. If cmdline contains more, it will
742 * return with failure.
744 static int parse_cmdline(const char *cmdline,
745 int *pnb_args, char **args)
754 while (qemu_isspace(*p)) {
760 if (nb_args >= MAX_ARGS) {
763 ret = get_str(buf, sizeof(buf), &p);
767 args[nb_args] = g_strdup(buf);
774 free_cmdline_args(args, nb_args);
778 static void help_cmd_dump_one(Monitor *mon,
779 const mon_cmd_t *cmd,
785 for (i = 0; i < prefix_args_nb; i++) {
786 monitor_printf(mon, "%s ", prefix_args[i]);
788 monitor_printf(mon, "%s %s -- %s\n", cmd->name, cmd->params, cmd->help);
791 /* @args[@arg_index] is the valid command need to find in @cmds */
792 static void help_cmd_dump(Monitor *mon, const mon_cmd_t *cmds,
793 char **args, int nb_args, int arg_index)
795 const mon_cmd_t *cmd;
797 /* No valid arg need to compare with, dump all in *cmds */
798 if (arg_index >= nb_args) {
799 for (cmd = cmds; cmd->name != NULL; cmd++) {
800 help_cmd_dump_one(mon, cmd, args, arg_index);
805 /* Find one entry to dump */
806 for (cmd = cmds; cmd->name != NULL; cmd++) {
807 if (compare_cmd(args[arg_index], cmd->name)) {
808 if (cmd->sub_table) {
809 /* continue with next arg */
810 help_cmd_dump(mon, cmd->sub_table,
811 args, nb_args, arg_index + 1);
813 help_cmd_dump_one(mon, cmd, args, arg_index);
820 static void help_cmd(Monitor *mon, const char *name)
822 char *args[MAX_ARGS];
825 /* 1. parse user input */
827 /* special case for log, directly dump and return */
828 if (!strcmp(name, "log")) {
829 const QEMULogItem *item;
830 monitor_printf(mon, "Log items (comma separated):\n");
831 monitor_printf(mon, "%-10s %s\n", "none", "remove all logs");
832 for (item = qemu_log_items; item->mask != 0; item++) {
833 monitor_printf(mon, "%-10s %s\n", item->name, item->help);
838 if (parse_cmdline(name, &nb_args, args) < 0) {
843 /* 2. dump the contents according to parsed args */
844 help_cmd_dump(mon, mon->cmd_table, args, nb_args, 0);
846 free_cmdline_args(args, nb_args);
849 static void do_help_cmd(Monitor *mon, const QDict *qdict)
851 help_cmd(mon, qdict_get_try_str(qdict, "name"));
854 static void hmp_trace_event(Monitor *mon, const QDict *qdict)
856 const char *tp_name = qdict_get_str(qdict, "name");
857 bool new_state = qdict_get_bool(qdict, "option");
858 Error *local_err = NULL;
860 qmp_trace_event_set_state(tp_name, new_state, true, true, &local_err);
862 error_report_err(local_err);
866 #ifdef CONFIG_TRACE_SIMPLE
867 static void hmp_trace_file(Monitor *mon, const QDict *qdict)
869 const char *op = qdict_get_try_str(qdict, "op");
870 const char *arg = qdict_get_try_str(qdict, "arg");
873 st_print_trace_file_status((FILE *)mon, &monitor_fprintf);
874 } else if (!strcmp(op, "on")) {
875 st_set_trace_file_enabled(true);
876 } else if (!strcmp(op, "off")) {
877 st_set_trace_file_enabled(false);
878 } else if (!strcmp(op, "flush")) {
879 st_flush_trace_buffer();
880 } else if (!strcmp(op, "set")) {
882 st_set_trace_file(arg);
885 monitor_printf(mon, "unexpected argument \"%s\"\n", op);
886 help_cmd(mon, "trace-file");
891 static void hmp_info_help(Monitor *mon, const QDict *qdict)
893 help_cmd(mon, "info");
896 CommandInfoList *qmp_query_commands(Error **errp)
898 CommandInfoList *info, *cmd_list = NULL;
899 const mon_cmd_t *cmd;
901 for (cmd = qmp_cmds; cmd->name != NULL; cmd++) {
902 info = g_malloc0(sizeof(*info));
903 info->value = g_malloc0(sizeof(*info->value));
904 info->value->name = g_strdup(cmd->name);
906 info->next = cmd_list;
913 EventInfoList *qmp_query_events(Error **errp)
915 EventInfoList *info, *ev_list = NULL;
918 for (e = 0 ; e < QAPI_EVENT_MAX ; e++) {
919 const char *event_name = QAPIEvent_lookup[e];
920 assert(event_name != NULL);
921 info = g_malloc0(sizeof(*info));
922 info->value = g_malloc0(sizeof(*info->value));
923 info->value->name = g_strdup(event_name);
925 info->next = ev_list;
932 /* set the current CPU defined by the user */
933 int monitor_set_cpu(int cpu_index)
937 cpu = qemu_get_cpu(cpu_index);
941 cur_mon->mon_cpu = cpu;
945 static CPUState *mon_get_cpu(void)
947 if (!cur_mon->mon_cpu) {
950 cpu_synchronize_state(cur_mon->mon_cpu);
951 return cur_mon->mon_cpu;
954 CPUArchState *mon_get_cpu_env(void)
956 return mon_get_cpu()->env_ptr;
959 int monitor_get_cpu_index(void)
961 return mon_get_cpu()->cpu_index;
964 static void hmp_info_registers(Monitor *mon, const QDict *qdict)
966 cpu_dump_state(mon_get_cpu(), (FILE *)mon, monitor_fprintf, CPU_DUMP_FPU);
969 static void hmp_info_jit(Monitor *mon, const QDict *qdict)
971 dump_exec_info((FILE *)mon, monitor_fprintf);
972 dump_drift_info((FILE *)mon, monitor_fprintf);
975 static void hmp_info_opcount(Monitor *mon, const QDict *qdict)
977 dump_opcount_info((FILE *)mon, monitor_fprintf);
980 static void hmp_info_history(Monitor *mon, const QDict *qdict)
989 str = readline_get_history(mon->rs, i);
992 monitor_printf(mon, "%d: '%s'\n", i, str);
997 static void hmp_info_cpustats(Monitor *mon, const QDict *qdict)
999 cpu_dump_statistics(mon_get_cpu(), (FILE *)mon, &monitor_fprintf, 0);
1002 static void hmp_info_trace_events(Monitor *mon, const QDict *qdict)
1004 TraceEventInfoList *events = qmp_trace_event_get_state("*", NULL);
1005 TraceEventInfoList *elem;
1007 for (elem = events; elem != NULL; elem = elem->next) {
1008 monitor_printf(mon, "%s : state %u\n",
1010 elem->value->state == TRACE_EVENT_STATE_ENABLED ? 1 : 0);
1012 qapi_free_TraceEventInfoList(events);
1015 void qmp_client_migrate_info(const char *protocol, const char *hostname,
1016 bool has_port, int64_t port,
1017 bool has_tls_port, int64_t tls_port,
1018 bool has_cert_subject, const char *cert_subject,
1021 if (strcmp(protocol, "spice") == 0) {
1022 if (!qemu_using_spice(errp)) {
1026 if (!has_port && !has_tls_port) {
1027 error_setg(errp, QERR_MISSING_PARAMETER, "port/tls-port");
1031 if (qemu_spice_migrate_info(hostname,
1032 has_port ? port : -1,
1033 has_tls_port ? tls_port : -1,
1035 error_setg(errp, QERR_UNDEFINED_ERROR);
1041 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "protocol", "spice");
1044 static void hmp_logfile(Monitor *mon, const QDict *qdict)
1046 qemu_set_log_filename(qdict_get_str(qdict, "filename"));
1049 static void hmp_log(Monitor *mon, const QDict *qdict)
1052 const char *items = qdict_get_str(qdict, "items");
1054 if (!strcmp(items, "none")) {
1057 mask = qemu_str_to_log_mask(items);
1059 help_cmd(mon, "log");
1066 static void hmp_singlestep(Monitor *mon, const QDict *qdict)
1068 const char *option = qdict_get_try_str(qdict, "option");
1069 if (!option || !strcmp(option, "on")) {
1071 } else if (!strcmp(option, "off")) {
1074 monitor_printf(mon, "unexpected option %s\n", option);
1078 static void hmp_gdbserver(Monitor *mon, const QDict *qdict)
1080 const char *device = qdict_get_try_str(qdict, "device");
1082 device = "tcp::" DEFAULT_GDBSTUB_PORT;
1083 if (gdbserver_start(device) < 0) {
1084 monitor_printf(mon, "Could not open gdbserver on device '%s'\n",
1086 } else if (strcmp(device, "none") == 0) {
1087 monitor_printf(mon, "Disabled gdbserver\n");
1089 monitor_printf(mon, "Waiting for gdb connection on device '%s'\n",
1094 static void hmp_watchdog_action(Monitor *mon, const QDict *qdict)
1096 const char *action = qdict_get_str(qdict, "action");
1097 if (select_watchdog_action(action) == -1) {
1098 monitor_printf(mon, "Unknown watchdog action '%s'\n", action);
1102 static void monitor_printc(Monitor *mon, int c)
1104 monitor_printf(mon, "'");
1107 monitor_printf(mon, "\\'");
1110 monitor_printf(mon, "\\\\");
1113 monitor_printf(mon, "\\n");
1116 monitor_printf(mon, "\\r");
1119 if (c >= 32 && c <= 126) {
1120 monitor_printf(mon, "%c", c);
1122 monitor_printf(mon, "\\x%02x", c);
1126 monitor_printf(mon, "'");
1129 static void memory_dump(Monitor *mon, int count, int format, int wsize,
1130 hwaddr addr, int is_physical)
1132 int l, line_size, i, max_digits, len;
1136 if (format == 'i') {
1139 CPUArchState *env = mon_get_cpu_env();
1142 } else if (wsize == 4) {
1145 /* as default we use the current CS size */
1148 #ifdef TARGET_X86_64
1149 if ((env->efer & MSR_EFER_LMA) &&
1150 (env->segs[R_CS].flags & DESC_L_MASK))
1154 if (!(env->segs[R_CS].flags & DESC_B_MASK))
1160 CPUArchState *env = mon_get_cpu_env();
1161 flags = msr_le << 16;
1162 flags |= env->bfd_mach;
1164 monitor_disas(mon, mon_get_cpu(), addr, count, is_physical, flags);
1168 len = wsize * count;
1177 max_digits = (wsize * 8 + 2) / 3;
1181 max_digits = (wsize * 8) / 4;
1185 max_digits = (wsize * 8 * 10 + 32) / 33;
1194 monitor_printf(mon, TARGET_FMT_plx ":", addr);
1196 monitor_printf(mon, TARGET_FMT_lx ":", (target_ulong)addr);
1201 cpu_physical_memory_read(addr, buf, l);
1203 if (cpu_memory_rw_debug(mon_get_cpu(), addr, buf, l, 0) < 0) {
1204 monitor_printf(mon, " Cannot access memory\n");
1213 v = ldub_p(buf + i);
1216 v = lduw_p(buf + i);
1219 v = (uint32_t)ldl_p(buf + i);
1225 monitor_printf(mon, " ");
1228 monitor_printf(mon, "%#*" PRIo64, max_digits, v);
1231 monitor_printf(mon, "0x%0*" PRIx64, max_digits, v);
1234 monitor_printf(mon, "%*" PRIu64, max_digits, v);
1237 monitor_printf(mon, "%*" PRId64, max_digits, v);
1240 monitor_printc(mon, v);
1245 monitor_printf(mon, "\n");
1251 static void hmp_memory_dump(Monitor *mon, const QDict *qdict)
1253 int count = qdict_get_int(qdict, "count");
1254 int format = qdict_get_int(qdict, "format");
1255 int size = qdict_get_int(qdict, "size");
1256 target_long addr = qdict_get_int(qdict, "addr");
1258 memory_dump(mon, count, format, size, addr, 0);
1261 static void hmp_physical_memory_dump(Monitor *mon, const QDict *qdict)
1263 int count = qdict_get_int(qdict, "count");
1264 int format = qdict_get_int(qdict, "format");
1265 int size = qdict_get_int(qdict, "size");
1266 hwaddr addr = qdict_get_int(qdict, "addr");
1268 memory_dump(mon, count, format, size, addr, 1);
1271 static void do_print(Monitor *mon, const QDict *qdict)
1273 int format = qdict_get_int(qdict, "format");
1274 hwaddr val = qdict_get_int(qdict, "val");
1278 monitor_printf(mon, "%#" HWADDR_PRIo, val);
1281 monitor_printf(mon, "%#" HWADDR_PRIx, val);
1284 monitor_printf(mon, "%" HWADDR_PRIu, val);
1288 monitor_printf(mon, "%" HWADDR_PRId, val);
1291 monitor_printc(mon, val);
1294 monitor_printf(mon, "\n");
1297 static void hmp_sum(Monitor *mon, const QDict *qdict)
1301 uint32_t start = qdict_get_int(qdict, "start");
1302 uint32_t size = qdict_get_int(qdict, "size");
1305 for(addr = start; addr < (start + size); addr++) {
1306 uint8_t val = address_space_ldub(&address_space_memory, addr,
1307 MEMTXATTRS_UNSPECIFIED, NULL);
1308 /* BSD sum algorithm ('sum' Unix command) */
1309 sum = (sum >> 1) | (sum << 15);
1312 monitor_printf(mon, "%05d\n", sum);
1315 static int mouse_button_state;
1317 static void hmp_mouse_move(Monitor *mon, const QDict *qdict)
1319 int dx, dy, dz, button;
1320 const char *dx_str = qdict_get_str(qdict, "dx_str");
1321 const char *dy_str = qdict_get_str(qdict, "dy_str");
1322 const char *dz_str = qdict_get_try_str(qdict, "dz_str");
1324 dx = strtol(dx_str, NULL, 0);
1325 dy = strtol(dy_str, NULL, 0);
1326 qemu_input_queue_rel(NULL, INPUT_AXIS_X, dx);
1327 qemu_input_queue_rel(NULL, INPUT_AXIS_Y, dy);
1330 dz = strtol(dz_str, NULL, 0);
1332 button = (dz > 0) ? INPUT_BUTTON_WHEEL_UP : INPUT_BUTTON_WHEEL_DOWN;
1333 qemu_input_queue_btn(NULL, button, true);
1334 qemu_input_event_sync();
1335 qemu_input_queue_btn(NULL, button, false);
1338 qemu_input_event_sync();
1341 static void hmp_mouse_button(Monitor *mon, const QDict *qdict)
1343 static uint32_t bmap[INPUT_BUTTON_MAX] = {
1344 [INPUT_BUTTON_LEFT] = MOUSE_EVENT_LBUTTON,
1345 [INPUT_BUTTON_MIDDLE] = MOUSE_EVENT_MBUTTON,
1346 [INPUT_BUTTON_RIGHT] = MOUSE_EVENT_RBUTTON,
1348 int button_state = qdict_get_int(qdict, "button_state");
1350 if (mouse_button_state == button_state) {
1353 qemu_input_update_buttons(NULL, bmap, mouse_button_state, button_state);
1354 qemu_input_event_sync();
1355 mouse_button_state = button_state;
1358 static void hmp_ioport_read(Monitor *mon, const QDict *qdict)
1360 int size = qdict_get_int(qdict, "size");
1361 int addr = qdict_get_int(qdict, "addr");
1362 int has_index = qdict_haskey(qdict, "index");
1367 int index = qdict_get_int(qdict, "index");
1368 cpu_outb(addr & IOPORTS_MASK, index & 0xff);
1376 val = cpu_inb(addr);
1380 val = cpu_inw(addr);
1384 val = cpu_inl(addr);
1388 monitor_printf(mon, "port%c[0x%04x] = %#0*x\n",
1389 suffix, addr, size * 2, val);
1392 static void hmp_ioport_write(Monitor *mon, const QDict *qdict)
1394 int size = qdict_get_int(qdict, "size");
1395 int addr = qdict_get_int(qdict, "addr");
1396 int val = qdict_get_int(qdict, "val");
1398 addr &= IOPORTS_MASK;
1403 cpu_outb(addr, val);
1406 cpu_outw(addr, val);
1409 cpu_outl(addr, val);
1414 static void hmp_boot_set(Monitor *mon, const QDict *qdict)
1416 Error *local_err = NULL;
1417 const char *bootdevice = qdict_get_str(qdict, "bootdevice");
1419 qemu_boot_set(bootdevice, &local_err);
1421 monitor_printf(mon, "%s\n", error_get_pretty(local_err));
1422 error_free(local_err);
1424 monitor_printf(mon, "boot device list now set to %s\n", bootdevice);
1428 static void hmp_info_mtree(Monitor *mon, const QDict *qdict)
1430 mtree_info((fprintf_function)monitor_printf, mon);
1433 static void hmp_info_numa(Monitor *mon, const QDict *qdict)
1439 node_mem = g_new0(uint64_t, nb_numa_nodes);
1440 query_numa_node_mem(node_mem);
1441 monitor_printf(mon, "%d nodes\n", nb_numa_nodes);
1442 for (i = 0; i < nb_numa_nodes; i++) {
1443 monitor_printf(mon, "node %d cpus:", i);
1445 if (cpu->numa_node == i) {
1446 monitor_printf(mon, " %d", cpu->cpu_index);
1449 monitor_printf(mon, "\n");
1450 monitor_printf(mon, "node %d size: %" PRId64 " MB\n", i,
1456 #ifdef CONFIG_PROFILER
1461 static void hmp_info_profile(Monitor *mon, const QDict *qdict)
1463 monitor_printf(mon, "async time %" PRId64 " (%0.3f)\n",
1464 dev_time, dev_time / (double)get_ticks_per_sec());
1465 monitor_printf(mon, "qemu time %" PRId64 " (%0.3f)\n",
1466 tcg_time, tcg_time / (double)get_ticks_per_sec());
1471 static void hmp_info_profile(Monitor *mon, const QDict *qdict)
1473 monitor_printf(mon, "Internal profiler not compiled\n");
1477 /* Capture support */
1478 static QLIST_HEAD (capture_list_head, CaptureState) capture_head;
1480 static void hmp_info_capture(Monitor *mon, const QDict *qdict)
1485 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
1486 monitor_printf(mon, "[%d]: ", i);
1487 s->ops.info (s->opaque);
1491 static void hmp_stopcapture(Monitor *mon, const QDict *qdict)
1494 int n = qdict_get_int(qdict, "n");
1497 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
1499 s->ops.destroy (s->opaque);
1500 QLIST_REMOVE (s, entries);
1507 static void hmp_wavcapture(Monitor *mon, const QDict *qdict)
1509 const char *path = qdict_get_str(qdict, "path");
1510 int has_freq = qdict_haskey(qdict, "freq");
1511 int freq = qdict_get_try_int(qdict, "freq", -1);
1512 int has_bits = qdict_haskey(qdict, "bits");
1513 int bits = qdict_get_try_int(qdict, "bits", -1);
1514 int has_channels = qdict_haskey(qdict, "nchannels");
1515 int nchannels = qdict_get_try_int(qdict, "nchannels", -1);
1518 s = g_malloc0 (sizeof (*s));
1520 freq = has_freq ? freq : 44100;
1521 bits = has_bits ? bits : 16;
1522 nchannels = has_channels ? nchannels : 2;
1524 if (wav_start_capture (s, path, freq, bits, nchannels)) {
1525 monitor_printf(mon, "Failed to add wave capture\n");
1529 QLIST_INSERT_HEAD (&capture_head, s, entries);
1532 static qemu_acl *find_acl(Monitor *mon, const char *name)
1534 qemu_acl *acl = qemu_acl_find(name);
1537 monitor_printf(mon, "acl: unknown list '%s'\n", name);
1542 static void hmp_acl_show(Monitor *mon, const QDict *qdict)
1544 const char *aclname = qdict_get_str(qdict, "aclname");
1545 qemu_acl *acl = find_acl(mon, aclname);
1546 qemu_acl_entry *entry;
1550 monitor_printf(mon, "policy: %s\n",
1551 acl->defaultDeny ? "deny" : "allow");
1552 QTAILQ_FOREACH(entry, &acl->entries, next) {
1554 monitor_printf(mon, "%d: %s %s\n", i,
1555 entry->deny ? "deny" : "allow", entry->match);
1560 static void hmp_acl_reset(Monitor *mon, const QDict *qdict)
1562 const char *aclname = qdict_get_str(qdict, "aclname");
1563 qemu_acl *acl = find_acl(mon, aclname);
1566 qemu_acl_reset(acl);
1567 monitor_printf(mon, "acl: removed all rules\n");
1571 static void hmp_acl_policy(Monitor *mon, const QDict *qdict)
1573 const char *aclname = qdict_get_str(qdict, "aclname");
1574 const char *policy = qdict_get_str(qdict, "policy");
1575 qemu_acl *acl = find_acl(mon, aclname);
1578 if (strcmp(policy, "allow") == 0) {
1579 acl->defaultDeny = 0;
1580 monitor_printf(mon, "acl: policy set to 'allow'\n");
1581 } else if (strcmp(policy, "deny") == 0) {
1582 acl->defaultDeny = 1;
1583 monitor_printf(mon, "acl: policy set to 'deny'\n");
1585 monitor_printf(mon, "acl: unknown policy '%s', "
1586 "expected 'deny' or 'allow'\n", policy);
1591 static void hmp_acl_add(Monitor *mon, const QDict *qdict)
1593 const char *aclname = qdict_get_str(qdict, "aclname");
1594 const char *match = qdict_get_str(qdict, "match");
1595 const char *policy = qdict_get_str(qdict, "policy");
1596 int has_index = qdict_haskey(qdict, "index");
1597 int index = qdict_get_try_int(qdict, "index", -1);
1598 qemu_acl *acl = find_acl(mon, aclname);
1602 if (strcmp(policy, "allow") == 0) {
1604 } else if (strcmp(policy, "deny") == 0) {
1607 monitor_printf(mon, "acl: unknown policy '%s', "
1608 "expected 'deny' or 'allow'\n", policy);
1612 ret = qemu_acl_insert(acl, deny, match, index);
1614 ret = qemu_acl_append(acl, deny, match);
1616 monitor_printf(mon, "acl: unable to add acl entry\n");
1618 monitor_printf(mon, "acl: added rule at position %d\n", ret);
1622 static void hmp_acl_remove(Monitor *mon, const QDict *qdict)
1624 const char *aclname = qdict_get_str(qdict, "aclname");
1625 const char *match = qdict_get_str(qdict, "match");
1626 qemu_acl *acl = find_acl(mon, aclname);
1630 ret = qemu_acl_remove(acl, match);
1632 monitor_printf(mon, "acl: no matching acl entry\n");
1634 monitor_printf(mon, "acl: removed rule at position %d\n", ret);
1638 void qmp_getfd(const char *fdname, Error **errp)
1643 fd = qemu_chr_fe_get_msgfd(cur_mon->chr);
1645 error_setg(errp, QERR_FD_NOT_SUPPLIED);
1649 if (qemu_isdigit(fdname[0])) {
1651 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "fdname",
1652 "a name not starting with a digit");
1656 QLIST_FOREACH(monfd, &cur_mon->fds, next) {
1657 if (strcmp(monfd->name, fdname) != 0) {
1666 monfd = g_malloc0(sizeof(mon_fd_t));
1667 monfd->name = g_strdup(fdname);
1670 QLIST_INSERT_HEAD(&cur_mon->fds, monfd, next);
1673 void qmp_closefd(const char *fdname, Error **errp)
1677 QLIST_FOREACH(monfd, &cur_mon->fds, next) {
1678 if (strcmp(monfd->name, fdname) != 0) {
1682 QLIST_REMOVE(monfd, next);
1684 g_free(monfd->name);
1689 error_setg(errp, QERR_FD_NOT_FOUND, fdname);
1692 static void hmp_loadvm(Monitor *mon, const QDict *qdict)
1694 int saved_vm_running = runstate_is_running();
1695 const char *name = qdict_get_str(qdict, "name");
1697 vm_stop(RUN_STATE_RESTORE_VM);
1699 if (load_vmstate(name) == 0 && saved_vm_running) {
1704 int monitor_get_fd(Monitor *mon, const char *fdname, Error **errp)
1708 QLIST_FOREACH(monfd, &mon->fds, next) {
1711 if (strcmp(monfd->name, fdname) != 0) {
1717 /* caller takes ownership of fd */
1718 QLIST_REMOVE(monfd, next);
1719 g_free(monfd->name);
1725 error_setg(errp, "File descriptor named '%s' has not been found", fdname);
1729 static void monitor_fdset_cleanup(MonFdset *mon_fdset)
1731 MonFdsetFd *mon_fdset_fd;
1732 MonFdsetFd *mon_fdset_fd_next;
1734 QLIST_FOREACH_SAFE(mon_fdset_fd, &mon_fdset->fds, next, mon_fdset_fd_next) {
1735 if ((mon_fdset_fd->removed ||
1736 (QLIST_EMPTY(&mon_fdset->dup_fds) && mon_refcount == 0)) &&
1737 runstate_is_running()) {
1738 close(mon_fdset_fd->fd);
1739 g_free(mon_fdset_fd->opaque);
1740 QLIST_REMOVE(mon_fdset_fd, next);
1741 g_free(mon_fdset_fd);
1745 if (QLIST_EMPTY(&mon_fdset->fds) && QLIST_EMPTY(&mon_fdset->dup_fds)) {
1746 QLIST_REMOVE(mon_fdset, next);
1751 static void monitor_fdsets_cleanup(void)
1753 MonFdset *mon_fdset;
1754 MonFdset *mon_fdset_next;
1756 QLIST_FOREACH_SAFE(mon_fdset, &mon_fdsets, next, mon_fdset_next) {
1757 monitor_fdset_cleanup(mon_fdset);
1761 AddfdInfo *qmp_add_fd(bool has_fdset_id, int64_t fdset_id, bool has_opaque,
1762 const char *opaque, Error **errp)
1765 Monitor *mon = cur_mon;
1768 fd = qemu_chr_fe_get_msgfd(mon->chr);
1770 error_setg(errp, QERR_FD_NOT_SUPPLIED);
1774 fdinfo = monitor_fdset_add_fd(fd, has_fdset_id, fdset_id,
1775 has_opaque, opaque, errp);
1787 void qmp_remove_fd(int64_t fdset_id, bool has_fd, int64_t fd, Error **errp)
1789 MonFdset *mon_fdset;
1790 MonFdsetFd *mon_fdset_fd;
1793 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
1794 if (mon_fdset->id != fdset_id) {
1797 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
1799 if (mon_fdset_fd->fd != fd) {
1802 mon_fdset_fd->removed = true;
1805 mon_fdset_fd->removed = true;
1808 if (has_fd && !mon_fdset_fd) {
1811 monitor_fdset_cleanup(mon_fdset);
1817 snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64 ", fd:%" PRId64,
1820 snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64, fdset_id);
1822 error_setg(errp, QERR_FD_NOT_FOUND, fd_str);
1825 FdsetInfoList *qmp_query_fdsets(Error **errp)
1827 MonFdset *mon_fdset;
1828 MonFdsetFd *mon_fdset_fd;
1829 FdsetInfoList *fdset_list = NULL;
1831 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
1832 FdsetInfoList *fdset_info = g_malloc0(sizeof(*fdset_info));
1833 FdsetFdInfoList *fdsetfd_list = NULL;
1835 fdset_info->value = g_malloc0(sizeof(*fdset_info->value));
1836 fdset_info->value->fdset_id = mon_fdset->id;
1838 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
1839 FdsetFdInfoList *fdsetfd_info;
1841 fdsetfd_info = g_malloc0(sizeof(*fdsetfd_info));
1842 fdsetfd_info->value = g_malloc0(sizeof(*fdsetfd_info->value));
1843 fdsetfd_info->value->fd = mon_fdset_fd->fd;
1844 if (mon_fdset_fd->opaque) {
1845 fdsetfd_info->value->has_opaque = true;
1846 fdsetfd_info->value->opaque = g_strdup(mon_fdset_fd->opaque);
1848 fdsetfd_info->value->has_opaque = false;
1851 fdsetfd_info->next = fdsetfd_list;
1852 fdsetfd_list = fdsetfd_info;
1855 fdset_info->value->fds = fdsetfd_list;
1857 fdset_info->next = fdset_list;
1858 fdset_list = fdset_info;
1864 AddfdInfo *monitor_fdset_add_fd(int fd, bool has_fdset_id, int64_t fdset_id,
1865 bool has_opaque, const char *opaque,
1868 MonFdset *mon_fdset = NULL;
1869 MonFdsetFd *mon_fdset_fd;
1873 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
1874 /* Break if match found or match impossible due to ordering by ID */
1875 if (fdset_id <= mon_fdset->id) {
1876 if (fdset_id < mon_fdset->id) {
1884 if (mon_fdset == NULL) {
1885 int64_t fdset_id_prev = -1;
1886 MonFdset *mon_fdset_cur = QLIST_FIRST(&mon_fdsets);
1890 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "fdset-id",
1891 "a non-negative value");
1894 /* Use specified fdset ID */
1895 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
1896 mon_fdset_cur = mon_fdset;
1897 if (fdset_id < mon_fdset_cur->id) {
1902 /* Use first available fdset ID */
1903 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
1904 mon_fdset_cur = mon_fdset;
1905 if (fdset_id_prev == mon_fdset_cur->id - 1) {
1906 fdset_id_prev = mon_fdset_cur->id;
1913 mon_fdset = g_malloc0(sizeof(*mon_fdset));
1915 mon_fdset->id = fdset_id;
1917 mon_fdset->id = fdset_id_prev + 1;
1920 /* The fdset list is ordered by fdset ID */
1921 if (!mon_fdset_cur) {
1922 QLIST_INSERT_HEAD(&mon_fdsets, mon_fdset, next);
1923 } else if (mon_fdset->id < mon_fdset_cur->id) {
1924 QLIST_INSERT_BEFORE(mon_fdset_cur, mon_fdset, next);
1926 QLIST_INSERT_AFTER(mon_fdset_cur, mon_fdset, next);
1930 mon_fdset_fd = g_malloc0(sizeof(*mon_fdset_fd));
1931 mon_fdset_fd->fd = fd;
1932 mon_fdset_fd->removed = false;
1934 mon_fdset_fd->opaque = g_strdup(opaque);
1936 QLIST_INSERT_HEAD(&mon_fdset->fds, mon_fdset_fd, next);
1938 fdinfo = g_malloc0(sizeof(*fdinfo));
1939 fdinfo->fdset_id = mon_fdset->id;
1940 fdinfo->fd = mon_fdset_fd->fd;
1945 int monitor_fdset_get_fd(int64_t fdset_id, int flags)
1948 MonFdset *mon_fdset;
1949 MonFdsetFd *mon_fdset_fd;
1952 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
1953 if (mon_fdset->id != fdset_id) {
1956 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
1957 mon_fd_flags = fcntl(mon_fdset_fd->fd, F_GETFL);
1958 if (mon_fd_flags == -1) {
1962 if ((flags & O_ACCMODE) == (mon_fd_flags & O_ACCMODE)) {
1963 return mon_fdset_fd->fd;
1975 int monitor_fdset_dup_fd_add(int64_t fdset_id, int dup_fd)
1977 MonFdset *mon_fdset;
1978 MonFdsetFd *mon_fdset_fd_dup;
1980 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
1981 if (mon_fdset->id != fdset_id) {
1984 QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
1985 if (mon_fdset_fd_dup->fd == dup_fd) {
1989 mon_fdset_fd_dup = g_malloc0(sizeof(*mon_fdset_fd_dup));
1990 mon_fdset_fd_dup->fd = dup_fd;
1991 QLIST_INSERT_HEAD(&mon_fdset->dup_fds, mon_fdset_fd_dup, next);
1997 static int monitor_fdset_dup_fd_find_remove(int dup_fd, bool remove)
1999 MonFdset *mon_fdset;
2000 MonFdsetFd *mon_fdset_fd_dup;
2002 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2003 QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
2004 if (mon_fdset_fd_dup->fd == dup_fd) {
2006 QLIST_REMOVE(mon_fdset_fd_dup, next);
2007 if (QLIST_EMPTY(&mon_fdset->dup_fds)) {
2008 monitor_fdset_cleanup(mon_fdset);
2012 return mon_fdset->id;
2020 int monitor_fdset_dup_fd_find(int dup_fd)
2022 return monitor_fdset_dup_fd_find_remove(dup_fd, false);
2025 void monitor_fdset_dup_fd_remove(int dup_fd)
2027 monitor_fdset_dup_fd_find_remove(dup_fd, true);
2030 int monitor_fd_param(Monitor *mon, const char *fdname, Error **errp)
2033 Error *local_err = NULL;
2035 if (!qemu_isdigit(fdname[0]) && mon) {
2036 fd = monitor_get_fd(mon, fdname, &local_err);
2038 fd = qemu_parse_fd(fdname);
2040 error_setg(&local_err, "Invalid file descriptor number '%s'",
2045 error_propagate(errp, local_err);
2054 /* Please update hmp-commands.hx when adding or changing commands */
2055 static mon_cmd_t info_cmds[] = {
2056 #include "hmp-commands-info.h"
2060 /* mon_cmds and info_cmds would be sorted at runtime */
2061 static mon_cmd_t mon_cmds[] = {
2062 #include "hmp-commands.h"
2066 static const mon_cmd_t qmp_cmds[] = {
2067 #include "qmp-commands-old.h"
2071 /*******************************************************************/
2073 static const char *pch;
2074 static sigjmp_buf expr_env;
2077 static void GCC_FMT_ATTR(2, 3) QEMU_NORETURN
2078 expr_error(Monitor *mon, const char *fmt, ...)
2082 monitor_vprintf(mon, fmt, ap);
2083 monitor_printf(mon, "\n");
2085 siglongjmp(expr_env, 1);
2088 /* return 0 if OK, -1 if not found */
2089 static int get_monitor_def(target_long *pval, const char *name)
2091 const MonitorDef *md = target_monitor_defs();
2098 for(; md->name != NULL; md++) {
2099 if (compare_cmd(name, md->name)) {
2100 if (md->get_value) {
2101 *pval = md->get_value(md, md->offset);
2103 CPUArchState *env = mon_get_cpu_env();
2104 ptr = (uint8_t *)env + md->offset;
2107 *pval = *(int32_t *)ptr;
2110 *pval = *(target_long *)ptr;
2123 static void next(void)
2127 while (qemu_isspace(*pch))
2132 static int64_t expr_sum(Monitor *mon);
2134 static int64_t expr_unary(Monitor *mon)
2143 n = expr_unary(mon);
2147 n = -expr_unary(mon);
2151 n = ~expr_unary(mon);
2157 expr_error(mon, "')' expected");
2164 expr_error(mon, "character constant expected");
2168 expr_error(mon, "missing terminating \' character");
2178 while ((*pch >= 'a' && *pch <= 'z') ||
2179 (*pch >= 'A' && *pch <= 'Z') ||
2180 (*pch >= '0' && *pch <= '9') ||
2181 *pch == '_' || *pch == '.') {
2182 if ((q - buf) < sizeof(buf) - 1)
2186 while (qemu_isspace(*pch))
2189 ret = get_monitor_def(®, buf);
2191 expr_error(mon, "unknown register");
2196 expr_error(mon, "unexpected end of expression");
2201 n = strtoull(pch, &p, 0);
2202 if (errno == ERANGE) {
2203 expr_error(mon, "number too large");
2206 expr_error(mon, "invalid char '%c' in expression", *p);
2209 while (qemu_isspace(*pch))
2217 static int64_t expr_prod(Monitor *mon)
2222 val = expr_unary(mon);
2225 if (op != '*' && op != '/' && op != '%')
2228 val2 = expr_unary(mon);
2237 expr_error(mon, "division by zero");
2248 static int64_t expr_logic(Monitor *mon)
2253 val = expr_prod(mon);
2256 if (op != '&' && op != '|' && op != '^')
2259 val2 = expr_prod(mon);
2276 static int64_t expr_sum(Monitor *mon)
2281 val = expr_logic(mon);
2284 if (op != '+' && op != '-')
2287 val2 = expr_logic(mon);
2296 static int get_expr(Monitor *mon, int64_t *pval, const char **pp)
2299 if (sigsetjmp(expr_env, 0)) {
2303 while (qemu_isspace(*pch))
2305 *pval = expr_sum(mon);
2310 static int get_double(Monitor *mon, double *pval, const char **pp)
2312 const char *p = *pp;
2316 d = strtod(p, &tailp);
2318 monitor_printf(mon, "Number expected\n");
2321 if (d != d || d - d != 0) {
2322 /* NaN or infinity */
2323 monitor_printf(mon, "Bad number\n");
2332 * Store the command-name in cmdname, and return a pointer to
2333 * the remaining of the command string.
2335 static const char *get_command_name(const char *cmdline,
2336 char *cmdname, size_t nlen)
2339 const char *p, *pstart;
2342 while (qemu_isspace(*p))
2347 while (*p != '\0' && *p != '/' && !qemu_isspace(*p))
2352 memcpy(cmdname, pstart, len);
2353 cmdname[len] = '\0';
2358 * Read key of 'type' into 'key' and return the current
2361 static char *key_get_info(const char *type, char **key)
2369 p = strchr(type, ':');
2376 str = g_malloc(len + 1);
2377 memcpy(str, type, len);
2384 static int default_fmt_format = 'x';
2385 static int default_fmt_size = 4;
2387 static int is_valid_option(const char *c, const char *typestr)
2395 typestr = strstr(typestr, option);
2396 return (typestr != NULL);
2399 static const mon_cmd_t *search_dispatch_table(const mon_cmd_t *disp_table,
2400 const char *cmdname)
2402 const mon_cmd_t *cmd;
2404 for (cmd = disp_table; cmd->name != NULL; cmd++) {
2405 if (compare_cmd(cmdname, cmd->name)) {
2413 static const mon_cmd_t *qmp_find_cmd(const char *cmdname)
2415 return search_dispatch_table(qmp_cmds, cmdname);
2419 * Parse command name from @cmdp according to command table @table.
2420 * If blank, return NULL.
2421 * Else, if no valid command can be found, report to @mon, and return
2423 * Else, change @cmdp to point right behind the name, and return its
2424 * command table entry.
2425 * Do not assume the return value points into @table! It doesn't when
2426 * the command is found in a sub-command table.
2428 static const mon_cmd_t *monitor_parse_command(Monitor *mon,
2433 const mon_cmd_t *cmd;
2436 /* extract the command name */
2437 p = get_command_name(*cmdp, cmdname, sizeof(cmdname));
2441 cmd = search_dispatch_table(table, cmdname);
2443 monitor_printf(mon, "unknown command: '%.*s'\n",
2444 (int)(p - *cmdp), *cmdp);
2448 /* filter out following useless space */
2449 while (qemu_isspace(*p)) {
2454 /* search sub command */
2455 if (cmd->sub_table != NULL && *p != '\0') {
2456 return monitor_parse_command(mon, cmdp, cmd->sub_table);
2463 * Parse arguments for @cmd.
2464 * If it can't be parsed, report to @mon, and return NULL.
2465 * Else, insert command arguments into a QDict, and return it.
2466 * Note: On success, caller has to free the QDict structure.
2469 static QDict *monitor_parse_arguments(Monitor *mon,
2471 const mon_cmd_t *cmd)
2473 const char *typestr;
2476 const char *p = *endp;
2478 QDict *qdict = qdict_new();
2480 /* parse the parameters */
2481 typestr = cmd->args_type;
2483 typestr = key_get_info(typestr, &key);
2495 while (qemu_isspace(*p))
2497 if (*typestr == '?') {
2500 /* no optional string: NULL argument */
2504 ret = get_str(buf, sizeof(buf), &p);
2508 monitor_printf(mon, "%s: filename expected\n",
2512 monitor_printf(mon, "%s: block device name expected\n",
2516 monitor_printf(mon, "%s: string expected\n", cmd->name);
2521 qdict_put(qdict, key, qstring_from_str(buf));
2526 QemuOptsList *opts_list;
2529 opts_list = qemu_find_opts(key);
2530 if (!opts_list || opts_list->desc->name) {
2533 while (qemu_isspace(*p)) {
2538 if (get_str(buf, sizeof(buf), &p) < 0) {
2541 opts = qemu_opts_parse_noisily(opts_list, buf, true);
2545 qemu_opts_to_qdict(opts, qdict);
2546 qemu_opts_del(opts);
2551 int count, format, size;
2553 while (qemu_isspace(*p))
2559 if (qemu_isdigit(*p)) {
2561 while (qemu_isdigit(*p)) {
2562 count = count * 10 + (*p - '0');
2600 if (*p != '\0' && !qemu_isspace(*p)) {
2601 monitor_printf(mon, "invalid char in format: '%c'\n",
2606 format = default_fmt_format;
2607 if (format != 'i') {
2608 /* for 'i', not specifying a size gives -1 as size */
2610 size = default_fmt_size;
2611 default_fmt_size = size;
2613 default_fmt_format = format;
2616 format = default_fmt_format;
2617 if (format != 'i') {
2618 size = default_fmt_size;
2623 qdict_put(qdict, "count", qint_from_int(count));
2624 qdict_put(qdict, "format", qint_from_int(format));
2625 qdict_put(qdict, "size", qint_from_int(size));
2634 while (qemu_isspace(*p))
2636 if (*typestr == '?' || *typestr == '.') {
2637 if (*typestr == '?') {
2645 while (qemu_isspace(*p))
2654 if (get_expr(mon, &val, &p))
2656 /* Check if 'i' is greater than 32-bit */
2657 if ((c == 'i') && ((val >> 32) & 0xffffffff)) {
2658 monitor_printf(mon, "\'%s\' has failed: ", cmd->name);
2659 monitor_printf(mon, "integer is for 32-bit values\n");
2661 } else if (c == 'M') {
2663 monitor_printf(mon, "enter a positive value\n");
2668 qdict_put(qdict, key, qint_from_int(val));
2676 while (qemu_isspace(*p)) {
2679 if (*typestr == '?') {
2685 val = strtosz(p, &end);
2687 monitor_printf(mon, "invalid size\n");
2690 qdict_put(qdict, key, qint_from_int(val));
2698 while (qemu_isspace(*p))
2700 if (*typestr == '?') {
2706 if (get_double(mon, &val, &p) < 0) {
2709 if (p[0] && p[1] == 's') {
2712 val /= 1e3; p += 2; break;
2714 val /= 1e6; p += 2; break;
2716 val /= 1e9; p += 2; break;
2719 if (*p && !qemu_isspace(*p)) {
2720 monitor_printf(mon, "Unknown unit suffix\n");
2723 qdict_put(qdict, key, qfloat_from_double(val));
2731 while (qemu_isspace(*p)) {
2735 while (qemu_isgraph(*p)) {
2738 if (p - beg == 2 && !memcmp(beg, "on", p - beg)) {
2740 } else if (p - beg == 3 && !memcmp(beg, "off", p - beg)) {
2743 monitor_printf(mon, "Expected 'on' or 'off'\n");
2746 qdict_put(qdict, key, qbool_from_bool(val));
2751 const char *tmp = p;
2758 while (qemu_isspace(*p))
2763 if(!is_valid_option(p, typestr)) {
2765 monitor_printf(mon, "%s: unsupported option -%c\n",
2777 qdict_put(qdict, key, qbool_from_bool(true));
2784 /* package all remaining string */
2787 while (qemu_isspace(*p)) {
2790 if (*typestr == '?') {
2793 /* no remaining string: NULL argument */
2799 monitor_printf(mon, "%s: string expected\n",
2803 qdict_put(qdict, key, qstring_from_str(p));
2809 monitor_printf(mon, "%s: unknown type '%c'\n", cmd->name, c);
2815 /* check that all arguments were parsed */
2816 while (qemu_isspace(*p))
2819 monitor_printf(mon, "%s: extraneous characters at the end of line\n",
2832 static void handle_hmp_command(Monitor *mon, const char *cmdline)
2835 const mon_cmd_t *cmd;
2837 cmd = monitor_parse_command(mon, &cmdline, mon->cmd_table);
2842 qdict = monitor_parse_arguments(mon, &cmdline, cmd);
2844 monitor_printf(mon, "Try \"help %s\" for more information\n",
2849 cmd->mhandler.cmd(mon, qdict);
2853 static void cmd_completion(Monitor *mon, const char *name, const char *list)
2855 const char *p, *pstart;
2864 p = pstart + strlen(pstart);
2866 if (len > sizeof(cmd) - 2)
2867 len = sizeof(cmd) - 2;
2868 memcpy(cmd, pstart, len);
2870 if (name[0] == '\0' || !strncmp(name, cmd, strlen(name))) {
2871 readline_add_completion(mon->rs, cmd);
2879 static void file_completion(Monitor *mon, const char *input)
2884 char file[1024], file_prefix[1024];
2888 p = strrchr(input, '/');
2891 pstrcpy(file_prefix, sizeof(file_prefix), input);
2892 pstrcpy(path, sizeof(path), ".");
2894 input_path_len = p - input + 1;
2895 memcpy(path, input, input_path_len);
2896 if (input_path_len > sizeof(path) - 1)
2897 input_path_len = sizeof(path) - 1;
2898 path[input_path_len] = '\0';
2899 pstrcpy(file_prefix, sizeof(file_prefix), p + 1);
2902 ffs = opendir(path);
2911 if (strcmp(d->d_name, ".") == 0 || strcmp(d->d_name, "..") == 0) {
2915 if (strstart(d->d_name, file_prefix, NULL)) {
2916 memcpy(file, input, input_path_len);
2917 if (input_path_len < sizeof(file))
2918 pstrcpy(file + input_path_len, sizeof(file) - input_path_len,
2920 /* stat the file to find out if it's a directory.
2921 * In that case add a slash to speed up typing long paths
2923 if (stat(file, &sb) == 0 && S_ISDIR(sb.st_mode)) {
2924 pstrcat(file, sizeof(file), "/");
2926 readline_add_completion(mon->rs, file);
2932 static const char *next_arg_type(const char *typestr)
2934 const char *p = strchr(typestr, ':');
2935 return (p != NULL ? ++p : typestr);
2938 static void add_completion_option(ReadLineState *rs, const char *str,
2941 if (!str || !option) {
2944 if (!strncmp(option, str, strlen(str))) {
2945 readline_add_completion(rs, option);
2949 void chardev_add_completion(ReadLineState *rs, int nb_args, const char *str)
2952 ChardevBackendInfoList *list, *start;
2958 readline_set_completion_index(rs, len);
2960 start = list = qmp_query_chardev_backends(NULL);
2962 const char *chr_name = list->value->name;
2964 if (!strncmp(chr_name, str, len)) {
2965 readline_add_completion(rs, chr_name);
2969 qapi_free_ChardevBackendInfoList(start);
2972 void netdev_add_completion(ReadLineState *rs, int nb_args, const char *str)
2981 readline_set_completion_index(rs, len);
2982 for (i = 0; NetClientOptionsKind_lookup[i]; i++) {
2983 add_completion_option(rs, str, NetClientOptionsKind_lookup[i]);
2987 void device_add_completion(ReadLineState *rs, int nb_args, const char *str)
2997 readline_set_completion_index(rs, len);
2998 list = elt = object_class_get_list(TYPE_DEVICE, false);
3001 DeviceClass *dc = OBJECT_CLASS_CHECK(DeviceClass, elt->data,
3003 name = object_class_get_name(OBJECT_CLASS(dc));
3005 if (!dc->cannot_instantiate_with_device_add_yet
3006 && !strncmp(name, str, len)) {
3007 readline_add_completion(rs, name);
3014 void object_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_USER_CREATABLE, false);
3029 name = object_class_get_name(OBJECT_CLASS(elt->data));
3030 if (!strncmp(name, str, len) && strcmp(name, TYPE_USER_CREATABLE)) {
3031 readline_add_completion(rs, name);
3038 static void peripheral_device_del_completion(ReadLineState *rs,
3039 const char *str, size_t len)
3041 Object *peripheral = container_get(qdev_get_machine(), "/peripheral");
3042 GSList *list, *item;
3044 list = qdev_build_hotpluggable_device_list(peripheral);
3049 for (item = list; item; item = g_slist_next(item)) {
3050 DeviceState *dev = item->data;
3052 if (dev->id && !strncmp(str, dev->id, len)) {
3053 readline_add_completion(rs, dev->id);
3060 void chardev_remove_completion(ReadLineState *rs, int nb_args, const char *str)
3063 ChardevInfoList *list, *start;
3069 readline_set_completion_index(rs, len);
3071 start = list = qmp_query_chardev(NULL);
3073 ChardevInfo *chr = list->value;
3075 if (!strncmp(chr->label, str, len)) {
3076 readline_add_completion(rs, chr->label);
3080 qapi_free_ChardevInfoList(start);
3083 static void ringbuf_completion(ReadLineState *rs, const char *str)
3086 ChardevInfoList *list, *start;
3089 readline_set_completion_index(rs, len);
3091 start = list = qmp_query_chardev(NULL);
3093 ChardevInfo *chr_info = list->value;
3095 if (!strncmp(chr_info->label, str, len)) {
3096 CharDriverState *chr = qemu_chr_find(chr_info->label);
3097 if (chr && chr_is_ringbuf(chr)) {
3098 readline_add_completion(rs, chr_info->label);
3103 qapi_free_ChardevInfoList(start);
3106 void ringbuf_write_completion(ReadLineState *rs, int nb_args, const char *str)
3111 ringbuf_completion(rs, str);
3114 void device_del_completion(ReadLineState *rs, int nb_args, const char *str)
3123 readline_set_completion_index(rs, len);
3124 peripheral_device_del_completion(rs, str, len);
3127 void object_del_completion(ReadLineState *rs, int nb_args, const char *str)
3129 ObjectPropertyInfoList *list, *start;
3136 readline_set_completion_index(rs, len);
3138 start = list = qmp_qom_list("/objects", NULL);
3140 ObjectPropertyInfo *info = list->value;
3142 if (!strncmp(info->type, "child<", 5)
3143 && !strncmp(info->name, str, len)) {
3144 readline_add_completion(rs, info->name);
3148 qapi_free_ObjectPropertyInfoList(start);
3151 void sendkey_completion(ReadLineState *rs, int nb_args, const char *str)
3160 sep = strrchr(str, '-');
3165 readline_set_completion_index(rs, len);
3166 for (i = 0; i < Q_KEY_CODE_MAX; i++) {
3167 if (!strncmp(str, QKeyCode_lookup[i], len)) {
3168 readline_add_completion(rs, QKeyCode_lookup[i]);
3173 void set_link_completion(ReadLineState *rs, int nb_args, const char *str)
3178 readline_set_completion_index(rs, len);
3180 NetClientState *ncs[MAX_QUEUE_NUM];
3182 count = qemu_find_net_clients_except(NULL, ncs,
3183 NET_CLIENT_OPTIONS_KIND_NONE,
3185 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3186 const char *name = ncs[i]->name;
3187 if (!strncmp(str, name, len)) {
3188 readline_add_completion(rs, name);
3191 } else if (nb_args == 3) {
3192 add_completion_option(rs, str, "on");
3193 add_completion_option(rs, str, "off");
3197 void netdev_del_completion(ReadLineState *rs, int nb_args, const char *str)
3200 NetClientState *ncs[MAX_QUEUE_NUM];
3207 readline_set_completion_index(rs, len);
3208 count = qemu_find_net_clients_except(NULL, ncs, NET_CLIENT_OPTIONS_KIND_NIC,
3210 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3212 const char *name = ncs[i]->name;
3213 if (strncmp(str, name, len)) {
3216 opts = qemu_opts_find(qemu_find_opts_err("netdev", NULL), name);
3218 readline_add_completion(rs, name);
3223 void trace_event_completion(ReadLineState *rs, int nb_args, const char *str)
3228 readline_set_completion_index(rs, len);
3231 for (id = 0; id < trace_event_count(); id++) {
3232 const char *event_name = trace_event_get_name(trace_event_id(id));
3233 if (!strncmp(str, event_name, len)) {
3234 readline_add_completion(rs, event_name);
3237 } else if (nb_args == 3) {
3238 add_completion_option(rs, str, "on");
3239 add_completion_option(rs, str, "off");
3243 void watchdog_action_completion(ReadLineState *rs, int nb_args, const char *str)
3250 readline_set_completion_index(rs, strlen(str));
3251 for (i = 0; WatchdogExpirationAction_lookup[i]; i++) {
3252 add_completion_option(rs, str, WatchdogExpirationAction_lookup[i]);
3256 void migrate_set_capability_completion(ReadLineState *rs, int nb_args,
3262 readline_set_completion_index(rs, len);
3265 for (i = 0; i < MIGRATION_CAPABILITY_MAX; i++) {
3266 const char *name = MigrationCapability_lookup[i];
3267 if (!strncmp(str, name, len)) {
3268 readline_add_completion(rs, name);
3271 } else if (nb_args == 3) {
3272 add_completion_option(rs, str, "on");
3273 add_completion_option(rs, str, "off");
3277 void migrate_set_parameter_completion(ReadLineState *rs, int nb_args,
3283 readline_set_completion_index(rs, len);
3286 for (i = 0; i < MIGRATION_PARAMETER_MAX; i++) {
3287 const char *name = MigrationParameter_lookup[i];
3288 if (!strncmp(str, name, len)) {
3289 readline_add_completion(rs, name);
3295 void host_net_add_completion(ReadLineState *rs, int nb_args, const char *str)
3303 readline_set_completion_index(rs, len);
3304 for (i = 0; host_net_devices[i]; i++) {
3305 if (!strncmp(host_net_devices[i], str, len)) {
3306 readline_add_completion(rs, host_net_devices[i]);
3311 void host_net_remove_completion(ReadLineState *rs, int nb_args, const char *str)
3313 NetClientState *ncs[MAX_QUEUE_NUM];
3317 readline_set_completion_index(rs, len);
3319 count = qemu_find_net_clients_except(NULL, ncs,
3320 NET_CLIENT_OPTIONS_KIND_NONE,
3322 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3326 if (net_hub_id_for_client(ncs[i], &id)) {
3329 snprintf(name, sizeof(name), "%d", id);
3330 if (!strncmp(str, name, len)) {
3331 readline_add_completion(rs, name);
3335 } else if (nb_args == 3) {
3336 count = qemu_find_net_clients_except(NULL, ncs,
3337 NET_CLIENT_OPTIONS_KIND_NIC,
3339 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3343 if (ncs[i]->info->type == NET_CLIENT_OPTIONS_KIND_HUBPORT ||
3344 net_hub_id_for_client(ncs[i], &id)) {
3347 name = ncs[i]->name;
3348 if (!strncmp(str, name, len)) {
3349 readline_add_completion(rs, name);
3356 static void vm_completion(ReadLineState *rs, const char *str)
3359 BlockDriverState *bs = NULL;
3362 readline_set_completion_index(rs, len);
3363 while ((bs = bdrv_next(bs))) {
3364 SnapshotInfoList *snapshots, *snapshot;
3366 if (!bdrv_can_snapshot(bs)) {
3369 if (bdrv_query_snapshot_info_list(bs, &snapshots, NULL)) {
3372 snapshot = snapshots;
3374 char *completion = snapshot->value->name;
3375 if (!strncmp(str, completion, len)) {
3376 readline_add_completion(rs, completion);
3378 completion = snapshot->value->id;
3379 if (!strncmp(str, completion, len)) {
3380 readline_add_completion(rs, completion);
3382 snapshot = snapshot->next;
3384 qapi_free_SnapshotInfoList(snapshots);
3389 void delvm_completion(ReadLineState *rs, int nb_args, const char *str)
3392 vm_completion(rs, str);
3396 void loadvm_completion(ReadLineState *rs, int nb_args, const char *str)
3399 vm_completion(rs, str);
3403 static void monitor_find_completion_by_table(Monitor *mon,
3404 const mon_cmd_t *cmd_table,
3408 const char *cmdname;
3410 const char *ptype, *str, *name;
3411 const mon_cmd_t *cmd;
3412 BlockDriverState *bs;
3415 /* command completion */
3420 readline_set_completion_index(mon->rs, strlen(cmdname));
3421 for (cmd = cmd_table; cmd->name != NULL; cmd++) {
3422 cmd_completion(mon, cmdname, cmd->name);
3425 /* find the command */
3426 for (cmd = cmd_table; cmd->name != NULL; cmd++) {
3427 if (compare_cmd(args[0], cmd->name)) {
3435 if (cmd->sub_table) {
3436 /* do the job again */
3437 monitor_find_completion_by_table(mon, cmd->sub_table,
3438 &args[1], nb_args - 1);
3441 if (cmd->command_completion) {
3442 cmd->command_completion(mon->rs, nb_args, args[nb_args - 1]);
3446 ptype = next_arg_type(cmd->args_type);
3447 for(i = 0; i < nb_args - 2; i++) {
3448 if (*ptype != '\0') {
3449 ptype = next_arg_type(ptype);
3450 while (*ptype == '?')
3451 ptype = next_arg_type(ptype);
3454 str = args[nb_args - 1];
3455 while (*ptype == '-' && ptype[1] != '\0') {
3456 ptype = next_arg_type(ptype);
3460 /* file completion */
3461 readline_set_completion_index(mon->rs, strlen(str));
3462 file_completion(mon, str);
3465 /* block device name completion */
3466 readline_set_completion_index(mon->rs, strlen(str));
3467 for (bs = bdrv_next(NULL); bs; bs = bdrv_next(bs)) {
3468 name = bdrv_get_device_name(bs);
3469 if (str[0] == '\0' ||
3470 !strncmp(name, str, strlen(str))) {
3471 readline_add_completion(mon->rs, name);
3477 if (!strcmp(cmd->name, "help|?")) {
3478 monitor_find_completion_by_table(mon, cmd_table,
3479 &args[1], nb_args - 1);
3488 static void monitor_find_completion(void *opaque,
3489 const char *cmdline)
3491 Monitor *mon = opaque;
3492 char *args[MAX_ARGS];
3495 /* 1. parse the cmdline */
3496 if (parse_cmdline(cmdline, &nb_args, args) < 0) {
3500 /* if the line ends with a space, it means we want to complete the
3502 len = strlen(cmdline);
3503 if (len > 0 && qemu_isspace(cmdline[len - 1])) {
3504 if (nb_args >= MAX_ARGS) {
3507 args[nb_args++] = g_strdup("");
3510 /* 2. auto complete according to args */
3511 monitor_find_completion_by_table(mon, mon->cmd_table, args, nb_args);
3514 free_cmdline_args(args, nb_args);
3517 static int monitor_can_read(void *opaque)
3519 Monitor *mon = opaque;
3521 return (mon->suspend_cnt == 0) ? 1 : 0;
3524 static bool invalid_qmp_mode(const Monitor *mon, const mon_cmd_t *cmd,
3527 bool is_cap = cmd->mhandler.cmd_new == qmp_capabilities;
3529 if (is_cap && mon->qmp.in_command_mode) {
3530 error_set(errp, ERROR_CLASS_COMMAND_NOT_FOUND,
3531 "Capabilities negotiation is already complete, command "
3532 "'%s' ignored", cmd->name);
3535 if (!is_cap && !mon->qmp.in_command_mode) {
3536 error_set(errp, ERROR_CLASS_COMMAND_NOT_FOUND,
3537 "Expecting capabilities negotiation with "
3538 "'qmp_capabilities' before command '%s'", cmd->name);
3545 * Argument validation rules:
3547 * 1. The argument must exist in cmd_args qdict
3548 * 2. The argument type must be the expected one
3550 * Special case: If the argument doesn't exist in cmd_args and
3551 * the QMP_ACCEPT_UNKNOWNS flag is set, then the
3552 * checking is skipped for it.
3554 static void check_client_args_type(const QDict *client_args,
3555 const QDict *cmd_args, int flags,
3558 const QDictEntry *ent;
3560 for (ent = qdict_first(client_args); ent;ent = qdict_next(client_args,ent)){
3563 const QObject *client_arg = qdict_entry_value(ent);
3564 const char *client_arg_name = qdict_entry_key(ent);
3566 obj = qdict_get(cmd_args, client_arg_name);
3568 if (flags & QMP_ACCEPT_UNKNOWNS) {
3569 /* handler accepts unknowns */
3572 /* client arg doesn't exist */
3573 error_setg(errp, QERR_INVALID_PARAMETER, client_arg_name);
3577 arg_type = qobject_to_qstring(obj);
3578 assert(arg_type != NULL);
3580 /* check if argument's type is correct */
3581 switch (qstring_get_str(arg_type)[0]) {
3585 if (qobject_type(client_arg) != QTYPE_QSTRING) {
3586 error_setg(errp, QERR_INVALID_PARAMETER_TYPE,
3587 client_arg_name, "string");
3595 if (qobject_type(client_arg) != QTYPE_QINT) {
3596 error_setg(errp, QERR_INVALID_PARAMETER_TYPE,
3597 client_arg_name, "int");
3602 if (qobject_type(client_arg) != QTYPE_QINT &&
3603 qobject_type(client_arg) != QTYPE_QFLOAT) {
3604 error_setg(errp, QERR_INVALID_PARAMETER_TYPE,
3605 client_arg_name, "number");
3611 if (qobject_type(client_arg) != QTYPE_QBOOL) {
3612 error_setg(errp, QERR_INVALID_PARAMETER_TYPE,
3613 client_arg_name, "bool");
3618 assert(flags & QMP_ACCEPT_UNKNOWNS);
3621 /* Any QObject can be passed. */
3626 * These types are not supported by QMP and thus are not
3627 * handled here. Fall through.
3636 * - Check if the client has passed all mandatory args
3637 * - Set special flags for argument validation
3639 static void check_mandatory_args(const QDict *cmd_args,
3640 const QDict *client_args, int *flags,
3643 const QDictEntry *ent;
3645 for (ent = qdict_first(cmd_args); ent; ent = qdict_next(cmd_args, ent)) {
3646 const char *cmd_arg_name = qdict_entry_key(ent);
3647 QString *type = qobject_to_qstring(qdict_entry_value(ent));
3648 assert(type != NULL);
3650 if (qstring_get_str(type)[0] == 'O') {
3651 assert((*flags & QMP_ACCEPT_UNKNOWNS) == 0);
3652 *flags |= QMP_ACCEPT_UNKNOWNS;
3653 } else if (qstring_get_str(type)[0] != '-' &&
3654 qstring_get_str(type)[1] != '?' &&
3655 !qdict_haskey(client_args, cmd_arg_name)) {
3656 error_setg(errp, QERR_MISSING_PARAMETER, cmd_arg_name);
3662 static QDict *qdict_from_args_type(const char *args_type)
3666 QString *key, *type, *cur_qs;
3668 assert(args_type != NULL);
3670 qdict = qdict_new();
3672 if (args_type == NULL || args_type[0] == '\0') {
3673 /* no args, empty qdict */
3677 key = qstring_new();
3678 type = qstring_new();
3683 switch (args_type[i]) {
3686 qdict_put(qdict, qstring_get_str(key), type);
3688 if (args_type[i] == '\0') {
3691 type = qstring_new(); /* qdict has ref */
3692 cur_qs = key = qstring_new();
3698 qstring_append_chr(cur_qs, args_type[i]);
3708 * Client argument checking rules:
3710 * 1. Client must provide all mandatory arguments
3711 * 2. Each argument provided by the client must be expected
3712 * 3. Each argument provided by the client must have the type expected
3715 static void qmp_check_client_args(const mon_cmd_t *cmd, QDict *client_args,
3722 cmd_args = qdict_from_args_type(cmd->args_type);
3725 check_mandatory_args(cmd_args, client_args, &flags, &err);
3730 check_client_args_type(client_args, cmd_args, flags, &err);
3733 error_propagate(errp, err);
3738 * Input object checking rules
3740 * 1. Input object must be a dict
3741 * 2. The "execute" key must exist
3742 * 3. The "execute" key must be a string
3743 * 4. If the "arguments" key exists, it must be a dict
3744 * 5. If the "id" key exists, it can be anything (ie. json-value)
3745 * 6. Any argument not listed above is considered invalid
3747 static QDict *qmp_check_input_obj(QObject *input_obj, Error **errp)
3749 const QDictEntry *ent;
3750 int has_exec_key = 0;
3753 if (qobject_type(input_obj) != QTYPE_QDICT) {
3754 error_setg(errp, QERR_QMP_BAD_INPUT_OBJECT, "object");
3758 input_dict = qobject_to_qdict(input_obj);
3760 for (ent = qdict_first(input_dict); ent; ent = qdict_next(input_dict, ent)){
3761 const char *arg_name = qdict_entry_key(ent);
3762 const QObject *arg_obj = qdict_entry_value(ent);
3764 if (!strcmp(arg_name, "execute")) {
3765 if (qobject_type(arg_obj) != QTYPE_QSTRING) {
3766 error_setg(errp, QERR_QMP_BAD_INPUT_OBJECT_MEMBER,
3767 "execute", "string");
3771 } else if (!strcmp(arg_name, "arguments")) {
3772 if (qobject_type(arg_obj) != QTYPE_QDICT) {
3773 error_setg(errp, QERR_QMP_BAD_INPUT_OBJECT_MEMBER,
3774 "arguments", "object");
3777 } else if (!strcmp(arg_name, "id")) {
3778 /* Any string is acceptable as "id", so nothing to check */
3780 error_setg(errp, QERR_QMP_EXTRA_MEMBER, arg_name);
3785 if (!has_exec_key) {
3786 error_setg(errp, QERR_QMP_BAD_INPUT_OBJECT, "execute");
3793 static void handle_qmp_command(JSONMessageParser *parser, QList *tokens)
3795 Error *local_err = NULL;
3796 QObject *obj, *data;
3797 QDict *input, *args;
3798 const mon_cmd_t *cmd;
3799 const char *cmd_name;
3800 Monitor *mon = cur_mon;
3802 args = input = NULL;
3805 obj = json_parser_parse(tokens, NULL);
3807 // FIXME: should be triggered in json_parser_parse()
3808 error_setg(&local_err, QERR_JSON_PARSING);
3812 input = qmp_check_input_obj(obj, &local_err);
3814 qobject_decref(obj);
3818 mon->qmp.id = qdict_get(input, "id");
3819 qobject_incref(mon->qmp.id);
3821 cmd_name = qdict_get_str(input, "execute");
3822 trace_handle_qmp_command(mon, cmd_name);
3823 cmd = qmp_find_cmd(cmd_name);
3825 error_set(&local_err, ERROR_CLASS_COMMAND_NOT_FOUND,
3826 "The command %s has not been found", cmd_name);
3829 if (invalid_qmp_mode(mon, cmd, &local_err)) {
3833 obj = qdict_get(input, "arguments");
3837 args = qobject_to_qdict(obj);
3841 qmp_check_client_args(cmd, args, &local_err);
3846 cmd->mhandler.cmd_new(args, &data, &local_err);
3849 monitor_protocol_emitter(mon, data, local_err);
3850 qobject_decref(data);
3855 static void monitor_qmp_read(void *opaque, const uint8_t *buf, int size)
3857 Monitor *old_mon = cur_mon;
3861 json_message_parser_feed(&cur_mon->qmp.parser, (const char *) buf, size);
3866 static void monitor_read(void *opaque, const uint8_t *buf, int size)
3868 Monitor *old_mon = cur_mon;
3874 for (i = 0; i < size; i++)
3875 readline_handle_byte(cur_mon->rs, buf[i]);
3877 if (size == 0 || buf[size - 1] != 0)
3878 monitor_printf(cur_mon, "corrupted command\n");
3880 handle_hmp_command(cur_mon, (char *)buf);
3886 static void monitor_command_cb(void *opaque, const char *cmdline,
3887 void *readline_opaque)
3889 Monitor *mon = opaque;
3891 monitor_suspend(mon);
3892 handle_hmp_command(mon, cmdline);
3893 monitor_resume(mon);
3896 int monitor_suspend(Monitor *mon)
3904 void monitor_resume(Monitor *mon)
3908 if (--mon->suspend_cnt == 0)
3909 readline_show_prompt(mon->rs);
3912 static QObject *get_qmp_greeting(void)
3914 QObject *ver = NULL;
3916 qmp_marshal_input_query_version(NULL, &ver, NULL);
3917 return qobject_from_jsonf("{'QMP':{'version': %p,'capabilities': []}}",ver);
3920 static void monitor_qmp_event(void *opaque, int event)
3923 Monitor *mon = opaque;
3926 case CHR_EVENT_OPENED:
3927 mon->qmp.in_command_mode = false;
3928 data = get_qmp_greeting();
3929 monitor_json_emitter(mon, data);
3930 qobject_decref(data);
3933 case CHR_EVENT_CLOSED:
3934 json_message_parser_destroy(&mon->qmp.parser);
3935 json_message_parser_init(&mon->qmp.parser, handle_qmp_command);
3937 monitor_fdsets_cleanup();
3942 static void monitor_event(void *opaque, int event)
3944 Monitor *mon = opaque;
3947 case CHR_EVENT_MUX_IN:
3948 qemu_mutex_lock(&mon->out_lock);
3950 qemu_mutex_unlock(&mon->out_lock);
3951 if (mon->reset_seen) {
3952 readline_restart(mon->rs);
3953 monitor_resume(mon);
3956 mon->suspend_cnt = 0;
3960 case CHR_EVENT_MUX_OUT:
3961 if (mon->reset_seen) {
3962 if (mon->suspend_cnt == 0) {
3963 monitor_printf(mon, "\n");
3966 monitor_suspend(mon);
3970 qemu_mutex_lock(&mon->out_lock);
3972 qemu_mutex_unlock(&mon->out_lock);
3975 case CHR_EVENT_OPENED:
3976 monitor_printf(mon, "QEMU %s monitor - type 'help' for more "
3977 "information\n", QEMU_VERSION);
3978 if (!mon->mux_out) {
3979 readline_restart(mon->rs);
3980 readline_show_prompt(mon->rs);
3982 mon->reset_seen = 1;
3986 case CHR_EVENT_CLOSED:
3988 monitor_fdsets_cleanup();
3994 compare_mon_cmd(const void *a, const void *b)
3996 return strcmp(((const mon_cmd_t *)a)->name,
3997 ((const mon_cmd_t *)b)->name);
4000 static void sortcmdlist(void)
4003 int elem_size = sizeof(mon_cmd_t);
4005 array_num = sizeof(mon_cmds)/elem_size-1;
4006 qsort((void *)mon_cmds, array_num, elem_size, compare_mon_cmd);
4008 array_num = sizeof(info_cmds)/elem_size-1;
4009 qsort((void *)info_cmds, array_num, elem_size, compare_mon_cmd);
4021 /* These functions just adapt the readline interface in a typesafe way. We
4022 * could cast function pointers but that discards compiler checks.
4024 static void GCC_FMT_ATTR(2, 3) monitor_readline_printf(void *opaque,
4025 const char *fmt, ...)
4029 monitor_vprintf(opaque, fmt, ap);
4033 static void monitor_readline_flush(void *opaque)
4035 monitor_flush(opaque);
4038 static void __attribute__((constructor)) monitor_lock_init(void)
4040 qemu_mutex_init(&monitor_lock);
4043 void monitor_init(CharDriverState *chr, int flags)
4045 static int is_first_init = 1;
4048 if (is_first_init) {
4049 monitor_qapi_event_init();
4054 mon = g_malloc(sizeof(*mon));
4055 monitor_data_init(mon);
4059 if (flags & MONITOR_USE_READLINE) {
4060 mon->rs = readline_init(monitor_readline_printf,
4061 monitor_readline_flush,
4063 monitor_find_completion);
4064 monitor_read_command(mon, 0);
4067 if (monitor_is_qmp(mon)) {
4068 qemu_chr_add_handlers(chr, monitor_can_read, monitor_qmp_read,
4069 monitor_qmp_event, mon);
4070 qemu_chr_fe_set_echo(chr, true);
4071 json_message_parser_init(&mon->qmp.parser, handle_qmp_command);
4073 qemu_chr_add_handlers(chr, monitor_can_read, monitor_read,
4074 monitor_event, mon);
4077 qemu_mutex_lock(&monitor_lock);
4078 QLIST_INSERT_HEAD(&mon_list, mon, entry);
4079 qemu_mutex_unlock(&monitor_lock);
4082 static void bdrv_password_cb(void *opaque, const char *password,
4083 void *readline_opaque)
4085 Monitor *mon = opaque;
4086 BlockDriverState *bs = readline_opaque;
4088 Error *local_err = NULL;
4090 bdrv_add_key(bs, password, &local_err);
4092 monitor_printf(mon, "%s\n", error_get_pretty(local_err));
4093 error_free(local_err);
4096 if (mon->password_completion_cb)
4097 mon->password_completion_cb(mon->password_opaque, ret);
4099 monitor_read_command(mon, 1);
4102 int monitor_read_bdrv_key_start(Monitor *mon, BlockDriverState *bs,
4103 BlockCompletionFunc *completion_cb,
4108 monitor_printf(mon, "%s (%s) is encrypted.\n", bdrv_get_device_name(bs),
4109 bdrv_get_encrypted_filename(bs));
4111 mon->password_completion_cb = completion_cb;
4112 mon->password_opaque = opaque;
4114 err = monitor_read_password(mon, bdrv_password_cb, bs);
4116 if (err && completion_cb)
4117 completion_cb(opaque, err);
4122 int monitor_read_block_device_key(Monitor *mon, const char *device,
4123 BlockCompletionFunc *completion_cb,
4129 blk = blk_by_name(device);
4131 monitor_printf(mon, "Device not found %s\n", device);
4135 bdrv_add_key(blk_bs(blk), NULL, &err);
4138 return monitor_read_bdrv_key_start(mon, blk_bs(blk), completion_cb, opaque);
4141 if (completion_cb) {
4142 completion_cb(opaque, 0);
4147 QemuOptsList qemu_mon_opts = {
4149 .implied_opt_name = "chardev",
4150 .head = QTAILQ_HEAD_INITIALIZER(qemu_mon_opts.head),
4154 .type = QEMU_OPT_STRING,
4157 .type = QEMU_OPT_STRING,
4160 .type = QEMU_OPT_BOOL,
4163 .type = QEMU_OPT_BOOL,
4165 { /* end of list */ }
4170 void qmp_rtc_reset_reinjection(Error **errp)
4172 error_setg(errp, QERR_FEATURE_DISABLED, "rtc-reset-reinjection");
4176 #ifndef TARGET_S390X
4177 void qmp_dump_skeys(const char *filename, Error **errp)
4179 error_setg(errp, QERR_FEATURE_DISABLED, "dump-skeys");