qapi: introduce new cmd option "allow-oob"
[qemu/ar7.git] / monitor.c
blob017ddca6e27fda4cc9329f079d1f00e10dd031bd
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 <dirent.h>
27 #include "cpu.h"
28 #include "hw/hw.h"
29 #include "monitor/qdev.h"
30 #include "hw/usb.h"
31 #include "hw/pci/pci.h"
32 #include "sysemu/watchdog.h"
33 #include "hw/loader.h"
34 #include "exec/gdbstub.h"
35 #include "net/net.h"
36 #include "net/slirp.h"
37 #include "chardev/char-fe.h"
38 #include "chardev/char-io.h"
39 #include "ui/qemu-spice.h"
40 #include "sysemu/numa.h"
41 #include "monitor/monitor.h"
42 #include "qemu/config-file.h"
43 #include "qemu/readline.h"
44 #include "ui/console.h"
45 #include "ui/input.h"
46 #include "sysemu/blockdev.h"
47 #include "sysemu/block-backend.h"
48 #include "audio/audio.h"
49 #include "disas/disas.h"
50 #include "sysemu/balloon.h"
51 #include "qemu/timer.h"
52 #include "sysemu/hw_accel.h"
53 #include "qemu/acl.h"
54 #include "sysemu/tpm.h"
55 #include "qapi/qmp/qdict.h"
56 #include "qapi/qmp/qerror.h"
57 #include "qapi/qmp/qnum.h"
58 #include "qapi/qmp/qstring.h"
59 #include "qapi/qmp/qjson.h"
60 #include "qapi/qmp/json-streamer.h"
61 #include "qapi/qmp/json-parser.h"
62 #include "qapi/qmp/qlist.h"
63 #include "qom/object_interfaces.h"
64 #include "trace-root.h"
65 #include "trace/control.h"
66 #include "monitor/hmp-target.h"
67 #ifdef CONFIG_TRACE_SIMPLE
68 #include "trace/simple.h"
69 #endif
70 #include "exec/memory.h"
71 #include "exec/exec-all.h"
72 #include "qemu/log.h"
73 #include "qemu/option.h"
74 #include "hmp.h"
75 #include "qemu/thread.h"
76 #include "block/qapi.h"
77 #include "qapi/qapi-commands.h"
78 #include "qapi/qapi-events.h"
79 #include "qapi/error.h"
80 #include "qapi/qmp-event.h"
81 #include "qapi/qapi-introspect.h"
82 #include "sysemu/qtest.h"
83 #include "sysemu/cpus.h"
84 #include "sysemu/iothread.h"
85 #include "qemu/cutils.h"
87 #if defined(TARGET_S390X)
88 #include "hw/s390x/storage-keys.h"
89 #include "hw/s390x/storage-attributes.h"
90 #endif
93 * Supported types:
95 * 'F' filename
96 * 'B' block device name
97 * 's' string (accept optional quote)
98 * 'S' it just appends the rest of the string (accept optional quote)
99 * 'O' option string of the form NAME=VALUE,...
100 * parsed according to QemuOptsList given by its name
101 * Example: 'device:O' uses qemu_device_opts.
102 * Restriction: only lists with empty desc are supported
103 * TODO lift the restriction
104 * 'i' 32 bit integer
105 * 'l' target long (32 or 64 bit)
106 * 'M' Non-negative target long (32 or 64 bit), in user mode the
107 * value is multiplied by 2^20 (think Mebibyte)
108 * 'o' octets (aka bytes)
109 * user mode accepts an optional E, e, P, p, T, t, G, g, M, m,
110 * K, k suffix, which multiplies the value by 2^60 for suffixes E
111 * and e, 2^50 for suffixes P and p, 2^40 for suffixes T and t,
112 * 2^30 for suffixes G and g, 2^20 for M and m, 2^10 for K and k
113 * 'T' double
114 * user mode accepts an optional ms, us, ns suffix,
115 * which divides the value by 1e3, 1e6, 1e9, respectively
116 * '/' optional gdb-like print format (like "/10x")
118 * '?' optional type (for all types, except '/')
119 * '.' other form of optional type (for 'i' and 'l')
120 * 'b' boolean
121 * user mode accepts "on" or "off"
122 * '-' optional parameter (eg. '-f')
126 typedef struct mon_cmd_t {
127 const char *name;
128 const char *args_type;
129 const char *params;
130 const char *help;
131 void (*cmd)(Monitor *mon, const QDict *qdict);
132 /* @sub_table is a list of 2nd level of commands. If it does not exist,
133 * cmd should be used. If it exists, sub_table[?].cmd should be
134 * used, and cmd of 1st level plays the role of help function.
136 struct mon_cmd_t *sub_table;
137 void (*command_completion)(ReadLineState *rs, int nb_args, const char *str);
138 } mon_cmd_t;
140 /* file descriptors passed via SCM_RIGHTS */
141 typedef struct mon_fd_t mon_fd_t;
142 struct mon_fd_t {
143 char *name;
144 int fd;
145 QLIST_ENTRY(mon_fd_t) next;
148 /* file descriptor associated with a file descriptor set */
149 typedef struct MonFdsetFd MonFdsetFd;
150 struct MonFdsetFd {
151 int fd;
152 bool removed;
153 char *opaque;
154 QLIST_ENTRY(MonFdsetFd) next;
157 /* file descriptor set containing fds passed via SCM_RIGHTS */
158 typedef struct MonFdset MonFdset;
159 struct MonFdset {
160 int64_t id;
161 QLIST_HEAD(, MonFdsetFd) fds;
162 QLIST_HEAD(, MonFdsetFd) dup_fds;
163 QLIST_ENTRY(MonFdset) next;
166 typedef struct {
167 JSONMessageParser parser;
169 * When a client connects, we're in capabilities negotiation mode.
170 * When command qmp_capabilities succeeds, we go into command
171 * mode.
173 QmpCommandList *commands;
174 bool qmp_caps[QMP_CAPABILITY__MAX];
176 * Protects qmp request/response queue. Please take monitor_lock
177 * first when used together.
179 QemuMutex qmp_queue_lock;
180 /* Input queue that holds all the parsed QMP requests */
181 GQueue *qmp_requests;
182 } MonitorQMP;
185 * To prevent flooding clients, events can be throttled. The
186 * throttling is calculated globally, rather than per-Monitor
187 * instance.
189 typedef struct MonitorQAPIEventState {
190 QAPIEvent event; /* Throttling state for this event type and... */
191 QDict *data; /* ... data, see qapi_event_throttle_equal() */
192 QEMUTimer *timer; /* Timer for handling delayed events */
193 QDict *qdict; /* Delayed event (if any) */
194 } MonitorQAPIEventState;
196 typedef struct {
197 int64_t rate; /* Minimum time (in ns) between two events */
198 } MonitorQAPIEventConf;
200 struct Monitor {
201 CharBackend chr;
202 int reset_seen;
203 int flags;
204 int suspend_cnt; /* Needs to be accessed atomically */
205 bool skip_flush;
206 bool use_io_thr;
208 QemuMutex out_lock;
209 QString *outbuf;
210 guint out_watch;
212 /* Read under either BQL or out_lock, written with BQL+out_lock. */
213 int mux_out;
215 ReadLineState *rs;
216 MonitorQMP qmp;
217 gchar *mon_cpu_path;
218 BlockCompletionFunc *password_completion_cb;
219 void *password_opaque;
220 mon_cmd_t *cmd_table;
221 QLIST_HEAD(,mon_fd_t) fds;
222 QTAILQ_ENTRY(Monitor) entry;
225 /* Let's add monitor global variables to this struct. */
226 static struct {
227 IOThread *mon_iothread;
228 /* Bottom half to dispatch the requests received from IO thread */
229 QEMUBH *qmp_dispatcher_bh;
230 } mon_global;
232 /* QMP checker flags */
233 #define QMP_ACCEPT_UNKNOWNS 1
235 /* Protects mon_list, monitor_event_state. */
236 static QemuMutex monitor_lock;
238 static QTAILQ_HEAD(mon_list, Monitor) mon_list;
239 static QLIST_HEAD(mon_fdsets, MonFdset) mon_fdsets;
240 static int mon_refcount;
242 static mon_cmd_t mon_cmds[];
243 static mon_cmd_t info_cmds[];
245 QmpCommandList qmp_commands, qmp_cap_negotiation_commands;
247 Monitor *cur_mon;
249 static QEMUClockType event_clock_type = QEMU_CLOCK_REALTIME;
251 static void monitor_command_cb(void *opaque, const char *cmdline,
252 void *readline_opaque);
255 * Is @mon a QMP monitor?
257 static inline bool monitor_is_qmp(const Monitor *mon)
259 return (mon->flags & MONITOR_USE_CONTROL);
263 * Whether @mon is using readline? Note: not all HMP monitors use
264 * readline, e.g., gdbserver has a non-interactive HMP monitor, so
265 * readline is not used there.
267 static inline bool monitor_uses_readline(const Monitor *mon)
269 return mon->flags & MONITOR_USE_READLINE;
272 static inline bool monitor_is_hmp_non_interactive(const Monitor *mon)
274 return !monitor_is_qmp(mon) && !monitor_uses_readline(mon);
278 * Is the current monitor, if any, a QMP monitor?
280 bool monitor_cur_is_qmp(void)
282 return cur_mon && monitor_is_qmp(cur_mon);
285 void monitor_read_command(Monitor *mon, int show_prompt)
287 if (!mon->rs)
288 return;
290 readline_start(mon->rs, "(qemu) ", 0, monitor_command_cb, NULL);
291 if (show_prompt)
292 readline_show_prompt(mon->rs);
295 int monitor_read_password(Monitor *mon, ReadLineFunc *readline_func,
296 void *opaque)
298 if (mon->rs) {
299 readline_start(mon->rs, "Password: ", 1, readline_func, opaque);
300 /* prompt is printed on return from the command handler */
301 return 0;
302 } else {
303 monitor_printf(mon, "terminal does not support password prompting\n");
304 return -ENOTTY;
308 static void monitor_flush_locked(Monitor *mon);
310 static gboolean monitor_unblocked(GIOChannel *chan, GIOCondition cond,
311 void *opaque)
313 Monitor *mon = opaque;
315 qemu_mutex_lock(&mon->out_lock);
316 mon->out_watch = 0;
317 monitor_flush_locked(mon);
318 qemu_mutex_unlock(&mon->out_lock);
319 return FALSE;
322 /* Called with mon->out_lock held. */
323 static void monitor_flush_locked(Monitor *mon)
325 int rc;
326 size_t len;
327 const char *buf;
329 if (mon->skip_flush) {
330 return;
333 buf = qstring_get_str(mon->outbuf);
334 len = qstring_get_length(mon->outbuf);
336 if (len && !mon->mux_out) {
337 rc = qemu_chr_fe_write(&mon->chr, (const uint8_t *) buf, len);
338 if ((rc < 0 && errno != EAGAIN) || (rc == len)) {
339 /* all flushed or error */
340 QDECREF(mon->outbuf);
341 mon->outbuf = qstring_new();
342 return;
344 if (rc > 0) {
345 /* partial write */
346 QString *tmp = qstring_from_str(buf + rc);
347 QDECREF(mon->outbuf);
348 mon->outbuf = tmp;
350 if (mon->out_watch == 0) {
351 mon->out_watch =
352 qemu_chr_fe_add_watch(&mon->chr, G_IO_OUT | G_IO_HUP,
353 monitor_unblocked, mon);
358 void monitor_flush(Monitor *mon)
360 qemu_mutex_lock(&mon->out_lock);
361 monitor_flush_locked(mon);
362 qemu_mutex_unlock(&mon->out_lock);
365 /* flush at every end of line */
366 static void monitor_puts(Monitor *mon, const char *str)
368 char c;
370 qemu_mutex_lock(&mon->out_lock);
371 for(;;) {
372 c = *str++;
373 if (c == '\0')
374 break;
375 if (c == '\n') {
376 qstring_append_chr(mon->outbuf, '\r');
378 qstring_append_chr(mon->outbuf, c);
379 if (c == '\n') {
380 monitor_flush_locked(mon);
383 qemu_mutex_unlock(&mon->out_lock);
386 void monitor_vprintf(Monitor *mon, const char *fmt, va_list ap)
388 char *buf;
390 if (!mon)
391 return;
393 if (monitor_is_qmp(mon)) {
394 return;
397 buf = g_strdup_vprintf(fmt, ap);
398 monitor_puts(mon, buf);
399 g_free(buf);
402 void monitor_printf(Monitor *mon, const char *fmt, ...)
404 va_list ap;
405 va_start(ap, fmt);
406 monitor_vprintf(mon, fmt, ap);
407 va_end(ap);
410 int monitor_fprintf(FILE *stream, const char *fmt, ...)
412 va_list ap;
413 va_start(ap, fmt);
414 monitor_vprintf((Monitor *)stream, fmt, ap);
415 va_end(ap);
416 return 0;
419 static void monitor_json_emitter(Monitor *mon, const QObject *data)
421 QString *json;
423 json = mon->flags & MONITOR_USE_PRETTY ? qobject_to_json_pretty(data) :
424 qobject_to_json(data);
425 assert(json != NULL);
427 qstring_append_chr(json, '\n');
428 monitor_puts(mon, qstring_get_str(json));
430 QDECREF(json);
433 static MonitorQAPIEventConf monitor_qapi_event_conf[QAPI_EVENT__MAX] = {
434 /* Limit guest-triggerable events to 1 per second */
435 [QAPI_EVENT_RTC_CHANGE] = { 1000 * SCALE_MS },
436 [QAPI_EVENT_WATCHDOG] = { 1000 * SCALE_MS },
437 [QAPI_EVENT_BALLOON_CHANGE] = { 1000 * SCALE_MS },
438 [QAPI_EVENT_QUORUM_REPORT_BAD] = { 1000 * SCALE_MS },
439 [QAPI_EVENT_QUORUM_FAILURE] = { 1000 * SCALE_MS },
440 [QAPI_EVENT_VSERPORT_CHANGE] = { 1000 * SCALE_MS },
443 GHashTable *monitor_qapi_event_state;
446 * Emits the event to every monitor instance, @event is only used for trace
447 * Called with monitor_lock held.
449 static void monitor_qapi_event_emit(QAPIEvent event, QDict *qdict)
451 Monitor *mon;
453 trace_monitor_protocol_event_emit(event, qdict);
454 QTAILQ_FOREACH(mon, &mon_list, entry) {
455 if (monitor_is_qmp(mon)
456 && mon->qmp.commands != &qmp_cap_negotiation_commands) {
457 monitor_json_emitter(mon, QOBJECT(qdict));
462 static void monitor_qapi_event_handler(void *opaque);
465 * Queue a new event for emission to Monitor instances,
466 * applying any rate limiting if required.
468 static void
469 monitor_qapi_event_queue(QAPIEvent event, QDict *qdict, Error **errp)
471 MonitorQAPIEventConf *evconf;
472 MonitorQAPIEventState *evstate;
474 assert(event < QAPI_EVENT__MAX);
475 evconf = &monitor_qapi_event_conf[event];
476 trace_monitor_protocol_event_queue(event, qdict, evconf->rate);
478 qemu_mutex_lock(&monitor_lock);
480 if (!evconf->rate) {
481 /* Unthrottled event */
482 monitor_qapi_event_emit(event, qdict);
483 } else {
484 QDict *data = qobject_to(QDict, qdict_get(qdict, "data"));
485 MonitorQAPIEventState key = { .event = event, .data = data };
487 evstate = g_hash_table_lookup(monitor_qapi_event_state, &key);
488 assert(!evstate || timer_pending(evstate->timer));
490 if (evstate) {
492 * Timer is pending for (at least) evconf->rate ns after
493 * last send. Store event for sending when timer fires,
494 * replacing a prior stored event if any.
496 QDECREF(evstate->qdict);
497 evstate->qdict = qdict;
498 QINCREF(evstate->qdict);
499 } else {
501 * Last send was (at least) evconf->rate ns ago.
502 * Send immediately, and arm the timer to call
503 * monitor_qapi_event_handler() in evconf->rate ns. Any
504 * events arriving before then will be delayed until then.
506 int64_t now = qemu_clock_get_ns(event_clock_type);
508 monitor_qapi_event_emit(event, qdict);
510 evstate = g_new(MonitorQAPIEventState, 1);
511 evstate->event = event;
512 evstate->data = data;
513 QINCREF(evstate->data);
514 evstate->qdict = NULL;
515 evstate->timer = timer_new_ns(event_clock_type,
516 monitor_qapi_event_handler,
517 evstate);
518 g_hash_table_add(monitor_qapi_event_state, evstate);
519 timer_mod_ns(evstate->timer, now + evconf->rate);
523 qemu_mutex_unlock(&monitor_lock);
527 * This function runs evconf->rate ns after sending a throttled
528 * event.
529 * If another event has since been stored, send it.
531 static void monitor_qapi_event_handler(void *opaque)
533 MonitorQAPIEventState *evstate = opaque;
534 MonitorQAPIEventConf *evconf = &monitor_qapi_event_conf[evstate->event];
536 trace_monitor_protocol_event_handler(evstate->event, evstate->qdict);
537 qemu_mutex_lock(&monitor_lock);
539 if (evstate->qdict) {
540 int64_t now = qemu_clock_get_ns(event_clock_type);
542 monitor_qapi_event_emit(evstate->event, evstate->qdict);
543 QDECREF(evstate->qdict);
544 evstate->qdict = NULL;
545 timer_mod_ns(evstate->timer, now + evconf->rate);
546 } else {
547 g_hash_table_remove(monitor_qapi_event_state, evstate);
548 QDECREF(evstate->data);
549 timer_free(evstate->timer);
550 g_free(evstate);
553 qemu_mutex_unlock(&monitor_lock);
556 static unsigned int qapi_event_throttle_hash(const void *key)
558 const MonitorQAPIEventState *evstate = key;
559 unsigned int hash = evstate->event * 255;
561 if (evstate->event == QAPI_EVENT_VSERPORT_CHANGE) {
562 hash += g_str_hash(qdict_get_str(evstate->data, "id"));
565 if (evstate->event == QAPI_EVENT_QUORUM_REPORT_BAD) {
566 hash += g_str_hash(qdict_get_str(evstate->data, "node-name"));
569 return hash;
572 static gboolean qapi_event_throttle_equal(const void *a, const void *b)
574 const MonitorQAPIEventState *eva = a;
575 const MonitorQAPIEventState *evb = b;
577 if (eva->event != evb->event) {
578 return FALSE;
581 if (eva->event == QAPI_EVENT_VSERPORT_CHANGE) {
582 return !strcmp(qdict_get_str(eva->data, "id"),
583 qdict_get_str(evb->data, "id"));
586 if (eva->event == QAPI_EVENT_QUORUM_REPORT_BAD) {
587 return !strcmp(qdict_get_str(eva->data, "node-name"),
588 qdict_get_str(evb->data, "node-name"));
591 return TRUE;
594 static void monitor_qapi_event_init(void)
596 if (qtest_enabled()) {
597 event_clock_type = QEMU_CLOCK_VIRTUAL;
600 monitor_qapi_event_state = g_hash_table_new(qapi_event_throttle_hash,
601 qapi_event_throttle_equal);
602 qmp_event_set_func_emit(monitor_qapi_event_queue);
605 static void handle_hmp_command(Monitor *mon, const char *cmdline);
607 static void monitor_data_init(Monitor *mon, bool skip_flush,
608 bool use_io_thr)
610 memset(mon, 0, sizeof(Monitor));
611 qemu_mutex_init(&mon->out_lock);
612 qemu_mutex_init(&mon->qmp.qmp_queue_lock);
613 mon->outbuf = qstring_new();
614 /* Use *mon_cmds by default. */
615 mon->cmd_table = mon_cmds;
616 mon->skip_flush = skip_flush;
617 mon->use_io_thr = use_io_thr;
618 mon->qmp.qmp_requests = g_queue_new();
621 static void monitor_data_destroy(Monitor *mon)
623 g_free(mon->mon_cpu_path);
624 qemu_chr_fe_deinit(&mon->chr, false);
625 if (monitor_is_qmp(mon)) {
626 json_message_parser_destroy(&mon->qmp.parser);
628 readline_free(mon->rs);
629 QDECREF(mon->outbuf);
630 qemu_mutex_destroy(&mon->out_lock);
631 qemu_mutex_destroy(&mon->qmp.qmp_queue_lock);
632 g_queue_free(mon->qmp.qmp_requests);
635 char *qmp_human_monitor_command(const char *command_line, bool has_cpu_index,
636 int64_t cpu_index, Error **errp)
638 char *output = NULL;
639 Monitor *old_mon, hmp;
641 monitor_data_init(&hmp, true, false);
643 old_mon = cur_mon;
644 cur_mon = &hmp;
646 if (has_cpu_index) {
647 int ret = monitor_set_cpu(cpu_index);
648 if (ret < 0) {
649 cur_mon = old_mon;
650 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cpu-index",
651 "a CPU number");
652 goto out;
656 handle_hmp_command(&hmp, command_line);
657 cur_mon = old_mon;
659 qemu_mutex_lock(&hmp.out_lock);
660 if (qstring_get_length(hmp.outbuf) > 0) {
661 output = g_strdup(qstring_get_str(hmp.outbuf));
662 } else {
663 output = g_strdup("");
665 qemu_mutex_unlock(&hmp.out_lock);
667 out:
668 monitor_data_destroy(&hmp);
669 return output;
672 static int compare_cmd(const char *name, const char *list)
674 const char *p, *pstart;
675 int len;
676 len = strlen(name);
677 p = list;
678 for(;;) {
679 pstart = p;
680 p = strchr(p, '|');
681 if (!p)
682 p = pstart + strlen(pstart);
683 if ((p - pstart) == len && !memcmp(pstart, name, len))
684 return 1;
685 if (*p == '\0')
686 break;
687 p++;
689 return 0;
692 static int get_str(char *buf, int buf_size, const char **pp)
694 const char *p;
695 char *q;
696 int c;
698 q = buf;
699 p = *pp;
700 while (qemu_isspace(*p)) {
701 p++;
703 if (*p == '\0') {
704 fail:
705 *q = '\0';
706 *pp = p;
707 return -1;
709 if (*p == '\"') {
710 p++;
711 while (*p != '\0' && *p != '\"') {
712 if (*p == '\\') {
713 p++;
714 c = *p++;
715 switch (c) {
716 case 'n':
717 c = '\n';
718 break;
719 case 'r':
720 c = '\r';
721 break;
722 case '\\':
723 case '\'':
724 case '\"':
725 break;
726 default:
727 printf("unsupported escape code: '\\%c'\n", c);
728 goto fail;
730 if ((q - buf) < buf_size - 1) {
731 *q++ = c;
733 } else {
734 if ((q - buf) < buf_size - 1) {
735 *q++ = *p;
737 p++;
740 if (*p != '\"') {
741 printf("unterminated string\n");
742 goto fail;
744 p++;
745 } else {
746 while (*p != '\0' && !qemu_isspace(*p)) {
747 if ((q - buf) < buf_size - 1) {
748 *q++ = *p;
750 p++;
753 *q = '\0';
754 *pp = p;
755 return 0;
758 #define MAX_ARGS 16
760 static void free_cmdline_args(char **args, int nb_args)
762 int i;
764 assert(nb_args <= MAX_ARGS);
766 for (i = 0; i < nb_args; i++) {
767 g_free(args[i]);
773 * Parse the command line to get valid args.
774 * @cmdline: command line to be parsed.
775 * @pnb_args: location to store the number of args, must NOT be NULL.
776 * @args: location to store the args, which should be freed by caller, must
777 * NOT be NULL.
779 * Returns 0 on success, negative on failure.
781 * NOTE: this parser is an approximate form of the real command parser. Number
782 * of args have a limit of MAX_ARGS. If cmdline contains more, it will
783 * return with failure.
785 static int parse_cmdline(const char *cmdline,
786 int *pnb_args, char **args)
788 const char *p;
789 int nb_args, ret;
790 char buf[1024];
792 p = cmdline;
793 nb_args = 0;
794 for (;;) {
795 while (qemu_isspace(*p)) {
796 p++;
798 if (*p == '\0') {
799 break;
801 if (nb_args >= MAX_ARGS) {
802 goto fail;
804 ret = get_str(buf, sizeof(buf), &p);
805 if (ret < 0) {
806 goto fail;
808 args[nb_args] = g_strdup(buf);
809 nb_args++;
811 *pnb_args = nb_args;
812 return 0;
814 fail:
815 free_cmdline_args(args, nb_args);
816 return -1;
819 static void help_cmd_dump_one(Monitor *mon,
820 const mon_cmd_t *cmd,
821 char **prefix_args,
822 int prefix_args_nb)
824 int i;
826 for (i = 0; i < prefix_args_nb; i++) {
827 monitor_printf(mon, "%s ", prefix_args[i]);
829 monitor_printf(mon, "%s %s -- %s\n", cmd->name, cmd->params, cmd->help);
832 /* @args[@arg_index] is the valid command need to find in @cmds */
833 static void help_cmd_dump(Monitor *mon, const mon_cmd_t *cmds,
834 char **args, int nb_args, int arg_index)
836 const mon_cmd_t *cmd;
838 /* No valid arg need to compare with, dump all in *cmds */
839 if (arg_index >= nb_args) {
840 for (cmd = cmds; cmd->name != NULL; cmd++) {
841 help_cmd_dump_one(mon, cmd, args, arg_index);
843 return;
846 /* Find one entry to dump */
847 for (cmd = cmds; cmd->name != NULL; cmd++) {
848 if (compare_cmd(args[arg_index], cmd->name)) {
849 if (cmd->sub_table) {
850 /* continue with next arg */
851 help_cmd_dump(mon, cmd->sub_table,
852 args, nb_args, arg_index + 1);
853 } else {
854 help_cmd_dump_one(mon, cmd, args, arg_index);
856 break;
861 static void help_cmd(Monitor *mon, const char *name)
863 char *args[MAX_ARGS];
864 int nb_args = 0;
866 /* 1. parse user input */
867 if (name) {
868 /* special case for log, directly dump and return */
869 if (!strcmp(name, "log")) {
870 const QEMULogItem *item;
871 monitor_printf(mon, "Log items (comma separated):\n");
872 monitor_printf(mon, "%-10s %s\n", "none", "remove all logs");
873 for (item = qemu_log_items; item->mask != 0; item++) {
874 monitor_printf(mon, "%-10s %s\n", item->name, item->help);
876 return;
879 if (parse_cmdline(name, &nb_args, args) < 0) {
880 return;
884 /* 2. dump the contents according to parsed args */
885 help_cmd_dump(mon, mon->cmd_table, args, nb_args, 0);
887 free_cmdline_args(args, nb_args);
890 static void do_help_cmd(Monitor *mon, const QDict *qdict)
892 help_cmd(mon, qdict_get_try_str(qdict, "name"));
895 static void hmp_trace_event(Monitor *mon, const QDict *qdict)
897 const char *tp_name = qdict_get_str(qdict, "name");
898 bool new_state = qdict_get_bool(qdict, "option");
899 bool has_vcpu = qdict_haskey(qdict, "vcpu");
900 int vcpu = qdict_get_try_int(qdict, "vcpu", 0);
901 Error *local_err = NULL;
903 if (vcpu < 0) {
904 monitor_printf(mon, "argument vcpu must be positive");
905 return;
908 qmp_trace_event_set_state(tp_name, new_state, true, true, has_vcpu, vcpu, &local_err);
909 if (local_err) {
910 error_report_err(local_err);
914 #ifdef CONFIG_TRACE_SIMPLE
915 static void hmp_trace_file(Monitor *mon, const QDict *qdict)
917 const char *op = qdict_get_try_str(qdict, "op");
918 const char *arg = qdict_get_try_str(qdict, "arg");
920 if (!op) {
921 st_print_trace_file_status((FILE *)mon, &monitor_fprintf);
922 } else if (!strcmp(op, "on")) {
923 st_set_trace_file_enabled(true);
924 } else if (!strcmp(op, "off")) {
925 st_set_trace_file_enabled(false);
926 } else if (!strcmp(op, "flush")) {
927 st_flush_trace_buffer();
928 } else if (!strcmp(op, "set")) {
929 if (arg) {
930 st_set_trace_file(arg);
932 } else {
933 monitor_printf(mon, "unexpected argument \"%s\"\n", op);
934 help_cmd(mon, "trace-file");
937 #endif
939 static void hmp_info_help(Monitor *mon, const QDict *qdict)
941 help_cmd(mon, "info");
944 static void query_commands_cb(QmpCommand *cmd, void *opaque)
946 CommandInfoList *info, **list = opaque;
948 if (!cmd->enabled) {
949 return;
952 info = g_malloc0(sizeof(*info));
953 info->value = g_malloc0(sizeof(*info->value));
954 info->value->name = g_strdup(cmd->name);
955 info->next = *list;
956 *list = info;
959 CommandInfoList *qmp_query_commands(Error **errp)
961 CommandInfoList *list = NULL;
963 qmp_for_each_command(cur_mon->qmp.commands, query_commands_cb, &list);
965 return list;
968 EventInfoList *qmp_query_events(Error **errp)
970 EventInfoList *info, *ev_list = NULL;
971 QAPIEvent e;
973 for (e = 0 ; e < QAPI_EVENT__MAX ; e++) {
974 const char *event_name = QAPIEvent_str(e);
975 assert(event_name != NULL);
976 info = g_malloc0(sizeof(*info));
977 info->value = g_malloc0(sizeof(*info->value));
978 info->value->name = g_strdup(event_name);
980 info->next = ev_list;
981 ev_list = info;
984 return ev_list;
988 * Minor hack: generated marshalling suppressed for this command
989 * ('gen': false in the schema) so we can parse the JSON string
990 * directly into QObject instead of first parsing it with
991 * visit_type_SchemaInfoList() into a SchemaInfoList, then marshal it
992 * to QObject with generated output marshallers, every time. Instead,
993 * we do it in test-qobject-input-visitor.c, just to make sure
994 * qapi-gen.py's output actually conforms to the schema.
996 static void qmp_query_qmp_schema(QDict *qdict, QObject **ret_data,
997 Error **errp)
999 *ret_data = qobject_from_qlit(&qmp_schema_qlit);
1003 * We used to define commands in qmp-commands.hx in addition to the
1004 * QAPI schema. This permitted defining some of them only in certain
1005 * configurations. query-commands has always reflected that (good,
1006 * because it lets QMP clients figure out what's actually available),
1007 * while query-qmp-schema never did (not so good). This function is a
1008 * hack to keep the configuration-specific commands defined exactly as
1009 * before, even though qmp-commands.hx is gone.
1011 * FIXME Educate the QAPI schema on configuration-specific commands,
1012 * and drop this hack.
1014 static void qmp_unregister_commands_hack(void)
1016 #ifndef CONFIG_SPICE
1017 qmp_unregister_command(&qmp_commands, "query-spice");
1018 #endif
1019 #ifndef CONFIG_REPLICATION
1020 qmp_unregister_command(&qmp_commands, "xen-set-replication");
1021 qmp_unregister_command(&qmp_commands, "query-xen-replication-status");
1022 qmp_unregister_command(&qmp_commands, "xen-colo-do-checkpoint");
1023 #endif
1024 #ifndef TARGET_I386
1025 qmp_unregister_command(&qmp_commands, "rtc-reset-reinjection");
1026 qmp_unregister_command(&qmp_commands, "query-sev");
1027 qmp_unregister_command(&qmp_commands, "query-sev-launch-measure");
1028 qmp_unregister_command(&qmp_commands, "query-sev-capabilities");
1029 #endif
1030 #ifndef TARGET_S390X
1031 qmp_unregister_command(&qmp_commands, "dump-skeys");
1032 #endif
1033 #ifndef TARGET_ARM
1034 qmp_unregister_command(&qmp_commands, "query-gic-capabilities");
1035 #endif
1036 #if !defined(TARGET_S390X) && !defined(TARGET_I386)
1037 qmp_unregister_command(&qmp_commands, "query-cpu-model-expansion");
1038 #endif
1039 #if !defined(TARGET_S390X)
1040 qmp_unregister_command(&qmp_commands, "query-cpu-model-baseline");
1041 qmp_unregister_command(&qmp_commands, "query-cpu-model-comparison");
1042 #endif
1043 #if !defined(TARGET_PPC) && !defined(TARGET_ARM) && !defined(TARGET_I386) \
1044 && !defined(TARGET_S390X)
1045 qmp_unregister_command(&qmp_commands, "query-cpu-definitions");
1046 #endif
1049 static void monitor_init_qmp_commands(void)
1052 * Two command lists:
1053 * - qmp_commands contains all QMP commands
1054 * - qmp_cap_negotiation_commands contains just
1055 * "qmp_capabilities", to enforce capability negotiation
1058 qmp_init_marshal(&qmp_commands);
1060 qmp_register_command(&qmp_commands, "query-qmp-schema",
1061 qmp_query_qmp_schema,
1062 QCO_NO_OPTIONS);
1063 qmp_register_command(&qmp_commands, "device_add", qmp_device_add,
1064 QCO_NO_OPTIONS);
1065 qmp_register_command(&qmp_commands, "netdev_add", qmp_netdev_add,
1066 QCO_NO_OPTIONS);
1068 qmp_unregister_commands_hack();
1070 QTAILQ_INIT(&qmp_cap_negotiation_commands);
1071 qmp_register_command(&qmp_cap_negotiation_commands, "qmp_capabilities",
1072 qmp_marshal_qmp_capabilities, QCO_NO_OPTIONS);
1075 static bool qmp_cap_enabled(Monitor *mon, QMPCapability cap)
1077 return mon->qmp.qmp_caps[cap];
1080 static bool qmp_oob_enabled(Monitor *mon)
1082 return qmp_cap_enabled(mon, QMP_CAPABILITY_OOB);
1085 static void qmp_caps_check(Monitor *mon, QMPCapabilityList *list,
1086 Error **errp)
1088 for (; list; list = list->next) {
1089 assert(list->value < QMP_CAPABILITY__MAX);
1090 switch (list->value) {
1091 case QMP_CAPABILITY_OOB:
1092 if (!mon->use_io_thr) {
1094 * Out-Of-Band only works with monitors that are
1095 * running on dedicated IOThread.
1097 error_setg(errp, "This monitor does not support "
1098 "Out-Of-Band (OOB)");
1099 return;
1101 break;
1102 default:
1103 break;
1108 /* This function should only be called after capabilities are checked. */
1109 static void qmp_caps_apply(Monitor *mon, QMPCapabilityList *list)
1111 for (; list; list = list->next) {
1112 mon->qmp.qmp_caps[list->value] = true;
1116 void qmp_qmp_capabilities(bool has_enable, QMPCapabilityList *enable,
1117 Error **errp)
1119 Error *local_err = NULL;
1121 if (cur_mon->qmp.commands == &qmp_commands) {
1122 error_set(errp, ERROR_CLASS_COMMAND_NOT_FOUND,
1123 "Capabilities negotiation is already complete, command "
1124 "ignored");
1125 return;
1128 /* Enable QMP capabilities provided by the client if applicable. */
1129 if (has_enable) {
1130 qmp_caps_check(cur_mon, enable, &local_err);
1131 if (local_err) {
1133 * Failed check on any of the capabilities will fail the
1134 * entire command (and thus not apply any of the other
1135 * capabilities that were also requested).
1137 error_propagate(errp, local_err);
1138 return;
1140 qmp_caps_apply(cur_mon, enable);
1143 cur_mon->qmp.commands = &qmp_commands;
1146 /* set the current CPU defined by the user */
1147 int monitor_set_cpu(int cpu_index)
1149 CPUState *cpu;
1151 cpu = qemu_get_cpu(cpu_index);
1152 if (cpu == NULL) {
1153 return -1;
1155 g_free(cur_mon->mon_cpu_path);
1156 cur_mon->mon_cpu_path = object_get_canonical_path(OBJECT(cpu));
1157 return 0;
1160 static CPUState *mon_get_cpu_sync(bool synchronize)
1162 CPUState *cpu;
1164 if (cur_mon->mon_cpu_path) {
1165 cpu = (CPUState *) object_resolve_path_type(cur_mon->mon_cpu_path,
1166 TYPE_CPU, NULL);
1167 if (!cpu) {
1168 g_free(cur_mon->mon_cpu_path);
1169 cur_mon->mon_cpu_path = NULL;
1172 if (!cur_mon->mon_cpu_path) {
1173 if (!first_cpu) {
1174 return NULL;
1176 monitor_set_cpu(first_cpu->cpu_index);
1177 cpu = first_cpu;
1179 if (synchronize) {
1180 cpu_synchronize_state(cpu);
1182 return cpu;
1185 CPUState *mon_get_cpu(void)
1187 return mon_get_cpu_sync(true);
1190 CPUArchState *mon_get_cpu_env(void)
1192 CPUState *cs = mon_get_cpu();
1194 return cs ? cs->env_ptr : NULL;
1197 int monitor_get_cpu_index(void)
1199 CPUState *cs = mon_get_cpu_sync(false);
1201 return cs ? cs->cpu_index : UNASSIGNED_CPU_INDEX;
1204 static void hmp_info_registers(Monitor *mon, const QDict *qdict)
1206 bool all_cpus = qdict_get_try_bool(qdict, "cpustate_all", false);
1207 CPUState *cs;
1209 if (all_cpus) {
1210 CPU_FOREACH(cs) {
1211 monitor_printf(mon, "\nCPU#%d\n", cs->cpu_index);
1212 cpu_dump_state(cs, (FILE *)mon, monitor_fprintf, CPU_DUMP_FPU);
1214 } else {
1215 cs = mon_get_cpu();
1217 if (!cs) {
1218 monitor_printf(mon, "No CPU available\n");
1219 return;
1222 cpu_dump_state(cs, (FILE *)mon, monitor_fprintf, CPU_DUMP_FPU);
1226 #ifdef CONFIG_TCG
1227 static void hmp_info_jit(Monitor *mon, const QDict *qdict)
1229 if (!tcg_enabled()) {
1230 error_report("JIT information is only available with accel=tcg");
1231 return;
1234 dump_exec_info((FILE *)mon, monitor_fprintf);
1235 dump_drift_info((FILE *)mon, monitor_fprintf);
1238 static void hmp_info_opcount(Monitor *mon, const QDict *qdict)
1240 dump_opcount_info((FILE *)mon, monitor_fprintf);
1242 #endif
1244 static void hmp_info_history(Monitor *mon, const QDict *qdict)
1246 int i;
1247 const char *str;
1249 if (!mon->rs)
1250 return;
1251 i = 0;
1252 for(;;) {
1253 str = readline_get_history(mon->rs, i);
1254 if (!str)
1255 break;
1256 monitor_printf(mon, "%d: '%s'\n", i, str);
1257 i++;
1261 static void hmp_info_cpustats(Monitor *mon, const QDict *qdict)
1263 CPUState *cs = mon_get_cpu();
1265 if (!cs) {
1266 monitor_printf(mon, "No CPU available\n");
1267 return;
1269 cpu_dump_statistics(cs, (FILE *)mon, &monitor_fprintf, 0);
1272 static void hmp_info_trace_events(Monitor *mon, const QDict *qdict)
1274 const char *name = qdict_get_try_str(qdict, "name");
1275 bool has_vcpu = qdict_haskey(qdict, "vcpu");
1276 int vcpu = qdict_get_try_int(qdict, "vcpu", 0);
1277 TraceEventInfoList *events;
1278 TraceEventInfoList *elem;
1279 Error *local_err = NULL;
1281 if (name == NULL) {
1282 name = "*";
1284 if (vcpu < 0) {
1285 monitor_printf(mon, "argument vcpu must be positive");
1286 return;
1289 events = qmp_trace_event_get_state(name, has_vcpu, vcpu, &local_err);
1290 if (local_err) {
1291 error_report_err(local_err);
1292 return;
1295 for (elem = events; elem != NULL; elem = elem->next) {
1296 monitor_printf(mon, "%s : state %u\n",
1297 elem->value->name,
1298 elem->value->state == TRACE_EVENT_STATE_ENABLED ? 1 : 0);
1300 qapi_free_TraceEventInfoList(events);
1303 void qmp_client_migrate_info(const char *protocol, const char *hostname,
1304 bool has_port, int64_t port,
1305 bool has_tls_port, int64_t tls_port,
1306 bool has_cert_subject, const char *cert_subject,
1307 Error **errp)
1309 if (strcmp(protocol, "spice") == 0) {
1310 if (!qemu_using_spice(errp)) {
1311 return;
1314 if (!has_port && !has_tls_port) {
1315 error_setg(errp, QERR_MISSING_PARAMETER, "port/tls-port");
1316 return;
1319 if (qemu_spice_migrate_info(hostname,
1320 has_port ? port : -1,
1321 has_tls_port ? tls_port : -1,
1322 cert_subject)) {
1323 error_setg(errp, QERR_UNDEFINED_ERROR);
1324 return;
1326 return;
1329 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "protocol", "spice");
1332 static void hmp_logfile(Monitor *mon, const QDict *qdict)
1334 Error *err = NULL;
1336 qemu_set_log_filename(qdict_get_str(qdict, "filename"), &err);
1337 if (err) {
1338 error_report_err(err);
1342 static void hmp_log(Monitor *mon, const QDict *qdict)
1344 int mask;
1345 const char *items = qdict_get_str(qdict, "items");
1347 if (!strcmp(items, "none")) {
1348 mask = 0;
1349 } else {
1350 mask = qemu_str_to_log_mask(items);
1351 if (!mask) {
1352 help_cmd(mon, "log");
1353 return;
1356 qemu_set_log(mask);
1359 static void hmp_singlestep(Monitor *mon, const QDict *qdict)
1361 const char *option = qdict_get_try_str(qdict, "option");
1362 if (!option || !strcmp(option, "on")) {
1363 singlestep = 1;
1364 } else if (!strcmp(option, "off")) {
1365 singlestep = 0;
1366 } else {
1367 monitor_printf(mon, "unexpected option %s\n", option);
1371 static void hmp_gdbserver(Monitor *mon, const QDict *qdict)
1373 const char *device = qdict_get_try_str(qdict, "device");
1374 if (!device)
1375 device = "tcp::" DEFAULT_GDBSTUB_PORT;
1376 if (gdbserver_start(device) < 0) {
1377 monitor_printf(mon, "Could not open gdbserver on device '%s'\n",
1378 device);
1379 } else if (strcmp(device, "none") == 0) {
1380 monitor_printf(mon, "Disabled gdbserver\n");
1381 } else {
1382 monitor_printf(mon, "Waiting for gdb connection on device '%s'\n",
1383 device);
1387 static void hmp_watchdog_action(Monitor *mon, const QDict *qdict)
1389 const char *action = qdict_get_str(qdict, "action");
1390 if (select_watchdog_action(action) == -1) {
1391 monitor_printf(mon, "Unknown watchdog action '%s'\n", action);
1395 static void monitor_printc(Monitor *mon, int c)
1397 monitor_printf(mon, "'");
1398 switch(c) {
1399 case '\'':
1400 monitor_printf(mon, "\\'");
1401 break;
1402 case '\\':
1403 monitor_printf(mon, "\\\\");
1404 break;
1405 case '\n':
1406 monitor_printf(mon, "\\n");
1407 break;
1408 case '\r':
1409 monitor_printf(mon, "\\r");
1410 break;
1411 default:
1412 if (c >= 32 && c <= 126) {
1413 monitor_printf(mon, "%c", c);
1414 } else {
1415 monitor_printf(mon, "\\x%02x", c);
1417 break;
1419 monitor_printf(mon, "'");
1422 static void memory_dump(Monitor *mon, int count, int format, int wsize,
1423 hwaddr addr, int is_physical)
1425 int l, line_size, i, max_digits, len;
1426 uint8_t buf[16];
1427 uint64_t v;
1428 CPUState *cs = mon_get_cpu();
1430 if (!cs && (format == 'i' || !is_physical)) {
1431 monitor_printf(mon, "Can not dump without CPU\n");
1432 return;
1435 if (format == 'i') {
1436 monitor_disas(mon, cs, addr, count, is_physical);
1437 return;
1440 len = wsize * count;
1441 if (wsize == 1)
1442 line_size = 8;
1443 else
1444 line_size = 16;
1445 max_digits = 0;
1447 switch(format) {
1448 case 'o':
1449 max_digits = DIV_ROUND_UP(wsize * 8, 3);
1450 break;
1451 default:
1452 case 'x':
1453 max_digits = (wsize * 8) / 4;
1454 break;
1455 case 'u':
1456 case 'd':
1457 max_digits = DIV_ROUND_UP(wsize * 8 * 10, 33);
1458 break;
1459 case 'c':
1460 wsize = 1;
1461 break;
1464 while (len > 0) {
1465 if (is_physical)
1466 monitor_printf(mon, TARGET_FMT_plx ":", addr);
1467 else
1468 monitor_printf(mon, TARGET_FMT_lx ":", (target_ulong)addr);
1469 l = len;
1470 if (l > line_size)
1471 l = line_size;
1472 if (is_physical) {
1473 cpu_physical_memory_read(addr, buf, l);
1474 } else {
1475 if (cpu_memory_rw_debug(cs, addr, buf, l, 0) < 0) {
1476 monitor_printf(mon, " Cannot access memory\n");
1477 break;
1480 i = 0;
1481 while (i < l) {
1482 switch(wsize) {
1483 default:
1484 case 1:
1485 v = ldub_p(buf + i);
1486 break;
1487 case 2:
1488 v = lduw_p(buf + i);
1489 break;
1490 case 4:
1491 v = (uint32_t)ldl_p(buf + i);
1492 break;
1493 case 8:
1494 v = ldq_p(buf + i);
1495 break;
1497 monitor_printf(mon, " ");
1498 switch(format) {
1499 case 'o':
1500 monitor_printf(mon, "%#*" PRIo64, max_digits, v);
1501 break;
1502 case 'x':
1503 monitor_printf(mon, "0x%0*" PRIx64, max_digits, v);
1504 break;
1505 case 'u':
1506 monitor_printf(mon, "%*" PRIu64, max_digits, v);
1507 break;
1508 case 'd':
1509 monitor_printf(mon, "%*" PRId64, max_digits, v);
1510 break;
1511 case 'c':
1512 monitor_printc(mon, v);
1513 break;
1515 i += wsize;
1517 monitor_printf(mon, "\n");
1518 addr += l;
1519 len -= l;
1523 static void hmp_memory_dump(Monitor *mon, const QDict *qdict)
1525 int count = qdict_get_int(qdict, "count");
1526 int format = qdict_get_int(qdict, "format");
1527 int size = qdict_get_int(qdict, "size");
1528 target_long addr = qdict_get_int(qdict, "addr");
1530 memory_dump(mon, count, format, size, addr, 0);
1533 static void hmp_physical_memory_dump(Monitor *mon, const QDict *qdict)
1535 int count = qdict_get_int(qdict, "count");
1536 int format = qdict_get_int(qdict, "format");
1537 int size = qdict_get_int(qdict, "size");
1538 hwaddr addr = qdict_get_int(qdict, "addr");
1540 memory_dump(mon, count, format, size, addr, 1);
1543 static void *gpa2hva(MemoryRegion **p_mr, hwaddr addr, Error **errp)
1545 MemoryRegionSection mrs = memory_region_find(get_system_memory(),
1546 addr, 1);
1548 if (!mrs.mr) {
1549 error_setg(errp, "No memory is mapped at address 0x%" HWADDR_PRIx, addr);
1550 return NULL;
1553 if (!memory_region_is_ram(mrs.mr) && !memory_region_is_romd(mrs.mr)) {
1554 error_setg(errp, "Memory at address 0x%" HWADDR_PRIx "is not RAM", addr);
1555 memory_region_unref(mrs.mr);
1556 return NULL;
1559 *p_mr = mrs.mr;
1560 return qemu_map_ram_ptr(mrs.mr->ram_block, mrs.offset_within_region);
1563 static void hmp_gpa2hva(Monitor *mon, const QDict *qdict)
1565 hwaddr addr = qdict_get_int(qdict, "addr");
1566 Error *local_err = NULL;
1567 MemoryRegion *mr = NULL;
1568 void *ptr;
1570 ptr = gpa2hva(&mr, addr, &local_err);
1571 if (local_err) {
1572 error_report_err(local_err);
1573 return;
1576 monitor_printf(mon, "Host virtual address for 0x%" HWADDR_PRIx
1577 " (%s) is %p\n",
1578 addr, mr->name, ptr);
1580 memory_region_unref(mr);
1583 #ifdef CONFIG_LINUX
1584 static uint64_t vtop(void *ptr, Error **errp)
1586 uint64_t pinfo;
1587 uint64_t ret = -1;
1588 uintptr_t addr = (uintptr_t) ptr;
1589 uintptr_t pagesize = getpagesize();
1590 off_t offset = addr / pagesize * sizeof(pinfo);
1591 int fd;
1593 fd = open("/proc/self/pagemap", O_RDONLY);
1594 if (fd == -1) {
1595 error_setg_errno(errp, errno, "Cannot open /proc/self/pagemap");
1596 return -1;
1599 /* Force copy-on-write if necessary. */
1600 atomic_add((uint8_t *)ptr, 0);
1602 if (pread(fd, &pinfo, sizeof(pinfo), offset) != sizeof(pinfo)) {
1603 error_setg_errno(errp, errno, "Cannot read pagemap");
1604 goto out;
1606 if ((pinfo & (1ull << 63)) == 0) {
1607 error_setg(errp, "Page not present");
1608 goto out;
1610 ret = ((pinfo & 0x007fffffffffffffull) * pagesize) | (addr & (pagesize - 1));
1612 out:
1613 close(fd);
1614 return ret;
1617 static void hmp_gpa2hpa(Monitor *mon, const QDict *qdict)
1619 hwaddr addr = qdict_get_int(qdict, "addr");
1620 Error *local_err = NULL;
1621 MemoryRegion *mr = NULL;
1622 void *ptr;
1623 uint64_t physaddr;
1625 ptr = gpa2hva(&mr, addr, &local_err);
1626 if (local_err) {
1627 error_report_err(local_err);
1628 return;
1631 physaddr = vtop(ptr, &local_err);
1632 if (local_err) {
1633 error_report_err(local_err);
1634 } else {
1635 monitor_printf(mon, "Host physical address for 0x%" HWADDR_PRIx
1636 " (%s) is 0x%" PRIx64 "\n",
1637 addr, mr->name, (uint64_t) physaddr);
1640 memory_region_unref(mr);
1642 #endif
1644 static void do_print(Monitor *mon, const QDict *qdict)
1646 int format = qdict_get_int(qdict, "format");
1647 hwaddr val = qdict_get_int(qdict, "val");
1649 switch(format) {
1650 case 'o':
1651 monitor_printf(mon, "%#" HWADDR_PRIo, val);
1652 break;
1653 case 'x':
1654 monitor_printf(mon, "%#" HWADDR_PRIx, val);
1655 break;
1656 case 'u':
1657 monitor_printf(mon, "%" HWADDR_PRIu, val);
1658 break;
1659 default:
1660 case 'd':
1661 monitor_printf(mon, "%" HWADDR_PRId, val);
1662 break;
1663 case 'c':
1664 monitor_printc(mon, val);
1665 break;
1667 monitor_printf(mon, "\n");
1670 static void hmp_sum(Monitor *mon, const QDict *qdict)
1672 uint32_t addr;
1673 uint16_t sum;
1674 uint32_t start = qdict_get_int(qdict, "start");
1675 uint32_t size = qdict_get_int(qdict, "size");
1677 sum = 0;
1678 for(addr = start; addr < (start + size); addr++) {
1679 uint8_t val = address_space_ldub(&address_space_memory, addr,
1680 MEMTXATTRS_UNSPECIFIED, NULL);
1681 /* BSD sum algorithm ('sum' Unix command) */
1682 sum = (sum >> 1) | (sum << 15);
1683 sum += val;
1685 monitor_printf(mon, "%05d\n", sum);
1688 static int mouse_button_state;
1690 static void hmp_mouse_move(Monitor *mon, const QDict *qdict)
1692 int dx, dy, dz, button;
1693 const char *dx_str = qdict_get_str(qdict, "dx_str");
1694 const char *dy_str = qdict_get_str(qdict, "dy_str");
1695 const char *dz_str = qdict_get_try_str(qdict, "dz_str");
1697 dx = strtol(dx_str, NULL, 0);
1698 dy = strtol(dy_str, NULL, 0);
1699 qemu_input_queue_rel(NULL, INPUT_AXIS_X, dx);
1700 qemu_input_queue_rel(NULL, INPUT_AXIS_Y, dy);
1702 if (dz_str) {
1703 dz = strtol(dz_str, NULL, 0);
1704 if (dz != 0) {
1705 button = (dz > 0) ? INPUT_BUTTON_WHEEL_UP : INPUT_BUTTON_WHEEL_DOWN;
1706 qemu_input_queue_btn(NULL, button, true);
1707 qemu_input_event_sync();
1708 qemu_input_queue_btn(NULL, button, false);
1711 qemu_input_event_sync();
1714 static void hmp_mouse_button(Monitor *mon, const QDict *qdict)
1716 static uint32_t bmap[INPUT_BUTTON__MAX] = {
1717 [INPUT_BUTTON_LEFT] = MOUSE_EVENT_LBUTTON,
1718 [INPUT_BUTTON_MIDDLE] = MOUSE_EVENT_MBUTTON,
1719 [INPUT_BUTTON_RIGHT] = MOUSE_EVENT_RBUTTON,
1721 int button_state = qdict_get_int(qdict, "button_state");
1723 if (mouse_button_state == button_state) {
1724 return;
1726 qemu_input_update_buttons(NULL, bmap, mouse_button_state, button_state);
1727 qemu_input_event_sync();
1728 mouse_button_state = button_state;
1731 static void hmp_ioport_read(Monitor *mon, const QDict *qdict)
1733 int size = qdict_get_int(qdict, "size");
1734 int addr = qdict_get_int(qdict, "addr");
1735 int has_index = qdict_haskey(qdict, "index");
1736 uint32_t val;
1737 int suffix;
1739 if (has_index) {
1740 int index = qdict_get_int(qdict, "index");
1741 cpu_outb(addr & IOPORTS_MASK, index & 0xff);
1742 addr++;
1744 addr &= 0xffff;
1746 switch(size) {
1747 default:
1748 case 1:
1749 val = cpu_inb(addr);
1750 suffix = 'b';
1751 break;
1752 case 2:
1753 val = cpu_inw(addr);
1754 suffix = 'w';
1755 break;
1756 case 4:
1757 val = cpu_inl(addr);
1758 suffix = 'l';
1759 break;
1761 monitor_printf(mon, "port%c[0x%04x] = %#0*x\n",
1762 suffix, addr, size * 2, val);
1765 static void hmp_ioport_write(Monitor *mon, const QDict *qdict)
1767 int size = qdict_get_int(qdict, "size");
1768 int addr = qdict_get_int(qdict, "addr");
1769 int val = qdict_get_int(qdict, "val");
1771 addr &= IOPORTS_MASK;
1773 switch (size) {
1774 default:
1775 case 1:
1776 cpu_outb(addr, val);
1777 break;
1778 case 2:
1779 cpu_outw(addr, val);
1780 break;
1781 case 4:
1782 cpu_outl(addr, val);
1783 break;
1787 static void hmp_boot_set(Monitor *mon, const QDict *qdict)
1789 Error *local_err = NULL;
1790 const char *bootdevice = qdict_get_str(qdict, "bootdevice");
1792 qemu_boot_set(bootdevice, &local_err);
1793 if (local_err) {
1794 error_report_err(local_err);
1795 } else {
1796 monitor_printf(mon, "boot device list now set to %s\n", bootdevice);
1800 static void hmp_info_mtree(Monitor *mon, const QDict *qdict)
1802 bool flatview = qdict_get_try_bool(qdict, "flatview", false);
1803 bool dispatch_tree = qdict_get_try_bool(qdict, "dispatch_tree", false);
1805 mtree_info((fprintf_function)monitor_printf, mon, flatview, dispatch_tree);
1808 static void hmp_info_numa(Monitor *mon, const QDict *qdict)
1810 int i;
1811 NumaNodeMem *node_mem;
1812 CpuInfoList *cpu_list, *cpu;
1814 cpu_list = qmp_query_cpus(&error_abort);
1815 node_mem = g_new0(NumaNodeMem, nb_numa_nodes);
1817 query_numa_node_mem(node_mem);
1818 monitor_printf(mon, "%d nodes\n", nb_numa_nodes);
1819 for (i = 0; i < nb_numa_nodes; i++) {
1820 monitor_printf(mon, "node %d cpus:", i);
1821 for (cpu = cpu_list; cpu; cpu = cpu->next) {
1822 if (cpu->value->has_props && cpu->value->props->has_node_id &&
1823 cpu->value->props->node_id == i) {
1824 monitor_printf(mon, " %" PRIi64, cpu->value->CPU);
1827 monitor_printf(mon, "\n");
1828 monitor_printf(mon, "node %d size: %" PRId64 " MB\n", i,
1829 node_mem[i].node_mem >> 20);
1830 monitor_printf(mon, "node %d plugged: %" PRId64 " MB\n", i,
1831 node_mem[i].node_plugged_mem >> 20);
1833 qapi_free_CpuInfoList(cpu_list);
1834 g_free(node_mem);
1837 #ifdef CONFIG_PROFILER
1839 int64_t tcg_time;
1840 int64_t dev_time;
1842 static void hmp_info_profile(Monitor *mon, const QDict *qdict)
1844 monitor_printf(mon, "async time %" PRId64 " (%0.3f)\n",
1845 dev_time, dev_time / (double)NANOSECONDS_PER_SECOND);
1846 monitor_printf(mon, "qemu time %" PRId64 " (%0.3f)\n",
1847 tcg_time, tcg_time / (double)NANOSECONDS_PER_SECOND);
1848 tcg_time = 0;
1849 dev_time = 0;
1851 #else
1852 static void hmp_info_profile(Monitor *mon, const QDict *qdict)
1854 monitor_printf(mon, "Internal profiler not compiled\n");
1856 #endif
1858 /* Capture support */
1859 static QLIST_HEAD (capture_list_head, CaptureState) capture_head;
1861 static void hmp_info_capture(Monitor *mon, const QDict *qdict)
1863 int i;
1864 CaptureState *s;
1866 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
1867 monitor_printf(mon, "[%d]: ", i);
1868 s->ops.info (s->opaque);
1872 static void hmp_stopcapture(Monitor *mon, const QDict *qdict)
1874 int i;
1875 int n = qdict_get_int(qdict, "n");
1876 CaptureState *s;
1878 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
1879 if (i == n) {
1880 s->ops.destroy (s->opaque);
1881 QLIST_REMOVE (s, entries);
1882 g_free (s);
1883 return;
1888 static void hmp_wavcapture(Monitor *mon, const QDict *qdict)
1890 const char *path = qdict_get_str(qdict, "path");
1891 int has_freq = qdict_haskey(qdict, "freq");
1892 int freq = qdict_get_try_int(qdict, "freq", -1);
1893 int has_bits = qdict_haskey(qdict, "bits");
1894 int bits = qdict_get_try_int(qdict, "bits", -1);
1895 int has_channels = qdict_haskey(qdict, "nchannels");
1896 int nchannels = qdict_get_try_int(qdict, "nchannels", -1);
1897 CaptureState *s;
1899 s = g_malloc0 (sizeof (*s));
1901 freq = has_freq ? freq : 44100;
1902 bits = has_bits ? bits : 16;
1903 nchannels = has_channels ? nchannels : 2;
1905 if (wav_start_capture (s, path, freq, bits, nchannels)) {
1906 monitor_printf(mon, "Failed to add wave capture\n");
1907 g_free (s);
1908 return;
1910 QLIST_INSERT_HEAD (&capture_head, s, entries);
1913 static qemu_acl *find_acl(Monitor *mon, const char *name)
1915 qemu_acl *acl = qemu_acl_find(name);
1917 if (!acl) {
1918 monitor_printf(mon, "acl: unknown list '%s'\n", name);
1920 return acl;
1923 static void hmp_acl_show(Monitor *mon, const QDict *qdict)
1925 const char *aclname = qdict_get_str(qdict, "aclname");
1926 qemu_acl *acl = find_acl(mon, aclname);
1927 qemu_acl_entry *entry;
1928 int i = 0;
1930 if (acl) {
1931 monitor_printf(mon, "policy: %s\n",
1932 acl->defaultDeny ? "deny" : "allow");
1933 QTAILQ_FOREACH(entry, &acl->entries, next) {
1934 i++;
1935 monitor_printf(mon, "%d: %s %s\n", i,
1936 entry->deny ? "deny" : "allow", entry->match);
1941 static void hmp_acl_reset(Monitor *mon, const QDict *qdict)
1943 const char *aclname = qdict_get_str(qdict, "aclname");
1944 qemu_acl *acl = find_acl(mon, aclname);
1946 if (acl) {
1947 qemu_acl_reset(acl);
1948 monitor_printf(mon, "acl: removed all rules\n");
1952 static void hmp_acl_policy(Monitor *mon, const QDict *qdict)
1954 const char *aclname = qdict_get_str(qdict, "aclname");
1955 const char *policy = qdict_get_str(qdict, "policy");
1956 qemu_acl *acl = find_acl(mon, aclname);
1958 if (acl) {
1959 if (strcmp(policy, "allow") == 0) {
1960 acl->defaultDeny = 0;
1961 monitor_printf(mon, "acl: policy set to 'allow'\n");
1962 } else if (strcmp(policy, "deny") == 0) {
1963 acl->defaultDeny = 1;
1964 monitor_printf(mon, "acl: policy set to 'deny'\n");
1965 } else {
1966 monitor_printf(mon, "acl: unknown policy '%s', "
1967 "expected 'deny' or 'allow'\n", policy);
1972 static void hmp_acl_add(Monitor *mon, const QDict *qdict)
1974 const char *aclname = qdict_get_str(qdict, "aclname");
1975 const char *match = qdict_get_str(qdict, "match");
1976 const char *policy = qdict_get_str(qdict, "policy");
1977 int has_index = qdict_haskey(qdict, "index");
1978 int index = qdict_get_try_int(qdict, "index", -1);
1979 qemu_acl *acl = find_acl(mon, aclname);
1980 int deny, ret;
1982 if (acl) {
1983 if (strcmp(policy, "allow") == 0) {
1984 deny = 0;
1985 } else if (strcmp(policy, "deny") == 0) {
1986 deny = 1;
1987 } else {
1988 monitor_printf(mon, "acl: unknown policy '%s', "
1989 "expected 'deny' or 'allow'\n", policy);
1990 return;
1992 if (has_index)
1993 ret = qemu_acl_insert(acl, deny, match, index);
1994 else
1995 ret = qemu_acl_append(acl, deny, match);
1996 if (ret < 0)
1997 monitor_printf(mon, "acl: unable to add acl entry\n");
1998 else
1999 monitor_printf(mon, "acl: added rule at position %d\n", ret);
2003 static void hmp_acl_remove(Monitor *mon, const QDict *qdict)
2005 const char *aclname = qdict_get_str(qdict, "aclname");
2006 const char *match = qdict_get_str(qdict, "match");
2007 qemu_acl *acl = find_acl(mon, aclname);
2008 int ret;
2010 if (acl) {
2011 ret = qemu_acl_remove(acl, match);
2012 if (ret < 0)
2013 monitor_printf(mon, "acl: no matching acl entry\n");
2014 else
2015 monitor_printf(mon, "acl: removed rule at position %d\n", ret);
2019 void qmp_getfd(const char *fdname, Error **errp)
2021 mon_fd_t *monfd;
2022 int fd;
2024 fd = qemu_chr_fe_get_msgfd(&cur_mon->chr);
2025 if (fd == -1) {
2026 error_setg(errp, QERR_FD_NOT_SUPPLIED);
2027 return;
2030 if (qemu_isdigit(fdname[0])) {
2031 close(fd);
2032 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "fdname",
2033 "a name not starting with a digit");
2034 return;
2037 QLIST_FOREACH(monfd, &cur_mon->fds, next) {
2038 if (strcmp(monfd->name, fdname) != 0) {
2039 continue;
2042 close(monfd->fd);
2043 monfd->fd = fd;
2044 return;
2047 monfd = g_malloc0(sizeof(mon_fd_t));
2048 monfd->name = g_strdup(fdname);
2049 monfd->fd = fd;
2051 QLIST_INSERT_HEAD(&cur_mon->fds, monfd, next);
2054 void qmp_closefd(const char *fdname, Error **errp)
2056 mon_fd_t *monfd;
2058 QLIST_FOREACH(monfd, &cur_mon->fds, next) {
2059 if (strcmp(monfd->name, fdname) != 0) {
2060 continue;
2063 QLIST_REMOVE(monfd, next);
2064 close(monfd->fd);
2065 g_free(monfd->name);
2066 g_free(monfd);
2067 return;
2070 error_setg(errp, QERR_FD_NOT_FOUND, fdname);
2073 int monitor_get_fd(Monitor *mon, const char *fdname, Error **errp)
2075 mon_fd_t *monfd;
2077 QLIST_FOREACH(monfd, &mon->fds, next) {
2078 int fd;
2080 if (strcmp(monfd->name, fdname) != 0) {
2081 continue;
2084 fd = monfd->fd;
2086 /* caller takes ownership of fd */
2087 QLIST_REMOVE(monfd, next);
2088 g_free(monfd->name);
2089 g_free(monfd);
2091 return fd;
2094 error_setg(errp, "File descriptor named '%s' has not been found", fdname);
2095 return -1;
2098 static void monitor_fdset_cleanup(MonFdset *mon_fdset)
2100 MonFdsetFd *mon_fdset_fd;
2101 MonFdsetFd *mon_fdset_fd_next;
2103 QLIST_FOREACH_SAFE(mon_fdset_fd, &mon_fdset->fds, next, mon_fdset_fd_next) {
2104 if ((mon_fdset_fd->removed ||
2105 (QLIST_EMPTY(&mon_fdset->dup_fds) && mon_refcount == 0)) &&
2106 runstate_is_running()) {
2107 close(mon_fdset_fd->fd);
2108 g_free(mon_fdset_fd->opaque);
2109 QLIST_REMOVE(mon_fdset_fd, next);
2110 g_free(mon_fdset_fd);
2114 if (QLIST_EMPTY(&mon_fdset->fds) && QLIST_EMPTY(&mon_fdset->dup_fds)) {
2115 QLIST_REMOVE(mon_fdset, next);
2116 g_free(mon_fdset);
2120 static void monitor_fdsets_cleanup(void)
2122 MonFdset *mon_fdset;
2123 MonFdset *mon_fdset_next;
2125 QLIST_FOREACH_SAFE(mon_fdset, &mon_fdsets, next, mon_fdset_next) {
2126 monitor_fdset_cleanup(mon_fdset);
2130 AddfdInfo *qmp_add_fd(bool has_fdset_id, int64_t fdset_id, bool has_opaque,
2131 const char *opaque, Error **errp)
2133 int fd;
2134 Monitor *mon = cur_mon;
2135 AddfdInfo *fdinfo;
2137 fd = qemu_chr_fe_get_msgfd(&mon->chr);
2138 if (fd == -1) {
2139 error_setg(errp, QERR_FD_NOT_SUPPLIED);
2140 goto error;
2143 fdinfo = monitor_fdset_add_fd(fd, has_fdset_id, fdset_id,
2144 has_opaque, opaque, errp);
2145 if (fdinfo) {
2146 return fdinfo;
2149 error:
2150 if (fd != -1) {
2151 close(fd);
2153 return NULL;
2156 void qmp_remove_fd(int64_t fdset_id, bool has_fd, int64_t fd, Error **errp)
2158 MonFdset *mon_fdset;
2159 MonFdsetFd *mon_fdset_fd;
2160 char fd_str[60];
2162 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2163 if (mon_fdset->id != fdset_id) {
2164 continue;
2166 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2167 if (has_fd) {
2168 if (mon_fdset_fd->fd != fd) {
2169 continue;
2171 mon_fdset_fd->removed = true;
2172 break;
2173 } else {
2174 mon_fdset_fd->removed = true;
2177 if (has_fd && !mon_fdset_fd) {
2178 goto error;
2180 monitor_fdset_cleanup(mon_fdset);
2181 return;
2184 error:
2185 if (has_fd) {
2186 snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64 ", fd:%" PRId64,
2187 fdset_id, fd);
2188 } else {
2189 snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64, fdset_id);
2191 error_setg(errp, QERR_FD_NOT_FOUND, fd_str);
2194 FdsetInfoList *qmp_query_fdsets(Error **errp)
2196 MonFdset *mon_fdset;
2197 MonFdsetFd *mon_fdset_fd;
2198 FdsetInfoList *fdset_list = NULL;
2200 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2201 FdsetInfoList *fdset_info = g_malloc0(sizeof(*fdset_info));
2202 FdsetFdInfoList *fdsetfd_list = NULL;
2204 fdset_info->value = g_malloc0(sizeof(*fdset_info->value));
2205 fdset_info->value->fdset_id = mon_fdset->id;
2207 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2208 FdsetFdInfoList *fdsetfd_info;
2210 fdsetfd_info = g_malloc0(sizeof(*fdsetfd_info));
2211 fdsetfd_info->value = g_malloc0(sizeof(*fdsetfd_info->value));
2212 fdsetfd_info->value->fd = mon_fdset_fd->fd;
2213 if (mon_fdset_fd->opaque) {
2214 fdsetfd_info->value->has_opaque = true;
2215 fdsetfd_info->value->opaque = g_strdup(mon_fdset_fd->opaque);
2216 } else {
2217 fdsetfd_info->value->has_opaque = false;
2220 fdsetfd_info->next = fdsetfd_list;
2221 fdsetfd_list = fdsetfd_info;
2224 fdset_info->value->fds = fdsetfd_list;
2226 fdset_info->next = fdset_list;
2227 fdset_list = fdset_info;
2230 return fdset_list;
2233 AddfdInfo *monitor_fdset_add_fd(int fd, bool has_fdset_id, int64_t fdset_id,
2234 bool has_opaque, const char *opaque,
2235 Error **errp)
2237 MonFdset *mon_fdset = NULL;
2238 MonFdsetFd *mon_fdset_fd;
2239 AddfdInfo *fdinfo;
2241 if (has_fdset_id) {
2242 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2243 /* Break if match found or match impossible due to ordering by ID */
2244 if (fdset_id <= mon_fdset->id) {
2245 if (fdset_id < mon_fdset->id) {
2246 mon_fdset = NULL;
2248 break;
2253 if (mon_fdset == NULL) {
2254 int64_t fdset_id_prev = -1;
2255 MonFdset *mon_fdset_cur = QLIST_FIRST(&mon_fdsets);
2257 if (has_fdset_id) {
2258 if (fdset_id < 0) {
2259 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "fdset-id",
2260 "a non-negative value");
2261 return NULL;
2263 /* Use specified fdset ID */
2264 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2265 mon_fdset_cur = mon_fdset;
2266 if (fdset_id < mon_fdset_cur->id) {
2267 break;
2270 } else {
2271 /* Use first available fdset ID */
2272 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2273 mon_fdset_cur = mon_fdset;
2274 if (fdset_id_prev == mon_fdset_cur->id - 1) {
2275 fdset_id_prev = mon_fdset_cur->id;
2276 continue;
2278 break;
2282 mon_fdset = g_malloc0(sizeof(*mon_fdset));
2283 if (has_fdset_id) {
2284 mon_fdset->id = fdset_id;
2285 } else {
2286 mon_fdset->id = fdset_id_prev + 1;
2289 /* The fdset list is ordered by fdset ID */
2290 if (!mon_fdset_cur) {
2291 QLIST_INSERT_HEAD(&mon_fdsets, mon_fdset, next);
2292 } else if (mon_fdset->id < mon_fdset_cur->id) {
2293 QLIST_INSERT_BEFORE(mon_fdset_cur, mon_fdset, next);
2294 } else {
2295 QLIST_INSERT_AFTER(mon_fdset_cur, mon_fdset, next);
2299 mon_fdset_fd = g_malloc0(sizeof(*mon_fdset_fd));
2300 mon_fdset_fd->fd = fd;
2301 mon_fdset_fd->removed = false;
2302 if (has_opaque) {
2303 mon_fdset_fd->opaque = g_strdup(opaque);
2305 QLIST_INSERT_HEAD(&mon_fdset->fds, mon_fdset_fd, next);
2307 fdinfo = g_malloc0(sizeof(*fdinfo));
2308 fdinfo->fdset_id = mon_fdset->id;
2309 fdinfo->fd = mon_fdset_fd->fd;
2311 return fdinfo;
2314 int monitor_fdset_get_fd(int64_t fdset_id, int flags)
2316 #ifndef _WIN32
2317 MonFdset *mon_fdset;
2318 MonFdsetFd *mon_fdset_fd;
2319 int mon_fd_flags;
2321 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2322 if (mon_fdset->id != fdset_id) {
2323 continue;
2325 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2326 mon_fd_flags = fcntl(mon_fdset_fd->fd, F_GETFL);
2327 if (mon_fd_flags == -1) {
2328 return -1;
2331 if ((flags & O_ACCMODE) == (mon_fd_flags & O_ACCMODE)) {
2332 return mon_fdset_fd->fd;
2335 errno = EACCES;
2336 return -1;
2338 #endif
2340 errno = ENOENT;
2341 return -1;
2344 int monitor_fdset_dup_fd_add(int64_t fdset_id, int dup_fd)
2346 MonFdset *mon_fdset;
2347 MonFdsetFd *mon_fdset_fd_dup;
2349 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2350 if (mon_fdset->id != fdset_id) {
2351 continue;
2353 QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
2354 if (mon_fdset_fd_dup->fd == dup_fd) {
2355 return -1;
2358 mon_fdset_fd_dup = g_malloc0(sizeof(*mon_fdset_fd_dup));
2359 mon_fdset_fd_dup->fd = dup_fd;
2360 QLIST_INSERT_HEAD(&mon_fdset->dup_fds, mon_fdset_fd_dup, next);
2361 return 0;
2363 return -1;
2366 static int monitor_fdset_dup_fd_find_remove(int dup_fd, bool remove)
2368 MonFdset *mon_fdset;
2369 MonFdsetFd *mon_fdset_fd_dup;
2371 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2372 QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
2373 if (mon_fdset_fd_dup->fd == dup_fd) {
2374 if (remove) {
2375 QLIST_REMOVE(mon_fdset_fd_dup, next);
2376 if (QLIST_EMPTY(&mon_fdset->dup_fds)) {
2377 monitor_fdset_cleanup(mon_fdset);
2379 return -1;
2380 } else {
2381 return mon_fdset->id;
2386 return -1;
2389 int monitor_fdset_dup_fd_find(int dup_fd)
2391 return monitor_fdset_dup_fd_find_remove(dup_fd, false);
2394 void monitor_fdset_dup_fd_remove(int dup_fd)
2396 monitor_fdset_dup_fd_find_remove(dup_fd, true);
2399 int monitor_fd_param(Monitor *mon, const char *fdname, Error **errp)
2401 int fd;
2402 Error *local_err = NULL;
2404 if (!qemu_isdigit(fdname[0]) && mon) {
2405 fd = monitor_get_fd(mon, fdname, &local_err);
2406 } else {
2407 fd = qemu_parse_fd(fdname);
2408 if (fd == -1) {
2409 error_setg(&local_err, "Invalid file descriptor number '%s'",
2410 fdname);
2413 if (local_err) {
2414 error_propagate(errp, local_err);
2415 assert(fd == -1);
2416 } else {
2417 assert(fd != -1);
2420 return fd;
2423 /* Please update hmp-commands.hx when adding or changing commands */
2424 static mon_cmd_t info_cmds[] = {
2425 #include "hmp-commands-info.h"
2426 { NULL, NULL, },
2429 /* mon_cmds and info_cmds would be sorted at runtime */
2430 static mon_cmd_t mon_cmds[] = {
2431 #include "hmp-commands.h"
2432 { NULL, NULL, },
2435 /*******************************************************************/
2437 static const char *pch;
2438 static sigjmp_buf expr_env;
2441 static void GCC_FMT_ATTR(2, 3) QEMU_NORETURN
2442 expr_error(Monitor *mon, const char *fmt, ...)
2444 va_list ap;
2445 va_start(ap, fmt);
2446 monitor_vprintf(mon, fmt, ap);
2447 monitor_printf(mon, "\n");
2448 va_end(ap);
2449 siglongjmp(expr_env, 1);
2452 /* return 0 if OK, -1 if not found */
2453 static int get_monitor_def(target_long *pval, const char *name)
2455 const MonitorDef *md = target_monitor_defs();
2456 CPUState *cs = mon_get_cpu();
2457 void *ptr;
2458 uint64_t tmp = 0;
2459 int ret;
2461 if (cs == NULL || md == NULL) {
2462 return -1;
2465 for(; md->name != NULL; md++) {
2466 if (compare_cmd(name, md->name)) {
2467 if (md->get_value) {
2468 *pval = md->get_value(md, md->offset);
2469 } else {
2470 CPUArchState *env = mon_get_cpu_env();
2471 ptr = (uint8_t *)env + md->offset;
2472 switch(md->type) {
2473 case MD_I32:
2474 *pval = *(int32_t *)ptr;
2475 break;
2476 case MD_TLONG:
2477 *pval = *(target_long *)ptr;
2478 break;
2479 default:
2480 *pval = 0;
2481 break;
2484 return 0;
2488 ret = target_get_monitor_def(cs, name, &tmp);
2489 if (!ret) {
2490 *pval = (target_long) tmp;
2493 return ret;
2496 static void next(void)
2498 if (*pch != '\0') {
2499 pch++;
2500 while (qemu_isspace(*pch))
2501 pch++;
2505 static int64_t expr_sum(Monitor *mon);
2507 static int64_t expr_unary(Monitor *mon)
2509 int64_t n;
2510 char *p;
2511 int ret;
2513 switch(*pch) {
2514 case '+':
2515 next();
2516 n = expr_unary(mon);
2517 break;
2518 case '-':
2519 next();
2520 n = -expr_unary(mon);
2521 break;
2522 case '~':
2523 next();
2524 n = ~expr_unary(mon);
2525 break;
2526 case '(':
2527 next();
2528 n = expr_sum(mon);
2529 if (*pch != ')') {
2530 expr_error(mon, "')' expected");
2532 next();
2533 break;
2534 case '\'':
2535 pch++;
2536 if (*pch == '\0')
2537 expr_error(mon, "character constant expected");
2538 n = *pch;
2539 pch++;
2540 if (*pch != '\'')
2541 expr_error(mon, "missing terminating \' character");
2542 next();
2543 break;
2544 case '$':
2546 char buf[128], *q;
2547 target_long reg=0;
2549 pch++;
2550 q = buf;
2551 while ((*pch >= 'a' && *pch <= 'z') ||
2552 (*pch >= 'A' && *pch <= 'Z') ||
2553 (*pch >= '0' && *pch <= '9') ||
2554 *pch == '_' || *pch == '.') {
2555 if ((q - buf) < sizeof(buf) - 1)
2556 *q++ = *pch;
2557 pch++;
2559 while (qemu_isspace(*pch))
2560 pch++;
2561 *q = 0;
2562 ret = get_monitor_def(&reg, buf);
2563 if (ret < 0)
2564 expr_error(mon, "unknown register");
2565 n = reg;
2567 break;
2568 case '\0':
2569 expr_error(mon, "unexpected end of expression");
2570 n = 0;
2571 break;
2572 default:
2573 errno = 0;
2574 n = strtoull(pch, &p, 0);
2575 if (errno == ERANGE) {
2576 expr_error(mon, "number too large");
2578 if (pch == p) {
2579 expr_error(mon, "invalid char '%c' in expression", *p);
2581 pch = p;
2582 while (qemu_isspace(*pch))
2583 pch++;
2584 break;
2586 return n;
2590 static int64_t expr_prod(Monitor *mon)
2592 int64_t val, val2;
2593 int op;
2595 val = expr_unary(mon);
2596 for(;;) {
2597 op = *pch;
2598 if (op != '*' && op != '/' && op != '%')
2599 break;
2600 next();
2601 val2 = expr_unary(mon);
2602 switch(op) {
2603 default:
2604 case '*':
2605 val *= val2;
2606 break;
2607 case '/':
2608 case '%':
2609 if (val2 == 0)
2610 expr_error(mon, "division by zero");
2611 if (op == '/')
2612 val /= val2;
2613 else
2614 val %= val2;
2615 break;
2618 return val;
2621 static int64_t expr_logic(Monitor *mon)
2623 int64_t val, val2;
2624 int op;
2626 val = expr_prod(mon);
2627 for(;;) {
2628 op = *pch;
2629 if (op != '&' && op != '|' && op != '^')
2630 break;
2631 next();
2632 val2 = expr_prod(mon);
2633 switch(op) {
2634 default:
2635 case '&':
2636 val &= val2;
2637 break;
2638 case '|':
2639 val |= val2;
2640 break;
2641 case '^':
2642 val ^= val2;
2643 break;
2646 return val;
2649 static int64_t expr_sum(Monitor *mon)
2651 int64_t val, val2;
2652 int op;
2654 val = expr_logic(mon);
2655 for(;;) {
2656 op = *pch;
2657 if (op != '+' && op != '-')
2658 break;
2659 next();
2660 val2 = expr_logic(mon);
2661 if (op == '+')
2662 val += val2;
2663 else
2664 val -= val2;
2666 return val;
2669 static int get_expr(Monitor *mon, int64_t *pval, const char **pp)
2671 pch = *pp;
2672 if (sigsetjmp(expr_env, 0)) {
2673 *pp = pch;
2674 return -1;
2676 while (qemu_isspace(*pch))
2677 pch++;
2678 *pval = expr_sum(mon);
2679 *pp = pch;
2680 return 0;
2683 static int get_double(Monitor *mon, double *pval, const char **pp)
2685 const char *p = *pp;
2686 char *tailp;
2687 double d;
2689 d = strtod(p, &tailp);
2690 if (tailp == p) {
2691 monitor_printf(mon, "Number expected\n");
2692 return -1;
2694 if (d != d || d - d != 0) {
2695 /* NaN or infinity */
2696 monitor_printf(mon, "Bad number\n");
2697 return -1;
2699 *pval = d;
2700 *pp = tailp;
2701 return 0;
2705 * Store the command-name in cmdname, and return a pointer to
2706 * the remaining of the command string.
2708 static const char *get_command_name(const char *cmdline,
2709 char *cmdname, size_t nlen)
2711 size_t len;
2712 const char *p, *pstart;
2714 p = cmdline;
2715 while (qemu_isspace(*p))
2716 p++;
2717 if (*p == '\0')
2718 return NULL;
2719 pstart = p;
2720 while (*p != '\0' && *p != '/' && !qemu_isspace(*p))
2721 p++;
2722 len = p - pstart;
2723 if (len > nlen - 1)
2724 len = nlen - 1;
2725 memcpy(cmdname, pstart, len);
2726 cmdname[len] = '\0';
2727 return p;
2731 * Read key of 'type' into 'key' and return the current
2732 * 'type' pointer.
2734 static char *key_get_info(const char *type, char **key)
2736 size_t len;
2737 char *p, *str;
2739 if (*type == ',')
2740 type++;
2742 p = strchr(type, ':');
2743 if (!p) {
2744 *key = NULL;
2745 return NULL;
2747 len = p - type;
2749 str = g_malloc(len + 1);
2750 memcpy(str, type, len);
2751 str[len] = '\0';
2753 *key = str;
2754 return ++p;
2757 static int default_fmt_format = 'x';
2758 static int default_fmt_size = 4;
2760 static int is_valid_option(const char *c, const char *typestr)
2762 char option[3];
2764 option[0] = '-';
2765 option[1] = *c;
2766 option[2] = '\0';
2768 typestr = strstr(typestr, option);
2769 return (typestr != NULL);
2772 static const mon_cmd_t *search_dispatch_table(const mon_cmd_t *disp_table,
2773 const char *cmdname)
2775 const mon_cmd_t *cmd;
2777 for (cmd = disp_table; cmd->name != NULL; cmd++) {
2778 if (compare_cmd(cmdname, cmd->name)) {
2779 return cmd;
2783 return NULL;
2787 * Parse command name from @cmdp according to command table @table.
2788 * If blank, return NULL.
2789 * Else, if no valid command can be found, report to @mon, and return
2790 * NULL.
2791 * Else, change @cmdp to point right behind the name, and return its
2792 * command table entry.
2793 * Do not assume the return value points into @table! It doesn't when
2794 * the command is found in a sub-command table.
2796 static const mon_cmd_t *monitor_parse_command(Monitor *mon,
2797 const char *cmdp_start,
2798 const char **cmdp,
2799 mon_cmd_t *table)
2801 const char *p;
2802 const mon_cmd_t *cmd;
2803 char cmdname[256];
2805 /* extract the command name */
2806 p = get_command_name(*cmdp, cmdname, sizeof(cmdname));
2807 if (!p)
2808 return NULL;
2810 cmd = search_dispatch_table(table, cmdname);
2811 if (!cmd) {
2812 monitor_printf(mon, "unknown command: '%.*s'\n",
2813 (int)(p - cmdp_start), cmdp_start);
2814 return NULL;
2817 /* filter out following useless space */
2818 while (qemu_isspace(*p)) {
2819 p++;
2822 *cmdp = p;
2823 /* search sub command */
2824 if (cmd->sub_table != NULL && *p != '\0') {
2825 return monitor_parse_command(mon, cmdp_start, cmdp, cmd->sub_table);
2828 return cmd;
2832 * Parse arguments for @cmd.
2833 * If it can't be parsed, report to @mon, and return NULL.
2834 * Else, insert command arguments into a QDict, and return it.
2835 * Note: On success, caller has to free the QDict structure.
2838 static QDict *monitor_parse_arguments(Monitor *mon,
2839 const char **endp,
2840 const mon_cmd_t *cmd)
2842 const char *typestr;
2843 char *key;
2844 int c;
2845 const char *p = *endp;
2846 char buf[1024];
2847 QDict *qdict = qdict_new();
2849 /* parse the parameters */
2850 typestr = cmd->args_type;
2851 for(;;) {
2852 typestr = key_get_info(typestr, &key);
2853 if (!typestr)
2854 break;
2855 c = *typestr;
2856 typestr++;
2857 switch(c) {
2858 case 'F':
2859 case 'B':
2860 case 's':
2862 int ret;
2864 while (qemu_isspace(*p))
2865 p++;
2866 if (*typestr == '?') {
2867 typestr++;
2868 if (*p == '\0') {
2869 /* no optional string: NULL argument */
2870 break;
2873 ret = get_str(buf, sizeof(buf), &p);
2874 if (ret < 0) {
2875 switch(c) {
2876 case 'F':
2877 monitor_printf(mon, "%s: filename expected\n",
2878 cmd->name);
2879 break;
2880 case 'B':
2881 monitor_printf(mon, "%s: block device name expected\n",
2882 cmd->name);
2883 break;
2884 default:
2885 monitor_printf(mon, "%s: string expected\n", cmd->name);
2886 break;
2888 goto fail;
2890 qdict_put_str(qdict, key, buf);
2892 break;
2893 case 'O':
2895 QemuOptsList *opts_list;
2896 QemuOpts *opts;
2898 opts_list = qemu_find_opts(key);
2899 if (!opts_list || opts_list->desc->name) {
2900 goto bad_type;
2902 while (qemu_isspace(*p)) {
2903 p++;
2905 if (!*p)
2906 break;
2907 if (get_str(buf, sizeof(buf), &p) < 0) {
2908 goto fail;
2910 opts = qemu_opts_parse_noisily(opts_list, buf, true);
2911 if (!opts) {
2912 goto fail;
2914 qemu_opts_to_qdict(opts, qdict);
2915 qemu_opts_del(opts);
2917 break;
2918 case '/':
2920 int count, format, size;
2922 while (qemu_isspace(*p))
2923 p++;
2924 if (*p == '/') {
2925 /* format found */
2926 p++;
2927 count = 1;
2928 if (qemu_isdigit(*p)) {
2929 count = 0;
2930 while (qemu_isdigit(*p)) {
2931 count = count * 10 + (*p - '0');
2932 p++;
2935 size = -1;
2936 format = -1;
2937 for(;;) {
2938 switch(*p) {
2939 case 'o':
2940 case 'd':
2941 case 'u':
2942 case 'x':
2943 case 'i':
2944 case 'c':
2945 format = *p++;
2946 break;
2947 case 'b':
2948 size = 1;
2949 p++;
2950 break;
2951 case 'h':
2952 size = 2;
2953 p++;
2954 break;
2955 case 'w':
2956 size = 4;
2957 p++;
2958 break;
2959 case 'g':
2960 case 'L':
2961 size = 8;
2962 p++;
2963 break;
2964 default:
2965 goto next;
2968 next:
2969 if (*p != '\0' && !qemu_isspace(*p)) {
2970 monitor_printf(mon, "invalid char in format: '%c'\n",
2971 *p);
2972 goto fail;
2974 if (format < 0)
2975 format = default_fmt_format;
2976 if (format != 'i') {
2977 /* for 'i', not specifying a size gives -1 as size */
2978 if (size < 0)
2979 size = default_fmt_size;
2980 default_fmt_size = size;
2982 default_fmt_format = format;
2983 } else {
2984 count = 1;
2985 format = default_fmt_format;
2986 if (format != 'i') {
2987 size = default_fmt_size;
2988 } else {
2989 size = -1;
2992 qdict_put_int(qdict, "count", count);
2993 qdict_put_int(qdict, "format", format);
2994 qdict_put_int(qdict, "size", size);
2996 break;
2997 case 'i':
2998 case 'l':
2999 case 'M':
3001 int64_t val;
3003 while (qemu_isspace(*p))
3004 p++;
3005 if (*typestr == '?' || *typestr == '.') {
3006 if (*typestr == '?') {
3007 if (*p == '\0') {
3008 typestr++;
3009 break;
3011 } else {
3012 if (*p == '.') {
3013 p++;
3014 while (qemu_isspace(*p))
3015 p++;
3016 } else {
3017 typestr++;
3018 break;
3021 typestr++;
3023 if (get_expr(mon, &val, &p))
3024 goto fail;
3025 /* Check if 'i' is greater than 32-bit */
3026 if ((c == 'i') && ((val >> 32) & 0xffffffff)) {
3027 monitor_printf(mon, "\'%s\' has failed: ", cmd->name);
3028 monitor_printf(mon, "integer is for 32-bit values\n");
3029 goto fail;
3030 } else if (c == 'M') {
3031 if (val < 0) {
3032 monitor_printf(mon, "enter a positive value\n");
3033 goto fail;
3035 val <<= 20;
3037 qdict_put_int(qdict, key, val);
3039 break;
3040 case 'o':
3042 int ret;
3043 uint64_t val;
3044 char *end;
3046 while (qemu_isspace(*p)) {
3047 p++;
3049 if (*typestr == '?') {
3050 typestr++;
3051 if (*p == '\0') {
3052 break;
3055 ret = qemu_strtosz_MiB(p, &end, &val);
3056 if (ret < 0 || val > INT64_MAX) {
3057 monitor_printf(mon, "invalid size\n");
3058 goto fail;
3060 qdict_put_int(qdict, key, val);
3061 p = end;
3063 break;
3064 case 'T':
3066 double val;
3068 while (qemu_isspace(*p))
3069 p++;
3070 if (*typestr == '?') {
3071 typestr++;
3072 if (*p == '\0') {
3073 break;
3076 if (get_double(mon, &val, &p) < 0) {
3077 goto fail;
3079 if (p[0] && p[1] == 's') {
3080 switch (*p) {
3081 case 'm':
3082 val /= 1e3; p += 2; break;
3083 case 'u':
3084 val /= 1e6; p += 2; break;
3085 case 'n':
3086 val /= 1e9; p += 2; break;
3089 if (*p && !qemu_isspace(*p)) {
3090 monitor_printf(mon, "Unknown unit suffix\n");
3091 goto fail;
3093 qdict_put(qdict, key, qnum_from_double(val));
3095 break;
3096 case 'b':
3098 const char *beg;
3099 bool val;
3101 while (qemu_isspace(*p)) {
3102 p++;
3104 beg = p;
3105 while (qemu_isgraph(*p)) {
3106 p++;
3108 if (p - beg == 2 && !memcmp(beg, "on", p - beg)) {
3109 val = true;
3110 } else if (p - beg == 3 && !memcmp(beg, "off", p - beg)) {
3111 val = false;
3112 } else {
3113 monitor_printf(mon, "Expected 'on' or 'off'\n");
3114 goto fail;
3116 qdict_put_bool(qdict, key, val);
3118 break;
3119 case '-':
3121 const char *tmp = p;
3122 int skip_key = 0;
3123 /* option */
3125 c = *typestr++;
3126 if (c == '\0')
3127 goto bad_type;
3128 while (qemu_isspace(*p))
3129 p++;
3130 if (*p == '-') {
3131 p++;
3132 if(c != *p) {
3133 if(!is_valid_option(p, typestr)) {
3135 monitor_printf(mon, "%s: unsupported option -%c\n",
3136 cmd->name, *p);
3137 goto fail;
3138 } else {
3139 skip_key = 1;
3142 if(skip_key) {
3143 p = tmp;
3144 } else {
3145 /* has option */
3146 p++;
3147 qdict_put_bool(qdict, key, true);
3151 break;
3152 case 'S':
3154 /* package all remaining string */
3155 int len;
3157 while (qemu_isspace(*p)) {
3158 p++;
3160 if (*typestr == '?') {
3161 typestr++;
3162 if (*p == '\0') {
3163 /* no remaining string: NULL argument */
3164 break;
3167 len = strlen(p);
3168 if (len <= 0) {
3169 monitor_printf(mon, "%s: string expected\n",
3170 cmd->name);
3171 goto fail;
3173 qdict_put_str(qdict, key, p);
3174 p += len;
3176 break;
3177 default:
3178 bad_type:
3179 monitor_printf(mon, "%s: unknown type '%c'\n", cmd->name, c);
3180 goto fail;
3182 g_free(key);
3183 key = NULL;
3185 /* check that all arguments were parsed */
3186 while (qemu_isspace(*p))
3187 p++;
3188 if (*p != '\0') {
3189 monitor_printf(mon, "%s: extraneous characters at the end of line\n",
3190 cmd->name);
3191 goto fail;
3194 return qdict;
3196 fail:
3197 QDECREF(qdict);
3198 g_free(key);
3199 return NULL;
3202 static void handle_hmp_command(Monitor *mon, const char *cmdline)
3204 QDict *qdict;
3205 const mon_cmd_t *cmd;
3207 trace_handle_hmp_command(mon, cmdline);
3209 cmd = monitor_parse_command(mon, cmdline, &cmdline, mon->cmd_table);
3210 if (!cmd) {
3211 return;
3214 qdict = monitor_parse_arguments(mon, &cmdline, cmd);
3215 if (!qdict) {
3216 monitor_printf(mon, "Try \"help %s\" for more information\n",
3217 cmd->name);
3218 return;
3221 cmd->cmd(mon, qdict);
3222 QDECREF(qdict);
3225 static void cmd_completion(Monitor *mon, const char *name, const char *list)
3227 const char *p, *pstart;
3228 char cmd[128];
3229 int len;
3231 p = list;
3232 for(;;) {
3233 pstart = p;
3234 p = strchr(p, '|');
3235 if (!p)
3236 p = pstart + strlen(pstart);
3237 len = p - pstart;
3238 if (len > sizeof(cmd) - 2)
3239 len = sizeof(cmd) - 2;
3240 memcpy(cmd, pstart, len);
3241 cmd[len] = '\0';
3242 if (name[0] == '\0' || !strncmp(name, cmd, strlen(name))) {
3243 readline_add_completion(mon->rs, cmd);
3245 if (*p == '\0')
3246 break;
3247 p++;
3251 static void file_completion(Monitor *mon, const char *input)
3253 DIR *ffs;
3254 struct dirent *d;
3255 char path[1024];
3256 char file[1024], file_prefix[1024];
3257 int input_path_len;
3258 const char *p;
3260 p = strrchr(input, '/');
3261 if (!p) {
3262 input_path_len = 0;
3263 pstrcpy(file_prefix, sizeof(file_prefix), input);
3264 pstrcpy(path, sizeof(path), ".");
3265 } else {
3266 input_path_len = p - input + 1;
3267 memcpy(path, input, input_path_len);
3268 if (input_path_len > sizeof(path) - 1)
3269 input_path_len = sizeof(path) - 1;
3270 path[input_path_len] = '\0';
3271 pstrcpy(file_prefix, sizeof(file_prefix), p + 1);
3274 ffs = opendir(path);
3275 if (!ffs)
3276 return;
3277 for(;;) {
3278 struct stat sb;
3279 d = readdir(ffs);
3280 if (!d)
3281 break;
3283 if (strcmp(d->d_name, ".") == 0 || strcmp(d->d_name, "..") == 0) {
3284 continue;
3287 if (strstart(d->d_name, file_prefix, NULL)) {
3288 memcpy(file, input, input_path_len);
3289 if (input_path_len < sizeof(file))
3290 pstrcpy(file + input_path_len, sizeof(file) - input_path_len,
3291 d->d_name);
3292 /* stat the file to find out if it's a directory.
3293 * In that case add a slash to speed up typing long paths
3295 if (stat(file, &sb) == 0 && S_ISDIR(sb.st_mode)) {
3296 pstrcat(file, sizeof(file), "/");
3298 readline_add_completion(mon->rs, file);
3301 closedir(ffs);
3304 static const char *next_arg_type(const char *typestr)
3306 const char *p = strchr(typestr, ':');
3307 return (p != NULL ? ++p : typestr);
3310 static void add_completion_option(ReadLineState *rs, const char *str,
3311 const char *option)
3313 if (!str || !option) {
3314 return;
3316 if (!strncmp(option, str, strlen(str))) {
3317 readline_add_completion(rs, option);
3321 void chardev_add_completion(ReadLineState *rs, int nb_args, const char *str)
3323 size_t len;
3324 ChardevBackendInfoList *list, *start;
3326 if (nb_args != 2) {
3327 return;
3329 len = strlen(str);
3330 readline_set_completion_index(rs, len);
3332 start = list = qmp_query_chardev_backends(NULL);
3333 while (list) {
3334 const char *chr_name = list->value->name;
3336 if (!strncmp(chr_name, str, len)) {
3337 readline_add_completion(rs, chr_name);
3339 list = list->next;
3341 qapi_free_ChardevBackendInfoList(start);
3344 void netdev_add_completion(ReadLineState *rs, int nb_args, const char *str)
3346 size_t len;
3347 int i;
3349 if (nb_args != 2) {
3350 return;
3352 len = strlen(str);
3353 readline_set_completion_index(rs, len);
3354 for (i = 0; i < NET_CLIENT_DRIVER__MAX; i++) {
3355 add_completion_option(rs, str, NetClientDriver_str(i));
3359 void device_add_completion(ReadLineState *rs, int nb_args, const char *str)
3361 GSList *list, *elt;
3362 size_t len;
3364 if (nb_args != 2) {
3365 return;
3368 len = strlen(str);
3369 readline_set_completion_index(rs, len);
3370 list = elt = object_class_get_list(TYPE_DEVICE, false);
3371 while (elt) {
3372 const char *name;
3373 DeviceClass *dc = OBJECT_CLASS_CHECK(DeviceClass, elt->data,
3374 TYPE_DEVICE);
3375 name = object_class_get_name(OBJECT_CLASS(dc));
3377 if (dc->user_creatable
3378 && !strncmp(name, str, len)) {
3379 readline_add_completion(rs, name);
3381 elt = elt->next;
3383 g_slist_free(list);
3386 void object_add_completion(ReadLineState *rs, int nb_args, const char *str)
3388 GSList *list, *elt;
3389 size_t len;
3391 if (nb_args != 2) {
3392 return;
3395 len = strlen(str);
3396 readline_set_completion_index(rs, len);
3397 list = elt = object_class_get_list(TYPE_USER_CREATABLE, false);
3398 while (elt) {
3399 const char *name;
3401 name = object_class_get_name(OBJECT_CLASS(elt->data));
3402 if (!strncmp(name, str, len) && strcmp(name, TYPE_USER_CREATABLE)) {
3403 readline_add_completion(rs, name);
3405 elt = elt->next;
3407 g_slist_free(list);
3410 static void peripheral_device_del_completion(ReadLineState *rs,
3411 const char *str, size_t len)
3413 Object *peripheral = container_get(qdev_get_machine(), "/peripheral");
3414 GSList *list, *item;
3416 list = qdev_build_hotpluggable_device_list(peripheral);
3417 if (!list) {
3418 return;
3421 for (item = list; item; item = g_slist_next(item)) {
3422 DeviceState *dev = item->data;
3424 if (dev->id && !strncmp(str, dev->id, len)) {
3425 readline_add_completion(rs, dev->id);
3429 g_slist_free(list);
3432 void chardev_remove_completion(ReadLineState *rs, int nb_args, const char *str)
3434 size_t len;
3435 ChardevInfoList *list, *start;
3437 if (nb_args != 2) {
3438 return;
3440 len = strlen(str);
3441 readline_set_completion_index(rs, len);
3443 start = list = qmp_query_chardev(NULL);
3444 while (list) {
3445 ChardevInfo *chr = list->value;
3447 if (!strncmp(chr->label, str, len)) {
3448 readline_add_completion(rs, chr->label);
3450 list = list->next;
3452 qapi_free_ChardevInfoList(start);
3455 static void ringbuf_completion(ReadLineState *rs, const char *str)
3457 size_t len;
3458 ChardevInfoList *list, *start;
3460 len = strlen(str);
3461 readline_set_completion_index(rs, len);
3463 start = list = qmp_query_chardev(NULL);
3464 while (list) {
3465 ChardevInfo *chr_info = list->value;
3467 if (!strncmp(chr_info->label, str, len)) {
3468 Chardev *chr = qemu_chr_find(chr_info->label);
3469 if (chr && CHARDEV_IS_RINGBUF(chr)) {
3470 readline_add_completion(rs, chr_info->label);
3473 list = list->next;
3475 qapi_free_ChardevInfoList(start);
3478 void ringbuf_write_completion(ReadLineState *rs, int nb_args, const char *str)
3480 if (nb_args != 2) {
3481 return;
3483 ringbuf_completion(rs, str);
3486 void device_del_completion(ReadLineState *rs, int nb_args, const char *str)
3488 size_t len;
3490 if (nb_args != 2) {
3491 return;
3494 len = strlen(str);
3495 readline_set_completion_index(rs, len);
3496 peripheral_device_del_completion(rs, str, len);
3499 void object_del_completion(ReadLineState *rs, int nb_args, const char *str)
3501 ObjectPropertyInfoList *list, *start;
3502 size_t len;
3504 if (nb_args != 2) {
3505 return;
3507 len = strlen(str);
3508 readline_set_completion_index(rs, len);
3510 start = list = qmp_qom_list("/objects", NULL);
3511 while (list) {
3512 ObjectPropertyInfo *info = list->value;
3514 if (!strncmp(info->type, "child<", 5)
3515 && !strncmp(info->name, str, len)) {
3516 readline_add_completion(rs, info->name);
3518 list = list->next;
3520 qapi_free_ObjectPropertyInfoList(start);
3523 void sendkey_completion(ReadLineState *rs, int nb_args, const char *str)
3525 int i;
3526 char *sep;
3527 size_t len;
3529 if (nb_args != 2) {
3530 return;
3532 sep = strrchr(str, '-');
3533 if (sep) {
3534 str = sep + 1;
3536 len = strlen(str);
3537 readline_set_completion_index(rs, len);
3538 for (i = 0; i < Q_KEY_CODE__MAX; i++) {
3539 if (!strncmp(str, QKeyCode_str(i), len)) {
3540 readline_add_completion(rs, QKeyCode_str(i));
3545 void set_link_completion(ReadLineState *rs, int nb_args, const char *str)
3547 size_t len;
3549 len = strlen(str);
3550 readline_set_completion_index(rs, len);
3551 if (nb_args == 2) {
3552 NetClientState *ncs[MAX_QUEUE_NUM];
3553 int count, i;
3554 count = qemu_find_net_clients_except(NULL, ncs,
3555 NET_CLIENT_DRIVER_NONE,
3556 MAX_QUEUE_NUM);
3557 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3558 const char *name = ncs[i]->name;
3559 if (!strncmp(str, name, len)) {
3560 readline_add_completion(rs, name);
3563 } else if (nb_args == 3) {
3564 add_completion_option(rs, str, "on");
3565 add_completion_option(rs, str, "off");
3569 void netdev_del_completion(ReadLineState *rs, int nb_args, const char *str)
3571 int len, count, i;
3572 NetClientState *ncs[MAX_QUEUE_NUM];
3574 if (nb_args != 2) {
3575 return;
3578 len = strlen(str);
3579 readline_set_completion_index(rs, len);
3580 count = qemu_find_net_clients_except(NULL, ncs, NET_CLIENT_DRIVER_NIC,
3581 MAX_QUEUE_NUM);
3582 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3583 QemuOpts *opts;
3584 const char *name = ncs[i]->name;
3585 if (strncmp(str, name, len)) {
3586 continue;
3588 opts = qemu_opts_find(qemu_find_opts_err("netdev", NULL), name);
3589 if (opts) {
3590 readline_add_completion(rs, name);
3595 void info_trace_events_completion(ReadLineState *rs, int nb_args, const char *str)
3597 size_t len;
3599 len = strlen(str);
3600 readline_set_completion_index(rs, len);
3601 if (nb_args == 2) {
3602 TraceEventIter iter;
3603 TraceEvent *ev;
3604 char *pattern = g_strdup_printf("%s*", str);
3605 trace_event_iter_init(&iter, pattern);
3606 while ((ev = trace_event_iter_next(&iter)) != NULL) {
3607 readline_add_completion(rs, trace_event_get_name(ev));
3609 g_free(pattern);
3613 void trace_event_completion(ReadLineState *rs, int nb_args, const char *str)
3615 size_t len;
3617 len = strlen(str);
3618 readline_set_completion_index(rs, len);
3619 if (nb_args == 2) {
3620 TraceEventIter iter;
3621 TraceEvent *ev;
3622 char *pattern = g_strdup_printf("%s*", str);
3623 trace_event_iter_init(&iter, pattern);
3624 while ((ev = trace_event_iter_next(&iter)) != NULL) {
3625 readline_add_completion(rs, trace_event_get_name(ev));
3627 g_free(pattern);
3628 } else if (nb_args == 3) {
3629 add_completion_option(rs, str, "on");
3630 add_completion_option(rs, str, "off");
3634 void watchdog_action_completion(ReadLineState *rs, int nb_args, const char *str)
3636 int i;
3638 if (nb_args != 2) {
3639 return;
3641 readline_set_completion_index(rs, strlen(str));
3642 for (i = 0; i < WATCHDOG_ACTION__MAX; i++) {
3643 add_completion_option(rs, str, WatchdogAction_str(i));
3647 void migrate_set_capability_completion(ReadLineState *rs, int nb_args,
3648 const char *str)
3650 size_t len;
3652 len = strlen(str);
3653 readline_set_completion_index(rs, len);
3654 if (nb_args == 2) {
3655 int i;
3656 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
3657 const char *name = MigrationCapability_str(i);
3658 if (!strncmp(str, name, len)) {
3659 readline_add_completion(rs, name);
3662 } else if (nb_args == 3) {
3663 add_completion_option(rs, str, "on");
3664 add_completion_option(rs, str, "off");
3668 void migrate_set_parameter_completion(ReadLineState *rs, int nb_args,
3669 const char *str)
3671 size_t len;
3673 len = strlen(str);
3674 readline_set_completion_index(rs, len);
3675 if (nb_args == 2) {
3676 int i;
3677 for (i = 0; i < MIGRATION_PARAMETER__MAX; i++) {
3678 const char *name = MigrationParameter_str(i);
3679 if (!strncmp(str, name, len)) {
3680 readline_add_completion(rs, name);
3686 static void vm_completion(ReadLineState *rs, const char *str)
3688 size_t len;
3689 BlockDriverState *bs;
3690 BdrvNextIterator it;
3692 len = strlen(str);
3693 readline_set_completion_index(rs, len);
3695 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
3696 SnapshotInfoList *snapshots, *snapshot;
3697 AioContext *ctx = bdrv_get_aio_context(bs);
3698 bool ok = false;
3700 aio_context_acquire(ctx);
3701 if (bdrv_can_snapshot(bs)) {
3702 ok = bdrv_query_snapshot_info_list(bs, &snapshots, NULL) == 0;
3704 aio_context_release(ctx);
3705 if (!ok) {
3706 continue;
3709 snapshot = snapshots;
3710 while (snapshot) {
3711 char *completion = snapshot->value->name;
3712 if (!strncmp(str, completion, len)) {
3713 readline_add_completion(rs, completion);
3715 completion = snapshot->value->id;
3716 if (!strncmp(str, completion, len)) {
3717 readline_add_completion(rs, completion);
3719 snapshot = snapshot->next;
3721 qapi_free_SnapshotInfoList(snapshots);
3726 void delvm_completion(ReadLineState *rs, int nb_args, const char *str)
3728 if (nb_args == 2) {
3729 vm_completion(rs, str);
3733 void loadvm_completion(ReadLineState *rs, int nb_args, const char *str)
3735 if (nb_args == 2) {
3736 vm_completion(rs, str);
3740 static void monitor_find_completion_by_table(Monitor *mon,
3741 const mon_cmd_t *cmd_table,
3742 char **args,
3743 int nb_args)
3745 const char *cmdname;
3746 int i;
3747 const char *ptype, *old_ptype, *str, *name;
3748 const mon_cmd_t *cmd;
3749 BlockBackend *blk = NULL;
3751 if (nb_args <= 1) {
3752 /* command completion */
3753 if (nb_args == 0)
3754 cmdname = "";
3755 else
3756 cmdname = args[0];
3757 readline_set_completion_index(mon->rs, strlen(cmdname));
3758 for (cmd = cmd_table; cmd->name != NULL; cmd++) {
3759 cmd_completion(mon, cmdname, cmd->name);
3761 } else {
3762 /* find the command */
3763 for (cmd = cmd_table; cmd->name != NULL; cmd++) {
3764 if (compare_cmd(args[0], cmd->name)) {
3765 break;
3768 if (!cmd->name) {
3769 return;
3772 if (cmd->sub_table) {
3773 /* do the job again */
3774 monitor_find_completion_by_table(mon, cmd->sub_table,
3775 &args[1], nb_args - 1);
3776 return;
3778 if (cmd->command_completion) {
3779 cmd->command_completion(mon->rs, nb_args, args[nb_args - 1]);
3780 return;
3783 ptype = next_arg_type(cmd->args_type);
3784 for(i = 0; i < nb_args - 2; i++) {
3785 if (*ptype != '\0') {
3786 ptype = next_arg_type(ptype);
3787 while (*ptype == '?')
3788 ptype = next_arg_type(ptype);
3791 str = args[nb_args - 1];
3792 old_ptype = NULL;
3793 while (*ptype == '-' && old_ptype != ptype) {
3794 old_ptype = ptype;
3795 ptype = next_arg_type(ptype);
3797 switch(*ptype) {
3798 case 'F':
3799 /* file completion */
3800 readline_set_completion_index(mon->rs, strlen(str));
3801 file_completion(mon, str);
3802 break;
3803 case 'B':
3804 /* block device name completion */
3805 readline_set_completion_index(mon->rs, strlen(str));
3806 while ((blk = blk_next(blk)) != NULL) {
3807 name = blk_name(blk);
3808 if (str[0] == '\0' ||
3809 !strncmp(name, str, strlen(str))) {
3810 readline_add_completion(mon->rs, name);
3813 break;
3814 case 's':
3815 case 'S':
3816 if (!strcmp(cmd->name, "help|?")) {
3817 monitor_find_completion_by_table(mon, cmd_table,
3818 &args[1], nb_args - 1);
3820 break;
3821 default:
3822 break;
3827 static void monitor_find_completion(void *opaque,
3828 const char *cmdline)
3830 Monitor *mon = opaque;
3831 char *args[MAX_ARGS];
3832 int nb_args, len;
3834 /* 1. parse the cmdline */
3835 if (parse_cmdline(cmdline, &nb_args, args) < 0) {
3836 return;
3839 /* if the line ends with a space, it means we want to complete the
3840 next arg */
3841 len = strlen(cmdline);
3842 if (len > 0 && qemu_isspace(cmdline[len - 1])) {
3843 if (nb_args >= MAX_ARGS) {
3844 goto cleanup;
3846 args[nb_args++] = g_strdup("");
3849 /* 2. auto complete according to args */
3850 monitor_find_completion_by_table(mon, mon->cmd_table, args, nb_args);
3852 cleanup:
3853 free_cmdline_args(args, nb_args);
3856 static int monitor_can_read(void *opaque)
3858 Monitor *mon = opaque;
3860 return !atomic_mb_read(&mon->suspend_cnt);
3864 * 1. This function takes ownership of rsp, err, and id.
3865 * 2. rsp, err, and id may be NULL.
3866 * 3. If err != NULL then rsp must be NULL.
3868 static void monitor_qmp_respond(Monitor *mon, QObject *rsp,
3869 Error *err, QObject *id)
3871 QDict *qdict = NULL;
3873 if (err) {
3874 assert(!rsp);
3875 qdict = qdict_new();
3876 qdict_put_obj(qdict, "error", qmp_build_error_object(err));
3877 error_free(err);
3878 rsp = QOBJECT(qdict);
3881 if (rsp) {
3882 if (id) {
3883 /* This is for the qdict below. */
3884 qobject_incref(id);
3885 qdict_put_obj(qobject_to(QDict, rsp), "id", id);
3888 monitor_json_emitter(mon, rsp);
3891 qobject_decref(id);
3892 qobject_decref(rsp);
3895 struct QMPRequest {
3896 /* Owner of the request */
3897 Monitor *mon;
3898 /* "id" field of the request */
3899 QObject *id;
3900 /* Request object to be handled */
3901 QObject *req;
3903 * Whether we need to resume the monitor afterward. This flag is
3904 * used to emulate the old QMP server behavior that the current
3905 * command must be completed before execution of the next one.
3907 bool need_resume;
3909 typedef struct QMPRequest QMPRequest;
3912 * Dispatch one single QMP request. The function will free the req_obj
3913 * and objects inside it before return.
3915 static void monitor_qmp_dispatch_one(QMPRequest *req_obj)
3917 Monitor *mon, *old_mon;
3918 QObject *req, *rsp = NULL, *id;
3919 QDict *qdict = NULL;
3920 bool need_resume;
3922 req = req_obj->req;
3923 mon = req_obj->mon;
3924 id = req_obj->id;
3925 need_resume = req_obj->need_resume;
3927 g_free(req_obj);
3929 if (trace_event_get_state_backends(TRACE_HANDLE_QMP_COMMAND)) {
3930 QString *req_json = qobject_to_json(req);
3931 trace_handle_qmp_command(mon, qstring_get_str(req_json));
3932 QDECREF(req_json);
3935 old_mon = cur_mon;
3936 cur_mon = mon;
3938 rsp = qmp_dispatch(mon->qmp.commands, req);
3940 cur_mon = old_mon;
3942 if (mon->qmp.commands == &qmp_cap_negotiation_commands) {
3943 qdict = qdict_get_qdict(qobject_to(QDict, rsp), "error");
3944 if (qdict
3945 && !g_strcmp0(qdict_get_try_str(qdict, "class"),
3946 QapiErrorClass_str(ERROR_CLASS_COMMAND_NOT_FOUND))) {
3947 /* Provide a more useful error message */
3948 qdict_del(qdict, "desc");
3949 qdict_put_str(qdict, "desc", "Expecting capabilities negotiation"
3950 " with 'qmp_capabilities'");
3954 /* Respond if necessary */
3955 monitor_qmp_respond(mon, rsp, NULL, id);
3957 /* This pairs with the monitor_suspend() in handle_qmp_command(). */
3958 if (need_resume) {
3959 monitor_resume(mon);
3962 qobject_decref(req);
3966 * Pop one QMP request from monitor queues, return NULL if not found.
3967 * We are using round-robin fashion to pop the request, to avoid
3968 * processing commands only on a very busy monitor. To achieve that,
3969 * when we process one request on a specific monitor, we put that
3970 * monitor to the end of mon_list queue.
3972 static QMPRequest *monitor_qmp_requests_pop_one(void)
3974 QMPRequest *req_obj = NULL;
3975 Monitor *mon;
3977 qemu_mutex_lock(&monitor_lock);
3979 QTAILQ_FOREACH(mon, &mon_list, entry) {
3980 qemu_mutex_lock(&mon->qmp.qmp_queue_lock);
3981 req_obj = g_queue_pop_head(mon->qmp.qmp_requests);
3982 qemu_mutex_unlock(&mon->qmp.qmp_queue_lock);
3983 if (req_obj) {
3984 break;
3988 if (req_obj) {
3990 * We found one request on the monitor. Degrade this monitor's
3991 * priority to lowest by re-inserting it to end of queue.
3993 QTAILQ_REMOVE(&mon_list, mon, entry);
3994 QTAILQ_INSERT_TAIL(&mon_list, mon, entry);
3997 qemu_mutex_unlock(&monitor_lock);
3999 return req_obj;
4002 static void monitor_qmp_bh_dispatcher(void *data)
4004 QMPRequest *req_obj = monitor_qmp_requests_pop_one();
4006 if (req_obj) {
4007 monitor_qmp_dispatch_one(req_obj);
4008 /* Reschedule instead of looping so the main loop stays responsive */
4009 qemu_bh_schedule(mon_global.qmp_dispatcher_bh);
4013 #define QMP_REQ_QUEUE_LEN_MAX (8)
4015 static void handle_qmp_command(JSONMessageParser *parser, GQueue *tokens)
4017 QObject *req, *id = NULL;
4018 QDict *qdict = NULL;
4019 MonitorQMP *mon_qmp = container_of(parser, MonitorQMP, parser);
4020 Monitor *mon = container_of(mon_qmp, Monitor, qmp);
4021 Error *err = NULL;
4022 QMPRequest *req_obj;
4024 req = json_parser_parse_err(tokens, NULL, &err);
4025 if (!req && !err) {
4026 /* json_parser_parse_err() sucks: can fail without setting @err */
4027 error_setg(&err, QERR_JSON_PARSING);
4029 if (err) {
4030 monitor_qmp_respond(mon, NULL, err, NULL);
4031 qobject_decref(req);
4032 return;
4035 qdict = qobject_to(QDict, req);
4036 if (qdict) {
4037 id = qdict_get(qdict, "id");
4038 qobject_incref(id);
4039 qdict_del(qdict, "id");
4040 } /* else will fail qmp_dispatch() */
4042 req_obj = g_new0(QMPRequest, 1);
4043 req_obj->mon = mon;
4044 req_obj->id = id;
4045 req_obj->req = req;
4046 req_obj->need_resume = false;
4048 /* Protect qmp_requests and fetching its length. */
4049 qemu_mutex_lock(&mon->qmp.qmp_queue_lock);
4052 * If OOB is not enabled on the current monitor, we'll emulate the
4053 * old behavior that we won't process the current monitor any more
4054 * until it has responded. This helps make sure that as long as
4055 * OOB is not enabled, the server will never drop any command.
4057 if (!qmp_oob_enabled(mon)) {
4058 monitor_suspend(mon);
4059 req_obj->need_resume = true;
4060 } else {
4061 /* Drop the request if queue is full. */
4062 if (mon->qmp.qmp_requests->length >= QMP_REQ_QUEUE_LEN_MAX) {
4063 qemu_mutex_unlock(&mon->qmp.qmp_queue_lock);
4064 qapi_event_send_command_dropped(id,
4065 COMMAND_DROP_REASON_QUEUE_FULL,
4066 &error_abort);
4067 qobject_decref(id);
4068 qobject_decref(req);
4069 g_free(req_obj);
4070 return;
4075 * Put the request to the end of queue so that requests will be
4076 * handled in time order. Ownership for req_obj, req, id,
4077 * etc. will be delivered to the handler side.
4079 g_queue_push_tail(mon->qmp.qmp_requests, req_obj);
4080 qemu_mutex_unlock(&mon->qmp.qmp_queue_lock);
4082 /* Kick the dispatcher routine */
4083 qemu_bh_schedule(mon_global.qmp_dispatcher_bh);
4086 static void monitor_qmp_read(void *opaque, const uint8_t *buf, int size)
4088 Monitor *mon = opaque;
4090 json_message_parser_feed(&mon->qmp.parser, (const char *) buf, size);
4093 static void monitor_read(void *opaque, const uint8_t *buf, int size)
4095 Monitor *old_mon = cur_mon;
4096 int i;
4098 cur_mon = opaque;
4100 if (cur_mon->rs) {
4101 for (i = 0; i < size; i++)
4102 readline_handle_byte(cur_mon->rs, buf[i]);
4103 } else {
4104 if (size == 0 || buf[size - 1] != 0)
4105 monitor_printf(cur_mon, "corrupted command\n");
4106 else
4107 handle_hmp_command(cur_mon, (char *)buf);
4110 cur_mon = old_mon;
4113 static void monitor_command_cb(void *opaque, const char *cmdline,
4114 void *readline_opaque)
4116 Monitor *mon = opaque;
4118 monitor_suspend(mon);
4119 handle_hmp_command(mon, cmdline);
4120 monitor_resume(mon);
4123 int monitor_suspend(Monitor *mon)
4125 if (monitor_is_hmp_non_interactive(mon)) {
4126 return -ENOTTY;
4129 atomic_inc(&mon->suspend_cnt);
4131 if (monitor_is_qmp(mon)) {
4133 * Kick iothread to make sure this takes effect. It'll be
4134 * evaluated again in prepare() of the watch object.
4136 aio_notify(iothread_get_aio_context(mon_global.mon_iothread));
4139 trace_monitor_suspend(mon, 1);
4140 return 0;
4143 void monitor_resume(Monitor *mon)
4145 if (monitor_is_hmp_non_interactive(mon)) {
4146 return;
4149 if (atomic_dec_fetch(&mon->suspend_cnt) == 0) {
4150 if (monitor_is_qmp(mon)) {
4152 * For QMP monitors that are running in IOThread, let's
4153 * kick the thread in case it's sleeping.
4155 if (mon->use_io_thr) {
4156 aio_notify(iothread_get_aio_context(mon_global.mon_iothread));
4158 } else {
4159 assert(mon->rs);
4160 readline_show_prompt(mon->rs);
4163 trace_monitor_suspend(mon, -1);
4166 static QObject *get_qmp_greeting(Monitor *mon)
4168 QList *cap_list = qlist_new();
4169 QObject *ver = NULL;
4170 QMPCapability cap;
4172 qmp_marshal_query_version(NULL, &ver, NULL);
4174 for (cap = 0; cap < QMP_CAPABILITY__MAX; cap++) {
4175 if (!mon->use_io_thr && cap == QMP_CAPABILITY_OOB) {
4176 /* Monitors that are not using IOThread won't support OOB */
4177 continue;
4179 qlist_append(cap_list, qstring_from_str(QMPCapability_str(cap)));
4182 return qobject_from_jsonf("{'QMP': {'version': %p, 'capabilities': %p}}",
4183 ver, cap_list);
4186 static void monitor_qmp_caps_reset(Monitor *mon)
4188 memset(mon->qmp.qmp_caps, 0, sizeof(mon->qmp.qmp_caps));
4191 static void monitor_qmp_event(void *opaque, int event)
4193 QObject *data;
4194 Monitor *mon = opaque;
4196 switch (event) {
4197 case CHR_EVENT_OPENED:
4198 mon->qmp.commands = &qmp_cap_negotiation_commands;
4199 monitor_qmp_caps_reset(mon);
4200 data = get_qmp_greeting(mon);
4201 monitor_json_emitter(mon, data);
4202 qobject_decref(data);
4203 mon_refcount++;
4204 break;
4205 case CHR_EVENT_CLOSED:
4206 json_message_parser_destroy(&mon->qmp.parser);
4207 json_message_parser_init(&mon->qmp.parser, handle_qmp_command);
4208 mon_refcount--;
4209 monitor_fdsets_cleanup();
4210 break;
4214 static void monitor_event(void *opaque, int event)
4216 Monitor *mon = opaque;
4218 switch (event) {
4219 case CHR_EVENT_MUX_IN:
4220 qemu_mutex_lock(&mon->out_lock);
4221 mon->mux_out = 0;
4222 qemu_mutex_unlock(&mon->out_lock);
4223 if (mon->reset_seen) {
4224 readline_restart(mon->rs);
4225 monitor_resume(mon);
4226 monitor_flush(mon);
4227 } else {
4228 atomic_mb_set(&mon->suspend_cnt, 0);
4230 break;
4232 case CHR_EVENT_MUX_OUT:
4233 if (mon->reset_seen) {
4234 if (atomic_mb_read(&mon->suspend_cnt) == 0) {
4235 monitor_printf(mon, "\n");
4237 monitor_flush(mon);
4238 monitor_suspend(mon);
4239 } else {
4240 atomic_inc(&mon->suspend_cnt);
4242 qemu_mutex_lock(&mon->out_lock);
4243 mon->mux_out = 1;
4244 qemu_mutex_unlock(&mon->out_lock);
4245 break;
4247 case CHR_EVENT_OPENED:
4248 monitor_printf(mon, "QEMU %s monitor - type 'help' for more "
4249 "information\n", QEMU_VERSION);
4250 if (!mon->mux_out) {
4251 readline_restart(mon->rs);
4252 readline_show_prompt(mon->rs);
4254 mon->reset_seen = 1;
4255 mon_refcount++;
4256 break;
4258 case CHR_EVENT_CLOSED:
4259 mon_refcount--;
4260 monitor_fdsets_cleanup();
4261 break;
4265 static int
4266 compare_mon_cmd(const void *a, const void *b)
4268 return strcmp(((const mon_cmd_t *)a)->name,
4269 ((const mon_cmd_t *)b)->name);
4272 static void sortcmdlist(void)
4274 int array_num;
4275 int elem_size = sizeof(mon_cmd_t);
4277 array_num = sizeof(mon_cmds)/elem_size-1;
4278 qsort((void *)mon_cmds, array_num, elem_size, compare_mon_cmd);
4280 array_num = sizeof(info_cmds)/elem_size-1;
4281 qsort((void *)info_cmds, array_num, elem_size, compare_mon_cmd);
4284 static GMainContext *monitor_get_io_context(void)
4286 return iothread_get_g_main_context(mon_global.mon_iothread);
4289 static AioContext *monitor_get_aio_context(void)
4291 return iothread_get_aio_context(mon_global.mon_iothread);
4294 static void monitor_iothread_init(void)
4296 mon_global.mon_iothread = iothread_create("mon_iothread",
4297 &error_abort);
4300 * This MUST be on main loop thread since we have commands that
4301 * have assumption to be run on main loop thread. It would be
4302 * nice that one day we can remove this assumption in the future.
4304 mon_global.qmp_dispatcher_bh = aio_bh_new(qemu_get_aio_context(),
4305 monitor_qmp_bh_dispatcher,
4306 NULL);
4309 void monitor_init_globals(void)
4311 monitor_init_qmp_commands();
4312 monitor_qapi_event_init();
4313 sortcmdlist();
4314 qemu_mutex_init(&monitor_lock);
4315 monitor_iothread_init();
4318 /* These functions just adapt the readline interface in a typesafe way. We
4319 * could cast function pointers but that discards compiler checks.
4321 static void GCC_FMT_ATTR(2, 3) monitor_readline_printf(void *opaque,
4322 const char *fmt, ...)
4324 va_list ap;
4325 va_start(ap, fmt);
4326 monitor_vprintf(opaque, fmt, ap);
4327 va_end(ap);
4330 static void monitor_readline_flush(void *opaque)
4332 monitor_flush(opaque);
4336 * Print to current monitor if we have one, else to stderr.
4337 * TODO should return int, so callers can calculate width, but that
4338 * requires surgery to monitor_vprintf(). Left for another day.
4340 void error_vprintf(const char *fmt, va_list ap)
4342 if (cur_mon && !monitor_cur_is_qmp()) {
4343 monitor_vprintf(cur_mon, fmt, ap);
4344 } else {
4345 vfprintf(stderr, fmt, ap);
4349 void error_vprintf_unless_qmp(const char *fmt, va_list ap)
4351 if (cur_mon && !monitor_cur_is_qmp()) {
4352 monitor_vprintf(cur_mon, fmt, ap);
4353 } else if (!cur_mon) {
4354 vfprintf(stderr, fmt, ap);
4358 static void monitor_list_append(Monitor *mon)
4360 qemu_mutex_lock(&monitor_lock);
4361 QTAILQ_INSERT_HEAD(&mon_list, mon, entry);
4362 qemu_mutex_unlock(&monitor_lock);
4365 static void monitor_qmp_setup_handlers_bh(void *opaque)
4367 Monitor *mon = opaque;
4368 GMainContext *context;
4370 if (mon->use_io_thr) {
4372 * When use_io_thr is set, we use the global shared dedicated
4373 * IO thread for this monitor to handle input/output.
4375 context = monitor_get_io_context();
4376 /* We should have inited globals before reaching here. */
4377 assert(context);
4378 } else {
4379 /* The default main loop, which is the main thread */
4380 context = NULL;
4383 qemu_chr_fe_set_handlers(&mon->chr, monitor_can_read, monitor_qmp_read,
4384 monitor_qmp_event, NULL, mon, context, true);
4385 monitor_list_append(mon);
4388 void monitor_init(Chardev *chr, int flags)
4390 Monitor *mon = g_malloc(sizeof(*mon));
4392 monitor_data_init(mon, false, false);
4394 qemu_chr_fe_init(&mon->chr, chr, &error_abort);
4395 mon->flags = flags;
4396 if (flags & MONITOR_USE_READLINE) {
4397 mon->rs = readline_init(monitor_readline_printf,
4398 monitor_readline_flush,
4399 mon,
4400 monitor_find_completion);
4401 monitor_read_command(mon, 0);
4404 if (monitor_is_qmp(mon)) {
4405 qemu_chr_fe_set_echo(&mon->chr, true);
4406 json_message_parser_init(&mon->qmp.parser, handle_qmp_command);
4407 if (mon->use_io_thr) {
4409 * Make sure the old iowatch is gone. It's possible when
4410 * e.g. the chardev is in client mode, with wait=on.
4412 remove_fd_in_watch(chr);
4414 * We can't call qemu_chr_fe_set_handlers() directly here
4415 * since during the procedure the chardev will be active
4416 * and running in monitor iothread, while we'll still do
4417 * something before returning from it, which is a possible
4418 * race too. To avoid that, we just create a BH to setup
4419 * the handlers.
4421 aio_bh_schedule_oneshot(monitor_get_aio_context(),
4422 monitor_qmp_setup_handlers_bh, mon);
4423 /* We'll add this to mon_list in the BH when setup done */
4424 return;
4425 } else {
4426 qemu_chr_fe_set_handlers(&mon->chr, monitor_can_read,
4427 monitor_qmp_read, monitor_qmp_event,
4428 NULL, mon, NULL, true);
4430 } else {
4431 qemu_chr_fe_set_handlers(&mon->chr, monitor_can_read, monitor_read,
4432 monitor_event, NULL, mon, NULL, true);
4435 monitor_list_append(mon);
4438 void monitor_cleanup(void)
4440 Monitor *mon, *next;
4443 * We need to explicitly stop the iothread (but not destroy it),
4444 * cleanup the monitor resources, then destroy the iothread since
4445 * we need to unregister from chardev below in
4446 * monitor_data_destroy(), and chardev is not thread-safe yet
4448 iothread_stop(mon_global.mon_iothread);
4450 qemu_mutex_lock(&monitor_lock);
4451 QTAILQ_FOREACH_SAFE(mon, &mon_list, entry, next) {
4452 QTAILQ_REMOVE(&mon_list, mon, entry);
4453 monitor_data_destroy(mon);
4454 g_free(mon);
4456 qemu_mutex_unlock(&monitor_lock);
4458 /* QEMUBHs needs to be deleted before destroying the IOThread. */
4459 qemu_bh_delete(mon_global.qmp_dispatcher_bh);
4460 mon_global.qmp_dispatcher_bh = NULL;
4462 iothread_destroy(mon_global.mon_iothread);
4463 mon_global.mon_iothread = NULL;
4466 QemuOptsList qemu_mon_opts = {
4467 .name = "mon",
4468 .implied_opt_name = "chardev",
4469 .head = QTAILQ_HEAD_INITIALIZER(qemu_mon_opts.head),
4470 .desc = {
4472 .name = "mode",
4473 .type = QEMU_OPT_STRING,
4475 .name = "chardev",
4476 .type = QEMU_OPT_STRING,
4478 .name = "pretty",
4479 .type = QEMU_OPT_BOOL,
4481 { /* end of list */ }
4485 #ifndef TARGET_I386
4486 void qmp_rtc_reset_reinjection(Error **errp)
4488 error_setg(errp, QERR_FEATURE_DISABLED, "rtc-reset-reinjection");
4491 SevInfo *qmp_query_sev(Error **errp)
4493 error_setg(errp, QERR_FEATURE_DISABLED, "query-sev");
4494 return NULL;
4497 SevLaunchMeasureInfo *qmp_query_sev_launch_measure(Error **errp)
4499 error_setg(errp, QERR_FEATURE_DISABLED, "query-sev-launch-measure");
4500 return NULL;
4503 SevCapability *qmp_query_sev_capabilities(Error **errp)
4505 error_setg(errp, QERR_FEATURE_DISABLED, "query-sev-capabilities");
4506 return NULL;
4508 #endif
4510 #ifndef TARGET_S390X
4511 void qmp_dump_skeys(const char *filename, Error **errp)
4513 error_setg(errp, QERR_FEATURE_DISABLED, "dump-skeys");
4515 #endif
4517 #ifndef TARGET_ARM
4518 GICCapabilityList *qmp_query_gic_capabilities(Error **errp)
4520 error_setg(errp, QERR_FEATURE_DISABLED, "query-gic-capabilities");
4521 return NULL;
4523 #endif
4525 HotpluggableCPUList *qmp_query_hotpluggable_cpus(Error **errp)
4527 MachineState *ms = MACHINE(qdev_get_machine());
4528 MachineClass *mc = MACHINE_GET_CLASS(ms);
4530 if (!mc->has_hotpluggable_cpus) {
4531 error_setg(errp, QERR_FEATURE_DISABLED, "query-hotpluggable-cpus");
4532 return NULL;
4535 return machine_query_hotpluggable_cpus(ms);