monitor: Improve and document client_migrate_info protocol error
[qemu.git] / monitor.c
blob81703093f91f433e555ba08a3f5d64243c362541
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.
24 #include <dirent.h>
25 #include "hw/hw.h"
26 #include "monitor/qdev.h"
27 #include "hw/usb.h"
28 #include "hw/i386/pc.h"
29 #include "hw/pci/pci.h"
30 #include "sysemu/watchdog.h"
31 #include "hw/loader.h"
32 #include "exec/gdbstub.h"
33 #include "net/net.h"
34 #include "net/slirp.h"
35 #include "sysemu/char.h"
36 #include "ui/qemu-spice.h"
37 #include "sysemu/sysemu.h"
38 #include "sysemu/numa.h"
39 #include "monitor/monitor.h"
40 #include "qemu/readline.h"
41 #include "ui/console.h"
42 #include "ui/input.h"
43 #include "sysemu/blockdev.h"
44 #include "audio/audio.h"
45 #include "disas/disas.h"
46 #include "sysemu/balloon.h"
47 #include "qemu/timer.h"
48 #include "migration/migration.h"
49 #include "sysemu/kvm.h"
50 #include "qemu/acl.h"
51 #include "sysemu/tpm.h"
52 #include "qapi/qmp/qint.h"
53 #include "qapi/qmp/qfloat.h"
54 #include "qapi/qmp/qlist.h"
55 #include "qapi/qmp/qbool.h"
56 #include "qapi/qmp/qstring.h"
57 #include "qapi/qmp/qjson.h"
58 #include "qapi/qmp/json-streamer.h"
59 #include "qapi/qmp/json-parser.h"
60 #include <qom/object_interfaces.h>
61 #include "qemu/osdep.h"
62 #include "cpu.h"
63 #include "trace.h"
64 #include "trace/control.h"
65 #ifdef CONFIG_TRACE_SIMPLE
66 #include "trace/simple.h"
67 #endif
68 #include "exec/memory.h"
69 #include "exec/cpu_ldst.h"
70 #include "qmp-commands.h"
71 #include "hmp.h"
72 #include "qemu/thread.h"
73 #include "block/qapi.h"
74 #include "qapi/qmp-event.h"
75 #include "qapi-event.h"
76 #include "sysemu/block-backend.h"
78 /* for hmp_info_irq/pic */
79 #if defined(TARGET_SPARC)
80 #include "hw/sparc/sun4m.h"
81 #endif
82 #include "hw/lm32/lm32_pic.h"
84 //#define DEBUG
85 //#define DEBUG_COMPLETION
88 * Supported types:
90 * 'F' filename
91 * 'B' block device name
92 * 's' string (accept optional quote)
93 * 'S' it just appends the rest of the string (accept optional quote)
94 * 'O' option string of the form NAME=VALUE,...
95 * parsed according to QemuOptsList given by its name
96 * Example: 'device:O' uses qemu_device_opts.
97 * Restriction: only lists with empty desc are supported
98 * TODO lift the restriction
99 * 'i' 32 bit integer
100 * 'l' target long (32 or 64 bit)
101 * 'M' Non-negative target long (32 or 64 bit), in user mode the
102 * value is multiplied by 2^20 (think Mebibyte)
103 * 'o' octets (aka bytes)
104 * user mode accepts an optional E, e, P, p, T, t, G, g, M, m,
105 * K, k suffix, which multiplies the value by 2^60 for suffixes E
106 * and e, 2^50 for suffixes P and p, 2^40 for suffixes T and t,
107 * 2^30 for suffixes G and g, 2^20 for M and m, 2^10 for K and k
108 * 'T' double
109 * user mode accepts an optional ms, us, ns suffix,
110 * which divides the value by 1e3, 1e6, 1e9, respectively
111 * '/' optional gdb-like print format (like "/10x")
113 * '?' optional type (for all types, except '/')
114 * '.' other form of optional type (for 'i' and 'l')
115 * 'b' boolean
116 * user mode accepts "on" or "off"
117 * '-' optional parameter (eg. '-f')
121 typedef struct mon_cmd_t {
122 const char *name;
123 const char *args_type;
124 const char *params;
125 const char *help;
126 void (*user_print)(Monitor *mon, const QObject *data);
127 union {
128 void (*cmd)(Monitor *mon, const QDict *qdict);
129 int (*cmd_new)(Monitor *mon, const QDict *params, QObject **ret_data);
130 } mhandler;
131 /* @sub_table is a list of 2nd level of commands. If it do not exist,
132 * mhandler should be used. If it exist, sub_table[?].mhandler should be
133 * used, and mhandler of 1st level plays the role of help function.
135 struct mon_cmd_t *sub_table;
136 void (*command_completion)(ReadLineState *rs, int nb_args, const char *str);
137 } mon_cmd_t;
139 /* file descriptors passed via SCM_RIGHTS */
140 typedef struct mon_fd_t mon_fd_t;
141 struct mon_fd_t {
142 char *name;
143 int fd;
144 QLIST_ENTRY(mon_fd_t) next;
147 /* file descriptor associated with a file descriptor set */
148 typedef struct MonFdsetFd MonFdsetFd;
149 struct MonFdsetFd {
150 int fd;
151 bool removed;
152 char *opaque;
153 QLIST_ENTRY(MonFdsetFd) next;
156 /* file descriptor set containing fds passed via SCM_RIGHTS */
157 typedef struct MonFdset MonFdset;
158 struct MonFdset {
159 int64_t id;
160 QLIST_HEAD(, MonFdsetFd) fds;
161 QLIST_HEAD(, MonFdsetFd) dup_fds;
162 QLIST_ENTRY(MonFdset) next;
165 typedef struct MonitorControl {
166 QObject *id;
167 JSONMessageParser parser;
168 int command_mode;
169 } MonitorControl;
172 * To prevent flooding clients, events can be throttled. The
173 * throttling is calculated globally, rather than per-Monitor
174 * instance.
176 typedef struct MonitorQAPIEventState {
177 QAPIEvent event; /* Event being tracked */
178 int64_t rate; /* Minimum time (in ns) between two events */
179 int64_t last; /* QEMU_CLOCK_REALTIME value at last emission */
180 QEMUTimer *timer; /* Timer for handling delayed events */
181 QObject *data; /* Event pending delayed dispatch */
182 } MonitorQAPIEventState;
184 struct Monitor {
185 CharDriverState *chr;
186 int reset_seen;
187 int flags;
188 int suspend_cnt;
189 bool skip_flush;
191 QemuMutex out_lock;
192 QString *outbuf;
193 guint out_watch;
195 /* Read under either BQL or out_lock, written with BQL+out_lock. */
196 int mux_out;
198 ReadLineState *rs;
199 MonitorControl *mc;
200 CPUState *mon_cpu;
201 BlockCompletionFunc *password_completion_cb;
202 void *password_opaque;
203 mon_cmd_t *cmd_table;
204 QError *error;
205 QLIST_HEAD(,mon_fd_t) fds;
206 QLIST_ENTRY(Monitor) entry;
209 /* QMP checker flags */
210 #define QMP_ACCEPT_UNKNOWNS 1
212 /* Protects mon_list, monitor_event_state. */
213 static QemuMutex monitor_lock;
215 static QLIST_HEAD(mon_list, Monitor) mon_list;
216 static QLIST_HEAD(mon_fdsets, MonFdset) mon_fdsets;
217 static int mon_refcount;
219 static mon_cmd_t mon_cmds[];
220 static mon_cmd_t info_cmds[];
222 static const mon_cmd_t qmp_cmds[];
224 Monitor *cur_mon;
225 Monitor *default_mon;
227 static void monitor_command_cb(void *opaque, const char *cmdline,
228 void *readline_opaque);
230 static inline int qmp_cmd_mode(const Monitor *mon)
232 return (mon->mc ? mon->mc->command_mode : 0);
235 /* Return true if in control mode, false otherwise */
236 static inline int monitor_ctrl_mode(const Monitor *mon)
238 return (mon->flags & MONITOR_USE_CONTROL);
241 /* Return non-zero iff we have a current monitor, and it is in QMP mode. */
242 int monitor_cur_is_qmp(void)
244 return cur_mon && monitor_ctrl_mode(cur_mon);
247 void monitor_read_command(Monitor *mon, int show_prompt)
249 if (!mon->rs)
250 return;
252 readline_start(mon->rs, "(qemu) ", 0, monitor_command_cb, NULL);
253 if (show_prompt)
254 readline_show_prompt(mon->rs);
257 int monitor_read_password(Monitor *mon, ReadLineFunc *readline_func,
258 void *opaque)
260 if (mon->rs) {
261 readline_start(mon->rs, "Password: ", 1, readline_func, opaque);
262 /* prompt is printed on return from the command handler */
263 return 0;
264 } else {
265 monitor_printf(mon, "terminal does not support password prompting\n");
266 return -ENOTTY;
270 static void monitor_flush_locked(Monitor *mon);
272 static gboolean monitor_unblocked(GIOChannel *chan, GIOCondition cond,
273 void *opaque)
275 Monitor *mon = opaque;
277 qemu_mutex_lock(&mon->out_lock);
278 mon->out_watch = 0;
279 monitor_flush_locked(mon);
280 qemu_mutex_unlock(&mon->out_lock);
281 return FALSE;
284 /* Called with mon->out_lock held. */
285 static void monitor_flush_locked(Monitor *mon)
287 int rc;
288 size_t len;
289 const char *buf;
291 if (mon->skip_flush) {
292 return;
295 buf = qstring_get_str(mon->outbuf);
296 len = qstring_get_length(mon->outbuf);
298 if (len && !mon->mux_out) {
299 rc = qemu_chr_fe_write(mon->chr, (const uint8_t *) buf, len);
300 if ((rc < 0 && errno != EAGAIN) || (rc == len)) {
301 /* all flushed or error */
302 QDECREF(mon->outbuf);
303 mon->outbuf = qstring_new();
304 return;
306 if (rc > 0) {
307 /* partinal write */
308 QString *tmp = qstring_from_str(buf + rc);
309 QDECREF(mon->outbuf);
310 mon->outbuf = tmp;
312 if (mon->out_watch == 0) {
313 mon->out_watch = qemu_chr_fe_add_watch(mon->chr, G_IO_OUT|G_IO_HUP,
314 monitor_unblocked, mon);
319 void monitor_flush(Monitor *mon)
321 qemu_mutex_lock(&mon->out_lock);
322 monitor_flush_locked(mon);
323 qemu_mutex_unlock(&mon->out_lock);
326 /* flush at every end of line */
327 static void monitor_puts(Monitor *mon, const char *str)
329 char c;
331 qemu_mutex_lock(&mon->out_lock);
332 for(;;) {
333 c = *str++;
334 if (c == '\0')
335 break;
336 if (c == '\n') {
337 qstring_append_chr(mon->outbuf, '\r');
339 qstring_append_chr(mon->outbuf, c);
340 if (c == '\n') {
341 monitor_flush_locked(mon);
344 qemu_mutex_unlock(&mon->out_lock);
347 void monitor_vprintf(Monitor *mon, const char *fmt, va_list ap)
349 char *buf;
351 if (!mon)
352 return;
354 if (monitor_ctrl_mode(mon)) {
355 return;
358 buf = g_strdup_vprintf(fmt, ap);
359 monitor_puts(mon, buf);
360 g_free(buf);
363 void monitor_printf(Monitor *mon, const char *fmt, ...)
365 va_list ap;
366 va_start(ap, fmt);
367 monitor_vprintf(mon, fmt, ap);
368 va_end(ap);
371 static int GCC_FMT_ATTR(2, 3) monitor_fprintf(FILE *stream,
372 const char *fmt, ...)
374 va_list ap;
375 va_start(ap, fmt);
376 monitor_vprintf((Monitor *)stream, fmt, ap);
377 va_end(ap);
378 return 0;
381 static void monitor_user_noop(Monitor *mon, const QObject *data) { }
383 static inline int handler_is_qobject(const mon_cmd_t *cmd)
385 return cmd->user_print != NULL;
388 static inline int monitor_has_error(const Monitor *mon)
390 return mon->error != NULL;
393 static void monitor_json_emitter(Monitor *mon, const QObject *data)
395 QString *json;
397 json = mon->flags & MONITOR_USE_PRETTY ? qobject_to_json_pretty(data) :
398 qobject_to_json(data);
399 assert(json != NULL);
401 qstring_append_chr(json, '\n');
402 monitor_puts(mon, qstring_get_str(json));
404 QDECREF(json);
407 static QDict *build_qmp_error_dict(const QError *err)
409 QObject *obj;
411 obj = qobject_from_jsonf("{ 'error': { 'class': %s, 'desc': %p } }",
412 ErrorClass_lookup[err->err_class],
413 qerror_human(err));
415 return qobject_to_qdict(obj);
418 static void monitor_protocol_emitter(Monitor *mon, QObject *data)
420 QDict *qmp;
422 trace_monitor_protocol_emitter(mon);
424 if (!monitor_has_error(mon)) {
425 /* success response */
426 qmp = qdict_new();
427 if (data) {
428 qobject_incref(data);
429 qdict_put_obj(qmp, "return", data);
430 } else {
431 /* return an empty QDict by default */
432 qdict_put(qmp, "return", qdict_new());
434 } else {
435 /* error response */
436 qmp = build_qmp_error_dict(mon->error);
437 QDECREF(mon->error);
438 mon->error = NULL;
441 if (mon->mc->id) {
442 qdict_put_obj(qmp, "id", mon->mc->id);
443 mon->mc->id = NULL;
446 monitor_json_emitter(mon, QOBJECT(qmp));
447 QDECREF(qmp);
451 static MonitorQAPIEventState monitor_qapi_event_state[QAPI_EVENT_MAX];
454 * Emits the event to every monitor instance, @event is only used for trace
455 * Called with monitor_lock held.
457 static void monitor_qapi_event_emit(QAPIEvent event, QObject *data)
459 Monitor *mon;
461 trace_monitor_protocol_event_emit(event, data);
462 QLIST_FOREACH(mon, &mon_list, entry) {
463 if (monitor_ctrl_mode(mon) && qmp_cmd_mode(mon)) {
464 monitor_json_emitter(mon, data);
470 * Queue a new event for emission to Monitor instances,
471 * applying any rate limiting if required.
473 static void
474 monitor_qapi_event_queue(QAPIEvent event, QDict *data, Error **errp)
476 MonitorQAPIEventState *evstate;
477 assert(event < QAPI_EVENT_MAX);
478 int64_t now = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
480 evstate = &(monitor_qapi_event_state[event]);
481 trace_monitor_protocol_event_queue(event,
482 data,
483 evstate->rate,
484 evstate->last,
485 now);
487 /* Rate limit of 0 indicates no throttling */
488 qemu_mutex_lock(&monitor_lock);
489 if (!evstate->rate) {
490 monitor_qapi_event_emit(event, QOBJECT(data));
491 evstate->last = now;
492 } else {
493 int64_t delta = now - evstate->last;
494 if (evstate->data ||
495 delta < evstate->rate) {
496 /* If there's an existing event pending, replace
497 * it with the new event, otherwise schedule a
498 * timer for delayed emission
500 if (evstate->data) {
501 qobject_decref(evstate->data);
502 } else {
503 int64_t then = evstate->last + evstate->rate;
504 timer_mod_ns(evstate->timer, then);
506 evstate->data = QOBJECT(data);
507 qobject_incref(evstate->data);
508 } else {
509 monitor_qapi_event_emit(event, QOBJECT(data));
510 evstate->last = now;
513 qemu_mutex_unlock(&monitor_lock);
517 * The callback invoked by QemuTimer when a delayed
518 * event is ready to be emitted
520 static void monitor_qapi_event_handler(void *opaque)
522 MonitorQAPIEventState *evstate = opaque;
523 int64_t now = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
525 trace_monitor_protocol_event_handler(evstate->event,
526 evstate->data,
527 evstate->last,
528 now);
529 qemu_mutex_lock(&monitor_lock);
530 if (evstate->data) {
531 monitor_qapi_event_emit(evstate->event, evstate->data);
532 qobject_decref(evstate->data);
533 evstate->data = NULL;
535 evstate->last = now;
536 qemu_mutex_unlock(&monitor_lock);
540 * @event: the event ID to be limited
541 * @rate: the rate limit in milliseconds
543 * Sets a rate limit on a particular event, so no
544 * more than 1 event will be emitted within @rate
545 * milliseconds
547 static void
548 monitor_qapi_event_throttle(QAPIEvent event, int64_t rate)
550 MonitorQAPIEventState *evstate;
551 assert(event < QAPI_EVENT_MAX);
553 evstate = &(monitor_qapi_event_state[event]);
555 trace_monitor_protocol_event_throttle(event, rate);
556 evstate->event = event;
557 assert(rate * SCALE_MS <= INT64_MAX);
558 evstate->rate = rate * SCALE_MS;
559 evstate->last = 0;
560 evstate->data = NULL;
561 evstate->timer = timer_new(QEMU_CLOCK_REALTIME,
562 SCALE_MS,
563 monitor_qapi_event_handler,
564 evstate);
567 static void monitor_qapi_event_init(void)
569 /* Limit guest-triggerable events to 1 per second */
570 monitor_qapi_event_throttle(QAPI_EVENT_RTC_CHANGE, 1000);
571 monitor_qapi_event_throttle(QAPI_EVENT_WATCHDOG, 1000);
572 monitor_qapi_event_throttle(QAPI_EVENT_BALLOON_CHANGE, 1000);
573 monitor_qapi_event_throttle(QAPI_EVENT_QUORUM_REPORT_BAD, 1000);
574 monitor_qapi_event_throttle(QAPI_EVENT_QUORUM_FAILURE, 1000);
575 monitor_qapi_event_throttle(QAPI_EVENT_VSERPORT_CHANGE, 1000);
577 qmp_event_set_func_emit(monitor_qapi_event_queue);
580 static int do_qmp_capabilities(Monitor *mon, const QDict *params,
581 QObject **ret_data)
583 /* Will setup QMP capabilities in the future */
584 if (monitor_ctrl_mode(mon)) {
585 mon->mc->command_mode = 1;
588 return 0;
591 static void handle_user_command(Monitor *mon, const char *cmdline);
593 static void monitor_data_init(Monitor *mon)
595 memset(mon, 0, sizeof(Monitor));
596 qemu_mutex_init(&mon->out_lock);
597 mon->outbuf = qstring_new();
598 /* Use *mon_cmds by default. */
599 mon->cmd_table = mon_cmds;
602 static void monitor_data_destroy(Monitor *mon)
604 QDECREF(mon->outbuf);
605 qemu_mutex_destroy(&mon->out_lock);
608 char *qmp_human_monitor_command(const char *command_line, bool has_cpu_index,
609 int64_t cpu_index, Error **errp)
611 char *output = NULL;
612 Monitor *old_mon, hmp;
614 monitor_data_init(&hmp);
615 hmp.skip_flush = true;
617 old_mon = cur_mon;
618 cur_mon = &hmp;
620 if (has_cpu_index) {
621 int ret = monitor_set_cpu(cpu_index);
622 if (ret < 0) {
623 cur_mon = old_mon;
624 error_set(errp, QERR_INVALID_PARAMETER_VALUE, "cpu-index",
625 "a CPU number");
626 goto out;
630 handle_user_command(&hmp, command_line);
631 cur_mon = old_mon;
633 qemu_mutex_lock(&hmp.out_lock);
634 if (qstring_get_length(hmp.outbuf) > 0) {
635 output = g_strdup(qstring_get_str(hmp.outbuf));
636 } else {
637 output = g_strdup("");
639 qemu_mutex_unlock(&hmp.out_lock);
641 out:
642 monitor_data_destroy(&hmp);
643 return output;
646 static int compare_cmd(const char *name, const char *list)
648 const char *p, *pstart;
649 int len;
650 len = strlen(name);
651 p = list;
652 for(;;) {
653 pstart = p;
654 p = strchr(p, '|');
655 if (!p)
656 p = pstart + strlen(pstart);
657 if ((p - pstart) == len && !memcmp(pstart, name, len))
658 return 1;
659 if (*p == '\0')
660 break;
661 p++;
663 return 0;
666 static int get_str(char *buf, int buf_size, const char **pp)
668 const char *p;
669 char *q;
670 int c;
672 q = buf;
673 p = *pp;
674 while (qemu_isspace(*p)) {
675 p++;
677 if (*p == '\0') {
678 fail:
679 *q = '\0';
680 *pp = p;
681 return -1;
683 if (*p == '\"') {
684 p++;
685 while (*p != '\0' && *p != '\"') {
686 if (*p == '\\') {
687 p++;
688 c = *p++;
689 switch (c) {
690 case 'n':
691 c = '\n';
692 break;
693 case 'r':
694 c = '\r';
695 break;
696 case '\\':
697 case '\'':
698 case '\"':
699 break;
700 default:
701 qemu_printf("unsupported escape code: '\\%c'\n", c);
702 goto fail;
704 if ((q - buf) < buf_size - 1) {
705 *q++ = c;
707 } else {
708 if ((q - buf) < buf_size - 1) {
709 *q++ = *p;
711 p++;
714 if (*p != '\"') {
715 qemu_printf("unterminated string\n");
716 goto fail;
718 p++;
719 } else {
720 while (*p != '\0' && !qemu_isspace(*p)) {
721 if ((q - buf) < buf_size - 1) {
722 *q++ = *p;
724 p++;
727 *q = '\0';
728 *pp = p;
729 return 0;
732 #define MAX_ARGS 16
734 static void free_cmdline_args(char **args, int nb_args)
736 int i;
738 assert(nb_args <= MAX_ARGS);
740 for (i = 0; i < nb_args; i++) {
741 g_free(args[i]);
747 * Parse the command line to get valid args.
748 * @cmdline: command line to be parsed.
749 * @pnb_args: location to store the number of args, must NOT be NULL.
750 * @args: location to store the args, which should be freed by caller, must
751 * NOT be NULL.
753 * Returns 0 on success, negative on failure.
755 * NOTE: this parser is an approximate form of the real command parser. Number
756 * of args have a limit of MAX_ARGS. If cmdline contains more, it will
757 * return with failure.
759 static int parse_cmdline(const char *cmdline,
760 int *pnb_args, char **args)
762 const char *p;
763 int nb_args, ret;
764 char buf[1024];
766 p = cmdline;
767 nb_args = 0;
768 for (;;) {
769 while (qemu_isspace(*p)) {
770 p++;
772 if (*p == '\0') {
773 break;
775 if (nb_args >= MAX_ARGS) {
776 goto fail;
778 ret = get_str(buf, sizeof(buf), &p);
779 if (ret < 0) {
780 goto fail;
782 args[nb_args] = g_strdup(buf);
783 nb_args++;
785 *pnb_args = nb_args;
786 return 0;
788 fail:
789 free_cmdline_args(args, nb_args);
790 return -1;
793 static void help_cmd_dump_one(Monitor *mon,
794 const mon_cmd_t *cmd,
795 char **prefix_args,
796 int prefix_args_nb)
798 int i;
800 for (i = 0; i < prefix_args_nb; i++) {
801 monitor_printf(mon, "%s ", prefix_args[i]);
803 monitor_printf(mon, "%s %s -- %s\n", cmd->name, cmd->params, cmd->help);
806 /* @args[@arg_index] is the valid command need to find in @cmds */
807 static void help_cmd_dump(Monitor *mon, const mon_cmd_t *cmds,
808 char **args, int nb_args, int arg_index)
810 const mon_cmd_t *cmd;
812 /* No valid arg need to compare with, dump all in *cmds */
813 if (arg_index >= nb_args) {
814 for (cmd = cmds; cmd->name != NULL; cmd++) {
815 help_cmd_dump_one(mon, cmd, args, arg_index);
817 return;
820 /* Find one entry to dump */
821 for (cmd = cmds; cmd->name != NULL; cmd++) {
822 if (compare_cmd(args[arg_index], cmd->name)) {
823 if (cmd->sub_table) {
824 /* continue with next arg */
825 help_cmd_dump(mon, cmd->sub_table,
826 args, nb_args, arg_index + 1);
827 } else {
828 help_cmd_dump_one(mon, cmd, args, arg_index);
830 break;
835 static void help_cmd(Monitor *mon, const char *name)
837 char *args[MAX_ARGS];
838 int nb_args = 0;
840 /* 1. parse user input */
841 if (name) {
842 /* special case for log, directly dump and return */
843 if (!strcmp(name, "log")) {
844 const QEMULogItem *item;
845 monitor_printf(mon, "Log items (comma separated):\n");
846 monitor_printf(mon, "%-10s %s\n", "none", "remove all logs");
847 for (item = qemu_log_items; item->mask != 0; item++) {
848 monitor_printf(mon, "%-10s %s\n", item->name, item->help);
850 return;
853 if (parse_cmdline(name, &nb_args, args) < 0) {
854 return;
858 /* 2. dump the contents according to parsed args */
859 help_cmd_dump(mon, mon->cmd_table, args, nb_args, 0);
861 free_cmdline_args(args, nb_args);
864 static void do_help_cmd(Monitor *mon, const QDict *qdict)
866 help_cmd(mon, qdict_get_try_str(qdict, "name"));
869 static void hmp_trace_event(Monitor *mon, const QDict *qdict)
871 const char *tp_name = qdict_get_str(qdict, "name");
872 bool new_state = qdict_get_bool(qdict, "option");
873 Error *local_err = NULL;
875 qmp_trace_event_set_state(tp_name, new_state, true, true, &local_err);
876 if (local_err) {
877 error_report_err(local_err);
881 #ifdef CONFIG_TRACE_SIMPLE
882 static void hmp_trace_file(Monitor *mon, const QDict *qdict)
884 const char *op = qdict_get_try_str(qdict, "op");
885 const char *arg = qdict_get_try_str(qdict, "arg");
887 if (!op) {
888 st_print_trace_file_status((FILE *)mon, &monitor_fprintf);
889 } else if (!strcmp(op, "on")) {
890 st_set_trace_file_enabled(true);
891 } else if (!strcmp(op, "off")) {
892 st_set_trace_file_enabled(false);
893 } else if (!strcmp(op, "flush")) {
894 st_flush_trace_buffer();
895 } else if (!strcmp(op, "set")) {
896 if (arg) {
897 st_set_trace_file(arg);
899 } else {
900 monitor_printf(mon, "unexpected argument \"%s\"\n", op);
901 help_cmd(mon, "trace-file");
904 #endif
906 static void hmp_info_help(Monitor *mon, const QDict *qdict)
908 help_cmd(mon, "info");
911 CommandInfoList *qmp_query_commands(Error **errp)
913 CommandInfoList *info, *cmd_list = NULL;
914 const mon_cmd_t *cmd;
916 for (cmd = qmp_cmds; cmd->name != NULL; cmd++) {
917 info = g_malloc0(sizeof(*info));
918 info->value = g_malloc0(sizeof(*info->value));
919 info->value->name = g_strdup(cmd->name);
921 info->next = cmd_list;
922 cmd_list = info;
925 return cmd_list;
928 EventInfoList *qmp_query_events(Error **errp)
930 EventInfoList *info, *ev_list = NULL;
931 QAPIEvent e;
933 for (e = 0 ; e < QAPI_EVENT_MAX ; e++) {
934 const char *event_name = QAPIEvent_lookup[e];
935 assert(event_name != NULL);
936 info = g_malloc0(sizeof(*info));
937 info->value = g_malloc0(sizeof(*info->value));
938 info->value->name = g_strdup(event_name);
940 info->next = ev_list;
941 ev_list = info;
944 return ev_list;
947 /* set the current CPU defined by the user */
948 int monitor_set_cpu(int cpu_index)
950 CPUState *cpu;
952 cpu = qemu_get_cpu(cpu_index);
953 if (cpu == NULL) {
954 return -1;
956 cur_mon->mon_cpu = cpu;
957 return 0;
960 static CPUArchState *mon_get_cpu(void)
962 if (!cur_mon->mon_cpu) {
963 monitor_set_cpu(0);
965 cpu_synchronize_state(cur_mon->mon_cpu);
966 return cur_mon->mon_cpu->env_ptr;
969 int monitor_get_cpu_index(void)
971 CPUState *cpu = ENV_GET_CPU(mon_get_cpu());
972 return cpu->cpu_index;
975 static void hmp_info_registers(Monitor *mon, const QDict *qdict)
977 CPUState *cpu;
978 CPUArchState *env;
979 env = mon_get_cpu();
980 cpu = ENV_GET_CPU(env);
981 cpu_dump_state(cpu, (FILE *)mon, monitor_fprintf, CPU_DUMP_FPU);
984 static void hmp_info_jit(Monitor *mon, const QDict *qdict)
986 dump_exec_info((FILE *)mon, monitor_fprintf);
987 dump_drift_info((FILE *)mon, monitor_fprintf);
990 static void hmp_info_opcount(Monitor *mon, const QDict *qdict)
992 dump_opcount_info((FILE *)mon, monitor_fprintf);
995 static void hmp_info_history(Monitor *mon, const QDict *qdict)
997 int i;
998 const char *str;
1000 if (!mon->rs)
1001 return;
1002 i = 0;
1003 for(;;) {
1004 str = readline_get_history(mon->rs, i);
1005 if (!str)
1006 break;
1007 monitor_printf(mon, "%d: '%s'\n", i, str);
1008 i++;
1012 static void hmp_info_cpustats(Monitor *mon, const QDict *qdict)
1014 CPUState *cpu;
1015 CPUArchState *env;
1017 env = mon_get_cpu();
1018 cpu = ENV_GET_CPU(env);
1019 cpu_dump_statistics(cpu, (FILE *)mon, &monitor_fprintf, 0);
1022 static void hmp_info_trace_events(Monitor *mon, const QDict *qdict)
1024 TraceEventInfoList *events = qmp_trace_event_get_state("*", NULL);
1025 TraceEventInfoList *elem;
1027 for (elem = events; elem != NULL; elem = elem->next) {
1028 monitor_printf(mon, "%s : state %u\n",
1029 elem->value->name,
1030 elem->value->state == TRACE_EVENT_STATE_ENABLED ? 1 : 0);
1032 qapi_free_TraceEventInfoList(events);
1035 static int client_migrate_info(Monitor *mon, const QDict *qdict,
1036 QObject **ret_data)
1038 const char *protocol = qdict_get_str(qdict, "protocol");
1039 const char *hostname = qdict_get_str(qdict, "hostname");
1040 const char *subject = qdict_get_try_str(qdict, "cert-subject");
1041 int port = qdict_get_try_int(qdict, "port", -1);
1042 int tls_port = qdict_get_try_int(qdict, "tls-port", -1);
1043 Error *err = NULL;
1044 int ret;
1046 if (strcmp(protocol, "spice") == 0) {
1047 if (!qemu_using_spice(&err)) {
1048 qerror_report_err(err);
1049 error_free(err);
1050 return -1;
1053 if (port == -1 && tls_port == -1) {
1054 qerror_report(QERR_MISSING_PARAMETER, "port/tls-port");
1055 return -1;
1058 ret = qemu_spice_migrate_info(hostname, port, tls_port, subject);
1059 if (ret != 0) {
1060 qerror_report(QERR_UNDEFINED_ERROR);
1061 return -1;
1063 return 0;
1066 qerror_report(QERR_INVALID_PARAMETER_VALUE, "protocol", "spice");
1067 return -1;
1070 static void hmp_logfile(Monitor *mon, const QDict *qdict)
1072 qemu_set_log_filename(qdict_get_str(qdict, "filename"));
1075 static void hmp_log(Monitor *mon, const QDict *qdict)
1077 int mask;
1078 const char *items = qdict_get_str(qdict, "items");
1080 if (!strcmp(items, "none")) {
1081 mask = 0;
1082 } else {
1083 mask = qemu_str_to_log_mask(items);
1084 if (!mask) {
1085 help_cmd(mon, "log");
1086 return;
1089 qemu_set_log(mask);
1092 static void hmp_singlestep(Monitor *mon, const QDict *qdict)
1094 const char *option = qdict_get_try_str(qdict, "option");
1095 if (!option || !strcmp(option, "on")) {
1096 singlestep = 1;
1097 } else if (!strcmp(option, "off")) {
1098 singlestep = 0;
1099 } else {
1100 monitor_printf(mon, "unexpected option %s\n", option);
1104 static void hmp_gdbserver(Monitor *mon, const QDict *qdict)
1106 const char *device = qdict_get_try_str(qdict, "device");
1107 if (!device)
1108 device = "tcp::" DEFAULT_GDBSTUB_PORT;
1109 if (gdbserver_start(device) < 0) {
1110 monitor_printf(mon, "Could not open gdbserver on device '%s'\n",
1111 device);
1112 } else if (strcmp(device, "none") == 0) {
1113 monitor_printf(mon, "Disabled gdbserver\n");
1114 } else {
1115 monitor_printf(mon, "Waiting for gdb connection on device '%s'\n",
1116 device);
1120 static void hmp_watchdog_action(Monitor *mon, const QDict *qdict)
1122 const char *action = qdict_get_str(qdict, "action");
1123 if (select_watchdog_action(action) == -1) {
1124 monitor_printf(mon, "Unknown watchdog action '%s'\n", action);
1128 static void monitor_printc(Monitor *mon, int c)
1130 monitor_printf(mon, "'");
1131 switch(c) {
1132 case '\'':
1133 monitor_printf(mon, "\\'");
1134 break;
1135 case '\\':
1136 monitor_printf(mon, "\\\\");
1137 break;
1138 case '\n':
1139 monitor_printf(mon, "\\n");
1140 break;
1141 case '\r':
1142 monitor_printf(mon, "\\r");
1143 break;
1144 default:
1145 if (c >= 32 && c <= 126) {
1146 monitor_printf(mon, "%c", c);
1147 } else {
1148 monitor_printf(mon, "\\x%02x", c);
1150 break;
1152 monitor_printf(mon, "'");
1155 static void memory_dump(Monitor *mon, int count, int format, int wsize,
1156 hwaddr addr, int is_physical)
1158 CPUArchState *env;
1159 int l, line_size, i, max_digits, len;
1160 uint8_t buf[16];
1161 uint64_t v;
1163 if (format == 'i') {
1164 int flags;
1165 flags = 0;
1166 env = mon_get_cpu();
1167 #ifdef TARGET_I386
1168 if (wsize == 2) {
1169 flags = 1;
1170 } else if (wsize == 4) {
1171 flags = 0;
1172 } else {
1173 /* as default we use the current CS size */
1174 flags = 0;
1175 if (env) {
1176 #ifdef TARGET_X86_64
1177 if ((env->efer & MSR_EFER_LMA) &&
1178 (env->segs[R_CS].flags & DESC_L_MASK))
1179 flags = 2;
1180 else
1181 #endif
1182 if (!(env->segs[R_CS].flags & DESC_B_MASK))
1183 flags = 1;
1186 #endif
1187 #ifdef TARGET_PPC
1188 flags = msr_le << 16;
1189 flags |= env->bfd_mach;
1190 #endif
1191 monitor_disas(mon, env, addr, count, is_physical, flags);
1192 return;
1195 len = wsize * count;
1196 if (wsize == 1)
1197 line_size = 8;
1198 else
1199 line_size = 16;
1200 max_digits = 0;
1202 switch(format) {
1203 case 'o':
1204 max_digits = (wsize * 8 + 2) / 3;
1205 break;
1206 default:
1207 case 'x':
1208 max_digits = (wsize * 8) / 4;
1209 break;
1210 case 'u':
1211 case 'd':
1212 max_digits = (wsize * 8 * 10 + 32) / 33;
1213 break;
1214 case 'c':
1215 wsize = 1;
1216 break;
1219 while (len > 0) {
1220 if (is_physical)
1221 monitor_printf(mon, TARGET_FMT_plx ":", addr);
1222 else
1223 monitor_printf(mon, TARGET_FMT_lx ":", (target_ulong)addr);
1224 l = len;
1225 if (l > line_size)
1226 l = line_size;
1227 if (is_physical) {
1228 cpu_physical_memory_read(addr, buf, l);
1229 } else {
1230 env = mon_get_cpu();
1231 if (cpu_memory_rw_debug(ENV_GET_CPU(env), addr, buf, l, 0) < 0) {
1232 monitor_printf(mon, " Cannot access memory\n");
1233 break;
1236 i = 0;
1237 while (i < l) {
1238 switch(wsize) {
1239 default:
1240 case 1:
1241 v = ldub_p(buf + i);
1242 break;
1243 case 2:
1244 v = lduw_p(buf + i);
1245 break;
1246 case 4:
1247 v = (uint32_t)ldl_p(buf + i);
1248 break;
1249 case 8:
1250 v = ldq_p(buf + i);
1251 break;
1253 monitor_printf(mon, " ");
1254 switch(format) {
1255 case 'o':
1256 monitor_printf(mon, "%#*" PRIo64, max_digits, v);
1257 break;
1258 case 'x':
1259 monitor_printf(mon, "0x%0*" PRIx64, max_digits, v);
1260 break;
1261 case 'u':
1262 monitor_printf(mon, "%*" PRIu64, max_digits, v);
1263 break;
1264 case 'd':
1265 monitor_printf(mon, "%*" PRId64, max_digits, v);
1266 break;
1267 case 'c':
1268 monitor_printc(mon, v);
1269 break;
1271 i += wsize;
1273 monitor_printf(mon, "\n");
1274 addr += l;
1275 len -= l;
1279 static void hmp_memory_dump(Monitor *mon, const QDict *qdict)
1281 int count = qdict_get_int(qdict, "count");
1282 int format = qdict_get_int(qdict, "format");
1283 int size = qdict_get_int(qdict, "size");
1284 target_long addr = qdict_get_int(qdict, "addr");
1286 memory_dump(mon, count, format, size, addr, 0);
1289 static void hmp_physical_memory_dump(Monitor *mon, const QDict *qdict)
1291 int count = qdict_get_int(qdict, "count");
1292 int format = qdict_get_int(qdict, "format");
1293 int size = qdict_get_int(qdict, "size");
1294 hwaddr addr = qdict_get_int(qdict, "addr");
1296 memory_dump(mon, count, format, size, addr, 1);
1299 static void do_print(Monitor *mon, const QDict *qdict)
1301 int format = qdict_get_int(qdict, "format");
1302 hwaddr val = qdict_get_int(qdict, "val");
1304 switch(format) {
1305 case 'o':
1306 monitor_printf(mon, "%#" HWADDR_PRIo, val);
1307 break;
1308 case 'x':
1309 monitor_printf(mon, "%#" HWADDR_PRIx, val);
1310 break;
1311 case 'u':
1312 monitor_printf(mon, "%" HWADDR_PRIu, val);
1313 break;
1314 default:
1315 case 'd':
1316 monitor_printf(mon, "%" HWADDR_PRId, val);
1317 break;
1318 case 'c':
1319 monitor_printc(mon, val);
1320 break;
1322 monitor_printf(mon, "\n");
1325 static void hmp_sum(Monitor *mon, const QDict *qdict)
1327 uint32_t addr;
1328 uint16_t sum;
1329 uint32_t start = qdict_get_int(qdict, "start");
1330 uint32_t size = qdict_get_int(qdict, "size");
1332 sum = 0;
1333 for(addr = start; addr < (start + size); addr++) {
1334 uint8_t val = address_space_ldub(&address_space_memory, addr,
1335 MEMTXATTRS_UNSPECIFIED, NULL);
1336 /* BSD sum algorithm ('sum' Unix command) */
1337 sum = (sum >> 1) | (sum << 15);
1338 sum += val;
1340 monitor_printf(mon, "%05d\n", sum);
1343 static int mouse_button_state;
1345 static void hmp_mouse_move(Monitor *mon, const QDict *qdict)
1347 int dx, dy, dz, button;
1348 const char *dx_str = qdict_get_str(qdict, "dx_str");
1349 const char *dy_str = qdict_get_str(qdict, "dy_str");
1350 const char *dz_str = qdict_get_try_str(qdict, "dz_str");
1352 dx = strtol(dx_str, NULL, 0);
1353 dy = strtol(dy_str, NULL, 0);
1354 qemu_input_queue_rel(NULL, INPUT_AXIS_X, dx);
1355 qemu_input_queue_rel(NULL, INPUT_AXIS_Y, dy);
1357 if (dz_str) {
1358 dz = strtol(dz_str, NULL, 0);
1359 if (dz != 0) {
1360 button = (dz > 0) ? INPUT_BUTTON_WHEEL_UP : INPUT_BUTTON_WHEEL_DOWN;
1361 qemu_input_queue_btn(NULL, button, true);
1362 qemu_input_event_sync();
1363 qemu_input_queue_btn(NULL, button, false);
1366 qemu_input_event_sync();
1369 static void hmp_mouse_button(Monitor *mon, const QDict *qdict)
1371 static uint32_t bmap[INPUT_BUTTON_MAX] = {
1372 [INPUT_BUTTON_LEFT] = MOUSE_EVENT_LBUTTON,
1373 [INPUT_BUTTON_MIDDLE] = MOUSE_EVENT_MBUTTON,
1374 [INPUT_BUTTON_RIGHT] = MOUSE_EVENT_RBUTTON,
1376 int button_state = qdict_get_int(qdict, "button_state");
1378 if (mouse_button_state == button_state) {
1379 return;
1381 qemu_input_update_buttons(NULL, bmap, mouse_button_state, button_state);
1382 qemu_input_event_sync();
1383 mouse_button_state = button_state;
1386 static void hmp_ioport_read(Monitor *mon, const QDict *qdict)
1388 int size = qdict_get_int(qdict, "size");
1389 int addr = qdict_get_int(qdict, "addr");
1390 int has_index = qdict_haskey(qdict, "index");
1391 uint32_t val;
1392 int suffix;
1394 if (has_index) {
1395 int index = qdict_get_int(qdict, "index");
1396 cpu_outb(addr & IOPORTS_MASK, index & 0xff);
1397 addr++;
1399 addr &= 0xffff;
1401 switch(size) {
1402 default:
1403 case 1:
1404 val = cpu_inb(addr);
1405 suffix = 'b';
1406 break;
1407 case 2:
1408 val = cpu_inw(addr);
1409 suffix = 'w';
1410 break;
1411 case 4:
1412 val = cpu_inl(addr);
1413 suffix = 'l';
1414 break;
1416 monitor_printf(mon, "port%c[0x%04x] = %#0*x\n",
1417 suffix, addr, size * 2, val);
1420 static void hmp_ioport_write(Monitor *mon, const QDict *qdict)
1422 int size = qdict_get_int(qdict, "size");
1423 int addr = qdict_get_int(qdict, "addr");
1424 int val = qdict_get_int(qdict, "val");
1426 addr &= IOPORTS_MASK;
1428 switch (size) {
1429 default:
1430 case 1:
1431 cpu_outb(addr, val);
1432 break;
1433 case 2:
1434 cpu_outw(addr, val);
1435 break;
1436 case 4:
1437 cpu_outl(addr, val);
1438 break;
1442 static void hmp_boot_set(Monitor *mon, const QDict *qdict)
1444 Error *local_err = NULL;
1445 const char *bootdevice = qdict_get_str(qdict, "bootdevice");
1447 qemu_boot_set(bootdevice, &local_err);
1448 if (local_err) {
1449 monitor_printf(mon, "%s\n", error_get_pretty(local_err));
1450 error_free(local_err);
1451 } else {
1452 monitor_printf(mon, "boot device list now set to %s\n", bootdevice);
1456 #if defined(TARGET_I386)
1457 static void print_pte(Monitor *mon, hwaddr addr,
1458 hwaddr pte,
1459 hwaddr mask)
1461 #ifdef TARGET_X86_64
1462 if (addr & (1ULL << 47)) {
1463 addr |= -1LL << 48;
1465 #endif
1466 monitor_printf(mon, TARGET_FMT_plx ": " TARGET_FMT_plx
1467 " %c%c%c%c%c%c%c%c%c\n",
1468 addr,
1469 pte & mask,
1470 pte & PG_NX_MASK ? 'X' : '-',
1471 pte & PG_GLOBAL_MASK ? 'G' : '-',
1472 pte & PG_PSE_MASK ? 'P' : '-',
1473 pte & PG_DIRTY_MASK ? 'D' : '-',
1474 pte & PG_ACCESSED_MASK ? 'A' : '-',
1475 pte & PG_PCD_MASK ? 'C' : '-',
1476 pte & PG_PWT_MASK ? 'T' : '-',
1477 pte & PG_USER_MASK ? 'U' : '-',
1478 pte & PG_RW_MASK ? 'W' : '-');
1481 static void tlb_info_32(Monitor *mon, CPUArchState *env)
1483 unsigned int l1, l2;
1484 uint32_t pgd, pde, pte;
1486 pgd = env->cr[3] & ~0xfff;
1487 for(l1 = 0; l1 < 1024; l1++) {
1488 cpu_physical_memory_read(pgd + l1 * 4, &pde, 4);
1489 pde = le32_to_cpu(pde);
1490 if (pde & PG_PRESENT_MASK) {
1491 if ((pde & PG_PSE_MASK) && (env->cr[4] & CR4_PSE_MASK)) {
1492 /* 4M pages */
1493 print_pte(mon, (l1 << 22), pde, ~((1 << 21) - 1));
1494 } else {
1495 for(l2 = 0; l2 < 1024; l2++) {
1496 cpu_physical_memory_read((pde & ~0xfff) + l2 * 4, &pte, 4);
1497 pte = le32_to_cpu(pte);
1498 if (pte & PG_PRESENT_MASK) {
1499 print_pte(mon, (l1 << 22) + (l2 << 12),
1500 pte & ~PG_PSE_MASK,
1501 ~0xfff);
1509 static void tlb_info_pae32(Monitor *mon, CPUArchState *env)
1511 unsigned int l1, l2, l3;
1512 uint64_t pdpe, pde, pte;
1513 uint64_t pdp_addr, pd_addr, pt_addr;
1515 pdp_addr = env->cr[3] & ~0x1f;
1516 for (l1 = 0; l1 < 4; l1++) {
1517 cpu_physical_memory_read(pdp_addr + l1 * 8, &pdpe, 8);
1518 pdpe = le64_to_cpu(pdpe);
1519 if (pdpe & PG_PRESENT_MASK) {
1520 pd_addr = pdpe & 0x3fffffffff000ULL;
1521 for (l2 = 0; l2 < 512; l2++) {
1522 cpu_physical_memory_read(pd_addr + l2 * 8, &pde, 8);
1523 pde = le64_to_cpu(pde);
1524 if (pde & PG_PRESENT_MASK) {
1525 if (pde & PG_PSE_MASK) {
1526 /* 2M pages with PAE, CR4.PSE is ignored */
1527 print_pte(mon, (l1 << 30 ) + (l2 << 21), pde,
1528 ~((hwaddr)(1 << 20) - 1));
1529 } else {
1530 pt_addr = pde & 0x3fffffffff000ULL;
1531 for (l3 = 0; l3 < 512; l3++) {
1532 cpu_physical_memory_read(pt_addr + l3 * 8, &pte, 8);
1533 pte = le64_to_cpu(pte);
1534 if (pte & PG_PRESENT_MASK) {
1535 print_pte(mon, (l1 << 30 ) + (l2 << 21)
1536 + (l3 << 12),
1537 pte & ~PG_PSE_MASK,
1538 ~(hwaddr)0xfff);
1548 #ifdef TARGET_X86_64
1549 static void tlb_info_64(Monitor *mon, CPUArchState *env)
1551 uint64_t l1, l2, l3, l4;
1552 uint64_t pml4e, pdpe, pde, pte;
1553 uint64_t pml4_addr, pdp_addr, pd_addr, pt_addr;
1555 pml4_addr = env->cr[3] & 0x3fffffffff000ULL;
1556 for (l1 = 0; l1 < 512; l1++) {
1557 cpu_physical_memory_read(pml4_addr + l1 * 8, &pml4e, 8);
1558 pml4e = le64_to_cpu(pml4e);
1559 if (pml4e & PG_PRESENT_MASK) {
1560 pdp_addr = pml4e & 0x3fffffffff000ULL;
1561 for (l2 = 0; l2 < 512; l2++) {
1562 cpu_physical_memory_read(pdp_addr + l2 * 8, &pdpe, 8);
1563 pdpe = le64_to_cpu(pdpe);
1564 if (pdpe & PG_PRESENT_MASK) {
1565 if (pdpe & PG_PSE_MASK) {
1566 /* 1G pages, CR4.PSE is ignored */
1567 print_pte(mon, (l1 << 39) + (l2 << 30), pdpe,
1568 0x3ffffc0000000ULL);
1569 } else {
1570 pd_addr = pdpe & 0x3fffffffff000ULL;
1571 for (l3 = 0; l3 < 512; l3++) {
1572 cpu_physical_memory_read(pd_addr + l3 * 8, &pde, 8);
1573 pde = le64_to_cpu(pde);
1574 if (pde & PG_PRESENT_MASK) {
1575 if (pde & PG_PSE_MASK) {
1576 /* 2M pages, CR4.PSE is ignored */
1577 print_pte(mon, (l1 << 39) + (l2 << 30) +
1578 (l3 << 21), pde,
1579 0x3ffffffe00000ULL);
1580 } else {
1581 pt_addr = pde & 0x3fffffffff000ULL;
1582 for (l4 = 0; l4 < 512; l4++) {
1583 cpu_physical_memory_read(pt_addr
1584 + l4 * 8,
1585 &pte, 8);
1586 pte = le64_to_cpu(pte);
1587 if (pte & PG_PRESENT_MASK) {
1588 print_pte(mon, (l1 << 39) +
1589 (l2 << 30) +
1590 (l3 << 21) + (l4 << 12),
1591 pte & ~PG_PSE_MASK,
1592 0x3fffffffff000ULL);
1604 #endif
1606 static void hmp_info_tlb(Monitor *mon, const QDict *qdict)
1608 CPUArchState *env;
1610 env = mon_get_cpu();
1612 if (!(env->cr[0] & CR0_PG_MASK)) {
1613 monitor_printf(mon, "PG disabled\n");
1614 return;
1616 if (env->cr[4] & CR4_PAE_MASK) {
1617 #ifdef TARGET_X86_64
1618 if (env->hflags & HF_LMA_MASK) {
1619 tlb_info_64(mon, env);
1620 } else
1621 #endif
1623 tlb_info_pae32(mon, env);
1625 } else {
1626 tlb_info_32(mon, env);
1630 static void mem_print(Monitor *mon, hwaddr *pstart,
1631 int *plast_prot,
1632 hwaddr end, int prot)
1634 int prot1;
1635 prot1 = *plast_prot;
1636 if (prot != prot1) {
1637 if (*pstart != -1) {
1638 monitor_printf(mon, TARGET_FMT_plx "-" TARGET_FMT_plx " "
1639 TARGET_FMT_plx " %c%c%c\n",
1640 *pstart, end, end - *pstart,
1641 prot1 & PG_USER_MASK ? 'u' : '-',
1642 'r',
1643 prot1 & PG_RW_MASK ? 'w' : '-');
1645 if (prot != 0)
1646 *pstart = end;
1647 else
1648 *pstart = -1;
1649 *plast_prot = prot;
1653 static void mem_info_32(Monitor *mon, CPUArchState *env)
1655 unsigned int l1, l2;
1656 int prot, last_prot;
1657 uint32_t pgd, pde, pte;
1658 hwaddr start, end;
1660 pgd = env->cr[3] & ~0xfff;
1661 last_prot = 0;
1662 start = -1;
1663 for(l1 = 0; l1 < 1024; l1++) {
1664 cpu_physical_memory_read(pgd + l1 * 4, &pde, 4);
1665 pde = le32_to_cpu(pde);
1666 end = l1 << 22;
1667 if (pde & PG_PRESENT_MASK) {
1668 if ((pde & PG_PSE_MASK) && (env->cr[4] & CR4_PSE_MASK)) {
1669 prot = pde & (PG_USER_MASK | PG_RW_MASK | PG_PRESENT_MASK);
1670 mem_print(mon, &start, &last_prot, end, prot);
1671 } else {
1672 for(l2 = 0; l2 < 1024; l2++) {
1673 cpu_physical_memory_read((pde & ~0xfff) + l2 * 4, &pte, 4);
1674 pte = le32_to_cpu(pte);
1675 end = (l1 << 22) + (l2 << 12);
1676 if (pte & PG_PRESENT_MASK) {
1677 prot = pte & pde &
1678 (PG_USER_MASK | PG_RW_MASK | PG_PRESENT_MASK);
1679 } else {
1680 prot = 0;
1682 mem_print(mon, &start, &last_prot, end, prot);
1685 } else {
1686 prot = 0;
1687 mem_print(mon, &start, &last_prot, end, prot);
1690 /* Flush last range */
1691 mem_print(mon, &start, &last_prot, (hwaddr)1 << 32, 0);
1694 static void mem_info_pae32(Monitor *mon, CPUArchState *env)
1696 unsigned int l1, l2, l3;
1697 int prot, last_prot;
1698 uint64_t pdpe, pde, pte;
1699 uint64_t pdp_addr, pd_addr, pt_addr;
1700 hwaddr start, end;
1702 pdp_addr = env->cr[3] & ~0x1f;
1703 last_prot = 0;
1704 start = -1;
1705 for (l1 = 0; l1 < 4; l1++) {
1706 cpu_physical_memory_read(pdp_addr + l1 * 8, &pdpe, 8);
1707 pdpe = le64_to_cpu(pdpe);
1708 end = l1 << 30;
1709 if (pdpe & PG_PRESENT_MASK) {
1710 pd_addr = pdpe & 0x3fffffffff000ULL;
1711 for (l2 = 0; l2 < 512; l2++) {
1712 cpu_physical_memory_read(pd_addr + l2 * 8, &pde, 8);
1713 pde = le64_to_cpu(pde);
1714 end = (l1 << 30) + (l2 << 21);
1715 if (pde & PG_PRESENT_MASK) {
1716 if (pde & PG_PSE_MASK) {
1717 prot = pde & (PG_USER_MASK | PG_RW_MASK |
1718 PG_PRESENT_MASK);
1719 mem_print(mon, &start, &last_prot, end, prot);
1720 } else {
1721 pt_addr = pde & 0x3fffffffff000ULL;
1722 for (l3 = 0; l3 < 512; l3++) {
1723 cpu_physical_memory_read(pt_addr + l3 * 8, &pte, 8);
1724 pte = le64_to_cpu(pte);
1725 end = (l1 << 30) + (l2 << 21) + (l3 << 12);
1726 if (pte & PG_PRESENT_MASK) {
1727 prot = pte & pde & (PG_USER_MASK | PG_RW_MASK |
1728 PG_PRESENT_MASK);
1729 } else {
1730 prot = 0;
1732 mem_print(mon, &start, &last_prot, end, prot);
1735 } else {
1736 prot = 0;
1737 mem_print(mon, &start, &last_prot, end, prot);
1740 } else {
1741 prot = 0;
1742 mem_print(mon, &start, &last_prot, end, prot);
1745 /* Flush last range */
1746 mem_print(mon, &start, &last_prot, (hwaddr)1 << 32, 0);
1750 #ifdef TARGET_X86_64
1751 static void mem_info_64(Monitor *mon, CPUArchState *env)
1753 int prot, last_prot;
1754 uint64_t l1, l2, l3, l4;
1755 uint64_t pml4e, pdpe, pde, pte;
1756 uint64_t pml4_addr, pdp_addr, pd_addr, pt_addr, start, end;
1758 pml4_addr = env->cr[3] & 0x3fffffffff000ULL;
1759 last_prot = 0;
1760 start = -1;
1761 for (l1 = 0; l1 < 512; l1++) {
1762 cpu_physical_memory_read(pml4_addr + l1 * 8, &pml4e, 8);
1763 pml4e = le64_to_cpu(pml4e);
1764 end = l1 << 39;
1765 if (pml4e & PG_PRESENT_MASK) {
1766 pdp_addr = pml4e & 0x3fffffffff000ULL;
1767 for (l2 = 0; l2 < 512; l2++) {
1768 cpu_physical_memory_read(pdp_addr + l2 * 8, &pdpe, 8);
1769 pdpe = le64_to_cpu(pdpe);
1770 end = (l1 << 39) + (l2 << 30);
1771 if (pdpe & PG_PRESENT_MASK) {
1772 if (pdpe & PG_PSE_MASK) {
1773 prot = pdpe & (PG_USER_MASK | PG_RW_MASK |
1774 PG_PRESENT_MASK);
1775 prot &= pml4e;
1776 mem_print(mon, &start, &last_prot, end, prot);
1777 } else {
1778 pd_addr = pdpe & 0x3fffffffff000ULL;
1779 for (l3 = 0; l3 < 512; l3++) {
1780 cpu_physical_memory_read(pd_addr + l3 * 8, &pde, 8);
1781 pde = le64_to_cpu(pde);
1782 end = (l1 << 39) + (l2 << 30) + (l3 << 21);
1783 if (pde & PG_PRESENT_MASK) {
1784 if (pde & PG_PSE_MASK) {
1785 prot = pde & (PG_USER_MASK | PG_RW_MASK |
1786 PG_PRESENT_MASK);
1787 prot &= pml4e & pdpe;
1788 mem_print(mon, &start, &last_prot, end, prot);
1789 } else {
1790 pt_addr = pde & 0x3fffffffff000ULL;
1791 for (l4 = 0; l4 < 512; l4++) {
1792 cpu_physical_memory_read(pt_addr
1793 + l4 * 8,
1794 &pte, 8);
1795 pte = le64_to_cpu(pte);
1796 end = (l1 << 39) + (l2 << 30) +
1797 (l3 << 21) + (l4 << 12);
1798 if (pte & PG_PRESENT_MASK) {
1799 prot = pte & (PG_USER_MASK | PG_RW_MASK |
1800 PG_PRESENT_MASK);
1801 prot &= pml4e & pdpe & pde;
1802 } else {
1803 prot = 0;
1805 mem_print(mon, &start, &last_prot, end, prot);
1808 } else {
1809 prot = 0;
1810 mem_print(mon, &start, &last_prot, end, prot);
1814 } else {
1815 prot = 0;
1816 mem_print(mon, &start, &last_prot, end, prot);
1819 } else {
1820 prot = 0;
1821 mem_print(mon, &start, &last_prot, end, prot);
1824 /* Flush last range */
1825 mem_print(mon, &start, &last_prot, (hwaddr)1 << 48, 0);
1827 #endif
1829 static void hmp_info_mem(Monitor *mon, const QDict *qdict)
1831 CPUArchState *env;
1833 env = mon_get_cpu();
1835 if (!(env->cr[0] & CR0_PG_MASK)) {
1836 monitor_printf(mon, "PG disabled\n");
1837 return;
1839 if (env->cr[4] & CR4_PAE_MASK) {
1840 #ifdef TARGET_X86_64
1841 if (env->hflags & HF_LMA_MASK) {
1842 mem_info_64(mon, env);
1843 } else
1844 #endif
1846 mem_info_pae32(mon, env);
1848 } else {
1849 mem_info_32(mon, env);
1852 #endif
1854 #if defined(TARGET_SH4)
1856 static void print_tlb(Monitor *mon, int idx, tlb_t *tlb)
1858 monitor_printf(mon, " tlb%i:\t"
1859 "asid=%hhu vpn=%x\tppn=%x\tsz=%hhu size=%u\t"
1860 "v=%hhu shared=%hhu cached=%hhu prot=%hhu "
1861 "dirty=%hhu writethrough=%hhu\n",
1862 idx,
1863 tlb->asid, tlb->vpn, tlb->ppn, tlb->sz, tlb->size,
1864 tlb->v, tlb->sh, tlb->c, tlb->pr,
1865 tlb->d, tlb->wt);
1868 static void hmp_info_tlb(Monitor *mon, const QDict *qdict)
1870 CPUArchState *env = mon_get_cpu();
1871 int i;
1873 monitor_printf (mon, "ITLB:\n");
1874 for (i = 0 ; i < ITLB_SIZE ; i++)
1875 print_tlb (mon, i, &env->itlb[i]);
1876 monitor_printf (mon, "UTLB:\n");
1877 for (i = 0 ; i < UTLB_SIZE ; i++)
1878 print_tlb (mon, i, &env->utlb[i]);
1881 #endif
1883 #if defined(TARGET_SPARC) || defined(TARGET_PPC) || defined(TARGET_XTENSA)
1884 static void hmp_info_tlb(Monitor *mon, const QDict *qdict)
1886 CPUArchState *env1 = mon_get_cpu();
1888 dump_mmu((FILE*)mon, (fprintf_function)monitor_printf, env1);
1890 #endif
1892 static void hmp_info_mtree(Monitor *mon, const QDict *qdict)
1894 mtree_info((fprintf_function)monitor_printf, mon);
1897 static void hmp_info_numa(Monitor *mon, const QDict *qdict)
1899 int i;
1900 CPUState *cpu;
1901 uint64_t *node_mem;
1903 node_mem = g_new0(uint64_t, nb_numa_nodes);
1904 query_numa_node_mem(node_mem);
1905 monitor_printf(mon, "%d nodes\n", nb_numa_nodes);
1906 for (i = 0; i < nb_numa_nodes; i++) {
1907 monitor_printf(mon, "node %d cpus:", i);
1908 CPU_FOREACH(cpu) {
1909 if (cpu->numa_node == i) {
1910 monitor_printf(mon, " %d", cpu->cpu_index);
1913 monitor_printf(mon, "\n");
1914 monitor_printf(mon, "node %d size: %" PRId64 " MB\n", i,
1915 node_mem[i] >> 20);
1917 g_free(node_mem);
1920 #ifdef CONFIG_PROFILER
1922 int64_t tcg_time;
1923 int64_t dev_time;
1925 static void hmp_info_profile(Monitor *mon, const QDict *qdict)
1927 monitor_printf(mon, "async time %" PRId64 " (%0.3f)\n",
1928 dev_time, dev_time / (double)get_ticks_per_sec());
1929 monitor_printf(mon, "qemu time %" PRId64 " (%0.3f)\n",
1930 tcg_time, tcg_time / (double)get_ticks_per_sec());
1931 tcg_time = 0;
1932 dev_time = 0;
1934 #else
1935 static void hmp_info_profile(Monitor *mon, const QDict *qdict)
1937 monitor_printf(mon, "Internal profiler not compiled\n");
1939 #endif
1941 /* Capture support */
1942 static QLIST_HEAD (capture_list_head, CaptureState) capture_head;
1944 static void hmp_info_capture(Monitor *mon, const QDict *qdict)
1946 int i;
1947 CaptureState *s;
1949 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
1950 monitor_printf(mon, "[%d]: ", i);
1951 s->ops.info (s->opaque);
1955 static void hmp_stopcapture(Monitor *mon, const QDict *qdict)
1957 int i;
1958 int n = qdict_get_int(qdict, "n");
1959 CaptureState *s;
1961 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
1962 if (i == n) {
1963 s->ops.destroy (s->opaque);
1964 QLIST_REMOVE (s, entries);
1965 g_free (s);
1966 return;
1971 static void hmp_wavcapture(Monitor *mon, const QDict *qdict)
1973 const char *path = qdict_get_str(qdict, "path");
1974 int has_freq = qdict_haskey(qdict, "freq");
1975 int freq = qdict_get_try_int(qdict, "freq", -1);
1976 int has_bits = qdict_haskey(qdict, "bits");
1977 int bits = qdict_get_try_int(qdict, "bits", -1);
1978 int has_channels = qdict_haskey(qdict, "nchannels");
1979 int nchannels = qdict_get_try_int(qdict, "nchannels", -1);
1980 CaptureState *s;
1982 s = g_malloc0 (sizeof (*s));
1984 freq = has_freq ? freq : 44100;
1985 bits = has_bits ? bits : 16;
1986 nchannels = has_channels ? nchannels : 2;
1988 if (wav_start_capture (s, path, freq, bits, nchannels)) {
1989 monitor_printf(mon, "Failed to add wave capture\n");
1990 g_free (s);
1991 return;
1993 QLIST_INSERT_HEAD (&capture_head, s, entries);
1996 static qemu_acl *find_acl(Monitor *mon, const char *name)
1998 qemu_acl *acl = qemu_acl_find(name);
2000 if (!acl) {
2001 monitor_printf(mon, "acl: unknown list '%s'\n", name);
2003 return acl;
2006 static void hmp_acl_show(Monitor *mon, const QDict *qdict)
2008 const char *aclname = qdict_get_str(qdict, "aclname");
2009 qemu_acl *acl = find_acl(mon, aclname);
2010 qemu_acl_entry *entry;
2011 int i = 0;
2013 if (acl) {
2014 monitor_printf(mon, "policy: %s\n",
2015 acl->defaultDeny ? "deny" : "allow");
2016 QTAILQ_FOREACH(entry, &acl->entries, next) {
2017 i++;
2018 monitor_printf(mon, "%d: %s %s\n", i,
2019 entry->deny ? "deny" : "allow", entry->match);
2024 static void hmp_acl_reset(Monitor *mon, const QDict *qdict)
2026 const char *aclname = qdict_get_str(qdict, "aclname");
2027 qemu_acl *acl = find_acl(mon, aclname);
2029 if (acl) {
2030 qemu_acl_reset(acl);
2031 monitor_printf(mon, "acl: removed all rules\n");
2035 static void hmp_acl_policy(Monitor *mon, const QDict *qdict)
2037 const char *aclname = qdict_get_str(qdict, "aclname");
2038 const char *policy = qdict_get_str(qdict, "policy");
2039 qemu_acl *acl = find_acl(mon, aclname);
2041 if (acl) {
2042 if (strcmp(policy, "allow") == 0) {
2043 acl->defaultDeny = 0;
2044 monitor_printf(mon, "acl: policy set to 'allow'\n");
2045 } else if (strcmp(policy, "deny") == 0) {
2046 acl->defaultDeny = 1;
2047 monitor_printf(mon, "acl: policy set to 'deny'\n");
2048 } else {
2049 monitor_printf(mon, "acl: unknown policy '%s', "
2050 "expected 'deny' or 'allow'\n", policy);
2055 static void hmp_acl_add(Monitor *mon, const QDict *qdict)
2057 const char *aclname = qdict_get_str(qdict, "aclname");
2058 const char *match = qdict_get_str(qdict, "match");
2059 const char *policy = qdict_get_str(qdict, "policy");
2060 int has_index = qdict_haskey(qdict, "index");
2061 int index = qdict_get_try_int(qdict, "index", -1);
2062 qemu_acl *acl = find_acl(mon, aclname);
2063 int deny, ret;
2065 if (acl) {
2066 if (strcmp(policy, "allow") == 0) {
2067 deny = 0;
2068 } else if (strcmp(policy, "deny") == 0) {
2069 deny = 1;
2070 } else {
2071 monitor_printf(mon, "acl: unknown policy '%s', "
2072 "expected 'deny' or 'allow'\n", policy);
2073 return;
2075 if (has_index)
2076 ret = qemu_acl_insert(acl, deny, match, index);
2077 else
2078 ret = qemu_acl_append(acl, deny, match);
2079 if (ret < 0)
2080 monitor_printf(mon, "acl: unable to add acl entry\n");
2081 else
2082 monitor_printf(mon, "acl: added rule at position %d\n", ret);
2086 static void hmp_acl_remove(Monitor *mon, const QDict *qdict)
2088 const char *aclname = qdict_get_str(qdict, "aclname");
2089 const char *match = qdict_get_str(qdict, "match");
2090 qemu_acl *acl = find_acl(mon, aclname);
2091 int ret;
2093 if (acl) {
2094 ret = qemu_acl_remove(acl, match);
2095 if (ret < 0)
2096 monitor_printf(mon, "acl: no matching acl entry\n");
2097 else
2098 monitor_printf(mon, "acl: removed rule at position %d\n", ret);
2102 #if defined(TARGET_I386)
2103 static void hmp_mce(Monitor *mon, const QDict *qdict)
2105 X86CPU *cpu;
2106 CPUState *cs;
2107 int cpu_index = qdict_get_int(qdict, "cpu_index");
2108 int bank = qdict_get_int(qdict, "bank");
2109 uint64_t status = qdict_get_int(qdict, "status");
2110 uint64_t mcg_status = qdict_get_int(qdict, "mcg_status");
2111 uint64_t addr = qdict_get_int(qdict, "addr");
2112 uint64_t misc = qdict_get_int(qdict, "misc");
2113 int flags = MCE_INJECT_UNCOND_AO;
2115 if (qdict_get_try_bool(qdict, "broadcast", 0)) {
2116 flags |= MCE_INJECT_BROADCAST;
2118 cs = qemu_get_cpu(cpu_index);
2119 if (cs != NULL) {
2120 cpu = X86_CPU(cs);
2121 cpu_x86_inject_mce(mon, cpu, bank, status, mcg_status, addr, misc,
2122 flags);
2125 #endif
2127 void qmp_getfd(const char *fdname, Error **errp)
2129 mon_fd_t *monfd;
2130 int fd;
2132 fd = qemu_chr_fe_get_msgfd(cur_mon->chr);
2133 if (fd == -1) {
2134 error_set(errp, QERR_FD_NOT_SUPPLIED);
2135 return;
2138 if (qemu_isdigit(fdname[0])) {
2139 close(fd);
2140 error_set(errp, QERR_INVALID_PARAMETER_VALUE, "fdname",
2141 "a name not starting with a digit");
2142 return;
2145 QLIST_FOREACH(monfd, &cur_mon->fds, next) {
2146 if (strcmp(monfd->name, fdname) != 0) {
2147 continue;
2150 close(monfd->fd);
2151 monfd->fd = fd;
2152 return;
2155 monfd = g_malloc0(sizeof(mon_fd_t));
2156 monfd->name = g_strdup(fdname);
2157 monfd->fd = fd;
2159 QLIST_INSERT_HEAD(&cur_mon->fds, monfd, next);
2162 void qmp_closefd(const char *fdname, Error **errp)
2164 mon_fd_t *monfd;
2166 QLIST_FOREACH(monfd, &cur_mon->fds, next) {
2167 if (strcmp(monfd->name, fdname) != 0) {
2168 continue;
2171 QLIST_REMOVE(monfd, next);
2172 close(monfd->fd);
2173 g_free(monfd->name);
2174 g_free(monfd);
2175 return;
2178 error_set(errp, QERR_FD_NOT_FOUND, fdname);
2181 static void hmp_loadvm(Monitor *mon, const QDict *qdict)
2183 int saved_vm_running = runstate_is_running();
2184 const char *name = qdict_get_str(qdict, "name");
2186 vm_stop(RUN_STATE_RESTORE_VM);
2188 if (load_vmstate(name) == 0 && saved_vm_running) {
2189 vm_start();
2193 int monitor_get_fd(Monitor *mon, const char *fdname, Error **errp)
2195 mon_fd_t *monfd;
2197 QLIST_FOREACH(monfd, &mon->fds, next) {
2198 int fd;
2200 if (strcmp(monfd->name, fdname) != 0) {
2201 continue;
2204 fd = monfd->fd;
2206 /* caller takes ownership of fd */
2207 QLIST_REMOVE(monfd, next);
2208 g_free(monfd->name);
2209 g_free(monfd);
2211 return fd;
2214 error_setg(errp, "File descriptor named '%s' has not been found", fdname);
2215 return -1;
2218 static void monitor_fdset_cleanup(MonFdset *mon_fdset)
2220 MonFdsetFd *mon_fdset_fd;
2221 MonFdsetFd *mon_fdset_fd_next;
2223 QLIST_FOREACH_SAFE(mon_fdset_fd, &mon_fdset->fds, next, mon_fdset_fd_next) {
2224 if ((mon_fdset_fd->removed ||
2225 (QLIST_EMPTY(&mon_fdset->dup_fds) && mon_refcount == 0)) &&
2226 runstate_is_running()) {
2227 close(mon_fdset_fd->fd);
2228 g_free(mon_fdset_fd->opaque);
2229 QLIST_REMOVE(mon_fdset_fd, next);
2230 g_free(mon_fdset_fd);
2234 if (QLIST_EMPTY(&mon_fdset->fds) && QLIST_EMPTY(&mon_fdset->dup_fds)) {
2235 QLIST_REMOVE(mon_fdset, next);
2236 g_free(mon_fdset);
2240 static void monitor_fdsets_cleanup(void)
2242 MonFdset *mon_fdset;
2243 MonFdset *mon_fdset_next;
2245 QLIST_FOREACH_SAFE(mon_fdset, &mon_fdsets, next, mon_fdset_next) {
2246 monitor_fdset_cleanup(mon_fdset);
2250 AddfdInfo *qmp_add_fd(bool has_fdset_id, int64_t fdset_id, bool has_opaque,
2251 const char *opaque, Error **errp)
2253 int fd;
2254 Monitor *mon = cur_mon;
2255 AddfdInfo *fdinfo;
2257 fd = qemu_chr_fe_get_msgfd(mon->chr);
2258 if (fd == -1) {
2259 error_set(errp, QERR_FD_NOT_SUPPLIED);
2260 goto error;
2263 fdinfo = monitor_fdset_add_fd(fd, has_fdset_id, fdset_id,
2264 has_opaque, opaque, errp);
2265 if (fdinfo) {
2266 return fdinfo;
2269 error:
2270 if (fd != -1) {
2271 close(fd);
2273 return NULL;
2276 void qmp_remove_fd(int64_t fdset_id, bool has_fd, int64_t fd, Error **errp)
2278 MonFdset *mon_fdset;
2279 MonFdsetFd *mon_fdset_fd;
2280 char fd_str[60];
2282 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2283 if (mon_fdset->id != fdset_id) {
2284 continue;
2286 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2287 if (has_fd) {
2288 if (mon_fdset_fd->fd != fd) {
2289 continue;
2291 mon_fdset_fd->removed = true;
2292 break;
2293 } else {
2294 mon_fdset_fd->removed = true;
2297 if (has_fd && !mon_fdset_fd) {
2298 goto error;
2300 monitor_fdset_cleanup(mon_fdset);
2301 return;
2304 error:
2305 if (has_fd) {
2306 snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64 ", fd:%" PRId64,
2307 fdset_id, fd);
2308 } else {
2309 snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64, fdset_id);
2311 error_set(errp, QERR_FD_NOT_FOUND, fd_str);
2314 FdsetInfoList *qmp_query_fdsets(Error **errp)
2316 MonFdset *mon_fdset;
2317 MonFdsetFd *mon_fdset_fd;
2318 FdsetInfoList *fdset_list = NULL;
2320 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2321 FdsetInfoList *fdset_info = g_malloc0(sizeof(*fdset_info));
2322 FdsetFdInfoList *fdsetfd_list = NULL;
2324 fdset_info->value = g_malloc0(sizeof(*fdset_info->value));
2325 fdset_info->value->fdset_id = mon_fdset->id;
2327 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2328 FdsetFdInfoList *fdsetfd_info;
2330 fdsetfd_info = g_malloc0(sizeof(*fdsetfd_info));
2331 fdsetfd_info->value = g_malloc0(sizeof(*fdsetfd_info->value));
2332 fdsetfd_info->value->fd = mon_fdset_fd->fd;
2333 if (mon_fdset_fd->opaque) {
2334 fdsetfd_info->value->has_opaque = true;
2335 fdsetfd_info->value->opaque = g_strdup(mon_fdset_fd->opaque);
2336 } else {
2337 fdsetfd_info->value->has_opaque = false;
2340 fdsetfd_info->next = fdsetfd_list;
2341 fdsetfd_list = fdsetfd_info;
2344 fdset_info->value->fds = fdsetfd_list;
2346 fdset_info->next = fdset_list;
2347 fdset_list = fdset_info;
2350 return fdset_list;
2353 AddfdInfo *monitor_fdset_add_fd(int fd, bool has_fdset_id, int64_t fdset_id,
2354 bool has_opaque, const char *opaque,
2355 Error **errp)
2357 MonFdset *mon_fdset = NULL;
2358 MonFdsetFd *mon_fdset_fd;
2359 AddfdInfo *fdinfo;
2361 if (has_fdset_id) {
2362 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2363 /* Break if match found or match impossible due to ordering by ID */
2364 if (fdset_id <= mon_fdset->id) {
2365 if (fdset_id < mon_fdset->id) {
2366 mon_fdset = NULL;
2368 break;
2373 if (mon_fdset == NULL) {
2374 int64_t fdset_id_prev = -1;
2375 MonFdset *mon_fdset_cur = QLIST_FIRST(&mon_fdsets);
2377 if (has_fdset_id) {
2378 if (fdset_id < 0) {
2379 error_set(errp, QERR_INVALID_PARAMETER_VALUE, "fdset-id",
2380 "a non-negative value");
2381 return NULL;
2383 /* Use specified fdset ID */
2384 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2385 mon_fdset_cur = mon_fdset;
2386 if (fdset_id < mon_fdset_cur->id) {
2387 break;
2390 } else {
2391 /* Use first available fdset ID */
2392 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2393 mon_fdset_cur = mon_fdset;
2394 if (fdset_id_prev == mon_fdset_cur->id - 1) {
2395 fdset_id_prev = mon_fdset_cur->id;
2396 continue;
2398 break;
2402 mon_fdset = g_malloc0(sizeof(*mon_fdset));
2403 if (has_fdset_id) {
2404 mon_fdset->id = fdset_id;
2405 } else {
2406 mon_fdset->id = fdset_id_prev + 1;
2409 /* The fdset list is ordered by fdset ID */
2410 if (!mon_fdset_cur) {
2411 QLIST_INSERT_HEAD(&mon_fdsets, mon_fdset, next);
2412 } else if (mon_fdset->id < mon_fdset_cur->id) {
2413 QLIST_INSERT_BEFORE(mon_fdset_cur, mon_fdset, next);
2414 } else {
2415 QLIST_INSERT_AFTER(mon_fdset_cur, mon_fdset, next);
2419 mon_fdset_fd = g_malloc0(sizeof(*mon_fdset_fd));
2420 mon_fdset_fd->fd = fd;
2421 mon_fdset_fd->removed = false;
2422 if (has_opaque) {
2423 mon_fdset_fd->opaque = g_strdup(opaque);
2425 QLIST_INSERT_HEAD(&mon_fdset->fds, mon_fdset_fd, next);
2427 fdinfo = g_malloc0(sizeof(*fdinfo));
2428 fdinfo->fdset_id = mon_fdset->id;
2429 fdinfo->fd = mon_fdset_fd->fd;
2431 return fdinfo;
2434 int monitor_fdset_get_fd(int64_t fdset_id, int flags)
2436 #ifndef _WIN32
2437 MonFdset *mon_fdset;
2438 MonFdsetFd *mon_fdset_fd;
2439 int mon_fd_flags;
2441 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2442 if (mon_fdset->id != fdset_id) {
2443 continue;
2445 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2446 mon_fd_flags = fcntl(mon_fdset_fd->fd, F_GETFL);
2447 if (mon_fd_flags == -1) {
2448 return -1;
2451 if ((flags & O_ACCMODE) == (mon_fd_flags & O_ACCMODE)) {
2452 return mon_fdset_fd->fd;
2455 errno = EACCES;
2456 return -1;
2458 #endif
2460 errno = ENOENT;
2461 return -1;
2464 int monitor_fdset_dup_fd_add(int64_t fdset_id, int dup_fd)
2466 MonFdset *mon_fdset;
2467 MonFdsetFd *mon_fdset_fd_dup;
2469 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2470 if (mon_fdset->id != fdset_id) {
2471 continue;
2473 QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
2474 if (mon_fdset_fd_dup->fd == dup_fd) {
2475 return -1;
2478 mon_fdset_fd_dup = g_malloc0(sizeof(*mon_fdset_fd_dup));
2479 mon_fdset_fd_dup->fd = dup_fd;
2480 QLIST_INSERT_HEAD(&mon_fdset->dup_fds, mon_fdset_fd_dup, next);
2481 return 0;
2483 return -1;
2486 static int monitor_fdset_dup_fd_find_remove(int dup_fd, bool remove)
2488 MonFdset *mon_fdset;
2489 MonFdsetFd *mon_fdset_fd_dup;
2491 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2492 QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
2493 if (mon_fdset_fd_dup->fd == dup_fd) {
2494 if (remove) {
2495 QLIST_REMOVE(mon_fdset_fd_dup, next);
2496 if (QLIST_EMPTY(&mon_fdset->dup_fds)) {
2497 monitor_fdset_cleanup(mon_fdset);
2499 return -1;
2500 } else {
2501 return mon_fdset->id;
2506 return -1;
2509 int monitor_fdset_dup_fd_find(int dup_fd)
2511 return monitor_fdset_dup_fd_find_remove(dup_fd, false);
2514 void monitor_fdset_dup_fd_remove(int dup_fd)
2516 monitor_fdset_dup_fd_find_remove(dup_fd, true);
2519 int monitor_fd_param(Monitor *mon, const char *fdname, Error **errp)
2521 int fd;
2522 Error *local_err = NULL;
2524 if (!qemu_isdigit(fdname[0]) && mon) {
2525 fd = monitor_get_fd(mon, fdname, &local_err);
2526 } else {
2527 fd = qemu_parse_fd(fdname);
2528 if (fd == -1) {
2529 error_setg(&local_err, "Invalid file descriptor number '%s'",
2530 fdname);
2533 if (local_err) {
2534 error_propagate(errp, local_err);
2535 assert(fd == -1);
2536 } else {
2537 assert(fd != -1);
2540 return fd;
2543 /* Please update hmp-commands.hx when adding or changing commands */
2544 static mon_cmd_t info_cmds[] = {
2546 .name = "version",
2547 .args_type = "",
2548 .params = "",
2549 .help = "show the version of QEMU",
2550 .mhandler.cmd = hmp_info_version,
2553 .name = "network",
2554 .args_type = "",
2555 .params = "",
2556 .help = "show the network state",
2557 .mhandler.cmd = hmp_info_network,
2560 .name = "chardev",
2561 .args_type = "",
2562 .params = "",
2563 .help = "show the character devices",
2564 .mhandler.cmd = hmp_info_chardev,
2567 .name = "block",
2568 .args_type = "nodes:-n,verbose:-v,device:B?",
2569 .params = "[-n] [-v] [device]",
2570 .help = "show info of one block device or all block devices "
2571 "(-n: show named nodes; -v: show details)",
2572 .mhandler.cmd = hmp_info_block,
2575 .name = "blockstats",
2576 .args_type = "",
2577 .params = "",
2578 .help = "show block device statistics",
2579 .mhandler.cmd = hmp_info_blockstats,
2582 .name = "block-jobs",
2583 .args_type = "",
2584 .params = "",
2585 .help = "show progress of ongoing block device operations",
2586 .mhandler.cmd = hmp_info_block_jobs,
2589 .name = "registers",
2590 .args_type = "",
2591 .params = "",
2592 .help = "show the cpu registers",
2593 .mhandler.cmd = hmp_info_registers,
2596 .name = "cpus",
2597 .args_type = "",
2598 .params = "",
2599 .help = "show infos for each CPU",
2600 .mhandler.cmd = hmp_info_cpus,
2603 .name = "history",
2604 .args_type = "",
2605 .params = "",
2606 .help = "show the command line history",
2607 .mhandler.cmd = hmp_info_history,
2609 #if defined(TARGET_I386) || defined(TARGET_PPC) || defined(TARGET_MIPS) || \
2610 defined(TARGET_LM32) || (defined(TARGET_SPARC) && !defined(TARGET_SPARC64))
2612 .name = "irq",
2613 .args_type = "",
2614 .params = "",
2615 .help = "show the interrupts statistics (if available)",
2616 #ifdef TARGET_SPARC
2617 .mhandler.cmd = sun4m_hmp_info_irq,
2618 #elif defined(TARGET_LM32)
2619 .mhandler.cmd = lm32_hmp_info_irq,
2620 #else
2621 .mhandler.cmd = hmp_info_irq,
2622 #endif
2625 .name = "pic",
2626 .args_type = "",
2627 .params = "",
2628 .help = "show i8259 (PIC) state",
2629 #ifdef TARGET_SPARC
2630 .mhandler.cmd = sun4m_hmp_info_pic,
2631 #elif defined(TARGET_LM32)
2632 .mhandler.cmd = lm32_hmp_info_pic,
2633 #else
2634 .mhandler.cmd = hmp_info_pic,
2635 #endif
2637 #endif
2639 .name = "pci",
2640 .args_type = "",
2641 .params = "",
2642 .help = "show PCI info",
2643 .mhandler.cmd = hmp_info_pci,
2645 #if defined(TARGET_I386) || defined(TARGET_SH4) || defined(TARGET_SPARC) || \
2646 defined(TARGET_PPC) || defined(TARGET_XTENSA)
2648 .name = "tlb",
2649 .args_type = "",
2650 .params = "",
2651 .help = "show virtual to physical memory mappings",
2652 .mhandler.cmd = hmp_info_tlb,
2654 #endif
2655 #if defined(TARGET_I386)
2657 .name = "mem",
2658 .args_type = "",
2659 .params = "",
2660 .help = "show the active virtual memory mappings",
2661 .mhandler.cmd = hmp_info_mem,
2663 #endif
2665 .name = "mtree",
2666 .args_type = "",
2667 .params = "",
2668 .help = "show memory tree",
2669 .mhandler.cmd = hmp_info_mtree,
2672 .name = "jit",
2673 .args_type = "",
2674 .params = "",
2675 .help = "show dynamic compiler info",
2676 .mhandler.cmd = hmp_info_jit,
2679 .name = "opcount",
2680 .args_type = "",
2681 .params = "",
2682 .help = "show dynamic compiler opcode counters",
2683 .mhandler.cmd = hmp_info_opcount,
2686 .name = "kvm",
2687 .args_type = "",
2688 .params = "",
2689 .help = "show KVM information",
2690 .mhandler.cmd = hmp_info_kvm,
2693 .name = "numa",
2694 .args_type = "",
2695 .params = "",
2696 .help = "show NUMA information",
2697 .mhandler.cmd = hmp_info_numa,
2700 .name = "usb",
2701 .args_type = "",
2702 .params = "",
2703 .help = "show guest USB devices",
2704 .mhandler.cmd = hmp_info_usb,
2707 .name = "usbhost",
2708 .args_type = "",
2709 .params = "",
2710 .help = "show host USB devices",
2711 .mhandler.cmd = hmp_info_usbhost,
2714 .name = "profile",
2715 .args_type = "",
2716 .params = "",
2717 .help = "show profiling information",
2718 .mhandler.cmd = hmp_info_profile,
2721 .name = "capture",
2722 .args_type = "",
2723 .params = "",
2724 .help = "show capture information",
2725 .mhandler.cmd = hmp_info_capture,
2728 .name = "snapshots",
2729 .args_type = "",
2730 .params = "",
2731 .help = "show the currently saved VM snapshots",
2732 .mhandler.cmd = hmp_info_snapshots,
2735 .name = "status",
2736 .args_type = "",
2737 .params = "",
2738 .help = "show the current VM status (running|paused)",
2739 .mhandler.cmd = hmp_info_status,
2742 .name = "mice",
2743 .args_type = "",
2744 .params = "",
2745 .help = "show which guest mouse is receiving events",
2746 .mhandler.cmd = hmp_info_mice,
2749 .name = "vnc",
2750 .args_type = "",
2751 .params = "",
2752 .help = "show the vnc server status",
2753 .mhandler.cmd = hmp_info_vnc,
2755 #if defined(CONFIG_SPICE)
2757 .name = "spice",
2758 .args_type = "",
2759 .params = "",
2760 .help = "show the spice server status",
2761 .mhandler.cmd = hmp_info_spice,
2763 #endif
2765 .name = "name",
2766 .args_type = "",
2767 .params = "",
2768 .help = "show the current VM name",
2769 .mhandler.cmd = hmp_info_name,
2772 .name = "uuid",
2773 .args_type = "",
2774 .params = "",
2775 .help = "show the current VM UUID",
2776 .mhandler.cmd = hmp_info_uuid,
2779 .name = "cpustats",
2780 .args_type = "",
2781 .params = "",
2782 .help = "show CPU statistics",
2783 .mhandler.cmd = hmp_info_cpustats,
2785 #if defined(CONFIG_SLIRP)
2787 .name = "usernet",
2788 .args_type = "",
2789 .params = "",
2790 .help = "show user network stack connection states",
2791 .mhandler.cmd = hmp_info_usernet,
2793 #endif
2795 .name = "migrate",
2796 .args_type = "",
2797 .params = "",
2798 .help = "show migration status",
2799 .mhandler.cmd = hmp_info_migrate,
2802 .name = "migrate_capabilities",
2803 .args_type = "",
2804 .params = "",
2805 .help = "show current migration capabilities",
2806 .mhandler.cmd = hmp_info_migrate_capabilities,
2809 .name = "migrate_parameters",
2810 .args_type = "",
2811 .params = "",
2812 .help = "show current migration parameters",
2813 .mhandler.cmd = hmp_info_migrate_parameters,
2816 .name = "migrate_cache_size",
2817 .args_type = "",
2818 .params = "",
2819 .help = "show current migration xbzrle cache size",
2820 .mhandler.cmd = hmp_info_migrate_cache_size,
2823 .name = "balloon",
2824 .args_type = "",
2825 .params = "",
2826 .help = "show balloon information",
2827 .mhandler.cmd = hmp_info_balloon,
2830 .name = "qtree",
2831 .args_type = "",
2832 .params = "",
2833 .help = "show device tree",
2834 .mhandler.cmd = hmp_info_qtree,
2837 .name = "qdm",
2838 .args_type = "",
2839 .params = "",
2840 .help = "show qdev device model list",
2841 .mhandler.cmd = hmp_info_qdm,
2844 .name = "qom-tree",
2845 .args_type = "path:s?",
2846 .params = "[path]",
2847 .help = "show QOM composition tree",
2848 .mhandler.cmd = hmp_info_qom_tree,
2851 .name = "roms",
2852 .args_type = "",
2853 .params = "",
2854 .help = "show roms",
2855 .mhandler.cmd = hmp_info_roms,
2858 .name = "trace-events",
2859 .args_type = "",
2860 .params = "",
2861 .help = "show available trace-events & their state",
2862 .mhandler.cmd = hmp_info_trace_events,
2865 .name = "tpm",
2866 .args_type = "",
2867 .params = "",
2868 .help = "show the TPM device",
2869 .mhandler.cmd = hmp_info_tpm,
2872 .name = "memdev",
2873 .args_type = "",
2874 .params = "",
2875 .help = "show memory backends",
2876 .mhandler.cmd = hmp_info_memdev,
2879 .name = "memory-devices",
2880 .args_type = "",
2881 .params = "",
2882 .help = "show memory devices",
2883 .mhandler.cmd = hmp_info_memory_devices,
2886 .name = NULL,
2890 /* mon_cmds and info_cmds would be sorted at runtime */
2891 static mon_cmd_t mon_cmds[] = {
2892 #include "hmp-commands.h"
2893 { NULL, NULL, },
2896 static const mon_cmd_t qmp_cmds[] = {
2897 #include "qmp-commands-old.h"
2898 { /* NULL */ },
2901 /*******************************************************************/
2903 static const char *pch;
2904 static sigjmp_buf expr_env;
2906 #define MD_TLONG 0
2907 #define MD_I32 1
2909 typedef struct MonitorDef {
2910 const char *name;
2911 int offset;
2912 target_long (*get_value)(const struct MonitorDef *md, int val);
2913 int type;
2914 } MonitorDef;
2916 #if defined(TARGET_I386)
2917 static target_long monitor_get_pc (const struct MonitorDef *md, int val)
2919 CPUArchState *env = mon_get_cpu();
2920 return env->eip + env->segs[R_CS].base;
2922 #endif
2924 #if defined(TARGET_PPC)
2925 static target_long monitor_get_ccr (const struct MonitorDef *md, int val)
2927 CPUArchState *env = mon_get_cpu();
2928 unsigned int u;
2929 int i;
2931 u = 0;
2932 for (i = 0; i < 8; i++)
2933 u |= env->crf[i] << (32 - (4 * (i + 1)));
2935 return u;
2938 static target_long monitor_get_msr (const struct MonitorDef *md, int val)
2940 CPUArchState *env = mon_get_cpu();
2941 return env->msr;
2944 static target_long monitor_get_xer (const struct MonitorDef *md, int val)
2946 CPUArchState *env = mon_get_cpu();
2947 return env->xer;
2950 static target_long monitor_get_decr (const struct MonitorDef *md, int val)
2952 CPUArchState *env = mon_get_cpu();
2953 return cpu_ppc_load_decr(env);
2956 static target_long monitor_get_tbu (const struct MonitorDef *md, int val)
2958 CPUArchState *env = mon_get_cpu();
2959 return cpu_ppc_load_tbu(env);
2962 static target_long monitor_get_tbl (const struct MonitorDef *md, int val)
2964 CPUArchState *env = mon_get_cpu();
2965 return cpu_ppc_load_tbl(env);
2967 #endif
2969 #if defined(TARGET_SPARC)
2970 #ifndef TARGET_SPARC64
2971 static target_long monitor_get_psr (const struct MonitorDef *md, int val)
2973 CPUArchState *env = mon_get_cpu();
2975 return cpu_get_psr(env);
2977 #endif
2979 static target_long monitor_get_reg(const struct MonitorDef *md, int val)
2981 CPUArchState *env = mon_get_cpu();
2982 return env->regwptr[val];
2984 #endif
2986 static const MonitorDef monitor_defs[] = {
2987 #ifdef TARGET_I386
2989 #define SEG(name, seg) \
2990 { name, offsetof(CPUX86State, segs[seg].selector), NULL, MD_I32 },\
2991 { name ".base", offsetof(CPUX86State, segs[seg].base) },\
2992 { name ".limit", offsetof(CPUX86State, segs[seg].limit), NULL, MD_I32 },
2994 { "eax", offsetof(CPUX86State, regs[0]) },
2995 { "ecx", offsetof(CPUX86State, regs[1]) },
2996 { "edx", offsetof(CPUX86State, regs[2]) },
2997 { "ebx", offsetof(CPUX86State, regs[3]) },
2998 { "esp|sp", offsetof(CPUX86State, regs[4]) },
2999 { "ebp|fp", offsetof(CPUX86State, regs[5]) },
3000 { "esi", offsetof(CPUX86State, regs[6]) },
3001 { "edi", offsetof(CPUX86State, regs[7]) },
3002 #ifdef TARGET_X86_64
3003 { "r8", offsetof(CPUX86State, regs[8]) },
3004 { "r9", offsetof(CPUX86State, regs[9]) },
3005 { "r10", offsetof(CPUX86State, regs[10]) },
3006 { "r11", offsetof(CPUX86State, regs[11]) },
3007 { "r12", offsetof(CPUX86State, regs[12]) },
3008 { "r13", offsetof(CPUX86State, regs[13]) },
3009 { "r14", offsetof(CPUX86State, regs[14]) },
3010 { "r15", offsetof(CPUX86State, regs[15]) },
3011 #endif
3012 { "eflags", offsetof(CPUX86State, eflags) },
3013 { "eip", offsetof(CPUX86State, eip) },
3014 SEG("cs", R_CS)
3015 SEG("ds", R_DS)
3016 SEG("es", R_ES)
3017 SEG("ss", R_SS)
3018 SEG("fs", R_FS)
3019 SEG("gs", R_GS)
3020 { "pc", 0, monitor_get_pc, },
3021 #elif defined(TARGET_PPC)
3022 /* General purpose registers */
3023 { "r0", offsetof(CPUPPCState, gpr[0]) },
3024 { "r1", offsetof(CPUPPCState, gpr[1]) },
3025 { "r2", offsetof(CPUPPCState, gpr[2]) },
3026 { "r3", offsetof(CPUPPCState, gpr[3]) },
3027 { "r4", offsetof(CPUPPCState, gpr[4]) },
3028 { "r5", offsetof(CPUPPCState, gpr[5]) },
3029 { "r6", offsetof(CPUPPCState, gpr[6]) },
3030 { "r7", offsetof(CPUPPCState, gpr[7]) },
3031 { "r8", offsetof(CPUPPCState, gpr[8]) },
3032 { "r9", offsetof(CPUPPCState, gpr[9]) },
3033 { "r10", offsetof(CPUPPCState, gpr[10]) },
3034 { "r11", offsetof(CPUPPCState, gpr[11]) },
3035 { "r12", offsetof(CPUPPCState, gpr[12]) },
3036 { "r13", offsetof(CPUPPCState, gpr[13]) },
3037 { "r14", offsetof(CPUPPCState, gpr[14]) },
3038 { "r15", offsetof(CPUPPCState, gpr[15]) },
3039 { "r16", offsetof(CPUPPCState, gpr[16]) },
3040 { "r17", offsetof(CPUPPCState, gpr[17]) },
3041 { "r18", offsetof(CPUPPCState, gpr[18]) },
3042 { "r19", offsetof(CPUPPCState, gpr[19]) },
3043 { "r20", offsetof(CPUPPCState, gpr[20]) },
3044 { "r21", offsetof(CPUPPCState, gpr[21]) },
3045 { "r22", offsetof(CPUPPCState, gpr[22]) },
3046 { "r23", offsetof(CPUPPCState, gpr[23]) },
3047 { "r24", offsetof(CPUPPCState, gpr[24]) },
3048 { "r25", offsetof(CPUPPCState, gpr[25]) },
3049 { "r26", offsetof(CPUPPCState, gpr[26]) },
3050 { "r27", offsetof(CPUPPCState, gpr[27]) },
3051 { "r28", offsetof(CPUPPCState, gpr[28]) },
3052 { "r29", offsetof(CPUPPCState, gpr[29]) },
3053 { "r30", offsetof(CPUPPCState, gpr[30]) },
3054 { "r31", offsetof(CPUPPCState, gpr[31]) },
3055 /* Floating point registers */
3056 { "f0", offsetof(CPUPPCState, fpr[0]) },
3057 { "f1", offsetof(CPUPPCState, fpr[1]) },
3058 { "f2", offsetof(CPUPPCState, fpr[2]) },
3059 { "f3", offsetof(CPUPPCState, fpr[3]) },
3060 { "f4", offsetof(CPUPPCState, fpr[4]) },
3061 { "f5", offsetof(CPUPPCState, fpr[5]) },
3062 { "f6", offsetof(CPUPPCState, fpr[6]) },
3063 { "f7", offsetof(CPUPPCState, fpr[7]) },
3064 { "f8", offsetof(CPUPPCState, fpr[8]) },
3065 { "f9", offsetof(CPUPPCState, fpr[9]) },
3066 { "f10", offsetof(CPUPPCState, fpr[10]) },
3067 { "f11", offsetof(CPUPPCState, fpr[11]) },
3068 { "f12", offsetof(CPUPPCState, fpr[12]) },
3069 { "f13", offsetof(CPUPPCState, fpr[13]) },
3070 { "f14", offsetof(CPUPPCState, fpr[14]) },
3071 { "f15", offsetof(CPUPPCState, fpr[15]) },
3072 { "f16", offsetof(CPUPPCState, fpr[16]) },
3073 { "f17", offsetof(CPUPPCState, fpr[17]) },
3074 { "f18", offsetof(CPUPPCState, fpr[18]) },
3075 { "f19", offsetof(CPUPPCState, fpr[19]) },
3076 { "f20", offsetof(CPUPPCState, fpr[20]) },
3077 { "f21", offsetof(CPUPPCState, fpr[21]) },
3078 { "f22", offsetof(CPUPPCState, fpr[22]) },
3079 { "f23", offsetof(CPUPPCState, fpr[23]) },
3080 { "f24", offsetof(CPUPPCState, fpr[24]) },
3081 { "f25", offsetof(CPUPPCState, fpr[25]) },
3082 { "f26", offsetof(CPUPPCState, fpr[26]) },
3083 { "f27", offsetof(CPUPPCState, fpr[27]) },
3084 { "f28", offsetof(CPUPPCState, fpr[28]) },
3085 { "f29", offsetof(CPUPPCState, fpr[29]) },
3086 { "f30", offsetof(CPUPPCState, fpr[30]) },
3087 { "f31", offsetof(CPUPPCState, fpr[31]) },
3088 { "fpscr", offsetof(CPUPPCState, fpscr) },
3089 /* Next instruction pointer */
3090 { "nip|pc", offsetof(CPUPPCState, nip) },
3091 { "lr", offsetof(CPUPPCState, lr) },
3092 { "ctr", offsetof(CPUPPCState, ctr) },
3093 { "decr", 0, &monitor_get_decr, },
3094 { "ccr", 0, &monitor_get_ccr, },
3095 /* Machine state register */
3096 { "msr", 0, &monitor_get_msr, },
3097 { "xer", 0, &monitor_get_xer, },
3098 { "tbu", 0, &monitor_get_tbu, },
3099 { "tbl", 0, &monitor_get_tbl, },
3100 /* Segment registers */
3101 { "sdr1", offsetof(CPUPPCState, spr[SPR_SDR1]) },
3102 { "sr0", offsetof(CPUPPCState, sr[0]) },
3103 { "sr1", offsetof(CPUPPCState, sr[1]) },
3104 { "sr2", offsetof(CPUPPCState, sr[2]) },
3105 { "sr3", offsetof(CPUPPCState, sr[3]) },
3106 { "sr4", offsetof(CPUPPCState, sr[4]) },
3107 { "sr5", offsetof(CPUPPCState, sr[5]) },
3108 { "sr6", offsetof(CPUPPCState, sr[6]) },
3109 { "sr7", offsetof(CPUPPCState, sr[7]) },
3110 { "sr8", offsetof(CPUPPCState, sr[8]) },
3111 { "sr9", offsetof(CPUPPCState, sr[9]) },
3112 { "sr10", offsetof(CPUPPCState, sr[10]) },
3113 { "sr11", offsetof(CPUPPCState, sr[11]) },
3114 { "sr12", offsetof(CPUPPCState, sr[12]) },
3115 { "sr13", offsetof(CPUPPCState, sr[13]) },
3116 { "sr14", offsetof(CPUPPCState, sr[14]) },
3117 { "sr15", offsetof(CPUPPCState, sr[15]) },
3118 /* Too lazy to put BATs... */
3119 { "pvr", offsetof(CPUPPCState, spr[SPR_PVR]) },
3121 { "srr0", offsetof(CPUPPCState, spr[SPR_SRR0]) },
3122 { "srr1", offsetof(CPUPPCState, spr[SPR_SRR1]) },
3123 { "dar", offsetof(CPUPPCState, spr[SPR_DAR]) },
3124 { "dsisr", offsetof(CPUPPCState, spr[SPR_DSISR]) },
3125 { "cfar", offsetof(CPUPPCState, spr[SPR_CFAR]) },
3126 { "sprg0", offsetof(CPUPPCState, spr[SPR_SPRG0]) },
3127 { "sprg1", offsetof(CPUPPCState, spr[SPR_SPRG1]) },
3128 { "sprg2", offsetof(CPUPPCState, spr[SPR_SPRG2]) },
3129 { "sprg3", offsetof(CPUPPCState, spr[SPR_SPRG3]) },
3130 { "sprg4", offsetof(CPUPPCState, spr[SPR_SPRG4]) },
3131 { "sprg5", offsetof(CPUPPCState, spr[SPR_SPRG5]) },
3132 { "sprg6", offsetof(CPUPPCState, spr[SPR_SPRG6]) },
3133 { "sprg7", offsetof(CPUPPCState, spr[SPR_SPRG7]) },
3134 { "pid", offsetof(CPUPPCState, spr[SPR_BOOKE_PID]) },
3135 { "csrr0", offsetof(CPUPPCState, spr[SPR_BOOKE_CSRR0]) },
3136 { "csrr1", offsetof(CPUPPCState, spr[SPR_BOOKE_CSRR1]) },
3137 { "esr", offsetof(CPUPPCState, spr[SPR_BOOKE_ESR]) },
3138 { "dear", offsetof(CPUPPCState, spr[SPR_BOOKE_DEAR]) },
3139 { "mcsr", offsetof(CPUPPCState, spr[SPR_BOOKE_MCSR]) },
3140 { "tsr", offsetof(CPUPPCState, spr[SPR_BOOKE_TSR]) },
3141 { "tcr", offsetof(CPUPPCState, spr[SPR_BOOKE_TCR]) },
3142 { "vrsave", offsetof(CPUPPCState, spr[SPR_VRSAVE]) },
3143 { "pir", offsetof(CPUPPCState, spr[SPR_BOOKE_PIR]) },
3144 { "mcsrr0", offsetof(CPUPPCState, spr[SPR_BOOKE_MCSRR0]) },
3145 { "mcsrr1", offsetof(CPUPPCState, spr[SPR_BOOKE_MCSRR1]) },
3146 { "decar", offsetof(CPUPPCState, spr[SPR_BOOKE_DECAR]) },
3147 { "ivpr", offsetof(CPUPPCState, spr[SPR_BOOKE_IVPR]) },
3148 { "epcr", offsetof(CPUPPCState, spr[SPR_BOOKE_EPCR]) },
3149 { "sprg8", offsetof(CPUPPCState, spr[SPR_BOOKE_SPRG8]) },
3150 { "ivor0", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR0]) },
3151 { "ivor1", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR1]) },
3152 { "ivor2", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR2]) },
3153 { "ivor3", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR3]) },
3154 { "ivor4", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR4]) },
3155 { "ivor5", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR5]) },
3156 { "ivor6", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR6]) },
3157 { "ivor7", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR7]) },
3158 { "ivor8", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR8]) },
3159 { "ivor9", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR9]) },
3160 { "ivor10", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR10]) },
3161 { "ivor11", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR11]) },
3162 { "ivor12", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR12]) },
3163 { "ivor13", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR13]) },
3164 { "ivor14", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR14]) },
3165 { "ivor15", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR15]) },
3166 { "ivor32", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR32]) },
3167 { "ivor33", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR33]) },
3168 { "ivor34", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR34]) },
3169 { "ivor35", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR35]) },
3170 { "ivor36", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR36]) },
3171 { "ivor37", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR37]) },
3172 { "mas0", offsetof(CPUPPCState, spr[SPR_BOOKE_MAS0]) },
3173 { "mas1", offsetof(CPUPPCState, spr[SPR_BOOKE_MAS1]) },
3174 { "mas2", offsetof(CPUPPCState, spr[SPR_BOOKE_MAS2]) },
3175 { "mas3", offsetof(CPUPPCState, spr[SPR_BOOKE_MAS3]) },
3176 { "mas4", offsetof(CPUPPCState, spr[SPR_BOOKE_MAS4]) },
3177 { "mas6", offsetof(CPUPPCState, spr[SPR_BOOKE_MAS6]) },
3178 { "mas7", offsetof(CPUPPCState, spr[SPR_BOOKE_MAS7]) },
3179 { "mmucfg", offsetof(CPUPPCState, spr[SPR_MMUCFG]) },
3180 { "tlb0cfg", offsetof(CPUPPCState, spr[SPR_BOOKE_TLB0CFG]) },
3181 { "tlb1cfg", offsetof(CPUPPCState, spr[SPR_BOOKE_TLB1CFG]) },
3182 { "epr", offsetof(CPUPPCState, spr[SPR_BOOKE_EPR]) },
3183 { "eplc", offsetof(CPUPPCState, spr[SPR_BOOKE_EPLC]) },
3184 { "epsc", offsetof(CPUPPCState, spr[SPR_BOOKE_EPSC]) },
3185 { "svr", offsetof(CPUPPCState, spr[SPR_E500_SVR]) },
3186 { "mcar", offsetof(CPUPPCState, spr[SPR_Exxx_MCAR]) },
3187 { "pid1", offsetof(CPUPPCState, spr[SPR_BOOKE_PID1]) },
3188 { "pid2", offsetof(CPUPPCState, spr[SPR_BOOKE_PID2]) },
3189 { "hid0", offsetof(CPUPPCState, spr[SPR_HID0]) },
3191 #elif defined(TARGET_SPARC)
3192 { "g0", offsetof(CPUSPARCState, gregs[0]) },
3193 { "g1", offsetof(CPUSPARCState, gregs[1]) },
3194 { "g2", offsetof(CPUSPARCState, gregs[2]) },
3195 { "g3", offsetof(CPUSPARCState, gregs[3]) },
3196 { "g4", offsetof(CPUSPARCState, gregs[4]) },
3197 { "g5", offsetof(CPUSPARCState, gregs[5]) },
3198 { "g6", offsetof(CPUSPARCState, gregs[6]) },
3199 { "g7", offsetof(CPUSPARCState, gregs[7]) },
3200 { "o0", 0, monitor_get_reg },
3201 { "o1", 1, monitor_get_reg },
3202 { "o2", 2, monitor_get_reg },
3203 { "o3", 3, monitor_get_reg },
3204 { "o4", 4, monitor_get_reg },
3205 { "o5", 5, monitor_get_reg },
3206 { "o6", 6, monitor_get_reg },
3207 { "o7", 7, monitor_get_reg },
3208 { "l0", 8, monitor_get_reg },
3209 { "l1", 9, monitor_get_reg },
3210 { "l2", 10, monitor_get_reg },
3211 { "l3", 11, monitor_get_reg },
3212 { "l4", 12, monitor_get_reg },
3213 { "l5", 13, monitor_get_reg },
3214 { "l6", 14, monitor_get_reg },
3215 { "l7", 15, monitor_get_reg },
3216 { "i0", 16, monitor_get_reg },
3217 { "i1", 17, monitor_get_reg },
3218 { "i2", 18, monitor_get_reg },
3219 { "i3", 19, monitor_get_reg },
3220 { "i4", 20, monitor_get_reg },
3221 { "i5", 21, monitor_get_reg },
3222 { "i6", 22, monitor_get_reg },
3223 { "i7", 23, monitor_get_reg },
3224 { "pc", offsetof(CPUSPARCState, pc) },
3225 { "npc", offsetof(CPUSPARCState, npc) },
3226 { "y", offsetof(CPUSPARCState, y) },
3227 #ifndef TARGET_SPARC64
3228 { "psr", 0, &monitor_get_psr, },
3229 { "wim", offsetof(CPUSPARCState, wim) },
3230 #endif
3231 { "tbr", offsetof(CPUSPARCState, tbr) },
3232 { "fsr", offsetof(CPUSPARCState, fsr) },
3233 { "f0", offsetof(CPUSPARCState, fpr[0].l.upper) },
3234 { "f1", offsetof(CPUSPARCState, fpr[0].l.lower) },
3235 { "f2", offsetof(CPUSPARCState, fpr[1].l.upper) },
3236 { "f3", offsetof(CPUSPARCState, fpr[1].l.lower) },
3237 { "f4", offsetof(CPUSPARCState, fpr[2].l.upper) },
3238 { "f5", offsetof(CPUSPARCState, fpr[2].l.lower) },
3239 { "f6", offsetof(CPUSPARCState, fpr[3].l.upper) },
3240 { "f7", offsetof(CPUSPARCState, fpr[3].l.lower) },
3241 { "f8", offsetof(CPUSPARCState, fpr[4].l.upper) },
3242 { "f9", offsetof(CPUSPARCState, fpr[4].l.lower) },
3243 { "f10", offsetof(CPUSPARCState, fpr[5].l.upper) },
3244 { "f11", offsetof(CPUSPARCState, fpr[5].l.lower) },
3245 { "f12", offsetof(CPUSPARCState, fpr[6].l.upper) },
3246 { "f13", offsetof(CPUSPARCState, fpr[6].l.lower) },
3247 { "f14", offsetof(CPUSPARCState, fpr[7].l.upper) },
3248 { "f15", offsetof(CPUSPARCState, fpr[7].l.lower) },
3249 { "f16", offsetof(CPUSPARCState, fpr[8].l.upper) },
3250 { "f17", offsetof(CPUSPARCState, fpr[8].l.lower) },
3251 { "f18", offsetof(CPUSPARCState, fpr[9].l.upper) },
3252 { "f19", offsetof(CPUSPARCState, fpr[9].l.lower) },
3253 { "f20", offsetof(CPUSPARCState, fpr[10].l.upper) },
3254 { "f21", offsetof(CPUSPARCState, fpr[10].l.lower) },
3255 { "f22", offsetof(CPUSPARCState, fpr[11].l.upper) },
3256 { "f23", offsetof(CPUSPARCState, fpr[11].l.lower) },
3257 { "f24", offsetof(CPUSPARCState, fpr[12].l.upper) },
3258 { "f25", offsetof(CPUSPARCState, fpr[12].l.lower) },
3259 { "f26", offsetof(CPUSPARCState, fpr[13].l.upper) },
3260 { "f27", offsetof(CPUSPARCState, fpr[13].l.lower) },
3261 { "f28", offsetof(CPUSPARCState, fpr[14].l.upper) },
3262 { "f29", offsetof(CPUSPARCState, fpr[14].l.lower) },
3263 { "f30", offsetof(CPUSPARCState, fpr[15].l.upper) },
3264 { "f31", offsetof(CPUSPARCState, fpr[15].l.lower) },
3265 #ifdef TARGET_SPARC64
3266 { "f32", offsetof(CPUSPARCState, fpr[16]) },
3267 { "f34", offsetof(CPUSPARCState, fpr[17]) },
3268 { "f36", offsetof(CPUSPARCState, fpr[18]) },
3269 { "f38", offsetof(CPUSPARCState, fpr[19]) },
3270 { "f40", offsetof(CPUSPARCState, fpr[20]) },
3271 { "f42", offsetof(CPUSPARCState, fpr[21]) },
3272 { "f44", offsetof(CPUSPARCState, fpr[22]) },
3273 { "f46", offsetof(CPUSPARCState, fpr[23]) },
3274 { "f48", offsetof(CPUSPARCState, fpr[24]) },
3275 { "f50", offsetof(CPUSPARCState, fpr[25]) },
3276 { "f52", offsetof(CPUSPARCState, fpr[26]) },
3277 { "f54", offsetof(CPUSPARCState, fpr[27]) },
3278 { "f56", offsetof(CPUSPARCState, fpr[28]) },
3279 { "f58", offsetof(CPUSPARCState, fpr[29]) },
3280 { "f60", offsetof(CPUSPARCState, fpr[30]) },
3281 { "f62", offsetof(CPUSPARCState, fpr[31]) },
3282 { "asi", offsetof(CPUSPARCState, asi) },
3283 { "pstate", offsetof(CPUSPARCState, pstate) },
3284 { "cansave", offsetof(CPUSPARCState, cansave) },
3285 { "canrestore", offsetof(CPUSPARCState, canrestore) },
3286 { "otherwin", offsetof(CPUSPARCState, otherwin) },
3287 { "wstate", offsetof(CPUSPARCState, wstate) },
3288 { "cleanwin", offsetof(CPUSPARCState, cleanwin) },
3289 { "fprs", offsetof(CPUSPARCState, fprs) },
3290 #endif
3291 #endif
3292 { NULL },
3295 static void GCC_FMT_ATTR(2, 3) QEMU_NORETURN
3296 expr_error(Monitor *mon, const char *fmt, ...)
3298 va_list ap;
3299 va_start(ap, fmt);
3300 monitor_vprintf(mon, fmt, ap);
3301 monitor_printf(mon, "\n");
3302 va_end(ap);
3303 siglongjmp(expr_env, 1);
3306 /* return 0 if OK, -1 if not found */
3307 static int get_monitor_def(target_long *pval, const char *name)
3309 const MonitorDef *md;
3310 void *ptr;
3312 for(md = monitor_defs; md->name != NULL; md++) {
3313 if (compare_cmd(name, md->name)) {
3314 if (md->get_value) {
3315 *pval = md->get_value(md, md->offset);
3316 } else {
3317 CPUArchState *env = mon_get_cpu();
3318 ptr = (uint8_t *)env + md->offset;
3319 switch(md->type) {
3320 case MD_I32:
3321 *pval = *(int32_t *)ptr;
3322 break;
3323 case MD_TLONG:
3324 *pval = *(target_long *)ptr;
3325 break;
3326 default:
3327 *pval = 0;
3328 break;
3331 return 0;
3334 return -1;
3337 static void next(void)
3339 if (*pch != '\0') {
3340 pch++;
3341 while (qemu_isspace(*pch))
3342 pch++;
3346 static int64_t expr_sum(Monitor *mon);
3348 static int64_t expr_unary(Monitor *mon)
3350 int64_t n;
3351 char *p;
3352 int ret;
3354 switch(*pch) {
3355 case '+':
3356 next();
3357 n = expr_unary(mon);
3358 break;
3359 case '-':
3360 next();
3361 n = -expr_unary(mon);
3362 break;
3363 case '~':
3364 next();
3365 n = ~expr_unary(mon);
3366 break;
3367 case '(':
3368 next();
3369 n = expr_sum(mon);
3370 if (*pch != ')') {
3371 expr_error(mon, "')' expected");
3373 next();
3374 break;
3375 case '\'':
3376 pch++;
3377 if (*pch == '\0')
3378 expr_error(mon, "character constant expected");
3379 n = *pch;
3380 pch++;
3381 if (*pch != '\'')
3382 expr_error(mon, "missing terminating \' character");
3383 next();
3384 break;
3385 case '$':
3387 char buf[128], *q;
3388 target_long reg=0;
3390 pch++;
3391 q = buf;
3392 while ((*pch >= 'a' && *pch <= 'z') ||
3393 (*pch >= 'A' && *pch <= 'Z') ||
3394 (*pch >= '0' && *pch <= '9') ||
3395 *pch == '_' || *pch == '.') {
3396 if ((q - buf) < sizeof(buf) - 1)
3397 *q++ = *pch;
3398 pch++;
3400 while (qemu_isspace(*pch))
3401 pch++;
3402 *q = 0;
3403 ret = get_monitor_def(&reg, buf);
3404 if (ret < 0)
3405 expr_error(mon, "unknown register");
3406 n = reg;
3408 break;
3409 case '\0':
3410 expr_error(mon, "unexpected end of expression");
3411 n = 0;
3412 break;
3413 default:
3414 errno = 0;
3415 n = strtoull(pch, &p, 0);
3416 if (errno == ERANGE) {
3417 expr_error(mon, "number too large");
3419 if (pch == p) {
3420 expr_error(mon, "invalid char '%c' in expression", *p);
3422 pch = p;
3423 while (qemu_isspace(*pch))
3424 pch++;
3425 break;
3427 return n;
3431 static int64_t expr_prod(Monitor *mon)
3433 int64_t val, val2;
3434 int op;
3436 val = expr_unary(mon);
3437 for(;;) {
3438 op = *pch;
3439 if (op != '*' && op != '/' && op != '%')
3440 break;
3441 next();
3442 val2 = expr_unary(mon);
3443 switch(op) {
3444 default:
3445 case '*':
3446 val *= val2;
3447 break;
3448 case '/':
3449 case '%':
3450 if (val2 == 0)
3451 expr_error(mon, "division by zero");
3452 if (op == '/')
3453 val /= val2;
3454 else
3455 val %= val2;
3456 break;
3459 return val;
3462 static int64_t expr_logic(Monitor *mon)
3464 int64_t val, val2;
3465 int op;
3467 val = expr_prod(mon);
3468 for(;;) {
3469 op = *pch;
3470 if (op != '&' && op != '|' && op != '^')
3471 break;
3472 next();
3473 val2 = expr_prod(mon);
3474 switch(op) {
3475 default:
3476 case '&':
3477 val &= val2;
3478 break;
3479 case '|':
3480 val |= val2;
3481 break;
3482 case '^':
3483 val ^= val2;
3484 break;
3487 return val;
3490 static int64_t expr_sum(Monitor *mon)
3492 int64_t val, val2;
3493 int op;
3495 val = expr_logic(mon);
3496 for(;;) {
3497 op = *pch;
3498 if (op != '+' && op != '-')
3499 break;
3500 next();
3501 val2 = expr_logic(mon);
3502 if (op == '+')
3503 val += val2;
3504 else
3505 val -= val2;
3507 return val;
3510 static int get_expr(Monitor *mon, int64_t *pval, const char **pp)
3512 pch = *pp;
3513 if (sigsetjmp(expr_env, 0)) {
3514 *pp = pch;
3515 return -1;
3517 while (qemu_isspace(*pch))
3518 pch++;
3519 *pval = expr_sum(mon);
3520 *pp = pch;
3521 return 0;
3524 static int get_double(Monitor *mon, double *pval, const char **pp)
3526 const char *p = *pp;
3527 char *tailp;
3528 double d;
3530 d = strtod(p, &tailp);
3531 if (tailp == p) {
3532 monitor_printf(mon, "Number expected\n");
3533 return -1;
3535 if (d != d || d - d != 0) {
3536 /* NaN or infinity */
3537 monitor_printf(mon, "Bad number\n");
3538 return -1;
3540 *pval = d;
3541 *pp = tailp;
3542 return 0;
3546 * Store the command-name in cmdname, and return a pointer to
3547 * the remaining of the command string.
3549 static const char *get_command_name(const char *cmdline,
3550 char *cmdname, size_t nlen)
3552 size_t len;
3553 const char *p, *pstart;
3555 p = cmdline;
3556 while (qemu_isspace(*p))
3557 p++;
3558 if (*p == '\0')
3559 return NULL;
3560 pstart = p;
3561 while (*p != '\0' && *p != '/' && !qemu_isspace(*p))
3562 p++;
3563 len = p - pstart;
3564 if (len > nlen - 1)
3565 len = nlen - 1;
3566 memcpy(cmdname, pstart, len);
3567 cmdname[len] = '\0';
3568 return p;
3572 * Read key of 'type' into 'key' and return the current
3573 * 'type' pointer.
3575 static char *key_get_info(const char *type, char **key)
3577 size_t len;
3578 char *p, *str;
3580 if (*type == ',')
3581 type++;
3583 p = strchr(type, ':');
3584 if (!p) {
3585 *key = NULL;
3586 return NULL;
3588 len = p - type;
3590 str = g_malloc(len + 1);
3591 memcpy(str, type, len);
3592 str[len] = '\0';
3594 *key = str;
3595 return ++p;
3598 static int default_fmt_format = 'x';
3599 static int default_fmt_size = 4;
3601 static int is_valid_option(const char *c, const char *typestr)
3603 char option[3];
3605 option[0] = '-';
3606 option[1] = *c;
3607 option[2] = '\0';
3609 typestr = strstr(typestr, option);
3610 return (typestr != NULL);
3613 static const mon_cmd_t *search_dispatch_table(const mon_cmd_t *disp_table,
3614 const char *cmdname)
3616 const mon_cmd_t *cmd;
3618 for (cmd = disp_table; cmd->name != NULL; cmd++) {
3619 if (compare_cmd(cmdname, cmd->name)) {
3620 return cmd;
3624 return NULL;
3627 static const mon_cmd_t *qmp_find_cmd(const char *cmdname)
3629 return search_dispatch_table(qmp_cmds, cmdname);
3633 * Parse @cmdline according to command table @table.
3634 * If @cmdline is blank, return NULL.
3635 * If it can't be parsed, report to @mon, and return NULL.
3636 * Else, insert command arguments into @qdict, and return the command.
3637 * If a sub-command table exists, and if @cmdline contains an additional string
3638 * for a sub-command, this function will try to search the sub-command table.
3639 * If no additional string for a sub-command is present, this function will
3640 * return the command found in @table.
3641 * Do not assume the returned command points into @table! It doesn't
3642 * when the command is a sub-command.
3644 static const mon_cmd_t *monitor_parse_command(Monitor *mon,
3645 const char *cmdline,
3646 int start,
3647 mon_cmd_t *table,
3648 QDict *qdict)
3650 const char *p, *typestr;
3651 int c;
3652 const mon_cmd_t *cmd;
3653 char cmdname[256];
3654 char buf[1024];
3655 char *key;
3657 #ifdef DEBUG
3658 monitor_printf(mon, "command='%s', start='%d'\n", cmdline, start);
3659 #endif
3661 /* extract the command name */
3662 p = get_command_name(cmdline + start, cmdname, sizeof(cmdname));
3663 if (!p)
3664 return NULL;
3666 cmd = search_dispatch_table(table, cmdname);
3667 if (!cmd) {
3668 monitor_printf(mon, "unknown command: '%.*s'\n",
3669 (int)(p - cmdline), cmdline);
3670 return NULL;
3673 /* filter out following useless space */
3674 while (qemu_isspace(*p)) {
3675 p++;
3677 /* search sub command */
3678 if (cmd->sub_table != NULL) {
3679 /* check if user set additional command */
3680 if (*p == '\0') {
3681 return cmd;
3683 return monitor_parse_command(mon, cmdline, p - cmdline,
3684 cmd->sub_table, qdict);
3687 /* parse the parameters */
3688 typestr = cmd->args_type;
3689 for(;;) {
3690 typestr = key_get_info(typestr, &key);
3691 if (!typestr)
3692 break;
3693 c = *typestr;
3694 typestr++;
3695 switch(c) {
3696 case 'F':
3697 case 'B':
3698 case 's':
3700 int ret;
3702 while (qemu_isspace(*p))
3703 p++;
3704 if (*typestr == '?') {
3705 typestr++;
3706 if (*p == '\0') {
3707 /* no optional string: NULL argument */
3708 break;
3711 ret = get_str(buf, sizeof(buf), &p);
3712 if (ret < 0) {
3713 switch(c) {
3714 case 'F':
3715 monitor_printf(mon, "%s: filename expected\n",
3716 cmdname);
3717 break;
3718 case 'B':
3719 monitor_printf(mon, "%s: block device name expected\n",
3720 cmdname);
3721 break;
3722 default:
3723 monitor_printf(mon, "%s: string expected\n", cmdname);
3724 break;
3726 goto fail;
3728 qdict_put(qdict, key, qstring_from_str(buf));
3730 break;
3731 case 'O':
3733 QemuOptsList *opts_list;
3734 QemuOpts *opts;
3736 opts_list = qemu_find_opts(key);
3737 if (!opts_list || opts_list->desc->name) {
3738 goto bad_type;
3740 while (qemu_isspace(*p)) {
3741 p++;
3743 if (!*p)
3744 break;
3745 if (get_str(buf, sizeof(buf), &p) < 0) {
3746 goto fail;
3748 opts = qemu_opts_parse(opts_list, buf, 1);
3749 if (!opts) {
3750 goto fail;
3752 qemu_opts_to_qdict(opts, qdict);
3753 qemu_opts_del(opts);
3755 break;
3756 case '/':
3758 int count, format, size;
3760 while (qemu_isspace(*p))
3761 p++;
3762 if (*p == '/') {
3763 /* format found */
3764 p++;
3765 count = 1;
3766 if (qemu_isdigit(*p)) {
3767 count = 0;
3768 while (qemu_isdigit(*p)) {
3769 count = count * 10 + (*p - '0');
3770 p++;
3773 size = -1;
3774 format = -1;
3775 for(;;) {
3776 switch(*p) {
3777 case 'o':
3778 case 'd':
3779 case 'u':
3780 case 'x':
3781 case 'i':
3782 case 'c':
3783 format = *p++;
3784 break;
3785 case 'b':
3786 size = 1;
3787 p++;
3788 break;
3789 case 'h':
3790 size = 2;
3791 p++;
3792 break;
3793 case 'w':
3794 size = 4;
3795 p++;
3796 break;
3797 case 'g':
3798 case 'L':
3799 size = 8;
3800 p++;
3801 break;
3802 default:
3803 goto next;
3806 next:
3807 if (*p != '\0' && !qemu_isspace(*p)) {
3808 monitor_printf(mon, "invalid char in format: '%c'\n",
3809 *p);
3810 goto fail;
3812 if (format < 0)
3813 format = default_fmt_format;
3814 if (format != 'i') {
3815 /* for 'i', not specifying a size gives -1 as size */
3816 if (size < 0)
3817 size = default_fmt_size;
3818 default_fmt_size = size;
3820 default_fmt_format = format;
3821 } else {
3822 count = 1;
3823 format = default_fmt_format;
3824 if (format != 'i') {
3825 size = default_fmt_size;
3826 } else {
3827 size = -1;
3830 qdict_put(qdict, "count", qint_from_int(count));
3831 qdict_put(qdict, "format", qint_from_int(format));
3832 qdict_put(qdict, "size", qint_from_int(size));
3834 break;
3835 case 'i':
3836 case 'l':
3837 case 'M':
3839 int64_t val;
3841 while (qemu_isspace(*p))
3842 p++;
3843 if (*typestr == '?' || *typestr == '.') {
3844 if (*typestr == '?') {
3845 if (*p == '\0') {
3846 typestr++;
3847 break;
3849 } else {
3850 if (*p == '.') {
3851 p++;
3852 while (qemu_isspace(*p))
3853 p++;
3854 } else {
3855 typestr++;
3856 break;
3859 typestr++;
3861 if (get_expr(mon, &val, &p))
3862 goto fail;
3863 /* Check if 'i' is greater than 32-bit */
3864 if ((c == 'i') && ((val >> 32) & 0xffffffff)) {
3865 monitor_printf(mon, "\'%s\' has failed: ", cmdname);
3866 monitor_printf(mon, "integer is for 32-bit values\n");
3867 goto fail;
3868 } else if (c == 'M') {
3869 if (val < 0) {
3870 monitor_printf(mon, "enter a positive value\n");
3871 goto fail;
3873 val <<= 20;
3875 qdict_put(qdict, key, qint_from_int(val));
3877 break;
3878 case 'o':
3880 int64_t val;
3881 char *end;
3883 while (qemu_isspace(*p)) {
3884 p++;
3886 if (*typestr == '?') {
3887 typestr++;
3888 if (*p == '\0') {
3889 break;
3892 val = strtosz(p, &end);
3893 if (val < 0) {
3894 monitor_printf(mon, "invalid size\n");
3895 goto fail;
3897 qdict_put(qdict, key, qint_from_int(val));
3898 p = end;
3900 break;
3901 case 'T':
3903 double val;
3905 while (qemu_isspace(*p))
3906 p++;
3907 if (*typestr == '?') {
3908 typestr++;
3909 if (*p == '\0') {
3910 break;
3913 if (get_double(mon, &val, &p) < 0) {
3914 goto fail;
3916 if (p[0] && p[1] == 's') {
3917 switch (*p) {
3918 case 'm':
3919 val /= 1e3; p += 2; break;
3920 case 'u':
3921 val /= 1e6; p += 2; break;
3922 case 'n':
3923 val /= 1e9; p += 2; break;
3926 if (*p && !qemu_isspace(*p)) {
3927 monitor_printf(mon, "Unknown unit suffix\n");
3928 goto fail;
3930 qdict_put(qdict, key, qfloat_from_double(val));
3932 break;
3933 case 'b':
3935 const char *beg;
3936 int val;
3938 while (qemu_isspace(*p)) {
3939 p++;
3941 beg = p;
3942 while (qemu_isgraph(*p)) {
3943 p++;
3945 if (p - beg == 2 && !memcmp(beg, "on", p - beg)) {
3946 val = 1;
3947 } else if (p - beg == 3 && !memcmp(beg, "off", p - beg)) {
3948 val = 0;
3949 } else {
3950 monitor_printf(mon, "Expected 'on' or 'off'\n");
3951 goto fail;
3953 qdict_put(qdict, key, qbool_from_int(val));
3955 break;
3956 case '-':
3958 const char *tmp = p;
3959 int skip_key = 0;
3960 /* option */
3962 c = *typestr++;
3963 if (c == '\0')
3964 goto bad_type;
3965 while (qemu_isspace(*p))
3966 p++;
3967 if (*p == '-') {
3968 p++;
3969 if(c != *p) {
3970 if(!is_valid_option(p, typestr)) {
3972 monitor_printf(mon, "%s: unsupported option -%c\n",
3973 cmdname, *p);
3974 goto fail;
3975 } else {
3976 skip_key = 1;
3979 if(skip_key) {
3980 p = tmp;
3981 } else {
3982 /* has option */
3983 p++;
3984 qdict_put(qdict, key, qbool_from_int(1));
3988 break;
3989 case 'S':
3991 /* package all remaining string */
3992 int len;
3994 while (qemu_isspace(*p)) {
3995 p++;
3997 if (*typestr == '?') {
3998 typestr++;
3999 if (*p == '\0') {
4000 /* no remaining string: NULL argument */
4001 break;
4004 len = strlen(p);
4005 if (len <= 0) {
4006 monitor_printf(mon, "%s: string expected\n",
4007 cmdname);
4008 break;
4010 qdict_put(qdict, key, qstring_from_str(p));
4011 p += len;
4013 break;
4014 default:
4015 bad_type:
4016 monitor_printf(mon, "%s: unknown type '%c'\n", cmdname, c);
4017 goto fail;
4019 g_free(key);
4020 key = NULL;
4022 /* check that all arguments were parsed */
4023 while (qemu_isspace(*p))
4024 p++;
4025 if (*p != '\0') {
4026 monitor_printf(mon, "%s: extraneous characters at the end of line\n",
4027 cmdname);
4028 goto fail;
4031 return cmd;
4033 fail:
4034 g_free(key);
4035 return NULL;
4038 void monitor_set_error(Monitor *mon, QError *qerror)
4040 /* report only the first error */
4041 if (!mon->error) {
4042 mon->error = qerror;
4043 } else {
4044 QDECREF(qerror);
4048 static void handle_user_command(Monitor *mon, const char *cmdline)
4050 QDict *qdict;
4051 const mon_cmd_t *cmd;
4053 qdict = qdict_new();
4055 cmd = monitor_parse_command(mon, cmdline, 0, mon->cmd_table, qdict);
4056 if (!cmd)
4057 goto out;
4059 if (handler_is_qobject(cmd)) {
4060 QObject *data = NULL;
4062 /* XXX: ignores the error code */
4063 cmd->mhandler.cmd_new(mon, qdict, &data);
4064 assert(!monitor_has_error(mon));
4065 if (data) {
4066 cmd->user_print(mon, data);
4067 qobject_decref(data);
4069 } else {
4070 cmd->mhandler.cmd(mon, qdict);
4073 out:
4074 QDECREF(qdict);
4077 static void cmd_completion(Monitor *mon, const char *name, const char *list)
4079 const char *p, *pstart;
4080 char cmd[128];
4081 int len;
4083 p = list;
4084 for(;;) {
4085 pstart = p;
4086 p = strchr(p, '|');
4087 if (!p)
4088 p = pstart + strlen(pstart);
4089 len = p - pstart;
4090 if (len > sizeof(cmd) - 2)
4091 len = sizeof(cmd) - 2;
4092 memcpy(cmd, pstart, len);
4093 cmd[len] = '\0';
4094 if (name[0] == '\0' || !strncmp(name, cmd, strlen(name))) {
4095 readline_add_completion(mon->rs, cmd);
4097 if (*p == '\0')
4098 break;
4099 p++;
4103 static void file_completion(Monitor *mon, const char *input)
4105 DIR *ffs;
4106 struct dirent *d;
4107 char path[1024];
4108 char file[1024], file_prefix[1024];
4109 int input_path_len;
4110 const char *p;
4112 p = strrchr(input, '/');
4113 if (!p) {
4114 input_path_len = 0;
4115 pstrcpy(file_prefix, sizeof(file_prefix), input);
4116 pstrcpy(path, sizeof(path), ".");
4117 } else {
4118 input_path_len = p - input + 1;
4119 memcpy(path, input, input_path_len);
4120 if (input_path_len > sizeof(path) - 1)
4121 input_path_len = sizeof(path) - 1;
4122 path[input_path_len] = '\0';
4123 pstrcpy(file_prefix, sizeof(file_prefix), p + 1);
4125 #ifdef DEBUG_COMPLETION
4126 monitor_printf(mon, "input='%s' path='%s' prefix='%s'\n",
4127 input, path, file_prefix);
4128 #endif
4129 ffs = opendir(path);
4130 if (!ffs)
4131 return;
4132 for(;;) {
4133 struct stat sb;
4134 d = readdir(ffs);
4135 if (!d)
4136 break;
4138 if (strcmp(d->d_name, ".") == 0 || strcmp(d->d_name, "..") == 0) {
4139 continue;
4142 if (strstart(d->d_name, file_prefix, NULL)) {
4143 memcpy(file, input, input_path_len);
4144 if (input_path_len < sizeof(file))
4145 pstrcpy(file + input_path_len, sizeof(file) - input_path_len,
4146 d->d_name);
4147 /* stat the file to find out if it's a directory.
4148 * In that case add a slash to speed up typing long paths
4150 if (stat(file, &sb) == 0 && S_ISDIR(sb.st_mode)) {
4151 pstrcat(file, sizeof(file), "/");
4153 readline_add_completion(mon->rs, file);
4156 closedir(ffs);
4159 static const char *next_arg_type(const char *typestr)
4161 const char *p = strchr(typestr, ':');
4162 return (p != NULL ? ++p : typestr);
4165 static void add_completion_option(ReadLineState *rs, const char *str,
4166 const char *option)
4168 if (!str || !option) {
4169 return;
4171 if (!strncmp(option, str, strlen(str))) {
4172 readline_add_completion(rs, option);
4176 void chardev_add_completion(ReadLineState *rs, int nb_args, const char *str)
4178 size_t len;
4179 ChardevBackendInfoList *list, *start;
4181 if (nb_args != 2) {
4182 return;
4184 len = strlen(str);
4185 readline_set_completion_index(rs, len);
4187 start = list = qmp_query_chardev_backends(NULL);
4188 while (list) {
4189 const char *chr_name = list->value->name;
4191 if (!strncmp(chr_name, str, len)) {
4192 readline_add_completion(rs, chr_name);
4194 list = list->next;
4196 qapi_free_ChardevBackendInfoList(start);
4199 void netdev_add_completion(ReadLineState *rs, int nb_args, const char *str)
4201 size_t len;
4202 int i;
4204 if (nb_args != 2) {
4205 return;
4207 len = strlen(str);
4208 readline_set_completion_index(rs, len);
4209 for (i = 0; NetClientOptionsKind_lookup[i]; i++) {
4210 add_completion_option(rs, str, NetClientOptionsKind_lookup[i]);
4214 void device_add_completion(ReadLineState *rs, int nb_args, const char *str)
4216 GSList *list, *elt;
4217 size_t len;
4219 if (nb_args != 2) {
4220 return;
4223 len = strlen(str);
4224 readline_set_completion_index(rs, len);
4225 list = elt = object_class_get_list(TYPE_DEVICE, false);
4226 while (elt) {
4227 const char *name;
4228 DeviceClass *dc = OBJECT_CLASS_CHECK(DeviceClass, elt->data,
4229 TYPE_DEVICE);
4230 name = object_class_get_name(OBJECT_CLASS(dc));
4232 if (!dc->cannot_instantiate_with_device_add_yet
4233 && !strncmp(name, str, len)) {
4234 readline_add_completion(rs, name);
4236 elt = elt->next;
4238 g_slist_free(list);
4241 void object_add_completion(ReadLineState *rs, int nb_args, const char *str)
4243 GSList *list, *elt;
4244 size_t len;
4246 if (nb_args != 2) {
4247 return;
4250 len = strlen(str);
4251 readline_set_completion_index(rs, len);
4252 list = elt = object_class_get_list(TYPE_USER_CREATABLE, false);
4253 while (elt) {
4254 const char *name;
4256 name = object_class_get_name(OBJECT_CLASS(elt->data));
4257 if (!strncmp(name, str, len) && strcmp(name, TYPE_USER_CREATABLE)) {
4258 readline_add_completion(rs, name);
4260 elt = elt->next;
4262 g_slist_free(list);
4265 static void peripheral_device_del_completion(ReadLineState *rs,
4266 const char *str, size_t len)
4268 Object *peripheral = container_get(qdev_get_machine(), "/peripheral");
4269 GSList *list, *item;
4271 list = qdev_build_hotpluggable_device_list(peripheral);
4272 if (!list) {
4273 return;
4276 for (item = list; item; item = g_slist_next(item)) {
4277 DeviceState *dev = item->data;
4279 if (dev->id && !strncmp(str, dev->id, len)) {
4280 readline_add_completion(rs, dev->id);
4284 g_slist_free(list);
4287 void chardev_remove_completion(ReadLineState *rs, int nb_args, const char *str)
4289 size_t len;
4290 ChardevInfoList *list, *start;
4292 if (nb_args != 2) {
4293 return;
4295 len = strlen(str);
4296 readline_set_completion_index(rs, len);
4298 start = list = qmp_query_chardev(NULL);
4299 while (list) {
4300 ChardevInfo *chr = list->value;
4302 if (!strncmp(chr->label, str, len)) {
4303 readline_add_completion(rs, chr->label);
4305 list = list->next;
4307 qapi_free_ChardevInfoList(start);
4310 static void ringbuf_completion(ReadLineState *rs, const char *str)
4312 size_t len;
4313 ChardevInfoList *list, *start;
4315 len = strlen(str);
4316 readline_set_completion_index(rs, len);
4318 start = list = qmp_query_chardev(NULL);
4319 while (list) {
4320 ChardevInfo *chr_info = list->value;
4322 if (!strncmp(chr_info->label, str, len)) {
4323 CharDriverState *chr = qemu_chr_find(chr_info->label);
4324 if (chr && chr_is_ringbuf(chr)) {
4325 readline_add_completion(rs, chr_info->label);
4328 list = list->next;
4330 qapi_free_ChardevInfoList(start);
4333 void ringbuf_write_completion(ReadLineState *rs, int nb_args, const char *str)
4335 if (nb_args != 2) {
4336 return;
4338 ringbuf_completion(rs, str);
4341 void device_del_completion(ReadLineState *rs, int nb_args, const char *str)
4343 size_t len;
4345 if (nb_args != 2) {
4346 return;
4349 len = strlen(str);
4350 readline_set_completion_index(rs, len);
4351 peripheral_device_del_completion(rs, str, len);
4354 void object_del_completion(ReadLineState *rs, int nb_args, const char *str)
4356 ObjectPropertyInfoList *list, *start;
4357 size_t len;
4359 if (nb_args != 2) {
4360 return;
4362 len = strlen(str);
4363 readline_set_completion_index(rs, len);
4365 start = list = qmp_qom_list("/objects", NULL);
4366 while (list) {
4367 ObjectPropertyInfo *info = list->value;
4369 if (!strncmp(info->type, "child<", 5)
4370 && !strncmp(info->name, str, len)) {
4371 readline_add_completion(rs, info->name);
4373 list = list->next;
4375 qapi_free_ObjectPropertyInfoList(start);
4378 void sendkey_completion(ReadLineState *rs, int nb_args, const char *str)
4380 int i;
4381 char *sep;
4382 size_t len;
4384 if (nb_args != 2) {
4385 return;
4387 sep = strrchr(str, '-');
4388 if (sep) {
4389 str = sep + 1;
4391 len = strlen(str);
4392 readline_set_completion_index(rs, len);
4393 for (i = 0; i < Q_KEY_CODE_MAX; i++) {
4394 if (!strncmp(str, QKeyCode_lookup[i], len)) {
4395 readline_add_completion(rs, QKeyCode_lookup[i]);
4400 void set_link_completion(ReadLineState *rs, int nb_args, const char *str)
4402 size_t len;
4404 len = strlen(str);
4405 readline_set_completion_index(rs, len);
4406 if (nb_args == 2) {
4407 NetClientState *ncs[MAX_QUEUE_NUM];
4408 int count, i;
4409 count = qemu_find_net_clients_except(NULL, ncs,
4410 NET_CLIENT_OPTIONS_KIND_NONE,
4411 MAX_QUEUE_NUM);
4412 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
4413 const char *name = ncs[i]->name;
4414 if (!strncmp(str, name, len)) {
4415 readline_add_completion(rs, name);
4418 } else if (nb_args == 3) {
4419 add_completion_option(rs, str, "on");
4420 add_completion_option(rs, str, "off");
4424 void netdev_del_completion(ReadLineState *rs, int nb_args, const char *str)
4426 int len, count, i;
4427 NetClientState *ncs[MAX_QUEUE_NUM];
4429 if (nb_args != 2) {
4430 return;
4433 len = strlen(str);
4434 readline_set_completion_index(rs, len);
4435 count = qemu_find_net_clients_except(NULL, ncs, NET_CLIENT_OPTIONS_KIND_NIC,
4436 MAX_QUEUE_NUM);
4437 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
4438 QemuOpts *opts;
4439 const char *name = ncs[i]->name;
4440 if (strncmp(str, name, len)) {
4441 continue;
4443 opts = qemu_opts_find(qemu_find_opts_err("netdev", NULL), name);
4444 if (opts) {
4445 readline_add_completion(rs, name);
4450 void watchdog_action_completion(ReadLineState *rs, int nb_args, const char *str)
4452 int i;
4454 if (nb_args != 2) {
4455 return;
4457 readline_set_completion_index(rs, strlen(str));
4458 for (i = 0; WatchdogExpirationAction_lookup[i]; i++) {
4459 add_completion_option(rs, str, WatchdogExpirationAction_lookup[i]);
4463 void migrate_set_capability_completion(ReadLineState *rs, int nb_args,
4464 const char *str)
4466 size_t len;
4468 len = strlen(str);
4469 readline_set_completion_index(rs, len);
4470 if (nb_args == 2) {
4471 int i;
4472 for (i = 0; i < MIGRATION_CAPABILITY_MAX; i++) {
4473 const char *name = MigrationCapability_lookup[i];
4474 if (!strncmp(str, name, len)) {
4475 readline_add_completion(rs, name);
4478 } else if (nb_args == 3) {
4479 add_completion_option(rs, str, "on");
4480 add_completion_option(rs, str, "off");
4484 void migrate_set_parameter_completion(ReadLineState *rs, int nb_args,
4485 const char *str)
4487 size_t len;
4489 len = strlen(str);
4490 readline_set_completion_index(rs, len);
4491 if (nb_args == 2) {
4492 int i;
4493 for (i = 0; i < MIGRATION_PARAMETER_MAX; i++) {
4494 const char *name = MigrationParameter_lookup[i];
4495 if (!strncmp(str, name, len)) {
4496 readline_add_completion(rs, name);
4502 void host_net_add_completion(ReadLineState *rs, int nb_args, const char *str)
4504 int i;
4505 size_t len;
4506 if (nb_args != 2) {
4507 return;
4509 len = strlen(str);
4510 readline_set_completion_index(rs, len);
4511 for (i = 0; host_net_devices[i]; i++) {
4512 if (!strncmp(host_net_devices[i], str, len)) {
4513 readline_add_completion(rs, host_net_devices[i]);
4518 void host_net_remove_completion(ReadLineState *rs, int nb_args, const char *str)
4520 NetClientState *ncs[MAX_QUEUE_NUM];
4521 int count, i, len;
4523 len = strlen(str);
4524 readline_set_completion_index(rs, len);
4525 if (nb_args == 2) {
4526 count = qemu_find_net_clients_except(NULL, ncs,
4527 NET_CLIENT_OPTIONS_KIND_NONE,
4528 MAX_QUEUE_NUM);
4529 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
4530 int id;
4531 char name[16];
4533 if (net_hub_id_for_client(ncs[i], &id)) {
4534 continue;
4536 snprintf(name, sizeof(name), "%d", id);
4537 if (!strncmp(str, name, len)) {
4538 readline_add_completion(rs, name);
4541 return;
4542 } else if (nb_args == 3) {
4543 count = qemu_find_net_clients_except(NULL, ncs,
4544 NET_CLIENT_OPTIONS_KIND_NIC,
4545 MAX_QUEUE_NUM);
4546 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
4547 int id;
4548 const char *name;
4550 if (ncs[i]->info->type == NET_CLIENT_OPTIONS_KIND_HUBPORT ||
4551 net_hub_id_for_client(ncs[i], &id)) {
4552 continue;
4554 name = ncs[i]->name;
4555 if (!strncmp(str, name, len)) {
4556 readline_add_completion(rs, name);
4559 return;
4563 static void vm_completion(ReadLineState *rs, const char *str)
4565 size_t len;
4566 BlockDriverState *bs = NULL;
4568 len = strlen(str);
4569 readline_set_completion_index(rs, len);
4570 while ((bs = bdrv_next(bs))) {
4571 SnapshotInfoList *snapshots, *snapshot;
4573 if (!bdrv_can_snapshot(bs)) {
4574 continue;
4576 if (bdrv_query_snapshot_info_list(bs, &snapshots, NULL)) {
4577 continue;
4579 snapshot = snapshots;
4580 while (snapshot) {
4581 char *completion = snapshot->value->name;
4582 if (!strncmp(str, completion, len)) {
4583 readline_add_completion(rs, completion);
4585 completion = snapshot->value->id;
4586 if (!strncmp(str, completion, len)) {
4587 readline_add_completion(rs, completion);
4589 snapshot = snapshot->next;
4591 qapi_free_SnapshotInfoList(snapshots);
4596 void delvm_completion(ReadLineState *rs, int nb_args, const char *str)
4598 if (nb_args == 2) {
4599 vm_completion(rs, str);
4603 void loadvm_completion(ReadLineState *rs, int nb_args, const char *str)
4605 if (nb_args == 2) {
4606 vm_completion(rs, str);
4610 static void monitor_find_completion_by_table(Monitor *mon,
4611 const mon_cmd_t *cmd_table,
4612 char **args,
4613 int nb_args)
4615 const char *cmdname;
4616 int i;
4617 const char *ptype, *str, *name;
4618 const mon_cmd_t *cmd;
4619 BlockDriverState *bs;
4621 if (nb_args <= 1) {
4622 /* command completion */
4623 if (nb_args == 0)
4624 cmdname = "";
4625 else
4626 cmdname = args[0];
4627 readline_set_completion_index(mon->rs, strlen(cmdname));
4628 for (cmd = cmd_table; cmd->name != NULL; cmd++) {
4629 cmd_completion(mon, cmdname, cmd->name);
4631 } else {
4632 /* find the command */
4633 for (cmd = cmd_table; cmd->name != NULL; cmd++) {
4634 if (compare_cmd(args[0], cmd->name)) {
4635 break;
4638 if (!cmd->name) {
4639 return;
4642 if (cmd->sub_table) {
4643 /* do the job again */
4644 monitor_find_completion_by_table(mon, cmd->sub_table,
4645 &args[1], nb_args - 1);
4646 return;
4648 if (cmd->command_completion) {
4649 cmd->command_completion(mon->rs, nb_args, args[nb_args - 1]);
4650 return;
4653 ptype = next_arg_type(cmd->args_type);
4654 for(i = 0; i < nb_args - 2; i++) {
4655 if (*ptype != '\0') {
4656 ptype = next_arg_type(ptype);
4657 while (*ptype == '?')
4658 ptype = next_arg_type(ptype);
4661 str = args[nb_args - 1];
4662 while (*ptype == '-' && ptype[1] != '\0') {
4663 ptype = next_arg_type(ptype);
4665 switch(*ptype) {
4666 case 'F':
4667 /* file completion */
4668 readline_set_completion_index(mon->rs, strlen(str));
4669 file_completion(mon, str);
4670 break;
4671 case 'B':
4672 /* block device name completion */
4673 readline_set_completion_index(mon->rs, strlen(str));
4674 for (bs = bdrv_next(NULL); bs; bs = bdrv_next(bs)) {
4675 name = bdrv_get_device_name(bs);
4676 if (str[0] == '\0' ||
4677 !strncmp(name, str, strlen(str))) {
4678 readline_add_completion(mon->rs, name);
4681 break;
4682 case 's':
4683 case 'S':
4684 if (!strcmp(cmd->name, "help|?")) {
4685 monitor_find_completion_by_table(mon, cmd_table,
4686 &args[1], nb_args - 1);
4688 break;
4689 default:
4690 break;
4695 static void monitor_find_completion(void *opaque,
4696 const char *cmdline)
4698 Monitor *mon = opaque;
4699 char *args[MAX_ARGS];
4700 int nb_args, len;
4702 /* 1. parse the cmdline */
4703 if (parse_cmdline(cmdline, &nb_args, args) < 0) {
4704 return;
4706 #ifdef DEBUG_COMPLETION
4708 int i;
4709 for (i = 0; i < nb_args; i++) {
4710 monitor_printf(mon, "arg%d = '%s'\n", i, args[i]);
4713 #endif
4715 /* if the line ends with a space, it means we want to complete the
4716 next arg */
4717 len = strlen(cmdline);
4718 if (len > 0 && qemu_isspace(cmdline[len - 1])) {
4719 if (nb_args >= MAX_ARGS) {
4720 goto cleanup;
4722 args[nb_args++] = g_strdup("");
4725 /* 2. auto complete according to args */
4726 monitor_find_completion_by_table(mon, mon->cmd_table, args, nb_args);
4728 cleanup:
4729 free_cmdline_args(args, nb_args);
4732 static int monitor_can_read(void *opaque)
4734 Monitor *mon = opaque;
4736 return (mon->suspend_cnt == 0) ? 1 : 0;
4739 static bool invalid_qmp_mode(const Monitor *mon, const mon_cmd_t *cmd)
4741 bool is_cap = cmd->mhandler.cmd_new == do_qmp_capabilities;
4742 if (is_cap && qmp_cmd_mode(mon)) {
4743 qerror_report(ERROR_CLASS_COMMAND_NOT_FOUND,
4744 "Capabilities negotiation is already complete, command "
4745 "'%s' ignored", cmd->name);
4746 return true;
4748 if (!is_cap && !qmp_cmd_mode(mon)) {
4749 qerror_report(ERROR_CLASS_COMMAND_NOT_FOUND,
4750 "Expecting capabilities negotiation with "
4751 "'qmp_capabilities' before command '%s'", cmd->name);
4752 return true;
4754 return false;
4758 * Argument validation rules:
4760 * 1. The argument must exist in cmd_args qdict
4761 * 2. The argument type must be the expected one
4763 * Special case: If the argument doesn't exist in cmd_args and
4764 * the QMP_ACCEPT_UNKNOWNS flag is set, then the
4765 * checking is skipped for it.
4767 static int check_client_args_type(const QDict *client_args,
4768 const QDict *cmd_args, int flags)
4770 const QDictEntry *ent;
4772 for (ent = qdict_first(client_args); ent;ent = qdict_next(client_args,ent)){
4773 QObject *obj;
4774 QString *arg_type;
4775 const QObject *client_arg = qdict_entry_value(ent);
4776 const char *client_arg_name = qdict_entry_key(ent);
4778 obj = qdict_get(cmd_args, client_arg_name);
4779 if (!obj) {
4780 if (flags & QMP_ACCEPT_UNKNOWNS) {
4781 /* handler accepts unknowns */
4782 continue;
4784 /* client arg doesn't exist */
4785 qerror_report(QERR_INVALID_PARAMETER, client_arg_name);
4786 return -1;
4789 arg_type = qobject_to_qstring(obj);
4790 assert(arg_type != NULL);
4792 /* check if argument's type is correct */
4793 switch (qstring_get_str(arg_type)[0]) {
4794 case 'F':
4795 case 'B':
4796 case 's':
4797 if (qobject_type(client_arg) != QTYPE_QSTRING) {
4798 qerror_report(QERR_INVALID_PARAMETER_TYPE, client_arg_name,
4799 "string");
4800 return -1;
4802 break;
4803 case 'i':
4804 case 'l':
4805 case 'M':
4806 case 'o':
4807 if (qobject_type(client_arg) != QTYPE_QINT) {
4808 qerror_report(QERR_INVALID_PARAMETER_TYPE, client_arg_name,
4809 "int");
4810 return -1;
4812 break;
4813 case 'T':
4814 if (qobject_type(client_arg) != QTYPE_QINT &&
4815 qobject_type(client_arg) != QTYPE_QFLOAT) {
4816 qerror_report(QERR_INVALID_PARAMETER_TYPE, client_arg_name,
4817 "number");
4818 return -1;
4820 break;
4821 case 'b':
4822 case '-':
4823 if (qobject_type(client_arg) != QTYPE_QBOOL) {
4824 qerror_report(QERR_INVALID_PARAMETER_TYPE, client_arg_name,
4825 "bool");
4826 return -1;
4828 break;
4829 case 'O':
4830 assert(flags & QMP_ACCEPT_UNKNOWNS);
4831 break;
4832 case 'q':
4833 /* Any QObject can be passed. */
4834 break;
4835 case '/':
4836 case '.':
4838 * These types are not supported by QMP and thus are not
4839 * handled here. Fall through.
4841 default:
4842 abort();
4846 return 0;
4850 * - Check if the client has passed all mandatory args
4851 * - Set special flags for argument validation
4853 static int check_mandatory_args(const QDict *cmd_args,
4854 const QDict *client_args, int *flags)
4856 const QDictEntry *ent;
4858 for (ent = qdict_first(cmd_args); ent; ent = qdict_next(cmd_args, ent)) {
4859 const char *cmd_arg_name = qdict_entry_key(ent);
4860 QString *type = qobject_to_qstring(qdict_entry_value(ent));
4861 assert(type != NULL);
4863 if (qstring_get_str(type)[0] == 'O') {
4864 assert((*flags & QMP_ACCEPT_UNKNOWNS) == 0);
4865 *flags |= QMP_ACCEPT_UNKNOWNS;
4866 } else if (qstring_get_str(type)[0] != '-' &&
4867 qstring_get_str(type)[1] != '?' &&
4868 !qdict_haskey(client_args, cmd_arg_name)) {
4869 qerror_report(QERR_MISSING_PARAMETER, cmd_arg_name);
4870 return -1;
4874 return 0;
4877 static QDict *qdict_from_args_type(const char *args_type)
4879 int i;
4880 QDict *qdict;
4881 QString *key, *type, *cur_qs;
4883 assert(args_type != NULL);
4885 qdict = qdict_new();
4887 if (args_type == NULL || args_type[0] == '\0') {
4888 /* no args, empty qdict */
4889 goto out;
4892 key = qstring_new();
4893 type = qstring_new();
4895 cur_qs = key;
4897 for (i = 0;; i++) {
4898 switch (args_type[i]) {
4899 case ',':
4900 case '\0':
4901 qdict_put(qdict, qstring_get_str(key), type);
4902 QDECREF(key);
4903 if (args_type[i] == '\0') {
4904 goto out;
4906 type = qstring_new(); /* qdict has ref */
4907 cur_qs = key = qstring_new();
4908 break;
4909 case ':':
4910 cur_qs = type;
4911 break;
4912 default:
4913 qstring_append_chr(cur_qs, args_type[i]);
4914 break;
4918 out:
4919 return qdict;
4923 * Client argument checking rules:
4925 * 1. Client must provide all mandatory arguments
4926 * 2. Each argument provided by the client must be expected
4927 * 3. Each argument provided by the client must have the type expected
4928 * by the command
4930 static int qmp_check_client_args(const mon_cmd_t *cmd, QDict *client_args)
4932 int flags, err;
4933 QDict *cmd_args;
4935 cmd_args = qdict_from_args_type(cmd->args_type);
4937 flags = 0;
4938 err = check_mandatory_args(cmd_args, client_args, &flags);
4939 if (err) {
4940 goto out;
4943 err = check_client_args_type(client_args, cmd_args, flags);
4945 out:
4946 QDECREF(cmd_args);
4947 return err;
4951 * Input object checking rules
4953 * 1. Input object must be a dict
4954 * 2. The "execute" key must exist
4955 * 3. The "execute" key must be a string
4956 * 4. If the "arguments" key exists, it must be a dict
4957 * 5. If the "id" key exists, it can be anything (ie. json-value)
4958 * 6. Any argument not listed above is considered invalid
4960 static QDict *qmp_check_input_obj(QObject *input_obj)
4962 const QDictEntry *ent;
4963 int has_exec_key = 0;
4964 QDict *input_dict;
4966 if (qobject_type(input_obj) != QTYPE_QDICT) {
4967 qerror_report(QERR_QMP_BAD_INPUT_OBJECT, "object");
4968 return NULL;
4971 input_dict = qobject_to_qdict(input_obj);
4973 for (ent = qdict_first(input_dict); ent; ent = qdict_next(input_dict, ent)){
4974 const char *arg_name = qdict_entry_key(ent);
4975 const QObject *arg_obj = qdict_entry_value(ent);
4977 if (!strcmp(arg_name, "execute")) {
4978 if (qobject_type(arg_obj) != QTYPE_QSTRING) {
4979 qerror_report(QERR_QMP_BAD_INPUT_OBJECT_MEMBER, "execute",
4980 "string");
4981 return NULL;
4983 has_exec_key = 1;
4984 } else if (!strcmp(arg_name, "arguments")) {
4985 if (qobject_type(arg_obj) != QTYPE_QDICT) {
4986 qerror_report(QERR_QMP_BAD_INPUT_OBJECT_MEMBER, "arguments",
4987 "object");
4988 return NULL;
4990 } else {
4991 qerror_report(QERR_QMP_EXTRA_MEMBER, arg_name);
4992 return NULL;
4996 if (!has_exec_key) {
4997 qerror_report(QERR_QMP_BAD_INPUT_OBJECT, "execute");
4998 return NULL;
5001 return input_dict;
5004 static void handle_qmp_command(JSONMessageParser *parser, QList *tokens)
5006 int err;
5007 QObject *obj, *data;
5008 QDict *input, *args;
5009 const mon_cmd_t *cmd;
5010 const char *cmd_name;
5011 Monitor *mon = cur_mon;
5013 args = input = NULL;
5014 data = NULL;
5016 obj = json_parser_parse(tokens, NULL);
5017 if (!obj) {
5018 // FIXME: should be triggered in json_parser_parse()
5019 qerror_report(QERR_JSON_PARSING);
5020 goto err_out;
5023 input = qmp_check_input_obj(obj);
5024 if (!input) {
5025 qobject_decref(obj);
5026 goto err_out;
5029 mon->mc->id = qdict_get(input, "id");
5030 qobject_incref(mon->mc->id);
5032 cmd_name = qdict_get_str(input, "execute");
5033 trace_handle_qmp_command(mon, cmd_name);
5034 cmd = qmp_find_cmd(cmd_name);
5035 if (!cmd) {
5036 qerror_report(ERROR_CLASS_COMMAND_NOT_FOUND,
5037 "The command %s has not been found", cmd_name);
5038 goto err_out;
5040 if (invalid_qmp_mode(mon, cmd)) {
5041 goto err_out;
5044 obj = qdict_get(input, "arguments");
5045 if (!obj) {
5046 args = qdict_new();
5047 } else {
5048 args = qobject_to_qdict(obj);
5049 QINCREF(args);
5052 err = qmp_check_client_args(cmd, args);
5053 if (err < 0) {
5054 goto err_out;
5057 if (cmd->mhandler.cmd_new(mon, args, &data)) {
5058 /* Command failed... */
5059 if (!monitor_has_error(mon)) {
5060 /* ... without setting an error, so make one up */
5061 qerror_report(QERR_UNDEFINED_ERROR);
5065 err_out:
5066 monitor_protocol_emitter(mon, data);
5067 qobject_decref(data);
5068 QDECREF(input);
5069 QDECREF(args);
5073 * monitor_control_read(): Read and handle QMP input
5075 static void monitor_control_read(void *opaque, const uint8_t *buf, int size)
5077 Monitor *old_mon = cur_mon;
5079 cur_mon = opaque;
5081 json_message_parser_feed(&cur_mon->mc->parser, (const char *) buf, size);
5083 cur_mon = old_mon;
5086 static void monitor_read(void *opaque, const uint8_t *buf, int size)
5088 Monitor *old_mon = cur_mon;
5089 int i;
5091 cur_mon = opaque;
5093 if (cur_mon->rs) {
5094 for (i = 0; i < size; i++)
5095 readline_handle_byte(cur_mon->rs, buf[i]);
5096 } else {
5097 if (size == 0 || buf[size - 1] != 0)
5098 monitor_printf(cur_mon, "corrupted command\n");
5099 else
5100 handle_user_command(cur_mon, (char *)buf);
5103 cur_mon = old_mon;
5106 static void monitor_command_cb(void *opaque, const char *cmdline,
5107 void *readline_opaque)
5109 Monitor *mon = opaque;
5111 monitor_suspend(mon);
5112 handle_user_command(mon, cmdline);
5113 monitor_resume(mon);
5116 int monitor_suspend(Monitor *mon)
5118 if (!mon->rs)
5119 return -ENOTTY;
5120 mon->suspend_cnt++;
5121 return 0;
5124 void monitor_resume(Monitor *mon)
5126 if (!mon->rs)
5127 return;
5128 if (--mon->suspend_cnt == 0)
5129 readline_show_prompt(mon->rs);
5132 static QObject *get_qmp_greeting(void)
5134 QObject *ver = NULL;
5136 qmp_marshal_input_query_version(NULL, NULL, &ver);
5137 return qobject_from_jsonf("{'QMP':{'version': %p,'capabilities': []}}",ver);
5141 * monitor_control_event(): Print QMP gretting
5143 static void monitor_control_event(void *opaque, int event)
5145 QObject *data;
5146 Monitor *mon = opaque;
5148 switch (event) {
5149 case CHR_EVENT_OPENED:
5150 mon->mc->command_mode = 0;
5151 data = get_qmp_greeting();
5152 monitor_json_emitter(mon, data);
5153 qobject_decref(data);
5154 mon_refcount++;
5155 break;
5156 case CHR_EVENT_CLOSED:
5157 json_message_parser_destroy(&mon->mc->parser);
5158 json_message_parser_init(&mon->mc->parser, handle_qmp_command);
5159 mon_refcount--;
5160 monitor_fdsets_cleanup();
5161 break;
5165 static void monitor_event(void *opaque, int event)
5167 Monitor *mon = opaque;
5169 switch (event) {
5170 case CHR_EVENT_MUX_IN:
5171 qemu_mutex_lock(&mon->out_lock);
5172 mon->mux_out = 0;
5173 qemu_mutex_unlock(&mon->out_lock);
5174 if (mon->reset_seen) {
5175 readline_restart(mon->rs);
5176 monitor_resume(mon);
5177 monitor_flush(mon);
5178 } else {
5179 mon->suspend_cnt = 0;
5181 break;
5183 case CHR_EVENT_MUX_OUT:
5184 if (mon->reset_seen) {
5185 if (mon->suspend_cnt == 0) {
5186 monitor_printf(mon, "\n");
5188 monitor_flush(mon);
5189 monitor_suspend(mon);
5190 } else {
5191 mon->suspend_cnt++;
5193 qemu_mutex_lock(&mon->out_lock);
5194 mon->mux_out = 1;
5195 qemu_mutex_unlock(&mon->out_lock);
5196 break;
5198 case CHR_EVENT_OPENED:
5199 monitor_printf(mon, "QEMU %s monitor - type 'help' for more "
5200 "information\n", QEMU_VERSION);
5201 if (!mon->mux_out) {
5202 readline_restart(mon->rs);
5203 readline_show_prompt(mon->rs);
5205 mon->reset_seen = 1;
5206 mon_refcount++;
5207 break;
5209 case CHR_EVENT_CLOSED:
5210 mon_refcount--;
5211 monitor_fdsets_cleanup();
5212 break;
5216 static int
5217 compare_mon_cmd(const void *a, const void *b)
5219 return strcmp(((const mon_cmd_t *)a)->name,
5220 ((const mon_cmd_t *)b)->name);
5223 static void sortcmdlist(void)
5225 int array_num;
5226 int elem_size = sizeof(mon_cmd_t);
5228 array_num = sizeof(mon_cmds)/elem_size-1;
5229 qsort((void *)mon_cmds, array_num, elem_size, compare_mon_cmd);
5231 array_num = sizeof(info_cmds)/elem_size-1;
5232 qsort((void *)info_cmds, array_num, elem_size, compare_mon_cmd);
5237 * Local variables:
5238 * c-indent-level: 4
5239 * c-basic-offset: 4
5240 * tab-width: 8
5241 * End:
5244 /* These functions just adapt the readline interface in a typesafe way. We
5245 * could cast function pointers but that discards compiler checks.
5247 static void GCC_FMT_ATTR(2, 3) monitor_readline_printf(void *opaque,
5248 const char *fmt, ...)
5250 va_list ap;
5251 va_start(ap, fmt);
5252 monitor_vprintf(opaque, fmt, ap);
5253 va_end(ap);
5256 static void monitor_readline_flush(void *opaque)
5258 monitor_flush(opaque);
5261 static void __attribute__((constructor)) monitor_lock_init(void)
5263 qemu_mutex_init(&monitor_lock);
5266 void monitor_init(CharDriverState *chr, int flags)
5268 static int is_first_init = 1;
5269 Monitor *mon;
5271 if (is_first_init) {
5272 monitor_qapi_event_init();
5273 sortcmdlist();
5274 is_first_init = 0;
5277 mon = g_malloc(sizeof(*mon));
5278 monitor_data_init(mon);
5280 mon->chr = chr;
5281 mon->flags = flags;
5282 if (flags & MONITOR_USE_READLINE) {
5283 mon->rs = readline_init(monitor_readline_printf,
5284 monitor_readline_flush,
5285 mon,
5286 monitor_find_completion);
5287 monitor_read_command(mon, 0);
5290 if (monitor_ctrl_mode(mon)) {
5291 mon->mc = g_malloc0(sizeof(MonitorControl));
5292 /* Control mode requires special handlers */
5293 qemu_chr_add_handlers(chr, monitor_can_read, monitor_control_read,
5294 monitor_control_event, mon);
5295 qemu_chr_fe_set_echo(chr, true);
5297 json_message_parser_init(&mon->mc->parser, handle_qmp_command);
5298 } else {
5299 qemu_chr_add_handlers(chr, monitor_can_read, monitor_read,
5300 monitor_event, mon);
5303 qemu_mutex_lock(&monitor_lock);
5304 QLIST_INSERT_HEAD(&mon_list, mon, entry);
5305 qemu_mutex_unlock(&monitor_lock);
5307 if (!default_mon || (flags & MONITOR_IS_DEFAULT))
5308 default_mon = mon;
5311 static void bdrv_password_cb(void *opaque, const char *password,
5312 void *readline_opaque)
5314 Monitor *mon = opaque;
5315 BlockDriverState *bs = readline_opaque;
5316 int ret = 0;
5317 Error *local_err = NULL;
5319 bdrv_add_key(bs, password, &local_err);
5320 if (local_err) {
5321 monitor_printf(mon, "%s\n", error_get_pretty(local_err));
5322 error_free(local_err);
5323 ret = -EPERM;
5325 if (mon->password_completion_cb)
5326 mon->password_completion_cb(mon->password_opaque, ret);
5328 monitor_read_command(mon, 1);
5331 int monitor_read_bdrv_key_start(Monitor *mon, BlockDriverState *bs,
5332 BlockCompletionFunc *completion_cb,
5333 void *opaque)
5335 int err;
5337 monitor_printf(mon, "%s (%s) is encrypted.\n", bdrv_get_device_name(bs),
5338 bdrv_get_encrypted_filename(bs));
5340 mon->password_completion_cb = completion_cb;
5341 mon->password_opaque = opaque;
5343 err = monitor_read_password(mon, bdrv_password_cb, bs);
5345 if (err && completion_cb)
5346 completion_cb(opaque, err);
5348 return err;
5351 int monitor_read_block_device_key(Monitor *mon, const char *device,
5352 BlockCompletionFunc *completion_cb,
5353 void *opaque)
5355 Error *err = NULL;
5356 BlockBackend *blk;
5358 blk = blk_by_name(device);
5359 if (!blk) {
5360 monitor_printf(mon, "Device not found %s\n", device);
5361 return -1;
5364 bdrv_add_key(blk_bs(blk), NULL, &err);
5365 if (err) {
5366 error_free(err);
5367 return monitor_read_bdrv_key_start(mon, blk_bs(blk), completion_cb, opaque);
5370 if (completion_cb) {
5371 completion_cb(opaque, 0);
5373 return 0;
5376 QemuOptsList qemu_mon_opts = {
5377 .name = "mon",
5378 .implied_opt_name = "chardev",
5379 .head = QTAILQ_HEAD_INITIALIZER(qemu_mon_opts.head),
5380 .desc = {
5382 .name = "mode",
5383 .type = QEMU_OPT_STRING,
5385 .name = "chardev",
5386 .type = QEMU_OPT_STRING,
5388 .name = "default",
5389 .type = QEMU_OPT_BOOL,
5391 .name = "pretty",
5392 .type = QEMU_OPT_BOOL,
5394 { /* end of list */ }
5398 #ifndef TARGET_I386
5399 void qmp_rtc_reset_reinjection(Error **errp)
5401 error_set(errp, QERR_FEATURE_DISABLED, "rtc-reset-reinjection");
5403 #endif