monitor: Make MonitorQMP a child class of Monitor
[qemu/ar7.git] / monitor.c
blob15f94fc41fa8abd10eb38a79ae031d76118e93d8
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/ctype.h"
46 #include "qemu/readline.h"
47 #include "ui/console.h"
48 #include "ui/input.h"
49 #include "sysemu/block-backend.h"
50 #include "audio/audio.h"
51 #include "disas/disas.h"
52 #include "sysemu/balloon.h"
53 #include "qemu/timer.h"
54 #include "sysemu/hw_accel.h"
55 #include "authz/list.h"
56 #include "qapi/util.h"
57 #include "sysemu/tcg.h"
58 #include "sysemu/tpm.h"
59 #include "qapi/qmp/qdict.h"
60 #include "qapi/qmp/qerror.h"
61 #include "qapi/qmp/qnum.h"
62 #include "qapi/qmp/qstring.h"
63 #include "qapi/qmp/qjson.h"
64 #include "qapi/qmp/json-parser.h"
65 #include "qapi/qmp/qlist.h"
66 #include "qom/object_interfaces.h"
67 #include "trace-root.h"
68 #include "trace/control.h"
69 #include "monitor/hmp-target.h"
70 #ifdef CONFIG_TRACE_SIMPLE
71 #include "trace/simple.h"
72 #endif
73 #include "exec/memory.h"
74 #include "exec/exec-all.h"
75 #include "qemu/log.h"
76 #include "qemu/option.h"
77 #include "hmp.h"
78 #include "qemu/thread.h"
79 #include "block/qapi.h"
80 #include "qapi/qapi-commands.h"
81 #include "qapi/qapi-emit-events.h"
82 #include "qapi/error.h"
83 #include "qapi/qmp-event.h"
84 #include "qapi/qapi-introspect.h"
85 #include "sysemu/qtest.h"
86 #include "sysemu/cpus.h"
87 #include "sysemu/iothread.h"
88 #include "qemu/cutils.h"
89 #include "tcg/tcg.h"
91 #if defined(TARGET_S390X)
92 #include "hw/s390x/storage-keys.h"
93 #include "hw/s390x/storage-attributes.h"
94 #endif
97 * Supported types:
99 * 'F' filename
100 * 'B' block device name
101 * 's' string (accept optional quote)
102 * 'S' it just appends the rest of the string (accept optional quote)
103 * 'O' option string of the form NAME=VALUE,...
104 * parsed according to QemuOptsList given by its name
105 * Example: 'device:O' uses qemu_device_opts.
106 * Restriction: only lists with empty desc are supported
107 * TODO lift the restriction
108 * 'i' 32 bit integer
109 * 'l' target long (32 or 64 bit)
110 * 'M' Non-negative target long (32 or 64 bit), in user mode the
111 * value is multiplied by 2^20 (think Mebibyte)
112 * 'o' octets (aka bytes)
113 * user mode accepts an optional E, e, P, p, T, t, G, g, M, m,
114 * K, k suffix, which multiplies the value by 2^60 for suffixes E
115 * and e, 2^50 for suffixes P and p, 2^40 for suffixes T and t,
116 * 2^30 for suffixes G and g, 2^20 for M and m, 2^10 for K and k
117 * 'T' double
118 * user mode accepts an optional ms, us, ns suffix,
119 * which divides the value by 1e3, 1e6, 1e9, respectively
120 * '/' optional gdb-like print format (like "/10x")
122 * '?' optional type (for all types, except '/')
123 * '.' other form of optional type (for 'i' and 'l')
124 * 'b' boolean
125 * user mode accepts "on" or "off"
126 * '-' optional parameter (eg. '-f')
130 typedef struct mon_cmd_t {
131 const char *name;
132 const char *args_type;
133 const char *params;
134 const char *help;
135 const char *flags; /* p=preconfig */
136 void (*cmd)(Monitor *mon, const QDict *qdict);
137 /* @sub_table is a list of 2nd level of commands. If it does not exist,
138 * cmd should be used. If it exists, sub_table[?].cmd should be
139 * used, and cmd of 1st level plays the role of help function.
141 struct mon_cmd_t *sub_table;
142 void (*command_completion)(ReadLineState *rs, int nb_args, const char *str);
143 } mon_cmd_t;
145 /* file descriptors passed via SCM_RIGHTS */
146 typedef struct mon_fd_t mon_fd_t;
147 struct mon_fd_t {
148 char *name;
149 int fd;
150 QLIST_ENTRY(mon_fd_t) next;
153 /* file descriptor associated with a file descriptor set */
154 typedef struct MonFdsetFd MonFdsetFd;
155 struct MonFdsetFd {
156 int fd;
157 bool removed;
158 char *opaque;
159 QLIST_ENTRY(MonFdsetFd) next;
162 /* file descriptor set containing fds passed via SCM_RIGHTS */
163 typedef struct MonFdset MonFdset;
164 struct MonFdset {
165 int64_t id;
166 QLIST_HEAD(, MonFdsetFd) fds;
167 QLIST_HEAD(, MonFdsetFd) dup_fds;
168 QLIST_ENTRY(MonFdset) next;
172 * To prevent flooding clients, events can be throttled. The
173 * throttling is calculated globally, rather than per-Monitor
174 * instance.
176 typedef struct MonitorQAPIEventState {
177 QAPIEvent event; /* Throttling state for this event type and... */
178 QDict *data; /* ... data, see qapi_event_throttle_equal() */
179 QEMUTimer *timer; /* Timer for handling delayed events */
180 QDict *qdict; /* Delayed event (if any) */
181 } MonitorQAPIEventState;
183 typedef struct {
184 int64_t rate; /* Minimum time (in ns) between two events */
185 } MonitorQAPIEventConf;
187 struct Monitor {
188 CharBackend chr;
189 int reset_seen;
190 int flags;
191 int suspend_cnt; /* Needs to be accessed atomically */
192 bool skip_flush;
193 bool use_io_thread;
196 * State used only in the thread "owning" the monitor.
197 * If @use_io_thread, this is @mon_iothread.
198 * Else, it's the main thread.
199 * These members can be safely accessed without locks.
201 ReadLineState *rs;
203 gchar *mon_cpu_path;
204 mon_cmd_t *cmd_table;
205 QTAILQ_ENTRY(Monitor) entry;
208 * The per-monitor lock. We can't access guest memory when holding
209 * the lock.
211 QemuMutex mon_lock;
214 * Members that are protected by the per-monitor lock
216 QLIST_HEAD(, mon_fd_t) fds;
217 QString *outbuf;
218 guint out_watch;
219 /* Read under either BQL or mon_lock, written with BQL+mon_lock. */
220 int mux_out;
223 typedef struct {
224 Monitor common;
225 JSONMessageParser parser;
227 * When a client connects, we're in capabilities negotiation mode.
228 * @commands is &qmp_cap_negotiation_commands then. When command
229 * qmp_capabilities succeeds, we go into command mode, and
230 * @command becomes &qmp_commands.
232 QmpCommandList *commands;
233 bool capab_offered[QMP_CAPABILITY__MAX]; /* capabilities offered */
234 bool capab[QMP_CAPABILITY__MAX]; /* offered and accepted */
236 * Protects qmp request/response queue.
237 * Take monitor_lock first when you need both.
239 QemuMutex qmp_queue_lock;
240 /* Input queue that holds all the parsed QMP requests */
241 GQueue *qmp_requests;
242 } MonitorQMP;
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 MonitorQMP *mon;
254 * Request object to be handled or Error to be reported
255 * (exactly one of them is non-null)
257 QObject *req;
258 Error *err;
260 typedef struct QMPRequest QMPRequest;
262 /* QMP checker flags */
263 #define QMP_ACCEPT_UNKNOWNS 1
265 /* Protects mon_list, monitor_qapi_event_state, monitor_destroyed. */
266 static QemuMutex monitor_lock;
267 static GHashTable *monitor_qapi_event_state;
268 static QTAILQ_HEAD(, Monitor) mon_list;
269 static bool monitor_destroyed;
271 /* Protects mon_fdsets */
272 static QemuMutex mon_fdsets_lock;
273 static QLIST_HEAD(, MonFdset) mon_fdsets;
275 static int mon_refcount;
277 static mon_cmd_t mon_cmds[];
278 static mon_cmd_t info_cmds[];
280 QmpCommandList qmp_commands, qmp_cap_negotiation_commands;
282 __thread Monitor *cur_mon;
284 static void monitor_command_cb(void *opaque, const char *cmdline,
285 void *readline_opaque);
288 * Is @mon a QMP monitor?
290 static inline bool monitor_is_qmp(const Monitor *mon)
292 return (mon->flags & MONITOR_USE_CONTROL);
296 * Is @mon is using readline?
297 * Note: not all HMP monitors use readline, e.g., gdbserver has a
298 * non-interactive HMP monitor, so readline is not used there.
300 static inline bool monitor_uses_readline(const Monitor *mon)
302 return mon->flags & MONITOR_USE_READLINE;
305 static inline bool monitor_is_hmp_non_interactive(const Monitor *mon)
307 return !monitor_is_qmp(mon) && !monitor_uses_readline(mon);
311 * Return the clock to use for recording an event's time.
312 * It's QEMU_CLOCK_REALTIME, except for qtests it's
313 * QEMU_CLOCK_VIRTUAL, to support testing rate limits.
314 * Beware: result is invalid before configure_accelerator().
316 static inline QEMUClockType monitor_get_event_clock(void)
318 return qtest_enabled() ? QEMU_CLOCK_VIRTUAL : QEMU_CLOCK_REALTIME;
322 * Is the current monitor, if any, a QMP monitor?
324 bool monitor_cur_is_qmp(void)
326 return cur_mon && monitor_is_qmp(cur_mon);
329 void monitor_read_command(Monitor *mon, int show_prompt)
331 if (!mon->rs)
332 return;
334 readline_start(mon->rs, "(qemu) ", 0, monitor_command_cb, NULL);
335 if (show_prompt)
336 readline_show_prompt(mon->rs);
339 int monitor_read_password(Monitor *mon, ReadLineFunc *readline_func,
340 void *opaque)
342 if (mon->rs) {
343 readline_start(mon->rs, "Password: ", 1, readline_func, opaque);
344 /* prompt is printed on return from the command handler */
345 return 0;
346 } else {
347 monitor_printf(mon, "terminal does not support password prompting\n");
348 return -ENOTTY;
352 static void qmp_request_free(QMPRequest *req)
354 qobject_unref(req->req);
355 error_free(req->err);
356 g_free(req);
359 /* Caller must hold mon->qmp.qmp_queue_lock */
360 static void monitor_qmp_cleanup_req_queue_locked(MonitorQMP *mon)
362 while (!g_queue_is_empty(mon->qmp_requests)) {
363 qmp_request_free(g_queue_pop_head(mon->qmp_requests));
367 static void monitor_qmp_cleanup_queues(MonitorQMP *mon)
369 qemu_mutex_lock(&mon->qmp_queue_lock);
370 monitor_qmp_cleanup_req_queue_locked(mon);
371 qemu_mutex_unlock(&mon->qmp_queue_lock);
375 static void monitor_flush_locked(Monitor *mon);
377 static gboolean monitor_unblocked(GIOChannel *chan, GIOCondition cond,
378 void *opaque)
380 Monitor *mon = opaque;
382 qemu_mutex_lock(&mon->mon_lock);
383 mon->out_watch = 0;
384 monitor_flush_locked(mon);
385 qemu_mutex_unlock(&mon->mon_lock);
386 return FALSE;
389 /* Caller must hold mon->mon_lock */
390 static void monitor_flush_locked(Monitor *mon)
392 int rc;
393 size_t len;
394 const char *buf;
396 if (mon->skip_flush) {
397 return;
400 buf = qstring_get_str(mon->outbuf);
401 len = qstring_get_length(mon->outbuf);
403 if (len && !mon->mux_out) {
404 rc = qemu_chr_fe_write(&mon->chr, (const uint8_t *) buf, len);
405 if ((rc < 0 && errno != EAGAIN) || (rc == len)) {
406 /* all flushed or error */
407 qobject_unref(mon->outbuf);
408 mon->outbuf = qstring_new();
409 return;
411 if (rc > 0) {
412 /* partial write */
413 QString *tmp = qstring_from_str(buf + rc);
414 qobject_unref(mon->outbuf);
415 mon->outbuf = tmp;
417 if (mon->out_watch == 0) {
418 mon->out_watch =
419 qemu_chr_fe_add_watch(&mon->chr, G_IO_OUT | G_IO_HUP,
420 monitor_unblocked, mon);
425 void monitor_flush(Monitor *mon)
427 qemu_mutex_lock(&mon->mon_lock);
428 monitor_flush_locked(mon);
429 qemu_mutex_unlock(&mon->mon_lock);
432 /* flush at every end of line */
433 static int monitor_puts(Monitor *mon, const char *str)
435 int i;
436 char c;
438 qemu_mutex_lock(&mon->mon_lock);
439 for (i = 0; str[i]; i++) {
440 c = str[i];
441 if (c == '\n') {
442 qstring_append_chr(mon->outbuf, '\r');
444 qstring_append_chr(mon->outbuf, c);
445 if (c == '\n') {
446 monitor_flush_locked(mon);
449 qemu_mutex_unlock(&mon->mon_lock);
451 return i;
454 int monitor_vprintf(Monitor *mon, const char *fmt, va_list ap)
456 char *buf;
457 int n;
459 if (!mon)
460 return -1;
462 if (monitor_is_qmp(mon)) {
463 return -1;
466 buf = g_strdup_vprintf(fmt, ap);
467 n = monitor_puts(mon, buf);
468 g_free(buf);
469 return n;
472 int monitor_printf(Monitor *mon, const char *fmt, ...)
474 int ret;
476 va_list ap;
477 va_start(ap, fmt);
478 ret = monitor_vprintf(mon, fmt, ap);
479 va_end(ap);
480 return ret;
483 static void qmp_send_response(MonitorQMP *mon, const QDict *rsp)
485 const QObject *data = QOBJECT(rsp);
486 QString *json;
488 json = mon->common.flags & MONITOR_USE_PRETTY ?
489 qobject_to_json_pretty(data) : qobject_to_json(data);
490 assert(json != NULL);
492 qstring_append_chr(json, '\n');
493 monitor_puts(&mon->common, qstring_get_str(json));
495 qobject_unref(json);
498 static MonitorQAPIEventConf monitor_qapi_event_conf[QAPI_EVENT__MAX] = {
499 /* Limit guest-triggerable events to 1 per second */
500 [QAPI_EVENT_RTC_CHANGE] = { 1000 * SCALE_MS },
501 [QAPI_EVENT_WATCHDOG] = { 1000 * SCALE_MS },
502 [QAPI_EVENT_BALLOON_CHANGE] = { 1000 * SCALE_MS },
503 [QAPI_EVENT_QUORUM_REPORT_BAD] = { 1000 * SCALE_MS },
504 [QAPI_EVENT_QUORUM_FAILURE] = { 1000 * SCALE_MS },
505 [QAPI_EVENT_VSERPORT_CHANGE] = { 1000 * SCALE_MS },
509 * Broadcast an event to all monitors.
510 * @qdict is the event object. Its member "event" must match @event.
511 * Caller must hold monitor_lock.
513 static void monitor_qapi_event_emit(QAPIEvent event, QDict *qdict)
515 Monitor *mon;
516 MonitorQMP *qmp_mon;
518 trace_monitor_protocol_event_emit(event, qdict);
519 QTAILQ_FOREACH(mon, &mon_list, entry) {
520 if (!monitor_is_qmp(mon)) {
521 continue;
524 qmp_mon = container_of(mon, MonitorQMP, common);
525 if (qmp_mon->commands != &qmp_cap_negotiation_commands) {
526 qmp_send_response(qmp_mon, qdict);
531 static void monitor_qapi_event_handler(void *opaque);
534 * Queue a new event for emission to Monitor instances,
535 * applying any rate limiting if required.
537 static void
538 monitor_qapi_event_queue_no_reenter(QAPIEvent event, QDict *qdict)
540 MonitorQAPIEventConf *evconf;
541 MonitorQAPIEventState *evstate;
543 assert(event < QAPI_EVENT__MAX);
544 evconf = &monitor_qapi_event_conf[event];
545 trace_monitor_protocol_event_queue(event, qdict, evconf->rate);
547 qemu_mutex_lock(&monitor_lock);
549 if (!evconf->rate) {
550 /* Unthrottled event */
551 monitor_qapi_event_emit(event, qdict);
552 } else {
553 QDict *data = qobject_to(QDict, qdict_get(qdict, "data"));
554 MonitorQAPIEventState key = { .event = event, .data = data };
556 evstate = g_hash_table_lookup(monitor_qapi_event_state, &key);
557 assert(!evstate || timer_pending(evstate->timer));
559 if (evstate) {
561 * Timer is pending for (at least) evconf->rate ns after
562 * last send. Store event for sending when timer fires,
563 * replacing a prior stored event if any.
565 qobject_unref(evstate->qdict);
566 evstate->qdict = qobject_ref(qdict);
567 } else {
569 * Last send was (at least) evconf->rate ns ago.
570 * Send immediately, and arm the timer to call
571 * monitor_qapi_event_handler() in evconf->rate ns. Any
572 * events arriving before then will be delayed until then.
574 int64_t now = qemu_clock_get_ns(monitor_get_event_clock());
576 monitor_qapi_event_emit(event, qdict);
578 evstate = g_new(MonitorQAPIEventState, 1);
579 evstate->event = event;
580 evstate->data = qobject_ref(data);
581 evstate->qdict = NULL;
582 evstate->timer = timer_new_ns(monitor_get_event_clock(),
583 monitor_qapi_event_handler,
584 evstate);
585 g_hash_table_add(monitor_qapi_event_state, evstate);
586 timer_mod_ns(evstate->timer, now + evconf->rate);
590 qemu_mutex_unlock(&monitor_lock);
593 void qapi_event_emit(QAPIEvent event, QDict *qdict)
596 * monitor_qapi_event_queue_no_reenter() is not reentrant: it
597 * would deadlock on monitor_lock. Work around by queueing
598 * events in thread-local storage.
599 * TODO: remove this, make it re-enter safe.
601 typedef struct MonitorQapiEvent {
602 QAPIEvent event;
603 QDict *qdict;
604 QSIMPLEQ_ENTRY(MonitorQapiEvent) entry;
605 } MonitorQapiEvent;
606 static __thread QSIMPLEQ_HEAD(, MonitorQapiEvent) event_queue;
607 static __thread bool reentered;
608 MonitorQapiEvent *ev;
610 if (!reentered) {
611 QSIMPLEQ_INIT(&event_queue);
614 ev = g_new(MonitorQapiEvent, 1);
615 ev->qdict = qobject_ref(qdict);
616 ev->event = event;
617 QSIMPLEQ_INSERT_TAIL(&event_queue, ev, entry);
618 if (reentered) {
619 return;
622 reentered = true;
624 while ((ev = QSIMPLEQ_FIRST(&event_queue)) != NULL) {
625 QSIMPLEQ_REMOVE_HEAD(&event_queue, entry);
626 monitor_qapi_event_queue_no_reenter(ev->event, ev->qdict);
627 qobject_unref(ev->qdict);
628 g_free(ev);
631 reentered = false;
635 * This function runs evconf->rate ns after sending a throttled
636 * event.
637 * If another event has since been stored, send it.
639 static void monitor_qapi_event_handler(void *opaque)
641 MonitorQAPIEventState *evstate = opaque;
642 MonitorQAPIEventConf *evconf = &monitor_qapi_event_conf[evstate->event];
644 trace_monitor_protocol_event_handler(evstate->event, evstate->qdict);
645 qemu_mutex_lock(&monitor_lock);
647 if (evstate->qdict) {
648 int64_t now = qemu_clock_get_ns(monitor_get_event_clock());
650 monitor_qapi_event_emit(evstate->event, evstate->qdict);
651 qobject_unref(evstate->qdict);
652 evstate->qdict = NULL;
653 timer_mod_ns(evstate->timer, now + evconf->rate);
654 } else {
655 g_hash_table_remove(monitor_qapi_event_state, evstate);
656 qobject_unref(evstate->data);
657 timer_free(evstate->timer);
658 g_free(evstate);
661 qemu_mutex_unlock(&monitor_lock);
664 static unsigned int qapi_event_throttle_hash(const void *key)
666 const MonitorQAPIEventState *evstate = key;
667 unsigned int hash = evstate->event * 255;
669 if (evstate->event == QAPI_EVENT_VSERPORT_CHANGE) {
670 hash += g_str_hash(qdict_get_str(evstate->data, "id"));
673 if (evstate->event == QAPI_EVENT_QUORUM_REPORT_BAD) {
674 hash += g_str_hash(qdict_get_str(evstate->data, "node-name"));
677 return hash;
680 static gboolean qapi_event_throttle_equal(const void *a, const void *b)
682 const MonitorQAPIEventState *eva = a;
683 const MonitorQAPIEventState *evb = b;
685 if (eva->event != evb->event) {
686 return FALSE;
689 if (eva->event == QAPI_EVENT_VSERPORT_CHANGE) {
690 return !strcmp(qdict_get_str(eva->data, "id"),
691 qdict_get_str(evb->data, "id"));
694 if (eva->event == QAPI_EVENT_QUORUM_REPORT_BAD) {
695 return !strcmp(qdict_get_str(eva->data, "node-name"),
696 qdict_get_str(evb->data, "node-name"));
699 return TRUE;
702 static void monitor_qapi_event_init(void)
704 monitor_qapi_event_state = g_hash_table_new(qapi_event_throttle_hash,
705 qapi_event_throttle_equal);
708 static void handle_hmp_command(Monitor *mon, const char *cmdline);
710 static void monitor_iothread_init(void);
712 static void monitor_data_init(Monitor *mon, int flags, bool skip_flush,
713 bool use_io_thread)
715 if (use_io_thread && !mon_iothread) {
716 monitor_iothread_init();
718 qemu_mutex_init(&mon->mon_lock);
719 mon->outbuf = qstring_new();
720 /* Use *mon_cmds by default. */
721 mon->cmd_table = mon_cmds;
722 mon->skip_flush = skip_flush;
723 mon->use_io_thread = use_io_thread;
724 mon->flags = flags;
727 static void monitor_data_destroy_qmp(MonitorQMP *mon)
729 json_message_parser_destroy(&mon->parser);
730 qemu_mutex_destroy(&mon->qmp_queue_lock);
731 monitor_qmp_cleanup_req_queue_locked(mon);
732 g_queue_free(mon->qmp_requests);
735 static void monitor_data_destroy(Monitor *mon)
737 g_free(mon->mon_cpu_path);
738 qemu_chr_fe_deinit(&mon->chr, false);
739 if (monitor_is_qmp(mon)) {
740 monitor_data_destroy_qmp(container_of(mon, MonitorQMP, common));
742 readline_free(mon->rs);
743 qobject_unref(mon->outbuf);
744 qemu_mutex_destroy(&mon->mon_lock);
747 char *qmp_human_monitor_command(const char *command_line, bool has_cpu_index,
748 int64_t cpu_index, Error **errp)
750 char *output = NULL;
751 Monitor *old_mon;
752 Monitor hmp = {};
754 monitor_data_init(&hmp, 0, true, false);
756 old_mon = cur_mon;
757 cur_mon = &hmp;
759 if (has_cpu_index) {
760 int ret = monitor_set_cpu(cpu_index);
761 if (ret < 0) {
762 cur_mon = old_mon;
763 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cpu-index",
764 "a CPU number");
765 goto out;
769 handle_hmp_command(&hmp, command_line);
770 cur_mon = old_mon;
772 qemu_mutex_lock(&hmp.mon_lock);
773 if (qstring_get_length(hmp.outbuf) > 0) {
774 output = g_strdup(qstring_get_str(hmp.outbuf));
775 } else {
776 output = g_strdup("");
778 qemu_mutex_unlock(&hmp.mon_lock);
780 out:
781 monitor_data_destroy(&hmp);
782 return output;
785 static int compare_cmd(const char *name, const char *list)
787 const char *p, *pstart;
788 int len;
789 len = strlen(name);
790 p = list;
791 for(;;) {
792 pstart = p;
793 p = qemu_strchrnul(p, '|');
794 if ((p - pstart) == len && !memcmp(pstart, name, len))
795 return 1;
796 if (*p == '\0')
797 break;
798 p++;
800 return 0;
803 static int get_str(char *buf, int buf_size, const char **pp)
805 const char *p;
806 char *q;
807 int c;
809 q = buf;
810 p = *pp;
811 while (qemu_isspace(*p)) {
812 p++;
814 if (*p == '\0') {
815 fail:
816 *q = '\0';
817 *pp = p;
818 return -1;
820 if (*p == '\"') {
821 p++;
822 while (*p != '\0' && *p != '\"') {
823 if (*p == '\\') {
824 p++;
825 c = *p++;
826 switch (c) {
827 case 'n':
828 c = '\n';
829 break;
830 case 'r':
831 c = '\r';
832 break;
833 case '\\':
834 case '\'':
835 case '\"':
836 break;
837 default:
838 printf("unsupported escape code: '\\%c'\n", c);
839 goto fail;
841 if ((q - buf) < buf_size - 1) {
842 *q++ = c;
844 } else {
845 if ((q - buf) < buf_size - 1) {
846 *q++ = *p;
848 p++;
851 if (*p != '\"') {
852 printf("unterminated string\n");
853 goto fail;
855 p++;
856 } else {
857 while (*p != '\0' && !qemu_isspace(*p)) {
858 if ((q - buf) < buf_size - 1) {
859 *q++ = *p;
861 p++;
864 *q = '\0';
865 *pp = p;
866 return 0;
869 #define MAX_ARGS 16
871 static void free_cmdline_args(char **args, int nb_args)
873 int i;
875 assert(nb_args <= MAX_ARGS);
877 for (i = 0; i < nb_args; i++) {
878 g_free(args[i]);
884 * Parse the command line to get valid args.
885 * @cmdline: command line to be parsed.
886 * @pnb_args: location to store the number of args, must NOT be NULL.
887 * @args: location to store the args, which should be freed by caller, must
888 * NOT be NULL.
890 * Returns 0 on success, negative on failure.
892 * NOTE: this parser is an approximate form of the real command parser. Number
893 * of args have a limit of MAX_ARGS. If cmdline contains more, it will
894 * return with failure.
896 static int parse_cmdline(const char *cmdline,
897 int *pnb_args, char **args)
899 const char *p;
900 int nb_args, ret;
901 char buf[1024];
903 p = cmdline;
904 nb_args = 0;
905 for (;;) {
906 while (qemu_isspace(*p)) {
907 p++;
909 if (*p == '\0') {
910 break;
912 if (nb_args >= MAX_ARGS) {
913 goto fail;
915 ret = get_str(buf, sizeof(buf), &p);
916 if (ret < 0) {
917 goto fail;
919 args[nb_args] = g_strdup(buf);
920 nb_args++;
922 *pnb_args = nb_args;
923 return 0;
925 fail:
926 free_cmdline_args(args, nb_args);
927 return -1;
931 * Can command @cmd be executed in preconfig state?
933 static bool cmd_can_preconfig(const mon_cmd_t *cmd)
935 if (!cmd->flags) {
936 return false;
939 return strchr(cmd->flags, 'p');
942 static void help_cmd_dump_one(Monitor *mon,
943 const mon_cmd_t *cmd,
944 char **prefix_args,
945 int prefix_args_nb)
947 int i;
949 if (runstate_check(RUN_STATE_PRECONFIG) && !cmd_can_preconfig(cmd)) {
950 return;
953 for (i = 0; i < prefix_args_nb; i++) {
954 monitor_printf(mon, "%s ", prefix_args[i]);
956 monitor_printf(mon, "%s %s -- %s\n", cmd->name, cmd->params, cmd->help);
959 /* @args[@arg_index] is the valid command need to find in @cmds */
960 static void help_cmd_dump(Monitor *mon, const mon_cmd_t *cmds,
961 char **args, int nb_args, int arg_index)
963 const mon_cmd_t *cmd;
964 size_t i;
966 /* No valid arg need to compare with, dump all in *cmds */
967 if (arg_index >= nb_args) {
968 for (cmd = cmds; cmd->name != NULL; cmd++) {
969 help_cmd_dump_one(mon, cmd, args, arg_index);
971 return;
974 /* Find one entry to dump */
975 for (cmd = cmds; cmd->name != NULL; cmd++) {
976 if (compare_cmd(args[arg_index], cmd->name) &&
977 ((!runstate_check(RUN_STATE_PRECONFIG) ||
978 cmd_can_preconfig(cmd)))) {
979 if (cmd->sub_table) {
980 /* continue with next arg */
981 help_cmd_dump(mon, cmd->sub_table,
982 args, nb_args, arg_index + 1);
983 } else {
984 help_cmd_dump_one(mon, cmd, args, arg_index);
986 return;
990 /* Command not found */
991 monitor_printf(mon, "unknown command: '");
992 for (i = 0; i <= arg_index; i++) {
993 monitor_printf(mon, "%s%s", args[i], i == arg_index ? "'\n" : " ");
997 static void help_cmd(Monitor *mon, const char *name)
999 char *args[MAX_ARGS];
1000 int nb_args = 0;
1002 /* 1. parse user input */
1003 if (name) {
1004 /* special case for log, directly dump and return */
1005 if (!strcmp(name, "log")) {
1006 const QEMULogItem *item;
1007 monitor_printf(mon, "Log items (comma separated):\n");
1008 monitor_printf(mon, "%-10s %s\n", "none", "remove all logs");
1009 for (item = qemu_log_items; item->mask != 0; item++) {
1010 monitor_printf(mon, "%-10s %s\n", item->name, item->help);
1012 return;
1015 if (parse_cmdline(name, &nb_args, args) < 0) {
1016 return;
1020 /* 2. dump the contents according to parsed args */
1021 help_cmd_dump(mon, mon->cmd_table, args, nb_args, 0);
1023 free_cmdline_args(args, nb_args);
1026 static void do_help_cmd(Monitor *mon, const QDict *qdict)
1028 help_cmd(mon, qdict_get_try_str(qdict, "name"));
1031 static void hmp_trace_event(Monitor *mon, const QDict *qdict)
1033 const char *tp_name = qdict_get_str(qdict, "name");
1034 bool new_state = qdict_get_bool(qdict, "option");
1035 bool has_vcpu = qdict_haskey(qdict, "vcpu");
1036 int vcpu = qdict_get_try_int(qdict, "vcpu", 0);
1037 Error *local_err = NULL;
1039 if (vcpu < 0) {
1040 monitor_printf(mon, "argument vcpu must be positive");
1041 return;
1044 qmp_trace_event_set_state(tp_name, new_state, true, true, has_vcpu, vcpu, &local_err);
1045 if (local_err) {
1046 error_report_err(local_err);
1050 #ifdef CONFIG_TRACE_SIMPLE
1051 static void hmp_trace_file(Monitor *mon, const QDict *qdict)
1053 const char *op = qdict_get_try_str(qdict, "op");
1054 const char *arg = qdict_get_try_str(qdict, "arg");
1056 if (!op) {
1057 st_print_trace_file_status();
1058 } else if (!strcmp(op, "on")) {
1059 st_set_trace_file_enabled(true);
1060 } else if (!strcmp(op, "off")) {
1061 st_set_trace_file_enabled(false);
1062 } else if (!strcmp(op, "flush")) {
1063 st_flush_trace_buffer();
1064 } else if (!strcmp(op, "set")) {
1065 if (arg) {
1066 st_set_trace_file(arg);
1068 } else {
1069 monitor_printf(mon, "unexpected argument \"%s\"\n", op);
1070 help_cmd(mon, "trace-file");
1073 #endif
1075 static void hmp_info_help(Monitor *mon, const QDict *qdict)
1077 help_cmd(mon, "info");
1080 static void query_commands_cb(QmpCommand *cmd, void *opaque)
1082 CommandInfoList *info, **list = opaque;
1084 if (!cmd->enabled) {
1085 return;
1088 info = g_malloc0(sizeof(*info));
1089 info->value = g_malloc0(sizeof(*info->value));
1090 info->value->name = g_strdup(cmd->name);
1091 info->next = *list;
1092 *list = info;
1095 CommandInfoList *qmp_query_commands(Error **errp)
1097 CommandInfoList *list = NULL;
1098 MonitorQMP *mon;
1100 assert(monitor_is_qmp(cur_mon));
1101 mon = container_of(cur_mon, MonitorQMP, common);
1103 qmp_for_each_command(mon->commands, query_commands_cb, &list);
1105 return list;
1108 EventInfoList *qmp_query_events(Error **errp)
1111 * TODO This deprecated command is the only user of
1112 * QAPIEvent_str() and QAPIEvent_lookup[]. When the command goes,
1113 * they should go, too.
1115 EventInfoList *info, *ev_list = NULL;
1116 QAPIEvent e;
1118 for (e = 0 ; e < QAPI_EVENT__MAX ; e++) {
1119 const char *event_name = QAPIEvent_str(e);
1120 assert(event_name != NULL);
1121 info = g_malloc0(sizeof(*info));
1122 info->value = g_malloc0(sizeof(*info->value));
1123 info->value->name = g_strdup(event_name);
1125 info->next = ev_list;
1126 ev_list = info;
1129 return ev_list;
1133 * Minor hack: generated marshalling suppressed for this command
1134 * ('gen': false in the schema) so we can parse the JSON string
1135 * directly into QObject instead of first parsing it with
1136 * visit_type_SchemaInfoList() into a SchemaInfoList, then marshal it
1137 * to QObject with generated output marshallers, every time. Instead,
1138 * we do it in test-qobject-input-visitor.c, just to make sure
1139 * qapi-gen.py's output actually conforms to the schema.
1141 static void qmp_query_qmp_schema(QDict *qdict, QObject **ret_data,
1142 Error **errp)
1144 *ret_data = qobject_from_qlit(&qmp_schema_qlit);
1147 static void monitor_init_qmp_commands(void)
1150 * Two command lists:
1151 * - qmp_commands contains all QMP commands
1152 * - qmp_cap_negotiation_commands contains just
1153 * "qmp_capabilities", to enforce capability negotiation
1156 qmp_init_marshal(&qmp_commands);
1158 qmp_register_command(&qmp_commands, "query-qmp-schema",
1159 qmp_query_qmp_schema, QCO_ALLOW_PRECONFIG);
1160 qmp_register_command(&qmp_commands, "device_add", qmp_device_add,
1161 QCO_NO_OPTIONS);
1162 qmp_register_command(&qmp_commands, "netdev_add", qmp_netdev_add,
1163 QCO_NO_OPTIONS);
1165 QTAILQ_INIT(&qmp_cap_negotiation_commands);
1166 qmp_register_command(&qmp_cap_negotiation_commands, "qmp_capabilities",
1167 qmp_marshal_qmp_capabilities, QCO_ALLOW_PRECONFIG);
1170 static bool qmp_oob_enabled(MonitorQMP *mon)
1172 return mon->capab[QMP_CAPABILITY_OOB];
1175 static void monitor_qmp_caps_reset(MonitorQMP *mon)
1177 memset(mon->capab_offered, 0, sizeof(mon->capab_offered));
1178 memset(mon->capab, 0, sizeof(mon->capab));
1179 mon->capab_offered[QMP_CAPABILITY_OOB] = mon->common.use_io_thread;
1183 * Accept QMP capabilities in @list for @mon.
1184 * On success, set mon->qmp.capab[], and return true.
1185 * On error, set @errp, and return false.
1187 static bool qmp_caps_accept(MonitorQMP *mon, QMPCapabilityList *list,
1188 Error **errp)
1190 GString *unavailable = NULL;
1191 bool capab[QMP_CAPABILITY__MAX];
1193 memset(capab, 0, sizeof(capab));
1195 for (; list; list = list->next) {
1196 if (!mon->capab_offered[list->value]) {
1197 if (!unavailable) {
1198 unavailable = g_string_new(QMPCapability_str(list->value));
1199 } else {
1200 g_string_append_printf(unavailable, ", %s",
1201 QMPCapability_str(list->value));
1204 capab[list->value] = true;
1207 if (unavailable) {
1208 error_setg(errp, "Capability %s not available", unavailable->str);
1209 g_string_free(unavailable, true);
1210 return false;
1213 memcpy(mon->capab, capab, sizeof(capab));
1214 return true;
1217 void qmp_qmp_capabilities(bool has_enable, QMPCapabilityList *enable,
1218 Error **errp)
1220 MonitorQMP *mon;
1222 assert(monitor_is_qmp(cur_mon));
1223 mon = container_of(cur_mon, MonitorQMP, common);
1225 if (mon->commands == &qmp_commands) {
1226 error_set(errp, ERROR_CLASS_COMMAND_NOT_FOUND,
1227 "Capabilities negotiation is already complete, command "
1228 "ignored");
1229 return;
1232 if (!qmp_caps_accept(mon, enable, errp)) {
1233 return;
1236 mon->commands = &qmp_commands;
1239 /* Set the current CPU defined by the user. Callers must hold BQL. */
1240 int monitor_set_cpu(int cpu_index)
1242 CPUState *cpu;
1244 cpu = qemu_get_cpu(cpu_index);
1245 if (cpu == NULL) {
1246 return -1;
1248 g_free(cur_mon->mon_cpu_path);
1249 cur_mon->mon_cpu_path = object_get_canonical_path(OBJECT(cpu));
1250 return 0;
1253 /* Callers must hold BQL. */
1254 static CPUState *mon_get_cpu_sync(bool synchronize)
1256 CPUState *cpu;
1258 if (cur_mon->mon_cpu_path) {
1259 cpu = (CPUState *) object_resolve_path_type(cur_mon->mon_cpu_path,
1260 TYPE_CPU, NULL);
1261 if (!cpu) {
1262 g_free(cur_mon->mon_cpu_path);
1263 cur_mon->mon_cpu_path = NULL;
1266 if (!cur_mon->mon_cpu_path) {
1267 if (!first_cpu) {
1268 return NULL;
1270 monitor_set_cpu(first_cpu->cpu_index);
1271 cpu = first_cpu;
1273 if (synchronize) {
1274 cpu_synchronize_state(cpu);
1276 return cpu;
1279 CPUState *mon_get_cpu(void)
1281 return mon_get_cpu_sync(true);
1284 CPUArchState *mon_get_cpu_env(void)
1286 CPUState *cs = mon_get_cpu();
1288 return cs ? cs->env_ptr : NULL;
1291 int monitor_get_cpu_index(void)
1293 CPUState *cs = mon_get_cpu_sync(false);
1295 return cs ? cs->cpu_index : UNASSIGNED_CPU_INDEX;
1298 static void hmp_info_registers(Monitor *mon, const QDict *qdict)
1300 bool all_cpus = qdict_get_try_bool(qdict, "cpustate_all", false);
1301 CPUState *cs;
1303 if (all_cpus) {
1304 CPU_FOREACH(cs) {
1305 monitor_printf(mon, "\nCPU#%d\n", cs->cpu_index);
1306 cpu_dump_state(cs, NULL, CPU_DUMP_FPU);
1308 } else {
1309 cs = mon_get_cpu();
1311 if (!cs) {
1312 monitor_printf(mon, "No CPU available\n");
1313 return;
1316 cpu_dump_state(cs, NULL, CPU_DUMP_FPU);
1320 #ifdef CONFIG_TCG
1321 static void hmp_info_jit(Monitor *mon, const QDict *qdict)
1323 if (!tcg_enabled()) {
1324 error_report("JIT information is only available with accel=tcg");
1325 return;
1328 dump_exec_info();
1329 dump_drift_info();
1332 static void hmp_info_opcount(Monitor *mon, const QDict *qdict)
1334 dump_opcount_info();
1336 #endif
1338 static void hmp_info_sync_profile(Monitor *mon, const QDict *qdict)
1340 int64_t max = qdict_get_try_int(qdict, "max", 10);
1341 bool mean = qdict_get_try_bool(qdict, "mean", false);
1342 bool coalesce = !qdict_get_try_bool(qdict, "no_coalesce", false);
1343 enum QSPSortBy sort_by;
1345 sort_by = mean ? QSP_SORT_BY_AVG_WAIT_TIME : QSP_SORT_BY_TOTAL_WAIT_TIME;
1346 qsp_report(max, sort_by, coalesce);
1349 static void hmp_info_history(Monitor *mon, const QDict *qdict)
1351 int i;
1352 const char *str;
1354 if (!mon->rs)
1355 return;
1356 i = 0;
1357 for(;;) {
1358 str = readline_get_history(mon->rs, i);
1359 if (!str)
1360 break;
1361 monitor_printf(mon, "%d: '%s'\n", i, str);
1362 i++;
1366 static void hmp_info_cpustats(Monitor *mon, const QDict *qdict)
1368 CPUState *cs = mon_get_cpu();
1370 if (!cs) {
1371 monitor_printf(mon, "No CPU available\n");
1372 return;
1374 cpu_dump_statistics(cs, 0);
1377 static void hmp_info_trace_events(Monitor *mon, const QDict *qdict)
1379 const char *name = qdict_get_try_str(qdict, "name");
1380 bool has_vcpu = qdict_haskey(qdict, "vcpu");
1381 int vcpu = qdict_get_try_int(qdict, "vcpu", 0);
1382 TraceEventInfoList *events;
1383 TraceEventInfoList *elem;
1384 Error *local_err = NULL;
1386 if (name == NULL) {
1387 name = "*";
1389 if (vcpu < 0) {
1390 monitor_printf(mon, "argument vcpu must be positive");
1391 return;
1394 events = qmp_trace_event_get_state(name, has_vcpu, vcpu, &local_err);
1395 if (local_err) {
1396 error_report_err(local_err);
1397 return;
1400 for (elem = events; elem != NULL; elem = elem->next) {
1401 monitor_printf(mon, "%s : state %u\n",
1402 elem->value->name,
1403 elem->value->state == TRACE_EVENT_STATE_ENABLED ? 1 : 0);
1405 qapi_free_TraceEventInfoList(events);
1408 void qmp_client_migrate_info(const char *protocol, const char *hostname,
1409 bool has_port, int64_t port,
1410 bool has_tls_port, int64_t tls_port,
1411 bool has_cert_subject, const char *cert_subject,
1412 Error **errp)
1414 if (strcmp(protocol, "spice") == 0) {
1415 if (!qemu_using_spice(errp)) {
1416 return;
1419 if (!has_port && !has_tls_port) {
1420 error_setg(errp, QERR_MISSING_PARAMETER, "port/tls-port");
1421 return;
1424 if (qemu_spice_migrate_info(hostname,
1425 has_port ? port : -1,
1426 has_tls_port ? tls_port : -1,
1427 cert_subject)) {
1428 error_setg(errp, QERR_UNDEFINED_ERROR);
1429 return;
1431 return;
1434 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "protocol", "spice");
1437 static void hmp_logfile(Monitor *mon, const QDict *qdict)
1439 Error *err = NULL;
1441 qemu_set_log_filename(qdict_get_str(qdict, "filename"), &err);
1442 if (err) {
1443 error_report_err(err);
1447 static void hmp_log(Monitor *mon, const QDict *qdict)
1449 int mask;
1450 const char *items = qdict_get_str(qdict, "items");
1452 if (!strcmp(items, "none")) {
1453 mask = 0;
1454 } else {
1455 mask = qemu_str_to_log_mask(items);
1456 if (!mask) {
1457 help_cmd(mon, "log");
1458 return;
1461 qemu_set_log(mask);
1464 static void hmp_singlestep(Monitor *mon, const QDict *qdict)
1466 const char *option = qdict_get_try_str(qdict, "option");
1467 if (!option || !strcmp(option, "on")) {
1468 singlestep = 1;
1469 } else if (!strcmp(option, "off")) {
1470 singlestep = 0;
1471 } else {
1472 monitor_printf(mon, "unexpected option %s\n", option);
1476 static void hmp_gdbserver(Monitor *mon, const QDict *qdict)
1478 const char *device = qdict_get_try_str(qdict, "device");
1479 if (!device)
1480 device = "tcp::" DEFAULT_GDBSTUB_PORT;
1481 if (gdbserver_start(device) < 0) {
1482 monitor_printf(mon, "Could not open gdbserver on device '%s'\n",
1483 device);
1484 } else if (strcmp(device, "none") == 0) {
1485 monitor_printf(mon, "Disabled gdbserver\n");
1486 } else {
1487 monitor_printf(mon, "Waiting for gdb connection on device '%s'\n",
1488 device);
1492 static void hmp_watchdog_action(Monitor *mon, const QDict *qdict)
1494 const char *action = qdict_get_str(qdict, "action");
1495 if (select_watchdog_action(action) == -1) {
1496 monitor_printf(mon, "Unknown watchdog action '%s'\n", action);
1500 static void monitor_printc(Monitor *mon, int c)
1502 monitor_printf(mon, "'");
1503 switch(c) {
1504 case '\'':
1505 monitor_printf(mon, "\\'");
1506 break;
1507 case '\\':
1508 monitor_printf(mon, "\\\\");
1509 break;
1510 case '\n':
1511 monitor_printf(mon, "\\n");
1512 break;
1513 case '\r':
1514 monitor_printf(mon, "\\r");
1515 break;
1516 default:
1517 if (c >= 32 && c <= 126) {
1518 monitor_printf(mon, "%c", c);
1519 } else {
1520 monitor_printf(mon, "\\x%02x", c);
1522 break;
1524 monitor_printf(mon, "'");
1527 static void memory_dump(Monitor *mon, int count, int format, int wsize,
1528 hwaddr addr, int is_physical)
1530 int l, line_size, i, max_digits, len;
1531 uint8_t buf[16];
1532 uint64_t v;
1533 CPUState *cs = mon_get_cpu();
1535 if (!cs && (format == 'i' || !is_physical)) {
1536 monitor_printf(mon, "Can not dump without CPU\n");
1537 return;
1540 if (format == 'i') {
1541 monitor_disas(mon, cs, addr, count, is_physical);
1542 return;
1545 len = wsize * count;
1546 if (wsize == 1)
1547 line_size = 8;
1548 else
1549 line_size = 16;
1550 max_digits = 0;
1552 switch(format) {
1553 case 'o':
1554 max_digits = DIV_ROUND_UP(wsize * 8, 3);
1555 break;
1556 default:
1557 case 'x':
1558 max_digits = (wsize * 8) / 4;
1559 break;
1560 case 'u':
1561 case 'd':
1562 max_digits = DIV_ROUND_UP(wsize * 8 * 10, 33);
1563 break;
1564 case 'c':
1565 wsize = 1;
1566 break;
1569 while (len > 0) {
1570 if (is_physical)
1571 monitor_printf(mon, TARGET_FMT_plx ":", addr);
1572 else
1573 monitor_printf(mon, TARGET_FMT_lx ":", (target_ulong)addr);
1574 l = len;
1575 if (l > line_size)
1576 l = line_size;
1577 if (is_physical) {
1578 AddressSpace *as = cs ? cs->as : &address_space_memory;
1579 MemTxResult r = address_space_read(as, addr,
1580 MEMTXATTRS_UNSPECIFIED, buf, l);
1581 if (r != MEMTX_OK) {
1582 monitor_printf(mon, " Cannot access memory\n");
1583 break;
1585 } else {
1586 if (cpu_memory_rw_debug(cs, addr, buf, l, 0) < 0) {
1587 monitor_printf(mon, " Cannot access memory\n");
1588 break;
1591 i = 0;
1592 while (i < l) {
1593 switch(wsize) {
1594 default:
1595 case 1:
1596 v = ldub_p(buf + i);
1597 break;
1598 case 2:
1599 v = lduw_p(buf + i);
1600 break;
1601 case 4:
1602 v = (uint32_t)ldl_p(buf + i);
1603 break;
1604 case 8:
1605 v = ldq_p(buf + i);
1606 break;
1608 monitor_printf(mon, " ");
1609 switch(format) {
1610 case 'o':
1611 monitor_printf(mon, "%#*" PRIo64, max_digits, v);
1612 break;
1613 case 'x':
1614 monitor_printf(mon, "0x%0*" PRIx64, max_digits, v);
1615 break;
1616 case 'u':
1617 monitor_printf(mon, "%*" PRIu64, max_digits, v);
1618 break;
1619 case 'd':
1620 monitor_printf(mon, "%*" PRId64, max_digits, v);
1621 break;
1622 case 'c':
1623 monitor_printc(mon, v);
1624 break;
1626 i += wsize;
1628 monitor_printf(mon, "\n");
1629 addr += l;
1630 len -= l;
1634 static void hmp_memory_dump(Monitor *mon, const QDict *qdict)
1636 int count = qdict_get_int(qdict, "count");
1637 int format = qdict_get_int(qdict, "format");
1638 int size = qdict_get_int(qdict, "size");
1639 target_long addr = qdict_get_int(qdict, "addr");
1641 memory_dump(mon, count, format, size, addr, 0);
1644 static void hmp_physical_memory_dump(Monitor *mon, const QDict *qdict)
1646 int count = qdict_get_int(qdict, "count");
1647 int format = qdict_get_int(qdict, "format");
1648 int size = qdict_get_int(qdict, "size");
1649 hwaddr addr = qdict_get_int(qdict, "addr");
1651 memory_dump(mon, count, format, size, addr, 1);
1654 static void *gpa2hva(MemoryRegion **p_mr, hwaddr addr, Error **errp)
1656 MemoryRegionSection mrs = memory_region_find(get_system_memory(),
1657 addr, 1);
1659 if (!mrs.mr) {
1660 error_setg(errp, "No memory is mapped at address 0x%" HWADDR_PRIx, addr);
1661 return NULL;
1664 if (!memory_region_is_ram(mrs.mr) && !memory_region_is_romd(mrs.mr)) {
1665 error_setg(errp, "Memory at address 0x%" HWADDR_PRIx "is not RAM", addr);
1666 memory_region_unref(mrs.mr);
1667 return NULL;
1670 *p_mr = mrs.mr;
1671 return qemu_map_ram_ptr(mrs.mr->ram_block, mrs.offset_within_region);
1674 static void hmp_gpa2hva(Monitor *mon, const QDict *qdict)
1676 hwaddr addr = qdict_get_int(qdict, "addr");
1677 Error *local_err = NULL;
1678 MemoryRegion *mr = NULL;
1679 void *ptr;
1681 ptr = gpa2hva(&mr, addr, &local_err);
1682 if (local_err) {
1683 error_report_err(local_err);
1684 return;
1687 monitor_printf(mon, "Host virtual address for 0x%" HWADDR_PRIx
1688 " (%s) is %p\n",
1689 addr, mr->name, ptr);
1691 memory_region_unref(mr);
1694 static void hmp_gva2gpa(Monitor *mon, const QDict *qdict)
1696 target_ulong addr = qdict_get_int(qdict, "addr");
1697 MemTxAttrs attrs;
1698 CPUState *cs = mon_get_cpu();
1699 hwaddr gpa;
1701 if (!cs) {
1702 monitor_printf(mon, "No cpu\n");
1703 return;
1706 gpa = cpu_get_phys_page_attrs_debug(cs, addr & TARGET_PAGE_MASK, &attrs);
1707 if (gpa == -1) {
1708 monitor_printf(mon, "Unmapped\n");
1709 } else {
1710 monitor_printf(mon, "gpa: %#" HWADDR_PRIx "\n",
1711 gpa + (addr & ~TARGET_PAGE_MASK));
1715 #ifdef CONFIG_LINUX
1716 static uint64_t vtop(void *ptr, Error **errp)
1718 uint64_t pinfo;
1719 uint64_t ret = -1;
1720 uintptr_t addr = (uintptr_t) ptr;
1721 uintptr_t pagesize = getpagesize();
1722 off_t offset = addr / pagesize * sizeof(pinfo);
1723 int fd;
1725 fd = open("/proc/self/pagemap", O_RDONLY);
1726 if (fd == -1) {
1727 error_setg_errno(errp, errno, "Cannot open /proc/self/pagemap");
1728 return -1;
1731 /* Force copy-on-write if necessary. */
1732 atomic_add((uint8_t *)ptr, 0);
1734 if (pread(fd, &pinfo, sizeof(pinfo), offset) != sizeof(pinfo)) {
1735 error_setg_errno(errp, errno, "Cannot read pagemap");
1736 goto out;
1738 if ((pinfo & (1ull << 63)) == 0) {
1739 error_setg(errp, "Page not present");
1740 goto out;
1742 ret = ((pinfo & 0x007fffffffffffffull) * pagesize) | (addr & (pagesize - 1));
1744 out:
1745 close(fd);
1746 return ret;
1749 static void hmp_gpa2hpa(Monitor *mon, const QDict *qdict)
1751 hwaddr addr = qdict_get_int(qdict, "addr");
1752 Error *local_err = NULL;
1753 MemoryRegion *mr = NULL;
1754 void *ptr;
1755 uint64_t physaddr;
1757 ptr = gpa2hva(&mr, addr, &local_err);
1758 if (local_err) {
1759 error_report_err(local_err);
1760 return;
1763 physaddr = vtop(ptr, &local_err);
1764 if (local_err) {
1765 error_report_err(local_err);
1766 } else {
1767 monitor_printf(mon, "Host physical address for 0x%" HWADDR_PRIx
1768 " (%s) is 0x%" PRIx64 "\n",
1769 addr, mr->name, (uint64_t) physaddr);
1772 memory_region_unref(mr);
1774 #endif
1776 static void do_print(Monitor *mon, const QDict *qdict)
1778 int format = qdict_get_int(qdict, "format");
1779 hwaddr val = qdict_get_int(qdict, "val");
1781 switch(format) {
1782 case 'o':
1783 monitor_printf(mon, "%#" HWADDR_PRIo, val);
1784 break;
1785 case 'x':
1786 monitor_printf(mon, "%#" HWADDR_PRIx, val);
1787 break;
1788 case 'u':
1789 monitor_printf(mon, "%" HWADDR_PRIu, val);
1790 break;
1791 default:
1792 case 'd':
1793 monitor_printf(mon, "%" HWADDR_PRId, val);
1794 break;
1795 case 'c':
1796 monitor_printc(mon, val);
1797 break;
1799 monitor_printf(mon, "\n");
1802 static void hmp_sum(Monitor *mon, const QDict *qdict)
1804 uint32_t addr;
1805 uint16_t sum;
1806 uint32_t start = qdict_get_int(qdict, "start");
1807 uint32_t size = qdict_get_int(qdict, "size");
1809 sum = 0;
1810 for(addr = start; addr < (start + size); addr++) {
1811 uint8_t val = address_space_ldub(&address_space_memory, addr,
1812 MEMTXATTRS_UNSPECIFIED, NULL);
1813 /* BSD sum algorithm ('sum' Unix command) */
1814 sum = (sum >> 1) | (sum << 15);
1815 sum += val;
1817 monitor_printf(mon, "%05d\n", sum);
1820 static int mouse_button_state;
1822 static void hmp_mouse_move(Monitor *mon, const QDict *qdict)
1824 int dx, dy, dz, button;
1825 const char *dx_str = qdict_get_str(qdict, "dx_str");
1826 const char *dy_str = qdict_get_str(qdict, "dy_str");
1827 const char *dz_str = qdict_get_try_str(qdict, "dz_str");
1829 dx = strtol(dx_str, NULL, 0);
1830 dy = strtol(dy_str, NULL, 0);
1831 qemu_input_queue_rel(NULL, INPUT_AXIS_X, dx);
1832 qemu_input_queue_rel(NULL, INPUT_AXIS_Y, dy);
1834 if (dz_str) {
1835 dz = strtol(dz_str, NULL, 0);
1836 if (dz != 0) {
1837 button = (dz > 0) ? INPUT_BUTTON_WHEEL_UP : INPUT_BUTTON_WHEEL_DOWN;
1838 qemu_input_queue_btn(NULL, button, true);
1839 qemu_input_event_sync();
1840 qemu_input_queue_btn(NULL, button, false);
1843 qemu_input_event_sync();
1846 static void hmp_mouse_button(Monitor *mon, const QDict *qdict)
1848 static uint32_t bmap[INPUT_BUTTON__MAX] = {
1849 [INPUT_BUTTON_LEFT] = MOUSE_EVENT_LBUTTON,
1850 [INPUT_BUTTON_MIDDLE] = MOUSE_EVENT_MBUTTON,
1851 [INPUT_BUTTON_RIGHT] = MOUSE_EVENT_RBUTTON,
1853 int button_state = qdict_get_int(qdict, "button_state");
1855 if (mouse_button_state == button_state) {
1856 return;
1858 qemu_input_update_buttons(NULL, bmap, mouse_button_state, button_state);
1859 qemu_input_event_sync();
1860 mouse_button_state = button_state;
1863 static void hmp_ioport_read(Monitor *mon, const QDict *qdict)
1865 int size = qdict_get_int(qdict, "size");
1866 int addr = qdict_get_int(qdict, "addr");
1867 int has_index = qdict_haskey(qdict, "index");
1868 uint32_t val;
1869 int suffix;
1871 if (has_index) {
1872 int index = qdict_get_int(qdict, "index");
1873 cpu_outb(addr & IOPORTS_MASK, index & 0xff);
1874 addr++;
1876 addr &= 0xffff;
1878 switch(size) {
1879 default:
1880 case 1:
1881 val = cpu_inb(addr);
1882 suffix = 'b';
1883 break;
1884 case 2:
1885 val = cpu_inw(addr);
1886 suffix = 'w';
1887 break;
1888 case 4:
1889 val = cpu_inl(addr);
1890 suffix = 'l';
1891 break;
1893 monitor_printf(mon, "port%c[0x%04x] = %#0*x\n",
1894 suffix, addr, size * 2, val);
1897 static void hmp_ioport_write(Monitor *mon, const QDict *qdict)
1899 int size = qdict_get_int(qdict, "size");
1900 int addr = qdict_get_int(qdict, "addr");
1901 int val = qdict_get_int(qdict, "val");
1903 addr &= IOPORTS_MASK;
1905 switch (size) {
1906 default:
1907 case 1:
1908 cpu_outb(addr, val);
1909 break;
1910 case 2:
1911 cpu_outw(addr, val);
1912 break;
1913 case 4:
1914 cpu_outl(addr, val);
1915 break;
1919 static void hmp_boot_set(Monitor *mon, const QDict *qdict)
1921 Error *local_err = NULL;
1922 const char *bootdevice = qdict_get_str(qdict, "bootdevice");
1924 qemu_boot_set(bootdevice, &local_err);
1925 if (local_err) {
1926 error_report_err(local_err);
1927 } else {
1928 monitor_printf(mon, "boot device list now set to %s\n", bootdevice);
1932 static void hmp_info_mtree(Monitor *mon, const QDict *qdict)
1934 bool flatview = qdict_get_try_bool(qdict, "flatview", false);
1935 bool dispatch_tree = qdict_get_try_bool(qdict, "dispatch_tree", false);
1936 bool owner = qdict_get_try_bool(qdict, "owner", false);
1938 mtree_info(flatview, dispatch_tree, owner);
1941 static void hmp_info_numa(Monitor *mon, const QDict *qdict)
1943 int i;
1944 NumaNodeMem *node_mem;
1945 CpuInfoList *cpu_list, *cpu;
1947 cpu_list = qmp_query_cpus(&error_abort);
1948 node_mem = g_new0(NumaNodeMem, nb_numa_nodes);
1950 query_numa_node_mem(node_mem);
1951 monitor_printf(mon, "%d nodes\n", nb_numa_nodes);
1952 for (i = 0; i < nb_numa_nodes; i++) {
1953 monitor_printf(mon, "node %d cpus:", i);
1954 for (cpu = cpu_list; cpu; cpu = cpu->next) {
1955 if (cpu->value->has_props && cpu->value->props->has_node_id &&
1956 cpu->value->props->node_id == i) {
1957 monitor_printf(mon, " %" PRIi64, cpu->value->CPU);
1960 monitor_printf(mon, "\n");
1961 monitor_printf(mon, "node %d size: %" PRId64 " MB\n", i,
1962 node_mem[i].node_mem >> 20);
1963 monitor_printf(mon, "node %d plugged: %" PRId64 " MB\n", i,
1964 node_mem[i].node_plugged_mem >> 20);
1966 qapi_free_CpuInfoList(cpu_list);
1967 g_free(node_mem);
1970 #ifdef CONFIG_PROFILER
1972 int64_t dev_time;
1974 static void hmp_info_profile(Monitor *mon, const QDict *qdict)
1976 static int64_t last_cpu_exec_time;
1977 int64_t cpu_exec_time;
1978 int64_t delta;
1980 cpu_exec_time = tcg_cpu_exec_time();
1981 delta = cpu_exec_time - last_cpu_exec_time;
1983 monitor_printf(mon, "async time %" PRId64 " (%0.3f)\n",
1984 dev_time, dev_time / (double)NANOSECONDS_PER_SECOND);
1985 monitor_printf(mon, "qemu time %" PRId64 " (%0.3f)\n",
1986 delta, delta / (double)NANOSECONDS_PER_SECOND);
1987 last_cpu_exec_time = cpu_exec_time;
1988 dev_time = 0;
1990 #else
1991 static void hmp_info_profile(Monitor *mon, const QDict *qdict)
1993 monitor_printf(mon, "Internal profiler not compiled\n");
1995 #endif
1997 /* Capture support */
1998 static QLIST_HEAD (capture_list_head, CaptureState) capture_head;
2000 static void hmp_info_capture(Monitor *mon, const QDict *qdict)
2002 int i;
2003 CaptureState *s;
2005 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
2006 monitor_printf(mon, "[%d]: ", i);
2007 s->ops.info (s->opaque);
2011 static void hmp_stopcapture(Monitor *mon, const QDict *qdict)
2013 int i;
2014 int n = qdict_get_int(qdict, "n");
2015 CaptureState *s;
2017 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
2018 if (i == n) {
2019 s->ops.destroy (s->opaque);
2020 QLIST_REMOVE (s, entries);
2021 g_free (s);
2022 return;
2027 static void hmp_wavcapture(Monitor *mon, const QDict *qdict)
2029 const char *path = qdict_get_str(qdict, "path");
2030 int has_freq = qdict_haskey(qdict, "freq");
2031 int freq = qdict_get_try_int(qdict, "freq", -1);
2032 int has_bits = qdict_haskey(qdict, "bits");
2033 int bits = qdict_get_try_int(qdict, "bits", -1);
2034 int has_channels = qdict_haskey(qdict, "nchannels");
2035 int nchannels = qdict_get_try_int(qdict, "nchannels", -1);
2036 CaptureState *s;
2038 s = g_malloc0 (sizeof (*s));
2040 freq = has_freq ? freq : 44100;
2041 bits = has_bits ? bits : 16;
2042 nchannels = has_channels ? nchannels : 2;
2044 if (wav_start_capture (s, path, freq, bits, nchannels)) {
2045 monitor_printf(mon, "Failed to add wave capture\n");
2046 g_free (s);
2047 return;
2049 QLIST_INSERT_HEAD (&capture_head, s, entries);
2052 static QAuthZList *find_auth(Monitor *mon, const char *name)
2054 Object *obj;
2055 Object *container;
2057 container = object_get_objects_root();
2058 obj = object_resolve_path_component(container, name);
2059 if (!obj) {
2060 monitor_printf(mon, "acl: unknown list '%s'\n", name);
2061 return NULL;
2064 return QAUTHZ_LIST(obj);
2067 static bool warn_acl;
2068 static void hmp_warn_acl(void)
2070 if (warn_acl) {
2071 return;
2073 error_report("The acl_show, acl_reset, acl_policy, acl_add, acl_remove "
2074 "commands are deprecated with no replacement. Authorization "
2075 "for VNC should be performed using the pluggable QAuthZ "
2076 "objects");
2077 warn_acl = true;
2080 static void hmp_acl_show(Monitor *mon, const QDict *qdict)
2082 const char *aclname = qdict_get_str(qdict, "aclname");
2083 QAuthZList *auth = find_auth(mon, aclname);
2084 QAuthZListRuleList *rules;
2085 size_t i = 0;
2087 hmp_warn_acl();
2089 if (!auth) {
2090 return;
2093 monitor_printf(mon, "policy: %s\n",
2094 QAuthZListPolicy_str(auth->policy));
2096 rules = auth->rules;
2097 while (rules) {
2098 QAuthZListRule *rule = rules->value;
2099 i++;
2100 monitor_printf(mon, "%zu: %s %s\n", i,
2101 QAuthZListPolicy_str(rule->policy),
2102 rule->match);
2103 rules = rules->next;
2107 static void hmp_acl_reset(Monitor *mon, const QDict *qdict)
2109 const char *aclname = qdict_get_str(qdict, "aclname");
2110 QAuthZList *auth = find_auth(mon, aclname);
2112 hmp_warn_acl();
2114 if (!auth) {
2115 return;
2118 auth->policy = QAUTHZ_LIST_POLICY_DENY;
2119 qapi_free_QAuthZListRuleList(auth->rules);
2120 auth->rules = NULL;
2121 monitor_printf(mon, "acl: removed all rules\n");
2124 static void hmp_acl_policy(Monitor *mon, const QDict *qdict)
2126 const char *aclname = qdict_get_str(qdict, "aclname");
2127 const char *policy = qdict_get_str(qdict, "policy");
2128 QAuthZList *auth = find_auth(mon, aclname);
2129 int val;
2130 Error *err = NULL;
2132 hmp_warn_acl();
2134 if (!auth) {
2135 return;
2138 val = qapi_enum_parse(&QAuthZListPolicy_lookup,
2139 policy,
2140 QAUTHZ_LIST_POLICY_DENY,
2141 &err);
2142 if (err) {
2143 error_free(err);
2144 monitor_printf(mon, "acl: unknown policy '%s', "
2145 "expected 'deny' or 'allow'\n", policy);
2146 } else {
2147 auth->policy = val;
2148 if (auth->policy == QAUTHZ_LIST_POLICY_ALLOW) {
2149 monitor_printf(mon, "acl: policy set to 'allow'\n");
2150 } else {
2151 monitor_printf(mon, "acl: policy set to 'deny'\n");
2156 static QAuthZListFormat hmp_acl_get_format(const char *match)
2158 if (strchr(match, '*')) {
2159 return QAUTHZ_LIST_FORMAT_GLOB;
2160 } else {
2161 return QAUTHZ_LIST_FORMAT_EXACT;
2165 static void hmp_acl_add(Monitor *mon, const QDict *qdict)
2167 const char *aclname = qdict_get_str(qdict, "aclname");
2168 const char *match = qdict_get_str(qdict, "match");
2169 const char *policystr = qdict_get_str(qdict, "policy");
2170 int has_index = qdict_haskey(qdict, "index");
2171 int index = qdict_get_try_int(qdict, "index", -1);
2172 QAuthZList *auth = find_auth(mon, aclname);
2173 Error *err = NULL;
2174 QAuthZListPolicy policy;
2175 QAuthZListFormat format;
2176 size_t i = 0;
2178 hmp_warn_acl();
2180 if (!auth) {
2181 return;
2184 policy = qapi_enum_parse(&QAuthZListPolicy_lookup,
2185 policystr,
2186 QAUTHZ_LIST_POLICY_DENY,
2187 &err);
2188 if (err) {
2189 error_free(err);
2190 monitor_printf(mon, "acl: unknown policy '%s', "
2191 "expected 'deny' or 'allow'\n", policystr);
2192 return;
2195 format = hmp_acl_get_format(match);
2197 if (has_index && index == 0) {
2198 monitor_printf(mon, "acl: unable to add acl entry\n");
2199 return;
2202 if (has_index) {
2203 i = qauthz_list_insert_rule(auth, match, policy,
2204 format, index - 1, &err);
2205 } else {
2206 i = qauthz_list_append_rule(auth, match, policy,
2207 format, &err);
2209 if (err) {
2210 monitor_printf(mon, "acl: unable to add rule: %s",
2211 error_get_pretty(err));
2212 error_free(err);
2213 } else {
2214 monitor_printf(mon, "acl: added rule at position %zu\n", i + 1);
2218 static void hmp_acl_remove(Monitor *mon, const QDict *qdict)
2220 const char *aclname = qdict_get_str(qdict, "aclname");
2221 const char *match = qdict_get_str(qdict, "match");
2222 QAuthZList *auth = find_auth(mon, aclname);
2223 ssize_t i = 0;
2225 hmp_warn_acl();
2227 if (!auth) {
2228 return;
2231 i = qauthz_list_delete_rule(auth, match);
2232 if (i >= 0) {
2233 monitor_printf(mon, "acl: removed rule at position %zu\n", i + 1);
2234 } else {
2235 monitor_printf(mon, "acl: no matching acl entry\n");
2239 void qmp_getfd(const char *fdname, Error **errp)
2241 mon_fd_t *monfd;
2242 int fd, tmp_fd;
2244 fd = qemu_chr_fe_get_msgfd(&cur_mon->chr);
2245 if (fd == -1) {
2246 error_setg(errp, QERR_FD_NOT_SUPPLIED);
2247 return;
2250 if (qemu_isdigit(fdname[0])) {
2251 close(fd);
2252 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "fdname",
2253 "a name not starting with a digit");
2254 return;
2257 qemu_mutex_lock(&cur_mon->mon_lock);
2258 QLIST_FOREACH(monfd, &cur_mon->fds, next) {
2259 if (strcmp(monfd->name, fdname) != 0) {
2260 continue;
2263 tmp_fd = monfd->fd;
2264 monfd->fd = fd;
2265 qemu_mutex_unlock(&cur_mon->mon_lock);
2266 /* Make sure close() is outside critical section */
2267 close(tmp_fd);
2268 return;
2271 monfd = g_malloc0(sizeof(mon_fd_t));
2272 monfd->name = g_strdup(fdname);
2273 monfd->fd = fd;
2275 QLIST_INSERT_HEAD(&cur_mon->fds, monfd, next);
2276 qemu_mutex_unlock(&cur_mon->mon_lock);
2279 void qmp_closefd(const char *fdname, Error **errp)
2281 mon_fd_t *monfd;
2282 int tmp_fd;
2284 qemu_mutex_lock(&cur_mon->mon_lock);
2285 QLIST_FOREACH(monfd, &cur_mon->fds, next) {
2286 if (strcmp(monfd->name, fdname) != 0) {
2287 continue;
2290 QLIST_REMOVE(monfd, next);
2291 tmp_fd = monfd->fd;
2292 g_free(monfd->name);
2293 g_free(monfd);
2294 qemu_mutex_unlock(&cur_mon->mon_lock);
2295 /* Make sure close() is outside critical section */
2296 close(tmp_fd);
2297 return;
2300 qemu_mutex_unlock(&cur_mon->mon_lock);
2301 error_setg(errp, QERR_FD_NOT_FOUND, fdname);
2304 int monitor_get_fd(Monitor *mon, const char *fdname, Error **errp)
2306 mon_fd_t *monfd;
2308 qemu_mutex_lock(&mon->mon_lock);
2309 QLIST_FOREACH(monfd, &mon->fds, next) {
2310 int fd;
2312 if (strcmp(monfd->name, fdname) != 0) {
2313 continue;
2316 fd = monfd->fd;
2318 /* caller takes ownership of fd */
2319 QLIST_REMOVE(monfd, next);
2320 g_free(monfd->name);
2321 g_free(monfd);
2322 qemu_mutex_unlock(&mon->mon_lock);
2324 return fd;
2327 qemu_mutex_unlock(&mon->mon_lock);
2328 error_setg(errp, "File descriptor named '%s' has not been found", fdname);
2329 return -1;
2332 static void monitor_fdset_cleanup(MonFdset *mon_fdset)
2334 MonFdsetFd *mon_fdset_fd;
2335 MonFdsetFd *mon_fdset_fd_next;
2337 QLIST_FOREACH_SAFE(mon_fdset_fd, &mon_fdset->fds, next, mon_fdset_fd_next) {
2338 if ((mon_fdset_fd->removed ||
2339 (QLIST_EMPTY(&mon_fdset->dup_fds) && mon_refcount == 0)) &&
2340 runstate_is_running()) {
2341 close(mon_fdset_fd->fd);
2342 g_free(mon_fdset_fd->opaque);
2343 QLIST_REMOVE(mon_fdset_fd, next);
2344 g_free(mon_fdset_fd);
2348 if (QLIST_EMPTY(&mon_fdset->fds) && QLIST_EMPTY(&mon_fdset->dup_fds)) {
2349 QLIST_REMOVE(mon_fdset, next);
2350 g_free(mon_fdset);
2354 static void monitor_fdsets_cleanup(void)
2356 MonFdset *mon_fdset;
2357 MonFdset *mon_fdset_next;
2359 qemu_mutex_lock(&mon_fdsets_lock);
2360 QLIST_FOREACH_SAFE(mon_fdset, &mon_fdsets, next, mon_fdset_next) {
2361 monitor_fdset_cleanup(mon_fdset);
2363 qemu_mutex_unlock(&mon_fdsets_lock);
2366 AddfdInfo *qmp_add_fd(bool has_fdset_id, int64_t fdset_id, bool has_opaque,
2367 const char *opaque, Error **errp)
2369 int fd;
2370 Monitor *mon = cur_mon;
2371 AddfdInfo *fdinfo;
2373 fd = qemu_chr_fe_get_msgfd(&mon->chr);
2374 if (fd == -1) {
2375 error_setg(errp, QERR_FD_NOT_SUPPLIED);
2376 goto error;
2379 fdinfo = monitor_fdset_add_fd(fd, has_fdset_id, fdset_id,
2380 has_opaque, opaque, errp);
2381 if (fdinfo) {
2382 return fdinfo;
2385 error:
2386 if (fd != -1) {
2387 close(fd);
2389 return NULL;
2392 void qmp_remove_fd(int64_t fdset_id, bool has_fd, int64_t fd, Error **errp)
2394 MonFdset *mon_fdset;
2395 MonFdsetFd *mon_fdset_fd;
2396 char fd_str[60];
2398 qemu_mutex_lock(&mon_fdsets_lock);
2399 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2400 if (mon_fdset->id != fdset_id) {
2401 continue;
2403 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2404 if (has_fd) {
2405 if (mon_fdset_fd->fd != fd) {
2406 continue;
2408 mon_fdset_fd->removed = true;
2409 break;
2410 } else {
2411 mon_fdset_fd->removed = true;
2414 if (has_fd && !mon_fdset_fd) {
2415 goto error;
2417 monitor_fdset_cleanup(mon_fdset);
2418 qemu_mutex_unlock(&mon_fdsets_lock);
2419 return;
2422 error:
2423 qemu_mutex_unlock(&mon_fdsets_lock);
2424 if (has_fd) {
2425 snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64 ", fd:%" PRId64,
2426 fdset_id, fd);
2427 } else {
2428 snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64, fdset_id);
2430 error_setg(errp, QERR_FD_NOT_FOUND, fd_str);
2433 FdsetInfoList *qmp_query_fdsets(Error **errp)
2435 MonFdset *mon_fdset;
2436 MonFdsetFd *mon_fdset_fd;
2437 FdsetInfoList *fdset_list = NULL;
2439 qemu_mutex_lock(&mon_fdsets_lock);
2440 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2441 FdsetInfoList *fdset_info = g_malloc0(sizeof(*fdset_info));
2442 FdsetFdInfoList *fdsetfd_list = NULL;
2444 fdset_info->value = g_malloc0(sizeof(*fdset_info->value));
2445 fdset_info->value->fdset_id = mon_fdset->id;
2447 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2448 FdsetFdInfoList *fdsetfd_info;
2450 fdsetfd_info = g_malloc0(sizeof(*fdsetfd_info));
2451 fdsetfd_info->value = g_malloc0(sizeof(*fdsetfd_info->value));
2452 fdsetfd_info->value->fd = mon_fdset_fd->fd;
2453 if (mon_fdset_fd->opaque) {
2454 fdsetfd_info->value->has_opaque = true;
2455 fdsetfd_info->value->opaque = g_strdup(mon_fdset_fd->opaque);
2456 } else {
2457 fdsetfd_info->value->has_opaque = false;
2460 fdsetfd_info->next = fdsetfd_list;
2461 fdsetfd_list = fdsetfd_info;
2464 fdset_info->value->fds = fdsetfd_list;
2466 fdset_info->next = fdset_list;
2467 fdset_list = fdset_info;
2469 qemu_mutex_unlock(&mon_fdsets_lock);
2471 return fdset_list;
2474 AddfdInfo *monitor_fdset_add_fd(int fd, bool has_fdset_id, int64_t fdset_id,
2475 bool has_opaque, const char *opaque,
2476 Error **errp)
2478 MonFdset *mon_fdset = NULL;
2479 MonFdsetFd *mon_fdset_fd;
2480 AddfdInfo *fdinfo;
2482 qemu_mutex_lock(&mon_fdsets_lock);
2483 if (has_fdset_id) {
2484 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2485 /* Break if match found or match impossible due to ordering by ID */
2486 if (fdset_id <= mon_fdset->id) {
2487 if (fdset_id < mon_fdset->id) {
2488 mon_fdset = NULL;
2490 break;
2495 if (mon_fdset == NULL) {
2496 int64_t fdset_id_prev = -1;
2497 MonFdset *mon_fdset_cur = QLIST_FIRST(&mon_fdsets);
2499 if (has_fdset_id) {
2500 if (fdset_id < 0) {
2501 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "fdset-id",
2502 "a non-negative value");
2503 qemu_mutex_unlock(&mon_fdsets_lock);
2504 return NULL;
2506 /* Use specified fdset ID */
2507 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2508 mon_fdset_cur = mon_fdset;
2509 if (fdset_id < mon_fdset_cur->id) {
2510 break;
2513 } else {
2514 /* Use first available fdset ID */
2515 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2516 mon_fdset_cur = mon_fdset;
2517 if (fdset_id_prev == mon_fdset_cur->id - 1) {
2518 fdset_id_prev = mon_fdset_cur->id;
2519 continue;
2521 break;
2525 mon_fdset = g_malloc0(sizeof(*mon_fdset));
2526 if (has_fdset_id) {
2527 mon_fdset->id = fdset_id;
2528 } else {
2529 mon_fdset->id = fdset_id_prev + 1;
2532 /* The fdset list is ordered by fdset ID */
2533 if (!mon_fdset_cur) {
2534 QLIST_INSERT_HEAD(&mon_fdsets, mon_fdset, next);
2535 } else if (mon_fdset->id < mon_fdset_cur->id) {
2536 QLIST_INSERT_BEFORE(mon_fdset_cur, mon_fdset, next);
2537 } else {
2538 QLIST_INSERT_AFTER(mon_fdset_cur, mon_fdset, next);
2542 mon_fdset_fd = g_malloc0(sizeof(*mon_fdset_fd));
2543 mon_fdset_fd->fd = fd;
2544 mon_fdset_fd->removed = false;
2545 if (has_opaque) {
2546 mon_fdset_fd->opaque = g_strdup(opaque);
2548 QLIST_INSERT_HEAD(&mon_fdset->fds, mon_fdset_fd, next);
2550 fdinfo = g_malloc0(sizeof(*fdinfo));
2551 fdinfo->fdset_id = mon_fdset->id;
2552 fdinfo->fd = mon_fdset_fd->fd;
2554 qemu_mutex_unlock(&mon_fdsets_lock);
2555 return fdinfo;
2558 int monitor_fdset_get_fd(int64_t fdset_id, int flags)
2560 #ifdef _WIN32
2561 return -ENOENT;
2562 #else
2563 MonFdset *mon_fdset;
2564 MonFdsetFd *mon_fdset_fd;
2565 int mon_fd_flags;
2566 int ret;
2568 qemu_mutex_lock(&mon_fdsets_lock);
2569 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2570 if (mon_fdset->id != fdset_id) {
2571 continue;
2573 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2574 mon_fd_flags = fcntl(mon_fdset_fd->fd, F_GETFL);
2575 if (mon_fd_flags == -1) {
2576 ret = -errno;
2577 goto out;
2580 if ((flags & O_ACCMODE) == (mon_fd_flags & O_ACCMODE)) {
2581 ret = mon_fdset_fd->fd;
2582 goto out;
2585 ret = -EACCES;
2586 goto out;
2588 ret = -ENOENT;
2590 out:
2591 qemu_mutex_unlock(&mon_fdsets_lock);
2592 return ret;
2593 #endif
2596 int monitor_fdset_dup_fd_add(int64_t fdset_id, int dup_fd)
2598 MonFdset *mon_fdset;
2599 MonFdsetFd *mon_fdset_fd_dup;
2601 qemu_mutex_lock(&mon_fdsets_lock);
2602 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2603 if (mon_fdset->id != fdset_id) {
2604 continue;
2606 QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
2607 if (mon_fdset_fd_dup->fd == dup_fd) {
2608 goto err;
2611 mon_fdset_fd_dup = g_malloc0(sizeof(*mon_fdset_fd_dup));
2612 mon_fdset_fd_dup->fd = dup_fd;
2613 QLIST_INSERT_HEAD(&mon_fdset->dup_fds, mon_fdset_fd_dup, next);
2614 qemu_mutex_unlock(&mon_fdsets_lock);
2615 return 0;
2618 err:
2619 qemu_mutex_unlock(&mon_fdsets_lock);
2620 return -1;
2623 static int64_t monitor_fdset_dup_fd_find_remove(int dup_fd, bool remove)
2625 MonFdset *mon_fdset;
2626 MonFdsetFd *mon_fdset_fd_dup;
2628 qemu_mutex_lock(&mon_fdsets_lock);
2629 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2630 QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
2631 if (mon_fdset_fd_dup->fd == dup_fd) {
2632 if (remove) {
2633 QLIST_REMOVE(mon_fdset_fd_dup, next);
2634 if (QLIST_EMPTY(&mon_fdset->dup_fds)) {
2635 monitor_fdset_cleanup(mon_fdset);
2637 goto err;
2638 } else {
2639 qemu_mutex_unlock(&mon_fdsets_lock);
2640 return mon_fdset->id;
2646 err:
2647 qemu_mutex_unlock(&mon_fdsets_lock);
2648 return -1;
2651 int64_t monitor_fdset_dup_fd_find(int dup_fd)
2653 return monitor_fdset_dup_fd_find_remove(dup_fd, false);
2656 void monitor_fdset_dup_fd_remove(int dup_fd)
2658 monitor_fdset_dup_fd_find_remove(dup_fd, true);
2661 int monitor_fd_param(Monitor *mon, const char *fdname, Error **errp)
2663 int fd;
2664 Error *local_err = NULL;
2666 if (!qemu_isdigit(fdname[0]) && mon) {
2667 fd = monitor_get_fd(mon, fdname, &local_err);
2668 } else {
2669 fd = qemu_parse_fd(fdname);
2670 if (fd == -1) {
2671 error_setg(&local_err, "Invalid file descriptor number '%s'",
2672 fdname);
2675 if (local_err) {
2676 error_propagate(errp, local_err);
2677 assert(fd == -1);
2678 } else {
2679 assert(fd != -1);
2682 return fd;
2685 /* Please update hmp-commands.hx when adding or changing commands */
2686 static mon_cmd_t info_cmds[] = {
2687 #include "hmp-commands-info.h"
2688 { NULL, NULL, },
2691 /* mon_cmds and info_cmds would be sorted at runtime */
2692 static mon_cmd_t mon_cmds[] = {
2693 #include "hmp-commands.h"
2694 { NULL, NULL, },
2697 /*******************************************************************/
2699 static const char *pch;
2700 static sigjmp_buf expr_env;
2703 static void GCC_FMT_ATTR(2, 3) QEMU_NORETURN
2704 expr_error(Monitor *mon, const char *fmt, ...)
2706 va_list ap;
2707 va_start(ap, fmt);
2708 monitor_vprintf(mon, fmt, ap);
2709 monitor_printf(mon, "\n");
2710 va_end(ap);
2711 siglongjmp(expr_env, 1);
2714 /* return 0 if OK, -1 if not found */
2715 static int get_monitor_def(target_long *pval, const char *name)
2717 const MonitorDef *md = target_monitor_defs();
2718 CPUState *cs = mon_get_cpu();
2719 void *ptr;
2720 uint64_t tmp = 0;
2721 int ret;
2723 if (cs == NULL || md == NULL) {
2724 return -1;
2727 for(; md->name != NULL; md++) {
2728 if (compare_cmd(name, md->name)) {
2729 if (md->get_value) {
2730 *pval = md->get_value(md, md->offset);
2731 } else {
2732 CPUArchState *env = mon_get_cpu_env();
2733 ptr = (uint8_t *)env + md->offset;
2734 switch(md->type) {
2735 case MD_I32:
2736 *pval = *(int32_t *)ptr;
2737 break;
2738 case MD_TLONG:
2739 *pval = *(target_long *)ptr;
2740 break;
2741 default:
2742 *pval = 0;
2743 break;
2746 return 0;
2750 ret = target_get_monitor_def(cs, name, &tmp);
2751 if (!ret) {
2752 *pval = (target_long) tmp;
2755 return ret;
2758 static void next(void)
2760 if (*pch != '\0') {
2761 pch++;
2762 while (qemu_isspace(*pch))
2763 pch++;
2767 static int64_t expr_sum(Monitor *mon);
2769 static int64_t expr_unary(Monitor *mon)
2771 int64_t n;
2772 char *p;
2773 int ret;
2775 switch(*pch) {
2776 case '+':
2777 next();
2778 n = expr_unary(mon);
2779 break;
2780 case '-':
2781 next();
2782 n = -expr_unary(mon);
2783 break;
2784 case '~':
2785 next();
2786 n = ~expr_unary(mon);
2787 break;
2788 case '(':
2789 next();
2790 n = expr_sum(mon);
2791 if (*pch != ')') {
2792 expr_error(mon, "')' expected");
2794 next();
2795 break;
2796 case '\'':
2797 pch++;
2798 if (*pch == '\0')
2799 expr_error(mon, "character constant expected");
2800 n = *pch;
2801 pch++;
2802 if (*pch != '\'')
2803 expr_error(mon, "missing terminating \' character");
2804 next();
2805 break;
2806 case '$':
2808 char buf[128], *q;
2809 target_long reg=0;
2811 pch++;
2812 q = buf;
2813 while ((*pch >= 'a' && *pch <= 'z') ||
2814 (*pch >= 'A' && *pch <= 'Z') ||
2815 (*pch >= '0' && *pch <= '9') ||
2816 *pch == '_' || *pch == '.') {
2817 if ((q - buf) < sizeof(buf) - 1)
2818 *q++ = *pch;
2819 pch++;
2821 while (qemu_isspace(*pch))
2822 pch++;
2823 *q = 0;
2824 ret = get_monitor_def(&reg, buf);
2825 if (ret < 0)
2826 expr_error(mon, "unknown register");
2827 n = reg;
2829 break;
2830 case '\0':
2831 expr_error(mon, "unexpected end of expression");
2832 n = 0;
2833 break;
2834 default:
2835 errno = 0;
2836 n = strtoull(pch, &p, 0);
2837 if (errno == ERANGE) {
2838 expr_error(mon, "number too large");
2840 if (pch == p) {
2841 expr_error(mon, "invalid char '%c' in expression", *p);
2843 pch = p;
2844 while (qemu_isspace(*pch))
2845 pch++;
2846 break;
2848 return n;
2852 static int64_t expr_prod(Monitor *mon)
2854 int64_t val, val2;
2855 int op;
2857 val = expr_unary(mon);
2858 for(;;) {
2859 op = *pch;
2860 if (op != '*' && op != '/' && op != '%')
2861 break;
2862 next();
2863 val2 = expr_unary(mon);
2864 switch(op) {
2865 default:
2866 case '*':
2867 val *= val2;
2868 break;
2869 case '/':
2870 case '%':
2871 if (val2 == 0)
2872 expr_error(mon, "division by zero");
2873 if (op == '/')
2874 val /= val2;
2875 else
2876 val %= val2;
2877 break;
2880 return val;
2883 static int64_t expr_logic(Monitor *mon)
2885 int64_t val, val2;
2886 int op;
2888 val = expr_prod(mon);
2889 for(;;) {
2890 op = *pch;
2891 if (op != '&' && op != '|' && op != '^')
2892 break;
2893 next();
2894 val2 = expr_prod(mon);
2895 switch(op) {
2896 default:
2897 case '&':
2898 val &= val2;
2899 break;
2900 case '|':
2901 val |= val2;
2902 break;
2903 case '^':
2904 val ^= val2;
2905 break;
2908 return val;
2911 static int64_t expr_sum(Monitor *mon)
2913 int64_t val, val2;
2914 int op;
2916 val = expr_logic(mon);
2917 for(;;) {
2918 op = *pch;
2919 if (op != '+' && op != '-')
2920 break;
2921 next();
2922 val2 = expr_logic(mon);
2923 if (op == '+')
2924 val += val2;
2925 else
2926 val -= val2;
2928 return val;
2931 static int get_expr(Monitor *mon, int64_t *pval, const char **pp)
2933 pch = *pp;
2934 if (sigsetjmp(expr_env, 0)) {
2935 *pp = pch;
2936 return -1;
2938 while (qemu_isspace(*pch))
2939 pch++;
2940 *pval = expr_sum(mon);
2941 *pp = pch;
2942 return 0;
2945 static int get_double(Monitor *mon, double *pval, const char **pp)
2947 const char *p = *pp;
2948 char *tailp;
2949 double d;
2951 d = strtod(p, &tailp);
2952 if (tailp == p) {
2953 monitor_printf(mon, "Number expected\n");
2954 return -1;
2956 if (d != d || d - d != 0) {
2957 /* NaN or infinity */
2958 monitor_printf(mon, "Bad number\n");
2959 return -1;
2961 *pval = d;
2962 *pp = tailp;
2963 return 0;
2967 * Store the command-name in cmdname, and return a pointer to
2968 * the remaining of the command string.
2970 static const char *get_command_name(const char *cmdline,
2971 char *cmdname, size_t nlen)
2973 size_t len;
2974 const char *p, *pstart;
2976 p = cmdline;
2977 while (qemu_isspace(*p))
2978 p++;
2979 if (*p == '\0')
2980 return NULL;
2981 pstart = p;
2982 while (*p != '\0' && *p != '/' && !qemu_isspace(*p))
2983 p++;
2984 len = p - pstart;
2985 if (len > nlen - 1)
2986 len = nlen - 1;
2987 memcpy(cmdname, pstart, len);
2988 cmdname[len] = '\0';
2989 return p;
2993 * Read key of 'type' into 'key' and return the current
2994 * 'type' pointer.
2996 static char *key_get_info(const char *type, char **key)
2998 size_t len;
2999 char *p, *str;
3001 if (*type == ',')
3002 type++;
3004 p = strchr(type, ':');
3005 if (!p) {
3006 *key = NULL;
3007 return NULL;
3009 len = p - type;
3011 str = g_malloc(len + 1);
3012 memcpy(str, type, len);
3013 str[len] = '\0';
3015 *key = str;
3016 return ++p;
3019 static int default_fmt_format = 'x';
3020 static int default_fmt_size = 4;
3022 static int is_valid_option(const char *c, const char *typestr)
3024 char option[3];
3026 option[0] = '-';
3027 option[1] = *c;
3028 option[2] = '\0';
3030 typestr = strstr(typestr, option);
3031 return (typestr != NULL);
3034 static const mon_cmd_t *search_dispatch_table(const mon_cmd_t *disp_table,
3035 const char *cmdname)
3037 const mon_cmd_t *cmd;
3039 for (cmd = disp_table; cmd->name != NULL; cmd++) {
3040 if (compare_cmd(cmdname, cmd->name)) {
3041 return cmd;
3045 return NULL;
3049 * Parse command name from @cmdp according to command table @table.
3050 * If blank, return NULL.
3051 * Else, if no valid command can be found, report to @mon, and return
3052 * NULL.
3053 * Else, change @cmdp to point right behind the name, and return its
3054 * command table entry.
3055 * Do not assume the return value points into @table! It doesn't when
3056 * the command is found in a sub-command table.
3058 static const mon_cmd_t *monitor_parse_command(Monitor *mon,
3059 const char *cmdp_start,
3060 const char **cmdp,
3061 mon_cmd_t *table)
3063 const char *p;
3064 const mon_cmd_t *cmd;
3065 char cmdname[256];
3067 /* extract the command name */
3068 p = get_command_name(*cmdp, cmdname, sizeof(cmdname));
3069 if (!p)
3070 return NULL;
3072 cmd = search_dispatch_table(table, cmdname);
3073 if (!cmd) {
3074 monitor_printf(mon, "unknown command: '%.*s'\n",
3075 (int)(p - cmdp_start), cmdp_start);
3076 return NULL;
3078 if (runstate_check(RUN_STATE_PRECONFIG) && !cmd_can_preconfig(cmd)) {
3079 monitor_printf(mon, "Command '%.*s' not available with -preconfig "
3080 "until after exit_preconfig.\n",
3081 (int)(p - cmdp_start), cmdp_start);
3082 return NULL;
3085 /* filter out following useless space */
3086 while (qemu_isspace(*p)) {
3087 p++;
3090 *cmdp = p;
3091 /* search sub command */
3092 if (cmd->sub_table != NULL && *p != '\0') {
3093 return monitor_parse_command(mon, cmdp_start, cmdp, cmd->sub_table);
3096 return cmd;
3100 * Parse arguments for @cmd.
3101 * If it can't be parsed, report to @mon, and return NULL.
3102 * Else, insert command arguments into a QDict, and return it.
3103 * Note: On success, caller has to free the QDict structure.
3106 static QDict *monitor_parse_arguments(Monitor *mon,
3107 const char **endp,
3108 const mon_cmd_t *cmd)
3110 const char *typestr;
3111 char *key;
3112 int c;
3113 const char *p = *endp;
3114 char buf[1024];
3115 QDict *qdict = qdict_new();
3117 /* parse the parameters */
3118 typestr = cmd->args_type;
3119 for(;;) {
3120 typestr = key_get_info(typestr, &key);
3121 if (!typestr)
3122 break;
3123 c = *typestr;
3124 typestr++;
3125 switch(c) {
3126 case 'F':
3127 case 'B':
3128 case 's':
3130 int ret;
3132 while (qemu_isspace(*p))
3133 p++;
3134 if (*typestr == '?') {
3135 typestr++;
3136 if (*p == '\0') {
3137 /* no optional string: NULL argument */
3138 break;
3141 ret = get_str(buf, sizeof(buf), &p);
3142 if (ret < 0) {
3143 switch(c) {
3144 case 'F':
3145 monitor_printf(mon, "%s: filename expected\n",
3146 cmd->name);
3147 break;
3148 case 'B':
3149 monitor_printf(mon, "%s: block device name expected\n",
3150 cmd->name);
3151 break;
3152 default:
3153 monitor_printf(mon, "%s: string expected\n", cmd->name);
3154 break;
3156 goto fail;
3158 qdict_put_str(qdict, key, buf);
3160 break;
3161 case 'O':
3163 QemuOptsList *opts_list;
3164 QemuOpts *opts;
3166 opts_list = qemu_find_opts(key);
3167 if (!opts_list || opts_list->desc->name) {
3168 goto bad_type;
3170 while (qemu_isspace(*p)) {
3171 p++;
3173 if (!*p)
3174 break;
3175 if (get_str(buf, sizeof(buf), &p) < 0) {
3176 goto fail;
3178 opts = qemu_opts_parse_noisily(opts_list, buf, true);
3179 if (!opts) {
3180 goto fail;
3182 qemu_opts_to_qdict(opts, qdict);
3183 qemu_opts_del(opts);
3185 break;
3186 case '/':
3188 int count, format, size;
3190 while (qemu_isspace(*p))
3191 p++;
3192 if (*p == '/') {
3193 /* format found */
3194 p++;
3195 count = 1;
3196 if (qemu_isdigit(*p)) {
3197 count = 0;
3198 while (qemu_isdigit(*p)) {
3199 count = count * 10 + (*p - '0');
3200 p++;
3203 size = -1;
3204 format = -1;
3205 for(;;) {
3206 switch(*p) {
3207 case 'o':
3208 case 'd':
3209 case 'u':
3210 case 'x':
3211 case 'i':
3212 case 'c':
3213 format = *p++;
3214 break;
3215 case 'b':
3216 size = 1;
3217 p++;
3218 break;
3219 case 'h':
3220 size = 2;
3221 p++;
3222 break;
3223 case 'w':
3224 size = 4;
3225 p++;
3226 break;
3227 case 'g':
3228 case 'L':
3229 size = 8;
3230 p++;
3231 break;
3232 default:
3233 goto next;
3236 next:
3237 if (*p != '\0' && !qemu_isspace(*p)) {
3238 monitor_printf(mon, "invalid char in format: '%c'\n",
3239 *p);
3240 goto fail;
3242 if (format < 0)
3243 format = default_fmt_format;
3244 if (format != 'i') {
3245 /* for 'i', not specifying a size gives -1 as size */
3246 if (size < 0)
3247 size = default_fmt_size;
3248 default_fmt_size = size;
3250 default_fmt_format = format;
3251 } else {
3252 count = 1;
3253 format = default_fmt_format;
3254 if (format != 'i') {
3255 size = default_fmt_size;
3256 } else {
3257 size = -1;
3260 qdict_put_int(qdict, "count", count);
3261 qdict_put_int(qdict, "format", format);
3262 qdict_put_int(qdict, "size", size);
3264 break;
3265 case 'i':
3266 case 'l':
3267 case 'M':
3269 int64_t val;
3271 while (qemu_isspace(*p))
3272 p++;
3273 if (*typestr == '?' || *typestr == '.') {
3274 if (*typestr == '?') {
3275 if (*p == '\0') {
3276 typestr++;
3277 break;
3279 } else {
3280 if (*p == '.') {
3281 p++;
3282 while (qemu_isspace(*p))
3283 p++;
3284 } else {
3285 typestr++;
3286 break;
3289 typestr++;
3291 if (get_expr(mon, &val, &p))
3292 goto fail;
3293 /* Check if 'i' is greater than 32-bit */
3294 if ((c == 'i') && ((val >> 32) & 0xffffffff)) {
3295 monitor_printf(mon, "\'%s\' has failed: ", cmd->name);
3296 monitor_printf(mon, "integer is for 32-bit values\n");
3297 goto fail;
3298 } else if (c == 'M') {
3299 if (val < 0) {
3300 monitor_printf(mon, "enter a positive value\n");
3301 goto fail;
3303 val *= MiB;
3305 qdict_put_int(qdict, key, val);
3307 break;
3308 case 'o':
3310 int ret;
3311 uint64_t val;
3312 const char *end;
3314 while (qemu_isspace(*p)) {
3315 p++;
3317 if (*typestr == '?') {
3318 typestr++;
3319 if (*p == '\0') {
3320 break;
3323 ret = qemu_strtosz_MiB(p, &end, &val);
3324 if (ret < 0 || val > INT64_MAX) {
3325 monitor_printf(mon, "invalid size\n");
3326 goto fail;
3328 qdict_put_int(qdict, key, val);
3329 p = end;
3331 break;
3332 case 'T':
3334 double val;
3336 while (qemu_isspace(*p))
3337 p++;
3338 if (*typestr == '?') {
3339 typestr++;
3340 if (*p == '\0') {
3341 break;
3344 if (get_double(mon, &val, &p) < 0) {
3345 goto fail;
3347 if (p[0] && p[1] == 's') {
3348 switch (*p) {
3349 case 'm':
3350 val /= 1e3; p += 2; break;
3351 case 'u':
3352 val /= 1e6; p += 2; break;
3353 case 'n':
3354 val /= 1e9; p += 2; break;
3357 if (*p && !qemu_isspace(*p)) {
3358 monitor_printf(mon, "Unknown unit suffix\n");
3359 goto fail;
3361 qdict_put(qdict, key, qnum_from_double(val));
3363 break;
3364 case 'b':
3366 const char *beg;
3367 bool val;
3369 while (qemu_isspace(*p)) {
3370 p++;
3372 beg = p;
3373 while (qemu_isgraph(*p)) {
3374 p++;
3376 if (p - beg == 2 && !memcmp(beg, "on", p - beg)) {
3377 val = true;
3378 } else if (p - beg == 3 && !memcmp(beg, "off", p - beg)) {
3379 val = false;
3380 } else {
3381 monitor_printf(mon, "Expected 'on' or 'off'\n");
3382 goto fail;
3384 qdict_put_bool(qdict, key, val);
3386 break;
3387 case '-':
3389 const char *tmp = p;
3390 int skip_key = 0;
3391 /* option */
3393 c = *typestr++;
3394 if (c == '\0')
3395 goto bad_type;
3396 while (qemu_isspace(*p))
3397 p++;
3398 if (*p == '-') {
3399 p++;
3400 if(c != *p) {
3401 if(!is_valid_option(p, typestr)) {
3403 monitor_printf(mon, "%s: unsupported option -%c\n",
3404 cmd->name, *p);
3405 goto fail;
3406 } else {
3407 skip_key = 1;
3410 if(skip_key) {
3411 p = tmp;
3412 } else {
3413 /* has option */
3414 p++;
3415 qdict_put_bool(qdict, key, true);
3419 break;
3420 case 'S':
3422 /* package all remaining string */
3423 int len;
3425 while (qemu_isspace(*p)) {
3426 p++;
3428 if (*typestr == '?') {
3429 typestr++;
3430 if (*p == '\0') {
3431 /* no remaining string: NULL argument */
3432 break;
3435 len = strlen(p);
3436 if (len <= 0) {
3437 monitor_printf(mon, "%s: string expected\n",
3438 cmd->name);
3439 goto fail;
3441 qdict_put_str(qdict, key, p);
3442 p += len;
3444 break;
3445 default:
3446 bad_type:
3447 monitor_printf(mon, "%s: unknown type '%c'\n", cmd->name, c);
3448 goto fail;
3450 g_free(key);
3451 key = NULL;
3453 /* check that all arguments were parsed */
3454 while (qemu_isspace(*p))
3455 p++;
3456 if (*p != '\0') {
3457 monitor_printf(mon, "%s: extraneous characters at the end of line\n",
3458 cmd->name);
3459 goto fail;
3462 return qdict;
3464 fail:
3465 qobject_unref(qdict);
3466 g_free(key);
3467 return NULL;
3470 static void handle_hmp_command(Monitor *mon, const char *cmdline)
3472 QDict *qdict;
3473 const mon_cmd_t *cmd;
3474 const char *cmd_start = cmdline;
3476 trace_handle_hmp_command(mon, cmdline);
3478 cmd = monitor_parse_command(mon, cmdline, &cmdline, mon->cmd_table);
3479 if (!cmd) {
3480 return;
3483 qdict = monitor_parse_arguments(mon, &cmdline, cmd);
3484 if (!qdict) {
3485 while (cmdline > cmd_start && qemu_isspace(cmdline[-1])) {
3486 cmdline--;
3488 monitor_printf(mon, "Try \"help %.*s\" for more information\n",
3489 (int)(cmdline - cmd_start), cmd_start);
3490 return;
3493 cmd->cmd(mon, qdict);
3494 qobject_unref(qdict);
3497 static void cmd_completion(Monitor *mon, const char *name, const char *list)
3499 const char *p, *pstart;
3500 char cmd[128];
3501 int len;
3503 p = list;
3504 for(;;) {
3505 pstart = p;
3506 p = qemu_strchrnul(p, '|');
3507 len = p - pstart;
3508 if (len > sizeof(cmd) - 2)
3509 len = sizeof(cmd) - 2;
3510 memcpy(cmd, pstart, len);
3511 cmd[len] = '\0';
3512 if (name[0] == '\0' || !strncmp(name, cmd, strlen(name))) {
3513 readline_add_completion(mon->rs, cmd);
3515 if (*p == '\0')
3516 break;
3517 p++;
3521 static void file_completion(Monitor *mon, const char *input)
3523 DIR *ffs;
3524 struct dirent *d;
3525 char path[1024];
3526 char file[1024], file_prefix[1024];
3527 int input_path_len;
3528 const char *p;
3530 p = strrchr(input, '/');
3531 if (!p) {
3532 input_path_len = 0;
3533 pstrcpy(file_prefix, sizeof(file_prefix), input);
3534 pstrcpy(path, sizeof(path), ".");
3535 } else {
3536 input_path_len = p - input + 1;
3537 memcpy(path, input, input_path_len);
3538 if (input_path_len > sizeof(path) - 1)
3539 input_path_len = sizeof(path) - 1;
3540 path[input_path_len] = '\0';
3541 pstrcpy(file_prefix, sizeof(file_prefix), p + 1);
3544 ffs = opendir(path);
3545 if (!ffs)
3546 return;
3547 for(;;) {
3548 struct stat sb;
3549 d = readdir(ffs);
3550 if (!d)
3551 break;
3553 if (strcmp(d->d_name, ".") == 0 || strcmp(d->d_name, "..") == 0) {
3554 continue;
3557 if (strstart(d->d_name, file_prefix, NULL)) {
3558 memcpy(file, input, input_path_len);
3559 if (input_path_len < sizeof(file))
3560 pstrcpy(file + input_path_len, sizeof(file) - input_path_len,
3561 d->d_name);
3562 /* stat the file to find out if it's a directory.
3563 * In that case add a slash to speed up typing long paths
3565 if (stat(file, &sb) == 0 && S_ISDIR(sb.st_mode)) {
3566 pstrcat(file, sizeof(file), "/");
3568 readline_add_completion(mon->rs, file);
3571 closedir(ffs);
3574 static const char *next_arg_type(const char *typestr)
3576 const char *p = strchr(typestr, ':');
3577 return (p != NULL ? ++p : typestr);
3580 static void add_completion_option(ReadLineState *rs, const char *str,
3581 const char *option)
3583 if (!str || !option) {
3584 return;
3586 if (!strncmp(option, str, strlen(str))) {
3587 readline_add_completion(rs, option);
3591 void chardev_add_completion(ReadLineState *rs, int nb_args, const char *str)
3593 size_t len;
3594 ChardevBackendInfoList *list, *start;
3596 if (nb_args != 2) {
3597 return;
3599 len = strlen(str);
3600 readline_set_completion_index(rs, len);
3602 start = list = qmp_query_chardev_backends(NULL);
3603 while (list) {
3604 const char *chr_name = list->value->name;
3606 if (!strncmp(chr_name, str, len)) {
3607 readline_add_completion(rs, chr_name);
3609 list = list->next;
3611 qapi_free_ChardevBackendInfoList(start);
3614 void netdev_add_completion(ReadLineState *rs, int nb_args, const char *str)
3616 size_t len;
3617 int i;
3619 if (nb_args != 2) {
3620 return;
3622 len = strlen(str);
3623 readline_set_completion_index(rs, len);
3624 for (i = 0; i < NET_CLIENT_DRIVER__MAX; i++) {
3625 add_completion_option(rs, str, NetClientDriver_str(i));
3629 void device_add_completion(ReadLineState *rs, int nb_args, const char *str)
3631 GSList *list, *elt;
3632 size_t len;
3634 if (nb_args != 2) {
3635 return;
3638 len = strlen(str);
3639 readline_set_completion_index(rs, len);
3640 list = elt = object_class_get_list(TYPE_DEVICE, false);
3641 while (elt) {
3642 const char *name;
3643 DeviceClass *dc = OBJECT_CLASS_CHECK(DeviceClass, elt->data,
3644 TYPE_DEVICE);
3645 name = object_class_get_name(OBJECT_CLASS(dc));
3647 if (dc->user_creatable
3648 && !strncmp(name, str, len)) {
3649 readline_add_completion(rs, name);
3651 elt = elt->next;
3653 g_slist_free(list);
3656 void object_add_completion(ReadLineState *rs, int nb_args, const char *str)
3658 GSList *list, *elt;
3659 size_t len;
3661 if (nb_args != 2) {
3662 return;
3665 len = strlen(str);
3666 readline_set_completion_index(rs, len);
3667 list = elt = object_class_get_list(TYPE_USER_CREATABLE, false);
3668 while (elt) {
3669 const char *name;
3671 name = object_class_get_name(OBJECT_CLASS(elt->data));
3672 if (!strncmp(name, str, len) && strcmp(name, TYPE_USER_CREATABLE)) {
3673 readline_add_completion(rs, name);
3675 elt = elt->next;
3677 g_slist_free(list);
3680 static void peripheral_device_del_completion(ReadLineState *rs,
3681 const char *str, size_t len)
3683 Object *peripheral = container_get(qdev_get_machine(), "/peripheral");
3684 GSList *list, *item;
3686 list = qdev_build_hotpluggable_device_list(peripheral);
3687 if (!list) {
3688 return;
3691 for (item = list; item; item = g_slist_next(item)) {
3692 DeviceState *dev = item->data;
3694 if (dev->id && !strncmp(str, dev->id, len)) {
3695 readline_add_completion(rs, dev->id);
3699 g_slist_free(list);
3702 void chardev_remove_completion(ReadLineState *rs, int nb_args, const char *str)
3704 size_t len;
3705 ChardevInfoList *list, *start;
3707 if (nb_args != 2) {
3708 return;
3710 len = strlen(str);
3711 readline_set_completion_index(rs, len);
3713 start = list = qmp_query_chardev(NULL);
3714 while (list) {
3715 ChardevInfo *chr = list->value;
3717 if (!strncmp(chr->label, str, len)) {
3718 readline_add_completion(rs, chr->label);
3720 list = list->next;
3722 qapi_free_ChardevInfoList(start);
3725 static void ringbuf_completion(ReadLineState *rs, const char *str)
3727 size_t len;
3728 ChardevInfoList *list, *start;
3730 len = strlen(str);
3731 readline_set_completion_index(rs, len);
3733 start = list = qmp_query_chardev(NULL);
3734 while (list) {
3735 ChardevInfo *chr_info = list->value;
3737 if (!strncmp(chr_info->label, str, len)) {
3738 Chardev *chr = qemu_chr_find(chr_info->label);
3739 if (chr && CHARDEV_IS_RINGBUF(chr)) {
3740 readline_add_completion(rs, chr_info->label);
3743 list = list->next;
3745 qapi_free_ChardevInfoList(start);
3748 void ringbuf_write_completion(ReadLineState *rs, int nb_args, const char *str)
3750 if (nb_args != 2) {
3751 return;
3753 ringbuf_completion(rs, str);
3756 void device_del_completion(ReadLineState *rs, int nb_args, const char *str)
3758 size_t len;
3760 if (nb_args != 2) {
3761 return;
3764 len = strlen(str);
3765 readline_set_completion_index(rs, len);
3766 peripheral_device_del_completion(rs, str, len);
3769 void object_del_completion(ReadLineState *rs, int nb_args, const char *str)
3771 ObjectPropertyInfoList *list, *start;
3772 size_t len;
3774 if (nb_args != 2) {
3775 return;
3777 len = strlen(str);
3778 readline_set_completion_index(rs, len);
3780 start = list = qmp_qom_list("/objects", NULL);
3781 while (list) {
3782 ObjectPropertyInfo *info = list->value;
3784 if (!strncmp(info->type, "child<", 5)
3785 && !strncmp(info->name, str, len)) {
3786 readline_add_completion(rs, info->name);
3788 list = list->next;
3790 qapi_free_ObjectPropertyInfoList(start);
3793 void sendkey_completion(ReadLineState *rs, int nb_args, const char *str)
3795 int i;
3796 char *sep;
3797 size_t len;
3799 if (nb_args != 2) {
3800 return;
3802 sep = strrchr(str, '-');
3803 if (sep) {
3804 str = sep + 1;
3806 len = strlen(str);
3807 readline_set_completion_index(rs, len);
3808 for (i = 0; i < Q_KEY_CODE__MAX; i++) {
3809 if (!strncmp(str, QKeyCode_str(i), len)) {
3810 readline_add_completion(rs, QKeyCode_str(i));
3815 void set_link_completion(ReadLineState *rs, int nb_args, const char *str)
3817 size_t len;
3819 len = strlen(str);
3820 readline_set_completion_index(rs, len);
3821 if (nb_args == 2) {
3822 NetClientState *ncs[MAX_QUEUE_NUM];
3823 int count, i;
3824 count = qemu_find_net_clients_except(NULL, ncs,
3825 NET_CLIENT_DRIVER_NONE,
3826 MAX_QUEUE_NUM);
3827 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3828 const char *name = ncs[i]->name;
3829 if (!strncmp(str, name, len)) {
3830 readline_add_completion(rs, name);
3833 } else if (nb_args == 3) {
3834 add_completion_option(rs, str, "on");
3835 add_completion_option(rs, str, "off");
3839 void netdev_del_completion(ReadLineState *rs, int nb_args, const char *str)
3841 int len, count, i;
3842 NetClientState *ncs[MAX_QUEUE_NUM];
3844 if (nb_args != 2) {
3845 return;
3848 len = strlen(str);
3849 readline_set_completion_index(rs, len);
3850 count = qemu_find_net_clients_except(NULL, ncs, NET_CLIENT_DRIVER_NIC,
3851 MAX_QUEUE_NUM);
3852 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3853 QemuOpts *opts;
3854 const char *name = ncs[i]->name;
3855 if (strncmp(str, name, len)) {
3856 continue;
3858 opts = qemu_opts_find(qemu_find_opts_err("netdev", NULL), name);
3859 if (opts) {
3860 readline_add_completion(rs, name);
3865 void info_trace_events_completion(ReadLineState *rs, int nb_args, const char *str)
3867 size_t len;
3869 len = strlen(str);
3870 readline_set_completion_index(rs, len);
3871 if (nb_args == 2) {
3872 TraceEventIter iter;
3873 TraceEvent *ev;
3874 char *pattern = g_strdup_printf("%s*", str);
3875 trace_event_iter_init(&iter, pattern);
3876 while ((ev = trace_event_iter_next(&iter)) != NULL) {
3877 readline_add_completion(rs, trace_event_get_name(ev));
3879 g_free(pattern);
3883 void trace_event_completion(ReadLineState *rs, int nb_args, const char *str)
3885 size_t len;
3887 len = strlen(str);
3888 readline_set_completion_index(rs, len);
3889 if (nb_args == 2) {
3890 TraceEventIter iter;
3891 TraceEvent *ev;
3892 char *pattern = g_strdup_printf("%s*", str);
3893 trace_event_iter_init(&iter, pattern);
3894 while ((ev = trace_event_iter_next(&iter)) != NULL) {
3895 readline_add_completion(rs, trace_event_get_name(ev));
3897 g_free(pattern);
3898 } else if (nb_args == 3) {
3899 add_completion_option(rs, str, "on");
3900 add_completion_option(rs, str, "off");
3904 void watchdog_action_completion(ReadLineState *rs, int nb_args, const char *str)
3906 int i;
3908 if (nb_args != 2) {
3909 return;
3911 readline_set_completion_index(rs, strlen(str));
3912 for (i = 0; i < WATCHDOG_ACTION__MAX; i++) {
3913 add_completion_option(rs, str, WatchdogAction_str(i));
3917 void migrate_set_capability_completion(ReadLineState *rs, int nb_args,
3918 const char *str)
3920 size_t len;
3922 len = strlen(str);
3923 readline_set_completion_index(rs, len);
3924 if (nb_args == 2) {
3925 int i;
3926 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
3927 const char *name = MigrationCapability_str(i);
3928 if (!strncmp(str, name, len)) {
3929 readline_add_completion(rs, name);
3932 } else if (nb_args == 3) {
3933 add_completion_option(rs, str, "on");
3934 add_completion_option(rs, str, "off");
3938 void migrate_set_parameter_completion(ReadLineState *rs, int nb_args,
3939 const char *str)
3941 size_t len;
3943 len = strlen(str);
3944 readline_set_completion_index(rs, len);
3945 if (nb_args == 2) {
3946 int i;
3947 for (i = 0; i < MIGRATION_PARAMETER__MAX; i++) {
3948 const char *name = MigrationParameter_str(i);
3949 if (!strncmp(str, name, len)) {
3950 readline_add_completion(rs, name);
3956 static void vm_completion(ReadLineState *rs, const char *str)
3958 size_t len;
3959 BlockDriverState *bs;
3960 BdrvNextIterator it;
3962 len = strlen(str);
3963 readline_set_completion_index(rs, len);
3965 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
3966 SnapshotInfoList *snapshots, *snapshot;
3967 AioContext *ctx = bdrv_get_aio_context(bs);
3968 bool ok = false;
3970 aio_context_acquire(ctx);
3971 if (bdrv_can_snapshot(bs)) {
3972 ok = bdrv_query_snapshot_info_list(bs, &snapshots, NULL) == 0;
3974 aio_context_release(ctx);
3975 if (!ok) {
3976 continue;
3979 snapshot = snapshots;
3980 while (snapshot) {
3981 char *completion = snapshot->value->name;
3982 if (!strncmp(str, completion, len)) {
3983 readline_add_completion(rs, completion);
3985 completion = snapshot->value->id;
3986 if (!strncmp(str, completion, len)) {
3987 readline_add_completion(rs, completion);
3989 snapshot = snapshot->next;
3991 qapi_free_SnapshotInfoList(snapshots);
3996 void delvm_completion(ReadLineState *rs, int nb_args, const char *str)
3998 if (nb_args == 2) {
3999 vm_completion(rs, str);
4003 void loadvm_completion(ReadLineState *rs, int nb_args, const char *str)
4005 if (nb_args == 2) {
4006 vm_completion(rs, str);
4010 static void monitor_find_completion_by_table(Monitor *mon,
4011 const mon_cmd_t *cmd_table,
4012 char **args,
4013 int nb_args)
4015 const char *cmdname;
4016 int i;
4017 const char *ptype, *old_ptype, *str, *name;
4018 const mon_cmd_t *cmd;
4019 BlockBackend *blk = NULL;
4021 if (nb_args <= 1) {
4022 /* command completion */
4023 if (nb_args == 0)
4024 cmdname = "";
4025 else
4026 cmdname = args[0];
4027 readline_set_completion_index(mon->rs, strlen(cmdname));
4028 for (cmd = cmd_table; cmd->name != NULL; cmd++) {
4029 if (!runstate_check(RUN_STATE_PRECONFIG) ||
4030 cmd_can_preconfig(cmd)) {
4031 cmd_completion(mon, cmdname, cmd->name);
4034 } else {
4035 /* find the command */
4036 for (cmd = cmd_table; cmd->name != NULL; cmd++) {
4037 if (compare_cmd(args[0], cmd->name) &&
4038 (!runstate_check(RUN_STATE_PRECONFIG) ||
4039 cmd_can_preconfig(cmd))) {
4040 break;
4043 if (!cmd->name) {
4044 return;
4047 if (cmd->sub_table) {
4048 /* do the job again */
4049 monitor_find_completion_by_table(mon, cmd->sub_table,
4050 &args[1], nb_args - 1);
4051 return;
4053 if (cmd->command_completion) {
4054 cmd->command_completion(mon->rs, nb_args, args[nb_args - 1]);
4055 return;
4058 ptype = next_arg_type(cmd->args_type);
4059 for(i = 0; i < nb_args - 2; i++) {
4060 if (*ptype != '\0') {
4061 ptype = next_arg_type(ptype);
4062 while (*ptype == '?')
4063 ptype = next_arg_type(ptype);
4066 str = args[nb_args - 1];
4067 old_ptype = NULL;
4068 while (*ptype == '-' && old_ptype != ptype) {
4069 old_ptype = ptype;
4070 ptype = next_arg_type(ptype);
4072 switch(*ptype) {
4073 case 'F':
4074 /* file completion */
4075 readline_set_completion_index(mon->rs, strlen(str));
4076 file_completion(mon, str);
4077 break;
4078 case 'B':
4079 /* block device name completion */
4080 readline_set_completion_index(mon->rs, strlen(str));
4081 while ((blk = blk_next(blk)) != NULL) {
4082 name = blk_name(blk);
4083 if (str[0] == '\0' ||
4084 !strncmp(name, str, strlen(str))) {
4085 readline_add_completion(mon->rs, name);
4088 break;
4089 case 's':
4090 case 'S':
4091 if (!strcmp(cmd->name, "help|?")) {
4092 monitor_find_completion_by_table(mon, cmd_table,
4093 &args[1], nb_args - 1);
4095 break;
4096 default:
4097 break;
4102 static void monitor_find_completion(void *opaque,
4103 const char *cmdline)
4105 Monitor *mon = opaque;
4106 char *args[MAX_ARGS];
4107 int nb_args, len;
4109 /* 1. parse the cmdline */
4110 if (parse_cmdline(cmdline, &nb_args, args) < 0) {
4111 return;
4114 /* if the line ends with a space, it means we want to complete the
4115 next arg */
4116 len = strlen(cmdline);
4117 if (len > 0 && qemu_isspace(cmdline[len - 1])) {
4118 if (nb_args >= MAX_ARGS) {
4119 goto cleanup;
4121 args[nb_args++] = g_strdup("");
4124 /* 2. auto complete according to args */
4125 monitor_find_completion_by_table(mon, mon->cmd_table, args, nb_args);
4127 cleanup:
4128 free_cmdline_args(args, nb_args);
4131 static int monitor_can_read(void *opaque)
4133 Monitor *mon = opaque;
4135 return !atomic_mb_read(&mon->suspend_cnt);
4139 * Emit QMP response @rsp with ID @id to @mon.
4140 * Null @rsp can only happen for commands with QCO_NO_SUCCESS_RESP.
4141 * Nothing is emitted then.
4143 static void monitor_qmp_respond(MonitorQMP *mon, QDict *rsp)
4145 if (rsp) {
4146 qmp_send_response(mon, rsp);
4150 static void monitor_qmp_dispatch(MonitorQMP *mon, QObject *req)
4152 Monitor *old_mon;
4153 QDict *rsp;
4154 QDict *error;
4156 old_mon = cur_mon;
4157 cur_mon = &mon->common;
4159 rsp = qmp_dispatch(mon->commands, req, qmp_oob_enabled(mon));
4161 cur_mon = old_mon;
4163 if (mon->commands == &qmp_cap_negotiation_commands) {
4164 error = qdict_get_qdict(rsp, "error");
4165 if (error
4166 && !g_strcmp0(qdict_get_try_str(error, "class"),
4167 QapiErrorClass_str(ERROR_CLASS_COMMAND_NOT_FOUND))) {
4168 /* Provide a more useful error message */
4169 qdict_del(error, "desc");
4170 qdict_put_str(error, "desc", "Expecting capabilities negotiation"
4171 " with 'qmp_capabilities'");
4175 monitor_qmp_respond(mon, rsp);
4176 qobject_unref(rsp);
4180 * Pop a QMP request from a monitor request queue.
4181 * Return the request, or NULL all request queues are empty.
4182 * We are using round-robin fashion to pop the request, to avoid
4183 * processing commands only on a very busy monitor. To achieve that,
4184 * when we process one request on a specific monitor, we put that
4185 * monitor to the end of mon_list queue.
4187 * Note: if the function returned with non-NULL, then the caller will
4188 * be with qmp_mon->qmp_queue_lock held, and the caller is responsible
4189 * to release it.
4191 static QMPRequest *monitor_qmp_requests_pop_any_with_lock(void)
4193 QMPRequest *req_obj = NULL;
4194 Monitor *mon;
4195 MonitorQMP *qmp_mon;
4197 qemu_mutex_lock(&monitor_lock);
4199 QTAILQ_FOREACH(mon, &mon_list, entry) {
4200 if (!monitor_is_qmp(mon)) {
4201 continue;
4204 qmp_mon = container_of(mon, MonitorQMP, common);
4205 qemu_mutex_lock(&qmp_mon->qmp_queue_lock);
4206 req_obj = g_queue_pop_head(qmp_mon->qmp_requests);
4207 if (req_obj) {
4208 /* With the lock of corresponding queue held */
4209 break;
4211 qemu_mutex_unlock(&qmp_mon->qmp_queue_lock);
4214 if (req_obj) {
4216 * We found one request on the monitor. Degrade this monitor's
4217 * priority to lowest by re-inserting it to end of queue.
4219 QTAILQ_REMOVE(&mon_list, mon, entry);
4220 QTAILQ_INSERT_TAIL(&mon_list, mon, entry);
4223 qemu_mutex_unlock(&monitor_lock);
4225 return req_obj;
4228 static void monitor_qmp_bh_dispatcher(void *data)
4230 QMPRequest *req_obj = monitor_qmp_requests_pop_any_with_lock();
4231 QDict *rsp;
4232 bool need_resume;
4233 MonitorQMP *mon;
4235 if (!req_obj) {
4236 return;
4239 mon = req_obj->mon;
4240 /* qmp_oob_enabled() might change after "qmp_capabilities" */
4241 need_resume = !qmp_oob_enabled(mon) ||
4242 mon->qmp_requests->length == QMP_REQ_QUEUE_LEN_MAX - 1;
4243 qemu_mutex_unlock(&mon->qmp_queue_lock);
4244 if (req_obj->req) {
4245 QDict *qdict = qobject_to(QDict, req_obj->req);
4246 QObject *id = qdict ? qdict_get(qdict, "id") : NULL;
4247 trace_monitor_qmp_cmd_in_band(qobject_get_try_str(id) ?: "");
4248 monitor_qmp_dispatch(mon, req_obj->req);
4249 } else {
4250 assert(req_obj->err);
4251 rsp = qmp_error_response(req_obj->err);
4252 req_obj->err = NULL;
4253 monitor_qmp_respond(mon, rsp);
4254 qobject_unref(rsp);
4257 if (need_resume) {
4258 /* Pairs with the monitor_suspend() in handle_qmp_command() */
4259 monitor_resume(&mon->common);
4261 qmp_request_free(req_obj);
4263 /* Reschedule instead of looping so the main loop stays responsive */
4264 qemu_bh_schedule(qmp_dispatcher_bh);
4267 static void handle_qmp_command(void *opaque, QObject *req, Error *err)
4269 MonitorQMP *mon = opaque;
4270 QObject *id = NULL;
4271 QDict *qdict;
4272 QMPRequest *req_obj;
4274 assert(!req != !err);
4276 qdict = qobject_to(QDict, req);
4277 if (qdict) {
4278 id = qdict_get(qdict, "id");
4279 } /* else will fail qmp_dispatch() */
4281 if (req && trace_event_get_state_backends(TRACE_HANDLE_QMP_COMMAND)) {
4282 QString *req_json = qobject_to_json(req);
4283 trace_handle_qmp_command(mon, qstring_get_str(req_json));
4284 qobject_unref(req_json);
4287 if (qdict && qmp_is_oob(qdict)) {
4288 /* OOB commands are executed immediately */
4289 trace_monitor_qmp_cmd_out_of_band(qobject_get_try_str(id) ?: "");
4290 monitor_qmp_dispatch(mon, req);
4291 qobject_unref(req);
4292 return;
4295 req_obj = g_new0(QMPRequest, 1);
4296 req_obj->mon = mon;
4297 req_obj->req = req;
4298 req_obj->err = err;
4300 /* Protect qmp_requests and fetching its length. */
4301 qemu_mutex_lock(&mon->qmp_queue_lock);
4304 * Suspend the monitor when we can't queue more requests after
4305 * this one. Dequeuing in monitor_qmp_bh_dispatcher() will resume
4306 * it. Note that when OOB is disabled, we queue at most one
4307 * command, for backward compatibility.
4309 if (!qmp_oob_enabled(mon) ||
4310 mon->qmp_requests->length == QMP_REQ_QUEUE_LEN_MAX - 1) {
4311 monitor_suspend(&mon->common);
4315 * Put the request to the end of queue so that requests will be
4316 * handled in time order. Ownership for req_obj, req,
4317 * etc. will be delivered to the handler side.
4319 assert(mon->qmp_requests->length < QMP_REQ_QUEUE_LEN_MAX);
4320 g_queue_push_tail(mon->qmp_requests, req_obj);
4321 qemu_mutex_unlock(&mon->qmp_queue_lock);
4323 /* Kick the dispatcher routine */
4324 qemu_bh_schedule(qmp_dispatcher_bh);
4327 static void monitor_qmp_read(void *opaque, const uint8_t *buf, int size)
4329 MonitorQMP *mon = opaque;
4331 json_message_parser_feed(&mon->parser, (const char *) buf, size);
4334 static void monitor_read(void *opaque, const uint8_t *buf, int size)
4336 Monitor *old_mon = cur_mon;
4337 int i;
4339 cur_mon = opaque;
4341 if (cur_mon->rs) {
4342 for (i = 0; i < size; i++)
4343 readline_handle_byte(cur_mon->rs, buf[i]);
4344 } else {
4345 if (size == 0 || buf[size - 1] != 0)
4346 monitor_printf(cur_mon, "corrupted command\n");
4347 else
4348 handle_hmp_command(cur_mon, (char *)buf);
4351 cur_mon = old_mon;
4354 static void monitor_command_cb(void *opaque, const char *cmdline,
4355 void *readline_opaque)
4357 Monitor *mon = opaque;
4359 monitor_suspend(mon);
4360 handle_hmp_command(mon, cmdline);
4361 monitor_resume(mon);
4364 int monitor_suspend(Monitor *mon)
4366 if (monitor_is_hmp_non_interactive(mon)) {
4367 return -ENOTTY;
4370 atomic_inc(&mon->suspend_cnt);
4372 if (mon->use_io_thread) {
4374 * Kick I/O thread to make sure this takes effect. It'll be
4375 * evaluated again in prepare() of the watch object.
4377 aio_notify(iothread_get_aio_context(mon_iothread));
4380 trace_monitor_suspend(mon, 1);
4381 return 0;
4384 static void monitor_accept_input(void *opaque)
4386 Monitor *mon = opaque;
4388 qemu_chr_fe_accept_input(&mon->chr);
4391 void monitor_resume(Monitor *mon)
4393 if (monitor_is_hmp_non_interactive(mon)) {
4394 return;
4397 if (atomic_dec_fetch(&mon->suspend_cnt) == 0) {
4398 AioContext *ctx;
4400 if (mon->use_io_thread) {
4401 ctx = iothread_get_aio_context(mon_iothread);
4402 } else {
4403 ctx = qemu_get_aio_context();
4406 if (!monitor_is_qmp(mon)) {
4407 assert(mon->rs);
4408 readline_show_prompt(mon->rs);
4411 aio_bh_schedule_oneshot(ctx, monitor_accept_input, mon);
4414 trace_monitor_suspend(mon, -1);
4417 static QDict *qmp_greeting(MonitorQMP *mon)
4419 QList *cap_list = qlist_new();
4420 QObject *ver = NULL;
4421 QMPCapability cap;
4423 qmp_marshal_query_version(NULL, &ver, NULL);
4425 for (cap = 0; cap < QMP_CAPABILITY__MAX; cap++) {
4426 if (mon->capab_offered[cap]) {
4427 qlist_append_str(cap_list, QMPCapability_str(cap));
4431 return qdict_from_jsonf_nofail(
4432 "{'QMP': {'version': %p, 'capabilities': %p}}",
4433 ver, cap_list);
4436 static void monitor_qmp_event(void *opaque, int event)
4438 QDict *data;
4439 MonitorQMP *mon = opaque;
4441 switch (event) {
4442 case CHR_EVENT_OPENED:
4443 mon->commands = &qmp_cap_negotiation_commands;
4444 monitor_qmp_caps_reset(mon);
4445 data = qmp_greeting(mon);
4446 qmp_send_response(mon, data);
4447 qobject_unref(data);
4448 mon_refcount++;
4449 break;
4450 case CHR_EVENT_CLOSED:
4452 * Note: this is only useful when the output of the chardev
4453 * backend is still open. For example, when the backend is
4454 * stdio, it's possible that stdout is still open when stdin
4455 * is closed.
4457 monitor_qmp_cleanup_queues(mon);
4458 json_message_parser_destroy(&mon->parser);
4459 json_message_parser_init(&mon->parser, handle_qmp_command,
4460 mon, NULL);
4461 mon_refcount--;
4462 monitor_fdsets_cleanup();
4463 break;
4467 static void monitor_event(void *opaque, int event)
4469 Monitor *mon = opaque;
4471 switch (event) {
4472 case CHR_EVENT_MUX_IN:
4473 qemu_mutex_lock(&mon->mon_lock);
4474 mon->mux_out = 0;
4475 qemu_mutex_unlock(&mon->mon_lock);
4476 if (mon->reset_seen) {
4477 readline_restart(mon->rs);
4478 monitor_resume(mon);
4479 monitor_flush(mon);
4480 } else {
4481 atomic_mb_set(&mon->suspend_cnt, 0);
4483 break;
4485 case CHR_EVENT_MUX_OUT:
4486 if (mon->reset_seen) {
4487 if (atomic_mb_read(&mon->suspend_cnt) == 0) {
4488 monitor_printf(mon, "\n");
4490 monitor_flush(mon);
4491 monitor_suspend(mon);
4492 } else {
4493 atomic_inc(&mon->suspend_cnt);
4495 qemu_mutex_lock(&mon->mon_lock);
4496 mon->mux_out = 1;
4497 qemu_mutex_unlock(&mon->mon_lock);
4498 break;
4500 case CHR_EVENT_OPENED:
4501 monitor_printf(mon, "QEMU %s monitor - type 'help' for more "
4502 "information\n", QEMU_VERSION);
4503 if (!mon->mux_out) {
4504 readline_restart(mon->rs);
4505 readline_show_prompt(mon->rs);
4507 mon->reset_seen = 1;
4508 mon_refcount++;
4509 break;
4511 case CHR_EVENT_CLOSED:
4512 mon_refcount--;
4513 monitor_fdsets_cleanup();
4514 break;
4518 static int
4519 compare_mon_cmd(const void *a, const void *b)
4521 return strcmp(((const mon_cmd_t *)a)->name,
4522 ((const mon_cmd_t *)b)->name);
4525 static void sortcmdlist(void)
4527 int array_num;
4528 int elem_size = sizeof(mon_cmd_t);
4530 array_num = sizeof(mon_cmds)/elem_size-1;
4531 qsort((void *)mon_cmds, array_num, elem_size, compare_mon_cmd);
4533 array_num = sizeof(info_cmds)/elem_size-1;
4534 qsort((void *)info_cmds, array_num, elem_size, compare_mon_cmd);
4537 static void monitor_iothread_init(void)
4539 mon_iothread = iothread_create("mon_iothread", &error_abort);
4542 void monitor_init_globals(void)
4544 monitor_init_qmp_commands();
4545 monitor_qapi_event_init();
4546 sortcmdlist();
4547 qemu_mutex_init(&monitor_lock);
4548 qemu_mutex_init(&mon_fdsets_lock);
4551 * The dispatcher BH must run in the main loop thread, since we
4552 * have commands assuming that context. It would be nice to get
4553 * rid of those assumptions.
4555 qmp_dispatcher_bh = aio_bh_new(iohandler_get_aio_context(),
4556 monitor_qmp_bh_dispatcher,
4557 NULL);
4560 /* These functions just adapt the readline interface in a typesafe way. We
4561 * could cast function pointers but that discards compiler checks.
4563 static void GCC_FMT_ATTR(2, 3) monitor_readline_printf(void *opaque,
4564 const char *fmt, ...)
4566 va_list ap;
4567 va_start(ap, fmt);
4568 monitor_vprintf(opaque, fmt, ap);
4569 va_end(ap);
4572 static void monitor_readline_flush(void *opaque)
4574 monitor_flush(opaque);
4578 * Print to current monitor if we have one, else to stderr.
4580 int error_vprintf(const char *fmt, va_list ap)
4582 if (cur_mon && !monitor_cur_is_qmp()) {
4583 return monitor_vprintf(cur_mon, fmt, ap);
4585 return vfprintf(stderr, fmt, ap);
4588 int error_vprintf_unless_qmp(const char *fmt, va_list ap)
4590 if (!cur_mon) {
4591 return vfprintf(stderr, fmt, ap);
4593 if (!monitor_cur_is_qmp()) {
4594 return monitor_vprintf(cur_mon, fmt, ap);
4596 return -1;
4599 static void monitor_list_append(Monitor *mon)
4601 qemu_mutex_lock(&monitor_lock);
4603 * This prevents inserting new monitors during monitor_cleanup().
4604 * A cleaner solution would involve the main thread telling other
4605 * threads to terminate, waiting for their termination.
4607 if (!monitor_destroyed) {
4608 QTAILQ_INSERT_HEAD(&mon_list, mon, entry);
4609 mon = NULL;
4611 qemu_mutex_unlock(&monitor_lock);
4613 if (mon) {
4614 monitor_data_destroy(mon);
4615 g_free(mon);
4619 static void monitor_qmp_setup_handlers_bh(void *opaque)
4621 MonitorQMP *mon = opaque;
4622 GMainContext *context;
4624 assert(mon->common.use_io_thread);
4625 context = iothread_get_g_main_context(mon_iothread);
4626 assert(context);
4627 qemu_chr_fe_set_handlers(&mon->common.chr, monitor_can_read,
4628 monitor_qmp_read, monitor_qmp_event,
4629 NULL, &mon->common, context, true);
4630 monitor_list_append(&mon->common);
4633 static void monitor_init_qmp(Chardev *chr, int flags)
4635 MonitorQMP *mon = g_new0(MonitorQMP, 1);
4637 /* Only HMP supports readline */
4638 assert(!(flags & MONITOR_USE_READLINE));
4640 /* Note: we run QMP monitor in I/O thread when @chr supports that */
4641 monitor_data_init(&mon->common, flags, false,
4642 qemu_chr_has_feature(chr, QEMU_CHAR_FEATURE_GCONTEXT));
4644 qemu_mutex_init(&mon->qmp_queue_lock);
4645 mon->qmp_requests = g_queue_new();
4647 qemu_chr_fe_init(&mon->common.chr, chr, &error_abort);
4648 qemu_chr_fe_set_echo(&mon->common.chr, true);
4650 json_message_parser_init(&mon->parser, handle_qmp_command, mon, NULL);
4651 if (mon->common.use_io_thread) {
4653 * Make sure the old iowatch is gone. It's possible when
4654 * e.g. the chardev is in client mode, with wait=on.
4656 remove_fd_in_watch(chr);
4658 * We can't call qemu_chr_fe_set_handlers() directly here
4659 * since chardev might be running in the monitor I/O
4660 * thread. Schedule a bottom half.
4662 aio_bh_schedule_oneshot(iothread_get_aio_context(mon_iothread),
4663 monitor_qmp_setup_handlers_bh, mon);
4664 /* The bottom half will add @mon to @mon_list */
4665 } else {
4666 qemu_chr_fe_set_handlers(&mon->common.chr, monitor_can_read,
4667 monitor_qmp_read, monitor_qmp_event,
4668 NULL, &mon->common, NULL, true);
4669 monitor_list_append(&mon->common);
4673 static void monitor_init_hmp(Chardev *chr, int flags)
4675 Monitor *mon = g_new0(Monitor, 1);
4676 bool use_readline = flags & MONITOR_USE_READLINE;
4678 monitor_data_init(mon, flags, false, false);
4679 qemu_chr_fe_init(&mon->chr, chr, &error_abort);
4681 if (use_readline) {
4682 mon->rs = readline_init(monitor_readline_printf,
4683 monitor_readline_flush,
4684 mon,
4685 monitor_find_completion);
4686 monitor_read_command(mon, 0);
4689 qemu_chr_fe_set_handlers(&mon->chr, monitor_can_read, monitor_read,
4690 monitor_event, NULL, mon, NULL, true);
4691 monitor_list_append(mon);
4694 void monitor_init(Chardev *chr, int flags)
4696 if (flags & MONITOR_USE_CONTROL) {
4697 monitor_init_qmp(chr, flags);
4698 } else {
4699 monitor_init_hmp(chr, flags);
4703 void monitor_cleanup(void)
4706 * We need to explicitly stop the I/O thread (but not destroy it),
4707 * clean up the monitor resources, then destroy the I/O thread since
4708 * we need to unregister from chardev below in
4709 * monitor_data_destroy(), and chardev is not thread-safe yet
4711 if (mon_iothread) {
4712 iothread_stop(mon_iothread);
4715 /* Flush output buffers and destroy monitors */
4716 qemu_mutex_lock(&monitor_lock);
4717 monitor_destroyed = true;
4718 while (!QTAILQ_EMPTY(&mon_list)) {
4719 Monitor *mon = QTAILQ_FIRST(&mon_list);
4720 QTAILQ_REMOVE(&mon_list, mon, entry);
4721 /* Permit QAPI event emission from character frontend release */
4722 qemu_mutex_unlock(&monitor_lock);
4723 monitor_flush(mon);
4724 monitor_data_destroy(mon);
4725 qemu_mutex_lock(&monitor_lock);
4726 g_free(mon);
4728 qemu_mutex_unlock(&monitor_lock);
4730 /* QEMUBHs needs to be deleted before destroying the I/O thread */
4731 qemu_bh_delete(qmp_dispatcher_bh);
4732 qmp_dispatcher_bh = NULL;
4733 if (mon_iothread) {
4734 iothread_destroy(mon_iothread);
4735 mon_iothread = NULL;
4739 QemuOptsList qemu_mon_opts = {
4740 .name = "mon",
4741 .implied_opt_name = "chardev",
4742 .head = QTAILQ_HEAD_INITIALIZER(qemu_mon_opts.head),
4743 .desc = {
4745 .name = "mode",
4746 .type = QEMU_OPT_STRING,
4748 .name = "chardev",
4749 .type = QEMU_OPT_STRING,
4751 .name = "pretty",
4752 .type = QEMU_OPT_BOOL,
4754 { /* end of list */ }
4758 HotpluggableCPUList *qmp_query_hotpluggable_cpus(Error **errp)
4760 MachineState *ms = MACHINE(qdev_get_machine());
4761 MachineClass *mc = MACHINE_GET_CLASS(ms);
4763 if (!mc->has_hotpluggable_cpus) {
4764 error_setg(errp, QERR_FEATURE_DISABLED, "query-hotpluggable-cpus");
4765 return NULL;
4768 return machine_query_hotpluggable_cpus(ms);