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
25 #include "qemu/osdep.h"
27 #include "qemu-common.h"
30 #include "monitor/qdev.h"
32 #include "hw/pci/pci.h"
33 #include "sysemu/watchdog.h"
34 #include "hw/loader.h"
35 #include "exec/gdbstub.h"
37 #include "net/slirp.h"
38 #include "chardev/char-fe.h"
39 #include "ui/qemu-spice.h"
40 #include "sysemu/numa.h"
41 #include "monitor/monitor.h"
42 #include "qemu/config-file.h"
43 #include "qemu/readline.h"
44 #include "ui/console.h"
46 #include "sysemu/blockdev.h"
47 #include "sysemu/block-backend.h"
48 #include "audio/audio.h"
49 #include "disas/disas.h"
50 #include "sysemu/balloon.h"
51 #include "qemu/timer.h"
52 #include "sysemu/hw_accel.h"
54 #include "sysemu/tpm.h"
55 #include "qapi/qmp/qdict.h"
56 #include "qapi/qmp/qerror.h"
57 #include "qapi/qmp/qnum.h"
58 #include "qapi/qmp/qstring.h"
59 #include "qapi/qmp/qjson.h"
60 #include "qapi/qmp/json-streamer.h"
61 #include "qapi/qmp/json-parser.h"
62 #include "qom/object_interfaces.h"
63 #include "trace-root.h"
64 #include "trace/control.h"
65 #include "monitor/hmp-target.h"
66 #ifdef CONFIG_TRACE_SIMPLE
67 #include "trace/simple.h"
69 #include "exec/memory.h"
70 #include "exec/exec-all.h"
72 #include "qmp-commands.h"
74 #include "qemu/thread.h"
75 #include "block/qapi.h"
76 #include "qapi/error.h"
77 #include "qapi/qmp-event.h"
78 #include "qapi-event.h"
79 #include "qmp-introspect.h"
80 #include "sysemu/qtest.h"
81 #include "sysemu/cpus.h"
82 #include "qemu/cutils.h"
83 #include "qapi/qmp/dispatch.h"
85 #if defined(TARGET_S390X)
86 #include "hw/s390x/storage-keys.h"
87 #include "hw/s390x/storage-attributes.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;
129 void (*cmd)(Monitor *mon, const QDict *qdict);
130 /* @sub_table is a list of 2nd level of commands. If it does not exist,
131 * cmd should be used. If it exists, sub_table[?].cmd should be
132 * used, and cmd of 1st level plays the role of help function.
134 struct mon_cmd_t *sub_table;
135 void (*command_completion)(ReadLineState *rs, int nb_args, const char *str);
138 /* file descriptors passed via SCM_RIGHTS */
139 typedef struct mon_fd_t mon_fd_t;
143 QLIST_ENTRY(mon_fd_t) next;
146 /* file descriptor associated with a file descriptor set */
147 typedef struct MonFdsetFd MonFdsetFd;
152 QLIST_ENTRY(MonFdsetFd) next;
155 /* file descriptor set containing fds passed via SCM_RIGHTS */
156 typedef struct MonFdset MonFdset;
159 QLIST_HEAD(, MonFdsetFd) fds;
160 QLIST_HEAD(, MonFdsetFd) dup_fds;
161 QLIST_ENTRY(MonFdset) next;
165 JSONMessageParser parser;
167 * When a client connects, we're in capabilities negotiation mode.
168 * When command qmp_capabilities succeeds, we go into command
171 QmpCommandList *commands;
175 * To prevent flooding clients, events can be throttled. The
176 * throttling is calculated globally, rather than per-Monitor
179 typedef struct MonitorQAPIEventState {
180 QAPIEvent event; /* Throttling state for this event type and... */
181 QDict *data; /* ... data, see qapi_event_throttle_equal() */
182 QEMUTimer *timer; /* Timer for handling delayed events */
183 QDict *qdict; /* Delayed event (if any) */
184 } MonitorQAPIEventState;
187 int64_t rate; /* Minimum time (in ns) between two events */
188 } MonitorQAPIEventConf;
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 QmpCommandList qmp_commands, qmp_cap_negotiation_commands;
231 static QEMUClockType event_clock_type = QEMU_CLOCK_REALTIME;
233 static void monitor_command_cb(void *opaque, const char *cmdline,
234 void *readline_opaque);
237 * Is @mon a QMP monitor?
239 static inline bool monitor_is_qmp(const Monitor *mon)
241 return (mon->flags & MONITOR_USE_CONTROL);
245 * Is the current monitor, if any, a QMP monitor?
247 bool monitor_cur_is_qmp(void)
249 return cur_mon && monitor_is_qmp(cur_mon);
252 void monitor_read_command(Monitor *mon, int show_prompt)
257 readline_start(mon->rs, "(qemu) ", 0, monitor_command_cb, NULL);
259 readline_show_prompt(mon->rs);
262 int monitor_read_password(Monitor *mon, ReadLineFunc *readline_func,
266 readline_start(mon->rs, "Password: ", 1, readline_func, opaque);
267 /* prompt is printed on return from the command handler */
270 monitor_printf(mon, "terminal does not support password prompting\n");
275 static void monitor_flush_locked(Monitor *mon);
277 static gboolean monitor_unblocked(GIOChannel *chan, GIOCondition cond,
280 Monitor *mon = opaque;
282 qemu_mutex_lock(&mon->out_lock);
284 monitor_flush_locked(mon);
285 qemu_mutex_unlock(&mon->out_lock);
289 /* Called with mon->out_lock held. */
290 static void monitor_flush_locked(Monitor *mon)
296 if (mon->skip_flush) {
300 buf = qstring_get_str(mon->outbuf);
301 len = qstring_get_length(mon->outbuf);
303 if (len && !mon->mux_out) {
304 rc = qemu_chr_fe_write(&mon->chr, (const uint8_t *) buf, len);
305 if ((rc < 0 && errno != EAGAIN) || (rc == len)) {
306 /* all flushed or error */
307 QDECREF(mon->outbuf);
308 mon->outbuf = qstring_new();
313 QString *tmp = qstring_from_str(buf + rc);
314 QDECREF(mon->outbuf);
317 if (mon->out_watch == 0) {
319 qemu_chr_fe_add_watch(&mon->chr, G_IO_OUT | G_IO_HUP,
320 monitor_unblocked, mon);
325 void monitor_flush(Monitor *mon)
327 qemu_mutex_lock(&mon->out_lock);
328 monitor_flush_locked(mon);
329 qemu_mutex_unlock(&mon->out_lock);
332 /* flush at every end of line */
333 static void monitor_puts(Monitor *mon, const char *str)
337 qemu_mutex_lock(&mon->out_lock);
343 qstring_append_chr(mon->outbuf, '\r');
345 qstring_append_chr(mon->outbuf, c);
347 monitor_flush_locked(mon);
350 qemu_mutex_unlock(&mon->out_lock);
353 void monitor_vprintf(Monitor *mon, const char *fmt, va_list ap)
360 if (monitor_is_qmp(mon)) {
364 buf = g_strdup_vprintf(fmt, ap);
365 monitor_puts(mon, buf);
369 void monitor_printf(Monitor *mon, const char *fmt, ...)
373 monitor_vprintf(mon, fmt, ap);
377 int monitor_fprintf(FILE *stream, const char *fmt, ...)
381 monitor_vprintf((Monitor *)stream, fmt, ap);
386 static void monitor_json_emitter(Monitor *mon, const QObject *data)
390 json = mon->flags & MONITOR_USE_PRETTY ? qobject_to_json_pretty(data) :
391 qobject_to_json(data);
392 assert(json != NULL);
394 qstring_append_chr(json, '\n');
395 monitor_puts(mon, qstring_get_str(json));
400 static MonitorQAPIEventConf monitor_qapi_event_conf[QAPI_EVENT__MAX] = {
401 /* Limit guest-triggerable events to 1 per second */
402 [QAPI_EVENT_RTC_CHANGE] = { 1000 * SCALE_MS },
403 [QAPI_EVENT_WATCHDOG] = { 1000 * SCALE_MS },
404 [QAPI_EVENT_BALLOON_CHANGE] = { 1000 * SCALE_MS },
405 [QAPI_EVENT_QUORUM_REPORT_BAD] = { 1000 * SCALE_MS },
406 [QAPI_EVENT_QUORUM_FAILURE] = { 1000 * SCALE_MS },
407 [QAPI_EVENT_VSERPORT_CHANGE] = { 1000 * SCALE_MS },
410 GHashTable *monitor_qapi_event_state;
413 * Emits the event to every monitor instance, @event is only used for trace
414 * Called with monitor_lock held.
416 static void monitor_qapi_event_emit(QAPIEvent event, QDict *qdict)
420 trace_monitor_protocol_event_emit(event, qdict);
421 QLIST_FOREACH(mon, &mon_list, entry) {
422 if (monitor_is_qmp(mon)
423 && mon->qmp.commands != &qmp_cap_negotiation_commands) {
424 monitor_json_emitter(mon, QOBJECT(qdict));
429 static void monitor_qapi_event_handler(void *opaque);
432 * Queue a new event for emission to Monitor instances,
433 * applying any rate limiting if required.
436 monitor_qapi_event_queue(QAPIEvent event, QDict *qdict, Error **errp)
438 MonitorQAPIEventConf *evconf;
439 MonitorQAPIEventState *evstate;
441 assert(event < QAPI_EVENT__MAX);
442 evconf = &monitor_qapi_event_conf[event];
443 trace_monitor_protocol_event_queue(event, qdict, evconf->rate);
445 qemu_mutex_lock(&monitor_lock);
448 /* Unthrottled event */
449 monitor_qapi_event_emit(event, qdict);
451 QDict *data = qobject_to_qdict(qdict_get(qdict, "data"));
452 MonitorQAPIEventState key = { .event = event, .data = data };
454 evstate = g_hash_table_lookup(monitor_qapi_event_state, &key);
455 assert(!evstate || timer_pending(evstate->timer));
459 * Timer is pending for (at least) evconf->rate ns after
460 * last send. Store event for sending when timer fires,
461 * replacing a prior stored event if any.
463 QDECREF(evstate->qdict);
464 evstate->qdict = qdict;
465 QINCREF(evstate->qdict);
468 * Last send was (at least) evconf->rate ns ago.
469 * Send immediately, and arm the timer to call
470 * monitor_qapi_event_handler() in evconf->rate ns. Any
471 * events arriving before then will be delayed until then.
473 int64_t now = qemu_clock_get_ns(event_clock_type);
475 monitor_qapi_event_emit(event, qdict);
477 evstate = g_new(MonitorQAPIEventState, 1);
478 evstate->event = event;
479 evstate->data = data;
480 QINCREF(evstate->data);
481 evstate->qdict = NULL;
482 evstate->timer = timer_new_ns(event_clock_type,
483 monitor_qapi_event_handler,
485 g_hash_table_add(monitor_qapi_event_state, evstate);
486 timer_mod_ns(evstate->timer, now + evconf->rate);
490 qemu_mutex_unlock(&monitor_lock);
494 * This function runs evconf->rate ns after sending a throttled
496 * If another event has since been stored, send it.
498 static void monitor_qapi_event_handler(void *opaque)
500 MonitorQAPIEventState *evstate = opaque;
501 MonitorQAPIEventConf *evconf = &monitor_qapi_event_conf[evstate->event];
503 trace_monitor_protocol_event_handler(evstate->event, evstate->qdict);
504 qemu_mutex_lock(&monitor_lock);
506 if (evstate->qdict) {
507 int64_t now = qemu_clock_get_ns(event_clock_type);
509 monitor_qapi_event_emit(evstate->event, evstate->qdict);
510 QDECREF(evstate->qdict);
511 evstate->qdict = NULL;
512 timer_mod_ns(evstate->timer, now + evconf->rate);
514 g_hash_table_remove(monitor_qapi_event_state, evstate);
515 QDECREF(evstate->data);
516 timer_free(evstate->timer);
520 qemu_mutex_unlock(&monitor_lock);
523 static unsigned int qapi_event_throttle_hash(const void *key)
525 const MonitorQAPIEventState *evstate = key;
526 unsigned int hash = evstate->event * 255;
528 if (evstate->event == QAPI_EVENT_VSERPORT_CHANGE) {
529 hash += g_str_hash(qdict_get_str(evstate->data, "id"));
532 if (evstate->event == QAPI_EVENT_QUORUM_REPORT_BAD) {
533 hash += g_str_hash(qdict_get_str(evstate->data, "node-name"));
539 static gboolean qapi_event_throttle_equal(const void *a, const void *b)
541 const MonitorQAPIEventState *eva = a;
542 const MonitorQAPIEventState *evb = b;
544 if (eva->event != evb->event) {
548 if (eva->event == QAPI_EVENT_VSERPORT_CHANGE) {
549 return !strcmp(qdict_get_str(eva->data, "id"),
550 qdict_get_str(evb->data, "id"));
553 if (eva->event == QAPI_EVENT_QUORUM_REPORT_BAD) {
554 return !strcmp(qdict_get_str(eva->data, "node-name"),
555 qdict_get_str(evb->data, "node-name"));
561 static void monitor_qapi_event_init(void)
563 if (qtest_enabled()) {
564 event_clock_type = QEMU_CLOCK_VIRTUAL;
567 monitor_qapi_event_state = g_hash_table_new(qapi_event_throttle_hash,
568 qapi_event_throttle_equal);
569 qmp_event_set_func_emit(monitor_qapi_event_queue);
572 static void handle_hmp_command(Monitor *mon, const char *cmdline);
574 static void monitor_data_init(Monitor *mon)
576 memset(mon, 0, sizeof(Monitor));
577 qemu_mutex_init(&mon->out_lock);
578 mon->outbuf = qstring_new();
579 /* Use *mon_cmds by default. */
580 mon->cmd_table = mon_cmds;
583 static void monitor_data_destroy(Monitor *mon)
585 g_free(mon->mon_cpu_path);
586 qemu_chr_fe_deinit(&mon->chr, false);
587 if (monitor_is_qmp(mon)) {
588 json_message_parser_destroy(&mon->qmp.parser);
590 readline_free(mon->rs);
591 QDECREF(mon->outbuf);
592 qemu_mutex_destroy(&mon->out_lock);
595 char *qmp_human_monitor_command(const char *command_line, bool has_cpu_index,
596 int64_t cpu_index, Error **errp)
599 Monitor *old_mon, hmp;
601 monitor_data_init(&hmp);
602 hmp.skip_flush = true;
608 int ret = monitor_set_cpu(cpu_index);
611 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cpu-index",
617 handle_hmp_command(&hmp, command_line);
620 qemu_mutex_lock(&hmp.out_lock);
621 if (qstring_get_length(hmp.outbuf) > 0) {
622 output = g_strdup(qstring_get_str(hmp.outbuf));
624 output = g_strdup("");
626 qemu_mutex_unlock(&hmp.out_lock);
629 monitor_data_destroy(&hmp);
633 static int compare_cmd(const char *name, const char *list)
635 const char *p, *pstart;
643 p = pstart + strlen(pstart);
644 if ((p - pstart) == len && !memcmp(pstart, name, len))
653 static int get_str(char *buf, int buf_size, const char **pp)
661 while (qemu_isspace(*p)) {
672 while (*p != '\0' && *p != '\"') {
688 printf("unsupported escape code: '\\%c'\n", c);
691 if ((q - buf) < buf_size - 1) {
695 if ((q - buf) < buf_size - 1) {
702 printf("unterminated string\n");
707 while (*p != '\0' && !qemu_isspace(*p)) {
708 if ((q - buf) < buf_size - 1) {
721 static void free_cmdline_args(char **args, int nb_args)
725 assert(nb_args <= MAX_ARGS);
727 for (i = 0; i < nb_args; i++) {
734 * Parse the command line to get valid args.
735 * @cmdline: command line to be parsed.
736 * @pnb_args: location to store the number of args, must NOT be NULL.
737 * @args: location to store the args, which should be freed by caller, must
740 * Returns 0 on success, negative on failure.
742 * NOTE: this parser is an approximate form of the real command parser. Number
743 * of args have a limit of MAX_ARGS. If cmdline contains more, it will
744 * return with failure.
746 static int parse_cmdline(const char *cmdline,
747 int *pnb_args, char **args)
756 while (qemu_isspace(*p)) {
762 if (nb_args >= MAX_ARGS) {
765 ret = get_str(buf, sizeof(buf), &p);
769 args[nb_args] = g_strdup(buf);
776 free_cmdline_args(args, nb_args);
780 static void help_cmd_dump_one(Monitor *mon,
781 const mon_cmd_t *cmd,
787 for (i = 0; i < prefix_args_nb; i++) {
788 monitor_printf(mon, "%s ", prefix_args[i]);
790 monitor_printf(mon, "%s %s -- %s\n", cmd->name, cmd->params, cmd->help);
793 /* @args[@arg_index] is the valid command need to find in @cmds */
794 static void help_cmd_dump(Monitor *mon, const mon_cmd_t *cmds,
795 char **args, int nb_args, int arg_index)
797 const mon_cmd_t *cmd;
799 /* No valid arg need to compare with, dump all in *cmds */
800 if (arg_index >= nb_args) {
801 for (cmd = cmds; cmd->name != NULL; cmd++) {
802 help_cmd_dump_one(mon, cmd, args, arg_index);
807 /* Find one entry to dump */
808 for (cmd = cmds; cmd->name != NULL; cmd++) {
809 if (compare_cmd(args[arg_index], cmd->name)) {
810 if (cmd->sub_table) {
811 /* continue with next arg */
812 help_cmd_dump(mon, cmd->sub_table,
813 args, nb_args, arg_index + 1);
815 help_cmd_dump_one(mon, cmd, args, arg_index);
822 static void help_cmd(Monitor *mon, const char *name)
824 char *args[MAX_ARGS];
827 /* 1. parse user input */
829 /* special case for log, directly dump and return */
830 if (!strcmp(name, "log")) {
831 const QEMULogItem *item;
832 monitor_printf(mon, "Log items (comma separated):\n");
833 monitor_printf(mon, "%-10s %s\n", "none", "remove all logs");
834 for (item = qemu_log_items; item->mask != 0; item++) {
835 monitor_printf(mon, "%-10s %s\n", item->name, item->help);
840 if (parse_cmdline(name, &nb_args, args) < 0) {
845 /* 2. dump the contents according to parsed args */
846 help_cmd_dump(mon, mon->cmd_table, args, nb_args, 0);
848 free_cmdline_args(args, nb_args);
851 static void do_help_cmd(Monitor *mon, const QDict *qdict)
853 help_cmd(mon, qdict_get_try_str(qdict, "name"));
856 static void hmp_trace_event(Monitor *mon, const QDict *qdict)
858 const char *tp_name = qdict_get_str(qdict, "name");
859 bool new_state = qdict_get_bool(qdict, "option");
860 bool has_vcpu = qdict_haskey(qdict, "vcpu");
861 int vcpu = qdict_get_try_int(qdict, "vcpu", 0);
862 Error *local_err = NULL;
865 monitor_printf(mon, "argument vcpu must be positive");
869 qmp_trace_event_set_state(tp_name, new_state, true, true, has_vcpu, vcpu, &local_err);
871 error_report_err(local_err);
875 #ifdef CONFIG_TRACE_SIMPLE
876 static void hmp_trace_file(Monitor *mon, const QDict *qdict)
878 const char *op = qdict_get_try_str(qdict, "op");
879 const char *arg = qdict_get_try_str(qdict, "arg");
882 st_print_trace_file_status((FILE *)mon, &monitor_fprintf);
883 } else if (!strcmp(op, "on")) {
884 st_set_trace_file_enabled(true);
885 } else if (!strcmp(op, "off")) {
886 st_set_trace_file_enabled(false);
887 } else if (!strcmp(op, "flush")) {
888 st_flush_trace_buffer();
889 } else if (!strcmp(op, "set")) {
891 st_set_trace_file(arg);
894 monitor_printf(mon, "unexpected argument \"%s\"\n", op);
895 help_cmd(mon, "trace-file");
900 static void hmp_info_help(Monitor *mon, const QDict *qdict)
902 help_cmd(mon, "info");
905 static void query_commands_cb(QmpCommand *cmd, void *opaque)
907 CommandInfoList *info, **list = opaque;
913 info = g_malloc0(sizeof(*info));
914 info->value = g_malloc0(sizeof(*info->value));
915 info->value->name = g_strdup(cmd->name);
920 CommandInfoList *qmp_query_commands(Error **errp)
922 CommandInfoList *list = NULL;
924 qmp_for_each_command(cur_mon->qmp.commands, query_commands_cb, &list);
929 EventInfoList *qmp_query_events(Error **errp)
931 EventInfoList *info, *ev_list = NULL;
934 for (e = 0 ; e < QAPI_EVENT__MAX ; e++) {
935 const char *event_name = QAPIEvent_str(e);
936 assert(event_name != NULL);
937 info = g_malloc0(sizeof(*info));
938 info->value = g_malloc0(sizeof(*info->value));
939 info->value->name = g_strdup(event_name);
941 info->next = ev_list;
949 * Minor hack: generated marshalling suppressed for this command
950 * ('gen': false in the schema) so we can parse the JSON string
951 * directly into QObject instead of first parsing it with
952 * visit_type_SchemaInfoList() into a SchemaInfoList, then marshal it
953 * to QObject with generated output marshallers, every time. Instead,
954 * we do it in test-qobject-input-visitor.c, just to make sure
955 * qapi-introspect.py's output actually conforms to the schema.
957 static void qmp_query_qmp_schema(QDict *qdict, QObject **ret_data,
960 *ret_data = qobject_from_json(qmp_schema_json, &error_abort);
964 * We used to define commands in qmp-commands.hx in addition to the
965 * QAPI schema. This permitted defining some of them only in certain
966 * configurations. query-commands has always reflected that (good,
967 * because it lets QMP clients figure out what's actually available),
968 * while query-qmp-schema never did (not so good). This function is a
969 * hack to keep the configuration-specific commands defined exactly as
970 * before, even though qmp-commands.hx is gone.
972 * FIXME Educate the QAPI schema on configuration-specific commands,
973 * and drop this hack.
975 static void qmp_unregister_commands_hack(void)
978 qmp_unregister_command(&qmp_commands, "query-spice");
980 #ifndef CONFIG_REPLICATION
981 qmp_unregister_command(&qmp_commands, "xen-set-replication");
982 qmp_unregister_command(&qmp_commands, "query-xen-replication-status");
983 qmp_unregister_command(&qmp_commands, "xen-colo-do-checkpoint");
986 qmp_unregister_command(&qmp_commands, "rtc-reset-reinjection");
989 qmp_unregister_command(&qmp_commands, "dump-skeys");
992 qmp_unregister_command(&qmp_commands, "query-gic-capabilities");
994 #if !defined(TARGET_S390X) && !defined(TARGET_I386)
995 qmp_unregister_command(&qmp_commands, "query-cpu-model-expansion");
997 #if !defined(TARGET_S390X)
998 qmp_unregister_command(&qmp_commands, "query-cpu-model-baseline");
999 qmp_unregister_command(&qmp_commands, "query-cpu-model-comparison");
1001 #if !defined(TARGET_PPC) && !defined(TARGET_ARM) && !defined(TARGET_I386) \
1002 && !defined(TARGET_S390X)
1003 qmp_unregister_command(&qmp_commands, "query-cpu-definitions");
1007 void monitor_init_qmp_commands(void)
1010 * Two command lists:
1011 * - qmp_commands contains all QMP commands
1012 * - qmp_cap_negotiation_commands contains just
1013 * "qmp_capabilities", to enforce capability negotiation
1016 qmp_init_marshal(&qmp_commands);
1018 qmp_register_command(&qmp_commands, "query-qmp-schema",
1019 qmp_query_qmp_schema,
1021 qmp_register_command(&qmp_commands, "device_add", qmp_device_add,
1023 qmp_register_command(&qmp_commands, "netdev_add", qmp_netdev_add,
1026 qmp_unregister_commands_hack();
1028 QTAILQ_INIT(&qmp_cap_negotiation_commands);
1029 qmp_register_command(&qmp_cap_negotiation_commands, "qmp_capabilities",
1030 qmp_marshal_qmp_capabilities, QCO_NO_OPTIONS);
1033 void qmp_qmp_capabilities(Error **errp)
1035 if (cur_mon->qmp.commands == &qmp_commands) {
1036 error_set(errp, ERROR_CLASS_COMMAND_NOT_FOUND,
1037 "Capabilities negotiation is already complete, command "
1042 cur_mon->qmp.commands = &qmp_commands;
1045 /* set the current CPU defined by the user */
1046 int monitor_set_cpu(int cpu_index)
1050 cpu = qemu_get_cpu(cpu_index);
1054 g_free(cur_mon->mon_cpu_path);
1055 cur_mon->mon_cpu_path = object_get_canonical_path(OBJECT(cpu));
1059 CPUState *mon_get_cpu(void)
1063 if (cur_mon->mon_cpu_path) {
1064 cpu = (CPUState *) object_resolve_path_type(cur_mon->mon_cpu_path,
1067 g_free(cur_mon->mon_cpu_path);
1068 cur_mon->mon_cpu_path = NULL;
1071 if (!cur_mon->mon_cpu_path) {
1075 monitor_set_cpu(first_cpu->cpu_index);
1078 cpu_synchronize_state(cpu);
1082 CPUArchState *mon_get_cpu_env(void)
1084 CPUState *cs = mon_get_cpu();
1086 return cs ? cs->env_ptr : NULL;
1089 int monitor_get_cpu_index(void)
1091 CPUState *cs = mon_get_cpu();
1093 return cs ? cs->cpu_index : UNASSIGNED_CPU_INDEX;
1096 static void hmp_info_registers(Monitor *mon, const QDict *qdict)
1098 bool all_cpus = qdict_get_try_bool(qdict, "cpustate_all", false);
1103 monitor_printf(mon, "\nCPU#%d\n", cs->cpu_index);
1104 cpu_dump_state(cs, (FILE *)mon, monitor_fprintf, CPU_DUMP_FPU);
1110 monitor_printf(mon, "No CPU available\n");
1114 cpu_dump_state(cs, (FILE *)mon, monitor_fprintf, CPU_DUMP_FPU);
1119 static void hmp_info_jit(Monitor *mon, const QDict *qdict)
1121 if (!tcg_enabled()) {
1122 error_report("JIT information is only available with accel=tcg");
1126 dump_exec_info((FILE *)mon, monitor_fprintf);
1127 dump_drift_info((FILE *)mon, monitor_fprintf);
1130 static void hmp_info_opcount(Monitor *mon, const QDict *qdict)
1132 dump_opcount_info((FILE *)mon, monitor_fprintf);
1136 static void hmp_info_history(Monitor *mon, const QDict *qdict)
1145 str = readline_get_history(mon->rs, i);
1148 monitor_printf(mon, "%d: '%s'\n", i, str);
1153 static void hmp_info_cpustats(Monitor *mon, const QDict *qdict)
1155 CPUState *cs = mon_get_cpu();
1158 monitor_printf(mon, "No CPU available\n");
1161 cpu_dump_statistics(cs, (FILE *)mon, &monitor_fprintf, 0);
1164 static void hmp_info_trace_events(Monitor *mon, const QDict *qdict)
1166 const char *name = qdict_get_try_str(qdict, "name");
1167 bool has_vcpu = qdict_haskey(qdict, "vcpu");
1168 int vcpu = qdict_get_try_int(qdict, "vcpu", 0);
1169 TraceEventInfoList *events;
1170 TraceEventInfoList *elem;
1171 Error *local_err = NULL;
1177 monitor_printf(mon, "argument vcpu must be positive");
1181 events = qmp_trace_event_get_state(name, has_vcpu, vcpu, &local_err);
1183 error_report_err(local_err);
1187 for (elem = events; elem != NULL; elem = elem->next) {
1188 monitor_printf(mon, "%s : state %u\n",
1190 elem->value->state == TRACE_EVENT_STATE_ENABLED ? 1 : 0);
1192 qapi_free_TraceEventInfoList(events);
1195 void qmp_client_migrate_info(const char *protocol, const char *hostname,
1196 bool has_port, int64_t port,
1197 bool has_tls_port, int64_t tls_port,
1198 bool has_cert_subject, const char *cert_subject,
1201 if (strcmp(protocol, "spice") == 0) {
1202 if (!qemu_using_spice(errp)) {
1206 if (!has_port && !has_tls_port) {
1207 error_setg(errp, QERR_MISSING_PARAMETER, "port/tls-port");
1211 if (qemu_spice_migrate_info(hostname,
1212 has_port ? port : -1,
1213 has_tls_port ? tls_port : -1,
1215 error_setg(errp, QERR_UNDEFINED_ERROR);
1221 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "protocol", "spice");
1224 static void hmp_logfile(Monitor *mon, const QDict *qdict)
1228 qemu_set_log_filename(qdict_get_str(qdict, "filename"), &err);
1230 error_report_err(err);
1234 static void hmp_log(Monitor *mon, const QDict *qdict)
1237 const char *items = qdict_get_str(qdict, "items");
1239 if (!strcmp(items, "none")) {
1242 mask = qemu_str_to_log_mask(items);
1244 help_cmd(mon, "log");
1251 static void hmp_singlestep(Monitor *mon, const QDict *qdict)
1253 const char *option = qdict_get_try_str(qdict, "option");
1254 if (!option || !strcmp(option, "on")) {
1256 } else if (!strcmp(option, "off")) {
1259 monitor_printf(mon, "unexpected option %s\n", option);
1263 static void hmp_gdbserver(Monitor *mon, const QDict *qdict)
1265 const char *device = qdict_get_try_str(qdict, "device");
1267 device = "tcp::" DEFAULT_GDBSTUB_PORT;
1268 if (gdbserver_start(device) < 0) {
1269 monitor_printf(mon, "Could not open gdbserver on device '%s'\n",
1271 } else if (strcmp(device, "none") == 0) {
1272 monitor_printf(mon, "Disabled gdbserver\n");
1274 monitor_printf(mon, "Waiting for gdb connection on device '%s'\n",
1279 static void hmp_watchdog_action(Monitor *mon, const QDict *qdict)
1281 const char *action = qdict_get_str(qdict, "action");
1282 if (select_watchdog_action(action) == -1) {
1283 monitor_printf(mon, "Unknown watchdog action '%s'\n", action);
1287 static void monitor_printc(Monitor *mon, int c)
1289 monitor_printf(mon, "'");
1292 monitor_printf(mon, "\\'");
1295 monitor_printf(mon, "\\\\");
1298 monitor_printf(mon, "\\n");
1301 monitor_printf(mon, "\\r");
1304 if (c >= 32 && c <= 126) {
1305 monitor_printf(mon, "%c", c);
1307 monitor_printf(mon, "\\x%02x", c);
1311 monitor_printf(mon, "'");
1314 static void memory_dump(Monitor *mon, int count, int format, int wsize,
1315 hwaddr addr, int is_physical)
1317 int l, line_size, i, max_digits, len;
1320 CPUState *cs = mon_get_cpu();
1322 if (!cs && (format == 'i' || !is_physical)) {
1323 monitor_printf(mon, "Can not dump without CPU\n");
1327 if (format == 'i') {
1328 monitor_disas(mon, cs, addr, count, is_physical);
1332 len = wsize * count;
1341 max_digits = DIV_ROUND_UP(wsize * 8, 3);
1345 max_digits = (wsize * 8) / 4;
1349 max_digits = DIV_ROUND_UP(wsize * 8 * 10, 33);
1358 monitor_printf(mon, TARGET_FMT_plx ":", addr);
1360 monitor_printf(mon, TARGET_FMT_lx ":", (target_ulong)addr);
1365 cpu_physical_memory_read(addr, buf, l);
1367 if (cpu_memory_rw_debug(cs, addr, buf, l, 0) < 0) {
1368 monitor_printf(mon, " Cannot access memory\n");
1377 v = ldub_p(buf + i);
1380 v = lduw_p(buf + i);
1383 v = (uint32_t)ldl_p(buf + i);
1389 monitor_printf(mon, " ");
1392 monitor_printf(mon, "%#*" PRIo64, max_digits, v);
1395 monitor_printf(mon, "0x%0*" PRIx64, max_digits, v);
1398 monitor_printf(mon, "%*" PRIu64, max_digits, v);
1401 monitor_printf(mon, "%*" PRId64, max_digits, v);
1404 monitor_printc(mon, v);
1409 monitor_printf(mon, "\n");
1415 static void hmp_memory_dump(Monitor *mon, const QDict *qdict)
1417 int count = qdict_get_int(qdict, "count");
1418 int format = qdict_get_int(qdict, "format");
1419 int size = qdict_get_int(qdict, "size");
1420 target_long addr = qdict_get_int(qdict, "addr");
1422 memory_dump(mon, count, format, size, addr, 0);
1425 static void hmp_physical_memory_dump(Monitor *mon, const QDict *qdict)
1427 int count = qdict_get_int(qdict, "count");
1428 int format = qdict_get_int(qdict, "format");
1429 int size = qdict_get_int(qdict, "size");
1430 hwaddr addr = qdict_get_int(qdict, "addr");
1432 memory_dump(mon, count, format, size, addr, 1);
1435 static void *gpa2hva(MemoryRegion **p_mr, hwaddr addr, Error **errp)
1437 MemoryRegionSection mrs = memory_region_find(get_system_memory(),
1441 error_setg(errp, "No memory is mapped at address 0x%" HWADDR_PRIx, addr);
1445 if (!memory_region_is_ram(mrs.mr) && !memory_region_is_romd(mrs.mr)) {
1446 error_setg(errp, "Memory at address 0x%" HWADDR_PRIx "is not RAM", addr);
1447 memory_region_unref(mrs.mr);
1452 return qemu_map_ram_ptr(mrs.mr->ram_block, mrs.offset_within_region);
1455 static void hmp_gpa2hva(Monitor *mon, const QDict *qdict)
1457 hwaddr addr = qdict_get_int(qdict, "addr");
1458 Error *local_err = NULL;
1459 MemoryRegion *mr = NULL;
1462 ptr = gpa2hva(&mr, addr, &local_err);
1464 error_report_err(local_err);
1468 monitor_printf(mon, "Host virtual address for 0x%" HWADDR_PRIx
1470 addr, mr->name, ptr);
1472 memory_region_unref(mr);
1476 static uint64_t vtop(void *ptr, Error **errp)
1480 uintptr_t addr = (uintptr_t) ptr;
1481 uintptr_t pagesize = getpagesize();
1482 off_t offset = addr / pagesize * sizeof(pinfo);
1485 fd = open("/proc/self/pagemap", O_RDONLY);
1487 error_setg_errno(errp, errno, "Cannot open /proc/self/pagemap");
1491 /* Force copy-on-write if necessary. */
1492 atomic_add((uint8_t *)ptr, 0);
1494 if (pread(fd, &pinfo, sizeof(pinfo), offset) != sizeof(pinfo)) {
1495 error_setg_errno(errp, errno, "Cannot read pagemap");
1498 if ((pinfo & (1ull << 63)) == 0) {
1499 error_setg(errp, "Page not present");
1502 ret = ((pinfo & 0x007fffffffffffffull) * pagesize) | (addr & (pagesize - 1));
1509 static void hmp_gpa2hpa(Monitor *mon, const QDict *qdict)
1511 hwaddr addr = qdict_get_int(qdict, "addr");
1512 Error *local_err = NULL;
1513 MemoryRegion *mr = NULL;
1517 ptr = gpa2hva(&mr, addr, &local_err);
1519 error_report_err(local_err);
1523 physaddr = vtop(ptr, &local_err);
1525 error_report_err(local_err);
1527 monitor_printf(mon, "Host physical address for 0x%" HWADDR_PRIx
1528 " (%s) is 0x%" PRIx64 "\n",
1529 addr, mr->name, (uint64_t) physaddr);
1532 memory_region_unref(mr);
1536 static void do_print(Monitor *mon, const QDict *qdict)
1538 int format = qdict_get_int(qdict, "format");
1539 hwaddr val = qdict_get_int(qdict, "val");
1543 monitor_printf(mon, "%#" HWADDR_PRIo, val);
1546 monitor_printf(mon, "%#" HWADDR_PRIx, val);
1549 monitor_printf(mon, "%" HWADDR_PRIu, val);
1553 monitor_printf(mon, "%" HWADDR_PRId, val);
1556 monitor_printc(mon, val);
1559 monitor_printf(mon, "\n");
1562 static void hmp_sum(Monitor *mon, const QDict *qdict)
1566 uint32_t start = qdict_get_int(qdict, "start");
1567 uint32_t size = qdict_get_int(qdict, "size");
1570 for(addr = start; addr < (start + size); addr++) {
1571 uint8_t val = address_space_ldub(&address_space_memory, addr,
1572 MEMTXATTRS_UNSPECIFIED, NULL);
1573 /* BSD sum algorithm ('sum' Unix command) */
1574 sum = (sum >> 1) | (sum << 15);
1577 monitor_printf(mon, "%05d\n", sum);
1580 static int mouse_button_state;
1582 static void hmp_mouse_move(Monitor *mon, const QDict *qdict)
1584 int dx, dy, dz, button;
1585 const char *dx_str = qdict_get_str(qdict, "dx_str");
1586 const char *dy_str = qdict_get_str(qdict, "dy_str");
1587 const char *dz_str = qdict_get_try_str(qdict, "dz_str");
1589 dx = strtol(dx_str, NULL, 0);
1590 dy = strtol(dy_str, NULL, 0);
1591 qemu_input_queue_rel(NULL, INPUT_AXIS_X, dx);
1592 qemu_input_queue_rel(NULL, INPUT_AXIS_Y, dy);
1595 dz = strtol(dz_str, NULL, 0);
1597 button = (dz > 0) ? INPUT_BUTTON_WHEEL_UP : INPUT_BUTTON_WHEEL_DOWN;
1598 qemu_input_queue_btn(NULL, button, true);
1599 qemu_input_event_sync();
1600 qemu_input_queue_btn(NULL, button, false);
1603 qemu_input_event_sync();
1606 static void hmp_mouse_button(Monitor *mon, const QDict *qdict)
1608 static uint32_t bmap[INPUT_BUTTON__MAX] = {
1609 [INPUT_BUTTON_LEFT] = MOUSE_EVENT_LBUTTON,
1610 [INPUT_BUTTON_MIDDLE] = MOUSE_EVENT_MBUTTON,
1611 [INPUT_BUTTON_RIGHT] = MOUSE_EVENT_RBUTTON,
1613 int button_state = qdict_get_int(qdict, "button_state");
1615 if (mouse_button_state == button_state) {
1618 qemu_input_update_buttons(NULL, bmap, mouse_button_state, button_state);
1619 qemu_input_event_sync();
1620 mouse_button_state = button_state;
1623 static void hmp_ioport_read(Monitor *mon, const QDict *qdict)
1625 int size = qdict_get_int(qdict, "size");
1626 int addr = qdict_get_int(qdict, "addr");
1627 int has_index = qdict_haskey(qdict, "index");
1632 int index = qdict_get_int(qdict, "index");
1633 cpu_outb(addr & IOPORTS_MASK, index & 0xff);
1641 val = cpu_inb(addr);
1645 val = cpu_inw(addr);
1649 val = cpu_inl(addr);
1653 monitor_printf(mon, "port%c[0x%04x] = %#0*x\n",
1654 suffix, addr, size * 2, val);
1657 static void hmp_ioport_write(Monitor *mon, const QDict *qdict)
1659 int size = qdict_get_int(qdict, "size");
1660 int addr = qdict_get_int(qdict, "addr");
1661 int val = qdict_get_int(qdict, "val");
1663 addr &= IOPORTS_MASK;
1668 cpu_outb(addr, val);
1671 cpu_outw(addr, val);
1674 cpu_outl(addr, val);
1679 static void hmp_boot_set(Monitor *mon, const QDict *qdict)
1681 Error *local_err = NULL;
1682 const char *bootdevice = qdict_get_str(qdict, "bootdevice");
1684 qemu_boot_set(bootdevice, &local_err);
1686 error_report_err(local_err);
1688 monitor_printf(mon, "boot device list now set to %s\n", bootdevice);
1692 static void hmp_info_mtree(Monitor *mon, const QDict *qdict)
1694 bool flatview = qdict_get_try_bool(qdict, "flatview", false);
1695 bool dispatch_tree = qdict_get_try_bool(qdict, "dispatch_tree", false);
1697 mtree_info((fprintf_function)monitor_printf, mon, flatview, dispatch_tree);
1700 static void hmp_info_numa(Monitor *mon, const QDict *qdict)
1703 NumaNodeMem *node_mem;
1704 CpuInfoList *cpu_list, *cpu;
1706 cpu_list = qmp_query_cpus(&error_abort);
1707 node_mem = g_new0(NumaNodeMem, nb_numa_nodes);
1709 query_numa_node_mem(node_mem);
1710 monitor_printf(mon, "%d nodes\n", nb_numa_nodes);
1711 for (i = 0; i < nb_numa_nodes; i++) {
1712 monitor_printf(mon, "node %d cpus:", i);
1713 for (cpu = cpu_list; cpu; cpu = cpu->next) {
1714 if (cpu->value->has_props && cpu->value->props->has_node_id &&
1715 cpu->value->props->node_id == i) {
1716 monitor_printf(mon, " %" PRIi64, cpu->value->CPU);
1719 monitor_printf(mon, "\n");
1720 monitor_printf(mon, "node %d size: %" PRId64 " MB\n", i,
1721 node_mem[i].node_mem >> 20);
1722 monitor_printf(mon, "node %d plugged: %" PRId64 " MB\n", i,
1723 node_mem[i].node_plugged_mem >> 20);
1725 qapi_free_CpuInfoList(cpu_list);
1729 #ifdef CONFIG_PROFILER
1734 static void hmp_info_profile(Monitor *mon, const QDict *qdict)
1736 monitor_printf(mon, "async time %" PRId64 " (%0.3f)\n",
1737 dev_time, dev_time / (double)NANOSECONDS_PER_SECOND);
1738 monitor_printf(mon, "qemu time %" PRId64 " (%0.3f)\n",
1739 tcg_time, tcg_time / (double)NANOSECONDS_PER_SECOND);
1744 static void hmp_info_profile(Monitor *mon, const QDict *qdict)
1746 monitor_printf(mon, "Internal profiler not compiled\n");
1750 /* Capture support */
1751 static QLIST_HEAD (capture_list_head, CaptureState) capture_head;
1753 static void hmp_info_capture(Monitor *mon, const QDict *qdict)
1758 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
1759 monitor_printf(mon, "[%d]: ", i);
1760 s->ops.info (s->opaque);
1764 static void hmp_stopcapture(Monitor *mon, const QDict *qdict)
1767 int n = qdict_get_int(qdict, "n");
1770 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
1772 s->ops.destroy (s->opaque);
1773 QLIST_REMOVE (s, entries);
1780 static void hmp_wavcapture(Monitor *mon, const QDict *qdict)
1782 const char *path = qdict_get_str(qdict, "path");
1783 int has_freq = qdict_haskey(qdict, "freq");
1784 int freq = qdict_get_try_int(qdict, "freq", -1);
1785 int has_bits = qdict_haskey(qdict, "bits");
1786 int bits = qdict_get_try_int(qdict, "bits", -1);
1787 int has_channels = qdict_haskey(qdict, "nchannels");
1788 int nchannels = qdict_get_try_int(qdict, "nchannels", -1);
1791 s = g_malloc0 (sizeof (*s));
1793 freq = has_freq ? freq : 44100;
1794 bits = has_bits ? bits : 16;
1795 nchannels = has_channels ? nchannels : 2;
1797 if (wav_start_capture (s, path, freq, bits, nchannels)) {
1798 monitor_printf(mon, "Failed to add wave capture\n");
1802 QLIST_INSERT_HEAD (&capture_head, s, entries);
1805 static qemu_acl *find_acl(Monitor *mon, const char *name)
1807 qemu_acl *acl = qemu_acl_find(name);
1810 monitor_printf(mon, "acl: unknown list '%s'\n", name);
1815 static void hmp_acl_show(Monitor *mon, const QDict *qdict)
1817 const char *aclname = qdict_get_str(qdict, "aclname");
1818 qemu_acl *acl = find_acl(mon, aclname);
1819 qemu_acl_entry *entry;
1823 monitor_printf(mon, "policy: %s\n",
1824 acl->defaultDeny ? "deny" : "allow");
1825 QTAILQ_FOREACH(entry, &acl->entries, next) {
1827 monitor_printf(mon, "%d: %s %s\n", i,
1828 entry->deny ? "deny" : "allow", entry->match);
1833 static void hmp_acl_reset(Monitor *mon, const QDict *qdict)
1835 const char *aclname = qdict_get_str(qdict, "aclname");
1836 qemu_acl *acl = find_acl(mon, aclname);
1839 qemu_acl_reset(acl);
1840 monitor_printf(mon, "acl: removed all rules\n");
1844 static void hmp_acl_policy(Monitor *mon, const QDict *qdict)
1846 const char *aclname = qdict_get_str(qdict, "aclname");
1847 const char *policy = qdict_get_str(qdict, "policy");
1848 qemu_acl *acl = find_acl(mon, aclname);
1851 if (strcmp(policy, "allow") == 0) {
1852 acl->defaultDeny = 0;
1853 monitor_printf(mon, "acl: policy set to 'allow'\n");
1854 } else if (strcmp(policy, "deny") == 0) {
1855 acl->defaultDeny = 1;
1856 monitor_printf(mon, "acl: policy set to 'deny'\n");
1858 monitor_printf(mon, "acl: unknown policy '%s', "
1859 "expected 'deny' or 'allow'\n", policy);
1864 static void hmp_acl_add(Monitor *mon, const QDict *qdict)
1866 const char *aclname = qdict_get_str(qdict, "aclname");
1867 const char *match = qdict_get_str(qdict, "match");
1868 const char *policy = qdict_get_str(qdict, "policy");
1869 int has_index = qdict_haskey(qdict, "index");
1870 int index = qdict_get_try_int(qdict, "index", -1);
1871 qemu_acl *acl = find_acl(mon, aclname);
1875 if (strcmp(policy, "allow") == 0) {
1877 } else if (strcmp(policy, "deny") == 0) {
1880 monitor_printf(mon, "acl: unknown policy '%s', "
1881 "expected 'deny' or 'allow'\n", policy);
1885 ret = qemu_acl_insert(acl, deny, match, index);
1887 ret = qemu_acl_append(acl, deny, match);
1889 monitor_printf(mon, "acl: unable to add acl entry\n");
1891 monitor_printf(mon, "acl: added rule at position %d\n", ret);
1895 static void hmp_acl_remove(Monitor *mon, const QDict *qdict)
1897 const char *aclname = qdict_get_str(qdict, "aclname");
1898 const char *match = qdict_get_str(qdict, "match");
1899 qemu_acl *acl = find_acl(mon, aclname);
1903 ret = qemu_acl_remove(acl, match);
1905 monitor_printf(mon, "acl: no matching acl entry\n");
1907 monitor_printf(mon, "acl: removed rule at position %d\n", ret);
1911 void qmp_getfd(const char *fdname, Error **errp)
1916 fd = qemu_chr_fe_get_msgfd(&cur_mon->chr);
1918 error_setg(errp, QERR_FD_NOT_SUPPLIED);
1922 if (qemu_isdigit(fdname[0])) {
1924 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "fdname",
1925 "a name not starting with a digit");
1929 QLIST_FOREACH(monfd, &cur_mon->fds, next) {
1930 if (strcmp(monfd->name, fdname) != 0) {
1939 monfd = g_malloc0(sizeof(mon_fd_t));
1940 monfd->name = g_strdup(fdname);
1943 QLIST_INSERT_HEAD(&cur_mon->fds, monfd, next);
1946 void qmp_closefd(const char *fdname, Error **errp)
1950 QLIST_FOREACH(monfd, &cur_mon->fds, next) {
1951 if (strcmp(monfd->name, fdname) != 0) {
1955 QLIST_REMOVE(monfd, next);
1957 g_free(monfd->name);
1962 error_setg(errp, QERR_FD_NOT_FOUND, fdname);
1965 int monitor_get_fd(Monitor *mon, const char *fdname, Error **errp)
1969 QLIST_FOREACH(monfd, &mon->fds, next) {
1972 if (strcmp(monfd->name, fdname) != 0) {
1978 /* caller takes ownership of fd */
1979 QLIST_REMOVE(monfd, next);
1980 g_free(monfd->name);
1986 error_setg(errp, "File descriptor named '%s' has not been found", fdname);
1990 static void monitor_fdset_cleanup(MonFdset *mon_fdset)
1992 MonFdsetFd *mon_fdset_fd;
1993 MonFdsetFd *mon_fdset_fd_next;
1995 QLIST_FOREACH_SAFE(mon_fdset_fd, &mon_fdset->fds, next, mon_fdset_fd_next) {
1996 if ((mon_fdset_fd->removed ||
1997 (QLIST_EMPTY(&mon_fdset->dup_fds) && mon_refcount == 0)) &&
1998 runstate_is_running()) {
1999 close(mon_fdset_fd->fd);
2000 g_free(mon_fdset_fd->opaque);
2001 QLIST_REMOVE(mon_fdset_fd, next);
2002 g_free(mon_fdset_fd);
2006 if (QLIST_EMPTY(&mon_fdset->fds) && QLIST_EMPTY(&mon_fdset->dup_fds)) {
2007 QLIST_REMOVE(mon_fdset, next);
2012 static void monitor_fdsets_cleanup(void)
2014 MonFdset *mon_fdset;
2015 MonFdset *mon_fdset_next;
2017 QLIST_FOREACH_SAFE(mon_fdset, &mon_fdsets, next, mon_fdset_next) {
2018 monitor_fdset_cleanup(mon_fdset);
2022 AddfdInfo *qmp_add_fd(bool has_fdset_id, int64_t fdset_id, bool has_opaque,
2023 const char *opaque, Error **errp)
2026 Monitor *mon = cur_mon;
2029 fd = qemu_chr_fe_get_msgfd(&mon->chr);
2031 error_setg(errp, QERR_FD_NOT_SUPPLIED);
2035 fdinfo = monitor_fdset_add_fd(fd, has_fdset_id, fdset_id,
2036 has_opaque, opaque, errp);
2048 void qmp_remove_fd(int64_t fdset_id, bool has_fd, int64_t fd, Error **errp)
2050 MonFdset *mon_fdset;
2051 MonFdsetFd *mon_fdset_fd;
2054 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2055 if (mon_fdset->id != fdset_id) {
2058 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2060 if (mon_fdset_fd->fd != fd) {
2063 mon_fdset_fd->removed = true;
2066 mon_fdset_fd->removed = true;
2069 if (has_fd && !mon_fdset_fd) {
2072 monitor_fdset_cleanup(mon_fdset);
2078 snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64 ", fd:%" PRId64,
2081 snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64, fdset_id);
2083 error_setg(errp, QERR_FD_NOT_FOUND, fd_str);
2086 FdsetInfoList *qmp_query_fdsets(Error **errp)
2088 MonFdset *mon_fdset;
2089 MonFdsetFd *mon_fdset_fd;
2090 FdsetInfoList *fdset_list = NULL;
2092 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2093 FdsetInfoList *fdset_info = g_malloc0(sizeof(*fdset_info));
2094 FdsetFdInfoList *fdsetfd_list = NULL;
2096 fdset_info->value = g_malloc0(sizeof(*fdset_info->value));
2097 fdset_info->value->fdset_id = mon_fdset->id;
2099 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2100 FdsetFdInfoList *fdsetfd_info;
2102 fdsetfd_info = g_malloc0(sizeof(*fdsetfd_info));
2103 fdsetfd_info->value = g_malloc0(sizeof(*fdsetfd_info->value));
2104 fdsetfd_info->value->fd = mon_fdset_fd->fd;
2105 if (mon_fdset_fd->opaque) {
2106 fdsetfd_info->value->has_opaque = true;
2107 fdsetfd_info->value->opaque = g_strdup(mon_fdset_fd->opaque);
2109 fdsetfd_info->value->has_opaque = false;
2112 fdsetfd_info->next = fdsetfd_list;
2113 fdsetfd_list = fdsetfd_info;
2116 fdset_info->value->fds = fdsetfd_list;
2118 fdset_info->next = fdset_list;
2119 fdset_list = fdset_info;
2125 AddfdInfo *monitor_fdset_add_fd(int fd, bool has_fdset_id, int64_t fdset_id,
2126 bool has_opaque, const char *opaque,
2129 MonFdset *mon_fdset = NULL;
2130 MonFdsetFd *mon_fdset_fd;
2134 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2135 /* Break if match found or match impossible due to ordering by ID */
2136 if (fdset_id <= mon_fdset->id) {
2137 if (fdset_id < mon_fdset->id) {
2145 if (mon_fdset == NULL) {
2146 int64_t fdset_id_prev = -1;
2147 MonFdset *mon_fdset_cur = QLIST_FIRST(&mon_fdsets);
2151 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "fdset-id",
2152 "a non-negative value");
2155 /* Use specified fdset ID */
2156 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2157 mon_fdset_cur = mon_fdset;
2158 if (fdset_id < mon_fdset_cur->id) {
2163 /* Use first available fdset ID */
2164 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2165 mon_fdset_cur = mon_fdset;
2166 if (fdset_id_prev == mon_fdset_cur->id - 1) {
2167 fdset_id_prev = mon_fdset_cur->id;
2174 mon_fdset = g_malloc0(sizeof(*mon_fdset));
2176 mon_fdset->id = fdset_id;
2178 mon_fdset->id = fdset_id_prev + 1;
2181 /* The fdset list is ordered by fdset ID */
2182 if (!mon_fdset_cur) {
2183 QLIST_INSERT_HEAD(&mon_fdsets, mon_fdset, next);
2184 } else if (mon_fdset->id < mon_fdset_cur->id) {
2185 QLIST_INSERT_BEFORE(mon_fdset_cur, mon_fdset, next);
2187 QLIST_INSERT_AFTER(mon_fdset_cur, mon_fdset, next);
2191 mon_fdset_fd = g_malloc0(sizeof(*mon_fdset_fd));
2192 mon_fdset_fd->fd = fd;
2193 mon_fdset_fd->removed = false;
2195 mon_fdset_fd->opaque = g_strdup(opaque);
2197 QLIST_INSERT_HEAD(&mon_fdset->fds, mon_fdset_fd, next);
2199 fdinfo = g_malloc0(sizeof(*fdinfo));
2200 fdinfo->fdset_id = mon_fdset->id;
2201 fdinfo->fd = mon_fdset_fd->fd;
2206 int monitor_fdset_get_fd(int64_t fdset_id, int flags)
2209 MonFdset *mon_fdset;
2210 MonFdsetFd *mon_fdset_fd;
2213 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2214 if (mon_fdset->id != fdset_id) {
2217 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2218 mon_fd_flags = fcntl(mon_fdset_fd->fd, F_GETFL);
2219 if (mon_fd_flags == -1) {
2223 if ((flags & O_ACCMODE) == (mon_fd_flags & O_ACCMODE)) {
2224 return mon_fdset_fd->fd;
2236 int monitor_fdset_dup_fd_add(int64_t fdset_id, int dup_fd)
2238 MonFdset *mon_fdset;
2239 MonFdsetFd *mon_fdset_fd_dup;
2241 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2242 if (mon_fdset->id != fdset_id) {
2245 QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
2246 if (mon_fdset_fd_dup->fd == dup_fd) {
2250 mon_fdset_fd_dup = g_malloc0(sizeof(*mon_fdset_fd_dup));
2251 mon_fdset_fd_dup->fd = dup_fd;
2252 QLIST_INSERT_HEAD(&mon_fdset->dup_fds, mon_fdset_fd_dup, next);
2258 static int monitor_fdset_dup_fd_find_remove(int dup_fd, bool remove)
2260 MonFdset *mon_fdset;
2261 MonFdsetFd *mon_fdset_fd_dup;
2263 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2264 QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
2265 if (mon_fdset_fd_dup->fd == dup_fd) {
2267 QLIST_REMOVE(mon_fdset_fd_dup, next);
2268 if (QLIST_EMPTY(&mon_fdset->dup_fds)) {
2269 monitor_fdset_cleanup(mon_fdset);
2273 return mon_fdset->id;
2281 int monitor_fdset_dup_fd_find(int dup_fd)
2283 return monitor_fdset_dup_fd_find_remove(dup_fd, false);
2286 void monitor_fdset_dup_fd_remove(int dup_fd)
2288 monitor_fdset_dup_fd_find_remove(dup_fd, true);
2291 int monitor_fd_param(Monitor *mon, const char *fdname, Error **errp)
2294 Error *local_err = NULL;
2296 if (!qemu_isdigit(fdname[0]) && mon) {
2297 fd = monitor_get_fd(mon, fdname, &local_err);
2299 fd = qemu_parse_fd(fdname);
2301 error_setg(&local_err, "Invalid file descriptor number '%s'",
2306 error_propagate(errp, local_err);
2315 /* Please update hmp-commands.hx when adding or changing commands */
2316 static mon_cmd_t info_cmds[] = {
2317 #include "hmp-commands-info.h"
2321 /* mon_cmds and info_cmds would be sorted at runtime */
2322 static mon_cmd_t mon_cmds[] = {
2323 #include "hmp-commands.h"
2327 /*******************************************************************/
2329 static const char *pch;
2330 static sigjmp_buf expr_env;
2333 static void GCC_FMT_ATTR(2, 3) QEMU_NORETURN
2334 expr_error(Monitor *mon, const char *fmt, ...)
2338 monitor_vprintf(mon, fmt, ap);
2339 monitor_printf(mon, "\n");
2341 siglongjmp(expr_env, 1);
2344 /* return 0 if OK, -1 if not found */
2345 static int get_monitor_def(target_long *pval, const char *name)
2347 const MonitorDef *md = target_monitor_defs();
2348 CPUState *cs = mon_get_cpu();
2353 if (cs == NULL || md == NULL) {
2357 for(; md->name != NULL; md++) {
2358 if (compare_cmd(name, md->name)) {
2359 if (md->get_value) {
2360 *pval = md->get_value(md, md->offset);
2362 CPUArchState *env = mon_get_cpu_env();
2363 ptr = (uint8_t *)env + md->offset;
2366 *pval = *(int32_t *)ptr;
2369 *pval = *(target_long *)ptr;
2380 ret = target_get_monitor_def(cs, name, &tmp);
2382 *pval = (target_long) tmp;
2388 static void next(void)
2392 while (qemu_isspace(*pch))
2397 static int64_t expr_sum(Monitor *mon);
2399 static int64_t expr_unary(Monitor *mon)
2408 n = expr_unary(mon);
2412 n = -expr_unary(mon);
2416 n = ~expr_unary(mon);
2422 expr_error(mon, "')' expected");
2429 expr_error(mon, "character constant expected");
2433 expr_error(mon, "missing terminating \' character");
2443 while ((*pch >= 'a' && *pch <= 'z') ||
2444 (*pch >= 'A' && *pch <= 'Z') ||
2445 (*pch >= '0' && *pch <= '9') ||
2446 *pch == '_' || *pch == '.') {
2447 if ((q - buf) < sizeof(buf) - 1)
2451 while (qemu_isspace(*pch))
2454 ret = get_monitor_def(®, buf);
2456 expr_error(mon, "unknown register");
2461 expr_error(mon, "unexpected end of expression");
2466 n = strtoull(pch, &p, 0);
2467 if (errno == ERANGE) {
2468 expr_error(mon, "number too large");
2471 expr_error(mon, "invalid char '%c' in expression", *p);
2474 while (qemu_isspace(*pch))
2482 static int64_t expr_prod(Monitor *mon)
2487 val = expr_unary(mon);
2490 if (op != '*' && op != '/' && op != '%')
2493 val2 = expr_unary(mon);
2502 expr_error(mon, "division by zero");
2513 static int64_t expr_logic(Monitor *mon)
2518 val = expr_prod(mon);
2521 if (op != '&' && op != '|' && op != '^')
2524 val2 = expr_prod(mon);
2541 static int64_t expr_sum(Monitor *mon)
2546 val = expr_logic(mon);
2549 if (op != '+' && op != '-')
2552 val2 = expr_logic(mon);
2561 static int get_expr(Monitor *mon, int64_t *pval, const char **pp)
2564 if (sigsetjmp(expr_env, 0)) {
2568 while (qemu_isspace(*pch))
2570 *pval = expr_sum(mon);
2575 static int get_double(Monitor *mon, double *pval, const char **pp)
2577 const char *p = *pp;
2581 d = strtod(p, &tailp);
2583 monitor_printf(mon, "Number expected\n");
2586 if (d != d || d - d != 0) {
2587 /* NaN or infinity */
2588 monitor_printf(mon, "Bad number\n");
2597 * Store the command-name in cmdname, and return a pointer to
2598 * the remaining of the command string.
2600 static const char *get_command_name(const char *cmdline,
2601 char *cmdname, size_t nlen)
2604 const char *p, *pstart;
2607 while (qemu_isspace(*p))
2612 while (*p != '\0' && *p != '/' && !qemu_isspace(*p))
2617 memcpy(cmdname, pstart, len);
2618 cmdname[len] = '\0';
2623 * Read key of 'type' into 'key' and return the current
2626 static char *key_get_info(const char *type, char **key)
2634 p = strchr(type, ':');
2641 str = g_malloc(len + 1);
2642 memcpy(str, type, len);
2649 static int default_fmt_format = 'x';
2650 static int default_fmt_size = 4;
2652 static int is_valid_option(const char *c, const char *typestr)
2660 typestr = strstr(typestr, option);
2661 return (typestr != NULL);
2664 static const mon_cmd_t *search_dispatch_table(const mon_cmd_t *disp_table,
2665 const char *cmdname)
2667 const mon_cmd_t *cmd;
2669 for (cmd = disp_table; cmd->name != NULL; cmd++) {
2670 if (compare_cmd(cmdname, cmd->name)) {
2679 * Parse command name from @cmdp according to command table @table.
2680 * If blank, return NULL.
2681 * Else, if no valid command can be found, report to @mon, and return
2683 * Else, change @cmdp to point right behind the name, and return its
2684 * command table entry.
2685 * Do not assume the return value points into @table! It doesn't when
2686 * the command is found in a sub-command table.
2688 static const mon_cmd_t *monitor_parse_command(Monitor *mon,
2689 const char *cmdp_start,
2694 const mon_cmd_t *cmd;
2697 /* extract the command name */
2698 p = get_command_name(*cmdp, cmdname, sizeof(cmdname));
2702 cmd = search_dispatch_table(table, cmdname);
2704 monitor_printf(mon, "unknown command: '%.*s'\n",
2705 (int)(p - cmdp_start), cmdp_start);
2709 /* filter out following useless space */
2710 while (qemu_isspace(*p)) {
2715 /* search sub command */
2716 if (cmd->sub_table != NULL && *p != '\0') {
2717 return monitor_parse_command(mon, cmdp_start, cmdp, cmd->sub_table);
2724 * Parse arguments for @cmd.
2725 * If it can't be parsed, report to @mon, and return NULL.
2726 * Else, insert command arguments into a QDict, and return it.
2727 * Note: On success, caller has to free the QDict structure.
2730 static QDict *monitor_parse_arguments(Monitor *mon,
2732 const mon_cmd_t *cmd)
2734 const char *typestr;
2737 const char *p = *endp;
2739 QDict *qdict = qdict_new();
2741 /* parse the parameters */
2742 typestr = cmd->args_type;
2744 typestr = key_get_info(typestr, &key);
2756 while (qemu_isspace(*p))
2758 if (*typestr == '?') {
2761 /* no optional string: NULL argument */
2765 ret = get_str(buf, sizeof(buf), &p);
2769 monitor_printf(mon, "%s: filename expected\n",
2773 monitor_printf(mon, "%s: block device name expected\n",
2777 monitor_printf(mon, "%s: string expected\n", cmd->name);
2782 qdict_put_str(qdict, key, buf);
2787 QemuOptsList *opts_list;
2790 opts_list = qemu_find_opts(key);
2791 if (!opts_list || opts_list->desc->name) {
2794 while (qemu_isspace(*p)) {
2799 if (get_str(buf, sizeof(buf), &p) < 0) {
2802 opts = qemu_opts_parse_noisily(opts_list, buf, true);
2806 qemu_opts_to_qdict(opts, qdict);
2807 qemu_opts_del(opts);
2812 int count, format, size;
2814 while (qemu_isspace(*p))
2820 if (qemu_isdigit(*p)) {
2822 while (qemu_isdigit(*p)) {
2823 count = count * 10 + (*p - '0');
2861 if (*p != '\0' && !qemu_isspace(*p)) {
2862 monitor_printf(mon, "invalid char in format: '%c'\n",
2867 format = default_fmt_format;
2868 if (format != 'i') {
2869 /* for 'i', not specifying a size gives -1 as size */
2871 size = default_fmt_size;
2872 default_fmt_size = size;
2874 default_fmt_format = format;
2877 format = default_fmt_format;
2878 if (format != 'i') {
2879 size = default_fmt_size;
2884 qdict_put_int(qdict, "count", count);
2885 qdict_put_int(qdict, "format", format);
2886 qdict_put_int(qdict, "size", size);
2895 while (qemu_isspace(*p))
2897 if (*typestr == '?' || *typestr == '.') {
2898 if (*typestr == '?') {
2906 while (qemu_isspace(*p))
2915 if (get_expr(mon, &val, &p))
2917 /* Check if 'i' is greater than 32-bit */
2918 if ((c == 'i') && ((val >> 32) & 0xffffffff)) {
2919 monitor_printf(mon, "\'%s\' has failed: ", cmd->name);
2920 monitor_printf(mon, "integer is for 32-bit values\n");
2922 } else if (c == 'M') {
2924 monitor_printf(mon, "enter a positive value\n");
2929 qdict_put_int(qdict, key, val);
2938 while (qemu_isspace(*p)) {
2941 if (*typestr == '?') {
2947 ret = qemu_strtosz_MiB(p, &end, &val);
2948 if (ret < 0 || val > INT64_MAX) {
2949 monitor_printf(mon, "invalid size\n");
2952 qdict_put_int(qdict, key, val);
2960 while (qemu_isspace(*p))
2962 if (*typestr == '?') {
2968 if (get_double(mon, &val, &p) < 0) {
2971 if (p[0] && p[1] == 's') {
2974 val /= 1e3; p += 2; break;
2976 val /= 1e6; p += 2; break;
2978 val /= 1e9; p += 2; break;
2981 if (*p && !qemu_isspace(*p)) {
2982 monitor_printf(mon, "Unknown unit suffix\n");
2985 qdict_put(qdict, key, qnum_from_double(val));
2993 while (qemu_isspace(*p)) {
2997 while (qemu_isgraph(*p)) {
3000 if (p - beg == 2 && !memcmp(beg, "on", p - beg)) {
3002 } else if (p - beg == 3 && !memcmp(beg, "off", p - beg)) {
3005 monitor_printf(mon, "Expected 'on' or 'off'\n");
3008 qdict_put_bool(qdict, key, val);
3013 const char *tmp = p;
3020 while (qemu_isspace(*p))
3025 if(!is_valid_option(p, typestr)) {
3027 monitor_printf(mon, "%s: unsupported option -%c\n",
3039 qdict_put_bool(qdict, key, true);
3046 /* package all remaining string */
3049 while (qemu_isspace(*p)) {
3052 if (*typestr == '?') {
3055 /* no remaining string: NULL argument */
3061 monitor_printf(mon, "%s: string expected\n",
3065 qdict_put_str(qdict, key, p);
3071 monitor_printf(mon, "%s: unknown type '%c'\n", cmd->name, c);
3077 /* check that all arguments were parsed */
3078 while (qemu_isspace(*p))
3081 monitor_printf(mon, "%s: extraneous characters at the end of line\n",
3094 static void handle_hmp_command(Monitor *mon, const char *cmdline)
3097 const mon_cmd_t *cmd;
3099 trace_handle_hmp_command(mon, cmdline);
3101 cmd = monitor_parse_command(mon, cmdline, &cmdline, mon->cmd_table);
3106 qdict = monitor_parse_arguments(mon, &cmdline, cmd);
3108 monitor_printf(mon, "Try \"help %s\" for more information\n",
3113 cmd->cmd(mon, qdict);
3117 static void cmd_completion(Monitor *mon, const char *name, const char *list)
3119 const char *p, *pstart;
3128 p = pstart + strlen(pstart);
3130 if (len > sizeof(cmd) - 2)
3131 len = sizeof(cmd) - 2;
3132 memcpy(cmd, pstart, len);
3134 if (name[0] == '\0' || !strncmp(name, cmd, strlen(name))) {
3135 readline_add_completion(mon->rs, cmd);
3143 static void file_completion(Monitor *mon, const char *input)
3148 char file[1024], file_prefix[1024];
3152 p = strrchr(input, '/');
3155 pstrcpy(file_prefix, sizeof(file_prefix), input);
3156 pstrcpy(path, sizeof(path), ".");
3158 input_path_len = p - input + 1;
3159 memcpy(path, input, input_path_len);
3160 if (input_path_len > sizeof(path) - 1)
3161 input_path_len = sizeof(path) - 1;
3162 path[input_path_len] = '\0';
3163 pstrcpy(file_prefix, sizeof(file_prefix), p + 1);
3166 ffs = opendir(path);
3175 if (strcmp(d->d_name, ".") == 0 || strcmp(d->d_name, "..") == 0) {
3179 if (strstart(d->d_name, file_prefix, NULL)) {
3180 memcpy(file, input, input_path_len);
3181 if (input_path_len < sizeof(file))
3182 pstrcpy(file + input_path_len, sizeof(file) - input_path_len,
3184 /* stat the file to find out if it's a directory.
3185 * In that case add a slash to speed up typing long paths
3187 if (stat(file, &sb) == 0 && S_ISDIR(sb.st_mode)) {
3188 pstrcat(file, sizeof(file), "/");
3190 readline_add_completion(mon->rs, file);
3196 static const char *next_arg_type(const char *typestr)
3198 const char *p = strchr(typestr, ':');
3199 return (p != NULL ? ++p : typestr);
3202 static void add_completion_option(ReadLineState *rs, const char *str,
3205 if (!str || !option) {
3208 if (!strncmp(option, str, strlen(str))) {
3209 readline_add_completion(rs, option);
3213 void chardev_add_completion(ReadLineState *rs, int nb_args, const char *str)
3216 ChardevBackendInfoList *list, *start;
3222 readline_set_completion_index(rs, len);
3224 start = list = qmp_query_chardev_backends(NULL);
3226 const char *chr_name = list->value->name;
3228 if (!strncmp(chr_name, str, len)) {
3229 readline_add_completion(rs, chr_name);
3233 qapi_free_ChardevBackendInfoList(start);
3236 void netdev_add_completion(ReadLineState *rs, int nb_args, const char *str)
3245 readline_set_completion_index(rs, len);
3246 for (i = 0; i < NET_CLIENT_DRIVER__MAX; i++) {
3247 add_completion_option(rs, str, NetClientDriver_str(i));
3251 void device_add_completion(ReadLineState *rs, int nb_args, const char *str)
3261 readline_set_completion_index(rs, len);
3262 list = elt = object_class_get_list(TYPE_DEVICE, false);
3265 DeviceClass *dc = OBJECT_CLASS_CHECK(DeviceClass, elt->data,
3267 name = object_class_get_name(OBJECT_CLASS(dc));
3269 if (dc->user_creatable
3270 && !strncmp(name, str, len)) {
3271 readline_add_completion(rs, name);
3278 void object_add_completion(ReadLineState *rs, int nb_args, const char *str)
3288 readline_set_completion_index(rs, len);
3289 list = elt = object_class_get_list(TYPE_USER_CREATABLE, false);
3293 name = object_class_get_name(OBJECT_CLASS(elt->data));
3294 if (!strncmp(name, str, len) && strcmp(name, TYPE_USER_CREATABLE)) {
3295 readline_add_completion(rs, name);
3302 static void peripheral_device_del_completion(ReadLineState *rs,
3303 const char *str, size_t len)
3305 Object *peripheral = container_get(qdev_get_machine(), "/peripheral");
3306 GSList *list, *item;
3308 list = qdev_build_hotpluggable_device_list(peripheral);
3313 for (item = list; item; item = g_slist_next(item)) {
3314 DeviceState *dev = item->data;
3316 if (dev->id && !strncmp(str, dev->id, len)) {
3317 readline_add_completion(rs, dev->id);
3324 void chardev_remove_completion(ReadLineState *rs, int nb_args, const char *str)
3327 ChardevInfoList *list, *start;
3333 readline_set_completion_index(rs, len);
3335 start = list = qmp_query_chardev(NULL);
3337 ChardevInfo *chr = list->value;
3339 if (!strncmp(chr->label, str, len)) {
3340 readline_add_completion(rs, chr->label);
3344 qapi_free_ChardevInfoList(start);
3347 static void ringbuf_completion(ReadLineState *rs, const char *str)
3350 ChardevInfoList *list, *start;
3353 readline_set_completion_index(rs, len);
3355 start = list = qmp_query_chardev(NULL);
3357 ChardevInfo *chr_info = list->value;
3359 if (!strncmp(chr_info->label, str, len)) {
3360 Chardev *chr = qemu_chr_find(chr_info->label);
3361 if (chr && CHARDEV_IS_RINGBUF(chr)) {
3362 readline_add_completion(rs, chr_info->label);
3367 qapi_free_ChardevInfoList(start);
3370 void ringbuf_write_completion(ReadLineState *rs, int nb_args, const char *str)
3375 ringbuf_completion(rs, str);
3378 void device_del_completion(ReadLineState *rs, int nb_args, const char *str)
3387 readline_set_completion_index(rs, len);
3388 peripheral_device_del_completion(rs, str, len);
3391 void object_del_completion(ReadLineState *rs, int nb_args, const char *str)
3393 ObjectPropertyInfoList *list, *start;
3400 readline_set_completion_index(rs, len);
3402 start = list = qmp_qom_list("/objects", NULL);
3404 ObjectPropertyInfo *info = list->value;
3406 if (!strncmp(info->type, "child<", 5)
3407 && !strncmp(info->name, str, len)) {
3408 readline_add_completion(rs, info->name);
3412 qapi_free_ObjectPropertyInfoList(start);
3415 void sendkey_completion(ReadLineState *rs, int nb_args, const char *str)
3424 sep = strrchr(str, '-');
3429 readline_set_completion_index(rs, len);
3430 for (i = 0; i < Q_KEY_CODE__MAX; i++) {
3431 if (!strncmp(str, QKeyCode_str(i), len)) {
3432 readline_add_completion(rs, QKeyCode_str(i));
3437 void set_link_completion(ReadLineState *rs, int nb_args, const char *str)
3442 readline_set_completion_index(rs, len);
3444 NetClientState *ncs[MAX_QUEUE_NUM];
3446 count = qemu_find_net_clients_except(NULL, ncs,
3447 NET_CLIENT_DRIVER_NONE,
3449 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3450 const char *name = ncs[i]->name;
3451 if (!strncmp(str, name, len)) {
3452 readline_add_completion(rs, name);
3455 } else if (nb_args == 3) {
3456 add_completion_option(rs, str, "on");
3457 add_completion_option(rs, str, "off");
3461 void netdev_del_completion(ReadLineState *rs, int nb_args, const char *str)
3464 NetClientState *ncs[MAX_QUEUE_NUM];
3471 readline_set_completion_index(rs, len);
3472 count = qemu_find_net_clients_except(NULL, ncs, NET_CLIENT_DRIVER_NIC,
3474 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3476 const char *name = ncs[i]->name;
3477 if (strncmp(str, name, len)) {
3480 opts = qemu_opts_find(qemu_find_opts_err("netdev", NULL), name);
3482 readline_add_completion(rs, name);
3487 void info_trace_events_completion(ReadLineState *rs, int nb_args, const char *str)
3492 readline_set_completion_index(rs, len);
3494 TraceEventIter iter;
3496 char *pattern = g_strdup_printf("%s*", str);
3497 trace_event_iter_init(&iter, pattern);
3498 while ((ev = trace_event_iter_next(&iter)) != NULL) {
3499 readline_add_completion(rs, trace_event_get_name(ev));
3505 void trace_event_completion(ReadLineState *rs, int nb_args, const char *str)
3510 readline_set_completion_index(rs, len);
3512 TraceEventIter iter;
3514 char *pattern = g_strdup_printf("%s*", str);
3515 trace_event_iter_init(&iter, pattern);
3516 while ((ev = trace_event_iter_next(&iter)) != NULL) {
3517 readline_add_completion(rs, trace_event_get_name(ev));
3520 } else if (nb_args == 3) {
3521 add_completion_option(rs, str, "on");
3522 add_completion_option(rs, str, "off");
3526 void watchdog_action_completion(ReadLineState *rs, int nb_args, const char *str)
3533 readline_set_completion_index(rs, strlen(str));
3534 for (i = 0; i < WATCHDOG_ACTION__MAX; i++) {
3535 add_completion_option(rs, str, WatchdogAction_str(i));
3539 void migrate_set_capability_completion(ReadLineState *rs, int nb_args,
3545 readline_set_completion_index(rs, len);
3548 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
3549 const char *name = MigrationCapability_str(i);
3550 if (!strncmp(str, name, len)) {
3551 readline_add_completion(rs, name);
3554 } else if (nb_args == 3) {
3555 add_completion_option(rs, str, "on");
3556 add_completion_option(rs, str, "off");
3560 void migrate_set_parameter_completion(ReadLineState *rs, int nb_args,
3566 readline_set_completion_index(rs, len);
3569 for (i = 0; i < MIGRATION_PARAMETER__MAX; i++) {
3570 const char *name = MigrationParameter_str(i);
3571 if (!strncmp(str, name, len)) {
3572 readline_add_completion(rs, name);
3578 void host_net_add_completion(ReadLineState *rs, int nb_args, const char *str)
3586 readline_set_completion_index(rs, len);
3587 for (i = 0; host_net_devices[i]; i++) {
3588 if (!strncmp(host_net_devices[i], str, len)) {
3589 readline_add_completion(rs, host_net_devices[i]);
3594 void host_net_remove_completion(ReadLineState *rs, int nb_args, const char *str)
3596 NetClientState *ncs[MAX_QUEUE_NUM];
3600 readline_set_completion_index(rs, len);
3602 count = qemu_find_net_clients_except(NULL, ncs,
3603 NET_CLIENT_DRIVER_NONE,
3605 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3609 if (net_hub_id_for_client(ncs[i], &id)) {
3612 snprintf(name, sizeof(name), "%d", id);
3613 if (!strncmp(str, name, len)) {
3614 readline_add_completion(rs, name);
3618 } else if (nb_args == 3) {
3619 count = qemu_find_net_clients_except(NULL, ncs,
3620 NET_CLIENT_DRIVER_NIC,
3622 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3626 if (ncs[i]->info->type == NET_CLIENT_DRIVER_HUBPORT ||
3627 net_hub_id_for_client(ncs[i], &id)) {
3630 name = ncs[i]->name;
3631 if (!strncmp(str, name, len)) {
3632 readline_add_completion(rs, name);
3639 static void vm_completion(ReadLineState *rs, const char *str)
3642 BlockDriverState *bs;
3643 BdrvNextIterator it;
3646 readline_set_completion_index(rs, len);
3648 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
3649 SnapshotInfoList *snapshots, *snapshot;
3650 AioContext *ctx = bdrv_get_aio_context(bs);
3653 aio_context_acquire(ctx);
3654 if (bdrv_can_snapshot(bs)) {
3655 ok = bdrv_query_snapshot_info_list(bs, &snapshots, NULL) == 0;
3657 aio_context_release(ctx);
3662 snapshot = snapshots;
3664 char *completion = snapshot->value->name;
3665 if (!strncmp(str, completion, len)) {
3666 readline_add_completion(rs, completion);
3668 completion = snapshot->value->id;
3669 if (!strncmp(str, completion, len)) {
3670 readline_add_completion(rs, completion);
3672 snapshot = snapshot->next;
3674 qapi_free_SnapshotInfoList(snapshots);
3679 void delvm_completion(ReadLineState *rs, int nb_args, const char *str)
3682 vm_completion(rs, str);
3686 void loadvm_completion(ReadLineState *rs, int nb_args, const char *str)
3689 vm_completion(rs, str);
3693 static void monitor_find_completion_by_table(Monitor *mon,
3694 const mon_cmd_t *cmd_table,
3698 const char *cmdname;
3700 const char *ptype, *str, *name;
3701 const mon_cmd_t *cmd;
3702 BlockBackend *blk = NULL;
3705 /* command completion */
3710 readline_set_completion_index(mon->rs, strlen(cmdname));
3711 for (cmd = cmd_table; cmd->name != NULL; cmd++) {
3712 cmd_completion(mon, cmdname, cmd->name);
3715 /* find the command */
3716 for (cmd = cmd_table; cmd->name != NULL; cmd++) {
3717 if (compare_cmd(args[0], cmd->name)) {
3725 if (cmd->sub_table) {
3726 /* do the job again */
3727 monitor_find_completion_by_table(mon, cmd->sub_table,
3728 &args[1], nb_args - 1);
3731 if (cmd->command_completion) {
3732 cmd->command_completion(mon->rs, nb_args, args[nb_args - 1]);
3736 ptype = next_arg_type(cmd->args_type);
3737 for(i = 0; i < nb_args - 2; i++) {
3738 if (*ptype != '\0') {
3739 ptype = next_arg_type(ptype);
3740 while (*ptype == '?')
3741 ptype = next_arg_type(ptype);
3744 str = args[nb_args - 1];
3745 while (*ptype == '-' && ptype[1] != '\0') {
3746 ptype = next_arg_type(ptype);
3750 /* file completion */
3751 readline_set_completion_index(mon->rs, strlen(str));
3752 file_completion(mon, str);
3755 /* block device name completion */
3756 readline_set_completion_index(mon->rs, strlen(str));
3757 while ((blk = blk_next(blk)) != NULL) {
3758 name = blk_name(blk);
3759 if (str[0] == '\0' ||
3760 !strncmp(name, str, strlen(str))) {
3761 readline_add_completion(mon->rs, name);
3767 if (!strcmp(cmd->name, "help|?")) {
3768 monitor_find_completion_by_table(mon, cmd_table,
3769 &args[1], nb_args - 1);
3778 static void monitor_find_completion(void *opaque,
3779 const char *cmdline)
3781 Monitor *mon = opaque;
3782 char *args[MAX_ARGS];
3785 /* 1. parse the cmdline */
3786 if (parse_cmdline(cmdline, &nb_args, args) < 0) {
3790 /* if the line ends with a space, it means we want to complete the
3792 len = strlen(cmdline);
3793 if (len > 0 && qemu_isspace(cmdline[len - 1])) {
3794 if (nb_args >= MAX_ARGS) {
3797 args[nb_args++] = g_strdup("");
3800 /* 2. auto complete according to args */
3801 monitor_find_completion_by_table(mon, mon->cmd_table, args, nb_args);
3804 free_cmdline_args(args, nb_args);
3807 static int monitor_can_read(void *opaque)
3809 Monitor *mon = opaque;
3811 return (mon->suspend_cnt == 0) ? 1 : 0;
3814 static void handle_qmp_command(JSONMessageParser *parser, GQueue *tokens)
3816 QObject *req, *rsp = NULL, *id = NULL;
3817 QDict *qdict = NULL;
3818 Monitor *mon = cur_mon;
3821 req = json_parser_parse_err(tokens, NULL, &err);
3823 /* json_parser_parse_err() sucks: can fail without setting @err */
3824 error_setg(&err, QERR_JSON_PARSING);
3830 qdict = qobject_to_qdict(req);
3832 id = qdict_get(qdict, "id");
3834 qdict_del(qdict, "id");
3835 } /* else will fail qmp_dispatch() */
3837 if (trace_event_get_state_backends(TRACE_HANDLE_QMP_COMMAND)) {
3838 QString *req_json = qobject_to_json(req);
3839 trace_handle_qmp_command(mon, qstring_get_str(req_json));
3843 rsp = qmp_dispatch(cur_mon->qmp.commands, req);
3845 if (mon->qmp.commands == &qmp_cap_negotiation_commands) {
3846 qdict = qdict_get_qdict(qobject_to_qdict(rsp), "error");
3848 && !g_strcmp0(qdict_get_try_str(qdict, "class"),
3849 QapiErrorClass_str(ERROR_CLASS_COMMAND_NOT_FOUND))) {
3850 /* Provide a more useful error message */
3851 qdict_del(qdict, "desc");
3852 qdict_put_str(qdict, "desc", "Expecting capabilities negotiation"
3853 " with 'qmp_capabilities'");
3859 qdict = qdict_new();
3860 qdict_put_obj(qdict, "error", qmp_build_error_object(err));
3862 rsp = QOBJECT(qdict);
3867 qdict_put_obj(qobject_to_qdict(rsp), "id", id);
3871 monitor_json_emitter(mon, rsp);
3875 qobject_decref(rsp);
3876 qobject_decref(req);
3879 static void monitor_qmp_read(void *opaque, const uint8_t *buf, int size)
3881 Monitor *old_mon = cur_mon;
3885 json_message_parser_feed(&cur_mon->qmp.parser, (const char *) buf, size);
3890 static void monitor_read(void *opaque, const uint8_t *buf, int size)
3892 Monitor *old_mon = cur_mon;
3898 for (i = 0; i < size; i++)
3899 readline_handle_byte(cur_mon->rs, buf[i]);
3901 if (size == 0 || buf[size - 1] != 0)
3902 monitor_printf(cur_mon, "corrupted command\n");
3904 handle_hmp_command(cur_mon, (char *)buf);
3910 static void monitor_command_cb(void *opaque, const char *cmdline,
3911 void *readline_opaque)
3913 Monitor *mon = opaque;
3915 monitor_suspend(mon);
3916 handle_hmp_command(mon, cmdline);
3917 monitor_resume(mon);
3920 int monitor_suspend(Monitor *mon)
3928 void monitor_resume(Monitor *mon)
3932 if (--mon->suspend_cnt == 0)
3933 readline_show_prompt(mon->rs);
3936 static QObject *get_qmp_greeting(void)
3938 QObject *ver = NULL;
3940 qmp_marshal_query_version(NULL, &ver, NULL);
3942 return qobject_from_jsonf("{'QMP': {'version': %p, 'capabilities': []}}",
3946 static void monitor_qmp_event(void *opaque, int event)
3949 Monitor *mon = opaque;
3952 case CHR_EVENT_OPENED:
3953 mon->qmp.commands = &qmp_cap_negotiation_commands;
3954 data = get_qmp_greeting();
3955 monitor_json_emitter(mon, data);
3956 qobject_decref(data);
3959 case CHR_EVENT_CLOSED:
3960 json_message_parser_destroy(&mon->qmp.parser);
3961 json_message_parser_init(&mon->qmp.parser, handle_qmp_command);
3963 monitor_fdsets_cleanup();
3968 static void monitor_event(void *opaque, int event)
3970 Monitor *mon = opaque;
3973 case CHR_EVENT_MUX_IN:
3974 qemu_mutex_lock(&mon->out_lock);
3976 qemu_mutex_unlock(&mon->out_lock);
3977 if (mon->reset_seen) {
3978 readline_restart(mon->rs);
3979 monitor_resume(mon);
3982 mon->suspend_cnt = 0;
3986 case CHR_EVENT_MUX_OUT:
3987 if (mon->reset_seen) {
3988 if (mon->suspend_cnt == 0) {
3989 monitor_printf(mon, "\n");
3992 monitor_suspend(mon);
3996 qemu_mutex_lock(&mon->out_lock);
3998 qemu_mutex_unlock(&mon->out_lock);
4001 case CHR_EVENT_OPENED:
4002 monitor_printf(mon, "QEMU %s monitor - type 'help' for more "
4003 "information\n", QEMU_VERSION);
4004 if (!mon->mux_out) {
4005 readline_restart(mon->rs);
4006 readline_show_prompt(mon->rs);
4008 mon->reset_seen = 1;
4012 case CHR_EVENT_CLOSED:
4014 monitor_fdsets_cleanup();
4020 compare_mon_cmd(const void *a, const void *b)
4022 return strcmp(((const mon_cmd_t *)a)->name,
4023 ((const mon_cmd_t *)b)->name);
4026 static void sortcmdlist(void)
4029 int elem_size = sizeof(mon_cmd_t);
4031 array_num = sizeof(mon_cmds)/elem_size-1;
4032 qsort((void *)mon_cmds, array_num, elem_size, compare_mon_cmd);
4034 array_num = sizeof(info_cmds)/elem_size-1;
4035 qsort((void *)info_cmds, array_num, elem_size, compare_mon_cmd);
4038 /* These functions just adapt the readline interface in a typesafe way. We
4039 * could cast function pointers but that discards compiler checks.
4041 static void GCC_FMT_ATTR(2, 3) monitor_readline_printf(void *opaque,
4042 const char *fmt, ...)
4046 monitor_vprintf(opaque, fmt, ap);
4050 static void monitor_readline_flush(void *opaque)
4052 monitor_flush(opaque);
4056 * Print to current monitor if we have one, else to stderr.
4057 * TODO should return int, so callers can calculate width, but that
4058 * requires surgery to monitor_vprintf(). Left for another day.
4060 void error_vprintf(const char *fmt, va_list ap)
4062 if (cur_mon && !monitor_cur_is_qmp()) {
4063 monitor_vprintf(cur_mon, fmt, ap);
4065 vfprintf(stderr, fmt, ap);
4069 void error_vprintf_unless_qmp(const char *fmt, va_list ap)
4071 if (cur_mon && !monitor_cur_is_qmp()) {
4072 monitor_vprintf(cur_mon, fmt, ap);
4073 } else if (!cur_mon) {
4074 vfprintf(stderr, fmt, ap);
4078 static void __attribute__((constructor)) monitor_lock_init(void)
4080 qemu_mutex_init(&monitor_lock);
4083 void monitor_init(Chardev *chr, int flags)
4085 static int is_first_init = 1;
4088 if (is_first_init) {
4089 monitor_qapi_event_init();
4094 mon = g_malloc(sizeof(*mon));
4095 monitor_data_init(mon);
4097 qemu_chr_fe_init(&mon->chr, chr, &error_abort);
4099 if (flags & MONITOR_USE_READLINE) {
4100 mon->rs = readline_init(monitor_readline_printf,
4101 monitor_readline_flush,
4103 monitor_find_completion);
4104 monitor_read_command(mon, 0);
4107 if (monitor_is_qmp(mon)) {
4108 qemu_chr_fe_set_handlers(&mon->chr, monitor_can_read, monitor_qmp_read,
4109 monitor_qmp_event, NULL, mon, NULL, true);
4110 qemu_chr_fe_set_echo(&mon->chr, true);
4111 json_message_parser_init(&mon->qmp.parser, handle_qmp_command);
4113 qemu_chr_fe_set_handlers(&mon->chr, monitor_can_read, monitor_read,
4114 monitor_event, NULL, mon, NULL, true);
4117 qemu_mutex_lock(&monitor_lock);
4118 QLIST_INSERT_HEAD(&mon_list, mon, entry);
4119 qemu_mutex_unlock(&monitor_lock);
4122 void monitor_cleanup(void)
4124 Monitor *mon, *next;
4126 qemu_mutex_lock(&monitor_lock);
4127 QLIST_FOREACH_SAFE(mon, &mon_list, entry, next) {
4128 QLIST_REMOVE(mon, entry);
4129 monitor_data_destroy(mon);
4132 qemu_mutex_unlock(&monitor_lock);
4135 QemuOptsList qemu_mon_opts = {
4137 .implied_opt_name = "chardev",
4138 .head = QTAILQ_HEAD_INITIALIZER(qemu_mon_opts.head),
4142 .type = QEMU_OPT_STRING,
4145 .type = QEMU_OPT_STRING,
4147 .name = "default", /* deprecated */
4148 .type = QEMU_OPT_BOOL,
4151 .type = QEMU_OPT_BOOL,
4153 { /* end of list */ }
4158 void qmp_rtc_reset_reinjection(Error **errp)
4160 error_setg(errp, QERR_FEATURE_DISABLED, "rtc-reset-reinjection");
4164 #ifndef TARGET_S390X
4165 void qmp_dump_skeys(const char *filename, Error **errp)
4167 error_setg(errp, QERR_FEATURE_DISABLED, "dump-skeys");
4172 GICCapabilityList *qmp_query_gic_capabilities(Error **errp)
4174 error_setg(errp, QERR_FEATURE_DISABLED, "query-gic-capabilities");
4179 HotpluggableCPUList *qmp_query_hotpluggable_cpus(Error **errp)
4181 MachineState *ms = MACHINE(qdev_get_machine());
4182 MachineClass *mc = MACHINE_GET_CLASS(ms);
4184 if (!mc->has_hotpluggable_cpus) {
4185 error_setg(errp, QERR_FEATURE_DISABLED, "query-hotpluggable-cpus");
4189 return machine_query_hotpluggable_cpus(ms);