qemu-iotests: commit to backing file with auto-read-only
[qemu/ar7.git] / monitor.c
blob72061d5baeb44ac7e535d3e9db6028774b9e32b8
1 /*
2 * QEMU monitor
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
22 * THE SOFTWARE.
25 #include "qemu/osdep.h"
26 #include "qemu/units.h"
27 #include <dirent.h>
28 #include "cpu.h"
29 #include "hw/hw.h"
30 #include "monitor/qdev.h"
31 #include "hw/usb.h"
32 #include "hw/pci/pci.h"
33 #include "sysemu/watchdog.h"
34 #include "hw/loader.h"
35 #include "exec/gdbstub.h"
36 #include "net/net.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"
47 #include "ui/input.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"
70 #endif
71 #include "exec/memory.h"
72 #include "exec/exec-all.h"
73 #include "qemu/log.h"
74 #include "qemu/option.h"
75 #include "hmp.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"
87 #include "tcg/tcg.h"
89 #if defined(TARGET_S390X)
90 #include "hw/s390x/storage-keys.h"
91 #include "hw/s390x/storage-attributes.h"
92 #endif
95 * Supported types:
97 * 'F' filename
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
106 * 'i' 32 bit integer
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
115 * 'T' double
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')
122 * 'b' boolean
123 * user mode accepts "on" or "off"
124 * '-' optional parameter (eg. '-f')
128 typedef struct mon_cmd_t {
129 const char *name;
130 const char *args_type;
131 const char *params;
132 const char *help;
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);
141 } mon_cmd_t;
143 /* file descriptors passed via SCM_RIGHTS */
144 typedef struct mon_fd_t mon_fd_t;
145 struct mon_fd_t {
146 char *name;
147 int fd;
148 QLIST_ENTRY(mon_fd_t) next;
151 /* file descriptor associated with a file descriptor set */
152 typedef struct MonFdsetFd MonFdsetFd;
153 struct MonFdsetFd {
154 int fd;
155 bool removed;
156 char *opaque;
157 QLIST_ENTRY(MonFdsetFd) next;
160 /* file descriptor set containing fds passed via SCM_RIGHTS */
161 typedef struct MonFdset MonFdset;
162 struct MonFdset {
163 int64_t id;
164 QLIST_HEAD(, MonFdsetFd) fds;
165 QLIST_HEAD(, MonFdsetFd) dup_fds;
166 QLIST_ENTRY(MonFdset) next;
169 typedef struct {
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;
187 } MonitorQMP;
190 * To prevent flooding clients, events can be throttled. The
191 * throttling is calculated globally, rather than per-Monitor
192 * instance.
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;
201 typedef struct {
202 int64_t rate; /* Minimum time (in ns) between two events */
203 } MonitorQAPIEventConf;
205 struct Monitor {
206 CharBackend chr;
207 int reset_seen;
208 int flags;
209 int suspend_cnt; /* Needs to be accessed atomically */
210 bool skip_flush;
211 bool use_io_thread;
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.
219 ReadLineState *rs;
221 MonitorQMP qmp;
222 gchar *mon_cpu_path;
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
230 * the lock.
232 QemuMutex mon_lock;
235 * Members that are protected by the per-monitor lock
237 QLIST_HEAD(, mon_fd_t) fds;
238 QString *outbuf;
239 guint out_watch;
240 /* Read under either BQL or mon_lock, written with BQL+mon_lock. */
241 int mux_out;
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;
250 struct QMPRequest {
251 /* Owner of the request */
252 Monitor *mon;
253 /* "id" field of the request */
254 QObject *id;
256 * Request object to be handled or Error to be reported
257 * (exactly one of them is non-null)
259 QObject *req;
260 Error *err;
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)
333 if (!mon->rs)
334 return;
336 readline_start(mon->rs, "(qemu) ", 0, monitor_command_cb, NULL);
337 if (show_prompt)
338 readline_show_prompt(mon->rs);
341 int monitor_read_password(Monitor *mon, ReadLineFunc *readline_func,
342 void *opaque)
344 if (mon->rs) {
345 readline_start(mon->rs, "Password: ", 1, readline_func, opaque);
346 /* prompt is printed on return from the command handler */
347 return 0;
348 } else {
349 monitor_printf(mon, "terminal does not support password prompting\n");
350 return -ENOTTY;
354 static void qmp_request_free(QMPRequest *req)
356 qobject_unref(req->id);
357 qobject_unref(req->req);
358 error_free(req->err);
359 g_free(req);
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,
381 void *opaque)
383 Monitor *mon = opaque;
385 qemu_mutex_lock(&mon->mon_lock);
386 mon->out_watch = 0;
387 monitor_flush_locked(mon);
388 qemu_mutex_unlock(&mon->mon_lock);
389 return FALSE;
392 /* Caller must hold mon->mon_lock */
393 static void monitor_flush_locked(Monitor *mon)
395 int rc;
396 size_t len;
397 const char *buf;
399 if (mon->skip_flush) {
400 return;
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();
412 return;
414 if (rc > 0) {
415 /* partial write */
416 QString *tmp = qstring_from_str(buf + rc);
417 qobject_unref(mon->outbuf);
418 mon->outbuf = tmp;
420 if (mon->out_watch == 0) {
421 mon->out_watch =
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)
438 char c;
440 qemu_mutex_lock(&mon->mon_lock);
441 for(;;) {
442 c = *str++;
443 if (c == '\0')
444 break;
445 if (c == '\n') {
446 qstring_append_chr(mon->outbuf, '\r');
448 qstring_append_chr(mon->outbuf, c);
449 if (c == '\n') {
450 monitor_flush_locked(mon);
453 qemu_mutex_unlock(&mon->mon_lock);
456 void monitor_vprintf(Monitor *mon, const char *fmt, va_list ap)
458 char *buf;
460 if (!mon)
461 return;
463 if (monitor_is_qmp(mon)) {
464 return;
467 buf = g_strdup_vprintf(fmt, ap);
468 monitor_puts(mon, buf);
469 g_free(buf);
472 void monitor_printf(Monitor *mon, const char *fmt, ...)
474 va_list ap;
475 va_start(ap, fmt);
476 monitor_vprintf(mon, fmt, ap);
477 va_end(ap);
480 int monitor_fprintf(FILE *stream, const char *fmt, ...)
482 va_list ap;
483 va_start(ap, fmt);
484 monitor_vprintf((Monitor *)stream, fmt, ap);
485 va_end(ap);
486 return 0;
489 static void qmp_send_response(Monitor *mon, const QDict *rsp)
491 const QObject *data = QOBJECT(rsp);
492 QString *json;
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));
501 qobject_unref(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)
521 Monitor *mon;
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.
538 static void
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);
550 if (!evconf->rate) {
551 /* Unthrottled event */
552 monitor_qapi_event_emit(event, qdict);
553 } else {
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));
560 if (evstate) {
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);
568 } else {
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,
585 evstate);
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 {
603 QAPIEvent event;
604 QDict *qdict;
605 QSIMPLEQ_ENTRY(MonitorQapiEvent) entry;
606 } MonitorQapiEvent;
607 static __thread QSIMPLEQ_HEAD(, MonitorQapiEvent) event_queue;
608 static __thread bool reentered;
609 MonitorQapiEvent *ev;
611 if (!reentered) {
612 QSIMPLEQ_INIT(&event_queue);
615 ev = g_new(MonitorQapiEvent, 1);
616 ev->qdict = qobject_ref(qdict);
617 ev->event = event;
618 QSIMPLEQ_INSERT_TAIL(&event_queue, ev, entry);
619 if (reentered) {
620 return;
623 reentered = true;
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);
629 g_free(ev);
632 reentered = false;
636 * This function runs evconf->rate ns after sending a throttled
637 * event.
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);
655 } else {
656 g_hash_table_remove(monitor_qapi_event_state, evstate);
657 qobject_unref(evstate->data);
658 timer_free(evstate->timer);
659 g_free(evstate);
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"));
678 return hash;
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) {
687 return FALSE;
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"));
700 return TRUE;
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,
714 bool use_io_thread)
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)
748 char *output = NULL;
749 Monitor *old_mon, hmp;
751 monitor_data_init(&hmp, true, false);
753 old_mon = cur_mon;
754 cur_mon = &hmp;
756 if (has_cpu_index) {
757 int ret = monitor_set_cpu(cpu_index);
758 if (ret < 0) {
759 cur_mon = old_mon;
760 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cpu-index",
761 "a CPU number");
762 goto out;
766 handle_hmp_command(&hmp, command_line);
767 cur_mon = old_mon;
769 qemu_mutex_lock(&hmp.mon_lock);
770 if (qstring_get_length(hmp.outbuf) > 0) {
771 output = g_strdup(qstring_get_str(hmp.outbuf));
772 } else {
773 output = g_strdup("");
775 qemu_mutex_unlock(&hmp.mon_lock);
777 out:
778 monitor_data_destroy(&hmp);
779 return output;
782 static int compare_cmd(const char *name, const char *list)
784 const char *p, *pstart;
785 int len;
786 len = strlen(name);
787 p = list;
788 for(;;) {
789 pstart = p;
790 p = qemu_strchrnul(p, '|');
791 if ((p - pstart) == len && !memcmp(pstart, name, len))
792 return 1;
793 if (*p == '\0')
794 break;
795 p++;
797 return 0;
800 static int get_str(char *buf, int buf_size, const char **pp)
802 const char *p;
803 char *q;
804 int c;
806 q = buf;
807 p = *pp;
808 while (qemu_isspace(*p)) {
809 p++;
811 if (*p == '\0') {
812 fail:
813 *q = '\0';
814 *pp = p;
815 return -1;
817 if (*p == '\"') {
818 p++;
819 while (*p != '\0' && *p != '\"') {
820 if (*p == '\\') {
821 p++;
822 c = *p++;
823 switch (c) {
824 case 'n':
825 c = '\n';
826 break;
827 case 'r':
828 c = '\r';
829 break;
830 case '\\':
831 case '\'':
832 case '\"':
833 break;
834 default:
835 printf("unsupported escape code: '\\%c'\n", c);
836 goto fail;
838 if ((q - buf) < buf_size - 1) {
839 *q++ = c;
841 } else {
842 if ((q - buf) < buf_size - 1) {
843 *q++ = *p;
845 p++;
848 if (*p != '\"') {
849 printf("unterminated string\n");
850 goto fail;
852 p++;
853 } else {
854 while (*p != '\0' && !qemu_isspace(*p)) {
855 if ((q - buf) < buf_size - 1) {
856 *q++ = *p;
858 p++;
861 *q = '\0';
862 *pp = p;
863 return 0;
866 #define MAX_ARGS 16
868 static void free_cmdline_args(char **args, int nb_args)
870 int i;
872 assert(nb_args <= MAX_ARGS);
874 for (i = 0; i < nb_args; i++) {
875 g_free(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
885 * NOT be NULL.
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)
896 const char *p;
897 int nb_args, ret;
898 char buf[1024];
900 p = cmdline;
901 nb_args = 0;
902 for (;;) {
903 while (qemu_isspace(*p)) {
904 p++;
906 if (*p == '\0') {
907 break;
909 if (nb_args >= MAX_ARGS) {
910 goto fail;
912 ret = get_str(buf, sizeof(buf), &p);
913 if (ret < 0) {
914 goto fail;
916 args[nb_args] = g_strdup(buf);
917 nb_args++;
919 *pnb_args = nb_args;
920 return 0;
922 fail:
923 free_cmdline_args(args, nb_args);
924 return -1;
928 * Can command @cmd be executed in preconfig state?
930 static bool cmd_can_preconfig(const mon_cmd_t *cmd)
932 if (!cmd->flags) {
933 return false;
936 return strchr(cmd->flags, 'p');
939 static void help_cmd_dump_one(Monitor *mon,
940 const mon_cmd_t *cmd,
941 char **prefix_args,
942 int prefix_args_nb)
944 int i;
946 if (runstate_check(RUN_STATE_PRECONFIG) && !cmd_can_preconfig(cmd)) {
947 return;
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;
961 size_t i;
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);
968 return;
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);
980 } else {
981 help_cmd_dump_one(mon, cmd, args, arg_index);
983 return;
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];
997 int nb_args = 0;
999 /* 1. parse user input */
1000 if (name) {
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);
1009 return;
1012 if (parse_cmdline(name, &nb_args, args) < 0) {
1013 return;
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;
1036 if (vcpu < 0) {
1037 monitor_printf(mon, "argument vcpu must be positive");
1038 return;
1041 qmp_trace_event_set_state(tp_name, new_state, true, true, has_vcpu, vcpu, &local_err);
1042 if (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");
1053 if (!op) {
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")) {
1062 if (arg) {
1063 st_set_trace_file(arg);
1065 } else {
1066 monitor_printf(mon, "unexpected argument \"%s\"\n", op);
1067 help_cmd(mon, "trace-file");
1070 #endif
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) {
1082 return;
1085 info = g_malloc0(sizeof(*info));
1086 info->value = g_malloc0(sizeof(*info->value));
1087 info->value->name = g_strdup(cmd->name);
1088 info->next = *list;
1089 *list = info;
1092 CommandInfoList *qmp_query_commands(Error **errp)
1094 CommandInfoList *list = NULL;
1096 qmp_for_each_command(cur_mon->qmp.commands, query_commands_cb, &list);
1098 return 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;
1109 QAPIEvent e;
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;
1119 ev_list = info;
1122 return 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,
1135 Error **errp)
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,
1154 QCO_NO_OPTIONS);
1155 qmp_register_command(&qmp_commands, "netdev_add", qmp_netdev_add,
1156 QCO_NO_OPTIONS);
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,
1181 Error **errp)
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]) {
1190 if (!unavailable) {
1191 unavailable = g_string_new(QMPCapability_str(list->value));
1192 } else {
1193 g_string_append_printf(unavailable, ", %s",
1194 QMPCapability_str(list->value));
1197 capab[list->value] = true;
1200 if (unavailable) {
1201 error_setg(errp, "Capability %s not available", unavailable->str);
1202 g_string_free(unavailable, true);
1203 return false;
1206 memcpy(mon->qmp.capab, capab, sizeof(capab));
1207 return true;
1210 void qmp_qmp_capabilities(bool has_enable, QMPCapabilityList *enable,
1211 Error **errp)
1213 if (cur_mon->qmp.commands == &qmp_commands) {
1214 error_set(errp, ERROR_CLASS_COMMAND_NOT_FOUND,
1215 "Capabilities negotiation is already complete, command "
1216 "ignored");
1217 return;
1220 if (!qmp_caps_accept(cur_mon, enable, errp)) {
1221 return;
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)
1230 CPUState *cpu;
1232 cpu = qemu_get_cpu(cpu_index);
1233 if (cpu == NULL) {
1234 return -1;
1236 g_free(cur_mon->mon_cpu_path);
1237 cur_mon->mon_cpu_path = object_get_canonical_path(OBJECT(cpu));
1238 return 0;
1241 /* Callers must hold BQL. */
1242 static CPUState *mon_get_cpu_sync(bool synchronize)
1244 CPUState *cpu;
1246 if (cur_mon->mon_cpu_path) {
1247 cpu = (CPUState *) object_resolve_path_type(cur_mon->mon_cpu_path,
1248 TYPE_CPU, NULL);
1249 if (!cpu) {
1250 g_free(cur_mon->mon_cpu_path);
1251 cur_mon->mon_cpu_path = NULL;
1254 if (!cur_mon->mon_cpu_path) {
1255 if (!first_cpu) {
1256 return NULL;
1258 monitor_set_cpu(first_cpu->cpu_index);
1259 cpu = first_cpu;
1261 if (synchronize) {
1262 cpu_synchronize_state(cpu);
1264 return 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);
1289 CPUState *cs;
1291 if (all_cpus) {
1292 CPU_FOREACH(cs) {
1293 monitor_printf(mon, "\nCPU#%d\n", cs->cpu_index);
1294 cpu_dump_state(cs, (FILE *)mon, monitor_fprintf, CPU_DUMP_FPU);
1296 } else {
1297 cs = mon_get_cpu();
1299 if (!cs) {
1300 monitor_printf(mon, "No CPU available\n");
1301 return;
1304 cpu_dump_state(cs, (FILE *)mon, monitor_fprintf, CPU_DUMP_FPU);
1308 #ifdef CONFIG_TCG
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");
1313 return;
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);
1324 #endif
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)
1339 int i;
1340 const char *str;
1342 if (!mon->rs)
1343 return;
1344 i = 0;
1345 for(;;) {
1346 str = readline_get_history(mon->rs, i);
1347 if (!str)
1348 break;
1349 monitor_printf(mon, "%d: '%s'\n", i, str);
1350 i++;
1354 static void hmp_info_cpustats(Monitor *mon, const QDict *qdict)
1356 CPUState *cs = mon_get_cpu();
1358 if (!cs) {
1359 monitor_printf(mon, "No CPU available\n");
1360 return;
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;
1374 if (name == NULL) {
1375 name = "*";
1377 if (vcpu < 0) {
1378 monitor_printf(mon, "argument vcpu must be positive");
1379 return;
1382 events = qmp_trace_event_get_state(name, has_vcpu, vcpu, &local_err);
1383 if (local_err) {
1384 error_report_err(local_err);
1385 return;
1388 for (elem = events; elem != NULL; elem = elem->next) {
1389 monitor_printf(mon, "%s : state %u\n",
1390 elem->value->name,
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,
1400 Error **errp)
1402 if (strcmp(protocol, "spice") == 0) {
1403 if (!qemu_using_spice(errp)) {
1404 return;
1407 if (!has_port && !has_tls_port) {
1408 error_setg(errp, QERR_MISSING_PARAMETER, "port/tls-port");
1409 return;
1412 if (qemu_spice_migrate_info(hostname,
1413 has_port ? port : -1,
1414 has_tls_port ? tls_port : -1,
1415 cert_subject)) {
1416 error_setg(errp, QERR_UNDEFINED_ERROR);
1417 return;
1419 return;
1422 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "protocol", "spice");
1425 static void hmp_logfile(Monitor *mon, const QDict *qdict)
1427 Error *err = NULL;
1429 qemu_set_log_filename(qdict_get_str(qdict, "filename"), &err);
1430 if (err) {
1431 error_report_err(err);
1435 static void hmp_log(Monitor *mon, const QDict *qdict)
1437 int mask;
1438 const char *items = qdict_get_str(qdict, "items");
1440 if (!strcmp(items, "none")) {
1441 mask = 0;
1442 } else {
1443 mask = qemu_str_to_log_mask(items);
1444 if (!mask) {
1445 help_cmd(mon, "log");
1446 return;
1449 qemu_set_log(mask);
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")) {
1456 singlestep = 1;
1457 } else if (!strcmp(option, "off")) {
1458 singlestep = 0;
1459 } else {
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");
1467 if (!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",
1471 device);
1472 } else if (strcmp(device, "none") == 0) {
1473 monitor_printf(mon, "Disabled gdbserver\n");
1474 } else {
1475 monitor_printf(mon, "Waiting for gdb connection on device '%s'\n",
1476 device);
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, "'");
1491 switch(c) {
1492 case '\'':
1493 monitor_printf(mon, "\\'");
1494 break;
1495 case '\\':
1496 monitor_printf(mon, "\\\\");
1497 break;
1498 case '\n':
1499 monitor_printf(mon, "\\n");
1500 break;
1501 case '\r':
1502 monitor_printf(mon, "\\r");
1503 break;
1504 default:
1505 if (c >= 32 && c <= 126) {
1506 monitor_printf(mon, "%c", c);
1507 } else {
1508 monitor_printf(mon, "\\x%02x", c);
1510 break;
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;
1519 uint8_t buf[16];
1520 uint64_t v;
1521 CPUState *cs = mon_get_cpu();
1523 if (!cs && (format == 'i' || !is_physical)) {
1524 monitor_printf(mon, "Can not dump without CPU\n");
1525 return;
1528 if (format == 'i') {
1529 monitor_disas(mon, cs, addr, count, is_physical);
1530 return;
1533 len = wsize * count;
1534 if (wsize == 1)
1535 line_size = 8;
1536 else
1537 line_size = 16;
1538 max_digits = 0;
1540 switch(format) {
1541 case 'o':
1542 max_digits = DIV_ROUND_UP(wsize * 8, 3);
1543 break;
1544 default:
1545 case 'x':
1546 max_digits = (wsize * 8) / 4;
1547 break;
1548 case 'u':
1549 case 'd':
1550 max_digits = DIV_ROUND_UP(wsize * 8 * 10, 33);
1551 break;
1552 case 'c':
1553 wsize = 1;
1554 break;
1557 while (len > 0) {
1558 if (is_physical)
1559 monitor_printf(mon, TARGET_FMT_plx ":", addr);
1560 else
1561 monitor_printf(mon, TARGET_FMT_lx ":", (target_ulong)addr);
1562 l = len;
1563 if (l > line_size)
1564 l = line_size;
1565 if (is_physical) {
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");
1571 break;
1573 } else {
1574 if (cpu_memory_rw_debug(cs, addr, buf, l, 0) < 0) {
1575 monitor_printf(mon, " Cannot access memory\n");
1576 break;
1579 i = 0;
1580 while (i < l) {
1581 switch(wsize) {
1582 default:
1583 case 1:
1584 v = ldub_p(buf + i);
1585 break;
1586 case 2:
1587 v = lduw_p(buf + i);
1588 break;
1589 case 4:
1590 v = (uint32_t)ldl_p(buf + i);
1591 break;
1592 case 8:
1593 v = ldq_p(buf + i);
1594 break;
1596 monitor_printf(mon, " ");
1597 switch(format) {
1598 case 'o':
1599 monitor_printf(mon, "%#*" PRIo64, max_digits, v);
1600 break;
1601 case 'x':
1602 monitor_printf(mon, "0x%0*" PRIx64, max_digits, v);
1603 break;
1604 case 'u':
1605 monitor_printf(mon, "%*" PRIu64, max_digits, v);
1606 break;
1607 case 'd':
1608 monitor_printf(mon, "%*" PRId64, max_digits, v);
1609 break;
1610 case 'c':
1611 monitor_printc(mon, v);
1612 break;
1614 i += wsize;
1616 monitor_printf(mon, "\n");
1617 addr += l;
1618 len -= l;
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(),
1645 addr, 1);
1647 if (!mrs.mr) {
1648 error_setg(errp, "No memory is mapped at address 0x%" HWADDR_PRIx, addr);
1649 return NULL;
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);
1655 return NULL;
1658 *p_mr = 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;
1667 void *ptr;
1669 ptr = gpa2hva(&mr, addr, &local_err);
1670 if (local_err) {
1671 error_report_err(local_err);
1672 return;
1675 monitor_printf(mon, "Host virtual address for 0x%" HWADDR_PRIx
1676 " (%s) is %p\n",
1677 addr, mr->name, ptr);
1679 memory_region_unref(mr);
1682 #ifdef CONFIG_LINUX
1683 static uint64_t vtop(void *ptr, Error **errp)
1685 uint64_t pinfo;
1686 uint64_t ret = -1;
1687 uintptr_t addr = (uintptr_t) ptr;
1688 uintptr_t pagesize = getpagesize();
1689 off_t offset = addr / pagesize * sizeof(pinfo);
1690 int fd;
1692 fd = open("/proc/self/pagemap", O_RDONLY);
1693 if (fd == -1) {
1694 error_setg_errno(errp, errno, "Cannot open /proc/self/pagemap");
1695 return -1;
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");
1703 goto out;
1705 if ((pinfo & (1ull << 63)) == 0) {
1706 error_setg(errp, "Page not present");
1707 goto out;
1709 ret = ((pinfo & 0x007fffffffffffffull) * pagesize) | (addr & (pagesize - 1));
1711 out:
1712 close(fd);
1713 return ret;
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;
1721 void *ptr;
1722 uint64_t physaddr;
1724 ptr = gpa2hva(&mr, addr, &local_err);
1725 if (local_err) {
1726 error_report_err(local_err);
1727 return;
1730 physaddr = vtop(ptr, &local_err);
1731 if (local_err) {
1732 error_report_err(local_err);
1733 } else {
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);
1741 #endif
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");
1748 switch(format) {
1749 case 'o':
1750 monitor_printf(mon, "%#" HWADDR_PRIo, val);
1751 break;
1752 case 'x':
1753 monitor_printf(mon, "%#" HWADDR_PRIx, val);
1754 break;
1755 case 'u':
1756 monitor_printf(mon, "%" HWADDR_PRIu, val);
1757 break;
1758 default:
1759 case 'd':
1760 monitor_printf(mon, "%" HWADDR_PRId, val);
1761 break;
1762 case 'c':
1763 monitor_printc(mon, val);
1764 break;
1766 monitor_printf(mon, "\n");
1769 static void hmp_sum(Monitor *mon, const QDict *qdict)
1771 uint32_t addr;
1772 uint16_t sum;
1773 uint32_t start = qdict_get_int(qdict, "start");
1774 uint32_t size = qdict_get_int(qdict, "size");
1776 sum = 0;
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);
1782 sum += val;
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);
1801 if (dz_str) {
1802 dz = strtol(dz_str, NULL, 0);
1803 if (dz != 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) {
1823 return;
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");
1835 uint32_t val;
1836 int suffix;
1838 if (has_index) {
1839 int index = qdict_get_int(qdict, "index");
1840 cpu_outb(addr & IOPORTS_MASK, index & 0xff);
1841 addr++;
1843 addr &= 0xffff;
1845 switch(size) {
1846 default:
1847 case 1:
1848 val = cpu_inb(addr);
1849 suffix = 'b';
1850 break;
1851 case 2:
1852 val = cpu_inw(addr);
1853 suffix = 'w';
1854 break;
1855 case 4:
1856 val = cpu_inl(addr);
1857 suffix = 'l';
1858 break;
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;
1872 switch (size) {
1873 default:
1874 case 1:
1875 cpu_outb(addr, val);
1876 break;
1877 case 2:
1878 cpu_outw(addr, val);
1879 break;
1880 case 4:
1881 cpu_outl(addr, val);
1882 break;
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);
1892 if (local_err) {
1893 error_report_err(local_err);
1894 } else {
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,
1906 owner);
1909 static void hmp_info_numa(Monitor *mon, const QDict *qdict)
1911 int i;
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);
1935 g_free(node_mem);
1938 #ifdef CONFIG_PROFILER
1940 int64_t dev_time;
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;
1946 int64_t delta;
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;
1956 dev_time = 0;
1958 #else
1959 static void hmp_info_profile(Monitor *mon, const QDict *qdict)
1961 monitor_printf(mon, "Internal profiler not compiled\n");
1963 #endif
1965 /* Capture support */
1966 static QLIST_HEAD (capture_list_head, CaptureState) capture_head;
1968 static void hmp_info_capture(Monitor *mon, const QDict *qdict)
1970 int i;
1971 CaptureState *s;
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)
1981 int i;
1982 int n = qdict_get_int(qdict, "n");
1983 CaptureState *s;
1985 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
1986 if (i == n) {
1987 s->ops.destroy (s->opaque);
1988 QLIST_REMOVE (s, entries);
1989 g_free (s);
1990 return;
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);
2004 CaptureState *s;
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");
2014 g_free (s);
2015 return;
2017 QLIST_INSERT_HEAD (&capture_head, s, entries);
2020 static QAuthZList *find_auth(Monitor *mon, const char *name)
2022 Object *obj;
2023 Object *container;
2025 container = object_get_objects_root();
2026 obj = object_resolve_path_component(container, name);
2027 if (!obj) {
2028 monitor_printf(mon, "acl: unknown list '%s'\n", name);
2029 return NULL;
2032 return QAUTHZ_LIST(obj);
2035 static bool warn_acl;
2036 static void hmp_warn_acl(void)
2038 if (warn_acl) {
2039 return;
2041 error_report("The acl_show, acl_reset, acl_policy, acl_add, acl_remove "
2042 "commands are deprecated with no replacement. Authorization "
2043 "for VNC should be performed using the pluggable QAuthZ "
2044 "objects");
2045 warn_acl = true;
2048 static void hmp_acl_show(Monitor *mon, const QDict *qdict)
2050 const char *aclname = qdict_get_str(qdict, "aclname");
2051 QAuthZList *auth = find_auth(mon, aclname);
2052 QAuthZListRuleList *rules;
2053 size_t i = 0;
2055 hmp_warn_acl();
2057 if (!auth) {
2058 return;
2061 monitor_printf(mon, "policy: %s\n",
2062 QAuthZListPolicy_str(auth->policy));
2064 rules = auth->rules;
2065 while (rules) {
2066 QAuthZListRule *rule = rules->value;
2067 i++;
2068 monitor_printf(mon, "%zu: %s %s\n", i,
2069 QAuthZListPolicy_str(rule->policy),
2070 rule->match);
2071 rules = rules->next;
2075 static void hmp_acl_reset(Monitor *mon, const QDict *qdict)
2077 const char *aclname = qdict_get_str(qdict, "aclname");
2078 QAuthZList *auth = find_auth(mon, aclname);
2080 hmp_warn_acl();
2082 if (!auth) {
2083 return;
2086 auth->policy = QAUTHZ_LIST_POLICY_DENY;
2087 qapi_free_QAuthZListRuleList(auth->rules);
2088 auth->rules = NULL;
2089 monitor_printf(mon, "acl: removed all rules\n");
2092 static void hmp_acl_policy(Monitor *mon, const QDict *qdict)
2094 const char *aclname = qdict_get_str(qdict, "aclname");
2095 const char *policy = qdict_get_str(qdict, "policy");
2096 QAuthZList *auth = find_auth(mon, aclname);
2097 int val;
2098 Error *err = NULL;
2100 hmp_warn_acl();
2102 if (!auth) {
2103 return;
2106 val = qapi_enum_parse(&QAuthZListPolicy_lookup,
2107 policy,
2108 QAUTHZ_LIST_POLICY_DENY,
2109 &err);
2110 if (err) {
2111 error_free(err);
2112 monitor_printf(mon, "acl: unknown policy '%s', "
2113 "expected 'deny' or 'allow'\n", policy);
2114 } else {
2115 auth->policy = val;
2116 if (auth->policy == QAUTHZ_LIST_POLICY_ALLOW) {
2117 monitor_printf(mon, "acl: policy set to 'allow'\n");
2118 } else {
2119 monitor_printf(mon, "acl: policy set to 'deny'\n");
2124 static QAuthZListFormat hmp_acl_get_format(const char *match)
2126 if (strchr(match, '*')) {
2127 return QAUTHZ_LIST_FORMAT_GLOB;
2128 } else {
2129 return QAUTHZ_LIST_FORMAT_EXACT;
2133 static void hmp_acl_add(Monitor *mon, const QDict *qdict)
2135 const char *aclname = qdict_get_str(qdict, "aclname");
2136 const char *match = qdict_get_str(qdict, "match");
2137 const char *policystr = qdict_get_str(qdict, "policy");
2138 int has_index = qdict_haskey(qdict, "index");
2139 int index = qdict_get_try_int(qdict, "index", -1);
2140 QAuthZList *auth = find_auth(mon, aclname);
2141 Error *err = NULL;
2142 QAuthZListPolicy policy;
2143 QAuthZListFormat format;
2144 size_t i = 0;
2146 hmp_warn_acl();
2148 if (!auth) {
2149 return;
2152 policy = qapi_enum_parse(&QAuthZListPolicy_lookup,
2153 policystr,
2154 QAUTHZ_LIST_POLICY_DENY,
2155 &err);
2156 if (err) {
2157 error_free(err);
2158 monitor_printf(mon, "acl: unknown policy '%s', "
2159 "expected 'deny' or 'allow'\n", policystr);
2160 return;
2163 format = hmp_acl_get_format(match);
2165 if (has_index && index == 0) {
2166 monitor_printf(mon, "acl: unable to add acl entry\n");
2167 return;
2170 if (has_index) {
2171 i = qauthz_list_insert_rule(auth, match, policy,
2172 format, index - 1, &err);
2173 } else {
2174 i = qauthz_list_append_rule(auth, match, policy,
2175 format, &err);
2177 if (err) {
2178 monitor_printf(mon, "acl: unable to add rule: %s",
2179 error_get_pretty(err));
2180 error_free(err);
2181 } else {
2182 monitor_printf(mon, "acl: added rule at position %zu\n", i + 1);
2186 static void hmp_acl_remove(Monitor *mon, const QDict *qdict)
2188 const char *aclname = qdict_get_str(qdict, "aclname");
2189 const char *match = qdict_get_str(qdict, "match");
2190 QAuthZList *auth = find_auth(mon, aclname);
2191 ssize_t i = 0;
2193 hmp_warn_acl();
2195 if (!auth) {
2196 return;
2199 i = qauthz_list_delete_rule(auth, match);
2200 if (i >= 0) {
2201 monitor_printf(mon, "acl: removed rule at position %zu\n", i + 1);
2202 } else {
2203 monitor_printf(mon, "acl: no matching acl entry\n");
2207 void qmp_getfd(const char *fdname, Error **errp)
2209 mon_fd_t *monfd;
2210 int fd, tmp_fd;
2212 fd = qemu_chr_fe_get_msgfd(&cur_mon->chr);
2213 if (fd == -1) {
2214 error_setg(errp, QERR_FD_NOT_SUPPLIED);
2215 return;
2218 if (qemu_isdigit(fdname[0])) {
2219 close(fd);
2220 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "fdname",
2221 "a name not starting with a digit");
2222 return;
2225 qemu_mutex_lock(&cur_mon->mon_lock);
2226 QLIST_FOREACH(monfd, &cur_mon->fds, next) {
2227 if (strcmp(monfd->name, fdname) != 0) {
2228 continue;
2231 tmp_fd = monfd->fd;
2232 monfd->fd = fd;
2233 qemu_mutex_unlock(&cur_mon->mon_lock);
2234 /* Make sure close() is outside critical section */
2235 close(tmp_fd);
2236 return;
2239 monfd = g_malloc0(sizeof(mon_fd_t));
2240 monfd->name = g_strdup(fdname);
2241 monfd->fd = fd;
2243 QLIST_INSERT_HEAD(&cur_mon->fds, monfd, next);
2244 qemu_mutex_unlock(&cur_mon->mon_lock);
2247 void qmp_closefd(const char *fdname, Error **errp)
2249 mon_fd_t *monfd;
2250 int tmp_fd;
2252 qemu_mutex_lock(&cur_mon->mon_lock);
2253 QLIST_FOREACH(monfd, &cur_mon->fds, next) {
2254 if (strcmp(monfd->name, fdname) != 0) {
2255 continue;
2258 QLIST_REMOVE(monfd, next);
2259 tmp_fd = monfd->fd;
2260 g_free(monfd->name);
2261 g_free(monfd);
2262 qemu_mutex_unlock(&cur_mon->mon_lock);
2263 /* Make sure close() is outside critical section */
2264 close(tmp_fd);
2265 return;
2268 qemu_mutex_unlock(&cur_mon->mon_lock);
2269 error_setg(errp, QERR_FD_NOT_FOUND, fdname);
2272 int monitor_get_fd(Monitor *mon, const char *fdname, Error **errp)
2274 mon_fd_t *monfd;
2276 qemu_mutex_lock(&mon->mon_lock);
2277 QLIST_FOREACH(monfd, &mon->fds, next) {
2278 int fd;
2280 if (strcmp(monfd->name, fdname) != 0) {
2281 continue;
2284 fd = monfd->fd;
2286 /* caller takes ownership of fd */
2287 QLIST_REMOVE(monfd, next);
2288 g_free(monfd->name);
2289 g_free(monfd);
2290 qemu_mutex_unlock(&mon->mon_lock);
2292 return fd;
2295 qemu_mutex_unlock(&mon->mon_lock);
2296 error_setg(errp, "File descriptor named '%s' has not been found", fdname);
2297 return -1;
2300 static void monitor_fdset_cleanup(MonFdset *mon_fdset)
2302 MonFdsetFd *mon_fdset_fd;
2303 MonFdsetFd *mon_fdset_fd_next;
2305 QLIST_FOREACH_SAFE(mon_fdset_fd, &mon_fdset->fds, next, mon_fdset_fd_next) {
2306 if ((mon_fdset_fd->removed ||
2307 (QLIST_EMPTY(&mon_fdset->dup_fds) && mon_refcount == 0)) &&
2308 runstate_is_running()) {
2309 close(mon_fdset_fd->fd);
2310 g_free(mon_fdset_fd->opaque);
2311 QLIST_REMOVE(mon_fdset_fd, next);
2312 g_free(mon_fdset_fd);
2316 if (QLIST_EMPTY(&mon_fdset->fds) && QLIST_EMPTY(&mon_fdset->dup_fds)) {
2317 QLIST_REMOVE(mon_fdset, next);
2318 g_free(mon_fdset);
2322 static void monitor_fdsets_cleanup(void)
2324 MonFdset *mon_fdset;
2325 MonFdset *mon_fdset_next;
2327 qemu_mutex_lock(&mon_fdsets_lock);
2328 QLIST_FOREACH_SAFE(mon_fdset, &mon_fdsets, next, mon_fdset_next) {
2329 monitor_fdset_cleanup(mon_fdset);
2331 qemu_mutex_unlock(&mon_fdsets_lock);
2334 AddfdInfo *qmp_add_fd(bool has_fdset_id, int64_t fdset_id, bool has_opaque,
2335 const char *opaque, Error **errp)
2337 int fd;
2338 Monitor *mon = cur_mon;
2339 AddfdInfo *fdinfo;
2341 fd = qemu_chr_fe_get_msgfd(&mon->chr);
2342 if (fd == -1) {
2343 error_setg(errp, QERR_FD_NOT_SUPPLIED);
2344 goto error;
2347 fdinfo = monitor_fdset_add_fd(fd, has_fdset_id, fdset_id,
2348 has_opaque, opaque, errp);
2349 if (fdinfo) {
2350 return fdinfo;
2353 error:
2354 if (fd != -1) {
2355 close(fd);
2357 return NULL;
2360 void qmp_remove_fd(int64_t fdset_id, bool has_fd, int64_t fd, Error **errp)
2362 MonFdset *mon_fdset;
2363 MonFdsetFd *mon_fdset_fd;
2364 char fd_str[60];
2366 qemu_mutex_lock(&mon_fdsets_lock);
2367 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2368 if (mon_fdset->id != fdset_id) {
2369 continue;
2371 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2372 if (has_fd) {
2373 if (mon_fdset_fd->fd != fd) {
2374 continue;
2376 mon_fdset_fd->removed = true;
2377 break;
2378 } else {
2379 mon_fdset_fd->removed = true;
2382 if (has_fd && !mon_fdset_fd) {
2383 goto error;
2385 monitor_fdset_cleanup(mon_fdset);
2386 qemu_mutex_unlock(&mon_fdsets_lock);
2387 return;
2390 error:
2391 qemu_mutex_unlock(&mon_fdsets_lock);
2392 if (has_fd) {
2393 snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64 ", fd:%" PRId64,
2394 fdset_id, fd);
2395 } else {
2396 snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64, fdset_id);
2398 error_setg(errp, QERR_FD_NOT_FOUND, fd_str);
2401 FdsetInfoList *qmp_query_fdsets(Error **errp)
2403 MonFdset *mon_fdset;
2404 MonFdsetFd *mon_fdset_fd;
2405 FdsetInfoList *fdset_list = NULL;
2407 qemu_mutex_lock(&mon_fdsets_lock);
2408 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2409 FdsetInfoList *fdset_info = g_malloc0(sizeof(*fdset_info));
2410 FdsetFdInfoList *fdsetfd_list = NULL;
2412 fdset_info->value = g_malloc0(sizeof(*fdset_info->value));
2413 fdset_info->value->fdset_id = mon_fdset->id;
2415 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2416 FdsetFdInfoList *fdsetfd_info;
2418 fdsetfd_info = g_malloc0(sizeof(*fdsetfd_info));
2419 fdsetfd_info->value = g_malloc0(sizeof(*fdsetfd_info->value));
2420 fdsetfd_info->value->fd = mon_fdset_fd->fd;
2421 if (mon_fdset_fd->opaque) {
2422 fdsetfd_info->value->has_opaque = true;
2423 fdsetfd_info->value->opaque = g_strdup(mon_fdset_fd->opaque);
2424 } else {
2425 fdsetfd_info->value->has_opaque = false;
2428 fdsetfd_info->next = fdsetfd_list;
2429 fdsetfd_list = fdsetfd_info;
2432 fdset_info->value->fds = fdsetfd_list;
2434 fdset_info->next = fdset_list;
2435 fdset_list = fdset_info;
2437 qemu_mutex_unlock(&mon_fdsets_lock);
2439 return fdset_list;
2442 AddfdInfo *monitor_fdset_add_fd(int fd, bool has_fdset_id, int64_t fdset_id,
2443 bool has_opaque, const char *opaque,
2444 Error **errp)
2446 MonFdset *mon_fdset = NULL;
2447 MonFdsetFd *mon_fdset_fd;
2448 AddfdInfo *fdinfo;
2450 qemu_mutex_lock(&mon_fdsets_lock);
2451 if (has_fdset_id) {
2452 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2453 /* Break if match found or match impossible due to ordering by ID */
2454 if (fdset_id <= mon_fdset->id) {
2455 if (fdset_id < mon_fdset->id) {
2456 mon_fdset = NULL;
2458 break;
2463 if (mon_fdset == NULL) {
2464 int64_t fdset_id_prev = -1;
2465 MonFdset *mon_fdset_cur = QLIST_FIRST(&mon_fdsets);
2467 if (has_fdset_id) {
2468 if (fdset_id < 0) {
2469 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "fdset-id",
2470 "a non-negative value");
2471 qemu_mutex_unlock(&mon_fdsets_lock);
2472 return NULL;
2474 /* Use specified fdset ID */
2475 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2476 mon_fdset_cur = mon_fdset;
2477 if (fdset_id < mon_fdset_cur->id) {
2478 break;
2481 } else {
2482 /* Use first available fdset ID */
2483 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2484 mon_fdset_cur = mon_fdset;
2485 if (fdset_id_prev == mon_fdset_cur->id - 1) {
2486 fdset_id_prev = mon_fdset_cur->id;
2487 continue;
2489 break;
2493 mon_fdset = g_malloc0(sizeof(*mon_fdset));
2494 if (has_fdset_id) {
2495 mon_fdset->id = fdset_id;
2496 } else {
2497 mon_fdset->id = fdset_id_prev + 1;
2500 /* The fdset list is ordered by fdset ID */
2501 if (!mon_fdset_cur) {
2502 QLIST_INSERT_HEAD(&mon_fdsets, mon_fdset, next);
2503 } else if (mon_fdset->id < mon_fdset_cur->id) {
2504 QLIST_INSERT_BEFORE(mon_fdset_cur, mon_fdset, next);
2505 } else {
2506 QLIST_INSERT_AFTER(mon_fdset_cur, mon_fdset, next);
2510 mon_fdset_fd = g_malloc0(sizeof(*mon_fdset_fd));
2511 mon_fdset_fd->fd = fd;
2512 mon_fdset_fd->removed = false;
2513 if (has_opaque) {
2514 mon_fdset_fd->opaque = g_strdup(opaque);
2516 QLIST_INSERT_HEAD(&mon_fdset->fds, mon_fdset_fd, next);
2518 fdinfo = g_malloc0(sizeof(*fdinfo));
2519 fdinfo->fdset_id = mon_fdset->id;
2520 fdinfo->fd = mon_fdset_fd->fd;
2522 qemu_mutex_unlock(&mon_fdsets_lock);
2523 return fdinfo;
2526 int monitor_fdset_get_fd(int64_t fdset_id, int flags)
2528 #ifdef _WIN32
2529 return -ENOENT;
2530 #else
2531 MonFdset *mon_fdset;
2532 MonFdsetFd *mon_fdset_fd;
2533 int mon_fd_flags;
2534 int ret;
2536 qemu_mutex_lock(&mon_fdsets_lock);
2537 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2538 if (mon_fdset->id != fdset_id) {
2539 continue;
2541 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2542 mon_fd_flags = fcntl(mon_fdset_fd->fd, F_GETFL);
2543 if (mon_fd_flags == -1) {
2544 ret = -errno;
2545 goto out;
2548 if ((flags & O_ACCMODE) == (mon_fd_flags & O_ACCMODE)) {
2549 ret = mon_fdset_fd->fd;
2550 goto out;
2553 ret = -EACCES;
2554 goto out;
2556 ret = -ENOENT;
2558 out:
2559 qemu_mutex_unlock(&mon_fdsets_lock);
2560 return ret;
2561 #endif
2564 int monitor_fdset_dup_fd_add(int64_t fdset_id, int dup_fd)
2566 MonFdset *mon_fdset;
2567 MonFdsetFd *mon_fdset_fd_dup;
2569 qemu_mutex_lock(&mon_fdsets_lock);
2570 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2571 if (mon_fdset->id != fdset_id) {
2572 continue;
2574 QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
2575 if (mon_fdset_fd_dup->fd == dup_fd) {
2576 goto err;
2579 mon_fdset_fd_dup = g_malloc0(sizeof(*mon_fdset_fd_dup));
2580 mon_fdset_fd_dup->fd = dup_fd;
2581 QLIST_INSERT_HEAD(&mon_fdset->dup_fds, mon_fdset_fd_dup, next);
2582 qemu_mutex_unlock(&mon_fdsets_lock);
2583 return 0;
2586 err:
2587 qemu_mutex_unlock(&mon_fdsets_lock);
2588 return -1;
2591 static int monitor_fdset_dup_fd_find_remove(int dup_fd, bool remove)
2593 MonFdset *mon_fdset;
2594 MonFdsetFd *mon_fdset_fd_dup;
2596 qemu_mutex_lock(&mon_fdsets_lock);
2597 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2598 QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
2599 if (mon_fdset_fd_dup->fd == dup_fd) {
2600 if (remove) {
2601 QLIST_REMOVE(mon_fdset_fd_dup, next);
2602 if (QLIST_EMPTY(&mon_fdset->dup_fds)) {
2603 monitor_fdset_cleanup(mon_fdset);
2605 goto err;
2606 } else {
2607 qemu_mutex_unlock(&mon_fdsets_lock);
2608 return mon_fdset->id;
2614 err:
2615 qemu_mutex_unlock(&mon_fdsets_lock);
2616 return -1;
2619 int monitor_fdset_dup_fd_find(int dup_fd)
2621 return monitor_fdset_dup_fd_find_remove(dup_fd, false);
2624 void monitor_fdset_dup_fd_remove(int dup_fd)
2626 monitor_fdset_dup_fd_find_remove(dup_fd, true);
2629 int monitor_fd_param(Monitor *mon, const char *fdname, Error **errp)
2631 int fd;
2632 Error *local_err = NULL;
2634 if (!qemu_isdigit(fdname[0]) && mon) {
2635 fd = monitor_get_fd(mon, fdname, &local_err);
2636 } else {
2637 fd = qemu_parse_fd(fdname);
2638 if (fd == -1) {
2639 error_setg(&local_err, "Invalid file descriptor number '%s'",
2640 fdname);
2643 if (local_err) {
2644 error_propagate(errp, local_err);
2645 assert(fd == -1);
2646 } else {
2647 assert(fd != -1);
2650 return fd;
2653 /* Please update hmp-commands.hx when adding or changing commands */
2654 static mon_cmd_t info_cmds[] = {
2655 #include "hmp-commands-info.h"
2656 { NULL, NULL, },
2659 /* mon_cmds and info_cmds would be sorted at runtime */
2660 static mon_cmd_t mon_cmds[] = {
2661 #include "hmp-commands.h"
2662 { NULL, NULL, },
2665 /*******************************************************************/
2667 static const char *pch;
2668 static sigjmp_buf expr_env;
2671 static void GCC_FMT_ATTR(2, 3) QEMU_NORETURN
2672 expr_error(Monitor *mon, const char *fmt, ...)
2674 va_list ap;
2675 va_start(ap, fmt);
2676 monitor_vprintf(mon, fmt, ap);
2677 monitor_printf(mon, "\n");
2678 va_end(ap);
2679 siglongjmp(expr_env, 1);
2682 /* return 0 if OK, -1 if not found */
2683 static int get_monitor_def(target_long *pval, const char *name)
2685 const MonitorDef *md = target_monitor_defs();
2686 CPUState *cs = mon_get_cpu();
2687 void *ptr;
2688 uint64_t tmp = 0;
2689 int ret;
2691 if (cs == NULL || md == NULL) {
2692 return -1;
2695 for(; md->name != NULL; md++) {
2696 if (compare_cmd(name, md->name)) {
2697 if (md->get_value) {
2698 *pval = md->get_value(md, md->offset);
2699 } else {
2700 CPUArchState *env = mon_get_cpu_env();
2701 ptr = (uint8_t *)env + md->offset;
2702 switch(md->type) {
2703 case MD_I32:
2704 *pval = *(int32_t *)ptr;
2705 break;
2706 case MD_TLONG:
2707 *pval = *(target_long *)ptr;
2708 break;
2709 default:
2710 *pval = 0;
2711 break;
2714 return 0;
2718 ret = target_get_monitor_def(cs, name, &tmp);
2719 if (!ret) {
2720 *pval = (target_long) tmp;
2723 return ret;
2726 static void next(void)
2728 if (*pch != '\0') {
2729 pch++;
2730 while (qemu_isspace(*pch))
2731 pch++;
2735 static int64_t expr_sum(Monitor *mon);
2737 static int64_t expr_unary(Monitor *mon)
2739 int64_t n;
2740 char *p;
2741 int ret;
2743 switch(*pch) {
2744 case '+':
2745 next();
2746 n = expr_unary(mon);
2747 break;
2748 case '-':
2749 next();
2750 n = -expr_unary(mon);
2751 break;
2752 case '~':
2753 next();
2754 n = ~expr_unary(mon);
2755 break;
2756 case '(':
2757 next();
2758 n = expr_sum(mon);
2759 if (*pch != ')') {
2760 expr_error(mon, "')' expected");
2762 next();
2763 break;
2764 case '\'':
2765 pch++;
2766 if (*pch == '\0')
2767 expr_error(mon, "character constant expected");
2768 n = *pch;
2769 pch++;
2770 if (*pch != '\'')
2771 expr_error(mon, "missing terminating \' character");
2772 next();
2773 break;
2774 case '$':
2776 char buf[128], *q;
2777 target_long reg=0;
2779 pch++;
2780 q = buf;
2781 while ((*pch >= 'a' && *pch <= 'z') ||
2782 (*pch >= 'A' && *pch <= 'Z') ||
2783 (*pch >= '0' && *pch <= '9') ||
2784 *pch == '_' || *pch == '.') {
2785 if ((q - buf) < sizeof(buf) - 1)
2786 *q++ = *pch;
2787 pch++;
2789 while (qemu_isspace(*pch))
2790 pch++;
2791 *q = 0;
2792 ret = get_monitor_def(&reg, buf);
2793 if (ret < 0)
2794 expr_error(mon, "unknown register");
2795 n = reg;
2797 break;
2798 case '\0':
2799 expr_error(mon, "unexpected end of expression");
2800 n = 0;
2801 break;
2802 default:
2803 errno = 0;
2804 n = strtoull(pch, &p, 0);
2805 if (errno == ERANGE) {
2806 expr_error(mon, "number too large");
2808 if (pch == p) {
2809 expr_error(mon, "invalid char '%c' in expression", *p);
2811 pch = p;
2812 while (qemu_isspace(*pch))
2813 pch++;
2814 break;
2816 return n;
2820 static int64_t expr_prod(Monitor *mon)
2822 int64_t val, val2;
2823 int op;
2825 val = expr_unary(mon);
2826 for(;;) {
2827 op = *pch;
2828 if (op != '*' && op != '/' && op != '%')
2829 break;
2830 next();
2831 val2 = expr_unary(mon);
2832 switch(op) {
2833 default:
2834 case '*':
2835 val *= val2;
2836 break;
2837 case '/':
2838 case '%':
2839 if (val2 == 0)
2840 expr_error(mon, "division by zero");
2841 if (op == '/')
2842 val /= val2;
2843 else
2844 val %= val2;
2845 break;
2848 return val;
2851 static int64_t expr_logic(Monitor *mon)
2853 int64_t val, val2;
2854 int op;
2856 val = expr_prod(mon);
2857 for(;;) {
2858 op = *pch;
2859 if (op != '&' && op != '|' && op != '^')
2860 break;
2861 next();
2862 val2 = expr_prod(mon);
2863 switch(op) {
2864 default:
2865 case '&':
2866 val &= val2;
2867 break;
2868 case '|':
2869 val |= val2;
2870 break;
2871 case '^':
2872 val ^= val2;
2873 break;
2876 return val;
2879 static int64_t expr_sum(Monitor *mon)
2881 int64_t val, val2;
2882 int op;
2884 val = expr_logic(mon);
2885 for(;;) {
2886 op = *pch;
2887 if (op != '+' && op != '-')
2888 break;
2889 next();
2890 val2 = expr_logic(mon);
2891 if (op == '+')
2892 val += val2;
2893 else
2894 val -= val2;
2896 return val;
2899 static int get_expr(Monitor *mon, int64_t *pval, const char **pp)
2901 pch = *pp;
2902 if (sigsetjmp(expr_env, 0)) {
2903 *pp = pch;
2904 return -1;
2906 while (qemu_isspace(*pch))
2907 pch++;
2908 *pval = expr_sum(mon);
2909 *pp = pch;
2910 return 0;
2913 static int get_double(Monitor *mon, double *pval, const char **pp)
2915 const char *p = *pp;
2916 char *tailp;
2917 double d;
2919 d = strtod(p, &tailp);
2920 if (tailp == p) {
2921 monitor_printf(mon, "Number expected\n");
2922 return -1;
2924 if (d != d || d - d != 0) {
2925 /* NaN or infinity */
2926 monitor_printf(mon, "Bad number\n");
2927 return -1;
2929 *pval = d;
2930 *pp = tailp;
2931 return 0;
2935 * Store the command-name in cmdname, and return a pointer to
2936 * the remaining of the command string.
2938 static const char *get_command_name(const char *cmdline,
2939 char *cmdname, size_t nlen)
2941 size_t len;
2942 const char *p, *pstart;
2944 p = cmdline;
2945 while (qemu_isspace(*p))
2946 p++;
2947 if (*p == '\0')
2948 return NULL;
2949 pstart = p;
2950 while (*p != '\0' && *p != '/' && !qemu_isspace(*p))
2951 p++;
2952 len = p - pstart;
2953 if (len > nlen - 1)
2954 len = nlen - 1;
2955 memcpy(cmdname, pstart, len);
2956 cmdname[len] = '\0';
2957 return p;
2961 * Read key of 'type' into 'key' and return the current
2962 * 'type' pointer.
2964 static char *key_get_info(const char *type, char **key)
2966 size_t len;
2967 char *p, *str;
2969 if (*type == ',')
2970 type++;
2972 p = strchr(type, ':');
2973 if (!p) {
2974 *key = NULL;
2975 return NULL;
2977 len = p - type;
2979 str = g_malloc(len + 1);
2980 memcpy(str, type, len);
2981 str[len] = '\0';
2983 *key = str;
2984 return ++p;
2987 static int default_fmt_format = 'x';
2988 static int default_fmt_size = 4;
2990 static int is_valid_option(const char *c, const char *typestr)
2992 char option[3];
2994 option[0] = '-';
2995 option[1] = *c;
2996 option[2] = '\0';
2998 typestr = strstr(typestr, option);
2999 return (typestr != NULL);
3002 static const mon_cmd_t *search_dispatch_table(const mon_cmd_t *disp_table,
3003 const char *cmdname)
3005 const mon_cmd_t *cmd;
3007 for (cmd = disp_table; cmd->name != NULL; cmd++) {
3008 if (compare_cmd(cmdname, cmd->name)) {
3009 return cmd;
3013 return NULL;
3017 * Parse command name from @cmdp according to command table @table.
3018 * If blank, return NULL.
3019 * Else, if no valid command can be found, report to @mon, and return
3020 * NULL.
3021 * Else, change @cmdp to point right behind the name, and return its
3022 * command table entry.
3023 * Do not assume the return value points into @table! It doesn't when
3024 * the command is found in a sub-command table.
3026 static const mon_cmd_t *monitor_parse_command(Monitor *mon,
3027 const char *cmdp_start,
3028 const char **cmdp,
3029 mon_cmd_t *table)
3031 const char *p;
3032 const mon_cmd_t *cmd;
3033 char cmdname[256];
3035 /* extract the command name */
3036 p = get_command_name(*cmdp, cmdname, sizeof(cmdname));
3037 if (!p)
3038 return NULL;
3040 cmd = search_dispatch_table(table, cmdname);
3041 if (!cmd) {
3042 monitor_printf(mon, "unknown command: '%.*s'\n",
3043 (int)(p - cmdp_start), cmdp_start);
3044 return NULL;
3046 if (runstate_check(RUN_STATE_PRECONFIG) && !cmd_can_preconfig(cmd)) {
3047 monitor_printf(mon, "Command '%.*s' not available with -preconfig "
3048 "until after exit_preconfig.\n",
3049 (int)(p - cmdp_start), cmdp_start);
3050 return NULL;
3053 /* filter out following useless space */
3054 while (qemu_isspace(*p)) {
3055 p++;
3058 *cmdp = p;
3059 /* search sub command */
3060 if (cmd->sub_table != NULL && *p != '\0') {
3061 return monitor_parse_command(mon, cmdp_start, cmdp, cmd->sub_table);
3064 return cmd;
3068 * Parse arguments for @cmd.
3069 * If it can't be parsed, report to @mon, and return NULL.
3070 * Else, insert command arguments into a QDict, and return it.
3071 * Note: On success, caller has to free the QDict structure.
3074 static QDict *monitor_parse_arguments(Monitor *mon,
3075 const char **endp,
3076 const mon_cmd_t *cmd)
3078 const char *typestr;
3079 char *key;
3080 int c;
3081 const char *p = *endp;
3082 char buf[1024];
3083 QDict *qdict = qdict_new();
3085 /* parse the parameters */
3086 typestr = cmd->args_type;
3087 for(;;) {
3088 typestr = key_get_info(typestr, &key);
3089 if (!typestr)
3090 break;
3091 c = *typestr;
3092 typestr++;
3093 switch(c) {
3094 case 'F':
3095 case 'B':
3096 case 's':
3098 int ret;
3100 while (qemu_isspace(*p))
3101 p++;
3102 if (*typestr == '?') {
3103 typestr++;
3104 if (*p == '\0') {
3105 /* no optional string: NULL argument */
3106 break;
3109 ret = get_str(buf, sizeof(buf), &p);
3110 if (ret < 0) {
3111 switch(c) {
3112 case 'F':
3113 monitor_printf(mon, "%s: filename expected\n",
3114 cmd->name);
3115 break;
3116 case 'B':
3117 monitor_printf(mon, "%s: block device name expected\n",
3118 cmd->name);
3119 break;
3120 default:
3121 monitor_printf(mon, "%s: string expected\n", cmd->name);
3122 break;
3124 goto fail;
3126 qdict_put_str(qdict, key, buf);
3128 break;
3129 case 'O':
3131 QemuOptsList *opts_list;
3132 QemuOpts *opts;
3134 opts_list = qemu_find_opts(key);
3135 if (!opts_list || opts_list->desc->name) {
3136 goto bad_type;
3138 while (qemu_isspace(*p)) {
3139 p++;
3141 if (!*p)
3142 break;
3143 if (get_str(buf, sizeof(buf), &p) < 0) {
3144 goto fail;
3146 opts = qemu_opts_parse_noisily(opts_list, buf, true);
3147 if (!opts) {
3148 goto fail;
3150 qemu_opts_to_qdict(opts, qdict);
3151 qemu_opts_del(opts);
3153 break;
3154 case '/':
3156 int count, format, size;
3158 while (qemu_isspace(*p))
3159 p++;
3160 if (*p == '/') {
3161 /* format found */
3162 p++;
3163 count = 1;
3164 if (qemu_isdigit(*p)) {
3165 count = 0;
3166 while (qemu_isdigit(*p)) {
3167 count = count * 10 + (*p - '0');
3168 p++;
3171 size = -1;
3172 format = -1;
3173 for(;;) {
3174 switch(*p) {
3175 case 'o':
3176 case 'd':
3177 case 'u':
3178 case 'x':
3179 case 'i':
3180 case 'c':
3181 format = *p++;
3182 break;
3183 case 'b':
3184 size = 1;
3185 p++;
3186 break;
3187 case 'h':
3188 size = 2;
3189 p++;
3190 break;
3191 case 'w':
3192 size = 4;
3193 p++;
3194 break;
3195 case 'g':
3196 case 'L':
3197 size = 8;
3198 p++;
3199 break;
3200 default:
3201 goto next;
3204 next:
3205 if (*p != '\0' && !qemu_isspace(*p)) {
3206 monitor_printf(mon, "invalid char in format: '%c'\n",
3207 *p);
3208 goto fail;
3210 if (format < 0)
3211 format = default_fmt_format;
3212 if (format != 'i') {
3213 /* for 'i', not specifying a size gives -1 as size */
3214 if (size < 0)
3215 size = default_fmt_size;
3216 default_fmt_size = size;
3218 default_fmt_format = format;
3219 } else {
3220 count = 1;
3221 format = default_fmt_format;
3222 if (format != 'i') {
3223 size = default_fmt_size;
3224 } else {
3225 size = -1;
3228 qdict_put_int(qdict, "count", count);
3229 qdict_put_int(qdict, "format", format);
3230 qdict_put_int(qdict, "size", size);
3232 break;
3233 case 'i':
3234 case 'l':
3235 case 'M':
3237 int64_t val;
3239 while (qemu_isspace(*p))
3240 p++;
3241 if (*typestr == '?' || *typestr == '.') {
3242 if (*typestr == '?') {
3243 if (*p == '\0') {
3244 typestr++;
3245 break;
3247 } else {
3248 if (*p == '.') {
3249 p++;
3250 while (qemu_isspace(*p))
3251 p++;
3252 } else {
3253 typestr++;
3254 break;
3257 typestr++;
3259 if (get_expr(mon, &val, &p))
3260 goto fail;
3261 /* Check if 'i' is greater than 32-bit */
3262 if ((c == 'i') && ((val >> 32) & 0xffffffff)) {
3263 monitor_printf(mon, "\'%s\' has failed: ", cmd->name);
3264 monitor_printf(mon, "integer is for 32-bit values\n");
3265 goto fail;
3266 } else if (c == 'M') {
3267 if (val < 0) {
3268 monitor_printf(mon, "enter a positive value\n");
3269 goto fail;
3271 val *= MiB;
3273 qdict_put_int(qdict, key, val);
3275 break;
3276 case 'o':
3278 int ret;
3279 uint64_t val;
3280 const char *end;
3282 while (qemu_isspace(*p)) {
3283 p++;
3285 if (*typestr == '?') {
3286 typestr++;
3287 if (*p == '\0') {
3288 break;
3291 ret = qemu_strtosz_MiB(p, &end, &val);
3292 if (ret < 0 || val > INT64_MAX) {
3293 monitor_printf(mon, "invalid size\n");
3294 goto fail;
3296 qdict_put_int(qdict, key, val);
3297 p = end;
3299 break;
3300 case 'T':
3302 double val;
3304 while (qemu_isspace(*p))
3305 p++;
3306 if (*typestr == '?') {
3307 typestr++;
3308 if (*p == '\0') {
3309 break;
3312 if (get_double(mon, &val, &p) < 0) {
3313 goto fail;
3315 if (p[0] && p[1] == 's') {
3316 switch (*p) {
3317 case 'm':
3318 val /= 1e3; p += 2; break;
3319 case 'u':
3320 val /= 1e6; p += 2; break;
3321 case 'n':
3322 val /= 1e9; p += 2; break;
3325 if (*p && !qemu_isspace(*p)) {
3326 monitor_printf(mon, "Unknown unit suffix\n");
3327 goto fail;
3329 qdict_put(qdict, key, qnum_from_double(val));
3331 break;
3332 case 'b':
3334 const char *beg;
3335 bool val;
3337 while (qemu_isspace(*p)) {
3338 p++;
3340 beg = p;
3341 while (qemu_isgraph(*p)) {
3342 p++;
3344 if (p - beg == 2 && !memcmp(beg, "on", p - beg)) {
3345 val = true;
3346 } else if (p - beg == 3 && !memcmp(beg, "off", p - beg)) {
3347 val = false;
3348 } else {
3349 monitor_printf(mon, "Expected 'on' or 'off'\n");
3350 goto fail;
3352 qdict_put_bool(qdict, key, val);
3354 break;
3355 case '-':
3357 const char *tmp = p;
3358 int skip_key = 0;
3359 /* option */
3361 c = *typestr++;
3362 if (c == '\0')
3363 goto bad_type;
3364 while (qemu_isspace(*p))
3365 p++;
3366 if (*p == '-') {
3367 p++;
3368 if(c != *p) {
3369 if(!is_valid_option(p, typestr)) {
3371 monitor_printf(mon, "%s: unsupported option -%c\n",
3372 cmd->name, *p);
3373 goto fail;
3374 } else {
3375 skip_key = 1;
3378 if(skip_key) {
3379 p = tmp;
3380 } else {
3381 /* has option */
3382 p++;
3383 qdict_put_bool(qdict, key, true);
3387 break;
3388 case 'S':
3390 /* package all remaining string */
3391 int len;
3393 while (qemu_isspace(*p)) {
3394 p++;
3396 if (*typestr == '?') {
3397 typestr++;
3398 if (*p == '\0') {
3399 /* no remaining string: NULL argument */
3400 break;
3403 len = strlen(p);
3404 if (len <= 0) {
3405 monitor_printf(mon, "%s: string expected\n",
3406 cmd->name);
3407 goto fail;
3409 qdict_put_str(qdict, key, p);
3410 p += len;
3412 break;
3413 default:
3414 bad_type:
3415 monitor_printf(mon, "%s: unknown type '%c'\n", cmd->name, c);
3416 goto fail;
3418 g_free(key);
3419 key = NULL;
3421 /* check that all arguments were parsed */
3422 while (qemu_isspace(*p))
3423 p++;
3424 if (*p != '\0') {
3425 monitor_printf(mon, "%s: extraneous characters at the end of line\n",
3426 cmd->name);
3427 goto fail;
3430 return qdict;
3432 fail:
3433 qobject_unref(qdict);
3434 g_free(key);
3435 return NULL;
3438 static void handle_hmp_command(Monitor *mon, const char *cmdline)
3440 QDict *qdict;
3441 const mon_cmd_t *cmd;
3442 const char *cmd_start = cmdline;
3444 trace_handle_hmp_command(mon, cmdline);
3446 cmd = monitor_parse_command(mon, cmdline, &cmdline, mon->cmd_table);
3447 if (!cmd) {
3448 return;
3451 qdict = monitor_parse_arguments(mon, &cmdline, cmd);
3452 if (!qdict) {
3453 while (cmdline > cmd_start && qemu_isspace(cmdline[-1])) {
3454 cmdline--;
3456 monitor_printf(mon, "Try \"help %.*s\" for more information\n",
3457 (int)(cmdline - cmd_start), cmd_start);
3458 return;
3461 cmd->cmd(mon, qdict);
3462 qobject_unref(qdict);
3465 static void cmd_completion(Monitor *mon, const char *name, const char *list)
3467 const char *p, *pstart;
3468 char cmd[128];
3469 int len;
3471 p = list;
3472 for(;;) {
3473 pstart = p;
3474 p = qemu_strchrnul(p, '|');
3475 len = p - pstart;
3476 if (len > sizeof(cmd) - 2)
3477 len = sizeof(cmd) - 2;
3478 memcpy(cmd, pstart, len);
3479 cmd[len] = '\0';
3480 if (name[0] == '\0' || !strncmp(name, cmd, strlen(name))) {
3481 readline_add_completion(mon->rs, cmd);
3483 if (*p == '\0')
3484 break;
3485 p++;
3489 static void file_completion(Monitor *mon, const char *input)
3491 DIR *ffs;
3492 struct dirent *d;
3493 char path[1024];
3494 char file[1024], file_prefix[1024];
3495 int input_path_len;
3496 const char *p;
3498 p = strrchr(input, '/');
3499 if (!p) {
3500 input_path_len = 0;
3501 pstrcpy(file_prefix, sizeof(file_prefix), input);
3502 pstrcpy(path, sizeof(path), ".");
3503 } else {
3504 input_path_len = p - input + 1;
3505 memcpy(path, input, input_path_len);
3506 if (input_path_len > sizeof(path) - 1)
3507 input_path_len = sizeof(path) - 1;
3508 path[input_path_len] = '\0';
3509 pstrcpy(file_prefix, sizeof(file_prefix), p + 1);
3512 ffs = opendir(path);
3513 if (!ffs)
3514 return;
3515 for(;;) {
3516 struct stat sb;
3517 d = readdir(ffs);
3518 if (!d)
3519 break;
3521 if (strcmp(d->d_name, ".") == 0 || strcmp(d->d_name, "..") == 0) {
3522 continue;
3525 if (strstart(d->d_name, file_prefix, NULL)) {
3526 memcpy(file, input, input_path_len);
3527 if (input_path_len < sizeof(file))
3528 pstrcpy(file + input_path_len, sizeof(file) - input_path_len,
3529 d->d_name);
3530 /* stat the file to find out if it's a directory.
3531 * In that case add a slash to speed up typing long paths
3533 if (stat(file, &sb) == 0 && S_ISDIR(sb.st_mode)) {
3534 pstrcat(file, sizeof(file), "/");
3536 readline_add_completion(mon->rs, file);
3539 closedir(ffs);
3542 static const char *next_arg_type(const char *typestr)
3544 const char *p = strchr(typestr, ':');
3545 return (p != NULL ? ++p : typestr);
3548 static void add_completion_option(ReadLineState *rs, const char *str,
3549 const char *option)
3551 if (!str || !option) {
3552 return;
3554 if (!strncmp(option, str, strlen(str))) {
3555 readline_add_completion(rs, option);
3559 void chardev_add_completion(ReadLineState *rs, int nb_args, const char *str)
3561 size_t len;
3562 ChardevBackendInfoList *list, *start;
3564 if (nb_args != 2) {
3565 return;
3567 len = strlen(str);
3568 readline_set_completion_index(rs, len);
3570 start = list = qmp_query_chardev_backends(NULL);
3571 while (list) {
3572 const char *chr_name = list->value->name;
3574 if (!strncmp(chr_name, str, len)) {
3575 readline_add_completion(rs, chr_name);
3577 list = list->next;
3579 qapi_free_ChardevBackendInfoList(start);
3582 void netdev_add_completion(ReadLineState *rs, int nb_args, const char *str)
3584 size_t len;
3585 int i;
3587 if (nb_args != 2) {
3588 return;
3590 len = strlen(str);
3591 readline_set_completion_index(rs, len);
3592 for (i = 0; i < NET_CLIENT_DRIVER__MAX; i++) {
3593 add_completion_option(rs, str, NetClientDriver_str(i));
3597 void device_add_completion(ReadLineState *rs, int nb_args, const char *str)
3599 GSList *list, *elt;
3600 size_t len;
3602 if (nb_args != 2) {
3603 return;
3606 len = strlen(str);
3607 readline_set_completion_index(rs, len);
3608 list = elt = object_class_get_list(TYPE_DEVICE, false);
3609 while (elt) {
3610 const char *name;
3611 DeviceClass *dc = OBJECT_CLASS_CHECK(DeviceClass, elt->data,
3612 TYPE_DEVICE);
3613 name = object_class_get_name(OBJECT_CLASS(dc));
3615 if (dc->user_creatable
3616 && !strncmp(name, str, len)) {
3617 readline_add_completion(rs, name);
3619 elt = elt->next;
3621 g_slist_free(list);
3624 void object_add_completion(ReadLineState *rs, int nb_args, const char *str)
3626 GSList *list, *elt;
3627 size_t len;
3629 if (nb_args != 2) {
3630 return;
3633 len = strlen(str);
3634 readline_set_completion_index(rs, len);
3635 list = elt = object_class_get_list(TYPE_USER_CREATABLE, false);
3636 while (elt) {
3637 const char *name;
3639 name = object_class_get_name(OBJECT_CLASS(elt->data));
3640 if (!strncmp(name, str, len) && strcmp(name, TYPE_USER_CREATABLE)) {
3641 readline_add_completion(rs, name);
3643 elt = elt->next;
3645 g_slist_free(list);
3648 static void peripheral_device_del_completion(ReadLineState *rs,
3649 const char *str, size_t len)
3651 Object *peripheral = container_get(qdev_get_machine(), "/peripheral");
3652 GSList *list, *item;
3654 list = qdev_build_hotpluggable_device_list(peripheral);
3655 if (!list) {
3656 return;
3659 for (item = list; item; item = g_slist_next(item)) {
3660 DeviceState *dev = item->data;
3662 if (dev->id && !strncmp(str, dev->id, len)) {
3663 readline_add_completion(rs, dev->id);
3667 g_slist_free(list);
3670 void chardev_remove_completion(ReadLineState *rs, int nb_args, const char *str)
3672 size_t len;
3673 ChardevInfoList *list, *start;
3675 if (nb_args != 2) {
3676 return;
3678 len = strlen(str);
3679 readline_set_completion_index(rs, len);
3681 start = list = qmp_query_chardev(NULL);
3682 while (list) {
3683 ChardevInfo *chr = list->value;
3685 if (!strncmp(chr->label, str, len)) {
3686 readline_add_completion(rs, chr->label);
3688 list = list->next;
3690 qapi_free_ChardevInfoList(start);
3693 static void ringbuf_completion(ReadLineState *rs, const char *str)
3695 size_t len;
3696 ChardevInfoList *list, *start;
3698 len = strlen(str);
3699 readline_set_completion_index(rs, len);
3701 start = list = qmp_query_chardev(NULL);
3702 while (list) {
3703 ChardevInfo *chr_info = list->value;
3705 if (!strncmp(chr_info->label, str, len)) {
3706 Chardev *chr = qemu_chr_find(chr_info->label);
3707 if (chr && CHARDEV_IS_RINGBUF(chr)) {
3708 readline_add_completion(rs, chr_info->label);
3711 list = list->next;
3713 qapi_free_ChardevInfoList(start);
3716 void ringbuf_write_completion(ReadLineState *rs, int nb_args, const char *str)
3718 if (nb_args != 2) {
3719 return;
3721 ringbuf_completion(rs, str);
3724 void device_del_completion(ReadLineState *rs, int nb_args, const char *str)
3726 size_t len;
3728 if (nb_args != 2) {
3729 return;
3732 len = strlen(str);
3733 readline_set_completion_index(rs, len);
3734 peripheral_device_del_completion(rs, str, len);
3737 void object_del_completion(ReadLineState *rs, int nb_args, const char *str)
3739 ObjectPropertyInfoList *list, *start;
3740 size_t len;
3742 if (nb_args != 2) {
3743 return;
3745 len = strlen(str);
3746 readline_set_completion_index(rs, len);
3748 start = list = qmp_qom_list("/objects", NULL);
3749 while (list) {
3750 ObjectPropertyInfo *info = list->value;
3752 if (!strncmp(info->type, "child<", 5)
3753 && !strncmp(info->name, str, len)) {
3754 readline_add_completion(rs, info->name);
3756 list = list->next;
3758 qapi_free_ObjectPropertyInfoList(start);
3761 void sendkey_completion(ReadLineState *rs, int nb_args, const char *str)
3763 int i;
3764 char *sep;
3765 size_t len;
3767 if (nb_args != 2) {
3768 return;
3770 sep = strrchr(str, '-');
3771 if (sep) {
3772 str = sep + 1;
3774 len = strlen(str);
3775 readline_set_completion_index(rs, len);
3776 for (i = 0; i < Q_KEY_CODE__MAX; i++) {
3777 if (!strncmp(str, QKeyCode_str(i), len)) {
3778 readline_add_completion(rs, QKeyCode_str(i));
3783 void set_link_completion(ReadLineState *rs, int nb_args, const char *str)
3785 size_t len;
3787 len = strlen(str);
3788 readline_set_completion_index(rs, len);
3789 if (nb_args == 2) {
3790 NetClientState *ncs[MAX_QUEUE_NUM];
3791 int count, i;
3792 count = qemu_find_net_clients_except(NULL, ncs,
3793 NET_CLIENT_DRIVER_NONE,
3794 MAX_QUEUE_NUM);
3795 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3796 const char *name = ncs[i]->name;
3797 if (!strncmp(str, name, len)) {
3798 readline_add_completion(rs, name);
3801 } else if (nb_args == 3) {
3802 add_completion_option(rs, str, "on");
3803 add_completion_option(rs, str, "off");
3807 void netdev_del_completion(ReadLineState *rs, int nb_args, const char *str)
3809 int len, count, i;
3810 NetClientState *ncs[MAX_QUEUE_NUM];
3812 if (nb_args != 2) {
3813 return;
3816 len = strlen(str);
3817 readline_set_completion_index(rs, len);
3818 count = qemu_find_net_clients_except(NULL, ncs, NET_CLIENT_DRIVER_NIC,
3819 MAX_QUEUE_NUM);
3820 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3821 QemuOpts *opts;
3822 const char *name = ncs[i]->name;
3823 if (strncmp(str, name, len)) {
3824 continue;
3826 opts = qemu_opts_find(qemu_find_opts_err("netdev", NULL), name);
3827 if (opts) {
3828 readline_add_completion(rs, name);
3833 void info_trace_events_completion(ReadLineState *rs, int nb_args, const char *str)
3835 size_t len;
3837 len = strlen(str);
3838 readline_set_completion_index(rs, len);
3839 if (nb_args == 2) {
3840 TraceEventIter iter;
3841 TraceEvent *ev;
3842 char *pattern = g_strdup_printf("%s*", str);
3843 trace_event_iter_init(&iter, pattern);
3844 while ((ev = trace_event_iter_next(&iter)) != NULL) {
3845 readline_add_completion(rs, trace_event_get_name(ev));
3847 g_free(pattern);
3851 void trace_event_completion(ReadLineState *rs, int nb_args, const char *str)
3853 size_t len;
3855 len = strlen(str);
3856 readline_set_completion_index(rs, len);
3857 if (nb_args == 2) {
3858 TraceEventIter iter;
3859 TraceEvent *ev;
3860 char *pattern = g_strdup_printf("%s*", str);
3861 trace_event_iter_init(&iter, pattern);
3862 while ((ev = trace_event_iter_next(&iter)) != NULL) {
3863 readline_add_completion(rs, trace_event_get_name(ev));
3865 g_free(pattern);
3866 } else if (nb_args == 3) {
3867 add_completion_option(rs, str, "on");
3868 add_completion_option(rs, str, "off");
3872 void watchdog_action_completion(ReadLineState *rs, int nb_args, const char *str)
3874 int i;
3876 if (nb_args != 2) {
3877 return;
3879 readline_set_completion_index(rs, strlen(str));
3880 for (i = 0; i < WATCHDOG_ACTION__MAX; i++) {
3881 add_completion_option(rs, str, WatchdogAction_str(i));
3885 void migrate_set_capability_completion(ReadLineState *rs, int nb_args,
3886 const char *str)
3888 size_t len;
3890 len = strlen(str);
3891 readline_set_completion_index(rs, len);
3892 if (nb_args == 2) {
3893 int i;
3894 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
3895 const char *name = MigrationCapability_str(i);
3896 if (!strncmp(str, name, len)) {
3897 readline_add_completion(rs, name);
3900 } else if (nb_args == 3) {
3901 add_completion_option(rs, str, "on");
3902 add_completion_option(rs, str, "off");
3906 void migrate_set_parameter_completion(ReadLineState *rs, int nb_args,
3907 const char *str)
3909 size_t len;
3911 len = strlen(str);
3912 readline_set_completion_index(rs, len);
3913 if (nb_args == 2) {
3914 int i;
3915 for (i = 0; i < MIGRATION_PARAMETER__MAX; i++) {
3916 const char *name = MigrationParameter_str(i);
3917 if (!strncmp(str, name, len)) {
3918 readline_add_completion(rs, name);
3924 static void vm_completion(ReadLineState *rs, const char *str)
3926 size_t len;
3927 BlockDriverState *bs;
3928 BdrvNextIterator it;
3930 len = strlen(str);
3931 readline_set_completion_index(rs, len);
3933 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
3934 SnapshotInfoList *snapshots, *snapshot;
3935 AioContext *ctx = bdrv_get_aio_context(bs);
3936 bool ok = false;
3938 aio_context_acquire(ctx);
3939 if (bdrv_can_snapshot(bs)) {
3940 ok = bdrv_query_snapshot_info_list(bs, &snapshots, NULL) == 0;
3942 aio_context_release(ctx);
3943 if (!ok) {
3944 continue;
3947 snapshot = snapshots;
3948 while (snapshot) {
3949 char *completion = snapshot->value->name;
3950 if (!strncmp(str, completion, len)) {
3951 readline_add_completion(rs, completion);
3953 completion = snapshot->value->id;
3954 if (!strncmp(str, completion, len)) {
3955 readline_add_completion(rs, completion);
3957 snapshot = snapshot->next;
3959 qapi_free_SnapshotInfoList(snapshots);
3964 void delvm_completion(ReadLineState *rs, int nb_args, const char *str)
3966 if (nb_args == 2) {
3967 vm_completion(rs, str);
3971 void loadvm_completion(ReadLineState *rs, int nb_args, const char *str)
3973 if (nb_args == 2) {
3974 vm_completion(rs, str);
3978 static void monitor_find_completion_by_table(Monitor *mon,
3979 const mon_cmd_t *cmd_table,
3980 char **args,
3981 int nb_args)
3983 const char *cmdname;
3984 int i;
3985 const char *ptype, *old_ptype, *str, *name;
3986 const mon_cmd_t *cmd;
3987 BlockBackend *blk = NULL;
3989 if (nb_args <= 1) {
3990 /* command completion */
3991 if (nb_args == 0)
3992 cmdname = "";
3993 else
3994 cmdname = args[0];
3995 readline_set_completion_index(mon->rs, strlen(cmdname));
3996 for (cmd = cmd_table; cmd->name != NULL; cmd++) {
3997 if (!runstate_check(RUN_STATE_PRECONFIG) ||
3998 cmd_can_preconfig(cmd)) {
3999 cmd_completion(mon, cmdname, cmd->name);
4002 } else {
4003 /* find the command */
4004 for (cmd = cmd_table; cmd->name != NULL; cmd++) {
4005 if (compare_cmd(args[0], cmd->name) &&
4006 (!runstate_check(RUN_STATE_PRECONFIG) ||
4007 cmd_can_preconfig(cmd))) {
4008 break;
4011 if (!cmd->name) {
4012 return;
4015 if (cmd->sub_table) {
4016 /* do the job again */
4017 monitor_find_completion_by_table(mon, cmd->sub_table,
4018 &args[1], nb_args - 1);
4019 return;
4021 if (cmd->command_completion) {
4022 cmd->command_completion(mon->rs, nb_args, args[nb_args - 1]);
4023 return;
4026 ptype = next_arg_type(cmd->args_type);
4027 for(i = 0; i < nb_args - 2; i++) {
4028 if (*ptype != '\0') {
4029 ptype = next_arg_type(ptype);
4030 while (*ptype == '?')
4031 ptype = next_arg_type(ptype);
4034 str = args[nb_args - 1];
4035 old_ptype = NULL;
4036 while (*ptype == '-' && old_ptype != ptype) {
4037 old_ptype = ptype;
4038 ptype = next_arg_type(ptype);
4040 switch(*ptype) {
4041 case 'F':
4042 /* file completion */
4043 readline_set_completion_index(mon->rs, strlen(str));
4044 file_completion(mon, str);
4045 break;
4046 case 'B':
4047 /* block device name completion */
4048 readline_set_completion_index(mon->rs, strlen(str));
4049 while ((blk = blk_next(blk)) != NULL) {
4050 name = blk_name(blk);
4051 if (str[0] == '\0' ||
4052 !strncmp(name, str, strlen(str))) {
4053 readline_add_completion(mon->rs, name);
4056 break;
4057 case 's':
4058 case 'S':
4059 if (!strcmp(cmd->name, "help|?")) {
4060 monitor_find_completion_by_table(mon, cmd_table,
4061 &args[1], nb_args - 1);
4063 break;
4064 default:
4065 break;
4070 static void monitor_find_completion(void *opaque,
4071 const char *cmdline)
4073 Monitor *mon = opaque;
4074 char *args[MAX_ARGS];
4075 int nb_args, len;
4077 /* 1. parse the cmdline */
4078 if (parse_cmdline(cmdline, &nb_args, args) < 0) {
4079 return;
4082 /* if the line ends with a space, it means we want to complete the
4083 next arg */
4084 len = strlen(cmdline);
4085 if (len > 0 && qemu_isspace(cmdline[len - 1])) {
4086 if (nb_args >= MAX_ARGS) {
4087 goto cleanup;
4089 args[nb_args++] = g_strdup("");
4092 /* 2. auto complete according to args */
4093 monitor_find_completion_by_table(mon, mon->cmd_table, args, nb_args);
4095 cleanup:
4096 free_cmdline_args(args, nb_args);
4099 static int monitor_can_read(void *opaque)
4101 Monitor *mon = opaque;
4103 return !atomic_mb_read(&mon->suspend_cnt);
4107 * Emit QMP response @rsp with ID @id to @mon.
4108 * Null @rsp can only happen for commands with QCO_NO_SUCCESS_RESP.
4109 * Nothing is emitted then.
4111 static void monitor_qmp_respond(Monitor *mon, QDict *rsp, QObject *id)
4113 if (rsp) {
4114 if (id) {
4115 qdict_put_obj(rsp, "id", qobject_ref(id));
4118 qmp_send_response(mon, rsp);
4122 static void monitor_qmp_dispatch(Monitor *mon, QObject *req, QObject *id)
4124 Monitor *old_mon;
4125 QDict *rsp;
4126 QDict *error;
4128 old_mon = cur_mon;
4129 cur_mon = mon;
4131 rsp = qmp_dispatch(mon->qmp.commands, req, qmp_oob_enabled(mon));
4133 cur_mon = old_mon;
4135 if (mon->qmp.commands == &qmp_cap_negotiation_commands) {
4136 error = qdict_get_qdict(rsp, "error");
4137 if (error
4138 && !g_strcmp0(qdict_get_try_str(error, "class"),
4139 QapiErrorClass_str(ERROR_CLASS_COMMAND_NOT_FOUND))) {
4140 /* Provide a more useful error message */
4141 qdict_del(error, "desc");
4142 qdict_put_str(error, "desc", "Expecting capabilities negotiation"
4143 " with 'qmp_capabilities'");
4147 monitor_qmp_respond(mon, rsp, id);
4148 qobject_unref(rsp);
4152 * Pop a QMP request from a monitor request queue.
4153 * Return the request, or NULL all request queues are empty.
4154 * We are using round-robin fashion to pop the request, to avoid
4155 * processing commands only on a very busy monitor. To achieve that,
4156 * when we process one request on a specific monitor, we put that
4157 * monitor to the end of mon_list queue.
4159 * Note: if the function returned with non-NULL, then the caller will
4160 * be with mon->qmp.qmp_queue_lock held, and the caller is responsible
4161 * to release it.
4163 static QMPRequest *monitor_qmp_requests_pop_any_with_lock(void)
4165 QMPRequest *req_obj = NULL;
4166 Monitor *mon;
4168 qemu_mutex_lock(&monitor_lock);
4170 QTAILQ_FOREACH(mon, &mon_list, entry) {
4171 qemu_mutex_lock(&mon->qmp.qmp_queue_lock);
4172 req_obj = g_queue_pop_head(mon->qmp.qmp_requests);
4173 if (req_obj) {
4174 /* With the lock of corresponding queue held */
4175 break;
4177 qemu_mutex_unlock(&mon->qmp.qmp_queue_lock);
4180 if (req_obj) {
4182 * We found one request on the monitor. Degrade this monitor's
4183 * priority to lowest by re-inserting it to end of queue.
4185 QTAILQ_REMOVE(&mon_list, mon, entry);
4186 QTAILQ_INSERT_TAIL(&mon_list, mon, entry);
4189 qemu_mutex_unlock(&monitor_lock);
4191 return req_obj;
4194 static void monitor_qmp_bh_dispatcher(void *data)
4196 QMPRequest *req_obj = monitor_qmp_requests_pop_any_with_lock();
4197 QDict *rsp;
4198 bool need_resume;
4199 Monitor *mon;
4201 if (!req_obj) {
4202 return;
4205 mon = req_obj->mon;
4206 /* qmp_oob_enabled() might change after "qmp_capabilities" */
4207 need_resume = !qmp_oob_enabled(mon) ||
4208 mon->qmp.qmp_requests->length == QMP_REQ_QUEUE_LEN_MAX - 1;
4209 qemu_mutex_unlock(&mon->qmp.qmp_queue_lock);
4210 if (req_obj->req) {
4211 trace_monitor_qmp_cmd_in_band(qobject_get_try_str(req_obj->id) ?: "");
4212 monitor_qmp_dispatch(mon, req_obj->req, req_obj->id);
4213 } else {
4214 assert(req_obj->err);
4215 rsp = qmp_error_response(req_obj->err);
4216 req_obj->err = NULL;
4217 monitor_qmp_respond(mon, rsp, NULL);
4218 qobject_unref(rsp);
4221 if (need_resume) {
4222 /* Pairs with the monitor_suspend() in handle_qmp_command() */
4223 monitor_resume(mon);
4225 qmp_request_free(req_obj);
4227 /* Reschedule instead of looping so the main loop stays responsive */
4228 qemu_bh_schedule(qmp_dispatcher_bh);
4231 static void handle_qmp_command(void *opaque, QObject *req, Error *err)
4233 Monitor *mon = opaque;
4234 QObject *id = NULL;
4235 QDict *qdict;
4236 QMPRequest *req_obj;
4238 assert(!req != !err);
4240 qdict = qobject_to(QDict, req);
4241 if (qdict) {
4242 id = qobject_ref(qdict_get(qdict, "id"));
4243 qdict_del(qdict, "id");
4244 } /* else will fail qmp_dispatch() */
4246 if (req && trace_event_get_state_backends(TRACE_HANDLE_QMP_COMMAND)) {
4247 QString *req_json = qobject_to_json(req);
4248 trace_handle_qmp_command(mon, qstring_get_str(req_json));
4249 qobject_unref(req_json);
4252 if (qdict && qmp_is_oob(qdict)) {
4253 /* OOB commands are executed immediately */
4254 trace_monitor_qmp_cmd_out_of_band(qobject_get_try_str(id)
4255 ?: "");
4256 monitor_qmp_dispatch(mon, req, id);
4257 qobject_unref(req);
4258 qobject_unref(id);
4259 return;
4262 req_obj = g_new0(QMPRequest, 1);
4263 req_obj->mon = mon;
4264 req_obj->id = id;
4265 req_obj->req = req;
4266 req_obj->err = err;
4268 /* Protect qmp_requests and fetching its length. */
4269 qemu_mutex_lock(&mon->qmp.qmp_queue_lock);
4272 * Suspend the monitor when we can't queue more requests after
4273 * this one. Dequeuing in monitor_qmp_bh_dispatcher() will resume
4274 * it. Note that when OOB is disabled, we queue at most one
4275 * command, for backward compatibility.
4277 if (!qmp_oob_enabled(mon) ||
4278 mon->qmp.qmp_requests->length == QMP_REQ_QUEUE_LEN_MAX - 1) {
4279 monitor_suspend(mon);
4283 * Put the request to the end of queue so that requests will be
4284 * handled in time order. Ownership for req_obj, req, id,
4285 * etc. will be delivered to the handler side.
4287 assert(mon->qmp.qmp_requests->length < QMP_REQ_QUEUE_LEN_MAX);
4288 g_queue_push_tail(mon->qmp.qmp_requests, req_obj);
4289 qemu_mutex_unlock(&mon->qmp.qmp_queue_lock);
4291 /* Kick the dispatcher routine */
4292 qemu_bh_schedule(qmp_dispatcher_bh);
4295 static void monitor_qmp_read(void *opaque, const uint8_t *buf, int size)
4297 Monitor *mon = opaque;
4299 json_message_parser_feed(&mon->qmp.parser, (const char *) buf, size);
4302 static void monitor_read(void *opaque, const uint8_t *buf, int size)
4304 Monitor *old_mon = cur_mon;
4305 int i;
4307 cur_mon = opaque;
4309 if (cur_mon->rs) {
4310 for (i = 0; i < size; i++)
4311 readline_handle_byte(cur_mon->rs, buf[i]);
4312 } else {
4313 if (size == 0 || buf[size - 1] != 0)
4314 monitor_printf(cur_mon, "corrupted command\n");
4315 else
4316 handle_hmp_command(cur_mon, (char *)buf);
4319 cur_mon = old_mon;
4322 static void monitor_command_cb(void *opaque, const char *cmdline,
4323 void *readline_opaque)
4325 Monitor *mon = opaque;
4327 monitor_suspend(mon);
4328 handle_hmp_command(mon, cmdline);
4329 monitor_resume(mon);
4332 int monitor_suspend(Monitor *mon)
4334 if (monitor_is_hmp_non_interactive(mon)) {
4335 return -ENOTTY;
4338 atomic_inc(&mon->suspend_cnt);
4340 if (mon->use_io_thread) {
4342 * Kick I/O thread to make sure this takes effect. It'll be
4343 * evaluated again in prepare() of the watch object.
4345 aio_notify(iothread_get_aio_context(mon_iothread));
4348 trace_monitor_suspend(mon, 1);
4349 return 0;
4352 static void monitor_accept_input(void *opaque)
4354 Monitor *mon = opaque;
4356 qemu_chr_fe_accept_input(&mon->chr);
4359 void monitor_resume(Monitor *mon)
4361 if (monitor_is_hmp_non_interactive(mon)) {
4362 return;
4365 if (atomic_dec_fetch(&mon->suspend_cnt) == 0) {
4366 AioContext *ctx;
4368 if (mon->use_io_thread) {
4369 ctx = iothread_get_aio_context(mon_iothread);
4370 } else {
4371 ctx = qemu_get_aio_context();
4374 if (!monitor_is_qmp(mon)) {
4375 assert(mon->rs);
4376 readline_show_prompt(mon->rs);
4379 aio_bh_schedule_oneshot(ctx, monitor_accept_input, mon);
4382 trace_monitor_suspend(mon, -1);
4385 static QDict *qmp_greeting(Monitor *mon)
4387 QList *cap_list = qlist_new();
4388 QObject *ver = NULL;
4389 QMPCapability cap;
4391 qmp_marshal_query_version(NULL, &ver, NULL);
4393 for (cap = 0; cap < QMP_CAPABILITY__MAX; cap++) {
4394 if (mon->qmp.capab_offered[cap]) {
4395 qlist_append_str(cap_list, QMPCapability_str(cap));
4399 return qdict_from_jsonf_nofail(
4400 "{'QMP': {'version': %p, 'capabilities': %p}}",
4401 ver, cap_list);
4404 static void monitor_qmp_event(void *opaque, int event)
4406 QDict *data;
4407 Monitor *mon = opaque;
4409 switch (event) {
4410 case CHR_EVENT_OPENED:
4411 mon->qmp.commands = &qmp_cap_negotiation_commands;
4412 monitor_qmp_caps_reset(mon);
4413 data = qmp_greeting(mon);
4414 qmp_send_response(mon, data);
4415 qobject_unref(data);
4416 mon_refcount++;
4417 break;
4418 case CHR_EVENT_CLOSED:
4420 * Note: this is only useful when the output of the chardev
4421 * backend is still open. For example, when the backend is
4422 * stdio, it's possible that stdout is still open when stdin
4423 * is closed.
4425 monitor_qmp_cleanup_queues(mon);
4426 json_message_parser_destroy(&mon->qmp.parser);
4427 json_message_parser_init(&mon->qmp.parser, handle_qmp_command,
4428 mon, NULL);
4429 mon_refcount--;
4430 monitor_fdsets_cleanup();
4431 break;
4435 static void monitor_event(void *opaque, int event)
4437 Monitor *mon = opaque;
4439 switch (event) {
4440 case CHR_EVENT_MUX_IN:
4441 qemu_mutex_lock(&mon->mon_lock);
4442 mon->mux_out = 0;
4443 qemu_mutex_unlock(&mon->mon_lock);
4444 if (mon->reset_seen) {
4445 readline_restart(mon->rs);
4446 monitor_resume(mon);
4447 monitor_flush(mon);
4448 } else {
4449 atomic_mb_set(&mon->suspend_cnt, 0);
4451 break;
4453 case CHR_EVENT_MUX_OUT:
4454 if (mon->reset_seen) {
4455 if (atomic_mb_read(&mon->suspend_cnt) == 0) {
4456 monitor_printf(mon, "\n");
4458 monitor_flush(mon);
4459 monitor_suspend(mon);
4460 } else {
4461 atomic_inc(&mon->suspend_cnt);
4463 qemu_mutex_lock(&mon->mon_lock);
4464 mon->mux_out = 1;
4465 qemu_mutex_unlock(&mon->mon_lock);
4466 break;
4468 case CHR_EVENT_OPENED:
4469 monitor_printf(mon, "QEMU %s monitor - type 'help' for more "
4470 "information\n", QEMU_VERSION);
4471 if (!mon->mux_out) {
4472 readline_restart(mon->rs);
4473 readline_show_prompt(mon->rs);
4475 mon->reset_seen = 1;
4476 mon_refcount++;
4477 break;
4479 case CHR_EVENT_CLOSED:
4480 mon_refcount--;
4481 monitor_fdsets_cleanup();
4482 break;
4486 static int
4487 compare_mon_cmd(const void *a, const void *b)
4489 return strcmp(((const mon_cmd_t *)a)->name,
4490 ((const mon_cmd_t *)b)->name);
4493 static void sortcmdlist(void)
4495 int array_num;
4496 int elem_size = sizeof(mon_cmd_t);
4498 array_num = sizeof(mon_cmds)/elem_size-1;
4499 qsort((void *)mon_cmds, array_num, elem_size, compare_mon_cmd);
4501 array_num = sizeof(info_cmds)/elem_size-1;
4502 qsort((void *)info_cmds, array_num, elem_size, compare_mon_cmd);
4505 static void monitor_iothread_init(void)
4507 mon_iothread = iothread_create("mon_iothread", &error_abort);
4510 void monitor_init_globals(void)
4512 monitor_init_qmp_commands();
4513 monitor_qapi_event_init();
4514 sortcmdlist();
4515 qemu_mutex_init(&monitor_lock);
4516 qemu_mutex_init(&mon_fdsets_lock);
4519 * The dispatcher BH must run in the main loop thread, since we
4520 * have commands assuming that context. It would be nice to get
4521 * rid of those assumptions.
4523 qmp_dispatcher_bh = aio_bh_new(iohandler_get_aio_context(),
4524 monitor_qmp_bh_dispatcher,
4525 NULL);
4528 /* These functions just adapt the readline interface in a typesafe way. We
4529 * could cast function pointers but that discards compiler checks.
4531 static void GCC_FMT_ATTR(2, 3) monitor_readline_printf(void *opaque,
4532 const char *fmt, ...)
4534 va_list ap;
4535 va_start(ap, fmt);
4536 monitor_vprintf(opaque, fmt, ap);
4537 va_end(ap);
4540 static void monitor_readline_flush(void *opaque)
4542 monitor_flush(opaque);
4546 * Print to current monitor if we have one, else to stream.
4547 * TODO should return int, so callers can calculate width, but that
4548 * requires surgery to monitor_vprintf(). Left for another day.
4550 void monitor_vfprintf(FILE *stream, const char *fmt, va_list ap)
4552 if (cur_mon && !monitor_cur_is_qmp()) {
4553 monitor_vprintf(cur_mon, fmt, ap);
4554 } else {
4555 vfprintf(stream, fmt, ap);
4560 * Print to current monitor if we have one, else to stderr.
4561 * TODO should return int, so callers can calculate width, but that
4562 * requires surgery to monitor_vprintf(). Left for another day.
4564 void error_vprintf(const char *fmt, va_list ap)
4566 monitor_vfprintf(stderr, fmt, ap);
4569 void error_vprintf_unless_qmp(const char *fmt, va_list ap)
4571 if (cur_mon && !monitor_cur_is_qmp()) {
4572 monitor_vprintf(cur_mon, fmt, ap);
4573 } else if (!cur_mon) {
4574 vfprintf(stderr, fmt, ap);
4578 static void monitor_list_append(Monitor *mon)
4580 qemu_mutex_lock(&monitor_lock);
4582 * This prevents inserting new monitors during monitor_cleanup().
4583 * A cleaner solution would involve the main thread telling other
4584 * threads to terminate, waiting for their termination.
4586 if (!monitor_destroyed) {
4587 QTAILQ_INSERT_HEAD(&mon_list, mon, entry);
4588 mon = NULL;
4590 qemu_mutex_unlock(&monitor_lock);
4592 if (mon) {
4593 monitor_data_destroy(mon);
4594 g_free(mon);
4598 static void monitor_qmp_setup_handlers_bh(void *opaque)
4600 Monitor *mon = opaque;
4601 GMainContext *context;
4603 assert(mon->use_io_thread);
4604 context = iothread_get_g_main_context(mon_iothread);
4605 assert(context);
4606 qemu_chr_fe_set_handlers(&mon->chr, monitor_can_read, monitor_qmp_read,
4607 monitor_qmp_event, NULL, mon, context, true);
4608 monitor_list_append(mon);
4611 void monitor_init(Chardev *chr, int flags)
4613 Monitor *mon = g_malloc(sizeof(*mon));
4614 bool use_readline = flags & MONITOR_USE_READLINE;
4616 /* Note: we run QMP monitor in I/O thread when @chr supports that */
4617 monitor_data_init(mon, false,
4618 (flags & MONITOR_USE_CONTROL)
4619 && qemu_chr_has_feature(chr,
4620 QEMU_CHAR_FEATURE_GCONTEXT));
4622 qemu_chr_fe_init(&mon->chr, chr, &error_abort);
4623 mon->flags = flags;
4624 if (use_readline) {
4625 mon->rs = readline_init(monitor_readline_printf,
4626 monitor_readline_flush,
4627 mon,
4628 monitor_find_completion);
4629 monitor_read_command(mon, 0);
4632 if (monitor_is_qmp(mon)) {
4633 qemu_chr_fe_set_echo(&mon->chr, true);
4634 json_message_parser_init(&mon->qmp.parser, handle_qmp_command,
4635 mon, NULL);
4636 if (mon->use_io_thread) {
4638 * Make sure the old iowatch is gone. It's possible when
4639 * e.g. the chardev is in client mode, with wait=on.
4641 remove_fd_in_watch(chr);
4643 * We can't call qemu_chr_fe_set_handlers() directly here
4644 * since chardev might be running in the monitor I/O
4645 * thread. Schedule a bottom half.
4647 aio_bh_schedule_oneshot(iothread_get_aio_context(mon_iothread),
4648 monitor_qmp_setup_handlers_bh, mon);
4649 /* The bottom half will add @mon to @mon_list */
4650 return;
4651 } else {
4652 qemu_chr_fe_set_handlers(&mon->chr, monitor_can_read,
4653 monitor_qmp_read, monitor_qmp_event,
4654 NULL, mon, NULL, true);
4656 } else {
4657 qemu_chr_fe_set_handlers(&mon->chr, monitor_can_read, monitor_read,
4658 monitor_event, NULL, mon, NULL, true);
4661 monitor_list_append(mon);
4664 void monitor_cleanup(void)
4667 * We need to explicitly stop the I/O thread (but not destroy it),
4668 * clean up the monitor resources, then destroy the I/O thread since
4669 * we need to unregister from chardev below in
4670 * monitor_data_destroy(), and chardev is not thread-safe yet
4672 if (mon_iothread) {
4673 iothread_stop(mon_iothread);
4676 /* Flush output buffers and destroy monitors */
4677 qemu_mutex_lock(&monitor_lock);
4678 monitor_destroyed = true;
4679 while (!QTAILQ_EMPTY(&mon_list)) {
4680 Monitor *mon = QTAILQ_FIRST(&mon_list);
4681 QTAILQ_REMOVE(&mon_list, mon, entry);
4682 /* Permit QAPI event emission from character frontend release */
4683 qemu_mutex_unlock(&monitor_lock);
4684 monitor_flush(mon);
4685 monitor_data_destroy(mon);
4686 qemu_mutex_lock(&monitor_lock);
4687 g_free(mon);
4689 qemu_mutex_unlock(&monitor_lock);
4691 /* QEMUBHs needs to be deleted before destroying the I/O thread */
4692 qemu_bh_delete(qmp_dispatcher_bh);
4693 qmp_dispatcher_bh = NULL;
4694 if (mon_iothread) {
4695 iothread_destroy(mon_iothread);
4696 mon_iothread = NULL;
4700 QemuOptsList qemu_mon_opts = {
4701 .name = "mon",
4702 .implied_opt_name = "chardev",
4703 .head = QTAILQ_HEAD_INITIALIZER(qemu_mon_opts.head),
4704 .desc = {
4706 .name = "mode",
4707 .type = QEMU_OPT_STRING,
4709 .name = "chardev",
4710 .type = QEMU_OPT_STRING,
4712 .name = "pretty",
4713 .type = QEMU_OPT_BOOL,
4715 { /* end of list */ }
4719 HotpluggableCPUList *qmp_query_hotpluggable_cpus(Error **errp)
4721 MachineState *ms = MACHINE(qdev_get_machine());
4722 MachineClass *mc = MACHINE_GET_CLASS(ms);
4724 if (!mc->has_hotpluggable_cpus) {
4725 error_setg(errp, QERR_FEATURE_DISABLED, "query-hotpluggable-cpus");
4726 return NULL;
4729 return machine_query_hotpluggable_cpus(ms);