monitor: let suspend_cnt be thread safe
[qemu/ar7.git] / monitor.c
blob00de3c37ab9b106899f2e93a44641ef490bbc2b5
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];
175 } MonitorQMP;
178 * To prevent flooding clients, events can be throttled. The
179 * throttling is calculated globally, rather than per-Monitor
180 * instance.
182 typedef struct MonitorQAPIEventState {
183 QAPIEvent event; /* Throttling state for this event type and... */
184 QDict *data; /* ... data, see qapi_event_throttle_equal() */
185 QEMUTimer *timer; /* Timer for handling delayed events */
186 QDict *qdict; /* Delayed event (if any) */
187 } MonitorQAPIEventState;
189 typedef struct {
190 int64_t rate; /* Minimum time (in ns) between two events */
191 } MonitorQAPIEventConf;
193 struct Monitor {
194 CharBackend chr;
195 int reset_seen;
196 int flags;
197 int suspend_cnt; /* Needs to be accessed atomically */
198 bool skip_flush;
199 bool use_io_thr;
201 QemuMutex out_lock;
202 QString *outbuf;
203 guint out_watch;
205 /* Read under either BQL or out_lock, written with BQL+out_lock. */
206 int mux_out;
208 ReadLineState *rs;
209 MonitorQMP qmp;
210 gchar *mon_cpu_path;
211 BlockCompletionFunc *password_completion_cb;
212 void *password_opaque;
213 mon_cmd_t *cmd_table;
214 QLIST_HEAD(,mon_fd_t) fds;
215 QTAILQ_ENTRY(Monitor) entry;
218 /* Let's add monitor global variables to this struct. */
219 static struct {
220 IOThread *mon_iothread;
221 } mon_global;
223 /* QMP checker flags */
224 #define QMP_ACCEPT_UNKNOWNS 1
226 /* Protects mon_list, monitor_event_state. */
227 static QemuMutex monitor_lock;
229 static QTAILQ_HEAD(mon_list, Monitor) mon_list;
230 static QLIST_HEAD(mon_fdsets, MonFdset) mon_fdsets;
231 static int mon_refcount;
233 static mon_cmd_t mon_cmds[];
234 static mon_cmd_t info_cmds[];
236 QmpCommandList qmp_commands, qmp_cap_negotiation_commands;
238 Monitor *cur_mon;
240 static QEMUClockType event_clock_type = QEMU_CLOCK_REALTIME;
242 static void monitor_command_cb(void *opaque, const char *cmdline,
243 void *readline_opaque);
246 * Is @mon a QMP monitor?
248 static inline bool monitor_is_qmp(const Monitor *mon)
250 return (mon->flags & MONITOR_USE_CONTROL);
254 * Is the current monitor, if any, a QMP monitor?
256 bool monitor_cur_is_qmp(void)
258 return cur_mon && monitor_is_qmp(cur_mon);
261 void monitor_read_command(Monitor *mon, int show_prompt)
263 if (!mon->rs)
264 return;
266 readline_start(mon->rs, "(qemu) ", 0, monitor_command_cb, NULL);
267 if (show_prompt)
268 readline_show_prompt(mon->rs);
271 int monitor_read_password(Monitor *mon, ReadLineFunc *readline_func,
272 void *opaque)
274 if (mon->rs) {
275 readline_start(mon->rs, "Password: ", 1, readline_func, opaque);
276 /* prompt is printed on return from the command handler */
277 return 0;
278 } else {
279 monitor_printf(mon, "terminal does not support password prompting\n");
280 return -ENOTTY;
284 static void monitor_flush_locked(Monitor *mon);
286 static gboolean monitor_unblocked(GIOChannel *chan, GIOCondition cond,
287 void *opaque)
289 Monitor *mon = opaque;
291 qemu_mutex_lock(&mon->out_lock);
292 mon->out_watch = 0;
293 monitor_flush_locked(mon);
294 qemu_mutex_unlock(&mon->out_lock);
295 return FALSE;
298 /* Called with mon->out_lock held. */
299 static void monitor_flush_locked(Monitor *mon)
301 int rc;
302 size_t len;
303 const char *buf;
305 if (mon->skip_flush) {
306 return;
309 buf = qstring_get_str(mon->outbuf);
310 len = qstring_get_length(mon->outbuf);
312 if (len && !mon->mux_out) {
313 rc = qemu_chr_fe_write(&mon->chr, (const uint8_t *) buf, len);
314 if ((rc < 0 && errno != EAGAIN) || (rc == len)) {
315 /* all flushed or error */
316 QDECREF(mon->outbuf);
317 mon->outbuf = qstring_new();
318 return;
320 if (rc > 0) {
321 /* partial write */
322 QString *tmp = qstring_from_str(buf + rc);
323 QDECREF(mon->outbuf);
324 mon->outbuf = tmp;
326 if (mon->out_watch == 0) {
327 mon->out_watch =
328 qemu_chr_fe_add_watch(&mon->chr, G_IO_OUT | G_IO_HUP,
329 monitor_unblocked, mon);
334 void monitor_flush(Monitor *mon)
336 qemu_mutex_lock(&mon->out_lock);
337 monitor_flush_locked(mon);
338 qemu_mutex_unlock(&mon->out_lock);
341 /* flush at every end of line */
342 static void monitor_puts(Monitor *mon, const char *str)
344 char c;
346 qemu_mutex_lock(&mon->out_lock);
347 for(;;) {
348 c = *str++;
349 if (c == '\0')
350 break;
351 if (c == '\n') {
352 qstring_append_chr(mon->outbuf, '\r');
354 qstring_append_chr(mon->outbuf, c);
355 if (c == '\n') {
356 monitor_flush_locked(mon);
359 qemu_mutex_unlock(&mon->out_lock);
362 void monitor_vprintf(Monitor *mon, const char *fmt, va_list ap)
364 char *buf;
366 if (!mon)
367 return;
369 if (monitor_is_qmp(mon)) {
370 return;
373 buf = g_strdup_vprintf(fmt, ap);
374 monitor_puts(mon, buf);
375 g_free(buf);
378 void monitor_printf(Monitor *mon, const char *fmt, ...)
380 va_list ap;
381 va_start(ap, fmt);
382 monitor_vprintf(mon, fmt, ap);
383 va_end(ap);
386 int monitor_fprintf(FILE *stream, const char *fmt, ...)
388 va_list ap;
389 va_start(ap, fmt);
390 monitor_vprintf((Monitor *)stream, fmt, ap);
391 va_end(ap);
392 return 0;
395 static void monitor_json_emitter(Monitor *mon, const QObject *data)
397 QString *json;
399 json = mon->flags & MONITOR_USE_PRETTY ? qobject_to_json_pretty(data) :
400 qobject_to_json(data);
401 assert(json != NULL);
403 qstring_append_chr(json, '\n');
404 monitor_puts(mon, qstring_get_str(json));
406 QDECREF(json);
409 static MonitorQAPIEventConf monitor_qapi_event_conf[QAPI_EVENT__MAX] = {
410 /* Limit guest-triggerable events to 1 per second */
411 [QAPI_EVENT_RTC_CHANGE] = { 1000 * SCALE_MS },
412 [QAPI_EVENT_WATCHDOG] = { 1000 * SCALE_MS },
413 [QAPI_EVENT_BALLOON_CHANGE] = { 1000 * SCALE_MS },
414 [QAPI_EVENT_QUORUM_REPORT_BAD] = { 1000 * SCALE_MS },
415 [QAPI_EVENT_QUORUM_FAILURE] = { 1000 * SCALE_MS },
416 [QAPI_EVENT_VSERPORT_CHANGE] = { 1000 * SCALE_MS },
419 GHashTable *monitor_qapi_event_state;
422 * Emits the event to every monitor instance, @event is only used for trace
423 * Called with monitor_lock held.
425 static void monitor_qapi_event_emit(QAPIEvent event, QDict *qdict)
427 Monitor *mon;
429 trace_monitor_protocol_event_emit(event, qdict);
430 QTAILQ_FOREACH(mon, &mon_list, entry) {
431 if (monitor_is_qmp(mon)
432 && mon->qmp.commands != &qmp_cap_negotiation_commands) {
433 monitor_json_emitter(mon, QOBJECT(qdict));
438 static void monitor_qapi_event_handler(void *opaque);
441 * Queue a new event for emission to Monitor instances,
442 * applying any rate limiting if required.
444 static void
445 monitor_qapi_event_queue(QAPIEvent event, QDict *qdict, Error **errp)
447 MonitorQAPIEventConf *evconf;
448 MonitorQAPIEventState *evstate;
450 assert(event < QAPI_EVENT__MAX);
451 evconf = &monitor_qapi_event_conf[event];
452 trace_monitor_protocol_event_queue(event, qdict, evconf->rate);
454 qemu_mutex_lock(&monitor_lock);
456 if (!evconf->rate) {
457 /* Unthrottled event */
458 monitor_qapi_event_emit(event, qdict);
459 } else {
460 QDict *data = qobject_to(QDict, qdict_get(qdict, "data"));
461 MonitorQAPIEventState key = { .event = event, .data = data };
463 evstate = g_hash_table_lookup(monitor_qapi_event_state, &key);
464 assert(!evstate || timer_pending(evstate->timer));
466 if (evstate) {
468 * Timer is pending for (at least) evconf->rate ns after
469 * last send. Store event for sending when timer fires,
470 * replacing a prior stored event if any.
472 QDECREF(evstate->qdict);
473 evstate->qdict = qdict;
474 QINCREF(evstate->qdict);
475 } else {
477 * Last send was (at least) evconf->rate ns ago.
478 * Send immediately, and arm the timer to call
479 * monitor_qapi_event_handler() in evconf->rate ns. Any
480 * events arriving before then will be delayed until then.
482 int64_t now = qemu_clock_get_ns(event_clock_type);
484 monitor_qapi_event_emit(event, qdict);
486 evstate = g_new(MonitorQAPIEventState, 1);
487 evstate->event = event;
488 evstate->data = data;
489 QINCREF(evstate->data);
490 evstate->qdict = NULL;
491 evstate->timer = timer_new_ns(event_clock_type,
492 monitor_qapi_event_handler,
493 evstate);
494 g_hash_table_add(monitor_qapi_event_state, evstate);
495 timer_mod_ns(evstate->timer, now + evconf->rate);
499 qemu_mutex_unlock(&monitor_lock);
503 * This function runs evconf->rate ns after sending a throttled
504 * event.
505 * If another event has since been stored, send it.
507 static void monitor_qapi_event_handler(void *opaque)
509 MonitorQAPIEventState *evstate = opaque;
510 MonitorQAPIEventConf *evconf = &monitor_qapi_event_conf[evstate->event];
512 trace_monitor_protocol_event_handler(evstate->event, evstate->qdict);
513 qemu_mutex_lock(&monitor_lock);
515 if (evstate->qdict) {
516 int64_t now = qemu_clock_get_ns(event_clock_type);
518 monitor_qapi_event_emit(evstate->event, evstate->qdict);
519 QDECREF(evstate->qdict);
520 evstate->qdict = NULL;
521 timer_mod_ns(evstate->timer, now + evconf->rate);
522 } else {
523 g_hash_table_remove(monitor_qapi_event_state, evstate);
524 QDECREF(evstate->data);
525 timer_free(evstate->timer);
526 g_free(evstate);
529 qemu_mutex_unlock(&monitor_lock);
532 static unsigned int qapi_event_throttle_hash(const void *key)
534 const MonitorQAPIEventState *evstate = key;
535 unsigned int hash = evstate->event * 255;
537 if (evstate->event == QAPI_EVENT_VSERPORT_CHANGE) {
538 hash += g_str_hash(qdict_get_str(evstate->data, "id"));
541 if (evstate->event == QAPI_EVENT_QUORUM_REPORT_BAD) {
542 hash += g_str_hash(qdict_get_str(evstate->data, "node-name"));
545 return hash;
548 static gboolean qapi_event_throttle_equal(const void *a, const void *b)
550 const MonitorQAPIEventState *eva = a;
551 const MonitorQAPIEventState *evb = b;
553 if (eva->event != evb->event) {
554 return FALSE;
557 if (eva->event == QAPI_EVENT_VSERPORT_CHANGE) {
558 return !strcmp(qdict_get_str(eva->data, "id"),
559 qdict_get_str(evb->data, "id"));
562 if (eva->event == QAPI_EVENT_QUORUM_REPORT_BAD) {
563 return !strcmp(qdict_get_str(eva->data, "node-name"),
564 qdict_get_str(evb->data, "node-name"));
567 return TRUE;
570 static void monitor_qapi_event_init(void)
572 if (qtest_enabled()) {
573 event_clock_type = QEMU_CLOCK_VIRTUAL;
576 monitor_qapi_event_state = g_hash_table_new(qapi_event_throttle_hash,
577 qapi_event_throttle_equal);
578 qmp_event_set_func_emit(monitor_qapi_event_queue);
581 static void handle_hmp_command(Monitor *mon, const char *cmdline);
583 static void monitor_data_init(Monitor *mon, bool skip_flush,
584 bool use_io_thr)
586 memset(mon, 0, sizeof(Monitor));
587 qemu_mutex_init(&mon->out_lock);
588 mon->outbuf = qstring_new();
589 /* Use *mon_cmds by default. */
590 mon->cmd_table = mon_cmds;
591 mon->skip_flush = skip_flush;
592 mon->use_io_thr = use_io_thr;
595 static void monitor_data_destroy(Monitor *mon)
597 g_free(mon->mon_cpu_path);
598 qemu_chr_fe_deinit(&mon->chr, false);
599 if (monitor_is_qmp(mon)) {
600 json_message_parser_destroy(&mon->qmp.parser);
602 readline_free(mon->rs);
603 QDECREF(mon->outbuf);
604 qemu_mutex_destroy(&mon->out_lock);
607 char *qmp_human_monitor_command(const char *command_line, bool has_cpu_index,
608 int64_t cpu_index, Error **errp)
610 char *output = NULL;
611 Monitor *old_mon, hmp;
613 monitor_data_init(&hmp, true, false);
615 old_mon = cur_mon;
616 cur_mon = &hmp;
618 if (has_cpu_index) {
619 int ret = monitor_set_cpu(cpu_index);
620 if (ret < 0) {
621 cur_mon = old_mon;
622 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cpu-index",
623 "a CPU number");
624 goto out;
628 handle_hmp_command(&hmp, command_line);
629 cur_mon = old_mon;
631 qemu_mutex_lock(&hmp.out_lock);
632 if (qstring_get_length(hmp.outbuf) > 0) {
633 output = g_strdup(qstring_get_str(hmp.outbuf));
634 } else {
635 output = g_strdup("");
637 qemu_mutex_unlock(&hmp.out_lock);
639 out:
640 monitor_data_destroy(&hmp);
641 return output;
644 static int compare_cmd(const char *name, const char *list)
646 const char *p, *pstart;
647 int len;
648 len = strlen(name);
649 p = list;
650 for(;;) {
651 pstart = p;
652 p = strchr(p, '|');
653 if (!p)
654 p = pstart + strlen(pstart);
655 if ((p - pstart) == len && !memcmp(pstart, name, len))
656 return 1;
657 if (*p == '\0')
658 break;
659 p++;
661 return 0;
664 static int get_str(char *buf, int buf_size, const char **pp)
666 const char *p;
667 char *q;
668 int c;
670 q = buf;
671 p = *pp;
672 while (qemu_isspace(*p)) {
673 p++;
675 if (*p == '\0') {
676 fail:
677 *q = '\0';
678 *pp = p;
679 return -1;
681 if (*p == '\"') {
682 p++;
683 while (*p != '\0' && *p != '\"') {
684 if (*p == '\\') {
685 p++;
686 c = *p++;
687 switch (c) {
688 case 'n':
689 c = '\n';
690 break;
691 case 'r':
692 c = '\r';
693 break;
694 case '\\':
695 case '\'':
696 case '\"':
697 break;
698 default:
699 printf("unsupported escape code: '\\%c'\n", c);
700 goto fail;
702 if ((q - buf) < buf_size - 1) {
703 *q++ = c;
705 } else {
706 if ((q - buf) < buf_size - 1) {
707 *q++ = *p;
709 p++;
712 if (*p != '\"') {
713 printf("unterminated string\n");
714 goto fail;
716 p++;
717 } else {
718 while (*p != '\0' && !qemu_isspace(*p)) {
719 if ((q - buf) < buf_size - 1) {
720 *q++ = *p;
722 p++;
725 *q = '\0';
726 *pp = p;
727 return 0;
730 #define MAX_ARGS 16
732 static void free_cmdline_args(char **args, int nb_args)
734 int i;
736 assert(nb_args <= MAX_ARGS);
738 for (i = 0; i < nb_args; i++) {
739 g_free(args[i]);
745 * Parse the command line to get valid args.
746 * @cmdline: command line to be parsed.
747 * @pnb_args: location to store the number of args, must NOT be NULL.
748 * @args: location to store the args, which should be freed by caller, must
749 * NOT be NULL.
751 * Returns 0 on success, negative on failure.
753 * NOTE: this parser is an approximate form of the real command parser. Number
754 * of args have a limit of MAX_ARGS. If cmdline contains more, it will
755 * return with failure.
757 static int parse_cmdline(const char *cmdline,
758 int *pnb_args, char **args)
760 const char *p;
761 int nb_args, ret;
762 char buf[1024];
764 p = cmdline;
765 nb_args = 0;
766 for (;;) {
767 while (qemu_isspace(*p)) {
768 p++;
770 if (*p == '\0') {
771 break;
773 if (nb_args >= MAX_ARGS) {
774 goto fail;
776 ret = get_str(buf, sizeof(buf), &p);
777 if (ret < 0) {
778 goto fail;
780 args[nb_args] = g_strdup(buf);
781 nb_args++;
783 *pnb_args = nb_args;
784 return 0;
786 fail:
787 free_cmdline_args(args, nb_args);
788 return -1;
791 static void help_cmd_dump_one(Monitor *mon,
792 const mon_cmd_t *cmd,
793 char **prefix_args,
794 int prefix_args_nb)
796 int i;
798 for (i = 0; i < prefix_args_nb; i++) {
799 monitor_printf(mon, "%s ", prefix_args[i]);
801 monitor_printf(mon, "%s %s -- %s\n", cmd->name, cmd->params, cmd->help);
804 /* @args[@arg_index] is the valid command need to find in @cmds */
805 static void help_cmd_dump(Monitor *mon, const mon_cmd_t *cmds,
806 char **args, int nb_args, int arg_index)
808 const mon_cmd_t *cmd;
810 /* No valid arg need to compare with, dump all in *cmds */
811 if (arg_index >= nb_args) {
812 for (cmd = cmds; cmd->name != NULL; cmd++) {
813 help_cmd_dump_one(mon, cmd, args, arg_index);
815 return;
818 /* Find one entry to dump */
819 for (cmd = cmds; cmd->name != NULL; cmd++) {
820 if (compare_cmd(args[arg_index], cmd->name)) {
821 if (cmd->sub_table) {
822 /* continue with next arg */
823 help_cmd_dump(mon, cmd->sub_table,
824 args, nb_args, arg_index + 1);
825 } else {
826 help_cmd_dump_one(mon, cmd, args, arg_index);
828 break;
833 static void help_cmd(Monitor *mon, const char *name)
835 char *args[MAX_ARGS];
836 int nb_args = 0;
838 /* 1. parse user input */
839 if (name) {
840 /* special case for log, directly dump and return */
841 if (!strcmp(name, "log")) {
842 const QEMULogItem *item;
843 monitor_printf(mon, "Log items (comma separated):\n");
844 monitor_printf(mon, "%-10s %s\n", "none", "remove all logs");
845 for (item = qemu_log_items; item->mask != 0; item++) {
846 monitor_printf(mon, "%-10s %s\n", item->name, item->help);
848 return;
851 if (parse_cmdline(name, &nb_args, args) < 0) {
852 return;
856 /* 2. dump the contents according to parsed args */
857 help_cmd_dump(mon, mon->cmd_table, args, nb_args, 0);
859 free_cmdline_args(args, nb_args);
862 static void do_help_cmd(Monitor *mon, const QDict *qdict)
864 help_cmd(mon, qdict_get_try_str(qdict, "name"));
867 static void hmp_trace_event(Monitor *mon, const QDict *qdict)
869 const char *tp_name = qdict_get_str(qdict, "name");
870 bool new_state = qdict_get_bool(qdict, "option");
871 bool has_vcpu = qdict_haskey(qdict, "vcpu");
872 int vcpu = qdict_get_try_int(qdict, "vcpu", 0);
873 Error *local_err = NULL;
875 if (vcpu < 0) {
876 monitor_printf(mon, "argument vcpu must be positive");
877 return;
880 qmp_trace_event_set_state(tp_name, new_state, true, true, has_vcpu, vcpu, &local_err);
881 if (local_err) {
882 error_report_err(local_err);
886 #ifdef CONFIG_TRACE_SIMPLE
887 static void hmp_trace_file(Monitor *mon, const QDict *qdict)
889 const char *op = qdict_get_try_str(qdict, "op");
890 const char *arg = qdict_get_try_str(qdict, "arg");
892 if (!op) {
893 st_print_trace_file_status((FILE *)mon, &monitor_fprintf);
894 } else if (!strcmp(op, "on")) {
895 st_set_trace_file_enabled(true);
896 } else if (!strcmp(op, "off")) {
897 st_set_trace_file_enabled(false);
898 } else if (!strcmp(op, "flush")) {
899 st_flush_trace_buffer();
900 } else if (!strcmp(op, "set")) {
901 if (arg) {
902 st_set_trace_file(arg);
904 } else {
905 monitor_printf(mon, "unexpected argument \"%s\"\n", op);
906 help_cmd(mon, "trace-file");
909 #endif
911 static void hmp_info_help(Monitor *mon, const QDict *qdict)
913 help_cmd(mon, "info");
916 static void query_commands_cb(QmpCommand *cmd, void *opaque)
918 CommandInfoList *info, **list = opaque;
920 if (!cmd->enabled) {
921 return;
924 info = g_malloc0(sizeof(*info));
925 info->value = g_malloc0(sizeof(*info->value));
926 info->value->name = g_strdup(cmd->name);
927 info->next = *list;
928 *list = info;
931 CommandInfoList *qmp_query_commands(Error **errp)
933 CommandInfoList *list = NULL;
935 qmp_for_each_command(cur_mon->qmp.commands, query_commands_cb, &list);
937 return list;
940 EventInfoList *qmp_query_events(Error **errp)
942 EventInfoList *info, *ev_list = NULL;
943 QAPIEvent e;
945 for (e = 0 ; e < QAPI_EVENT__MAX ; e++) {
946 const char *event_name = QAPIEvent_str(e);
947 assert(event_name != NULL);
948 info = g_malloc0(sizeof(*info));
949 info->value = g_malloc0(sizeof(*info->value));
950 info->value->name = g_strdup(event_name);
952 info->next = ev_list;
953 ev_list = info;
956 return ev_list;
960 * Minor hack: generated marshalling suppressed for this command
961 * ('gen': false in the schema) so we can parse the JSON string
962 * directly into QObject instead of first parsing it with
963 * visit_type_SchemaInfoList() into a SchemaInfoList, then marshal it
964 * to QObject with generated output marshallers, every time. Instead,
965 * we do it in test-qobject-input-visitor.c, just to make sure
966 * qapi-gen.py's output actually conforms to the schema.
968 static void qmp_query_qmp_schema(QDict *qdict, QObject **ret_data,
969 Error **errp)
971 *ret_data = qobject_from_qlit(&qmp_schema_qlit);
975 * We used to define commands in qmp-commands.hx in addition to the
976 * QAPI schema. This permitted defining some of them only in certain
977 * configurations. query-commands has always reflected that (good,
978 * because it lets QMP clients figure out what's actually available),
979 * while query-qmp-schema never did (not so good). This function is a
980 * hack to keep the configuration-specific commands defined exactly as
981 * before, even though qmp-commands.hx is gone.
983 * FIXME Educate the QAPI schema on configuration-specific commands,
984 * and drop this hack.
986 static void qmp_unregister_commands_hack(void)
988 #ifndef CONFIG_SPICE
989 qmp_unregister_command(&qmp_commands, "query-spice");
990 #endif
991 #ifndef CONFIG_REPLICATION
992 qmp_unregister_command(&qmp_commands, "xen-set-replication");
993 qmp_unregister_command(&qmp_commands, "query-xen-replication-status");
994 qmp_unregister_command(&qmp_commands, "xen-colo-do-checkpoint");
995 #endif
996 #ifndef TARGET_I386
997 qmp_unregister_command(&qmp_commands, "rtc-reset-reinjection");
998 qmp_unregister_command(&qmp_commands, "query-sev");
999 qmp_unregister_command(&qmp_commands, "query-sev-launch-measure");
1000 qmp_unregister_command(&qmp_commands, "query-sev-capabilities");
1001 #endif
1002 #ifndef TARGET_S390X
1003 qmp_unregister_command(&qmp_commands, "dump-skeys");
1004 #endif
1005 #ifndef TARGET_ARM
1006 qmp_unregister_command(&qmp_commands, "query-gic-capabilities");
1007 #endif
1008 #if !defined(TARGET_S390X) && !defined(TARGET_I386)
1009 qmp_unregister_command(&qmp_commands, "query-cpu-model-expansion");
1010 #endif
1011 #if !defined(TARGET_S390X)
1012 qmp_unregister_command(&qmp_commands, "query-cpu-model-baseline");
1013 qmp_unregister_command(&qmp_commands, "query-cpu-model-comparison");
1014 #endif
1015 #if !defined(TARGET_PPC) && !defined(TARGET_ARM) && !defined(TARGET_I386) \
1016 && !defined(TARGET_S390X)
1017 qmp_unregister_command(&qmp_commands, "query-cpu-definitions");
1018 #endif
1021 static void monitor_init_qmp_commands(void)
1024 * Two command lists:
1025 * - qmp_commands contains all QMP commands
1026 * - qmp_cap_negotiation_commands contains just
1027 * "qmp_capabilities", to enforce capability negotiation
1030 qmp_init_marshal(&qmp_commands);
1032 qmp_register_command(&qmp_commands, "query-qmp-schema",
1033 qmp_query_qmp_schema,
1034 QCO_NO_OPTIONS);
1035 qmp_register_command(&qmp_commands, "device_add", qmp_device_add,
1036 QCO_NO_OPTIONS);
1037 qmp_register_command(&qmp_commands, "netdev_add", qmp_netdev_add,
1038 QCO_NO_OPTIONS);
1040 qmp_unregister_commands_hack();
1042 QTAILQ_INIT(&qmp_cap_negotiation_commands);
1043 qmp_register_command(&qmp_cap_negotiation_commands, "qmp_capabilities",
1044 qmp_marshal_qmp_capabilities, QCO_NO_OPTIONS);
1047 static void qmp_caps_check(Monitor *mon, QMPCapabilityList *list,
1048 Error **errp)
1050 for (; list; list = list->next) {
1051 assert(list->value < QMP_CAPABILITY__MAX);
1052 switch (list->value) {
1053 case QMP_CAPABILITY_OOB:
1054 if (!mon->use_io_thr) {
1056 * Out-Of-Band only works with monitors that are
1057 * running on dedicated IOThread.
1059 error_setg(errp, "This monitor does not support "
1060 "Out-Of-Band (OOB)");
1061 return;
1063 break;
1064 default:
1065 break;
1070 /* This function should only be called after capabilities are checked. */
1071 static void qmp_caps_apply(Monitor *mon, QMPCapabilityList *list)
1073 for (; list; list = list->next) {
1074 mon->qmp.qmp_caps[list->value] = true;
1078 void qmp_qmp_capabilities(bool has_enable, QMPCapabilityList *enable,
1079 Error **errp)
1081 Error *local_err = NULL;
1083 if (cur_mon->qmp.commands == &qmp_commands) {
1084 error_set(errp, ERROR_CLASS_COMMAND_NOT_FOUND,
1085 "Capabilities negotiation is already complete, command "
1086 "ignored");
1087 return;
1090 /* Enable QMP capabilities provided by the client if applicable. */
1091 if (has_enable) {
1092 qmp_caps_check(cur_mon, enable, &local_err);
1093 if (local_err) {
1095 * Failed check on any of the capabilities will fail the
1096 * entire command (and thus not apply any of the other
1097 * capabilities that were also requested).
1099 error_propagate(errp, local_err);
1100 return;
1102 qmp_caps_apply(cur_mon, enable);
1105 cur_mon->qmp.commands = &qmp_commands;
1108 /* set the current CPU defined by the user */
1109 int monitor_set_cpu(int cpu_index)
1111 CPUState *cpu;
1113 cpu = qemu_get_cpu(cpu_index);
1114 if (cpu == NULL) {
1115 return -1;
1117 g_free(cur_mon->mon_cpu_path);
1118 cur_mon->mon_cpu_path = object_get_canonical_path(OBJECT(cpu));
1119 return 0;
1122 static CPUState *mon_get_cpu_sync(bool synchronize)
1124 CPUState *cpu;
1126 if (cur_mon->mon_cpu_path) {
1127 cpu = (CPUState *) object_resolve_path_type(cur_mon->mon_cpu_path,
1128 TYPE_CPU, NULL);
1129 if (!cpu) {
1130 g_free(cur_mon->mon_cpu_path);
1131 cur_mon->mon_cpu_path = NULL;
1134 if (!cur_mon->mon_cpu_path) {
1135 if (!first_cpu) {
1136 return NULL;
1138 monitor_set_cpu(first_cpu->cpu_index);
1139 cpu = first_cpu;
1141 if (synchronize) {
1142 cpu_synchronize_state(cpu);
1144 return cpu;
1147 CPUState *mon_get_cpu(void)
1149 return mon_get_cpu_sync(true);
1152 CPUArchState *mon_get_cpu_env(void)
1154 CPUState *cs = mon_get_cpu();
1156 return cs ? cs->env_ptr : NULL;
1159 int monitor_get_cpu_index(void)
1161 CPUState *cs = mon_get_cpu_sync(false);
1163 return cs ? cs->cpu_index : UNASSIGNED_CPU_INDEX;
1166 static void hmp_info_registers(Monitor *mon, const QDict *qdict)
1168 bool all_cpus = qdict_get_try_bool(qdict, "cpustate_all", false);
1169 CPUState *cs;
1171 if (all_cpus) {
1172 CPU_FOREACH(cs) {
1173 monitor_printf(mon, "\nCPU#%d\n", cs->cpu_index);
1174 cpu_dump_state(cs, (FILE *)mon, monitor_fprintf, CPU_DUMP_FPU);
1176 } else {
1177 cs = mon_get_cpu();
1179 if (!cs) {
1180 monitor_printf(mon, "No CPU available\n");
1181 return;
1184 cpu_dump_state(cs, (FILE *)mon, monitor_fprintf, CPU_DUMP_FPU);
1188 #ifdef CONFIG_TCG
1189 static void hmp_info_jit(Monitor *mon, const QDict *qdict)
1191 if (!tcg_enabled()) {
1192 error_report("JIT information is only available with accel=tcg");
1193 return;
1196 dump_exec_info((FILE *)mon, monitor_fprintf);
1197 dump_drift_info((FILE *)mon, monitor_fprintf);
1200 static void hmp_info_opcount(Monitor *mon, const QDict *qdict)
1202 dump_opcount_info((FILE *)mon, monitor_fprintf);
1204 #endif
1206 static void hmp_info_history(Monitor *mon, const QDict *qdict)
1208 int i;
1209 const char *str;
1211 if (!mon->rs)
1212 return;
1213 i = 0;
1214 for(;;) {
1215 str = readline_get_history(mon->rs, i);
1216 if (!str)
1217 break;
1218 monitor_printf(mon, "%d: '%s'\n", i, str);
1219 i++;
1223 static void hmp_info_cpustats(Monitor *mon, const QDict *qdict)
1225 CPUState *cs = mon_get_cpu();
1227 if (!cs) {
1228 monitor_printf(mon, "No CPU available\n");
1229 return;
1231 cpu_dump_statistics(cs, (FILE *)mon, &monitor_fprintf, 0);
1234 static void hmp_info_trace_events(Monitor *mon, const QDict *qdict)
1236 const char *name = qdict_get_try_str(qdict, "name");
1237 bool has_vcpu = qdict_haskey(qdict, "vcpu");
1238 int vcpu = qdict_get_try_int(qdict, "vcpu", 0);
1239 TraceEventInfoList *events;
1240 TraceEventInfoList *elem;
1241 Error *local_err = NULL;
1243 if (name == NULL) {
1244 name = "*";
1246 if (vcpu < 0) {
1247 monitor_printf(mon, "argument vcpu must be positive");
1248 return;
1251 events = qmp_trace_event_get_state(name, has_vcpu, vcpu, &local_err);
1252 if (local_err) {
1253 error_report_err(local_err);
1254 return;
1257 for (elem = events; elem != NULL; elem = elem->next) {
1258 monitor_printf(mon, "%s : state %u\n",
1259 elem->value->name,
1260 elem->value->state == TRACE_EVENT_STATE_ENABLED ? 1 : 0);
1262 qapi_free_TraceEventInfoList(events);
1265 void qmp_client_migrate_info(const char *protocol, const char *hostname,
1266 bool has_port, int64_t port,
1267 bool has_tls_port, int64_t tls_port,
1268 bool has_cert_subject, const char *cert_subject,
1269 Error **errp)
1271 if (strcmp(protocol, "spice") == 0) {
1272 if (!qemu_using_spice(errp)) {
1273 return;
1276 if (!has_port && !has_tls_port) {
1277 error_setg(errp, QERR_MISSING_PARAMETER, "port/tls-port");
1278 return;
1281 if (qemu_spice_migrate_info(hostname,
1282 has_port ? port : -1,
1283 has_tls_port ? tls_port : -1,
1284 cert_subject)) {
1285 error_setg(errp, QERR_UNDEFINED_ERROR);
1286 return;
1288 return;
1291 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "protocol", "spice");
1294 static void hmp_logfile(Monitor *mon, const QDict *qdict)
1296 Error *err = NULL;
1298 qemu_set_log_filename(qdict_get_str(qdict, "filename"), &err);
1299 if (err) {
1300 error_report_err(err);
1304 static void hmp_log(Monitor *mon, const QDict *qdict)
1306 int mask;
1307 const char *items = qdict_get_str(qdict, "items");
1309 if (!strcmp(items, "none")) {
1310 mask = 0;
1311 } else {
1312 mask = qemu_str_to_log_mask(items);
1313 if (!mask) {
1314 help_cmd(mon, "log");
1315 return;
1318 qemu_set_log(mask);
1321 static void hmp_singlestep(Monitor *mon, const QDict *qdict)
1323 const char *option = qdict_get_try_str(qdict, "option");
1324 if (!option || !strcmp(option, "on")) {
1325 singlestep = 1;
1326 } else if (!strcmp(option, "off")) {
1327 singlestep = 0;
1328 } else {
1329 monitor_printf(mon, "unexpected option %s\n", option);
1333 static void hmp_gdbserver(Monitor *mon, const QDict *qdict)
1335 const char *device = qdict_get_try_str(qdict, "device");
1336 if (!device)
1337 device = "tcp::" DEFAULT_GDBSTUB_PORT;
1338 if (gdbserver_start(device) < 0) {
1339 monitor_printf(mon, "Could not open gdbserver on device '%s'\n",
1340 device);
1341 } else if (strcmp(device, "none") == 0) {
1342 monitor_printf(mon, "Disabled gdbserver\n");
1343 } else {
1344 monitor_printf(mon, "Waiting for gdb connection on device '%s'\n",
1345 device);
1349 static void hmp_watchdog_action(Monitor *mon, const QDict *qdict)
1351 const char *action = qdict_get_str(qdict, "action");
1352 if (select_watchdog_action(action) == -1) {
1353 monitor_printf(mon, "Unknown watchdog action '%s'\n", action);
1357 static void monitor_printc(Monitor *mon, int c)
1359 monitor_printf(mon, "'");
1360 switch(c) {
1361 case '\'':
1362 monitor_printf(mon, "\\'");
1363 break;
1364 case '\\':
1365 monitor_printf(mon, "\\\\");
1366 break;
1367 case '\n':
1368 monitor_printf(mon, "\\n");
1369 break;
1370 case '\r':
1371 monitor_printf(mon, "\\r");
1372 break;
1373 default:
1374 if (c >= 32 && c <= 126) {
1375 monitor_printf(mon, "%c", c);
1376 } else {
1377 monitor_printf(mon, "\\x%02x", c);
1379 break;
1381 monitor_printf(mon, "'");
1384 static void memory_dump(Monitor *mon, int count, int format, int wsize,
1385 hwaddr addr, int is_physical)
1387 int l, line_size, i, max_digits, len;
1388 uint8_t buf[16];
1389 uint64_t v;
1390 CPUState *cs = mon_get_cpu();
1392 if (!cs && (format == 'i' || !is_physical)) {
1393 monitor_printf(mon, "Can not dump without CPU\n");
1394 return;
1397 if (format == 'i') {
1398 monitor_disas(mon, cs, addr, count, is_physical);
1399 return;
1402 len = wsize * count;
1403 if (wsize == 1)
1404 line_size = 8;
1405 else
1406 line_size = 16;
1407 max_digits = 0;
1409 switch(format) {
1410 case 'o':
1411 max_digits = DIV_ROUND_UP(wsize * 8, 3);
1412 break;
1413 default:
1414 case 'x':
1415 max_digits = (wsize * 8) / 4;
1416 break;
1417 case 'u':
1418 case 'd':
1419 max_digits = DIV_ROUND_UP(wsize * 8 * 10, 33);
1420 break;
1421 case 'c':
1422 wsize = 1;
1423 break;
1426 while (len > 0) {
1427 if (is_physical)
1428 monitor_printf(mon, TARGET_FMT_plx ":", addr);
1429 else
1430 monitor_printf(mon, TARGET_FMT_lx ":", (target_ulong)addr);
1431 l = len;
1432 if (l > line_size)
1433 l = line_size;
1434 if (is_physical) {
1435 cpu_physical_memory_read(addr, buf, l);
1436 } else {
1437 if (cpu_memory_rw_debug(cs, addr, buf, l, 0) < 0) {
1438 monitor_printf(mon, " Cannot access memory\n");
1439 break;
1442 i = 0;
1443 while (i < l) {
1444 switch(wsize) {
1445 default:
1446 case 1:
1447 v = ldub_p(buf + i);
1448 break;
1449 case 2:
1450 v = lduw_p(buf + i);
1451 break;
1452 case 4:
1453 v = (uint32_t)ldl_p(buf + i);
1454 break;
1455 case 8:
1456 v = ldq_p(buf + i);
1457 break;
1459 monitor_printf(mon, " ");
1460 switch(format) {
1461 case 'o':
1462 monitor_printf(mon, "%#*" PRIo64, max_digits, v);
1463 break;
1464 case 'x':
1465 monitor_printf(mon, "0x%0*" PRIx64, max_digits, v);
1466 break;
1467 case 'u':
1468 monitor_printf(mon, "%*" PRIu64, max_digits, v);
1469 break;
1470 case 'd':
1471 monitor_printf(mon, "%*" PRId64, max_digits, v);
1472 break;
1473 case 'c':
1474 monitor_printc(mon, v);
1475 break;
1477 i += wsize;
1479 monitor_printf(mon, "\n");
1480 addr += l;
1481 len -= l;
1485 static void hmp_memory_dump(Monitor *mon, const QDict *qdict)
1487 int count = qdict_get_int(qdict, "count");
1488 int format = qdict_get_int(qdict, "format");
1489 int size = qdict_get_int(qdict, "size");
1490 target_long addr = qdict_get_int(qdict, "addr");
1492 memory_dump(mon, count, format, size, addr, 0);
1495 static void hmp_physical_memory_dump(Monitor *mon, const QDict *qdict)
1497 int count = qdict_get_int(qdict, "count");
1498 int format = qdict_get_int(qdict, "format");
1499 int size = qdict_get_int(qdict, "size");
1500 hwaddr addr = qdict_get_int(qdict, "addr");
1502 memory_dump(mon, count, format, size, addr, 1);
1505 static void *gpa2hva(MemoryRegion **p_mr, hwaddr addr, Error **errp)
1507 MemoryRegionSection mrs = memory_region_find(get_system_memory(),
1508 addr, 1);
1510 if (!mrs.mr) {
1511 error_setg(errp, "No memory is mapped at address 0x%" HWADDR_PRIx, addr);
1512 return NULL;
1515 if (!memory_region_is_ram(mrs.mr) && !memory_region_is_romd(mrs.mr)) {
1516 error_setg(errp, "Memory at address 0x%" HWADDR_PRIx "is not RAM", addr);
1517 memory_region_unref(mrs.mr);
1518 return NULL;
1521 *p_mr = mrs.mr;
1522 return qemu_map_ram_ptr(mrs.mr->ram_block, mrs.offset_within_region);
1525 static void hmp_gpa2hva(Monitor *mon, const QDict *qdict)
1527 hwaddr addr = qdict_get_int(qdict, "addr");
1528 Error *local_err = NULL;
1529 MemoryRegion *mr = NULL;
1530 void *ptr;
1532 ptr = gpa2hva(&mr, addr, &local_err);
1533 if (local_err) {
1534 error_report_err(local_err);
1535 return;
1538 monitor_printf(mon, "Host virtual address for 0x%" HWADDR_PRIx
1539 " (%s) is %p\n",
1540 addr, mr->name, ptr);
1542 memory_region_unref(mr);
1545 #ifdef CONFIG_LINUX
1546 static uint64_t vtop(void *ptr, Error **errp)
1548 uint64_t pinfo;
1549 uint64_t ret = -1;
1550 uintptr_t addr = (uintptr_t) ptr;
1551 uintptr_t pagesize = getpagesize();
1552 off_t offset = addr / pagesize * sizeof(pinfo);
1553 int fd;
1555 fd = open("/proc/self/pagemap", O_RDONLY);
1556 if (fd == -1) {
1557 error_setg_errno(errp, errno, "Cannot open /proc/self/pagemap");
1558 return -1;
1561 /* Force copy-on-write if necessary. */
1562 atomic_add((uint8_t *)ptr, 0);
1564 if (pread(fd, &pinfo, sizeof(pinfo), offset) != sizeof(pinfo)) {
1565 error_setg_errno(errp, errno, "Cannot read pagemap");
1566 goto out;
1568 if ((pinfo & (1ull << 63)) == 0) {
1569 error_setg(errp, "Page not present");
1570 goto out;
1572 ret = ((pinfo & 0x007fffffffffffffull) * pagesize) | (addr & (pagesize - 1));
1574 out:
1575 close(fd);
1576 return ret;
1579 static void hmp_gpa2hpa(Monitor *mon, const QDict *qdict)
1581 hwaddr addr = qdict_get_int(qdict, "addr");
1582 Error *local_err = NULL;
1583 MemoryRegion *mr = NULL;
1584 void *ptr;
1585 uint64_t physaddr;
1587 ptr = gpa2hva(&mr, addr, &local_err);
1588 if (local_err) {
1589 error_report_err(local_err);
1590 return;
1593 physaddr = vtop(ptr, &local_err);
1594 if (local_err) {
1595 error_report_err(local_err);
1596 } else {
1597 monitor_printf(mon, "Host physical address for 0x%" HWADDR_PRIx
1598 " (%s) is 0x%" PRIx64 "\n",
1599 addr, mr->name, (uint64_t) physaddr);
1602 memory_region_unref(mr);
1604 #endif
1606 static void do_print(Monitor *mon, const QDict *qdict)
1608 int format = qdict_get_int(qdict, "format");
1609 hwaddr val = qdict_get_int(qdict, "val");
1611 switch(format) {
1612 case 'o':
1613 monitor_printf(mon, "%#" HWADDR_PRIo, val);
1614 break;
1615 case 'x':
1616 monitor_printf(mon, "%#" HWADDR_PRIx, val);
1617 break;
1618 case 'u':
1619 monitor_printf(mon, "%" HWADDR_PRIu, val);
1620 break;
1621 default:
1622 case 'd':
1623 monitor_printf(mon, "%" HWADDR_PRId, val);
1624 break;
1625 case 'c':
1626 monitor_printc(mon, val);
1627 break;
1629 monitor_printf(mon, "\n");
1632 static void hmp_sum(Monitor *mon, const QDict *qdict)
1634 uint32_t addr;
1635 uint16_t sum;
1636 uint32_t start = qdict_get_int(qdict, "start");
1637 uint32_t size = qdict_get_int(qdict, "size");
1639 sum = 0;
1640 for(addr = start; addr < (start + size); addr++) {
1641 uint8_t val = address_space_ldub(&address_space_memory, addr,
1642 MEMTXATTRS_UNSPECIFIED, NULL);
1643 /* BSD sum algorithm ('sum' Unix command) */
1644 sum = (sum >> 1) | (sum << 15);
1645 sum += val;
1647 monitor_printf(mon, "%05d\n", sum);
1650 static int mouse_button_state;
1652 static void hmp_mouse_move(Monitor *mon, const QDict *qdict)
1654 int dx, dy, dz, button;
1655 const char *dx_str = qdict_get_str(qdict, "dx_str");
1656 const char *dy_str = qdict_get_str(qdict, "dy_str");
1657 const char *dz_str = qdict_get_try_str(qdict, "dz_str");
1659 dx = strtol(dx_str, NULL, 0);
1660 dy = strtol(dy_str, NULL, 0);
1661 qemu_input_queue_rel(NULL, INPUT_AXIS_X, dx);
1662 qemu_input_queue_rel(NULL, INPUT_AXIS_Y, dy);
1664 if (dz_str) {
1665 dz = strtol(dz_str, NULL, 0);
1666 if (dz != 0) {
1667 button = (dz > 0) ? INPUT_BUTTON_WHEEL_UP : INPUT_BUTTON_WHEEL_DOWN;
1668 qemu_input_queue_btn(NULL, button, true);
1669 qemu_input_event_sync();
1670 qemu_input_queue_btn(NULL, button, false);
1673 qemu_input_event_sync();
1676 static void hmp_mouse_button(Monitor *mon, const QDict *qdict)
1678 static uint32_t bmap[INPUT_BUTTON__MAX] = {
1679 [INPUT_BUTTON_LEFT] = MOUSE_EVENT_LBUTTON,
1680 [INPUT_BUTTON_MIDDLE] = MOUSE_EVENT_MBUTTON,
1681 [INPUT_BUTTON_RIGHT] = MOUSE_EVENT_RBUTTON,
1683 int button_state = qdict_get_int(qdict, "button_state");
1685 if (mouse_button_state == button_state) {
1686 return;
1688 qemu_input_update_buttons(NULL, bmap, mouse_button_state, button_state);
1689 qemu_input_event_sync();
1690 mouse_button_state = button_state;
1693 static void hmp_ioport_read(Monitor *mon, const QDict *qdict)
1695 int size = qdict_get_int(qdict, "size");
1696 int addr = qdict_get_int(qdict, "addr");
1697 int has_index = qdict_haskey(qdict, "index");
1698 uint32_t val;
1699 int suffix;
1701 if (has_index) {
1702 int index = qdict_get_int(qdict, "index");
1703 cpu_outb(addr & IOPORTS_MASK, index & 0xff);
1704 addr++;
1706 addr &= 0xffff;
1708 switch(size) {
1709 default:
1710 case 1:
1711 val = cpu_inb(addr);
1712 suffix = 'b';
1713 break;
1714 case 2:
1715 val = cpu_inw(addr);
1716 suffix = 'w';
1717 break;
1718 case 4:
1719 val = cpu_inl(addr);
1720 suffix = 'l';
1721 break;
1723 monitor_printf(mon, "port%c[0x%04x] = %#0*x\n",
1724 suffix, addr, size * 2, val);
1727 static void hmp_ioport_write(Monitor *mon, const QDict *qdict)
1729 int size = qdict_get_int(qdict, "size");
1730 int addr = qdict_get_int(qdict, "addr");
1731 int val = qdict_get_int(qdict, "val");
1733 addr &= IOPORTS_MASK;
1735 switch (size) {
1736 default:
1737 case 1:
1738 cpu_outb(addr, val);
1739 break;
1740 case 2:
1741 cpu_outw(addr, val);
1742 break;
1743 case 4:
1744 cpu_outl(addr, val);
1745 break;
1749 static void hmp_boot_set(Monitor *mon, const QDict *qdict)
1751 Error *local_err = NULL;
1752 const char *bootdevice = qdict_get_str(qdict, "bootdevice");
1754 qemu_boot_set(bootdevice, &local_err);
1755 if (local_err) {
1756 error_report_err(local_err);
1757 } else {
1758 monitor_printf(mon, "boot device list now set to %s\n", bootdevice);
1762 static void hmp_info_mtree(Monitor *mon, const QDict *qdict)
1764 bool flatview = qdict_get_try_bool(qdict, "flatview", false);
1765 bool dispatch_tree = qdict_get_try_bool(qdict, "dispatch_tree", false);
1767 mtree_info((fprintf_function)monitor_printf, mon, flatview, dispatch_tree);
1770 static void hmp_info_numa(Monitor *mon, const QDict *qdict)
1772 int i;
1773 NumaNodeMem *node_mem;
1774 CpuInfoList *cpu_list, *cpu;
1776 cpu_list = qmp_query_cpus(&error_abort);
1777 node_mem = g_new0(NumaNodeMem, nb_numa_nodes);
1779 query_numa_node_mem(node_mem);
1780 monitor_printf(mon, "%d nodes\n", nb_numa_nodes);
1781 for (i = 0; i < nb_numa_nodes; i++) {
1782 monitor_printf(mon, "node %d cpus:", i);
1783 for (cpu = cpu_list; cpu; cpu = cpu->next) {
1784 if (cpu->value->has_props && cpu->value->props->has_node_id &&
1785 cpu->value->props->node_id == i) {
1786 monitor_printf(mon, " %" PRIi64, cpu->value->CPU);
1789 monitor_printf(mon, "\n");
1790 monitor_printf(mon, "node %d size: %" PRId64 " MB\n", i,
1791 node_mem[i].node_mem >> 20);
1792 monitor_printf(mon, "node %d plugged: %" PRId64 " MB\n", i,
1793 node_mem[i].node_plugged_mem >> 20);
1795 qapi_free_CpuInfoList(cpu_list);
1796 g_free(node_mem);
1799 #ifdef CONFIG_PROFILER
1801 int64_t tcg_time;
1802 int64_t dev_time;
1804 static void hmp_info_profile(Monitor *mon, const QDict *qdict)
1806 monitor_printf(mon, "async time %" PRId64 " (%0.3f)\n",
1807 dev_time, dev_time / (double)NANOSECONDS_PER_SECOND);
1808 monitor_printf(mon, "qemu time %" PRId64 " (%0.3f)\n",
1809 tcg_time, tcg_time / (double)NANOSECONDS_PER_SECOND);
1810 tcg_time = 0;
1811 dev_time = 0;
1813 #else
1814 static void hmp_info_profile(Monitor *mon, const QDict *qdict)
1816 monitor_printf(mon, "Internal profiler not compiled\n");
1818 #endif
1820 /* Capture support */
1821 static QLIST_HEAD (capture_list_head, CaptureState) capture_head;
1823 static void hmp_info_capture(Monitor *mon, const QDict *qdict)
1825 int i;
1826 CaptureState *s;
1828 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
1829 monitor_printf(mon, "[%d]: ", i);
1830 s->ops.info (s->opaque);
1834 static void hmp_stopcapture(Monitor *mon, const QDict *qdict)
1836 int i;
1837 int n = qdict_get_int(qdict, "n");
1838 CaptureState *s;
1840 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
1841 if (i == n) {
1842 s->ops.destroy (s->opaque);
1843 QLIST_REMOVE (s, entries);
1844 g_free (s);
1845 return;
1850 static void hmp_wavcapture(Monitor *mon, const QDict *qdict)
1852 const char *path = qdict_get_str(qdict, "path");
1853 int has_freq = qdict_haskey(qdict, "freq");
1854 int freq = qdict_get_try_int(qdict, "freq", -1);
1855 int has_bits = qdict_haskey(qdict, "bits");
1856 int bits = qdict_get_try_int(qdict, "bits", -1);
1857 int has_channels = qdict_haskey(qdict, "nchannels");
1858 int nchannels = qdict_get_try_int(qdict, "nchannels", -1);
1859 CaptureState *s;
1861 s = g_malloc0 (sizeof (*s));
1863 freq = has_freq ? freq : 44100;
1864 bits = has_bits ? bits : 16;
1865 nchannels = has_channels ? nchannels : 2;
1867 if (wav_start_capture (s, path, freq, bits, nchannels)) {
1868 monitor_printf(mon, "Failed to add wave capture\n");
1869 g_free (s);
1870 return;
1872 QLIST_INSERT_HEAD (&capture_head, s, entries);
1875 static qemu_acl *find_acl(Monitor *mon, const char *name)
1877 qemu_acl *acl = qemu_acl_find(name);
1879 if (!acl) {
1880 monitor_printf(mon, "acl: unknown list '%s'\n", name);
1882 return acl;
1885 static void hmp_acl_show(Monitor *mon, const QDict *qdict)
1887 const char *aclname = qdict_get_str(qdict, "aclname");
1888 qemu_acl *acl = find_acl(mon, aclname);
1889 qemu_acl_entry *entry;
1890 int i = 0;
1892 if (acl) {
1893 monitor_printf(mon, "policy: %s\n",
1894 acl->defaultDeny ? "deny" : "allow");
1895 QTAILQ_FOREACH(entry, &acl->entries, next) {
1896 i++;
1897 monitor_printf(mon, "%d: %s %s\n", i,
1898 entry->deny ? "deny" : "allow", entry->match);
1903 static void hmp_acl_reset(Monitor *mon, const QDict *qdict)
1905 const char *aclname = qdict_get_str(qdict, "aclname");
1906 qemu_acl *acl = find_acl(mon, aclname);
1908 if (acl) {
1909 qemu_acl_reset(acl);
1910 monitor_printf(mon, "acl: removed all rules\n");
1914 static void hmp_acl_policy(Monitor *mon, const QDict *qdict)
1916 const char *aclname = qdict_get_str(qdict, "aclname");
1917 const char *policy = qdict_get_str(qdict, "policy");
1918 qemu_acl *acl = find_acl(mon, aclname);
1920 if (acl) {
1921 if (strcmp(policy, "allow") == 0) {
1922 acl->defaultDeny = 0;
1923 monitor_printf(mon, "acl: policy set to 'allow'\n");
1924 } else if (strcmp(policy, "deny") == 0) {
1925 acl->defaultDeny = 1;
1926 monitor_printf(mon, "acl: policy set to 'deny'\n");
1927 } else {
1928 monitor_printf(mon, "acl: unknown policy '%s', "
1929 "expected 'deny' or 'allow'\n", policy);
1934 static void hmp_acl_add(Monitor *mon, const QDict *qdict)
1936 const char *aclname = qdict_get_str(qdict, "aclname");
1937 const char *match = qdict_get_str(qdict, "match");
1938 const char *policy = qdict_get_str(qdict, "policy");
1939 int has_index = qdict_haskey(qdict, "index");
1940 int index = qdict_get_try_int(qdict, "index", -1);
1941 qemu_acl *acl = find_acl(mon, aclname);
1942 int deny, ret;
1944 if (acl) {
1945 if (strcmp(policy, "allow") == 0) {
1946 deny = 0;
1947 } else if (strcmp(policy, "deny") == 0) {
1948 deny = 1;
1949 } else {
1950 monitor_printf(mon, "acl: unknown policy '%s', "
1951 "expected 'deny' or 'allow'\n", policy);
1952 return;
1954 if (has_index)
1955 ret = qemu_acl_insert(acl, deny, match, index);
1956 else
1957 ret = qemu_acl_append(acl, deny, match);
1958 if (ret < 0)
1959 monitor_printf(mon, "acl: unable to add acl entry\n");
1960 else
1961 monitor_printf(mon, "acl: added rule at position %d\n", ret);
1965 static void hmp_acl_remove(Monitor *mon, const QDict *qdict)
1967 const char *aclname = qdict_get_str(qdict, "aclname");
1968 const char *match = qdict_get_str(qdict, "match");
1969 qemu_acl *acl = find_acl(mon, aclname);
1970 int ret;
1972 if (acl) {
1973 ret = qemu_acl_remove(acl, match);
1974 if (ret < 0)
1975 monitor_printf(mon, "acl: no matching acl entry\n");
1976 else
1977 monitor_printf(mon, "acl: removed rule at position %d\n", ret);
1981 void qmp_getfd(const char *fdname, Error **errp)
1983 mon_fd_t *monfd;
1984 int fd;
1986 fd = qemu_chr_fe_get_msgfd(&cur_mon->chr);
1987 if (fd == -1) {
1988 error_setg(errp, QERR_FD_NOT_SUPPLIED);
1989 return;
1992 if (qemu_isdigit(fdname[0])) {
1993 close(fd);
1994 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "fdname",
1995 "a name not starting with a digit");
1996 return;
1999 QLIST_FOREACH(monfd, &cur_mon->fds, next) {
2000 if (strcmp(monfd->name, fdname) != 0) {
2001 continue;
2004 close(monfd->fd);
2005 monfd->fd = fd;
2006 return;
2009 monfd = g_malloc0(sizeof(mon_fd_t));
2010 monfd->name = g_strdup(fdname);
2011 monfd->fd = fd;
2013 QLIST_INSERT_HEAD(&cur_mon->fds, monfd, next);
2016 void qmp_closefd(const char *fdname, Error **errp)
2018 mon_fd_t *monfd;
2020 QLIST_FOREACH(monfd, &cur_mon->fds, next) {
2021 if (strcmp(monfd->name, fdname) != 0) {
2022 continue;
2025 QLIST_REMOVE(monfd, next);
2026 close(monfd->fd);
2027 g_free(monfd->name);
2028 g_free(monfd);
2029 return;
2032 error_setg(errp, QERR_FD_NOT_FOUND, fdname);
2035 int monitor_get_fd(Monitor *mon, const char *fdname, Error **errp)
2037 mon_fd_t *monfd;
2039 QLIST_FOREACH(monfd, &mon->fds, next) {
2040 int fd;
2042 if (strcmp(monfd->name, fdname) != 0) {
2043 continue;
2046 fd = monfd->fd;
2048 /* caller takes ownership of fd */
2049 QLIST_REMOVE(monfd, next);
2050 g_free(monfd->name);
2051 g_free(monfd);
2053 return fd;
2056 error_setg(errp, "File descriptor named '%s' has not been found", fdname);
2057 return -1;
2060 static void monitor_fdset_cleanup(MonFdset *mon_fdset)
2062 MonFdsetFd *mon_fdset_fd;
2063 MonFdsetFd *mon_fdset_fd_next;
2065 QLIST_FOREACH_SAFE(mon_fdset_fd, &mon_fdset->fds, next, mon_fdset_fd_next) {
2066 if ((mon_fdset_fd->removed ||
2067 (QLIST_EMPTY(&mon_fdset->dup_fds) && mon_refcount == 0)) &&
2068 runstate_is_running()) {
2069 close(mon_fdset_fd->fd);
2070 g_free(mon_fdset_fd->opaque);
2071 QLIST_REMOVE(mon_fdset_fd, next);
2072 g_free(mon_fdset_fd);
2076 if (QLIST_EMPTY(&mon_fdset->fds) && QLIST_EMPTY(&mon_fdset->dup_fds)) {
2077 QLIST_REMOVE(mon_fdset, next);
2078 g_free(mon_fdset);
2082 static void monitor_fdsets_cleanup(void)
2084 MonFdset *mon_fdset;
2085 MonFdset *mon_fdset_next;
2087 QLIST_FOREACH_SAFE(mon_fdset, &mon_fdsets, next, mon_fdset_next) {
2088 monitor_fdset_cleanup(mon_fdset);
2092 AddfdInfo *qmp_add_fd(bool has_fdset_id, int64_t fdset_id, bool has_opaque,
2093 const char *opaque, Error **errp)
2095 int fd;
2096 Monitor *mon = cur_mon;
2097 AddfdInfo *fdinfo;
2099 fd = qemu_chr_fe_get_msgfd(&mon->chr);
2100 if (fd == -1) {
2101 error_setg(errp, QERR_FD_NOT_SUPPLIED);
2102 goto error;
2105 fdinfo = monitor_fdset_add_fd(fd, has_fdset_id, fdset_id,
2106 has_opaque, opaque, errp);
2107 if (fdinfo) {
2108 return fdinfo;
2111 error:
2112 if (fd != -1) {
2113 close(fd);
2115 return NULL;
2118 void qmp_remove_fd(int64_t fdset_id, bool has_fd, int64_t fd, Error **errp)
2120 MonFdset *mon_fdset;
2121 MonFdsetFd *mon_fdset_fd;
2122 char fd_str[60];
2124 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2125 if (mon_fdset->id != fdset_id) {
2126 continue;
2128 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2129 if (has_fd) {
2130 if (mon_fdset_fd->fd != fd) {
2131 continue;
2133 mon_fdset_fd->removed = true;
2134 break;
2135 } else {
2136 mon_fdset_fd->removed = true;
2139 if (has_fd && !mon_fdset_fd) {
2140 goto error;
2142 monitor_fdset_cleanup(mon_fdset);
2143 return;
2146 error:
2147 if (has_fd) {
2148 snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64 ", fd:%" PRId64,
2149 fdset_id, fd);
2150 } else {
2151 snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64, fdset_id);
2153 error_setg(errp, QERR_FD_NOT_FOUND, fd_str);
2156 FdsetInfoList *qmp_query_fdsets(Error **errp)
2158 MonFdset *mon_fdset;
2159 MonFdsetFd *mon_fdset_fd;
2160 FdsetInfoList *fdset_list = NULL;
2162 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2163 FdsetInfoList *fdset_info = g_malloc0(sizeof(*fdset_info));
2164 FdsetFdInfoList *fdsetfd_list = NULL;
2166 fdset_info->value = g_malloc0(sizeof(*fdset_info->value));
2167 fdset_info->value->fdset_id = mon_fdset->id;
2169 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2170 FdsetFdInfoList *fdsetfd_info;
2172 fdsetfd_info = g_malloc0(sizeof(*fdsetfd_info));
2173 fdsetfd_info->value = g_malloc0(sizeof(*fdsetfd_info->value));
2174 fdsetfd_info->value->fd = mon_fdset_fd->fd;
2175 if (mon_fdset_fd->opaque) {
2176 fdsetfd_info->value->has_opaque = true;
2177 fdsetfd_info->value->opaque = g_strdup(mon_fdset_fd->opaque);
2178 } else {
2179 fdsetfd_info->value->has_opaque = false;
2182 fdsetfd_info->next = fdsetfd_list;
2183 fdsetfd_list = fdsetfd_info;
2186 fdset_info->value->fds = fdsetfd_list;
2188 fdset_info->next = fdset_list;
2189 fdset_list = fdset_info;
2192 return fdset_list;
2195 AddfdInfo *monitor_fdset_add_fd(int fd, bool has_fdset_id, int64_t fdset_id,
2196 bool has_opaque, const char *opaque,
2197 Error **errp)
2199 MonFdset *mon_fdset = NULL;
2200 MonFdsetFd *mon_fdset_fd;
2201 AddfdInfo *fdinfo;
2203 if (has_fdset_id) {
2204 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2205 /* Break if match found or match impossible due to ordering by ID */
2206 if (fdset_id <= mon_fdset->id) {
2207 if (fdset_id < mon_fdset->id) {
2208 mon_fdset = NULL;
2210 break;
2215 if (mon_fdset == NULL) {
2216 int64_t fdset_id_prev = -1;
2217 MonFdset *mon_fdset_cur = QLIST_FIRST(&mon_fdsets);
2219 if (has_fdset_id) {
2220 if (fdset_id < 0) {
2221 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "fdset-id",
2222 "a non-negative value");
2223 return NULL;
2225 /* Use specified fdset ID */
2226 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2227 mon_fdset_cur = mon_fdset;
2228 if (fdset_id < mon_fdset_cur->id) {
2229 break;
2232 } else {
2233 /* Use first available fdset ID */
2234 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2235 mon_fdset_cur = mon_fdset;
2236 if (fdset_id_prev == mon_fdset_cur->id - 1) {
2237 fdset_id_prev = mon_fdset_cur->id;
2238 continue;
2240 break;
2244 mon_fdset = g_malloc0(sizeof(*mon_fdset));
2245 if (has_fdset_id) {
2246 mon_fdset->id = fdset_id;
2247 } else {
2248 mon_fdset->id = fdset_id_prev + 1;
2251 /* The fdset list is ordered by fdset ID */
2252 if (!mon_fdset_cur) {
2253 QLIST_INSERT_HEAD(&mon_fdsets, mon_fdset, next);
2254 } else if (mon_fdset->id < mon_fdset_cur->id) {
2255 QLIST_INSERT_BEFORE(mon_fdset_cur, mon_fdset, next);
2256 } else {
2257 QLIST_INSERT_AFTER(mon_fdset_cur, mon_fdset, next);
2261 mon_fdset_fd = g_malloc0(sizeof(*mon_fdset_fd));
2262 mon_fdset_fd->fd = fd;
2263 mon_fdset_fd->removed = false;
2264 if (has_opaque) {
2265 mon_fdset_fd->opaque = g_strdup(opaque);
2267 QLIST_INSERT_HEAD(&mon_fdset->fds, mon_fdset_fd, next);
2269 fdinfo = g_malloc0(sizeof(*fdinfo));
2270 fdinfo->fdset_id = mon_fdset->id;
2271 fdinfo->fd = mon_fdset_fd->fd;
2273 return fdinfo;
2276 int monitor_fdset_get_fd(int64_t fdset_id, int flags)
2278 #ifndef _WIN32
2279 MonFdset *mon_fdset;
2280 MonFdsetFd *mon_fdset_fd;
2281 int mon_fd_flags;
2283 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2284 if (mon_fdset->id != fdset_id) {
2285 continue;
2287 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2288 mon_fd_flags = fcntl(mon_fdset_fd->fd, F_GETFL);
2289 if (mon_fd_flags == -1) {
2290 return -1;
2293 if ((flags & O_ACCMODE) == (mon_fd_flags & O_ACCMODE)) {
2294 return mon_fdset_fd->fd;
2297 errno = EACCES;
2298 return -1;
2300 #endif
2302 errno = ENOENT;
2303 return -1;
2306 int monitor_fdset_dup_fd_add(int64_t fdset_id, int dup_fd)
2308 MonFdset *mon_fdset;
2309 MonFdsetFd *mon_fdset_fd_dup;
2311 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2312 if (mon_fdset->id != fdset_id) {
2313 continue;
2315 QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
2316 if (mon_fdset_fd_dup->fd == dup_fd) {
2317 return -1;
2320 mon_fdset_fd_dup = g_malloc0(sizeof(*mon_fdset_fd_dup));
2321 mon_fdset_fd_dup->fd = dup_fd;
2322 QLIST_INSERT_HEAD(&mon_fdset->dup_fds, mon_fdset_fd_dup, next);
2323 return 0;
2325 return -1;
2328 static int monitor_fdset_dup_fd_find_remove(int dup_fd, bool remove)
2330 MonFdset *mon_fdset;
2331 MonFdsetFd *mon_fdset_fd_dup;
2333 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2334 QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
2335 if (mon_fdset_fd_dup->fd == dup_fd) {
2336 if (remove) {
2337 QLIST_REMOVE(mon_fdset_fd_dup, next);
2338 if (QLIST_EMPTY(&mon_fdset->dup_fds)) {
2339 monitor_fdset_cleanup(mon_fdset);
2341 return -1;
2342 } else {
2343 return mon_fdset->id;
2348 return -1;
2351 int monitor_fdset_dup_fd_find(int dup_fd)
2353 return monitor_fdset_dup_fd_find_remove(dup_fd, false);
2356 void monitor_fdset_dup_fd_remove(int dup_fd)
2358 monitor_fdset_dup_fd_find_remove(dup_fd, true);
2361 int monitor_fd_param(Monitor *mon, const char *fdname, Error **errp)
2363 int fd;
2364 Error *local_err = NULL;
2366 if (!qemu_isdigit(fdname[0]) && mon) {
2367 fd = monitor_get_fd(mon, fdname, &local_err);
2368 } else {
2369 fd = qemu_parse_fd(fdname);
2370 if (fd == -1) {
2371 error_setg(&local_err, "Invalid file descriptor number '%s'",
2372 fdname);
2375 if (local_err) {
2376 error_propagate(errp, local_err);
2377 assert(fd == -1);
2378 } else {
2379 assert(fd != -1);
2382 return fd;
2385 /* Please update hmp-commands.hx when adding or changing commands */
2386 static mon_cmd_t info_cmds[] = {
2387 #include "hmp-commands-info.h"
2388 { NULL, NULL, },
2391 /* mon_cmds and info_cmds would be sorted at runtime */
2392 static mon_cmd_t mon_cmds[] = {
2393 #include "hmp-commands.h"
2394 { NULL, NULL, },
2397 /*******************************************************************/
2399 static const char *pch;
2400 static sigjmp_buf expr_env;
2403 static void GCC_FMT_ATTR(2, 3) QEMU_NORETURN
2404 expr_error(Monitor *mon, const char *fmt, ...)
2406 va_list ap;
2407 va_start(ap, fmt);
2408 monitor_vprintf(mon, fmt, ap);
2409 monitor_printf(mon, "\n");
2410 va_end(ap);
2411 siglongjmp(expr_env, 1);
2414 /* return 0 if OK, -1 if not found */
2415 static int get_monitor_def(target_long *pval, const char *name)
2417 const MonitorDef *md = target_monitor_defs();
2418 CPUState *cs = mon_get_cpu();
2419 void *ptr;
2420 uint64_t tmp = 0;
2421 int ret;
2423 if (cs == NULL || md == NULL) {
2424 return -1;
2427 for(; md->name != NULL; md++) {
2428 if (compare_cmd(name, md->name)) {
2429 if (md->get_value) {
2430 *pval = md->get_value(md, md->offset);
2431 } else {
2432 CPUArchState *env = mon_get_cpu_env();
2433 ptr = (uint8_t *)env + md->offset;
2434 switch(md->type) {
2435 case MD_I32:
2436 *pval = *(int32_t *)ptr;
2437 break;
2438 case MD_TLONG:
2439 *pval = *(target_long *)ptr;
2440 break;
2441 default:
2442 *pval = 0;
2443 break;
2446 return 0;
2450 ret = target_get_monitor_def(cs, name, &tmp);
2451 if (!ret) {
2452 *pval = (target_long) tmp;
2455 return ret;
2458 static void next(void)
2460 if (*pch != '\0') {
2461 pch++;
2462 while (qemu_isspace(*pch))
2463 pch++;
2467 static int64_t expr_sum(Monitor *mon);
2469 static int64_t expr_unary(Monitor *mon)
2471 int64_t n;
2472 char *p;
2473 int ret;
2475 switch(*pch) {
2476 case '+':
2477 next();
2478 n = expr_unary(mon);
2479 break;
2480 case '-':
2481 next();
2482 n = -expr_unary(mon);
2483 break;
2484 case '~':
2485 next();
2486 n = ~expr_unary(mon);
2487 break;
2488 case '(':
2489 next();
2490 n = expr_sum(mon);
2491 if (*pch != ')') {
2492 expr_error(mon, "')' expected");
2494 next();
2495 break;
2496 case '\'':
2497 pch++;
2498 if (*pch == '\0')
2499 expr_error(mon, "character constant expected");
2500 n = *pch;
2501 pch++;
2502 if (*pch != '\'')
2503 expr_error(mon, "missing terminating \' character");
2504 next();
2505 break;
2506 case '$':
2508 char buf[128], *q;
2509 target_long reg=0;
2511 pch++;
2512 q = buf;
2513 while ((*pch >= 'a' && *pch <= 'z') ||
2514 (*pch >= 'A' && *pch <= 'Z') ||
2515 (*pch >= '0' && *pch <= '9') ||
2516 *pch == '_' || *pch == '.') {
2517 if ((q - buf) < sizeof(buf) - 1)
2518 *q++ = *pch;
2519 pch++;
2521 while (qemu_isspace(*pch))
2522 pch++;
2523 *q = 0;
2524 ret = get_monitor_def(&reg, buf);
2525 if (ret < 0)
2526 expr_error(mon, "unknown register");
2527 n = reg;
2529 break;
2530 case '\0':
2531 expr_error(mon, "unexpected end of expression");
2532 n = 0;
2533 break;
2534 default:
2535 errno = 0;
2536 n = strtoull(pch, &p, 0);
2537 if (errno == ERANGE) {
2538 expr_error(mon, "number too large");
2540 if (pch == p) {
2541 expr_error(mon, "invalid char '%c' in expression", *p);
2543 pch = p;
2544 while (qemu_isspace(*pch))
2545 pch++;
2546 break;
2548 return n;
2552 static int64_t expr_prod(Monitor *mon)
2554 int64_t val, val2;
2555 int op;
2557 val = expr_unary(mon);
2558 for(;;) {
2559 op = *pch;
2560 if (op != '*' && op != '/' && op != '%')
2561 break;
2562 next();
2563 val2 = expr_unary(mon);
2564 switch(op) {
2565 default:
2566 case '*':
2567 val *= val2;
2568 break;
2569 case '/':
2570 case '%':
2571 if (val2 == 0)
2572 expr_error(mon, "division by zero");
2573 if (op == '/')
2574 val /= val2;
2575 else
2576 val %= val2;
2577 break;
2580 return val;
2583 static int64_t expr_logic(Monitor *mon)
2585 int64_t val, val2;
2586 int op;
2588 val = expr_prod(mon);
2589 for(;;) {
2590 op = *pch;
2591 if (op != '&' && op != '|' && op != '^')
2592 break;
2593 next();
2594 val2 = expr_prod(mon);
2595 switch(op) {
2596 default:
2597 case '&':
2598 val &= val2;
2599 break;
2600 case '|':
2601 val |= val2;
2602 break;
2603 case '^':
2604 val ^= val2;
2605 break;
2608 return val;
2611 static int64_t expr_sum(Monitor *mon)
2613 int64_t val, val2;
2614 int op;
2616 val = expr_logic(mon);
2617 for(;;) {
2618 op = *pch;
2619 if (op != '+' && op != '-')
2620 break;
2621 next();
2622 val2 = expr_logic(mon);
2623 if (op == '+')
2624 val += val2;
2625 else
2626 val -= val2;
2628 return val;
2631 static int get_expr(Monitor *mon, int64_t *pval, const char **pp)
2633 pch = *pp;
2634 if (sigsetjmp(expr_env, 0)) {
2635 *pp = pch;
2636 return -1;
2638 while (qemu_isspace(*pch))
2639 pch++;
2640 *pval = expr_sum(mon);
2641 *pp = pch;
2642 return 0;
2645 static int get_double(Monitor *mon, double *pval, const char **pp)
2647 const char *p = *pp;
2648 char *tailp;
2649 double d;
2651 d = strtod(p, &tailp);
2652 if (tailp == p) {
2653 monitor_printf(mon, "Number expected\n");
2654 return -1;
2656 if (d != d || d - d != 0) {
2657 /* NaN or infinity */
2658 monitor_printf(mon, "Bad number\n");
2659 return -1;
2661 *pval = d;
2662 *pp = tailp;
2663 return 0;
2667 * Store the command-name in cmdname, and return a pointer to
2668 * the remaining of the command string.
2670 static const char *get_command_name(const char *cmdline,
2671 char *cmdname, size_t nlen)
2673 size_t len;
2674 const char *p, *pstart;
2676 p = cmdline;
2677 while (qemu_isspace(*p))
2678 p++;
2679 if (*p == '\0')
2680 return NULL;
2681 pstart = p;
2682 while (*p != '\0' && *p != '/' && !qemu_isspace(*p))
2683 p++;
2684 len = p - pstart;
2685 if (len > nlen - 1)
2686 len = nlen - 1;
2687 memcpy(cmdname, pstart, len);
2688 cmdname[len] = '\0';
2689 return p;
2693 * Read key of 'type' into 'key' and return the current
2694 * 'type' pointer.
2696 static char *key_get_info(const char *type, char **key)
2698 size_t len;
2699 char *p, *str;
2701 if (*type == ',')
2702 type++;
2704 p = strchr(type, ':');
2705 if (!p) {
2706 *key = NULL;
2707 return NULL;
2709 len = p - type;
2711 str = g_malloc(len + 1);
2712 memcpy(str, type, len);
2713 str[len] = '\0';
2715 *key = str;
2716 return ++p;
2719 static int default_fmt_format = 'x';
2720 static int default_fmt_size = 4;
2722 static int is_valid_option(const char *c, const char *typestr)
2724 char option[3];
2726 option[0] = '-';
2727 option[1] = *c;
2728 option[2] = '\0';
2730 typestr = strstr(typestr, option);
2731 return (typestr != NULL);
2734 static const mon_cmd_t *search_dispatch_table(const mon_cmd_t *disp_table,
2735 const char *cmdname)
2737 const mon_cmd_t *cmd;
2739 for (cmd = disp_table; cmd->name != NULL; cmd++) {
2740 if (compare_cmd(cmdname, cmd->name)) {
2741 return cmd;
2745 return NULL;
2749 * Parse command name from @cmdp according to command table @table.
2750 * If blank, return NULL.
2751 * Else, if no valid command can be found, report to @mon, and return
2752 * NULL.
2753 * Else, change @cmdp to point right behind the name, and return its
2754 * command table entry.
2755 * Do not assume the return value points into @table! It doesn't when
2756 * the command is found in a sub-command table.
2758 static const mon_cmd_t *monitor_parse_command(Monitor *mon,
2759 const char *cmdp_start,
2760 const char **cmdp,
2761 mon_cmd_t *table)
2763 const char *p;
2764 const mon_cmd_t *cmd;
2765 char cmdname[256];
2767 /* extract the command name */
2768 p = get_command_name(*cmdp, cmdname, sizeof(cmdname));
2769 if (!p)
2770 return NULL;
2772 cmd = search_dispatch_table(table, cmdname);
2773 if (!cmd) {
2774 monitor_printf(mon, "unknown command: '%.*s'\n",
2775 (int)(p - cmdp_start), cmdp_start);
2776 return NULL;
2779 /* filter out following useless space */
2780 while (qemu_isspace(*p)) {
2781 p++;
2784 *cmdp = p;
2785 /* search sub command */
2786 if (cmd->sub_table != NULL && *p != '\0') {
2787 return monitor_parse_command(mon, cmdp_start, cmdp, cmd->sub_table);
2790 return cmd;
2794 * Parse arguments for @cmd.
2795 * If it can't be parsed, report to @mon, and return NULL.
2796 * Else, insert command arguments into a QDict, and return it.
2797 * Note: On success, caller has to free the QDict structure.
2800 static QDict *monitor_parse_arguments(Monitor *mon,
2801 const char **endp,
2802 const mon_cmd_t *cmd)
2804 const char *typestr;
2805 char *key;
2806 int c;
2807 const char *p = *endp;
2808 char buf[1024];
2809 QDict *qdict = qdict_new();
2811 /* parse the parameters */
2812 typestr = cmd->args_type;
2813 for(;;) {
2814 typestr = key_get_info(typestr, &key);
2815 if (!typestr)
2816 break;
2817 c = *typestr;
2818 typestr++;
2819 switch(c) {
2820 case 'F':
2821 case 'B':
2822 case 's':
2824 int ret;
2826 while (qemu_isspace(*p))
2827 p++;
2828 if (*typestr == '?') {
2829 typestr++;
2830 if (*p == '\0') {
2831 /* no optional string: NULL argument */
2832 break;
2835 ret = get_str(buf, sizeof(buf), &p);
2836 if (ret < 0) {
2837 switch(c) {
2838 case 'F':
2839 monitor_printf(mon, "%s: filename expected\n",
2840 cmd->name);
2841 break;
2842 case 'B':
2843 monitor_printf(mon, "%s: block device name expected\n",
2844 cmd->name);
2845 break;
2846 default:
2847 monitor_printf(mon, "%s: string expected\n", cmd->name);
2848 break;
2850 goto fail;
2852 qdict_put_str(qdict, key, buf);
2854 break;
2855 case 'O':
2857 QemuOptsList *opts_list;
2858 QemuOpts *opts;
2860 opts_list = qemu_find_opts(key);
2861 if (!opts_list || opts_list->desc->name) {
2862 goto bad_type;
2864 while (qemu_isspace(*p)) {
2865 p++;
2867 if (!*p)
2868 break;
2869 if (get_str(buf, sizeof(buf), &p) < 0) {
2870 goto fail;
2872 opts = qemu_opts_parse_noisily(opts_list, buf, true);
2873 if (!opts) {
2874 goto fail;
2876 qemu_opts_to_qdict(opts, qdict);
2877 qemu_opts_del(opts);
2879 break;
2880 case '/':
2882 int count, format, size;
2884 while (qemu_isspace(*p))
2885 p++;
2886 if (*p == '/') {
2887 /* format found */
2888 p++;
2889 count = 1;
2890 if (qemu_isdigit(*p)) {
2891 count = 0;
2892 while (qemu_isdigit(*p)) {
2893 count = count * 10 + (*p - '0');
2894 p++;
2897 size = -1;
2898 format = -1;
2899 for(;;) {
2900 switch(*p) {
2901 case 'o':
2902 case 'd':
2903 case 'u':
2904 case 'x':
2905 case 'i':
2906 case 'c':
2907 format = *p++;
2908 break;
2909 case 'b':
2910 size = 1;
2911 p++;
2912 break;
2913 case 'h':
2914 size = 2;
2915 p++;
2916 break;
2917 case 'w':
2918 size = 4;
2919 p++;
2920 break;
2921 case 'g':
2922 case 'L':
2923 size = 8;
2924 p++;
2925 break;
2926 default:
2927 goto next;
2930 next:
2931 if (*p != '\0' && !qemu_isspace(*p)) {
2932 monitor_printf(mon, "invalid char in format: '%c'\n",
2933 *p);
2934 goto fail;
2936 if (format < 0)
2937 format = default_fmt_format;
2938 if (format != 'i') {
2939 /* for 'i', not specifying a size gives -1 as size */
2940 if (size < 0)
2941 size = default_fmt_size;
2942 default_fmt_size = size;
2944 default_fmt_format = format;
2945 } else {
2946 count = 1;
2947 format = default_fmt_format;
2948 if (format != 'i') {
2949 size = default_fmt_size;
2950 } else {
2951 size = -1;
2954 qdict_put_int(qdict, "count", count);
2955 qdict_put_int(qdict, "format", format);
2956 qdict_put_int(qdict, "size", size);
2958 break;
2959 case 'i':
2960 case 'l':
2961 case 'M':
2963 int64_t val;
2965 while (qemu_isspace(*p))
2966 p++;
2967 if (*typestr == '?' || *typestr == '.') {
2968 if (*typestr == '?') {
2969 if (*p == '\0') {
2970 typestr++;
2971 break;
2973 } else {
2974 if (*p == '.') {
2975 p++;
2976 while (qemu_isspace(*p))
2977 p++;
2978 } else {
2979 typestr++;
2980 break;
2983 typestr++;
2985 if (get_expr(mon, &val, &p))
2986 goto fail;
2987 /* Check if 'i' is greater than 32-bit */
2988 if ((c == 'i') && ((val >> 32) & 0xffffffff)) {
2989 monitor_printf(mon, "\'%s\' has failed: ", cmd->name);
2990 monitor_printf(mon, "integer is for 32-bit values\n");
2991 goto fail;
2992 } else if (c == 'M') {
2993 if (val < 0) {
2994 monitor_printf(mon, "enter a positive value\n");
2995 goto fail;
2997 val <<= 20;
2999 qdict_put_int(qdict, key, val);
3001 break;
3002 case 'o':
3004 int ret;
3005 uint64_t val;
3006 char *end;
3008 while (qemu_isspace(*p)) {
3009 p++;
3011 if (*typestr == '?') {
3012 typestr++;
3013 if (*p == '\0') {
3014 break;
3017 ret = qemu_strtosz_MiB(p, &end, &val);
3018 if (ret < 0 || val > INT64_MAX) {
3019 monitor_printf(mon, "invalid size\n");
3020 goto fail;
3022 qdict_put_int(qdict, key, val);
3023 p = end;
3025 break;
3026 case 'T':
3028 double val;
3030 while (qemu_isspace(*p))
3031 p++;
3032 if (*typestr == '?') {
3033 typestr++;
3034 if (*p == '\0') {
3035 break;
3038 if (get_double(mon, &val, &p) < 0) {
3039 goto fail;
3041 if (p[0] && p[1] == 's') {
3042 switch (*p) {
3043 case 'm':
3044 val /= 1e3; p += 2; break;
3045 case 'u':
3046 val /= 1e6; p += 2; break;
3047 case 'n':
3048 val /= 1e9; p += 2; break;
3051 if (*p && !qemu_isspace(*p)) {
3052 monitor_printf(mon, "Unknown unit suffix\n");
3053 goto fail;
3055 qdict_put(qdict, key, qnum_from_double(val));
3057 break;
3058 case 'b':
3060 const char *beg;
3061 bool val;
3063 while (qemu_isspace(*p)) {
3064 p++;
3066 beg = p;
3067 while (qemu_isgraph(*p)) {
3068 p++;
3070 if (p - beg == 2 && !memcmp(beg, "on", p - beg)) {
3071 val = true;
3072 } else if (p - beg == 3 && !memcmp(beg, "off", p - beg)) {
3073 val = false;
3074 } else {
3075 monitor_printf(mon, "Expected 'on' or 'off'\n");
3076 goto fail;
3078 qdict_put_bool(qdict, key, val);
3080 break;
3081 case '-':
3083 const char *tmp = p;
3084 int skip_key = 0;
3085 /* option */
3087 c = *typestr++;
3088 if (c == '\0')
3089 goto bad_type;
3090 while (qemu_isspace(*p))
3091 p++;
3092 if (*p == '-') {
3093 p++;
3094 if(c != *p) {
3095 if(!is_valid_option(p, typestr)) {
3097 monitor_printf(mon, "%s: unsupported option -%c\n",
3098 cmd->name, *p);
3099 goto fail;
3100 } else {
3101 skip_key = 1;
3104 if(skip_key) {
3105 p = tmp;
3106 } else {
3107 /* has option */
3108 p++;
3109 qdict_put_bool(qdict, key, true);
3113 break;
3114 case 'S':
3116 /* package all remaining string */
3117 int len;
3119 while (qemu_isspace(*p)) {
3120 p++;
3122 if (*typestr == '?') {
3123 typestr++;
3124 if (*p == '\0') {
3125 /* no remaining string: NULL argument */
3126 break;
3129 len = strlen(p);
3130 if (len <= 0) {
3131 monitor_printf(mon, "%s: string expected\n",
3132 cmd->name);
3133 goto fail;
3135 qdict_put_str(qdict, key, p);
3136 p += len;
3138 break;
3139 default:
3140 bad_type:
3141 monitor_printf(mon, "%s: unknown type '%c'\n", cmd->name, c);
3142 goto fail;
3144 g_free(key);
3145 key = NULL;
3147 /* check that all arguments were parsed */
3148 while (qemu_isspace(*p))
3149 p++;
3150 if (*p != '\0') {
3151 monitor_printf(mon, "%s: extraneous characters at the end of line\n",
3152 cmd->name);
3153 goto fail;
3156 return qdict;
3158 fail:
3159 QDECREF(qdict);
3160 g_free(key);
3161 return NULL;
3164 static void handle_hmp_command(Monitor *mon, const char *cmdline)
3166 QDict *qdict;
3167 const mon_cmd_t *cmd;
3169 trace_handle_hmp_command(mon, cmdline);
3171 cmd = monitor_parse_command(mon, cmdline, &cmdline, mon->cmd_table);
3172 if (!cmd) {
3173 return;
3176 qdict = monitor_parse_arguments(mon, &cmdline, cmd);
3177 if (!qdict) {
3178 monitor_printf(mon, "Try \"help %s\" for more information\n",
3179 cmd->name);
3180 return;
3183 cmd->cmd(mon, qdict);
3184 QDECREF(qdict);
3187 static void cmd_completion(Monitor *mon, const char *name, const char *list)
3189 const char *p, *pstart;
3190 char cmd[128];
3191 int len;
3193 p = list;
3194 for(;;) {
3195 pstart = p;
3196 p = strchr(p, '|');
3197 if (!p)
3198 p = pstart + strlen(pstart);
3199 len = p - pstart;
3200 if (len > sizeof(cmd) - 2)
3201 len = sizeof(cmd) - 2;
3202 memcpy(cmd, pstart, len);
3203 cmd[len] = '\0';
3204 if (name[0] == '\0' || !strncmp(name, cmd, strlen(name))) {
3205 readline_add_completion(mon->rs, cmd);
3207 if (*p == '\0')
3208 break;
3209 p++;
3213 static void file_completion(Monitor *mon, const char *input)
3215 DIR *ffs;
3216 struct dirent *d;
3217 char path[1024];
3218 char file[1024], file_prefix[1024];
3219 int input_path_len;
3220 const char *p;
3222 p = strrchr(input, '/');
3223 if (!p) {
3224 input_path_len = 0;
3225 pstrcpy(file_prefix, sizeof(file_prefix), input);
3226 pstrcpy(path, sizeof(path), ".");
3227 } else {
3228 input_path_len = p - input + 1;
3229 memcpy(path, input, input_path_len);
3230 if (input_path_len > sizeof(path) - 1)
3231 input_path_len = sizeof(path) - 1;
3232 path[input_path_len] = '\0';
3233 pstrcpy(file_prefix, sizeof(file_prefix), p + 1);
3236 ffs = opendir(path);
3237 if (!ffs)
3238 return;
3239 for(;;) {
3240 struct stat sb;
3241 d = readdir(ffs);
3242 if (!d)
3243 break;
3245 if (strcmp(d->d_name, ".") == 0 || strcmp(d->d_name, "..") == 0) {
3246 continue;
3249 if (strstart(d->d_name, file_prefix, NULL)) {
3250 memcpy(file, input, input_path_len);
3251 if (input_path_len < sizeof(file))
3252 pstrcpy(file + input_path_len, sizeof(file) - input_path_len,
3253 d->d_name);
3254 /* stat the file to find out if it's a directory.
3255 * In that case add a slash to speed up typing long paths
3257 if (stat(file, &sb) == 0 && S_ISDIR(sb.st_mode)) {
3258 pstrcat(file, sizeof(file), "/");
3260 readline_add_completion(mon->rs, file);
3263 closedir(ffs);
3266 static const char *next_arg_type(const char *typestr)
3268 const char *p = strchr(typestr, ':');
3269 return (p != NULL ? ++p : typestr);
3272 static void add_completion_option(ReadLineState *rs, const char *str,
3273 const char *option)
3275 if (!str || !option) {
3276 return;
3278 if (!strncmp(option, str, strlen(str))) {
3279 readline_add_completion(rs, option);
3283 void chardev_add_completion(ReadLineState *rs, int nb_args, const char *str)
3285 size_t len;
3286 ChardevBackendInfoList *list, *start;
3288 if (nb_args != 2) {
3289 return;
3291 len = strlen(str);
3292 readline_set_completion_index(rs, len);
3294 start = list = qmp_query_chardev_backends(NULL);
3295 while (list) {
3296 const char *chr_name = list->value->name;
3298 if (!strncmp(chr_name, str, len)) {
3299 readline_add_completion(rs, chr_name);
3301 list = list->next;
3303 qapi_free_ChardevBackendInfoList(start);
3306 void netdev_add_completion(ReadLineState *rs, int nb_args, const char *str)
3308 size_t len;
3309 int i;
3311 if (nb_args != 2) {
3312 return;
3314 len = strlen(str);
3315 readline_set_completion_index(rs, len);
3316 for (i = 0; i < NET_CLIENT_DRIVER__MAX; i++) {
3317 add_completion_option(rs, str, NetClientDriver_str(i));
3321 void device_add_completion(ReadLineState *rs, int nb_args, const char *str)
3323 GSList *list, *elt;
3324 size_t len;
3326 if (nb_args != 2) {
3327 return;
3330 len = strlen(str);
3331 readline_set_completion_index(rs, len);
3332 list = elt = object_class_get_list(TYPE_DEVICE, false);
3333 while (elt) {
3334 const char *name;
3335 DeviceClass *dc = OBJECT_CLASS_CHECK(DeviceClass, elt->data,
3336 TYPE_DEVICE);
3337 name = object_class_get_name(OBJECT_CLASS(dc));
3339 if (dc->user_creatable
3340 && !strncmp(name, str, len)) {
3341 readline_add_completion(rs, name);
3343 elt = elt->next;
3345 g_slist_free(list);
3348 void object_add_completion(ReadLineState *rs, int nb_args, const char *str)
3350 GSList *list, *elt;
3351 size_t len;
3353 if (nb_args != 2) {
3354 return;
3357 len = strlen(str);
3358 readline_set_completion_index(rs, len);
3359 list = elt = object_class_get_list(TYPE_USER_CREATABLE, false);
3360 while (elt) {
3361 const char *name;
3363 name = object_class_get_name(OBJECT_CLASS(elt->data));
3364 if (!strncmp(name, str, len) && strcmp(name, TYPE_USER_CREATABLE)) {
3365 readline_add_completion(rs, name);
3367 elt = elt->next;
3369 g_slist_free(list);
3372 static void peripheral_device_del_completion(ReadLineState *rs,
3373 const char *str, size_t len)
3375 Object *peripheral = container_get(qdev_get_machine(), "/peripheral");
3376 GSList *list, *item;
3378 list = qdev_build_hotpluggable_device_list(peripheral);
3379 if (!list) {
3380 return;
3383 for (item = list; item; item = g_slist_next(item)) {
3384 DeviceState *dev = item->data;
3386 if (dev->id && !strncmp(str, dev->id, len)) {
3387 readline_add_completion(rs, dev->id);
3391 g_slist_free(list);
3394 void chardev_remove_completion(ReadLineState *rs, int nb_args, const char *str)
3396 size_t len;
3397 ChardevInfoList *list, *start;
3399 if (nb_args != 2) {
3400 return;
3402 len = strlen(str);
3403 readline_set_completion_index(rs, len);
3405 start = list = qmp_query_chardev(NULL);
3406 while (list) {
3407 ChardevInfo *chr = list->value;
3409 if (!strncmp(chr->label, str, len)) {
3410 readline_add_completion(rs, chr->label);
3412 list = list->next;
3414 qapi_free_ChardevInfoList(start);
3417 static void ringbuf_completion(ReadLineState *rs, const char *str)
3419 size_t len;
3420 ChardevInfoList *list, *start;
3422 len = strlen(str);
3423 readline_set_completion_index(rs, len);
3425 start = list = qmp_query_chardev(NULL);
3426 while (list) {
3427 ChardevInfo *chr_info = list->value;
3429 if (!strncmp(chr_info->label, str, len)) {
3430 Chardev *chr = qemu_chr_find(chr_info->label);
3431 if (chr && CHARDEV_IS_RINGBUF(chr)) {
3432 readline_add_completion(rs, chr_info->label);
3435 list = list->next;
3437 qapi_free_ChardevInfoList(start);
3440 void ringbuf_write_completion(ReadLineState *rs, int nb_args, const char *str)
3442 if (nb_args != 2) {
3443 return;
3445 ringbuf_completion(rs, str);
3448 void device_del_completion(ReadLineState *rs, int nb_args, const char *str)
3450 size_t len;
3452 if (nb_args != 2) {
3453 return;
3456 len = strlen(str);
3457 readline_set_completion_index(rs, len);
3458 peripheral_device_del_completion(rs, str, len);
3461 void object_del_completion(ReadLineState *rs, int nb_args, const char *str)
3463 ObjectPropertyInfoList *list, *start;
3464 size_t len;
3466 if (nb_args != 2) {
3467 return;
3469 len = strlen(str);
3470 readline_set_completion_index(rs, len);
3472 start = list = qmp_qom_list("/objects", NULL);
3473 while (list) {
3474 ObjectPropertyInfo *info = list->value;
3476 if (!strncmp(info->type, "child<", 5)
3477 && !strncmp(info->name, str, len)) {
3478 readline_add_completion(rs, info->name);
3480 list = list->next;
3482 qapi_free_ObjectPropertyInfoList(start);
3485 void sendkey_completion(ReadLineState *rs, int nb_args, const char *str)
3487 int i;
3488 char *sep;
3489 size_t len;
3491 if (nb_args != 2) {
3492 return;
3494 sep = strrchr(str, '-');
3495 if (sep) {
3496 str = sep + 1;
3498 len = strlen(str);
3499 readline_set_completion_index(rs, len);
3500 for (i = 0; i < Q_KEY_CODE__MAX; i++) {
3501 if (!strncmp(str, QKeyCode_str(i), len)) {
3502 readline_add_completion(rs, QKeyCode_str(i));
3507 void set_link_completion(ReadLineState *rs, int nb_args, const char *str)
3509 size_t len;
3511 len = strlen(str);
3512 readline_set_completion_index(rs, len);
3513 if (nb_args == 2) {
3514 NetClientState *ncs[MAX_QUEUE_NUM];
3515 int count, i;
3516 count = qemu_find_net_clients_except(NULL, ncs,
3517 NET_CLIENT_DRIVER_NONE,
3518 MAX_QUEUE_NUM);
3519 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3520 const char *name = ncs[i]->name;
3521 if (!strncmp(str, name, len)) {
3522 readline_add_completion(rs, name);
3525 } else if (nb_args == 3) {
3526 add_completion_option(rs, str, "on");
3527 add_completion_option(rs, str, "off");
3531 void netdev_del_completion(ReadLineState *rs, int nb_args, const char *str)
3533 int len, count, i;
3534 NetClientState *ncs[MAX_QUEUE_NUM];
3536 if (nb_args != 2) {
3537 return;
3540 len = strlen(str);
3541 readline_set_completion_index(rs, len);
3542 count = qemu_find_net_clients_except(NULL, ncs, NET_CLIENT_DRIVER_NIC,
3543 MAX_QUEUE_NUM);
3544 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3545 QemuOpts *opts;
3546 const char *name = ncs[i]->name;
3547 if (strncmp(str, name, len)) {
3548 continue;
3550 opts = qemu_opts_find(qemu_find_opts_err("netdev", NULL), name);
3551 if (opts) {
3552 readline_add_completion(rs, name);
3557 void info_trace_events_completion(ReadLineState *rs, int nb_args, const char *str)
3559 size_t len;
3561 len = strlen(str);
3562 readline_set_completion_index(rs, len);
3563 if (nb_args == 2) {
3564 TraceEventIter iter;
3565 TraceEvent *ev;
3566 char *pattern = g_strdup_printf("%s*", str);
3567 trace_event_iter_init(&iter, pattern);
3568 while ((ev = trace_event_iter_next(&iter)) != NULL) {
3569 readline_add_completion(rs, trace_event_get_name(ev));
3571 g_free(pattern);
3575 void trace_event_completion(ReadLineState *rs, int nb_args, const char *str)
3577 size_t len;
3579 len = strlen(str);
3580 readline_set_completion_index(rs, len);
3581 if (nb_args == 2) {
3582 TraceEventIter iter;
3583 TraceEvent *ev;
3584 char *pattern = g_strdup_printf("%s*", str);
3585 trace_event_iter_init(&iter, pattern);
3586 while ((ev = trace_event_iter_next(&iter)) != NULL) {
3587 readline_add_completion(rs, trace_event_get_name(ev));
3589 g_free(pattern);
3590 } else if (nb_args == 3) {
3591 add_completion_option(rs, str, "on");
3592 add_completion_option(rs, str, "off");
3596 void watchdog_action_completion(ReadLineState *rs, int nb_args, const char *str)
3598 int i;
3600 if (nb_args != 2) {
3601 return;
3603 readline_set_completion_index(rs, strlen(str));
3604 for (i = 0; i < WATCHDOG_ACTION__MAX; i++) {
3605 add_completion_option(rs, str, WatchdogAction_str(i));
3609 void migrate_set_capability_completion(ReadLineState *rs, int nb_args,
3610 const char *str)
3612 size_t len;
3614 len = strlen(str);
3615 readline_set_completion_index(rs, len);
3616 if (nb_args == 2) {
3617 int i;
3618 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
3619 const char *name = MigrationCapability_str(i);
3620 if (!strncmp(str, name, len)) {
3621 readline_add_completion(rs, name);
3624 } else if (nb_args == 3) {
3625 add_completion_option(rs, str, "on");
3626 add_completion_option(rs, str, "off");
3630 void migrate_set_parameter_completion(ReadLineState *rs, int nb_args,
3631 const char *str)
3633 size_t len;
3635 len = strlen(str);
3636 readline_set_completion_index(rs, len);
3637 if (nb_args == 2) {
3638 int i;
3639 for (i = 0; i < MIGRATION_PARAMETER__MAX; i++) {
3640 const char *name = MigrationParameter_str(i);
3641 if (!strncmp(str, name, len)) {
3642 readline_add_completion(rs, name);
3648 static void vm_completion(ReadLineState *rs, const char *str)
3650 size_t len;
3651 BlockDriverState *bs;
3652 BdrvNextIterator it;
3654 len = strlen(str);
3655 readline_set_completion_index(rs, len);
3657 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
3658 SnapshotInfoList *snapshots, *snapshot;
3659 AioContext *ctx = bdrv_get_aio_context(bs);
3660 bool ok = false;
3662 aio_context_acquire(ctx);
3663 if (bdrv_can_snapshot(bs)) {
3664 ok = bdrv_query_snapshot_info_list(bs, &snapshots, NULL) == 0;
3666 aio_context_release(ctx);
3667 if (!ok) {
3668 continue;
3671 snapshot = snapshots;
3672 while (snapshot) {
3673 char *completion = snapshot->value->name;
3674 if (!strncmp(str, completion, len)) {
3675 readline_add_completion(rs, completion);
3677 completion = snapshot->value->id;
3678 if (!strncmp(str, completion, len)) {
3679 readline_add_completion(rs, completion);
3681 snapshot = snapshot->next;
3683 qapi_free_SnapshotInfoList(snapshots);
3688 void delvm_completion(ReadLineState *rs, int nb_args, const char *str)
3690 if (nb_args == 2) {
3691 vm_completion(rs, str);
3695 void loadvm_completion(ReadLineState *rs, int nb_args, const char *str)
3697 if (nb_args == 2) {
3698 vm_completion(rs, str);
3702 static void monitor_find_completion_by_table(Monitor *mon,
3703 const mon_cmd_t *cmd_table,
3704 char **args,
3705 int nb_args)
3707 const char *cmdname;
3708 int i;
3709 const char *ptype, *old_ptype, *str, *name;
3710 const mon_cmd_t *cmd;
3711 BlockBackend *blk = NULL;
3713 if (nb_args <= 1) {
3714 /* command completion */
3715 if (nb_args == 0)
3716 cmdname = "";
3717 else
3718 cmdname = args[0];
3719 readline_set_completion_index(mon->rs, strlen(cmdname));
3720 for (cmd = cmd_table; cmd->name != NULL; cmd++) {
3721 cmd_completion(mon, cmdname, cmd->name);
3723 } else {
3724 /* find the command */
3725 for (cmd = cmd_table; cmd->name != NULL; cmd++) {
3726 if (compare_cmd(args[0], cmd->name)) {
3727 break;
3730 if (!cmd->name) {
3731 return;
3734 if (cmd->sub_table) {
3735 /* do the job again */
3736 monitor_find_completion_by_table(mon, cmd->sub_table,
3737 &args[1], nb_args - 1);
3738 return;
3740 if (cmd->command_completion) {
3741 cmd->command_completion(mon->rs, nb_args, args[nb_args - 1]);
3742 return;
3745 ptype = next_arg_type(cmd->args_type);
3746 for(i = 0; i < nb_args - 2; i++) {
3747 if (*ptype != '\0') {
3748 ptype = next_arg_type(ptype);
3749 while (*ptype == '?')
3750 ptype = next_arg_type(ptype);
3753 str = args[nb_args - 1];
3754 old_ptype = NULL;
3755 while (*ptype == '-' && old_ptype != ptype) {
3756 old_ptype = ptype;
3757 ptype = next_arg_type(ptype);
3759 switch(*ptype) {
3760 case 'F':
3761 /* file completion */
3762 readline_set_completion_index(mon->rs, strlen(str));
3763 file_completion(mon, str);
3764 break;
3765 case 'B':
3766 /* block device name completion */
3767 readline_set_completion_index(mon->rs, strlen(str));
3768 while ((blk = blk_next(blk)) != NULL) {
3769 name = blk_name(blk);
3770 if (str[0] == '\0' ||
3771 !strncmp(name, str, strlen(str))) {
3772 readline_add_completion(mon->rs, name);
3775 break;
3776 case 's':
3777 case 'S':
3778 if (!strcmp(cmd->name, "help|?")) {
3779 monitor_find_completion_by_table(mon, cmd_table,
3780 &args[1], nb_args - 1);
3782 break;
3783 default:
3784 break;
3789 static void monitor_find_completion(void *opaque,
3790 const char *cmdline)
3792 Monitor *mon = opaque;
3793 char *args[MAX_ARGS];
3794 int nb_args, len;
3796 /* 1. parse the cmdline */
3797 if (parse_cmdline(cmdline, &nb_args, args) < 0) {
3798 return;
3801 /* if the line ends with a space, it means we want to complete the
3802 next arg */
3803 len = strlen(cmdline);
3804 if (len > 0 && qemu_isspace(cmdline[len - 1])) {
3805 if (nb_args >= MAX_ARGS) {
3806 goto cleanup;
3808 args[nb_args++] = g_strdup("");
3811 /* 2. auto complete according to args */
3812 monitor_find_completion_by_table(mon, mon->cmd_table, args, nb_args);
3814 cleanup:
3815 free_cmdline_args(args, nb_args);
3818 static int monitor_can_read(void *opaque)
3820 Monitor *mon = opaque;
3822 return !atomic_mb_read(&mon->suspend_cnt);
3826 * 1. This function takes ownership of rsp, err, and id.
3827 * 2. rsp, err, and id may be NULL.
3828 * 3. If err != NULL then rsp must be NULL.
3830 static void monitor_qmp_respond(Monitor *mon, QObject *rsp,
3831 Error *err, QObject *id)
3833 QDict *qdict = NULL;
3835 if (err) {
3836 assert(!rsp);
3837 qdict = qdict_new();
3838 qdict_put_obj(qdict, "error", qmp_build_error_object(err));
3839 error_free(err);
3840 rsp = QOBJECT(qdict);
3843 if (rsp) {
3844 if (id) {
3845 /* This is for the qdict below. */
3846 qobject_incref(id);
3847 qdict_put_obj(qobject_to(QDict, rsp), "id", id);
3850 monitor_json_emitter(mon, rsp);
3853 qobject_decref(id);
3854 qobject_decref(rsp);
3857 static void handle_qmp_command(JSONMessageParser *parser, GQueue *tokens)
3859 QObject *req, *rsp = NULL, *id = NULL;
3860 QDict *qdict = NULL;
3861 MonitorQMP *mon_qmp = container_of(parser, MonitorQMP, parser);
3862 Monitor *old_mon, *mon = container_of(mon_qmp, Monitor, qmp);
3864 Error *err = NULL;
3866 req = json_parser_parse_err(tokens, NULL, &err);
3867 if (!req && !err) {
3868 /* json_parser_parse_err() sucks: can fail without setting @err */
3869 error_setg(&err, QERR_JSON_PARSING);
3871 if (err) {
3872 goto err_out;
3875 qdict = qobject_to(QDict, req);
3876 if (qdict) {
3877 id = qdict_get(qdict, "id");
3878 qobject_incref(id);
3879 qdict_del(qdict, "id");
3880 } /* else will fail qmp_dispatch() */
3882 if (trace_event_get_state_backends(TRACE_HANDLE_QMP_COMMAND)) {
3883 QString *req_json = qobject_to_json(req);
3884 trace_handle_qmp_command(mon, qstring_get_str(req_json));
3885 QDECREF(req_json);
3888 old_mon = cur_mon;
3889 cur_mon = mon;
3891 rsp = qmp_dispatch(cur_mon->qmp.commands, req);
3893 cur_mon = old_mon;
3895 if (mon->qmp.commands == &qmp_cap_negotiation_commands) {
3896 qdict = qdict_get_qdict(qobject_to(QDict, rsp), "error");
3897 if (qdict
3898 && !g_strcmp0(qdict_get_try_str(qdict, "class"),
3899 QapiErrorClass_str(ERROR_CLASS_COMMAND_NOT_FOUND))) {
3900 /* Provide a more useful error message */
3901 qdict_del(qdict, "desc");
3902 qdict_put_str(qdict, "desc", "Expecting capabilities negotiation"
3903 " with 'qmp_capabilities'");
3907 err_out:
3908 monitor_qmp_respond(mon, rsp, err, id);
3910 qobject_decref(req);
3913 static void monitor_qmp_read(void *opaque, const uint8_t *buf, int size)
3915 Monitor *mon = opaque;
3917 json_message_parser_feed(&mon->qmp.parser, (const char *) buf, size);
3920 static void monitor_read(void *opaque, const uint8_t *buf, int size)
3922 Monitor *old_mon = cur_mon;
3923 int i;
3925 cur_mon = opaque;
3927 if (cur_mon->rs) {
3928 for (i = 0; i < size; i++)
3929 readline_handle_byte(cur_mon->rs, buf[i]);
3930 } else {
3931 if (size == 0 || buf[size - 1] != 0)
3932 monitor_printf(cur_mon, "corrupted command\n");
3933 else
3934 handle_hmp_command(cur_mon, (char *)buf);
3937 cur_mon = old_mon;
3940 static void monitor_command_cb(void *opaque, const char *cmdline,
3941 void *readline_opaque)
3943 Monitor *mon = opaque;
3945 monitor_suspend(mon);
3946 handle_hmp_command(mon, cmdline);
3947 monitor_resume(mon);
3950 int monitor_suspend(Monitor *mon)
3952 if (!mon->rs)
3953 return -ENOTTY;
3954 atomic_inc(&mon->suspend_cnt);
3955 return 0;
3958 void monitor_resume(Monitor *mon)
3960 if (!mon->rs)
3961 return;
3962 if (atomic_dec_fetch(&mon->suspend_cnt) == 0) {
3963 readline_show_prompt(mon->rs);
3967 static QObject *get_qmp_greeting(Monitor *mon)
3969 QList *cap_list = qlist_new();
3970 QObject *ver = NULL;
3971 QMPCapability cap;
3973 qmp_marshal_query_version(NULL, &ver, NULL);
3975 for (cap = 0; cap < QMP_CAPABILITY__MAX; cap++) {
3976 if (!mon->use_io_thr && cap == QMP_CAPABILITY_OOB) {
3977 /* Monitors that are not using IOThread won't support OOB */
3978 continue;
3980 qlist_append(cap_list, qstring_from_str(QMPCapability_str(cap)));
3983 return qobject_from_jsonf("{'QMP': {'version': %p, 'capabilities': %p}}",
3984 ver, cap_list);
3987 static void monitor_qmp_caps_reset(Monitor *mon)
3989 memset(mon->qmp.qmp_caps, 0, sizeof(mon->qmp.qmp_caps));
3992 static void monitor_qmp_event(void *opaque, int event)
3994 QObject *data;
3995 Monitor *mon = opaque;
3997 switch (event) {
3998 case CHR_EVENT_OPENED:
3999 mon->qmp.commands = &qmp_cap_negotiation_commands;
4000 monitor_qmp_caps_reset(mon);
4001 data = get_qmp_greeting(mon);
4002 monitor_json_emitter(mon, data);
4003 qobject_decref(data);
4004 mon_refcount++;
4005 break;
4006 case CHR_EVENT_CLOSED:
4007 json_message_parser_destroy(&mon->qmp.parser);
4008 json_message_parser_init(&mon->qmp.parser, handle_qmp_command);
4009 mon_refcount--;
4010 monitor_fdsets_cleanup();
4011 break;
4015 static void monitor_event(void *opaque, int event)
4017 Monitor *mon = opaque;
4019 switch (event) {
4020 case CHR_EVENT_MUX_IN:
4021 qemu_mutex_lock(&mon->out_lock);
4022 mon->mux_out = 0;
4023 qemu_mutex_unlock(&mon->out_lock);
4024 if (mon->reset_seen) {
4025 readline_restart(mon->rs);
4026 monitor_resume(mon);
4027 monitor_flush(mon);
4028 } else {
4029 atomic_mb_set(&mon->suspend_cnt, 0);
4031 break;
4033 case CHR_EVENT_MUX_OUT:
4034 if (mon->reset_seen) {
4035 if (atomic_mb_read(&mon->suspend_cnt) == 0) {
4036 monitor_printf(mon, "\n");
4038 monitor_flush(mon);
4039 monitor_suspend(mon);
4040 } else {
4041 atomic_inc(&mon->suspend_cnt);
4043 qemu_mutex_lock(&mon->out_lock);
4044 mon->mux_out = 1;
4045 qemu_mutex_unlock(&mon->out_lock);
4046 break;
4048 case CHR_EVENT_OPENED:
4049 monitor_printf(mon, "QEMU %s monitor - type 'help' for more "
4050 "information\n", QEMU_VERSION);
4051 if (!mon->mux_out) {
4052 readline_restart(mon->rs);
4053 readline_show_prompt(mon->rs);
4055 mon->reset_seen = 1;
4056 mon_refcount++;
4057 break;
4059 case CHR_EVENT_CLOSED:
4060 mon_refcount--;
4061 monitor_fdsets_cleanup();
4062 break;
4066 static int
4067 compare_mon_cmd(const void *a, const void *b)
4069 return strcmp(((const mon_cmd_t *)a)->name,
4070 ((const mon_cmd_t *)b)->name);
4073 static void sortcmdlist(void)
4075 int array_num;
4076 int elem_size = sizeof(mon_cmd_t);
4078 array_num = sizeof(mon_cmds)/elem_size-1;
4079 qsort((void *)mon_cmds, array_num, elem_size, compare_mon_cmd);
4081 array_num = sizeof(info_cmds)/elem_size-1;
4082 qsort((void *)info_cmds, array_num, elem_size, compare_mon_cmd);
4085 static GMainContext *monitor_get_io_context(void)
4087 return iothread_get_g_main_context(mon_global.mon_iothread);
4090 static AioContext *monitor_get_aio_context(void)
4092 return iothread_get_aio_context(mon_global.mon_iothread);
4095 static void monitor_iothread_init(void)
4097 mon_global.mon_iothread = iothread_create("mon_iothread",
4098 &error_abort);
4101 void monitor_init_globals(void)
4103 monitor_init_qmp_commands();
4104 monitor_qapi_event_init();
4105 sortcmdlist();
4106 qemu_mutex_init(&monitor_lock);
4107 monitor_iothread_init();
4110 /* These functions just adapt the readline interface in a typesafe way. We
4111 * could cast function pointers but that discards compiler checks.
4113 static void GCC_FMT_ATTR(2, 3) monitor_readline_printf(void *opaque,
4114 const char *fmt, ...)
4116 va_list ap;
4117 va_start(ap, fmt);
4118 monitor_vprintf(opaque, fmt, ap);
4119 va_end(ap);
4122 static void monitor_readline_flush(void *opaque)
4124 monitor_flush(opaque);
4128 * Print to current monitor if we have one, else to stderr.
4129 * TODO should return int, so callers can calculate width, but that
4130 * requires surgery to monitor_vprintf(). Left for another day.
4132 void error_vprintf(const char *fmt, va_list ap)
4134 if (cur_mon && !monitor_cur_is_qmp()) {
4135 monitor_vprintf(cur_mon, fmt, ap);
4136 } else {
4137 vfprintf(stderr, fmt, ap);
4141 void error_vprintf_unless_qmp(const char *fmt, va_list ap)
4143 if (cur_mon && !monitor_cur_is_qmp()) {
4144 monitor_vprintf(cur_mon, fmt, ap);
4145 } else if (!cur_mon) {
4146 vfprintf(stderr, fmt, ap);
4150 static void monitor_list_append(Monitor *mon)
4152 qemu_mutex_lock(&monitor_lock);
4153 QTAILQ_INSERT_HEAD(&mon_list, mon, entry);
4154 qemu_mutex_unlock(&monitor_lock);
4157 static void monitor_qmp_setup_handlers_bh(void *opaque)
4159 Monitor *mon = opaque;
4160 GMainContext *context;
4162 if (mon->use_io_thr) {
4164 * When use_io_thr is set, we use the global shared dedicated
4165 * IO thread for this monitor to handle input/output.
4167 context = monitor_get_io_context();
4168 /* We should have inited globals before reaching here. */
4169 assert(context);
4170 } else {
4171 /* The default main loop, which is the main thread */
4172 context = NULL;
4175 qemu_chr_fe_set_handlers(&mon->chr, monitor_can_read, monitor_qmp_read,
4176 monitor_qmp_event, NULL, mon, context, true);
4177 monitor_list_append(mon);
4180 void monitor_init(Chardev *chr, int flags)
4182 Monitor *mon = g_malloc(sizeof(*mon));
4184 monitor_data_init(mon, false, false);
4186 qemu_chr_fe_init(&mon->chr, chr, &error_abort);
4187 mon->flags = flags;
4188 if (flags & MONITOR_USE_READLINE) {
4189 mon->rs = readline_init(monitor_readline_printf,
4190 monitor_readline_flush,
4191 mon,
4192 monitor_find_completion);
4193 monitor_read_command(mon, 0);
4196 if (monitor_is_qmp(mon)) {
4197 qemu_chr_fe_set_echo(&mon->chr, true);
4198 json_message_parser_init(&mon->qmp.parser, handle_qmp_command);
4199 if (mon->use_io_thr) {
4201 * Make sure the old iowatch is gone. It's possible when
4202 * e.g. the chardev is in client mode, with wait=on.
4204 remove_fd_in_watch(chr);
4206 * We can't call qemu_chr_fe_set_handlers() directly here
4207 * since during the procedure the chardev will be active
4208 * and running in monitor iothread, while we'll still do
4209 * something before returning from it, which is a possible
4210 * race too. To avoid that, we just create a BH to setup
4211 * the handlers.
4213 aio_bh_schedule_oneshot(monitor_get_aio_context(),
4214 monitor_qmp_setup_handlers_bh, mon);
4215 /* We'll add this to mon_list in the BH when setup done */
4216 return;
4217 } else {
4218 qemu_chr_fe_set_handlers(&mon->chr, monitor_can_read,
4219 monitor_qmp_read, monitor_qmp_event,
4220 NULL, mon, NULL, true);
4222 } else {
4223 qemu_chr_fe_set_handlers(&mon->chr, monitor_can_read, monitor_read,
4224 monitor_event, NULL, mon, NULL, true);
4227 monitor_list_append(mon);
4230 void monitor_cleanup(void)
4232 Monitor *mon, *next;
4235 * We need to explicitly stop the iothread (but not destroy it),
4236 * cleanup the monitor resources, then destroy the iothread since
4237 * we need to unregister from chardev below in
4238 * monitor_data_destroy(), and chardev is not thread-safe yet
4240 iothread_stop(mon_global.mon_iothread);
4242 qemu_mutex_lock(&monitor_lock);
4243 QTAILQ_FOREACH_SAFE(mon, &mon_list, entry, next) {
4244 QTAILQ_REMOVE(&mon_list, mon, entry);
4245 monitor_data_destroy(mon);
4246 g_free(mon);
4248 qemu_mutex_unlock(&monitor_lock);
4250 iothread_destroy(mon_global.mon_iothread);
4251 mon_global.mon_iothread = NULL;
4254 QemuOptsList qemu_mon_opts = {
4255 .name = "mon",
4256 .implied_opt_name = "chardev",
4257 .head = QTAILQ_HEAD_INITIALIZER(qemu_mon_opts.head),
4258 .desc = {
4260 .name = "mode",
4261 .type = QEMU_OPT_STRING,
4263 .name = "chardev",
4264 .type = QEMU_OPT_STRING,
4266 .name = "pretty",
4267 .type = QEMU_OPT_BOOL,
4269 { /* end of list */ }
4273 #ifndef TARGET_I386
4274 void qmp_rtc_reset_reinjection(Error **errp)
4276 error_setg(errp, QERR_FEATURE_DISABLED, "rtc-reset-reinjection");
4279 SevInfo *qmp_query_sev(Error **errp)
4281 error_setg(errp, QERR_FEATURE_DISABLED, "query-sev");
4282 return NULL;
4285 SevLaunchMeasureInfo *qmp_query_sev_launch_measure(Error **errp)
4287 error_setg(errp, QERR_FEATURE_DISABLED, "query-sev-launch-measure");
4288 return NULL;
4291 SevCapability *qmp_query_sev_capabilities(Error **errp)
4293 error_setg(errp, QERR_FEATURE_DISABLED, "query-sev-capabilities");
4294 return NULL;
4296 #endif
4298 #ifndef TARGET_S390X
4299 void qmp_dump_skeys(const char *filename, Error **errp)
4301 error_setg(errp, QERR_FEATURE_DISABLED, "dump-skeys");
4303 #endif
4305 #ifndef TARGET_ARM
4306 GICCapabilityList *qmp_query_gic_capabilities(Error **errp)
4308 error_setg(errp, QERR_FEATURE_DISABLED, "query-gic-capabilities");
4309 return NULL;
4311 #endif
4313 HotpluggableCPUList *qmp_query_hotpluggable_cpus(Error **errp)
4315 MachineState *ms = MACHINE(qdev_get_machine());
4316 MachineClass *mc = MACHINE_GET_CLASS(ms);
4318 if (!mc->has_hotpluggable_cpus) {
4319 error_setg(errp, QERR_FEATURE_DISABLED, "query-hotpluggable-cpus");
4320 return NULL;
4323 return machine_query_hotpluggable_cpus(ms);