monitor: let suspend/resume work even with QMPs
[qemu/ar7.git] / monitor.c
blob0dab6a450fc89c62270da98bcd2b30690061665c
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 * Whether @mon is using readline? Note: not all HMP monitors use
255 * readline, e.g., gdbserver has a non-interactive HMP monitor, so
256 * readline is not used there.
258 static inline bool monitor_uses_readline(const Monitor *mon)
260 return mon->flags & MONITOR_USE_READLINE;
263 static inline bool monitor_is_hmp_non_interactive(const Monitor *mon)
265 return !monitor_is_qmp(mon) && !monitor_uses_readline(mon);
269 * Is the current monitor, if any, a QMP monitor?
271 bool monitor_cur_is_qmp(void)
273 return cur_mon && monitor_is_qmp(cur_mon);
276 void monitor_read_command(Monitor *mon, int show_prompt)
278 if (!mon->rs)
279 return;
281 readline_start(mon->rs, "(qemu) ", 0, monitor_command_cb, NULL);
282 if (show_prompt)
283 readline_show_prompt(mon->rs);
286 int monitor_read_password(Monitor *mon, ReadLineFunc *readline_func,
287 void *opaque)
289 if (mon->rs) {
290 readline_start(mon->rs, "Password: ", 1, readline_func, opaque);
291 /* prompt is printed on return from the command handler */
292 return 0;
293 } else {
294 monitor_printf(mon, "terminal does not support password prompting\n");
295 return -ENOTTY;
299 static void monitor_flush_locked(Monitor *mon);
301 static gboolean monitor_unblocked(GIOChannel *chan, GIOCondition cond,
302 void *opaque)
304 Monitor *mon = opaque;
306 qemu_mutex_lock(&mon->out_lock);
307 mon->out_watch = 0;
308 monitor_flush_locked(mon);
309 qemu_mutex_unlock(&mon->out_lock);
310 return FALSE;
313 /* Called with mon->out_lock held. */
314 static void monitor_flush_locked(Monitor *mon)
316 int rc;
317 size_t len;
318 const char *buf;
320 if (mon->skip_flush) {
321 return;
324 buf = qstring_get_str(mon->outbuf);
325 len = qstring_get_length(mon->outbuf);
327 if (len && !mon->mux_out) {
328 rc = qemu_chr_fe_write(&mon->chr, (const uint8_t *) buf, len);
329 if ((rc < 0 && errno != EAGAIN) || (rc == len)) {
330 /* all flushed or error */
331 QDECREF(mon->outbuf);
332 mon->outbuf = qstring_new();
333 return;
335 if (rc > 0) {
336 /* partial write */
337 QString *tmp = qstring_from_str(buf + rc);
338 QDECREF(mon->outbuf);
339 mon->outbuf = tmp;
341 if (mon->out_watch == 0) {
342 mon->out_watch =
343 qemu_chr_fe_add_watch(&mon->chr, G_IO_OUT | G_IO_HUP,
344 monitor_unblocked, mon);
349 void monitor_flush(Monitor *mon)
351 qemu_mutex_lock(&mon->out_lock);
352 monitor_flush_locked(mon);
353 qemu_mutex_unlock(&mon->out_lock);
356 /* flush at every end of line */
357 static void monitor_puts(Monitor *mon, const char *str)
359 char c;
361 qemu_mutex_lock(&mon->out_lock);
362 for(;;) {
363 c = *str++;
364 if (c == '\0')
365 break;
366 if (c == '\n') {
367 qstring_append_chr(mon->outbuf, '\r');
369 qstring_append_chr(mon->outbuf, c);
370 if (c == '\n') {
371 monitor_flush_locked(mon);
374 qemu_mutex_unlock(&mon->out_lock);
377 void monitor_vprintf(Monitor *mon, const char *fmt, va_list ap)
379 char *buf;
381 if (!mon)
382 return;
384 if (monitor_is_qmp(mon)) {
385 return;
388 buf = g_strdup_vprintf(fmt, ap);
389 monitor_puts(mon, buf);
390 g_free(buf);
393 void monitor_printf(Monitor *mon, const char *fmt, ...)
395 va_list ap;
396 va_start(ap, fmt);
397 monitor_vprintf(mon, fmt, ap);
398 va_end(ap);
401 int monitor_fprintf(FILE *stream, const char *fmt, ...)
403 va_list ap;
404 va_start(ap, fmt);
405 monitor_vprintf((Monitor *)stream, fmt, ap);
406 va_end(ap);
407 return 0;
410 static void monitor_json_emitter(Monitor *mon, const QObject *data)
412 QString *json;
414 json = mon->flags & MONITOR_USE_PRETTY ? qobject_to_json_pretty(data) :
415 qobject_to_json(data);
416 assert(json != NULL);
418 qstring_append_chr(json, '\n');
419 monitor_puts(mon, qstring_get_str(json));
421 QDECREF(json);
424 static MonitorQAPIEventConf monitor_qapi_event_conf[QAPI_EVENT__MAX] = {
425 /* Limit guest-triggerable events to 1 per second */
426 [QAPI_EVENT_RTC_CHANGE] = { 1000 * SCALE_MS },
427 [QAPI_EVENT_WATCHDOG] = { 1000 * SCALE_MS },
428 [QAPI_EVENT_BALLOON_CHANGE] = { 1000 * SCALE_MS },
429 [QAPI_EVENT_QUORUM_REPORT_BAD] = { 1000 * SCALE_MS },
430 [QAPI_EVENT_QUORUM_FAILURE] = { 1000 * SCALE_MS },
431 [QAPI_EVENT_VSERPORT_CHANGE] = { 1000 * SCALE_MS },
434 GHashTable *monitor_qapi_event_state;
437 * Emits the event to every monitor instance, @event is only used for trace
438 * Called with monitor_lock held.
440 static void monitor_qapi_event_emit(QAPIEvent event, QDict *qdict)
442 Monitor *mon;
444 trace_monitor_protocol_event_emit(event, qdict);
445 QTAILQ_FOREACH(mon, &mon_list, entry) {
446 if (monitor_is_qmp(mon)
447 && mon->qmp.commands != &qmp_cap_negotiation_commands) {
448 monitor_json_emitter(mon, QOBJECT(qdict));
453 static void monitor_qapi_event_handler(void *opaque);
456 * Queue a new event for emission to Monitor instances,
457 * applying any rate limiting if required.
459 static void
460 monitor_qapi_event_queue(QAPIEvent event, QDict *qdict, Error **errp)
462 MonitorQAPIEventConf *evconf;
463 MonitorQAPIEventState *evstate;
465 assert(event < QAPI_EVENT__MAX);
466 evconf = &monitor_qapi_event_conf[event];
467 trace_monitor_protocol_event_queue(event, qdict, evconf->rate);
469 qemu_mutex_lock(&monitor_lock);
471 if (!evconf->rate) {
472 /* Unthrottled event */
473 monitor_qapi_event_emit(event, qdict);
474 } else {
475 QDict *data = qobject_to(QDict, qdict_get(qdict, "data"));
476 MonitorQAPIEventState key = { .event = event, .data = data };
478 evstate = g_hash_table_lookup(monitor_qapi_event_state, &key);
479 assert(!evstate || timer_pending(evstate->timer));
481 if (evstate) {
483 * Timer is pending for (at least) evconf->rate ns after
484 * last send. Store event for sending when timer fires,
485 * replacing a prior stored event if any.
487 QDECREF(evstate->qdict);
488 evstate->qdict = qdict;
489 QINCREF(evstate->qdict);
490 } else {
492 * Last send was (at least) evconf->rate ns ago.
493 * Send immediately, and arm the timer to call
494 * monitor_qapi_event_handler() in evconf->rate ns. Any
495 * events arriving before then will be delayed until then.
497 int64_t now = qemu_clock_get_ns(event_clock_type);
499 monitor_qapi_event_emit(event, qdict);
501 evstate = g_new(MonitorQAPIEventState, 1);
502 evstate->event = event;
503 evstate->data = data;
504 QINCREF(evstate->data);
505 evstate->qdict = NULL;
506 evstate->timer = timer_new_ns(event_clock_type,
507 monitor_qapi_event_handler,
508 evstate);
509 g_hash_table_add(monitor_qapi_event_state, evstate);
510 timer_mod_ns(evstate->timer, now + evconf->rate);
514 qemu_mutex_unlock(&monitor_lock);
518 * This function runs evconf->rate ns after sending a throttled
519 * event.
520 * If another event has since been stored, send it.
522 static void monitor_qapi_event_handler(void *opaque)
524 MonitorQAPIEventState *evstate = opaque;
525 MonitorQAPIEventConf *evconf = &monitor_qapi_event_conf[evstate->event];
527 trace_monitor_protocol_event_handler(evstate->event, evstate->qdict);
528 qemu_mutex_lock(&monitor_lock);
530 if (evstate->qdict) {
531 int64_t now = qemu_clock_get_ns(event_clock_type);
533 monitor_qapi_event_emit(evstate->event, evstate->qdict);
534 QDECREF(evstate->qdict);
535 evstate->qdict = NULL;
536 timer_mod_ns(evstate->timer, now + evconf->rate);
537 } else {
538 g_hash_table_remove(monitor_qapi_event_state, evstate);
539 QDECREF(evstate->data);
540 timer_free(evstate->timer);
541 g_free(evstate);
544 qemu_mutex_unlock(&monitor_lock);
547 static unsigned int qapi_event_throttle_hash(const void *key)
549 const MonitorQAPIEventState *evstate = key;
550 unsigned int hash = evstate->event * 255;
552 if (evstate->event == QAPI_EVENT_VSERPORT_CHANGE) {
553 hash += g_str_hash(qdict_get_str(evstate->data, "id"));
556 if (evstate->event == QAPI_EVENT_QUORUM_REPORT_BAD) {
557 hash += g_str_hash(qdict_get_str(evstate->data, "node-name"));
560 return hash;
563 static gboolean qapi_event_throttle_equal(const void *a, const void *b)
565 const MonitorQAPIEventState *eva = a;
566 const MonitorQAPIEventState *evb = b;
568 if (eva->event != evb->event) {
569 return FALSE;
572 if (eva->event == QAPI_EVENT_VSERPORT_CHANGE) {
573 return !strcmp(qdict_get_str(eva->data, "id"),
574 qdict_get_str(evb->data, "id"));
577 if (eva->event == QAPI_EVENT_QUORUM_REPORT_BAD) {
578 return !strcmp(qdict_get_str(eva->data, "node-name"),
579 qdict_get_str(evb->data, "node-name"));
582 return TRUE;
585 static void monitor_qapi_event_init(void)
587 if (qtest_enabled()) {
588 event_clock_type = QEMU_CLOCK_VIRTUAL;
591 monitor_qapi_event_state = g_hash_table_new(qapi_event_throttle_hash,
592 qapi_event_throttle_equal);
593 qmp_event_set_func_emit(monitor_qapi_event_queue);
596 static void handle_hmp_command(Monitor *mon, const char *cmdline);
598 static void monitor_data_init(Monitor *mon, bool skip_flush,
599 bool use_io_thr)
601 memset(mon, 0, sizeof(Monitor));
602 qemu_mutex_init(&mon->out_lock);
603 mon->outbuf = qstring_new();
604 /* Use *mon_cmds by default. */
605 mon->cmd_table = mon_cmds;
606 mon->skip_flush = skip_flush;
607 mon->use_io_thr = use_io_thr;
610 static void monitor_data_destroy(Monitor *mon)
612 g_free(mon->mon_cpu_path);
613 qemu_chr_fe_deinit(&mon->chr, false);
614 if (monitor_is_qmp(mon)) {
615 json_message_parser_destroy(&mon->qmp.parser);
617 readline_free(mon->rs);
618 QDECREF(mon->outbuf);
619 qemu_mutex_destroy(&mon->out_lock);
622 char *qmp_human_monitor_command(const char *command_line, bool has_cpu_index,
623 int64_t cpu_index, Error **errp)
625 char *output = NULL;
626 Monitor *old_mon, hmp;
628 monitor_data_init(&hmp, true, false);
630 old_mon = cur_mon;
631 cur_mon = &hmp;
633 if (has_cpu_index) {
634 int ret = monitor_set_cpu(cpu_index);
635 if (ret < 0) {
636 cur_mon = old_mon;
637 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cpu-index",
638 "a CPU number");
639 goto out;
643 handle_hmp_command(&hmp, command_line);
644 cur_mon = old_mon;
646 qemu_mutex_lock(&hmp.out_lock);
647 if (qstring_get_length(hmp.outbuf) > 0) {
648 output = g_strdup(qstring_get_str(hmp.outbuf));
649 } else {
650 output = g_strdup("");
652 qemu_mutex_unlock(&hmp.out_lock);
654 out:
655 monitor_data_destroy(&hmp);
656 return output;
659 static int compare_cmd(const char *name, const char *list)
661 const char *p, *pstart;
662 int len;
663 len = strlen(name);
664 p = list;
665 for(;;) {
666 pstart = p;
667 p = strchr(p, '|');
668 if (!p)
669 p = pstart + strlen(pstart);
670 if ((p - pstart) == len && !memcmp(pstart, name, len))
671 return 1;
672 if (*p == '\0')
673 break;
674 p++;
676 return 0;
679 static int get_str(char *buf, int buf_size, const char **pp)
681 const char *p;
682 char *q;
683 int c;
685 q = buf;
686 p = *pp;
687 while (qemu_isspace(*p)) {
688 p++;
690 if (*p == '\0') {
691 fail:
692 *q = '\0';
693 *pp = p;
694 return -1;
696 if (*p == '\"') {
697 p++;
698 while (*p != '\0' && *p != '\"') {
699 if (*p == '\\') {
700 p++;
701 c = *p++;
702 switch (c) {
703 case 'n':
704 c = '\n';
705 break;
706 case 'r':
707 c = '\r';
708 break;
709 case '\\':
710 case '\'':
711 case '\"':
712 break;
713 default:
714 printf("unsupported escape code: '\\%c'\n", c);
715 goto fail;
717 if ((q - buf) < buf_size - 1) {
718 *q++ = c;
720 } else {
721 if ((q - buf) < buf_size - 1) {
722 *q++ = *p;
724 p++;
727 if (*p != '\"') {
728 printf("unterminated string\n");
729 goto fail;
731 p++;
732 } else {
733 while (*p != '\0' && !qemu_isspace(*p)) {
734 if ((q - buf) < buf_size - 1) {
735 *q++ = *p;
737 p++;
740 *q = '\0';
741 *pp = p;
742 return 0;
745 #define MAX_ARGS 16
747 static void free_cmdline_args(char **args, int nb_args)
749 int i;
751 assert(nb_args <= MAX_ARGS);
753 for (i = 0; i < nb_args; i++) {
754 g_free(args[i]);
760 * Parse the command line to get valid args.
761 * @cmdline: command line to be parsed.
762 * @pnb_args: location to store the number of args, must NOT be NULL.
763 * @args: location to store the args, which should be freed by caller, must
764 * NOT be NULL.
766 * Returns 0 on success, negative on failure.
768 * NOTE: this parser is an approximate form of the real command parser. Number
769 * of args have a limit of MAX_ARGS. If cmdline contains more, it will
770 * return with failure.
772 static int parse_cmdline(const char *cmdline,
773 int *pnb_args, char **args)
775 const char *p;
776 int nb_args, ret;
777 char buf[1024];
779 p = cmdline;
780 nb_args = 0;
781 for (;;) {
782 while (qemu_isspace(*p)) {
783 p++;
785 if (*p == '\0') {
786 break;
788 if (nb_args >= MAX_ARGS) {
789 goto fail;
791 ret = get_str(buf, sizeof(buf), &p);
792 if (ret < 0) {
793 goto fail;
795 args[nb_args] = g_strdup(buf);
796 nb_args++;
798 *pnb_args = nb_args;
799 return 0;
801 fail:
802 free_cmdline_args(args, nb_args);
803 return -1;
806 static void help_cmd_dump_one(Monitor *mon,
807 const mon_cmd_t *cmd,
808 char **prefix_args,
809 int prefix_args_nb)
811 int i;
813 for (i = 0; i < prefix_args_nb; i++) {
814 monitor_printf(mon, "%s ", prefix_args[i]);
816 monitor_printf(mon, "%s %s -- %s\n", cmd->name, cmd->params, cmd->help);
819 /* @args[@arg_index] is the valid command need to find in @cmds */
820 static void help_cmd_dump(Monitor *mon, const mon_cmd_t *cmds,
821 char **args, int nb_args, int arg_index)
823 const mon_cmd_t *cmd;
825 /* No valid arg need to compare with, dump all in *cmds */
826 if (arg_index >= nb_args) {
827 for (cmd = cmds; cmd->name != NULL; cmd++) {
828 help_cmd_dump_one(mon, cmd, args, arg_index);
830 return;
833 /* Find one entry to dump */
834 for (cmd = cmds; cmd->name != NULL; cmd++) {
835 if (compare_cmd(args[arg_index], cmd->name)) {
836 if (cmd->sub_table) {
837 /* continue with next arg */
838 help_cmd_dump(mon, cmd->sub_table,
839 args, nb_args, arg_index + 1);
840 } else {
841 help_cmd_dump_one(mon, cmd, args, arg_index);
843 break;
848 static void help_cmd(Monitor *mon, const char *name)
850 char *args[MAX_ARGS];
851 int nb_args = 0;
853 /* 1. parse user input */
854 if (name) {
855 /* special case for log, directly dump and return */
856 if (!strcmp(name, "log")) {
857 const QEMULogItem *item;
858 monitor_printf(mon, "Log items (comma separated):\n");
859 monitor_printf(mon, "%-10s %s\n", "none", "remove all logs");
860 for (item = qemu_log_items; item->mask != 0; item++) {
861 monitor_printf(mon, "%-10s %s\n", item->name, item->help);
863 return;
866 if (parse_cmdline(name, &nb_args, args) < 0) {
867 return;
871 /* 2. dump the contents according to parsed args */
872 help_cmd_dump(mon, mon->cmd_table, args, nb_args, 0);
874 free_cmdline_args(args, nb_args);
877 static void do_help_cmd(Monitor *mon, const QDict *qdict)
879 help_cmd(mon, qdict_get_try_str(qdict, "name"));
882 static void hmp_trace_event(Monitor *mon, const QDict *qdict)
884 const char *tp_name = qdict_get_str(qdict, "name");
885 bool new_state = qdict_get_bool(qdict, "option");
886 bool has_vcpu = qdict_haskey(qdict, "vcpu");
887 int vcpu = qdict_get_try_int(qdict, "vcpu", 0);
888 Error *local_err = NULL;
890 if (vcpu < 0) {
891 monitor_printf(mon, "argument vcpu must be positive");
892 return;
895 qmp_trace_event_set_state(tp_name, new_state, true, true, has_vcpu, vcpu, &local_err);
896 if (local_err) {
897 error_report_err(local_err);
901 #ifdef CONFIG_TRACE_SIMPLE
902 static void hmp_trace_file(Monitor *mon, const QDict *qdict)
904 const char *op = qdict_get_try_str(qdict, "op");
905 const char *arg = qdict_get_try_str(qdict, "arg");
907 if (!op) {
908 st_print_trace_file_status((FILE *)mon, &monitor_fprintf);
909 } else if (!strcmp(op, "on")) {
910 st_set_trace_file_enabled(true);
911 } else if (!strcmp(op, "off")) {
912 st_set_trace_file_enabled(false);
913 } else if (!strcmp(op, "flush")) {
914 st_flush_trace_buffer();
915 } else if (!strcmp(op, "set")) {
916 if (arg) {
917 st_set_trace_file(arg);
919 } else {
920 monitor_printf(mon, "unexpected argument \"%s\"\n", op);
921 help_cmd(mon, "trace-file");
924 #endif
926 static void hmp_info_help(Monitor *mon, const QDict *qdict)
928 help_cmd(mon, "info");
931 static void query_commands_cb(QmpCommand *cmd, void *opaque)
933 CommandInfoList *info, **list = opaque;
935 if (!cmd->enabled) {
936 return;
939 info = g_malloc0(sizeof(*info));
940 info->value = g_malloc0(sizeof(*info->value));
941 info->value->name = g_strdup(cmd->name);
942 info->next = *list;
943 *list = info;
946 CommandInfoList *qmp_query_commands(Error **errp)
948 CommandInfoList *list = NULL;
950 qmp_for_each_command(cur_mon->qmp.commands, query_commands_cb, &list);
952 return list;
955 EventInfoList *qmp_query_events(Error **errp)
957 EventInfoList *info, *ev_list = NULL;
958 QAPIEvent e;
960 for (e = 0 ; e < QAPI_EVENT__MAX ; e++) {
961 const char *event_name = QAPIEvent_str(e);
962 assert(event_name != NULL);
963 info = g_malloc0(sizeof(*info));
964 info->value = g_malloc0(sizeof(*info->value));
965 info->value->name = g_strdup(event_name);
967 info->next = ev_list;
968 ev_list = info;
971 return ev_list;
975 * Minor hack: generated marshalling suppressed for this command
976 * ('gen': false in the schema) so we can parse the JSON string
977 * directly into QObject instead of first parsing it with
978 * visit_type_SchemaInfoList() into a SchemaInfoList, then marshal it
979 * to QObject with generated output marshallers, every time. Instead,
980 * we do it in test-qobject-input-visitor.c, just to make sure
981 * qapi-gen.py's output actually conforms to the schema.
983 static void qmp_query_qmp_schema(QDict *qdict, QObject **ret_data,
984 Error **errp)
986 *ret_data = qobject_from_qlit(&qmp_schema_qlit);
990 * We used to define commands in qmp-commands.hx in addition to the
991 * QAPI schema. This permitted defining some of them only in certain
992 * configurations. query-commands has always reflected that (good,
993 * because it lets QMP clients figure out what's actually available),
994 * while query-qmp-schema never did (not so good). This function is a
995 * hack to keep the configuration-specific commands defined exactly as
996 * before, even though qmp-commands.hx is gone.
998 * FIXME Educate the QAPI schema on configuration-specific commands,
999 * and drop this hack.
1001 static void qmp_unregister_commands_hack(void)
1003 #ifndef CONFIG_SPICE
1004 qmp_unregister_command(&qmp_commands, "query-spice");
1005 #endif
1006 #ifndef CONFIG_REPLICATION
1007 qmp_unregister_command(&qmp_commands, "xen-set-replication");
1008 qmp_unregister_command(&qmp_commands, "query-xen-replication-status");
1009 qmp_unregister_command(&qmp_commands, "xen-colo-do-checkpoint");
1010 #endif
1011 #ifndef TARGET_I386
1012 qmp_unregister_command(&qmp_commands, "rtc-reset-reinjection");
1013 qmp_unregister_command(&qmp_commands, "query-sev");
1014 qmp_unregister_command(&qmp_commands, "query-sev-launch-measure");
1015 qmp_unregister_command(&qmp_commands, "query-sev-capabilities");
1016 #endif
1017 #ifndef TARGET_S390X
1018 qmp_unregister_command(&qmp_commands, "dump-skeys");
1019 #endif
1020 #ifndef TARGET_ARM
1021 qmp_unregister_command(&qmp_commands, "query-gic-capabilities");
1022 #endif
1023 #if !defined(TARGET_S390X) && !defined(TARGET_I386)
1024 qmp_unregister_command(&qmp_commands, "query-cpu-model-expansion");
1025 #endif
1026 #if !defined(TARGET_S390X)
1027 qmp_unregister_command(&qmp_commands, "query-cpu-model-baseline");
1028 qmp_unregister_command(&qmp_commands, "query-cpu-model-comparison");
1029 #endif
1030 #if !defined(TARGET_PPC) && !defined(TARGET_ARM) && !defined(TARGET_I386) \
1031 && !defined(TARGET_S390X)
1032 qmp_unregister_command(&qmp_commands, "query-cpu-definitions");
1033 #endif
1036 static void monitor_init_qmp_commands(void)
1039 * Two command lists:
1040 * - qmp_commands contains all QMP commands
1041 * - qmp_cap_negotiation_commands contains just
1042 * "qmp_capabilities", to enforce capability negotiation
1045 qmp_init_marshal(&qmp_commands);
1047 qmp_register_command(&qmp_commands, "query-qmp-schema",
1048 qmp_query_qmp_schema,
1049 QCO_NO_OPTIONS);
1050 qmp_register_command(&qmp_commands, "device_add", qmp_device_add,
1051 QCO_NO_OPTIONS);
1052 qmp_register_command(&qmp_commands, "netdev_add", qmp_netdev_add,
1053 QCO_NO_OPTIONS);
1055 qmp_unregister_commands_hack();
1057 QTAILQ_INIT(&qmp_cap_negotiation_commands);
1058 qmp_register_command(&qmp_cap_negotiation_commands, "qmp_capabilities",
1059 qmp_marshal_qmp_capabilities, QCO_NO_OPTIONS);
1062 static void qmp_caps_check(Monitor *mon, QMPCapabilityList *list,
1063 Error **errp)
1065 for (; list; list = list->next) {
1066 assert(list->value < QMP_CAPABILITY__MAX);
1067 switch (list->value) {
1068 case QMP_CAPABILITY_OOB:
1069 if (!mon->use_io_thr) {
1071 * Out-Of-Band only works with monitors that are
1072 * running on dedicated IOThread.
1074 error_setg(errp, "This monitor does not support "
1075 "Out-Of-Band (OOB)");
1076 return;
1078 break;
1079 default:
1080 break;
1085 /* This function should only be called after capabilities are checked. */
1086 static void qmp_caps_apply(Monitor *mon, QMPCapabilityList *list)
1088 for (; list; list = list->next) {
1089 mon->qmp.qmp_caps[list->value] = true;
1093 void qmp_qmp_capabilities(bool has_enable, QMPCapabilityList *enable,
1094 Error **errp)
1096 Error *local_err = NULL;
1098 if (cur_mon->qmp.commands == &qmp_commands) {
1099 error_set(errp, ERROR_CLASS_COMMAND_NOT_FOUND,
1100 "Capabilities negotiation is already complete, command "
1101 "ignored");
1102 return;
1105 /* Enable QMP capabilities provided by the client if applicable. */
1106 if (has_enable) {
1107 qmp_caps_check(cur_mon, enable, &local_err);
1108 if (local_err) {
1110 * Failed check on any of the capabilities will fail the
1111 * entire command (and thus not apply any of the other
1112 * capabilities that were also requested).
1114 error_propagate(errp, local_err);
1115 return;
1117 qmp_caps_apply(cur_mon, enable);
1120 cur_mon->qmp.commands = &qmp_commands;
1123 /* set the current CPU defined by the user */
1124 int monitor_set_cpu(int cpu_index)
1126 CPUState *cpu;
1128 cpu = qemu_get_cpu(cpu_index);
1129 if (cpu == NULL) {
1130 return -1;
1132 g_free(cur_mon->mon_cpu_path);
1133 cur_mon->mon_cpu_path = object_get_canonical_path(OBJECT(cpu));
1134 return 0;
1137 static CPUState *mon_get_cpu_sync(bool synchronize)
1139 CPUState *cpu;
1141 if (cur_mon->mon_cpu_path) {
1142 cpu = (CPUState *) object_resolve_path_type(cur_mon->mon_cpu_path,
1143 TYPE_CPU, NULL);
1144 if (!cpu) {
1145 g_free(cur_mon->mon_cpu_path);
1146 cur_mon->mon_cpu_path = NULL;
1149 if (!cur_mon->mon_cpu_path) {
1150 if (!first_cpu) {
1151 return NULL;
1153 monitor_set_cpu(first_cpu->cpu_index);
1154 cpu = first_cpu;
1156 if (synchronize) {
1157 cpu_synchronize_state(cpu);
1159 return cpu;
1162 CPUState *mon_get_cpu(void)
1164 return mon_get_cpu_sync(true);
1167 CPUArchState *mon_get_cpu_env(void)
1169 CPUState *cs = mon_get_cpu();
1171 return cs ? cs->env_ptr : NULL;
1174 int monitor_get_cpu_index(void)
1176 CPUState *cs = mon_get_cpu_sync(false);
1178 return cs ? cs->cpu_index : UNASSIGNED_CPU_INDEX;
1181 static void hmp_info_registers(Monitor *mon, const QDict *qdict)
1183 bool all_cpus = qdict_get_try_bool(qdict, "cpustate_all", false);
1184 CPUState *cs;
1186 if (all_cpus) {
1187 CPU_FOREACH(cs) {
1188 monitor_printf(mon, "\nCPU#%d\n", cs->cpu_index);
1189 cpu_dump_state(cs, (FILE *)mon, monitor_fprintf, CPU_DUMP_FPU);
1191 } else {
1192 cs = mon_get_cpu();
1194 if (!cs) {
1195 monitor_printf(mon, "No CPU available\n");
1196 return;
1199 cpu_dump_state(cs, (FILE *)mon, monitor_fprintf, CPU_DUMP_FPU);
1203 #ifdef CONFIG_TCG
1204 static void hmp_info_jit(Monitor *mon, const QDict *qdict)
1206 if (!tcg_enabled()) {
1207 error_report("JIT information is only available with accel=tcg");
1208 return;
1211 dump_exec_info((FILE *)mon, monitor_fprintf);
1212 dump_drift_info((FILE *)mon, monitor_fprintf);
1215 static void hmp_info_opcount(Monitor *mon, const QDict *qdict)
1217 dump_opcount_info((FILE *)mon, monitor_fprintf);
1219 #endif
1221 static void hmp_info_history(Monitor *mon, const QDict *qdict)
1223 int i;
1224 const char *str;
1226 if (!mon->rs)
1227 return;
1228 i = 0;
1229 for(;;) {
1230 str = readline_get_history(mon->rs, i);
1231 if (!str)
1232 break;
1233 monitor_printf(mon, "%d: '%s'\n", i, str);
1234 i++;
1238 static void hmp_info_cpustats(Monitor *mon, const QDict *qdict)
1240 CPUState *cs = mon_get_cpu();
1242 if (!cs) {
1243 monitor_printf(mon, "No CPU available\n");
1244 return;
1246 cpu_dump_statistics(cs, (FILE *)mon, &monitor_fprintf, 0);
1249 static void hmp_info_trace_events(Monitor *mon, const QDict *qdict)
1251 const char *name = qdict_get_try_str(qdict, "name");
1252 bool has_vcpu = qdict_haskey(qdict, "vcpu");
1253 int vcpu = qdict_get_try_int(qdict, "vcpu", 0);
1254 TraceEventInfoList *events;
1255 TraceEventInfoList *elem;
1256 Error *local_err = NULL;
1258 if (name == NULL) {
1259 name = "*";
1261 if (vcpu < 0) {
1262 monitor_printf(mon, "argument vcpu must be positive");
1263 return;
1266 events = qmp_trace_event_get_state(name, has_vcpu, vcpu, &local_err);
1267 if (local_err) {
1268 error_report_err(local_err);
1269 return;
1272 for (elem = events; elem != NULL; elem = elem->next) {
1273 monitor_printf(mon, "%s : state %u\n",
1274 elem->value->name,
1275 elem->value->state == TRACE_EVENT_STATE_ENABLED ? 1 : 0);
1277 qapi_free_TraceEventInfoList(events);
1280 void qmp_client_migrate_info(const char *protocol, const char *hostname,
1281 bool has_port, int64_t port,
1282 bool has_tls_port, int64_t tls_port,
1283 bool has_cert_subject, const char *cert_subject,
1284 Error **errp)
1286 if (strcmp(protocol, "spice") == 0) {
1287 if (!qemu_using_spice(errp)) {
1288 return;
1291 if (!has_port && !has_tls_port) {
1292 error_setg(errp, QERR_MISSING_PARAMETER, "port/tls-port");
1293 return;
1296 if (qemu_spice_migrate_info(hostname,
1297 has_port ? port : -1,
1298 has_tls_port ? tls_port : -1,
1299 cert_subject)) {
1300 error_setg(errp, QERR_UNDEFINED_ERROR);
1301 return;
1303 return;
1306 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "protocol", "spice");
1309 static void hmp_logfile(Monitor *mon, const QDict *qdict)
1311 Error *err = NULL;
1313 qemu_set_log_filename(qdict_get_str(qdict, "filename"), &err);
1314 if (err) {
1315 error_report_err(err);
1319 static void hmp_log(Monitor *mon, const QDict *qdict)
1321 int mask;
1322 const char *items = qdict_get_str(qdict, "items");
1324 if (!strcmp(items, "none")) {
1325 mask = 0;
1326 } else {
1327 mask = qemu_str_to_log_mask(items);
1328 if (!mask) {
1329 help_cmd(mon, "log");
1330 return;
1333 qemu_set_log(mask);
1336 static void hmp_singlestep(Monitor *mon, const QDict *qdict)
1338 const char *option = qdict_get_try_str(qdict, "option");
1339 if (!option || !strcmp(option, "on")) {
1340 singlestep = 1;
1341 } else if (!strcmp(option, "off")) {
1342 singlestep = 0;
1343 } else {
1344 monitor_printf(mon, "unexpected option %s\n", option);
1348 static void hmp_gdbserver(Monitor *mon, const QDict *qdict)
1350 const char *device = qdict_get_try_str(qdict, "device");
1351 if (!device)
1352 device = "tcp::" DEFAULT_GDBSTUB_PORT;
1353 if (gdbserver_start(device) < 0) {
1354 monitor_printf(mon, "Could not open gdbserver on device '%s'\n",
1355 device);
1356 } else if (strcmp(device, "none") == 0) {
1357 monitor_printf(mon, "Disabled gdbserver\n");
1358 } else {
1359 monitor_printf(mon, "Waiting for gdb connection on device '%s'\n",
1360 device);
1364 static void hmp_watchdog_action(Monitor *mon, const QDict *qdict)
1366 const char *action = qdict_get_str(qdict, "action");
1367 if (select_watchdog_action(action) == -1) {
1368 monitor_printf(mon, "Unknown watchdog action '%s'\n", action);
1372 static void monitor_printc(Monitor *mon, int c)
1374 monitor_printf(mon, "'");
1375 switch(c) {
1376 case '\'':
1377 monitor_printf(mon, "\\'");
1378 break;
1379 case '\\':
1380 monitor_printf(mon, "\\\\");
1381 break;
1382 case '\n':
1383 monitor_printf(mon, "\\n");
1384 break;
1385 case '\r':
1386 monitor_printf(mon, "\\r");
1387 break;
1388 default:
1389 if (c >= 32 && c <= 126) {
1390 monitor_printf(mon, "%c", c);
1391 } else {
1392 monitor_printf(mon, "\\x%02x", c);
1394 break;
1396 monitor_printf(mon, "'");
1399 static void memory_dump(Monitor *mon, int count, int format, int wsize,
1400 hwaddr addr, int is_physical)
1402 int l, line_size, i, max_digits, len;
1403 uint8_t buf[16];
1404 uint64_t v;
1405 CPUState *cs = mon_get_cpu();
1407 if (!cs && (format == 'i' || !is_physical)) {
1408 monitor_printf(mon, "Can not dump without CPU\n");
1409 return;
1412 if (format == 'i') {
1413 monitor_disas(mon, cs, addr, count, is_physical);
1414 return;
1417 len = wsize * count;
1418 if (wsize == 1)
1419 line_size = 8;
1420 else
1421 line_size = 16;
1422 max_digits = 0;
1424 switch(format) {
1425 case 'o':
1426 max_digits = DIV_ROUND_UP(wsize * 8, 3);
1427 break;
1428 default:
1429 case 'x':
1430 max_digits = (wsize * 8) / 4;
1431 break;
1432 case 'u':
1433 case 'd':
1434 max_digits = DIV_ROUND_UP(wsize * 8 * 10, 33);
1435 break;
1436 case 'c':
1437 wsize = 1;
1438 break;
1441 while (len > 0) {
1442 if (is_physical)
1443 monitor_printf(mon, TARGET_FMT_plx ":", addr);
1444 else
1445 monitor_printf(mon, TARGET_FMT_lx ":", (target_ulong)addr);
1446 l = len;
1447 if (l > line_size)
1448 l = line_size;
1449 if (is_physical) {
1450 cpu_physical_memory_read(addr, buf, l);
1451 } else {
1452 if (cpu_memory_rw_debug(cs, addr, buf, l, 0) < 0) {
1453 monitor_printf(mon, " Cannot access memory\n");
1454 break;
1457 i = 0;
1458 while (i < l) {
1459 switch(wsize) {
1460 default:
1461 case 1:
1462 v = ldub_p(buf + i);
1463 break;
1464 case 2:
1465 v = lduw_p(buf + i);
1466 break;
1467 case 4:
1468 v = (uint32_t)ldl_p(buf + i);
1469 break;
1470 case 8:
1471 v = ldq_p(buf + i);
1472 break;
1474 monitor_printf(mon, " ");
1475 switch(format) {
1476 case 'o':
1477 monitor_printf(mon, "%#*" PRIo64, max_digits, v);
1478 break;
1479 case 'x':
1480 monitor_printf(mon, "0x%0*" PRIx64, max_digits, v);
1481 break;
1482 case 'u':
1483 monitor_printf(mon, "%*" PRIu64, max_digits, v);
1484 break;
1485 case 'd':
1486 monitor_printf(mon, "%*" PRId64, max_digits, v);
1487 break;
1488 case 'c':
1489 monitor_printc(mon, v);
1490 break;
1492 i += wsize;
1494 monitor_printf(mon, "\n");
1495 addr += l;
1496 len -= l;
1500 static void hmp_memory_dump(Monitor *mon, const QDict *qdict)
1502 int count = qdict_get_int(qdict, "count");
1503 int format = qdict_get_int(qdict, "format");
1504 int size = qdict_get_int(qdict, "size");
1505 target_long addr = qdict_get_int(qdict, "addr");
1507 memory_dump(mon, count, format, size, addr, 0);
1510 static void hmp_physical_memory_dump(Monitor *mon, const QDict *qdict)
1512 int count = qdict_get_int(qdict, "count");
1513 int format = qdict_get_int(qdict, "format");
1514 int size = qdict_get_int(qdict, "size");
1515 hwaddr addr = qdict_get_int(qdict, "addr");
1517 memory_dump(mon, count, format, size, addr, 1);
1520 static void *gpa2hva(MemoryRegion **p_mr, hwaddr addr, Error **errp)
1522 MemoryRegionSection mrs = memory_region_find(get_system_memory(),
1523 addr, 1);
1525 if (!mrs.mr) {
1526 error_setg(errp, "No memory is mapped at address 0x%" HWADDR_PRIx, addr);
1527 return NULL;
1530 if (!memory_region_is_ram(mrs.mr) && !memory_region_is_romd(mrs.mr)) {
1531 error_setg(errp, "Memory at address 0x%" HWADDR_PRIx "is not RAM", addr);
1532 memory_region_unref(mrs.mr);
1533 return NULL;
1536 *p_mr = mrs.mr;
1537 return qemu_map_ram_ptr(mrs.mr->ram_block, mrs.offset_within_region);
1540 static void hmp_gpa2hva(Monitor *mon, const QDict *qdict)
1542 hwaddr addr = qdict_get_int(qdict, "addr");
1543 Error *local_err = NULL;
1544 MemoryRegion *mr = NULL;
1545 void *ptr;
1547 ptr = gpa2hva(&mr, addr, &local_err);
1548 if (local_err) {
1549 error_report_err(local_err);
1550 return;
1553 monitor_printf(mon, "Host virtual address for 0x%" HWADDR_PRIx
1554 " (%s) is %p\n",
1555 addr, mr->name, ptr);
1557 memory_region_unref(mr);
1560 #ifdef CONFIG_LINUX
1561 static uint64_t vtop(void *ptr, Error **errp)
1563 uint64_t pinfo;
1564 uint64_t ret = -1;
1565 uintptr_t addr = (uintptr_t) ptr;
1566 uintptr_t pagesize = getpagesize();
1567 off_t offset = addr / pagesize * sizeof(pinfo);
1568 int fd;
1570 fd = open("/proc/self/pagemap", O_RDONLY);
1571 if (fd == -1) {
1572 error_setg_errno(errp, errno, "Cannot open /proc/self/pagemap");
1573 return -1;
1576 /* Force copy-on-write if necessary. */
1577 atomic_add((uint8_t *)ptr, 0);
1579 if (pread(fd, &pinfo, sizeof(pinfo), offset) != sizeof(pinfo)) {
1580 error_setg_errno(errp, errno, "Cannot read pagemap");
1581 goto out;
1583 if ((pinfo & (1ull << 63)) == 0) {
1584 error_setg(errp, "Page not present");
1585 goto out;
1587 ret = ((pinfo & 0x007fffffffffffffull) * pagesize) | (addr & (pagesize - 1));
1589 out:
1590 close(fd);
1591 return ret;
1594 static void hmp_gpa2hpa(Monitor *mon, const QDict *qdict)
1596 hwaddr addr = qdict_get_int(qdict, "addr");
1597 Error *local_err = NULL;
1598 MemoryRegion *mr = NULL;
1599 void *ptr;
1600 uint64_t physaddr;
1602 ptr = gpa2hva(&mr, addr, &local_err);
1603 if (local_err) {
1604 error_report_err(local_err);
1605 return;
1608 physaddr = vtop(ptr, &local_err);
1609 if (local_err) {
1610 error_report_err(local_err);
1611 } else {
1612 monitor_printf(mon, "Host physical address for 0x%" HWADDR_PRIx
1613 " (%s) is 0x%" PRIx64 "\n",
1614 addr, mr->name, (uint64_t) physaddr);
1617 memory_region_unref(mr);
1619 #endif
1621 static void do_print(Monitor *mon, const QDict *qdict)
1623 int format = qdict_get_int(qdict, "format");
1624 hwaddr val = qdict_get_int(qdict, "val");
1626 switch(format) {
1627 case 'o':
1628 monitor_printf(mon, "%#" HWADDR_PRIo, val);
1629 break;
1630 case 'x':
1631 monitor_printf(mon, "%#" HWADDR_PRIx, val);
1632 break;
1633 case 'u':
1634 monitor_printf(mon, "%" HWADDR_PRIu, val);
1635 break;
1636 default:
1637 case 'd':
1638 monitor_printf(mon, "%" HWADDR_PRId, val);
1639 break;
1640 case 'c':
1641 monitor_printc(mon, val);
1642 break;
1644 monitor_printf(mon, "\n");
1647 static void hmp_sum(Monitor *mon, const QDict *qdict)
1649 uint32_t addr;
1650 uint16_t sum;
1651 uint32_t start = qdict_get_int(qdict, "start");
1652 uint32_t size = qdict_get_int(qdict, "size");
1654 sum = 0;
1655 for(addr = start; addr < (start + size); addr++) {
1656 uint8_t val = address_space_ldub(&address_space_memory, addr,
1657 MEMTXATTRS_UNSPECIFIED, NULL);
1658 /* BSD sum algorithm ('sum' Unix command) */
1659 sum = (sum >> 1) | (sum << 15);
1660 sum += val;
1662 monitor_printf(mon, "%05d\n", sum);
1665 static int mouse_button_state;
1667 static void hmp_mouse_move(Monitor *mon, const QDict *qdict)
1669 int dx, dy, dz, button;
1670 const char *dx_str = qdict_get_str(qdict, "dx_str");
1671 const char *dy_str = qdict_get_str(qdict, "dy_str");
1672 const char *dz_str = qdict_get_try_str(qdict, "dz_str");
1674 dx = strtol(dx_str, NULL, 0);
1675 dy = strtol(dy_str, NULL, 0);
1676 qemu_input_queue_rel(NULL, INPUT_AXIS_X, dx);
1677 qemu_input_queue_rel(NULL, INPUT_AXIS_Y, dy);
1679 if (dz_str) {
1680 dz = strtol(dz_str, NULL, 0);
1681 if (dz != 0) {
1682 button = (dz > 0) ? INPUT_BUTTON_WHEEL_UP : INPUT_BUTTON_WHEEL_DOWN;
1683 qemu_input_queue_btn(NULL, button, true);
1684 qemu_input_event_sync();
1685 qemu_input_queue_btn(NULL, button, false);
1688 qemu_input_event_sync();
1691 static void hmp_mouse_button(Monitor *mon, const QDict *qdict)
1693 static uint32_t bmap[INPUT_BUTTON__MAX] = {
1694 [INPUT_BUTTON_LEFT] = MOUSE_EVENT_LBUTTON,
1695 [INPUT_BUTTON_MIDDLE] = MOUSE_EVENT_MBUTTON,
1696 [INPUT_BUTTON_RIGHT] = MOUSE_EVENT_RBUTTON,
1698 int button_state = qdict_get_int(qdict, "button_state");
1700 if (mouse_button_state == button_state) {
1701 return;
1703 qemu_input_update_buttons(NULL, bmap, mouse_button_state, button_state);
1704 qemu_input_event_sync();
1705 mouse_button_state = button_state;
1708 static void hmp_ioport_read(Monitor *mon, const QDict *qdict)
1710 int size = qdict_get_int(qdict, "size");
1711 int addr = qdict_get_int(qdict, "addr");
1712 int has_index = qdict_haskey(qdict, "index");
1713 uint32_t val;
1714 int suffix;
1716 if (has_index) {
1717 int index = qdict_get_int(qdict, "index");
1718 cpu_outb(addr & IOPORTS_MASK, index & 0xff);
1719 addr++;
1721 addr &= 0xffff;
1723 switch(size) {
1724 default:
1725 case 1:
1726 val = cpu_inb(addr);
1727 suffix = 'b';
1728 break;
1729 case 2:
1730 val = cpu_inw(addr);
1731 suffix = 'w';
1732 break;
1733 case 4:
1734 val = cpu_inl(addr);
1735 suffix = 'l';
1736 break;
1738 monitor_printf(mon, "port%c[0x%04x] = %#0*x\n",
1739 suffix, addr, size * 2, val);
1742 static void hmp_ioport_write(Monitor *mon, const QDict *qdict)
1744 int size = qdict_get_int(qdict, "size");
1745 int addr = qdict_get_int(qdict, "addr");
1746 int val = qdict_get_int(qdict, "val");
1748 addr &= IOPORTS_MASK;
1750 switch (size) {
1751 default:
1752 case 1:
1753 cpu_outb(addr, val);
1754 break;
1755 case 2:
1756 cpu_outw(addr, val);
1757 break;
1758 case 4:
1759 cpu_outl(addr, val);
1760 break;
1764 static void hmp_boot_set(Monitor *mon, const QDict *qdict)
1766 Error *local_err = NULL;
1767 const char *bootdevice = qdict_get_str(qdict, "bootdevice");
1769 qemu_boot_set(bootdevice, &local_err);
1770 if (local_err) {
1771 error_report_err(local_err);
1772 } else {
1773 monitor_printf(mon, "boot device list now set to %s\n", bootdevice);
1777 static void hmp_info_mtree(Monitor *mon, const QDict *qdict)
1779 bool flatview = qdict_get_try_bool(qdict, "flatview", false);
1780 bool dispatch_tree = qdict_get_try_bool(qdict, "dispatch_tree", false);
1782 mtree_info((fprintf_function)monitor_printf, mon, flatview, dispatch_tree);
1785 static void hmp_info_numa(Monitor *mon, const QDict *qdict)
1787 int i;
1788 NumaNodeMem *node_mem;
1789 CpuInfoList *cpu_list, *cpu;
1791 cpu_list = qmp_query_cpus(&error_abort);
1792 node_mem = g_new0(NumaNodeMem, nb_numa_nodes);
1794 query_numa_node_mem(node_mem);
1795 monitor_printf(mon, "%d nodes\n", nb_numa_nodes);
1796 for (i = 0; i < nb_numa_nodes; i++) {
1797 monitor_printf(mon, "node %d cpus:", i);
1798 for (cpu = cpu_list; cpu; cpu = cpu->next) {
1799 if (cpu->value->has_props && cpu->value->props->has_node_id &&
1800 cpu->value->props->node_id == i) {
1801 monitor_printf(mon, " %" PRIi64, cpu->value->CPU);
1804 monitor_printf(mon, "\n");
1805 monitor_printf(mon, "node %d size: %" PRId64 " MB\n", i,
1806 node_mem[i].node_mem >> 20);
1807 monitor_printf(mon, "node %d plugged: %" PRId64 " MB\n", i,
1808 node_mem[i].node_plugged_mem >> 20);
1810 qapi_free_CpuInfoList(cpu_list);
1811 g_free(node_mem);
1814 #ifdef CONFIG_PROFILER
1816 int64_t tcg_time;
1817 int64_t dev_time;
1819 static void hmp_info_profile(Monitor *mon, const QDict *qdict)
1821 monitor_printf(mon, "async time %" PRId64 " (%0.3f)\n",
1822 dev_time, dev_time / (double)NANOSECONDS_PER_SECOND);
1823 monitor_printf(mon, "qemu time %" PRId64 " (%0.3f)\n",
1824 tcg_time, tcg_time / (double)NANOSECONDS_PER_SECOND);
1825 tcg_time = 0;
1826 dev_time = 0;
1828 #else
1829 static void hmp_info_profile(Monitor *mon, const QDict *qdict)
1831 monitor_printf(mon, "Internal profiler not compiled\n");
1833 #endif
1835 /* Capture support */
1836 static QLIST_HEAD (capture_list_head, CaptureState) capture_head;
1838 static void hmp_info_capture(Monitor *mon, const QDict *qdict)
1840 int i;
1841 CaptureState *s;
1843 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
1844 monitor_printf(mon, "[%d]: ", i);
1845 s->ops.info (s->opaque);
1849 static void hmp_stopcapture(Monitor *mon, const QDict *qdict)
1851 int i;
1852 int n = qdict_get_int(qdict, "n");
1853 CaptureState *s;
1855 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
1856 if (i == n) {
1857 s->ops.destroy (s->opaque);
1858 QLIST_REMOVE (s, entries);
1859 g_free (s);
1860 return;
1865 static void hmp_wavcapture(Monitor *mon, const QDict *qdict)
1867 const char *path = qdict_get_str(qdict, "path");
1868 int has_freq = qdict_haskey(qdict, "freq");
1869 int freq = qdict_get_try_int(qdict, "freq", -1);
1870 int has_bits = qdict_haskey(qdict, "bits");
1871 int bits = qdict_get_try_int(qdict, "bits", -1);
1872 int has_channels = qdict_haskey(qdict, "nchannels");
1873 int nchannels = qdict_get_try_int(qdict, "nchannels", -1);
1874 CaptureState *s;
1876 s = g_malloc0 (sizeof (*s));
1878 freq = has_freq ? freq : 44100;
1879 bits = has_bits ? bits : 16;
1880 nchannels = has_channels ? nchannels : 2;
1882 if (wav_start_capture (s, path, freq, bits, nchannels)) {
1883 monitor_printf(mon, "Failed to add wave capture\n");
1884 g_free (s);
1885 return;
1887 QLIST_INSERT_HEAD (&capture_head, s, entries);
1890 static qemu_acl *find_acl(Monitor *mon, const char *name)
1892 qemu_acl *acl = qemu_acl_find(name);
1894 if (!acl) {
1895 monitor_printf(mon, "acl: unknown list '%s'\n", name);
1897 return acl;
1900 static void hmp_acl_show(Monitor *mon, const QDict *qdict)
1902 const char *aclname = qdict_get_str(qdict, "aclname");
1903 qemu_acl *acl = find_acl(mon, aclname);
1904 qemu_acl_entry *entry;
1905 int i = 0;
1907 if (acl) {
1908 monitor_printf(mon, "policy: %s\n",
1909 acl->defaultDeny ? "deny" : "allow");
1910 QTAILQ_FOREACH(entry, &acl->entries, next) {
1911 i++;
1912 monitor_printf(mon, "%d: %s %s\n", i,
1913 entry->deny ? "deny" : "allow", entry->match);
1918 static void hmp_acl_reset(Monitor *mon, const QDict *qdict)
1920 const char *aclname = qdict_get_str(qdict, "aclname");
1921 qemu_acl *acl = find_acl(mon, aclname);
1923 if (acl) {
1924 qemu_acl_reset(acl);
1925 monitor_printf(mon, "acl: removed all rules\n");
1929 static void hmp_acl_policy(Monitor *mon, const QDict *qdict)
1931 const char *aclname = qdict_get_str(qdict, "aclname");
1932 const char *policy = qdict_get_str(qdict, "policy");
1933 qemu_acl *acl = find_acl(mon, aclname);
1935 if (acl) {
1936 if (strcmp(policy, "allow") == 0) {
1937 acl->defaultDeny = 0;
1938 monitor_printf(mon, "acl: policy set to 'allow'\n");
1939 } else if (strcmp(policy, "deny") == 0) {
1940 acl->defaultDeny = 1;
1941 monitor_printf(mon, "acl: policy set to 'deny'\n");
1942 } else {
1943 monitor_printf(mon, "acl: unknown policy '%s', "
1944 "expected 'deny' or 'allow'\n", policy);
1949 static void hmp_acl_add(Monitor *mon, const QDict *qdict)
1951 const char *aclname = qdict_get_str(qdict, "aclname");
1952 const char *match = qdict_get_str(qdict, "match");
1953 const char *policy = qdict_get_str(qdict, "policy");
1954 int has_index = qdict_haskey(qdict, "index");
1955 int index = qdict_get_try_int(qdict, "index", -1);
1956 qemu_acl *acl = find_acl(mon, aclname);
1957 int deny, ret;
1959 if (acl) {
1960 if (strcmp(policy, "allow") == 0) {
1961 deny = 0;
1962 } else if (strcmp(policy, "deny") == 0) {
1963 deny = 1;
1964 } else {
1965 monitor_printf(mon, "acl: unknown policy '%s', "
1966 "expected 'deny' or 'allow'\n", policy);
1967 return;
1969 if (has_index)
1970 ret = qemu_acl_insert(acl, deny, match, index);
1971 else
1972 ret = qemu_acl_append(acl, deny, match);
1973 if (ret < 0)
1974 monitor_printf(mon, "acl: unable to add acl entry\n");
1975 else
1976 monitor_printf(mon, "acl: added rule at position %d\n", ret);
1980 static void hmp_acl_remove(Monitor *mon, const QDict *qdict)
1982 const char *aclname = qdict_get_str(qdict, "aclname");
1983 const char *match = qdict_get_str(qdict, "match");
1984 qemu_acl *acl = find_acl(mon, aclname);
1985 int ret;
1987 if (acl) {
1988 ret = qemu_acl_remove(acl, match);
1989 if (ret < 0)
1990 monitor_printf(mon, "acl: no matching acl entry\n");
1991 else
1992 monitor_printf(mon, "acl: removed rule at position %d\n", ret);
1996 void qmp_getfd(const char *fdname, Error **errp)
1998 mon_fd_t *monfd;
1999 int fd;
2001 fd = qemu_chr_fe_get_msgfd(&cur_mon->chr);
2002 if (fd == -1) {
2003 error_setg(errp, QERR_FD_NOT_SUPPLIED);
2004 return;
2007 if (qemu_isdigit(fdname[0])) {
2008 close(fd);
2009 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "fdname",
2010 "a name not starting with a digit");
2011 return;
2014 QLIST_FOREACH(monfd, &cur_mon->fds, next) {
2015 if (strcmp(monfd->name, fdname) != 0) {
2016 continue;
2019 close(monfd->fd);
2020 monfd->fd = fd;
2021 return;
2024 monfd = g_malloc0(sizeof(mon_fd_t));
2025 monfd->name = g_strdup(fdname);
2026 monfd->fd = fd;
2028 QLIST_INSERT_HEAD(&cur_mon->fds, monfd, next);
2031 void qmp_closefd(const char *fdname, Error **errp)
2033 mon_fd_t *monfd;
2035 QLIST_FOREACH(monfd, &cur_mon->fds, next) {
2036 if (strcmp(monfd->name, fdname) != 0) {
2037 continue;
2040 QLIST_REMOVE(monfd, next);
2041 close(monfd->fd);
2042 g_free(monfd->name);
2043 g_free(monfd);
2044 return;
2047 error_setg(errp, QERR_FD_NOT_FOUND, fdname);
2050 int monitor_get_fd(Monitor *mon, const char *fdname, Error **errp)
2052 mon_fd_t *monfd;
2054 QLIST_FOREACH(monfd, &mon->fds, next) {
2055 int fd;
2057 if (strcmp(monfd->name, fdname) != 0) {
2058 continue;
2061 fd = monfd->fd;
2063 /* caller takes ownership of fd */
2064 QLIST_REMOVE(monfd, next);
2065 g_free(monfd->name);
2066 g_free(monfd);
2068 return fd;
2071 error_setg(errp, "File descriptor named '%s' has not been found", fdname);
2072 return -1;
2075 static void monitor_fdset_cleanup(MonFdset *mon_fdset)
2077 MonFdsetFd *mon_fdset_fd;
2078 MonFdsetFd *mon_fdset_fd_next;
2080 QLIST_FOREACH_SAFE(mon_fdset_fd, &mon_fdset->fds, next, mon_fdset_fd_next) {
2081 if ((mon_fdset_fd->removed ||
2082 (QLIST_EMPTY(&mon_fdset->dup_fds) && mon_refcount == 0)) &&
2083 runstate_is_running()) {
2084 close(mon_fdset_fd->fd);
2085 g_free(mon_fdset_fd->opaque);
2086 QLIST_REMOVE(mon_fdset_fd, next);
2087 g_free(mon_fdset_fd);
2091 if (QLIST_EMPTY(&mon_fdset->fds) && QLIST_EMPTY(&mon_fdset->dup_fds)) {
2092 QLIST_REMOVE(mon_fdset, next);
2093 g_free(mon_fdset);
2097 static void monitor_fdsets_cleanup(void)
2099 MonFdset *mon_fdset;
2100 MonFdset *mon_fdset_next;
2102 QLIST_FOREACH_SAFE(mon_fdset, &mon_fdsets, next, mon_fdset_next) {
2103 monitor_fdset_cleanup(mon_fdset);
2107 AddfdInfo *qmp_add_fd(bool has_fdset_id, int64_t fdset_id, bool has_opaque,
2108 const char *opaque, Error **errp)
2110 int fd;
2111 Monitor *mon = cur_mon;
2112 AddfdInfo *fdinfo;
2114 fd = qemu_chr_fe_get_msgfd(&mon->chr);
2115 if (fd == -1) {
2116 error_setg(errp, QERR_FD_NOT_SUPPLIED);
2117 goto error;
2120 fdinfo = monitor_fdset_add_fd(fd, has_fdset_id, fdset_id,
2121 has_opaque, opaque, errp);
2122 if (fdinfo) {
2123 return fdinfo;
2126 error:
2127 if (fd != -1) {
2128 close(fd);
2130 return NULL;
2133 void qmp_remove_fd(int64_t fdset_id, bool has_fd, int64_t fd, Error **errp)
2135 MonFdset *mon_fdset;
2136 MonFdsetFd *mon_fdset_fd;
2137 char fd_str[60];
2139 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2140 if (mon_fdset->id != fdset_id) {
2141 continue;
2143 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2144 if (has_fd) {
2145 if (mon_fdset_fd->fd != fd) {
2146 continue;
2148 mon_fdset_fd->removed = true;
2149 break;
2150 } else {
2151 mon_fdset_fd->removed = true;
2154 if (has_fd && !mon_fdset_fd) {
2155 goto error;
2157 monitor_fdset_cleanup(mon_fdset);
2158 return;
2161 error:
2162 if (has_fd) {
2163 snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64 ", fd:%" PRId64,
2164 fdset_id, fd);
2165 } else {
2166 snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64, fdset_id);
2168 error_setg(errp, QERR_FD_NOT_FOUND, fd_str);
2171 FdsetInfoList *qmp_query_fdsets(Error **errp)
2173 MonFdset *mon_fdset;
2174 MonFdsetFd *mon_fdset_fd;
2175 FdsetInfoList *fdset_list = NULL;
2177 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2178 FdsetInfoList *fdset_info = g_malloc0(sizeof(*fdset_info));
2179 FdsetFdInfoList *fdsetfd_list = NULL;
2181 fdset_info->value = g_malloc0(sizeof(*fdset_info->value));
2182 fdset_info->value->fdset_id = mon_fdset->id;
2184 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2185 FdsetFdInfoList *fdsetfd_info;
2187 fdsetfd_info = g_malloc0(sizeof(*fdsetfd_info));
2188 fdsetfd_info->value = g_malloc0(sizeof(*fdsetfd_info->value));
2189 fdsetfd_info->value->fd = mon_fdset_fd->fd;
2190 if (mon_fdset_fd->opaque) {
2191 fdsetfd_info->value->has_opaque = true;
2192 fdsetfd_info->value->opaque = g_strdup(mon_fdset_fd->opaque);
2193 } else {
2194 fdsetfd_info->value->has_opaque = false;
2197 fdsetfd_info->next = fdsetfd_list;
2198 fdsetfd_list = fdsetfd_info;
2201 fdset_info->value->fds = fdsetfd_list;
2203 fdset_info->next = fdset_list;
2204 fdset_list = fdset_info;
2207 return fdset_list;
2210 AddfdInfo *monitor_fdset_add_fd(int fd, bool has_fdset_id, int64_t fdset_id,
2211 bool has_opaque, const char *opaque,
2212 Error **errp)
2214 MonFdset *mon_fdset = NULL;
2215 MonFdsetFd *mon_fdset_fd;
2216 AddfdInfo *fdinfo;
2218 if (has_fdset_id) {
2219 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2220 /* Break if match found or match impossible due to ordering by ID */
2221 if (fdset_id <= mon_fdset->id) {
2222 if (fdset_id < mon_fdset->id) {
2223 mon_fdset = NULL;
2225 break;
2230 if (mon_fdset == NULL) {
2231 int64_t fdset_id_prev = -1;
2232 MonFdset *mon_fdset_cur = QLIST_FIRST(&mon_fdsets);
2234 if (has_fdset_id) {
2235 if (fdset_id < 0) {
2236 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "fdset-id",
2237 "a non-negative value");
2238 return NULL;
2240 /* Use specified fdset ID */
2241 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2242 mon_fdset_cur = mon_fdset;
2243 if (fdset_id < mon_fdset_cur->id) {
2244 break;
2247 } else {
2248 /* Use first available fdset ID */
2249 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2250 mon_fdset_cur = mon_fdset;
2251 if (fdset_id_prev == mon_fdset_cur->id - 1) {
2252 fdset_id_prev = mon_fdset_cur->id;
2253 continue;
2255 break;
2259 mon_fdset = g_malloc0(sizeof(*mon_fdset));
2260 if (has_fdset_id) {
2261 mon_fdset->id = fdset_id;
2262 } else {
2263 mon_fdset->id = fdset_id_prev + 1;
2266 /* The fdset list is ordered by fdset ID */
2267 if (!mon_fdset_cur) {
2268 QLIST_INSERT_HEAD(&mon_fdsets, mon_fdset, next);
2269 } else if (mon_fdset->id < mon_fdset_cur->id) {
2270 QLIST_INSERT_BEFORE(mon_fdset_cur, mon_fdset, next);
2271 } else {
2272 QLIST_INSERT_AFTER(mon_fdset_cur, mon_fdset, next);
2276 mon_fdset_fd = g_malloc0(sizeof(*mon_fdset_fd));
2277 mon_fdset_fd->fd = fd;
2278 mon_fdset_fd->removed = false;
2279 if (has_opaque) {
2280 mon_fdset_fd->opaque = g_strdup(opaque);
2282 QLIST_INSERT_HEAD(&mon_fdset->fds, mon_fdset_fd, next);
2284 fdinfo = g_malloc0(sizeof(*fdinfo));
2285 fdinfo->fdset_id = mon_fdset->id;
2286 fdinfo->fd = mon_fdset_fd->fd;
2288 return fdinfo;
2291 int monitor_fdset_get_fd(int64_t fdset_id, int flags)
2293 #ifndef _WIN32
2294 MonFdset *mon_fdset;
2295 MonFdsetFd *mon_fdset_fd;
2296 int mon_fd_flags;
2298 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2299 if (mon_fdset->id != fdset_id) {
2300 continue;
2302 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2303 mon_fd_flags = fcntl(mon_fdset_fd->fd, F_GETFL);
2304 if (mon_fd_flags == -1) {
2305 return -1;
2308 if ((flags & O_ACCMODE) == (mon_fd_flags & O_ACCMODE)) {
2309 return mon_fdset_fd->fd;
2312 errno = EACCES;
2313 return -1;
2315 #endif
2317 errno = ENOENT;
2318 return -1;
2321 int monitor_fdset_dup_fd_add(int64_t fdset_id, int dup_fd)
2323 MonFdset *mon_fdset;
2324 MonFdsetFd *mon_fdset_fd_dup;
2326 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2327 if (mon_fdset->id != fdset_id) {
2328 continue;
2330 QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
2331 if (mon_fdset_fd_dup->fd == dup_fd) {
2332 return -1;
2335 mon_fdset_fd_dup = g_malloc0(sizeof(*mon_fdset_fd_dup));
2336 mon_fdset_fd_dup->fd = dup_fd;
2337 QLIST_INSERT_HEAD(&mon_fdset->dup_fds, mon_fdset_fd_dup, next);
2338 return 0;
2340 return -1;
2343 static int monitor_fdset_dup_fd_find_remove(int dup_fd, bool remove)
2345 MonFdset *mon_fdset;
2346 MonFdsetFd *mon_fdset_fd_dup;
2348 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2349 QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
2350 if (mon_fdset_fd_dup->fd == dup_fd) {
2351 if (remove) {
2352 QLIST_REMOVE(mon_fdset_fd_dup, next);
2353 if (QLIST_EMPTY(&mon_fdset->dup_fds)) {
2354 monitor_fdset_cleanup(mon_fdset);
2356 return -1;
2357 } else {
2358 return mon_fdset->id;
2363 return -1;
2366 int monitor_fdset_dup_fd_find(int dup_fd)
2368 return monitor_fdset_dup_fd_find_remove(dup_fd, false);
2371 void monitor_fdset_dup_fd_remove(int dup_fd)
2373 monitor_fdset_dup_fd_find_remove(dup_fd, true);
2376 int monitor_fd_param(Monitor *mon, const char *fdname, Error **errp)
2378 int fd;
2379 Error *local_err = NULL;
2381 if (!qemu_isdigit(fdname[0]) && mon) {
2382 fd = monitor_get_fd(mon, fdname, &local_err);
2383 } else {
2384 fd = qemu_parse_fd(fdname);
2385 if (fd == -1) {
2386 error_setg(&local_err, "Invalid file descriptor number '%s'",
2387 fdname);
2390 if (local_err) {
2391 error_propagate(errp, local_err);
2392 assert(fd == -1);
2393 } else {
2394 assert(fd != -1);
2397 return fd;
2400 /* Please update hmp-commands.hx when adding or changing commands */
2401 static mon_cmd_t info_cmds[] = {
2402 #include "hmp-commands-info.h"
2403 { NULL, NULL, },
2406 /* mon_cmds and info_cmds would be sorted at runtime */
2407 static mon_cmd_t mon_cmds[] = {
2408 #include "hmp-commands.h"
2409 { NULL, NULL, },
2412 /*******************************************************************/
2414 static const char *pch;
2415 static sigjmp_buf expr_env;
2418 static void GCC_FMT_ATTR(2, 3) QEMU_NORETURN
2419 expr_error(Monitor *mon, const char *fmt, ...)
2421 va_list ap;
2422 va_start(ap, fmt);
2423 monitor_vprintf(mon, fmt, ap);
2424 monitor_printf(mon, "\n");
2425 va_end(ap);
2426 siglongjmp(expr_env, 1);
2429 /* return 0 if OK, -1 if not found */
2430 static int get_monitor_def(target_long *pval, const char *name)
2432 const MonitorDef *md = target_monitor_defs();
2433 CPUState *cs = mon_get_cpu();
2434 void *ptr;
2435 uint64_t tmp = 0;
2436 int ret;
2438 if (cs == NULL || md == NULL) {
2439 return -1;
2442 for(; md->name != NULL; md++) {
2443 if (compare_cmd(name, md->name)) {
2444 if (md->get_value) {
2445 *pval = md->get_value(md, md->offset);
2446 } else {
2447 CPUArchState *env = mon_get_cpu_env();
2448 ptr = (uint8_t *)env + md->offset;
2449 switch(md->type) {
2450 case MD_I32:
2451 *pval = *(int32_t *)ptr;
2452 break;
2453 case MD_TLONG:
2454 *pval = *(target_long *)ptr;
2455 break;
2456 default:
2457 *pval = 0;
2458 break;
2461 return 0;
2465 ret = target_get_monitor_def(cs, name, &tmp);
2466 if (!ret) {
2467 *pval = (target_long) tmp;
2470 return ret;
2473 static void next(void)
2475 if (*pch != '\0') {
2476 pch++;
2477 while (qemu_isspace(*pch))
2478 pch++;
2482 static int64_t expr_sum(Monitor *mon);
2484 static int64_t expr_unary(Monitor *mon)
2486 int64_t n;
2487 char *p;
2488 int ret;
2490 switch(*pch) {
2491 case '+':
2492 next();
2493 n = expr_unary(mon);
2494 break;
2495 case '-':
2496 next();
2497 n = -expr_unary(mon);
2498 break;
2499 case '~':
2500 next();
2501 n = ~expr_unary(mon);
2502 break;
2503 case '(':
2504 next();
2505 n = expr_sum(mon);
2506 if (*pch != ')') {
2507 expr_error(mon, "')' expected");
2509 next();
2510 break;
2511 case '\'':
2512 pch++;
2513 if (*pch == '\0')
2514 expr_error(mon, "character constant expected");
2515 n = *pch;
2516 pch++;
2517 if (*pch != '\'')
2518 expr_error(mon, "missing terminating \' character");
2519 next();
2520 break;
2521 case '$':
2523 char buf[128], *q;
2524 target_long reg=0;
2526 pch++;
2527 q = buf;
2528 while ((*pch >= 'a' && *pch <= 'z') ||
2529 (*pch >= 'A' && *pch <= 'Z') ||
2530 (*pch >= '0' && *pch <= '9') ||
2531 *pch == '_' || *pch == '.') {
2532 if ((q - buf) < sizeof(buf) - 1)
2533 *q++ = *pch;
2534 pch++;
2536 while (qemu_isspace(*pch))
2537 pch++;
2538 *q = 0;
2539 ret = get_monitor_def(&reg, buf);
2540 if (ret < 0)
2541 expr_error(mon, "unknown register");
2542 n = reg;
2544 break;
2545 case '\0':
2546 expr_error(mon, "unexpected end of expression");
2547 n = 0;
2548 break;
2549 default:
2550 errno = 0;
2551 n = strtoull(pch, &p, 0);
2552 if (errno == ERANGE) {
2553 expr_error(mon, "number too large");
2555 if (pch == p) {
2556 expr_error(mon, "invalid char '%c' in expression", *p);
2558 pch = p;
2559 while (qemu_isspace(*pch))
2560 pch++;
2561 break;
2563 return n;
2567 static int64_t expr_prod(Monitor *mon)
2569 int64_t val, val2;
2570 int op;
2572 val = expr_unary(mon);
2573 for(;;) {
2574 op = *pch;
2575 if (op != '*' && op != '/' && op != '%')
2576 break;
2577 next();
2578 val2 = expr_unary(mon);
2579 switch(op) {
2580 default:
2581 case '*':
2582 val *= val2;
2583 break;
2584 case '/':
2585 case '%':
2586 if (val2 == 0)
2587 expr_error(mon, "division by zero");
2588 if (op == '/')
2589 val /= val2;
2590 else
2591 val %= val2;
2592 break;
2595 return val;
2598 static int64_t expr_logic(Monitor *mon)
2600 int64_t val, val2;
2601 int op;
2603 val = expr_prod(mon);
2604 for(;;) {
2605 op = *pch;
2606 if (op != '&' && op != '|' && op != '^')
2607 break;
2608 next();
2609 val2 = expr_prod(mon);
2610 switch(op) {
2611 default:
2612 case '&':
2613 val &= val2;
2614 break;
2615 case '|':
2616 val |= val2;
2617 break;
2618 case '^':
2619 val ^= val2;
2620 break;
2623 return val;
2626 static int64_t expr_sum(Monitor *mon)
2628 int64_t val, val2;
2629 int op;
2631 val = expr_logic(mon);
2632 for(;;) {
2633 op = *pch;
2634 if (op != '+' && op != '-')
2635 break;
2636 next();
2637 val2 = expr_logic(mon);
2638 if (op == '+')
2639 val += val2;
2640 else
2641 val -= val2;
2643 return val;
2646 static int get_expr(Monitor *mon, int64_t *pval, const char **pp)
2648 pch = *pp;
2649 if (sigsetjmp(expr_env, 0)) {
2650 *pp = pch;
2651 return -1;
2653 while (qemu_isspace(*pch))
2654 pch++;
2655 *pval = expr_sum(mon);
2656 *pp = pch;
2657 return 0;
2660 static int get_double(Monitor *mon, double *pval, const char **pp)
2662 const char *p = *pp;
2663 char *tailp;
2664 double d;
2666 d = strtod(p, &tailp);
2667 if (tailp == p) {
2668 monitor_printf(mon, "Number expected\n");
2669 return -1;
2671 if (d != d || d - d != 0) {
2672 /* NaN or infinity */
2673 monitor_printf(mon, "Bad number\n");
2674 return -1;
2676 *pval = d;
2677 *pp = tailp;
2678 return 0;
2682 * Store the command-name in cmdname, and return a pointer to
2683 * the remaining of the command string.
2685 static const char *get_command_name(const char *cmdline,
2686 char *cmdname, size_t nlen)
2688 size_t len;
2689 const char *p, *pstart;
2691 p = cmdline;
2692 while (qemu_isspace(*p))
2693 p++;
2694 if (*p == '\0')
2695 return NULL;
2696 pstart = p;
2697 while (*p != '\0' && *p != '/' && !qemu_isspace(*p))
2698 p++;
2699 len = p - pstart;
2700 if (len > nlen - 1)
2701 len = nlen - 1;
2702 memcpy(cmdname, pstart, len);
2703 cmdname[len] = '\0';
2704 return p;
2708 * Read key of 'type' into 'key' and return the current
2709 * 'type' pointer.
2711 static char *key_get_info(const char *type, char **key)
2713 size_t len;
2714 char *p, *str;
2716 if (*type == ',')
2717 type++;
2719 p = strchr(type, ':');
2720 if (!p) {
2721 *key = NULL;
2722 return NULL;
2724 len = p - type;
2726 str = g_malloc(len + 1);
2727 memcpy(str, type, len);
2728 str[len] = '\0';
2730 *key = str;
2731 return ++p;
2734 static int default_fmt_format = 'x';
2735 static int default_fmt_size = 4;
2737 static int is_valid_option(const char *c, const char *typestr)
2739 char option[3];
2741 option[0] = '-';
2742 option[1] = *c;
2743 option[2] = '\0';
2745 typestr = strstr(typestr, option);
2746 return (typestr != NULL);
2749 static const mon_cmd_t *search_dispatch_table(const mon_cmd_t *disp_table,
2750 const char *cmdname)
2752 const mon_cmd_t *cmd;
2754 for (cmd = disp_table; cmd->name != NULL; cmd++) {
2755 if (compare_cmd(cmdname, cmd->name)) {
2756 return cmd;
2760 return NULL;
2764 * Parse command name from @cmdp according to command table @table.
2765 * If blank, return NULL.
2766 * Else, if no valid command can be found, report to @mon, and return
2767 * NULL.
2768 * Else, change @cmdp to point right behind the name, and return its
2769 * command table entry.
2770 * Do not assume the return value points into @table! It doesn't when
2771 * the command is found in a sub-command table.
2773 static const mon_cmd_t *monitor_parse_command(Monitor *mon,
2774 const char *cmdp_start,
2775 const char **cmdp,
2776 mon_cmd_t *table)
2778 const char *p;
2779 const mon_cmd_t *cmd;
2780 char cmdname[256];
2782 /* extract the command name */
2783 p = get_command_name(*cmdp, cmdname, sizeof(cmdname));
2784 if (!p)
2785 return NULL;
2787 cmd = search_dispatch_table(table, cmdname);
2788 if (!cmd) {
2789 monitor_printf(mon, "unknown command: '%.*s'\n",
2790 (int)(p - cmdp_start), cmdp_start);
2791 return NULL;
2794 /* filter out following useless space */
2795 while (qemu_isspace(*p)) {
2796 p++;
2799 *cmdp = p;
2800 /* search sub command */
2801 if (cmd->sub_table != NULL && *p != '\0') {
2802 return monitor_parse_command(mon, cmdp_start, cmdp, cmd->sub_table);
2805 return cmd;
2809 * Parse arguments for @cmd.
2810 * If it can't be parsed, report to @mon, and return NULL.
2811 * Else, insert command arguments into a QDict, and return it.
2812 * Note: On success, caller has to free the QDict structure.
2815 static QDict *monitor_parse_arguments(Monitor *mon,
2816 const char **endp,
2817 const mon_cmd_t *cmd)
2819 const char *typestr;
2820 char *key;
2821 int c;
2822 const char *p = *endp;
2823 char buf[1024];
2824 QDict *qdict = qdict_new();
2826 /* parse the parameters */
2827 typestr = cmd->args_type;
2828 for(;;) {
2829 typestr = key_get_info(typestr, &key);
2830 if (!typestr)
2831 break;
2832 c = *typestr;
2833 typestr++;
2834 switch(c) {
2835 case 'F':
2836 case 'B':
2837 case 's':
2839 int ret;
2841 while (qemu_isspace(*p))
2842 p++;
2843 if (*typestr == '?') {
2844 typestr++;
2845 if (*p == '\0') {
2846 /* no optional string: NULL argument */
2847 break;
2850 ret = get_str(buf, sizeof(buf), &p);
2851 if (ret < 0) {
2852 switch(c) {
2853 case 'F':
2854 monitor_printf(mon, "%s: filename expected\n",
2855 cmd->name);
2856 break;
2857 case 'B':
2858 monitor_printf(mon, "%s: block device name expected\n",
2859 cmd->name);
2860 break;
2861 default:
2862 monitor_printf(mon, "%s: string expected\n", cmd->name);
2863 break;
2865 goto fail;
2867 qdict_put_str(qdict, key, buf);
2869 break;
2870 case 'O':
2872 QemuOptsList *opts_list;
2873 QemuOpts *opts;
2875 opts_list = qemu_find_opts(key);
2876 if (!opts_list || opts_list->desc->name) {
2877 goto bad_type;
2879 while (qemu_isspace(*p)) {
2880 p++;
2882 if (!*p)
2883 break;
2884 if (get_str(buf, sizeof(buf), &p) < 0) {
2885 goto fail;
2887 opts = qemu_opts_parse_noisily(opts_list, buf, true);
2888 if (!opts) {
2889 goto fail;
2891 qemu_opts_to_qdict(opts, qdict);
2892 qemu_opts_del(opts);
2894 break;
2895 case '/':
2897 int count, format, size;
2899 while (qemu_isspace(*p))
2900 p++;
2901 if (*p == '/') {
2902 /* format found */
2903 p++;
2904 count = 1;
2905 if (qemu_isdigit(*p)) {
2906 count = 0;
2907 while (qemu_isdigit(*p)) {
2908 count = count * 10 + (*p - '0');
2909 p++;
2912 size = -1;
2913 format = -1;
2914 for(;;) {
2915 switch(*p) {
2916 case 'o':
2917 case 'd':
2918 case 'u':
2919 case 'x':
2920 case 'i':
2921 case 'c':
2922 format = *p++;
2923 break;
2924 case 'b':
2925 size = 1;
2926 p++;
2927 break;
2928 case 'h':
2929 size = 2;
2930 p++;
2931 break;
2932 case 'w':
2933 size = 4;
2934 p++;
2935 break;
2936 case 'g':
2937 case 'L':
2938 size = 8;
2939 p++;
2940 break;
2941 default:
2942 goto next;
2945 next:
2946 if (*p != '\0' && !qemu_isspace(*p)) {
2947 monitor_printf(mon, "invalid char in format: '%c'\n",
2948 *p);
2949 goto fail;
2951 if (format < 0)
2952 format = default_fmt_format;
2953 if (format != 'i') {
2954 /* for 'i', not specifying a size gives -1 as size */
2955 if (size < 0)
2956 size = default_fmt_size;
2957 default_fmt_size = size;
2959 default_fmt_format = format;
2960 } else {
2961 count = 1;
2962 format = default_fmt_format;
2963 if (format != 'i') {
2964 size = default_fmt_size;
2965 } else {
2966 size = -1;
2969 qdict_put_int(qdict, "count", count);
2970 qdict_put_int(qdict, "format", format);
2971 qdict_put_int(qdict, "size", size);
2973 break;
2974 case 'i':
2975 case 'l':
2976 case 'M':
2978 int64_t val;
2980 while (qemu_isspace(*p))
2981 p++;
2982 if (*typestr == '?' || *typestr == '.') {
2983 if (*typestr == '?') {
2984 if (*p == '\0') {
2985 typestr++;
2986 break;
2988 } else {
2989 if (*p == '.') {
2990 p++;
2991 while (qemu_isspace(*p))
2992 p++;
2993 } else {
2994 typestr++;
2995 break;
2998 typestr++;
3000 if (get_expr(mon, &val, &p))
3001 goto fail;
3002 /* Check if 'i' is greater than 32-bit */
3003 if ((c == 'i') && ((val >> 32) & 0xffffffff)) {
3004 monitor_printf(mon, "\'%s\' has failed: ", cmd->name);
3005 monitor_printf(mon, "integer is for 32-bit values\n");
3006 goto fail;
3007 } else if (c == 'M') {
3008 if (val < 0) {
3009 monitor_printf(mon, "enter a positive value\n");
3010 goto fail;
3012 val <<= 20;
3014 qdict_put_int(qdict, key, val);
3016 break;
3017 case 'o':
3019 int ret;
3020 uint64_t val;
3021 char *end;
3023 while (qemu_isspace(*p)) {
3024 p++;
3026 if (*typestr == '?') {
3027 typestr++;
3028 if (*p == '\0') {
3029 break;
3032 ret = qemu_strtosz_MiB(p, &end, &val);
3033 if (ret < 0 || val > INT64_MAX) {
3034 monitor_printf(mon, "invalid size\n");
3035 goto fail;
3037 qdict_put_int(qdict, key, val);
3038 p = end;
3040 break;
3041 case 'T':
3043 double val;
3045 while (qemu_isspace(*p))
3046 p++;
3047 if (*typestr == '?') {
3048 typestr++;
3049 if (*p == '\0') {
3050 break;
3053 if (get_double(mon, &val, &p) < 0) {
3054 goto fail;
3056 if (p[0] && p[1] == 's') {
3057 switch (*p) {
3058 case 'm':
3059 val /= 1e3; p += 2; break;
3060 case 'u':
3061 val /= 1e6; p += 2; break;
3062 case 'n':
3063 val /= 1e9; p += 2; break;
3066 if (*p && !qemu_isspace(*p)) {
3067 monitor_printf(mon, "Unknown unit suffix\n");
3068 goto fail;
3070 qdict_put(qdict, key, qnum_from_double(val));
3072 break;
3073 case 'b':
3075 const char *beg;
3076 bool val;
3078 while (qemu_isspace(*p)) {
3079 p++;
3081 beg = p;
3082 while (qemu_isgraph(*p)) {
3083 p++;
3085 if (p - beg == 2 && !memcmp(beg, "on", p - beg)) {
3086 val = true;
3087 } else if (p - beg == 3 && !memcmp(beg, "off", p - beg)) {
3088 val = false;
3089 } else {
3090 monitor_printf(mon, "Expected 'on' or 'off'\n");
3091 goto fail;
3093 qdict_put_bool(qdict, key, val);
3095 break;
3096 case '-':
3098 const char *tmp = p;
3099 int skip_key = 0;
3100 /* option */
3102 c = *typestr++;
3103 if (c == '\0')
3104 goto bad_type;
3105 while (qemu_isspace(*p))
3106 p++;
3107 if (*p == '-') {
3108 p++;
3109 if(c != *p) {
3110 if(!is_valid_option(p, typestr)) {
3112 monitor_printf(mon, "%s: unsupported option -%c\n",
3113 cmd->name, *p);
3114 goto fail;
3115 } else {
3116 skip_key = 1;
3119 if(skip_key) {
3120 p = tmp;
3121 } else {
3122 /* has option */
3123 p++;
3124 qdict_put_bool(qdict, key, true);
3128 break;
3129 case 'S':
3131 /* package all remaining string */
3132 int len;
3134 while (qemu_isspace(*p)) {
3135 p++;
3137 if (*typestr == '?') {
3138 typestr++;
3139 if (*p == '\0') {
3140 /* no remaining string: NULL argument */
3141 break;
3144 len = strlen(p);
3145 if (len <= 0) {
3146 monitor_printf(mon, "%s: string expected\n",
3147 cmd->name);
3148 goto fail;
3150 qdict_put_str(qdict, key, p);
3151 p += len;
3153 break;
3154 default:
3155 bad_type:
3156 monitor_printf(mon, "%s: unknown type '%c'\n", cmd->name, c);
3157 goto fail;
3159 g_free(key);
3160 key = NULL;
3162 /* check that all arguments were parsed */
3163 while (qemu_isspace(*p))
3164 p++;
3165 if (*p != '\0') {
3166 monitor_printf(mon, "%s: extraneous characters at the end of line\n",
3167 cmd->name);
3168 goto fail;
3171 return qdict;
3173 fail:
3174 QDECREF(qdict);
3175 g_free(key);
3176 return NULL;
3179 static void handle_hmp_command(Monitor *mon, const char *cmdline)
3181 QDict *qdict;
3182 const mon_cmd_t *cmd;
3184 trace_handle_hmp_command(mon, cmdline);
3186 cmd = monitor_parse_command(mon, cmdline, &cmdline, mon->cmd_table);
3187 if (!cmd) {
3188 return;
3191 qdict = monitor_parse_arguments(mon, &cmdline, cmd);
3192 if (!qdict) {
3193 monitor_printf(mon, "Try \"help %s\" for more information\n",
3194 cmd->name);
3195 return;
3198 cmd->cmd(mon, qdict);
3199 QDECREF(qdict);
3202 static void cmd_completion(Monitor *mon, const char *name, const char *list)
3204 const char *p, *pstart;
3205 char cmd[128];
3206 int len;
3208 p = list;
3209 for(;;) {
3210 pstart = p;
3211 p = strchr(p, '|');
3212 if (!p)
3213 p = pstart + strlen(pstart);
3214 len = p - pstart;
3215 if (len > sizeof(cmd) - 2)
3216 len = sizeof(cmd) - 2;
3217 memcpy(cmd, pstart, len);
3218 cmd[len] = '\0';
3219 if (name[0] == '\0' || !strncmp(name, cmd, strlen(name))) {
3220 readline_add_completion(mon->rs, cmd);
3222 if (*p == '\0')
3223 break;
3224 p++;
3228 static void file_completion(Monitor *mon, const char *input)
3230 DIR *ffs;
3231 struct dirent *d;
3232 char path[1024];
3233 char file[1024], file_prefix[1024];
3234 int input_path_len;
3235 const char *p;
3237 p = strrchr(input, '/');
3238 if (!p) {
3239 input_path_len = 0;
3240 pstrcpy(file_prefix, sizeof(file_prefix), input);
3241 pstrcpy(path, sizeof(path), ".");
3242 } else {
3243 input_path_len = p - input + 1;
3244 memcpy(path, input, input_path_len);
3245 if (input_path_len > sizeof(path) - 1)
3246 input_path_len = sizeof(path) - 1;
3247 path[input_path_len] = '\0';
3248 pstrcpy(file_prefix, sizeof(file_prefix), p + 1);
3251 ffs = opendir(path);
3252 if (!ffs)
3253 return;
3254 for(;;) {
3255 struct stat sb;
3256 d = readdir(ffs);
3257 if (!d)
3258 break;
3260 if (strcmp(d->d_name, ".") == 0 || strcmp(d->d_name, "..") == 0) {
3261 continue;
3264 if (strstart(d->d_name, file_prefix, NULL)) {
3265 memcpy(file, input, input_path_len);
3266 if (input_path_len < sizeof(file))
3267 pstrcpy(file + input_path_len, sizeof(file) - input_path_len,
3268 d->d_name);
3269 /* stat the file to find out if it's a directory.
3270 * In that case add a slash to speed up typing long paths
3272 if (stat(file, &sb) == 0 && S_ISDIR(sb.st_mode)) {
3273 pstrcat(file, sizeof(file), "/");
3275 readline_add_completion(mon->rs, file);
3278 closedir(ffs);
3281 static const char *next_arg_type(const char *typestr)
3283 const char *p = strchr(typestr, ':');
3284 return (p != NULL ? ++p : typestr);
3287 static void add_completion_option(ReadLineState *rs, const char *str,
3288 const char *option)
3290 if (!str || !option) {
3291 return;
3293 if (!strncmp(option, str, strlen(str))) {
3294 readline_add_completion(rs, option);
3298 void chardev_add_completion(ReadLineState *rs, int nb_args, const char *str)
3300 size_t len;
3301 ChardevBackendInfoList *list, *start;
3303 if (nb_args != 2) {
3304 return;
3306 len = strlen(str);
3307 readline_set_completion_index(rs, len);
3309 start = list = qmp_query_chardev_backends(NULL);
3310 while (list) {
3311 const char *chr_name = list->value->name;
3313 if (!strncmp(chr_name, str, len)) {
3314 readline_add_completion(rs, chr_name);
3316 list = list->next;
3318 qapi_free_ChardevBackendInfoList(start);
3321 void netdev_add_completion(ReadLineState *rs, int nb_args, const char *str)
3323 size_t len;
3324 int i;
3326 if (nb_args != 2) {
3327 return;
3329 len = strlen(str);
3330 readline_set_completion_index(rs, len);
3331 for (i = 0; i < NET_CLIENT_DRIVER__MAX; i++) {
3332 add_completion_option(rs, str, NetClientDriver_str(i));
3336 void device_add_completion(ReadLineState *rs, int nb_args, const char *str)
3338 GSList *list, *elt;
3339 size_t len;
3341 if (nb_args != 2) {
3342 return;
3345 len = strlen(str);
3346 readline_set_completion_index(rs, len);
3347 list = elt = object_class_get_list(TYPE_DEVICE, false);
3348 while (elt) {
3349 const char *name;
3350 DeviceClass *dc = OBJECT_CLASS_CHECK(DeviceClass, elt->data,
3351 TYPE_DEVICE);
3352 name = object_class_get_name(OBJECT_CLASS(dc));
3354 if (dc->user_creatable
3355 && !strncmp(name, str, len)) {
3356 readline_add_completion(rs, name);
3358 elt = elt->next;
3360 g_slist_free(list);
3363 void object_add_completion(ReadLineState *rs, int nb_args, const char *str)
3365 GSList *list, *elt;
3366 size_t len;
3368 if (nb_args != 2) {
3369 return;
3372 len = strlen(str);
3373 readline_set_completion_index(rs, len);
3374 list = elt = object_class_get_list(TYPE_USER_CREATABLE, false);
3375 while (elt) {
3376 const char *name;
3378 name = object_class_get_name(OBJECT_CLASS(elt->data));
3379 if (!strncmp(name, str, len) && strcmp(name, TYPE_USER_CREATABLE)) {
3380 readline_add_completion(rs, name);
3382 elt = elt->next;
3384 g_slist_free(list);
3387 static void peripheral_device_del_completion(ReadLineState *rs,
3388 const char *str, size_t len)
3390 Object *peripheral = container_get(qdev_get_machine(), "/peripheral");
3391 GSList *list, *item;
3393 list = qdev_build_hotpluggable_device_list(peripheral);
3394 if (!list) {
3395 return;
3398 for (item = list; item; item = g_slist_next(item)) {
3399 DeviceState *dev = item->data;
3401 if (dev->id && !strncmp(str, dev->id, len)) {
3402 readline_add_completion(rs, dev->id);
3406 g_slist_free(list);
3409 void chardev_remove_completion(ReadLineState *rs, int nb_args, const char *str)
3411 size_t len;
3412 ChardevInfoList *list, *start;
3414 if (nb_args != 2) {
3415 return;
3417 len = strlen(str);
3418 readline_set_completion_index(rs, len);
3420 start = list = qmp_query_chardev(NULL);
3421 while (list) {
3422 ChardevInfo *chr = list->value;
3424 if (!strncmp(chr->label, str, len)) {
3425 readline_add_completion(rs, chr->label);
3427 list = list->next;
3429 qapi_free_ChardevInfoList(start);
3432 static void ringbuf_completion(ReadLineState *rs, const char *str)
3434 size_t len;
3435 ChardevInfoList *list, *start;
3437 len = strlen(str);
3438 readline_set_completion_index(rs, len);
3440 start = list = qmp_query_chardev(NULL);
3441 while (list) {
3442 ChardevInfo *chr_info = list->value;
3444 if (!strncmp(chr_info->label, str, len)) {
3445 Chardev *chr = qemu_chr_find(chr_info->label);
3446 if (chr && CHARDEV_IS_RINGBUF(chr)) {
3447 readline_add_completion(rs, chr_info->label);
3450 list = list->next;
3452 qapi_free_ChardevInfoList(start);
3455 void ringbuf_write_completion(ReadLineState *rs, int nb_args, const char *str)
3457 if (nb_args != 2) {
3458 return;
3460 ringbuf_completion(rs, str);
3463 void device_del_completion(ReadLineState *rs, int nb_args, const char *str)
3465 size_t len;
3467 if (nb_args != 2) {
3468 return;
3471 len = strlen(str);
3472 readline_set_completion_index(rs, len);
3473 peripheral_device_del_completion(rs, str, len);
3476 void object_del_completion(ReadLineState *rs, int nb_args, const char *str)
3478 ObjectPropertyInfoList *list, *start;
3479 size_t len;
3481 if (nb_args != 2) {
3482 return;
3484 len = strlen(str);
3485 readline_set_completion_index(rs, len);
3487 start = list = qmp_qom_list("/objects", NULL);
3488 while (list) {
3489 ObjectPropertyInfo *info = list->value;
3491 if (!strncmp(info->type, "child<", 5)
3492 && !strncmp(info->name, str, len)) {
3493 readline_add_completion(rs, info->name);
3495 list = list->next;
3497 qapi_free_ObjectPropertyInfoList(start);
3500 void sendkey_completion(ReadLineState *rs, int nb_args, const char *str)
3502 int i;
3503 char *sep;
3504 size_t len;
3506 if (nb_args != 2) {
3507 return;
3509 sep = strrchr(str, '-');
3510 if (sep) {
3511 str = sep + 1;
3513 len = strlen(str);
3514 readline_set_completion_index(rs, len);
3515 for (i = 0; i < Q_KEY_CODE__MAX; i++) {
3516 if (!strncmp(str, QKeyCode_str(i), len)) {
3517 readline_add_completion(rs, QKeyCode_str(i));
3522 void set_link_completion(ReadLineState *rs, int nb_args, const char *str)
3524 size_t len;
3526 len = strlen(str);
3527 readline_set_completion_index(rs, len);
3528 if (nb_args == 2) {
3529 NetClientState *ncs[MAX_QUEUE_NUM];
3530 int count, i;
3531 count = qemu_find_net_clients_except(NULL, ncs,
3532 NET_CLIENT_DRIVER_NONE,
3533 MAX_QUEUE_NUM);
3534 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3535 const char *name = ncs[i]->name;
3536 if (!strncmp(str, name, len)) {
3537 readline_add_completion(rs, name);
3540 } else if (nb_args == 3) {
3541 add_completion_option(rs, str, "on");
3542 add_completion_option(rs, str, "off");
3546 void netdev_del_completion(ReadLineState *rs, int nb_args, const char *str)
3548 int len, count, i;
3549 NetClientState *ncs[MAX_QUEUE_NUM];
3551 if (nb_args != 2) {
3552 return;
3555 len = strlen(str);
3556 readline_set_completion_index(rs, len);
3557 count = qemu_find_net_clients_except(NULL, ncs, NET_CLIENT_DRIVER_NIC,
3558 MAX_QUEUE_NUM);
3559 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3560 QemuOpts *opts;
3561 const char *name = ncs[i]->name;
3562 if (strncmp(str, name, len)) {
3563 continue;
3565 opts = qemu_opts_find(qemu_find_opts_err("netdev", NULL), name);
3566 if (opts) {
3567 readline_add_completion(rs, name);
3572 void info_trace_events_completion(ReadLineState *rs, int nb_args, const char *str)
3574 size_t len;
3576 len = strlen(str);
3577 readline_set_completion_index(rs, len);
3578 if (nb_args == 2) {
3579 TraceEventIter iter;
3580 TraceEvent *ev;
3581 char *pattern = g_strdup_printf("%s*", str);
3582 trace_event_iter_init(&iter, pattern);
3583 while ((ev = trace_event_iter_next(&iter)) != NULL) {
3584 readline_add_completion(rs, trace_event_get_name(ev));
3586 g_free(pattern);
3590 void trace_event_completion(ReadLineState *rs, int nb_args, const char *str)
3592 size_t len;
3594 len = strlen(str);
3595 readline_set_completion_index(rs, len);
3596 if (nb_args == 2) {
3597 TraceEventIter iter;
3598 TraceEvent *ev;
3599 char *pattern = g_strdup_printf("%s*", str);
3600 trace_event_iter_init(&iter, pattern);
3601 while ((ev = trace_event_iter_next(&iter)) != NULL) {
3602 readline_add_completion(rs, trace_event_get_name(ev));
3604 g_free(pattern);
3605 } else if (nb_args == 3) {
3606 add_completion_option(rs, str, "on");
3607 add_completion_option(rs, str, "off");
3611 void watchdog_action_completion(ReadLineState *rs, int nb_args, const char *str)
3613 int i;
3615 if (nb_args != 2) {
3616 return;
3618 readline_set_completion_index(rs, strlen(str));
3619 for (i = 0; i < WATCHDOG_ACTION__MAX; i++) {
3620 add_completion_option(rs, str, WatchdogAction_str(i));
3624 void migrate_set_capability_completion(ReadLineState *rs, int nb_args,
3625 const char *str)
3627 size_t len;
3629 len = strlen(str);
3630 readline_set_completion_index(rs, len);
3631 if (nb_args == 2) {
3632 int i;
3633 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
3634 const char *name = MigrationCapability_str(i);
3635 if (!strncmp(str, name, len)) {
3636 readline_add_completion(rs, name);
3639 } else if (nb_args == 3) {
3640 add_completion_option(rs, str, "on");
3641 add_completion_option(rs, str, "off");
3645 void migrate_set_parameter_completion(ReadLineState *rs, int nb_args,
3646 const char *str)
3648 size_t len;
3650 len = strlen(str);
3651 readline_set_completion_index(rs, len);
3652 if (nb_args == 2) {
3653 int i;
3654 for (i = 0; i < MIGRATION_PARAMETER__MAX; i++) {
3655 const char *name = MigrationParameter_str(i);
3656 if (!strncmp(str, name, len)) {
3657 readline_add_completion(rs, name);
3663 static void vm_completion(ReadLineState *rs, const char *str)
3665 size_t len;
3666 BlockDriverState *bs;
3667 BdrvNextIterator it;
3669 len = strlen(str);
3670 readline_set_completion_index(rs, len);
3672 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
3673 SnapshotInfoList *snapshots, *snapshot;
3674 AioContext *ctx = bdrv_get_aio_context(bs);
3675 bool ok = false;
3677 aio_context_acquire(ctx);
3678 if (bdrv_can_snapshot(bs)) {
3679 ok = bdrv_query_snapshot_info_list(bs, &snapshots, NULL) == 0;
3681 aio_context_release(ctx);
3682 if (!ok) {
3683 continue;
3686 snapshot = snapshots;
3687 while (snapshot) {
3688 char *completion = snapshot->value->name;
3689 if (!strncmp(str, completion, len)) {
3690 readline_add_completion(rs, completion);
3692 completion = snapshot->value->id;
3693 if (!strncmp(str, completion, len)) {
3694 readline_add_completion(rs, completion);
3696 snapshot = snapshot->next;
3698 qapi_free_SnapshotInfoList(snapshots);
3703 void delvm_completion(ReadLineState *rs, int nb_args, const char *str)
3705 if (nb_args == 2) {
3706 vm_completion(rs, str);
3710 void loadvm_completion(ReadLineState *rs, int nb_args, const char *str)
3712 if (nb_args == 2) {
3713 vm_completion(rs, str);
3717 static void monitor_find_completion_by_table(Monitor *mon,
3718 const mon_cmd_t *cmd_table,
3719 char **args,
3720 int nb_args)
3722 const char *cmdname;
3723 int i;
3724 const char *ptype, *old_ptype, *str, *name;
3725 const mon_cmd_t *cmd;
3726 BlockBackend *blk = NULL;
3728 if (nb_args <= 1) {
3729 /* command completion */
3730 if (nb_args == 0)
3731 cmdname = "";
3732 else
3733 cmdname = args[0];
3734 readline_set_completion_index(mon->rs, strlen(cmdname));
3735 for (cmd = cmd_table; cmd->name != NULL; cmd++) {
3736 cmd_completion(mon, cmdname, cmd->name);
3738 } else {
3739 /* find the command */
3740 for (cmd = cmd_table; cmd->name != NULL; cmd++) {
3741 if (compare_cmd(args[0], cmd->name)) {
3742 break;
3745 if (!cmd->name) {
3746 return;
3749 if (cmd->sub_table) {
3750 /* do the job again */
3751 monitor_find_completion_by_table(mon, cmd->sub_table,
3752 &args[1], nb_args - 1);
3753 return;
3755 if (cmd->command_completion) {
3756 cmd->command_completion(mon->rs, nb_args, args[nb_args - 1]);
3757 return;
3760 ptype = next_arg_type(cmd->args_type);
3761 for(i = 0; i < nb_args - 2; i++) {
3762 if (*ptype != '\0') {
3763 ptype = next_arg_type(ptype);
3764 while (*ptype == '?')
3765 ptype = next_arg_type(ptype);
3768 str = args[nb_args - 1];
3769 old_ptype = NULL;
3770 while (*ptype == '-' && old_ptype != ptype) {
3771 old_ptype = ptype;
3772 ptype = next_arg_type(ptype);
3774 switch(*ptype) {
3775 case 'F':
3776 /* file completion */
3777 readline_set_completion_index(mon->rs, strlen(str));
3778 file_completion(mon, str);
3779 break;
3780 case 'B':
3781 /* block device name completion */
3782 readline_set_completion_index(mon->rs, strlen(str));
3783 while ((blk = blk_next(blk)) != NULL) {
3784 name = blk_name(blk);
3785 if (str[0] == '\0' ||
3786 !strncmp(name, str, strlen(str))) {
3787 readline_add_completion(mon->rs, name);
3790 break;
3791 case 's':
3792 case 'S':
3793 if (!strcmp(cmd->name, "help|?")) {
3794 monitor_find_completion_by_table(mon, cmd_table,
3795 &args[1], nb_args - 1);
3797 break;
3798 default:
3799 break;
3804 static void monitor_find_completion(void *opaque,
3805 const char *cmdline)
3807 Monitor *mon = opaque;
3808 char *args[MAX_ARGS];
3809 int nb_args, len;
3811 /* 1. parse the cmdline */
3812 if (parse_cmdline(cmdline, &nb_args, args) < 0) {
3813 return;
3816 /* if the line ends with a space, it means we want to complete the
3817 next arg */
3818 len = strlen(cmdline);
3819 if (len > 0 && qemu_isspace(cmdline[len - 1])) {
3820 if (nb_args >= MAX_ARGS) {
3821 goto cleanup;
3823 args[nb_args++] = g_strdup("");
3826 /* 2. auto complete according to args */
3827 monitor_find_completion_by_table(mon, mon->cmd_table, args, nb_args);
3829 cleanup:
3830 free_cmdline_args(args, nb_args);
3833 static int monitor_can_read(void *opaque)
3835 Monitor *mon = opaque;
3837 return !atomic_mb_read(&mon->suspend_cnt);
3841 * 1. This function takes ownership of rsp, err, and id.
3842 * 2. rsp, err, and id may be NULL.
3843 * 3. If err != NULL then rsp must be NULL.
3845 static void monitor_qmp_respond(Monitor *mon, QObject *rsp,
3846 Error *err, QObject *id)
3848 QDict *qdict = NULL;
3850 if (err) {
3851 assert(!rsp);
3852 qdict = qdict_new();
3853 qdict_put_obj(qdict, "error", qmp_build_error_object(err));
3854 error_free(err);
3855 rsp = QOBJECT(qdict);
3858 if (rsp) {
3859 if (id) {
3860 /* This is for the qdict below. */
3861 qobject_incref(id);
3862 qdict_put_obj(qobject_to(QDict, rsp), "id", id);
3865 monitor_json_emitter(mon, rsp);
3868 qobject_decref(id);
3869 qobject_decref(rsp);
3872 static void handle_qmp_command(JSONMessageParser *parser, GQueue *tokens)
3874 QObject *req, *rsp = NULL, *id = NULL;
3875 QDict *qdict = NULL;
3876 MonitorQMP *mon_qmp = container_of(parser, MonitorQMP, parser);
3877 Monitor *old_mon, *mon = container_of(mon_qmp, Monitor, qmp);
3879 Error *err = NULL;
3881 req = json_parser_parse_err(tokens, NULL, &err);
3882 if (!req && !err) {
3883 /* json_parser_parse_err() sucks: can fail without setting @err */
3884 error_setg(&err, QERR_JSON_PARSING);
3886 if (err) {
3887 goto err_out;
3890 qdict = qobject_to(QDict, req);
3891 if (qdict) {
3892 id = qdict_get(qdict, "id");
3893 qobject_incref(id);
3894 qdict_del(qdict, "id");
3895 } /* else will fail qmp_dispatch() */
3897 if (trace_event_get_state_backends(TRACE_HANDLE_QMP_COMMAND)) {
3898 QString *req_json = qobject_to_json(req);
3899 trace_handle_qmp_command(mon, qstring_get_str(req_json));
3900 QDECREF(req_json);
3903 old_mon = cur_mon;
3904 cur_mon = mon;
3906 rsp = qmp_dispatch(cur_mon->qmp.commands, req);
3908 cur_mon = old_mon;
3910 if (mon->qmp.commands == &qmp_cap_negotiation_commands) {
3911 qdict = qdict_get_qdict(qobject_to(QDict, rsp), "error");
3912 if (qdict
3913 && !g_strcmp0(qdict_get_try_str(qdict, "class"),
3914 QapiErrorClass_str(ERROR_CLASS_COMMAND_NOT_FOUND))) {
3915 /* Provide a more useful error message */
3916 qdict_del(qdict, "desc");
3917 qdict_put_str(qdict, "desc", "Expecting capabilities negotiation"
3918 " with 'qmp_capabilities'");
3922 err_out:
3923 monitor_qmp_respond(mon, rsp, err, id);
3925 qobject_decref(req);
3928 static void monitor_qmp_read(void *opaque, const uint8_t *buf, int size)
3930 Monitor *mon = opaque;
3932 json_message_parser_feed(&mon->qmp.parser, (const char *) buf, size);
3935 static void monitor_read(void *opaque, const uint8_t *buf, int size)
3937 Monitor *old_mon = cur_mon;
3938 int i;
3940 cur_mon = opaque;
3942 if (cur_mon->rs) {
3943 for (i = 0; i < size; i++)
3944 readline_handle_byte(cur_mon->rs, buf[i]);
3945 } else {
3946 if (size == 0 || buf[size - 1] != 0)
3947 monitor_printf(cur_mon, "corrupted command\n");
3948 else
3949 handle_hmp_command(cur_mon, (char *)buf);
3952 cur_mon = old_mon;
3955 static void monitor_command_cb(void *opaque, const char *cmdline,
3956 void *readline_opaque)
3958 Monitor *mon = opaque;
3960 monitor_suspend(mon);
3961 handle_hmp_command(mon, cmdline);
3962 monitor_resume(mon);
3965 int monitor_suspend(Monitor *mon)
3967 if (monitor_is_hmp_non_interactive(mon)) {
3968 return -ENOTTY;
3971 atomic_inc(&mon->suspend_cnt);
3973 if (monitor_is_qmp(mon)) {
3975 * Kick iothread to make sure this takes effect. It'll be
3976 * evaluated again in prepare() of the watch object.
3978 aio_notify(iothread_get_aio_context(mon_global.mon_iothread));
3981 trace_monitor_suspend(mon, 1);
3982 return 0;
3985 void monitor_resume(Monitor *mon)
3987 if (monitor_is_hmp_non_interactive(mon)) {
3988 return;
3991 if (atomic_dec_fetch(&mon->suspend_cnt) == 0) {
3992 if (monitor_is_qmp(mon)) {
3994 * For QMP monitors that are running in IOThread, let's
3995 * kick the thread in case it's sleeping.
3997 if (mon->use_io_thr) {
3998 aio_notify(iothread_get_aio_context(mon_global.mon_iothread));
4000 } else {
4001 assert(mon->rs);
4002 readline_show_prompt(mon->rs);
4005 trace_monitor_suspend(mon, -1);
4008 static QObject *get_qmp_greeting(Monitor *mon)
4010 QList *cap_list = qlist_new();
4011 QObject *ver = NULL;
4012 QMPCapability cap;
4014 qmp_marshal_query_version(NULL, &ver, NULL);
4016 for (cap = 0; cap < QMP_CAPABILITY__MAX; cap++) {
4017 if (!mon->use_io_thr && cap == QMP_CAPABILITY_OOB) {
4018 /* Monitors that are not using IOThread won't support OOB */
4019 continue;
4021 qlist_append(cap_list, qstring_from_str(QMPCapability_str(cap)));
4024 return qobject_from_jsonf("{'QMP': {'version': %p, 'capabilities': %p}}",
4025 ver, cap_list);
4028 static void monitor_qmp_caps_reset(Monitor *mon)
4030 memset(mon->qmp.qmp_caps, 0, sizeof(mon->qmp.qmp_caps));
4033 static void monitor_qmp_event(void *opaque, int event)
4035 QObject *data;
4036 Monitor *mon = opaque;
4038 switch (event) {
4039 case CHR_EVENT_OPENED:
4040 mon->qmp.commands = &qmp_cap_negotiation_commands;
4041 monitor_qmp_caps_reset(mon);
4042 data = get_qmp_greeting(mon);
4043 monitor_json_emitter(mon, data);
4044 qobject_decref(data);
4045 mon_refcount++;
4046 break;
4047 case CHR_EVENT_CLOSED:
4048 json_message_parser_destroy(&mon->qmp.parser);
4049 json_message_parser_init(&mon->qmp.parser, handle_qmp_command);
4050 mon_refcount--;
4051 monitor_fdsets_cleanup();
4052 break;
4056 static void monitor_event(void *opaque, int event)
4058 Monitor *mon = opaque;
4060 switch (event) {
4061 case CHR_EVENT_MUX_IN:
4062 qemu_mutex_lock(&mon->out_lock);
4063 mon->mux_out = 0;
4064 qemu_mutex_unlock(&mon->out_lock);
4065 if (mon->reset_seen) {
4066 readline_restart(mon->rs);
4067 monitor_resume(mon);
4068 monitor_flush(mon);
4069 } else {
4070 atomic_mb_set(&mon->suspend_cnt, 0);
4072 break;
4074 case CHR_EVENT_MUX_OUT:
4075 if (mon->reset_seen) {
4076 if (atomic_mb_read(&mon->suspend_cnt) == 0) {
4077 monitor_printf(mon, "\n");
4079 monitor_flush(mon);
4080 monitor_suspend(mon);
4081 } else {
4082 atomic_inc(&mon->suspend_cnt);
4084 qemu_mutex_lock(&mon->out_lock);
4085 mon->mux_out = 1;
4086 qemu_mutex_unlock(&mon->out_lock);
4087 break;
4089 case CHR_EVENT_OPENED:
4090 monitor_printf(mon, "QEMU %s monitor - type 'help' for more "
4091 "information\n", QEMU_VERSION);
4092 if (!mon->mux_out) {
4093 readline_restart(mon->rs);
4094 readline_show_prompt(mon->rs);
4096 mon->reset_seen = 1;
4097 mon_refcount++;
4098 break;
4100 case CHR_EVENT_CLOSED:
4101 mon_refcount--;
4102 monitor_fdsets_cleanup();
4103 break;
4107 static int
4108 compare_mon_cmd(const void *a, const void *b)
4110 return strcmp(((const mon_cmd_t *)a)->name,
4111 ((const mon_cmd_t *)b)->name);
4114 static void sortcmdlist(void)
4116 int array_num;
4117 int elem_size = sizeof(mon_cmd_t);
4119 array_num = sizeof(mon_cmds)/elem_size-1;
4120 qsort((void *)mon_cmds, array_num, elem_size, compare_mon_cmd);
4122 array_num = sizeof(info_cmds)/elem_size-1;
4123 qsort((void *)info_cmds, array_num, elem_size, compare_mon_cmd);
4126 static GMainContext *monitor_get_io_context(void)
4128 return iothread_get_g_main_context(mon_global.mon_iothread);
4131 static AioContext *monitor_get_aio_context(void)
4133 return iothread_get_aio_context(mon_global.mon_iothread);
4136 static void monitor_iothread_init(void)
4138 mon_global.mon_iothread = iothread_create("mon_iothread",
4139 &error_abort);
4142 void monitor_init_globals(void)
4144 monitor_init_qmp_commands();
4145 monitor_qapi_event_init();
4146 sortcmdlist();
4147 qemu_mutex_init(&monitor_lock);
4148 monitor_iothread_init();
4151 /* These functions just adapt the readline interface in a typesafe way. We
4152 * could cast function pointers but that discards compiler checks.
4154 static void GCC_FMT_ATTR(2, 3) monitor_readline_printf(void *opaque,
4155 const char *fmt, ...)
4157 va_list ap;
4158 va_start(ap, fmt);
4159 monitor_vprintf(opaque, fmt, ap);
4160 va_end(ap);
4163 static void monitor_readline_flush(void *opaque)
4165 monitor_flush(opaque);
4169 * Print to current monitor if we have one, else to stderr.
4170 * TODO should return int, so callers can calculate width, but that
4171 * requires surgery to monitor_vprintf(). Left for another day.
4173 void error_vprintf(const char *fmt, va_list ap)
4175 if (cur_mon && !monitor_cur_is_qmp()) {
4176 monitor_vprintf(cur_mon, fmt, ap);
4177 } else {
4178 vfprintf(stderr, fmt, ap);
4182 void error_vprintf_unless_qmp(const char *fmt, va_list ap)
4184 if (cur_mon && !monitor_cur_is_qmp()) {
4185 monitor_vprintf(cur_mon, fmt, ap);
4186 } else if (!cur_mon) {
4187 vfprintf(stderr, fmt, ap);
4191 static void monitor_list_append(Monitor *mon)
4193 qemu_mutex_lock(&monitor_lock);
4194 QTAILQ_INSERT_HEAD(&mon_list, mon, entry);
4195 qemu_mutex_unlock(&monitor_lock);
4198 static void monitor_qmp_setup_handlers_bh(void *opaque)
4200 Monitor *mon = opaque;
4201 GMainContext *context;
4203 if (mon->use_io_thr) {
4205 * When use_io_thr is set, we use the global shared dedicated
4206 * IO thread for this monitor to handle input/output.
4208 context = monitor_get_io_context();
4209 /* We should have inited globals before reaching here. */
4210 assert(context);
4211 } else {
4212 /* The default main loop, which is the main thread */
4213 context = NULL;
4216 qemu_chr_fe_set_handlers(&mon->chr, monitor_can_read, monitor_qmp_read,
4217 monitor_qmp_event, NULL, mon, context, true);
4218 monitor_list_append(mon);
4221 void monitor_init(Chardev *chr, int flags)
4223 Monitor *mon = g_malloc(sizeof(*mon));
4225 monitor_data_init(mon, false, false);
4227 qemu_chr_fe_init(&mon->chr, chr, &error_abort);
4228 mon->flags = flags;
4229 if (flags & MONITOR_USE_READLINE) {
4230 mon->rs = readline_init(monitor_readline_printf,
4231 monitor_readline_flush,
4232 mon,
4233 monitor_find_completion);
4234 monitor_read_command(mon, 0);
4237 if (monitor_is_qmp(mon)) {
4238 qemu_chr_fe_set_echo(&mon->chr, true);
4239 json_message_parser_init(&mon->qmp.parser, handle_qmp_command);
4240 if (mon->use_io_thr) {
4242 * Make sure the old iowatch is gone. It's possible when
4243 * e.g. the chardev is in client mode, with wait=on.
4245 remove_fd_in_watch(chr);
4247 * We can't call qemu_chr_fe_set_handlers() directly here
4248 * since during the procedure the chardev will be active
4249 * and running in monitor iothread, while we'll still do
4250 * something before returning from it, which is a possible
4251 * race too. To avoid that, we just create a BH to setup
4252 * the handlers.
4254 aio_bh_schedule_oneshot(monitor_get_aio_context(),
4255 monitor_qmp_setup_handlers_bh, mon);
4256 /* We'll add this to mon_list in the BH when setup done */
4257 return;
4258 } else {
4259 qemu_chr_fe_set_handlers(&mon->chr, monitor_can_read,
4260 monitor_qmp_read, monitor_qmp_event,
4261 NULL, mon, NULL, true);
4263 } else {
4264 qemu_chr_fe_set_handlers(&mon->chr, monitor_can_read, monitor_read,
4265 monitor_event, NULL, mon, NULL, true);
4268 monitor_list_append(mon);
4271 void monitor_cleanup(void)
4273 Monitor *mon, *next;
4276 * We need to explicitly stop the iothread (but not destroy it),
4277 * cleanup the monitor resources, then destroy the iothread since
4278 * we need to unregister from chardev below in
4279 * monitor_data_destroy(), and chardev is not thread-safe yet
4281 iothread_stop(mon_global.mon_iothread);
4283 qemu_mutex_lock(&monitor_lock);
4284 QTAILQ_FOREACH_SAFE(mon, &mon_list, entry, next) {
4285 QTAILQ_REMOVE(&mon_list, mon, entry);
4286 monitor_data_destroy(mon);
4287 g_free(mon);
4289 qemu_mutex_unlock(&monitor_lock);
4291 iothread_destroy(mon_global.mon_iothread);
4292 mon_global.mon_iothread = NULL;
4295 QemuOptsList qemu_mon_opts = {
4296 .name = "mon",
4297 .implied_opt_name = "chardev",
4298 .head = QTAILQ_HEAD_INITIALIZER(qemu_mon_opts.head),
4299 .desc = {
4301 .name = "mode",
4302 .type = QEMU_OPT_STRING,
4304 .name = "chardev",
4305 .type = QEMU_OPT_STRING,
4307 .name = "pretty",
4308 .type = QEMU_OPT_BOOL,
4310 { /* end of list */ }
4314 #ifndef TARGET_I386
4315 void qmp_rtc_reset_reinjection(Error **errp)
4317 error_setg(errp, QERR_FEATURE_DISABLED, "rtc-reset-reinjection");
4320 SevInfo *qmp_query_sev(Error **errp)
4322 error_setg(errp, QERR_FEATURE_DISABLED, "query-sev");
4323 return NULL;
4326 SevLaunchMeasureInfo *qmp_query_sev_launch_measure(Error **errp)
4328 error_setg(errp, QERR_FEATURE_DISABLED, "query-sev-launch-measure");
4329 return NULL;
4332 SevCapability *qmp_query_sev_capabilities(Error **errp)
4334 error_setg(errp, QERR_FEATURE_DISABLED, "query-sev-capabilities");
4335 return NULL;
4337 #endif
4339 #ifndef TARGET_S390X
4340 void qmp_dump_skeys(const char *filename, Error **errp)
4342 error_setg(errp, QERR_FEATURE_DISABLED, "dump-skeys");
4344 #endif
4346 #ifndef TARGET_ARM
4347 GICCapabilityList *qmp_query_gic_capabilities(Error **errp)
4349 error_setg(errp, QERR_FEATURE_DISABLED, "query-gic-capabilities");
4350 return NULL;
4352 #endif
4354 HotpluggableCPUList *qmp_query_hotpluggable_cpus(Error **errp)
4356 MachineState *ms = MACHINE(qdev_get_machine());
4357 MachineClass *mc = MACHINE_GET_CLASS(ms);
4359 if (!mc->has_hotpluggable_cpus) {
4360 error_setg(errp, QERR_FEATURE_DISABLED, "query-hotpluggable-cpus");
4361 return NULL;
4364 return machine_query_hotpluggable_cpus(ms);