qemu-char: introduce qemu_chr_alloc
[qemu/ar7.git] / monitor.c
blob5c9eec109fea244283a11c07a82644f9cc76cc0c
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/pcmcia.h"
29 #include "hw/i386/pc.h"
30 #include "hw/pci/pci.h"
31 #include "sysemu/watchdog.h"
32 #include "hw/loader.h"
33 #include "exec/gdbstub.h"
34 #include "net/net.h"
35 #include "net/slirp.h"
36 #include "sysemu/char.h"
37 #include "ui/qemu-spice.h"
38 #include "sysemu/sysemu.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"
77 /* for pic/irq_info */
78 #if defined(TARGET_SPARC)
79 #include "hw/sparc/sun4m.h"
80 #endif
81 #include "hw/lm32/lm32_pic.h"
83 //#define DEBUG
84 //#define DEBUG_COMPLETION
87 * Supported types:
89 * 'F' filename
90 * 'B' block device name
91 * 's' string (accept optional quote)
92 * 'S' it just appends the rest of the string (accept optional quote)
93 * 'O' option string of the form NAME=VALUE,...
94 * parsed according to QemuOptsList given by its name
95 * Example: 'device:O' uses qemu_device_opts.
96 * Restriction: only lists with empty desc are supported
97 * TODO lift the restriction
98 * 'i' 32 bit integer
99 * 'l' target long (32 or 64 bit)
100 * 'M' Non-negative target long (32 or 64 bit), in user mode the
101 * value is multiplied by 2^20 (think Mebibyte)
102 * 'o' octets (aka bytes)
103 * user mode accepts an optional E, e, P, p, T, t, G, g, M, m,
104 * K, k suffix, which multiplies the value by 2^60 for suffixes E
105 * and e, 2^50 for suffixes P and p, 2^40 for suffixes T and t,
106 * 2^30 for suffixes G and g, 2^20 for M and m, 2^10 for K and k
107 * 'T' double
108 * user mode accepts an optional ms, us, ns suffix,
109 * which divides the value by 1e3, 1e6, 1e9, respectively
110 * '/' optional gdb-like print format (like "/10x")
112 * '?' optional type (for all types, except '/')
113 * '.' other form of optional type (for 'i' and 'l')
114 * 'b' boolean
115 * user mode accepts "on" or "off"
116 * '-' optional parameter (eg. '-f')
120 typedef struct MonitorCompletionData MonitorCompletionData;
121 struct MonitorCompletionData {
122 Monitor *mon;
123 void (*user_print)(Monitor *mon, const QObject *data);
126 typedef struct mon_cmd_t {
127 const char *name;
128 const char *args_type;
129 const char *params;
130 const char *help;
131 void (*user_print)(Monitor *mon, const QObject *data);
132 union {
133 void (*cmd)(Monitor *mon, const QDict *qdict);
134 int (*cmd_new)(Monitor *mon, const QDict *params, QObject **ret_data);
135 int (*cmd_async)(Monitor *mon, const QDict *params,
136 MonitorCompletion *cb, void *opaque);
137 } mhandler;
138 int flags;
139 /* @sub_table is a list of 2nd level of commands. If it do not exist,
140 * mhandler should be used. If it exist, sub_table[?].mhandler should be
141 * used, and mhandler of 1st level plays the role of help function.
143 struct mon_cmd_t *sub_table;
144 void (*command_completion)(ReadLineState *rs, int nb_args, const char *str);
145 } mon_cmd_t;
147 /* file descriptors passed via SCM_RIGHTS */
148 typedef struct mon_fd_t mon_fd_t;
149 struct mon_fd_t {
150 char *name;
151 int fd;
152 QLIST_ENTRY(mon_fd_t) next;
155 /* file descriptor associated with a file descriptor set */
156 typedef struct MonFdsetFd MonFdsetFd;
157 struct MonFdsetFd {
158 int fd;
159 bool removed;
160 char *opaque;
161 QLIST_ENTRY(MonFdsetFd) next;
164 /* file descriptor set containing fds passed via SCM_RIGHTS */
165 typedef struct MonFdset MonFdset;
166 struct MonFdset {
167 int64_t id;
168 QLIST_HEAD(, MonFdsetFd) fds;
169 QLIST_HEAD(, MonFdsetFd) dup_fds;
170 QLIST_ENTRY(MonFdset) next;
173 typedef struct MonitorControl {
174 QObject *id;
175 JSONMessageParser parser;
176 int command_mode;
177 } MonitorControl;
180 * To prevent flooding clients, events can be throttled. The
181 * throttling is calculated globally, rather than per-Monitor
182 * instance.
184 typedef struct MonitorQAPIEventState {
185 QAPIEvent event; /* Event being tracked */
186 int64_t rate; /* Minimum time (in ns) between two events */
187 int64_t last; /* QEMU_CLOCK_REALTIME value at last emission */
188 QEMUTimer *timer; /* Timer for handling delayed events */
189 QObject *data; /* Event pending delayed dispatch */
190 } MonitorQAPIEventState;
192 struct Monitor {
193 CharDriverState *chr;
194 int mux_out;
195 int reset_seen;
196 int flags;
197 int suspend_cnt;
198 bool skip_flush;
199 QString *outbuf;
200 guint watch;
201 ReadLineState *rs;
202 MonitorControl *mc;
203 CPUState *mon_cpu;
204 BlockDriverCompletionFunc *password_completion_cb;
205 void *password_opaque;
206 mon_cmd_t *cmd_table;
207 QError *error;
208 QLIST_HEAD(,mon_fd_t) fds;
209 QLIST_ENTRY(Monitor) entry;
212 /* QMP checker flags */
213 #define QMP_ACCEPT_UNKNOWNS 1
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 (monitor_ctrl_mode(mon)) {
261 qerror_report(QERR_MISSING_PARAMETER, "password");
262 return -EINVAL;
263 } else if (mon->rs) {
264 readline_start(mon->rs, "Password: ", 1, readline_func, opaque);
265 /* prompt is printed on return from the command handler */
266 return 0;
267 } else {
268 monitor_printf(mon, "terminal does not support password prompting\n");
269 return -ENOTTY;
273 static gboolean monitor_unblocked(GIOChannel *chan, GIOCondition cond,
274 void *opaque)
276 Monitor *mon = opaque;
278 mon->watch = 0;
279 monitor_flush(mon);
280 return FALSE;
283 void monitor_flush(Monitor *mon)
285 int rc;
286 size_t len;
287 const char *buf;
289 if (mon->skip_flush) {
290 return;
293 buf = qstring_get_str(mon->outbuf);
294 len = qstring_get_length(mon->outbuf);
296 if (len && !mon->mux_out) {
297 rc = qemu_chr_fe_write(mon->chr, (const uint8_t *) buf, len);
298 if ((rc < 0 && errno != EAGAIN) || (rc == len)) {
299 /* all flushed or error */
300 QDECREF(mon->outbuf);
301 mon->outbuf = qstring_new();
302 return;
304 if (rc > 0) {
305 /* partinal write */
306 QString *tmp = qstring_from_str(buf + rc);
307 QDECREF(mon->outbuf);
308 mon->outbuf = tmp;
310 if (mon->watch == 0) {
311 mon->watch = qemu_chr_fe_add_watch(mon->chr, G_IO_OUT,
312 monitor_unblocked, mon);
317 /* flush at every end of line */
318 static void monitor_puts(Monitor *mon, const char *str)
320 char c;
322 for(;;) {
323 c = *str++;
324 if (c == '\0')
325 break;
326 if (c == '\n') {
327 qstring_append_chr(mon->outbuf, '\r');
329 qstring_append_chr(mon->outbuf, c);
330 if (c == '\n') {
331 monitor_flush(mon);
336 void monitor_vprintf(Monitor *mon, const char *fmt, va_list ap)
338 char *buf;
340 if (!mon)
341 return;
343 if (monitor_ctrl_mode(mon)) {
344 return;
347 buf = g_strdup_vprintf(fmt, ap);
348 monitor_puts(mon, buf);
349 g_free(buf);
352 void monitor_printf(Monitor *mon, const char *fmt, ...)
354 va_list ap;
355 va_start(ap, fmt);
356 monitor_vprintf(mon, fmt, ap);
357 va_end(ap);
360 static int GCC_FMT_ATTR(2, 3) monitor_fprintf(FILE *stream,
361 const char *fmt, ...)
363 va_list ap;
364 va_start(ap, fmt);
365 monitor_vprintf((Monitor *)stream, fmt, ap);
366 va_end(ap);
367 return 0;
370 static void monitor_user_noop(Monitor *mon, const QObject *data) { }
372 static inline int handler_is_qobject(const mon_cmd_t *cmd)
374 return cmd->user_print != NULL;
377 static inline bool handler_is_async(const mon_cmd_t *cmd)
379 return cmd->flags & MONITOR_CMD_ASYNC;
382 static inline int monitor_has_error(const Monitor *mon)
384 return mon->error != NULL;
387 static void monitor_json_emitter(Monitor *mon, const QObject *data)
389 QString *json;
391 json = mon->flags & MONITOR_USE_PRETTY ? qobject_to_json_pretty(data) :
392 qobject_to_json(data);
393 assert(json != NULL);
395 qstring_append_chr(json, '\n');
396 monitor_puts(mon, qstring_get_str(json));
398 QDECREF(json);
401 static QDict *build_qmp_error_dict(const QError *err)
403 QObject *obj;
405 obj = qobject_from_jsonf("{ 'error': { 'class': %s, 'desc': %p } }",
406 ErrorClass_lookup[err->err_class],
407 qerror_human(err));
409 return qobject_to_qdict(obj);
412 static void monitor_protocol_emitter(Monitor *mon, QObject *data)
414 QDict *qmp;
416 trace_monitor_protocol_emitter(mon);
418 if (!monitor_has_error(mon)) {
419 /* success response */
420 qmp = qdict_new();
421 if (data) {
422 qobject_incref(data);
423 qdict_put_obj(qmp, "return", data);
424 } else {
425 /* return an empty QDict by default */
426 qdict_put(qmp, "return", qdict_new());
428 } else {
429 /* error response */
430 qmp = build_qmp_error_dict(mon->error);
431 QDECREF(mon->error);
432 mon->error = NULL;
435 if (mon->mc->id) {
436 qdict_put_obj(qmp, "id", mon->mc->id);
437 mon->mc->id = NULL;
440 monitor_json_emitter(mon, QOBJECT(qmp));
441 QDECREF(qmp);
445 static MonitorQAPIEventState monitor_qapi_event_state[QAPI_EVENT_MAX];
448 * Emits the event to every monitor instance, @event is only used for trace
450 static void monitor_qapi_event_emit(QAPIEvent event, QObject *data)
452 Monitor *mon;
454 trace_monitor_protocol_event_emit(event, data);
455 QLIST_FOREACH(mon, &mon_list, entry) {
456 if (monitor_ctrl_mode(mon) && qmp_cmd_mode(mon)) {
457 monitor_json_emitter(mon, data);
463 * Queue a new event for emission to Monitor instances,
464 * applying any rate limiting if required.
466 static void
467 monitor_qapi_event_queue(QAPIEvent event, QDict *data, Error **errp)
469 MonitorQAPIEventState *evstate;
470 assert(event < QAPI_EVENT_MAX);
471 int64_t now = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
473 evstate = &(monitor_qapi_event_state[event]);
474 trace_monitor_protocol_event_queue(event,
475 data,
476 evstate->rate,
477 evstate->last,
478 now);
480 /* Rate limit of 0 indicates no throttling */
481 if (!evstate->rate) {
482 monitor_qapi_event_emit(event, QOBJECT(data));
483 evstate->last = now;
484 } else {
485 int64_t delta = now - evstate->last;
486 if (evstate->data ||
487 delta < evstate->rate) {
488 /* If there's an existing event pending, replace
489 * it with the new event, otherwise schedule a
490 * timer for delayed emission
492 if (evstate->data) {
493 qobject_decref(evstate->data);
494 } else {
495 int64_t then = evstate->last + evstate->rate;
496 timer_mod_ns(evstate->timer, then);
498 evstate->data = QOBJECT(data);
499 qobject_incref(evstate->data);
500 } else {
501 monitor_qapi_event_emit(event, QOBJECT(data));
502 evstate->last = now;
508 * The callback invoked by QemuTimer when a delayed
509 * event is ready to be emitted
511 static void monitor_qapi_event_handler(void *opaque)
513 MonitorQAPIEventState *evstate = opaque;
514 int64_t now = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
516 trace_monitor_protocol_event_handler(evstate->event,
517 evstate->data,
518 evstate->last,
519 now);
520 if (evstate->data) {
521 monitor_qapi_event_emit(evstate->event, evstate->data);
522 qobject_decref(evstate->data);
523 evstate->data = NULL;
525 evstate->last = now;
529 * @event: the event ID to be limited
530 * @rate: the rate limit in milliseconds
532 * Sets a rate limit on a particular event, so no
533 * more than 1 event will be emitted within @rate
534 * milliseconds
536 static void
537 monitor_qapi_event_throttle(QAPIEvent event, int64_t rate)
539 MonitorQAPIEventState *evstate;
540 assert(event < QAPI_EVENT_MAX);
542 evstate = &(monitor_qapi_event_state[event]);
544 trace_monitor_protocol_event_throttle(event, rate);
545 evstate->event = event;
546 evstate->rate = rate * SCALE_MS;
547 evstate->last = 0;
548 evstate->data = NULL;
549 evstate->timer = timer_new(QEMU_CLOCK_REALTIME,
550 SCALE_MS,
551 monitor_qapi_event_handler,
552 evstate);
555 static void monitor_qapi_event_init(void)
557 /* Limit guest-triggerable events to 1 per second */
558 monitor_qapi_event_throttle(QAPI_EVENT_RTC_CHANGE, 1000);
559 monitor_qapi_event_throttle(QAPI_EVENT_WATCHDOG, 1000);
560 monitor_qapi_event_throttle(QAPI_EVENT_BALLOON_CHANGE, 1000);
561 /* limit the rate of quorum events to avoid hammering the management */
562 monitor_qapi_event_throttle(QAPI_EVENT_QUORUM_REPORT_BAD, 1000);
563 monitor_qapi_event_throttle(QAPI_EVENT_QUORUM_FAILURE, 1000);
565 qmp_event_set_func_emit(monitor_qapi_event_queue);
568 static int do_qmp_capabilities(Monitor *mon, const QDict *params,
569 QObject **ret_data)
571 /* Will setup QMP capabilities in the future */
572 if (monitor_ctrl_mode(mon)) {
573 mon->mc->command_mode = 1;
576 return 0;
579 static void handle_user_command(Monitor *mon, const char *cmdline);
581 static void monitor_data_init(Monitor *mon)
583 memset(mon, 0, sizeof(Monitor));
584 mon->outbuf = qstring_new();
585 /* Use *mon_cmds by default. */
586 mon->cmd_table = mon_cmds;
589 static void monitor_data_destroy(Monitor *mon)
591 QDECREF(mon->outbuf);
594 char *qmp_human_monitor_command(const char *command_line, bool has_cpu_index,
595 int64_t cpu_index, Error **errp)
597 char *output = NULL;
598 Monitor *old_mon, hmp;
600 monitor_data_init(&hmp);
601 hmp.skip_flush = true;
603 old_mon = cur_mon;
604 cur_mon = &hmp;
606 if (has_cpu_index) {
607 int ret = monitor_set_cpu(cpu_index);
608 if (ret < 0) {
609 cur_mon = old_mon;
610 error_set(errp, QERR_INVALID_PARAMETER_VALUE, "cpu-index",
611 "a CPU number");
612 goto out;
616 handle_user_command(&hmp, command_line);
617 cur_mon = old_mon;
619 if (qstring_get_length(hmp.outbuf) > 0) {
620 output = g_strdup(qstring_get_str(hmp.outbuf));
621 } else {
622 output = g_strdup("");
625 out:
626 monitor_data_destroy(&hmp);
627 return output;
630 static int compare_cmd(const char *name, const char *list)
632 const char *p, *pstart;
633 int len;
634 len = strlen(name);
635 p = list;
636 for(;;) {
637 pstart = p;
638 p = strchr(p, '|');
639 if (!p)
640 p = pstart + strlen(pstart);
641 if ((p - pstart) == len && !memcmp(pstart, name, len))
642 return 1;
643 if (*p == '\0')
644 break;
645 p++;
647 return 0;
650 static int get_str(char *buf, int buf_size, const char **pp)
652 const char *p;
653 char *q;
654 int c;
656 q = buf;
657 p = *pp;
658 while (qemu_isspace(*p)) {
659 p++;
661 if (*p == '\0') {
662 fail:
663 *q = '\0';
664 *pp = p;
665 return -1;
667 if (*p == '\"') {
668 p++;
669 while (*p != '\0' && *p != '\"') {
670 if (*p == '\\') {
671 p++;
672 c = *p++;
673 switch (c) {
674 case 'n':
675 c = '\n';
676 break;
677 case 'r':
678 c = '\r';
679 break;
680 case '\\':
681 case '\'':
682 case '\"':
683 break;
684 default:
685 qemu_printf("unsupported escape code: '\\%c'\n", c);
686 goto fail;
688 if ((q - buf) < buf_size - 1) {
689 *q++ = c;
691 } else {
692 if ((q - buf) < buf_size - 1) {
693 *q++ = *p;
695 p++;
698 if (*p != '\"') {
699 qemu_printf("unterminated string\n");
700 goto fail;
702 p++;
703 } else {
704 while (*p != '\0' && !qemu_isspace(*p)) {
705 if ((q - buf) < buf_size - 1) {
706 *q++ = *p;
708 p++;
711 *q = '\0';
712 *pp = p;
713 return 0;
716 #define MAX_ARGS 16
718 static void free_cmdline_args(char **args, int nb_args)
720 int i;
722 assert(nb_args <= MAX_ARGS);
724 for (i = 0; i < nb_args; i++) {
725 g_free(args[i]);
731 * Parse the command line to get valid args.
732 * @cmdline: command line to be parsed.
733 * @pnb_args: location to store the number of args, must NOT be NULL.
734 * @args: location to store the args, which should be freed by caller, must
735 * NOT be NULL.
737 * Returns 0 on success, negative on failure.
739 * NOTE: this parser is an approximate form of the real command parser. Number
740 * of args have a limit of MAX_ARGS. If cmdline contains more, it will
741 * return with failure.
743 static int parse_cmdline(const char *cmdline,
744 int *pnb_args, char **args)
746 const char *p;
747 int nb_args, ret;
748 char buf[1024];
750 p = cmdline;
751 nb_args = 0;
752 for (;;) {
753 while (qemu_isspace(*p)) {
754 p++;
756 if (*p == '\0') {
757 break;
759 if (nb_args >= MAX_ARGS) {
760 goto fail;
762 ret = get_str(buf, sizeof(buf), &p);
763 if (ret < 0) {
764 goto fail;
766 args[nb_args] = g_strdup(buf);
767 nb_args++;
769 *pnb_args = nb_args;
770 return 0;
772 fail:
773 free_cmdline_args(args, nb_args);
774 return -1;
777 static void help_cmd_dump_one(Monitor *mon,
778 const mon_cmd_t *cmd,
779 char **prefix_args,
780 int prefix_args_nb)
782 int i;
784 for (i = 0; i < prefix_args_nb; i++) {
785 monitor_printf(mon, "%s ", prefix_args[i]);
787 monitor_printf(mon, "%s %s -- %s\n", cmd->name, cmd->params, cmd->help);
790 /* @args[@arg_index] is the valid command need to find in @cmds */
791 static void help_cmd_dump(Monitor *mon, const mon_cmd_t *cmds,
792 char **args, int nb_args, int arg_index)
794 const mon_cmd_t *cmd;
796 /* No valid arg need to compare with, dump all in *cmds */
797 if (arg_index >= nb_args) {
798 for (cmd = cmds; cmd->name != NULL; cmd++) {
799 help_cmd_dump_one(mon, cmd, args, arg_index);
801 return;
804 /* Find one entry to dump */
805 for (cmd = cmds; cmd->name != NULL; cmd++) {
806 if (compare_cmd(args[arg_index], cmd->name)) {
807 if (cmd->sub_table) {
808 /* continue with next arg */
809 help_cmd_dump(mon, cmd->sub_table,
810 args, nb_args, arg_index + 1);
811 } else {
812 help_cmd_dump_one(mon, cmd, args, arg_index);
814 break;
819 static void help_cmd(Monitor *mon, const char *name)
821 char *args[MAX_ARGS];
822 int nb_args = 0;
824 /* 1. parse user input */
825 if (name) {
826 /* special case for log, directly dump and return */
827 if (!strcmp(name, "log")) {
828 const QEMULogItem *item;
829 monitor_printf(mon, "Log items (comma separated):\n");
830 monitor_printf(mon, "%-10s %s\n", "none", "remove all logs");
831 for (item = qemu_log_items; item->mask != 0; item++) {
832 monitor_printf(mon, "%-10s %s\n", item->name, item->help);
834 return;
837 if (parse_cmdline(name, &nb_args, args) < 0) {
838 return;
842 /* 2. dump the contents according to parsed args */
843 help_cmd_dump(mon, mon->cmd_table, args, nb_args, 0);
845 free_cmdline_args(args, nb_args);
848 static void do_help_cmd(Monitor *mon, const QDict *qdict)
850 help_cmd(mon, qdict_get_try_str(qdict, "name"));
853 static void do_trace_event_set_state(Monitor *mon, const QDict *qdict)
855 const char *tp_name = qdict_get_str(qdict, "name");
856 bool new_state = qdict_get_bool(qdict, "option");
858 bool found = false;
859 TraceEvent *ev = NULL;
860 while ((ev = trace_event_pattern(tp_name, ev)) != NULL) {
861 found = true;
862 if (!trace_event_get_state_static(ev)) {
863 monitor_printf(mon, "event \"%s\" is not traceable\n", tp_name);
864 } else {
865 trace_event_set_state_dynamic(ev, new_state);
868 if (!trace_event_is_pattern(tp_name) && !found) {
869 monitor_printf(mon, "unknown event name \"%s\"\n", tp_name);
873 #ifdef CONFIG_TRACE_SIMPLE
874 static void do_trace_file(Monitor *mon, const QDict *qdict)
876 const char *op = qdict_get_try_str(qdict, "op");
877 const char *arg = qdict_get_try_str(qdict, "arg");
879 if (!op) {
880 st_print_trace_file_status((FILE *)mon, &monitor_fprintf);
881 } else if (!strcmp(op, "on")) {
882 st_set_trace_file_enabled(true);
883 } else if (!strcmp(op, "off")) {
884 st_set_trace_file_enabled(false);
885 } else if (!strcmp(op, "flush")) {
886 st_flush_trace_buffer();
887 } else if (!strcmp(op, "set")) {
888 if (arg) {
889 st_set_trace_file(arg);
891 } else {
892 monitor_printf(mon, "unexpected argument \"%s\"\n", op);
893 help_cmd(mon, "trace-file");
896 #endif
898 static void user_monitor_complete(void *opaque, QObject *ret_data)
900 MonitorCompletionData *data = (MonitorCompletionData *)opaque;
902 if (ret_data) {
903 data->user_print(data->mon, ret_data);
905 monitor_resume(data->mon);
906 g_free(data);
909 static void qmp_monitor_complete(void *opaque, QObject *ret_data)
911 monitor_protocol_emitter(opaque, ret_data);
914 static int qmp_async_cmd_handler(Monitor *mon, const mon_cmd_t *cmd,
915 const QDict *params)
917 return cmd->mhandler.cmd_async(mon, params, qmp_monitor_complete, mon);
920 static void user_async_cmd_handler(Monitor *mon, const mon_cmd_t *cmd,
921 const QDict *params)
923 int ret;
925 MonitorCompletionData *cb_data = g_malloc(sizeof(*cb_data));
926 cb_data->mon = mon;
927 cb_data->user_print = cmd->user_print;
928 monitor_suspend(mon);
929 ret = cmd->mhandler.cmd_async(mon, params,
930 user_monitor_complete, cb_data);
931 if (ret < 0) {
932 monitor_resume(mon);
933 g_free(cb_data);
937 static void do_info_help(Monitor *mon, const QDict *qdict)
939 help_cmd(mon, "info");
942 CommandInfoList *qmp_query_commands(Error **errp)
944 CommandInfoList *info, *cmd_list = NULL;
945 const mon_cmd_t *cmd;
947 for (cmd = qmp_cmds; cmd->name != NULL; cmd++) {
948 info = g_malloc0(sizeof(*info));
949 info->value = g_malloc0(sizeof(*info->value));
950 info->value->name = g_strdup(cmd->name);
952 info->next = cmd_list;
953 cmd_list = info;
956 return cmd_list;
959 EventInfoList *qmp_query_events(Error **errp)
961 EventInfoList *info, *ev_list = NULL;
962 QAPIEvent e;
964 for (e = 0 ; e < QAPI_EVENT_MAX ; e++) {
965 const char *event_name = QAPIEvent_lookup[e];
966 assert(event_name != NULL);
967 info = g_malloc0(sizeof(*info));
968 info->value = g_malloc0(sizeof(*info->value));
969 info->value->name = g_strdup(event_name);
971 info->next = ev_list;
972 ev_list = info;
975 return ev_list;
978 /* set the current CPU defined by the user */
979 int monitor_set_cpu(int cpu_index)
981 CPUState *cpu;
983 cpu = qemu_get_cpu(cpu_index);
984 if (cpu == NULL) {
985 return -1;
987 cur_mon->mon_cpu = cpu;
988 return 0;
991 static CPUArchState *mon_get_cpu(void)
993 if (!cur_mon->mon_cpu) {
994 monitor_set_cpu(0);
996 cpu_synchronize_state(cur_mon->mon_cpu);
997 return cur_mon->mon_cpu->env_ptr;
1000 int monitor_get_cpu_index(void)
1002 CPUState *cpu = ENV_GET_CPU(mon_get_cpu());
1003 return cpu->cpu_index;
1006 static void do_info_registers(Monitor *mon, const QDict *qdict)
1008 CPUState *cpu;
1009 CPUArchState *env;
1010 env = mon_get_cpu();
1011 cpu = ENV_GET_CPU(env);
1012 cpu_dump_state(cpu, (FILE *)mon, monitor_fprintf, CPU_DUMP_FPU);
1015 static void do_info_jit(Monitor *mon, const QDict *qdict)
1017 dump_exec_info((FILE *)mon, monitor_fprintf);
1020 static void do_info_history(Monitor *mon, const QDict *qdict)
1022 int i;
1023 const char *str;
1025 if (!mon->rs)
1026 return;
1027 i = 0;
1028 for(;;) {
1029 str = readline_get_history(mon->rs, i);
1030 if (!str)
1031 break;
1032 monitor_printf(mon, "%d: '%s'\n", i, str);
1033 i++;
1037 static void do_info_cpu_stats(Monitor *mon, const QDict *qdict)
1039 CPUState *cpu;
1040 CPUArchState *env;
1042 env = mon_get_cpu();
1043 cpu = ENV_GET_CPU(env);
1044 cpu_dump_statistics(cpu, (FILE *)mon, &monitor_fprintf, 0);
1047 static void do_trace_print_events(Monitor *mon, const QDict *qdict)
1049 trace_print_events((FILE *)mon, &monitor_fprintf);
1052 static int client_migrate_info(Monitor *mon, const QDict *qdict,
1053 MonitorCompletion cb, void *opaque)
1055 const char *protocol = qdict_get_str(qdict, "protocol");
1056 const char *hostname = qdict_get_str(qdict, "hostname");
1057 const char *subject = qdict_get_try_str(qdict, "cert-subject");
1058 int port = qdict_get_try_int(qdict, "port", -1);
1059 int tls_port = qdict_get_try_int(qdict, "tls-port", -1);
1060 int ret;
1062 if (strcmp(protocol, "spice") == 0) {
1063 if (!using_spice) {
1064 qerror_report(QERR_DEVICE_NOT_ACTIVE, "spice");
1065 return -1;
1068 if (port == -1 && tls_port == -1) {
1069 qerror_report(QERR_MISSING_PARAMETER, "port/tls-port");
1070 return -1;
1073 ret = qemu_spice_migrate_info(hostname, port, tls_port, subject,
1074 cb, opaque);
1075 if (ret != 0) {
1076 qerror_report(QERR_UNDEFINED_ERROR);
1077 return -1;
1079 return 0;
1082 qerror_report(QERR_INVALID_PARAMETER, "protocol");
1083 return -1;
1086 static void do_logfile(Monitor *mon, const QDict *qdict)
1088 qemu_set_log_filename(qdict_get_str(qdict, "filename"));
1091 static void do_log(Monitor *mon, const QDict *qdict)
1093 int mask;
1094 const char *items = qdict_get_str(qdict, "items");
1096 if (!strcmp(items, "none")) {
1097 mask = 0;
1098 } else {
1099 mask = qemu_str_to_log_mask(items);
1100 if (!mask) {
1101 help_cmd(mon, "log");
1102 return;
1105 qemu_set_log(mask);
1108 static void do_singlestep(Monitor *mon, const QDict *qdict)
1110 const char *option = qdict_get_try_str(qdict, "option");
1111 if (!option || !strcmp(option, "on")) {
1112 singlestep = 1;
1113 } else if (!strcmp(option, "off")) {
1114 singlestep = 0;
1115 } else {
1116 monitor_printf(mon, "unexpected option %s\n", option);
1120 static void do_gdbserver(Monitor *mon, const QDict *qdict)
1122 const char *device = qdict_get_try_str(qdict, "device");
1123 if (!device)
1124 device = "tcp::" DEFAULT_GDBSTUB_PORT;
1125 if (gdbserver_start(device) < 0) {
1126 monitor_printf(mon, "Could not open gdbserver on device '%s'\n",
1127 device);
1128 } else if (strcmp(device, "none") == 0) {
1129 monitor_printf(mon, "Disabled gdbserver\n");
1130 } else {
1131 monitor_printf(mon, "Waiting for gdb connection on device '%s'\n",
1132 device);
1136 static void do_watchdog_action(Monitor *mon, const QDict *qdict)
1138 const char *action = qdict_get_str(qdict, "action");
1139 if (select_watchdog_action(action) == -1) {
1140 monitor_printf(mon, "Unknown watchdog action '%s'\n", action);
1144 static void monitor_printc(Monitor *mon, int c)
1146 monitor_printf(mon, "'");
1147 switch(c) {
1148 case '\'':
1149 monitor_printf(mon, "\\'");
1150 break;
1151 case '\\':
1152 monitor_printf(mon, "\\\\");
1153 break;
1154 case '\n':
1155 monitor_printf(mon, "\\n");
1156 break;
1157 case '\r':
1158 monitor_printf(mon, "\\r");
1159 break;
1160 default:
1161 if (c >= 32 && c <= 126) {
1162 monitor_printf(mon, "%c", c);
1163 } else {
1164 monitor_printf(mon, "\\x%02x", c);
1166 break;
1168 monitor_printf(mon, "'");
1171 static void memory_dump(Monitor *mon, int count, int format, int wsize,
1172 hwaddr addr, int is_physical)
1174 CPUArchState *env;
1175 int l, line_size, i, max_digits, len;
1176 uint8_t buf[16];
1177 uint64_t v;
1179 if (format == 'i') {
1180 int flags;
1181 flags = 0;
1182 env = mon_get_cpu();
1183 #ifdef TARGET_I386
1184 if (wsize == 2) {
1185 flags = 1;
1186 } else if (wsize == 4) {
1187 flags = 0;
1188 } else {
1189 /* as default we use the current CS size */
1190 flags = 0;
1191 if (env) {
1192 #ifdef TARGET_X86_64
1193 if ((env->efer & MSR_EFER_LMA) &&
1194 (env->segs[R_CS].flags & DESC_L_MASK))
1195 flags = 2;
1196 else
1197 #endif
1198 if (!(env->segs[R_CS].flags & DESC_B_MASK))
1199 flags = 1;
1202 #endif
1203 #ifdef TARGET_PPC
1204 flags = msr_le << 16;
1205 flags |= env->bfd_mach;
1206 #endif
1207 monitor_disas(mon, env, addr, count, is_physical, flags);
1208 return;
1211 len = wsize * count;
1212 if (wsize == 1)
1213 line_size = 8;
1214 else
1215 line_size = 16;
1216 max_digits = 0;
1218 switch(format) {
1219 case 'o':
1220 max_digits = (wsize * 8 + 2) / 3;
1221 break;
1222 default:
1223 case 'x':
1224 max_digits = (wsize * 8) / 4;
1225 break;
1226 case 'u':
1227 case 'd':
1228 max_digits = (wsize * 8 * 10 + 32) / 33;
1229 break;
1230 case 'c':
1231 wsize = 1;
1232 break;
1235 while (len > 0) {
1236 if (is_physical)
1237 monitor_printf(mon, TARGET_FMT_plx ":", addr);
1238 else
1239 monitor_printf(mon, TARGET_FMT_lx ":", (target_ulong)addr);
1240 l = len;
1241 if (l > line_size)
1242 l = line_size;
1243 if (is_physical) {
1244 cpu_physical_memory_read(addr, buf, l);
1245 } else {
1246 env = mon_get_cpu();
1247 if (cpu_memory_rw_debug(ENV_GET_CPU(env), addr, buf, l, 0) < 0) {
1248 monitor_printf(mon, " Cannot access memory\n");
1249 break;
1252 i = 0;
1253 while (i < l) {
1254 switch(wsize) {
1255 default:
1256 case 1:
1257 v = ldub_raw(buf + i);
1258 break;
1259 case 2:
1260 v = lduw_raw(buf + i);
1261 break;
1262 case 4:
1263 v = (uint32_t)ldl_raw(buf + i);
1264 break;
1265 case 8:
1266 v = ldq_raw(buf + i);
1267 break;
1269 monitor_printf(mon, " ");
1270 switch(format) {
1271 case 'o':
1272 monitor_printf(mon, "%#*" PRIo64, max_digits, v);
1273 break;
1274 case 'x':
1275 monitor_printf(mon, "0x%0*" PRIx64, max_digits, v);
1276 break;
1277 case 'u':
1278 monitor_printf(mon, "%*" PRIu64, max_digits, v);
1279 break;
1280 case 'd':
1281 monitor_printf(mon, "%*" PRId64, max_digits, v);
1282 break;
1283 case 'c':
1284 monitor_printc(mon, v);
1285 break;
1287 i += wsize;
1289 monitor_printf(mon, "\n");
1290 addr += l;
1291 len -= l;
1295 static void do_memory_dump(Monitor *mon, const QDict *qdict)
1297 int count = qdict_get_int(qdict, "count");
1298 int format = qdict_get_int(qdict, "format");
1299 int size = qdict_get_int(qdict, "size");
1300 target_long addr = qdict_get_int(qdict, "addr");
1302 memory_dump(mon, count, format, size, addr, 0);
1305 static void do_physical_memory_dump(Monitor *mon, const QDict *qdict)
1307 int count = qdict_get_int(qdict, "count");
1308 int format = qdict_get_int(qdict, "format");
1309 int size = qdict_get_int(qdict, "size");
1310 hwaddr addr = qdict_get_int(qdict, "addr");
1312 memory_dump(mon, count, format, size, addr, 1);
1315 static void do_print(Monitor *mon, const QDict *qdict)
1317 int format = qdict_get_int(qdict, "format");
1318 hwaddr val = qdict_get_int(qdict, "val");
1320 switch(format) {
1321 case 'o':
1322 monitor_printf(mon, "%#" HWADDR_PRIo, val);
1323 break;
1324 case 'x':
1325 monitor_printf(mon, "%#" HWADDR_PRIx, val);
1326 break;
1327 case 'u':
1328 monitor_printf(mon, "%" HWADDR_PRIu, val);
1329 break;
1330 default:
1331 case 'd':
1332 monitor_printf(mon, "%" HWADDR_PRId, val);
1333 break;
1334 case 'c':
1335 monitor_printc(mon, val);
1336 break;
1338 monitor_printf(mon, "\n");
1341 static void do_sum(Monitor *mon, const QDict *qdict)
1343 uint32_t addr;
1344 uint16_t sum;
1345 uint32_t start = qdict_get_int(qdict, "start");
1346 uint32_t size = qdict_get_int(qdict, "size");
1348 sum = 0;
1349 for(addr = start; addr < (start + size); addr++) {
1350 uint8_t val = ldub_phys(&address_space_memory, addr);
1351 /* BSD sum algorithm ('sum' Unix command) */
1352 sum = (sum >> 1) | (sum << 15);
1353 sum += val;
1355 monitor_printf(mon, "%05d\n", sum);
1358 static int mouse_button_state;
1360 static void do_mouse_move(Monitor *mon, const QDict *qdict)
1362 int dx, dy, dz, button;
1363 const char *dx_str = qdict_get_str(qdict, "dx_str");
1364 const char *dy_str = qdict_get_str(qdict, "dy_str");
1365 const char *dz_str = qdict_get_try_str(qdict, "dz_str");
1367 dx = strtol(dx_str, NULL, 0);
1368 dy = strtol(dy_str, NULL, 0);
1369 qemu_input_queue_rel(NULL, INPUT_AXIS_X, dx);
1370 qemu_input_queue_rel(NULL, INPUT_AXIS_Y, dy);
1372 if (dz_str) {
1373 dz = strtol(dz_str, NULL, 0);
1374 if (dz != 0) {
1375 button = (dz > 0) ? INPUT_BUTTON_WHEEL_UP : INPUT_BUTTON_WHEEL_DOWN;
1376 qemu_input_queue_btn(NULL, button, true);
1377 qemu_input_event_sync();
1378 qemu_input_queue_btn(NULL, button, false);
1381 qemu_input_event_sync();
1384 static void do_mouse_button(Monitor *mon, const QDict *qdict)
1386 static uint32_t bmap[INPUT_BUTTON_MAX] = {
1387 [INPUT_BUTTON_LEFT] = MOUSE_EVENT_LBUTTON,
1388 [INPUT_BUTTON_MIDDLE] = MOUSE_EVENT_MBUTTON,
1389 [INPUT_BUTTON_RIGHT] = MOUSE_EVENT_RBUTTON,
1391 int button_state = qdict_get_int(qdict, "button_state");
1393 if (mouse_button_state == button_state) {
1394 return;
1396 qemu_input_update_buttons(NULL, bmap, mouse_button_state, button_state);
1397 qemu_input_event_sync();
1398 mouse_button_state = button_state;
1401 static void do_ioport_read(Monitor *mon, const QDict *qdict)
1403 int size = qdict_get_int(qdict, "size");
1404 int addr = qdict_get_int(qdict, "addr");
1405 int has_index = qdict_haskey(qdict, "index");
1406 uint32_t val;
1407 int suffix;
1409 if (has_index) {
1410 int index = qdict_get_int(qdict, "index");
1411 cpu_outb(addr & IOPORTS_MASK, index & 0xff);
1412 addr++;
1414 addr &= 0xffff;
1416 switch(size) {
1417 default:
1418 case 1:
1419 val = cpu_inb(addr);
1420 suffix = 'b';
1421 break;
1422 case 2:
1423 val = cpu_inw(addr);
1424 suffix = 'w';
1425 break;
1426 case 4:
1427 val = cpu_inl(addr);
1428 suffix = 'l';
1429 break;
1431 monitor_printf(mon, "port%c[0x%04x] = %#0*x\n",
1432 suffix, addr, size * 2, val);
1435 static void do_ioport_write(Monitor *mon, const QDict *qdict)
1437 int size = qdict_get_int(qdict, "size");
1438 int addr = qdict_get_int(qdict, "addr");
1439 int val = qdict_get_int(qdict, "val");
1441 addr &= IOPORTS_MASK;
1443 switch (size) {
1444 default:
1445 case 1:
1446 cpu_outb(addr, val);
1447 break;
1448 case 2:
1449 cpu_outw(addr, val);
1450 break;
1451 case 4:
1452 cpu_outl(addr, val);
1453 break;
1457 static void do_boot_set(Monitor *mon, const QDict *qdict)
1459 int res;
1460 const char *bootdevice = qdict_get_str(qdict, "bootdevice");
1462 res = qemu_boot_set(bootdevice);
1463 if (res == 0) {
1464 monitor_printf(mon, "boot device list now set to %s\n", bootdevice);
1465 } else if (res > 0) {
1466 monitor_printf(mon, "setting boot device list failed\n");
1467 } else {
1468 monitor_printf(mon, "no function defined to set boot device list for "
1469 "this architecture\n");
1473 #if defined(TARGET_I386)
1474 static void print_pte(Monitor *mon, hwaddr addr,
1475 hwaddr pte,
1476 hwaddr mask)
1478 #ifdef TARGET_X86_64
1479 if (addr & (1ULL << 47)) {
1480 addr |= -1LL << 48;
1482 #endif
1483 monitor_printf(mon, TARGET_FMT_plx ": " TARGET_FMT_plx
1484 " %c%c%c%c%c%c%c%c%c\n",
1485 addr,
1486 pte & mask,
1487 pte & PG_NX_MASK ? 'X' : '-',
1488 pte & PG_GLOBAL_MASK ? 'G' : '-',
1489 pte & PG_PSE_MASK ? 'P' : '-',
1490 pte & PG_DIRTY_MASK ? 'D' : '-',
1491 pte & PG_ACCESSED_MASK ? 'A' : '-',
1492 pte & PG_PCD_MASK ? 'C' : '-',
1493 pte & PG_PWT_MASK ? 'T' : '-',
1494 pte & PG_USER_MASK ? 'U' : '-',
1495 pte & PG_RW_MASK ? 'W' : '-');
1498 static void tlb_info_32(Monitor *mon, CPUArchState *env)
1500 unsigned int l1, l2;
1501 uint32_t pgd, pde, pte;
1503 pgd = env->cr[3] & ~0xfff;
1504 for(l1 = 0; l1 < 1024; l1++) {
1505 cpu_physical_memory_read(pgd + l1 * 4, &pde, 4);
1506 pde = le32_to_cpu(pde);
1507 if (pde & PG_PRESENT_MASK) {
1508 if ((pde & PG_PSE_MASK) && (env->cr[4] & CR4_PSE_MASK)) {
1509 /* 4M pages */
1510 print_pte(mon, (l1 << 22), pde, ~((1 << 21) - 1));
1511 } else {
1512 for(l2 = 0; l2 < 1024; l2++) {
1513 cpu_physical_memory_read((pde & ~0xfff) + l2 * 4, &pte, 4);
1514 pte = le32_to_cpu(pte);
1515 if (pte & PG_PRESENT_MASK) {
1516 print_pte(mon, (l1 << 22) + (l2 << 12),
1517 pte & ~PG_PSE_MASK,
1518 ~0xfff);
1526 static void tlb_info_pae32(Monitor *mon, CPUArchState *env)
1528 unsigned int l1, l2, l3;
1529 uint64_t pdpe, pde, pte;
1530 uint64_t pdp_addr, pd_addr, pt_addr;
1532 pdp_addr = env->cr[3] & ~0x1f;
1533 for (l1 = 0; l1 < 4; l1++) {
1534 cpu_physical_memory_read(pdp_addr + l1 * 8, &pdpe, 8);
1535 pdpe = le64_to_cpu(pdpe);
1536 if (pdpe & PG_PRESENT_MASK) {
1537 pd_addr = pdpe & 0x3fffffffff000ULL;
1538 for (l2 = 0; l2 < 512; l2++) {
1539 cpu_physical_memory_read(pd_addr + l2 * 8, &pde, 8);
1540 pde = le64_to_cpu(pde);
1541 if (pde & PG_PRESENT_MASK) {
1542 if (pde & PG_PSE_MASK) {
1543 /* 2M pages with PAE, CR4.PSE is ignored */
1544 print_pte(mon, (l1 << 30 ) + (l2 << 21), pde,
1545 ~((hwaddr)(1 << 20) - 1));
1546 } else {
1547 pt_addr = pde & 0x3fffffffff000ULL;
1548 for (l3 = 0; l3 < 512; l3++) {
1549 cpu_physical_memory_read(pt_addr + l3 * 8, &pte, 8);
1550 pte = le64_to_cpu(pte);
1551 if (pte & PG_PRESENT_MASK) {
1552 print_pte(mon, (l1 << 30 ) + (l2 << 21)
1553 + (l3 << 12),
1554 pte & ~PG_PSE_MASK,
1555 ~(hwaddr)0xfff);
1565 #ifdef TARGET_X86_64
1566 static void tlb_info_64(Monitor *mon, CPUArchState *env)
1568 uint64_t l1, l2, l3, l4;
1569 uint64_t pml4e, pdpe, pde, pte;
1570 uint64_t pml4_addr, pdp_addr, pd_addr, pt_addr;
1572 pml4_addr = env->cr[3] & 0x3fffffffff000ULL;
1573 for (l1 = 0; l1 < 512; l1++) {
1574 cpu_physical_memory_read(pml4_addr + l1 * 8, &pml4e, 8);
1575 pml4e = le64_to_cpu(pml4e);
1576 if (pml4e & PG_PRESENT_MASK) {
1577 pdp_addr = pml4e & 0x3fffffffff000ULL;
1578 for (l2 = 0; l2 < 512; l2++) {
1579 cpu_physical_memory_read(pdp_addr + l2 * 8, &pdpe, 8);
1580 pdpe = le64_to_cpu(pdpe);
1581 if (pdpe & PG_PRESENT_MASK) {
1582 if (pdpe & PG_PSE_MASK) {
1583 /* 1G pages, CR4.PSE is ignored */
1584 print_pte(mon, (l1 << 39) + (l2 << 30), pdpe,
1585 0x3ffffc0000000ULL);
1586 } else {
1587 pd_addr = pdpe & 0x3fffffffff000ULL;
1588 for (l3 = 0; l3 < 512; l3++) {
1589 cpu_physical_memory_read(pd_addr + l3 * 8, &pde, 8);
1590 pde = le64_to_cpu(pde);
1591 if (pde & PG_PRESENT_MASK) {
1592 if (pde & PG_PSE_MASK) {
1593 /* 2M pages, CR4.PSE is ignored */
1594 print_pte(mon, (l1 << 39) + (l2 << 30) +
1595 (l3 << 21), pde,
1596 0x3ffffffe00000ULL);
1597 } else {
1598 pt_addr = pde & 0x3fffffffff000ULL;
1599 for (l4 = 0; l4 < 512; l4++) {
1600 cpu_physical_memory_read(pt_addr
1601 + l4 * 8,
1602 &pte, 8);
1603 pte = le64_to_cpu(pte);
1604 if (pte & PG_PRESENT_MASK) {
1605 print_pte(mon, (l1 << 39) +
1606 (l2 << 30) +
1607 (l3 << 21) + (l4 << 12),
1608 pte & ~PG_PSE_MASK,
1609 0x3fffffffff000ULL);
1621 #endif
1623 static void tlb_info(Monitor *mon, const QDict *qdict)
1625 CPUArchState *env;
1627 env = mon_get_cpu();
1629 if (!(env->cr[0] & CR0_PG_MASK)) {
1630 monitor_printf(mon, "PG disabled\n");
1631 return;
1633 if (env->cr[4] & CR4_PAE_MASK) {
1634 #ifdef TARGET_X86_64
1635 if (env->hflags & HF_LMA_MASK) {
1636 tlb_info_64(mon, env);
1637 } else
1638 #endif
1640 tlb_info_pae32(mon, env);
1642 } else {
1643 tlb_info_32(mon, env);
1647 static void mem_print(Monitor *mon, hwaddr *pstart,
1648 int *plast_prot,
1649 hwaddr end, int prot)
1651 int prot1;
1652 prot1 = *plast_prot;
1653 if (prot != prot1) {
1654 if (*pstart != -1) {
1655 monitor_printf(mon, TARGET_FMT_plx "-" TARGET_FMT_plx " "
1656 TARGET_FMT_plx " %c%c%c\n",
1657 *pstart, end, end - *pstart,
1658 prot1 & PG_USER_MASK ? 'u' : '-',
1659 'r',
1660 prot1 & PG_RW_MASK ? 'w' : '-');
1662 if (prot != 0)
1663 *pstart = end;
1664 else
1665 *pstart = -1;
1666 *plast_prot = prot;
1670 static void mem_info_32(Monitor *mon, CPUArchState *env)
1672 unsigned int l1, l2;
1673 int prot, last_prot;
1674 uint32_t pgd, pde, pte;
1675 hwaddr start, end;
1677 pgd = env->cr[3] & ~0xfff;
1678 last_prot = 0;
1679 start = -1;
1680 for(l1 = 0; l1 < 1024; l1++) {
1681 cpu_physical_memory_read(pgd + l1 * 4, &pde, 4);
1682 pde = le32_to_cpu(pde);
1683 end = l1 << 22;
1684 if (pde & PG_PRESENT_MASK) {
1685 if ((pde & PG_PSE_MASK) && (env->cr[4] & CR4_PSE_MASK)) {
1686 prot = pde & (PG_USER_MASK | PG_RW_MASK | PG_PRESENT_MASK);
1687 mem_print(mon, &start, &last_prot, end, prot);
1688 } else {
1689 for(l2 = 0; l2 < 1024; l2++) {
1690 cpu_physical_memory_read((pde & ~0xfff) + l2 * 4, &pte, 4);
1691 pte = le32_to_cpu(pte);
1692 end = (l1 << 22) + (l2 << 12);
1693 if (pte & PG_PRESENT_MASK) {
1694 prot = pte & pde &
1695 (PG_USER_MASK | PG_RW_MASK | PG_PRESENT_MASK);
1696 } else {
1697 prot = 0;
1699 mem_print(mon, &start, &last_prot, end, prot);
1702 } else {
1703 prot = 0;
1704 mem_print(mon, &start, &last_prot, end, prot);
1707 /* Flush last range */
1708 mem_print(mon, &start, &last_prot, (hwaddr)1 << 32, 0);
1711 static void mem_info_pae32(Monitor *mon, CPUArchState *env)
1713 unsigned int l1, l2, l3;
1714 int prot, last_prot;
1715 uint64_t pdpe, pde, pte;
1716 uint64_t pdp_addr, pd_addr, pt_addr;
1717 hwaddr start, end;
1719 pdp_addr = env->cr[3] & ~0x1f;
1720 last_prot = 0;
1721 start = -1;
1722 for (l1 = 0; l1 < 4; l1++) {
1723 cpu_physical_memory_read(pdp_addr + l1 * 8, &pdpe, 8);
1724 pdpe = le64_to_cpu(pdpe);
1725 end = l1 << 30;
1726 if (pdpe & PG_PRESENT_MASK) {
1727 pd_addr = pdpe & 0x3fffffffff000ULL;
1728 for (l2 = 0; l2 < 512; l2++) {
1729 cpu_physical_memory_read(pd_addr + l2 * 8, &pde, 8);
1730 pde = le64_to_cpu(pde);
1731 end = (l1 << 30) + (l2 << 21);
1732 if (pde & PG_PRESENT_MASK) {
1733 if (pde & PG_PSE_MASK) {
1734 prot = pde & (PG_USER_MASK | PG_RW_MASK |
1735 PG_PRESENT_MASK);
1736 mem_print(mon, &start, &last_prot, end, prot);
1737 } else {
1738 pt_addr = pde & 0x3fffffffff000ULL;
1739 for (l3 = 0; l3 < 512; l3++) {
1740 cpu_physical_memory_read(pt_addr + l3 * 8, &pte, 8);
1741 pte = le64_to_cpu(pte);
1742 end = (l1 << 30) + (l2 << 21) + (l3 << 12);
1743 if (pte & PG_PRESENT_MASK) {
1744 prot = pte & pde & (PG_USER_MASK | PG_RW_MASK |
1745 PG_PRESENT_MASK);
1746 } else {
1747 prot = 0;
1749 mem_print(mon, &start, &last_prot, end, prot);
1752 } else {
1753 prot = 0;
1754 mem_print(mon, &start, &last_prot, end, prot);
1757 } else {
1758 prot = 0;
1759 mem_print(mon, &start, &last_prot, end, prot);
1762 /* Flush last range */
1763 mem_print(mon, &start, &last_prot, (hwaddr)1 << 32, 0);
1767 #ifdef TARGET_X86_64
1768 static void mem_info_64(Monitor *mon, CPUArchState *env)
1770 int prot, last_prot;
1771 uint64_t l1, l2, l3, l4;
1772 uint64_t pml4e, pdpe, pde, pte;
1773 uint64_t pml4_addr, pdp_addr, pd_addr, pt_addr, start, end;
1775 pml4_addr = env->cr[3] & 0x3fffffffff000ULL;
1776 last_prot = 0;
1777 start = -1;
1778 for (l1 = 0; l1 < 512; l1++) {
1779 cpu_physical_memory_read(pml4_addr + l1 * 8, &pml4e, 8);
1780 pml4e = le64_to_cpu(pml4e);
1781 end = l1 << 39;
1782 if (pml4e & PG_PRESENT_MASK) {
1783 pdp_addr = pml4e & 0x3fffffffff000ULL;
1784 for (l2 = 0; l2 < 512; l2++) {
1785 cpu_physical_memory_read(pdp_addr + l2 * 8, &pdpe, 8);
1786 pdpe = le64_to_cpu(pdpe);
1787 end = (l1 << 39) + (l2 << 30);
1788 if (pdpe & PG_PRESENT_MASK) {
1789 if (pdpe & PG_PSE_MASK) {
1790 prot = pdpe & (PG_USER_MASK | PG_RW_MASK |
1791 PG_PRESENT_MASK);
1792 prot &= pml4e;
1793 mem_print(mon, &start, &last_prot, end, prot);
1794 } else {
1795 pd_addr = pdpe & 0x3fffffffff000ULL;
1796 for (l3 = 0; l3 < 512; l3++) {
1797 cpu_physical_memory_read(pd_addr + l3 * 8, &pde, 8);
1798 pde = le64_to_cpu(pde);
1799 end = (l1 << 39) + (l2 << 30) + (l3 << 21);
1800 if (pde & PG_PRESENT_MASK) {
1801 if (pde & PG_PSE_MASK) {
1802 prot = pde & (PG_USER_MASK | PG_RW_MASK |
1803 PG_PRESENT_MASK);
1804 prot &= pml4e & pdpe;
1805 mem_print(mon, &start, &last_prot, end, prot);
1806 } else {
1807 pt_addr = pde & 0x3fffffffff000ULL;
1808 for (l4 = 0; l4 < 512; l4++) {
1809 cpu_physical_memory_read(pt_addr
1810 + l4 * 8,
1811 &pte, 8);
1812 pte = le64_to_cpu(pte);
1813 end = (l1 << 39) + (l2 << 30) +
1814 (l3 << 21) + (l4 << 12);
1815 if (pte & PG_PRESENT_MASK) {
1816 prot = pte & (PG_USER_MASK | PG_RW_MASK |
1817 PG_PRESENT_MASK);
1818 prot &= pml4e & pdpe & pde;
1819 } else {
1820 prot = 0;
1822 mem_print(mon, &start, &last_prot, end, prot);
1825 } else {
1826 prot = 0;
1827 mem_print(mon, &start, &last_prot, end, prot);
1831 } else {
1832 prot = 0;
1833 mem_print(mon, &start, &last_prot, end, prot);
1836 } else {
1837 prot = 0;
1838 mem_print(mon, &start, &last_prot, end, prot);
1841 /* Flush last range */
1842 mem_print(mon, &start, &last_prot, (hwaddr)1 << 48, 0);
1844 #endif
1846 static void mem_info(Monitor *mon, const QDict *qdict)
1848 CPUArchState *env;
1850 env = mon_get_cpu();
1852 if (!(env->cr[0] & CR0_PG_MASK)) {
1853 monitor_printf(mon, "PG disabled\n");
1854 return;
1856 if (env->cr[4] & CR4_PAE_MASK) {
1857 #ifdef TARGET_X86_64
1858 if (env->hflags & HF_LMA_MASK) {
1859 mem_info_64(mon, env);
1860 } else
1861 #endif
1863 mem_info_pae32(mon, env);
1865 } else {
1866 mem_info_32(mon, env);
1869 #endif
1871 #if defined(TARGET_SH4)
1873 static void print_tlb(Monitor *mon, int idx, tlb_t *tlb)
1875 monitor_printf(mon, " tlb%i:\t"
1876 "asid=%hhu vpn=%x\tppn=%x\tsz=%hhu size=%u\t"
1877 "v=%hhu shared=%hhu cached=%hhu prot=%hhu "
1878 "dirty=%hhu writethrough=%hhu\n",
1879 idx,
1880 tlb->asid, tlb->vpn, tlb->ppn, tlb->sz, tlb->size,
1881 tlb->v, tlb->sh, tlb->c, tlb->pr,
1882 tlb->d, tlb->wt);
1885 static void tlb_info(Monitor *mon, const QDict *qdict)
1887 CPUArchState *env = mon_get_cpu();
1888 int i;
1890 monitor_printf (mon, "ITLB:\n");
1891 for (i = 0 ; i < ITLB_SIZE ; i++)
1892 print_tlb (mon, i, &env->itlb[i]);
1893 monitor_printf (mon, "UTLB:\n");
1894 for (i = 0 ; i < UTLB_SIZE ; i++)
1895 print_tlb (mon, i, &env->utlb[i]);
1898 #endif
1900 #if defined(TARGET_SPARC) || defined(TARGET_PPC) || defined(TARGET_XTENSA)
1901 static void tlb_info(Monitor *mon, const QDict *qdict)
1903 CPUArchState *env1 = mon_get_cpu();
1905 dump_mmu((FILE*)mon, (fprintf_function)monitor_printf, env1);
1907 #endif
1909 static void do_info_mtree(Monitor *mon, const QDict *qdict)
1911 mtree_info((fprintf_function)monitor_printf, mon);
1914 static void do_info_numa(Monitor *mon, const QDict *qdict)
1916 int i;
1917 CPUState *cpu;
1919 monitor_printf(mon, "%d nodes\n", nb_numa_nodes);
1920 for (i = 0; i < nb_numa_nodes; i++) {
1921 monitor_printf(mon, "node %d cpus:", i);
1922 CPU_FOREACH(cpu) {
1923 if (cpu->numa_node == i) {
1924 monitor_printf(mon, " %d", cpu->cpu_index);
1927 monitor_printf(mon, "\n");
1928 monitor_printf(mon, "node %d size: %" PRId64 " MB\n", i,
1929 numa_info[i].node_mem >> 20);
1933 #ifdef CONFIG_PROFILER
1935 int64_t qemu_time;
1936 int64_t dev_time;
1938 static void do_info_profile(Monitor *mon, const QDict *qdict)
1940 monitor_printf(mon, "async time %" PRId64 " (%0.3f)\n",
1941 dev_time, dev_time / (double)get_ticks_per_sec());
1942 monitor_printf(mon, "qemu time %" PRId64 " (%0.3f)\n",
1943 qemu_time, qemu_time / (double)get_ticks_per_sec());
1944 qemu_time = 0;
1945 dev_time = 0;
1947 #else
1948 static void do_info_profile(Monitor *mon, const QDict *qdict)
1950 monitor_printf(mon, "Internal profiler not compiled\n");
1952 #endif
1954 /* Capture support */
1955 static QLIST_HEAD (capture_list_head, CaptureState) capture_head;
1957 static void do_info_capture(Monitor *mon, const QDict *qdict)
1959 int i;
1960 CaptureState *s;
1962 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
1963 monitor_printf(mon, "[%d]: ", i);
1964 s->ops.info (s->opaque);
1968 static void do_stop_capture(Monitor *mon, const QDict *qdict)
1970 int i;
1971 int n = qdict_get_int(qdict, "n");
1972 CaptureState *s;
1974 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
1975 if (i == n) {
1976 s->ops.destroy (s->opaque);
1977 QLIST_REMOVE (s, entries);
1978 g_free (s);
1979 return;
1984 static void do_wav_capture(Monitor *mon, const QDict *qdict)
1986 const char *path = qdict_get_str(qdict, "path");
1987 int has_freq = qdict_haskey(qdict, "freq");
1988 int freq = qdict_get_try_int(qdict, "freq", -1);
1989 int has_bits = qdict_haskey(qdict, "bits");
1990 int bits = qdict_get_try_int(qdict, "bits", -1);
1991 int has_channels = qdict_haskey(qdict, "nchannels");
1992 int nchannels = qdict_get_try_int(qdict, "nchannels", -1);
1993 CaptureState *s;
1995 s = g_malloc0 (sizeof (*s));
1997 freq = has_freq ? freq : 44100;
1998 bits = has_bits ? bits : 16;
1999 nchannels = has_channels ? nchannels : 2;
2001 if (wav_start_capture (s, path, freq, bits, nchannels)) {
2002 monitor_printf(mon, "Failed to add wave capture\n");
2003 g_free (s);
2004 return;
2006 QLIST_INSERT_HEAD (&capture_head, s, entries);
2009 static qemu_acl *find_acl(Monitor *mon, const char *name)
2011 qemu_acl *acl = qemu_acl_find(name);
2013 if (!acl) {
2014 monitor_printf(mon, "acl: unknown list '%s'\n", name);
2016 return acl;
2019 static void do_acl_show(Monitor *mon, const QDict *qdict)
2021 const char *aclname = qdict_get_str(qdict, "aclname");
2022 qemu_acl *acl = find_acl(mon, aclname);
2023 qemu_acl_entry *entry;
2024 int i = 0;
2026 if (acl) {
2027 monitor_printf(mon, "policy: %s\n",
2028 acl->defaultDeny ? "deny" : "allow");
2029 QTAILQ_FOREACH(entry, &acl->entries, next) {
2030 i++;
2031 monitor_printf(mon, "%d: %s %s\n", i,
2032 entry->deny ? "deny" : "allow", entry->match);
2037 static void do_acl_reset(Monitor *mon, const QDict *qdict)
2039 const char *aclname = qdict_get_str(qdict, "aclname");
2040 qemu_acl *acl = find_acl(mon, aclname);
2042 if (acl) {
2043 qemu_acl_reset(acl);
2044 monitor_printf(mon, "acl: removed all rules\n");
2048 static void do_acl_policy(Monitor *mon, const QDict *qdict)
2050 const char *aclname = qdict_get_str(qdict, "aclname");
2051 const char *policy = qdict_get_str(qdict, "policy");
2052 qemu_acl *acl = find_acl(mon, aclname);
2054 if (acl) {
2055 if (strcmp(policy, "allow") == 0) {
2056 acl->defaultDeny = 0;
2057 monitor_printf(mon, "acl: policy set to 'allow'\n");
2058 } else if (strcmp(policy, "deny") == 0) {
2059 acl->defaultDeny = 1;
2060 monitor_printf(mon, "acl: policy set to 'deny'\n");
2061 } else {
2062 monitor_printf(mon, "acl: unknown policy '%s', "
2063 "expected 'deny' or 'allow'\n", policy);
2068 static void do_acl_add(Monitor *mon, const QDict *qdict)
2070 const char *aclname = qdict_get_str(qdict, "aclname");
2071 const char *match = qdict_get_str(qdict, "match");
2072 const char *policy = qdict_get_str(qdict, "policy");
2073 int has_index = qdict_haskey(qdict, "index");
2074 int index = qdict_get_try_int(qdict, "index", -1);
2075 qemu_acl *acl = find_acl(mon, aclname);
2076 int deny, ret;
2078 if (acl) {
2079 if (strcmp(policy, "allow") == 0) {
2080 deny = 0;
2081 } else if (strcmp(policy, "deny") == 0) {
2082 deny = 1;
2083 } else {
2084 monitor_printf(mon, "acl: unknown policy '%s', "
2085 "expected 'deny' or 'allow'\n", policy);
2086 return;
2088 if (has_index)
2089 ret = qemu_acl_insert(acl, deny, match, index);
2090 else
2091 ret = qemu_acl_append(acl, deny, match);
2092 if (ret < 0)
2093 monitor_printf(mon, "acl: unable to add acl entry\n");
2094 else
2095 monitor_printf(mon, "acl: added rule at position %d\n", ret);
2099 static void do_acl_remove(Monitor *mon, const QDict *qdict)
2101 const char *aclname = qdict_get_str(qdict, "aclname");
2102 const char *match = qdict_get_str(qdict, "match");
2103 qemu_acl *acl = find_acl(mon, aclname);
2104 int ret;
2106 if (acl) {
2107 ret = qemu_acl_remove(acl, match);
2108 if (ret < 0)
2109 monitor_printf(mon, "acl: no matching acl entry\n");
2110 else
2111 monitor_printf(mon, "acl: removed rule at position %d\n", ret);
2115 #if defined(TARGET_I386)
2116 static void do_inject_mce(Monitor *mon, const QDict *qdict)
2118 X86CPU *cpu;
2119 CPUState *cs;
2120 int cpu_index = qdict_get_int(qdict, "cpu_index");
2121 int bank = qdict_get_int(qdict, "bank");
2122 uint64_t status = qdict_get_int(qdict, "status");
2123 uint64_t mcg_status = qdict_get_int(qdict, "mcg_status");
2124 uint64_t addr = qdict_get_int(qdict, "addr");
2125 uint64_t misc = qdict_get_int(qdict, "misc");
2126 int flags = MCE_INJECT_UNCOND_AO;
2128 if (qdict_get_try_bool(qdict, "broadcast", 0)) {
2129 flags |= MCE_INJECT_BROADCAST;
2131 cs = qemu_get_cpu(cpu_index);
2132 if (cs != NULL) {
2133 cpu = X86_CPU(cs);
2134 cpu_x86_inject_mce(mon, cpu, bank, status, mcg_status, addr, misc,
2135 flags);
2138 #endif
2140 void qmp_getfd(const char *fdname, Error **errp)
2142 mon_fd_t *monfd;
2143 int fd;
2145 fd = qemu_chr_fe_get_msgfd(cur_mon->chr);
2146 if (fd == -1) {
2147 error_set(errp, QERR_FD_NOT_SUPPLIED);
2148 return;
2151 if (qemu_isdigit(fdname[0])) {
2152 close(fd);
2153 error_set(errp, QERR_INVALID_PARAMETER_VALUE, "fdname",
2154 "a name not starting with a digit");
2155 return;
2158 QLIST_FOREACH(monfd, &cur_mon->fds, next) {
2159 if (strcmp(monfd->name, fdname) != 0) {
2160 continue;
2163 close(monfd->fd);
2164 monfd->fd = fd;
2165 return;
2168 monfd = g_malloc0(sizeof(mon_fd_t));
2169 monfd->name = g_strdup(fdname);
2170 monfd->fd = fd;
2172 QLIST_INSERT_HEAD(&cur_mon->fds, monfd, next);
2175 void qmp_closefd(const char *fdname, Error **errp)
2177 mon_fd_t *monfd;
2179 QLIST_FOREACH(monfd, &cur_mon->fds, next) {
2180 if (strcmp(monfd->name, fdname) != 0) {
2181 continue;
2184 QLIST_REMOVE(monfd, next);
2185 close(monfd->fd);
2186 g_free(monfd->name);
2187 g_free(monfd);
2188 return;
2191 error_set(errp, QERR_FD_NOT_FOUND, fdname);
2194 static void do_loadvm(Monitor *mon, const QDict *qdict)
2196 int saved_vm_running = runstate_is_running();
2197 const char *name = qdict_get_str(qdict, "name");
2199 vm_stop(RUN_STATE_RESTORE_VM);
2201 if (load_vmstate(name) == 0 && saved_vm_running) {
2202 vm_start();
2206 int monitor_get_fd(Monitor *mon, const char *fdname, Error **errp)
2208 mon_fd_t *monfd;
2210 QLIST_FOREACH(monfd, &mon->fds, next) {
2211 int fd;
2213 if (strcmp(monfd->name, fdname) != 0) {
2214 continue;
2217 fd = monfd->fd;
2219 /* caller takes ownership of fd */
2220 QLIST_REMOVE(monfd, next);
2221 g_free(monfd->name);
2222 g_free(monfd);
2224 return fd;
2227 error_setg(errp, "File descriptor named '%s' has not been found", fdname);
2228 return -1;
2231 static void monitor_fdset_cleanup(MonFdset *mon_fdset)
2233 MonFdsetFd *mon_fdset_fd;
2234 MonFdsetFd *mon_fdset_fd_next;
2236 QLIST_FOREACH_SAFE(mon_fdset_fd, &mon_fdset->fds, next, mon_fdset_fd_next) {
2237 if ((mon_fdset_fd->removed ||
2238 (QLIST_EMPTY(&mon_fdset->dup_fds) && mon_refcount == 0)) &&
2239 runstate_is_running()) {
2240 close(mon_fdset_fd->fd);
2241 g_free(mon_fdset_fd->opaque);
2242 QLIST_REMOVE(mon_fdset_fd, next);
2243 g_free(mon_fdset_fd);
2247 if (QLIST_EMPTY(&mon_fdset->fds) && QLIST_EMPTY(&mon_fdset->dup_fds)) {
2248 QLIST_REMOVE(mon_fdset, next);
2249 g_free(mon_fdset);
2253 static void monitor_fdsets_cleanup(void)
2255 MonFdset *mon_fdset;
2256 MonFdset *mon_fdset_next;
2258 QLIST_FOREACH_SAFE(mon_fdset, &mon_fdsets, next, mon_fdset_next) {
2259 monitor_fdset_cleanup(mon_fdset);
2263 AddfdInfo *qmp_add_fd(bool has_fdset_id, int64_t fdset_id, bool has_opaque,
2264 const char *opaque, Error **errp)
2266 int fd;
2267 Monitor *mon = cur_mon;
2268 AddfdInfo *fdinfo;
2270 fd = qemu_chr_fe_get_msgfd(mon->chr);
2271 if (fd == -1) {
2272 error_set(errp, QERR_FD_NOT_SUPPLIED);
2273 goto error;
2276 fdinfo = monitor_fdset_add_fd(fd, has_fdset_id, fdset_id,
2277 has_opaque, opaque, errp);
2278 if (fdinfo) {
2279 return fdinfo;
2282 error:
2283 if (fd != -1) {
2284 close(fd);
2286 return NULL;
2289 void qmp_remove_fd(int64_t fdset_id, bool has_fd, int64_t fd, Error **errp)
2291 MonFdset *mon_fdset;
2292 MonFdsetFd *mon_fdset_fd;
2293 char fd_str[60];
2295 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2296 if (mon_fdset->id != fdset_id) {
2297 continue;
2299 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2300 if (has_fd) {
2301 if (mon_fdset_fd->fd != fd) {
2302 continue;
2304 mon_fdset_fd->removed = true;
2305 break;
2306 } else {
2307 mon_fdset_fd->removed = true;
2310 if (has_fd && !mon_fdset_fd) {
2311 goto error;
2313 monitor_fdset_cleanup(mon_fdset);
2314 return;
2317 error:
2318 if (has_fd) {
2319 snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64 ", fd:%" PRId64,
2320 fdset_id, fd);
2321 } else {
2322 snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64, fdset_id);
2324 error_set(errp, QERR_FD_NOT_FOUND, fd_str);
2327 FdsetInfoList *qmp_query_fdsets(Error **errp)
2329 MonFdset *mon_fdset;
2330 MonFdsetFd *mon_fdset_fd;
2331 FdsetInfoList *fdset_list = NULL;
2333 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2334 FdsetInfoList *fdset_info = g_malloc0(sizeof(*fdset_info));
2335 FdsetFdInfoList *fdsetfd_list = NULL;
2337 fdset_info->value = g_malloc0(sizeof(*fdset_info->value));
2338 fdset_info->value->fdset_id = mon_fdset->id;
2340 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2341 FdsetFdInfoList *fdsetfd_info;
2343 fdsetfd_info = g_malloc0(sizeof(*fdsetfd_info));
2344 fdsetfd_info->value = g_malloc0(sizeof(*fdsetfd_info->value));
2345 fdsetfd_info->value->fd = mon_fdset_fd->fd;
2346 if (mon_fdset_fd->opaque) {
2347 fdsetfd_info->value->has_opaque = true;
2348 fdsetfd_info->value->opaque = g_strdup(mon_fdset_fd->opaque);
2349 } else {
2350 fdsetfd_info->value->has_opaque = false;
2353 fdsetfd_info->next = fdsetfd_list;
2354 fdsetfd_list = fdsetfd_info;
2357 fdset_info->value->fds = fdsetfd_list;
2359 fdset_info->next = fdset_list;
2360 fdset_list = fdset_info;
2363 return fdset_list;
2366 AddfdInfo *monitor_fdset_add_fd(int fd, bool has_fdset_id, int64_t fdset_id,
2367 bool has_opaque, const char *opaque,
2368 Error **errp)
2370 MonFdset *mon_fdset = NULL;
2371 MonFdsetFd *mon_fdset_fd;
2372 AddfdInfo *fdinfo;
2374 if (has_fdset_id) {
2375 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2376 /* Break if match found or match impossible due to ordering by ID */
2377 if (fdset_id <= mon_fdset->id) {
2378 if (fdset_id < mon_fdset->id) {
2379 mon_fdset = NULL;
2381 break;
2386 if (mon_fdset == NULL) {
2387 int64_t fdset_id_prev = -1;
2388 MonFdset *mon_fdset_cur = QLIST_FIRST(&mon_fdsets);
2390 if (has_fdset_id) {
2391 if (fdset_id < 0) {
2392 error_set(errp, QERR_INVALID_PARAMETER_VALUE, "fdset-id",
2393 "a non-negative value");
2394 return NULL;
2396 /* Use specified fdset ID */
2397 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2398 mon_fdset_cur = mon_fdset;
2399 if (fdset_id < mon_fdset_cur->id) {
2400 break;
2403 } else {
2404 /* Use first available fdset ID */
2405 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2406 mon_fdset_cur = mon_fdset;
2407 if (fdset_id_prev == mon_fdset_cur->id - 1) {
2408 fdset_id_prev = mon_fdset_cur->id;
2409 continue;
2411 break;
2415 mon_fdset = g_malloc0(sizeof(*mon_fdset));
2416 if (has_fdset_id) {
2417 mon_fdset->id = fdset_id;
2418 } else {
2419 mon_fdset->id = fdset_id_prev + 1;
2422 /* The fdset list is ordered by fdset ID */
2423 if (!mon_fdset_cur) {
2424 QLIST_INSERT_HEAD(&mon_fdsets, mon_fdset, next);
2425 } else if (mon_fdset->id < mon_fdset_cur->id) {
2426 QLIST_INSERT_BEFORE(mon_fdset_cur, mon_fdset, next);
2427 } else {
2428 QLIST_INSERT_AFTER(mon_fdset_cur, mon_fdset, next);
2432 mon_fdset_fd = g_malloc0(sizeof(*mon_fdset_fd));
2433 mon_fdset_fd->fd = fd;
2434 mon_fdset_fd->removed = false;
2435 if (has_opaque) {
2436 mon_fdset_fd->opaque = g_strdup(opaque);
2438 QLIST_INSERT_HEAD(&mon_fdset->fds, mon_fdset_fd, next);
2440 fdinfo = g_malloc0(sizeof(*fdinfo));
2441 fdinfo->fdset_id = mon_fdset->id;
2442 fdinfo->fd = mon_fdset_fd->fd;
2444 return fdinfo;
2447 int monitor_fdset_get_fd(int64_t fdset_id, int flags)
2449 #ifndef _WIN32
2450 MonFdset *mon_fdset;
2451 MonFdsetFd *mon_fdset_fd;
2452 int mon_fd_flags;
2454 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2455 if (mon_fdset->id != fdset_id) {
2456 continue;
2458 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2459 mon_fd_flags = fcntl(mon_fdset_fd->fd, F_GETFL);
2460 if (mon_fd_flags == -1) {
2461 return -1;
2464 if ((flags & O_ACCMODE) == (mon_fd_flags & O_ACCMODE)) {
2465 return mon_fdset_fd->fd;
2468 errno = EACCES;
2469 return -1;
2471 #endif
2473 errno = ENOENT;
2474 return -1;
2477 int monitor_fdset_dup_fd_add(int64_t fdset_id, int dup_fd)
2479 MonFdset *mon_fdset;
2480 MonFdsetFd *mon_fdset_fd_dup;
2482 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2483 if (mon_fdset->id != fdset_id) {
2484 continue;
2486 QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
2487 if (mon_fdset_fd_dup->fd == dup_fd) {
2488 return -1;
2491 mon_fdset_fd_dup = g_malloc0(sizeof(*mon_fdset_fd_dup));
2492 mon_fdset_fd_dup->fd = dup_fd;
2493 QLIST_INSERT_HEAD(&mon_fdset->dup_fds, mon_fdset_fd_dup, next);
2494 return 0;
2496 return -1;
2499 static int monitor_fdset_dup_fd_find_remove(int dup_fd, bool remove)
2501 MonFdset *mon_fdset;
2502 MonFdsetFd *mon_fdset_fd_dup;
2504 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2505 QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
2506 if (mon_fdset_fd_dup->fd == dup_fd) {
2507 if (remove) {
2508 QLIST_REMOVE(mon_fdset_fd_dup, next);
2509 if (QLIST_EMPTY(&mon_fdset->dup_fds)) {
2510 monitor_fdset_cleanup(mon_fdset);
2513 return mon_fdset->id;
2517 return -1;
2520 int monitor_fdset_dup_fd_find(int dup_fd)
2522 return monitor_fdset_dup_fd_find_remove(dup_fd, false);
2525 int monitor_fdset_dup_fd_remove(int dup_fd)
2527 return monitor_fdset_dup_fd_find_remove(dup_fd, true);
2530 int monitor_handle_fd_param(Monitor *mon, const char *fdname)
2532 int fd;
2533 Error *local_err = NULL;
2535 fd = monitor_handle_fd_param2(mon, fdname, &local_err);
2536 if (local_err) {
2537 qerror_report_err(local_err);
2538 error_free(local_err);
2540 return fd;
2543 int monitor_handle_fd_param2(Monitor *mon, const char *fdname, Error **errp)
2545 int fd;
2546 Error *local_err = NULL;
2548 if (!qemu_isdigit(fdname[0]) && mon) {
2549 fd = monitor_get_fd(mon, fdname, &local_err);
2550 } else {
2551 fd = qemu_parse_fd(fdname);
2552 if (fd == -1) {
2553 error_setg(&local_err, "Invalid file descriptor number '%s'",
2554 fdname);
2557 if (local_err) {
2558 error_propagate(errp, local_err);
2559 assert(fd == -1);
2560 } else {
2561 assert(fd != -1);
2564 return fd;
2567 /* Please update hmp-commands.hx when adding or changing commands */
2568 static mon_cmd_t info_cmds[] = {
2570 .name = "version",
2571 .args_type = "",
2572 .params = "",
2573 .help = "show the version of QEMU",
2574 .mhandler.cmd = hmp_info_version,
2577 .name = "network",
2578 .args_type = "",
2579 .params = "",
2580 .help = "show the network state",
2581 .mhandler.cmd = do_info_network,
2584 .name = "chardev",
2585 .args_type = "",
2586 .params = "",
2587 .help = "show the character devices",
2588 .mhandler.cmd = hmp_info_chardev,
2591 .name = "block",
2592 .args_type = "verbose:-v,device:B?",
2593 .params = "[-v] [device]",
2594 .help = "show info of one block device or all block devices "
2595 "(and details of images with -v option)",
2596 .mhandler.cmd = hmp_info_block,
2599 .name = "blockstats",
2600 .args_type = "",
2601 .params = "",
2602 .help = "show block device statistics",
2603 .mhandler.cmd = hmp_info_blockstats,
2606 .name = "block-jobs",
2607 .args_type = "",
2608 .params = "",
2609 .help = "show progress of ongoing block device operations",
2610 .mhandler.cmd = hmp_info_block_jobs,
2613 .name = "registers",
2614 .args_type = "",
2615 .params = "",
2616 .help = "show the cpu registers",
2617 .mhandler.cmd = do_info_registers,
2620 .name = "cpus",
2621 .args_type = "",
2622 .params = "",
2623 .help = "show infos for each CPU",
2624 .mhandler.cmd = hmp_info_cpus,
2627 .name = "history",
2628 .args_type = "",
2629 .params = "",
2630 .help = "show the command line history",
2631 .mhandler.cmd = do_info_history,
2633 #if defined(TARGET_I386) || defined(TARGET_PPC) || defined(TARGET_MIPS) || \
2634 defined(TARGET_LM32) || (defined(TARGET_SPARC) && !defined(TARGET_SPARC64))
2636 .name = "irq",
2637 .args_type = "",
2638 .params = "",
2639 .help = "show the interrupts statistics (if available)",
2640 #ifdef TARGET_SPARC
2641 .mhandler.cmd = sun4m_irq_info,
2642 #elif defined(TARGET_LM32)
2643 .mhandler.cmd = lm32_irq_info,
2644 #else
2645 .mhandler.cmd = irq_info,
2646 #endif
2649 .name = "pic",
2650 .args_type = "",
2651 .params = "",
2652 .help = "show i8259 (PIC) state",
2653 #ifdef TARGET_SPARC
2654 .mhandler.cmd = sun4m_pic_info,
2655 #elif defined(TARGET_LM32)
2656 .mhandler.cmd = lm32_do_pic_info,
2657 #else
2658 .mhandler.cmd = pic_info,
2659 #endif
2661 #endif
2663 .name = "pci",
2664 .args_type = "",
2665 .params = "",
2666 .help = "show PCI info",
2667 .mhandler.cmd = hmp_info_pci,
2669 #if defined(TARGET_I386) || defined(TARGET_SH4) || defined(TARGET_SPARC) || \
2670 defined(TARGET_PPC) || defined(TARGET_XTENSA)
2672 .name = "tlb",
2673 .args_type = "",
2674 .params = "",
2675 .help = "show virtual to physical memory mappings",
2676 .mhandler.cmd = tlb_info,
2678 #endif
2679 #if defined(TARGET_I386)
2681 .name = "mem",
2682 .args_type = "",
2683 .params = "",
2684 .help = "show the active virtual memory mappings",
2685 .mhandler.cmd = mem_info,
2687 #endif
2689 .name = "mtree",
2690 .args_type = "",
2691 .params = "",
2692 .help = "show memory tree",
2693 .mhandler.cmd = do_info_mtree,
2696 .name = "jit",
2697 .args_type = "",
2698 .params = "",
2699 .help = "show dynamic compiler info",
2700 .mhandler.cmd = do_info_jit,
2703 .name = "kvm",
2704 .args_type = "",
2705 .params = "",
2706 .help = "show KVM information",
2707 .mhandler.cmd = hmp_info_kvm,
2710 .name = "numa",
2711 .args_type = "",
2712 .params = "",
2713 .help = "show NUMA information",
2714 .mhandler.cmd = do_info_numa,
2717 .name = "usb",
2718 .args_type = "",
2719 .params = "",
2720 .help = "show guest USB devices",
2721 .mhandler.cmd = usb_info,
2724 .name = "usbhost",
2725 .args_type = "",
2726 .params = "",
2727 .help = "show host USB devices",
2728 .mhandler.cmd = usb_host_info,
2731 .name = "profile",
2732 .args_type = "",
2733 .params = "",
2734 .help = "show profiling information",
2735 .mhandler.cmd = do_info_profile,
2738 .name = "capture",
2739 .args_type = "",
2740 .params = "",
2741 .help = "show capture information",
2742 .mhandler.cmd = do_info_capture,
2745 .name = "snapshots",
2746 .args_type = "",
2747 .params = "",
2748 .help = "show the currently saved VM snapshots",
2749 .mhandler.cmd = do_info_snapshots,
2752 .name = "status",
2753 .args_type = "",
2754 .params = "",
2755 .help = "show the current VM status (running|paused)",
2756 .mhandler.cmd = hmp_info_status,
2759 .name = "pcmcia",
2760 .args_type = "",
2761 .params = "",
2762 .help = "show guest PCMCIA status",
2763 .mhandler.cmd = pcmcia_info,
2766 .name = "mice",
2767 .args_type = "",
2768 .params = "",
2769 .help = "show which guest mouse is receiving events",
2770 .mhandler.cmd = hmp_info_mice,
2773 .name = "vnc",
2774 .args_type = "",
2775 .params = "",
2776 .help = "show the vnc server status",
2777 .mhandler.cmd = hmp_info_vnc,
2779 #if defined(CONFIG_SPICE)
2781 .name = "spice",
2782 .args_type = "",
2783 .params = "",
2784 .help = "show the spice server status",
2785 .mhandler.cmd = hmp_info_spice,
2787 #endif
2789 .name = "name",
2790 .args_type = "",
2791 .params = "",
2792 .help = "show the current VM name",
2793 .mhandler.cmd = hmp_info_name,
2796 .name = "uuid",
2797 .args_type = "",
2798 .params = "",
2799 .help = "show the current VM UUID",
2800 .mhandler.cmd = hmp_info_uuid,
2803 .name = "cpustats",
2804 .args_type = "",
2805 .params = "",
2806 .help = "show CPU statistics",
2807 .mhandler.cmd = do_info_cpu_stats,
2809 #if defined(CONFIG_SLIRP)
2811 .name = "usernet",
2812 .args_type = "",
2813 .params = "",
2814 .help = "show user network stack connection states",
2815 .mhandler.cmd = do_info_usernet,
2817 #endif
2819 .name = "migrate",
2820 .args_type = "",
2821 .params = "",
2822 .help = "show migration status",
2823 .mhandler.cmd = hmp_info_migrate,
2826 .name = "migrate_capabilities",
2827 .args_type = "",
2828 .params = "",
2829 .help = "show current migration capabilities",
2830 .mhandler.cmd = hmp_info_migrate_capabilities,
2833 .name = "migrate_cache_size",
2834 .args_type = "",
2835 .params = "",
2836 .help = "show current migration xbzrle cache size",
2837 .mhandler.cmd = hmp_info_migrate_cache_size,
2840 .name = "balloon",
2841 .args_type = "",
2842 .params = "",
2843 .help = "show balloon information",
2844 .mhandler.cmd = hmp_info_balloon,
2847 .name = "qtree",
2848 .args_type = "",
2849 .params = "",
2850 .help = "show device tree",
2851 .mhandler.cmd = do_info_qtree,
2854 .name = "qdm",
2855 .args_type = "",
2856 .params = "",
2857 .help = "show qdev device model list",
2858 .mhandler.cmd = do_info_qdm,
2861 .name = "roms",
2862 .args_type = "",
2863 .params = "",
2864 .help = "show roms",
2865 .mhandler.cmd = do_info_roms,
2868 .name = "trace-events",
2869 .args_type = "",
2870 .params = "",
2871 .help = "show available trace-events & their state",
2872 .mhandler.cmd = do_trace_print_events,
2875 .name = "tpm",
2876 .args_type = "",
2877 .params = "",
2878 .help = "show the TPM device",
2879 .mhandler.cmd = hmp_info_tpm,
2882 .name = "memdev",
2883 .args_type = "",
2884 .params = "",
2885 .help = "show the memory device",
2886 .mhandler.cmd = hmp_info_memdev,
2889 .name = NULL,
2893 /* mon_cmds and info_cmds would be sorted at runtime */
2894 static mon_cmd_t mon_cmds[] = {
2895 #include "hmp-commands.h"
2896 { NULL, NULL, },
2899 static const mon_cmd_t qmp_cmds[] = {
2900 #include "qmp-commands-old.h"
2901 { /* NULL */ },
2904 /*******************************************************************/
2906 static const char *pch;
2907 static sigjmp_buf expr_env;
2909 #define MD_TLONG 0
2910 #define MD_I32 1
2912 typedef struct MonitorDef {
2913 const char *name;
2914 int offset;
2915 target_long (*get_value)(const struct MonitorDef *md, int val);
2916 int type;
2917 } MonitorDef;
2919 #if defined(TARGET_I386)
2920 static target_long monitor_get_pc (const struct MonitorDef *md, int val)
2922 CPUArchState *env = mon_get_cpu();
2923 return env->eip + env->segs[R_CS].base;
2925 #endif
2927 #if defined(TARGET_PPC)
2928 static target_long monitor_get_ccr (const struct MonitorDef *md, int val)
2930 CPUArchState *env = mon_get_cpu();
2931 unsigned int u;
2932 int i;
2934 u = 0;
2935 for (i = 0; i < 8; i++)
2936 u |= env->crf[i] << (32 - (4 * i));
2938 return u;
2941 static target_long monitor_get_msr (const struct MonitorDef *md, int val)
2943 CPUArchState *env = mon_get_cpu();
2944 return env->msr;
2947 static target_long monitor_get_xer (const struct MonitorDef *md, int val)
2949 CPUArchState *env = mon_get_cpu();
2950 return env->xer;
2953 static target_long monitor_get_decr (const struct MonitorDef *md, int val)
2955 CPUArchState *env = mon_get_cpu();
2956 return cpu_ppc_load_decr(env);
2959 static target_long monitor_get_tbu (const struct MonitorDef *md, int val)
2961 CPUArchState *env = mon_get_cpu();
2962 return cpu_ppc_load_tbu(env);
2965 static target_long monitor_get_tbl (const struct MonitorDef *md, int val)
2967 CPUArchState *env = mon_get_cpu();
2968 return cpu_ppc_load_tbl(env);
2970 #endif
2972 #if defined(TARGET_SPARC)
2973 #ifndef TARGET_SPARC64
2974 static target_long monitor_get_psr (const struct MonitorDef *md, int val)
2976 CPUArchState *env = mon_get_cpu();
2978 return cpu_get_psr(env);
2980 #endif
2982 static target_long monitor_get_reg(const struct MonitorDef *md, int val)
2984 CPUArchState *env = mon_get_cpu();
2985 return env->regwptr[val];
2987 #endif
2989 static const MonitorDef monitor_defs[] = {
2990 #ifdef TARGET_I386
2992 #define SEG(name, seg) \
2993 { name, offsetof(CPUX86State, segs[seg].selector), NULL, MD_I32 },\
2994 { name ".base", offsetof(CPUX86State, segs[seg].base) },\
2995 { name ".limit", offsetof(CPUX86State, segs[seg].limit), NULL, MD_I32 },
2997 { "eax", offsetof(CPUX86State, regs[0]) },
2998 { "ecx", offsetof(CPUX86State, regs[1]) },
2999 { "edx", offsetof(CPUX86State, regs[2]) },
3000 { "ebx", offsetof(CPUX86State, regs[3]) },
3001 { "esp|sp", offsetof(CPUX86State, regs[4]) },
3002 { "ebp|fp", offsetof(CPUX86State, regs[5]) },
3003 { "esi", offsetof(CPUX86State, regs[6]) },
3004 { "edi", offsetof(CPUX86State, regs[7]) },
3005 #ifdef TARGET_X86_64
3006 { "r8", offsetof(CPUX86State, regs[8]) },
3007 { "r9", offsetof(CPUX86State, regs[9]) },
3008 { "r10", offsetof(CPUX86State, regs[10]) },
3009 { "r11", offsetof(CPUX86State, regs[11]) },
3010 { "r12", offsetof(CPUX86State, regs[12]) },
3011 { "r13", offsetof(CPUX86State, regs[13]) },
3012 { "r14", offsetof(CPUX86State, regs[14]) },
3013 { "r15", offsetof(CPUX86State, regs[15]) },
3014 #endif
3015 { "eflags", offsetof(CPUX86State, eflags) },
3016 { "eip", offsetof(CPUX86State, eip) },
3017 SEG("cs", R_CS)
3018 SEG("ds", R_DS)
3019 SEG("es", R_ES)
3020 SEG("ss", R_SS)
3021 SEG("fs", R_FS)
3022 SEG("gs", R_GS)
3023 { "pc", 0, monitor_get_pc, },
3024 #elif defined(TARGET_PPC)
3025 /* General purpose registers */
3026 { "r0", offsetof(CPUPPCState, gpr[0]) },
3027 { "r1", offsetof(CPUPPCState, gpr[1]) },
3028 { "r2", offsetof(CPUPPCState, gpr[2]) },
3029 { "r3", offsetof(CPUPPCState, gpr[3]) },
3030 { "r4", offsetof(CPUPPCState, gpr[4]) },
3031 { "r5", offsetof(CPUPPCState, gpr[5]) },
3032 { "r6", offsetof(CPUPPCState, gpr[6]) },
3033 { "r7", offsetof(CPUPPCState, gpr[7]) },
3034 { "r8", offsetof(CPUPPCState, gpr[8]) },
3035 { "r9", offsetof(CPUPPCState, gpr[9]) },
3036 { "r10", offsetof(CPUPPCState, gpr[10]) },
3037 { "r11", offsetof(CPUPPCState, gpr[11]) },
3038 { "r12", offsetof(CPUPPCState, gpr[12]) },
3039 { "r13", offsetof(CPUPPCState, gpr[13]) },
3040 { "r14", offsetof(CPUPPCState, gpr[14]) },
3041 { "r15", offsetof(CPUPPCState, gpr[15]) },
3042 { "r16", offsetof(CPUPPCState, gpr[16]) },
3043 { "r17", offsetof(CPUPPCState, gpr[17]) },
3044 { "r18", offsetof(CPUPPCState, gpr[18]) },
3045 { "r19", offsetof(CPUPPCState, gpr[19]) },
3046 { "r20", offsetof(CPUPPCState, gpr[20]) },
3047 { "r21", offsetof(CPUPPCState, gpr[21]) },
3048 { "r22", offsetof(CPUPPCState, gpr[22]) },
3049 { "r23", offsetof(CPUPPCState, gpr[23]) },
3050 { "r24", offsetof(CPUPPCState, gpr[24]) },
3051 { "r25", offsetof(CPUPPCState, gpr[25]) },
3052 { "r26", offsetof(CPUPPCState, gpr[26]) },
3053 { "r27", offsetof(CPUPPCState, gpr[27]) },
3054 { "r28", offsetof(CPUPPCState, gpr[28]) },
3055 { "r29", offsetof(CPUPPCState, gpr[29]) },
3056 { "r30", offsetof(CPUPPCState, gpr[30]) },
3057 { "r31", offsetof(CPUPPCState, gpr[31]) },
3058 /* Floating point registers */
3059 { "f0", offsetof(CPUPPCState, fpr[0]) },
3060 { "f1", offsetof(CPUPPCState, fpr[1]) },
3061 { "f2", offsetof(CPUPPCState, fpr[2]) },
3062 { "f3", offsetof(CPUPPCState, fpr[3]) },
3063 { "f4", offsetof(CPUPPCState, fpr[4]) },
3064 { "f5", offsetof(CPUPPCState, fpr[5]) },
3065 { "f6", offsetof(CPUPPCState, fpr[6]) },
3066 { "f7", offsetof(CPUPPCState, fpr[7]) },
3067 { "f8", offsetof(CPUPPCState, fpr[8]) },
3068 { "f9", offsetof(CPUPPCState, fpr[9]) },
3069 { "f10", offsetof(CPUPPCState, fpr[10]) },
3070 { "f11", offsetof(CPUPPCState, fpr[11]) },
3071 { "f12", offsetof(CPUPPCState, fpr[12]) },
3072 { "f13", offsetof(CPUPPCState, fpr[13]) },
3073 { "f14", offsetof(CPUPPCState, fpr[14]) },
3074 { "f15", offsetof(CPUPPCState, fpr[15]) },
3075 { "f16", offsetof(CPUPPCState, fpr[16]) },
3076 { "f17", offsetof(CPUPPCState, fpr[17]) },
3077 { "f18", offsetof(CPUPPCState, fpr[18]) },
3078 { "f19", offsetof(CPUPPCState, fpr[19]) },
3079 { "f20", offsetof(CPUPPCState, fpr[20]) },
3080 { "f21", offsetof(CPUPPCState, fpr[21]) },
3081 { "f22", offsetof(CPUPPCState, fpr[22]) },
3082 { "f23", offsetof(CPUPPCState, fpr[23]) },
3083 { "f24", offsetof(CPUPPCState, fpr[24]) },
3084 { "f25", offsetof(CPUPPCState, fpr[25]) },
3085 { "f26", offsetof(CPUPPCState, fpr[26]) },
3086 { "f27", offsetof(CPUPPCState, fpr[27]) },
3087 { "f28", offsetof(CPUPPCState, fpr[28]) },
3088 { "f29", offsetof(CPUPPCState, fpr[29]) },
3089 { "f30", offsetof(CPUPPCState, fpr[30]) },
3090 { "f31", offsetof(CPUPPCState, fpr[31]) },
3091 { "fpscr", offsetof(CPUPPCState, fpscr) },
3092 /* Next instruction pointer */
3093 { "nip|pc", offsetof(CPUPPCState, nip) },
3094 { "lr", offsetof(CPUPPCState, lr) },
3095 { "ctr", offsetof(CPUPPCState, ctr) },
3096 { "decr", 0, &monitor_get_decr, },
3097 { "ccr", 0, &monitor_get_ccr, },
3098 /* Machine state register */
3099 { "msr", 0, &monitor_get_msr, },
3100 { "xer", 0, &monitor_get_xer, },
3101 { "tbu", 0, &monitor_get_tbu, },
3102 { "tbl", 0, &monitor_get_tbl, },
3103 /* Segment registers */
3104 { "sdr1", offsetof(CPUPPCState, spr[SPR_SDR1]) },
3105 { "sr0", offsetof(CPUPPCState, sr[0]) },
3106 { "sr1", offsetof(CPUPPCState, sr[1]) },
3107 { "sr2", offsetof(CPUPPCState, sr[2]) },
3108 { "sr3", offsetof(CPUPPCState, sr[3]) },
3109 { "sr4", offsetof(CPUPPCState, sr[4]) },
3110 { "sr5", offsetof(CPUPPCState, sr[5]) },
3111 { "sr6", offsetof(CPUPPCState, sr[6]) },
3112 { "sr7", offsetof(CPUPPCState, sr[7]) },
3113 { "sr8", offsetof(CPUPPCState, sr[8]) },
3114 { "sr9", offsetof(CPUPPCState, sr[9]) },
3115 { "sr10", offsetof(CPUPPCState, sr[10]) },
3116 { "sr11", offsetof(CPUPPCState, sr[11]) },
3117 { "sr12", offsetof(CPUPPCState, sr[12]) },
3118 { "sr13", offsetof(CPUPPCState, sr[13]) },
3119 { "sr14", offsetof(CPUPPCState, sr[14]) },
3120 { "sr15", offsetof(CPUPPCState, sr[15]) },
3121 /* Too lazy to put BATs... */
3122 { "pvr", offsetof(CPUPPCState, spr[SPR_PVR]) },
3124 { "srr0", offsetof(CPUPPCState, spr[SPR_SRR0]) },
3125 { "srr1", offsetof(CPUPPCState, spr[SPR_SRR1]) },
3126 { "dar", offsetof(CPUPPCState, spr[SPR_DAR]) },
3127 { "dsisr", offsetof(CPUPPCState, spr[SPR_DSISR]) },
3128 { "cfar", offsetof(CPUPPCState, spr[SPR_CFAR]) },
3129 { "sprg0", offsetof(CPUPPCState, spr[SPR_SPRG0]) },
3130 { "sprg1", offsetof(CPUPPCState, spr[SPR_SPRG1]) },
3131 { "sprg2", offsetof(CPUPPCState, spr[SPR_SPRG2]) },
3132 { "sprg3", offsetof(CPUPPCState, spr[SPR_SPRG3]) },
3133 { "sprg4", offsetof(CPUPPCState, spr[SPR_SPRG4]) },
3134 { "sprg5", offsetof(CPUPPCState, spr[SPR_SPRG5]) },
3135 { "sprg6", offsetof(CPUPPCState, spr[SPR_SPRG6]) },
3136 { "sprg7", offsetof(CPUPPCState, spr[SPR_SPRG7]) },
3137 { "pid", offsetof(CPUPPCState, spr[SPR_BOOKE_PID]) },
3138 { "csrr0", offsetof(CPUPPCState, spr[SPR_BOOKE_CSRR0]) },
3139 { "csrr1", offsetof(CPUPPCState, spr[SPR_BOOKE_CSRR1]) },
3140 { "esr", offsetof(CPUPPCState, spr[SPR_BOOKE_ESR]) },
3141 { "dear", offsetof(CPUPPCState, spr[SPR_BOOKE_DEAR]) },
3142 { "mcsr", offsetof(CPUPPCState, spr[SPR_BOOKE_MCSR]) },
3143 { "tsr", offsetof(CPUPPCState, spr[SPR_BOOKE_TSR]) },
3144 { "tcr", offsetof(CPUPPCState, spr[SPR_BOOKE_TCR]) },
3145 { "vrsave", offsetof(CPUPPCState, spr[SPR_VRSAVE]) },
3146 { "pir", offsetof(CPUPPCState, spr[SPR_BOOKE_PIR]) },
3147 { "mcsrr0", offsetof(CPUPPCState, spr[SPR_BOOKE_MCSRR0]) },
3148 { "mcsrr1", offsetof(CPUPPCState, spr[SPR_BOOKE_MCSRR1]) },
3149 { "decar", offsetof(CPUPPCState, spr[SPR_BOOKE_DECAR]) },
3150 { "ivpr", offsetof(CPUPPCState, spr[SPR_BOOKE_IVPR]) },
3151 { "epcr", offsetof(CPUPPCState, spr[SPR_BOOKE_EPCR]) },
3152 { "sprg8", offsetof(CPUPPCState, spr[SPR_BOOKE_SPRG8]) },
3153 { "ivor0", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR0]) },
3154 { "ivor1", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR1]) },
3155 { "ivor2", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR2]) },
3156 { "ivor3", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR3]) },
3157 { "ivor4", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR4]) },
3158 { "ivor5", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR5]) },
3159 { "ivor6", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR6]) },
3160 { "ivor7", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR7]) },
3161 { "ivor8", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR8]) },
3162 { "ivor9", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR9]) },
3163 { "ivor10", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR10]) },
3164 { "ivor11", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR11]) },
3165 { "ivor12", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR12]) },
3166 { "ivor13", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR13]) },
3167 { "ivor14", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR14]) },
3168 { "ivor15", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR15]) },
3169 { "ivor32", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR32]) },
3170 { "ivor33", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR33]) },
3171 { "ivor34", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR34]) },
3172 { "ivor35", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR35]) },
3173 { "ivor36", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR36]) },
3174 { "ivor37", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR37]) },
3175 { "mas0", offsetof(CPUPPCState, spr[SPR_BOOKE_MAS0]) },
3176 { "mas1", offsetof(CPUPPCState, spr[SPR_BOOKE_MAS1]) },
3177 { "mas2", offsetof(CPUPPCState, spr[SPR_BOOKE_MAS2]) },
3178 { "mas3", offsetof(CPUPPCState, spr[SPR_BOOKE_MAS3]) },
3179 { "mas4", offsetof(CPUPPCState, spr[SPR_BOOKE_MAS4]) },
3180 { "mas6", offsetof(CPUPPCState, spr[SPR_BOOKE_MAS6]) },
3181 { "mas7", offsetof(CPUPPCState, spr[SPR_BOOKE_MAS7]) },
3182 { "mmucfg", offsetof(CPUPPCState, spr[SPR_MMUCFG]) },
3183 { "tlb0cfg", offsetof(CPUPPCState, spr[SPR_BOOKE_TLB0CFG]) },
3184 { "tlb1cfg", offsetof(CPUPPCState, spr[SPR_BOOKE_TLB1CFG]) },
3185 { "epr", offsetof(CPUPPCState, spr[SPR_BOOKE_EPR]) },
3186 { "eplc", offsetof(CPUPPCState, spr[SPR_BOOKE_EPLC]) },
3187 { "epsc", offsetof(CPUPPCState, spr[SPR_BOOKE_EPSC]) },
3188 { "svr", offsetof(CPUPPCState, spr[SPR_E500_SVR]) },
3189 { "mcar", offsetof(CPUPPCState, spr[SPR_Exxx_MCAR]) },
3190 { "pid1", offsetof(CPUPPCState, spr[SPR_BOOKE_PID1]) },
3191 { "pid2", offsetof(CPUPPCState, spr[SPR_BOOKE_PID2]) },
3192 { "hid0", offsetof(CPUPPCState, spr[SPR_HID0]) },
3194 #elif defined(TARGET_SPARC)
3195 { "g0", offsetof(CPUSPARCState, gregs[0]) },
3196 { "g1", offsetof(CPUSPARCState, gregs[1]) },
3197 { "g2", offsetof(CPUSPARCState, gregs[2]) },
3198 { "g3", offsetof(CPUSPARCState, gregs[3]) },
3199 { "g4", offsetof(CPUSPARCState, gregs[4]) },
3200 { "g5", offsetof(CPUSPARCState, gregs[5]) },
3201 { "g6", offsetof(CPUSPARCState, gregs[6]) },
3202 { "g7", offsetof(CPUSPARCState, gregs[7]) },
3203 { "o0", 0, monitor_get_reg },
3204 { "o1", 1, monitor_get_reg },
3205 { "o2", 2, monitor_get_reg },
3206 { "o3", 3, monitor_get_reg },
3207 { "o4", 4, monitor_get_reg },
3208 { "o5", 5, monitor_get_reg },
3209 { "o6", 6, monitor_get_reg },
3210 { "o7", 7, monitor_get_reg },
3211 { "l0", 8, monitor_get_reg },
3212 { "l1", 9, monitor_get_reg },
3213 { "l2", 10, monitor_get_reg },
3214 { "l3", 11, monitor_get_reg },
3215 { "l4", 12, monitor_get_reg },
3216 { "l5", 13, monitor_get_reg },
3217 { "l6", 14, monitor_get_reg },
3218 { "l7", 15, monitor_get_reg },
3219 { "i0", 16, monitor_get_reg },
3220 { "i1", 17, monitor_get_reg },
3221 { "i2", 18, monitor_get_reg },
3222 { "i3", 19, monitor_get_reg },
3223 { "i4", 20, monitor_get_reg },
3224 { "i5", 21, monitor_get_reg },
3225 { "i6", 22, monitor_get_reg },
3226 { "i7", 23, monitor_get_reg },
3227 { "pc", offsetof(CPUSPARCState, pc) },
3228 { "npc", offsetof(CPUSPARCState, npc) },
3229 { "y", offsetof(CPUSPARCState, y) },
3230 #ifndef TARGET_SPARC64
3231 { "psr", 0, &monitor_get_psr, },
3232 { "wim", offsetof(CPUSPARCState, wim) },
3233 #endif
3234 { "tbr", offsetof(CPUSPARCState, tbr) },
3235 { "fsr", offsetof(CPUSPARCState, fsr) },
3236 { "f0", offsetof(CPUSPARCState, fpr[0].l.upper) },
3237 { "f1", offsetof(CPUSPARCState, fpr[0].l.lower) },
3238 { "f2", offsetof(CPUSPARCState, fpr[1].l.upper) },
3239 { "f3", offsetof(CPUSPARCState, fpr[1].l.lower) },
3240 { "f4", offsetof(CPUSPARCState, fpr[2].l.upper) },
3241 { "f5", offsetof(CPUSPARCState, fpr[2].l.lower) },
3242 { "f6", offsetof(CPUSPARCState, fpr[3].l.upper) },
3243 { "f7", offsetof(CPUSPARCState, fpr[3].l.lower) },
3244 { "f8", offsetof(CPUSPARCState, fpr[4].l.upper) },
3245 { "f9", offsetof(CPUSPARCState, fpr[4].l.lower) },
3246 { "f10", offsetof(CPUSPARCState, fpr[5].l.upper) },
3247 { "f11", offsetof(CPUSPARCState, fpr[5].l.lower) },
3248 { "f12", offsetof(CPUSPARCState, fpr[6].l.upper) },
3249 { "f13", offsetof(CPUSPARCState, fpr[6].l.lower) },
3250 { "f14", offsetof(CPUSPARCState, fpr[7].l.upper) },
3251 { "f15", offsetof(CPUSPARCState, fpr[7].l.lower) },
3252 { "f16", offsetof(CPUSPARCState, fpr[8].l.upper) },
3253 { "f17", offsetof(CPUSPARCState, fpr[8].l.lower) },
3254 { "f18", offsetof(CPUSPARCState, fpr[9].l.upper) },
3255 { "f19", offsetof(CPUSPARCState, fpr[9].l.lower) },
3256 { "f20", offsetof(CPUSPARCState, fpr[10].l.upper) },
3257 { "f21", offsetof(CPUSPARCState, fpr[10].l.lower) },
3258 { "f22", offsetof(CPUSPARCState, fpr[11].l.upper) },
3259 { "f23", offsetof(CPUSPARCState, fpr[11].l.lower) },
3260 { "f24", offsetof(CPUSPARCState, fpr[12].l.upper) },
3261 { "f25", offsetof(CPUSPARCState, fpr[12].l.lower) },
3262 { "f26", offsetof(CPUSPARCState, fpr[13].l.upper) },
3263 { "f27", offsetof(CPUSPARCState, fpr[13].l.lower) },
3264 { "f28", offsetof(CPUSPARCState, fpr[14].l.upper) },
3265 { "f29", offsetof(CPUSPARCState, fpr[14].l.lower) },
3266 { "f30", offsetof(CPUSPARCState, fpr[15].l.upper) },
3267 { "f31", offsetof(CPUSPARCState, fpr[15].l.lower) },
3268 #ifdef TARGET_SPARC64
3269 { "f32", offsetof(CPUSPARCState, fpr[16]) },
3270 { "f34", offsetof(CPUSPARCState, fpr[17]) },
3271 { "f36", offsetof(CPUSPARCState, fpr[18]) },
3272 { "f38", offsetof(CPUSPARCState, fpr[19]) },
3273 { "f40", offsetof(CPUSPARCState, fpr[20]) },
3274 { "f42", offsetof(CPUSPARCState, fpr[21]) },
3275 { "f44", offsetof(CPUSPARCState, fpr[22]) },
3276 { "f46", offsetof(CPUSPARCState, fpr[23]) },
3277 { "f48", offsetof(CPUSPARCState, fpr[24]) },
3278 { "f50", offsetof(CPUSPARCState, fpr[25]) },
3279 { "f52", offsetof(CPUSPARCState, fpr[26]) },
3280 { "f54", offsetof(CPUSPARCState, fpr[27]) },
3281 { "f56", offsetof(CPUSPARCState, fpr[28]) },
3282 { "f58", offsetof(CPUSPARCState, fpr[29]) },
3283 { "f60", offsetof(CPUSPARCState, fpr[30]) },
3284 { "f62", offsetof(CPUSPARCState, fpr[31]) },
3285 { "asi", offsetof(CPUSPARCState, asi) },
3286 { "pstate", offsetof(CPUSPARCState, pstate) },
3287 { "cansave", offsetof(CPUSPARCState, cansave) },
3288 { "canrestore", offsetof(CPUSPARCState, canrestore) },
3289 { "otherwin", offsetof(CPUSPARCState, otherwin) },
3290 { "wstate", offsetof(CPUSPARCState, wstate) },
3291 { "cleanwin", offsetof(CPUSPARCState, cleanwin) },
3292 { "fprs", offsetof(CPUSPARCState, fprs) },
3293 #endif
3294 #endif
3295 { NULL },
3298 static void GCC_FMT_ATTR(2, 3) QEMU_NORETURN
3299 expr_error(Monitor *mon, const char *fmt, ...)
3301 va_list ap;
3302 va_start(ap, fmt);
3303 monitor_vprintf(mon, fmt, ap);
3304 monitor_printf(mon, "\n");
3305 va_end(ap);
3306 siglongjmp(expr_env, 1);
3309 /* return 0 if OK, -1 if not found */
3310 static int get_monitor_def(target_long *pval, const char *name)
3312 const MonitorDef *md;
3313 void *ptr;
3315 for(md = monitor_defs; md->name != NULL; md++) {
3316 if (compare_cmd(name, md->name)) {
3317 if (md->get_value) {
3318 *pval = md->get_value(md, md->offset);
3319 } else {
3320 CPUArchState *env = mon_get_cpu();
3321 ptr = (uint8_t *)env + md->offset;
3322 switch(md->type) {
3323 case MD_I32:
3324 *pval = *(int32_t *)ptr;
3325 break;
3326 case MD_TLONG:
3327 *pval = *(target_long *)ptr;
3328 break;
3329 default:
3330 *pval = 0;
3331 break;
3334 return 0;
3337 return -1;
3340 static void next(void)
3342 if (*pch != '\0') {
3343 pch++;
3344 while (qemu_isspace(*pch))
3345 pch++;
3349 static int64_t expr_sum(Monitor *mon);
3351 static int64_t expr_unary(Monitor *mon)
3353 int64_t n;
3354 char *p;
3355 int ret;
3357 switch(*pch) {
3358 case '+':
3359 next();
3360 n = expr_unary(mon);
3361 break;
3362 case '-':
3363 next();
3364 n = -expr_unary(mon);
3365 break;
3366 case '~':
3367 next();
3368 n = ~expr_unary(mon);
3369 break;
3370 case '(':
3371 next();
3372 n = expr_sum(mon);
3373 if (*pch != ')') {
3374 expr_error(mon, "')' expected");
3376 next();
3377 break;
3378 case '\'':
3379 pch++;
3380 if (*pch == '\0')
3381 expr_error(mon, "character constant expected");
3382 n = *pch;
3383 pch++;
3384 if (*pch != '\'')
3385 expr_error(mon, "missing terminating \' character");
3386 next();
3387 break;
3388 case '$':
3390 char buf[128], *q;
3391 target_long reg=0;
3393 pch++;
3394 q = buf;
3395 while ((*pch >= 'a' && *pch <= 'z') ||
3396 (*pch >= 'A' && *pch <= 'Z') ||
3397 (*pch >= '0' && *pch <= '9') ||
3398 *pch == '_' || *pch == '.') {
3399 if ((q - buf) < sizeof(buf) - 1)
3400 *q++ = *pch;
3401 pch++;
3403 while (qemu_isspace(*pch))
3404 pch++;
3405 *q = 0;
3406 ret = get_monitor_def(&reg, buf);
3407 if (ret < 0)
3408 expr_error(mon, "unknown register");
3409 n = reg;
3411 break;
3412 case '\0':
3413 expr_error(mon, "unexpected end of expression");
3414 n = 0;
3415 break;
3416 default:
3417 errno = 0;
3418 n = strtoull(pch, &p, 0);
3419 if (errno == ERANGE) {
3420 expr_error(mon, "number too large");
3422 if (pch == p) {
3423 expr_error(mon, "invalid char '%c' in expression", *p);
3425 pch = p;
3426 while (qemu_isspace(*pch))
3427 pch++;
3428 break;
3430 return n;
3434 static int64_t expr_prod(Monitor *mon)
3436 int64_t val, val2;
3437 int op;
3439 val = expr_unary(mon);
3440 for(;;) {
3441 op = *pch;
3442 if (op != '*' && op != '/' && op != '%')
3443 break;
3444 next();
3445 val2 = expr_unary(mon);
3446 switch(op) {
3447 default:
3448 case '*':
3449 val *= val2;
3450 break;
3451 case '/':
3452 case '%':
3453 if (val2 == 0)
3454 expr_error(mon, "division by zero");
3455 if (op == '/')
3456 val /= val2;
3457 else
3458 val %= val2;
3459 break;
3462 return val;
3465 static int64_t expr_logic(Monitor *mon)
3467 int64_t val, val2;
3468 int op;
3470 val = expr_prod(mon);
3471 for(;;) {
3472 op = *pch;
3473 if (op != '&' && op != '|' && op != '^')
3474 break;
3475 next();
3476 val2 = expr_prod(mon);
3477 switch(op) {
3478 default:
3479 case '&':
3480 val &= val2;
3481 break;
3482 case '|':
3483 val |= val2;
3484 break;
3485 case '^':
3486 val ^= val2;
3487 break;
3490 return val;
3493 static int64_t expr_sum(Monitor *mon)
3495 int64_t val, val2;
3496 int op;
3498 val = expr_logic(mon);
3499 for(;;) {
3500 op = *pch;
3501 if (op != '+' && op != '-')
3502 break;
3503 next();
3504 val2 = expr_logic(mon);
3505 if (op == '+')
3506 val += val2;
3507 else
3508 val -= val2;
3510 return val;
3513 static int get_expr(Monitor *mon, int64_t *pval, const char **pp)
3515 pch = *pp;
3516 if (sigsetjmp(expr_env, 0)) {
3517 *pp = pch;
3518 return -1;
3520 while (qemu_isspace(*pch))
3521 pch++;
3522 *pval = expr_sum(mon);
3523 *pp = pch;
3524 return 0;
3527 static int get_double(Monitor *mon, double *pval, const char **pp)
3529 const char *p = *pp;
3530 char *tailp;
3531 double d;
3533 d = strtod(p, &tailp);
3534 if (tailp == p) {
3535 monitor_printf(mon, "Number expected\n");
3536 return -1;
3538 if (d != d || d - d != 0) {
3539 /* NaN or infinity */
3540 monitor_printf(mon, "Bad number\n");
3541 return -1;
3543 *pval = d;
3544 *pp = tailp;
3545 return 0;
3549 * Store the command-name in cmdname, and return a pointer to
3550 * the remaining of the command string.
3552 static const char *get_command_name(const char *cmdline,
3553 char *cmdname, size_t nlen)
3555 size_t len;
3556 const char *p, *pstart;
3558 p = cmdline;
3559 while (qemu_isspace(*p))
3560 p++;
3561 if (*p == '\0')
3562 return NULL;
3563 pstart = p;
3564 while (*p != '\0' && *p != '/' && !qemu_isspace(*p))
3565 p++;
3566 len = p - pstart;
3567 if (len > nlen - 1)
3568 len = nlen - 1;
3569 memcpy(cmdname, pstart, len);
3570 cmdname[len] = '\0';
3571 return p;
3575 * Read key of 'type' into 'key' and return the current
3576 * 'type' pointer.
3578 static char *key_get_info(const char *type, char **key)
3580 size_t len;
3581 char *p, *str;
3583 if (*type == ',')
3584 type++;
3586 p = strchr(type, ':');
3587 if (!p) {
3588 *key = NULL;
3589 return NULL;
3591 len = p - type;
3593 str = g_malloc(len + 1);
3594 memcpy(str, type, len);
3595 str[len] = '\0';
3597 *key = str;
3598 return ++p;
3601 static int default_fmt_format = 'x';
3602 static int default_fmt_size = 4;
3604 static int is_valid_option(const char *c, const char *typestr)
3606 char option[3];
3608 option[0] = '-';
3609 option[1] = *c;
3610 option[2] = '\0';
3612 typestr = strstr(typestr, option);
3613 return (typestr != NULL);
3616 static const mon_cmd_t *search_dispatch_table(const mon_cmd_t *disp_table,
3617 const char *cmdname)
3619 const mon_cmd_t *cmd;
3621 for (cmd = disp_table; cmd->name != NULL; cmd++) {
3622 if (compare_cmd(cmdname, cmd->name)) {
3623 return cmd;
3627 return NULL;
3630 static const mon_cmd_t *qmp_find_cmd(const char *cmdname)
3632 return search_dispatch_table(qmp_cmds, cmdname);
3636 * Parse @cmdline according to command table @table.
3637 * If @cmdline is blank, return NULL.
3638 * If it can't be parsed, report to @mon, and return NULL.
3639 * Else, insert command arguments into @qdict, and return the command.
3640 * If a sub-command table exists, and if @cmdline contains an additional string
3641 * for a sub-command, this function will try to search the sub-command table.
3642 * If no additional string for a sub-command is present, this function will
3643 * return the command found in @table.
3644 * Do not assume the returned command points into @table! It doesn't
3645 * when the command is a sub-command.
3647 static const mon_cmd_t *monitor_parse_command(Monitor *mon,
3648 const char *cmdline,
3649 int start,
3650 mon_cmd_t *table,
3651 QDict *qdict)
3653 const char *p, *typestr;
3654 int c;
3655 const mon_cmd_t *cmd;
3656 char cmdname[256];
3657 char buf[1024];
3658 char *key;
3660 #ifdef DEBUG
3661 monitor_printf(mon, "command='%s', start='%d'\n", cmdline, start);
3662 #endif
3664 /* extract the command name */
3665 p = get_command_name(cmdline + start, cmdname, sizeof(cmdname));
3666 if (!p)
3667 return NULL;
3669 cmd = search_dispatch_table(table, cmdname);
3670 if (!cmd) {
3671 monitor_printf(mon, "unknown command: '%.*s'\n",
3672 (int)(p - cmdline), cmdline);
3673 return NULL;
3676 /* filter out following useless space */
3677 while (qemu_isspace(*p)) {
3678 p++;
3680 /* search sub command */
3681 if (cmd->sub_table != NULL) {
3682 /* check if user set additional command */
3683 if (*p == '\0') {
3684 return cmd;
3686 return monitor_parse_command(mon, cmdline, p - cmdline,
3687 cmd->sub_table, qdict);
3690 /* parse the parameters */
3691 typestr = cmd->args_type;
3692 for(;;) {
3693 typestr = key_get_info(typestr, &key);
3694 if (!typestr)
3695 break;
3696 c = *typestr;
3697 typestr++;
3698 switch(c) {
3699 case 'F':
3700 case 'B':
3701 case 's':
3703 int ret;
3705 while (qemu_isspace(*p))
3706 p++;
3707 if (*typestr == '?') {
3708 typestr++;
3709 if (*p == '\0') {
3710 /* no optional string: NULL argument */
3711 break;
3714 ret = get_str(buf, sizeof(buf), &p);
3715 if (ret < 0) {
3716 switch(c) {
3717 case 'F':
3718 monitor_printf(mon, "%s: filename expected\n",
3719 cmdname);
3720 break;
3721 case 'B':
3722 monitor_printf(mon, "%s: block device name expected\n",
3723 cmdname);
3724 break;
3725 default:
3726 monitor_printf(mon, "%s: string expected\n", cmdname);
3727 break;
3729 goto fail;
3731 qdict_put(qdict, key, qstring_from_str(buf));
3733 break;
3734 case 'O':
3736 QemuOptsList *opts_list;
3737 QemuOpts *opts;
3739 opts_list = qemu_find_opts(key);
3740 if (!opts_list || opts_list->desc->name) {
3741 goto bad_type;
3743 while (qemu_isspace(*p)) {
3744 p++;
3746 if (!*p)
3747 break;
3748 if (get_str(buf, sizeof(buf), &p) < 0) {
3749 goto fail;
3751 opts = qemu_opts_parse(opts_list, buf, 1);
3752 if (!opts) {
3753 goto fail;
3755 qemu_opts_to_qdict(opts, qdict);
3756 qemu_opts_del(opts);
3758 break;
3759 case '/':
3761 int count, format, size;
3763 while (qemu_isspace(*p))
3764 p++;
3765 if (*p == '/') {
3766 /* format found */
3767 p++;
3768 count = 1;
3769 if (qemu_isdigit(*p)) {
3770 count = 0;
3771 while (qemu_isdigit(*p)) {
3772 count = count * 10 + (*p - '0');
3773 p++;
3776 size = -1;
3777 format = -1;
3778 for(;;) {
3779 switch(*p) {
3780 case 'o':
3781 case 'd':
3782 case 'u':
3783 case 'x':
3784 case 'i':
3785 case 'c':
3786 format = *p++;
3787 break;
3788 case 'b':
3789 size = 1;
3790 p++;
3791 break;
3792 case 'h':
3793 size = 2;
3794 p++;
3795 break;
3796 case 'w':
3797 size = 4;
3798 p++;
3799 break;
3800 case 'g':
3801 case 'L':
3802 size = 8;
3803 p++;
3804 break;
3805 default:
3806 goto next;
3809 next:
3810 if (*p != '\0' && !qemu_isspace(*p)) {
3811 monitor_printf(mon, "invalid char in format: '%c'\n",
3812 *p);
3813 goto fail;
3815 if (format < 0)
3816 format = default_fmt_format;
3817 if (format != 'i') {
3818 /* for 'i', not specifying a size gives -1 as size */
3819 if (size < 0)
3820 size = default_fmt_size;
3821 default_fmt_size = size;
3823 default_fmt_format = format;
3824 } else {
3825 count = 1;
3826 format = default_fmt_format;
3827 if (format != 'i') {
3828 size = default_fmt_size;
3829 } else {
3830 size = -1;
3833 qdict_put(qdict, "count", qint_from_int(count));
3834 qdict_put(qdict, "format", qint_from_int(format));
3835 qdict_put(qdict, "size", qint_from_int(size));
3837 break;
3838 case 'i':
3839 case 'l':
3840 case 'M':
3842 int64_t val;
3844 while (qemu_isspace(*p))
3845 p++;
3846 if (*typestr == '?' || *typestr == '.') {
3847 if (*typestr == '?') {
3848 if (*p == '\0') {
3849 typestr++;
3850 break;
3852 } else {
3853 if (*p == '.') {
3854 p++;
3855 while (qemu_isspace(*p))
3856 p++;
3857 } else {
3858 typestr++;
3859 break;
3862 typestr++;
3864 if (get_expr(mon, &val, &p))
3865 goto fail;
3866 /* Check if 'i' is greater than 32-bit */
3867 if ((c == 'i') && ((val >> 32) & 0xffffffff)) {
3868 monitor_printf(mon, "\'%s\' has failed: ", cmdname);
3869 monitor_printf(mon, "integer is for 32-bit values\n");
3870 goto fail;
3871 } else if (c == 'M') {
3872 if (val < 0) {
3873 monitor_printf(mon, "enter a positive value\n");
3874 goto fail;
3876 val <<= 20;
3878 qdict_put(qdict, key, qint_from_int(val));
3880 break;
3881 case 'o':
3883 int64_t val;
3884 char *end;
3886 while (qemu_isspace(*p)) {
3887 p++;
3889 if (*typestr == '?') {
3890 typestr++;
3891 if (*p == '\0') {
3892 break;
3895 val = strtosz(p, &end);
3896 if (val < 0) {
3897 monitor_printf(mon, "invalid size\n");
3898 goto fail;
3900 qdict_put(qdict, key, qint_from_int(val));
3901 p = end;
3903 break;
3904 case 'T':
3906 double val;
3908 while (qemu_isspace(*p))
3909 p++;
3910 if (*typestr == '?') {
3911 typestr++;
3912 if (*p == '\0') {
3913 break;
3916 if (get_double(mon, &val, &p) < 0) {
3917 goto fail;
3919 if (p[0] && p[1] == 's') {
3920 switch (*p) {
3921 case 'm':
3922 val /= 1e3; p += 2; break;
3923 case 'u':
3924 val /= 1e6; p += 2; break;
3925 case 'n':
3926 val /= 1e9; p += 2; break;
3929 if (*p && !qemu_isspace(*p)) {
3930 monitor_printf(mon, "Unknown unit suffix\n");
3931 goto fail;
3933 qdict_put(qdict, key, qfloat_from_double(val));
3935 break;
3936 case 'b':
3938 const char *beg;
3939 int val;
3941 while (qemu_isspace(*p)) {
3942 p++;
3944 beg = p;
3945 while (qemu_isgraph(*p)) {
3946 p++;
3948 if (p - beg == 2 && !memcmp(beg, "on", p - beg)) {
3949 val = 1;
3950 } else if (p - beg == 3 && !memcmp(beg, "off", p - beg)) {
3951 val = 0;
3952 } else {
3953 monitor_printf(mon, "Expected 'on' or 'off'\n");
3954 goto fail;
3956 qdict_put(qdict, key, qbool_from_int(val));
3958 break;
3959 case '-':
3961 const char *tmp = p;
3962 int skip_key = 0;
3963 /* option */
3965 c = *typestr++;
3966 if (c == '\0')
3967 goto bad_type;
3968 while (qemu_isspace(*p))
3969 p++;
3970 if (*p == '-') {
3971 p++;
3972 if(c != *p) {
3973 if(!is_valid_option(p, typestr)) {
3975 monitor_printf(mon, "%s: unsupported option -%c\n",
3976 cmdname, *p);
3977 goto fail;
3978 } else {
3979 skip_key = 1;
3982 if(skip_key) {
3983 p = tmp;
3984 } else {
3985 /* has option */
3986 p++;
3987 qdict_put(qdict, key, qbool_from_int(1));
3991 break;
3992 case 'S':
3994 /* package all remaining string */
3995 int len;
3997 while (qemu_isspace(*p)) {
3998 p++;
4000 if (*typestr == '?') {
4001 typestr++;
4002 if (*p == '\0') {
4003 /* no remaining string: NULL argument */
4004 break;
4007 len = strlen(p);
4008 if (len <= 0) {
4009 monitor_printf(mon, "%s: string expected\n",
4010 cmdname);
4011 break;
4013 qdict_put(qdict, key, qstring_from_str(p));
4014 p += len;
4016 break;
4017 default:
4018 bad_type:
4019 monitor_printf(mon, "%s: unknown type '%c'\n", cmdname, c);
4020 goto fail;
4022 g_free(key);
4023 key = NULL;
4025 /* check that all arguments were parsed */
4026 while (qemu_isspace(*p))
4027 p++;
4028 if (*p != '\0') {
4029 monitor_printf(mon, "%s: extraneous characters at the end of line\n",
4030 cmdname);
4031 goto fail;
4034 return cmd;
4036 fail:
4037 g_free(key);
4038 return NULL;
4041 void monitor_set_error(Monitor *mon, QError *qerror)
4043 /* report only the first error */
4044 if (!mon->error) {
4045 mon->error = qerror;
4046 } else {
4047 QDECREF(qerror);
4051 static void handler_audit(Monitor *mon, const mon_cmd_t *cmd, int ret)
4053 if (ret && !monitor_has_error(mon)) {
4055 * If it returns failure, it must have passed on error.
4057 * Action: Report an internal error to the client if in QMP.
4059 qerror_report(QERR_UNDEFINED_ERROR);
4063 static void handle_user_command(Monitor *mon, const char *cmdline)
4065 QDict *qdict;
4066 const mon_cmd_t *cmd;
4068 qdict = qdict_new();
4070 cmd = monitor_parse_command(mon, cmdline, 0, mon->cmd_table, qdict);
4071 if (!cmd)
4072 goto out;
4074 if (handler_is_async(cmd)) {
4075 user_async_cmd_handler(mon, cmd, qdict);
4076 } else if (handler_is_qobject(cmd)) {
4077 QObject *data = NULL;
4079 /* XXX: ignores the error code */
4080 cmd->mhandler.cmd_new(mon, qdict, &data);
4081 assert(!monitor_has_error(mon));
4082 if (data) {
4083 cmd->user_print(mon, data);
4084 qobject_decref(data);
4086 } else {
4087 cmd->mhandler.cmd(mon, qdict);
4090 out:
4091 QDECREF(qdict);
4094 static void cmd_completion(Monitor *mon, const char *name, const char *list)
4096 const char *p, *pstart;
4097 char cmd[128];
4098 int len;
4100 p = list;
4101 for(;;) {
4102 pstart = p;
4103 p = strchr(p, '|');
4104 if (!p)
4105 p = pstart + strlen(pstart);
4106 len = p - pstart;
4107 if (len > sizeof(cmd) - 2)
4108 len = sizeof(cmd) - 2;
4109 memcpy(cmd, pstart, len);
4110 cmd[len] = '\0';
4111 if (name[0] == '\0' || !strncmp(name, cmd, strlen(name))) {
4112 readline_add_completion(mon->rs, cmd);
4114 if (*p == '\0')
4115 break;
4116 p++;
4120 static void file_completion(Monitor *mon, const char *input)
4122 DIR *ffs;
4123 struct dirent *d;
4124 char path[1024];
4125 char file[1024], file_prefix[1024];
4126 int input_path_len;
4127 const char *p;
4129 p = strrchr(input, '/');
4130 if (!p) {
4131 input_path_len = 0;
4132 pstrcpy(file_prefix, sizeof(file_prefix), input);
4133 pstrcpy(path, sizeof(path), ".");
4134 } else {
4135 input_path_len = p - input + 1;
4136 memcpy(path, input, input_path_len);
4137 if (input_path_len > sizeof(path) - 1)
4138 input_path_len = sizeof(path) - 1;
4139 path[input_path_len] = '\0';
4140 pstrcpy(file_prefix, sizeof(file_prefix), p + 1);
4142 #ifdef DEBUG_COMPLETION
4143 monitor_printf(mon, "input='%s' path='%s' prefix='%s'\n",
4144 input, path, file_prefix);
4145 #endif
4146 ffs = opendir(path);
4147 if (!ffs)
4148 return;
4149 for(;;) {
4150 struct stat sb;
4151 d = readdir(ffs);
4152 if (!d)
4153 break;
4155 if (strcmp(d->d_name, ".") == 0 || strcmp(d->d_name, "..") == 0) {
4156 continue;
4159 if (strstart(d->d_name, file_prefix, NULL)) {
4160 memcpy(file, input, input_path_len);
4161 if (input_path_len < sizeof(file))
4162 pstrcpy(file + input_path_len, sizeof(file) - input_path_len,
4163 d->d_name);
4164 /* stat the file to find out if it's a directory.
4165 * In that case add a slash to speed up typing long paths
4167 if (stat(file, &sb) == 0 && S_ISDIR(sb.st_mode)) {
4168 pstrcat(file, sizeof(file), "/");
4170 readline_add_completion(mon->rs, file);
4173 closedir(ffs);
4176 typedef struct MonitorBlockComplete {
4177 Monitor *mon;
4178 const char *input;
4179 } MonitorBlockComplete;
4181 static void block_completion_it(void *opaque, BlockDriverState *bs)
4183 const char *name = bdrv_get_device_name(bs);
4184 MonitorBlockComplete *mbc = opaque;
4185 Monitor *mon = mbc->mon;
4186 const char *input = mbc->input;
4188 if (input[0] == '\0' ||
4189 !strncmp(name, (char *)input, strlen(input))) {
4190 readline_add_completion(mon->rs, name);
4194 static const char *next_arg_type(const char *typestr)
4196 const char *p = strchr(typestr, ':');
4197 return (p != NULL ? ++p : typestr);
4200 static void add_completion_option(ReadLineState *rs, const char *str,
4201 const char *option)
4203 if (!str || !option) {
4204 return;
4206 if (!strncmp(option, str, strlen(str))) {
4207 readline_add_completion(rs, option);
4211 void chardev_add_completion(ReadLineState *rs, int nb_args, const char *str)
4213 size_t len;
4214 ChardevBackendInfoList *list, *start;
4216 if (nb_args != 2) {
4217 return;
4219 len = strlen(str);
4220 readline_set_completion_index(rs, len);
4222 start = list = qmp_query_chardev_backends(NULL);
4223 while (list) {
4224 const char *chr_name = list->value->name;
4226 if (!strncmp(chr_name, str, len)) {
4227 readline_add_completion(rs, chr_name);
4229 list = list->next;
4231 qapi_free_ChardevBackendInfoList(start);
4234 void netdev_add_completion(ReadLineState *rs, int nb_args, const char *str)
4236 size_t len;
4237 int i;
4239 if (nb_args != 2) {
4240 return;
4242 len = strlen(str);
4243 readline_set_completion_index(rs, len);
4244 for (i = 0; NetClientOptionsKind_lookup[i]; i++) {
4245 add_completion_option(rs, str, NetClientOptionsKind_lookup[i]);
4249 void device_add_completion(ReadLineState *rs, int nb_args, const char *str)
4251 GSList *list, *elt;
4252 size_t len;
4254 if (nb_args != 2) {
4255 return;
4258 len = strlen(str);
4259 readline_set_completion_index(rs, len);
4260 list = elt = object_class_get_list(TYPE_DEVICE, false);
4261 while (elt) {
4262 const char *name;
4263 DeviceClass *dc = OBJECT_CLASS_CHECK(DeviceClass, elt->data,
4264 TYPE_DEVICE);
4265 name = object_class_get_name(OBJECT_CLASS(dc));
4267 if (!dc->cannot_instantiate_with_device_add_yet
4268 && !strncmp(name, str, len)) {
4269 readline_add_completion(rs, name);
4271 elt = elt->next;
4273 g_slist_free(list);
4276 void object_add_completion(ReadLineState *rs, int nb_args, const char *str)
4278 GSList *list, *elt;
4279 size_t len;
4281 if (nb_args != 2) {
4282 return;
4285 len = strlen(str);
4286 readline_set_completion_index(rs, len);
4287 list = elt = object_class_get_list(TYPE_USER_CREATABLE, false);
4288 while (elt) {
4289 const char *name;
4291 name = object_class_get_name(OBJECT_CLASS(elt->data));
4292 if (!strncmp(name, str, len) && strcmp(name, TYPE_USER_CREATABLE)) {
4293 readline_add_completion(rs, name);
4295 elt = elt->next;
4297 g_slist_free(list);
4300 static void device_del_bus_completion(ReadLineState *rs, BusState *bus,
4301 const char *str, size_t len)
4303 BusChild *kid;
4305 QTAILQ_FOREACH(kid, &bus->children, sibling) {
4306 DeviceState *dev = kid->child;
4307 BusState *dev_child;
4309 if (dev->id && !strncmp(str, dev->id, len)) {
4310 readline_add_completion(rs, dev->id);
4313 QLIST_FOREACH(dev_child, &dev->child_bus, sibling) {
4314 device_del_bus_completion(rs, dev_child, str, len);
4319 void chardev_remove_completion(ReadLineState *rs, int nb_args, const char *str)
4321 size_t len;
4322 ChardevInfoList *list, *start;
4324 if (nb_args != 2) {
4325 return;
4327 len = strlen(str);
4328 readline_set_completion_index(rs, len);
4330 start = list = qmp_query_chardev(NULL);
4331 while (list) {
4332 ChardevInfo *chr = list->value;
4334 if (!strncmp(chr->label, str, len)) {
4335 readline_add_completion(rs, chr->label);
4337 list = list->next;
4339 qapi_free_ChardevInfoList(start);
4342 static void ringbuf_completion(ReadLineState *rs, const char *str)
4344 size_t len;
4345 ChardevInfoList *list, *start;
4347 len = strlen(str);
4348 readline_set_completion_index(rs, len);
4350 start = list = qmp_query_chardev(NULL);
4351 while (list) {
4352 ChardevInfo *chr_info = list->value;
4354 if (!strncmp(chr_info->label, str, len)) {
4355 CharDriverState *chr = qemu_chr_find(chr_info->label);
4356 if (chr && chr_is_ringbuf(chr)) {
4357 readline_add_completion(rs, chr_info->label);
4360 list = list->next;
4362 qapi_free_ChardevInfoList(start);
4365 void ringbuf_read_completion(ReadLineState *rs, int nb_args, const char *str)
4367 if (nb_args != 2) {
4368 return;
4370 ringbuf_completion(rs, str);
4373 void ringbuf_write_completion(ReadLineState *rs, int nb_args, const char *str)
4375 if (nb_args != 2) {
4376 return;
4378 ringbuf_completion(rs, str);
4381 void device_del_completion(ReadLineState *rs, int nb_args, const char *str)
4383 size_t len;
4385 if (nb_args != 2) {
4386 return;
4389 len = strlen(str);
4390 readline_set_completion_index(rs, len);
4391 device_del_bus_completion(rs, sysbus_get_default(), str, len);
4394 void object_del_completion(ReadLineState *rs, int nb_args, const char *str)
4396 ObjectPropertyInfoList *list, *start;
4397 size_t len;
4399 if (nb_args != 2) {
4400 return;
4402 len = strlen(str);
4403 readline_set_completion_index(rs, len);
4405 start = list = qmp_qom_list("/objects", NULL);
4406 while (list) {
4407 ObjectPropertyInfo *info = list->value;
4409 if (!strncmp(info->type, "child<", 5)
4410 && !strncmp(info->name, str, len)) {
4411 readline_add_completion(rs, info->name);
4413 list = list->next;
4415 qapi_free_ObjectPropertyInfoList(start);
4418 void sendkey_completion(ReadLineState *rs, int nb_args, const char *str)
4420 int i;
4421 char *sep;
4422 size_t len;
4424 if (nb_args != 2) {
4425 return;
4427 sep = strrchr(str, '-');
4428 if (sep) {
4429 str = sep + 1;
4431 len = strlen(str);
4432 readline_set_completion_index(rs, len);
4433 for (i = 0; i < Q_KEY_CODE_MAX; i++) {
4434 if (!strncmp(str, QKeyCode_lookup[i], len)) {
4435 readline_add_completion(rs, QKeyCode_lookup[i]);
4440 void set_link_completion(ReadLineState *rs, int nb_args, const char *str)
4442 size_t len;
4444 len = strlen(str);
4445 readline_set_completion_index(rs, len);
4446 if (nb_args == 2) {
4447 NetClientState *ncs[255];
4448 int count, i;
4449 count = qemu_find_net_clients_except(NULL, ncs,
4450 NET_CLIENT_OPTIONS_KIND_NONE, 255);
4451 for (i = 0; i < count; i++) {
4452 const char *name = ncs[i]->name;
4453 if (!strncmp(str, name, len)) {
4454 readline_add_completion(rs, name);
4457 } else if (nb_args == 3) {
4458 add_completion_option(rs, str, "on");
4459 add_completion_option(rs, str, "off");
4463 void netdev_del_completion(ReadLineState *rs, int nb_args, const char *str)
4465 int len, count, i;
4466 NetClientState *ncs[255];
4468 if (nb_args != 2) {
4469 return;
4472 len = strlen(str);
4473 readline_set_completion_index(rs, len);
4474 count = qemu_find_net_clients_except(NULL, ncs, NET_CLIENT_OPTIONS_KIND_NIC,
4475 255);
4476 for (i = 0; i < count; i++) {
4477 QemuOpts *opts;
4478 const char *name = ncs[i]->name;
4479 if (strncmp(str, name, len)) {
4480 continue;
4482 opts = qemu_opts_find(qemu_find_opts_err("netdev", NULL), name);
4483 if (opts) {
4484 readline_add_completion(rs, name);
4489 void watchdog_action_completion(ReadLineState *rs, int nb_args, const char *str)
4491 if (nb_args != 2) {
4492 return;
4494 readline_set_completion_index(rs, strlen(str));
4495 add_completion_option(rs, str, "reset");
4496 add_completion_option(rs, str, "shutdown");
4497 add_completion_option(rs, str, "poweroff");
4498 add_completion_option(rs, str, "pause");
4499 add_completion_option(rs, str, "debug");
4500 add_completion_option(rs, str, "none");
4503 void migrate_set_capability_completion(ReadLineState *rs, int nb_args,
4504 const char *str)
4506 size_t len;
4508 len = strlen(str);
4509 readline_set_completion_index(rs, len);
4510 if (nb_args == 2) {
4511 int i;
4512 for (i = 0; i < MIGRATION_CAPABILITY_MAX; i++) {
4513 const char *name = MigrationCapability_lookup[i];
4514 if (!strncmp(str, name, len)) {
4515 readline_add_completion(rs, name);
4518 } else if (nb_args == 3) {
4519 add_completion_option(rs, str, "on");
4520 add_completion_option(rs, str, "off");
4524 void host_net_add_completion(ReadLineState *rs, int nb_args, const char *str)
4526 int i;
4527 size_t len;
4528 if (nb_args != 2) {
4529 return;
4531 len = strlen(str);
4532 readline_set_completion_index(rs, len);
4533 for (i = 0; host_net_devices[i]; i++) {
4534 if (!strncmp(host_net_devices[i], str, len)) {
4535 readline_add_completion(rs, host_net_devices[i]);
4540 void host_net_remove_completion(ReadLineState *rs, int nb_args, const char *str)
4542 NetClientState *ncs[255];
4543 int count, i, len;
4545 len = strlen(str);
4546 readline_set_completion_index(rs, len);
4547 if (nb_args == 2) {
4548 count = qemu_find_net_clients_except(NULL, ncs,
4549 NET_CLIENT_OPTIONS_KIND_NONE, 255);
4550 for (i = 0; i < count; i++) {
4551 int id;
4552 char name[16];
4554 if (net_hub_id_for_client(ncs[i], &id)) {
4555 continue;
4557 snprintf(name, sizeof(name), "%d", id);
4558 if (!strncmp(str, name, len)) {
4559 readline_add_completion(rs, name);
4562 return;
4563 } else if (nb_args == 3) {
4564 count = qemu_find_net_clients_except(NULL, ncs,
4565 NET_CLIENT_OPTIONS_KIND_NIC, 255);
4566 for (i = 0; i < count; i++) {
4567 const char *name;
4569 name = ncs[i]->name;
4570 if (!strncmp(str, name, len)) {
4571 readline_add_completion(rs, name);
4574 return;
4578 static void vm_completion(ReadLineState *rs, const char *str)
4580 size_t len;
4581 BlockDriverState *bs = NULL;
4583 len = strlen(str);
4584 readline_set_completion_index(rs, len);
4585 while ((bs = bdrv_next(bs))) {
4586 SnapshotInfoList *snapshots, *snapshot;
4588 if (!bdrv_can_snapshot(bs)) {
4589 continue;
4591 if (bdrv_query_snapshot_info_list(bs, &snapshots, NULL)) {
4592 continue;
4594 snapshot = snapshots;
4595 while (snapshot) {
4596 char *completion = snapshot->value->name;
4597 if (!strncmp(str, completion, len)) {
4598 readline_add_completion(rs, completion);
4600 completion = snapshot->value->id;
4601 if (!strncmp(str, completion, len)) {
4602 readline_add_completion(rs, completion);
4604 snapshot = snapshot->next;
4606 qapi_free_SnapshotInfoList(snapshots);
4611 void delvm_completion(ReadLineState *rs, int nb_args, const char *str)
4613 if (nb_args == 2) {
4614 vm_completion(rs, str);
4618 void loadvm_completion(ReadLineState *rs, int nb_args, const char *str)
4620 if (nb_args == 2) {
4621 vm_completion(rs, str);
4625 static void monitor_find_completion_by_table(Monitor *mon,
4626 const mon_cmd_t *cmd_table,
4627 char **args,
4628 int nb_args)
4630 const char *cmdname;
4631 int i;
4632 const char *ptype, *str;
4633 const mon_cmd_t *cmd;
4634 MonitorBlockComplete mbs;
4636 if (nb_args <= 1) {
4637 /* command completion */
4638 if (nb_args == 0)
4639 cmdname = "";
4640 else
4641 cmdname = args[0];
4642 readline_set_completion_index(mon->rs, strlen(cmdname));
4643 for (cmd = cmd_table; cmd->name != NULL; cmd++) {
4644 cmd_completion(mon, cmdname, cmd->name);
4646 } else {
4647 /* find the command */
4648 for (cmd = cmd_table; cmd->name != NULL; cmd++) {
4649 if (compare_cmd(args[0], cmd->name)) {
4650 break;
4653 if (!cmd->name) {
4654 return;
4657 if (cmd->sub_table) {
4658 /* do the job again */
4659 return monitor_find_completion_by_table(mon, cmd->sub_table,
4660 &args[1], nb_args - 1);
4662 if (cmd->command_completion) {
4663 return cmd->command_completion(mon->rs, nb_args, args[nb_args - 1]);
4666 ptype = next_arg_type(cmd->args_type);
4667 for(i = 0; i < nb_args - 2; i++) {
4668 if (*ptype != '\0') {
4669 ptype = next_arg_type(ptype);
4670 while (*ptype == '?')
4671 ptype = next_arg_type(ptype);
4674 str = args[nb_args - 1];
4675 if (*ptype == '-' && ptype[1] != '\0') {
4676 ptype = next_arg_type(ptype);
4678 switch(*ptype) {
4679 case 'F':
4680 /* file completion */
4681 readline_set_completion_index(mon->rs, strlen(str));
4682 file_completion(mon, str);
4683 break;
4684 case 'B':
4685 /* block device name completion */
4686 mbs.mon = mon;
4687 mbs.input = str;
4688 readline_set_completion_index(mon->rs, strlen(str));
4689 bdrv_iterate(block_completion_it, &mbs);
4690 break;
4691 case 's':
4692 case 'S':
4693 if (!strcmp(cmd->name, "help|?")) {
4694 monitor_find_completion_by_table(mon, cmd_table,
4695 &args[1], nb_args - 1);
4697 break;
4698 default:
4699 break;
4704 static void monitor_find_completion(void *opaque,
4705 const char *cmdline)
4707 Monitor *mon = opaque;
4708 char *args[MAX_ARGS];
4709 int nb_args, len;
4711 /* 1. parse the cmdline */
4712 if (parse_cmdline(cmdline, &nb_args, args) < 0) {
4713 return;
4715 #ifdef DEBUG_COMPLETION
4716 for (i = 0; i < nb_args; i++) {
4717 monitor_printf(mon, "arg%d = '%s'\n", i, args[i]);
4719 #endif
4721 /* if the line ends with a space, it means we want to complete the
4722 next arg */
4723 len = strlen(cmdline);
4724 if (len > 0 && qemu_isspace(cmdline[len - 1])) {
4725 if (nb_args >= MAX_ARGS) {
4726 goto cleanup;
4728 args[nb_args++] = g_strdup("");
4731 /* 2. auto complete according to args */
4732 monitor_find_completion_by_table(mon, mon->cmd_table, args, nb_args);
4734 cleanup:
4735 free_cmdline_args(args, nb_args);
4738 static int monitor_can_read(void *opaque)
4740 Monitor *mon = opaque;
4742 return (mon->suspend_cnt == 0) ? 1 : 0;
4745 static int invalid_qmp_mode(const Monitor *mon, const char *cmd_name)
4747 int is_cap = compare_cmd(cmd_name, "qmp_capabilities");
4748 return (qmp_cmd_mode(mon) ? is_cap : !is_cap);
4752 * Argument validation rules:
4754 * 1. The argument must exist in cmd_args qdict
4755 * 2. The argument type must be the expected one
4757 * Special case: If the argument doesn't exist in cmd_args and
4758 * the QMP_ACCEPT_UNKNOWNS flag is set, then the
4759 * checking is skipped for it.
4761 static int check_client_args_type(const QDict *client_args,
4762 const QDict *cmd_args, int flags)
4764 const QDictEntry *ent;
4766 for (ent = qdict_first(client_args); ent;ent = qdict_next(client_args,ent)){
4767 QObject *obj;
4768 QString *arg_type;
4769 const QObject *client_arg = qdict_entry_value(ent);
4770 const char *client_arg_name = qdict_entry_key(ent);
4772 obj = qdict_get(cmd_args, client_arg_name);
4773 if (!obj) {
4774 if (flags & QMP_ACCEPT_UNKNOWNS) {
4775 /* handler accepts unknowns */
4776 continue;
4778 /* client arg doesn't exist */
4779 qerror_report(QERR_INVALID_PARAMETER, client_arg_name);
4780 return -1;
4783 arg_type = qobject_to_qstring(obj);
4784 assert(arg_type != NULL);
4786 /* check if argument's type is correct */
4787 switch (qstring_get_str(arg_type)[0]) {
4788 case 'F':
4789 case 'B':
4790 case 's':
4791 if (qobject_type(client_arg) != QTYPE_QSTRING) {
4792 qerror_report(QERR_INVALID_PARAMETER_TYPE, client_arg_name,
4793 "string");
4794 return -1;
4796 break;
4797 case 'i':
4798 case 'l':
4799 case 'M':
4800 case 'o':
4801 if (qobject_type(client_arg) != QTYPE_QINT) {
4802 qerror_report(QERR_INVALID_PARAMETER_TYPE, client_arg_name,
4803 "int");
4804 return -1;
4806 break;
4807 case 'T':
4808 if (qobject_type(client_arg) != QTYPE_QINT &&
4809 qobject_type(client_arg) != QTYPE_QFLOAT) {
4810 qerror_report(QERR_INVALID_PARAMETER_TYPE, client_arg_name,
4811 "number");
4812 return -1;
4814 break;
4815 case 'b':
4816 case '-':
4817 if (qobject_type(client_arg) != QTYPE_QBOOL) {
4818 qerror_report(QERR_INVALID_PARAMETER_TYPE, client_arg_name,
4819 "bool");
4820 return -1;
4822 break;
4823 case 'O':
4824 assert(flags & QMP_ACCEPT_UNKNOWNS);
4825 break;
4826 case 'q':
4827 /* Any QObject can be passed. */
4828 break;
4829 case '/':
4830 case '.':
4832 * These types are not supported by QMP and thus are not
4833 * handled here. Fall through.
4835 default:
4836 abort();
4840 return 0;
4844 * - Check if the client has passed all mandatory args
4845 * - Set special flags for argument validation
4847 static int check_mandatory_args(const QDict *cmd_args,
4848 const QDict *client_args, int *flags)
4850 const QDictEntry *ent;
4852 for (ent = qdict_first(cmd_args); ent; ent = qdict_next(cmd_args, ent)) {
4853 const char *cmd_arg_name = qdict_entry_key(ent);
4854 QString *type = qobject_to_qstring(qdict_entry_value(ent));
4855 assert(type != NULL);
4857 if (qstring_get_str(type)[0] == 'O') {
4858 assert((*flags & QMP_ACCEPT_UNKNOWNS) == 0);
4859 *flags |= QMP_ACCEPT_UNKNOWNS;
4860 } else if (qstring_get_str(type)[0] != '-' &&
4861 qstring_get_str(type)[1] != '?' &&
4862 !qdict_haskey(client_args, cmd_arg_name)) {
4863 qerror_report(QERR_MISSING_PARAMETER, cmd_arg_name);
4864 return -1;
4868 return 0;
4871 static QDict *qdict_from_args_type(const char *args_type)
4873 int i;
4874 QDict *qdict;
4875 QString *key, *type, *cur_qs;
4877 assert(args_type != NULL);
4879 qdict = qdict_new();
4881 if (args_type == NULL || args_type[0] == '\0') {
4882 /* no args, empty qdict */
4883 goto out;
4886 key = qstring_new();
4887 type = qstring_new();
4889 cur_qs = key;
4891 for (i = 0;; i++) {
4892 switch (args_type[i]) {
4893 case ',':
4894 case '\0':
4895 qdict_put(qdict, qstring_get_str(key), type);
4896 QDECREF(key);
4897 if (args_type[i] == '\0') {
4898 goto out;
4900 type = qstring_new(); /* qdict has ref */
4901 cur_qs = key = qstring_new();
4902 break;
4903 case ':':
4904 cur_qs = type;
4905 break;
4906 default:
4907 qstring_append_chr(cur_qs, args_type[i]);
4908 break;
4912 out:
4913 return qdict;
4917 * Client argument checking rules:
4919 * 1. Client must provide all mandatory arguments
4920 * 2. Each argument provided by the client must be expected
4921 * 3. Each argument provided by the client must have the type expected
4922 * by the command
4924 static int qmp_check_client_args(const mon_cmd_t *cmd, QDict *client_args)
4926 int flags, err;
4927 QDict *cmd_args;
4929 cmd_args = qdict_from_args_type(cmd->args_type);
4931 flags = 0;
4932 err = check_mandatory_args(cmd_args, client_args, &flags);
4933 if (err) {
4934 goto out;
4937 err = check_client_args_type(client_args, cmd_args, flags);
4939 out:
4940 QDECREF(cmd_args);
4941 return err;
4945 * Input object checking rules
4947 * 1. Input object must be a dict
4948 * 2. The "execute" key must exist
4949 * 3. The "execute" key must be a string
4950 * 4. If the "arguments" key exists, it must be a dict
4951 * 5. If the "id" key exists, it can be anything (ie. json-value)
4952 * 6. Any argument not listed above is considered invalid
4954 static QDict *qmp_check_input_obj(QObject *input_obj)
4956 const QDictEntry *ent;
4957 int has_exec_key = 0;
4958 QDict *input_dict;
4960 if (qobject_type(input_obj) != QTYPE_QDICT) {
4961 qerror_report(QERR_QMP_BAD_INPUT_OBJECT, "object");
4962 return NULL;
4965 input_dict = qobject_to_qdict(input_obj);
4967 for (ent = qdict_first(input_dict); ent; ent = qdict_next(input_dict, ent)){
4968 const char *arg_name = qdict_entry_key(ent);
4969 const QObject *arg_obj = qdict_entry_value(ent);
4971 if (!strcmp(arg_name, "execute")) {
4972 if (qobject_type(arg_obj) != QTYPE_QSTRING) {
4973 qerror_report(QERR_QMP_BAD_INPUT_OBJECT_MEMBER, "execute",
4974 "string");
4975 return NULL;
4977 has_exec_key = 1;
4978 } else if (!strcmp(arg_name, "arguments")) {
4979 if (qobject_type(arg_obj) != QTYPE_QDICT) {
4980 qerror_report(QERR_QMP_BAD_INPUT_OBJECT_MEMBER, "arguments",
4981 "object");
4982 return NULL;
4984 } else if (!strcmp(arg_name, "id")) {
4985 /* FIXME: check duplicated IDs for async commands */
4986 } else {
4987 qerror_report(QERR_QMP_EXTRA_MEMBER, arg_name);
4988 return NULL;
4992 if (!has_exec_key) {
4993 qerror_report(QERR_QMP_BAD_INPUT_OBJECT, "execute");
4994 return NULL;
4997 return input_dict;
5000 static void qmp_call_cmd(Monitor *mon, const mon_cmd_t *cmd,
5001 const QDict *params)
5003 int ret;
5004 QObject *data = NULL;
5006 ret = cmd->mhandler.cmd_new(mon, params, &data);
5007 handler_audit(mon, cmd, ret);
5008 monitor_protocol_emitter(mon, data);
5009 qobject_decref(data);
5012 static void handle_qmp_command(JSONMessageParser *parser, QList *tokens)
5014 int err;
5015 QObject *obj;
5016 QDict *input, *args;
5017 const mon_cmd_t *cmd;
5018 const char *cmd_name;
5019 Monitor *mon = cur_mon;
5021 args = input = NULL;
5023 obj = json_parser_parse(tokens, NULL);
5024 if (!obj) {
5025 // FIXME: should be triggered in json_parser_parse()
5026 qerror_report(QERR_JSON_PARSING);
5027 goto err_out;
5030 input = qmp_check_input_obj(obj);
5031 if (!input) {
5032 qobject_decref(obj);
5033 goto err_out;
5036 mon->mc->id = qdict_get(input, "id");
5037 qobject_incref(mon->mc->id);
5039 cmd_name = qdict_get_str(input, "execute");
5040 trace_handle_qmp_command(mon, cmd_name);
5041 if (invalid_qmp_mode(mon, cmd_name)) {
5042 qerror_report(QERR_COMMAND_NOT_FOUND, cmd_name);
5043 goto err_out;
5046 cmd = qmp_find_cmd(cmd_name);
5047 if (!cmd) {
5048 qerror_report(QERR_COMMAND_NOT_FOUND, cmd_name);
5049 goto err_out;
5052 obj = qdict_get(input, "arguments");
5053 if (!obj) {
5054 args = qdict_new();
5055 } else {
5056 args = qobject_to_qdict(obj);
5057 QINCREF(args);
5060 err = qmp_check_client_args(cmd, args);
5061 if (err < 0) {
5062 goto err_out;
5065 if (handler_is_async(cmd)) {
5066 err = qmp_async_cmd_handler(mon, cmd, args);
5067 if (err) {
5068 /* emit the error response */
5069 goto err_out;
5071 } else {
5072 qmp_call_cmd(mon, cmd, args);
5075 goto out;
5077 err_out:
5078 monitor_protocol_emitter(mon, NULL);
5079 out:
5080 QDECREF(input);
5081 QDECREF(args);
5085 * monitor_control_read(): Read and handle QMP input
5087 static void monitor_control_read(void *opaque, const uint8_t *buf, int size)
5089 Monitor *old_mon = cur_mon;
5091 cur_mon = opaque;
5093 json_message_parser_feed(&cur_mon->mc->parser, (const char *) buf, size);
5095 cur_mon = old_mon;
5098 static void monitor_read(void *opaque, const uint8_t *buf, int size)
5100 Monitor *old_mon = cur_mon;
5101 int i;
5103 cur_mon = opaque;
5105 if (cur_mon->rs) {
5106 for (i = 0; i < size; i++)
5107 readline_handle_byte(cur_mon->rs, buf[i]);
5108 } else {
5109 if (size == 0 || buf[size - 1] != 0)
5110 monitor_printf(cur_mon, "corrupted command\n");
5111 else
5112 handle_user_command(cur_mon, (char *)buf);
5115 cur_mon = old_mon;
5118 static void monitor_command_cb(void *opaque, const char *cmdline,
5119 void *readline_opaque)
5121 Monitor *mon = opaque;
5123 monitor_suspend(mon);
5124 handle_user_command(mon, cmdline);
5125 monitor_resume(mon);
5128 int monitor_suspend(Monitor *mon)
5130 if (!mon->rs)
5131 return -ENOTTY;
5132 mon->suspend_cnt++;
5133 return 0;
5136 void monitor_resume(Monitor *mon)
5138 if (!mon->rs)
5139 return;
5140 if (--mon->suspend_cnt == 0)
5141 readline_show_prompt(mon->rs);
5144 static QObject *get_qmp_greeting(void)
5146 QObject *ver = NULL;
5148 qmp_marshal_input_query_version(NULL, NULL, &ver);
5149 return qobject_from_jsonf("{'QMP':{'version': %p,'capabilities': []}}",ver);
5153 * monitor_control_event(): Print QMP gretting
5155 static void monitor_control_event(void *opaque, int event)
5157 QObject *data;
5158 Monitor *mon = opaque;
5160 switch (event) {
5161 case CHR_EVENT_OPENED:
5162 mon->mc->command_mode = 0;
5163 data = get_qmp_greeting();
5164 monitor_json_emitter(mon, data);
5165 qobject_decref(data);
5166 mon_refcount++;
5167 break;
5168 case CHR_EVENT_CLOSED:
5169 json_message_parser_destroy(&mon->mc->parser);
5170 json_message_parser_init(&mon->mc->parser, handle_qmp_command);
5171 mon_refcount--;
5172 monitor_fdsets_cleanup();
5173 break;
5177 static void monitor_event(void *opaque, int event)
5179 Monitor *mon = opaque;
5181 switch (event) {
5182 case CHR_EVENT_MUX_IN:
5183 mon->mux_out = 0;
5184 if (mon->reset_seen) {
5185 readline_restart(mon->rs);
5186 monitor_resume(mon);
5187 monitor_flush(mon);
5188 } else {
5189 mon->suspend_cnt = 0;
5191 break;
5193 case CHR_EVENT_MUX_OUT:
5194 if (mon->reset_seen) {
5195 if (mon->suspend_cnt == 0) {
5196 monitor_printf(mon, "\n");
5198 monitor_flush(mon);
5199 monitor_suspend(mon);
5200 } else {
5201 mon->suspend_cnt++;
5203 mon->mux_out = 1;
5204 break;
5206 case CHR_EVENT_OPENED:
5207 monitor_printf(mon, "QEMU %s monitor - type 'help' for more "
5208 "information\n", QEMU_VERSION);
5209 if (!mon->mux_out) {
5210 readline_show_prompt(mon->rs);
5212 mon->reset_seen = 1;
5213 mon_refcount++;
5214 break;
5216 case CHR_EVENT_CLOSED:
5217 mon_refcount--;
5218 monitor_fdsets_cleanup();
5219 break;
5223 static int
5224 compare_mon_cmd(const void *a, const void *b)
5226 return strcmp(((const mon_cmd_t *)a)->name,
5227 ((const mon_cmd_t *)b)->name);
5230 static void sortcmdlist(void)
5232 int array_num;
5233 int elem_size = sizeof(mon_cmd_t);
5235 array_num = sizeof(mon_cmds)/elem_size-1;
5236 qsort((void *)mon_cmds, array_num, elem_size, compare_mon_cmd);
5238 array_num = sizeof(info_cmds)/elem_size-1;
5239 qsort((void *)info_cmds, array_num, elem_size, compare_mon_cmd);
5244 * Local variables:
5245 * c-indent-level: 4
5246 * c-basic-offset: 4
5247 * tab-width: 8
5248 * End:
5251 /* These functions just adapt the readline interface in a typesafe way. We
5252 * could cast function pointers but that discards compiler checks.
5254 static void GCC_FMT_ATTR(2, 3) monitor_readline_printf(void *opaque,
5255 const char *fmt, ...)
5257 va_list ap;
5258 va_start(ap, fmt);
5259 monitor_vprintf(opaque, fmt, ap);
5260 va_end(ap);
5263 static void monitor_readline_flush(void *opaque)
5265 monitor_flush(opaque);
5268 void monitor_init(CharDriverState *chr, int flags)
5270 static int is_first_init = 1;
5271 Monitor *mon;
5273 if (is_first_init) {
5274 monitor_qapi_event_init();
5275 sortcmdlist();
5276 is_first_init = 0;
5279 mon = g_malloc(sizeof(*mon));
5280 monitor_data_init(mon);
5282 mon->chr = chr;
5283 mon->flags = flags;
5284 if (flags & MONITOR_USE_READLINE) {
5285 mon->rs = readline_init(monitor_readline_printf,
5286 monitor_readline_flush,
5287 mon,
5288 monitor_find_completion);
5289 monitor_read_command(mon, 0);
5292 if (monitor_ctrl_mode(mon)) {
5293 mon->mc = g_malloc0(sizeof(MonitorControl));
5294 /* Control mode requires special handlers */
5295 qemu_chr_add_handlers(chr, monitor_can_read, monitor_control_read,
5296 monitor_control_event, mon);
5297 qemu_chr_fe_set_echo(chr, true);
5299 json_message_parser_init(&mon->mc->parser, handle_qmp_command);
5300 } else {
5301 qemu_chr_add_handlers(chr, monitor_can_read, monitor_read,
5302 monitor_event, mon);
5305 QLIST_INSERT_HEAD(&mon_list, mon, entry);
5306 if (!default_mon || (flags & MONITOR_IS_DEFAULT))
5307 default_mon = mon;
5310 static void bdrv_password_cb(void *opaque, const char *password,
5311 void *readline_opaque)
5313 Monitor *mon = opaque;
5314 BlockDriverState *bs = readline_opaque;
5315 int ret = 0;
5317 if (bdrv_set_key(bs, password) != 0) {
5318 monitor_printf(mon, "invalid password\n");
5319 ret = -EPERM;
5321 if (mon->password_completion_cb)
5322 mon->password_completion_cb(mon->password_opaque, ret);
5324 monitor_read_command(mon, 1);
5327 ReadLineState *monitor_get_rs(Monitor *mon)
5329 return mon->rs;
5332 int monitor_read_bdrv_key_start(Monitor *mon, BlockDriverState *bs,
5333 BlockDriverCompletionFunc *completion_cb,
5334 void *opaque)
5336 int err;
5338 if (!bdrv_key_required(bs)) {
5339 if (completion_cb)
5340 completion_cb(opaque, 0);
5341 return 0;
5344 if (monitor_ctrl_mode(mon)) {
5345 qerror_report(QERR_DEVICE_ENCRYPTED, bdrv_get_device_name(bs),
5346 bdrv_get_encrypted_filename(bs));
5347 return -1;
5350 monitor_printf(mon, "%s (%s) is encrypted.\n", bdrv_get_device_name(bs),
5351 bdrv_get_encrypted_filename(bs));
5353 mon->password_completion_cb = completion_cb;
5354 mon->password_opaque = opaque;
5356 err = monitor_read_password(mon, bdrv_password_cb, bs);
5358 if (err && completion_cb)
5359 completion_cb(opaque, err);
5361 return err;
5364 int monitor_read_block_device_key(Monitor *mon, const char *device,
5365 BlockDriverCompletionFunc *completion_cb,
5366 void *opaque)
5368 BlockDriverState *bs;
5370 bs = bdrv_find(device);
5371 if (!bs) {
5372 monitor_printf(mon, "Device not found %s\n", device);
5373 return -1;
5376 return monitor_read_bdrv_key_start(mon, bs, completion_cb, opaque);
5379 QemuOptsList qemu_mon_opts = {
5380 .name = "mon",
5381 .implied_opt_name = "chardev",
5382 .head = QTAILQ_HEAD_INITIALIZER(qemu_mon_opts.head),
5383 .desc = {
5385 .name = "mode",
5386 .type = QEMU_OPT_STRING,
5388 .name = "chardev",
5389 .type = QEMU_OPT_STRING,
5391 .name = "default",
5392 .type = QEMU_OPT_BOOL,
5394 .name = "pretty",
5395 .type = QEMU_OPT_BOOL,
5397 { /* end of list */ }