monitor: Create MonitorHMP with readline state
[qemu/ar7.git] / monitor.c
blob7c57308e2a009c93e094191b08791f20069a1241
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;
195 gchar *mon_cpu_path;
196 mon_cmd_t *cmd_table;
197 QTAILQ_ENTRY(Monitor) entry;
200 * The per-monitor lock. We can't access guest memory when holding
201 * the lock.
203 QemuMutex mon_lock;
206 * Members that are protected by the per-monitor lock
208 QLIST_HEAD(, mon_fd_t) fds;
209 QString *outbuf;
210 guint out_watch;
211 /* Read under either BQL or mon_lock, written with BQL+mon_lock. */
212 int mux_out;
215 struct MonitorHMP {
216 Monitor common;
218 * State used only in the thread "owning" the monitor.
219 * If @use_io_thread, this is @mon_iothread. (This does not actually happen
220 * in the current state of the code.)
221 * Else, it's the main thread.
222 * These members can be safely accessed without locks.
224 ReadLineState *rs;
227 typedef struct {
228 Monitor common;
229 JSONMessageParser parser;
231 * When a client connects, we're in capabilities negotiation mode.
232 * @commands is &qmp_cap_negotiation_commands then. When command
233 * qmp_capabilities succeeds, we go into command mode, and
234 * @command becomes &qmp_commands.
236 QmpCommandList *commands;
237 bool capab_offered[QMP_CAPABILITY__MAX]; /* capabilities offered */
238 bool capab[QMP_CAPABILITY__MAX]; /* offered and accepted */
240 * Protects qmp request/response queue.
241 * Take monitor_lock first when you need both.
243 QemuMutex qmp_queue_lock;
244 /* Input queue that holds all the parsed QMP requests */
245 GQueue *qmp_requests;
246 } MonitorQMP;
248 /* Shared monitor I/O thread */
249 IOThread *mon_iothread;
251 /* Bottom half to dispatch the requests received from I/O thread */
252 QEMUBH *qmp_dispatcher_bh;
254 struct QMPRequest {
255 /* Owner of the request */
256 MonitorQMP *mon;
258 * Request object to be handled or Error to be reported
259 * (exactly one of them is non-null)
261 QObject *req;
262 Error *err;
264 typedef struct QMPRequest QMPRequest;
266 /* QMP checker flags */
267 #define QMP_ACCEPT_UNKNOWNS 1
269 /* Protects mon_list, monitor_qapi_event_state, monitor_destroyed. */
270 static QemuMutex monitor_lock;
271 static GHashTable *monitor_qapi_event_state;
272 static QTAILQ_HEAD(, Monitor) mon_list;
273 static bool monitor_destroyed;
275 /* Protects mon_fdsets */
276 static QemuMutex mon_fdsets_lock;
277 static QLIST_HEAD(, MonFdset) mon_fdsets;
279 static int mon_refcount;
281 static mon_cmd_t mon_cmds[];
282 static mon_cmd_t info_cmds[];
284 QmpCommandList qmp_commands, qmp_cap_negotiation_commands;
286 __thread Monitor *cur_mon;
288 static void monitor_command_cb(void *opaque, const char *cmdline,
289 void *readline_opaque);
292 * Is @mon a QMP monitor?
294 static inline bool monitor_is_qmp(const Monitor *mon)
296 return (mon->flags & MONITOR_USE_CONTROL);
300 * Is @mon is using readline?
301 * Note: not all HMP monitors use readline, e.g., gdbserver has a
302 * non-interactive HMP monitor, so readline is not used there.
304 static inline bool monitor_uses_readline(const Monitor *mon)
306 return mon->flags & MONITOR_USE_READLINE;
309 static inline bool monitor_is_hmp_non_interactive(const Monitor *mon)
311 return !monitor_is_qmp(mon) && !monitor_uses_readline(mon);
315 * Return the clock to use for recording an event's time.
316 * It's QEMU_CLOCK_REALTIME, except for qtests it's
317 * QEMU_CLOCK_VIRTUAL, to support testing rate limits.
318 * Beware: result is invalid before configure_accelerator().
320 static inline QEMUClockType monitor_get_event_clock(void)
322 return qtest_enabled() ? QEMU_CLOCK_VIRTUAL : QEMU_CLOCK_REALTIME;
326 * Is the current monitor, if any, a QMP monitor?
328 bool monitor_cur_is_qmp(void)
330 return cur_mon && monitor_is_qmp(cur_mon);
333 void monitor_read_command(MonitorHMP *mon, int show_prompt)
335 if (!mon->rs)
336 return;
338 readline_start(mon->rs, "(qemu) ", 0, monitor_command_cb, NULL);
339 if (show_prompt)
340 readline_show_prompt(mon->rs);
343 int monitor_read_password(MonitorHMP *mon, ReadLineFunc *readline_func,
344 void *opaque)
346 if (mon->rs) {
347 readline_start(mon->rs, "Password: ", 1, readline_func, opaque);
348 /* prompt is printed on return from the command handler */
349 return 0;
350 } else {
351 monitor_printf(&mon->common,
352 "terminal does not support password prompting\n");
353 return -ENOTTY;
357 static void qmp_request_free(QMPRequest *req)
359 qobject_unref(req->req);
360 error_free(req->err);
361 g_free(req);
364 /* Caller must hold mon->qmp.qmp_queue_lock */
365 static void monitor_qmp_cleanup_req_queue_locked(MonitorQMP *mon)
367 while (!g_queue_is_empty(mon->qmp_requests)) {
368 qmp_request_free(g_queue_pop_head(mon->qmp_requests));
372 static void monitor_qmp_cleanup_queues(MonitorQMP *mon)
374 qemu_mutex_lock(&mon->qmp_queue_lock);
375 monitor_qmp_cleanup_req_queue_locked(mon);
376 qemu_mutex_unlock(&mon->qmp_queue_lock);
380 static void monitor_flush_locked(Monitor *mon);
382 static gboolean monitor_unblocked(GIOChannel *chan, GIOCondition cond,
383 void *opaque)
385 Monitor *mon = opaque;
387 qemu_mutex_lock(&mon->mon_lock);
388 mon->out_watch = 0;
389 monitor_flush_locked(mon);
390 qemu_mutex_unlock(&mon->mon_lock);
391 return FALSE;
394 /* Caller must hold mon->mon_lock */
395 static void monitor_flush_locked(Monitor *mon)
397 int rc;
398 size_t len;
399 const char *buf;
401 if (mon->skip_flush) {
402 return;
405 buf = qstring_get_str(mon->outbuf);
406 len = qstring_get_length(mon->outbuf);
408 if (len && !mon->mux_out) {
409 rc = qemu_chr_fe_write(&mon->chr, (const uint8_t *) buf, len);
410 if ((rc < 0 && errno != EAGAIN) || (rc == len)) {
411 /* all flushed or error */
412 qobject_unref(mon->outbuf);
413 mon->outbuf = qstring_new();
414 return;
416 if (rc > 0) {
417 /* partial write */
418 QString *tmp = qstring_from_str(buf + rc);
419 qobject_unref(mon->outbuf);
420 mon->outbuf = tmp;
422 if (mon->out_watch == 0) {
423 mon->out_watch =
424 qemu_chr_fe_add_watch(&mon->chr, G_IO_OUT | G_IO_HUP,
425 monitor_unblocked, mon);
430 void monitor_flush(Monitor *mon)
432 qemu_mutex_lock(&mon->mon_lock);
433 monitor_flush_locked(mon);
434 qemu_mutex_unlock(&mon->mon_lock);
437 /* flush at every end of line */
438 static int monitor_puts(Monitor *mon, const char *str)
440 int i;
441 char c;
443 qemu_mutex_lock(&mon->mon_lock);
444 for (i = 0; str[i]; i++) {
445 c = str[i];
446 if (c == '\n') {
447 qstring_append_chr(mon->outbuf, '\r');
449 qstring_append_chr(mon->outbuf, c);
450 if (c == '\n') {
451 monitor_flush_locked(mon);
454 qemu_mutex_unlock(&mon->mon_lock);
456 return i;
459 int monitor_vprintf(Monitor *mon, const char *fmt, va_list ap)
461 char *buf;
462 int n;
464 if (!mon)
465 return -1;
467 if (monitor_is_qmp(mon)) {
468 return -1;
471 buf = g_strdup_vprintf(fmt, ap);
472 n = monitor_puts(mon, buf);
473 g_free(buf);
474 return n;
477 int monitor_printf(Monitor *mon, const char *fmt, ...)
479 int ret;
481 va_list ap;
482 va_start(ap, fmt);
483 ret = monitor_vprintf(mon, fmt, ap);
484 va_end(ap);
485 return ret;
488 static void qmp_send_response(MonitorQMP *mon, const QDict *rsp)
490 const QObject *data = QOBJECT(rsp);
491 QString *json;
493 json = mon->common.flags & MONITOR_USE_PRETTY ?
494 qobject_to_json_pretty(data) : qobject_to_json(data);
495 assert(json != NULL);
497 qstring_append_chr(json, '\n');
498 monitor_puts(&mon->common, qstring_get_str(json));
500 qobject_unref(json);
503 static MonitorQAPIEventConf monitor_qapi_event_conf[QAPI_EVENT__MAX] = {
504 /* Limit guest-triggerable events to 1 per second */
505 [QAPI_EVENT_RTC_CHANGE] = { 1000 * SCALE_MS },
506 [QAPI_EVENT_WATCHDOG] = { 1000 * SCALE_MS },
507 [QAPI_EVENT_BALLOON_CHANGE] = { 1000 * SCALE_MS },
508 [QAPI_EVENT_QUORUM_REPORT_BAD] = { 1000 * SCALE_MS },
509 [QAPI_EVENT_QUORUM_FAILURE] = { 1000 * SCALE_MS },
510 [QAPI_EVENT_VSERPORT_CHANGE] = { 1000 * SCALE_MS },
514 * Broadcast an event to all monitors.
515 * @qdict is the event object. Its member "event" must match @event.
516 * Caller must hold monitor_lock.
518 static void monitor_qapi_event_emit(QAPIEvent event, QDict *qdict)
520 Monitor *mon;
521 MonitorQMP *qmp_mon;
523 trace_monitor_protocol_event_emit(event, qdict);
524 QTAILQ_FOREACH(mon, &mon_list, entry) {
525 if (!monitor_is_qmp(mon)) {
526 continue;
529 qmp_mon = container_of(mon, MonitorQMP, common);
530 if (qmp_mon->commands != &qmp_cap_negotiation_commands) {
531 qmp_send_response(qmp_mon, qdict);
536 static void monitor_qapi_event_handler(void *opaque);
539 * Queue a new event for emission to Monitor instances,
540 * applying any rate limiting if required.
542 static void
543 monitor_qapi_event_queue_no_reenter(QAPIEvent event, QDict *qdict)
545 MonitorQAPIEventConf *evconf;
546 MonitorQAPIEventState *evstate;
548 assert(event < QAPI_EVENT__MAX);
549 evconf = &monitor_qapi_event_conf[event];
550 trace_monitor_protocol_event_queue(event, qdict, evconf->rate);
552 qemu_mutex_lock(&monitor_lock);
554 if (!evconf->rate) {
555 /* Unthrottled event */
556 monitor_qapi_event_emit(event, qdict);
557 } else {
558 QDict *data = qobject_to(QDict, qdict_get(qdict, "data"));
559 MonitorQAPIEventState key = { .event = event, .data = data };
561 evstate = g_hash_table_lookup(monitor_qapi_event_state, &key);
562 assert(!evstate || timer_pending(evstate->timer));
564 if (evstate) {
566 * Timer is pending for (at least) evconf->rate ns after
567 * last send. Store event for sending when timer fires,
568 * replacing a prior stored event if any.
570 qobject_unref(evstate->qdict);
571 evstate->qdict = qobject_ref(qdict);
572 } else {
574 * Last send was (at least) evconf->rate ns ago.
575 * Send immediately, and arm the timer to call
576 * monitor_qapi_event_handler() in evconf->rate ns. Any
577 * events arriving before then will be delayed until then.
579 int64_t now = qemu_clock_get_ns(monitor_get_event_clock());
581 monitor_qapi_event_emit(event, qdict);
583 evstate = g_new(MonitorQAPIEventState, 1);
584 evstate->event = event;
585 evstate->data = qobject_ref(data);
586 evstate->qdict = NULL;
587 evstate->timer = timer_new_ns(monitor_get_event_clock(),
588 monitor_qapi_event_handler,
589 evstate);
590 g_hash_table_add(monitor_qapi_event_state, evstate);
591 timer_mod_ns(evstate->timer, now + evconf->rate);
595 qemu_mutex_unlock(&monitor_lock);
598 void qapi_event_emit(QAPIEvent event, QDict *qdict)
601 * monitor_qapi_event_queue_no_reenter() is not reentrant: it
602 * would deadlock on monitor_lock. Work around by queueing
603 * events in thread-local storage.
604 * TODO: remove this, make it re-enter safe.
606 typedef struct MonitorQapiEvent {
607 QAPIEvent event;
608 QDict *qdict;
609 QSIMPLEQ_ENTRY(MonitorQapiEvent) entry;
610 } MonitorQapiEvent;
611 static __thread QSIMPLEQ_HEAD(, MonitorQapiEvent) event_queue;
612 static __thread bool reentered;
613 MonitorQapiEvent *ev;
615 if (!reentered) {
616 QSIMPLEQ_INIT(&event_queue);
619 ev = g_new(MonitorQapiEvent, 1);
620 ev->qdict = qobject_ref(qdict);
621 ev->event = event;
622 QSIMPLEQ_INSERT_TAIL(&event_queue, ev, entry);
623 if (reentered) {
624 return;
627 reentered = true;
629 while ((ev = QSIMPLEQ_FIRST(&event_queue)) != NULL) {
630 QSIMPLEQ_REMOVE_HEAD(&event_queue, entry);
631 monitor_qapi_event_queue_no_reenter(ev->event, ev->qdict);
632 qobject_unref(ev->qdict);
633 g_free(ev);
636 reentered = false;
640 * This function runs evconf->rate ns after sending a throttled
641 * event.
642 * If another event has since been stored, send it.
644 static void monitor_qapi_event_handler(void *opaque)
646 MonitorQAPIEventState *evstate = opaque;
647 MonitorQAPIEventConf *evconf = &monitor_qapi_event_conf[evstate->event];
649 trace_monitor_protocol_event_handler(evstate->event, evstate->qdict);
650 qemu_mutex_lock(&monitor_lock);
652 if (evstate->qdict) {
653 int64_t now = qemu_clock_get_ns(monitor_get_event_clock());
655 monitor_qapi_event_emit(evstate->event, evstate->qdict);
656 qobject_unref(evstate->qdict);
657 evstate->qdict = NULL;
658 timer_mod_ns(evstate->timer, now + evconf->rate);
659 } else {
660 g_hash_table_remove(monitor_qapi_event_state, evstate);
661 qobject_unref(evstate->data);
662 timer_free(evstate->timer);
663 g_free(evstate);
666 qemu_mutex_unlock(&monitor_lock);
669 static unsigned int qapi_event_throttle_hash(const void *key)
671 const MonitorQAPIEventState *evstate = key;
672 unsigned int hash = evstate->event * 255;
674 if (evstate->event == QAPI_EVENT_VSERPORT_CHANGE) {
675 hash += g_str_hash(qdict_get_str(evstate->data, "id"));
678 if (evstate->event == QAPI_EVENT_QUORUM_REPORT_BAD) {
679 hash += g_str_hash(qdict_get_str(evstate->data, "node-name"));
682 return hash;
685 static gboolean qapi_event_throttle_equal(const void *a, const void *b)
687 const MonitorQAPIEventState *eva = a;
688 const MonitorQAPIEventState *evb = b;
690 if (eva->event != evb->event) {
691 return FALSE;
694 if (eva->event == QAPI_EVENT_VSERPORT_CHANGE) {
695 return !strcmp(qdict_get_str(eva->data, "id"),
696 qdict_get_str(evb->data, "id"));
699 if (eva->event == QAPI_EVENT_QUORUM_REPORT_BAD) {
700 return !strcmp(qdict_get_str(eva->data, "node-name"),
701 qdict_get_str(evb->data, "node-name"));
704 return TRUE;
707 static void monitor_qapi_event_init(void)
709 monitor_qapi_event_state = g_hash_table_new(qapi_event_throttle_hash,
710 qapi_event_throttle_equal);
713 static void handle_hmp_command(MonitorHMP *mon, const char *cmdline);
715 static void monitor_iothread_init(void);
717 static void monitor_data_init(Monitor *mon, int flags, bool skip_flush,
718 bool use_io_thread)
720 if (use_io_thread && !mon_iothread) {
721 monitor_iothread_init();
723 qemu_mutex_init(&mon->mon_lock);
724 mon->outbuf = qstring_new();
725 /* Use *mon_cmds by default. */
726 mon->cmd_table = mon_cmds;
727 mon->skip_flush = skip_flush;
728 mon->use_io_thread = use_io_thread;
729 mon->flags = flags;
732 static void monitor_data_destroy_qmp(MonitorQMP *mon)
734 json_message_parser_destroy(&mon->parser);
735 qemu_mutex_destroy(&mon->qmp_queue_lock);
736 monitor_qmp_cleanup_req_queue_locked(mon);
737 g_queue_free(mon->qmp_requests);
740 static void monitor_data_destroy(Monitor *mon)
742 g_free(mon->mon_cpu_path);
743 qemu_chr_fe_deinit(&mon->chr, false);
744 if (monitor_is_qmp(mon)) {
745 monitor_data_destroy_qmp(container_of(mon, MonitorQMP, common));
746 } else {
747 readline_free(container_of(mon, MonitorHMP, common)->rs);
749 qobject_unref(mon->outbuf);
750 qemu_mutex_destroy(&mon->mon_lock);
753 char *qmp_human_monitor_command(const char *command_line, bool has_cpu_index,
754 int64_t cpu_index, Error **errp)
756 char *output = NULL;
757 Monitor *old_mon;
758 MonitorHMP hmp = {};
760 monitor_data_init(&hmp.common, 0, true, false);
762 old_mon = cur_mon;
763 cur_mon = &hmp.common;
765 if (has_cpu_index) {
766 int ret = monitor_set_cpu(cpu_index);
767 if (ret < 0) {
768 cur_mon = old_mon;
769 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cpu-index",
770 "a CPU number");
771 goto out;
775 handle_hmp_command(&hmp, command_line);
776 cur_mon = old_mon;
778 qemu_mutex_lock(&hmp.common.mon_lock);
779 if (qstring_get_length(hmp.common.outbuf) > 0) {
780 output = g_strdup(qstring_get_str(hmp.common.outbuf));
781 } else {
782 output = g_strdup("");
784 qemu_mutex_unlock(&hmp.common.mon_lock);
786 out:
787 monitor_data_destroy(&hmp.common);
788 return output;
791 static int compare_cmd(const char *name, const char *list)
793 const char *p, *pstart;
794 int len;
795 len = strlen(name);
796 p = list;
797 for(;;) {
798 pstart = p;
799 p = qemu_strchrnul(p, '|');
800 if ((p - pstart) == len && !memcmp(pstart, name, len))
801 return 1;
802 if (*p == '\0')
803 break;
804 p++;
806 return 0;
809 static int get_str(char *buf, int buf_size, const char **pp)
811 const char *p;
812 char *q;
813 int c;
815 q = buf;
816 p = *pp;
817 while (qemu_isspace(*p)) {
818 p++;
820 if (*p == '\0') {
821 fail:
822 *q = '\0';
823 *pp = p;
824 return -1;
826 if (*p == '\"') {
827 p++;
828 while (*p != '\0' && *p != '\"') {
829 if (*p == '\\') {
830 p++;
831 c = *p++;
832 switch (c) {
833 case 'n':
834 c = '\n';
835 break;
836 case 'r':
837 c = '\r';
838 break;
839 case '\\':
840 case '\'':
841 case '\"':
842 break;
843 default:
844 printf("unsupported escape code: '\\%c'\n", c);
845 goto fail;
847 if ((q - buf) < buf_size - 1) {
848 *q++ = c;
850 } else {
851 if ((q - buf) < buf_size - 1) {
852 *q++ = *p;
854 p++;
857 if (*p != '\"') {
858 printf("unterminated string\n");
859 goto fail;
861 p++;
862 } else {
863 while (*p != '\0' && !qemu_isspace(*p)) {
864 if ((q - buf) < buf_size - 1) {
865 *q++ = *p;
867 p++;
870 *q = '\0';
871 *pp = p;
872 return 0;
875 #define MAX_ARGS 16
877 static void free_cmdline_args(char **args, int nb_args)
879 int i;
881 assert(nb_args <= MAX_ARGS);
883 for (i = 0; i < nb_args; i++) {
884 g_free(args[i]);
890 * Parse the command line to get valid args.
891 * @cmdline: command line to be parsed.
892 * @pnb_args: location to store the number of args, must NOT be NULL.
893 * @args: location to store the args, which should be freed by caller, must
894 * NOT be NULL.
896 * Returns 0 on success, negative on failure.
898 * NOTE: this parser is an approximate form of the real command parser. Number
899 * of args have a limit of MAX_ARGS. If cmdline contains more, it will
900 * return with failure.
902 static int parse_cmdline(const char *cmdline,
903 int *pnb_args, char **args)
905 const char *p;
906 int nb_args, ret;
907 char buf[1024];
909 p = cmdline;
910 nb_args = 0;
911 for (;;) {
912 while (qemu_isspace(*p)) {
913 p++;
915 if (*p == '\0') {
916 break;
918 if (nb_args >= MAX_ARGS) {
919 goto fail;
921 ret = get_str(buf, sizeof(buf), &p);
922 if (ret < 0) {
923 goto fail;
925 args[nb_args] = g_strdup(buf);
926 nb_args++;
928 *pnb_args = nb_args;
929 return 0;
931 fail:
932 free_cmdline_args(args, nb_args);
933 return -1;
937 * Can command @cmd be executed in preconfig state?
939 static bool cmd_can_preconfig(const mon_cmd_t *cmd)
941 if (!cmd->flags) {
942 return false;
945 return strchr(cmd->flags, 'p');
948 static void help_cmd_dump_one(Monitor *mon,
949 const mon_cmd_t *cmd,
950 char **prefix_args,
951 int prefix_args_nb)
953 int i;
955 if (runstate_check(RUN_STATE_PRECONFIG) && !cmd_can_preconfig(cmd)) {
956 return;
959 for (i = 0; i < prefix_args_nb; i++) {
960 monitor_printf(mon, "%s ", prefix_args[i]);
962 monitor_printf(mon, "%s %s -- %s\n", cmd->name, cmd->params, cmd->help);
965 /* @args[@arg_index] is the valid command need to find in @cmds */
966 static void help_cmd_dump(Monitor *mon, const mon_cmd_t *cmds,
967 char **args, int nb_args, int arg_index)
969 const mon_cmd_t *cmd;
970 size_t i;
972 /* No valid arg need to compare with, dump all in *cmds */
973 if (arg_index >= nb_args) {
974 for (cmd = cmds; cmd->name != NULL; cmd++) {
975 help_cmd_dump_one(mon, cmd, args, arg_index);
977 return;
980 /* Find one entry to dump */
981 for (cmd = cmds; cmd->name != NULL; cmd++) {
982 if (compare_cmd(args[arg_index], cmd->name) &&
983 ((!runstate_check(RUN_STATE_PRECONFIG) ||
984 cmd_can_preconfig(cmd)))) {
985 if (cmd->sub_table) {
986 /* continue with next arg */
987 help_cmd_dump(mon, cmd->sub_table,
988 args, nb_args, arg_index + 1);
989 } else {
990 help_cmd_dump_one(mon, cmd, args, arg_index);
992 return;
996 /* Command not found */
997 monitor_printf(mon, "unknown command: '");
998 for (i = 0; i <= arg_index; i++) {
999 monitor_printf(mon, "%s%s", args[i], i == arg_index ? "'\n" : " ");
1003 static void help_cmd(Monitor *mon, const char *name)
1005 char *args[MAX_ARGS];
1006 int nb_args = 0;
1008 /* 1. parse user input */
1009 if (name) {
1010 /* special case for log, directly dump and return */
1011 if (!strcmp(name, "log")) {
1012 const QEMULogItem *item;
1013 monitor_printf(mon, "Log items (comma separated):\n");
1014 monitor_printf(mon, "%-10s %s\n", "none", "remove all logs");
1015 for (item = qemu_log_items; item->mask != 0; item++) {
1016 monitor_printf(mon, "%-10s %s\n", item->name, item->help);
1018 return;
1021 if (parse_cmdline(name, &nb_args, args) < 0) {
1022 return;
1026 /* 2. dump the contents according to parsed args */
1027 help_cmd_dump(mon, mon->cmd_table, args, nb_args, 0);
1029 free_cmdline_args(args, nb_args);
1032 static void do_help_cmd(Monitor *mon, const QDict *qdict)
1034 help_cmd(mon, qdict_get_try_str(qdict, "name"));
1037 static void hmp_trace_event(Monitor *mon, const QDict *qdict)
1039 const char *tp_name = qdict_get_str(qdict, "name");
1040 bool new_state = qdict_get_bool(qdict, "option");
1041 bool has_vcpu = qdict_haskey(qdict, "vcpu");
1042 int vcpu = qdict_get_try_int(qdict, "vcpu", 0);
1043 Error *local_err = NULL;
1045 if (vcpu < 0) {
1046 monitor_printf(mon, "argument vcpu must be positive");
1047 return;
1050 qmp_trace_event_set_state(tp_name, new_state, true, true, has_vcpu, vcpu, &local_err);
1051 if (local_err) {
1052 error_report_err(local_err);
1056 #ifdef CONFIG_TRACE_SIMPLE
1057 static void hmp_trace_file(Monitor *mon, const QDict *qdict)
1059 const char *op = qdict_get_try_str(qdict, "op");
1060 const char *arg = qdict_get_try_str(qdict, "arg");
1062 if (!op) {
1063 st_print_trace_file_status();
1064 } else if (!strcmp(op, "on")) {
1065 st_set_trace_file_enabled(true);
1066 } else if (!strcmp(op, "off")) {
1067 st_set_trace_file_enabled(false);
1068 } else if (!strcmp(op, "flush")) {
1069 st_flush_trace_buffer();
1070 } else if (!strcmp(op, "set")) {
1071 if (arg) {
1072 st_set_trace_file(arg);
1074 } else {
1075 monitor_printf(mon, "unexpected argument \"%s\"\n", op);
1076 help_cmd(mon, "trace-file");
1079 #endif
1081 static void hmp_info_help(Monitor *mon, const QDict *qdict)
1083 help_cmd(mon, "info");
1086 static void query_commands_cb(QmpCommand *cmd, void *opaque)
1088 CommandInfoList *info, **list = opaque;
1090 if (!cmd->enabled) {
1091 return;
1094 info = g_malloc0(sizeof(*info));
1095 info->value = g_malloc0(sizeof(*info->value));
1096 info->value->name = g_strdup(cmd->name);
1097 info->next = *list;
1098 *list = info;
1101 CommandInfoList *qmp_query_commands(Error **errp)
1103 CommandInfoList *list = NULL;
1104 MonitorQMP *mon;
1106 assert(monitor_is_qmp(cur_mon));
1107 mon = container_of(cur_mon, MonitorQMP, common);
1109 qmp_for_each_command(mon->commands, query_commands_cb, &list);
1111 return list;
1114 EventInfoList *qmp_query_events(Error **errp)
1117 * TODO This deprecated command is the only user of
1118 * QAPIEvent_str() and QAPIEvent_lookup[]. When the command goes,
1119 * they should go, too.
1121 EventInfoList *info, *ev_list = NULL;
1122 QAPIEvent e;
1124 for (e = 0 ; e < QAPI_EVENT__MAX ; e++) {
1125 const char *event_name = QAPIEvent_str(e);
1126 assert(event_name != NULL);
1127 info = g_malloc0(sizeof(*info));
1128 info->value = g_malloc0(sizeof(*info->value));
1129 info->value->name = g_strdup(event_name);
1131 info->next = ev_list;
1132 ev_list = info;
1135 return ev_list;
1139 * Minor hack: generated marshalling suppressed for this command
1140 * ('gen': false in the schema) so we can parse the JSON string
1141 * directly into QObject instead of first parsing it with
1142 * visit_type_SchemaInfoList() into a SchemaInfoList, then marshal it
1143 * to QObject with generated output marshallers, every time. Instead,
1144 * we do it in test-qobject-input-visitor.c, just to make sure
1145 * qapi-gen.py's output actually conforms to the schema.
1147 static void qmp_query_qmp_schema(QDict *qdict, QObject **ret_data,
1148 Error **errp)
1150 *ret_data = qobject_from_qlit(&qmp_schema_qlit);
1153 static void monitor_init_qmp_commands(void)
1156 * Two command lists:
1157 * - qmp_commands contains all QMP commands
1158 * - qmp_cap_negotiation_commands contains just
1159 * "qmp_capabilities", to enforce capability negotiation
1162 qmp_init_marshal(&qmp_commands);
1164 qmp_register_command(&qmp_commands, "query-qmp-schema",
1165 qmp_query_qmp_schema, QCO_ALLOW_PRECONFIG);
1166 qmp_register_command(&qmp_commands, "device_add", qmp_device_add,
1167 QCO_NO_OPTIONS);
1168 qmp_register_command(&qmp_commands, "netdev_add", qmp_netdev_add,
1169 QCO_NO_OPTIONS);
1171 QTAILQ_INIT(&qmp_cap_negotiation_commands);
1172 qmp_register_command(&qmp_cap_negotiation_commands, "qmp_capabilities",
1173 qmp_marshal_qmp_capabilities, QCO_ALLOW_PRECONFIG);
1176 static bool qmp_oob_enabled(MonitorQMP *mon)
1178 return mon->capab[QMP_CAPABILITY_OOB];
1181 static void monitor_qmp_caps_reset(MonitorQMP *mon)
1183 memset(mon->capab_offered, 0, sizeof(mon->capab_offered));
1184 memset(mon->capab, 0, sizeof(mon->capab));
1185 mon->capab_offered[QMP_CAPABILITY_OOB] = mon->common.use_io_thread;
1189 * Accept QMP capabilities in @list for @mon.
1190 * On success, set mon->qmp.capab[], and return true.
1191 * On error, set @errp, and return false.
1193 static bool qmp_caps_accept(MonitorQMP *mon, QMPCapabilityList *list,
1194 Error **errp)
1196 GString *unavailable = NULL;
1197 bool capab[QMP_CAPABILITY__MAX];
1199 memset(capab, 0, sizeof(capab));
1201 for (; list; list = list->next) {
1202 if (!mon->capab_offered[list->value]) {
1203 if (!unavailable) {
1204 unavailable = g_string_new(QMPCapability_str(list->value));
1205 } else {
1206 g_string_append_printf(unavailable, ", %s",
1207 QMPCapability_str(list->value));
1210 capab[list->value] = true;
1213 if (unavailable) {
1214 error_setg(errp, "Capability %s not available", unavailable->str);
1215 g_string_free(unavailable, true);
1216 return false;
1219 memcpy(mon->capab, capab, sizeof(capab));
1220 return true;
1223 void qmp_qmp_capabilities(bool has_enable, QMPCapabilityList *enable,
1224 Error **errp)
1226 MonitorQMP *mon;
1228 assert(monitor_is_qmp(cur_mon));
1229 mon = container_of(cur_mon, MonitorQMP, common);
1231 if (mon->commands == &qmp_commands) {
1232 error_set(errp, ERROR_CLASS_COMMAND_NOT_FOUND,
1233 "Capabilities negotiation is already complete, command "
1234 "ignored");
1235 return;
1238 if (!qmp_caps_accept(mon, enable, errp)) {
1239 return;
1242 mon->commands = &qmp_commands;
1245 /* Set the current CPU defined by the user. Callers must hold BQL. */
1246 int monitor_set_cpu(int cpu_index)
1248 CPUState *cpu;
1250 cpu = qemu_get_cpu(cpu_index);
1251 if (cpu == NULL) {
1252 return -1;
1254 g_free(cur_mon->mon_cpu_path);
1255 cur_mon->mon_cpu_path = object_get_canonical_path(OBJECT(cpu));
1256 return 0;
1259 /* Callers must hold BQL. */
1260 static CPUState *mon_get_cpu_sync(bool synchronize)
1262 CPUState *cpu;
1264 if (cur_mon->mon_cpu_path) {
1265 cpu = (CPUState *) object_resolve_path_type(cur_mon->mon_cpu_path,
1266 TYPE_CPU, NULL);
1267 if (!cpu) {
1268 g_free(cur_mon->mon_cpu_path);
1269 cur_mon->mon_cpu_path = NULL;
1272 if (!cur_mon->mon_cpu_path) {
1273 if (!first_cpu) {
1274 return NULL;
1276 monitor_set_cpu(first_cpu->cpu_index);
1277 cpu = first_cpu;
1279 if (synchronize) {
1280 cpu_synchronize_state(cpu);
1282 return cpu;
1285 CPUState *mon_get_cpu(void)
1287 return mon_get_cpu_sync(true);
1290 CPUArchState *mon_get_cpu_env(void)
1292 CPUState *cs = mon_get_cpu();
1294 return cs ? cs->env_ptr : NULL;
1297 int monitor_get_cpu_index(void)
1299 CPUState *cs = mon_get_cpu_sync(false);
1301 return cs ? cs->cpu_index : UNASSIGNED_CPU_INDEX;
1304 static void hmp_info_registers(Monitor *mon, const QDict *qdict)
1306 bool all_cpus = qdict_get_try_bool(qdict, "cpustate_all", false);
1307 CPUState *cs;
1309 if (all_cpus) {
1310 CPU_FOREACH(cs) {
1311 monitor_printf(mon, "\nCPU#%d\n", cs->cpu_index);
1312 cpu_dump_state(cs, NULL, CPU_DUMP_FPU);
1314 } else {
1315 cs = mon_get_cpu();
1317 if (!cs) {
1318 monitor_printf(mon, "No CPU available\n");
1319 return;
1322 cpu_dump_state(cs, NULL, CPU_DUMP_FPU);
1326 #ifdef CONFIG_TCG
1327 static void hmp_info_jit(Monitor *mon, const QDict *qdict)
1329 if (!tcg_enabled()) {
1330 error_report("JIT information is only available with accel=tcg");
1331 return;
1334 dump_exec_info();
1335 dump_drift_info();
1338 static void hmp_info_opcount(Monitor *mon, const QDict *qdict)
1340 dump_opcount_info();
1342 #endif
1344 static void hmp_info_sync_profile(Monitor *mon, const QDict *qdict)
1346 int64_t max = qdict_get_try_int(qdict, "max", 10);
1347 bool mean = qdict_get_try_bool(qdict, "mean", false);
1348 bool coalesce = !qdict_get_try_bool(qdict, "no_coalesce", false);
1349 enum QSPSortBy sort_by;
1351 sort_by = mean ? QSP_SORT_BY_AVG_WAIT_TIME : QSP_SORT_BY_TOTAL_WAIT_TIME;
1352 qsp_report(max, sort_by, coalesce);
1355 static void hmp_info_history(Monitor *mon, const QDict *qdict)
1357 MonitorHMP *hmp_mon = container_of(mon, MonitorHMP, common);
1358 int i;
1359 const char *str;
1361 if (!hmp_mon->rs) {
1362 return;
1364 i = 0;
1365 for(;;) {
1366 str = readline_get_history(hmp_mon->rs, i);
1367 if (!str) {
1368 break;
1370 monitor_printf(mon, "%d: '%s'\n", i, str);
1371 i++;
1375 static void hmp_info_cpustats(Monitor *mon, const QDict *qdict)
1377 CPUState *cs = mon_get_cpu();
1379 if (!cs) {
1380 monitor_printf(mon, "No CPU available\n");
1381 return;
1383 cpu_dump_statistics(cs, 0);
1386 static void hmp_info_trace_events(Monitor *mon, const QDict *qdict)
1388 const char *name = qdict_get_try_str(qdict, "name");
1389 bool has_vcpu = qdict_haskey(qdict, "vcpu");
1390 int vcpu = qdict_get_try_int(qdict, "vcpu", 0);
1391 TraceEventInfoList *events;
1392 TraceEventInfoList *elem;
1393 Error *local_err = NULL;
1395 if (name == NULL) {
1396 name = "*";
1398 if (vcpu < 0) {
1399 monitor_printf(mon, "argument vcpu must be positive");
1400 return;
1403 events = qmp_trace_event_get_state(name, has_vcpu, vcpu, &local_err);
1404 if (local_err) {
1405 error_report_err(local_err);
1406 return;
1409 for (elem = events; elem != NULL; elem = elem->next) {
1410 monitor_printf(mon, "%s : state %u\n",
1411 elem->value->name,
1412 elem->value->state == TRACE_EVENT_STATE_ENABLED ? 1 : 0);
1414 qapi_free_TraceEventInfoList(events);
1417 void qmp_client_migrate_info(const char *protocol, const char *hostname,
1418 bool has_port, int64_t port,
1419 bool has_tls_port, int64_t tls_port,
1420 bool has_cert_subject, const char *cert_subject,
1421 Error **errp)
1423 if (strcmp(protocol, "spice") == 0) {
1424 if (!qemu_using_spice(errp)) {
1425 return;
1428 if (!has_port && !has_tls_port) {
1429 error_setg(errp, QERR_MISSING_PARAMETER, "port/tls-port");
1430 return;
1433 if (qemu_spice_migrate_info(hostname,
1434 has_port ? port : -1,
1435 has_tls_port ? tls_port : -1,
1436 cert_subject)) {
1437 error_setg(errp, QERR_UNDEFINED_ERROR);
1438 return;
1440 return;
1443 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "protocol", "spice");
1446 static void hmp_logfile(Monitor *mon, const QDict *qdict)
1448 Error *err = NULL;
1450 qemu_set_log_filename(qdict_get_str(qdict, "filename"), &err);
1451 if (err) {
1452 error_report_err(err);
1456 static void hmp_log(Monitor *mon, const QDict *qdict)
1458 int mask;
1459 const char *items = qdict_get_str(qdict, "items");
1461 if (!strcmp(items, "none")) {
1462 mask = 0;
1463 } else {
1464 mask = qemu_str_to_log_mask(items);
1465 if (!mask) {
1466 help_cmd(mon, "log");
1467 return;
1470 qemu_set_log(mask);
1473 static void hmp_singlestep(Monitor *mon, const QDict *qdict)
1475 const char *option = qdict_get_try_str(qdict, "option");
1476 if (!option || !strcmp(option, "on")) {
1477 singlestep = 1;
1478 } else if (!strcmp(option, "off")) {
1479 singlestep = 0;
1480 } else {
1481 monitor_printf(mon, "unexpected option %s\n", option);
1485 static void hmp_gdbserver(Monitor *mon, const QDict *qdict)
1487 const char *device = qdict_get_try_str(qdict, "device");
1488 if (!device)
1489 device = "tcp::" DEFAULT_GDBSTUB_PORT;
1490 if (gdbserver_start(device) < 0) {
1491 monitor_printf(mon, "Could not open gdbserver on device '%s'\n",
1492 device);
1493 } else if (strcmp(device, "none") == 0) {
1494 monitor_printf(mon, "Disabled gdbserver\n");
1495 } else {
1496 monitor_printf(mon, "Waiting for gdb connection on device '%s'\n",
1497 device);
1501 static void hmp_watchdog_action(Monitor *mon, const QDict *qdict)
1503 const char *action = qdict_get_str(qdict, "action");
1504 if (select_watchdog_action(action) == -1) {
1505 monitor_printf(mon, "Unknown watchdog action '%s'\n", action);
1509 static void monitor_printc(Monitor *mon, int c)
1511 monitor_printf(mon, "'");
1512 switch(c) {
1513 case '\'':
1514 monitor_printf(mon, "\\'");
1515 break;
1516 case '\\':
1517 monitor_printf(mon, "\\\\");
1518 break;
1519 case '\n':
1520 monitor_printf(mon, "\\n");
1521 break;
1522 case '\r':
1523 monitor_printf(mon, "\\r");
1524 break;
1525 default:
1526 if (c >= 32 && c <= 126) {
1527 monitor_printf(mon, "%c", c);
1528 } else {
1529 monitor_printf(mon, "\\x%02x", c);
1531 break;
1533 monitor_printf(mon, "'");
1536 static void memory_dump(Monitor *mon, int count, int format, int wsize,
1537 hwaddr addr, int is_physical)
1539 int l, line_size, i, max_digits, len;
1540 uint8_t buf[16];
1541 uint64_t v;
1542 CPUState *cs = mon_get_cpu();
1544 if (!cs && (format == 'i' || !is_physical)) {
1545 monitor_printf(mon, "Can not dump without CPU\n");
1546 return;
1549 if (format == 'i') {
1550 monitor_disas(mon, cs, addr, count, is_physical);
1551 return;
1554 len = wsize * count;
1555 if (wsize == 1)
1556 line_size = 8;
1557 else
1558 line_size = 16;
1559 max_digits = 0;
1561 switch(format) {
1562 case 'o':
1563 max_digits = DIV_ROUND_UP(wsize * 8, 3);
1564 break;
1565 default:
1566 case 'x':
1567 max_digits = (wsize * 8) / 4;
1568 break;
1569 case 'u':
1570 case 'd':
1571 max_digits = DIV_ROUND_UP(wsize * 8 * 10, 33);
1572 break;
1573 case 'c':
1574 wsize = 1;
1575 break;
1578 while (len > 0) {
1579 if (is_physical)
1580 monitor_printf(mon, TARGET_FMT_plx ":", addr);
1581 else
1582 monitor_printf(mon, TARGET_FMT_lx ":", (target_ulong)addr);
1583 l = len;
1584 if (l > line_size)
1585 l = line_size;
1586 if (is_physical) {
1587 AddressSpace *as = cs ? cs->as : &address_space_memory;
1588 MemTxResult r = address_space_read(as, addr,
1589 MEMTXATTRS_UNSPECIFIED, buf, l);
1590 if (r != MEMTX_OK) {
1591 monitor_printf(mon, " Cannot access memory\n");
1592 break;
1594 } else {
1595 if (cpu_memory_rw_debug(cs, addr, buf, l, 0) < 0) {
1596 monitor_printf(mon, " Cannot access memory\n");
1597 break;
1600 i = 0;
1601 while (i < l) {
1602 switch(wsize) {
1603 default:
1604 case 1:
1605 v = ldub_p(buf + i);
1606 break;
1607 case 2:
1608 v = lduw_p(buf + i);
1609 break;
1610 case 4:
1611 v = (uint32_t)ldl_p(buf + i);
1612 break;
1613 case 8:
1614 v = ldq_p(buf + i);
1615 break;
1617 monitor_printf(mon, " ");
1618 switch(format) {
1619 case 'o':
1620 monitor_printf(mon, "%#*" PRIo64, max_digits, v);
1621 break;
1622 case 'x':
1623 monitor_printf(mon, "0x%0*" PRIx64, max_digits, v);
1624 break;
1625 case 'u':
1626 monitor_printf(mon, "%*" PRIu64, max_digits, v);
1627 break;
1628 case 'd':
1629 monitor_printf(mon, "%*" PRId64, max_digits, v);
1630 break;
1631 case 'c':
1632 monitor_printc(mon, v);
1633 break;
1635 i += wsize;
1637 monitor_printf(mon, "\n");
1638 addr += l;
1639 len -= l;
1643 static void hmp_memory_dump(Monitor *mon, const QDict *qdict)
1645 int count = qdict_get_int(qdict, "count");
1646 int format = qdict_get_int(qdict, "format");
1647 int size = qdict_get_int(qdict, "size");
1648 target_long addr = qdict_get_int(qdict, "addr");
1650 memory_dump(mon, count, format, size, addr, 0);
1653 static void hmp_physical_memory_dump(Monitor *mon, const QDict *qdict)
1655 int count = qdict_get_int(qdict, "count");
1656 int format = qdict_get_int(qdict, "format");
1657 int size = qdict_get_int(qdict, "size");
1658 hwaddr addr = qdict_get_int(qdict, "addr");
1660 memory_dump(mon, count, format, size, addr, 1);
1663 static void *gpa2hva(MemoryRegion **p_mr, hwaddr addr, Error **errp)
1665 MemoryRegionSection mrs = memory_region_find(get_system_memory(),
1666 addr, 1);
1668 if (!mrs.mr) {
1669 error_setg(errp, "No memory is mapped at address 0x%" HWADDR_PRIx, addr);
1670 return NULL;
1673 if (!memory_region_is_ram(mrs.mr) && !memory_region_is_romd(mrs.mr)) {
1674 error_setg(errp, "Memory at address 0x%" HWADDR_PRIx "is not RAM", addr);
1675 memory_region_unref(mrs.mr);
1676 return NULL;
1679 *p_mr = mrs.mr;
1680 return qemu_map_ram_ptr(mrs.mr->ram_block, mrs.offset_within_region);
1683 static void hmp_gpa2hva(Monitor *mon, const QDict *qdict)
1685 hwaddr addr = qdict_get_int(qdict, "addr");
1686 Error *local_err = NULL;
1687 MemoryRegion *mr = NULL;
1688 void *ptr;
1690 ptr = gpa2hva(&mr, addr, &local_err);
1691 if (local_err) {
1692 error_report_err(local_err);
1693 return;
1696 monitor_printf(mon, "Host virtual address for 0x%" HWADDR_PRIx
1697 " (%s) is %p\n",
1698 addr, mr->name, ptr);
1700 memory_region_unref(mr);
1703 static void hmp_gva2gpa(Monitor *mon, const QDict *qdict)
1705 target_ulong addr = qdict_get_int(qdict, "addr");
1706 MemTxAttrs attrs;
1707 CPUState *cs = mon_get_cpu();
1708 hwaddr gpa;
1710 if (!cs) {
1711 monitor_printf(mon, "No cpu\n");
1712 return;
1715 gpa = cpu_get_phys_page_attrs_debug(cs, addr & TARGET_PAGE_MASK, &attrs);
1716 if (gpa == -1) {
1717 monitor_printf(mon, "Unmapped\n");
1718 } else {
1719 monitor_printf(mon, "gpa: %#" HWADDR_PRIx "\n",
1720 gpa + (addr & ~TARGET_PAGE_MASK));
1724 #ifdef CONFIG_LINUX
1725 static uint64_t vtop(void *ptr, Error **errp)
1727 uint64_t pinfo;
1728 uint64_t ret = -1;
1729 uintptr_t addr = (uintptr_t) ptr;
1730 uintptr_t pagesize = getpagesize();
1731 off_t offset = addr / pagesize * sizeof(pinfo);
1732 int fd;
1734 fd = open("/proc/self/pagemap", O_RDONLY);
1735 if (fd == -1) {
1736 error_setg_errno(errp, errno, "Cannot open /proc/self/pagemap");
1737 return -1;
1740 /* Force copy-on-write if necessary. */
1741 atomic_add((uint8_t *)ptr, 0);
1743 if (pread(fd, &pinfo, sizeof(pinfo), offset) != sizeof(pinfo)) {
1744 error_setg_errno(errp, errno, "Cannot read pagemap");
1745 goto out;
1747 if ((pinfo & (1ull << 63)) == 0) {
1748 error_setg(errp, "Page not present");
1749 goto out;
1751 ret = ((pinfo & 0x007fffffffffffffull) * pagesize) | (addr & (pagesize - 1));
1753 out:
1754 close(fd);
1755 return ret;
1758 static void hmp_gpa2hpa(Monitor *mon, const QDict *qdict)
1760 hwaddr addr = qdict_get_int(qdict, "addr");
1761 Error *local_err = NULL;
1762 MemoryRegion *mr = NULL;
1763 void *ptr;
1764 uint64_t physaddr;
1766 ptr = gpa2hva(&mr, addr, &local_err);
1767 if (local_err) {
1768 error_report_err(local_err);
1769 return;
1772 physaddr = vtop(ptr, &local_err);
1773 if (local_err) {
1774 error_report_err(local_err);
1775 } else {
1776 monitor_printf(mon, "Host physical address for 0x%" HWADDR_PRIx
1777 " (%s) is 0x%" PRIx64 "\n",
1778 addr, mr->name, (uint64_t) physaddr);
1781 memory_region_unref(mr);
1783 #endif
1785 static void do_print(Monitor *mon, const QDict *qdict)
1787 int format = qdict_get_int(qdict, "format");
1788 hwaddr val = qdict_get_int(qdict, "val");
1790 switch(format) {
1791 case 'o':
1792 monitor_printf(mon, "%#" HWADDR_PRIo, val);
1793 break;
1794 case 'x':
1795 monitor_printf(mon, "%#" HWADDR_PRIx, val);
1796 break;
1797 case 'u':
1798 monitor_printf(mon, "%" HWADDR_PRIu, val);
1799 break;
1800 default:
1801 case 'd':
1802 monitor_printf(mon, "%" HWADDR_PRId, val);
1803 break;
1804 case 'c':
1805 monitor_printc(mon, val);
1806 break;
1808 monitor_printf(mon, "\n");
1811 static void hmp_sum(Monitor *mon, const QDict *qdict)
1813 uint32_t addr;
1814 uint16_t sum;
1815 uint32_t start = qdict_get_int(qdict, "start");
1816 uint32_t size = qdict_get_int(qdict, "size");
1818 sum = 0;
1819 for(addr = start; addr < (start + size); addr++) {
1820 uint8_t val = address_space_ldub(&address_space_memory, addr,
1821 MEMTXATTRS_UNSPECIFIED, NULL);
1822 /* BSD sum algorithm ('sum' Unix command) */
1823 sum = (sum >> 1) | (sum << 15);
1824 sum += val;
1826 monitor_printf(mon, "%05d\n", sum);
1829 static int mouse_button_state;
1831 static void hmp_mouse_move(Monitor *mon, const QDict *qdict)
1833 int dx, dy, dz, button;
1834 const char *dx_str = qdict_get_str(qdict, "dx_str");
1835 const char *dy_str = qdict_get_str(qdict, "dy_str");
1836 const char *dz_str = qdict_get_try_str(qdict, "dz_str");
1838 dx = strtol(dx_str, NULL, 0);
1839 dy = strtol(dy_str, NULL, 0);
1840 qemu_input_queue_rel(NULL, INPUT_AXIS_X, dx);
1841 qemu_input_queue_rel(NULL, INPUT_AXIS_Y, dy);
1843 if (dz_str) {
1844 dz = strtol(dz_str, NULL, 0);
1845 if (dz != 0) {
1846 button = (dz > 0) ? INPUT_BUTTON_WHEEL_UP : INPUT_BUTTON_WHEEL_DOWN;
1847 qemu_input_queue_btn(NULL, button, true);
1848 qemu_input_event_sync();
1849 qemu_input_queue_btn(NULL, button, false);
1852 qemu_input_event_sync();
1855 static void hmp_mouse_button(Monitor *mon, const QDict *qdict)
1857 static uint32_t bmap[INPUT_BUTTON__MAX] = {
1858 [INPUT_BUTTON_LEFT] = MOUSE_EVENT_LBUTTON,
1859 [INPUT_BUTTON_MIDDLE] = MOUSE_EVENT_MBUTTON,
1860 [INPUT_BUTTON_RIGHT] = MOUSE_EVENT_RBUTTON,
1862 int button_state = qdict_get_int(qdict, "button_state");
1864 if (mouse_button_state == button_state) {
1865 return;
1867 qemu_input_update_buttons(NULL, bmap, mouse_button_state, button_state);
1868 qemu_input_event_sync();
1869 mouse_button_state = button_state;
1872 static void hmp_ioport_read(Monitor *mon, const QDict *qdict)
1874 int size = qdict_get_int(qdict, "size");
1875 int addr = qdict_get_int(qdict, "addr");
1876 int has_index = qdict_haskey(qdict, "index");
1877 uint32_t val;
1878 int suffix;
1880 if (has_index) {
1881 int index = qdict_get_int(qdict, "index");
1882 cpu_outb(addr & IOPORTS_MASK, index & 0xff);
1883 addr++;
1885 addr &= 0xffff;
1887 switch(size) {
1888 default:
1889 case 1:
1890 val = cpu_inb(addr);
1891 suffix = 'b';
1892 break;
1893 case 2:
1894 val = cpu_inw(addr);
1895 suffix = 'w';
1896 break;
1897 case 4:
1898 val = cpu_inl(addr);
1899 suffix = 'l';
1900 break;
1902 monitor_printf(mon, "port%c[0x%04x] = %#0*x\n",
1903 suffix, addr, size * 2, val);
1906 static void hmp_ioport_write(Monitor *mon, const QDict *qdict)
1908 int size = qdict_get_int(qdict, "size");
1909 int addr = qdict_get_int(qdict, "addr");
1910 int val = qdict_get_int(qdict, "val");
1912 addr &= IOPORTS_MASK;
1914 switch (size) {
1915 default:
1916 case 1:
1917 cpu_outb(addr, val);
1918 break;
1919 case 2:
1920 cpu_outw(addr, val);
1921 break;
1922 case 4:
1923 cpu_outl(addr, val);
1924 break;
1928 static void hmp_boot_set(Monitor *mon, const QDict *qdict)
1930 Error *local_err = NULL;
1931 const char *bootdevice = qdict_get_str(qdict, "bootdevice");
1933 qemu_boot_set(bootdevice, &local_err);
1934 if (local_err) {
1935 error_report_err(local_err);
1936 } else {
1937 monitor_printf(mon, "boot device list now set to %s\n", bootdevice);
1941 static void hmp_info_mtree(Monitor *mon, const QDict *qdict)
1943 bool flatview = qdict_get_try_bool(qdict, "flatview", false);
1944 bool dispatch_tree = qdict_get_try_bool(qdict, "dispatch_tree", false);
1945 bool owner = qdict_get_try_bool(qdict, "owner", false);
1947 mtree_info(flatview, dispatch_tree, owner);
1950 static void hmp_info_numa(Monitor *mon, const QDict *qdict)
1952 int i;
1953 NumaNodeMem *node_mem;
1954 CpuInfoList *cpu_list, *cpu;
1956 cpu_list = qmp_query_cpus(&error_abort);
1957 node_mem = g_new0(NumaNodeMem, nb_numa_nodes);
1959 query_numa_node_mem(node_mem);
1960 monitor_printf(mon, "%d nodes\n", nb_numa_nodes);
1961 for (i = 0; i < nb_numa_nodes; i++) {
1962 monitor_printf(mon, "node %d cpus:", i);
1963 for (cpu = cpu_list; cpu; cpu = cpu->next) {
1964 if (cpu->value->has_props && cpu->value->props->has_node_id &&
1965 cpu->value->props->node_id == i) {
1966 monitor_printf(mon, " %" PRIi64, cpu->value->CPU);
1969 monitor_printf(mon, "\n");
1970 monitor_printf(mon, "node %d size: %" PRId64 " MB\n", i,
1971 node_mem[i].node_mem >> 20);
1972 monitor_printf(mon, "node %d plugged: %" PRId64 " MB\n", i,
1973 node_mem[i].node_plugged_mem >> 20);
1975 qapi_free_CpuInfoList(cpu_list);
1976 g_free(node_mem);
1979 #ifdef CONFIG_PROFILER
1981 int64_t dev_time;
1983 static void hmp_info_profile(Monitor *mon, const QDict *qdict)
1985 static int64_t last_cpu_exec_time;
1986 int64_t cpu_exec_time;
1987 int64_t delta;
1989 cpu_exec_time = tcg_cpu_exec_time();
1990 delta = cpu_exec_time - last_cpu_exec_time;
1992 monitor_printf(mon, "async time %" PRId64 " (%0.3f)\n",
1993 dev_time, dev_time / (double)NANOSECONDS_PER_SECOND);
1994 monitor_printf(mon, "qemu time %" PRId64 " (%0.3f)\n",
1995 delta, delta / (double)NANOSECONDS_PER_SECOND);
1996 last_cpu_exec_time = cpu_exec_time;
1997 dev_time = 0;
1999 #else
2000 static void hmp_info_profile(Monitor *mon, const QDict *qdict)
2002 monitor_printf(mon, "Internal profiler not compiled\n");
2004 #endif
2006 /* Capture support */
2007 static QLIST_HEAD (capture_list_head, CaptureState) capture_head;
2009 static void hmp_info_capture(Monitor *mon, const QDict *qdict)
2011 int i;
2012 CaptureState *s;
2014 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
2015 monitor_printf(mon, "[%d]: ", i);
2016 s->ops.info (s->opaque);
2020 static void hmp_stopcapture(Monitor *mon, const QDict *qdict)
2022 int i;
2023 int n = qdict_get_int(qdict, "n");
2024 CaptureState *s;
2026 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
2027 if (i == n) {
2028 s->ops.destroy (s->opaque);
2029 QLIST_REMOVE (s, entries);
2030 g_free (s);
2031 return;
2036 static void hmp_wavcapture(Monitor *mon, const QDict *qdict)
2038 const char *path = qdict_get_str(qdict, "path");
2039 int has_freq = qdict_haskey(qdict, "freq");
2040 int freq = qdict_get_try_int(qdict, "freq", -1);
2041 int has_bits = qdict_haskey(qdict, "bits");
2042 int bits = qdict_get_try_int(qdict, "bits", -1);
2043 int has_channels = qdict_haskey(qdict, "nchannels");
2044 int nchannels = qdict_get_try_int(qdict, "nchannels", -1);
2045 CaptureState *s;
2047 s = g_malloc0 (sizeof (*s));
2049 freq = has_freq ? freq : 44100;
2050 bits = has_bits ? bits : 16;
2051 nchannels = has_channels ? nchannels : 2;
2053 if (wav_start_capture (s, path, freq, bits, nchannels)) {
2054 monitor_printf(mon, "Failed to add wave capture\n");
2055 g_free (s);
2056 return;
2058 QLIST_INSERT_HEAD (&capture_head, s, entries);
2061 static QAuthZList *find_auth(Monitor *mon, const char *name)
2063 Object *obj;
2064 Object *container;
2066 container = object_get_objects_root();
2067 obj = object_resolve_path_component(container, name);
2068 if (!obj) {
2069 monitor_printf(mon, "acl: unknown list '%s'\n", name);
2070 return NULL;
2073 return QAUTHZ_LIST(obj);
2076 static bool warn_acl;
2077 static void hmp_warn_acl(void)
2079 if (warn_acl) {
2080 return;
2082 error_report("The acl_show, acl_reset, acl_policy, acl_add, acl_remove "
2083 "commands are deprecated with no replacement. Authorization "
2084 "for VNC should be performed using the pluggable QAuthZ "
2085 "objects");
2086 warn_acl = true;
2089 static void hmp_acl_show(Monitor *mon, const QDict *qdict)
2091 const char *aclname = qdict_get_str(qdict, "aclname");
2092 QAuthZList *auth = find_auth(mon, aclname);
2093 QAuthZListRuleList *rules;
2094 size_t i = 0;
2096 hmp_warn_acl();
2098 if (!auth) {
2099 return;
2102 monitor_printf(mon, "policy: %s\n",
2103 QAuthZListPolicy_str(auth->policy));
2105 rules = auth->rules;
2106 while (rules) {
2107 QAuthZListRule *rule = rules->value;
2108 i++;
2109 monitor_printf(mon, "%zu: %s %s\n", i,
2110 QAuthZListPolicy_str(rule->policy),
2111 rule->match);
2112 rules = rules->next;
2116 static void hmp_acl_reset(Monitor *mon, const QDict *qdict)
2118 const char *aclname = qdict_get_str(qdict, "aclname");
2119 QAuthZList *auth = find_auth(mon, aclname);
2121 hmp_warn_acl();
2123 if (!auth) {
2124 return;
2127 auth->policy = QAUTHZ_LIST_POLICY_DENY;
2128 qapi_free_QAuthZListRuleList(auth->rules);
2129 auth->rules = NULL;
2130 monitor_printf(mon, "acl: removed all rules\n");
2133 static void hmp_acl_policy(Monitor *mon, const QDict *qdict)
2135 const char *aclname = qdict_get_str(qdict, "aclname");
2136 const char *policy = qdict_get_str(qdict, "policy");
2137 QAuthZList *auth = find_auth(mon, aclname);
2138 int val;
2139 Error *err = NULL;
2141 hmp_warn_acl();
2143 if (!auth) {
2144 return;
2147 val = qapi_enum_parse(&QAuthZListPolicy_lookup,
2148 policy,
2149 QAUTHZ_LIST_POLICY_DENY,
2150 &err);
2151 if (err) {
2152 error_free(err);
2153 monitor_printf(mon, "acl: unknown policy '%s', "
2154 "expected 'deny' or 'allow'\n", policy);
2155 } else {
2156 auth->policy = val;
2157 if (auth->policy == QAUTHZ_LIST_POLICY_ALLOW) {
2158 monitor_printf(mon, "acl: policy set to 'allow'\n");
2159 } else {
2160 monitor_printf(mon, "acl: policy set to 'deny'\n");
2165 static QAuthZListFormat hmp_acl_get_format(const char *match)
2167 if (strchr(match, '*')) {
2168 return QAUTHZ_LIST_FORMAT_GLOB;
2169 } else {
2170 return QAUTHZ_LIST_FORMAT_EXACT;
2174 static void hmp_acl_add(Monitor *mon, const QDict *qdict)
2176 const char *aclname = qdict_get_str(qdict, "aclname");
2177 const char *match = qdict_get_str(qdict, "match");
2178 const char *policystr = qdict_get_str(qdict, "policy");
2179 int has_index = qdict_haskey(qdict, "index");
2180 int index = qdict_get_try_int(qdict, "index", -1);
2181 QAuthZList *auth = find_auth(mon, aclname);
2182 Error *err = NULL;
2183 QAuthZListPolicy policy;
2184 QAuthZListFormat format;
2185 size_t i = 0;
2187 hmp_warn_acl();
2189 if (!auth) {
2190 return;
2193 policy = qapi_enum_parse(&QAuthZListPolicy_lookup,
2194 policystr,
2195 QAUTHZ_LIST_POLICY_DENY,
2196 &err);
2197 if (err) {
2198 error_free(err);
2199 monitor_printf(mon, "acl: unknown policy '%s', "
2200 "expected 'deny' or 'allow'\n", policystr);
2201 return;
2204 format = hmp_acl_get_format(match);
2206 if (has_index && index == 0) {
2207 monitor_printf(mon, "acl: unable to add acl entry\n");
2208 return;
2211 if (has_index) {
2212 i = qauthz_list_insert_rule(auth, match, policy,
2213 format, index - 1, &err);
2214 } else {
2215 i = qauthz_list_append_rule(auth, match, policy,
2216 format, &err);
2218 if (err) {
2219 monitor_printf(mon, "acl: unable to add rule: %s",
2220 error_get_pretty(err));
2221 error_free(err);
2222 } else {
2223 monitor_printf(mon, "acl: added rule at position %zu\n", i + 1);
2227 static void hmp_acl_remove(Monitor *mon, const QDict *qdict)
2229 const char *aclname = qdict_get_str(qdict, "aclname");
2230 const char *match = qdict_get_str(qdict, "match");
2231 QAuthZList *auth = find_auth(mon, aclname);
2232 ssize_t i = 0;
2234 hmp_warn_acl();
2236 if (!auth) {
2237 return;
2240 i = qauthz_list_delete_rule(auth, match);
2241 if (i >= 0) {
2242 monitor_printf(mon, "acl: removed rule at position %zu\n", i + 1);
2243 } else {
2244 monitor_printf(mon, "acl: no matching acl entry\n");
2248 void qmp_getfd(const char *fdname, Error **errp)
2250 mon_fd_t *monfd;
2251 int fd, tmp_fd;
2253 fd = qemu_chr_fe_get_msgfd(&cur_mon->chr);
2254 if (fd == -1) {
2255 error_setg(errp, QERR_FD_NOT_SUPPLIED);
2256 return;
2259 if (qemu_isdigit(fdname[0])) {
2260 close(fd);
2261 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "fdname",
2262 "a name not starting with a digit");
2263 return;
2266 qemu_mutex_lock(&cur_mon->mon_lock);
2267 QLIST_FOREACH(monfd, &cur_mon->fds, next) {
2268 if (strcmp(monfd->name, fdname) != 0) {
2269 continue;
2272 tmp_fd = monfd->fd;
2273 monfd->fd = fd;
2274 qemu_mutex_unlock(&cur_mon->mon_lock);
2275 /* Make sure close() is outside critical section */
2276 close(tmp_fd);
2277 return;
2280 monfd = g_malloc0(sizeof(mon_fd_t));
2281 monfd->name = g_strdup(fdname);
2282 monfd->fd = fd;
2284 QLIST_INSERT_HEAD(&cur_mon->fds, monfd, next);
2285 qemu_mutex_unlock(&cur_mon->mon_lock);
2288 void qmp_closefd(const char *fdname, Error **errp)
2290 mon_fd_t *monfd;
2291 int tmp_fd;
2293 qemu_mutex_lock(&cur_mon->mon_lock);
2294 QLIST_FOREACH(monfd, &cur_mon->fds, next) {
2295 if (strcmp(monfd->name, fdname) != 0) {
2296 continue;
2299 QLIST_REMOVE(monfd, next);
2300 tmp_fd = monfd->fd;
2301 g_free(monfd->name);
2302 g_free(monfd);
2303 qemu_mutex_unlock(&cur_mon->mon_lock);
2304 /* Make sure close() is outside critical section */
2305 close(tmp_fd);
2306 return;
2309 qemu_mutex_unlock(&cur_mon->mon_lock);
2310 error_setg(errp, QERR_FD_NOT_FOUND, fdname);
2313 int monitor_get_fd(Monitor *mon, const char *fdname, Error **errp)
2315 mon_fd_t *monfd;
2317 qemu_mutex_lock(&mon->mon_lock);
2318 QLIST_FOREACH(monfd, &mon->fds, next) {
2319 int fd;
2321 if (strcmp(monfd->name, fdname) != 0) {
2322 continue;
2325 fd = monfd->fd;
2327 /* caller takes ownership of fd */
2328 QLIST_REMOVE(monfd, next);
2329 g_free(monfd->name);
2330 g_free(monfd);
2331 qemu_mutex_unlock(&mon->mon_lock);
2333 return fd;
2336 qemu_mutex_unlock(&mon->mon_lock);
2337 error_setg(errp, "File descriptor named '%s' has not been found", fdname);
2338 return -1;
2341 static void monitor_fdset_cleanup(MonFdset *mon_fdset)
2343 MonFdsetFd *mon_fdset_fd;
2344 MonFdsetFd *mon_fdset_fd_next;
2346 QLIST_FOREACH_SAFE(mon_fdset_fd, &mon_fdset->fds, next, mon_fdset_fd_next) {
2347 if ((mon_fdset_fd->removed ||
2348 (QLIST_EMPTY(&mon_fdset->dup_fds) && mon_refcount == 0)) &&
2349 runstate_is_running()) {
2350 close(mon_fdset_fd->fd);
2351 g_free(mon_fdset_fd->opaque);
2352 QLIST_REMOVE(mon_fdset_fd, next);
2353 g_free(mon_fdset_fd);
2357 if (QLIST_EMPTY(&mon_fdset->fds) && QLIST_EMPTY(&mon_fdset->dup_fds)) {
2358 QLIST_REMOVE(mon_fdset, next);
2359 g_free(mon_fdset);
2363 static void monitor_fdsets_cleanup(void)
2365 MonFdset *mon_fdset;
2366 MonFdset *mon_fdset_next;
2368 qemu_mutex_lock(&mon_fdsets_lock);
2369 QLIST_FOREACH_SAFE(mon_fdset, &mon_fdsets, next, mon_fdset_next) {
2370 monitor_fdset_cleanup(mon_fdset);
2372 qemu_mutex_unlock(&mon_fdsets_lock);
2375 AddfdInfo *qmp_add_fd(bool has_fdset_id, int64_t fdset_id, bool has_opaque,
2376 const char *opaque, Error **errp)
2378 int fd;
2379 Monitor *mon = cur_mon;
2380 AddfdInfo *fdinfo;
2382 fd = qemu_chr_fe_get_msgfd(&mon->chr);
2383 if (fd == -1) {
2384 error_setg(errp, QERR_FD_NOT_SUPPLIED);
2385 goto error;
2388 fdinfo = monitor_fdset_add_fd(fd, has_fdset_id, fdset_id,
2389 has_opaque, opaque, errp);
2390 if (fdinfo) {
2391 return fdinfo;
2394 error:
2395 if (fd != -1) {
2396 close(fd);
2398 return NULL;
2401 void qmp_remove_fd(int64_t fdset_id, bool has_fd, int64_t fd, Error **errp)
2403 MonFdset *mon_fdset;
2404 MonFdsetFd *mon_fdset_fd;
2405 char fd_str[60];
2407 qemu_mutex_lock(&mon_fdsets_lock);
2408 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2409 if (mon_fdset->id != fdset_id) {
2410 continue;
2412 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2413 if (has_fd) {
2414 if (mon_fdset_fd->fd != fd) {
2415 continue;
2417 mon_fdset_fd->removed = true;
2418 break;
2419 } else {
2420 mon_fdset_fd->removed = true;
2423 if (has_fd && !mon_fdset_fd) {
2424 goto error;
2426 monitor_fdset_cleanup(mon_fdset);
2427 qemu_mutex_unlock(&mon_fdsets_lock);
2428 return;
2431 error:
2432 qemu_mutex_unlock(&mon_fdsets_lock);
2433 if (has_fd) {
2434 snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64 ", fd:%" PRId64,
2435 fdset_id, fd);
2436 } else {
2437 snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64, fdset_id);
2439 error_setg(errp, QERR_FD_NOT_FOUND, fd_str);
2442 FdsetInfoList *qmp_query_fdsets(Error **errp)
2444 MonFdset *mon_fdset;
2445 MonFdsetFd *mon_fdset_fd;
2446 FdsetInfoList *fdset_list = NULL;
2448 qemu_mutex_lock(&mon_fdsets_lock);
2449 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2450 FdsetInfoList *fdset_info = g_malloc0(sizeof(*fdset_info));
2451 FdsetFdInfoList *fdsetfd_list = NULL;
2453 fdset_info->value = g_malloc0(sizeof(*fdset_info->value));
2454 fdset_info->value->fdset_id = mon_fdset->id;
2456 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2457 FdsetFdInfoList *fdsetfd_info;
2459 fdsetfd_info = g_malloc0(sizeof(*fdsetfd_info));
2460 fdsetfd_info->value = g_malloc0(sizeof(*fdsetfd_info->value));
2461 fdsetfd_info->value->fd = mon_fdset_fd->fd;
2462 if (mon_fdset_fd->opaque) {
2463 fdsetfd_info->value->has_opaque = true;
2464 fdsetfd_info->value->opaque = g_strdup(mon_fdset_fd->opaque);
2465 } else {
2466 fdsetfd_info->value->has_opaque = false;
2469 fdsetfd_info->next = fdsetfd_list;
2470 fdsetfd_list = fdsetfd_info;
2473 fdset_info->value->fds = fdsetfd_list;
2475 fdset_info->next = fdset_list;
2476 fdset_list = fdset_info;
2478 qemu_mutex_unlock(&mon_fdsets_lock);
2480 return fdset_list;
2483 AddfdInfo *monitor_fdset_add_fd(int fd, bool has_fdset_id, int64_t fdset_id,
2484 bool has_opaque, const char *opaque,
2485 Error **errp)
2487 MonFdset *mon_fdset = NULL;
2488 MonFdsetFd *mon_fdset_fd;
2489 AddfdInfo *fdinfo;
2491 qemu_mutex_lock(&mon_fdsets_lock);
2492 if (has_fdset_id) {
2493 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2494 /* Break if match found or match impossible due to ordering by ID */
2495 if (fdset_id <= mon_fdset->id) {
2496 if (fdset_id < mon_fdset->id) {
2497 mon_fdset = NULL;
2499 break;
2504 if (mon_fdset == NULL) {
2505 int64_t fdset_id_prev = -1;
2506 MonFdset *mon_fdset_cur = QLIST_FIRST(&mon_fdsets);
2508 if (has_fdset_id) {
2509 if (fdset_id < 0) {
2510 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "fdset-id",
2511 "a non-negative value");
2512 qemu_mutex_unlock(&mon_fdsets_lock);
2513 return NULL;
2515 /* Use specified fdset ID */
2516 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2517 mon_fdset_cur = mon_fdset;
2518 if (fdset_id < mon_fdset_cur->id) {
2519 break;
2522 } else {
2523 /* Use first available fdset ID */
2524 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2525 mon_fdset_cur = mon_fdset;
2526 if (fdset_id_prev == mon_fdset_cur->id - 1) {
2527 fdset_id_prev = mon_fdset_cur->id;
2528 continue;
2530 break;
2534 mon_fdset = g_malloc0(sizeof(*mon_fdset));
2535 if (has_fdset_id) {
2536 mon_fdset->id = fdset_id;
2537 } else {
2538 mon_fdset->id = fdset_id_prev + 1;
2541 /* The fdset list is ordered by fdset ID */
2542 if (!mon_fdset_cur) {
2543 QLIST_INSERT_HEAD(&mon_fdsets, mon_fdset, next);
2544 } else if (mon_fdset->id < mon_fdset_cur->id) {
2545 QLIST_INSERT_BEFORE(mon_fdset_cur, mon_fdset, next);
2546 } else {
2547 QLIST_INSERT_AFTER(mon_fdset_cur, mon_fdset, next);
2551 mon_fdset_fd = g_malloc0(sizeof(*mon_fdset_fd));
2552 mon_fdset_fd->fd = fd;
2553 mon_fdset_fd->removed = false;
2554 if (has_opaque) {
2555 mon_fdset_fd->opaque = g_strdup(opaque);
2557 QLIST_INSERT_HEAD(&mon_fdset->fds, mon_fdset_fd, next);
2559 fdinfo = g_malloc0(sizeof(*fdinfo));
2560 fdinfo->fdset_id = mon_fdset->id;
2561 fdinfo->fd = mon_fdset_fd->fd;
2563 qemu_mutex_unlock(&mon_fdsets_lock);
2564 return fdinfo;
2567 int monitor_fdset_get_fd(int64_t fdset_id, int flags)
2569 #ifdef _WIN32
2570 return -ENOENT;
2571 #else
2572 MonFdset *mon_fdset;
2573 MonFdsetFd *mon_fdset_fd;
2574 int mon_fd_flags;
2575 int ret;
2577 qemu_mutex_lock(&mon_fdsets_lock);
2578 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2579 if (mon_fdset->id != fdset_id) {
2580 continue;
2582 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2583 mon_fd_flags = fcntl(mon_fdset_fd->fd, F_GETFL);
2584 if (mon_fd_flags == -1) {
2585 ret = -errno;
2586 goto out;
2589 if ((flags & O_ACCMODE) == (mon_fd_flags & O_ACCMODE)) {
2590 ret = mon_fdset_fd->fd;
2591 goto out;
2594 ret = -EACCES;
2595 goto out;
2597 ret = -ENOENT;
2599 out:
2600 qemu_mutex_unlock(&mon_fdsets_lock);
2601 return ret;
2602 #endif
2605 int monitor_fdset_dup_fd_add(int64_t fdset_id, int dup_fd)
2607 MonFdset *mon_fdset;
2608 MonFdsetFd *mon_fdset_fd_dup;
2610 qemu_mutex_lock(&mon_fdsets_lock);
2611 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2612 if (mon_fdset->id != fdset_id) {
2613 continue;
2615 QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
2616 if (mon_fdset_fd_dup->fd == dup_fd) {
2617 goto err;
2620 mon_fdset_fd_dup = g_malloc0(sizeof(*mon_fdset_fd_dup));
2621 mon_fdset_fd_dup->fd = dup_fd;
2622 QLIST_INSERT_HEAD(&mon_fdset->dup_fds, mon_fdset_fd_dup, next);
2623 qemu_mutex_unlock(&mon_fdsets_lock);
2624 return 0;
2627 err:
2628 qemu_mutex_unlock(&mon_fdsets_lock);
2629 return -1;
2632 static int64_t monitor_fdset_dup_fd_find_remove(int dup_fd, bool remove)
2634 MonFdset *mon_fdset;
2635 MonFdsetFd *mon_fdset_fd_dup;
2637 qemu_mutex_lock(&mon_fdsets_lock);
2638 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2639 QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
2640 if (mon_fdset_fd_dup->fd == dup_fd) {
2641 if (remove) {
2642 QLIST_REMOVE(mon_fdset_fd_dup, next);
2643 if (QLIST_EMPTY(&mon_fdset->dup_fds)) {
2644 monitor_fdset_cleanup(mon_fdset);
2646 goto err;
2647 } else {
2648 qemu_mutex_unlock(&mon_fdsets_lock);
2649 return mon_fdset->id;
2655 err:
2656 qemu_mutex_unlock(&mon_fdsets_lock);
2657 return -1;
2660 int64_t monitor_fdset_dup_fd_find(int dup_fd)
2662 return monitor_fdset_dup_fd_find_remove(dup_fd, false);
2665 void monitor_fdset_dup_fd_remove(int dup_fd)
2667 monitor_fdset_dup_fd_find_remove(dup_fd, true);
2670 int monitor_fd_param(Monitor *mon, const char *fdname, Error **errp)
2672 int fd;
2673 Error *local_err = NULL;
2675 if (!qemu_isdigit(fdname[0]) && mon) {
2676 fd = monitor_get_fd(mon, fdname, &local_err);
2677 } else {
2678 fd = qemu_parse_fd(fdname);
2679 if (fd == -1) {
2680 error_setg(&local_err, "Invalid file descriptor number '%s'",
2681 fdname);
2684 if (local_err) {
2685 error_propagate(errp, local_err);
2686 assert(fd == -1);
2687 } else {
2688 assert(fd != -1);
2691 return fd;
2694 /* Please update hmp-commands.hx when adding or changing commands */
2695 static mon_cmd_t info_cmds[] = {
2696 #include "hmp-commands-info.h"
2697 { NULL, NULL, },
2700 /* mon_cmds and info_cmds would be sorted at runtime */
2701 static mon_cmd_t mon_cmds[] = {
2702 #include "hmp-commands.h"
2703 { NULL, NULL, },
2706 /*******************************************************************/
2708 static const char *pch;
2709 static sigjmp_buf expr_env;
2712 static void GCC_FMT_ATTR(2, 3) QEMU_NORETURN
2713 expr_error(Monitor *mon, const char *fmt, ...)
2715 va_list ap;
2716 va_start(ap, fmt);
2717 monitor_vprintf(mon, fmt, ap);
2718 monitor_printf(mon, "\n");
2719 va_end(ap);
2720 siglongjmp(expr_env, 1);
2723 /* return 0 if OK, -1 if not found */
2724 static int get_monitor_def(target_long *pval, const char *name)
2726 const MonitorDef *md = target_monitor_defs();
2727 CPUState *cs = mon_get_cpu();
2728 void *ptr;
2729 uint64_t tmp = 0;
2730 int ret;
2732 if (cs == NULL || md == NULL) {
2733 return -1;
2736 for(; md->name != NULL; md++) {
2737 if (compare_cmd(name, md->name)) {
2738 if (md->get_value) {
2739 *pval = md->get_value(md, md->offset);
2740 } else {
2741 CPUArchState *env = mon_get_cpu_env();
2742 ptr = (uint8_t *)env + md->offset;
2743 switch(md->type) {
2744 case MD_I32:
2745 *pval = *(int32_t *)ptr;
2746 break;
2747 case MD_TLONG:
2748 *pval = *(target_long *)ptr;
2749 break;
2750 default:
2751 *pval = 0;
2752 break;
2755 return 0;
2759 ret = target_get_monitor_def(cs, name, &tmp);
2760 if (!ret) {
2761 *pval = (target_long) tmp;
2764 return ret;
2767 static void next(void)
2769 if (*pch != '\0') {
2770 pch++;
2771 while (qemu_isspace(*pch))
2772 pch++;
2776 static int64_t expr_sum(Monitor *mon);
2778 static int64_t expr_unary(Monitor *mon)
2780 int64_t n;
2781 char *p;
2782 int ret;
2784 switch(*pch) {
2785 case '+':
2786 next();
2787 n = expr_unary(mon);
2788 break;
2789 case '-':
2790 next();
2791 n = -expr_unary(mon);
2792 break;
2793 case '~':
2794 next();
2795 n = ~expr_unary(mon);
2796 break;
2797 case '(':
2798 next();
2799 n = expr_sum(mon);
2800 if (*pch != ')') {
2801 expr_error(mon, "')' expected");
2803 next();
2804 break;
2805 case '\'':
2806 pch++;
2807 if (*pch == '\0')
2808 expr_error(mon, "character constant expected");
2809 n = *pch;
2810 pch++;
2811 if (*pch != '\'')
2812 expr_error(mon, "missing terminating \' character");
2813 next();
2814 break;
2815 case '$':
2817 char buf[128], *q;
2818 target_long reg=0;
2820 pch++;
2821 q = buf;
2822 while ((*pch >= 'a' && *pch <= 'z') ||
2823 (*pch >= 'A' && *pch <= 'Z') ||
2824 (*pch >= '0' && *pch <= '9') ||
2825 *pch == '_' || *pch == '.') {
2826 if ((q - buf) < sizeof(buf) - 1)
2827 *q++ = *pch;
2828 pch++;
2830 while (qemu_isspace(*pch))
2831 pch++;
2832 *q = 0;
2833 ret = get_monitor_def(&reg, buf);
2834 if (ret < 0)
2835 expr_error(mon, "unknown register");
2836 n = reg;
2838 break;
2839 case '\0':
2840 expr_error(mon, "unexpected end of expression");
2841 n = 0;
2842 break;
2843 default:
2844 errno = 0;
2845 n = strtoull(pch, &p, 0);
2846 if (errno == ERANGE) {
2847 expr_error(mon, "number too large");
2849 if (pch == p) {
2850 expr_error(mon, "invalid char '%c' in expression", *p);
2852 pch = p;
2853 while (qemu_isspace(*pch))
2854 pch++;
2855 break;
2857 return n;
2861 static int64_t expr_prod(Monitor *mon)
2863 int64_t val, val2;
2864 int op;
2866 val = expr_unary(mon);
2867 for(;;) {
2868 op = *pch;
2869 if (op != '*' && op != '/' && op != '%')
2870 break;
2871 next();
2872 val2 = expr_unary(mon);
2873 switch(op) {
2874 default:
2875 case '*':
2876 val *= val2;
2877 break;
2878 case '/':
2879 case '%':
2880 if (val2 == 0)
2881 expr_error(mon, "division by zero");
2882 if (op == '/')
2883 val /= val2;
2884 else
2885 val %= val2;
2886 break;
2889 return val;
2892 static int64_t expr_logic(Monitor *mon)
2894 int64_t val, val2;
2895 int op;
2897 val = expr_prod(mon);
2898 for(;;) {
2899 op = *pch;
2900 if (op != '&' && op != '|' && op != '^')
2901 break;
2902 next();
2903 val2 = expr_prod(mon);
2904 switch(op) {
2905 default:
2906 case '&':
2907 val &= val2;
2908 break;
2909 case '|':
2910 val |= val2;
2911 break;
2912 case '^':
2913 val ^= val2;
2914 break;
2917 return val;
2920 static int64_t expr_sum(Monitor *mon)
2922 int64_t val, val2;
2923 int op;
2925 val = expr_logic(mon);
2926 for(;;) {
2927 op = *pch;
2928 if (op != '+' && op != '-')
2929 break;
2930 next();
2931 val2 = expr_logic(mon);
2932 if (op == '+')
2933 val += val2;
2934 else
2935 val -= val2;
2937 return val;
2940 static int get_expr(Monitor *mon, int64_t *pval, const char **pp)
2942 pch = *pp;
2943 if (sigsetjmp(expr_env, 0)) {
2944 *pp = pch;
2945 return -1;
2947 while (qemu_isspace(*pch))
2948 pch++;
2949 *pval = expr_sum(mon);
2950 *pp = pch;
2951 return 0;
2954 static int get_double(Monitor *mon, double *pval, const char **pp)
2956 const char *p = *pp;
2957 char *tailp;
2958 double d;
2960 d = strtod(p, &tailp);
2961 if (tailp == p) {
2962 monitor_printf(mon, "Number expected\n");
2963 return -1;
2965 if (d != d || d - d != 0) {
2966 /* NaN or infinity */
2967 monitor_printf(mon, "Bad number\n");
2968 return -1;
2970 *pval = d;
2971 *pp = tailp;
2972 return 0;
2976 * Store the command-name in cmdname, and return a pointer to
2977 * the remaining of the command string.
2979 static const char *get_command_name(const char *cmdline,
2980 char *cmdname, size_t nlen)
2982 size_t len;
2983 const char *p, *pstart;
2985 p = cmdline;
2986 while (qemu_isspace(*p))
2987 p++;
2988 if (*p == '\0')
2989 return NULL;
2990 pstart = p;
2991 while (*p != '\0' && *p != '/' && !qemu_isspace(*p))
2992 p++;
2993 len = p - pstart;
2994 if (len > nlen - 1)
2995 len = nlen - 1;
2996 memcpy(cmdname, pstart, len);
2997 cmdname[len] = '\0';
2998 return p;
3002 * Read key of 'type' into 'key' and return the current
3003 * 'type' pointer.
3005 static char *key_get_info(const char *type, char **key)
3007 size_t len;
3008 char *p, *str;
3010 if (*type == ',')
3011 type++;
3013 p = strchr(type, ':');
3014 if (!p) {
3015 *key = NULL;
3016 return NULL;
3018 len = p - type;
3020 str = g_malloc(len + 1);
3021 memcpy(str, type, len);
3022 str[len] = '\0';
3024 *key = str;
3025 return ++p;
3028 static int default_fmt_format = 'x';
3029 static int default_fmt_size = 4;
3031 static int is_valid_option(const char *c, const char *typestr)
3033 char option[3];
3035 option[0] = '-';
3036 option[1] = *c;
3037 option[2] = '\0';
3039 typestr = strstr(typestr, option);
3040 return (typestr != NULL);
3043 static const mon_cmd_t *search_dispatch_table(const mon_cmd_t *disp_table,
3044 const char *cmdname)
3046 const mon_cmd_t *cmd;
3048 for (cmd = disp_table; cmd->name != NULL; cmd++) {
3049 if (compare_cmd(cmdname, cmd->name)) {
3050 return cmd;
3054 return NULL;
3058 * Parse command name from @cmdp according to command table @table.
3059 * If blank, return NULL.
3060 * Else, if no valid command can be found, report to @mon, and return
3061 * NULL.
3062 * Else, change @cmdp to point right behind the name, and return its
3063 * command table entry.
3064 * Do not assume the return value points into @table! It doesn't when
3065 * the command is found in a sub-command table.
3067 static const mon_cmd_t *monitor_parse_command(MonitorHMP *hmp_mon,
3068 const char *cmdp_start,
3069 const char **cmdp,
3070 mon_cmd_t *table)
3072 Monitor *mon = &hmp_mon->common;
3073 const char *p;
3074 const mon_cmd_t *cmd;
3075 char cmdname[256];
3077 /* extract the command name */
3078 p = get_command_name(*cmdp, cmdname, sizeof(cmdname));
3079 if (!p)
3080 return NULL;
3082 cmd = search_dispatch_table(table, cmdname);
3083 if (!cmd) {
3084 monitor_printf(mon, "unknown command: '%.*s'\n",
3085 (int)(p - cmdp_start), cmdp_start);
3086 return NULL;
3088 if (runstate_check(RUN_STATE_PRECONFIG) && !cmd_can_preconfig(cmd)) {
3089 monitor_printf(mon, "Command '%.*s' not available with -preconfig "
3090 "until after exit_preconfig.\n",
3091 (int)(p - cmdp_start), cmdp_start);
3092 return NULL;
3095 /* filter out following useless space */
3096 while (qemu_isspace(*p)) {
3097 p++;
3100 *cmdp = p;
3101 /* search sub command */
3102 if (cmd->sub_table != NULL && *p != '\0') {
3103 return monitor_parse_command(hmp_mon, cmdp_start, cmdp, cmd->sub_table);
3106 return cmd;
3110 * Parse arguments for @cmd.
3111 * If it can't be parsed, report to @mon, and return NULL.
3112 * Else, insert command arguments into a QDict, and return it.
3113 * Note: On success, caller has to free the QDict structure.
3116 static QDict *monitor_parse_arguments(Monitor *mon,
3117 const char **endp,
3118 const mon_cmd_t *cmd)
3120 const char *typestr;
3121 char *key;
3122 int c;
3123 const char *p = *endp;
3124 char buf[1024];
3125 QDict *qdict = qdict_new();
3127 /* parse the parameters */
3128 typestr = cmd->args_type;
3129 for(;;) {
3130 typestr = key_get_info(typestr, &key);
3131 if (!typestr)
3132 break;
3133 c = *typestr;
3134 typestr++;
3135 switch(c) {
3136 case 'F':
3137 case 'B':
3138 case 's':
3140 int ret;
3142 while (qemu_isspace(*p))
3143 p++;
3144 if (*typestr == '?') {
3145 typestr++;
3146 if (*p == '\0') {
3147 /* no optional string: NULL argument */
3148 break;
3151 ret = get_str(buf, sizeof(buf), &p);
3152 if (ret < 0) {
3153 switch(c) {
3154 case 'F':
3155 monitor_printf(mon, "%s: filename expected\n",
3156 cmd->name);
3157 break;
3158 case 'B':
3159 monitor_printf(mon, "%s: block device name expected\n",
3160 cmd->name);
3161 break;
3162 default:
3163 monitor_printf(mon, "%s: string expected\n", cmd->name);
3164 break;
3166 goto fail;
3168 qdict_put_str(qdict, key, buf);
3170 break;
3171 case 'O':
3173 QemuOptsList *opts_list;
3174 QemuOpts *opts;
3176 opts_list = qemu_find_opts(key);
3177 if (!opts_list || opts_list->desc->name) {
3178 goto bad_type;
3180 while (qemu_isspace(*p)) {
3181 p++;
3183 if (!*p)
3184 break;
3185 if (get_str(buf, sizeof(buf), &p) < 0) {
3186 goto fail;
3188 opts = qemu_opts_parse_noisily(opts_list, buf, true);
3189 if (!opts) {
3190 goto fail;
3192 qemu_opts_to_qdict(opts, qdict);
3193 qemu_opts_del(opts);
3195 break;
3196 case '/':
3198 int count, format, size;
3200 while (qemu_isspace(*p))
3201 p++;
3202 if (*p == '/') {
3203 /* format found */
3204 p++;
3205 count = 1;
3206 if (qemu_isdigit(*p)) {
3207 count = 0;
3208 while (qemu_isdigit(*p)) {
3209 count = count * 10 + (*p - '0');
3210 p++;
3213 size = -1;
3214 format = -1;
3215 for(;;) {
3216 switch(*p) {
3217 case 'o':
3218 case 'd':
3219 case 'u':
3220 case 'x':
3221 case 'i':
3222 case 'c':
3223 format = *p++;
3224 break;
3225 case 'b':
3226 size = 1;
3227 p++;
3228 break;
3229 case 'h':
3230 size = 2;
3231 p++;
3232 break;
3233 case 'w':
3234 size = 4;
3235 p++;
3236 break;
3237 case 'g':
3238 case 'L':
3239 size = 8;
3240 p++;
3241 break;
3242 default:
3243 goto next;
3246 next:
3247 if (*p != '\0' && !qemu_isspace(*p)) {
3248 monitor_printf(mon, "invalid char in format: '%c'\n",
3249 *p);
3250 goto fail;
3252 if (format < 0)
3253 format = default_fmt_format;
3254 if (format != 'i') {
3255 /* for 'i', not specifying a size gives -1 as size */
3256 if (size < 0)
3257 size = default_fmt_size;
3258 default_fmt_size = size;
3260 default_fmt_format = format;
3261 } else {
3262 count = 1;
3263 format = default_fmt_format;
3264 if (format != 'i') {
3265 size = default_fmt_size;
3266 } else {
3267 size = -1;
3270 qdict_put_int(qdict, "count", count);
3271 qdict_put_int(qdict, "format", format);
3272 qdict_put_int(qdict, "size", size);
3274 break;
3275 case 'i':
3276 case 'l':
3277 case 'M':
3279 int64_t val;
3281 while (qemu_isspace(*p))
3282 p++;
3283 if (*typestr == '?' || *typestr == '.') {
3284 if (*typestr == '?') {
3285 if (*p == '\0') {
3286 typestr++;
3287 break;
3289 } else {
3290 if (*p == '.') {
3291 p++;
3292 while (qemu_isspace(*p))
3293 p++;
3294 } else {
3295 typestr++;
3296 break;
3299 typestr++;
3301 if (get_expr(mon, &val, &p))
3302 goto fail;
3303 /* Check if 'i' is greater than 32-bit */
3304 if ((c == 'i') && ((val >> 32) & 0xffffffff)) {
3305 monitor_printf(mon, "\'%s\' has failed: ", cmd->name);
3306 monitor_printf(mon, "integer is for 32-bit values\n");
3307 goto fail;
3308 } else if (c == 'M') {
3309 if (val < 0) {
3310 monitor_printf(mon, "enter a positive value\n");
3311 goto fail;
3313 val *= MiB;
3315 qdict_put_int(qdict, key, val);
3317 break;
3318 case 'o':
3320 int ret;
3321 uint64_t val;
3322 const char *end;
3324 while (qemu_isspace(*p)) {
3325 p++;
3327 if (*typestr == '?') {
3328 typestr++;
3329 if (*p == '\0') {
3330 break;
3333 ret = qemu_strtosz_MiB(p, &end, &val);
3334 if (ret < 0 || val > INT64_MAX) {
3335 monitor_printf(mon, "invalid size\n");
3336 goto fail;
3338 qdict_put_int(qdict, key, val);
3339 p = end;
3341 break;
3342 case 'T':
3344 double val;
3346 while (qemu_isspace(*p))
3347 p++;
3348 if (*typestr == '?') {
3349 typestr++;
3350 if (*p == '\0') {
3351 break;
3354 if (get_double(mon, &val, &p) < 0) {
3355 goto fail;
3357 if (p[0] && p[1] == 's') {
3358 switch (*p) {
3359 case 'm':
3360 val /= 1e3; p += 2; break;
3361 case 'u':
3362 val /= 1e6; p += 2; break;
3363 case 'n':
3364 val /= 1e9; p += 2; break;
3367 if (*p && !qemu_isspace(*p)) {
3368 monitor_printf(mon, "Unknown unit suffix\n");
3369 goto fail;
3371 qdict_put(qdict, key, qnum_from_double(val));
3373 break;
3374 case 'b':
3376 const char *beg;
3377 bool val;
3379 while (qemu_isspace(*p)) {
3380 p++;
3382 beg = p;
3383 while (qemu_isgraph(*p)) {
3384 p++;
3386 if (p - beg == 2 && !memcmp(beg, "on", p - beg)) {
3387 val = true;
3388 } else if (p - beg == 3 && !memcmp(beg, "off", p - beg)) {
3389 val = false;
3390 } else {
3391 monitor_printf(mon, "Expected 'on' or 'off'\n");
3392 goto fail;
3394 qdict_put_bool(qdict, key, val);
3396 break;
3397 case '-':
3399 const char *tmp = p;
3400 int skip_key = 0;
3401 /* option */
3403 c = *typestr++;
3404 if (c == '\0')
3405 goto bad_type;
3406 while (qemu_isspace(*p))
3407 p++;
3408 if (*p == '-') {
3409 p++;
3410 if(c != *p) {
3411 if(!is_valid_option(p, typestr)) {
3413 monitor_printf(mon, "%s: unsupported option -%c\n",
3414 cmd->name, *p);
3415 goto fail;
3416 } else {
3417 skip_key = 1;
3420 if(skip_key) {
3421 p = tmp;
3422 } else {
3423 /* has option */
3424 p++;
3425 qdict_put_bool(qdict, key, true);
3429 break;
3430 case 'S':
3432 /* package all remaining string */
3433 int len;
3435 while (qemu_isspace(*p)) {
3436 p++;
3438 if (*typestr == '?') {
3439 typestr++;
3440 if (*p == '\0') {
3441 /* no remaining string: NULL argument */
3442 break;
3445 len = strlen(p);
3446 if (len <= 0) {
3447 monitor_printf(mon, "%s: string expected\n",
3448 cmd->name);
3449 goto fail;
3451 qdict_put_str(qdict, key, p);
3452 p += len;
3454 break;
3455 default:
3456 bad_type:
3457 monitor_printf(mon, "%s: unknown type '%c'\n", cmd->name, c);
3458 goto fail;
3460 g_free(key);
3461 key = NULL;
3463 /* check that all arguments were parsed */
3464 while (qemu_isspace(*p))
3465 p++;
3466 if (*p != '\0') {
3467 monitor_printf(mon, "%s: extraneous characters at the end of line\n",
3468 cmd->name);
3469 goto fail;
3472 return qdict;
3474 fail:
3475 qobject_unref(qdict);
3476 g_free(key);
3477 return NULL;
3480 static void handle_hmp_command(MonitorHMP *mon, const char *cmdline)
3482 QDict *qdict;
3483 const mon_cmd_t *cmd;
3484 const char *cmd_start = cmdline;
3486 trace_handle_hmp_command(mon, cmdline);
3488 cmd = monitor_parse_command(mon, cmdline, &cmdline, mon->common.cmd_table);
3489 if (!cmd) {
3490 return;
3493 qdict = monitor_parse_arguments(&mon->common, &cmdline, cmd);
3494 if (!qdict) {
3495 while (cmdline > cmd_start && qemu_isspace(cmdline[-1])) {
3496 cmdline--;
3498 monitor_printf(&mon->common, "Try \"help %.*s\" for more information\n",
3499 (int)(cmdline - cmd_start), cmd_start);
3500 return;
3503 cmd->cmd(&mon->common, qdict);
3504 qobject_unref(qdict);
3507 static void cmd_completion(MonitorHMP *mon, const char *name, const char *list)
3509 const char *p, *pstart;
3510 char cmd[128];
3511 int len;
3513 p = list;
3514 for(;;) {
3515 pstart = p;
3516 p = qemu_strchrnul(p, '|');
3517 len = p - pstart;
3518 if (len > sizeof(cmd) - 2)
3519 len = sizeof(cmd) - 2;
3520 memcpy(cmd, pstart, len);
3521 cmd[len] = '\0';
3522 if (name[0] == '\0' || !strncmp(name, cmd, strlen(name))) {
3523 readline_add_completion(mon->rs, cmd);
3525 if (*p == '\0')
3526 break;
3527 p++;
3531 static void file_completion(MonitorHMP *mon, const char *input)
3533 DIR *ffs;
3534 struct dirent *d;
3535 char path[1024];
3536 char file[1024], file_prefix[1024];
3537 int input_path_len;
3538 const char *p;
3540 p = strrchr(input, '/');
3541 if (!p) {
3542 input_path_len = 0;
3543 pstrcpy(file_prefix, sizeof(file_prefix), input);
3544 pstrcpy(path, sizeof(path), ".");
3545 } else {
3546 input_path_len = p - input + 1;
3547 memcpy(path, input, input_path_len);
3548 if (input_path_len > sizeof(path) - 1)
3549 input_path_len = sizeof(path) - 1;
3550 path[input_path_len] = '\0';
3551 pstrcpy(file_prefix, sizeof(file_prefix), p + 1);
3554 ffs = opendir(path);
3555 if (!ffs)
3556 return;
3557 for(;;) {
3558 struct stat sb;
3559 d = readdir(ffs);
3560 if (!d)
3561 break;
3563 if (strcmp(d->d_name, ".") == 0 || strcmp(d->d_name, "..") == 0) {
3564 continue;
3567 if (strstart(d->d_name, file_prefix, NULL)) {
3568 memcpy(file, input, input_path_len);
3569 if (input_path_len < sizeof(file))
3570 pstrcpy(file + input_path_len, sizeof(file) - input_path_len,
3571 d->d_name);
3572 /* stat the file to find out if it's a directory.
3573 * In that case add a slash to speed up typing long paths
3575 if (stat(file, &sb) == 0 && S_ISDIR(sb.st_mode)) {
3576 pstrcat(file, sizeof(file), "/");
3578 readline_add_completion(mon->rs, file);
3581 closedir(ffs);
3584 static const char *next_arg_type(const char *typestr)
3586 const char *p = strchr(typestr, ':');
3587 return (p != NULL ? ++p : typestr);
3590 static void add_completion_option(ReadLineState *rs, const char *str,
3591 const char *option)
3593 if (!str || !option) {
3594 return;
3596 if (!strncmp(option, str, strlen(str))) {
3597 readline_add_completion(rs, option);
3601 void chardev_add_completion(ReadLineState *rs, int nb_args, const char *str)
3603 size_t len;
3604 ChardevBackendInfoList *list, *start;
3606 if (nb_args != 2) {
3607 return;
3609 len = strlen(str);
3610 readline_set_completion_index(rs, len);
3612 start = list = qmp_query_chardev_backends(NULL);
3613 while (list) {
3614 const char *chr_name = list->value->name;
3616 if (!strncmp(chr_name, str, len)) {
3617 readline_add_completion(rs, chr_name);
3619 list = list->next;
3621 qapi_free_ChardevBackendInfoList(start);
3624 void netdev_add_completion(ReadLineState *rs, int nb_args, const char *str)
3626 size_t len;
3627 int i;
3629 if (nb_args != 2) {
3630 return;
3632 len = strlen(str);
3633 readline_set_completion_index(rs, len);
3634 for (i = 0; i < NET_CLIENT_DRIVER__MAX; i++) {
3635 add_completion_option(rs, str, NetClientDriver_str(i));
3639 void device_add_completion(ReadLineState *rs, int nb_args, const char *str)
3641 GSList *list, *elt;
3642 size_t len;
3644 if (nb_args != 2) {
3645 return;
3648 len = strlen(str);
3649 readline_set_completion_index(rs, len);
3650 list = elt = object_class_get_list(TYPE_DEVICE, false);
3651 while (elt) {
3652 const char *name;
3653 DeviceClass *dc = OBJECT_CLASS_CHECK(DeviceClass, elt->data,
3654 TYPE_DEVICE);
3655 name = object_class_get_name(OBJECT_CLASS(dc));
3657 if (dc->user_creatable
3658 && !strncmp(name, str, len)) {
3659 readline_add_completion(rs, name);
3661 elt = elt->next;
3663 g_slist_free(list);
3666 void object_add_completion(ReadLineState *rs, int nb_args, const char *str)
3668 GSList *list, *elt;
3669 size_t len;
3671 if (nb_args != 2) {
3672 return;
3675 len = strlen(str);
3676 readline_set_completion_index(rs, len);
3677 list = elt = object_class_get_list(TYPE_USER_CREATABLE, false);
3678 while (elt) {
3679 const char *name;
3681 name = object_class_get_name(OBJECT_CLASS(elt->data));
3682 if (!strncmp(name, str, len) && strcmp(name, TYPE_USER_CREATABLE)) {
3683 readline_add_completion(rs, name);
3685 elt = elt->next;
3687 g_slist_free(list);
3690 static void peripheral_device_del_completion(ReadLineState *rs,
3691 const char *str, size_t len)
3693 Object *peripheral = container_get(qdev_get_machine(), "/peripheral");
3694 GSList *list, *item;
3696 list = qdev_build_hotpluggable_device_list(peripheral);
3697 if (!list) {
3698 return;
3701 for (item = list; item; item = g_slist_next(item)) {
3702 DeviceState *dev = item->data;
3704 if (dev->id && !strncmp(str, dev->id, len)) {
3705 readline_add_completion(rs, dev->id);
3709 g_slist_free(list);
3712 void chardev_remove_completion(ReadLineState *rs, int nb_args, const char *str)
3714 size_t len;
3715 ChardevInfoList *list, *start;
3717 if (nb_args != 2) {
3718 return;
3720 len = strlen(str);
3721 readline_set_completion_index(rs, len);
3723 start = list = qmp_query_chardev(NULL);
3724 while (list) {
3725 ChardevInfo *chr = list->value;
3727 if (!strncmp(chr->label, str, len)) {
3728 readline_add_completion(rs, chr->label);
3730 list = list->next;
3732 qapi_free_ChardevInfoList(start);
3735 static void ringbuf_completion(ReadLineState *rs, const char *str)
3737 size_t len;
3738 ChardevInfoList *list, *start;
3740 len = strlen(str);
3741 readline_set_completion_index(rs, len);
3743 start = list = qmp_query_chardev(NULL);
3744 while (list) {
3745 ChardevInfo *chr_info = list->value;
3747 if (!strncmp(chr_info->label, str, len)) {
3748 Chardev *chr = qemu_chr_find(chr_info->label);
3749 if (chr && CHARDEV_IS_RINGBUF(chr)) {
3750 readline_add_completion(rs, chr_info->label);
3753 list = list->next;
3755 qapi_free_ChardevInfoList(start);
3758 void ringbuf_write_completion(ReadLineState *rs, int nb_args, const char *str)
3760 if (nb_args != 2) {
3761 return;
3763 ringbuf_completion(rs, str);
3766 void device_del_completion(ReadLineState *rs, int nb_args, const char *str)
3768 size_t len;
3770 if (nb_args != 2) {
3771 return;
3774 len = strlen(str);
3775 readline_set_completion_index(rs, len);
3776 peripheral_device_del_completion(rs, str, len);
3779 void object_del_completion(ReadLineState *rs, int nb_args, const char *str)
3781 ObjectPropertyInfoList *list, *start;
3782 size_t len;
3784 if (nb_args != 2) {
3785 return;
3787 len = strlen(str);
3788 readline_set_completion_index(rs, len);
3790 start = list = qmp_qom_list("/objects", NULL);
3791 while (list) {
3792 ObjectPropertyInfo *info = list->value;
3794 if (!strncmp(info->type, "child<", 5)
3795 && !strncmp(info->name, str, len)) {
3796 readline_add_completion(rs, info->name);
3798 list = list->next;
3800 qapi_free_ObjectPropertyInfoList(start);
3803 void sendkey_completion(ReadLineState *rs, int nb_args, const char *str)
3805 int i;
3806 char *sep;
3807 size_t len;
3809 if (nb_args != 2) {
3810 return;
3812 sep = strrchr(str, '-');
3813 if (sep) {
3814 str = sep + 1;
3816 len = strlen(str);
3817 readline_set_completion_index(rs, len);
3818 for (i = 0; i < Q_KEY_CODE__MAX; i++) {
3819 if (!strncmp(str, QKeyCode_str(i), len)) {
3820 readline_add_completion(rs, QKeyCode_str(i));
3825 void set_link_completion(ReadLineState *rs, int nb_args, const char *str)
3827 size_t len;
3829 len = strlen(str);
3830 readline_set_completion_index(rs, len);
3831 if (nb_args == 2) {
3832 NetClientState *ncs[MAX_QUEUE_NUM];
3833 int count, i;
3834 count = qemu_find_net_clients_except(NULL, ncs,
3835 NET_CLIENT_DRIVER_NONE,
3836 MAX_QUEUE_NUM);
3837 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3838 const char *name = ncs[i]->name;
3839 if (!strncmp(str, name, len)) {
3840 readline_add_completion(rs, name);
3843 } else if (nb_args == 3) {
3844 add_completion_option(rs, str, "on");
3845 add_completion_option(rs, str, "off");
3849 void netdev_del_completion(ReadLineState *rs, int nb_args, const char *str)
3851 int len, count, i;
3852 NetClientState *ncs[MAX_QUEUE_NUM];
3854 if (nb_args != 2) {
3855 return;
3858 len = strlen(str);
3859 readline_set_completion_index(rs, len);
3860 count = qemu_find_net_clients_except(NULL, ncs, NET_CLIENT_DRIVER_NIC,
3861 MAX_QUEUE_NUM);
3862 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3863 QemuOpts *opts;
3864 const char *name = ncs[i]->name;
3865 if (strncmp(str, name, len)) {
3866 continue;
3868 opts = qemu_opts_find(qemu_find_opts_err("netdev", NULL), name);
3869 if (opts) {
3870 readline_add_completion(rs, name);
3875 void info_trace_events_completion(ReadLineState *rs, int nb_args, const char *str)
3877 size_t len;
3879 len = strlen(str);
3880 readline_set_completion_index(rs, len);
3881 if (nb_args == 2) {
3882 TraceEventIter iter;
3883 TraceEvent *ev;
3884 char *pattern = g_strdup_printf("%s*", str);
3885 trace_event_iter_init(&iter, pattern);
3886 while ((ev = trace_event_iter_next(&iter)) != NULL) {
3887 readline_add_completion(rs, trace_event_get_name(ev));
3889 g_free(pattern);
3893 void trace_event_completion(ReadLineState *rs, int nb_args, const char *str)
3895 size_t len;
3897 len = strlen(str);
3898 readline_set_completion_index(rs, len);
3899 if (nb_args == 2) {
3900 TraceEventIter iter;
3901 TraceEvent *ev;
3902 char *pattern = g_strdup_printf("%s*", str);
3903 trace_event_iter_init(&iter, pattern);
3904 while ((ev = trace_event_iter_next(&iter)) != NULL) {
3905 readline_add_completion(rs, trace_event_get_name(ev));
3907 g_free(pattern);
3908 } else if (nb_args == 3) {
3909 add_completion_option(rs, str, "on");
3910 add_completion_option(rs, str, "off");
3914 void watchdog_action_completion(ReadLineState *rs, int nb_args, const char *str)
3916 int i;
3918 if (nb_args != 2) {
3919 return;
3921 readline_set_completion_index(rs, strlen(str));
3922 for (i = 0; i < WATCHDOG_ACTION__MAX; i++) {
3923 add_completion_option(rs, str, WatchdogAction_str(i));
3927 void migrate_set_capability_completion(ReadLineState *rs, int nb_args,
3928 const char *str)
3930 size_t len;
3932 len = strlen(str);
3933 readline_set_completion_index(rs, len);
3934 if (nb_args == 2) {
3935 int i;
3936 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
3937 const char *name = MigrationCapability_str(i);
3938 if (!strncmp(str, name, len)) {
3939 readline_add_completion(rs, name);
3942 } else if (nb_args == 3) {
3943 add_completion_option(rs, str, "on");
3944 add_completion_option(rs, str, "off");
3948 void migrate_set_parameter_completion(ReadLineState *rs, int nb_args,
3949 const char *str)
3951 size_t len;
3953 len = strlen(str);
3954 readline_set_completion_index(rs, len);
3955 if (nb_args == 2) {
3956 int i;
3957 for (i = 0; i < MIGRATION_PARAMETER__MAX; i++) {
3958 const char *name = MigrationParameter_str(i);
3959 if (!strncmp(str, name, len)) {
3960 readline_add_completion(rs, name);
3966 static void vm_completion(ReadLineState *rs, const char *str)
3968 size_t len;
3969 BlockDriverState *bs;
3970 BdrvNextIterator it;
3972 len = strlen(str);
3973 readline_set_completion_index(rs, len);
3975 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
3976 SnapshotInfoList *snapshots, *snapshot;
3977 AioContext *ctx = bdrv_get_aio_context(bs);
3978 bool ok = false;
3980 aio_context_acquire(ctx);
3981 if (bdrv_can_snapshot(bs)) {
3982 ok = bdrv_query_snapshot_info_list(bs, &snapshots, NULL) == 0;
3984 aio_context_release(ctx);
3985 if (!ok) {
3986 continue;
3989 snapshot = snapshots;
3990 while (snapshot) {
3991 char *completion = snapshot->value->name;
3992 if (!strncmp(str, completion, len)) {
3993 readline_add_completion(rs, completion);
3995 completion = snapshot->value->id;
3996 if (!strncmp(str, completion, len)) {
3997 readline_add_completion(rs, completion);
3999 snapshot = snapshot->next;
4001 qapi_free_SnapshotInfoList(snapshots);
4006 void delvm_completion(ReadLineState *rs, int nb_args, const char *str)
4008 if (nb_args == 2) {
4009 vm_completion(rs, str);
4013 void loadvm_completion(ReadLineState *rs, int nb_args, const char *str)
4015 if (nb_args == 2) {
4016 vm_completion(rs, str);
4020 static void monitor_find_completion_by_table(MonitorHMP *mon,
4021 const mon_cmd_t *cmd_table,
4022 char **args,
4023 int nb_args)
4025 const char *cmdname;
4026 int i;
4027 const char *ptype, *old_ptype, *str, *name;
4028 const mon_cmd_t *cmd;
4029 BlockBackend *blk = NULL;
4031 if (nb_args <= 1) {
4032 /* command completion */
4033 if (nb_args == 0)
4034 cmdname = "";
4035 else
4036 cmdname = args[0];
4037 readline_set_completion_index(mon->rs, strlen(cmdname));
4038 for (cmd = cmd_table; cmd->name != NULL; cmd++) {
4039 if (!runstate_check(RUN_STATE_PRECONFIG) ||
4040 cmd_can_preconfig(cmd)) {
4041 cmd_completion(mon, cmdname, cmd->name);
4044 } else {
4045 /* find the command */
4046 for (cmd = cmd_table; cmd->name != NULL; cmd++) {
4047 if (compare_cmd(args[0], cmd->name) &&
4048 (!runstate_check(RUN_STATE_PRECONFIG) ||
4049 cmd_can_preconfig(cmd))) {
4050 break;
4053 if (!cmd->name) {
4054 return;
4057 if (cmd->sub_table) {
4058 /* do the job again */
4059 monitor_find_completion_by_table(mon, cmd->sub_table,
4060 &args[1], nb_args - 1);
4061 return;
4063 if (cmd->command_completion) {
4064 cmd->command_completion(mon->rs, nb_args, args[nb_args - 1]);
4065 return;
4068 ptype = next_arg_type(cmd->args_type);
4069 for(i = 0; i < nb_args - 2; i++) {
4070 if (*ptype != '\0') {
4071 ptype = next_arg_type(ptype);
4072 while (*ptype == '?')
4073 ptype = next_arg_type(ptype);
4076 str = args[nb_args - 1];
4077 old_ptype = NULL;
4078 while (*ptype == '-' && old_ptype != ptype) {
4079 old_ptype = ptype;
4080 ptype = next_arg_type(ptype);
4082 switch(*ptype) {
4083 case 'F':
4084 /* file completion */
4085 readline_set_completion_index(mon->rs, strlen(str));
4086 file_completion(mon, str);
4087 break;
4088 case 'B':
4089 /* block device name completion */
4090 readline_set_completion_index(mon->rs, strlen(str));
4091 while ((blk = blk_next(blk)) != NULL) {
4092 name = blk_name(blk);
4093 if (str[0] == '\0' ||
4094 !strncmp(name, str, strlen(str))) {
4095 readline_add_completion(mon->rs, name);
4098 break;
4099 case 's':
4100 case 'S':
4101 if (!strcmp(cmd->name, "help|?")) {
4102 monitor_find_completion_by_table(mon, cmd_table,
4103 &args[1], nb_args - 1);
4105 break;
4106 default:
4107 break;
4112 static void monitor_find_completion(void *opaque,
4113 const char *cmdline)
4115 MonitorHMP *mon = opaque;
4116 char *args[MAX_ARGS];
4117 int nb_args, len;
4119 /* 1. parse the cmdline */
4120 if (parse_cmdline(cmdline, &nb_args, args) < 0) {
4121 return;
4124 /* if the line ends with a space, it means we want to complete the
4125 next arg */
4126 len = strlen(cmdline);
4127 if (len > 0 && qemu_isspace(cmdline[len - 1])) {
4128 if (nb_args >= MAX_ARGS) {
4129 goto cleanup;
4131 args[nb_args++] = g_strdup("");
4134 /* 2. auto complete according to args */
4135 monitor_find_completion_by_table(mon, mon->common.cmd_table, args, nb_args);
4137 cleanup:
4138 free_cmdline_args(args, nb_args);
4141 static int monitor_can_read(void *opaque)
4143 Monitor *mon = opaque;
4145 return !atomic_mb_read(&mon->suspend_cnt);
4149 * Emit QMP response @rsp with ID @id to @mon.
4150 * Null @rsp can only happen for commands with QCO_NO_SUCCESS_RESP.
4151 * Nothing is emitted then.
4153 static void monitor_qmp_respond(MonitorQMP *mon, QDict *rsp)
4155 if (rsp) {
4156 qmp_send_response(mon, rsp);
4160 static void monitor_qmp_dispatch(MonitorQMP *mon, QObject *req)
4162 Monitor *old_mon;
4163 QDict *rsp;
4164 QDict *error;
4166 old_mon = cur_mon;
4167 cur_mon = &mon->common;
4169 rsp = qmp_dispatch(mon->commands, req, qmp_oob_enabled(mon));
4171 cur_mon = old_mon;
4173 if (mon->commands == &qmp_cap_negotiation_commands) {
4174 error = qdict_get_qdict(rsp, "error");
4175 if (error
4176 && !g_strcmp0(qdict_get_try_str(error, "class"),
4177 QapiErrorClass_str(ERROR_CLASS_COMMAND_NOT_FOUND))) {
4178 /* Provide a more useful error message */
4179 qdict_del(error, "desc");
4180 qdict_put_str(error, "desc", "Expecting capabilities negotiation"
4181 " with 'qmp_capabilities'");
4185 monitor_qmp_respond(mon, rsp);
4186 qobject_unref(rsp);
4190 * Pop a QMP request from a monitor request queue.
4191 * Return the request, or NULL all request queues are empty.
4192 * We are using round-robin fashion to pop the request, to avoid
4193 * processing commands only on a very busy monitor. To achieve that,
4194 * when we process one request on a specific monitor, we put that
4195 * monitor to the end of mon_list queue.
4197 * Note: if the function returned with non-NULL, then the caller will
4198 * be with qmp_mon->qmp_queue_lock held, and the caller is responsible
4199 * to release it.
4201 static QMPRequest *monitor_qmp_requests_pop_any_with_lock(void)
4203 QMPRequest *req_obj = NULL;
4204 Monitor *mon;
4205 MonitorQMP *qmp_mon;
4207 qemu_mutex_lock(&monitor_lock);
4209 QTAILQ_FOREACH(mon, &mon_list, entry) {
4210 if (!monitor_is_qmp(mon)) {
4211 continue;
4214 qmp_mon = container_of(mon, MonitorQMP, common);
4215 qemu_mutex_lock(&qmp_mon->qmp_queue_lock);
4216 req_obj = g_queue_pop_head(qmp_mon->qmp_requests);
4217 if (req_obj) {
4218 /* With the lock of corresponding queue held */
4219 break;
4221 qemu_mutex_unlock(&qmp_mon->qmp_queue_lock);
4224 if (req_obj) {
4226 * We found one request on the monitor. Degrade this monitor's
4227 * priority to lowest by re-inserting it to end of queue.
4229 QTAILQ_REMOVE(&mon_list, mon, entry);
4230 QTAILQ_INSERT_TAIL(&mon_list, mon, entry);
4233 qemu_mutex_unlock(&monitor_lock);
4235 return req_obj;
4238 static void monitor_qmp_bh_dispatcher(void *data)
4240 QMPRequest *req_obj = monitor_qmp_requests_pop_any_with_lock();
4241 QDict *rsp;
4242 bool need_resume;
4243 MonitorQMP *mon;
4245 if (!req_obj) {
4246 return;
4249 mon = req_obj->mon;
4250 /* qmp_oob_enabled() might change after "qmp_capabilities" */
4251 need_resume = !qmp_oob_enabled(mon) ||
4252 mon->qmp_requests->length == QMP_REQ_QUEUE_LEN_MAX - 1;
4253 qemu_mutex_unlock(&mon->qmp_queue_lock);
4254 if (req_obj->req) {
4255 QDict *qdict = qobject_to(QDict, req_obj->req);
4256 QObject *id = qdict ? qdict_get(qdict, "id") : NULL;
4257 trace_monitor_qmp_cmd_in_band(qobject_get_try_str(id) ?: "");
4258 monitor_qmp_dispatch(mon, req_obj->req);
4259 } else {
4260 assert(req_obj->err);
4261 rsp = qmp_error_response(req_obj->err);
4262 req_obj->err = NULL;
4263 monitor_qmp_respond(mon, rsp);
4264 qobject_unref(rsp);
4267 if (need_resume) {
4268 /* Pairs with the monitor_suspend() in handle_qmp_command() */
4269 monitor_resume(&mon->common);
4271 qmp_request_free(req_obj);
4273 /* Reschedule instead of looping so the main loop stays responsive */
4274 qemu_bh_schedule(qmp_dispatcher_bh);
4277 static void handle_qmp_command(void *opaque, QObject *req, Error *err)
4279 MonitorQMP *mon = opaque;
4280 QObject *id = NULL;
4281 QDict *qdict;
4282 QMPRequest *req_obj;
4284 assert(!req != !err);
4286 qdict = qobject_to(QDict, req);
4287 if (qdict) {
4288 id = qdict_get(qdict, "id");
4289 } /* else will fail qmp_dispatch() */
4291 if (req && trace_event_get_state_backends(TRACE_HANDLE_QMP_COMMAND)) {
4292 QString *req_json = qobject_to_json(req);
4293 trace_handle_qmp_command(mon, qstring_get_str(req_json));
4294 qobject_unref(req_json);
4297 if (qdict && qmp_is_oob(qdict)) {
4298 /* OOB commands are executed immediately */
4299 trace_monitor_qmp_cmd_out_of_band(qobject_get_try_str(id) ?: "");
4300 monitor_qmp_dispatch(mon, req);
4301 qobject_unref(req);
4302 return;
4305 req_obj = g_new0(QMPRequest, 1);
4306 req_obj->mon = mon;
4307 req_obj->req = req;
4308 req_obj->err = err;
4310 /* Protect qmp_requests and fetching its length. */
4311 qemu_mutex_lock(&mon->qmp_queue_lock);
4314 * Suspend the monitor when we can't queue more requests after
4315 * this one. Dequeuing in monitor_qmp_bh_dispatcher() will resume
4316 * it. Note that when OOB is disabled, we queue at most one
4317 * command, for backward compatibility.
4319 if (!qmp_oob_enabled(mon) ||
4320 mon->qmp_requests->length == QMP_REQ_QUEUE_LEN_MAX - 1) {
4321 monitor_suspend(&mon->common);
4325 * Put the request to the end of queue so that requests will be
4326 * handled in time order. Ownership for req_obj, req,
4327 * etc. will be delivered to the handler side.
4329 assert(mon->qmp_requests->length < QMP_REQ_QUEUE_LEN_MAX);
4330 g_queue_push_tail(mon->qmp_requests, req_obj);
4331 qemu_mutex_unlock(&mon->qmp_queue_lock);
4333 /* Kick the dispatcher routine */
4334 qemu_bh_schedule(qmp_dispatcher_bh);
4337 static void monitor_qmp_read(void *opaque, const uint8_t *buf, int size)
4339 MonitorQMP *mon = opaque;
4341 json_message_parser_feed(&mon->parser, (const char *) buf, size);
4344 static void monitor_read(void *opaque, const uint8_t *buf, int size)
4346 MonitorHMP *mon;
4347 Monitor *old_mon = cur_mon;
4348 int i;
4350 cur_mon = opaque;
4351 mon = container_of(cur_mon, MonitorHMP, common);
4353 if (mon->rs) {
4354 for (i = 0; i < size; i++)
4355 readline_handle_byte(mon->rs, buf[i]);
4356 } else {
4357 if (size == 0 || buf[size - 1] != 0)
4358 monitor_printf(cur_mon, "corrupted command\n");
4359 else
4360 handle_hmp_command(mon, (char *)buf);
4363 cur_mon = old_mon;
4366 static void monitor_command_cb(void *opaque, const char *cmdline,
4367 void *readline_opaque)
4369 MonitorHMP *mon = opaque;
4371 monitor_suspend(&mon->common);
4372 handle_hmp_command(mon, cmdline);
4373 monitor_resume(&mon->common);
4376 int monitor_suspend(Monitor *mon)
4378 if (monitor_is_hmp_non_interactive(mon)) {
4379 return -ENOTTY;
4382 atomic_inc(&mon->suspend_cnt);
4384 if (mon->use_io_thread) {
4386 * Kick I/O thread to make sure this takes effect. It'll be
4387 * evaluated again in prepare() of the watch object.
4389 aio_notify(iothread_get_aio_context(mon_iothread));
4392 trace_monitor_suspend(mon, 1);
4393 return 0;
4396 static void monitor_accept_input(void *opaque)
4398 Monitor *mon = opaque;
4400 qemu_chr_fe_accept_input(&mon->chr);
4403 void monitor_resume(Monitor *mon)
4405 if (monitor_is_hmp_non_interactive(mon)) {
4406 return;
4409 if (atomic_dec_fetch(&mon->suspend_cnt) == 0) {
4410 AioContext *ctx;
4412 if (mon->use_io_thread) {
4413 ctx = iothread_get_aio_context(mon_iothread);
4414 } else {
4415 ctx = qemu_get_aio_context();
4418 if (!monitor_is_qmp(mon)) {
4419 MonitorHMP *hmp_mon = container_of(mon, MonitorHMP, common);
4420 assert(hmp_mon->rs);
4421 readline_show_prompt(hmp_mon->rs);
4424 aio_bh_schedule_oneshot(ctx, monitor_accept_input, mon);
4427 trace_monitor_suspend(mon, -1);
4430 static QDict *qmp_greeting(MonitorQMP *mon)
4432 QList *cap_list = qlist_new();
4433 QObject *ver = NULL;
4434 QMPCapability cap;
4436 qmp_marshal_query_version(NULL, &ver, NULL);
4438 for (cap = 0; cap < QMP_CAPABILITY__MAX; cap++) {
4439 if (mon->capab_offered[cap]) {
4440 qlist_append_str(cap_list, QMPCapability_str(cap));
4444 return qdict_from_jsonf_nofail(
4445 "{'QMP': {'version': %p, 'capabilities': %p}}",
4446 ver, cap_list);
4449 static void monitor_qmp_event(void *opaque, int event)
4451 QDict *data;
4452 MonitorQMP *mon = opaque;
4454 switch (event) {
4455 case CHR_EVENT_OPENED:
4456 mon->commands = &qmp_cap_negotiation_commands;
4457 monitor_qmp_caps_reset(mon);
4458 data = qmp_greeting(mon);
4459 qmp_send_response(mon, data);
4460 qobject_unref(data);
4461 mon_refcount++;
4462 break;
4463 case CHR_EVENT_CLOSED:
4465 * Note: this is only useful when the output of the chardev
4466 * backend is still open. For example, when the backend is
4467 * stdio, it's possible that stdout is still open when stdin
4468 * is closed.
4470 monitor_qmp_cleanup_queues(mon);
4471 json_message_parser_destroy(&mon->parser);
4472 json_message_parser_init(&mon->parser, handle_qmp_command,
4473 mon, NULL);
4474 mon_refcount--;
4475 monitor_fdsets_cleanup();
4476 break;
4480 static void monitor_event(void *opaque, int event)
4482 Monitor *mon = opaque;
4483 MonitorHMP *hmp_mon = container_of(mon, MonitorHMP, common);
4485 switch (event) {
4486 case CHR_EVENT_MUX_IN:
4487 qemu_mutex_lock(&mon->mon_lock);
4488 mon->mux_out = 0;
4489 qemu_mutex_unlock(&mon->mon_lock);
4490 if (mon->reset_seen) {
4491 readline_restart(hmp_mon->rs);
4492 monitor_resume(mon);
4493 monitor_flush(mon);
4494 } else {
4495 atomic_mb_set(&mon->suspend_cnt, 0);
4497 break;
4499 case CHR_EVENT_MUX_OUT:
4500 if (mon->reset_seen) {
4501 if (atomic_mb_read(&mon->suspend_cnt) == 0) {
4502 monitor_printf(mon, "\n");
4504 monitor_flush(mon);
4505 monitor_suspend(mon);
4506 } else {
4507 atomic_inc(&mon->suspend_cnt);
4509 qemu_mutex_lock(&mon->mon_lock);
4510 mon->mux_out = 1;
4511 qemu_mutex_unlock(&mon->mon_lock);
4512 break;
4514 case CHR_EVENT_OPENED:
4515 monitor_printf(mon, "QEMU %s monitor - type 'help' for more "
4516 "information\n", QEMU_VERSION);
4517 if (!mon->mux_out) {
4518 readline_restart(hmp_mon->rs);
4519 readline_show_prompt(hmp_mon->rs);
4521 mon->reset_seen = 1;
4522 mon_refcount++;
4523 break;
4525 case CHR_EVENT_CLOSED:
4526 mon_refcount--;
4527 monitor_fdsets_cleanup();
4528 break;
4532 static int
4533 compare_mon_cmd(const void *a, const void *b)
4535 return strcmp(((const mon_cmd_t *)a)->name,
4536 ((const mon_cmd_t *)b)->name);
4539 static void sortcmdlist(void)
4541 int array_num;
4542 int elem_size = sizeof(mon_cmd_t);
4544 array_num = sizeof(mon_cmds)/elem_size-1;
4545 qsort((void *)mon_cmds, array_num, elem_size, compare_mon_cmd);
4547 array_num = sizeof(info_cmds)/elem_size-1;
4548 qsort((void *)info_cmds, array_num, elem_size, compare_mon_cmd);
4551 static void monitor_iothread_init(void)
4553 mon_iothread = iothread_create("mon_iothread", &error_abort);
4556 void monitor_init_globals(void)
4558 monitor_init_qmp_commands();
4559 monitor_qapi_event_init();
4560 sortcmdlist();
4561 qemu_mutex_init(&monitor_lock);
4562 qemu_mutex_init(&mon_fdsets_lock);
4565 * The dispatcher BH must run in the main loop thread, since we
4566 * have commands assuming that context. It would be nice to get
4567 * rid of those assumptions.
4569 qmp_dispatcher_bh = aio_bh_new(iohandler_get_aio_context(),
4570 monitor_qmp_bh_dispatcher,
4571 NULL);
4574 /* These functions just adapt the readline interface in a typesafe way. We
4575 * could cast function pointers but that discards compiler checks.
4577 static void GCC_FMT_ATTR(2, 3) monitor_readline_printf(void *opaque,
4578 const char *fmt, ...)
4580 MonitorHMP *mon = opaque;
4581 va_list ap;
4582 va_start(ap, fmt);
4583 monitor_vprintf(&mon->common, fmt, ap);
4584 va_end(ap);
4587 static void monitor_readline_flush(void *opaque)
4589 MonitorHMP *mon = opaque;
4590 monitor_flush(&mon->common);
4594 * Print to current monitor if we have one, else to stderr.
4596 int error_vprintf(const char *fmt, va_list ap)
4598 if (cur_mon && !monitor_cur_is_qmp()) {
4599 return monitor_vprintf(cur_mon, fmt, ap);
4601 return vfprintf(stderr, fmt, ap);
4604 int error_vprintf_unless_qmp(const char *fmt, va_list ap)
4606 if (!cur_mon) {
4607 return vfprintf(stderr, fmt, ap);
4609 if (!monitor_cur_is_qmp()) {
4610 return monitor_vprintf(cur_mon, fmt, ap);
4612 return -1;
4615 static void monitor_list_append(Monitor *mon)
4617 qemu_mutex_lock(&monitor_lock);
4619 * This prevents inserting new monitors during monitor_cleanup().
4620 * A cleaner solution would involve the main thread telling other
4621 * threads to terminate, waiting for their termination.
4623 if (!monitor_destroyed) {
4624 QTAILQ_INSERT_HEAD(&mon_list, mon, entry);
4625 mon = NULL;
4627 qemu_mutex_unlock(&monitor_lock);
4629 if (mon) {
4630 monitor_data_destroy(mon);
4631 g_free(mon);
4635 static void monitor_qmp_setup_handlers_bh(void *opaque)
4637 MonitorQMP *mon = opaque;
4638 GMainContext *context;
4640 assert(mon->common.use_io_thread);
4641 context = iothread_get_g_main_context(mon_iothread);
4642 assert(context);
4643 qemu_chr_fe_set_handlers(&mon->common.chr, monitor_can_read,
4644 monitor_qmp_read, monitor_qmp_event,
4645 NULL, &mon->common, context, true);
4646 monitor_list_append(&mon->common);
4649 static void monitor_init_qmp(Chardev *chr, int flags)
4651 MonitorQMP *mon = g_new0(MonitorQMP, 1);
4653 /* Only HMP supports readline */
4654 assert(!(flags & MONITOR_USE_READLINE));
4656 /* Note: we run QMP monitor in I/O thread when @chr supports that */
4657 monitor_data_init(&mon->common, flags, false,
4658 qemu_chr_has_feature(chr, QEMU_CHAR_FEATURE_GCONTEXT));
4660 qemu_mutex_init(&mon->qmp_queue_lock);
4661 mon->qmp_requests = g_queue_new();
4663 qemu_chr_fe_init(&mon->common.chr, chr, &error_abort);
4664 qemu_chr_fe_set_echo(&mon->common.chr, true);
4666 json_message_parser_init(&mon->parser, handle_qmp_command, mon, NULL);
4667 if (mon->common.use_io_thread) {
4669 * Make sure the old iowatch is gone. It's possible when
4670 * e.g. the chardev is in client mode, with wait=on.
4672 remove_fd_in_watch(chr);
4674 * We can't call qemu_chr_fe_set_handlers() directly here
4675 * since chardev might be running in the monitor I/O
4676 * thread. Schedule a bottom half.
4678 aio_bh_schedule_oneshot(iothread_get_aio_context(mon_iothread),
4679 monitor_qmp_setup_handlers_bh, mon);
4680 /* The bottom half will add @mon to @mon_list */
4681 } else {
4682 qemu_chr_fe_set_handlers(&mon->common.chr, monitor_can_read,
4683 monitor_qmp_read, monitor_qmp_event,
4684 NULL, &mon->common, NULL, true);
4685 monitor_list_append(&mon->common);
4689 static void monitor_init_hmp(Chardev *chr, int flags)
4691 MonitorHMP *mon = g_new0(MonitorHMP, 1);
4692 bool use_readline = flags & MONITOR_USE_READLINE;
4694 monitor_data_init(&mon->common, flags, false, false);
4695 qemu_chr_fe_init(&mon->common.chr, chr, &error_abort);
4697 if (use_readline) {
4698 mon->rs = readline_init(monitor_readline_printf,
4699 monitor_readline_flush,
4700 mon,
4701 monitor_find_completion);
4702 monitor_read_command(mon, 0);
4705 qemu_chr_fe_set_handlers(&mon->common.chr, monitor_can_read, monitor_read,
4706 monitor_event, NULL, &mon->common, NULL, true);
4707 monitor_list_append(&mon->common);
4710 void monitor_init(Chardev *chr, int flags)
4712 if (flags & MONITOR_USE_CONTROL) {
4713 monitor_init_qmp(chr, flags);
4714 } else {
4715 monitor_init_hmp(chr, flags);
4719 void monitor_cleanup(void)
4722 * We need to explicitly stop the I/O thread (but not destroy it),
4723 * clean up the monitor resources, then destroy the I/O thread since
4724 * we need to unregister from chardev below in
4725 * monitor_data_destroy(), and chardev is not thread-safe yet
4727 if (mon_iothread) {
4728 iothread_stop(mon_iothread);
4731 /* Flush output buffers and destroy monitors */
4732 qemu_mutex_lock(&monitor_lock);
4733 monitor_destroyed = true;
4734 while (!QTAILQ_EMPTY(&mon_list)) {
4735 Monitor *mon = QTAILQ_FIRST(&mon_list);
4736 QTAILQ_REMOVE(&mon_list, mon, entry);
4737 /* Permit QAPI event emission from character frontend release */
4738 qemu_mutex_unlock(&monitor_lock);
4739 monitor_flush(mon);
4740 monitor_data_destroy(mon);
4741 qemu_mutex_lock(&monitor_lock);
4742 g_free(mon);
4744 qemu_mutex_unlock(&monitor_lock);
4746 /* QEMUBHs needs to be deleted before destroying the I/O thread */
4747 qemu_bh_delete(qmp_dispatcher_bh);
4748 qmp_dispatcher_bh = NULL;
4749 if (mon_iothread) {
4750 iothread_destroy(mon_iothread);
4751 mon_iothread = NULL;
4755 QemuOptsList qemu_mon_opts = {
4756 .name = "mon",
4757 .implied_opt_name = "chardev",
4758 .head = QTAILQ_HEAD_INITIALIZER(qemu_mon_opts.head),
4759 .desc = {
4761 .name = "mode",
4762 .type = QEMU_OPT_STRING,
4764 .name = "chardev",
4765 .type = QEMU_OPT_STRING,
4767 .name = "pretty",
4768 .type = QEMU_OPT_BOOL,
4770 { /* end of list */ }
4774 HotpluggableCPUList *qmp_query_hotpluggable_cpus(Error **errp)
4776 MachineState *ms = MACHINE(qdev_get_machine());
4777 MachineClass *mc = MACHINE_GET_CLASS(ms);
4779 if (!mc->has_hotpluggable_cpus) {
4780 error_setg(errp, QERR_FEATURE_DISABLED, "query-hotpluggable-cpus");
4781 return NULL;
4784 return machine_query_hotpluggable_cpus(ms);