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"
26 #include "qemu/units.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 "chardev/char-io.h"
40 #include "chardev/char-mux.h"
41 #include "ui/qemu-spice.h"
42 #include "sysemu/numa.h"
43 #include "monitor/monitor.h"
44 #include "qemu/config-file.h"
45 #include "qemu/readline.h"
46 #include "ui/console.h"
48 #include "sysemu/block-backend.h"
49 #include "audio/audio.h"
50 #include "disas/disas.h"
51 #include "sysemu/balloon.h"
52 #include "qemu/timer.h"
53 #include "sysemu/hw_accel.h"
54 #include "authz/list.h"
55 #include "qapi/util.h"
56 #include "sysemu/tpm.h"
57 #include "qapi/qmp/qdict.h"
58 #include "qapi/qmp/qerror.h"
59 #include "qapi/qmp/qnum.h"
60 #include "qapi/qmp/qstring.h"
61 #include "qapi/qmp/qjson.h"
62 #include "qapi/qmp/json-parser.h"
63 #include "qapi/qmp/qlist.h"
64 #include "qom/object_interfaces.h"
65 #include "trace-root.h"
66 #include "trace/control.h"
67 #include "monitor/hmp-target.h"
68 #ifdef CONFIG_TRACE_SIMPLE
69 #include "trace/simple.h"
71 #include "exec/memory.h"
72 #include "exec/exec-all.h"
74 #include "qemu/option.h"
76 #include "qemu/thread.h"
77 #include "block/qapi.h"
78 #include "qapi/qapi-commands.h"
79 #include "qapi/qapi-emit-events.h"
80 #include "qapi/error.h"
81 #include "qapi/qmp-event.h"
82 #include "qapi/qapi-introspect.h"
83 #include "sysemu/qtest.h"
84 #include "sysemu/cpus.h"
85 #include "sysemu/iothread.h"
86 #include "qemu/cutils.h"
89 #if defined(TARGET_S390X)
90 #include "hw/s390x/storage-keys.h"
91 #include "hw/s390x/storage-attributes.h"
98 * 'B' block device name
99 * 's' string (accept optional quote)
100 * 'S' it just appends the rest of the string (accept optional quote)
101 * 'O' option string of the form NAME=VALUE,...
102 * parsed according to QemuOptsList given by its name
103 * Example: 'device:O' uses qemu_device_opts.
104 * Restriction: only lists with empty desc are supported
105 * TODO lift the restriction
107 * 'l' target long (32 or 64 bit)
108 * 'M' Non-negative target long (32 or 64 bit), in user mode the
109 * value is multiplied by 2^20 (think Mebibyte)
110 * 'o' octets (aka bytes)
111 * user mode accepts an optional E, e, P, p, T, t, G, g, M, m,
112 * K, k suffix, which multiplies the value by 2^60 for suffixes E
113 * and e, 2^50 for suffixes P and p, 2^40 for suffixes T and t,
114 * 2^30 for suffixes G and g, 2^20 for M and m, 2^10 for K and k
116 * user mode accepts an optional ms, us, ns suffix,
117 * which divides the value by 1e3, 1e6, 1e9, respectively
118 * '/' optional gdb-like print format (like "/10x")
120 * '?' optional type (for all types, except '/')
121 * '.' other form of optional type (for 'i' and 'l')
123 * user mode accepts "on" or "off"
124 * '-' optional parameter (eg. '-f')
128 typedef struct mon_cmd_t {
130 const char *args_type;
133 const char *flags; /* p=preconfig */
134 void (*cmd)(Monitor *mon, const QDict *qdict);
135 /* @sub_table is a list of 2nd level of commands. If it does not exist,
136 * cmd should be used. If it exists, sub_table[?].cmd should be
137 * used, and cmd of 1st level plays the role of help function.
139 struct mon_cmd_t *sub_table;
140 void (*command_completion)(ReadLineState *rs, int nb_args, const char *str);
143 /* file descriptors passed via SCM_RIGHTS */
144 typedef struct mon_fd_t mon_fd_t;
148 QLIST_ENTRY(mon_fd_t) next;
151 /* file descriptor associated with a file descriptor set */
152 typedef struct MonFdsetFd MonFdsetFd;
157 QLIST_ENTRY(MonFdsetFd) next;
160 /* file descriptor set containing fds passed via SCM_RIGHTS */
161 typedef struct MonFdset MonFdset;
164 QLIST_HEAD(, MonFdsetFd) fds;
165 QLIST_HEAD(, MonFdsetFd) dup_fds;
166 QLIST_ENTRY(MonFdset) next;
170 JSONMessageParser parser;
172 * When a client connects, we're in capabilities negotiation mode.
173 * @commands is &qmp_cap_negotiation_commands then. When command
174 * qmp_capabilities succeeds, we go into command mode, and
175 * @command becomes &qmp_commands.
177 QmpCommandList *commands;
178 bool capab_offered[QMP_CAPABILITY__MAX]; /* capabilities offered */
179 bool capab[QMP_CAPABILITY__MAX]; /* offered and accepted */
181 * Protects qmp request/response queue.
182 * Take monitor_lock first when you need both.
184 QemuMutex qmp_queue_lock;
185 /* Input queue that holds all the parsed QMP requests */
186 GQueue *qmp_requests;
190 * To prevent flooding clients, events can be throttled. The
191 * throttling is calculated globally, rather than per-Monitor
194 typedef struct MonitorQAPIEventState {
195 QAPIEvent event; /* Throttling state for this event type and... */
196 QDict *data; /* ... data, see qapi_event_throttle_equal() */
197 QEMUTimer *timer; /* Timer for handling delayed events */
198 QDict *qdict; /* Delayed event (if any) */
199 } MonitorQAPIEventState;
202 int64_t rate; /* Minimum time (in ns) between two events */
203 } MonitorQAPIEventConf;
209 int suspend_cnt; /* Needs to be accessed atomically */
214 * State used only in the thread "owning" the monitor.
215 * If @use_io_thread, this is @mon_iothread.
216 * Else, it's the main thread.
217 * These members can be safely accessed without locks.
223 BlockCompletionFunc *password_completion_cb;
224 void *password_opaque;
225 mon_cmd_t *cmd_table;
226 QTAILQ_ENTRY(Monitor) entry;
229 * The per-monitor lock. We can't access guest memory when holding
235 * Members that are protected by the per-monitor lock
237 QLIST_HEAD(, mon_fd_t) fds;
240 /* Read under either BQL or mon_lock, written with BQL+mon_lock. */
244 /* Shared monitor I/O thread */
245 IOThread *mon_iothread;
247 /* Bottom half to dispatch the requests received from I/O thread */
248 QEMUBH *qmp_dispatcher_bh;
251 /* Owner of the request */
253 /* "id" field of the request */
256 * Request object to be handled or Error to be reported
257 * (exactly one of them is non-null)
262 typedef struct QMPRequest QMPRequest;
264 /* QMP checker flags */
265 #define QMP_ACCEPT_UNKNOWNS 1
267 /* Protects mon_list, monitor_qapi_event_state, monitor_destroyed. */
268 static QemuMutex monitor_lock;
269 static GHashTable *monitor_qapi_event_state;
270 static QTAILQ_HEAD(, Monitor) mon_list;
271 static bool monitor_destroyed;
273 /* Protects mon_fdsets */
274 static QemuMutex mon_fdsets_lock;
275 static QLIST_HEAD(, MonFdset) mon_fdsets;
277 static int mon_refcount;
279 static mon_cmd_t mon_cmds[];
280 static mon_cmd_t info_cmds[];
282 QmpCommandList qmp_commands, qmp_cap_negotiation_commands;
284 __thread Monitor *cur_mon;
286 static void monitor_command_cb(void *opaque, const char *cmdline,
287 void *readline_opaque);
290 * Is @mon a QMP monitor?
292 static inline bool monitor_is_qmp(const Monitor *mon)
294 return (mon->flags & MONITOR_USE_CONTROL);
298 * Is @mon is using readline?
299 * Note: not all HMP monitors use readline, e.g., gdbserver has a
300 * non-interactive HMP monitor, so readline is not used there.
302 static inline bool monitor_uses_readline(const Monitor *mon)
304 return mon->flags & MONITOR_USE_READLINE;
307 static inline bool monitor_is_hmp_non_interactive(const Monitor *mon)
309 return !monitor_is_qmp(mon) && !monitor_uses_readline(mon);
313 * Return the clock to use for recording an event's time.
314 * It's QEMU_CLOCK_REALTIME, except for qtests it's
315 * QEMU_CLOCK_VIRTUAL, to support testing rate limits.
316 * Beware: result is invalid before configure_accelerator().
318 static inline QEMUClockType monitor_get_event_clock(void)
320 return qtest_enabled() ? QEMU_CLOCK_VIRTUAL : QEMU_CLOCK_REALTIME;
324 * Is the current monitor, if any, a QMP monitor?
326 bool monitor_cur_is_qmp(void)
328 return cur_mon && monitor_is_qmp(cur_mon);
331 void monitor_read_command(Monitor *mon, int show_prompt)
336 readline_start(mon->rs, "(qemu) ", 0, monitor_command_cb, NULL);
338 readline_show_prompt(mon->rs);
341 int monitor_read_password(Monitor *mon, ReadLineFunc *readline_func,
345 readline_start(mon->rs, "Password: ", 1, readline_func, opaque);
346 /* prompt is printed on return from the command handler */
349 monitor_printf(mon, "terminal does not support password prompting\n");
354 static void qmp_request_free(QMPRequest *req)
356 qobject_unref(req->id);
357 qobject_unref(req->req);
358 error_free(req->err);
362 /* Caller must hold mon->qmp.qmp_queue_lock */
363 static void monitor_qmp_cleanup_req_queue_locked(Monitor *mon)
365 while (!g_queue_is_empty(mon->qmp.qmp_requests)) {
366 qmp_request_free(g_queue_pop_head(mon->qmp.qmp_requests));
370 static void monitor_qmp_cleanup_queues(Monitor *mon)
372 qemu_mutex_lock(&mon->qmp.qmp_queue_lock);
373 monitor_qmp_cleanup_req_queue_locked(mon);
374 qemu_mutex_unlock(&mon->qmp.qmp_queue_lock);
378 static void monitor_flush_locked(Monitor *mon);
380 static gboolean monitor_unblocked(GIOChannel *chan, GIOCondition cond,
383 Monitor *mon = opaque;
385 qemu_mutex_lock(&mon->mon_lock);
387 monitor_flush_locked(mon);
388 qemu_mutex_unlock(&mon->mon_lock);
392 /* Caller must hold mon->mon_lock */
393 static void monitor_flush_locked(Monitor *mon)
399 if (mon->skip_flush) {
403 buf = qstring_get_str(mon->outbuf);
404 len = qstring_get_length(mon->outbuf);
406 if (len && !mon->mux_out) {
407 rc = qemu_chr_fe_write(&mon->chr, (const uint8_t *) buf, len);
408 if ((rc < 0 && errno != EAGAIN) || (rc == len)) {
409 /* all flushed or error */
410 qobject_unref(mon->outbuf);
411 mon->outbuf = qstring_new();
416 QString *tmp = qstring_from_str(buf + rc);
417 qobject_unref(mon->outbuf);
420 if (mon->out_watch == 0) {
422 qemu_chr_fe_add_watch(&mon->chr, G_IO_OUT | G_IO_HUP,
423 monitor_unblocked, mon);
428 void monitor_flush(Monitor *mon)
430 qemu_mutex_lock(&mon->mon_lock);
431 monitor_flush_locked(mon);
432 qemu_mutex_unlock(&mon->mon_lock);
435 /* flush at every end of line */
436 static void monitor_puts(Monitor *mon, const char *str)
440 qemu_mutex_lock(&mon->mon_lock);
446 qstring_append_chr(mon->outbuf, '\r');
448 qstring_append_chr(mon->outbuf, c);
450 monitor_flush_locked(mon);
453 qemu_mutex_unlock(&mon->mon_lock);
456 void monitor_vprintf(Monitor *mon, const char *fmt, va_list ap)
463 if (monitor_is_qmp(mon)) {
467 buf = g_strdup_vprintf(fmt, ap);
468 monitor_puts(mon, buf);
472 void monitor_printf(Monitor *mon, const char *fmt, ...)
476 monitor_vprintf(mon, fmt, ap);
480 int monitor_fprintf(FILE *stream, const char *fmt, ...)
484 monitor_vprintf((Monitor *)stream, fmt, ap);
489 static void qmp_send_response(Monitor *mon, const QDict *rsp)
491 const QObject *data = QOBJECT(rsp);
494 json = mon->flags & MONITOR_USE_PRETTY ? qobject_to_json_pretty(data) :
495 qobject_to_json(data);
496 assert(json != NULL);
498 qstring_append_chr(json, '\n');
499 monitor_puts(mon, qstring_get_str(json));
504 static MonitorQAPIEventConf monitor_qapi_event_conf[QAPI_EVENT__MAX] = {
505 /* Limit guest-triggerable events to 1 per second */
506 [QAPI_EVENT_RTC_CHANGE] = { 1000 * SCALE_MS },
507 [QAPI_EVENT_WATCHDOG] = { 1000 * SCALE_MS },
508 [QAPI_EVENT_BALLOON_CHANGE] = { 1000 * SCALE_MS },
509 [QAPI_EVENT_QUORUM_REPORT_BAD] = { 1000 * SCALE_MS },
510 [QAPI_EVENT_QUORUM_FAILURE] = { 1000 * SCALE_MS },
511 [QAPI_EVENT_VSERPORT_CHANGE] = { 1000 * SCALE_MS },
515 * Broadcast an event to all monitors.
516 * @qdict is the event object. Its member "event" must match @event.
517 * Caller must hold monitor_lock.
519 static void monitor_qapi_event_emit(QAPIEvent event, QDict *qdict)
523 trace_monitor_protocol_event_emit(event, qdict);
524 QTAILQ_FOREACH(mon, &mon_list, entry) {
525 if (monitor_is_qmp(mon)
526 && mon->qmp.commands != &qmp_cap_negotiation_commands) {
527 qmp_send_response(mon, qdict);
532 static void monitor_qapi_event_handler(void *opaque);
535 * Queue a new event for emission to Monitor instances,
536 * applying any rate limiting if required.
539 monitor_qapi_event_queue_no_reenter(QAPIEvent event, QDict *qdict)
541 MonitorQAPIEventConf *evconf;
542 MonitorQAPIEventState *evstate;
544 assert(event < QAPI_EVENT__MAX);
545 evconf = &monitor_qapi_event_conf[event];
546 trace_monitor_protocol_event_queue(event, qdict, evconf->rate);
548 qemu_mutex_lock(&monitor_lock);
551 /* Unthrottled event */
552 monitor_qapi_event_emit(event, qdict);
554 QDict *data = qobject_to(QDict, qdict_get(qdict, "data"));
555 MonitorQAPIEventState key = { .event = event, .data = data };
557 evstate = g_hash_table_lookup(monitor_qapi_event_state, &key);
558 assert(!evstate || timer_pending(evstate->timer));
562 * Timer is pending for (at least) evconf->rate ns after
563 * last send. Store event for sending when timer fires,
564 * replacing a prior stored event if any.
566 qobject_unref(evstate->qdict);
567 evstate->qdict = qobject_ref(qdict);
570 * Last send was (at least) evconf->rate ns ago.
571 * Send immediately, and arm the timer to call
572 * monitor_qapi_event_handler() in evconf->rate ns. Any
573 * events arriving before then will be delayed until then.
575 int64_t now = qemu_clock_get_ns(monitor_get_event_clock());
577 monitor_qapi_event_emit(event, qdict);
579 evstate = g_new(MonitorQAPIEventState, 1);
580 evstate->event = event;
581 evstate->data = qobject_ref(data);
582 evstate->qdict = NULL;
583 evstate->timer = timer_new_ns(monitor_get_event_clock(),
584 monitor_qapi_event_handler,
586 g_hash_table_add(monitor_qapi_event_state, evstate);
587 timer_mod_ns(evstate->timer, now + evconf->rate);
591 qemu_mutex_unlock(&monitor_lock);
594 void qapi_event_emit(QAPIEvent event, QDict *qdict)
597 * monitor_qapi_event_queue_no_reenter() is not reentrant: it
598 * would deadlock on monitor_lock. Work around by queueing
599 * events in thread-local storage.
600 * TODO: remove this, make it re-enter safe.
602 typedef struct MonitorQapiEvent {
605 QSIMPLEQ_ENTRY(MonitorQapiEvent) entry;
607 static __thread QSIMPLEQ_HEAD(, MonitorQapiEvent) event_queue;
608 static __thread bool reentered;
609 MonitorQapiEvent *ev;
612 QSIMPLEQ_INIT(&event_queue);
615 ev = g_new(MonitorQapiEvent, 1);
616 ev->qdict = qobject_ref(qdict);
618 QSIMPLEQ_INSERT_TAIL(&event_queue, ev, entry);
625 while ((ev = QSIMPLEQ_FIRST(&event_queue)) != NULL) {
626 QSIMPLEQ_REMOVE_HEAD(&event_queue, entry);
627 monitor_qapi_event_queue_no_reenter(ev->event, ev->qdict);
628 qobject_unref(ev->qdict);
636 * This function runs evconf->rate ns after sending a throttled
638 * If another event has since been stored, send it.
640 static void monitor_qapi_event_handler(void *opaque)
642 MonitorQAPIEventState *evstate = opaque;
643 MonitorQAPIEventConf *evconf = &monitor_qapi_event_conf[evstate->event];
645 trace_monitor_protocol_event_handler(evstate->event, evstate->qdict);
646 qemu_mutex_lock(&monitor_lock);
648 if (evstate->qdict) {
649 int64_t now = qemu_clock_get_ns(monitor_get_event_clock());
651 monitor_qapi_event_emit(evstate->event, evstate->qdict);
652 qobject_unref(evstate->qdict);
653 evstate->qdict = NULL;
654 timer_mod_ns(evstate->timer, now + evconf->rate);
656 g_hash_table_remove(monitor_qapi_event_state, evstate);
657 qobject_unref(evstate->data);
658 timer_free(evstate->timer);
662 qemu_mutex_unlock(&monitor_lock);
665 static unsigned int qapi_event_throttle_hash(const void *key)
667 const MonitorQAPIEventState *evstate = key;
668 unsigned int hash = evstate->event * 255;
670 if (evstate->event == QAPI_EVENT_VSERPORT_CHANGE) {
671 hash += g_str_hash(qdict_get_str(evstate->data, "id"));
674 if (evstate->event == QAPI_EVENT_QUORUM_REPORT_BAD) {
675 hash += g_str_hash(qdict_get_str(evstate->data, "node-name"));
681 static gboolean qapi_event_throttle_equal(const void *a, const void *b)
683 const MonitorQAPIEventState *eva = a;
684 const MonitorQAPIEventState *evb = b;
686 if (eva->event != evb->event) {
690 if (eva->event == QAPI_EVENT_VSERPORT_CHANGE) {
691 return !strcmp(qdict_get_str(eva->data, "id"),
692 qdict_get_str(evb->data, "id"));
695 if (eva->event == QAPI_EVENT_QUORUM_REPORT_BAD) {
696 return !strcmp(qdict_get_str(eva->data, "node-name"),
697 qdict_get_str(evb->data, "node-name"));
703 static void monitor_qapi_event_init(void)
705 monitor_qapi_event_state = g_hash_table_new(qapi_event_throttle_hash,
706 qapi_event_throttle_equal);
709 static void handle_hmp_command(Monitor *mon, const char *cmdline);
711 static void monitor_iothread_init(void);
713 static void monitor_data_init(Monitor *mon, bool skip_flush,
716 if (use_io_thread && !mon_iothread) {
717 monitor_iothread_init();
719 memset(mon, 0, sizeof(Monitor));
720 qemu_mutex_init(&mon->mon_lock);
721 qemu_mutex_init(&mon->qmp.qmp_queue_lock);
722 mon->outbuf = qstring_new();
723 /* Use *mon_cmds by default. */
724 mon->cmd_table = mon_cmds;
725 mon->skip_flush = skip_flush;
726 mon->use_io_thread = use_io_thread;
727 mon->qmp.qmp_requests = g_queue_new();
730 static void monitor_data_destroy(Monitor *mon)
732 g_free(mon->mon_cpu_path);
733 qemu_chr_fe_deinit(&mon->chr, false);
734 if (monitor_is_qmp(mon)) {
735 json_message_parser_destroy(&mon->qmp.parser);
737 readline_free(mon->rs);
738 qobject_unref(mon->outbuf);
739 qemu_mutex_destroy(&mon->mon_lock);
740 qemu_mutex_destroy(&mon->qmp.qmp_queue_lock);
741 monitor_qmp_cleanup_req_queue_locked(mon);
742 g_queue_free(mon->qmp.qmp_requests);
745 char *qmp_human_monitor_command(const char *command_line, bool has_cpu_index,
746 int64_t cpu_index, Error **errp)
749 Monitor *old_mon, hmp;
751 monitor_data_init(&hmp, true, false);
757 int ret = monitor_set_cpu(cpu_index);
760 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cpu-index",
766 handle_hmp_command(&hmp, command_line);
769 qemu_mutex_lock(&hmp.mon_lock);
770 if (qstring_get_length(hmp.outbuf) > 0) {
771 output = g_strdup(qstring_get_str(hmp.outbuf));
773 output = g_strdup("");
775 qemu_mutex_unlock(&hmp.mon_lock);
778 monitor_data_destroy(&hmp);
782 static int compare_cmd(const char *name, const char *list)
784 const char *p, *pstart;
790 p = qemu_strchrnul(p, '|');
791 if ((p - pstart) == len && !memcmp(pstart, name, len))
800 static int get_str(char *buf, int buf_size, const char **pp)
808 while (qemu_isspace(*p)) {
819 while (*p != '\0' && *p != '\"') {
835 printf("unsupported escape code: '\\%c'\n", c);
838 if ((q - buf) < buf_size - 1) {
842 if ((q - buf) < buf_size - 1) {
849 printf("unterminated string\n");
854 while (*p != '\0' && !qemu_isspace(*p)) {
855 if ((q - buf) < buf_size - 1) {
868 static void free_cmdline_args(char **args, int nb_args)
872 assert(nb_args <= MAX_ARGS);
874 for (i = 0; i < nb_args; i++) {
881 * Parse the command line to get valid args.
882 * @cmdline: command line to be parsed.
883 * @pnb_args: location to store the number of args, must NOT be NULL.
884 * @args: location to store the args, which should be freed by caller, must
887 * Returns 0 on success, negative on failure.
889 * NOTE: this parser is an approximate form of the real command parser. Number
890 * of args have a limit of MAX_ARGS. If cmdline contains more, it will
891 * return with failure.
893 static int parse_cmdline(const char *cmdline,
894 int *pnb_args, char **args)
903 while (qemu_isspace(*p)) {
909 if (nb_args >= MAX_ARGS) {
912 ret = get_str(buf, sizeof(buf), &p);
916 args[nb_args] = g_strdup(buf);
923 free_cmdline_args(args, nb_args);
928 * Can command @cmd be executed in preconfig state?
930 static bool cmd_can_preconfig(const mon_cmd_t *cmd)
936 return strchr(cmd->flags, 'p');
939 static void help_cmd_dump_one(Monitor *mon,
940 const mon_cmd_t *cmd,
946 if (runstate_check(RUN_STATE_PRECONFIG) && !cmd_can_preconfig(cmd)) {
950 for (i = 0; i < prefix_args_nb; i++) {
951 monitor_printf(mon, "%s ", prefix_args[i]);
953 monitor_printf(mon, "%s %s -- %s\n", cmd->name, cmd->params, cmd->help);
956 /* @args[@arg_index] is the valid command need to find in @cmds */
957 static void help_cmd_dump(Monitor *mon, const mon_cmd_t *cmds,
958 char **args, int nb_args, int arg_index)
960 const mon_cmd_t *cmd;
963 /* No valid arg need to compare with, dump all in *cmds */
964 if (arg_index >= nb_args) {
965 for (cmd = cmds; cmd->name != NULL; cmd++) {
966 help_cmd_dump_one(mon, cmd, args, arg_index);
971 /* Find one entry to dump */
972 for (cmd = cmds; cmd->name != NULL; cmd++) {
973 if (compare_cmd(args[arg_index], cmd->name) &&
974 ((!runstate_check(RUN_STATE_PRECONFIG) ||
975 cmd_can_preconfig(cmd)))) {
976 if (cmd->sub_table) {
977 /* continue with next arg */
978 help_cmd_dump(mon, cmd->sub_table,
979 args, nb_args, arg_index + 1);
981 help_cmd_dump_one(mon, cmd, args, arg_index);
987 /* Command not found */
988 monitor_printf(mon, "unknown command: '");
989 for (i = 0; i <= arg_index; i++) {
990 monitor_printf(mon, "%s%s", args[i], i == arg_index ? "'\n" : " ");
994 static void help_cmd(Monitor *mon, const char *name)
996 char *args[MAX_ARGS];
999 /* 1. parse user input */
1001 /* special case for log, directly dump and return */
1002 if (!strcmp(name, "log")) {
1003 const QEMULogItem *item;
1004 monitor_printf(mon, "Log items (comma separated):\n");
1005 monitor_printf(mon, "%-10s %s\n", "none", "remove all logs");
1006 for (item = qemu_log_items; item->mask != 0; item++) {
1007 monitor_printf(mon, "%-10s %s\n", item->name, item->help);
1012 if (parse_cmdline(name, &nb_args, args) < 0) {
1017 /* 2. dump the contents according to parsed args */
1018 help_cmd_dump(mon, mon->cmd_table, args, nb_args, 0);
1020 free_cmdline_args(args, nb_args);
1023 static void do_help_cmd(Monitor *mon, const QDict *qdict)
1025 help_cmd(mon, qdict_get_try_str(qdict, "name"));
1028 static void hmp_trace_event(Monitor *mon, const QDict *qdict)
1030 const char *tp_name = qdict_get_str(qdict, "name");
1031 bool new_state = qdict_get_bool(qdict, "option");
1032 bool has_vcpu = qdict_haskey(qdict, "vcpu");
1033 int vcpu = qdict_get_try_int(qdict, "vcpu", 0);
1034 Error *local_err = NULL;
1037 monitor_printf(mon, "argument vcpu must be positive");
1041 qmp_trace_event_set_state(tp_name, new_state, true, true, has_vcpu, vcpu, &local_err);
1043 error_report_err(local_err);
1047 #ifdef CONFIG_TRACE_SIMPLE
1048 static void hmp_trace_file(Monitor *mon, const QDict *qdict)
1050 const char *op = qdict_get_try_str(qdict, "op");
1051 const char *arg = qdict_get_try_str(qdict, "arg");
1054 st_print_trace_file_status((FILE *)mon, &monitor_fprintf);
1055 } else if (!strcmp(op, "on")) {
1056 st_set_trace_file_enabled(true);
1057 } else if (!strcmp(op, "off")) {
1058 st_set_trace_file_enabled(false);
1059 } else if (!strcmp(op, "flush")) {
1060 st_flush_trace_buffer();
1061 } else if (!strcmp(op, "set")) {
1063 st_set_trace_file(arg);
1066 monitor_printf(mon, "unexpected argument \"%s\"\n", op);
1067 help_cmd(mon, "trace-file");
1072 static void hmp_info_help(Monitor *mon, const QDict *qdict)
1074 help_cmd(mon, "info");
1077 static void query_commands_cb(QmpCommand *cmd, void *opaque)
1079 CommandInfoList *info, **list = opaque;
1081 if (!cmd->enabled) {
1085 info = g_malloc0(sizeof(*info));
1086 info->value = g_malloc0(sizeof(*info->value));
1087 info->value->name = g_strdup(cmd->name);
1092 CommandInfoList *qmp_query_commands(Error **errp)
1094 CommandInfoList *list = NULL;
1096 qmp_for_each_command(cur_mon->qmp.commands, query_commands_cb, &list);
1101 EventInfoList *qmp_query_events(Error **errp)
1104 * TODO This deprecated command is the only user of
1105 * QAPIEvent_str() and QAPIEvent_lookup[]. When the command goes,
1106 * they should go, too.
1108 EventInfoList *info, *ev_list = NULL;
1111 for (e = 0 ; e < QAPI_EVENT__MAX ; e++) {
1112 const char *event_name = QAPIEvent_str(e);
1113 assert(event_name != NULL);
1114 info = g_malloc0(sizeof(*info));
1115 info->value = g_malloc0(sizeof(*info->value));
1116 info->value->name = g_strdup(event_name);
1118 info->next = ev_list;
1126 * Minor hack: generated marshalling suppressed for this command
1127 * ('gen': false in the schema) so we can parse the JSON string
1128 * directly into QObject instead of first parsing it with
1129 * visit_type_SchemaInfoList() into a SchemaInfoList, then marshal it
1130 * to QObject with generated output marshallers, every time. Instead,
1131 * we do it in test-qobject-input-visitor.c, just to make sure
1132 * qapi-gen.py's output actually conforms to the schema.
1134 static void qmp_query_qmp_schema(QDict *qdict, QObject **ret_data,
1137 *ret_data = qobject_from_qlit(&qmp_schema_qlit);
1140 static void monitor_init_qmp_commands(void)
1143 * Two command lists:
1144 * - qmp_commands contains all QMP commands
1145 * - qmp_cap_negotiation_commands contains just
1146 * "qmp_capabilities", to enforce capability negotiation
1149 qmp_init_marshal(&qmp_commands);
1151 qmp_register_command(&qmp_commands, "query-qmp-schema",
1152 qmp_query_qmp_schema, QCO_ALLOW_PRECONFIG);
1153 qmp_register_command(&qmp_commands, "device_add", qmp_device_add,
1155 qmp_register_command(&qmp_commands, "netdev_add", qmp_netdev_add,
1158 QTAILQ_INIT(&qmp_cap_negotiation_commands);
1159 qmp_register_command(&qmp_cap_negotiation_commands, "qmp_capabilities",
1160 qmp_marshal_qmp_capabilities, QCO_ALLOW_PRECONFIG);
1163 static bool qmp_oob_enabled(Monitor *mon)
1165 return mon->qmp.capab[QMP_CAPABILITY_OOB];
1168 static void monitor_qmp_caps_reset(Monitor *mon)
1170 memset(mon->qmp.capab_offered, 0, sizeof(mon->qmp.capab_offered));
1171 memset(mon->qmp.capab, 0, sizeof(mon->qmp.capab));
1172 mon->qmp.capab_offered[QMP_CAPABILITY_OOB] = mon->use_io_thread;
1176 * Accept QMP capabilities in @list for @mon.
1177 * On success, set mon->qmp.capab[], and return true.
1178 * On error, set @errp, and return false.
1180 static bool qmp_caps_accept(Monitor *mon, QMPCapabilityList *list,
1183 GString *unavailable = NULL;
1184 bool capab[QMP_CAPABILITY__MAX];
1186 memset(capab, 0, sizeof(capab));
1188 for (; list; list = list->next) {
1189 if (!mon->qmp.capab_offered[list->value]) {
1191 unavailable = g_string_new(QMPCapability_str(list->value));
1193 g_string_append_printf(unavailable, ", %s",
1194 QMPCapability_str(list->value));
1197 capab[list->value] = true;
1201 error_setg(errp, "Capability %s not available", unavailable->str);
1202 g_string_free(unavailable, true);
1206 memcpy(mon->qmp.capab, capab, sizeof(capab));
1210 void qmp_qmp_capabilities(bool has_enable, QMPCapabilityList *enable,
1213 if (cur_mon->qmp.commands == &qmp_commands) {
1214 error_set(errp, ERROR_CLASS_COMMAND_NOT_FOUND,
1215 "Capabilities negotiation is already complete, command "
1220 if (!qmp_caps_accept(cur_mon, enable, errp)) {
1224 cur_mon->qmp.commands = &qmp_commands;
1227 /* Set the current CPU defined by the user. Callers must hold BQL. */
1228 int monitor_set_cpu(int cpu_index)
1232 cpu = qemu_get_cpu(cpu_index);
1236 g_free(cur_mon->mon_cpu_path);
1237 cur_mon->mon_cpu_path = object_get_canonical_path(OBJECT(cpu));
1241 /* Callers must hold BQL. */
1242 static CPUState *mon_get_cpu_sync(bool synchronize)
1246 if (cur_mon->mon_cpu_path) {
1247 cpu = (CPUState *) object_resolve_path_type(cur_mon->mon_cpu_path,
1250 g_free(cur_mon->mon_cpu_path);
1251 cur_mon->mon_cpu_path = NULL;
1254 if (!cur_mon->mon_cpu_path) {
1258 monitor_set_cpu(first_cpu->cpu_index);
1262 cpu_synchronize_state(cpu);
1267 CPUState *mon_get_cpu(void)
1269 return mon_get_cpu_sync(true);
1272 CPUArchState *mon_get_cpu_env(void)
1274 CPUState *cs = mon_get_cpu();
1276 return cs ? cs->env_ptr : NULL;
1279 int monitor_get_cpu_index(void)
1281 CPUState *cs = mon_get_cpu_sync(false);
1283 return cs ? cs->cpu_index : UNASSIGNED_CPU_INDEX;
1286 static void hmp_info_registers(Monitor *mon, const QDict *qdict)
1288 bool all_cpus = qdict_get_try_bool(qdict, "cpustate_all", false);
1293 monitor_printf(mon, "\nCPU#%d\n", cs->cpu_index);
1294 cpu_dump_state(cs, (FILE *)mon, monitor_fprintf, CPU_DUMP_FPU);
1300 monitor_printf(mon, "No CPU available\n");
1304 cpu_dump_state(cs, (FILE *)mon, monitor_fprintf, CPU_DUMP_FPU);
1309 static void hmp_info_jit(Monitor *mon, const QDict *qdict)
1311 if (!tcg_enabled()) {
1312 error_report("JIT information is only available with accel=tcg");
1316 dump_exec_info((FILE *)mon, monitor_fprintf);
1317 dump_drift_info((FILE *)mon, monitor_fprintf);
1320 static void hmp_info_opcount(Monitor *mon, const QDict *qdict)
1322 dump_opcount_info((FILE *)mon, monitor_fprintf);
1326 static void hmp_info_sync_profile(Monitor *mon, const QDict *qdict)
1328 int64_t max = qdict_get_try_int(qdict, "max", 10);
1329 bool mean = qdict_get_try_bool(qdict, "mean", false);
1330 bool coalesce = !qdict_get_try_bool(qdict, "no_coalesce", false);
1331 enum QSPSortBy sort_by;
1333 sort_by = mean ? QSP_SORT_BY_AVG_WAIT_TIME : QSP_SORT_BY_TOTAL_WAIT_TIME;
1334 qsp_report((FILE *)mon, monitor_fprintf, max, sort_by, coalesce);
1337 static void hmp_info_history(Monitor *mon, const QDict *qdict)
1346 str = readline_get_history(mon->rs, i);
1349 monitor_printf(mon, "%d: '%s'\n", i, str);
1354 static void hmp_info_cpustats(Monitor *mon, const QDict *qdict)
1356 CPUState *cs = mon_get_cpu();
1359 monitor_printf(mon, "No CPU available\n");
1362 cpu_dump_statistics(cs, (FILE *)mon, &monitor_fprintf, 0);
1365 static void hmp_info_trace_events(Monitor *mon, const QDict *qdict)
1367 const char *name = qdict_get_try_str(qdict, "name");
1368 bool has_vcpu = qdict_haskey(qdict, "vcpu");
1369 int vcpu = qdict_get_try_int(qdict, "vcpu", 0);
1370 TraceEventInfoList *events;
1371 TraceEventInfoList *elem;
1372 Error *local_err = NULL;
1378 monitor_printf(mon, "argument vcpu must be positive");
1382 events = qmp_trace_event_get_state(name, has_vcpu, vcpu, &local_err);
1384 error_report_err(local_err);
1388 for (elem = events; elem != NULL; elem = elem->next) {
1389 monitor_printf(mon, "%s : state %u\n",
1391 elem->value->state == TRACE_EVENT_STATE_ENABLED ? 1 : 0);
1393 qapi_free_TraceEventInfoList(events);
1396 void qmp_client_migrate_info(const char *protocol, const char *hostname,
1397 bool has_port, int64_t port,
1398 bool has_tls_port, int64_t tls_port,
1399 bool has_cert_subject, const char *cert_subject,
1402 if (strcmp(protocol, "spice") == 0) {
1403 if (!qemu_using_spice(errp)) {
1407 if (!has_port && !has_tls_port) {
1408 error_setg(errp, QERR_MISSING_PARAMETER, "port/tls-port");
1412 if (qemu_spice_migrate_info(hostname,
1413 has_port ? port : -1,
1414 has_tls_port ? tls_port : -1,
1416 error_setg(errp, QERR_UNDEFINED_ERROR);
1422 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "protocol", "spice");
1425 static void hmp_logfile(Monitor *mon, const QDict *qdict)
1429 qemu_set_log_filename(qdict_get_str(qdict, "filename"), &err);
1431 error_report_err(err);
1435 static void hmp_log(Monitor *mon, const QDict *qdict)
1438 const char *items = qdict_get_str(qdict, "items");
1440 if (!strcmp(items, "none")) {
1443 mask = qemu_str_to_log_mask(items);
1445 help_cmd(mon, "log");
1452 static void hmp_singlestep(Monitor *mon, const QDict *qdict)
1454 const char *option = qdict_get_try_str(qdict, "option");
1455 if (!option || !strcmp(option, "on")) {
1457 } else if (!strcmp(option, "off")) {
1460 monitor_printf(mon, "unexpected option %s\n", option);
1464 static void hmp_gdbserver(Monitor *mon, const QDict *qdict)
1466 const char *device = qdict_get_try_str(qdict, "device");
1468 device = "tcp::" DEFAULT_GDBSTUB_PORT;
1469 if (gdbserver_start(device) < 0) {
1470 monitor_printf(mon, "Could not open gdbserver on device '%s'\n",
1472 } else if (strcmp(device, "none") == 0) {
1473 monitor_printf(mon, "Disabled gdbserver\n");
1475 monitor_printf(mon, "Waiting for gdb connection on device '%s'\n",
1480 static void hmp_watchdog_action(Monitor *mon, const QDict *qdict)
1482 const char *action = qdict_get_str(qdict, "action");
1483 if (select_watchdog_action(action) == -1) {
1484 monitor_printf(mon, "Unknown watchdog action '%s'\n", action);
1488 static void monitor_printc(Monitor *mon, int c)
1490 monitor_printf(mon, "'");
1493 monitor_printf(mon, "\\'");
1496 monitor_printf(mon, "\\\\");
1499 monitor_printf(mon, "\\n");
1502 monitor_printf(mon, "\\r");
1505 if (c >= 32 && c <= 126) {
1506 monitor_printf(mon, "%c", c);
1508 monitor_printf(mon, "\\x%02x", c);
1512 monitor_printf(mon, "'");
1515 static void memory_dump(Monitor *mon, int count, int format, int wsize,
1516 hwaddr addr, int is_physical)
1518 int l, line_size, i, max_digits, len;
1521 CPUState *cs = mon_get_cpu();
1523 if (!cs && (format == 'i' || !is_physical)) {
1524 monitor_printf(mon, "Can not dump without CPU\n");
1528 if (format == 'i') {
1529 monitor_disas(mon, cs, addr, count, is_physical);
1533 len = wsize * count;
1542 max_digits = DIV_ROUND_UP(wsize * 8, 3);
1546 max_digits = (wsize * 8) / 4;
1550 max_digits = DIV_ROUND_UP(wsize * 8 * 10, 33);
1559 monitor_printf(mon, TARGET_FMT_plx ":", addr);
1561 monitor_printf(mon, TARGET_FMT_lx ":", (target_ulong)addr);
1566 AddressSpace *as = cs ? cs->as : &address_space_memory;
1567 MemTxResult r = address_space_read(as, addr,
1568 MEMTXATTRS_UNSPECIFIED, buf, l);
1569 if (r != MEMTX_OK) {
1570 monitor_printf(mon, " Cannot access memory\n");
1574 if (cpu_memory_rw_debug(cs, addr, buf, l, 0) < 0) {
1575 monitor_printf(mon, " Cannot access memory\n");
1584 v = ldub_p(buf + i);
1587 v = lduw_p(buf + i);
1590 v = (uint32_t)ldl_p(buf + i);
1596 monitor_printf(mon, " ");
1599 monitor_printf(mon, "%#*" PRIo64, max_digits, v);
1602 monitor_printf(mon, "0x%0*" PRIx64, max_digits, v);
1605 monitor_printf(mon, "%*" PRIu64, max_digits, v);
1608 monitor_printf(mon, "%*" PRId64, max_digits, v);
1611 monitor_printc(mon, v);
1616 monitor_printf(mon, "\n");
1622 static void hmp_memory_dump(Monitor *mon, const QDict *qdict)
1624 int count = qdict_get_int(qdict, "count");
1625 int format = qdict_get_int(qdict, "format");
1626 int size = qdict_get_int(qdict, "size");
1627 target_long addr = qdict_get_int(qdict, "addr");
1629 memory_dump(mon, count, format, size, addr, 0);
1632 static void hmp_physical_memory_dump(Monitor *mon, const QDict *qdict)
1634 int count = qdict_get_int(qdict, "count");
1635 int format = qdict_get_int(qdict, "format");
1636 int size = qdict_get_int(qdict, "size");
1637 hwaddr addr = qdict_get_int(qdict, "addr");
1639 memory_dump(mon, count, format, size, addr, 1);
1642 static void *gpa2hva(MemoryRegion **p_mr, hwaddr addr, Error **errp)
1644 MemoryRegionSection mrs = memory_region_find(get_system_memory(),
1648 error_setg(errp, "No memory is mapped at address 0x%" HWADDR_PRIx, addr);
1652 if (!memory_region_is_ram(mrs.mr) && !memory_region_is_romd(mrs.mr)) {
1653 error_setg(errp, "Memory at address 0x%" HWADDR_PRIx "is not RAM", addr);
1654 memory_region_unref(mrs.mr);
1659 return qemu_map_ram_ptr(mrs.mr->ram_block, mrs.offset_within_region);
1662 static void hmp_gpa2hva(Monitor *mon, const QDict *qdict)
1664 hwaddr addr = qdict_get_int(qdict, "addr");
1665 Error *local_err = NULL;
1666 MemoryRegion *mr = NULL;
1669 ptr = gpa2hva(&mr, addr, &local_err);
1671 error_report_err(local_err);
1675 monitor_printf(mon, "Host virtual address for 0x%" HWADDR_PRIx
1677 addr, mr->name, ptr);
1679 memory_region_unref(mr);
1683 static uint64_t vtop(void *ptr, Error **errp)
1687 uintptr_t addr = (uintptr_t) ptr;
1688 uintptr_t pagesize = getpagesize();
1689 off_t offset = addr / pagesize * sizeof(pinfo);
1692 fd = open("/proc/self/pagemap", O_RDONLY);
1694 error_setg_errno(errp, errno, "Cannot open /proc/self/pagemap");
1698 /* Force copy-on-write if necessary. */
1699 atomic_add((uint8_t *)ptr, 0);
1701 if (pread(fd, &pinfo, sizeof(pinfo), offset) != sizeof(pinfo)) {
1702 error_setg_errno(errp, errno, "Cannot read pagemap");
1705 if ((pinfo & (1ull << 63)) == 0) {
1706 error_setg(errp, "Page not present");
1709 ret = ((pinfo & 0x007fffffffffffffull) * pagesize) | (addr & (pagesize - 1));
1716 static void hmp_gpa2hpa(Monitor *mon, const QDict *qdict)
1718 hwaddr addr = qdict_get_int(qdict, "addr");
1719 Error *local_err = NULL;
1720 MemoryRegion *mr = NULL;
1724 ptr = gpa2hva(&mr, addr, &local_err);
1726 error_report_err(local_err);
1730 physaddr = vtop(ptr, &local_err);
1732 error_report_err(local_err);
1734 monitor_printf(mon, "Host physical address for 0x%" HWADDR_PRIx
1735 " (%s) is 0x%" PRIx64 "\n",
1736 addr, mr->name, (uint64_t) physaddr);
1739 memory_region_unref(mr);
1743 static void do_print(Monitor *mon, const QDict *qdict)
1745 int format = qdict_get_int(qdict, "format");
1746 hwaddr val = qdict_get_int(qdict, "val");
1750 monitor_printf(mon, "%#" HWADDR_PRIo, val);
1753 monitor_printf(mon, "%#" HWADDR_PRIx, val);
1756 monitor_printf(mon, "%" HWADDR_PRIu, val);
1760 monitor_printf(mon, "%" HWADDR_PRId, val);
1763 monitor_printc(mon, val);
1766 monitor_printf(mon, "\n");
1769 static void hmp_sum(Monitor *mon, const QDict *qdict)
1773 uint32_t start = qdict_get_int(qdict, "start");
1774 uint32_t size = qdict_get_int(qdict, "size");
1777 for(addr = start; addr < (start + size); addr++) {
1778 uint8_t val = address_space_ldub(&address_space_memory, addr,
1779 MEMTXATTRS_UNSPECIFIED, NULL);
1780 /* BSD sum algorithm ('sum' Unix command) */
1781 sum = (sum >> 1) | (sum << 15);
1784 monitor_printf(mon, "%05d\n", sum);
1787 static int mouse_button_state;
1789 static void hmp_mouse_move(Monitor *mon, const QDict *qdict)
1791 int dx, dy, dz, button;
1792 const char *dx_str = qdict_get_str(qdict, "dx_str");
1793 const char *dy_str = qdict_get_str(qdict, "dy_str");
1794 const char *dz_str = qdict_get_try_str(qdict, "dz_str");
1796 dx = strtol(dx_str, NULL, 0);
1797 dy = strtol(dy_str, NULL, 0);
1798 qemu_input_queue_rel(NULL, INPUT_AXIS_X, dx);
1799 qemu_input_queue_rel(NULL, INPUT_AXIS_Y, dy);
1802 dz = strtol(dz_str, NULL, 0);
1804 button = (dz > 0) ? INPUT_BUTTON_WHEEL_UP : INPUT_BUTTON_WHEEL_DOWN;
1805 qemu_input_queue_btn(NULL, button, true);
1806 qemu_input_event_sync();
1807 qemu_input_queue_btn(NULL, button, false);
1810 qemu_input_event_sync();
1813 static void hmp_mouse_button(Monitor *mon, const QDict *qdict)
1815 static uint32_t bmap[INPUT_BUTTON__MAX] = {
1816 [INPUT_BUTTON_LEFT] = MOUSE_EVENT_LBUTTON,
1817 [INPUT_BUTTON_MIDDLE] = MOUSE_EVENT_MBUTTON,
1818 [INPUT_BUTTON_RIGHT] = MOUSE_EVENT_RBUTTON,
1820 int button_state = qdict_get_int(qdict, "button_state");
1822 if (mouse_button_state == button_state) {
1825 qemu_input_update_buttons(NULL, bmap, mouse_button_state, button_state);
1826 qemu_input_event_sync();
1827 mouse_button_state = button_state;
1830 static void hmp_ioport_read(Monitor *mon, const QDict *qdict)
1832 int size = qdict_get_int(qdict, "size");
1833 int addr = qdict_get_int(qdict, "addr");
1834 int has_index = qdict_haskey(qdict, "index");
1839 int index = qdict_get_int(qdict, "index");
1840 cpu_outb(addr & IOPORTS_MASK, index & 0xff);
1848 val = cpu_inb(addr);
1852 val = cpu_inw(addr);
1856 val = cpu_inl(addr);
1860 monitor_printf(mon, "port%c[0x%04x] = %#0*x\n",
1861 suffix, addr, size * 2, val);
1864 static void hmp_ioport_write(Monitor *mon, const QDict *qdict)
1866 int size = qdict_get_int(qdict, "size");
1867 int addr = qdict_get_int(qdict, "addr");
1868 int val = qdict_get_int(qdict, "val");
1870 addr &= IOPORTS_MASK;
1875 cpu_outb(addr, val);
1878 cpu_outw(addr, val);
1881 cpu_outl(addr, val);
1886 static void hmp_boot_set(Monitor *mon, const QDict *qdict)
1888 Error *local_err = NULL;
1889 const char *bootdevice = qdict_get_str(qdict, "bootdevice");
1891 qemu_boot_set(bootdevice, &local_err);
1893 error_report_err(local_err);
1895 monitor_printf(mon, "boot device list now set to %s\n", bootdevice);
1899 static void hmp_info_mtree(Monitor *mon, const QDict *qdict)
1901 bool flatview = qdict_get_try_bool(qdict, "flatview", false);
1902 bool dispatch_tree = qdict_get_try_bool(qdict, "dispatch_tree", false);
1903 bool owner = qdict_get_try_bool(qdict, "owner", false);
1905 mtree_info((fprintf_function)monitor_printf, mon, flatview, dispatch_tree,
1909 static void hmp_info_numa(Monitor *mon, const QDict *qdict)
1912 NumaNodeMem *node_mem;
1913 CpuInfoList *cpu_list, *cpu;
1915 cpu_list = qmp_query_cpus(&error_abort);
1916 node_mem = g_new0(NumaNodeMem, nb_numa_nodes);
1918 query_numa_node_mem(node_mem);
1919 monitor_printf(mon, "%d nodes\n", nb_numa_nodes);
1920 for (i = 0; i < nb_numa_nodes; i++) {
1921 monitor_printf(mon, "node %d cpus:", i);
1922 for (cpu = cpu_list; cpu; cpu = cpu->next) {
1923 if (cpu->value->has_props && cpu->value->props->has_node_id &&
1924 cpu->value->props->node_id == i) {
1925 monitor_printf(mon, " %" PRIi64, cpu->value->CPU);
1928 monitor_printf(mon, "\n");
1929 monitor_printf(mon, "node %d size: %" PRId64 " MB\n", i,
1930 node_mem[i].node_mem >> 20);
1931 monitor_printf(mon, "node %d plugged: %" PRId64 " MB\n", i,
1932 node_mem[i].node_plugged_mem >> 20);
1934 qapi_free_CpuInfoList(cpu_list);
1938 #ifdef CONFIG_PROFILER
1942 static void hmp_info_profile(Monitor *mon, const QDict *qdict)
1944 static int64_t last_cpu_exec_time;
1945 int64_t cpu_exec_time;
1948 cpu_exec_time = tcg_cpu_exec_time();
1949 delta = cpu_exec_time - last_cpu_exec_time;
1951 monitor_printf(mon, "async time %" PRId64 " (%0.3f)\n",
1952 dev_time, dev_time / (double)NANOSECONDS_PER_SECOND);
1953 monitor_printf(mon, "qemu time %" PRId64 " (%0.3f)\n",
1954 delta, delta / (double)NANOSECONDS_PER_SECOND);
1955 last_cpu_exec_time = cpu_exec_time;
1959 static void hmp_info_profile(Monitor *mon, const QDict *qdict)
1961 monitor_printf(mon, "Internal profiler not compiled\n");
1965 /* Capture support */
1966 static QLIST_HEAD (capture_list_head, CaptureState) capture_head;
1968 static void hmp_info_capture(Monitor *mon, const QDict *qdict)
1973 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
1974 monitor_printf(mon, "[%d]: ", i);
1975 s->ops.info (s->opaque);
1979 static void hmp_stopcapture(Monitor *mon, const QDict *qdict)
1982 int n = qdict_get_int(qdict, "n");
1985 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
1987 s->ops.destroy (s->opaque);
1988 QLIST_REMOVE (s, entries);
1995 static void hmp_wavcapture(Monitor *mon, const QDict *qdict)
1997 const char *path = qdict_get_str(qdict, "path");
1998 int has_freq = qdict_haskey(qdict, "freq");
1999 int freq = qdict_get_try_int(qdict, "freq", -1);
2000 int has_bits = qdict_haskey(qdict, "bits");
2001 int bits = qdict_get_try_int(qdict, "bits", -1);
2002 int has_channels = qdict_haskey(qdict, "nchannels");
2003 int nchannels = qdict_get_try_int(qdict, "nchannels", -1);
2006 s = g_malloc0 (sizeof (*s));
2008 freq = has_freq ? freq : 44100;
2009 bits = has_bits ? bits : 16;
2010 nchannels = has_channels ? nchannels : 2;
2012 if (wav_start_capture (s, path, freq, bits, nchannels)) {
2013 monitor_printf(mon, "Failed to add wave capture\n");
2017 QLIST_INSERT_HEAD (&capture_head, s, entries);
2020 static QAuthZList *find_auth(Monitor *mon, const char *name)
2025 container = object_get_objects_root();
2026 obj = object_resolve_path_component(container, name);
2028 monitor_printf(mon, "acl: unknown list '%s'\n", name);
2032 return QAUTHZ_LIST(obj);
2035 static void hmp_acl_show(Monitor *mon, const QDict *qdict)
2037 const char *aclname = qdict_get_str(qdict, "aclname");
2038 QAuthZList *auth = find_auth(mon, aclname);
2039 QAuthZListRuleList *rules;
2046 monitor_printf(mon, "policy: %s\n",
2047 QAuthZListPolicy_str(auth->policy));
2049 rules = auth->rules;
2051 QAuthZListRule *rule = rules->value;
2053 monitor_printf(mon, "%zu: %s %s\n", i,
2054 QAuthZListPolicy_str(rule->policy),
2056 rules = rules->next;
2060 static void hmp_acl_reset(Monitor *mon, const QDict *qdict)
2062 const char *aclname = qdict_get_str(qdict, "aclname");
2063 QAuthZList *auth = find_auth(mon, aclname);
2069 auth->policy = QAUTHZ_LIST_POLICY_DENY;
2070 qapi_free_QAuthZListRuleList(auth->rules);
2072 monitor_printf(mon, "acl: removed all rules\n");
2075 static void hmp_acl_policy(Monitor *mon, const QDict *qdict)
2077 const char *aclname = qdict_get_str(qdict, "aclname");
2078 const char *policy = qdict_get_str(qdict, "policy");
2079 QAuthZList *auth = find_auth(mon, aclname);
2087 val = qapi_enum_parse(&QAuthZListPolicy_lookup,
2089 QAUTHZ_LIST_POLICY_DENY,
2093 monitor_printf(mon, "acl: unknown policy '%s', "
2094 "expected 'deny' or 'allow'\n", policy);
2097 if (auth->policy == QAUTHZ_LIST_POLICY_ALLOW) {
2098 monitor_printf(mon, "acl: policy set to 'allow'\n");
2100 monitor_printf(mon, "acl: policy set to 'deny'\n");
2105 static QAuthZListFormat hmp_acl_get_format(const char *match)
2107 if (strchr(match, '*')) {
2108 return QAUTHZ_LIST_FORMAT_GLOB;
2110 return QAUTHZ_LIST_FORMAT_EXACT;
2114 static void hmp_acl_add(Monitor *mon, const QDict *qdict)
2116 const char *aclname = qdict_get_str(qdict, "aclname");
2117 const char *match = qdict_get_str(qdict, "match");
2118 const char *policystr = qdict_get_str(qdict, "policy");
2119 int has_index = qdict_haskey(qdict, "index");
2120 int index = qdict_get_try_int(qdict, "index", -1);
2121 QAuthZList *auth = find_auth(mon, aclname);
2123 QAuthZListPolicy policy;
2124 QAuthZListFormat format;
2131 policy = qapi_enum_parse(&QAuthZListPolicy_lookup,
2133 QAUTHZ_LIST_POLICY_DENY,
2137 monitor_printf(mon, "acl: unknown policy '%s', "
2138 "expected 'deny' or 'allow'\n", policystr);
2142 format = hmp_acl_get_format(match);
2144 if (has_index && index == 0) {
2145 monitor_printf(mon, "acl: unable to add acl entry\n");
2150 i = qauthz_list_insert_rule(auth, match, policy,
2151 format, index - 1, &err);
2153 i = qauthz_list_append_rule(auth, match, policy,
2157 monitor_printf(mon, "acl: unable to add rule: %s",
2158 error_get_pretty(err));
2161 monitor_printf(mon, "acl: added rule at position %zu\n", i + 1);
2165 static void hmp_acl_remove(Monitor *mon, const QDict *qdict)
2167 const char *aclname = qdict_get_str(qdict, "aclname");
2168 const char *match = qdict_get_str(qdict, "match");
2169 QAuthZList *auth = find_auth(mon, aclname);
2176 i = qauthz_list_delete_rule(auth, match);
2178 monitor_printf(mon, "acl: removed rule at position %zu\n", i + 1);
2180 monitor_printf(mon, "acl: no matching acl entry\n");
2184 void qmp_getfd(const char *fdname, Error **errp)
2189 fd = qemu_chr_fe_get_msgfd(&cur_mon->chr);
2191 error_setg(errp, QERR_FD_NOT_SUPPLIED);
2195 if (qemu_isdigit(fdname[0])) {
2197 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "fdname",
2198 "a name not starting with a digit");
2202 qemu_mutex_lock(&cur_mon->mon_lock);
2203 QLIST_FOREACH(monfd, &cur_mon->fds, next) {
2204 if (strcmp(monfd->name, fdname) != 0) {
2210 qemu_mutex_unlock(&cur_mon->mon_lock);
2211 /* Make sure close() is outside critical section */
2216 monfd = g_malloc0(sizeof(mon_fd_t));
2217 monfd->name = g_strdup(fdname);
2220 QLIST_INSERT_HEAD(&cur_mon->fds, monfd, next);
2221 qemu_mutex_unlock(&cur_mon->mon_lock);
2224 void qmp_closefd(const char *fdname, Error **errp)
2229 qemu_mutex_lock(&cur_mon->mon_lock);
2230 QLIST_FOREACH(monfd, &cur_mon->fds, next) {
2231 if (strcmp(monfd->name, fdname) != 0) {
2235 QLIST_REMOVE(monfd, next);
2237 g_free(monfd->name);
2239 qemu_mutex_unlock(&cur_mon->mon_lock);
2240 /* Make sure close() is outside critical section */
2245 qemu_mutex_unlock(&cur_mon->mon_lock);
2246 error_setg(errp, QERR_FD_NOT_FOUND, fdname);
2249 int monitor_get_fd(Monitor *mon, const char *fdname, Error **errp)
2253 qemu_mutex_lock(&mon->mon_lock);
2254 QLIST_FOREACH(monfd, &mon->fds, next) {
2257 if (strcmp(monfd->name, fdname) != 0) {
2263 /* caller takes ownership of fd */
2264 QLIST_REMOVE(monfd, next);
2265 g_free(monfd->name);
2267 qemu_mutex_unlock(&mon->mon_lock);
2272 qemu_mutex_unlock(&mon->mon_lock);
2273 error_setg(errp, "File descriptor named '%s' has not been found", fdname);
2277 static void monitor_fdset_cleanup(MonFdset *mon_fdset)
2279 MonFdsetFd *mon_fdset_fd;
2280 MonFdsetFd *mon_fdset_fd_next;
2282 QLIST_FOREACH_SAFE(mon_fdset_fd, &mon_fdset->fds, next, mon_fdset_fd_next) {
2283 if ((mon_fdset_fd->removed ||
2284 (QLIST_EMPTY(&mon_fdset->dup_fds) && mon_refcount == 0)) &&
2285 runstate_is_running()) {
2286 close(mon_fdset_fd->fd);
2287 g_free(mon_fdset_fd->opaque);
2288 QLIST_REMOVE(mon_fdset_fd, next);
2289 g_free(mon_fdset_fd);
2293 if (QLIST_EMPTY(&mon_fdset->fds) && QLIST_EMPTY(&mon_fdset->dup_fds)) {
2294 QLIST_REMOVE(mon_fdset, next);
2299 static void monitor_fdsets_cleanup(void)
2301 MonFdset *mon_fdset;
2302 MonFdset *mon_fdset_next;
2304 qemu_mutex_lock(&mon_fdsets_lock);
2305 QLIST_FOREACH_SAFE(mon_fdset, &mon_fdsets, next, mon_fdset_next) {
2306 monitor_fdset_cleanup(mon_fdset);
2308 qemu_mutex_unlock(&mon_fdsets_lock);
2311 AddfdInfo *qmp_add_fd(bool has_fdset_id, int64_t fdset_id, bool has_opaque,
2312 const char *opaque, Error **errp)
2315 Monitor *mon = cur_mon;
2318 fd = qemu_chr_fe_get_msgfd(&mon->chr);
2320 error_setg(errp, QERR_FD_NOT_SUPPLIED);
2324 fdinfo = monitor_fdset_add_fd(fd, has_fdset_id, fdset_id,
2325 has_opaque, opaque, errp);
2337 void qmp_remove_fd(int64_t fdset_id, bool has_fd, int64_t fd, Error **errp)
2339 MonFdset *mon_fdset;
2340 MonFdsetFd *mon_fdset_fd;
2343 qemu_mutex_lock(&mon_fdsets_lock);
2344 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2345 if (mon_fdset->id != fdset_id) {
2348 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2350 if (mon_fdset_fd->fd != fd) {
2353 mon_fdset_fd->removed = true;
2356 mon_fdset_fd->removed = true;
2359 if (has_fd && !mon_fdset_fd) {
2362 monitor_fdset_cleanup(mon_fdset);
2363 qemu_mutex_unlock(&mon_fdsets_lock);
2368 qemu_mutex_unlock(&mon_fdsets_lock);
2370 snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64 ", fd:%" PRId64,
2373 snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64, fdset_id);
2375 error_setg(errp, QERR_FD_NOT_FOUND, fd_str);
2378 FdsetInfoList *qmp_query_fdsets(Error **errp)
2380 MonFdset *mon_fdset;
2381 MonFdsetFd *mon_fdset_fd;
2382 FdsetInfoList *fdset_list = NULL;
2384 qemu_mutex_lock(&mon_fdsets_lock);
2385 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2386 FdsetInfoList *fdset_info = g_malloc0(sizeof(*fdset_info));
2387 FdsetFdInfoList *fdsetfd_list = NULL;
2389 fdset_info->value = g_malloc0(sizeof(*fdset_info->value));
2390 fdset_info->value->fdset_id = mon_fdset->id;
2392 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2393 FdsetFdInfoList *fdsetfd_info;
2395 fdsetfd_info = g_malloc0(sizeof(*fdsetfd_info));
2396 fdsetfd_info->value = g_malloc0(sizeof(*fdsetfd_info->value));
2397 fdsetfd_info->value->fd = mon_fdset_fd->fd;
2398 if (mon_fdset_fd->opaque) {
2399 fdsetfd_info->value->has_opaque = true;
2400 fdsetfd_info->value->opaque = g_strdup(mon_fdset_fd->opaque);
2402 fdsetfd_info->value->has_opaque = false;
2405 fdsetfd_info->next = fdsetfd_list;
2406 fdsetfd_list = fdsetfd_info;
2409 fdset_info->value->fds = fdsetfd_list;
2411 fdset_info->next = fdset_list;
2412 fdset_list = fdset_info;
2414 qemu_mutex_unlock(&mon_fdsets_lock);
2419 AddfdInfo *monitor_fdset_add_fd(int fd, bool has_fdset_id, int64_t fdset_id,
2420 bool has_opaque, const char *opaque,
2423 MonFdset *mon_fdset = NULL;
2424 MonFdsetFd *mon_fdset_fd;
2427 qemu_mutex_lock(&mon_fdsets_lock);
2429 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2430 /* Break if match found or match impossible due to ordering by ID */
2431 if (fdset_id <= mon_fdset->id) {
2432 if (fdset_id < mon_fdset->id) {
2440 if (mon_fdset == NULL) {
2441 int64_t fdset_id_prev = -1;
2442 MonFdset *mon_fdset_cur = QLIST_FIRST(&mon_fdsets);
2446 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "fdset-id",
2447 "a non-negative value");
2448 qemu_mutex_unlock(&mon_fdsets_lock);
2451 /* Use specified fdset ID */
2452 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2453 mon_fdset_cur = mon_fdset;
2454 if (fdset_id < mon_fdset_cur->id) {
2459 /* Use first available fdset ID */
2460 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2461 mon_fdset_cur = mon_fdset;
2462 if (fdset_id_prev == mon_fdset_cur->id - 1) {
2463 fdset_id_prev = mon_fdset_cur->id;
2470 mon_fdset = g_malloc0(sizeof(*mon_fdset));
2472 mon_fdset->id = fdset_id;
2474 mon_fdset->id = fdset_id_prev + 1;
2477 /* The fdset list is ordered by fdset ID */
2478 if (!mon_fdset_cur) {
2479 QLIST_INSERT_HEAD(&mon_fdsets, mon_fdset, next);
2480 } else if (mon_fdset->id < mon_fdset_cur->id) {
2481 QLIST_INSERT_BEFORE(mon_fdset_cur, mon_fdset, next);
2483 QLIST_INSERT_AFTER(mon_fdset_cur, mon_fdset, next);
2487 mon_fdset_fd = g_malloc0(sizeof(*mon_fdset_fd));
2488 mon_fdset_fd->fd = fd;
2489 mon_fdset_fd->removed = false;
2491 mon_fdset_fd->opaque = g_strdup(opaque);
2493 QLIST_INSERT_HEAD(&mon_fdset->fds, mon_fdset_fd, next);
2495 fdinfo = g_malloc0(sizeof(*fdinfo));
2496 fdinfo->fdset_id = mon_fdset->id;
2497 fdinfo->fd = mon_fdset_fd->fd;
2499 qemu_mutex_unlock(&mon_fdsets_lock);
2503 int monitor_fdset_get_fd(int64_t fdset_id, int flags)
2508 MonFdset *mon_fdset;
2509 MonFdsetFd *mon_fdset_fd;
2513 qemu_mutex_lock(&mon_fdsets_lock);
2514 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2515 if (mon_fdset->id != fdset_id) {
2518 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2519 mon_fd_flags = fcntl(mon_fdset_fd->fd, F_GETFL);
2520 if (mon_fd_flags == -1) {
2525 if ((flags & O_ACCMODE) == (mon_fd_flags & O_ACCMODE)) {
2526 ret = mon_fdset_fd->fd;
2536 qemu_mutex_unlock(&mon_fdsets_lock);
2541 int monitor_fdset_dup_fd_add(int64_t fdset_id, int dup_fd)
2543 MonFdset *mon_fdset;
2544 MonFdsetFd *mon_fdset_fd_dup;
2546 qemu_mutex_lock(&mon_fdsets_lock);
2547 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2548 if (mon_fdset->id != fdset_id) {
2551 QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
2552 if (mon_fdset_fd_dup->fd == dup_fd) {
2556 mon_fdset_fd_dup = g_malloc0(sizeof(*mon_fdset_fd_dup));
2557 mon_fdset_fd_dup->fd = dup_fd;
2558 QLIST_INSERT_HEAD(&mon_fdset->dup_fds, mon_fdset_fd_dup, next);
2559 qemu_mutex_unlock(&mon_fdsets_lock);
2564 qemu_mutex_unlock(&mon_fdsets_lock);
2568 static int monitor_fdset_dup_fd_find_remove(int dup_fd, bool remove)
2570 MonFdset *mon_fdset;
2571 MonFdsetFd *mon_fdset_fd_dup;
2573 qemu_mutex_lock(&mon_fdsets_lock);
2574 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2575 QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
2576 if (mon_fdset_fd_dup->fd == dup_fd) {
2578 QLIST_REMOVE(mon_fdset_fd_dup, next);
2579 if (QLIST_EMPTY(&mon_fdset->dup_fds)) {
2580 monitor_fdset_cleanup(mon_fdset);
2584 qemu_mutex_unlock(&mon_fdsets_lock);
2585 return mon_fdset->id;
2592 qemu_mutex_unlock(&mon_fdsets_lock);
2596 int monitor_fdset_dup_fd_find(int dup_fd)
2598 return monitor_fdset_dup_fd_find_remove(dup_fd, false);
2601 void monitor_fdset_dup_fd_remove(int dup_fd)
2603 monitor_fdset_dup_fd_find_remove(dup_fd, true);
2606 int monitor_fd_param(Monitor *mon, const char *fdname, Error **errp)
2609 Error *local_err = NULL;
2611 if (!qemu_isdigit(fdname[0]) && mon) {
2612 fd = monitor_get_fd(mon, fdname, &local_err);
2614 fd = qemu_parse_fd(fdname);
2616 error_setg(&local_err, "Invalid file descriptor number '%s'",
2621 error_propagate(errp, local_err);
2630 /* Please update hmp-commands.hx when adding or changing commands */
2631 static mon_cmd_t info_cmds[] = {
2632 #include "hmp-commands-info.h"
2636 /* mon_cmds and info_cmds would be sorted at runtime */
2637 static mon_cmd_t mon_cmds[] = {
2638 #include "hmp-commands.h"
2642 /*******************************************************************/
2644 static const char *pch;
2645 static sigjmp_buf expr_env;
2648 static void GCC_FMT_ATTR(2, 3) QEMU_NORETURN
2649 expr_error(Monitor *mon, const char *fmt, ...)
2653 monitor_vprintf(mon, fmt, ap);
2654 monitor_printf(mon, "\n");
2656 siglongjmp(expr_env, 1);
2659 /* return 0 if OK, -1 if not found */
2660 static int get_monitor_def(target_long *pval, const char *name)
2662 const MonitorDef *md = target_monitor_defs();
2663 CPUState *cs = mon_get_cpu();
2668 if (cs == NULL || md == NULL) {
2672 for(; md->name != NULL; md++) {
2673 if (compare_cmd(name, md->name)) {
2674 if (md->get_value) {
2675 *pval = md->get_value(md, md->offset);
2677 CPUArchState *env = mon_get_cpu_env();
2678 ptr = (uint8_t *)env + md->offset;
2681 *pval = *(int32_t *)ptr;
2684 *pval = *(target_long *)ptr;
2695 ret = target_get_monitor_def(cs, name, &tmp);
2697 *pval = (target_long) tmp;
2703 static void next(void)
2707 while (qemu_isspace(*pch))
2712 static int64_t expr_sum(Monitor *mon);
2714 static int64_t expr_unary(Monitor *mon)
2723 n = expr_unary(mon);
2727 n = -expr_unary(mon);
2731 n = ~expr_unary(mon);
2737 expr_error(mon, "')' expected");
2744 expr_error(mon, "character constant expected");
2748 expr_error(mon, "missing terminating \' character");
2758 while ((*pch >= 'a' && *pch <= 'z') ||
2759 (*pch >= 'A' && *pch <= 'Z') ||
2760 (*pch >= '0' && *pch <= '9') ||
2761 *pch == '_' || *pch == '.') {
2762 if ((q - buf) < sizeof(buf) - 1)
2766 while (qemu_isspace(*pch))
2769 ret = get_monitor_def(®, buf);
2771 expr_error(mon, "unknown register");
2776 expr_error(mon, "unexpected end of expression");
2781 n = strtoull(pch, &p, 0);
2782 if (errno == ERANGE) {
2783 expr_error(mon, "number too large");
2786 expr_error(mon, "invalid char '%c' in expression", *p);
2789 while (qemu_isspace(*pch))
2797 static int64_t expr_prod(Monitor *mon)
2802 val = expr_unary(mon);
2805 if (op != '*' && op != '/' && op != '%')
2808 val2 = expr_unary(mon);
2817 expr_error(mon, "division by zero");
2828 static int64_t expr_logic(Monitor *mon)
2833 val = expr_prod(mon);
2836 if (op != '&' && op != '|' && op != '^')
2839 val2 = expr_prod(mon);
2856 static int64_t expr_sum(Monitor *mon)
2861 val = expr_logic(mon);
2864 if (op != '+' && op != '-')
2867 val2 = expr_logic(mon);
2876 static int get_expr(Monitor *mon, int64_t *pval, const char **pp)
2879 if (sigsetjmp(expr_env, 0)) {
2883 while (qemu_isspace(*pch))
2885 *pval = expr_sum(mon);
2890 static int get_double(Monitor *mon, double *pval, const char **pp)
2892 const char *p = *pp;
2896 d = strtod(p, &tailp);
2898 monitor_printf(mon, "Number expected\n");
2901 if (d != d || d - d != 0) {
2902 /* NaN or infinity */
2903 monitor_printf(mon, "Bad number\n");
2912 * Store the command-name in cmdname, and return a pointer to
2913 * the remaining of the command string.
2915 static const char *get_command_name(const char *cmdline,
2916 char *cmdname, size_t nlen)
2919 const char *p, *pstart;
2922 while (qemu_isspace(*p))
2927 while (*p != '\0' && *p != '/' && !qemu_isspace(*p))
2932 memcpy(cmdname, pstart, len);
2933 cmdname[len] = '\0';
2938 * Read key of 'type' into 'key' and return the current
2941 static char *key_get_info(const char *type, char **key)
2949 p = strchr(type, ':');
2956 str = g_malloc(len + 1);
2957 memcpy(str, type, len);
2964 static int default_fmt_format = 'x';
2965 static int default_fmt_size = 4;
2967 static int is_valid_option(const char *c, const char *typestr)
2975 typestr = strstr(typestr, option);
2976 return (typestr != NULL);
2979 static const mon_cmd_t *search_dispatch_table(const mon_cmd_t *disp_table,
2980 const char *cmdname)
2982 const mon_cmd_t *cmd;
2984 for (cmd = disp_table; cmd->name != NULL; cmd++) {
2985 if (compare_cmd(cmdname, cmd->name)) {
2994 * Parse command name from @cmdp according to command table @table.
2995 * If blank, return NULL.
2996 * Else, if no valid command can be found, report to @mon, and return
2998 * Else, change @cmdp to point right behind the name, and return its
2999 * command table entry.
3000 * Do not assume the return value points into @table! It doesn't when
3001 * the command is found in a sub-command table.
3003 static const mon_cmd_t *monitor_parse_command(Monitor *mon,
3004 const char *cmdp_start,
3009 const mon_cmd_t *cmd;
3012 /* extract the command name */
3013 p = get_command_name(*cmdp, cmdname, sizeof(cmdname));
3017 cmd = search_dispatch_table(table, cmdname);
3019 monitor_printf(mon, "unknown command: '%.*s'\n",
3020 (int)(p - cmdp_start), cmdp_start);
3023 if (runstate_check(RUN_STATE_PRECONFIG) && !cmd_can_preconfig(cmd)) {
3024 monitor_printf(mon, "Command '%.*s' not available with -preconfig "
3025 "until after exit_preconfig.\n",
3026 (int)(p - cmdp_start), cmdp_start);
3030 /* filter out following useless space */
3031 while (qemu_isspace(*p)) {
3036 /* search sub command */
3037 if (cmd->sub_table != NULL && *p != '\0') {
3038 return monitor_parse_command(mon, cmdp_start, cmdp, cmd->sub_table);
3045 * Parse arguments for @cmd.
3046 * If it can't be parsed, report to @mon, and return NULL.
3047 * Else, insert command arguments into a QDict, and return it.
3048 * Note: On success, caller has to free the QDict structure.
3051 static QDict *monitor_parse_arguments(Monitor *mon,
3053 const mon_cmd_t *cmd)
3055 const char *typestr;
3058 const char *p = *endp;
3060 QDict *qdict = qdict_new();
3062 /* parse the parameters */
3063 typestr = cmd->args_type;
3065 typestr = key_get_info(typestr, &key);
3077 while (qemu_isspace(*p))
3079 if (*typestr == '?') {
3082 /* no optional string: NULL argument */
3086 ret = get_str(buf, sizeof(buf), &p);
3090 monitor_printf(mon, "%s: filename expected\n",
3094 monitor_printf(mon, "%s: block device name expected\n",
3098 monitor_printf(mon, "%s: string expected\n", cmd->name);
3103 qdict_put_str(qdict, key, buf);
3108 QemuOptsList *opts_list;
3111 opts_list = qemu_find_opts(key);
3112 if (!opts_list || opts_list->desc->name) {
3115 while (qemu_isspace(*p)) {
3120 if (get_str(buf, sizeof(buf), &p) < 0) {
3123 opts = qemu_opts_parse_noisily(opts_list, buf, true);
3127 qemu_opts_to_qdict(opts, qdict);
3128 qemu_opts_del(opts);
3133 int count, format, size;
3135 while (qemu_isspace(*p))
3141 if (qemu_isdigit(*p)) {
3143 while (qemu_isdigit(*p)) {
3144 count = count * 10 + (*p - '0');
3182 if (*p != '\0' && !qemu_isspace(*p)) {
3183 monitor_printf(mon, "invalid char in format: '%c'\n",
3188 format = default_fmt_format;
3189 if (format != 'i') {
3190 /* for 'i', not specifying a size gives -1 as size */
3192 size = default_fmt_size;
3193 default_fmt_size = size;
3195 default_fmt_format = format;
3198 format = default_fmt_format;
3199 if (format != 'i') {
3200 size = default_fmt_size;
3205 qdict_put_int(qdict, "count", count);
3206 qdict_put_int(qdict, "format", format);
3207 qdict_put_int(qdict, "size", size);
3216 while (qemu_isspace(*p))
3218 if (*typestr == '?' || *typestr == '.') {
3219 if (*typestr == '?') {
3227 while (qemu_isspace(*p))
3236 if (get_expr(mon, &val, &p))
3238 /* Check if 'i' is greater than 32-bit */
3239 if ((c == 'i') && ((val >> 32) & 0xffffffff)) {
3240 monitor_printf(mon, "\'%s\' has failed: ", cmd->name);
3241 monitor_printf(mon, "integer is for 32-bit values\n");
3243 } else if (c == 'M') {
3245 monitor_printf(mon, "enter a positive value\n");
3250 qdict_put_int(qdict, key, val);
3259 while (qemu_isspace(*p)) {
3262 if (*typestr == '?') {
3268 ret = qemu_strtosz_MiB(p, &end, &val);
3269 if (ret < 0 || val > INT64_MAX) {
3270 monitor_printf(mon, "invalid size\n");
3273 qdict_put_int(qdict, key, val);
3281 while (qemu_isspace(*p))
3283 if (*typestr == '?') {
3289 if (get_double(mon, &val, &p) < 0) {
3292 if (p[0] && p[1] == 's') {
3295 val /= 1e3; p += 2; break;
3297 val /= 1e6; p += 2; break;
3299 val /= 1e9; p += 2; break;
3302 if (*p && !qemu_isspace(*p)) {
3303 monitor_printf(mon, "Unknown unit suffix\n");
3306 qdict_put(qdict, key, qnum_from_double(val));
3314 while (qemu_isspace(*p)) {
3318 while (qemu_isgraph(*p)) {
3321 if (p - beg == 2 && !memcmp(beg, "on", p - beg)) {
3323 } else if (p - beg == 3 && !memcmp(beg, "off", p - beg)) {
3326 monitor_printf(mon, "Expected 'on' or 'off'\n");
3329 qdict_put_bool(qdict, key, val);
3334 const char *tmp = p;
3341 while (qemu_isspace(*p))
3346 if(!is_valid_option(p, typestr)) {
3348 monitor_printf(mon, "%s: unsupported option -%c\n",
3360 qdict_put_bool(qdict, key, true);
3367 /* package all remaining string */
3370 while (qemu_isspace(*p)) {
3373 if (*typestr == '?') {
3376 /* no remaining string: NULL argument */
3382 monitor_printf(mon, "%s: string expected\n",
3386 qdict_put_str(qdict, key, p);
3392 monitor_printf(mon, "%s: unknown type '%c'\n", cmd->name, c);
3398 /* check that all arguments were parsed */
3399 while (qemu_isspace(*p))
3402 monitor_printf(mon, "%s: extraneous characters at the end of line\n",
3410 qobject_unref(qdict);
3415 static void handle_hmp_command(Monitor *mon, const char *cmdline)
3418 const mon_cmd_t *cmd;
3419 const char *cmd_start = cmdline;
3421 trace_handle_hmp_command(mon, cmdline);
3423 cmd = monitor_parse_command(mon, cmdline, &cmdline, mon->cmd_table);
3428 qdict = monitor_parse_arguments(mon, &cmdline, cmd);
3430 while (cmdline > cmd_start && qemu_isspace(cmdline[-1])) {
3433 monitor_printf(mon, "Try \"help %.*s\" for more information\n",
3434 (int)(cmdline - cmd_start), cmd_start);
3438 cmd->cmd(mon, qdict);
3439 qobject_unref(qdict);
3442 static void cmd_completion(Monitor *mon, const char *name, const char *list)
3444 const char *p, *pstart;
3451 p = qemu_strchrnul(p, '|');
3453 if (len > sizeof(cmd) - 2)
3454 len = sizeof(cmd) - 2;
3455 memcpy(cmd, pstart, len);
3457 if (name[0] == '\0' || !strncmp(name, cmd, strlen(name))) {
3458 readline_add_completion(mon->rs, cmd);
3466 static void file_completion(Monitor *mon, const char *input)
3471 char file[1024], file_prefix[1024];
3475 p = strrchr(input, '/');
3478 pstrcpy(file_prefix, sizeof(file_prefix), input);
3479 pstrcpy(path, sizeof(path), ".");
3481 input_path_len = p - input + 1;
3482 memcpy(path, input, input_path_len);
3483 if (input_path_len > sizeof(path) - 1)
3484 input_path_len = sizeof(path) - 1;
3485 path[input_path_len] = '\0';
3486 pstrcpy(file_prefix, sizeof(file_prefix), p + 1);
3489 ffs = opendir(path);
3498 if (strcmp(d->d_name, ".") == 0 || strcmp(d->d_name, "..") == 0) {
3502 if (strstart(d->d_name, file_prefix, NULL)) {
3503 memcpy(file, input, input_path_len);
3504 if (input_path_len < sizeof(file))
3505 pstrcpy(file + input_path_len, sizeof(file) - input_path_len,
3507 /* stat the file to find out if it's a directory.
3508 * In that case add a slash to speed up typing long paths
3510 if (stat(file, &sb) == 0 && S_ISDIR(sb.st_mode)) {
3511 pstrcat(file, sizeof(file), "/");
3513 readline_add_completion(mon->rs, file);
3519 static const char *next_arg_type(const char *typestr)
3521 const char *p = strchr(typestr, ':');
3522 return (p != NULL ? ++p : typestr);
3525 static void add_completion_option(ReadLineState *rs, const char *str,
3528 if (!str || !option) {
3531 if (!strncmp(option, str, strlen(str))) {
3532 readline_add_completion(rs, option);
3536 void chardev_add_completion(ReadLineState *rs, int nb_args, const char *str)
3539 ChardevBackendInfoList *list, *start;
3545 readline_set_completion_index(rs, len);
3547 start = list = qmp_query_chardev_backends(NULL);
3549 const char *chr_name = list->value->name;
3551 if (!strncmp(chr_name, str, len)) {
3552 readline_add_completion(rs, chr_name);
3556 qapi_free_ChardevBackendInfoList(start);
3559 void netdev_add_completion(ReadLineState *rs, int nb_args, const char *str)
3568 readline_set_completion_index(rs, len);
3569 for (i = 0; i < NET_CLIENT_DRIVER__MAX; i++) {
3570 add_completion_option(rs, str, NetClientDriver_str(i));
3574 void device_add_completion(ReadLineState *rs, int nb_args, const char *str)
3584 readline_set_completion_index(rs, len);
3585 list = elt = object_class_get_list(TYPE_DEVICE, false);
3588 DeviceClass *dc = OBJECT_CLASS_CHECK(DeviceClass, elt->data,
3590 name = object_class_get_name(OBJECT_CLASS(dc));
3592 if (dc->user_creatable
3593 && !strncmp(name, str, len)) {
3594 readline_add_completion(rs, name);
3601 void object_add_completion(ReadLineState *rs, int nb_args, const char *str)
3611 readline_set_completion_index(rs, len);
3612 list = elt = object_class_get_list(TYPE_USER_CREATABLE, false);
3616 name = object_class_get_name(OBJECT_CLASS(elt->data));
3617 if (!strncmp(name, str, len) && strcmp(name, TYPE_USER_CREATABLE)) {
3618 readline_add_completion(rs, name);
3625 static void peripheral_device_del_completion(ReadLineState *rs,
3626 const char *str, size_t len)
3628 Object *peripheral = container_get(qdev_get_machine(), "/peripheral");
3629 GSList *list, *item;
3631 list = qdev_build_hotpluggable_device_list(peripheral);
3636 for (item = list; item; item = g_slist_next(item)) {
3637 DeviceState *dev = item->data;
3639 if (dev->id && !strncmp(str, dev->id, len)) {
3640 readline_add_completion(rs, dev->id);
3647 void chardev_remove_completion(ReadLineState *rs, int nb_args, const char *str)
3650 ChardevInfoList *list, *start;
3656 readline_set_completion_index(rs, len);
3658 start = list = qmp_query_chardev(NULL);
3660 ChardevInfo *chr = list->value;
3662 if (!strncmp(chr->label, str, len)) {
3663 readline_add_completion(rs, chr->label);
3667 qapi_free_ChardevInfoList(start);
3670 static void ringbuf_completion(ReadLineState *rs, const char *str)
3673 ChardevInfoList *list, *start;
3676 readline_set_completion_index(rs, len);
3678 start = list = qmp_query_chardev(NULL);
3680 ChardevInfo *chr_info = list->value;
3682 if (!strncmp(chr_info->label, str, len)) {
3683 Chardev *chr = qemu_chr_find(chr_info->label);
3684 if (chr && CHARDEV_IS_RINGBUF(chr)) {
3685 readline_add_completion(rs, chr_info->label);
3690 qapi_free_ChardevInfoList(start);
3693 void ringbuf_write_completion(ReadLineState *rs, int nb_args, const char *str)
3698 ringbuf_completion(rs, str);
3701 void device_del_completion(ReadLineState *rs, int nb_args, const char *str)
3710 readline_set_completion_index(rs, len);
3711 peripheral_device_del_completion(rs, str, len);
3714 void object_del_completion(ReadLineState *rs, int nb_args, const char *str)
3716 ObjectPropertyInfoList *list, *start;
3723 readline_set_completion_index(rs, len);
3725 start = list = qmp_qom_list("/objects", NULL);
3727 ObjectPropertyInfo *info = list->value;
3729 if (!strncmp(info->type, "child<", 5)
3730 && !strncmp(info->name, str, len)) {
3731 readline_add_completion(rs, info->name);
3735 qapi_free_ObjectPropertyInfoList(start);
3738 void sendkey_completion(ReadLineState *rs, int nb_args, const char *str)
3747 sep = strrchr(str, '-');
3752 readline_set_completion_index(rs, len);
3753 for (i = 0; i < Q_KEY_CODE__MAX; i++) {
3754 if (!strncmp(str, QKeyCode_str(i), len)) {
3755 readline_add_completion(rs, QKeyCode_str(i));
3760 void set_link_completion(ReadLineState *rs, int nb_args, const char *str)
3765 readline_set_completion_index(rs, len);
3767 NetClientState *ncs[MAX_QUEUE_NUM];
3769 count = qemu_find_net_clients_except(NULL, ncs,
3770 NET_CLIENT_DRIVER_NONE,
3772 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3773 const char *name = ncs[i]->name;
3774 if (!strncmp(str, name, len)) {
3775 readline_add_completion(rs, name);
3778 } else if (nb_args == 3) {
3779 add_completion_option(rs, str, "on");
3780 add_completion_option(rs, str, "off");
3784 void netdev_del_completion(ReadLineState *rs, int nb_args, const char *str)
3787 NetClientState *ncs[MAX_QUEUE_NUM];
3794 readline_set_completion_index(rs, len);
3795 count = qemu_find_net_clients_except(NULL, ncs, NET_CLIENT_DRIVER_NIC,
3797 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3799 const char *name = ncs[i]->name;
3800 if (strncmp(str, name, len)) {
3803 opts = qemu_opts_find(qemu_find_opts_err("netdev", NULL), name);
3805 readline_add_completion(rs, name);
3810 void info_trace_events_completion(ReadLineState *rs, int nb_args, const char *str)
3815 readline_set_completion_index(rs, len);
3817 TraceEventIter iter;
3819 char *pattern = g_strdup_printf("%s*", str);
3820 trace_event_iter_init(&iter, pattern);
3821 while ((ev = trace_event_iter_next(&iter)) != NULL) {
3822 readline_add_completion(rs, trace_event_get_name(ev));
3828 void trace_event_completion(ReadLineState *rs, int nb_args, const char *str)
3833 readline_set_completion_index(rs, len);
3835 TraceEventIter iter;
3837 char *pattern = g_strdup_printf("%s*", str);
3838 trace_event_iter_init(&iter, pattern);
3839 while ((ev = trace_event_iter_next(&iter)) != NULL) {
3840 readline_add_completion(rs, trace_event_get_name(ev));
3843 } else if (nb_args == 3) {
3844 add_completion_option(rs, str, "on");
3845 add_completion_option(rs, str, "off");
3849 void watchdog_action_completion(ReadLineState *rs, int nb_args, const char *str)
3856 readline_set_completion_index(rs, strlen(str));
3857 for (i = 0; i < WATCHDOG_ACTION__MAX; i++) {
3858 add_completion_option(rs, str, WatchdogAction_str(i));
3862 void migrate_set_capability_completion(ReadLineState *rs, int nb_args,
3868 readline_set_completion_index(rs, len);
3871 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
3872 const char *name = MigrationCapability_str(i);
3873 if (!strncmp(str, name, len)) {
3874 readline_add_completion(rs, name);
3877 } else if (nb_args == 3) {
3878 add_completion_option(rs, str, "on");
3879 add_completion_option(rs, str, "off");
3883 void migrate_set_parameter_completion(ReadLineState *rs, int nb_args,
3889 readline_set_completion_index(rs, len);
3892 for (i = 0; i < MIGRATION_PARAMETER__MAX; i++) {
3893 const char *name = MigrationParameter_str(i);
3894 if (!strncmp(str, name, len)) {
3895 readline_add_completion(rs, name);
3901 static void vm_completion(ReadLineState *rs, const char *str)
3904 BlockDriverState *bs;
3905 BdrvNextIterator it;
3908 readline_set_completion_index(rs, len);
3910 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
3911 SnapshotInfoList *snapshots, *snapshot;
3912 AioContext *ctx = bdrv_get_aio_context(bs);
3915 aio_context_acquire(ctx);
3916 if (bdrv_can_snapshot(bs)) {
3917 ok = bdrv_query_snapshot_info_list(bs, &snapshots, NULL) == 0;
3919 aio_context_release(ctx);
3924 snapshot = snapshots;
3926 char *completion = snapshot->value->name;
3927 if (!strncmp(str, completion, len)) {
3928 readline_add_completion(rs, completion);
3930 completion = snapshot->value->id;
3931 if (!strncmp(str, completion, len)) {
3932 readline_add_completion(rs, completion);
3934 snapshot = snapshot->next;
3936 qapi_free_SnapshotInfoList(snapshots);
3941 void delvm_completion(ReadLineState *rs, int nb_args, const char *str)
3944 vm_completion(rs, str);
3948 void loadvm_completion(ReadLineState *rs, int nb_args, const char *str)
3951 vm_completion(rs, str);
3955 static void monitor_find_completion_by_table(Monitor *mon,
3956 const mon_cmd_t *cmd_table,
3960 const char *cmdname;
3962 const char *ptype, *old_ptype, *str, *name;
3963 const mon_cmd_t *cmd;
3964 BlockBackend *blk = NULL;
3967 /* command completion */
3972 readline_set_completion_index(mon->rs, strlen(cmdname));
3973 for (cmd = cmd_table; cmd->name != NULL; cmd++) {
3974 if (!runstate_check(RUN_STATE_PRECONFIG) ||
3975 cmd_can_preconfig(cmd)) {
3976 cmd_completion(mon, cmdname, cmd->name);
3980 /* find the command */
3981 for (cmd = cmd_table; cmd->name != NULL; cmd++) {
3982 if (compare_cmd(args[0], cmd->name) &&
3983 (!runstate_check(RUN_STATE_PRECONFIG) ||
3984 cmd_can_preconfig(cmd))) {
3992 if (cmd->sub_table) {
3993 /* do the job again */
3994 monitor_find_completion_by_table(mon, cmd->sub_table,
3995 &args[1], nb_args - 1);
3998 if (cmd->command_completion) {
3999 cmd->command_completion(mon->rs, nb_args, args[nb_args - 1]);
4003 ptype = next_arg_type(cmd->args_type);
4004 for(i = 0; i < nb_args - 2; i++) {
4005 if (*ptype != '\0') {
4006 ptype = next_arg_type(ptype);
4007 while (*ptype == '?')
4008 ptype = next_arg_type(ptype);
4011 str = args[nb_args - 1];
4013 while (*ptype == '-' && old_ptype != ptype) {
4015 ptype = next_arg_type(ptype);
4019 /* file completion */
4020 readline_set_completion_index(mon->rs, strlen(str));
4021 file_completion(mon, str);
4024 /* block device name completion */
4025 readline_set_completion_index(mon->rs, strlen(str));
4026 while ((blk = blk_next(blk)) != NULL) {
4027 name = blk_name(blk);
4028 if (str[0] == '\0' ||
4029 !strncmp(name, str, strlen(str))) {
4030 readline_add_completion(mon->rs, name);
4036 if (!strcmp(cmd->name, "help|?")) {
4037 monitor_find_completion_by_table(mon, cmd_table,
4038 &args[1], nb_args - 1);
4047 static void monitor_find_completion(void *opaque,
4048 const char *cmdline)
4050 Monitor *mon = opaque;
4051 char *args[MAX_ARGS];
4054 /* 1. parse the cmdline */
4055 if (parse_cmdline(cmdline, &nb_args, args) < 0) {
4059 /* if the line ends with a space, it means we want to complete the
4061 len = strlen(cmdline);
4062 if (len > 0 && qemu_isspace(cmdline[len - 1])) {
4063 if (nb_args >= MAX_ARGS) {
4066 args[nb_args++] = g_strdup("");
4069 /* 2. auto complete according to args */
4070 monitor_find_completion_by_table(mon, mon->cmd_table, args, nb_args);
4073 free_cmdline_args(args, nb_args);
4076 static int monitor_can_read(void *opaque)
4078 Monitor *mon = opaque;
4080 return !atomic_mb_read(&mon->suspend_cnt);
4084 * Emit QMP response @rsp with ID @id to @mon.
4085 * Null @rsp can only happen for commands with QCO_NO_SUCCESS_RESP.
4086 * Nothing is emitted then.
4088 static void monitor_qmp_respond(Monitor *mon, QDict *rsp, QObject *id)
4092 qdict_put_obj(rsp, "id", qobject_ref(id));
4095 qmp_send_response(mon, rsp);
4099 static void monitor_qmp_dispatch(Monitor *mon, QObject *req, QObject *id)
4108 rsp = qmp_dispatch(mon->qmp.commands, req, qmp_oob_enabled(mon));
4112 if (mon->qmp.commands == &qmp_cap_negotiation_commands) {
4113 error = qdict_get_qdict(rsp, "error");
4115 && !g_strcmp0(qdict_get_try_str(error, "class"),
4116 QapiErrorClass_str(ERROR_CLASS_COMMAND_NOT_FOUND))) {
4117 /* Provide a more useful error message */
4118 qdict_del(error, "desc");
4119 qdict_put_str(error, "desc", "Expecting capabilities negotiation"
4120 " with 'qmp_capabilities'");
4124 monitor_qmp_respond(mon, rsp, id);
4129 * Pop a QMP request from a monitor request queue.
4130 * Return the request, or NULL all request queues are empty.
4131 * We are using round-robin fashion to pop the request, to avoid
4132 * processing commands only on a very busy monitor. To achieve that,
4133 * when we process one request on a specific monitor, we put that
4134 * monitor to the end of mon_list queue.
4136 * Note: if the function returned with non-NULL, then the caller will
4137 * be with mon->qmp.qmp_queue_lock held, and the caller is responsible
4140 static QMPRequest *monitor_qmp_requests_pop_any_with_lock(void)
4142 QMPRequest *req_obj = NULL;
4145 qemu_mutex_lock(&monitor_lock);
4147 QTAILQ_FOREACH(mon, &mon_list, entry) {
4148 qemu_mutex_lock(&mon->qmp.qmp_queue_lock);
4149 req_obj = g_queue_pop_head(mon->qmp.qmp_requests);
4151 /* With the lock of corresponding queue held */
4154 qemu_mutex_unlock(&mon->qmp.qmp_queue_lock);
4159 * We found one request on the monitor. Degrade this monitor's
4160 * priority to lowest by re-inserting it to end of queue.
4162 QTAILQ_REMOVE(&mon_list, mon, entry);
4163 QTAILQ_INSERT_TAIL(&mon_list, mon, entry);
4166 qemu_mutex_unlock(&monitor_lock);
4171 static void monitor_qmp_bh_dispatcher(void *data)
4173 QMPRequest *req_obj = monitor_qmp_requests_pop_any_with_lock();
4183 /* qmp_oob_enabled() might change after "qmp_capabilities" */
4184 need_resume = !qmp_oob_enabled(mon) ||
4185 mon->qmp.qmp_requests->length == QMP_REQ_QUEUE_LEN_MAX - 1;
4186 qemu_mutex_unlock(&mon->qmp.qmp_queue_lock);
4188 trace_monitor_qmp_cmd_in_band(qobject_get_try_str(req_obj->id) ?: "");
4189 monitor_qmp_dispatch(mon, req_obj->req, req_obj->id);
4191 assert(req_obj->err);
4192 rsp = qmp_error_response(req_obj->err);
4193 req_obj->err = NULL;
4194 monitor_qmp_respond(mon, rsp, NULL);
4199 /* Pairs with the monitor_suspend() in handle_qmp_command() */
4200 monitor_resume(mon);
4202 qmp_request_free(req_obj);
4204 /* Reschedule instead of looping so the main loop stays responsive */
4205 qemu_bh_schedule(qmp_dispatcher_bh);
4208 static void handle_qmp_command(void *opaque, QObject *req, Error *err)
4210 Monitor *mon = opaque;
4213 QMPRequest *req_obj;
4215 assert(!req != !err);
4217 qdict = qobject_to(QDict, req);
4219 id = qobject_ref(qdict_get(qdict, "id"));
4220 qdict_del(qdict, "id");
4221 } /* else will fail qmp_dispatch() */
4223 if (req && trace_event_get_state_backends(TRACE_HANDLE_QMP_COMMAND)) {
4224 QString *req_json = qobject_to_json(req);
4225 trace_handle_qmp_command(mon, qstring_get_str(req_json));
4226 qobject_unref(req_json);
4229 if (qdict && qmp_is_oob(qdict)) {
4230 /* OOB commands are executed immediately */
4231 trace_monitor_qmp_cmd_out_of_band(qobject_get_try_str(id)
4233 monitor_qmp_dispatch(mon, req, id);
4239 req_obj = g_new0(QMPRequest, 1);
4245 /* Protect qmp_requests and fetching its length. */
4246 qemu_mutex_lock(&mon->qmp.qmp_queue_lock);
4249 * Suspend the monitor when we can't queue more requests after
4250 * this one. Dequeuing in monitor_qmp_bh_dispatcher() will resume
4251 * it. Note that when OOB is disabled, we queue at most one
4252 * command, for backward compatibility.
4254 if (!qmp_oob_enabled(mon) ||
4255 mon->qmp.qmp_requests->length == QMP_REQ_QUEUE_LEN_MAX - 1) {
4256 monitor_suspend(mon);
4260 * Put the request to the end of queue so that requests will be
4261 * handled in time order. Ownership for req_obj, req, id,
4262 * etc. will be delivered to the handler side.
4264 assert(mon->qmp.qmp_requests->length < QMP_REQ_QUEUE_LEN_MAX);
4265 g_queue_push_tail(mon->qmp.qmp_requests, req_obj);
4266 qemu_mutex_unlock(&mon->qmp.qmp_queue_lock);
4268 /* Kick the dispatcher routine */
4269 qemu_bh_schedule(qmp_dispatcher_bh);
4272 static void monitor_qmp_read(void *opaque, const uint8_t *buf, int size)
4274 Monitor *mon = opaque;
4276 json_message_parser_feed(&mon->qmp.parser, (const char *) buf, size);
4279 static void monitor_read(void *opaque, const uint8_t *buf, int size)
4281 Monitor *old_mon = cur_mon;
4287 for (i = 0; i < size; i++)
4288 readline_handle_byte(cur_mon->rs, buf[i]);
4290 if (size == 0 || buf[size - 1] != 0)
4291 monitor_printf(cur_mon, "corrupted command\n");
4293 handle_hmp_command(cur_mon, (char *)buf);
4299 static void monitor_command_cb(void *opaque, const char *cmdline,
4300 void *readline_opaque)
4302 Monitor *mon = opaque;
4304 monitor_suspend(mon);
4305 handle_hmp_command(mon, cmdline);
4306 monitor_resume(mon);
4309 int monitor_suspend(Monitor *mon)
4311 if (monitor_is_hmp_non_interactive(mon)) {
4315 atomic_inc(&mon->suspend_cnt);
4317 if (mon->use_io_thread) {
4319 * Kick I/O thread to make sure this takes effect. It'll be
4320 * evaluated again in prepare() of the watch object.
4322 aio_notify(iothread_get_aio_context(mon_iothread));
4325 trace_monitor_suspend(mon, 1);
4329 static void monitor_accept_input(void *opaque)
4331 Monitor *mon = opaque;
4333 qemu_chr_fe_accept_input(&mon->chr);
4336 void monitor_resume(Monitor *mon)
4338 if (monitor_is_hmp_non_interactive(mon)) {
4342 if (atomic_dec_fetch(&mon->suspend_cnt) == 0) {
4345 if (mon->use_io_thread) {
4346 ctx = iothread_get_aio_context(mon_iothread);
4348 ctx = qemu_get_aio_context();
4351 if (!monitor_is_qmp(mon)) {
4353 readline_show_prompt(mon->rs);
4356 aio_bh_schedule_oneshot(ctx, monitor_accept_input, mon);
4359 trace_monitor_suspend(mon, -1);
4362 static QDict *qmp_greeting(Monitor *mon)
4364 QList *cap_list = qlist_new();
4365 QObject *ver = NULL;
4368 qmp_marshal_query_version(NULL, &ver, NULL);
4370 for (cap = 0; cap < QMP_CAPABILITY__MAX; cap++) {
4371 if (mon->qmp.capab_offered[cap]) {
4372 qlist_append_str(cap_list, QMPCapability_str(cap));
4376 return qdict_from_jsonf_nofail(
4377 "{'QMP': {'version': %p, 'capabilities': %p}}",
4381 static void monitor_qmp_event(void *opaque, int event)
4384 Monitor *mon = opaque;
4387 case CHR_EVENT_OPENED:
4388 mon->qmp.commands = &qmp_cap_negotiation_commands;
4389 monitor_qmp_caps_reset(mon);
4390 data = qmp_greeting(mon);
4391 qmp_send_response(mon, data);
4392 qobject_unref(data);
4395 case CHR_EVENT_CLOSED:
4397 * Note: this is only useful when the output of the chardev
4398 * backend is still open. For example, when the backend is
4399 * stdio, it's possible that stdout is still open when stdin
4402 monitor_qmp_cleanup_queues(mon);
4403 json_message_parser_destroy(&mon->qmp.parser);
4404 json_message_parser_init(&mon->qmp.parser, handle_qmp_command,
4407 monitor_fdsets_cleanup();
4412 static void monitor_event(void *opaque, int event)
4414 Monitor *mon = opaque;
4417 case CHR_EVENT_MUX_IN:
4418 qemu_mutex_lock(&mon->mon_lock);
4420 qemu_mutex_unlock(&mon->mon_lock);
4421 if (mon->reset_seen) {
4422 readline_restart(mon->rs);
4423 monitor_resume(mon);
4426 atomic_mb_set(&mon->suspend_cnt, 0);
4430 case CHR_EVENT_MUX_OUT:
4431 if (mon->reset_seen) {
4432 if (atomic_mb_read(&mon->suspend_cnt) == 0) {
4433 monitor_printf(mon, "\n");
4436 monitor_suspend(mon);
4438 atomic_inc(&mon->suspend_cnt);
4440 qemu_mutex_lock(&mon->mon_lock);
4442 qemu_mutex_unlock(&mon->mon_lock);
4445 case CHR_EVENT_OPENED:
4446 monitor_printf(mon, "QEMU %s monitor - type 'help' for more "
4447 "information\n", QEMU_VERSION);
4448 if (!mon->mux_out) {
4449 readline_restart(mon->rs);
4450 readline_show_prompt(mon->rs);
4452 mon->reset_seen = 1;
4456 case CHR_EVENT_CLOSED:
4458 monitor_fdsets_cleanup();
4464 compare_mon_cmd(const void *a, const void *b)
4466 return strcmp(((const mon_cmd_t *)a)->name,
4467 ((const mon_cmd_t *)b)->name);
4470 static void sortcmdlist(void)
4473 int elem_size = sizeof(mon_cmd_t);
4475 array_num = sizeof(mon_cmds)/elem_size-1;
4476 qsort((void *)mon_cmds, array_num, elem_size, compare_mon_cmd);
4478 array_num = sizeof(info_cmds)/elem_size-1;
4479 qsort((void *)info_cmds, array_num, elem_size, compare_mon_cmd);
4482 static void monitor_iothread_init(void)
4484 mon_iothread = iothread_create("mon_iothread", &error_abort);
4487 void monitor_init_globals(void)
4489 monitor_init_qmp_commands();
4490 monitor_qapi_event_init();
4492 qemu_mutex_init(&monitor_lock);
4493 qemu_mutex_init(&mon_fdsets_lock);
4496 * The dispatcher BH must run in the main loop thread, since we
4497 * have commands assuming that context. It would be nice to get
4498 * rid of those assumptions.
4500 qmp_dispatcher_bh = aio_bh_new(iohandler_get_aio_context(),
4501 monitor_qmp_bh_dispatcher,
4505 /* These functions just adapt the readline interface in a typesafe way. We
4506 * could cast function pointers but that discards compiler checks.
4508 static void GCC_FMT_ATTR(2, 3) monitor_readline_printf(void *opaque,
4509 const char *fmt, ...)
4513 monitor_vprintf(opaque, fmt, ap);
4517 static void monitor_readline_flush(void *opaque)
4519 monitor_flush(opaque);
4523 * Print to current monitor if we have one, else to stream.
4524 * TODO should return int, so callers can calculate width, but that
4525 * requires surgery to monitor_vprintf(). Left for another day.
4527 void monitor_vfprintf(FILE *stream, const char *fmt, va_list ap)
4529 if (cur_mon && !monitor_cur_is_qmp()) {
4530 monitor_vprintf(cur_mon, fmt, ap);
4532 vfprintf(stream, fmt, ap);
4537 * Print to current monitor if we have one, else to stderr.
4538 * TODO should return int, so callers can calculate width, but that
4539 * requires surgery to monitor_vprintf(). Left for another day.
4541 void error_vprintf(const char *fmt, va_list ap)
4543 monitor_vfprintf(stderr, fmt, ap);
4546 void error_vprintf_unless_qmp(const char *fmt, va_list ap)
4548 if (cur_mon && !monitor_cur_is_qmp()) {
4549 monitor_vprintf(cur_mon, fmt, ap);
4550 } else if (!cur_mon) {
4551 vfprintf(stderr, fmt, ap);
4555 static void monitor_list_append(Monitor *mon)
4557 qemu_mutex_lock(&monitor_lock);
4559 * This prevents inserting new monitors during monitor_cleanup().
4560 * A cleaner solution would involve the main thread telling other
4561 * threads to terminate, waiting for their termination.
4563 if (!monitor_destroyed) {
4564 QTAILQ_INSERT_HEAD(&mon_list, mon, entry);
4567 qemu_mutex_unlock(&monitor_lock);
4570 monitor_data_destroy(mon);
4575 static void monitor_qmp_setup_handlers_bh(void *opaque)
4577 Monitor *mon = opaque;
4578 GMainContext *context;
4580 assert(mon->use_io_thread);
4581 context = iothread_get_g_main_context(mon_iothread);
4583 qemu_chr_fe_set_handlers(&mon->chr, monitor_can_read, monitor_qmp_read,
4584 monitor_qmp_event, NULL, mon, context, true);
4585 monitor_list_append(mon);
4588 void monitor_init(Chardev *chr, int flags)
4590 Monitor *mon = g_malloc(sizeof(*mon));
4591 bool use_readline = flags & MONITOR_USE_READLINE;
4593 /* Note: we run QMP monitor in I/O thread when @chr supports that */
4594 monitor_data_init(mon, false,
4595 (flags & MONITOR_USE_CONTROL)
4596 && qemu_chr_has_feature(chr,
4597 QEMU_CHAR_FEATURE_GCONTEXT));
4599 qemu_chr_fe_init(&mon->chr, chr, &error_abort);
4602 mon->rs = readline_init(monitor_readline_printf,
4603 monitor_readline_flush,
4605 monitor_find_completion);
4606 monitor_read_command(mon, 0);
4609 if (monitor_is_qmp(mon)) {
4610 qemu_chr_fe_set_echo(&mon->chr, true);
4611 json_message_parser_init(&mon->qmp.parser, handle_qmp_command,
4613 if (mon->use_io_thread) {
4615 * Make sure the old iowatch is gone. It's possible when
4616 * e.g. the chardev is in client mode, with wait=on.
4618 remove_fd_in_watch(chr);
4620 * We can't call qemu_chr_fe_set_handlers() directly here
4621 * since chardev might be running in the monitor I/O
4622 * thread. Schedule a bottom half.
4624 aio_bh_schedule_oneshot(iothread_get_aio_context(mon_iothread),
4625 monitor_qmp_setup_handlers_bh, mon);
4626 /* The bottom half will add @mon to @mon_list */
4629 qemu_chr_fe_set_handlers(&mon->chr, monitor_can_read,
4630 monitor_qmp_read, monitor_qmp_event,
4631 NULL, mon, NULL, true);
4634 qemu_chr_fe_set_handlers(&mon->chr, monitor_can_read, monitor_read,
4635 monitor_event, NULL, mon, NULL, true);
4638 monitor_list_append(mon);
4641 void monitor_cleanup(void)
4644 * We need to explicitly stop the I/O thread (but not destroy it),
4645 * clean up the monitor resources, then destroy the I/O thread since
4646 * we need to unregister from chardev below in
4647 * monitor_data_destroy(), and chardev is not thread-safe yet
4650 iothread_stop(mon_iothread);
4653 /* Flush output buffers and destroy monitors */
4654 qemu_mutex_lock(&monitor_lock);
4655 monitor_destroyed = true;
4656 while (!QTAILQ_EMPTY(&mon_list)) {
4657 Monitor *mon = QTAILQ_FIRST(&mon_list);
4658 QTAILQ_REMOVE(&mon_list, mon, entry);
4659 /* Permit QAPI event emission from character frontend release */
4660 qemu_mutex_unlock(&monitor_lock);
4662 monitor_data_destroy(mon);
4663 qemu_mutex_lock(&monitor_lock);
4666 qemu_mutex_unlock(&monitor_lock);
4668 /* QEMUBHs needs to be deleted before destroying the I/O thread */
4669 qemu_bh_delete(qmp_dispatcher_bh);
4670 qmp_dispatcher_bh = NULL;
4672 iothread_destroy(mon_iothread);
4673 mon_iothread = NULL;
4677 QemuOptsList qemu_mon_opts = {
4679 .implied_opt_name = "chardev",
4680 .head = QTAILQ_HEAD_INITIALIZER(qemu_mon_opts.head),
4684 .type = QEMU_OPT_STRING,
4687 .type = QEMU_OPT_STRING,
4690 .type = QEMU_OPT_BOOL,
4692 { /* end of list */ }
4696 HotpluggableCPUList *qmp_query_hotpluggable_cpus(Error **errp)
4698 MachineState *ms = MACHINE(qdev_get_machine());
4699 MachineClass *mc = MACHINE_GET_CLASS(ms);
4701 if (!mc->has_hotpluggable_cpus) {
4702 error_setg(errp, QERR_FEATURE_DISABLED, "query-hotpluggable-cpus");
4706 return machine_query_hotpluggable_cpus(ms);