4 * Copyright (c) 2003-2004 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24 #include "qemu/osdep.h"
26 #include "qemu-common.h"
29 #include "monitor/qdev.h"
31 #include "hw/pci/pci.h"
32 #include "sysemu/watchdog.h"
33 #include "hw/loader.h"
34 #include "exec/gdbstub.h"
36 #include "net/slirp.h"
37 #include "chardev/char-fe.h"
38 #include "ui/qemu-spice.h"
39 #include "sysemu/numa.h"
40 #include "monitor/monitor.h"
41 #include "qemu/config-file.h"
42 #include "qemu/readline.h"
43 #include "ui/console.h"
45 #include "sysemu/blockdev.h"
46 #include "sysemu/block-backend.h"
47 #include "audio/audio.h"
48 #include "disas/disas.h"
49 #include "sysemu/balloon.h"
50 #include "qemu/timer.h"
51 #include "sysemu/hw_accel.h"
53 #include "sysemu/tpm.h"
54 #include "qapi/qmp/qerror.h"
55 #include "qapi/qmp/types.h"
56 #include "qapi/qmp/qjson.h"
57 #include "qapi/qmp/json-streamer.h"
58 #include "qapi/qmp/json-parser.h"
59 #include "qom/object_interfaces.h"
60 #include "trace-root.h"
61 #include "trace/control.h"
62 #include "monitor/hmp-target.h"
63 #ifdef CONFIG_TRACE_SIMPLE
64 #include "trace/simple.h"
66 #include "exec/memory.h"
67 #include "exec/exec-all.h"
69 #include "qmp-commands.h"
71 #include "qemu/thread.h"
72 #include "block/qapi.h"
73 #include "qapi/qmp-event.h"
74 #include "qapi-event.h"
75 #include "qmp-introspect.h"
76 #include "sysemu/qtest.h"
77 #include "sysemu/cpus.h"
78 #include "qemu/cutils.h"
79 #include "qapi/qmp/dispatch.h"
81 #if defined(TARGET_S390X)
82 #include "hw/s390x/storage-keys.h"
83 #include "hw/s390x/storage-attributes.h"
90 * 'B' block device name
91 * 's' string (accept optional quote)
92 * 'S' it just appends the rest of the string (accept optional quote)
93 * 'O' option string of the form NAME=VALUE,...
94 * parsed according to QemuOptsList given by its name
95 * Example: 'device:O' uses qemu_device_opts.
96 * Restriction: only lists with empty desc are supported
97 * TODO lift the restriction
99 * 'l' target long (32 or 64 bit)
100 * 'M' Non-negative target long (32 or 64 bit), in user mode the
101 * value is multiplied by 2^20 (think Mebibyte)
102 * 'o' octets (aka bytes)
103 * user mode accepts an optional E, e, P, p, T, t, G, g, M, m,
104 * K, k suffix, which multiplies the value by 2^60 for suffixes E
105 * and e, 2^50 for suffixes P and p, 2^40 for suffixes T and t,
106 * 2^30 for suffixes G and g, 2^20 for M and m, 2^10 for K and k
108 * user mode accepts an optional ms, us, ns suffix,
109 * which divides the value by 1e3, 1e6, 1e9, respectively
110 * '/' optional gdb-like print format (like "/10x")
112 * '?' optional type (for all types, except '/')
113 * '.' other form of optional type (for 'i' and 'l')
115 * user mode accepts "on" or "off"
116 * '-' optional parameter (eg. '-f')
120 typedef struct mon_cmd_t {
122 const char *args_type;
125 void (*cmd)(Monitor *mon, const QDict *qdict);
126 /* @sub_table is a list of 2nd level of commands. If it does not exist,
127 * cmd should be used. If it exists, sub_table[?].cmd should be
128 * used, and cmd of 1st level plays the role of help function.
130 struct mon_cmd_t *sub_table;
131 void (*command_completion)(ReadLineState *rs, int nb_args, const char *str);
134 /* file descriptors passed via SCM_RIGHTS */
135 typedef struct mon_fd_t mon_fd_t;
139 QLIST_ENTRY(mon_fd_t) next;
142 /* file descriptor associated with a file descriptor set */
143 typedef struct MonFdsetFd MonFdsetFd;
148 QLIST_ENTRY(MonFdsetFd) next;
151 /* file descriptor set containing fds passed via SCM_RIGHTS */
152 typedef struct MonFdset MonFdset;
155 QLIST_HEAD(, MonFdsetFd) fds;
156 QLIST_HEAD(, MonFdsetFd) dup_fds;
157 QLIST_ENTRY(MonFdset) next;
161 JSONMessageParser parser;
163 * When a client connects, we're in capabilities negotiation mode.
164 * When command qmp_capabilities succeeds, we go into command
167 QmpCommandList *commands;
171 * To prevent flooding clients, events can be throttled. The
172 * throttling is calculated globally, rather than per-Monitor
175 typedef struct MonitorQAPIEventState {
176 QAPIEvent event; /* Throttling state for this event type and... */
177 QDict *data; /* ... data, see qapi_event_throttle_equal() */
178 QEMUTimer *timer; /* Timer for handling delayed events */
179 QDict *qdict; /* Delayed event (if any) */
180 } MonitorQAPIEventState;
183 int64_t rate; /* Minimum time (in ns) between two events */
184 } MonitorQAPIEventConf;
197 /* Read under either BQL or out_lock, written with BQL+out_lock. */
203 BlockCompletionFunc *password_completion_cb;
204 void *password_opaque;
205 mon_cmd_t *cmd_table;
206 QLIST_HEAD(,mon_fd_t) fds;
207 QLIST_ENTRY(Monitor) entry;
210 /* QMP checker flags */
211 #define QMP_ACCEPT_UNKNOWNS 1
213 /* Protects mon_list, monitor_event_state. */
214 static QemuMutex monitor_lock;
216 static QLIST_HEAD(mon_list, Monitor) mon_list;
217 static QLIST_HEAD(mon_fdsets, MonFdset) mon_fdsets;
218 static int mon_refcount;
220 static mon_cmd_t mon_cmds[];
221 static mon_cmd_t info_cmds[];
223 QmpCommandList qmp_commands, qmp_cap_negotiation_commands;
227 static QEMUClockType event_clock_type = QEMU_CLOCK_REALTIME;
229 static void monitor_command_cb(void *opaque, const char *cmdline,
230 void *readline_opaque);
233 * Is @mon a QMP monitor?
235 static inline bool monitor_is_qmp(const Monitor *mon)
237 return (mon->flags & MONITOR_USE_CONTROL);
241 * Is the current monitor, if any, a QMP monitor?
243 bool monitor_cur_is_qmp(void)
245 return cur_mon && monitor_is_qmp(cur_mon);
248 void monitor_read_command(Monitor *mon, int show_prompt)
253 readline_start(mon->rs, "(qemu) ", 0, monitor_command_cb, NULL);
255 readline_show_prompt(mon->rs);
258 int monitor_read_password(Monitor *mon, ReadLineFunc *readline_func,
262 readline_start(mon->rs, "Password: ", 1, readline_func, opaque);
263 /* prompt is printed on return from the command handler */
266 monitor_printf(mon, "terminal does not support password prompting\n");
271 static void monitor_flush_locked(Monitor *mon);
273 static gboolean monitor_unblocked(GIOChannel *chan, GIOCondition cond,
276 Monitor *mon = opaque;
278 qemu_mutex_lock(&mon->out_lock);
280 monitor_flush_locked(mon);
281 qemu_mutex_unlock(&mon->out_lock);
285 /* Called with mon->out_lock held. */
286 static void monitor_flush_locked(Monitor *mon)
292 if (mon->skip_flush) {
296 buf = qstring_get_str(mon->outbuf);
297 len = qstring_get_length(mon->outbuf);
299 if (len && !mon->mux_out) {
300 rc = qemu_chr_fe_write(&mon->chr, (const uint8_t *) buf, len);
301 if ((rc < 0 && errno != EAGAIN) || (rc == len)) {
302 /* all flushed or error */
303 QDECREF(mon->outbuf);
304 mon->outbuf = qstring_new();
309 QString *tmp = qstring_from_str(buf + rc);
310 QDECREF(mon->outbuf);
313 if (mon->out_watch == 0) {
315 qemu_chr_fe_add_watch(&mon->chr, G_IO_OUT | G_IO_HUP,
316 monitor_unblocked, mon);
321 void monitor_flush(Monitor *mon)
323 qemu_mutex_lock(&mon->out_lock);
324 monitor_flush_locked(mon);
325 qemu_mutex_unlock(&mon->out_lock);
328 /* flush at every end of line */
329 static void monitor_puts(Monitor *mon, const char *str)
333 qemu_mutex_lock(&mon->out_lock);
339 qstring_append_chr(mon->outbuf, '\r');
341 qstring_append_chr(mon->outbuf, c);
343 monitor_flush_locked(mon);
346 qemu_mutex_unlock(&mon->out_lock);
349 void monitor_vprintf(Monitor *mon, const char *fmt, va_list ap)
356 if (monitor_is_qmp(mon)) {
360 buf = g_strdup_vprintf(fmt, ap);
361 monitor_puts(mon, buf);
365 void monitor_printf(Monitor *mon, const char *fmt, ...)
369 monitor_vprintf(mon, fmt, ap);
373 int monitor_fprintf(FILE *stream, const char *fmt, ...)
377 monitor_vprintf((Monitor *)stream, fmt, ap);
382 static void monitor_json_emitter(Monitor *mon, const QObject *data)
386 json = mon->flags & MONITOR_USE_PRETTY ? qobject_to_json_pretty(data) :
387 qobject_to_json(data);
388 assert(json != NULL);
390 qstring_append_chr(json, '\n');
391 monitor_puts(mon, qstring_get_str(json));
396 static MonitorQAPIEventConf monitor_qapi_event_conf[QAPI_EVENT__MAX] = {
397 /* Limit guest-triggerable events to 1 per second */
398 [QAPI_EVENT_RTC_CHANGE] = { 1000 * SCALE_MS },
399 [QAPI_EVENT_WATCHDOG] = { 1000 * SCALE_MS },
400 [QAPI_EVENT_BALLOON_CHANGE] = { 1000 * SCALE_MS },
401 [QAPI_EVENT_QUORUM_REPORT_BAD] = { 1000 * SCALE_MS },
402 [QAPI_EVENT_QUORUM_FAILURE] = { 1000 * SCALE_MS },
403 [QAPI_EVENT_VSERPORT_CHANGE] = { 1000 * SCALE_MS },
406 GHashTable *monitor_qapi_event_state;
409 * Emits the event to every monitor instance, @event is only used for trace
410 * Called with monitor_lock held.
412 static void monitor_qapi_event_emit(QAPIEvent event, QDict *qdict)
416 trace_monitor_protocol_event_emit(event, qdict);
417 QLIST_FOREACH(mon, &mon_list, entry) {
418 if (monitor_is_qmp(mon)
419 && mon->qmp.commands != &qmp_cap_negotiation_commands) {
420 monitor_json_emitter(mon, QOBJECT(qdict));
425 static void monitor_qapi_event_handler(void *opaque);
428 * Queue a new event for emission to Monitor instances,
429 * applying any rate limiting if required.
432 monitor_qapi_event_queue(QAPIEvent event, QDict *qdict, Error **errp)
434 MonitorQAPIEventConf *evconf;
435 MonitorQAPIEventState *evstate;
437 assert(event < QAPI_EVENT__MAX);
438 evconf = &monitor_qapi_event_conf[event];
439 trace_monitor_protocol_event_queue(event, qdict, evconf->rate);
441 qemu_mutex_lock(&monitor_lock);
444 /* Unthrottled event */
445 monitor_qapi_event_emit(event, qdict);
447 QDict *data = qobject_to_qdict(qdict_get(qdict, "data"));
448 MonitorQAPIEventState key = { .event = event, .data = data };
450 evstate = g_hash_table_lookup(monitor_qapi_event_state, &key);
451 assert(!evstate || timer_pending(evstate->timer));
455 * Timer is pending for (at least) evconf->rate ns after
456 * last send. Store event for sending when timer fires,
457 * replacing a prior stored event if any.
459 QDECREF(evstate->qdict);
460 evstate->qdict = qdict;
461 QINCREF(evstate->qdict);
464 * Last send was (at least) evconf->rate ns ago.
465 * Send immediately, and arm the timer to call
466 * monitor_qapi_event_handler() in evconf->rate ns. Any
467 * events arriving before then will be delayed until then.
469 int64_t now = qemu_clock_get_ns(event_clock_type);
471 monitor_qapi_event_emit(event, qdict);
473 evstate = g_new(MonitorQAPIEventState, 1);
474 evstate->event = event;
475 evstate->data = data;
476 QINCREF(evstate->data);
477 evstate->qdict = NULL;
478 evstate->timer = timer_new_ns(event_clock_type,
479 monitor_qapi_event_handler,
481 g_hash_table_add(monitor_qapi_event_state, evstate);
482 timer_mod_ns(evstate->timer, now + evconf->rate);
486 qemu_mutex_unlock(&monitor_lock);
490 * This function runs evconf->rate ns after sending a throttled
492 * If another event has since been stored, send it.
494 static void monitor_qapi_event_handler(void *opaque)
496 MonitorQAPIEventState *evstate = opaque;
497 MonitorQAPIEventConf *evconf = &monitor_qapi_event_conf[evstate->event];
499 trace_monitor_protocol_event_handler(evstate->event, evstate->qdict);
500 qemu_mutex_lock(&monitor_lock);
502 if (evstate->qdict) {
503 int64_t now = qemu_clock_get_ns(event_clock_type);
505 monitor_qapi_event_emit(evstate->event, evstate->qdict);
506 QDECREF(evstate->qdict);
507 evstate->qdict = NULL;
508 timer_mod_ns(evstate->timer, now + evconf->rate);
510 g_hash_table_remove(monitor_qapi_event_state, evstate);
511 QDECREF(evstate->data);
512 timer_free(evstate->timer);
516 qemu_mutex_unlock(&monitor_lock);
519 static unsigned int qapi_event_throttle_hash(const void *key)
521 const MonitorQAPIEventState *evstate = key;
522 unsigned int hash = evstate->event * 255;
524 if (evstate->event == QAPI_EVENT_VSERPORT_CHANGE) {
525 hash += g_str_hash(qdict_get_str(evstate->data, "id"));
528 if (evstate->event == QAPI_EVENT_QUORUM_REPORT_BAD) {
529 hash += g_str_hash(qdict_get_str(evstate->data, "node-name"));
535 static gboolean qapi_event_throttle_equal(const void *a, const void *b)
537 const MonitorQAPIEventState *eva = a;
538 const MonitorQAPIEventState *evb = b;
540 if (eva->event != evb->event) {
544 if (eva->event == QAPI_EVENT_VSERPORT_CHANGE) {
545 return !strcmp(qdict_get_str(eva->data, "id"),
546 qdict_get_str(evb->data, "id"));
549 if (eva->event == QAPI_EVENT_QUORUM_REPORT_BAD) {
550 return !strcmp(qdict_get_str(eva->data, "node-name"),
551 qdict_get_str(evb->data, "node-name"));
557 static void monitor_qapi_event_init(void)
559 if (qtest_enabled()) {
560 event_clock_type = QEMU_CLOCK_VIRTUAL;
563 monitor_qapi_event_state = g_hash_table_new(qapi_event_throttle_hash,
564 qapi_event_throttle_equal);
565 qmp_event_set_func_emit(monitor_qapi_event_queue);
568 static void handle_hmp_command(Monitor *mon, const char *cmdline);
570 static void monitor_data_init(Monitor *mon)
572 memset(mon, 0, sizeof(Monitor));
573 qemu_mutex_init(&mon->out_lock);
574 mon->outbuf = qstring_new();
575 /* Use *mon_cmds by default. */
576 mon->cmd_table = mon_cmds;
579 static void monitor_data_destroy(Monitor *mon)
581 g_free(mon->mon_cpu_path);
582 qemu_chr_fe_deinit(&mon->chr, false);
583 if (monitor_is_qmp(mon)) {
584 json_message_parser_destroy(&mon->qmp.parser);
587 QDECREF(mon->outbuf);
588 qemu_mutex_destroy(&mon->out_lock);
591 char *qmp_human_monitor_command(const char *command_line, bool has_cpu_index,
592 int64_t cpu_index, Error **errp)
595 Monitor *old_mon, hmp;
597 monitor_data_init(&hmp);
598 hmp.skip_flush = true;
604 int ret = monitor_set_cpu(cpu_index);
607 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cpu-index",
613 handle_hmp_command(&hmp, command_line);
616 qemu_mutex_lock(&hmp.out_lock);
617 if (qstring_get_length(hmp.outbuf) > 0) {
618 output = g_strdup(qstring_get_str(hmp.outbuf));
620 output = g_strdup("");
622 qemu_mutex_unlock(&hmp.out_lock);
625 monitor_data_destroy(&hmp);
629 static int compare_cmd(const char *name, const char *list)
631 const char *p, *pstart;
639 p = pstart + strlen(pstart);
640 if ((p - pstart) == len && !memcmp(pstart, name, len))
649 static int get_str(char *buf, int buf_size, const char **pp)
657 while (qemu_isspace(*p)) {
668 while (*p != '\0' && *p != '\"') {
684 printf("unsupported escape code: '\\%c'\n", c);
687 if ((q - buf) < buf_size - 1) {
691 if ((q - buf) < buf_size - 1) {
698 printf("unterminated string\n");
703 while (*p != '\0' && !qemu_isspace(*p)) {
704 if ((q - buf) < buf_size - 1) {
717 static void free_cmdline_args(char **args, int nb_args)
721 assert(nb_args <= MAX_ARGS);
723 for (i = 0; i < nb_args; i++) {
730 * Parse the command line to get valid args.
731 * @cmdline: command line to be parsed.
732 * @pnb_args: location to store the number of args, must NOT be NULL.
733 * @args: location to store the args, which should be freed by caller, must
736 * Returns 0 on success, negative on failure.
738 * NOTE: this parser is an approximate form of the real command parser. Number
739 * of args have a limit of MAX_ARGS. If cmdline contains more, it will
740 * return with failure.
742 static int parse_cmdline(const char *cmdline,
743 int *pnb_args, char **args)
752 while (qemu_isspace(*p)) {
758 if (nb_args >= MAX_ARGS) {
761 ret = get_str(buf, sizeof(buf), &p);
765 args[nb_args] = g_strdup(buf);
772 free_cmdline_args(args, nb_args);
776 static void help_cmd_dump_one(Monitor *mon,
777 const mon_cmd_t *cmd,
783 for (i = 0; i < prefix_args_nb; i++) {
784 monitor_printf(mon, "%s ", prefix_args[i]);
786 monitor_printf(mon, "%s %s -- %s\n", cmd->name, cmd->params, cmd->help);
789 /* @args[@arg_index] is the valid command need to find in @cmds */
790 static void help_cmd_dump(Monitor *mon, const mon_cmd_t *cmds,
791 char **args, int nb_args, int arg_index)
793 const mon_cmd_t *cmd;
795 /* No valid arg need to compare with, dump all in *cmds */
796 if (arg_index >= nb_args) {
797 for (cmd = cmds; cmd->name != NULL; cmd++) {
798 help_cmd_dump_one(mon, cmd, args, arg_index);
803 /* Find one entry to dump */
804 for (cmd = cmds; cmd->name != NULL; cmd++) {
805 if (compare_cmd(args[arg_index], cmd->name)) {
806 if (cmd->sub_table) {
807 /* continue with next arg */
808 help_cmd_dump(mon, cmd->sub_table,
809 args, nb_args, arg_index + 1);
811 help_cmd_dump_one(mon, cmd, args, arg_index);
818 static void help_cmd(Monitor *mon, const char *name)
820 char *args[MAX_ARGS];
823 /* 1. parse user input */
825 /* special case for log, directly dump and return */
826 if (!strcmp(name, "log")) {
827 const QEMULogItem *item;
828 monitor_printf(mon, "Log items (comma separated):\n");
829 monitor_printf(mon, "%-10s %s\n", "none", "remove all logs");
830 for (item = qemu_log_items; item->mask != 0; item++) {
831 monitor_printf(mon, "%-10s %s\n", item->name, item->help);
836 if (parse_cmdline(name, &nb_args, args) < 0) {
841 /* 2. dump the contents according to parsed args */
842 help_cmd_dump(mon, mon->cmd_table, args, nb_args, 0);
844 free_cmdline_args(args, nb_args);
847 static void do_help_cmd(Monitor *mon, const QDict *qdict)
849 help_cmd(mon, qdict_get_try_str(qdict, "name"));
852 static void hmp_trace_event(Monitor *mon, const QDict *qdict)
854 const char *tp_name = qdict_get_str(qdict, "name");
855 bool new_state = qdict_get_bool(qdict, "option");
856 bool has_vcpu = qdict_haskey(qdict, "vcpu");
857 int vcpu = qdict_get_try_int(qdict, "vcpu", 0);
858 Error *local_err = NULL;
861 monitor_printf(mon, "argument vcpu must be positive");
865 qmp_trace_event_set_state(tp_name, new_state, true, true, has_vcpu, vcpu, &local_err);
867 error_report_err(local_err);
871 #ifdef CONFIG_TRACE_SIMPLE
872 static void hmp_trace_file(Monitor *mon, const QDict *qdict)
874 const char *op = qdict_get_try_str(qdict, "op");
875 const char *arg = qdict_get_try_str(qdict, "arg");
878 st_print_trace_file_status((FILE *)mon, &monitor_fprintf);
879 } else if (!strcmp(op, "on")) {
880 st_set_trace_file_enabled(true);
881 } else if (!strcmp(op, "off")) {
882 st_set_trace_file_enabled(false);
883 } else if (!strcmp(op, "flush")) {
884 st_flush_trace_buffer();
885 } else if (!strcmp(op, "set")) {
887 st_set_trace_file(arg);
890 monitor_printf(mon, "unexpected argument \"%s\"\n", op);
891 help_cmd(mon, "trace-file");
896 static void hmp_info_help(Monitor *mon, const QDict *qdict)
898 help_cmd(mon, "info");
901 static void query_commands_cb(QmpCommand *cmd, void *opaque)
903 CommandInfoList *info, **list = opaque;
909 info = g_malloc0(sizeof(*info));
910 info->value = g_malloc0(sizeof(*info->value));
911 info->value->name = g_strdup(cmd->name);
916 CommandInfoList *qmp_query_commands(Error **errp)
918 CommandInfoList *list = NULL;
920 qmp_for_each_command(cur_mon->qmp.commands, query_commands_cb, &list);
925 EventInfoList *qmp_query_events(Error **errp)
927 EventInfoList *info, *ev_list = NULL;
930 for (e = 0 ; e < QAPI_EVENT__MAX ; e++) {
931 const char *event_name = QAPIEvent_str(e);
932 assert(event_name != NULL);
933 info = g_malloc0(sizeof(*info));
934 info->value = g_malloc0(sizeof(*info->value));
935 info->value->name = g_strdup(event_name);
937 info->next = ev_list;
945 * Minor hack: generated marshalling suppressed for this command
946 * ('gen': false in the schema) so we can parse the JSON string
947 * directly into QObject instead of first parsing it with
948 * visit_type_SchemaInfoList() into a SchemaInfoList, then marshal it
949 * to QObject with generated output marshallers, every time. Instead,
950 * we do it in test-qobject-input-visitor.c, just to make sure
951 * qapi-introspect.py's output actually conforms to the schema.
953 static void qmp_query_qmp_schema(QDict *qdict, QObject **ret_data,
956 *ret_data = qobject_from_json(qmp_schema_json, &error_abort);
960 * We used to define commands in qmp-commands.hx in addition to the
961 * QAPI schema. This permitted defining some of them only in certain
962 * configurations. query-commands has always reflected that (good,
963 * because it lets QMP clients figure out what's actually available),
964 * while query-qmp-schema never did (not so good). This function is a
965 * hack to keep the configuration-specific commands defined exactly as
966 * before, even though qmp-commands.hx is gone.
968 * FIXME Educate the QAPI schema on configuration-specific commands,
969 * and drop this hack.
971 static void qmp_unregister_commands_hack(void)
974 qmp_unregister_command(&qmp_commands, "query-spice");
976 #ifndef CONFIG_REPLICATION
977 qmp_unregister_command(&qmp_commands, "xen-set-replication");
978 qmp_unregister_command(&qmp_commands, "query-xen-replication-status");
979 qmp_unregister_command(&qmp_commands, "xen-colo-do-checkpoint");
982 qmp_unregister_command(&qmp_commands, "rtc-reset-reinjection");
985 qmp_unregister_command(&qmp_commands, "dump-skeys");
988 qmp_unregister_command(&qmp_commands, "query-gic-capabilities");
990 #if !defined(TARGET_S390X) && !defined(TARGET_I386)
991 qmp_unregister_command(&qmp_commands, "query-cpu-model-expansion");
993 #if !defined(TARGET_S390X)
994 qmp_unregister_command(&qmp_commands, "query-cpu-model-baseline");
995 qmp_unregister_command(&qmp_commands, "query-cpu-model-comparison");
997 #if !defined(TARGET_PPC) && !defined(TARGET_ARM) && !defined(TARGET_I386) \
998 && !defined(TARGET_S390X)
999 qmp_unregister_command(&qmp_commands, "query-cpu-definitions");
1003 void monitor_init_qmp_commands(void)
1006 * Two command lists:
1007 * - qmp_commands contains all QMP commands
1008 * - qmp_cap_negotiation_commands contains just
1009 * "qmp_capabilities", to enforce capability negotiation
1012 qmp_init_marshal(&qmp_commands);
1014 qmp_register_command(&qmp_commands, "query-qmp-schema",
1015 qmp_query_qmp_schema,
1017 qmp_register_command(&qmp_commands, "device_add", qmp_device_add,
1019 qmp_register_command(&qmp_commands, "netdev_add", qmp_netdev_add,
1022 qmp_unregister_commands_hack();
1024 QTAILQ_INIT(&qmp_cap_negotiation_commands);
1025 qmp_register_command(&qmp_cap_negotiation_commands, "qmp_capabilities",
1026 qmp_marshal_qmp_capabilities, QCO_NO_OPTIONS);
1029 void qmp_qmp_capabilities(Error **errp)
1031 if (cur_mon->qmp.commands == &qmp_commands) {
1032 error_set(errp, ERROR_CLASS_COMMAND_NOT_FOUND,
1033 "Capabilities negotiation is already complete, command "
1038 cur_mon->qmp.commands = &qmp_commands;
1041 /* set the current CPU defined by the user */
1042 int monitor_set_cpu(int cpu_index)
1046 cpu = qemu_get_cpu(cpu_index);
1050 g_free(cur_mon->mon_cpu_path);
1051 cur_mon->mon_cpu_path = object_get_canonical_path(OBJECT(cpu));
1055 CPUState *mon_get_cpu(void)
1059 if (cur_mon->mon_cpu_path) {
1060 cpu = (CPUState *) object_resolve_path_type(cur_mon->mon_cpu_path,
1063 g_free(cur_mon->mon_cpu_path);
1064 cur_mon->mon_cpu_path = NULL;
1067 if (!cur_mon->mon_cpu_path) {
1071 monitor_set_cpu(first_cpu->cpu_index);
1074 cpu_synchronize_state(cpu);
1078 CPUArchState *mon_get_cpu_env(void)
1080 CPUState *cs = mon_get_cpu();
1082 return cs ? cs->env_ptr : NULL;
1085 int monitor_get_cpu_index(void)
1087 CPUState *cs = mon_get_cpu();
1089 return cs ? cs->cpu_index : UNASSIGNED_CPU_INDEX;
1092 static void hmp_info_registers(Monitor *mon, const QDict *qdict)
1094 bool all_cpus = qdict_get_try_bool(qdict, "cpustate_all", false);
1099 monitor_printf(mon, "\nCPU#%d\n", cs->cpu_index);
1100 cpu_dump_state(cs, (FILE *)mon, monitor_fprintf, CPU_DUMP_FPU);
1106 monitor_printf(mon, "No CPU available\n");
1110 cpu_dump_state(cs, (FILE *)mon, monitor_fprintf, CPU_DUMP_FPU);
1115 static void hmp_info_jit(Monitor *mon, const QDict *qdict)
1117 if (!tcg_enabled()) {
1118 error_report("JIT information is only available with accel=tcg");
1122 dump_exec_info((FILE *)mon, monitor_fprintf);
1123 dump_drift_info((FILE *)mon, monitor_fprintf);
1126 static void hmp_info_opcount(Monitor *mon, const QDict *qdict)
1128 dump_opcount_info((FILE *)mon, monitor_fprintf);
1132 static void hmp_info_history(Monitor *mon, const QDict *qdict)
1141 str = readline_get_history(mon->rs, i);
1144 monitor_printf(mon, "%d: '%s'\n", i, str);
1149 static void hmp_info_cpustats(Monitor *mon, const QDict *qdict)
1151 CPUState *cs = mon_get_cpu();
1154 monitor_printf(mon, "No CPU available\n");
1157 cpu_dump_statistics(cs, (FILE *)mon, &monitor_fprintf, 0);
1160 static void hmp_info_trace_events(Monitor *mon, const QDict *qdict)
1162 const char *name = qdict_get_try_str(qdict, "name");
1163 bool has_vcpu = qdict_haskey(qdict, "vcpu");
1164 int vcpu = qdict_get_try_int(qdict, "vcpu", 0);
1165 TraceEventInfoList *events;
1166 TraceEventInfoList *elem;
1167 Error *local_err = NULL;
1173 monitor_printf(mon, "argument vcpu must be positive");
1177 events = qmp_trace_event_get_state(name, has_vcpu, vcpu, &local_err);
1179 error_report_err(local_err);
1183 for (elem = events; elem != NULL; elem = elem->next) {
1184 monitor_printf(mon, "%s : state %u\n",
1186 elem->value->state == TRACE_EVENT_STATE_ENABLED ? 1 : 0);
1188 qapi_free_TraceEventInfoList(events);
1191 void qmp_client_migrate_info(const char *protocol, const char *hostname,
1192 bool has_port, int64_t port,
1193 bool has_tls_port, int64_t tls_port,
1194 bool has_cert_subject, const char *cert_subject,
1197 if (strcmp(protocol, "spice") == 0) {
1198 if (!qemu_using_spice(errp)) {
1202 if (!has_port && !has_tls_port) {
1203 error_setg(errp, QERR_MISSING_PARAMETER, "port/tls-port");
1207 if (qemu_spice_migrate_info(hostname,
1208 has_port ? port : -1,
1209 has_tls_port ? tls_port : -1,
1211 error_setg(errp, QERR_UNDEFINED_ERROR);
1217 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "protocol", "spice");
1220 static void hmp_logfile(Monitor *mon, const QDict *qdict)
1224 qemu_set_log_filename(qdict_get_str(qdict, "filename"), &err);
1226 error_report_err(err);
1230 static void hmp_log(Monitor *mon, const QDict *qdict)
1233 const char *items = qdict_get_str(qdict, "items");
1235 if (!strcmp(items, "none")) {
1238 mask = qemu_str_to_log_mask(items);
1240 help_cmd(mon, "log");
1247 static void hmp_singlestep(Monitor *mon, const QDict *qdict)
1249 const char *option = qdict_get_try_str(qdict, "option");
1250 if (!option || !strcmp(option, "on")) {
1252 } else if (!strcmp(option, "off")) {
1255 monitor_printf(mon, "unexpected option %s\n", option);
1259 static void hmp_gdbserver(Monitor *mon, const QDict *qdict)
1261 const char *device = qdict_get_try_str(qdict, "device");
1263 device = "tcp::" DEFAULT_GDBSTUB_PORT;
1264 if (gdbserver_start(device) < 0) {
1265 monitor_printf(mon, "Could not open gdbserver on device '%s'\n",
1267 } else if (strcmp(device, "none") == 0) {
1268 monitor_printf(mon, "Disabled gdbserver\n");
1270 monitor_printf(mon, "Waiting for gdb connection on device '%s'\n",
1275 static void hmp_watchdog_action(Monitor *mon, const QDict *qdict)
1277 const char *action = qdict_get_str(qdict, "action");
1278 if (select_watchdog_action(action) == -1) {
1279 monitor_printf(mon, "Unknown watchdog action '%s'\n", action);
1283 static void monitor_printc(Monitor *mon, int c)
1285 monitor_printf(mon, "'");
1288 monitor_printf(mon, "\\'");
1291 monitor_printf(mon, "\\\\");
1294 monitor_printf(mon, "\\n");
1297 monitor_printf(mon, "\\r");
1300 if (c >= 32 && c <= 126) {
1301 monitor_printf(mon, "%c", c);
1303 monitor_printf(mon, "\\x%02x", c);
1307 monitor_printf(mon, "'");
1310 static void memory_dump(Monitor *mon, int count, int format, int wsize,
1311 hwaddr addr, int is_physical)
1313 int l, line_size, i, max_digits, len;
1316 CPUState *cs = mon_get_cpu();
1318 if (!cs && (format == 'i' || !is_physical)) {
1319 monitor_printf(mon, "Can not dump without CPU\n");
1323 if (format == 'i') {
1324 monitor_disas(mon, cs, addr, count, is_physical);
1328 len = wsize * count;
1337 max_digits = DIV_ROUND_UP(wsize * 8, 3);
1341 max_digits = (wsize * 8) / 4;
1345 max_digits = DIV_ROUND_UP(wsize * 8 * 10, 33);
1354 monitor_printf(mon, TARGET_FMT_plx ":", addr);
1356 monitor_printf(mon, TARGET_FMT_lx ":", (target_ulong)addr);
1361 cpu_physical_memory_read(addr, buf, l);
1363 if (cpu_memory_rw_debug(cs, addr, buf, l, 0) < 0) {
1364 monitor_printf(mon, " Cannot access memory\n");
1373 v = ldub_p(buf + i);
1376 v = lduw_p(buf + i);
1379 v = (uint32_t)ldl_p(buf + i);
1385 monitor_printf(mon, " ");
1388 monitor_printf(mon, "%#*" PRIo64, max_digits, v);
1391 monitor_printf(mon, "0x%0*" PRIx64, max_digits, v);
1394 monitor_printf(mon, "%*" PRIu64, max_digits, v);
1397 monitor_printf(mon, "%*" PRId64, max_digits, v);
1400 monitor_printc(mon, v);
1405 monitor_printf(mon, "\n");
1411 static void hmp_memory_dump(Monitor *mon, const QDict *qdict)
1413 int count = qdict_get_int(qdict, "count");
1414 int format = qdict_get_int(qdict, "format");
1415 int size = qdict_get_int(qdict, "size");
1416 target_long addr = qdict_get_int(qdict, "addr");
1418 memory_dump(mon, count, format, size, addr, 0);
1421 static void hmp_physical_memory_dump(Monitor *mon, const QDict *qdict)
1423 int count = qdict_get_int(qdict, "count");
1424 int format = qdict_get_int(qdict, "format");
1425 int size = qdict_get_int(qdict, "size");
1426 hwaddr addr = qdict_get_int(qdict, "addr");
1428 memory_dump(mon, count, format, size, addr, 1);
1431 static void *gpa2hva(MemoryRegion **p_mr, hwaddr addr, Error **errp)
1433 MemoryRegionSection mrs = memory_region_find(get_system_memory(),
1437 error_setg(errp, "No memory is mapped at address 0x%" HWADDR_PRIx, addr);
1441 if (!memory_region_is_ram(mrs.mr) && !memory_region_is_romd(mrs.mr)) {
1442 error_setg(errp, "Memory at address 0x%" HWADDR_PRIx "is not RAM", addr);
1443 memory_region_unref(mrs.mr);
1448 return qemu_map_ram_ptr(mrs.mr->ram_block, mrs.offset_within_region);
1451 static void hmp_gpa2hva(Monitor *mon, const QDict *qdict)
1453 hwaddr addr = qdict_get_int(qdict, "addr");
1454 Error *local_err = NULL;
1455 MemoryRegion *mr = NULL;
1458 ptr = gpa2hva(&mr, addr, &local_err);
1460 error_report_err(local_err);
1464 monitor_printf(mon, "Host virtual address for 0x%" HWADDR_PRIx
1466 addr, mr->name, ptr);
1468 memory_region_unref(mr);
1472 static uint64_t vtop(void *ptr, Error **errp)
1476 uintptr_t addr = (uintptr_t) ptr;
1477 uintptr_t pagesize = getpagesize();
1478 off_t offset = addr / pagesize * sizeof(pinfo);
1481 fd = open("/proc/self/pagemap", O_RDONLY);
1483 error_setg_errno(errp, errno, "Cannot open /proc/self/pagemap");
1487 /* Force copy-on-write if necessary. */
1488 atomic_add((uint8_t *)ptr, 0);
1490 if (pread(fd, &pinfo, sizeof(pinfo), offset) != sizeof(pinfo)) {
1491 error_setg_errno(errp, errno, "Cannot read pagemap");
1494 if ((pinfo & (1ull << 63)) == 0) {
1495 error_setg(errp, "Page not present");
1498 ret = ((pinfo & 0x007fffffffffffffull) * pagesize) | (addr & (pagesize - 1));
1505 static void hmp_gpa2hpa(Monitor *mon, const QDict *qdict)
1507 hwaddr addr = qdict_get_int(qdict, "addr");
1508 Error *local_err = NULL;
1509 MemoryRegion *mr = NULL;
1513 ptr = gpa2hva(&mr, addr, &local_err);
1515 error_report_err(local_err);
1519 physaddr = vtop(ptr, &local_err);
1521 error_report_err(local_err);
1523 monitor_printf(mon, "Host physical address for 0x%" HWADDR_PRIx
1524 " (%s) is 0x%" PRIx64 "\n",
1525 addr, mr->name, (uint64_t) physaddr);
1528 memory_region_unref(mr);
1532 static void do_print(Monitor *mon, const QDict *qdict)
1534 int format = qdict_get_int(qdict, "format");
1535 hwaddr val = qdict_get_int(qdict, "val");
1539 monitor_printf(mon, "%#" HWADDR_PRIo, val);
1542 monitor_printf(mon, "%#" HWADDR_PRIx, val);
1545 monitor_printf(mon, "%" HWADDR_PRIu, val);
1549 monitor_printf(mon, "%" HWADDR_PRId, val);
1552 monitor_printc(mon, val);
1555 monitor_printf(mon, "\n");
1558 static void hmp_sum(Monitor *mon, const QDict *qdict)
1562 uint32_t start = qdict_get_int(qdict, "start");
1563 uint32_t size = qdict_get_int(qdict, "size");
1566 for(addr = start; addr < (start + size); addr++) {
1567 uint8_t val = address_space_ldub(&address_space_memory, addr,
1568 MEMTXATTRS_UNSPECIFIED, NULL);
1569 /* BSD sum algorithm ('sum' Unix command) */
1570 sum = (sum >> 1) | (sum << 15);
1573 monitor_printf(mon, "%05d\n", sum);
1576 static int mouse_button_state;
1578 static void hmp_mouse_move(Monitor *mon, const QDict *qdict)
1580 int dx, dy, dz, button;
1581 const char *dx_str = qdict_get_str(qdict, "dx_str");
1582 const char *dy_str = qdict_get_str(qdict, "dy_str");
1583 const char *dz_str = qdict_get_try_str(qdict, "dz_str");
1585 dx = strtol(dx_str, NULL, 0);
1586 dy = strtol(dy_str, NULL, 0);
1587 qemu_input_queue_rel(NULL, INPUT_AXIS_X, dx);
1588 qemu_input_queue_rel(NULL, INPUT_AXIS_Y, dy);
1591 dz = strtol(dz_str, NULL, 0);
1593 button = (dz > 0) ? INPUT_BUTTON_WHEEL_UP : INPUT_BUTTON_WHEEL_DOWN;
1594 qemu_input_queue_btn(NULL, button, true);
1595 qemu_input_event_sync();
1596 qemu_input_queue_btn(NULL, button, false);
1599 qemu_input_event_sync();
1602 static void hmp_mouse_button(Monitor *mon, const QDict *qdict)
1604 static uint32_t bmap[INPUT_BUTTON__MAX] = {
1605 [INPUT_BUTTON_LEFT] = MOUSE_EVENT_LBUTTON,
1606 [INPUT_BUTTON_MIDDLE] = MOUSE_EVENT_MBUTTON,
1607 [INPUT_BUTTON_RIGHT] = MOUSE_EVENT_RBUTTON,
1609 int button_state = qdict_get_int(qdict, "button_state");
1611 if (mouse_button_state == button_state) {
1614 qemu_input_update_buttons(NULL, bmap, mouse_button_state, button_state);
1615 qemu_input_event_sync();
1616 mouse_button_state = button_state;
1619 static void hmp_ioport_read(Monitor *mon, const QDict *qdict)
1621 int size = qdict_get_int(qdict, "size");
1622 int addr = qdict_get_int(qdict, "addr");
1623 int has_index = qdict_haskey(qdict, "index");
1628 int index = qdict_get_int(qdict, "index");
1629 cpu_outb(addr & IOPORTS_MASK, index & 0xff);
1637 val = cpu_inb(addr);
1641 val = cpu_inw(addr);
1645 val = cpu_inl(addr);
1649 monitor_printf(mon, "port%c[0x%04x] = %#0*x\n",
1650 suffix, addr, size * 2, val);
1653 static void hmp_ioport_write(Monitor *mon, const QDict *qdict)
1655 int size = qdict_get_int(qdict, "size");
1656 int addr = qdict_get_int(qdict, "addr");
1657 int val = qdict_get_int(qdict, "val");
1659 addr &= IOPORTS_MASK;
1664 cpu_outb(addr, val);
1667 cpu_outw(addr, val);
1670 cpu_outl(addr, val);
1675 static void hmp_boot_set(Monitor *mon, const QDict *qdict)
1677 Error *local_err = NULL;
1678 const char *bootdevice = qdict_get_str(qdict, "bootdevice");
1680 qemu_boot_set(bootdevice, &local_err);
1682 error_report_err(local_err);
1684 monitor_printf(mon, "boot device list now set to %s\n", bootdevice);
1688 static void hmp_info_mtree(Monitor *mon, const QDict *qdict)
1690 bool flatview = qdict_get_try_bool(qdict, "flatview", false);
1691 bool dispatch_tree = qdict_get_try_bool(qdict, "dispatch_tree", false);
1693 mtree_info((fprintf_function)monitor_printf, mon, flatview, dispatch_tree);
1696 static void hmp_info_numa(Monitor *mon, const QDict *qdict)
1699 NumaNodeMem *node_mem;
1700 CpuInfoList *cpu_list, *cpu;
1702 cpu_list = qmp_query_cpus(&error_abort);
1703 node_mem = g_new0(NumaNodeMem, nb_numa_nodes);
1705 query_numa_node_mem(node_mem);
1706 monitor_printf(mon, "%d nodes\n", nb_numa_nodes);
1707 for (i = 0; i < nb_numa_nodes; i++) {
1708 monitor_printf(mon, "node %d cpus:", i);
1709 for (cpu = cpu_list; cpu; cpu = cpu->next) {
1710 if (cpu->value->has_props && cpu->value->props->has_node_id &&
1711 cpu->value->props->node_id == i) {
1712 monitor_printf(mon, " %" PRIi64, cpu->value->CPU);
1715 monitor_printf(mon, "\n");
1716 monitor_printf(mon, "node %d size: %" PRId64 " MB\n", i,
1717 node_mem[i].node_mem >> 20);
1718 monitor_printf(mon, "node %d plugged: %" PRId64 " MB\n", i,
1719 node_mem[i].node_plugged_mem >> 20);
1721 qapi_free_CpuInfoList(cpu_list);
1725 #ifdef CONFIG_PROFILER
1730 static void hmp_info_profile(Monitor *mon, const QDict *qdict)
1732 monitor_printf(mon, "async time %" PRId64 " (%0.3f)\n",
1733 dev_time, dev_time / (double)NANOSECONDS_PER_SECOND);
1734 monitor_printf(mon, "qemu time %" PRId64 " (%0.3f)\n",
1735 tcg_time, tcg_time / (double)NANOSECONDS_PER_SECOND);
1740 static void hmp_info_profile(Monitor *mon, const QDict *qdict)
1742 monitor_printf(mon, "Internal profiler not compiled\n");
1746 /* Capture support */
1747 static QLIST_HEAD (capture_list_head, CaptureState) capture_head;
1749 static void hmp_info_capture(Monitor *mon, const QDict *qdict)
1754 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
1755 monitor_printf(mon, "[%d]: ", i);
1756 s->ops.info (s->opaque);
1760 static void hmp_stopcapture(Monitor *mon, const QDict *qdict)
1763 int n = qdict_get_int(qdict, "n");
1766 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
1768 s->ops.destroy (s->opaque);
1769 QLIST_REMOVE (s, entries);
1776 static void hmp_wavcapture(Monitor *mon, const QDict *qdict)
1778 const char *path = qdict_get_str(qdict, "path");
1779 int has_freq = qdict_haskey(qdict, "freq");
1780 int freq = qdict_get_try_int(qdict, "freq", -1);
1781 int has_bits = qdict_haskey(qdict, "bits");
1782 int bits = qdict_get_try_int(qdict, "bits", -1);
1783 int has_channels = qdict_haskey(qdict, "nchannels");
1784 int nchannels = qdict_get_try_int(qdict, "nchannels", -1);
1787 s = g_malloc0 (sizeof (*s));
1789 freq = has_freq ? freq : 44100;
1790 bits = has_bits ? bits : 16;
1791 nchannels = has_channels ? nchannels : 2;
1793 if (wav_start_capture (s, path, freq, bits, nchannels)) {
1794 monitor_printf(mon, "Failed to add wave capture\n");
1798 QLIST_INSERT_HEAD (&capture_head, s, entries);
1801 static qemu_acl *find_acl(Monitor *mon, const char *name)
1803 qemu_acl *acl = qemu_acl_find(name);
1806 monitor_printf(mon, "acl: unknown list '%s'\n", name);
1811 static void hmp_acl_show(Monitor *mon, const QDict *qdict)
1813 const char *aclname = qdict_get_str(qdict, "aclname");
1814 qemu_acl *acl = find_acl(mon, aclname);
1815 qemu_acl_entry *entry;
1819 monitor_printf(mon, "policy: %s\n",
1820 acl->defaultDeny ? "deny" : "allow");
1821 QTAILQ_FOREACH(entry, &acl->entries, next) {
1823 monitor_printf(mon, "%d: %s %s\n", i,
1824 entry->deny ? "deny" : "allow", entry->match);
1829 static void hmp_acl_reset(Monitor *mon, const QDict *qdict)
1831 const char *aclname = qdict_get_str(qdict, "aclname");
1832 qemu_acl *acl = find_acl(mon, aclname);
1835 qemu_acl_reset(acl);
1836 monitor_printf(mon, "acl: removed all rules\n");
1840 static void hmp_acl_policy(Monitor *mon, const QDict *qdict)
1842 const char *aclname = qdict_get_str(qdict, "aclname");
1843 const char *policy = qdict_get_str(qdict, "policy");
1844 qemu_acl *acl = find_acl(mon, aclname);
1847 if (strcmp(policy, "allow") == 0) {
1848 acl->defaultDeny = 0;
1849 monitor_printf(mon, "acl: policy set to 'allow'\n");
1850 } else if (strcmp(policy, "deny") == 0) {
1851 acl->defaultDeny = 1;
1852 monitor_printf(mon, "acl: policy set to 'deny'\n");
1854 monitor_printf(mon, "acl: unknown policy '%s', "
1855 "expected 'deny' or 'allow'\n", policy);
1860 static void hmp_acl_add(Monitor *mon, const QDict *qdict)
1862 const char *aclname = qdict_get_str(qdict, "aclname");
1863 const char *match = qdict_get_str(qdict, "match");
1864 const char *policy = qdict_get_str(qdict, "policy");
1865 int has_index = qdict_haskey(qdict, "index");
1866 int index = qdict_get_try_int(qdict, "index", -1);
1867 qemu_acl *acl = find_acl(mon, aclname);
1871 if (strcmp(policy, "allow") == 0) {
1873 } else if (strcmp(policy, "deny") == 0) {
1876 monitor_printf(mon, "acl: unknown policy '%s', "
1877 "expected 'deny' or 'allow'\n", policy);
1881 ret = qemu_acl_insert(acl, deny, match, index);
1883 ret = qemu_acl_append(acl, deny, match);
1885 monitor_printf(mon, "acl: unable to add acl entry\n");
1887 monitor_printf(mon, "acl: added rule at position %d\n", ret);
1891 static void hmp_acl_remove(Monitor *mon, const QDict *qdict)
1893 const char *aclname = qdict_get_str(qdict, "aclname");
1894 const char *match = qdict_get_str(qdict, "match");
1895 qemu_acl *acl = find_acl(mon, aclname);
1899 ret = qemu_acl_remove(acl, match);
1901 monitor_printf(mon, "acl: no matching acl entry\n");
1903 monitor_printf(mon, "acl: removed rule at position %d\n", ret);
1907 void qmp_getfd(const char *fdname, Error **errp)
1912 fd = qemu_chr_fe_get_msgfd(&cur_mon->chr);
1914 error_setg(errp, QERR_FD_NOT_SUPPLIED);
1918 if (qemu_isdigit(fdname[0])) {
1920 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "fdname",
1921 "a name not starting with a digit");
1925 QLIST_FOREACH(monfd, &cur_mon->fds, next) {
1926 if (strcmp(monfd->name, fdname) != 0) {
1935 monfd = g_malloc0(sizeof(mon_fd_t));
1936 monfd->name = g_strdup(fdname);
1939 QLIST_INSERT_HEAD(&cur_mon->fds, monfd, next);
1942 void qmp_closefd(const char *fdname, Error **errp)
1946 QLIST_FOREACH(monfd, &cur_mon->fds, next) {
1947 if (strcmp(monfd->name, fdname) != 0) {
1951 QLIST_REMOVE(monfd, next);
1953 g_free(monfd->name);
1958 error_setg(errp, QERR_FD_NOT_FOUND, fdname);
1961 int monitor_get_fd(Monitor *mon, const char *fdname, Error **errp)
1965 QLIST_FOREACH(monfd, &mon->fds, next) {
1968 if (strcmp(monfd->name, fdname) != 0) {
1974 /* caller takes ownership of fd */
1975 QLIST_REMOVE(monfd, next);
1976 g_free(monfd->name);
1982 error_setg(errp, "File descriptor named '%s' has not been found", fdname);
1986 static void monitor_fdset_cleanup(MonFdset *mon_fdset)
1988 MonFdsetFd *mon_fdset_fd;
1989 MonFdsetFd *mon_fdset_fd_next;
1991 QLIST_FOREACH_SAFE(mon_fdset_fd, &mon_fdset->fds, next, mon_fdset_fd_next) {
1992 if ((mon_fdset_fd->removed ||
1993 (QLIST_EMPTY(&mon_fdset->dup_fds) && mon_refcount == 0)) &&
1994 runstate_is_running()) {
1995 close(mon_fdset_fd->fd);
1996 g_free(mon_fdset_fd->opaque);
1997 QLIST_REMOVE(mon_fdset_fd, next);
1998 g_free(mon_fdset_fd);
2002 if (QLIST_EMPTY(&mon_fdset->fds) && QLIST_EMPTY(&mon_fdset->dup_fds)) {
2003 QLIST_REMOVE(mon_fdset, next);
2008 static void monitor_fdsets_cleanup(void)
2010 MonFdset *mon_fdset;
2011 MonFdset *mon_fdset_next;
2013 QLIST_FOREACH_SAFE(mon_fdset, &mon_fdsets, next, mon_fdset_next) {
2014 monitor_fdset_cleanup(mon_fdset);
2018 AddfdInfo *qmp_add_fd(bool has_fdset_id, int64_t fdset_id, bool has_opaque,
2019 const char *opaque, Error **errp)
2022 Monitor *mon = cur_mon;
2025 fd = qemu_chr_fe_get_msgfd(&mon->chr);
2027 error_setg(errp, QERR_FD_NOT_SUPPLIED);
2031 fdinfo = monitor_fdset_add_fd(fd, has_fdset_id, fdset_id,
2032 has_opaque, opaque, errp);
2044 void qmp_remove_fd(int64_t fdset_id, bool has_fd, int64_t fd, Error **errp)
2046 MonFdset *mon_fdset;
2047 MonFdsetFd *mon_fdset_fd;
2050 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2051 if (mon_fdset->id != fdset_id) {
2054 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2056 if (mon_fdset_fd->fd != fd) {
2059 mon_fdset_fd->removed = true;
2062 mon_fdset_fd->removed = true;
2065 if (has_fd && !mon_fdset_fd) {
2068 monitor_fdset_cleanup(mon_fdset);
2074 snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64 ", fd:%" PRId64,
2077 snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64, fdset_id);
2079 error_setg(errp, QERR_FD_NOT_FOUND, fd_str);
2082 FdsetInfoList *qmp_query_fdsets(Error **errp)
2084 MonFdset *mon_fdset;
2085 MonFdsetFd *mon_fdset_fd;
2086 FdsetInfoList *fdset_list = NULL;
2088 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2089 FdsetInfoList *fdset_info = g_malloc0(sizeof(*fdset_info));
2090 FdsetFdInfoList *fdsetfd_list = NULL;
2092 fdset_info->value = g_malloc0(sizeof(*fdset_info->value));
2093 fdset_info->value->fdset_id = mon_fdset->id;
2095 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2096 FdsetFdInfoList *fdsetfd_info;
2098 fdsetfd_info = g_malloc0(sizeof(*fdsetfd_info));
2099 fdsetfd_info->value = g_malloc0(sizeof(*fdsetfd_info->value));
2100 fdsetfd_info->value->fd = mon_fdset_fd->fd;
2101 if (mon_fdset_fd->opaque) {
2102 fdsetfd_info->value->has_opaque = true;
2103 fdsetfd_info->value->opaque = g_strdup(mon_fdset_fd->opaque);
2105 fdsetfd_info->value->has_opaque = false;
2108 fdsetfd_info->next = fdsetfd_list;
2109 fdsetfd_list = fdsetfd_info;
2112 fdset_info->value->fds = fdsetfd_list;
2114 fdset_info->next = fdset_list;
2115 fdset_list = fdset_info;
2121 AddfdInfo *monitor_fdset_add_fd(int fd, bool has_fdset_id, int64_t fdset_id,
2122 bool has_opaque, const char *opaque,
2125 MonFdset *mon_fdset = NULL;
2126 MonFdsetFd *mon_fdset_fd;
2130 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2131 /* Break if match found or match impossible due to ordering by ID */
2132 if (fdset_id <= mon_fdset->id) {
2133 if (fdset_id < mon_fdset->id) {
2141 if (mon_fdset == NULL) {
2142 int64_t fdset_id_prev = -1;
2143 MonFdset *mon_fdset_cur = QLIST_FIRST(&mon_fdsets);
2147 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "fdset-id",
2148 "a non-negative value");
2151 /* Use specified fdset ID */
2152 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2153 mon_fdset_cur = mon_fdset;
2154 if (fdset_id < mon_fdset_cur->id) {
2159 /* Use first available fdset ID */
2160 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2161 mon_fdset_cur = mon_fdset;
2162 if (fdset_id_prev == mon_fdset_cur->id - 1) {
2163 fdset_id_prev = mon_fdset_cur->id;
2170 mon_fdset = g_malloc0(sizeof(*mon_fdset));
2172 mon_fdset->id = fdset_id;
2174 mon_fdset->id = fdset_id_prev + 1;
2177 /* The fdset list is ordered by fdset ID */
2178 if (!mon_fdset_cur) {
2179 QLIST_INSERT_HEAD(&mon_fdsets, mon_fdset, next);
2180 } else if (mon_fdset->id < mon_fdset_cur->id) {
2181 QLIST_INSERT_BEFORE(mon_fdset_cur, mon_fdset, next);
2183 QLIST_INSERT_AFTER(mon_fdset_cur, mon_fdset, next);
2187 mon_fdset_fd = g_malloc0(sizeof(*mon_fdset_fd));
2188 mon_fdset_fd->fd = fd;
2189 mon_fdset_fd->removed = false;
2191 mon_fdset_fd->opaque = g_strdup(opaque);
2193 QLIST_INSERT_HEAD(&mon_fdset->fds, mon_fdset_fd, next);
2195 fdinfo = g_malloc0(sizeof(*fdinfo));
2196 fdinfo->fdset_id = mon_fdset->id;
2197 fdinfo->fd = mon_fdset_fd->fd;
2202 int monitor_fdset_get_fd(int64_t fdset_id, int flags)
2205 MonFdset *mon_fdset;
2206 MonFdsetFd *mon_fdset_fd;
2209 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2210 if (mon_fdset->id != fdset_id) {
2213 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2214 mon_fd_flags = fcntl(mon_fdset_fd->fd, F_GETFL);
2215 if (mon_fd_flags == -1) {
2219 if ((flags & O_ACCMODE) == (mon_fd_flags & O_ACCMODE)) {
2220 return mon_fdset_fd->fd;
2232 int monitor_fdset_dup_fd_add(int64_t fdset_id, int dup_fd)
2234 MonFdset *mon_fdset;
2235 MonFdsetFd *mon_fdset_fd_dup;
2237 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2238 if (mon_fdset->id != fdset_id) {
2241 QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
2242 if (mon_fdset_fd_dup->fd == dup_fd) {
2246 mon_fdset_fd_dup = g_malloc0(sizeof(*mon_fdset_fd_dup));
2247 mon_fdset_fd_dup->fd = dup_fd;
2248 QLIST_INSERT_HEAD(&mon_fdset->dup_fds, mon_fdset_fd_dup, next);
2254 static int monitor_fdset_dup_fd_find_remove(int dup_fd, bool remove)
2256 MonFdset *mon_fdset;
2257 MonFdsetFd *mon_fdset_fd_dup;
2259 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2260 QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
2261 if (mon_fdset_fd_dup->fd == dup_fd) {
2263 QLIST_REMOVE(mon_fdset_fd_dup, next);
2264 if (QLIST_EMPTY(&mon_fdset->dup_fds)) {
2265 monitor_fdset_cleanup(mon_fdset);
2269 return mon_fdset->id;
2277 int monitor_fdset_dup_fd_find(int dup_fd)
2279 return monitor_fdset_dup_fd_find_remove(dup_fd, false);
2282 void monitor_fdset_dup_fd_remove(int dup_fd)
2284 monitor_fdset_dup_fd_find_remove(dup_fd, true);
2287 int monitor_fd_param(Monitor *mon, const char *fdname, Error **errp)
2290 Error *local_err = NULL;
2292 if (!qemu_isdigit(fdname[0]) && mon) {
2293 fd = monitor_get_fd(mon, fdname, &local_err);
2295 fd = qemu_parse_fd(fdname);
2297 error_setg(&local_err, "Invalid file descriptor number '%s'",
2302 error_propagate(errp, local_err);
2311 /* Please update hmp-commands.hx when adding or changing commands */
2312 static mon_cmd_t info_cmds[] = {
2313 #include "hmp-commands-info.h"
2317 /* mon_cmds and info_cmds would be sorted at runtime */
2318 static mon_cmd_t mon_cmds[] = {
2319 #include "hmp-commands.h"
2323 /*******************************************************************/
2325 static const char *pch;
2326 static sigjmp_buf expr_env;
2329 static void GCC_FMT_ATTR(2, 3) QEMU_NORETURN
2330 expr_error(Monitor *mon, const char *fmt, ...)
2334 monitor_vprintf(mon, fmt, ap);
2335 monitor_printf(mon, "\n");
2337 siglongjmp(expr_env, 1);
2340 /* return 0 if OK, -1 if not found */
2341 static int get_monitor_def(target_long *pval, const char *name)
2343 const MonitorDef *md = target_monitor_defs();
2344 CPUState *cs = mon_get_cpu();
2349 if (cs == NULL || md == NULL) {
2353 for(; md->name != NULL; md++) {
2354 if (compare_cmd(name, md->name)) {
2355 if (md->get_value) {
2356 *pval = md->get_value(md, md->offset);
2358 CPUArchState *env = mon_get_cpu_env();
2359 ptr = (uint8_t *)env + md->offset;
2362 *pval = *(int32_t *)ptr;
2365 *pval = *(target_long *)ptr;
2376 ret = target_get_monitor_def(cs, name, &tmp);
2378 *pval = (target_long) tmp;
2384 static void next(void)
2388 while (qemu_isspace(*pch))
2393 static int64_t expr_sum(Monitor *mon);
2395 static int64_t expr_unary(Monitor *mon)
2404 n = expr_unary(mon);
2408 n = -expr_unary(mon);
2412 n = ~expr_unary(mon);
2418 expr_error(mon, "')' expected");
2425 expr_error(mon, "character constant expected");
2429 expr_error(mon, "missing terminating \' character");
2439 while ((*pch >= 'a' && *pch <= 'z') ||
2440 (*pch >= 'A' && *pch <= 'Z') ||
2441 (*pch >= '0' && *pch <= '9') ||
2442 *pch == '_' || *pch == '.') {
2443 if ((q - buf) < sizeof(buf) - 1)
2447 while (qemu_isspace(*pch))
2450 ret = get_monitor_def(®, buf);
2452 expr_error(mon, "unknown register");
2457 expr_error(mon, "unexpected end of expression");
2462 n = strtoull(pch, &p, 0);
2463 if (errno == ERANGE) {
2464 expr_error(mon, "number too large");
2467 expr_error(mon, "invalid char '%c' in expression", *p);
2470 while (qemu_isspace(*pch))
2478 static int64_t expr_prod(Monitor *mon)
2483 val = expr_unary(mon);
2486 if (op != '*' && op != '/' && op != '%')
2489 val2 = expr_unary(mon);
2498 expr_error(mon, "division by zero");
2509 static int64_t expr_logic(Monitor *mon)
2514 val = expr_prod(mon);
2517 if (op != '&' && op != '|' && op != '^')
2520 val2 = expr_prod(mon);
2537 static int64_t expr_sum(Monitor *mon)
2542 val = expr_logic(mon);
2545 if (op != '+' && op != '-')
2548 val2 = expr_logic(mon);
2557 static int get_expr(Monitor *mon, int64_t *pval, const char **pp)
2560 if (sigsetjmp(expr_env, 0)) {
2564 while (qemu_isspace(*pch))
2566 *pval = expr_sum(mon);
2571 static int get_double(Monitor *mon, double *pval, const char **pp)
2573 const char *p = *pp;
2577 d = strtod(p, &tailp);
2579 monitor_printf(mon, "Number expected\n");
2582 if (d != d || d - d != 0) {
2583 /* NaN or infinity */
2584 monitor_printf(mon, "Bad number\n");
2593 * Store the command-name in cmdname, and return a pointer to
2594 * the remaining of the command string.
2596 static const char *get_command_name(const char *cmdline,
2597 char *cmdname, size_t nlen)
2600 const char *p, *pstart;
2603 while (qemu_isspace(*p))
2608 while (*p != '\0' && *p != '/' && !qemu_isspace(*p))
2613 memcpy(cmdname, pstart, len);
2614 cmdname[len] = '\0';
2619 * Read key of 'type' into 'key' and return the current
2622 static char *key_get_info(const char *type, char **key)
2630 p = strchr(type, ':');
2637 str = g_malloc(len + 1);
2638 memcpy(str, type, len);
2645 static int default_fmt_format = 'x';
2646 static int default_fmt_size = 4;
2648 static int is_valid_option(const char *c, const char *typestr)
2656 typestr = strstr(typestr, option);
2657 return (typestr != NULL);
2660 static const mon_cmd_t *search_dispatch_table(const mon_cmd_t *disp_table,
2661 const char *cmdname)
2663 const mon_cmd_t *cmd;
2665 for (cmd = disp_table; cmd->name != NULL; cmd++) {
2666 if (compare_cmd(cmdname, cmd->name)) {
2675 * Parse command name from @cmdp according to command table @table.
2676 * If blank, return NULL.
2677 * Else, if no valid command can be found, report to @mon, and return
2679 * Else, change @cmdp to point right behind the name, and return its
2680 * command table entry.
2681 * Do not assume the return value points into @table! It doesn't when
2682 * the command is found in a sub-command table.
2684 static const mon_cmd_t *monitor_parse_command(Monitor *mon,
2685 const char *cmdp_start,
2690 const mon_cmd_t *cmd;
2693 /* extract the command name */
2694 p = get_command_name(*cmdp, cmdname, sizeof(cmdname));
2698 cmd = search_dispatch_table(table, cmdname);
2700 monitor_printf(mon, "unknown command: '%.*s'\n",
2701 (int)(p - cmdp_start), cmdp_start);
2705 /* filter out following useless space */
2706 while (qemu_isspace(*p)) {
2711 /* search sub command */
2712 if (cmd->sub_table != NULL && *p != '\0') {
2713 return monitor_parse_command(mon, cmdp_start, cmdp, cmd->sub_table);
2720 * Parse arguments for @cmd.
2721 * If it can't be parsed, report to @mon, and return NULL.
2722 * Else, insert command arguments into a QDict, and return it.
2723 * Note: On success, caller has to free the QDict structure.
2726 static QDict *monitor_parse_arguments(Monitor *mon,
2728 const mon_cmd_t *cmd)
2730 const char *typestr;
2733 const char *p = *endp;
2735 QDict *qdict = qdict_new();
2737 /* parse the parameters */
2738 typestr = cmd->args_type;
2740 typestr = key_get_info(typestr, &key);
2752 while (qemu_isspace(*p))
2754 if (*typestr == '?') {
2757 /* no optional string: NULL argument */
2761 ret = get_str(buf, sizeof(buf), &p);
2765 monitor_printf(mon, "%s: filename expected\n",
2769 monitor_printf(mon, "%s: block device name expected\n",
2773 monitor_printf(mon, "%s: string expected\n", cmd->name);
2778 qdict_put_str(qdict, key, buf);
2783 QemuOptsList *opts_list;
2786 opts_list = qemu_find_opts(key);
2787 if (!opts_list || opts_list->desc->name) {
2790 while (qemu_isspace(*p)) {
2795 if (get_str(buf, sizeof(buf), &p) < 0) {
2798 opts = qemu_opts_parse_noisily(opts_list, buf, true);
2802 qemu_opts_to_qdict(opts, qdict);
2803 qemu_opts_del(opts);
2808 int count, format, size;
2810 while (qemu_isspace(*p))
2816 if (qemu_isdigit(*p)) {
2818 while (qemu_isdigit(*p)) {
2819 count = count * 10 + (*p - '0');
2857 if (*p != '\0' && !qemu_isspace(*p)) {
2858 monitor_printf(mon, "invalid char in format: '%c'\n",
2863 format = default_fmt_format;
2864 if (format != 'i') {
2865 /* for 'i', not specifying a size gives -1 as size */
2867 size = default_fmt_size;
2868 default_fmt_size = size;
2870 default_fmt_format = format;
2873 format = default_fmt_format;
2874 if (format != 'i') {
2875 size = default_fmt_size;
2880 qdict_put_int(qdict, "count", count);
2881 qdict_put_int(qdict, "format", format);
2882 qdict_put_int(qdict, "size", size);
2891 while (qemu_isspace(*p))
2893 if (*typestr == '?' || *typestr == '.') {
2894 if (*typestr == '?') {
2902 while (qemu_isspace(*p))
2911 if (get_expr(mon, &val, &p))
2913 /* Check if 'i' is greater than 32-bit */
2914 if ((c == 'i') && ((val >> 32) & 0xffffffff)) {
2915 monitor_printf(mon, "\'%s\' has failed: ", cmd->name);
2916 monitor_printf(mon, "integer is for 32-bit values\n");
2918 } else if (c == 'M') {
2920 monitor_printf(mon, "enter a positive value\n");
2925 qdict_put_int(qdict, key, val);
2934 while (qemu_isspace(*p)) {
2937 if (*typestr == '?') {
2943 ret = qemu_strtosz_MiB(p, &end, &val);
2944 if (ret < 0 || val > INT64_MAX) {
2945 monitor_printf(mon, "invalid size\n");
2948 qdict_put_int(qdict, key, val);
2956 while (qemu_isspace(*p))
2958 if (*typestr == '?') {
2964 if (get_double(mon, &val, &p) < 0) {
2967 if (p[0] && p[1] == 's') {
2970 val /= 1e3; p += 2; break;
2972 val /= 1e6; p += 2; break;
2974 val /= 1e9; p += 2; break;
2977 if (*p && !qemu_isspace(*p)) {
2978 monitor_printf(mon, "Unknown unit suffix\n");
2981 qdict_put(qdict, key, qnum_from_double(val));
2989 while (qemu_isspace(*p)) {
2993 while (qemu_isgraph(*p)) {
2996 if (p - beg == 2 && !memcmp(beg, "on", p - beg)) {
2998 } else if (p - beg == 3 && !memcmp(beg, "off", p - beg)) {
3001 monitor_printf(mon, "Expected 'on' or 'off'\n");
3004 qdict_put_bool(qdict, key, val);
3009 const char *tmp = p;
3016 while (qemu_isspace(*p))
3021 if(!is_valid_option(p, typestr)) {
3023 monitor_printf(mon, "%s: unsupported option -%c\n",
3035 qdict_put_bool(qdict, key, true);
3042 /* package all remaining string */
3045 while (qemu_isspace(*p)) {
3048 if (*typestr == '?') {
3051 /* no remaining string: NULL argument */
3057 monitor_printf(mon, "%s: string expected\n",
3061 qdict_put_str(qdict, key, p);
3067 monitor_printf(mon, "%s: unknown type '%c'\n", cmd->name, c);
3073 /* check that all arguments were parsed */
3074 while (qemu_isspace(*p))
3077 monitor_printf(mon, "%s: extraneous characters at the end of line\n",
3090 static void handle_hmp_command(Monitor *mon, const char *cmdline)
3093 const mon_cmd_t *cmd;
3095 trace_handle_hmp_command(mon, cmdline);
3097 cmd = monitor_parse_command(mon, cmdline, &cmdline, mon->cmd_table);
3102 qdict = monitor_parse_arguments(mon, &cmdline, cmd);
3104 monitor_printf(mon, "Try \"help %s\" for more information\n",
3109 cmd->cmd(mon, qdict);
3113 static void cmd_completion(Monitor *mon, const char *name, const char *list)
3115 const char *p, *pstart;
3124 p = pstart + strlen(pstart);
3126 if (len > sizeof(cmd) - 2)
3127 len = sizeof(cmd) - 2;
3128 memcpy(cmd, pstart, len);
3130 if (name[0] == '\0' || !strncmp(name, cmd, strlen(name))) {
3131 readline_add_completion(mon->rs, cmd);
3139 static void file_completion(Monitor *mon, const char *input)
3144 char file[1024], file_prefix[1024];
3148 p = strrchr(input, '/');
3151 pstrcpy(file_prefix, sizeof(file_prefix), input);
3152 pstrcpy(path, sizeof(path), ".");
3154 input_path_len = p - input + 1;
3155 memcpy(path, input, input_path_len);
3156 if (input_path_len > sizeof(path) - 1)
3157 input_path_len = sizeof(path) - 1;
3158 path[input_path_len] = '\0';
3159 pstrcpy(file_prefix, sizeof(file_prefix), p + 1);
3162 ffs = opendir(path);
3171 if (strcmp(d->d_name, ".") == 0 || strcmp(d->d_name, "..") == 0) {
3175 if (strstart(d->d_name, file_prefix, NULL)) {
3176 memcpy(file, input, input_path_len);
3177 if (input_path_len < sizeof(file))
3178 pstrcpy(file + input_path_len, sizeof(file) - input_path_len,
3180 /* stat the file to find out if it's a directory.
3181 * In that case add a slash to speed up typing long paths
3183 if (stat(file, &sb) == 0 && S_ISDIR(sb.st_mode)) {
3184 pstrcat(file, sizeof(file), "/");
3186 readline_add_completion(mon->rs, file);
3192 static const char *next_arg_type(const char *typestr)
3194 const char *p = strchr(typestr, ':');
3195 return (p != NULL ? ++p : typestr);
3198 static void add_completion_option(ReadLineState *rs, const char *str,
3201 if (!str || !option) {
3204 if (!strncmp(option, str, strlen(str))) {
3205 readline_add_completion(rs, option);
3209 void chardev_add_completion(ReadLineState *rs, int nb_args, const char *str)
3212 ChardevBackendInfoList *list, *start;
3218 readline_set_completion_index(rs, len);
3220 start = list = qmp_query_chardev_backends(NULL);
3222 const char *chr_name = list->value->name;
3224 if (!strncmp(chr_name, str, len)) {
3225 readline_add_completion(rs, chr_name);
3229 qapi_free_ChardevBackendInfoList(start);
3232 void netdev_add_completion(ReadLineState *rs, int nb_args, const char *str)
3241 readline_set_completion_index(rs, len);
3242 for (i = 0; i < NET_CLIENT_DRIVER__MAX; i++) {
3243 add_completion_option(rs, str, NetClientDriver_str(i));
3247 void device_add_completion(ReadLineState *rs, int nb_args, const char *str)
3257 readline_set_completion_index(rs, len);
3258 list = elt = object_class_get_list(TYPE_DEVICE, false);
3261 DeviceClass *dc = OBJECT_CLASS_CHECK(DeviceClass, elt->data,
3263 name = object_class_get_name(OBJECT_CLASS(dc));
3265 if (dc->user_creatable
3266 && !strncmp(name, str, len)) {
3267 readline_add_completion(rs, name);
3274 void object_add_completion(ReadLineState *rs, int nb_args, const char *str)
3284 readline_set_completion_index(rs, len);
3285 list = elt = object_class_get_list(TYPE_USER_CREATABLE, false);
3289 name = object_class_get_name(OBJECT_CLASS(elt->data));
3290 if (!strncmp(name, str, len) && strcmp(name, TYPE_USER_CREATABLE)) {
3291 readline_add_completion(rs, name);
3298 static void peripheral_device_del_completion(ReadLineState *rs,
3299 const char *str, size_t len)
3301 Object *peripheral = container_get(qdev_get_machine(), "/peripheral");
3302 GSList *list, *item;
3304 list = qdev_build_hotpluggable_device_list(peripheral);
3309 for (item = list; item; item = g_slist_next(item)) {
3310 DeviceState *dev = item->data;
3312 if (dev->id && !strncmp(str, dev->id, len)) {
3313 readline_add_completion(rs, dev->id);
3320 void chardev_remove_completion(ReadLineState *rs, int nb_args, const char *str)
3323 ChardevInfoList *list, *start;
3329 readline_set_completion_index(rs, len);
3331 start = list = qmp_query_chardev(NULL);
3333 ChardevInfo *chr = list->value;
3335 if (!strncmp(chr->label, str, len)) {
3336 readline_add_completion(rs, chr->label);
3340 qapi_free_ChardevInfoList(start);
3343 static void ringbuf_completion(ReadLineState *rs, const char *str)
3346 ChardevInfoList *list, *start;
3349 readline_set_completion_index(rs, len);
3351 start = list = qmp_query_chardev(NULL);
3353 ChardevInfo *chr_info = list->value;
3355 if (!strncmp(chr_info->label, str, len)) {
3356 Chardev *chr = qemu_chr_find(chr_info->label);
3357 if (chr && CHARDEV_IS_RINGBUF(chr)) {
3358 readline_add_completion(rs, chr_info->label);
3363 qapi_free_ChardevInfoList(start);
3366 void ringbuf_write_completion(ReadLineState *rs, int nb_args, const char *str)
3371 ringbuf_completion(rs, str);
3374 void device_del_completion(ReadLineState *rs, int nb_args, const char *str)
3383 readline_set_completion_index(rs, len);
3384 peripheral_device_del_completion(rs, str, len);
3387 void object_del_completion(ReadLineState *rs, int nb_args, const char *str)
3389 ObjectPropertyInfoList *list, *start;
3396 readline_set_completion_index(rs, len);
3398 start = list = qmp_qom_list("/objects", NULL);
3400 ObjectPropertyInfo *info = list->value;
3402 if (!strncmp(info->type, "child<", 5)
3403 && !strncmp(info->name, str, len)) {
3404 readline_add_completion(rs, info->name);
3408 qapi_free_ObjectPropertyInfoList(start);
3411 void sendkey_completion(ReadLineState *rs, int nb_args, const char *str)
3420 sep = strrchr(str, '-');
3425 readline_set_completion_index(rs, len);
3426 for (i = 0; i < Q_KEY_CODE__MAX; i++) {
3427 if (!strncmp(str, QKeyCode_str(i), len)) {
3428 readline_add_completion(rs, QKeyCode_str(i));
3433 void set_link_completion(ReadLineState *rs, int nb_args, const char *str)
3438 readline_set_completion_index(rs, len);
3440 NetClientState *ncs[MAX_QUEUE_NUM];
3442 count = qemu_find_net_clients_except(NULL, ncs,
3443 NET_CLIENT_DRIVER_NONE,
3445 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3446 const char *name = ncs[i]->name;
3447 if (!strncmp(str, name, len)) {
3448 readline_add_completion(rs, name);
3451 } else if (nb_args == 3) {
3452 add_completion_option(rs, str, "on");
3453 add_completion_option(rs, str, "off");
3457 void netdev_del_completion(ReadLineState *rs, int nb_args, const char *str)
3460 NetClientState *ncs[MAX_QUEUE_NUM];
3467 readline_set_completion_index(rs, len);
3468 count = qemu_find_net_clients_except(NULL, ncs, NET_CLIENT_DRIVER_NIC,
3470 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3472 const char *name = ncs[i]->name;
3473 if (strncmp(str, name, len)) {
3476 opts = qemu_opts_find(qemu_find_opts_err("netdev", NULL), name);
3478 readline_add_completion(rs, name);
3483 void info_trace_events_completion(ReadLineState *rs, int nb_args, const char *str)
3488 readline_set_completion_index(rs, len);
3490 TraceEventIter iter;
3492 char *pattern = g_strdup_printf("%s*", str);
3493 trace_event_iter_init(&iter, pattern);
3494 while ((ev = trace_event_iter_next(&iter)) != NULL) {
3495 readline_add_completion(rs, trace_event_get_name(ev));
3501 void trace_event_completion(ReadLineState *rs, int nb_args, const char *str)
3506 readline_set_completion_index(rs, len);
3508 TraceEventIter iter;
3510 char *pattern = g_strdup_printf("%s*", str);
3511 trace_event_iter_init(&iter, pattern);
3512 while ((ev = trace_event_iter_next(&iter)) != NULL) {
3513 readline_add_completion(rs, trace_event_get_name(ev));
3516 } else if (nb_args == 3) {
3517 add_completion_option(rs, str, "on");
3518 add_completion_option(rs, str, "off");
3522 void watchdog_action_completion(ReadLineState *rs, int nb_args, const char *str)
3529 readline_set_completion_index(rs, strlen(str));
3530 for (i = 0; i < WATCHDOG_ACTION__MAX; i++) {
3531 add_completion_option(rs, str, WatchdogAction_str(i));
3535 void migrate_set_capability_completion(ReadLineState *rs, int nb_args,
3541 readline_set_completion_index(rs, len);
3544 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
3545 const char *name = MigrationCapability_str(i);
3546 if (!strncmp(str, name, len)) {
3547 readline_add_completion(rs, name);
3550 } else if (nb_args == 3) {
3551 add_completion_option(rs, str, "on");
3552 add_completion_option(rs, str, "off");
3556 void migrate_set_parameter_completion(ReadLineState *rs, int nb_args,
3562 readline_set_completion_index(rs, len);
3565 for (i = 0; i < MIGRATION_PARAMETER__MAX; i++) {
3566 const char *name = MigrationParameter_str(i);
3567 if (!strncmp(str, name, len)) {
3568 readline_add_completion(rs, name);
3574 void host_net_add_completion(ReadLineState *rs, int nb_args, const char *str)
3582 readline_set_completion_index(rs, len);
3583 for (i = 0; host_net_devices[i]; i++) {
3584 if (!strncmp(host_net_devices[i], str, len)) {
3585 readline_add_completion(rs, host_net_devices[i]);
3590 void host_net_remove_completion(ReadLineState *rs, int nb_args, const char *str)
3592 NetClientState *ncs[MAX_QUEUE_NUM];
3596 readline_set_completion_index(rs, len);
3598 count = qemu_find_net_clients_except(NULL, ncs,
3599 NET_CLIENT_DRIVER_NONE,
3601 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3605 if (net_hub_id_for_client(ncs[i], &id)) {
3608 snprintf(name, sizeof(name), "%d", id);
3609 if (!strncmp(str, name, len)) {
3610 readline_add_completion(rs, name);
3614 } else if (nb_args == 3) {
3615 count = qemu_find_net_clients_except(NULL, ncs,
3616 NET_CLIENT_DRIVER_NIC,
3618 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3622 if (ncs[i]->info->type == NET_CLIENT_DRIVER_HUBPORT ||
3623 net_hub_id_for_client(ncs[i], &id)) {
3626 name = ncs[i]->name;
3627 if (!strncmp(str, name, len)) {
3628 readline_add_completion(rs, name);
3635 static void vm_completion(ReadLineState *rs, const char *str)
3638 BlockDriverState *bs;
3639 BdrvNextIterator it;
3642 readline_set_completion_index(rs, len);
3644 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
3645 SnapshotInfoList *snapshots, *snapshot;
3646 AioContext *ctx = bdrv_get_aio_context(bs);
3649 aio_context_acquire(ctx);
3650 if (bdrv_can_snapshot(bs)) {
3651 ok = bdrv_query_snapshot_info_list(bs, &snapshots, NULL) == 0;
3653 aio_context_release(ctx);
3658 snapshot = snapshots;
3660 char *completion = snapshot->value->name;
3661 if (!strncmp(str, completion, len)) {
3662 readline_add_completion(rs, completion);
3664 completion = snapshot->value->id;
3665 if (!strncmp(str, completion, len)) {
3666 readline_add_completion(rs, completion);
3668 snapshot = snapshot->next;
3670 qapi_free_SnapshotInfoList(snapshots);
3675 void delvm_completion(ReadLineState *rs, int nb_args, const char *str)
3678 vm_completion(rs, str);
3682 void loadvm_completion(ReadLineState *rs, int nb_args, const char *str)
3685 vm_completion(rs, str);
3689 static void monitor_find_completion_by_table(Monitor *mon,
3690 const mon_cmd_t *cmd_table,
3694 const char *cmdname;
3696 const char *ptype, *str, *name;
3697 const mon_cmd_t *cmd;
3698 BlockBackend *blk = NULL;
3701 /* command completion */
3706 readline_set_completion_index(mon->rs, strlen(cmdname));
3707 for (cmd = cmd_table; cmd->name != NULL; cmd++) {
3708 cmd_completion(mon, cmdname, cmd->name);
3711 /* find the command */
3712 for (cmd = cmd_table; cmd->name != NULL; cmd++) {
3713 if (compare_cmd(args[0], cmd->name)) {
3721 if (cmd->sub_table) {
3722 /* do the job again */
3723 monitor_find_completion_by_table(mon, cmd->sub_table,
3724 &args[1], nb_args - 1);
3727 if (cmd->command_completion) {
3728 cmd->command_completion(mon->rs, nb_args, args[nb_args - 1]);
3732 ptype = next_arg_type(cmd->args_type);
3733 for(i = 0; i < nb_args - 2; i++) {
3734 if (*ptype != '\0') {
3735 ptype = next_arg_type(ptype);
3736 while (*ptype == '?')
3737 ptype = next_arg_type(ptype);
3740 str = args[nb_args - 1];
3741 while (*ptype == '-' && ptype[1] != '\0') {
3742 ptype = next_arg_type(ptype);
3746 /* file completion */
3747 readline_set_completion_index(mon->rs, strlen(str));
3748 file_completion(mon, str);
3751 /* block device name completion */
3752 readline_set_completion_index(mon->rs, strlen(str));
3753 while ((blk = blk_next(blk)) != NULL) {
3754 name = blk_name(blk);
3755 if (str[0] == '\0' ||
3756 !strncmp(name, str, strlen(str))) {
3757 readline_add_completion(mon->rs, name);
3763 if (!strcmp(cmd->name, "help|?")) {
3764 monitor_find_completion_by_table(mon, cmd_table,
3765 &args[1], nb_args - 1);
3774 static void monitor_find_completion(void *opaque,
3775 const char *cmdline)
3777 Monitor *mon = opaque;
3778 char *args[MAX_ARGS];
3781 /* 1. parse the cmdline */
3782 if (parse_cmdline(cmdline, &nb_args, args) < 0) {
3786 /* if the line ends with a space, it means we want to complete the
3788 len = strlen(cmdline);
3789 if (len > 0 && qemu_isspace(cmdline[len - 1])) {
3790 if (nb_args >= MAX_ARGS) {
3793 args[nb_args++] = g_strdup("");
3796 /* 2. auto complete according to args */
3797 monitor_find_completion_by_table(mon, mon->cmd_table, args, nb_args);
3800 free_cmdline_args(args, nb_args);
3803 static int monitor_can_read(void *opaque)
3805 Monitor *mon = opaque;
3807 return (mon->suspend_cnt == 0) ? 1 : 0;
3810 static void handle_qmp_command(JSONMessageParser *parser, GQueue *tokens)
3812 QObject *req, *rsp = NULL, *id = NULL;
3813 QDict *qdict = NULL;
3814 Monitor *mon = cur_mon;
3817 req = json_parser_parse_err(tokens, NULL, &err);
3819 /* json_parser_parse_err() sucks: can fail without setting @err */
3820 error_setg(&err, QERR_JSON_PARSING);
3826 qdict = qobject_to_qdict(req);
3828 id = qdict_get(qdict, "id");
3830 qdict_del(qdict, "id");
3831 } /* else will fail qmp_dispatch() */
3833 if (trace_event_get_state_backends(TRACE_HANDLE_QMP_COMMAND)) {
3834 QString *req_json = qobject_to_json(req);
3835 trace_handle_qmp_command(mon, qstring_get_str(req_json));
3839 rsp = qmp_dispatch(cur_mon->qmp.commands, req);
3841 if (mon->qmp.commands == &qmp_cap_negotiation_commands) {
3842 qdict = qdict_get_qdict(qobject_to_qdict(rsp), "error");
3844 && !g_strcmp0(qdict_get_try_str(qdict, "class"),
3845 QapiErrorClass_str(ERROR_CLASS_COMMAND_NOT_FOUND))) {
3846 /* Provide a more useful error message */
3847 qdict_del(qdict, "desc");
3848 qdict_put_str(qdict, "desc", "Expecting capabilities negotiation"
3849 " with 'qmp_capabilities'");
3855 qdict = qdict_new();
3856 qdict_put_obj(qdict, "error", qmp_build_error_object(err));
3858 rsp = QOBJECT(qdict);
3863 qdict_put_obj(qobject_to_qdict(rsp), "id", id);
3867 monitor_json_emitter(mon, rsp);
3871 qobject_decref(rsp);
3872 qobject_decref(req);
3875 static void monitor_qmp_read(void *opaque, const uint8_t *buf, int size)
3877 Monitor *old_mon = cur_mon;
3881 json_message_parser_feed(&cur_mon->qmp.parser, (const char *) buf, size);
3886 static void monitor_read(void *opaque, const uint8_t *buf, int size)
3888 Monitor *old_mon = cur_mon;
3894 for (i = 0; i < size; i++)
3895 readline_handle_byte(cur_mon->rs, buf[i]);
3897 if (size == 0 || buf[size - 1] != 0)
3898 monitor_printf(cur_mon, "corrupted command\n");
3900 handle_hmp_command(cur_mon, (char *)buf);
3906 static void monitor_command_cb(void *opaque, const char *cmdline,
3907 void *readline_opaque)
3909 Monitor *mon = opaque;
3911 monitor_suspend(mon);
3912 handle_hmp_command(mon, cmdline);
3913 monitor_resume(mon);
3916 int monitor_suspend(Monitor *mon)
3924 void monitor_resume(Monitor *mon)
3928 if (--mon->suspend_cnt == 0)
3929 readline_show_prompt(mon->rs);
3932 static QObject *get_qmp_greeting(void)
3934 QObject *ver = NULL;
3936 qmp_marshal_query_version(NULL, &ver, NULL);
3938 return qobject_from_jsonf("{'QMP': {'version': %p, 'capabilities': []}}",
3942 static void monitor_qmp_event(void *opaque, int event)
3945 Monitor *mon = opaque;
3948 case CHR_EVENT_OPENED:
3949 mon->qmp.commands = &qmp_cap_negotiation_commands;
3950 data = get_qmp_greeting();
3951 monitor_json_emitter(mon, data);
3952 qobject_decref(data);
3955 case CHR_EVENT_CLOSED:
3956 json_message_parser_destroy(&mon->qmp.parser);
3957 json_message_parser_init(&mon->qmp.parser, handle_qmp_command);
3959 monitor_fdsets_cleanup();
3964 static void monitor_event(void *opaque, int event)
3966 Monitor *mon = opaque;
3969 case CHR_EVENT_MUX_IN:
3970 qemu_mutex_lock(&mon->out_lock);
3972 qemu_mutex_unlock(&mon->out_lock);
3973 if (mon->reset_seen) {
3974 readline_restart(mon->rs);
3975 monitor_resume(mon);
3978 mon->suspend_cnt = 0;
3982 case CHR_EVENT_MUX_OUT:
3983 if (mon->reset_seen) {
3984 if (mon->suspend_cnt == 0) {
3985 monitor_printf(mon, "\n");
3988 monitor_suspend(mon);
3992 qemu_mutex_lock(&mon->out_lock);
3994 qemu_mutex_unlock(&mon->out_lock);
3997 case CHR_EVENT_OPENED:
3998 monitor_printf(mon, "QEMU %s monitor - type 'help' for more "
3999 "information\n", QEMU_VERSION);
4000 if (!mon->mux_out) {
4001 readline_restart(mon->rs);
4002 readline_show_prompt(mon->rs);
4004 mon->reset_seen = 1;
4008 case CHR_EVENT_CLOSED:
4010 monitor_fdsets_cleanup();
4016 compare_mon_cmd(const void *a, const void *b)
4018 return strcmp(((const mon_cmd_t *)a)->name,
4019 ((const mon_cmd_t *)b)->name);
4022 static void sortcmdlist(void)
4025 int elem_size = sizeof(mon_cmd_t);
4027 array_num = sizeof(mon_cmds)/elem_size-1;
4028 qsort((void *)mon_cmds, array_num, elem_size, compare_mon_cmd);
4030 array_num = sizeof(info_cmds)/elem_size-1;
4031 qsort((void *)info_cmds, array_num, elem_size, compare_mon_cmd);
4034 /* These functions just adapt the readline interface in a typesafe way. We
4035 * could cast function pointers but that discards compiler checks.
4037 static void GCC_FMT_ATTR(2, 3) monitor_readline_printf(void *opaque,
4038 const char *fmt, ...)
4042 monitor_vprintf(opaque, fmt, ap);
4046 static void monitor_readline_flush(void *opaque)
4048 monitor_flush(opaque);
4052 * Print to current monitor if we have one, else to stderr.
4053 * TODO should return int, so callers can calculate width, but that
4054 * requires surgery to monitor_vprintf(). Left for another day.
4056 void error_vprintf(const char *fmt, va_list ap)
4058 if (cur_mon && !monitor_cur_is_qmp()) {
4059 monitor_vprintf(cur_mon, fmt, ap);
4061 vfprintf(stderr, fmt, ap);
4065 void error_vprintf_unless_qmp(const char *fmt, va_list ap)
4067 if (cur_mon && !monitor_cur_is_qmp()) {
4068 monitor_vprintf(cur_mon, fmt, ap);
4069 } else if (!cur_mon) {
4070 vfprintf(stderr, fmt, ap);
4074 static void __attribute__((constructor)) monitor_lock_init(void)
4076 qemu_mutex_init(&monitor_lock);
4079 void monitor_init(Chardev *chr, int flags)
4081 static int is_first_init = 1;
4084 if (is_first_init) {
4085 monitor_qapi_event_init();
4090 mon = g_malloc(sizeof(*mon));
4091 monitor_data_init(mon);
4093 qemu_chr_fe_init(&mon->chr, chr, &error_abort);
4095 if (flags & MONITOR_USE_READLINE) {
4096 mon->rs = readline_init(monitor_readline_printf,
4097 monitor_readline_flush,
4099 monitor_find_completion);
4100 monitor_read_command(mon, 0);
4103 if (monitor_is_qmp(mon)) {
4104 qemu_chr_fe_set_handlers(&mon->chr, monitor_can_read, monitor_qmp_read,
4105 monitor_qmp_event, NULL, mon, NULL, true);
4106 qemu_chr_fe_set_echo(&mon->chr, true);
4107 json_message_parser_init(&mon->qmp.parser, handle_qmp_command);
4109 qemu_chr_fe_set_handlers(&mon->chr, monitor_can_read, monitor_read,
4110 monitor_event, NULL, mon, NULL, true);
4113 qemu_mutex_lock(&monitor_lock);
4114 QLIST_INSERT_HEAD(&mon_list, mon, entry);
4115 qemu_mutex_unlock(&monitor_lock);
4118 void monitor_cleanup(void)
4120 Monitor *mon, *next;
4122 qemu_mutex_lock(&monitor_lock);
4123 QLIST_FOREACH_SAFE(mon, &mon_list, entry, next) {
4124 QLIST_REMOVE(mon, entry);
4125 monitor_data_destroy(mon);
4128 qemu_mutex_unlock(&monitor_lock);
4131 QemuOptsList qemu_mon_opts = {
4133 .implied_opt_name = "chardev",
4134 .head = QTAILQ_HEAD_INITIALIZER(qemu_mon_opts.head),
4138 .type = QEMU_OPT_STRING,
4141 .type = QEMU_OPT_STRING,
4143 .name = "default", /* deprecated */
4144 .type = QEMU_OPT_BOOL,
4147 .type = QEMU_OPT_BOOL,
4149 { /* end of list */ }
4154 void qmp_rtc_reset_reinjection(Error **errp)
4156 error_setg(errp, QERR_FEATURE_DISABLED, "rtc-reset-reinjection");
4160 #ifndef TARGET_S390X
4161 void qmp_dump_skeys(const char *filename, Error **errp)
4163 error_setg(errp, QERR_FEATURE_DISABLED, "dump-skeys");
4168 GICCapabilityList *qmp_query_gic_capabilities(Error **errp)
4170 error_setg(errp, QERR_FEATURE_DISABLED, "query-gic-capabilities");
4175 HotpluggableCPUList *qmp_query_hotpluggable_cpus(Error **errp)
4177 MachineState *ms = MACHINE(qdev_get_machine());
4178 MachineClass *mc = MACHINE_GET_CLASS(ms);
4180 if (!mc->has_hotpluggable_cpus) {
4181 error_setg(errp, QERR_FEATURE_DISABLED, "query-hotpluggable-cpus");
4185 return machine_query_hotpluggable_cpus(ms);