monitor: Propagate errors through invalid_qmp_mode()
[qemu/ar7.git] / monitor.c
blobd336b8f94c17606ea116641832a4abd24e193d55
1 /*
2 * QEMU monitor
4 * Copyright (c) 2003-2004 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
24 #include <dirent.h>
25 #include "hw/hw.h"
26 #include "monitor/qdev.h"
27 #include "hw/usb.h"
28 #include "hw/i386/pc.h"
29 #include "hw/pci/pci.h"
30 #include "sysemu/watchdog.h"
31 #include "hw/loader.h"
32 #include "exec/gdbstub.h"
33 #include "net/net.h"
34 #include "net/slirp.h"
35 #include "sysemu/char.h"
36 #include "ui/qemu-spice.h"
37 #include "sysemu/sysemu.h"
38 #include "sysemu/numa.h"
39 #include "monitor/monitor.h"
40 #include "qemu/readline.h"
41 #include "ui/console.h"
42 #include "ui/input.h"
43 #include "sysemu/blockdev.h"
44 #include "audio/audio.h"
45 #include "disas/disas.h"
46 #include "sysemu/balloon.h"
47 #include "qemu/timer.h"
48 #include "migration/migration.h"
49 #include "sysemu/kvm.h"
50 #include "qemu/acl.h"
51 #include "sysemu/tpm.h"
52 #include "qapi/qmp/qint.h"
53 #include "qapi/qmp/qfloat.h"
54 #include "qapi/qmp/qlist.h"
55 #include "qapi/qmp/qbool.h"
56 #include "qapi/qmp/qstring.h"
57 #include "qapi/qmp/qjson.h"
58 #include "qapi/qmp/json-streamer.h"
59 #include "qapi/qmp/json-parser.h"
60 #include <qom/object_interfaces.h>
61 #include "qemu/osdep.h"
62 #include "cpu.h"
63 #include "trace.h"
64 #include "trace/control.h"
65 #ifdef CONFIG_TRACE_SIMPLE
66 #include "trace/simple.h"
67 #endif
68 #include "exec/memory.h"
69 #include "exec/cpu_ldst.h"
70 #include "qmp-commands.h"
71 #include "hmp.h"
72 #include "qemu/thread.h"
73 #include "block/qapi.h"
74 #include "qapi/qmp-event.h"
75 #include "qapi-event.h"
76 #include "sysemu/block-backend.h"
78 /* for hmp_info_irq/pic */
79 #if defined(TARGET_SPARC)
80 #include "hw/sparc/sun4m.h"
81 #endif
82 #include "hw/lm32/lm32_pic.h"
84 //#define DEBUG
85 //#define DEBUG_COMPLETION
88 * Supported types:
90 * 'F' filename
91 * 'B' block device name
92 * 's' string (accept optional quote)
93 * 'S' it just appends the rest of the string (accept optional quote)
94 * 'O' option string of the form NAME=VALUE,...
95 * parsed according to QemuOptsList given by its name
96 * Example: 'device:O' uses qemu_device_opts.
97 * Restriction: only lists with empty desc are supported
98 * TODO lift the restriction
99 * 'i' 32 bit integer
100 * 'l' target long (32 or 64 bit)
101 * 'M' Non-negative target long (32 or 64 bit), in user mode the
102 * value is multiplied by 2^20 (think Mebibyte)
103 * 'o' octets (aka bytes)
104 * user mode accepts an optional E, e, P, p, T, t, G, g, M, m,
105 * K, k suffix, which multiplies the value by 2^60 for suffixes E
106 * and e, 2^50 for suffixes P and p, 2^40 for suffixes T and t,
107 * 2^30 for suffixes G and g, 2^20 for M and m, 2^10 for K and k
108 * 'T' double
109 * user mode accepts an optional ms, us, ns suffix,
110 * which divides the value by 1e3, 1e6, 1e9, respectively
111 * '/' optional gdb-like print format (like "/10x")
113 * '?' optional type (for all types, except '/')
114 * '.' other form of optional type (for 'i' and 'l')
115 * 'b' boolean
116 * user mode accepts "on" or "off"
117 * '-' optional parameter (eg. '-f')
121 typedef struct mon_cmd_t {
122 const char *name;
123 const char *args_type;
124 const char *params;
125 const char *help;
126 union {
127 void (*cmd)(Monitor *mon, const QDict *qdict);
128 int (*cmd_new)(Monitor *mon, const QDict *params, QObject **ret_data);
129 } mhandler;
130 /* @sub_table is a list of 2nd level of commands. If it do not exist,
131 * mhandler should be used. If it exist, sub_table[?].mhandler should be
132 * used, and mhandler of 1st level plays the role of help function.
134 struct mon_cmd_t *sub_table;
135 void (*command_completion)(ReadLineState *rs, int nb_args, const char *str);
136 } mon_cmd_t;
138 /* file descriptors passed via SCM_RIGHTS */
139 typedef struct mon_fd_t mon_fd_t;
140 struct mon_fd_t {
141 char *name;
142 int fd;
143 QLIST_ENTRY(mon_fd_t) next;
146 /* file descriptor associated with a file descriptor set */
147 typedef struct MonFdsetFd MonFdsetFd;
148 struct MonFdsetFd {
149 int fd;
150 bool removed;
151 char *opaque;
152 QLIST_ENTRY(MonFdsetFd) next;
155 /* file descriptor set containing fds passed via SCM_RIGHTS */
156 typedef struct MonFdset MonFdset;
157 struct MonFdset {
158 int64_t id;
159 QLIST_HEAD(, MonFdsetFd) fds;
160 QLIST_HEAD(, MonFdsetFd) dup_fds;
161 QLIST_ENTRY(MonFdset) next;
164 typedef struct MonitorControl {
165 QObject *id;
166 JSONMessageParser parser;
167 int command_mode;
168 } MonitorControl;
171 * To prevent flooding clients, events can be throttled. The
172 * throttling is calculated globally, rather than per-Monitor
173 * instance.
175 typedef struct MonitorQAPIEventState {
176 QAPIEvent event; /* Event being tracked */
177 int64_t rate; /* Minimum time (in ns) between two events */
178 int64_t last; /* QEMU_CLOCK_REALTIME value at last emission */
179 QEMUTimer *timer; /* Timer for handling delayed events */
180 QObject *data; /* Event pending delayed dispatch */
181 } MonitorQAPIEventState;
183 struct Monitor {
184 CharDriverState *chr;
185 int reset_seen;
186 int flags;
187 int suspend_cnt;
188 bool skip_flush;
190 QemuMutex out_lock;
191 QString *outbuf;
192 guint out_watch;
194 /* Read under either BQL or out_lock, written with BQL+out_lock. */
195 int mux_out;
197 ReadLineState *rs;
198 MonitorControl *mc;
199 CPUState *mon_cpu;
200 BlockCompletionFunc *password_completion_cb;
201 void *password_opaque;
202 mon_cmd_t *cmd_table;
203 QError *error;
204 QLIST_HEAD(,mon_fd_t) fds;
205 QLIST_ENTRY(Monitor) entry;
208 /* QMP checker flags */
209 #define QMP_ACCEPT_UNKNOWNS 1
211 /* Protects mon_list, monitor_event_state. */
212 static QemuMutex monitor_lock;
214 static QLIST_HEAD(mon_list, Monitor) mon_list;
215 static QLIST_HEAD(mon_fdsets, MonFdset) mon_fdsets;
216 static int mon_refcount;
218 static mon_cmd_t mon_cmds[];
219 static mon_cmd_t info_cmds[];
221 static const mon_cmd_t qmp_cmds[];
223 Monitor *cur_mon;
224 Monitor *default_mon;
226 static void monitor_command_cb(void *opaque, const char *cmdline,
227 void *readline_opaque);
229 static inline int qmp_cmd_mode(const Monitor *mon)
231 return (mon->mc ? mon->mc->command_mode : 0);
234 /* Return true if in control mode, false otherwise */
235 static inline int monitor_ctrl_mode(const Monitor *mon)
237 return (mon->flags & MONITOR_USE_CONTROL);
240 /* Return non-zero iff we have a current monitor, and it is in QMP mode. */
241 int monitor_cur_is_qmp(void)
243 return cur_mon && monitor_ctrl_mode(cur_mon);
246 void monitor_read_command(Monitor *mon, int show_prompt)
248 if (!mon->rs)
249 return;
251 readline_start(mon->rs, "(qemu) ", 0, monitor_command_cb, NULL);
252 if (show_prompt)
253 readline_show_prompt(mon->rs);
256 int monitor_read_password(Monitor *mon, ReadLineFunc *readline_func,
257 void *opaque)
259 if (mon->rs) {
260 readline_start(mon->rs, "Password: ", 1, readline_func, opaque);
261 /* prompt is printed on return from the command handler */
262 return 0;
263 } else {
264 monitor_printf(mon, "terminal does not support password prompting\n");
265 return -ENOTTY;
269 static void monitor_flush_locked(Monitor *mon);
271 static gboolean monitor_unblocked(GIOChannel *chan, GIOCondition cond,
272 void *opaque)
274 Monitor *mon = opaque;
276 qemu_mutex_lock(&mon->out_lock);
277 mon->out_watch = 0;
278 monitor_flush_locked(mon);
279 qemu_mutex_unlock(&mon->out_lock);
280 return FALSE;
283 /* Called with mon->out_lock held. */
284 static void monitor_flush_locked(Monitor *mon)
286 int rc;
287 size_t len;
288 const char *buf;
290 if (mon->skip_flush) {
291 return;
294 buf = qstring_get_str(mon->outbuf);
295 len = qstring_get_length(mon->outbuf);
297 if (len && !mon->mux_out) {
298 rc = qemu_chr_fe_write(mon->chr, (const uint8_t *) buf, len);
299 if ((rc < 0 && errno != EAGAIN) || (rc == len)) {
300 /* all flushed or error */
301 QDECREF(mon->outbuf);
302 mon->outbuf = qstring_new();
303 return;
305 if (rc > 0) {
306 /* partinal write */
307 QString *tmp = qstring_from_str(buf + rc);
308 QDECREF(mon->outbuf);
309 mon->outbuf = tmp;
311 if (mon->out_watch == 0) {
312 mon->out_watch = qemu_chr_fe_add_watch(mon->chr, G_IO_OUT|G_IO_HUP,
313 monitor_unblocked, mon);
318 void monitor_flush(Monitor *mon)
320 qemu_mutex_lock(&mon->out_lock);
321 monitor_flush_locked(mon);
322 qemu_mutex_unlock(&mon->out_lock);
325 /* flush at every end of line */
326 static void monitor_puts(Monitor *mon, const char *str)
328 char c;
330 qemu_mutex_lock(&mon->out_lock);
331 for(;;) {
332 c = *str++;
333 if (c == '\0')
334 break;
335 if (c == '\n') {
336 qstring_append_chr(mon->outbuf, '\r');
338 qstring_append_chr(mon->outbuf, c);
339 if (c == '\n') {
340 monitor_flush_locked(mon);
343 qemu_mutex_unlock(&mon->out_lock);
346 void monitor_vprintf(Monitor *mon, const char *fmt, va_list ap)
348 char *buf;
350 if (!mon)
351 return;
353 if (monitor_ctrl_mode(mon)) {
354 return;
357 buf = g_strdup_vprintf(fmt, ap);
358 monitor_puts(mon, buf);
359 g_free(buf);
362 void monitor_printf(Monitor *mon, const char *fmt, ...)
364 va_list ap;
365 va_start(ap, fmt);
366 monitor_vprintf(mon, fmt, ap);
367 va_end(ap);
370 static int GCC_FMT_ATTR(2, 3) monitor_fprintf(FILE *stream,
371 const char *fmt, ...)
373 va_list ap;
374 va_start(ap, fmt);
375 monitor_vprintf((Monitor *)stream, fmt, ap);
376 va_end(ap);
377 return 0;
380 static inline int monitor_has_error(const Monitor *mon)
382 return mon->error != NULL;
385 static void monitor_json_emitter(Monitor *mon, const QObject *data)
387 QString *json;
389 json = mon->flags & MONITOR_USE_PRETTY ? qobject_to_json_pretty(data) :
390 qobject_to_json(data);
391 assert(json != NULL);
393 qstring_append_chr(json, '\n');
394 monitor_puts(mon, qstring_get_str(json));
396 QDECREF(json);
399 static QDict *build_qmp_error_dict(const QError *err)
401 QObject *obj;
403 obj = qobject_from_jsonf("{ 'error': { 'class': %s, 'desc': %p } }",
404 ErrorClass_lookup[err->err_class],
405 qerror_human(err));
407 return qobject_to_qdict(obj);
410 static void monitor_protocol_emitter(Monitor *mon, QObject *data)
412 QDict *qmp;
414 trace_monitor_protocol_emitter(mon);
416 if (!monitor_has_error(mon)) {
417 /* success response */
418 qmp = qdict_new();
419 if (data) {
420 qobject_incref(data);
421 qdict_put_obj(qmp, "return", data);
422 } else {
423 /* return an empty QDict by default */
424 qdict_put(qmp, "return", qdict_new());
426 } else {
427 /* error response */
428 qmp = build_qmp_error_dict(mon->error);
429 QDECREF(mon->error);
430 mon->error = NULL;
433 if (mon->mc->id) {
434 qdict_put_obj(qmp, "id", mon->mc->id);
435 mon->mc->id = NULL;
438 monitor_json_emitter(mon, QOBJECT(qmp));
439 QDECREF(qmp);
443 static MonitorQAPIEventState monitor_qapi_event_state[QAPI_EVENT_MAX];
446 * Emits the event to every monitor instance, @event is only used for trace
447 * Called with monitor_lock held.
449 static void monitor_qapi_event_emit(QAPIEvent event, QObject *data)
451 Monitor *mon;
453 trace_monitor_protocol_event_emit(event, data);
454 QLIST_FOREACH(mon, &mon_list, entry) {
455 if (monitor_ctrl_mode(mon) && qmp_cmd_mode(mon)) {
456 monitor_json_emitter(mon, data);
462 * Queue a new event for emission to Monitor instances,
463 * applying any rate limiting if required.
465 static void
466 monitor_qapi_event_queue(QAPIEvent event, QDict *data, Error **errp)
468 MonitorQAPIEventState *evstate;
469 assert(event < QAPI_EVENT_MAX);
470 int64_t now = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
472 evstate = &(monitor_qapi_event_state[event]);
473 trace_monitor_protocol_event_queue(event,
474 data,
475 evstate->rate,
476 evstate->last,
477 now);
479 /* Rate limit of 0 indicates no throttling */
480 qemu_mutex_lock(&monitor_lock);
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;
505 qemu_mutex_unlock(&monitor_lock);
509 * The callback invoked by QemuTimer when a delayed
510 * event is ready to be emitted
512 static void monitor_qapi_event_handler(void *opaque)
514 MonitorQAPIEventState *evstate = opaque;
515 int64_t now = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
517 trace_monitor_protocol_event_handler(evstate->event,
518 evstate->data,
519 evstate->last,
520 now);
521 qemu_mutex_lock(&monitor_lock);
522 if (evstate->data) {
523 monitor_qapi_event_emit(evstate->event, evstate->data);
524 qobject_decref(evstate->data);
525 evstate->data = NULL;
527 evstate->last = now;
528 qemu_mutex_unlock(&monitor_lock);
532 * @event: the event ID to be limited
533 * @rate: the rate limit in milliseconds
535 * Sets a rate limit on a particular event, so no
536 * more than 1 event will be emitted within @rate
537 * milliseconds
539 static void
540 monitor_qapi_event_throttle(QAPIEvent event, int64_t rate)
542 MonitorQAPIEventState *evstate;
543 assert(event < QAPI_EVENT_MAX);
545 evstate = &(monitor_qapi_event_state[event]);
547 trace_monitor_protocol_event_throttle(event, rate);
548 evstate->event = event;
549 assert(rate * SCALE_MS <= INT64_MAX);
550 evstate->rate = rate * SCALE_MS;
551 evstate->last = 0;
552 evstate->data = NULL;
553 evstate->timer = timer_new(QEMU_CLOCK_REALTIME,
554 SCALE_MS,
555 monitor_qapi_event_handler,
556 evstate);
559 static void monitor_qapi_event_init(void)
561 /* Limit guest-triggerable events to 1 per second */
562 monitor_qapi_event_throttle(QAPI_EVENT_RTC_CHANGE, 1000);
563 monitor_qapi_event_throttle(QAPI_EVENT_WATCHDOG, 1000);
564 monitor_qapi_event_throttle(QAPI_EVENT_BALLOON_CHANGE, 1000);
565 monitor_qapi_event_throttle(QAPI_EVENT_QUORUM_REPORT_BAD, 1000);
566 monitor_qapi_event_throttle(QAPI_EVENT_QUORUM_FAILURE, 1000);
567 monitor_qapi_event_throttle(QAPI_EVENT_VSERPORT_CHANGE, 1000);
569 qmp_event_set_func_emit(monitor_qapi_event_queue);
572 static int do_qmp_capabilities(Monitor *mon, const QDict *params,
573 QObject **ret_data)
575 /* Will setup QMP capabilities in the future */
576 if (monitor_ctrl_mode(mon)) {
577 mon->mc->command_mode = 1;
580 return 0;
583 static void handle_user_command(Monitor *mon, const char *cmdline);
585 static void monitor_data_init(Monitor *mon)
587 memset(mon, 0, sizeof(Monitor));
588 qemu_mutex_init(&mon->out_lock);
589 mon->outbuf = qstring_new();
590 /* Use *mon_cmds by default. */
591 mon->cmd_table = mon_cmds;
594 static void monitor_data_destroy(Monitor *mon)
596 QDECREF(mon->outbuf);
597 qemu_mutex_destroy(&mon->out_lock);
600 char *qmp_human_monitor_command(const char *command_line, bool has_cpu_index,
601 int64_t cpu_index, Error **errp)
603 char *output = NULL;
604 Monitor *old_mon, hmp;
606 monitor_data_init(&hmp);
607 hmp.skip_flush = true;
609 old_mon = cur_mon;
610 cur_mon = &hmp;
612 if (has_cpu_index) {
613 int ret = monitor_set_cpu(cpu_index);
614 if (ret < 0) {
615 cur_mon = old_mon;
616 error_set(errp, QERR_INVALID_PARAMETER_VALUE, "cpu-index",
617 "a CPU number");
618 goto out;
622 handle_user_command(&hmp, command_line);
623 cur_mon = old_mon;
625 qemu_mutex_lock(&hmp.out_lock);
626 if (qstring_get_length(hmp.outbuf) > 0) {
627 output = g_strdup(qstring_get_str(hmp.outbuf));
628 } else {
629 output = g_strdup("");
631 qemu_mutex_unlock(&hmp.out_lock);
633 out:
634 monitor_data_destroy(&hmp);
635 return output;
638 static int compare_cmd(const char *name, const char *list)
640 const char *p, *pstart;
641 int len;
642 len = strlen(name);
643 p = list;
644 for(;;) {
645 pstart = p;
646 p = strchr(p, '|');
647 if (!p)
648 p = pstart + strlen(pstart);
649 if ((p - pstart) == len && !memcmp(pstart, name, len))
650 return 1;
651 if (*p == '\0')
652 break;
653 p++;
655 return 0;
658 static int get_str(char *buf, int buf_size, const char **pp)
660 const char *p;
661 char *q;
662 int c;
664 q = buf;
665 p = *pp;
666 while (qemu_isspace(*p)) {
667 p++;
669 if (*p == '\0') {
670 fail:
671 *q = '\0';
672 *pp = p;
673 return -1;
675 if (*p == '\"') {
676 p++;
677 while (*p != '\0' && *p != '\"') {
678 if (*p == '\\') {
679 p++;
680 c = *p++;
681 switch (c) {
682 case 'n':
683 c = '\n';
684 break;
685 case 'r':
686 c = '\r';
687 break;
688 case '\\':
689 case '\'':
690 case '\"':
691 break;
692 default:
693 qemu_printf("unsupported escape code: '\\%c'\n", c);
694 goto fail;
696 if ((q - buf) < buf_size - 1) {
697 *q++ = c;
699 } else {
700 if ((q - buf) < buf_size - 1) {
701 *q++ = *p;
703 p++;
706 if (*p != '\"') {
707 qemu_printf("unterminated string\n");
708 goto fail;
710 p++;
711 } else {
712 while (*p != '\0' && !qemu_isspace(*p)) {
713 if ((q - buf) < buf_size - 1) {
714 *q++ = *p;
716 p++;
719 *q = '\0';
720 *pp = p;
721 return 0;
724 #define MAX_ARGS 16
726 static void free_cmdline_args(char **args, int nb_args)
728 int i;
730 assert(nb_args <= MAX_ARGS);
732 for (i = 0; i < nb_args; i++) {
733 g_free(args[i]);
739 * Parse the command line to get valid args.
740 * @cmdline: command line to be parsed.
741 * @pnb_args: location to store the number of args, must NOT be NULL.
742 * @args: location to store the args, which should be freed by caller, must
743 * NOT be NULL.
745 * Returns 0 on success, negative on failure.
747 * NOTE: this parser is an approximate form of the real command parser. Number
748 * of args have a limit of MAX_ARGS. If cmdline contains more, it will
749 * return with failure.
751 static int parse_cmdline(const char *cmdline,
752 int *pnb_args, char **args)
754 const char *p;
755 int nb_args, ret;
756 char buf[1024];
758 p = cmdline;
759 nb_args = 0;
760 for (;;) {
761 while (qemu_isspace(*p)) {
762 p++;
764 if (*p == '\0') {
765 break;
767 if (nb_args >= MAX_ARGS) {
768 goto fail;
770 ret = get_str(buf, sizeof(buf), &p);
771 if (ret < 0) {
772 goto fail;
774 args[nb_args] = g_strdup(buf);
775 nb_args++;
777 *pnb_args = nb_args;
778 return 0;
780 fail:
781 free_cmdline_args(args, nb_args);
782 return -1;
785 static void help_cmd_dump_one(Monitor *mon,
786 const mon_cmd_t *cmd,
787 char **prefix_args,
788 int prefix_args_nb)
790 int i;
792 for (i = 0; i < prefix_args_nb; i++) {
793 monitor_printf(mon, "%s ", prefix_args[i]);
795 monitor_printf(mon, "%s %s -- %s\n", cmd->name, cmd->params, cmd->help);
798 /* @args[@arg_index] is the valid command need to find in @cmds */
799 static void help_cmd_dump(Monitor *mon, const mon_cmd_t *cmds,
800 char **args, int nb_args, int arg_index)
802 const mon_cmd_t *cmd;
804 /* No valid arg need to compare with, dump all in *cmds */
805 if (arg_index >= nb_args) {
806 for (cmd = cmds; cmd->name != NULL; cmd++) {
807 help_cmd_dump_one(mon, cmd, args, arg_index);
809 return;
812 /* Find one entry to dump */
813 for (cmd = cmds; cmd->name != NULL; cmd++) {
814 if (compare_cmd(args[arg_index], cmd->name)) {
815 if (cmd->sub_table) {
816 /* continue with next arg */
817 help_cmd_dump(mon, cmd->sub_table,
818 args, nb_args, arg_index + 1);
819 } else {
820 help_cmd_dump_one(mon, cmd, args, arg_index);
822 break;
827 static void help_cmd(Monitor *mon, const char *name)
829 char *args[MAX_ARGS];
830 int nb_args = 0;
832 /* 1. parse user input */
833 if (name) {
834 /* special case for log, directly dump and return */
835 if (!strcmp(name, "log")) {
836 const QEMULogItem *item;
837 monitor_printf(mon, "Log items (comma separated):\n");
838 monitor_printf(mon, "%-10s %s\n", "none", "remove all logs");
839 for (item = qemu_log_items; item->mask != 0; item++) {
840 monitor_printf(mon, "%-10s %s\n", item->name, item->help);
842 return;
845 if (parse_cmdline(name, &nb_args, args) < 0) {
846 return;
850 /* 2. dump the contents according to parsed args */
851 help_cmd_dump(mon, mon->cmd_table, args, nb_args, 0);
853 free_cmdline_args(args, nb_args);
856 static void do_help_cmd(Monitor *mon, const QDict *qdict)
858 help_cmd(mon, qdict_get_try_str(qdict, "name"));
861 static void hmp_trace_event(Monitor *mon, const QDict *qdict)
863 const char *tp_name = qdict_get_str(qdict, "name");
864 bool new_state = qdict_get_bool(qdict, "option");
865 Error *local_err = NULL;
867 qmp_trace_event_set_state(tp_name, new_state, true, true, &local_err);
868 if (local_err) {
869 error_report_err(local_err);
873 #ifdef CONFIG_TRACE_SIMPLE
874 static void hmp_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 hmp_info_help(Monitor *mon, const QDict *qdict)
900 help_cmd(mon, "info");
903 CommandInfoList *qmp_query_commands(Error **errp)
905 CommandInfoList *info, *cmd_list = NULL;
906 const mon_cmd_t *cmd;
908 for (cmd = qmp_cmds; cmd->name != NULL; cmd++) {
909 info = g_malloc0(sizeof(*info));
910 info->value = g_malloc0(sizeof(*info->value));
911 info->value->name = g_strdup(cmd->name);
913 info->next = cmd_list;
914 cmd_list = info;
917 return cmd_list;
920 EventInfoList *qmp_query_events(Error **errp)
922 EventInfoList *info, *ev_list = NULL;
923 QAPIEvent e;
925 for (e = 0 ; e < QAPI_EVENT_MAX ; e++) {
926 const char *event_name = QAPIEvent_lookup[e];
927 assert(event_name != NULL);
928 info = g_malloc0(sizeof(*info));
929 info->value = g_malloc0(sizeof(*info->value));
930 info->value->name = g_strdup(event_name);
932 info->next = ev_list;
933 ev_list = info;
936 return ev_list;
939 /* set the current CPU defined by the user */
940 int monitor_set_cpu(int cpu_index)
942 CPUState *cpu;
944 cpu = qemu_get_cpu(cpu_index);
945 if (cpu == NULL) {
946 return -1;
948 cur_mon->mon_cpu = cpu;
949 return 0;
952 static CPUArchState *mon_get_cpu(void)
954 if (!cur_mon->mon_cpu) {
955 monitor_set_cpu(0);
957 cpu_synchronize_state(cur_mon->mon_cpu);
958 return cur_mon->mon_cpu->env_ptr;
961 int monitor_get_cpu_index(void)
963 CPUState *cpu = ENV_GET_CPU(mon_get_cpu());
964 return cpu->cpu_index;
967 static void hmp_info_registers(Monitor *mon, const QDict *qdict)
969 CPUState *cpu;
970 CPUArchState *env;
971 env = mon_get_cpu();
972 cpu = ENV_GET_CPU(env);
973 cpu_dump_state(cpu, (FILE *)mon, monitor_fprintf, CPU_DUMP_FPU);
976 static void hmp_info_jit(Monitor *mon, const QDict *qdict)
978 dump_exec_info((FILE *)mon, monitor_fprintf);
979 dump_drift_info((FILE *)mon, monitor_fprintf);
982 static void hmp_info_opcount(Monitor *mon, const QDict *qdict)
984 dump_opcount_info((FILE *)mon, monitor_fprintf);
987 static void hmp_info_history(Monitor *mon, const QDict *qdict)
989 int i;
990 const char *str;
992 if (!mon->rs)
993 return;
994 i = 0;
995 for(;;) {
996 str = readline_get_history(mon->rs, i);
997 if (!str)
998 break;
999 monitor_printf(mon, "%d: '%s'\n", i, str);
1000 i++;
1004 static void hmp_info_cpustats(Monitor *mon, const QDict *qdict)
1006 CPUState *cpu;
1007 CPUArchState *env;
1009 env = mon_get_cpu();
1010 cpu = ENV_GET_CPU(env);
1011 cpu_dump_statistics(cpu, (FILE *)mon, &monitor_fprintf, 0);
1014 static void hmp_info_trace_events(Monitor *mon, const QDict *qdict)
1016 TraceEventInfoList *events = qmp_trace_event_get_state("*", NULL);
1017 TraceEventInfoList *elem;
1019 for (elem = events; elem != NULL; elem = elem->next) {
1020 monitor_printf(mon, "%s : state %u\n",
1021 elem->value->name,
1022 elem->value->state == TRACE_EVENT_STATE_ENABLED ? 1 : 0);
1024 qapi_free_TraceEventInfoList(events);
1027 void qmp_client_migrate_info(const char *protocol, const char *hostname,
1028 bool has_port, int64_t port,
1029 bool has_tls_port, int64_t tls_port,
1030 bool has_cert_subject, const char *cert_subject,
1031 Error **errp)
1033 if (strcmp(protocol, "spice") == 0) {
1034 if (!qemu_using_spice(errp)) {
1035 return;
1038 if (!has_port && !has_tls_port) {
1039 error_set(errp, QERR_MISSING_PARAMETER, "port/tls-port");
1040 return;
1043 if (qemu_spice_migrate_info(hostname,
1044 has_port ? port : -1,
1045 has_tls_port ? tls_port : -1,
1046 cert_subject)) {
1047 error_set(errp, QERR_UNDEFINED_ERROR);
1048 return;
1050 return;
1053 error_set(errp, QERR_INVALID_PARAMETER_VALUE, "protocol", "spice");
1056 static void hmp_logfile(Monitor *mon, const QDict *qdict)
1058 qemu_set_log_filename(qdict_get_str(qdict, "filename"));
1061 static void hmp_log(Monitor *mon, const QDict *qdict)
1063 int mask;
1064 const char *items = qdict_get_str(qdict, "items");
1066 if (!strcmp(items, "none")) {
1067 mask = 0;
1068 } else {
1069 mask = qemu_str_to_log_mask(items);
1070 if (!mask) {
1071 help_cmd(mon, "log");
1072 return;
1075 qemu_set_log(mask);
1078 static void hmp_singlestep(Monitor *mon, const QDict *qdict)
1080 const char *option = qdict_get_try_str(qdict, "option");
1081 if (!option || !strcmp(option, "on")) {
1082 singlestep = 1;
1083 } else if (!strcmp(option, "off")) {
1084 singlestep = 0;
1085 } else {
1086 monitor_printf(mon, "unexpected option %s\n", option);
1090 static void hmp_gdbserver(Monitor *mon, const QDict *qdict)
1092 const char *device = qdict_get_try_str(qdict, "device");
1093 if (!device)
1094 device = "tcp::" DEFAULT_GDBSTUB_PORT;
1095 if (gdbserver_start(device) < 0) {
1096 monitor_printf(mon, "Could not open gdbserver on device '%s'\n",
1097 device);
1098 } else if (strcmp(device, "none") == 0) {
1099 monitor_printf(mon, "Disabled gdbserver\n");
1100 } else {
1101 monitor_printf(mon, "Waiting for gdb connection on device '%s'\n",
1102 device);
1106 static void hmp_watchdog_action(Monitor *mon, const QDict *qdict)
1108 const char *action = qdict_get_str(qdict, "action");
1109 if (select_watchdog_action(action) == -1) {
1110 monitor_printf(mon, "Unknown watchdog action '%s'\n", action);
1114 static void monitor_printc(Monitor *mon, int c)
1116 monitor_printf(mon, "'");
1117 switch(c) {
1118 case '\'':
1119 monitor_printf(mon, "\\'");
1120 break;
1121 case '\\':
1122 monitor_printf(mon, "\\\\");
1123 break;
1124 case '\n':
1125 monitor_printf(mon, "\\n");
1126 break;
1127 case '\r':
1128 monitor_printf(mon, "\\r");
1129 break;
1130 default:
1131 if (c >= 32 && c <= 126) {
1132 monitor_printf(mon, "%c", c);
1133 } else {
1134 monitor_printf(mon, "\\x%02x", c);
1136 break;
1138 monitor_printf(mon, "'");
1141 static void memory_dump(Monitor *mon, int count, int format, int wsize,
1142 hwaddr addr, int is_physical)
1144 CPUArchState *env;
1145 int l, line_size, i, max_digits, len;
1146 uint8_t buf[16];
1147 uint64_t v;
1149 if (format == 'i') {
1150 int flags;
1151 flags = 0;
1152 env = mon_get_cpu();
1153 #ifdef TARGET_I386
1154 if (wsize == 2) {
1155 flags = 1;
1156 } else if (wsize == 4) {
1157 flags = 0;
1158 } else {
1159 /* as default we use the current CS size */
1160 flags = 0;
1161 if (env) {
1162 #ifdef TARGET_X86_64
1163 if ((env->efer & MSR_EFER_LMA) &&
1164 (env->segs[R_CS].flags & DESC_L_MASK))
1165 flags = 2;
1166 else
1167 #endif
1168 if (!(env->segs[R_CS].flags & DESC_B_MASK))
1169 flags = 1;
1172 #endif
1173 #ifdef TARGET_PPC
1174 flags = msr_le << 16;
1175 flags |= env->bfd_mach;
1176 #endif
1177 monitor_disas(mon, env, addr, count, is_physical, flags);
1178 return;
1181 len = wsize * count;
1182 if (wsize == 1)
1183 line_size = 8;
1184 else
1185 line_size = 16;
1186 max_digits = 0;
1188 switch(format) {
1189 case 'o':
1190 max_digits = (wsize * 8 + 2) / 3;
1191 break;
1192 default:
1193 case 'x':
1194 max_digits = (wsize * 8) / 4;
1195 break;
1196 case 'u':
1197 case 'd':
1198 max_digits = (wsize * 8 * 10 + 32) / 33;
1199 break;
1200 case 'c':
1201 wsize = 1;
1202 break;
1205 while (len > 0) {
1206 if (is_physical)
1207 monitor_printf(mon, TARGET_FMT_plx ":", addr);
1208 else
1209 monitor_printf(mon, TARGET_FMT_lx ":", (target_ulong)addr);
1210 l = len;
1211 if (l > line_size)
1212 l = line_size;
1213 if (is_physical) {
1214 cpu_physical_memory_read(addr, buf, l);
1215 } else {
1216 env = mon_get_cpu();
1217 if (cpu_memory_rw_debug(ENV_GET_CPU(env), addr, buf, l, 0) < 0) {
1218 monitor_printf(mon, " Cannot access memory\n");
1219 break;
1222 i = 0;
1223 while (i < l) {
1224 switch(wsize) {
1225 default:
1226 case 1:
1227 v = ldub_p(buf + i);
1228 break;
1229 case 2:
1230 v = lduw_p(buf + i);
1231 break;
1232 case 4:
1233 v = (uint32_t)ldl_p(buf + i);
1234 break;
1235 case 8:
1236 v = ldq_p(buf + i);
1237 break;
1239 monitor_printf(mon, " ");
1240 switch(format) {
1241 case 'o':
1242 monitor_printf(mon, "%#*" PRIo64, max_digits, v);
1243 break;
1244 case 'x':
1245 monitor_printf(mon, "0x%0*" PRIx64, max_digits, v);
1246 break;
1247 case 'u':
1248 monitor_printf(mon, "%*" PRIu64, max_digits, v);
1249 break;
1250 case 'd':
1251 monitor_printf(mon, "%*" PRId64, max_digits, v);
1252 break;
1253 case 'c':
1254 monitor_printc(mon, v);
1255 break;
1257 i += wsize;
1259 monitor_printf(mon, "\n");
1260 addr += l;
1261 len -= l;
1265 static void hmp_memory_dump(Monitor *mon, const QDict *qdict)
1267 int count = qdict_get_int(qdict, "count");
1268 int format = qdict_get_int(qdict, "format");
1269 int size = qdict_get_int(qdict, "size");
1270 target_long addr = qdict_get_int(qdict, "addr");
1272 memory_dump(mon, count, format, size, addr, 0);
1275 static void hmp_physical_memory_dump(Monitor *mon, const QDict *qdict)
1277 int count = qdict_get_int(qdict, "count");
1278 int format = qdict_get_int(qdict, "format");
1279 int size = qdict_get_int(qdict, "size");
1280 hwaddr addr = qdict_get_int(qdict, "addr");
1282 memory_dump(mon, count, format, size, addr, 1);
1285 static void do_print(Monitor *mon, const QDict *qdict)
1287 int format = qdict_get_int(qdict, "format");
1288 hwaddr val = qdict_get_int(qdict, "val");
1290 switch(format) {
1291 case 'o':
1292 monitor_printf(mon, "%#" HWADDR_PRIo, val);
1293 break;
1294 case 'x':
1295 monitor_printf(mon, "%#" HWADDR_PRIx, val);
1296 break;
1297 case 'u':
1298 monitor_printf(mon, "%" HWADDR_PRIu, val);
1299 break;
1300 default:
1301 case 'd':
1302 monitor_printf(mon, "%" HWADDR_PRId, val);
1303 break;
1304 case 'c':
1305 monitor_printc(mon, val);
1306 break;
1308 monitor_printf(mon, "\n");
1311 static void hmp_sum(Monitor *mon, const QDict *qdict)
1313 uint32_t addr;
1314 uint16_t sum;
1315 uint32_t start = qdict_get_int(qdict, "start");
1316 uint32_t size = qdict_get_int(qdict, "size");
1318 sum = 0;
1319 for(addr = start; addr < (start + size); addr++) {
1320 uint8_t val = address_space_ldub(&address_space_memory, addr,
1321 MEMTXATTRS_UNSPECIFIED, NULL);
1322 /* BSD sum algorithm ('sum' Unix command) */
1323 sum = (sum >> 1) | (sum << 15);
1324 sum += val;
1326 monitor_printf(mon, "%05d\n", sum);
1329 static int mouse_button_state;
1331 static void hmp_mouse_move(Monitor *mon, const QDict *qdict)
1333 int dx, dy, dz, button;
1334 const char *dx_str = qdict_get_str(qdict, "dx_str");
1335 const char *dy_str = qdict_get_str(qdict, "dy_str");
1336 const char *dz_str = qdict_get_try_str(qdict, "dz_str");
1338 dx = strtol(dx_str, NULL, 0);
1339 dy = strtol(dy_str, NULL, 0);
1340 qemu_input_queue_rel(NULL, INPUT_AXIS_X, dx);
1341 qemu_input_queue_rel(NULL, INPUT_AXIS_Y, dy);
1343 if (dz_str) {
1344 dz = strtol(dz_str, NULL, 0);
1345 if (dz != 0) {
1346 button = (dz > 0) ? INPUT_BUTTON_WHEEL_UP : INPUT_BUTTON_WHEEL_DOWN;
1347 qemu_input_queue_btn(NULL, button, true);
1348 qemu_input_event_sync();
1349 qemu_input_queue_btn(NULL, button, false);
1352 qemu_input_event_sync();
1355 static void hmp_mouse_button(Monitor *mon, const QDict *qdict)
1357 static uint32_t bmap[INPUT_BUTTON_MAX] = {
1358 [INPUT_BUTTON_LEFT] = MOUSE_EVENT_LBUTTON,
1359 [INPUT_BUTTON_MIDDLE] = MOUSE_EVENT_MBUTTON,
1360 [INPUT_BUTTON_RIGHT] = MOUSE_EVENT_RBUTTON,
1362 int button_state = qdict_get_int(qdict, "button_state");
1364 if (mouse_button_state == button_state) {
1365 return;
1367 qemu_input_update_buttons(NULL, bmap, mouse_button_state, button_state);
1368 qemu_input_event_sync();
1369 mouse_button_state = button_state;
1372 static void hmp_ioport_read(Monitor *mon, const QDict *qdict)
1374 int size = qdict_get_int(qdict, "size");
1375 int addr = qdict_get_int(qdict, "addr");
1376 int has_index = qdict_haskey(qdict, "index");
1377 uint32_t val;
1378 int suffix;
1380 if (has_index) {
1381 int index = qdict_get_int(qdict, "index");
1382 cpu_outb(addr & IOPORTS_MASK, index & 0xff);
1383 addr++;
1385 addr &= 0xffff;
1387 switch(size) {
1388 default:
1389 case 1:
1390 val = cpu_inb(addr);
1391 suffix = 'b';
1392 break;
1393 case 2:
1394 val = cpu_inw(addr);
1395 suffix = 'w';
1396 break;
1397 case 4:
1398 val = cpu_inl(addr);
1399 suffix = 'l';
1400 break;
1402 monitor_printf(mon, "port%c[0x%04x] = %#0*x\n",
1403 suffix, addr, size * 2, val);
1406 static void hmp_ioport_write(Monitor *mon, const QDict *qdict)
1408 int size = qdict_get_int(qdict, "size");
1409 int addr = qdict_get_int(qdict, "addr");
1410 int val = qdict_get_int(qdict, "val");
1412 addr &= IOPORTS_MASK;
1414 switch (size) {
1415 default:
1416 case 1:
1417 cpu_outb(addr, val);
1418 break;
1419 case 2:
1420 cpu_outw(addr, val);
1421 break;
1422 case 4:
1423 cpu_outl(addr, val);
1424 break;
1428 static void hmp_boot_set(Monitor *mon, const QDict *qdict)
1430 Error *local_err = NULL;
1431 const char *bootdevice = qdict_get_str(qdict, "bootdevice");
1433 qemu_boot_set(bootdevice, &local_err);
1434 if (local_err) {
1435 monitor_printf(mon, "%s\n", error_get_pretty(local_err));
1436 error_free(local_err);
1437 } else {
1438 monitor_printf(mon, "boot device list now set to %s\n", bootdevice);
1442 #if defined(TARGET_I386)
1443 static void print_pte(Monitor *mon, hwaddr addr,
1444 hwaddr pte,
1445 hwaddr mask)
1447 #ifdef TARGET_X86_64
1448 if (addr & (1ULL << 47)) {
1449 addr |= -1LL << 48;
1451 #endif
1452 monitor_printf(mon, TARGET_FMT_plx ": " TARGET_FMT_plx
1453 " %c%c%c%c%c%c%c%c%c\n",
1454 addr,
1455 pte & mask,
1456 pte & PG_NX_MASK ? 'X' : '-',
1457 pte & PG_GLOBAL_MASK ? 'G' : '-',
1458 pte & PG_PSE_MASK ? 'P' : '-',
1459 pte & PG_DIRTY_MASK ? 'D' : '-',
1460 pte & PG_ACCESSED_MASK ? 'A' : '-',
1461 pte & PG_PCD_MASK ? 'C' : '-',
1462 pte & PG_PWT_MASK ? 'T' : '-',
1463 pte & PG_USER_MASK ? 'U' : '-',
1464 pte & PG_RW_MASK ? 'W' : '-');
1467 static void tlb_info_32(Monitor *mon, CPUArchState *env)
1469 unsigned int l1, l2;
1470 uint32_t pgd, pde, pte;
1472 pgd = env->cr[3] & ~0xfff;
1473 for(l1 = 0; l1 < 1024; l1++) {
1474 cpu_physical_memory_read(pgd + l1 * 4, &pde, 4);
1475 pde = le32_to_cpu(pde);
1476 if (pde & PG_PRESENT_MASK) {
1477 if ((pde & PG_PSE_MASK) && (env->cr[4] & CR4_PSE_MASK)) {
1478 /* 4M pages */
1479 print_pte(mon, (l1 << 22), pde, ~((1 << 21) - 1));
1480 } else {
1481 for(l2 = 0; l2 < 1024; l2++) {
1482 cpu_physical_memory_read((pde & ~0xfff) + l2 * 4, &pte, 4);
1483 pte = le32_to_cpu(pte);
1484 if (pte & PG_PRESENT_MASK) {
1485 print_pte(mon, (l1 << 22) + (l2 << 12),
1486 pte & ~PG_PSE_MASK,
1487 ~0xfff);
1495 static void tlb_info_pae32(Monitor *mon, CPUArchState *env)
1497 unsigned int l1, l2, l3;
1498 uint64_t pdpe, pde, pte;
1499 uint64_t pdp_addr, pd_addr, pt_addr;
1501 pdp_addr = env->cr[3] & ~0x1f;
1502 for (l1 = 0; l1 < 4; l1++) {
1503 cpu_physical_memory_read(pdp_addr + l1 * 8, &pdpe, 8);
1504 pdpe = le64_to_cpu(pdpe);
1505 if (pdpe & PG_PRESENT_MASK) {
1506 pd_addr = pdpe & 0x3fffffffff000ULL;
1507 for (l2 = 0; l2 < 512; l2++) {
1508 cpu_physical_memory_read(pd_addr + l2 * 8, &pde, 8);
1509 pde = le64_to_cpu(pde);
1510 if (pde & PG_PRESENT_MASK) {
1511 if (pde & PG_PSE_MASK) {
1512 /* 2M pages with PAE, CR4.PSE is ignored */
1513 print_pte(mon, (l1 << 30 ) + (l2 << 21), pde,
1514 ~((hwaddr)(1 << 20) - 1));
1515 } else {
1516 pt_addr = pde & 0x3fffffffff000ULL;
1517 for (l3 = 0; l3 < 512; l3++) {
1518 cpu_physical_memory_read(pt_addr + l3 * 8, &pte, 8);
1519 pte = le64_to_cpu(pte);
1520 if (pte & PG_PRESENT_MASK) {
1521 print_pte(mon, (l1 << 30 ) + (l2 << 21)
1522 + (l3 << 12),
1523 pte & ~PG_PSE_MASK,
1524 ~(hwaddr)0xfff);
1534 #ifdef TARGET_X86_64
1535 static void tlb_info_64(Monitor *mon, CPUArchState *env)
1537 uint64_t l1, l2, l3, l4;
1538 uint64_t pml4e, pdpe, pde, pte;
1539 uint64_t pml4_addr, pdp_addr, pd_addr, pt_addr;
1541 pml4_addr = env->cr[3] & 0x3fffffffff000ULL;
1542 for (l1 = 0; l1 < 512; l1++) {
1543 cpu_physical_memory_read(pml4_addr + l1 * 8, &pml4e, 8);
1544 pml4e = le64_to_cpu(pml4e);
1545 if (pml4e & PG_PRESENT_MASK) {
1546 pdp_addr = pml4e & 0x3fffffffff000ULL;
1547 for (l2 = 0; l2 < 512; l2++) {
1548 cpu_physical_memory_read(pdp_addr + l2 * 8, &pdpe, 8);
1549 pdpe = le64_to_cpu(pdpe);
1550 if (pdpe & PG_PRESENT_MASK) {
1551 if (pdpe & PG_PSE_MASK) {
1552 /* 1G pages, CR4.PSE is ignored */
1553 print_pte(mon, (l1 << 39) + (l2 << 30), pdpe,
1554 0x3ffffc0000000ULL);
1555 } else {
1556 pd_addr = pdpe & 0x3fffffffff000ULL;
1557 for (l3 = 0; l3 < 512; l3++) {
1558 cpu_physical_memory_read(pd_addr + l3 * 8, &pde, 8);
1559 pde = le64_to_cpu(pde);
1560 if (pde & PG_PRESENT_MASK) {
1561 if (pde & PG_PSE_MASK) {
1562 /* 2M pages, CR4.PSE is ignored */
1563 print_pte(mon, (l1 << 39) + (l2 << 30) +
1564 (l3 << 21), pde,
1565 0x3ffffffe00000ULL);
1566 } else {
1567 pt_addr = pde & 0x3fffffffff000ULL;
1568 for (l4 = 0; l4 < 512; l4++) {
1569 cpu_physical_memory_read(pt_addr
1570 + l4 * 8,
1571 &pte, 8);
1572 pte = le64_to_cpu(pte);
1573 if (pte & PG_PRESENT_MASK) {
1574 print_pte(mon, (l1 << 39) +
1575 (l2 << 30) +
1576 (l3 << 21) + (l4 << 12),
1577 pte & ~PG_PSE_MASK,
1578 0x3fffffffff000ULL);
1590 #endif
1592 static void hmp_info_tlb(Monitor *mon, const QDict *qdict)
1594 CPUArchState *env;
1596 env = mon_get_cpu();
1598 if (!(env->cr[0] & CR0_PG_MASK)) {
1599 monitor_printf(mon, "PG disabled\n");
1600 return;
1602 if (env->cr[4] & CR4_PAE_MASK) {
1603 #ifdef TARGET_X86_64
1604 if (env->hflags & HF_LMA_MASK) {
1605 tlb_info_64(mon, env);
1606 } else
1607 #endif
1609 tlb_info_pae32(mon, env);
1611 } else {
1612 tlb_info_32(mon, env);
1616 static void mem_print(Monitor *mon, hwaddr *pstart,
1617 int *plast_prot,
1618 hwaddr end, int prot)
1620 int prot1;
1621 prot1 = *plast_prot;
1622 if (prot != prot1) {
1623 if (*pstart != -1) {
1624 monitor_printf(mon, TARGET_FMT_plx "-" TARGET_FMT_plx " "
1625 TARGET_FMT_plx " %c%c%c\n",
1626 *pstart, end, end - *pstart,
1627 prot1 & PG_USER_MASK ? 'u' : '-',
1628 'r',
1629 prot1 & PG_RW_MASK ? 'w' : '-');
1631 if (prot != 0)
1632 *pstart = end;
1633 else
1634 *pstart = -1;
1635 *plast_prot = prot;
1639 static void mem_info_32(Monitor *mon, CPUArchState *env)
1641 unsigned int l1, l2;
1642 int prot, last_prot;
1643 uint32_t pgd, pde, pte;
1644 hwaddr start, end;
1646 pgd = env->cr[3] & ~0xfff;
1647 last_prot = 0;
1648 start = -1;
1649 for(l1 = 0; l1 < 1024; l1++) {
1650 cpu_physical_memory_read(pgd + l1 * 4, &pde, 4);
1651 pde = le32_to_cpu(pde);
1652 end = l1 << 22;
1653 if (pde & PG_PRESENT_MASK) {
1654 if ((pde & PG_PSE_MASK) && (env->cr[4] & CR4_PSE_MASK)) {
1655 prot = pde & (PG_USER_MASK | PG_RW_MASK | PG_PRESENT_MASK);
1656 mem_print(mon, &start, &last_prot, end, prot);
1657 } else {
1658 for(l2 = 0; l2 < 1024; l2++) {
1659 cpu_physical_memory_read((pde & ~0xfff) + l2 * 4, &pte, 4);
1660 pte = le32_to_cpu(pte);
1661 end = (l1 << 22) + (l2 << 12);
1662 if (pte & PG_PRESENT_MASK) {
1663 prot = pte & pde &
1664 (PG_USER_MASK | PG_RW_MASK | PG_PRESENT_MASK);
1665 } else {
1666 prot = 0;
1668 mem_print(mon, &start, &last_prot, end, prot);
1671 } else {
1672 prot = 0;
1673 mem_print(mon, &start, &last_prot, end, prot);
1676 /* Flush last range */
1677 mem_print(mon, &start, &last_prot, (hwaddr)1 << 32, 0);
1680 static void mem_info_pae32(Monitor *mon, CPUArchState *env)
1682 unsigned int l1, l2, l3;
1683 int prot, last_prot;
1684 uint64_t pdpe, pde, pte;
1685 uint64_t pdp_addr, pd_addr, pt_addr;
1686 hwaddr start, end;
1688 pdp_addr = env->cr[3] & ~0x1f;
1689 last_prot = 0;
1690 start = -1;
1691 for (l1 = 0; l1 < 4; l1++) {
1692 cpu_physical_memory_read(pdp_addr + l1 * 8, &pdpe, 8);
1693 pdpe = le64_to_cpu(pdpe);
1694 end = l1 << 30;
1695 if (pdpe & PG_PRESENT_MASK) {
1696 pd_addr = pdpe & 0x3fffffffff000ULL;
1697 for (l2 = 0; l2 < 512; l2++) {
1698 cpu_physical_memory_read(pd_addr + l2 * 8, &pde, 8);
1699 pde = le64_to_cpu(pde);
1700 end = (l1 << 30) + (l2 << 21);
1701 if (pde & PG_PRESENT_MASK) {
1702 if (pde & PG_PSE_MASK) {
1703 prot = pde & (PG_USER_MASK | PG_RW_MASK |
1704 PG_PRESENT_MASK);
1705 mem_print(mon, &start, &last_prot, end, prot);
1706 } else {
1707 pt_addr = pde & 0x3fffffffff000ULL;
1708 for (l3 = 0; l3 < 512; l3++) {
1709 cpu_physical_memory_read(pt_addr + l3 * 8, &pte, 8);
1710 pte = le64_to_cpu(pte);
1711 end = (l1 << 30) + (l2 << 21) + (l3 << 12);
1712 if (pte & PG_PRESENT_MASK) {
1713 prot = pte & pde & (PG_USER_MASK | PG_RW_MASK |
1714 PG_PRESENT_MASK);
1715 } else {
1716 prot = 0;
1718 mem_print(mon, &start, &last_prot, end, prot);
1721 } else {
1722 prot = 0;
1723 mem_print(mon, &start, &last_prot, end, prot);
1726 } else {
1727 prot = 0;
1728 mem_print(mon, &start, &last_prot, end, prot);
1731 /* Flush last range */
1732 mem_print(mon, &start, &last_prot, (hwaddr)1 << 32, 0);
1736 #ifdef TARGET_X86_64
1737 static void mem_info_64(Monitor *mon, CPUArchState *env)
1739 int prot, last_prot;
1740 uint64_t l1, l2, l3, l4;
1741 uint64_t pml4e, pdpe, pde, pte;
1742 uint64_t pml4_addr, pdp_addr, pd_addr, pt_addr, start, end;
1744 pml4_addr = env->cr[3] & 0x3fffffffff000ULL;
1745 last_prot = 0;
1746 start = -1;
1747 for (l1 = 0; l1 < 512; l1++) {
1748 cpu_physical_memory_read(pml4_addr + l1 * 8, &pml4e, 8);
1749 pml4e = le64_to_cpu(pml4e);
1750 end = l1 << 39;
1751 if (pml4e & PG_PRESENT_MASK) {
1752 pdp_addr = pml4e & 0x3fffffffff000ULL;
1753 for (l2 = 0; l2 < 512; l2++) {
1754 cpu_physical_memory_read(pdp_addr + l2 * 8, &pdpe, 8);
1755 pdpe = le64_to_cpu(pdpe);
1756 end = (l1 << 39) + (l2 << 30);
1757 if (pdpe & PG_PRESENT_MASK) {
1758 if (pdpe & PG_PSE_MASK) {
1759 prot = pdpe & (PG_USER_MASK | PG_RW_MASK |
1760 PG_PRESENT_MASK);
1761 prot &= pml4e;
1762 mem_print(mon, &start, &last_prot, end, prot);
1763 } else {
1764 pd_addr = pdpe & 0x3fffffffff000ULL;
1765 for (l3 = 0; l3 < 512; l3++) {
1766 cpu_physical_memory_read(pd_addr + l3 * 8, &pde, 8);
1767 pde = le64_to_cpu(pde);
1768 end = (l1 << 39) + (l2 << 30) + (l3 << 21);
1769 if (pde & PG_PRESENT_MASK) {
1770 if (pde & PG_PSE_MASK) {
1771 prot = pde & (PG_USER_MASK | PG_RW_MASK |
1772 PG_PRESENT_MASK);
1773 prot &= pml4e & pdpe;
1774 mem_print(mon, &start, &last_prot, end, prot);
1775 } else {
1776 pt_addr = pde & 0x3fffffffff000ULL;
1777 for (l4 = 0; l4 < 512; l4++) {
1778 cpu_physical_memory_read(pt_addr
1779 + l4 * 8,
1780 &pte, 8);
1781 pte = le64_to_cpu(pte);
1782 end = (l1 << 39) + (l2 << 30) +
1783 (l3 << 21) + (l4 << 12);
1784 if (pte & PG_PRESENT_MASK) {
1785 prot = pte & (PG_USER_MASK | PG_RW_MASK |
1786 PG_PRESENT_MASK);
1787 prot &= pml4e & pdpe & pde;
1788 } else {
1789 prot = 0;
1791 mem_print(mon, &start, &last_prot, end, prot);
1794 } else {
1795 prot = 0;
1796 mem_print(mon, &start, &last_prot, end, prot);
1800 } else {
1801 prot = 0;
1802 mem_print(mon, &start, &last_prot, end, prot);
1805 } else {
1806 prot = 0;
1807 mem_print(mon, &start, &last_prot, end, prot);
1810 /* Flush last range */
1811 mem_print(mon, &start, &last_prot, (hwaddr)1 << 48, 0);
1813 #endif
1815 static void hmp_info_mem(Monitor *mon, const QDict *qdict)
1817 CPUArchState *env;
1819 env = mon_get_cpu();
1821 if (!(env->cr[0] & CR0_PG_MASK)) {
1822 monitor_printf(mon, "PG disabled\n");
1823 return;
1825 if (env->cr[4] & CR4_PAE_MASK) {
1826 #ifdef TARGET_X86_64
1827 if (env->hflags & HF_LMA_MASK) {
1828 mem_info_64(mon, env);
1829 } else
1830 #endif
1832 mem_info_pae32(mon, env);
1834 } else {
1835 mem_info_32(mon, env);
1838 #endif
1840 #if defined(TARGET_SH4)
1842 static void print_tlb(Monitor *mon, int idx, tlb_t *tlb)
1844 monitor_printf(mon, " tlb%i:\t"
1845 "asid=%hhu vpn=%x\tppn=%x\tsz=%hhu size=%u\t"
1846 "v=%hhu shared=%hhu cached=%hhu prot=%hhu "
1847 "dirty=%hhu writethrough=%hhu\n",
1848 idx,
1849 tlb->asid, tlb->vpn, tlb->ppn, tlb->sz, tlb->size,
1850 tlb->v, tlb->sh, tlb->c, tlb->pr,
1851 tlb->d, tlb->wt);
1854 static void hmp_info_tlb(Monitor *mon, const QDict *qdict)
1856 CPUArchState *env = mon_get_cpu();
1857 int i;
1859 monitor_printf (mon, "ITLB:\n");
1860 for (i = 0 ; i < ITLB_SIZE ; i++)
1861 print_tlb (mon, i, &env->itlb[i]);
1862 monitor_printf (mon, "UTLB:\n");
1863 for (i = 0 ; i < UTLB_SIZE ; i++)
1864 print_tlb (mon, i, &env->utlb[i]);
1867 #endif
1869 #if defined(TARGET_SPARC) || defined(TARGET_PPC) || defined(TARGET_XTENSA)
1870 static void hmp_info_tlb(Monitor *mon, const QDict *qdict)
1872 CPUArchState *env1 = mon_get_cpu();
1874 dump_mmu((FILE*)mon, (fprintf_function)monitor_printf, env1);
1876 #endif
1878 static void hmp_info_mtree(Monitor *mon, const QDict *qdict)
1880 mtree_info((fprintf_function)monitor_printf, mon);
1883 static void hmp_info_numa(Monitor *mon, const QDict *qdict)
1885 int i;
1886 CPUState *cpu;
1887 uint64_t *node_mem;
1889 node_mem = g_new0(uint64_t, nb_numa_nodes);
1890 query_numa_node_mem(node_mem);
1891 monitor_printf(mon, "%d nodes\n", nb_numa_nodes);
1892 for (i = 0; i < nb_numa_nodes; i++) {
1893 monitor_printf(mon, "node %d cpus:", i);
1894 CPU_FOREACH(cpu) {
1895 if (cpu->numa_node == i) {
1896 monitor_printf(mon, " %d", cpu->cpu_index);
1899 monitor_printf(mon, "\n");
1900 monitor_printf(mon, "node %d size: %" PRId64 " MB\n", i,
1901 node_mem[i] >> 20);
1903 g_free(node_mem);
1906 #ifdef CONFIG_PROFILER
1908 int64_t tcg_time;
1909 int64_t dev_time;
1911 static void hmp_info_profile(Monitor *mon, const QDict *qdict)
1913 monitor_printf(mon, "async time %" PRId64 " (%0.3f)\n",
1914 dev_time, dev_time / (double)get_ticks_per_sec());
1915 monitor_printf(mon, "qemu time %" PRId64 " (%0.3f)\n",
1916 tcg_time, tcg_time / (double)get_ticks_per_sec());
1917 tcg_time = 0;
1918 dev_time = 0;
1920 #else
1921 static void hmp_info_profile(Monitor *mon, const QDict *qdict)
1923 monitor_printf(mon, "Internal profiler not compiled\n");
1925 #endif
1927 /* Capture support */
1928 static QLIST_HEAD (capture_list_head, CaptureState) capture_head;
1930 static void hmp_info_capture(Monitor *mon, const QDict *qdict)
1932 int i;
1933 CaptureState *s;
1935 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
1936 monitor_printf(mon, "[%d]: ", i);
1937 s->ops.info (s->opaque);
1941 static void hmp_stopcapture(Monitor *mon, const QDict *qdict)
1943 int i;
1944 int n = qdict_get_int(qdict, "n");
1945 CaptureState *s;
1947 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
1948 if (i == n) {
1949 s->ops.destroy (s->opaque);
1950 QLIST_REMOVE (s, entries);
1951 g_free (s);
1952 return;
1957 static void hmp_wavcapture(Monitor *mon, const QDict *qdict)
1959 const char *path = qdict_get_str(qdict, "path");
1960 int has_freq = qdict_haskey(qdict, "freq");
1961 int freq = qdict_get_try_int(qdict, "freq", -1);
1962 int has_bits = qdict_haskey(qdict, "bits");
1963 int bits = qdict_get_try_int(qdict, "bits", -1);
1964 int has_channels = qdict_haskey(qdict, "nchannels");
1965 int nchannels = qdict_get_try_int(qdict, "nchannels", -1);
1966 CaptureState *s;
1968 s = g_malloc0 (sizeof (*s));
1970 freq = has_freq ? freq : 44100;
1971 bits = has_bits ? bits : 16;
1972 nchannels = has_channels ? nchannels : 2;
1974 if (wav_start_capture (s, path, freq, bits, nchannels)) {
1975 monitor_printf(mon, "Failed to add wave capture\n");
1976 g_free (s);
1977 return;
1979 QLIST_INSERT_HEAD (&capture_head, s, entries);
1982 static qemu_acl *find_acl(Monitor *mon, const char *name)
1984 qemu_acl *acl = qemu_acl_find(name);
1986 if (!acl) {
1987 monitor_printf(mon, "acl: unknown list '%s'\n", name);
1989 return acl;
1992 static void hmp_acl_show(Monitor *mon, const QDict *qdict)
1994 const char *aclname = qdict_get_str(qdict, "aclname");
1995 qemu_acl *acl = find_acl(mon, aclname);
1996 qemu_acl_entry *entry;
1997 int i = 0;
1999 if (acl) {
2000 monitor_printf(mon, "policy: %s\n",
2001 acl->defaultDeny ? "deny" : "allow");
2002 QTAILQ_FOREACH(entry, &acl->entries, next) {
2003 i++;
2004 monitor_printf(mon, "%d: %s %s\n", i,
2005 entry->deny ? "deny" : "allow", entry->match);
2010 static void hmp_acl_reset(Monitor *mon, const QDict *qdict)
2012 const char *aclname = qdict_get_str(qdict, "aclname");
2013 qemu_acl *acl = find_acl(mon, aclname);
2015 if (acl) {
2016 qemu_acl_reset(acl);
2017 monitor_printf(mon, "acl: removed all rules\n");
2021 static void hmp_acl_policy(Monitor *mon, const QDict *qdict)
2023 const char *aclname = qdict_get_str(qdict, "aclname");
2024 const char *policy = qdict_get_str(qdict, "policy");
2025 qemu_acl *acl = find_acl(mon, aclname);
2027 if (acl) {
2028 if (strcmp(policy, "allow") == 0) {
2029 acl->defaultDeny = 0;
2030 monitor_printf(mon, "acl: policy set to 'allow'\n");
2031 } else if (strcmp(policy, "deny") == 0) {
2032 acl->defaultDeny = 1;
2033 monitor_printf(mon, "acl: policy set to 'deny'\n");
2034 } else {
2035 monitor_printf(mon, "acl: unknown policy '%s', "
2036 "expected 'deny' or 'allow'\n", policy);
2041 static void hmp_acl_add(Monitor *mon, const QDict *qdict)
2043 const char *aclname = qdict_get_str(qdict, "aclname");
2044 const char *match = qdict_get_str(qdict, "match");
2045 const char *policy = qdict_get_str(qdict, "policy");
2046 int has_index = qdict_haskey(qdict, "index");
2047 int index = qdict_get_try_int(qdict, "index", -1);
2048 qemu_acl *acl = find_acl(mon, aclname);
2049 int deny, ret;
2051 if (acl) {
2052 if (strcmp(policy, "allow") == 0) {
2053 deny = 0;
2054 } else if (strcmp(policy, "deny") == 0) {
2055 deny = 1;
2056 } else {
2057 monitor_printf(mon, "acl: unknown policy '%s', "
2058 "expected 'deny' or 'allow'\n", policy);
2059 return;
2061 if (has_index)
2062 ret = qemu_acl_insert(acl, deny, match, index);
2063 else
2064 ret = qemu_acl_append(acl, deny, match);
2065 if (ret < 0)
2066 monitor_printf(mon, "acl: unable to add acl entry\n");
2067 else
2068 monitor_printf(mon, "acl: added rule at position %d\n", ret);
2072 static void hmp_acl_remove(Monitor *mon, const QDict *qdict)
2074 const char *aclname = qdict_get_str(qdict, "aclname");
2075 const char *match = qdict_get_str(qdict, "match");
2076 qemu_acl *acl = find_acl(mon, aclname);
2077 int ret;
2079 if (acl) {
2080 ret = qemu_acl_remove(acl, match);
2081 if (ret < 0)
2082 monitor_printf(mon, "acl: no matching acl entry\n");
2083 else
2084 monitor_printf(mon, "acl: removed rule at position %d\n", ret);
2088 #if defined(TARGET_I386)
2089 static void hmp_mce(Monitor *mon, const QDict *qdict)
2091 X86CPU *cpu;
2092 CPUState *cs;
2093 int cpu_index = qdict_get_int(qdict, "cpu_index");
2094 int bank = qdict_get_int(qdict, "bank");
2095 uint64_t status = qdict_get_int(qdict, "status");
2096 uint64_t mcg_status = qdict_get_int(qdict, "mcg_status");
2097 uint64_t addr = qdict_get_int(qdict, "addr");
2098 uint64_t misc = qdict_get_int(qdict, "misc");
2099 int flags = MCE_INJECT_UNCOND_AO;
2101 if (qdict_get_try_bool(qdict, "broadcast", 0)) {
2102 flags |= MCE_INJECT_BROADCAST;
2104 cs = qemu_get_cpu(cpu_index);
2105 if (cs != NULL) {
2106 cpu = X86_CPU(cs);
2107 cpu_x86_inject_mce(mon, cpu, bank, status, mcg_status, addr, misc,
2108 flags);
2111 #endif
2113 void qmp_getfd(const char *fdname, Error **errp)
2115 mon_fd_t *monfd;
2116 int fd;
2118 fd = qemu_chr_fe_get_msgfd(cur_mon->chr);
2119 if (fd == -1) {
2120 error_set(errp, QERR_FD_NOT_SUPPLIED);
2121 return;
2124 if (qemu_isdigit(fdname[0])) {
2125 close(fd);
2126 error_set(errp, QERR_INVALID_PARAMETER_VALUE, "fdname",
2127 "a name not starting with a digit");
2128 return;
2131 QLIST_FOREACH(monfd, &cur_mon->fds, next) {
2132 if (strcmp(monfd->name, fdname) != 0) {
2133 continue;
2136 close(monfd->fd);
2137 monfd->fd = fd;
2138 return;
2141 monfd = g_malloc0(sizeof(mon_fd_t));
2142 monfd->name = g_strdup(fdname);
2143 monfd->fd = fd;
2145 QLIST_INSERT_HEAD(&cur_mon->fds, monfd, next);
2148 void qmp_closefd(const char *fdname, Error **errp)
2150 mon_fd_t *monfd;
2152 QLIST_FOREACH(monfd, &cur_mon->fds, next) {
2153 if (strcmp(monfd->name, fdname) != 0) {
2154 continue;
2157 QLIST_REMOVE(monfd, next);
2158 close(monfd->fd);
2159 g_free(monfd->name);
2160 g_free(monfd);
2161 return;
2164 error_set(errp, QERR_FD_NOT_FOUND, fdname);
2167 static void hmp_loadvm(Monitor *mon, const QDict *qdict)
2169 int saved_vm_running = runstate_is_running();
2170 const char *name = qdict_get_str(qdict, "name");
2172 vm_stop(RUN_STATE_RESTORE_VM);
2174 if (load_vmstate(name) == 0 && saved_vm_running) {
2175 vm_start();
2179 int monitor_get_fd(Monitor *mon, const char *fdname, Error **errp)
2181 mon_fd_t *monfd;
2183 QLIST_FOREACH(monfd, &mon->fds, next) {
2184 int fd;
2186 if (strcmp(monfd->name, fdname) != 0) {
2187 continue;
2190 fd = monfd->fd;
2192 /* caller takes ownership of fd */
2193 QLIST_REMOVE(monfd, next);
2194 g_free(monfd->name);
2195 g_free(monfd);
2197 return fd;
2200 error_setg(errp, "File descriptor named '%s' has not been found", fdname);
2201 return -1;
2204 static void monitor_fdset_cleanup(MonFdset *mon_fdset)
2206 MonFdsetFd *mon_fdset_fd;
2207 MonFdsetFd *mon_fdset_fd_next;
2209 QLIST_FOREACH_SAFE(mon_fdset_fd, &mon_fdset->fds, next, mon_fdset_fd_next) {
2210 if ((mon_fdset_fd->removed ||
2211 (QLIST_EMPTY(&mon_fdset->dup_fds) && mon_refcount == 0)) &&
2212 runstate_is_running()) {
2213 close(mon_fdset_fd->fd);
2214 g_free(mon_fdset_fd->opaque);
2215 QLIST_REMOVE(mon_fdset_fd, next);
2216 g_free(mon_fdset_fd);
2220 if (QLIST_EMPTY(&mon_fdset->fds) && QLIST_EMPTY(&mon_fdset->dup_fds)) {
2221 QLIST_REMOVE(mon_fdset, next);
2222 g_free(mon_fdset);
2226 static void monitor_fdsets_cleanup(void)
2228 MonFdset *mon_fdset;
2229 MonFdset *mon_fdset_next;
2231 QLIST_FOREACH_SAFE(mon_fdset, &mon_fdsets, next, mon_fdset_next) {
2232 monitor_fdset_cleanup(mon_fdset);
2236 AddfdInfo *qmp_add_fd(bool has_fdset_id, int64_t fdset_id, bool has_opaque,
2237 const char *opaque, Error **errp)
2239 int fd;
2240 Monitor *mon = cur_mon;
2241 AddfdInfo *fdinfo;
2243 fd = qemu_chr_fe_get_msgfd(mon->chr);
2244 if (fd == -1) {
2245 error_set(errp, QERR_FD_NOT_SUPPLIED);
2246 goto error;
2249 fdinfo = monitor_fdset_add_fd(fd, has_fdset_id, fdset_id,
2250 has_opaque, opaque, errp);
2251 if (fdinfo) {
2252 return fdinfo;
2255 error:
2256 if (fd != -1) {
2257 close(fd);
2259 return NULL;
2262 void qmp_remove_fd(int64_t fdset_id, bool has_fd, int64_t fd, Error **errp)
2264 MonFdset *mon_fdset;
2265 MonFdsetFd *mon_fdset_fd;
2266 char fd_str[60];
2268 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2269 if (mon_fdset->id != fdset_id) {
2270 continue;
2272 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2273 if (has_fd) {
2274 if (mon_fdset_fd->fd != fd) {
2275 continue;
2277 mon_fdset_fd->removed = true;
2278 break;
2279 } else {
2280 mon_fdset_fd->removed = true;
2283 if (has_fd && !mon_fdset_fd) {
2284 goto error;
2286 monitor_fdset_cleanup(mon_fdset);
2287 return;
2290 error:
2291 if (has_fd) {
2292 snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64 ", fd:%" PRId64,
2293 fdset_id, fd);
2294 } else {
2295 snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64, fdset_id);
2297 error_set(errp, QERR_FD_NOT_FOUND, fd_str);
2300 FdsetInfoList *qmp_query_fdsets(Error **errp)
2302 MonFdset *mon_fdset;
2303 MonFdsetFd *mon_fdset_fd;
2304 FdsetInfoList *fdset_list = NULL;
2306 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2307 FdsetInfoList *fdset_info = g_malloc0(sizeof(*fdset_info));
2308 FdsetFdInfoList *fdsetfd_list = NULL;
2310 fdset_info->value = g_malloc0(sizeof(*fdset_info->value));
2311 fdset_info->value->fdset_id = mon_fdset->id;
2313 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2314 FdsetFdInfoList *fdsetfd_info;
2316 fdsetfd_info = g_malloc0(sizeof(*fdsetfd_info));
2317 fdsetfd_info->value = g_malloc0(sizeof(*fdsetfd_info->value));
2318 fdsetfd_info->value->fd = mon_fdset_fd->fd;
2319 if (mon_fdset_fd->opaque) {
2320 fdsetfd_info->value->has_opaque = true;
2321 fdsetfd_info->value->opaque = g_strdup(mon_fdset_fd->opaque);
2322 } else {
2323 fdsetfd_info->value->has_opaque = false;
2326 fdsetfd_info->next = fdsetfd_list;
2327 fdsetfd_list = fdsetfd_info;
2330 fdset_info->value->fds = fdsetfd_list;
2332 fdset_info->next = fdset_list;
2333 fdset_list = fdset_info;
2336 return fdset_list;
2339 AddfdInfo *monitor_fdset_add_fd(int fd, bool has_fdset_id, int64_t fdset_id,
2340 bool has_opaque, const char *opaque,
2341 Error **errp)
2343 MonFdset *mon_fdset = NULL;
2344 MonFdsetFd *mon_fdset_fd;
2345 AddfdInfo *fdinfo;
2347 if (has_fdset_id) {
2348 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2349 /* Break if match found or match impossible due to ordering by ID */
2350 if (fdset_id <= mon_fdset->id) {
2351 if (fdset_id < mon_fdset->id) {
2352 mon_fdset = NULL;
2354 break;
2359 if (mon_fdset == NULL) {
2360 int64_t fdset_id_prev = -1;
2361 MonFdset *mon_fdset_cur = QLIST_FIRST(&mon_fdsets);
2363 if (has_fdset_id) {
2364 if (fdset_id < 0) {
2365 error_set(errp, QERR_INVALID_PARAMETER_VALUE, "fdset-id",
2366 "a non-negative value");
2367 return NULL;
2369 /* Use specified fdset ID */
2370 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2371 mon_fdset_cur = mon_fdset;
2372 if (fdset_id < mon_fdset_cur->id) {
2373 break;
2376 } else {
2377 /* Use first available fdset ID */
2378 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2379 mon_fdset_cur = mon_fdset;
2380 if (fdset_id_prev == mon_fdset_cur->id - 1) {
2381 fdset_id_prev = mon_fdset_cur->id;
2382 continue;
2384 break;
2388 mon_fdset = g_malloc0(sizeof(*mon_fdset));
2389 if (has_fdset_id) {
2390 mon_fdset->id = fdset_id;
2391 } else {
2392 mon_fdset->id = fdset_id_prev + 1;
2395 /* The fdset list is ordered by fdset ID */
2396 if (!mon_fdset_cur) {
2397 QLIST_INSERT_HEAD(&mon_fdsets, mon_fdset, next);
2398 } else if (mon_fdset->id < mon_fdset_cur->id) {
2399 QLIST_INSERT_BEFORE(mon_fdset_cur, mon_fdset, next);
2400 } else {
2401 QLIST_INSERT_AFTER(mon_fdset_cur, mon_fdset, next);
2405 mon_fdset_fd = g_malloc0(sizeof(*mon_fdset_fd));
2406 mon_fdset_fd->fd = fd;
2407 mon_fdset_fd->removed = false;
2408 if (has_opaque) {
2409 mon_fdset_fd->opaque = g_strdup(opaque);
2411 QLIST_INSERT_HEAD(&mon_fdset->fds, mon_fdset_fd, next);
2413 fdinfo = g_malloc0(sizeof(*fdinfo));
2414 fdinfo->fdset_id = mon_fdset->id;
2415 fdinfo->fd = mon_fdset_fd->fd;
2417 return fdinfo;
2420 int monitor_fdset_get_fd(int64_t fdset_id, int flags)
2422 #ifndef _WIN32
2423 MonFdset *mon_fdset;
2424 MonFdsetFd *mon_fdset_fd;
2425 int mon_fd_flags;
2427 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2428 if (mon_fdset->id != fdset_id) {
2429 continue;
2431 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2432 mon_fd_flags = fcntl(mon_fdset_fd->fd, F_GETFL);
2433 if (mon_fd_flags == -1) {
2434 return -1;
2437 if ((flags & O_ACCMODE) == (mon_fd_flags & O_ACCMODE)) {
2438 return mon_fdset_fd->fd;
2441 errno = EACCES;
2442 return -1;
2444 #endif
2446 errno = ENOENT;
2447 return -1;
2450 int monitor_fdset_dup_fd_add(int64_t fdset_id, int dup_fd)
2452 MonFdset *mon_fdset;
2453 MonFdsetFd *mon_fdset_fd_dup;
2455 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2456 if (mon_fdset->id != fdset_id) {
2457 continue;
2459 QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
2460 if (mon_fdset_fd_dup->fd == dup_fd) {
2461 return -1;
2464 mon_fdset_fd_dup = g_malloc0(sizeof(*mon_fdset_fd_dup));
2465 mon_fdset_fd_dup->fd = dup_fd;
2466 QLIST_INSERT_HEAD(&mon_fdset->dup_fds, mon_fdset_fd_dup, next);
2467 return 0;
2469 return -1;
2472 static int monitor_fdset_dup_fd_find_remove(int dup_fd, bool remove)
2474 MonFdset *mon_fdset;
2475 MonFdsetFd *mon_fdset_fd_dup;
2477 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2478 QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
2479 if (mon_fdset_fd_dup->fd == dup_fd) {
2480 if (remove) {
2481 QLIST_REMOVE(mon_fdset_fd_dup, next);
2482 if (QLIST_EMPTY(&mon_fdset->dup_fds)) {
2483 monitor_fdset_cleanup(mon_fdset);
2485 return -1;
2486 } else {
2487 return mon_fdset->id;
2492 return -1;
2495 int monitor_fdset_dup_fd_find(int dup_fd)
2497 return monitor_fdset_dup_fd_find_remove(dup_fd, false);
2500 void monitor_fdset_dup_fd_remove(int dup_fd)
2502 monitor_fdset_dup_fd_find_remove(dup_fd, true);
2505 int monitor_fd_param(Monitor *mon, const char *fdname, Error **errp)
2507 int fd;
2508 Error *local_err = NULL;
2510 if (!qemu_isdigit(fdname[0]) && mon) {
2511 fd = monitor_get_fd(mon, fdname, &local_err);
2512 } else {
2513 fd = qemu_parse_fd(fdname);
2514 if (fd == -1) {
2515 error_setg(&local_err, "Invalid file descriptor number '%s'",
2516 fdname);
2519 if (local_err) {
2520 error_propagate(errp, local_err);
2521 assert(fd == -1);
2522 } else {
2523 assert(fd != -1);
2526 return fd;
2529 /* Please update hmp-commands.hx when adding or changing commands */
2530 static mon_cmd_t info_cmds[] = {
2532 .name = "version",
2533 .args_type = "",
2534 .params = "",
2535 .help = "show the version of QEMU",
2536 .mhandler.cmd = hmp_info_version,
2539 .name = "network",
2540 .args_type = "",
2541 .params = "",
2542 .help = "show the network state",
2543 .mhandler.cmd = hmp_info_network,
2546 .name = "chardev",
2547 .args_type = "",
2548 .params = "",
2549 .help = "show the character devices",
2550 .mhandler.cmd = hmp_info_chardev,
2553 .name = "block",
2554 .args_type = "nodes:-n,verbose:-v,device:B?",
2555 .params = "[-n] [-v] [device]",
2556 .help = "show info of one block device or all block devices "
2557 "(-n: show named nodes; -v: show details)",
2558 .mhandler.cmd = hmp_info_block,
2561 .name = "blockstats",
2562 .args_type = "",
2563 .params = "",
2564 .help = "show block device statistics",
2565 .mhandler.cmd = hmp_info_blockstats,
2568 .name = "block-jobs",
2569 .args_type = "",
2570 .params = "",
2571 .help = "show progress of ongoing block device operations",
2572 .mhandler.cmd = hmp_info_block_jobs,
2575 .name = "registers",
2576 .args_type = "",
2577 .params = "",
2578 .help = "show the cpu registers",
2579 .mhandler.cmd = hmp_info_registers,
2582 .name = "cpus",
2583 .args_type = "",
2584 .params = "",
2585 .help = "show infos for each CPU",
2586 .mhandler.cmd = hmp_info_cpus,
2589 .name = "history",
2590 .args_type = "",
2591 .params = "",
2592 .help = "show the command line history",
2593 .mhandler.cmd = hmp_info_history,
2595 #if defined(TARGET_I386) || defined(TARGET_PPC) || defined(TARGET_MIPS) || \
2596 defined(TARGET_LM32) || (defined(TARGET_SPARC) && !defined(TARGET_SPARC64))
2598 .name = "irq",
2599 .args_type = "",
2600 .params = "",
2601 .help = "show the interrupts statistics (if available)",
2602 #ifdef TARGET_SPARC
2603 .mhandler.cmd = sun4m_hmp_info_irq,
2604 #elif defined(TARGET_LM32)
2605 .mhandler.cmd = lm32_hmp_info_irq,
2606 #else
2607 .mhandler.cmd = hmp_info_irq,
2608 #endif
2611 .name = "pic",
2612 .args_type = "",
2613 .params = "",
2614 .help = "show i8259 (PIC) state",
2615 #ifdef TARGET_SPARC
2616 .mhandler.cmd = sun4m_hmp_info_pic,
2617 #elif defined(TARGET_LM32)
2618 .mhandler.cmd = lm32_hmp_info_pic,
2619 #else
2620 .mhandler.cmd = hmp_info_pic,
2621 #endif
2623 #endif
2625 .name = "pci",
2626 .args_type = "",
2627 .params = "",
2628 .help = "show PCI info",
2629 .mhandler.cmd = hmp_info_pci,
2631 #if defined(TARGET_I386) || defined(TARGET_SH4) || defined(TARGET_SPARC) || \
2632 defined(TARGET_PPC) || defined(TARGET_XTENSA)
2634 .name = "tlb",
2635 .args_type = "",
2636 .params = "",
2637 .help = "show virtual to physical memory mappings",
2638 .mhandler.cmd = hmp_info_tlb,
2640 #endif
2641 #if defined(TARGET_I386)
2643 .name = "mem",
2644 .args_type = "",
2645 .params = "",
2646 .help = "show the active virtual memory mappings",
2647 .mhandler.cmd = hmp_info_mem,
2649 #endif
2651 .name = "mtree",
2652 .args_type = "",
2653 .params = "",
2654 .help = "show memory tree",
2655 .mhandler.cmd = hmp_info_mtree,
2658 .name = "jit",
2659 .args_type = "",
2660 .params = "",
2661 .help = "show dynamic compiler info",
2662 .mhandler.cmd = hmp_info_jit,
2665 .name = "opcount",
2666 .args_type = "",
2667 .params = "",
2668 .help = "show dynamic compiler opcode counters",
2669 .mhandler.cmd = hmp_info_opcount,
2672 .name = "kvm",
2673 .args_type = "",
2674 .params = "",
2675 .help = "show KVM information",
2676 .mhandler.cmd = hmp_info_kvm,
2679 .name = "numa",
2680 .args_type = "",
2681 .params = "",
2682 .help = "show NUMA information",
2683 .mhandler.cmd = hmp_info_numa,
2686 .name = "usb",
2687 .args_type = "",
2688 .params = "",
2689 .help = "show guest USB devices",
2690 .mhandler.cmd = hmp_info_usb,
2693 .name = "usbhost",
2694 .args_type = "",
2695 .params = "",
2696 .help = "show host USB devices",
2697 .mhandler.cmd = hmp_info_usbhost,
2700 .name = "profile",
2701 .args_type = "",
2702 .params = "",
2703 .help = "show profiling information",
2704 .mhandler.cmd = hmp_info_profile,
2707 .name = "capture",
2708 .args_type = "",
2709 .params = "",
2710 .help = "show capture information",
2711 .mhandler.cmd = hmp_info_capture,
2714 .name = "snapshots",
2715 .args_type = "",
2716 .params = "",
2717 .help = "show the currently saved VM snapshots",
2718 .mhandler.cmd = hmp_info_snapshots,
2721 .name = "status",
2722 .args_type = "",
2723 .params = "",
2724 .help = "show the current VM status (running|paused)",
2725 .mhandler.cmd = hmp_info_status,
2728 .name = "mice",
2729 .args_type = "",
2730 .params = "",
2731 .help = "show which guest mouse is receiving events",
2732 .mhandler.cmd = hmp_info_mice,
2735 .name = "vnc",
2736 .args_type = "",
2737 .params = "",
2738 .help = "show the vnc server status",
2739 .mhandler.cmd = hmp_info_vnc,
2741 #if defined(CONFIG_SPICE)
2743 .name = "spice",
2744 .args_type = "",
2745 .params = "",
2746 .help = "show the spice server status",
2747 .mhandler.cmd = hmp_info_spice,
2749 #endif
2751 .name = "name",
2752 .args_type = "",
2753 .params = "",
2754 .help = "show the current VM name",
2755 .mhandler.cmd = hmp_info_name,
2758 .name = "uuid",
2759 .args_type = "",
2760 .params = "",
2761 .help = "show the current VM UUID",
2762 .mhandler.cmd = hmp_info_uuid,
2765 .name = "cpustats",
2766 .args_type = "",
2767 .params = "",
2768 .help = "show CPU statistics",
2769 .mhandler.cmd = hmp_info_cpustats,
2771 #if defined(CONFIG_SLIRP)
2773 .name = "usernet",
2774 .args_type = "",
2775 .params = "",
2776 .help = "show user network stack connection states",
2777 .mhandler.cmd = hmp_info_usernet,
2779 #endif
2781 .name = "migrate",
2782 .args_type = "",
2783 .params = "",
2784 .help = "show migration status",
2785 .mhandler.cmd = hmp_info_migrate,
2788 .name = "migrate_capabilities",
2789 .args_type = "",
2790 .params = "",
2791 .help = "show current migration capabilities",
2792 .mhandler.cmd = hmp_info_migrate_capabilities,
2795 .name = "migrate_parameters",
2796 .args_type = "",
2797 .params = "",
2798 .help = "show current migration parameters",
2799 .mhandler.cmd = hmp_info_migrate_parameters,
2802 .name = "migrate_cache_size",
2803 .args_type = "",
2804 .params = "",
2805 .help = "show current migration xbzrle cache size",
2806 .mhandler.cmd = hmp_info_migrate_cache_size,
2809 .name = "balloon",
2810 .args_type = "",
2811 .params = "",
2812 .help = "show balloon information",
2813 .mhandler.cmd = hmp_info_balloon,
2816 .name = "qtree",
2817 .args_type = "",
2818 .params = "",
2819 .help = "show device tree",
2820 .mhandler.cmd = hmp_info_qtree,
2823 .name = "qdm",
2824 .args_type = "",
2825 .params = "",
2826 .help = "show qdev device model list",
2827 .mhandler.cmd = hmp_info_qdm,
2830 .name = "qom-tree",
2831 .args_type = "path:s?",
2832 .params = "[path]",
2833 .help = "show QOM composition tree",
2834 .mhandler.cmd = hmp_info_qom_tree,
2837 .name = "roms",
2838 .args_type = "",
2839 .params = "",
2840 .help = "show roms",
2841 .mhandler.cmd = hmp_info_roms,
2844 .name = "trace-events",
2845 .args_type = "",
2846 .params = "",
2847 .help = "show available trace-events & their state",
2848 .mhandler.cmd = hmp_info_trace_events,
2851 .name = "tpm",
2852 .args_type = "",
2853 .params = "",
2854 .help = "show the TPM device",
2855 .mhandler.cmd = hmp_info_tpm,
2858 .name = "memdev",
2859 .args_type = "",
2860 .params = "",
2861 .help = "show memory backends",
2862 .mhandler.cmd = hmp_info_memdev,
2865 .name = "memory-devices",
2866 .args_type = "",
2867 .params = "",
2868 .help = "show memory devices",
2869 .mhandler.cmd = hmp_info_memory_devices,
2872 .name = NULL,
2876 /* mon_cmds and info_cmds would be sorted at runtime */
2877 static mon_cmd_t mon_cmds[] = {
2878 #include "hmp-commands.h"
2879 { NULL, NULL, },
2882 static const mon_cmd_t qmp_cmds[] = {
2883 #include "qmp-commands-old.h"
2884 { /* NULL */ },
2887 /*******************************************************************/
2889 static const char *pch;
2890 static sigjmp_buf expr_env;
2892 #define MD_TLONG 0
2893 #define MD_I32 1
2895 typedef struct MonitorDef {
2896 const char *name;
2897 int offset;
2898 target_long (*get_value)(const struct MonitorDef *md, int val);
2899 int type;
2900 } MonitorDef;
2902 #if defined(TARGET_I386)
2903 static target_long monitor_get_pc (const struct MonitorDef *md, int val)
2905 CPUArchState *env = mon_get_cpu();
2906 return env->eip + env->segs[R_CS].base;
2908 #endif
2910 #if defined(TARGET_PPC)
2911 static target_long monitor_get_ccr (const struct MonitorDef *md, int val)
2913 CPUArchState *env = mon_get_cpu();
2914 unsigned int u;
2915 int i;
2917 u = 0;
2918 for (i = 0; i < 8; i++)
2919 u |= env->crf[i] << (32 - (4 * (i + 1)));
2921 return u;
2924 static target_long monitor_get_msr (const struct MonitorDef *md, int val)
2926 CPUArchState *env = mon_get_cpu();
2927 return env->msr;
2930 static target_long monitor_get_xer (const struct MonitorDef *md, int val)
2932 CPUArchState *env = mon_get_cpu();
2933 return env->xer;
2936 static target_long monitor_get_decr (const struct MonitorDef *md, int val)
2938 CPUArchState *env = mon_get_cpu();
2939 return cpu_ppc_load_decr(env);
2942 static target_long monitor_get_tbu (const struct MonitorDef *md, int val)
2944 CPUArchState *env = mon_get_cpu();
2945 return cpu_ppc_load_tbu(env);
2948 static target_long monitor_get_tbl (const struct MonitorDef *md, int val)
2950 CPUArchState *env = mon_get_cpu();
2951 return cpu_ppc_load_tbl(env);
2953 #endif
2955 #if defined(TARGET_SPARC)
2956 #ifndef TARGET_SPARC64
2957 static target_long monitor_get_psr (const struct MonitorDef *md, int val)
2959 CPUArchState *env = mon_get_cpu();
2961 return cpu_get_psr(env);
2963 #endif
2965 static target_long monitor_get_reg(const struct MonitorDef *md, int val)
2967 CPUArchState *env = mon_get_cpu();
2968 return env->regwptr[val];
2970 #endif
2972 static const MonitorDef monitor_defs[] = {
2973 #ifdef TARGET_I386
2975 #define SEG(name, seg) \
2976 { name, offsetof(CPUX86State, segs[seg].selector), NULL, MD_I32 },\
2977 { name ".base", offsetof(CPUX86State, segs[seg].base) },\
2978 { name ".limit", offsetof(CPUX86State, segs[seg].limit), NULL, MD_I32 },
2980 { "eax", offsetof(CPUX86State, regs[0]) },
2981 { "ecx", offsetof(CPUX86State, regs[1]) },
2982 { "edx", offsetof(CPUX86State, regs[2]) },
2983 { "ebx", offsetof(CPUX86State, regs[3]) },
2984 { "esp|sp", offsetof(CPUX86State, regs[4]) },
2985 { "ebp|fp", offsetof(CPUX86State, regs[5]) },
2986 { "esi", offsetof(CPUX86State, regs[6]) },
2987 { "edi", offsetof(CPUX86State, regs[7]) },
2988 #ifdef TARGET_X86_64
2989 { "r8", offsetof(CPUX86State, regs[8]) },
2990 { "r9", offsetof(CPUX86State, regs[9]) },
2991 { "r10", offsetof(CPUX86State, regs[10]) },
2992 { "r11", offsetof(CPUX86State, regs[11]) },
2993 { "r12", offsetof(CPUX86State, regs[12]) },
2994 { "r13", offsetof(CPUX86State, regs[13]) },
2995 { "r14", offsetof(CPUX86State, regs[14]) },
2996 { "r15", offsetof(CPUX86State, regs[15]) },
2997 #endif
2998 { "eflags", offsetof(CPUX86State, eflags) },
2999 { "eip", offsetof(CPUX86State, eip) },
3000 SEG("cs", R_CS)
3001 SEG("ds", R_DS)
3002 SEG("es", R_ES)
3003 SEG("ss", R_SS)
3004 SEG("fs", R_FS)
3005 SEG("gs", R_GS)
3006 { "pc", 0, monitor_get_pc, },
3007 #elif defined(TARGET_PPC)
3008 /* General purpose registers */
3009 { "r0", offsetof(CPUPPCState, gpr[0]) },
3010 { "r1", offsetof(CPUPPCState, gpr[1]) },
3011 { "r2", offsetof(CPUPPCState, gpr[2]) },
3012 { "r3", offsetof(CPUPPCState, gpr[3]) },
3013 { "r4", offsetof(CPUPPCState, gpr[4]) },
3014 { "r5", offsetof(CPUPPCState, gpr[5]) },
3015 { "r6", offsetof(CPUPPCState, gpr[6]) },
3016 { "r7", offsetof(CPUPPCState, gpr[7]) },
3017 { "r8", offsetof(CPUPPCState, gpr[8]) },
3018 { "r9", offsetof(CPUPPCState, gpr[9]) },
3019 { "r10", offsetof(CPUPPCState, gpr[10]) },
3020 { "r11", offsetof(CPUPPCState, gpr[11]) },
3021 { "r12", offsetof(CPUPPCState, gpr[12]) },
3022 { "r13", offsetof(CPUPPCState, gpr[13]) },
3023 { "r14", offsetof(CPUPPCState, gpr[14]) },
3024 { "r15", offsetof(CPUPPCState, gpr[15]) },
3025 { "r16", offsetof(CPUPPCState, gpr[16]) },
3026 { "r17", offsetof(CPUPPCState, gpr[17]) },
3027 { "r18", offsetof(CPUPPCState, gpr[18]) },
3028 { "r19", offsetof(CPUPPCState, gpr[19]) },
3029 { "r20", offsetof(CPUPPCState, gpr[20]) },
3030 { "r21", offsetof(CPUPPCState, gpr[21]) },
3031 { "r22", offsetof(CPUPPCState, gpr[22]) },
3032 { "r23", offsetof(CPUPPCState, gpr[23]) },
3033 { "r24", offsetof(CPUPPCState, gpr[24]) },
3034 { "r25", offsetof(CPUPPCState, gpr[25]) },
3035 { "r26", offsetof(CPUPPCState, gpr[26]) },
3036 { "r27", offsetof(CPUPPCState, gpr[27]) },
3037 { "r28", offsetof(CPUPPCState, gpr[28]) },
3038 { "r29", offsetof(CPUPPCState, gpr[29]) },
3039 { "r30", offsetof(CPUPPCState, gpr[30]) },
3040 { "r31", offsetof(CPUPPCState, gpr[31]) },
3041 /* Floating point registers */
3042 { "f0", offsetof(CPUPPCState, fpr[0]) },
3043 { "f1", offsetof(CPUPPCState, fpr[1]) },
3044 { "f2", offsetof(CPUPPCState, fpr[2]) },
3045 { "f3", offsetof(CPUPPCState, fpr[3]) },
3046 { "f4", offsetof(CPUPPCState, fpr[4]) },
3047 { "f5", offsetof(CPUPPCState, fpr[5]) },
3048 { "f6", offsetof(CPUPPCState, fpr[6]) },
3049 { "f7", offsetof(CPUPPCState, fpr[7]) },
3050 { "f8", offsetof(CPUPPCState, fpr[8]) },
3051 { "f9", offsetof(CPUPPCState, fpr[9]) },
3052 { "f10", offsetof(CPUPPCState, fpr[10]) },
3053 { "f11", offsetof(CPUPPCState, fpr[11]) },
3054 { "f12", offsetof(CPUPPCState, fpr[12]) },
3055 { "f13", offsetof(CPUPPCState, fpr[13]) },
3056 { "f14", offsetof(CPUPPCState, fpr[14]) },
3057 { "f15", offsetof(CPUPPCState, fpr[15]) },
3058 { "f16", offsetof(CPUPPCState, fpr[16]) },
3059 { "f17", offsetof(CPUPPCState, fpr[17]) },
3060 { "f18", offsetof(CPUPPCState, fpr[18]) },
3061 { "f19", offsetof(CPUPPCState, fpr[19]) },
3062 { "f20", offsetof(CPUPPCState, fpr[20]) },
3063 { "f21", offsetof(CPUPPCState, fpr[21]) },
3064 { "f22", offsetof(CPUPPCState, fpr[22]) },
3065 { "f23", offsetof(CPUPPCState, fpr[23]) },
3066 { "f24", offsetof(CPUPPCState, fpr[24]) },
3067 { "f25", offsetof(CPUPPCState, fpr[25]) },
3068 { "f26", offsetof(CPUPPCState, fpr[26]) },
3069 { "f27", offsetof(CPUPPCState, fpr[27]) },
3070 { "f28", offsetof(CPUPPCState, fpr[28]) },
3071 { "f29", offsetof(CPUPPCState, fpr[29]) },
3072 { "f30", offsetof(CPUPPCState, fpr[30]) },
3073 { "f31", offsetof(CPUPPCState, fpr[31]) },
3074 { "fpscr", offsetof(CPUPPCState, fpscr) },
3075 /* Next instruction pointer */
3076 { "nip|pc", offsetof(CPUPPCState, nip) },
3077 { "lr", offsetof(CPUPPCState, lr) },
3078 { "ctr", offsetof(CPUPPCState, ctr) },
3079 { "decr", 0, &monitor_get_decr, },
3080 { "ccr", 0, &monitor_get_ccr, },
3081 /* Machine state register */
3082 { "msr", 0, &monitor_get_msr, },
3083 { "xer", 0, &monitor_get_xer, },
3084 { "tbu", 0, &monitor_get_tbu, },
3085 { "tbl", 0, &monitor_get_tbl, },
3086 /* Segment registers */
3087 { "sdr1", offsetof(CPUPPCState, spr[SPR_SDR1]) },
3088 { "sr0", offsetof(CPUPPCState, sr[0]) },
3089 { "sr1", offsetof(CPUPPCState, sr[1]) },
3090 { "sr2", offsetof(CPUPPCState, sr[2]) },
3091 { "sr3", offsetof(CPUPPCState, sr[3]) },
3092 { "sr4", offsetof(CPUPPCState, sr[4]) },
3093 { "sr5", offsetof(CPUPPCState, sr[5]) },
3094 { "sr6", offsetof(CPUPPCState, sr[6]) },
3095 { "sr7", offsetof(CPUPPCState, sr[7]) },
3096 { "sr8", offsetof(CPUPPCState, sr[8]) },
3097 { "sr9", offsetof(CPUPPCState, sr[9]) },
3098 { "sr10", offsetof(CPUPPCState, sr[10]) },
3099 { "sr11", offsetof(CPUPPCState, sr[11]) },
3100 { "sr12", offsetof(CPUPPCState, sr[12]) },
3101 { "sr13", offsetof(CPUPPCState, sr[13]) },
3102 { "sr14", offsetof(CPUPPCState, sr[14]) },
3103 { "sr15", offsetof(CPUPPCState, sr[15]) },
3104 /* Too lazy to put BATs... */
3105 { "pvr", offsetof(CPUPPCState, spr[SPR_PVR]) },
3107 { "srr0", offsetof(CPUPPCState, spr[SPR_SRR0]) },
3108 { "srr1", offsetof(CPUPPCState, spr[SPR_SRR1]) },
3109 { "dar", offsetof(CPUPPCState, spr[SPR_DAR]) },
3110 { "dsisr", offsetof(CPUPPCState, spr[SPR_DSISR]) },
3111 { "cfar", offsetof(CPUPPCState, spr[SPR_CFAR]) },
3112 { "sprg0", offsetof(CPUPPCState, spr[SPR_SPRG0]) },
3113 { "sprg1", offsetof(CPUPPCState, spr[SPR_SPRG1]) },
3114 { "sprg2", offsetof(CPUPPCState, spr[SPR_SPRG2]) },
3115 { "sprg3", offsetof(CPUPPCState, spr[SPR_SPRG3]) },
3116 { "sprg4", offsetof(CPUPPCState, spr[SPR_SPRG4]) },
3117 { "sprg5", offsetof(CPUPPCState, spr[SPR_SPRG5]) },
3118 { "sprg6", offsetof(CPUPPCState, spr[SPR_SPRG6]) },
3119 { "sprg7", offsetof(CPUPPCState, spr[SPR_SPRG7]) },
3120 { "pid", offsetof(CPUPPCState, spr[SPR_BOOKE_PID]) },
3121 { "csrr0", offsetof(CPUPPCState, spr[SPR_BOOKE_CSRR0]) },
3122 { "csrr1", offsetof(CPUPPCState, spr[SPR_BOOKE_CSRR1]) },
3123 { "esr", offsetof(CPUPPCState, spr[SPR_BOOKE_ESR]) },
3124 { "dear", offsetof(CPUPPCState, spr[SPR_BOOKE_DEAR]) },
3125 { "mcsr", offsetof(CPUPPCState, spr[SPR_BOOKE_MCSR]) },
3126 { "tsr", offsetof(CPUPPCState, spr[SPR_BOOKE_TSR]) },
3127 { "tcr", offsetof(CPUPPCState, spr[SPR_BOOKE_TCR]) },
3128 { "vrsave", offsetof(CPUPPCState, spr[SPR_VRSAVE]) },
3129 { "pir", offsetof(CPUPPCState, spr[SPR_BOOKE_PIR]) },
3130 { "mcsrr0", offsetof(CPUPPCState, spr[SPR_BOOKE_MCSRR0]) },
3131 { "mcsrr1", offsetof(CPUPPCState, spr[SPR_BOOKE_MCSRR1]) },
3132 { "decar", offsetof(CPUPPCState, spr[SPR_BOOKE_DECAR]) },
3133 { "ivpr", offsetof(CPUPPCState, spr[SPR_BOOKE_IVPR]) },
3134 { "epcr", offsetof(CPUPPCState, spr[SPR_BOOKE_EPCR]) },
3135 { "sprg8", offsetof(CPUPPCState, spr[SPR_BOOKE_SPRG8]) },
3136 { "ivor0", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR0]) },
3137 { "ivor1", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR1]) },
3138 { "ivor2", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR2]) },
3139 { "ivor3", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR3]) },
3140 { "ivor4", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR4]) },
3141 { "ivor5", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR5]) },
3142 { "ivor6", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR6]) },
3143 { "ivor7", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR7]) },
3144 { "ivor8", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR8]) },
3145 { "ivor9", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR9]) },
3146 { "ivor10", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR10]) },
3147 { "ivor11", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR11]) },
3148 { "ivor12", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR12]) },
3149 { "ivor13", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR13]) },
3150 { "ivor14", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR14]) },
3151 { "ivor15", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR15]) },
3152 { "ivor32", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR32]) },
3153 { "ivor33", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR33]) },
3154 { "ivor34", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR34]) },
3155 { "ivor35", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR35]) },
3156 { "ivor36", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR36]) },
3157 { "ivor37", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR37]) },
3158 { "mas0", offsetof(CPUPPCState, spr[SPR_BOOKE_MAS0]) },
3159 { "mas1", offsetof(CPUPPCState, spr[SPR_BOOKE_MAS1]) },
3160 { "mas2", offsetof(CPUPPCState, spr[SPR_BOOKE_MAS2]) },
3161 { "mas3", offsetof(CPUPPCState, spr[SPR_BOOKE_MAS3]) },
3162 { "mas4", offsetof(CPUPPCState, spr[SPR_BOOKE_MAS4]) },
3163 { "mas6", offsetof(CPUPPCState, spr[SPR_BOOKE_MAS6]) },
3164 { "mas7", offsetof(CPUPPCState, spr[SPR_BOOKE_MAS7]) },
3165 { "mmucfg", offsetof(CPUPPCState, spr[SPR_MMUCFG]) },
3166 { "tlb0cfg", offsetof(CPUPPCState, spr[SPR_BOOKE_TLB0CFG]) },
3167 { "tlb1cfg", offsetof(CPUPPCState, spr[SPR_BOOKE_TLB1CFG]) },
3168 { "epr", offsetof(CPUPPCState, spr[SPR_BOOKE_EPR]) },
3169 { "eplc", offsetof(CPUPPCState, spr[SPR_BOOKE_EPLC]) },
3170 { "epsc", offsetof(CPUPPCState, spr[SPR_BOOKE_EPSC]) },
3171 { "svr", offsetof(CPUPPCState, spr[SPR_E500_SVR]) },
3172 { "mcar", offsetof(CPUPPCState, spr[SPR_Exxx_MCAR]) },
3173 { "pid1", offsetof(CPUPPCState, spr[SPR_BOOKE_PID1]) },
3174 { "pid2", offsetof(CPUPPCState, spr[SPR_BOOKE_PID2]) },
3175 { "hid0", offsetof(CPUPPCState, spr[SPR_HID0]) },
3177 #elif defined(TARGET_SPARC)
3178 { "g0", offsetof(CPUSPARCState, gregs[0]) },
3179 { "g1", offsetof(CPUSPARCState, gregs[1]) },
3180 { "g2", offsetof(CPUSPARCState, gregs[2]) },
3181 { "g3", offsetof(CPUSPARCState, gregs[3]) },
3182 { "g4", offsetof(CPUSPARCState, gregs[4]) },
3183 { "g5", offsetof(CPUSPARCState, gregs[5]) },
3184 { "g6", offsetof(CPUSPARCState, gregs[6]) },
3185 { "g7", offsetof(CPUSPARCState, gregs[7]) },
3186 { "o0", 0, monitor_get_reg },
3187 { "o1", 1, monitor_get_reg },
3188 { "o2", 2, monitor_get_reg },
3189 { "o3", 3, monitor_get_reg },
3190 { "o4", 4, monitor_get_reg },
3191 { "o5", 5, monitor_get_reg },
3192 { "o6", 6, monitor_get_reg },
3193 { "o7", 7, monitor_get_reg },
3194 { "l0", 8, monitor_get_reg },
3195 { "l1", 9, monitor_get_reg },
3196 { "l2", 10, monitor_get_reg },
3197 { "l3", 11, monitor_get_reg },
3198 { "l4", 12, monitor_get_reg },
3199 { "l5", 13, monitor_get_reg },
3200 { "l6", 14, monitor_get_reg },
3201 { "l7", 15, monitor_get_reg },
3202 { "i0", 16, monitor_get_reg },
3203 { "i1", 17, monitor_get_reg },
3204 { "i2", 18, monitor_get_reg },
3205 { "i3", 19, monitor_get_reg },
3206 { "i4", 20, monitor_get_reg },
3207 { "i5", 21, monitor_get_reg },
3208 { "i6", 22, monitor_get_reg },
3209 { "i7", 23, monitor_get_reg },
3210 { "pc", offsetof(CPUSPARCState, pc) },
3211 { "npc", offsetof(CPUSPARCState, npc) },
3212 { "y", offsetof(CPUSPARCState, y) },
3213 #ifndef TARGET_SPARC64
3214 { "psr", 0, &monitor_get_psr, },
3215 { "wim", offsetof(CPUSPARCState, wim) },
3216 #endif
3217 { "tbr", offsetof(CPUSPARCState, tbr) },
3218 { "fsr", offsetof(CPUSPARCState, fsr) },
3219 { "f0", offsetof(CPUSPARCState, fpr[0].l.upper) },
3220 { "f1", offsetof(CPUSPARCState, fpr[0].l.lower) },
3221 { "f2", offsetof(CPUSPARCState, fpr[1].l.upper) },
3222 { "f3", offsetof(CPUSPARCState, fpr[1].l.lower) },
3223 { "f4", offsetof(CPUSPARCState, fpr[2].l.upper) },
3224 { "f5", offsetof(CPUSPARCState, fpr[2].l.lower) },
3225 { "f6", offsetof(CPUSPARCState, fpr[3].l.upper) },
3226 { "f7", offsetof(CPUSPARCState, fpr[3].l.lower) },
3227 { "f8", offsetof(CPUSPARCState, fpr[4].l.upper) },
3228 { "f9", offsetof(CPUSPARCState, fpr[4].l.lower) },
3229 { "f10", offsetof(CPUSPARCState, fpr[5].l.upper) },
3230 { "f11", offsetof(CPUSPARCState, fpr[5].l.lower) },
3231 { "f12", offsetof(CPUSPARCState, fpr[6].l.upper) },
3232 { "f13", offsetof(CPUSPARCState, fpr[6].l.lower) },
3233 { "f14", offsetof(CPUSPARCState, fpr[7].l.upper) },
3234 { "f15", offsetof(CPUSPARCState, fpr[7].l.lower) },
3235 { "f16", offsetof(CPUSPARCState, fpr[8].l.upper) },
3236 { "f17", offsetof(CPUSPARCState, fpr[8].l.lower) },
3237 { "f18", offsetof(CPUSPARCState, fpr[9].l.upper) },
3238 { "f19", offsetof(CPUSPARCState, fpr[9].l.lower) },
3239 { "f20", offsetof(CPUSPARCState, fpr[10].l.upper) },
3240 { "f21", offsetof(CPUSPARCState, fpr[10].l.lower) },
3241 { "f22", offsetof(CPUSPARCState, fpr[11].l.upper) },
3242 { "f23", offsetof(CPUSPARCState, fpr[11].l.lower) },
3243 { "f24", offsetof(CPUSPARCState, fpr[12].l.upper) },
3244 { "f25", offsetof(CPUSPARCState, fpr[12].l.lower) },
3245 { "f26", offsetof(CPUSPARCState, fpr[13].l.upper) },
3246 { "f27", offsetof(CPUSPARCState, fpr[13].l.lower) },
3247 { "f28", offsetof(CPUSPARCState, fpr[14].l.upper) },
3248 { "f29", offsetof(CPUSPARCState, fpr[14].l.lower) },
3249 { "f30", offsetof(CPUSPARCState, fpr[15].l.upper) },
3250 { "f31", offsetof(CPUSPARCState, fpr[15].l.lower) },
3251 #ifdef TARGET_SPARC64
3252 { "f32", offsetof(CPUSPARCState, fpr[16]) },
3253 { "f34", offsetof(CPUSPARCState, fpr[17]) },
3254 { "f36", offsetof(CPUSPARCState, fpr[18]) },
3255 { "f38", offsetof(CPUSPARCState, fpr[19]) },
3256 { "f40", offsetof(CPUSPARCState, fpr[20]) },
3257 { "f42", offsetof(CPUSPARCState, fpr[21]) },
3258 { "f44", offsetof(CPUSPARCState, fpr[22]) },
3259 { "f46", offsetof(CPUSPARCState, fpr[23]) },
3260 { "f48", offsetof(CPUSPARCState, fpr[24]) },
3261 { "f50", offsetof(CPUSPARCState, fpr[25]) },
3262 { "f52", offsetof(CPUSPARCState, fpr[26]) },
3263 { "f54", offsetof(CPUSPARCState, fpr[27]) },
3264 { "f56", offsetof(CPUSPARCState, fpr[28]) },
3265 { "f58", offsetof(CPUSPARCState, fpr[29]) },
3266 { "f60", offsetof(CPUSPARCState, fpr[30]) },
3267 { "f62", offsetof(CPUSPARCState, fpr[31]) },
3268 { "asi", offsetof(CPUSPARCState, asi) },
3269 { "pstate", offsetof(CPUSPARCState, pstate) },
3270 { "cansave", offsetof(CPUSPARCState, cansave) },
3271 { "canrestore", offsetof(CPUSPARCState, canrestore) },
3272 { "otherwin", offsetof(CPUSPARCState, otherwin) },
3273 { "wstate", offsetof(CPUSPARCState, wstate) },
3274 { "cleanwin", offsetof(CPUSPARCState, cleanwin) },
3275 { "fprs", offsetof(CPUSPARCState, fprs) },
3276 #endif
3277 #endif
3278 { NULL },
3281 static void GCC_FMT_ATTR(2, 3) QEMU_NORETURN
3282 expr_error(Monitor *mon, const char *fmt, ...)
3284 va_list ap;
3285 va_start(ap, fmt);
3286 monitor_vprintf(mon, fmt, ap);
3287 monitor_printf(mon, "\n");
3288 va_end(ap);
3289 siglongjmp(expr_env, 1);
3292 /* return 0 if OK, -1 if not found */
3293 static int get_monitor_def(target_long *pval, const char *name)
3295 const MonitorDef *md;
3296 void *ptr;
3298 for(md = monitor_defs; md->name != NULL; md++) {
3299 if (compare_cmd(name, md->name)) {
3300 if (md->get_value) {
3301 *pval = md->get_value(md, md->offset);
3302 } else {
3303 CPUArchState *env = mon_get_cpu();
3304 ptr = (uint8_t *)env + md->offset;
3305 switch(md->type) {
3306 case MD_I32:
3307 *pval = *(int32_t *)ptr;
3308 break;
3309 case MD_TLONG:
3310 *pval = *(target_long *)ptr;
3311 break;
3312 default:
3313 *pval = 0;
3314 break;
3317 return 0;
3320 return -1;
3323 static void next(void)
3325 if (*pch != '\0') {
3326 pch++;
3327 while (qemu_isspace(*pch))
3328 pch++;
3332 static int64_t expr_sum(Monitor *mon);
3334 static int64_t expr_unary(Monitor *mon)
3336 int64_t n;
3337 char *p;
3338 int ret;
3340 switch(*pch) {
3341 case '+':
3342 next();
3343 n = expr_unary(mon);
3344 break;
3345 case '-':
3346 next();
3347 n = -expr_unary(mon);
3348 break;
3349 case '~':
3350 next();
3351 n = ~expr_unary(mon);
3352 break;
3353 case '(':
3354 next();
3355 n = expr_sum(mon);
3356 if (*pch != ')') {
3357 expr_error(mon, "')' expected");
3359 next();
3360 break;
3361 case '\'':
3362 pch++;
3363 if (*pch == '\0')
3364 expr_error(mon, "character constant expected");
3365 n = *pch;
3366 pch++;
3367 if (*pch != '\'')
3368 expr_error(mon, "missing terminating \' character");
3369 next();
3370 break;
3371 case '$':
3373 char buf[128], *q;
3374 target_long reg=0;
3376 pch++;
3377 q = buf;
3378 while ((*pch >= 'a' && *pch <= 'z') ||
3379 (*pch >= 'A' && *pch <= 'Z') ||
3380 (*pch >= '0' && *pch <= '9') ||
3381 *pch == '_' || *pch == '.') {
3382 if ((q - buf) < sizeof(buf) - 1)
3383 *q++ = *pch;
3384 pch++;
3386 while (qemu_isspace(*pch))
3387 pch++;
3388 *q = 0;
3389 ret = get_monitor_def(&reg, buf);
3390 if (ret < 0)
3391 expr_error(mon, "unknown register");
3392 n = reg;
3394 break;
3395 case '\0':
3396 expr_error(mon, "unexpected end of expression");
3397 n = 0;
3398 break;
3399 default:
3400 errno = 0;
3401 n = strtoull(pch, &p, 0);
3402 if (errno == ERANGE) {
3403 expr_error(mon, "number too large");
3405 if (pch == p) {
3406 expr_error(mon, "invalid char '%c' in expression", *p);
3408 pch = p;
3409 while (qemu_isspace(*pch))
3410 pch++;
3411 break;
3413 return n;
3417 static int64_t expr_prod(Monitor *mon)
3419 int64_t val, val2;
3420 int op;
3422 val = expr_unary(mon);
3423 for(;;) {
3424 op = *pch;
3425 if (op != '*' && op != '/' && op != '%')
3426 break;
3427 next();
3428 val2 = expr_unary(mon);
3429 switch(op) {
3430 default:
3431 case '*':
3432 val *= val2;
3433 break;
3434 case '/':
3435 case '%':
3436 if (val2 == 0)
3437 expr_error(mon, "division by zero");
3438 if (op == '/')
3439 val /= val2;
3440 else
3441 val %= val2;
3442 break;
3445 return val;
3448 static int64_t expr_logic(Monitor *mon)
3450 int64_t val, val2;
3451 int op;
3453 val = expr_prod(mon);
3454 for(;;) {
3455 op = *pch;
3456 if (op != '&' && op != '|' && op != '^')
3457 break;
3458 next();
3459 val2 = expr_prod(mon);
3460 switch(op) {
3461 default:
3462 case '&':
3463 val &= val2;
3464 break;
3465 case '|':
3466 val |= val2;
3467 break;
3468 case '^':
3469 val ^= val2;
3470 break;
3473 return val;
3476 static int64_t expr_sum(Monitor *mon)
3478 int64_t val, val2;
3479 int op;
3481 val = expr_logic(mon);
3482 for(;;) {
3483 op = *pch;
3484 if (op != '+' && op != '-')
3485 break;
3486 next();
3487 val2 = expr_logic(mon);
3488 if (op == '+')
3489 val += val2;
3490 else
3491 val -= val2;
3493 return val;
3496 static int get_expr(Monitor *mon, int64_t *pval, const char **pp)
3498 pch = *pp;
3499 if (sigsetjmp(expr_env, 0)) {
3500 *pp = pch;
3501 return -1;
3503 while (qemu_isspace(*pch))
3504 pch++;
3505 *pval = expr_sum(mon);
3506 *pp = pch;
3507 return 0;
3510 static int get_double(Monitor *mon, double *pval, const char **pp)
3512 const char *p = *pp;
3513 char *tailp;
3514 double d;
3516 d = strtod(p, &tailp);
3517 if (tailp == p) {
3518 monitor_printf(mon, "Number expected\n");
3519 return -1;
3521 if (d != d || d - d != 0) {
3522 /* NaN or infinity */
3523 monitor_printf(mon, "Bad number\n");
3524 return -1;
3526 *pval = d;
3527 *pp = tailp;
3528 return 0;
3532 * Store the command-name in cmdname, and return a pointer to
3533 * the remaining of the command string.
3535 static const char *get_command_name(const char *cmdline,
3536 char *cmdname, size_t nlen)
3538 size_t len;
3539 const char *p, *pstart;
3541 p = cmdline;
3542 while (qemu_isspace(*p))
3543 p++;
3544 if (*p == '\0')
3545 return NULL;
3546 pstart = p;
3547 while (*p != '\0' && *p != '/' && !qemu_isspace(*p))
3548 p++;
3549 len = p - pstart;
3550 if (len > nlen - 1)
3551 len = nlen - 1;
3552 memcpy(cmdname, pstart, len);
3553 cmdname[len] = '\0';
3554 return p;
3558 * Read key of 'type' into 'key' and return the current
3559 * 'type' pointer.
3561 static char *key_get_info(const char *type, char **key)
3563 size_t len;
3564 char *p, *str;
3566 if (*type == ',')
3567 type++;
3569 p = strchr(type, ':');
3570 if (!p) {
3571 *key = NULL;
3572 return NULL;
3574 len = p - type;
3576 str = g_malloc(len + 1);
3577 memcpy(str, type, len);
3578 str[len] = '\0';
3580 *key = str;
3581 return ++p;
3584 static int default_fmt_format = 'x';
3585 static int default_fmt_size = 4;
3587 static int is_valid_option(const char *c, const char *typestr)
3589 char option[3];
3591 option[0] = '-';
3592 option[1] = *c;
3593 option[2] = '\0';
3595 typestr = strstr(typestr, option);
3596 return (typestr != NULL);
3599 static const mon_cmd_t *search_dispatch_table(const mon_cmd_t *disp_table,
3600 const char *cmdname)
3602 const mon_cmd_t *cmd;
3604 for (cmd = disp_table; cmd->name != NULL; cmd++) {
3605 if (compare_cmd(cmdname, cmd->name)) {
3606 return cmd;
3610 return NULL;
3613 static const mon_cmd_t *qmp_find_cmd(const char *cmdname)
3615 return search_dispatch_table(qmp_cmds, cmdname);
3619 * Parse @cmdline according to command table @table.
3620 * If @cmdline is blank, return NULL.
3621 * If it can't be parsed, report to @mon, and return NULL.
3622 * Else, insert command arguments into @qdict, and return the command.
3623 * If a sub-command table exists, and if @cmdline contains an additional string
3624 * for a sub-command, this function will try to search the sub-command table.
3625 * If no additional string for a sub-command is present, this function will
3626 * return the command found in @table.
3627 * Do not assume the returned command points into @table! It doesn't
3628 * when the command is a sub-command.
3630 static const mon_cmd_t *monitor_parse_command(Monitor *mon,
3631 const char *cmdline,
3632 int start,
3633 mon_cmd_t *table,
3634 QDict *qdict)
3636 const char *p, *typestr;
3637 int c;
3638 const mon_cmd_t *cmd;
3639 char cmdname[256];
3640 char buf[1024];
3641 char *key;
3643 #ifdef DEBUG
3644 monitor_printf(mon, "command='%s', start='%d'\n", cmdline, start);
3645 #endif
3647 /* extract the command name */
3648 p = get_command_name(cmdline + start, cmdname, sizeof(cmdname));
3649 if (!p)
3650 return NULL;
3652 cmd = search_dispatch_table(table, cmdname);
3653 if (!cmd) {
3654 monitor_printf(mon, "unknown command: '%.*s'\n",
3655 (int)(p - cmdline), cmdline);
3656 return NULL;
3659 /* filter out following useless space */
3660 while (qemu_isspace(*p)) {
3661 p++;
3663 /* search sub command */
3664 if (cmd->sub_table != NULL) {
3665 /* check if user set additional command */
3666 if (*p == '\0') {
3667 return cmd;
3669 return monitor_parse_command(mon, cmdline, p - cmdline,
3670 cmd->sub_table, qdict);
3673 /* parse the parameters */
3674 typestr = cmd->args_type;
3675 for(;;) {
3676 typestr = key_get_info(typestr, &key);
3677 if (!typestr)
3678 break;
3679 c = *typestr;
3680 typestr++;
3681 switch(c) {
3682 case 'F':
3683 case 'B':
3684 case 's':
3686 int ret;
3688 while (qemu_isspace(*p))
3689 p++;
3690 if (*typestr == '?') {
3691 typestr++;
3692 if (*p == '\0') {
3693 /* no optional string: NULL argument */
3694 break;
3697 ret = get_str(buf, sizeof(buf), &p);
3698 if (ret < 0) {
3699 switch(c) {
3700 case 'F':
3701 monitor_printf(mon, "%s: filename expected\n",
3702 cmdname);
3703 break;
3704 case 'B':
3705 monitor_printf(mon, "%s: block device name expected\n",
3706 cmdname);
3707 break;
3708 default:
3709 monitor_printf(mon, "%s: string expected\n", cmdname);
3710 break;
3712 goto fail;
3714 qdict_put(qdict, key, qstring_from_str(buf));
3716 break;
3717 case 'O':
3719 QemuOptsList *opts_list;
3720 QemuOpts *opts;
3722 opts_list = qemu_find_opts(key);
3723 if (!opts_list || opts_list->desc->name) {
3724 goto bad_type;
3726 while (qemu_isspace(*p)) {
3727 p++;
3729 if (!*p)
3730 break;
3731 if (get_str(buf, sizeof(buf), &p) < 0) {
3732 goto fail;
3734 opts = qemu_opts_parse(opts_list, buf, 1);
3735 if (!opts) {
3736 goto fail;
3738 qemu_opts_to_qdict(opts, qdict);
3739 qemu_opts_del(opts);
3741 break;
3742 case '/':
3744 int count, format, size;
3746 while (qemu_isspace(*p))
3747 p++;
3748 if (*p == '/') {
3749 /* format found */
3750 p++;
3751 count = 1;
3752 if (qemu_isdigit(*p)) {
3753 count = 0;
3754 while (qemu_isdigit(*p)) {
3755 count = count * 10 + (*p - '0');
3756 p++;
3759 size = -1;
3760 format = -1;
3761 for(;;) {
3762 switch(*p) {
3763 case 'o':
3764 case 'd':
3765 case 'u':
3766 case 'x':
3767 case 'i':
3768 case 'c':
3769 format = *p++;
3770 break;
3771 case 'b':
3772 size = 1;
3773 p++;
3774 break;
3775 case 'h':
3776 size = 2;
3777 p++;
3778 break;
3779 case 'w':
3780 size = 4;
3781 p++;
3782 break;
3783 case 'g':
3784 case 'L':
3785 size = 8;
3786 p++;
3787 break;
3788 default:
3789 goto next;
3792 next:
3793 if (*p != '\0' && !qemu_isspace(*p)) {
3794 monitor_printf(mon, "invalid char in format: '%c'\n",
3795 *p);
3796 goto fail;
3798 if (format < 0)
3799 format = default_fmt_format;
3800 if (format != 'i') {
3801 /* for 'i', not specifying a size gives -1 as size */
3802 if (size < 0)
3803 size = default_fmt_size;
3804 default_fmt_size = size;
3806 default_fmt_format = format;
3807 } else {
3808 count = 1;
3809 format = default_fmt_format;
3810 if (format != 'i') {
3811 size = default_fmt_size;
3812 } else {
3813 size = -1;
3816 qdict_put(qdict, "count", qint_from_int(count));
3817 qdict_put(qdict, "format", qint_from_int(format));
3818 qdict_put(qdict, "size", qint_from_int(size));
3820 break;
3821 case 'i':
3822 case 'l':
3823 case 'M':
3825 int64_t val;
3827 while (qemu_isspace(*p))
3828 p++;
3829 if (*typestr == '?' || *typestr == '.') {
3830 if (*typestr == '?') {
3831 if (*p == '\0') {
3832 typestr++;
3833 break;
3835 } else {
3836 if (*p == '.') {
3837 p++;
3838 while (qemu_isspace(*p))
3839 p++;
3840 } else {
3841 typestr++;
3842 break;
3845 typestr++;
3847 if (get_expr(mon, &val, &p))
3848 goto fail;
3849 /* Check if 'i' is greater than 32-bit */
3850 if ((c == 'i') && ((val >> 32) & 0xffffffff)) {
3851 monitor_printf(mon, "\'%s\' has failed: ", cmdname);
3852 monitor_printf(mon, "integer is for 32-bit values\n");
3853 goto fail;
3854 } else if (c == 'M') {
3855 if (val < 0) {
3856 monitor_printf(mon, "enter a positive value\n");
3857 goto fail;
3859 val <<= 20;
3861 qdict_put(qdict, key, qint_from_int(val));
3863 break;
3864 case 'o':
3866 int64_t val;
3867 char *end;
3869 while (qemu_isspace(*p)) {
3870 p++;
3872 if (*typestr == '?') {
3873 typestr++;
3874 if (*p == '\0') {
3875 break;
3878 val = strtosz(p, &end);
3879 if (val < 0) {
3880 monitor_printf(mon, "invalid size\n");
3881 goto fail;
3883 qdict_put(qdict, key, qint_from_int(val));
3884 p = end;
3886 break;
3887 case 'T':
3889 double val;
3891 while (qemu_isspace(*p))
3892 p++;
3893 if (*typestr == '?') {
3894 typestr++;
3895 if (*p == '\0') {
3896 break;
3899 if (get_double(mon, &val, &p) < 0) {
3900 goto fail;
3902 if (p[0] && p[1] == 's') {
3903 switch (*p) {
3904 case 'm':
3905 val /= 1e3; p += 2; break;
3906 case 'u':
3907 val /= 1e6; p += 2; break;
3908 case 'n':
3909 val /= 1e9; p += 2; break;
3912 if (*p && !qemu_isspace(*p)) {
3913 monitor_printf(mon, "Unknown unit suffix\n");
3914 goto fail;
3916 qdict_put(qdict, key, qfloat_from_double(val));
3918 break;
3919 case 'b':
3921 const char *beg;
3922 int val;
3924 while (qemu_isspace(*p)) {
3925 p++;
3927 beg = p;
3928 while (qemu_isgraph(*p)) {
3929 p++;
3931 if (p - beg == 2 && !memcmp(beg, "on", p - beg)) {
3932 val = 1;
3933 } else if (p - beg == 3 && !memcmp(beg, "off", p - beg)) {
3934 val = 0;
3935 } else {
3936 monitor_printf(mon, "Expected 'on' or 'off'\n");
3937 goto fail;
3939 qdict_put(qdict, key, qbool_from_int(val));
3941 break;
3942 case '-':
3944 const char *tmp = p;
3945 int skip_key = 0;
3946 /* option */
3948 c = *typestr++;
3949 if (c == '\0')
3950 goto bad_type;
3951 while (qemu_isspace(*p))
3952 p++;
3953 if (*p == '-') {
3954 p++;
3955 if(c != *p) {
3956 if(!is_valid_option(p, typestr)) {
3958 monitor_printf(mon, "%s: unsupported option -%c\n",
3959 cmdname, *p);
3960 goto fail;
3961 } else {
3962 skip_key = 1;
3965 if(skip_key) {
3966 p = tmp;
3967 } else {
3968 /* has option */
3969 p++;
3970 qdict_put(qdict, key, qbool_from_int(1));
3974 break;
3975 case 'S':
3977 /* package all remaining string */
3978 int len;
3980 while (qemu_isspace(*p)) {
3981 p++;
3983 if (*typestr == '?') {
3984 typestr++;
3985 if (*p == '\0') {
3986 /* no remaining string: NULL argument */
3987 break;
3990 len = strlen(p);
3991 if (len <= 0) {
3992 monitor_printf(mon, "%s: string expected\n",
3993 cmdname);
3994 break;
3996 qdict_put(qdict, key, qstring_from_str(p));
3997 p += len;
3999 break;
4000 default:
4001 bad_type:
4002 monitor_printf(mon, "%s: unknown type '%c'\n", cmdname, c);
4003 goto fail;
4005 g_free(key);
4006 key = NULL;
4008 /* check that all arguments were parsed */
4009 while (qemu_isspace(*p))
4010 p++;
4011 if (*p != '\0') {
4012 monitor_printf(mon, "%s: extraneous characters at the end of line\n",
4013 cmdname);
4014 goto fail;
4017 return cmd;
4019 fail:
4020 g_free(key);
4021 return NULL;
4024 void monitor_set_error(Monitor *mon, QError *qerror)
4026 /* report only the first error */
4027 if (!mon->error) {
4028 mon->error = qerror;
4029 } else {
4030 QDECREF(qerror);
4034 static void handle_user_command(Monitor *mon, const char *cmdline)
4036 QDict *qdict;
4037 const mon_cmd_t *cmd;
4039 qdict = qdict_new();
4041 cmd = monitor_parse_command(mon, cmdline, 0, mon->cmd_table, qdict);
4042 if (cmd) {
4043 cmd->mhandler.cmd(mon, qdict);
4046 QDECREF(qdict);
4049 static void cmd_completion(Monitor *mon, const char *name, const char *list)
4051 const char *p, *pstart;
4052 char cmd[128];
4053 int len;
4055 p = list;
4056 for(;;) {
4057 pstart = p;
4058 p = strchr(p, '|');
4059 if (!p)
4060 p = pstart + strlen(pstart);
4061 len = p - pstart;
4062 if (len > sizeof(cmd) - 2)
4063 len = sizeof(cmd) - 2;
4064 memcpy(cmd, pstart, len);
4065 cmd[len] = '\0';
4066 if (name[0] == '\0' || !strncmp(name, cmd, strlen(name))) {
4067 readline_add_completion(mon->rs, cmd);
4069 if (*p == '\0')
4070 break;
4071 p++;
4075 static void file_completion(Monitor *mon, const char *input)
4077 DIR *ffs;
4078 struct dirent *d;
4079 char path[1024];
4080 char file[1024], file_prefix[1024];
4081 int input_path_len;
4082 const char *p;
4084 p = strrchr(input, '/');
4085 if (!p) {
4086 input_path_len = 0;
4087 pstrcpy(file_prefix, sizeof(file_prefix), input);
4088 pstrcpy(path, sizeof(path), ".");
4089 } else {
4090 input_path_len = p - input + 1;
4091 memcpy(path, input, input_path_len);
4092 if (input_path_len > sizeof(path) - 1)
4093 input_path_len = sizeof(path) - 1;
4094 path[input_path_len] = '\0';
4095 pstrcpy(file_prefix, sizeof(file_prefix), p + 1);
4097 #ifdef DEBUG_COMPLETION
4098 monitor_printf(mon, "input='%s' path='%s' prefix='%s'\n",
4099 input, path, file_prefix);
4100 #endif
4101 ffs = opendir(path);
4102 if (!ffs)
4103 return;
4104 for(;;) {
4105 struct stat sb;
4106 d = readdir(ffs);
4107 if (!d)
4108 break;
4110 if (strcmp(d->d_name, ".") == 0 || strcmp(d->d_name, "..") == 0) {
4111 continue;
4114 if (strstart(d->d_name, file_prefix, NULL)) {
4115 memcpy(file, input, input_path_len);
4116 if (input_path_len < sizeof(file))
4117 pstrcpy(file + input_path_len, sizeof(file) - input_path_len,
4118 d->d_name);
4119 /* stat the file to find out if it's a directory.
4120 * In that case add a slash to speed up typing long paths
4122 if (stat(file, &sb) == 0 && S_ISDIR(sb.st_mode)) {
4123 pstrcat(file, sizeof(file), "/");
4125 readline_add_completion(mon->rs, file);
4128 closedir(ffs);
4131 static const char *next_arg_type(const char *typestr)
4133 const char *p = strchr(typestr, ':');
4134 return (p != NULL ? ++p : typestr);
4137 static void add_completion_option(ReadLineState *rs, const char *str,
4138 const char *option)
4140 if (!str || !option) {
4141 return;
4143 if (!strncmp(option, str, strlen(str))) {
4144 readline_add_completion(rs, option);
4148 void chardev_add_completion(ReadLineState *rs, int nb_args, const char *str)
4150 size_t len;
4151 ChardevBackendInfoList *list, *start;
4153 if (nb_args != 2) {
4154 return;
4156 len = strlen(str);
4157 readline_set_completion_index(rs, len);
4159 start = list = qmp_query_chardev_backends(NULL);
4160 while (list) {
4161 const char *chr_name = list->value->name;
4163 if (!strncmp(chr_name, str, len)) {
4164 readline_add_completion(rs, chr_name);
4166 list = list->next;
4168 qapi_free_ChardevBackendInfoList(start);
4171 void netdev_add_completion(ReadLineState *rs, int nb_args, const char *str)
4173 size_t len;
4174 int i;
4176 if (nb_args != 2) {
4177 return;
4179 len = strlen(str);
4180 readline_set_completion_index(rs, len);
4181 for (i = 0; NetClientOptionsKind_lookup[i]; i++) {
4182 add_completion_option(rs, str, NetClientOptionsKind_lookup[i]);
4186 void device_add_completion(ReadLineState *rs, int nb_args, const char *str)
4188 GSList *list, *elt;
4189 size_t len;
4191 if (nb_args != 2) {
4192 return;
4195 len = strlen(str);
4196 readline_set_completion_index(rs, len);
4197 list = elt = object_class_get_list(TYPE_DEVICE, false);
4198 while (elt) {
4199 const char *name;
4200 DeviceClass *dc = OBJECT_CLASS_CHECK(DeviceClass, elt->data,
4201 TYPE_DEVICE);
4202 name = object_class_get_name(OBJECT_CLASS(dc));
4204 if (!dc->cannot_instantiate_with_device_add_yet
4205 && !strncmp(name, str, len)) {
4206 readline_add_completion(rs, name);
4208 elt = elt->next;
4210 g_slist_free(list);
4213 void object_add_completion(ReadLineState *rs, int nb_args, const char *str)
4215 GSList *list, *elt;
4216 size_t len;
4218 if (nb_args != 2) {
4219 return;
4222 len = strlen(str);
4223 readline_set_completion_index(rs, len);
4224 list = elt = object_class_get_list(TYPE_USER_CREATABLE, false);
4225 while (elt) {
4226 const char *name;
4228 name = object_class_get_name(OBJECT_CLASS(elt->data));
4229 if (!strncmp(name, str, len) && strcmp(name, TYPE_USER_CREATABLE)) {
4230 readline_add_completion(rs, name);
4232 elt = elt->next;
4234 g_slist_free(list);
4237 static void peripheral_device_del_completion(ReadLineState *rs,
4238 const char *str, size_t len)
4240 Object *peripheral = container_get(qdev_get_machine(), "/peripheral");
4241 GSList *list, *item;
4243 list = qdev_build_hotpluggable_device_list(peripheral);
4244 if (!list) {
4245 return;
4248 for (item = list; item; item = g_slist_next(item)) {
4249 DeviceState *dev = item->data;
4251 if (dev->id && !strncmp(str, dev->id, len)) {
4252 readline_add_completion(rs, dev->id);
4256 g_slist_free(list);
4259 void chardev_remove_completion(ReadLineState *rs, int nb_args, const char *str)
4261 size_t len;
4262 ChardevInfoList *list, *start;
4264 if (nb_args != 2) {
4265 return;
4267 len = strlen(str);
4268 readline_set_completion_index(rs, len);
4270 start = list = qmp_query_chardev(NULL);
4271 while (list) {
4272 ChardevInfo *chr = list->value;
4274 if (!strncmp(chr->label, str, len)) {
4275 readline_add_completion(rs, chr->label);
4277 list = list->next;
4279 qapi_free_ChardevInfoList(start);
4282 static void ringbuf_completion(ReadLineState *rs, const char *str)
4284 size_t len;
4285 ChardevInfoList *list, *start;
4287 len = strlen(str);
4288 readline_set_completion_index(rs, len);
4290 start = list = qmp_query_chardev(NULL);
4291 while (list) {
4292 ChardevInfo *chr_info = list->value;
4294 if (!strncmp(chr_info->label, str, len)) {
4295 CharDriverState *chr = qemu_chr_find(chr_info->label);
4296 if (chr && chr_is_ringbuf(chr)) {
4297 readline_add_completion(rs, chr_info->label);
4300 list = list->next;
4302 qapi_free_ChardevInfoList(start);
4305 void ringbuf_write_completion(ReadLineState *rs, int nb_args, const char *str)
4307 if (nb_args != 2) {
4308 return;
4310 ringbuf_completion(rs, str);
4313 void device_del_completion(ReadLineState *rs, int nb_args, const char *str)
4315 size_t len;
4317 if (nb_args != 2) {
4318 return;
4321 len = strlen(str);
4322 readline_set_completion_index(rs, len);
4323 peripheral_device_del_completion(rs, str, len);
4326 void object_del_completion(ReadLineState *rs, int nb_args, const char *str)
4328 ObjectPropertyInfoList *list, *start;
4329 size_t len;
4331 if (nb_args != 2) {
4332 return;
4334 len = strlen(str);
4335 readline_set_completion_index(rs, len);
4337 start = list = qmp_qom_list("/objects", NULL);
4338 while (list) {
4339 ObjectPropertyInfo *info = list->value;
4341 if (!strncmp(info->type, "child<", 5)
4342 && !strncmp(info->name, str, len)) {
4343 readline_add_completion(rs, info->name);
4345 list = list->next;
4347 qapi_free_ObjectPropertyInfoList(start);
4350 void sendkey_completion(ReadLineState *rs, int nb_args, const char *str)
4352 int i;
4353 char *sep;
4354 size_t len;
4356 if (nb_args != 2) {
4357 return;
4359 sep = strrchr(str, '-');
4360 if (sep) {
4361 str = sep + 1;
4363 len = strlen(str);
4364 readline_set_completion_index(rs, len);
4365 for (i = 0; i < Q_KEY_CODE_MAX; i++) {
4366 if (!strncmp(str, QKeyCode_lookup[i], len)) {
4367 readline_add_completion(rs, QKeyCode_lookup[i]);
4372 void set_link_completion(ReadLineState *rs, int nb_args, const char *str)
4374 size_t len;
4376 len = strlen(str);
4377 readline_set_completion_index(rs, len);
4378 if (nb_args == 2) {
4379 NetClientState *ncs[MAX_QUEUE_NUM];
4380 int count, i;
4381 count = qemu_find_net_clients_except(NULL, ncs,
4382 NET_CLIENT_OPTIONS_KIND_NONE,
4383 MAX_QUEUE_NUM);
4384 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
4385 const char *name = ncs[i]->name;
4386 if (!strncmp(str, name, len)) {
4387 readline_add_completion(rs, name);
4390 } else if (nb_args == 3) {
4391 add_completion_option(rs, str, "on");
4392 add_completion_option(rs, str, "off");
4396 void netdev_del_completion(ReadLineState *rs, int nb_args, const char *str)
4398 int len, count, i;
4399 NetClientState *ncs[MAX_QUEUE_NUM];
4401 if (nb_args != 2) {
4402 return;
4405 len = strlen(str);
4406 readline_set_completion_index(rs, len);
4407 count = qemu_find_net_clients_except(NULL, ncs, NET_CLIENT_OPTIONS_KIND_NIC,
4408 MAX_QUEUE_NUM);
4409 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
4410 QemuOpts *opts;
4411 const char *name = ncs[i]->name;
4412 if (strncmp(str, name, len)) {
4413 continue;
4415 opts = qemu_opts_find(qemu_find_opts_err("netdev", NULL), name);
4416 if (opts) {
4417 readline_add_completion(rs, name);
4422 void watchdog_action_completion(ReadLineState *rs, int nb_args, const char *str)
4424 int i;
4426 if (nb_args != 2) {
4427 return;
4429 readline_set_completion_index(rs, strlen(str));
4430 for (i = 0; WatchdogExpirationAction_lookup[i]; i++) {
4431 add_completion_option(rs, str, WatchdogExpirationAction_lookup[i]);
4435 void migrate_set_capability_completion(ReadLineState *rs, int nb_args,
4436 const char *str)
4438 size_t len;
4440 len = strlen(str);
4441 readline_set_completion_index(rs, len);
4442 if (nb_args == 2) {
4443 int i;
4444 for (i = 0; i < MIGRATION_CAPABILITY_MAX; i++) {
4445 const char *name = MigrationCapability_lookup[i];
4446 if (!strncmp(str, name, len)) {
4447 readline_add_completion(rs, name);
4450 } else if (nb_args == 3) {
4451 add_completion_option(rs, str, "on");
4452 add_completion_option(rs, str, "off");
4456 void migrate_set_parameter_completion(ReadLineState *rs, int nb_args,
4457 const char *str)
4459 size_t len;
4461 len = strlen(str);
4462 readline_set_completion_index(rs, len);
4463 if (nb_args == 2) {
4464 int i;
4465 for (i = 0; i < MIGRATION_PARAMETER_MAX; i++) {
4466 const char *name = MigrationParameter_lookup[i];
4467 if (!strncmp(str, name, len)) {
4468 readline_add_completion(rs, name);
4474 void host_net_add_completion(ReadLineState *rs, int nb_args, const char *str)
4476 int i;
4477 size_t len;
4478 if (nb_args != 2) {
4479 return;
4481 len = strlen(str);
4482 readline_set_completion_index(rs, len);
4483 for (i = 0; host_net_devices[i]; i++) {
4484 if (!strncmp(host_net_devices[i], str, len)) {
4485 readline_add_completion(rs, host_net_devices[i]);
4490 void host_net_remove_completion(ReadLineState *rs, int nb_args, const char *str)
4492 NetClientState *ncs[MAX_QUEUE_NUM];
4493 int count, i, len;
4495 len = strlen(str);
4496 readline_set_completion_index(rs, len);
4497 if (nb_args == 2) {
4498 count = qemu_find_net_clients_except(NULL, ncs,
4499 NET_CLIENT_OPTIONS_KIND_NONE,
4500 MAX_QUEUE_NUM);
4501 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
4502 int id;
4503 char name[16];
4505 if (net_hub_id_for_client(ncs[i], &id)) {
4506 continue;
4508 snprintf(name, sizeof(name), "%d", id);
4509 if (!strncmp(str, name, len)) {
4510 readline_add_completion(rs, name);
4513 return;
4514 } else if (nb_args == 3) {
4515 count = qemu_find_net_clients_except(NULL, ncs,
4516 NET_CLIENT_OPTIONS_KIND_NIC,
4517 MAX_QUEUE_NUM);
4518 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
4519 int id;
4520 const char *name;
4522 if (ncs[i]->info->type == NET_CLIENT_OPTIONS_KIND_HUBPORT ||
4523 net_hub_id_for_client(ncs[i], &id)) {
4524 continue;
4526 name = ncs[i]->name;
4527 if (!strncmp(str, name, len)) {
4528 readline_add_completion(rs, name);
4531 return;
4535 static void vm_completion(ReadLineState *rs, const char *str)
4537 size_t len;
4538 BlockDriverState *bs = NULL;
4540 len = strlen(str);
4541 readline_set_completion_index(rs, len);
4542 while ((bs = bdrv_next(bs))) {
4543 SnapshotInfoList *snapshots, *snapshot;
4545 if (!bdrv_can_snapshot(bs)) {
4546 continue;
4548 if (bdrv_query_snapshot_info_list(bs, &snapshots, NULL)) {
4549 continue;
4551 snapshot = snapshots;
4552 while (snapshot) {
4553 char *completion = snapshot->value->name;
4554 if (!strncmp(str, completion, len)) {
4555 readline_add_completion(rs, completion);
4557 completion = snapshot->value->id;
4558 if (!strncmp(str, completion, len)) {
4559 readline_add_completion(rs, completion);
4561 snapshot = snapshot->next;
4563 qapi_free_SnapshotInfoList(snapshots);
4568 void delvm_completion(ReadLineState *rs, int nb_args, const char *str)
4570 if (nb_args == 2) {
4571 vm_completion(rs, str);
4575 void loadvm_completion(ReadLineState *rs, int nb_args, const char *str)
4577 if (nb_args == 2) {
4578 vm_completion(rs, str);
4582 static void monitor_find_completion_by_table(Monitor *mon,
4583 const mon_cmd_t *cmd_table,
4584 char **args,
4585 int nb_args)
4587 const char *cmdname;
4588 int i;
4589 const char *ptype, *str, *name;
4590 const mon_cmd_t *cmd;
4591 BlockDriverState *bs;
4593 if (nb_args <= 1) {
4594 /* command completion */
4595 if (nb_args == 0)
4596 cmdname = "";
4597 else
4598 cmdname = args[0];
4599 readline_set_completion_index(mon->rs, strlen(cmdname));
4600 for (cmd = cmd_table; cmd->name != NULL; cmd++) {
4601 cmd_completion(mon, cmdname, cmd->name);
4603 } else {
4604 /* find the command */
4605 for (cmd = cmd_table; cmd->name != NULL; cmd++) {
4606 if (compare_cmd(args[0], cmd->name)) {
4607 break;
4610 if (!cmd->name) {
4611 return;
4614 if (cmd->sub_table) {
4615 /* do the job again */
4616 monitor_find_completion_by_table(mon, cmd->sub_table,
4617 &args[1], nb_args - 1);
4618 return;
4620 if (cmd->command_completion) {
4621 cmd->command_completion(mon->rs, nb_args, args[nb_args - 1]);
4622 return;
4625 ptype = next_arg_type(cmd->args_type);
4626 for(i = 0; i < nb_args - 2; i++) {
4627 if (*ptype != '\0') {
4628 ptype = next_arg_type(ptype);
4629 while (*ptype == '?')
4630 ptype = next_arg_type(ptype);
4633 str = args[nb_args - 1];
4634 while (*ptype == '-' && ptype[1] != '\0') {
4635 ptype = next_arg_type(ptype);
4637 switch(*ptype) {
4638 case 'F':
4639 /* file completion */
4640 readline_set_completion_index(mon->rs, strlen(str));
4641 file_completion(mon, str);
4642 break;
4643 case 'B':
4644 /* block device name completion */
4645 readline_set_completion_index(mon->rs, strlen(str));
4646 for (bs = bdrv_next(NULL); bs; bs = bdrv_next(bs)) {
4647 name = bdrv_get_device_name(bs);
4648 if (str[0] == '\0' ||
4649 !strncmp(name, str, strlen(str))) {
4650 readline_add_completion(mon->rs, name);
4653 break;
4654 case 's':
4655 case 'S':
4656 if (!strcmp(cmd->name, "help|?")) {
4657 monitor_find_completion_by_table(mon, cmd_table,
4658 &args[1], nb_args - 1);
4660 break;
4661 default:
4662 break;
4667 static void monitor_find_completion(void *opaque,
4668 const char *cmdline)
4670 Monitor *mon = opaque;
4671 char *args[MAX_ARGS];
4672 int nb_args, len;
4674 /* 1. parse the cmdline */
4675 if (parse_cmdline(cmdline, &nb_args, args) < 0) {
4676 return;
4678 #ifdef DEBUG_COMPLETION
4680 int i;
4681 for (i = 0; i < nb_args; i++) {
4682 monitor_printf(mon, "arg%d = '%s'\n", i, args[i]);
4685 #endif
4687 /* if the line ends with a space, it means we want to complete the
4688 next arg */
4689 len = strlen(cmdline);
4690 if (len > 0 && qemu_isspace(cmdline[len - 1])) {
4691 if (nb_args >= MAX_ARGS) {
4692 goto cleanup;
4694 args[nb_args++] = g_strdup("");
4697 /* 2. auto complete according to args */
4698 monitor_find_completion_by_table(mon, mon->cmd_table, args, nb_args);
4700 cleanup:
4701 free_cmdline_args(args, nb_args);
4704 static int monitor_can_read(void *opaque)
4706 Monitor *mon = opaque;
4708 return (mon->suspend_cnt == 0) ? 1 : 0;
4711 static bool invalid_qmp_mode(const Monitor *mon, const mon_cmd_t *cmd,
4712 Error **errp)
4714 bool is_cap = cmd->mhandler.cmd_new == do_qmp_capabilities;
4715 if (is_cap && qmp_cmd_mode(mon)) {
4716 error_set(errp, ERROR_CLASS_COMMAND_NOT_FOUND,
4717 "Capabilities negotiation is already complete, command "
4718 "'%s' ignored", cmd->name);
4719 return true;
4721 if (!is_cap && !qmp_cmd_mode(mon)) {
4722 error_set(errp, ERROR_CLASS_COMMAND_NOT_FOUND,
4723 "Expecting capabilities negotiation with "
4724 "'qmp_capabilities' before command '%s'", cmd->name);
4725 return true;
4727 return false;
4731 * Argument validation rules:
4733 * 1. The argument must exist in cmd_args qdict
4734 * 2. The argument type must be the expected one
4736 * Special case: If the argument doesn't exist in cmd_args and
4737 * the QMP_ACCEPT_UNKNOWNS flag is set, then the
4738 * checking is skipped for it.
4740 static void check_client_args_type(const QDict *client_args,
4741 const QDict *cmd_args, int flags,
4742 Error **errp)
4744 const QDictEntry *ent;
4746 for (ent = qdict_first(client_args); ent;ent = qdict_next(client_args,ent)){
4747 QObject *obj;
4748 QString *arg_type;
4749 const QObject *client_arg = qdict_entry_value(ent);
4750 const char *client_arg_name = qdict_entry_key(ent);
4752 obj = qdict_get(cmd_args, client_arg_name);
4753 if (!obj) {
4754 if (flags & QMP_ACCEPT_UNKNOWNS) {
4755 /* handler accepts unknowns */
4756 continue;
4758 /* client arg doesn't exist */
4759 error_set(errp, QERR_INVALID_PARAMETER, client_arg_name);
4760 return;
4763 arg_type = qobject_to_qstring(obj);
4764 assert(arg_type != NULL);
4766 /* check if argument's type is correct */
4767 switch (qstring_get_str(arg_type)[0]) {
4768 case 'F':
4769 case 'B':
4770 case 's':
4771 if (qobject_type(client_arg) != QTYPE_QSTRING) {
4772 error_set(errp, QERR_INVALID_PARAMETER_TYPE,
4773 client_arg_name, "string");
4774 return;
4776 break;
4777 case 'i':
4778 case 'l':
4779 case 'M':
4780 case 'o':
4781 if (qobject_type(client_arg) != QTYPE_QINT) {
4782 error_set(errp, QERR_INVALID_PARAMETER_TYPE,
4783 client_arg_name, "int");
4784 return;
4786 break;
4787 case 'T':
4788 if (qobject_type(client_arg) != QTYPE_QINT &&
4789 qobject_type(client_arg) != QTYPE_QFLOAT) {
4790 error_set(errp, QERR_INVALID_PARAMETER_TYPE,
4791 client_arg_name, "number");
4792 return;
4794 break;
4795 case 'b':
4796 case '-':
4797 if (qobject_type(client_arg) != QTYPE_QBOOL) {
4798 error_set(errp, QERR_INVALID_PARAMETER_TYPE,
4799 client_arg_name, "bool");
4800 return;
4802 break;
4803 case 'O':
4804 assert(flags & QMP_ACCEPT_UNKNOWNS);
4805 break;
4806 case 'q':
4807 /* Any QObject can be passed. */
4808 break;
4809 case '/':
4810 case '.':
4812 * These types are not supported by QMP and thus are not
4813 * handled here. Fall through.
4815 default:
4816 abort();
4822 * - Check if the client has passed all mandatory args
4823 * - Set special flags for argument validation
4825 static void check_mandatory_args(const QDict *cmd_args,
4826 const QDict *client_args, int *flags,
4827 Error **errp)
4829 const QDictEntry *ent;
4831 for (ent = qdict_first(cmd_args); ent; ent = qdict_next(cmd_args, ent)) {
4832 const char *cmd_arg_name = qdict_entry_key(ent);
4833 QString *type = qobject_to_qstring(qdict_entry_value(ent));
4834 assert(type != NULL);
4836 if (qstring_get_str(type)[0] == 'O') {
4837 assert((*flags & QMP_ACCEPT_UNKNOWNS) == 0);
4838 *flags |= QMP_ACCEPT_UNKNOWNS;
4839 } else if (qstring_get_str(type)[0] != '-' &&
4840 qstring_get_str(type)[1] != '?' &&
4841 !qdict_haskey(client_args, cmd_arg_name)) {
4842 error_set(errp, QERR_MISSING_PARAMETER, cmd_arg_name);
4843 return;
4848 static QDict *qdict_from_args_type(const char *args_type)
4850 int i;
4851 QDict *qdict;
4852 QString *key, *type, *cur_qs;
4854 assert(args_type != NULL);
4856 qdict = qdict_new();
4858 if (args_type == NULL || args_type[0] == '\0') {
4859 /* no args, empty qdict */
4860 goto out;
4863 key = qstring_new();
4864 type = qstring_new();
4866 cur_qs = key;
4868 for (i = 0;; i++) {
4869 switch (args_type[i]) {
4870 case ',':
4871 case '\0':
4872 qdict_put(qdict, qstring_get_str(key), type);
4873 QDECREF(key);
4874 if (args_type[i] == '\0') {
4875 goto out;
4877 type = qstring_new(); /* qdict has ref */
4878 cur_qs = key = qstring_new();
4879 break;
4880 case ':':
4881 cur_qs = type;
4882 break;
4883 default:
4884 qstring_append_chr(cur_qs, args_type[i]);
4885 break;
4889 out:
4890 return qdict;
4894 * Client argument checking rules:
4896 * 1. Client must provide all mandatory arguments
4897 * 2. Each argument provided by the client must be expected
4898 * 3. Each argument provided by the client must have the type expected
4899 * by the command
4901 static void qmp_check_client_args(const mon_cmd_t *cmd, QDict *client_args,
4902 Error **errp)
4904 Error *err = NULL;
4905 int flags;
4906 QDict *cmd_args;
4908 cmd_args = qdict_from_args_type(cmd->args_type);
4910 flags = 0;
4911 check_mandatory_args(cmd_args, client_args, &flags, &err);
4912 if (err) {
4913 goto out;
4916 check_client_args_type(client_args, cmd_args, flags, &err);
4918 out:
4919 error_propagate(errp, err);
4920 QDECREF(cmd_args);
4924 * Input object checking rules
4926 * 1. Input object must be a dict
4927 * 2. The "execute" key must exist
4928 * 3. The "execute" key must be a string
4929 * 4. If the "arguments" key exists, it must be a dict
4930 * 5. If the "id" key exists, it can be anything (ie. json-value)
4931 * 6. Any argument not listed above is considered invalid
4933 static QDict *qmp_check_input_obj(QObject *input_obj, Error **errp)
4935 const QDictEntry *ent;
4936 int has_exec_key = 0;
4937 QDict *input_dict;
4939 if (qobject_type(input_obj) != QTYPE_QDICT) {
4940 error_set(errp, QERR_QMP_BAD_INPUT_OBJECT, "object");
4941 return NULL;
4944 input_dict = qobject_to_qdict(input_obj);
4946 for (ent = qdict_first(input_dict); ent; ent = qdict_next(input_dict, ent)){
4947 const char *arg_name = qdict_entry_key(ent);
4948 const QObject *arg_obj = qdict_entry_value(ent);
4950 if (!strcmp(arg_name, "execute")) {
4951 if (qobject_type(arg_obj) != QTYPE_QSTRING) {
4952 error_set(errp, QERR_QMP_BAD_INPUT_OBJECT_MEMBER,
4953 "execute", "string");
4954 return NULL;
4956 has_exec_key = 1;
4957 } else if (!strcmp(arg_name, "arguments")) {
4958 if (qobject_type(arg_obj) != QTYPE_QDICT) {
4959 error_set(errp, QERR_QMP_BAD_INPUT_OBJECT_MEMBER,
4960 "arguments", "object");
4961 return NULL;
4963 } else {
4964 error_set(errp, QERR_QMP_EXTRA_MEMBER, arg_name);
4965 return NULL;
4969 if (!has_exec_key) {
4970 error_set(errp, QERR_QMP_BAD_INPUT_OBJECT, "execute");
4971 return NULL;
4974 return input_dict;
4977 static void handle_qmp_command(JSONMessageParser *parser, QList *tokens)
4979 Error *local_err = NULL;
4980 QObject *obj, *data;
4981 QDict *input, *args;
4982 const mon_cmd_t *cmd;
4983 const char *cmd_name;
4984 Monitor *mon = cur_mon;
4986 args = input = NULL;
4987 data = NULL;
4989 obj = json_parser_parse(tokens, NULL);
4990 if (!obj) {
4991 // FIXME: should be triggered in json_parser_parse()
4992 qerror_report(QERR_JSON_PARSING);
4993 goto err_out;
4996 input = qmp_check_input_obj(obj, &local_err);
4997 if (!input) {
4998 qerror_report_err(local_err);
4999 qobject_decref(obj);
5000 goto err_out;
5003 mon->mc->id = qdict_get(input, "id");
5004 qobject_incref(mon->mc->id);
5006 cmd_name = qdict_get_str(input, "execute");
5007 trace_handle_qmp_command(mon, cmd_name);
5008 cmd = qmp_find_cmd(cmd_name);
5009 if (!cmd) {
5010 qerror_report(ERROR_CLASS_COMMAND_NOT_FOUND,
5011 "The command %s has not been found", cmd_name);
5012 goto err_out;
5014 if (invalid_qmp_mode(mon, cmd, &local_err)) {
5015 qerror_report_err(local_err);
5016 goto err_out;
5019 obj = qdict_get(input, "arguments");
5020 if (!obj) {
5021 args = qdict_new();
5022 } else {
5023 args = qobject_to_qdict(obj);
5024 QINCREF(args);
5027 qmp_check_client_args(cmd, args, &local_err);
5028 if (local_err) {
5029 qerror_report_err(local_err);
5030 goto err_out;
5033 if (cmd->mhandler.cmd_new(mon, args, &data)) {
5034 /* Command failed... */
5035 if (!monitor_has_error(mon)) {
5036 /* ... without setting an error, so make one up */
5037 qerror_report(QERR_UNDEFINED_ERROR);
5041 err_out:
5042 monitor_protocol_emitter(mon, data);
5043 qobject_decref(data);
5044 QDECREF(input);
5045 QDECREF(args);
5049 * monitor_control_read(): Read and handle QMP input
5051 static void monitor_control_read(void *opaque, const uint8_t *buf, int size)
5053 Monitor *old_mon = cur_mon;
5055 cur_mon = opaque;
5057 json_message_parser_feed(&cur_mon->mc->parser, (const char *) buf, size);
5059 cur_mon = old_mon;
5062 static void monitor_read(void *opaque, const uint8_t *buf, int size)
5064 Monitor *old_mon = cur_mon;
5065 int i;
5067 cur_mon = opaque;
5069 if (cur_mon->rs) {
5070 for (i = 0; i < size; i++)
5071 readline_handle_byte(cur_mon->rs, buf[i]);
5072 } else {
5073 if (size == 0 || buf[size - 1] != 0)
5074 monitor_printf(cur_mon, "corrupted command\n");
5075 else
5076 handle_user_command(cur_mon, (char *)buf);
5079 cur_mon = old_mon;
5082 static void monitor_command_cb(void *opaque, const char *cmdline,
5083 void *readline_opaque)
5085 Monitor *mon = opaque;
5087 monitor_suspend(mon);
5088 handle_user_command(mon, cmdline);
5089 monitor_resume(mon);
5092 int monitor_suspend(Monitor *mon)
5094 if (!mon->rs)
5095 return -ENOTTY;
5096 mon->suspend_cnt++;
5097 return 0;
5100 void monitor_resume(Monitor *mon)
5102 if (!mon->rs)
5103 return;
5104 if (--mon->suspend_cnt == 0)
5105 readline_show_prompt(mon->rs);
5108 static QObject *get_qmp_greeting(void)
5110 QObject *ver = NULL;
5112 qmp_marshal_input_query_version(NULL, NULL, &ver);
5113 return qobject_from_jsonf("{'QMP':{'version': %p,'capabilities': []}}",ver);
5117 * monitor_control_event(): Print QMP gretting
5119 static void monitor_control_event(void *opaque, int event)
5121 QObject *data;
5122 Monitor *mon = opaque;
5124 switch (event) {
5125 case CHR_EVENT_OPENED:
5126 mon->mc->command_mode = 0;
5127 data = get_qmp_greeting();
5128 monitor_json_emitter(mon, data);
5129 qobject_decref(data);
5130 mon_refcount++;
5131 break;
5132 case CHR_EVENT_CLOSED:
5133 json_message_parser_destroy(&mon->mc->parser);
5134 json_message_parser_init(&mon->mc->parser, handle_qmp_command);
5135 mon_refcount--;
5136 monitor_fdsets_cleanup();
5137 break;
5141 static void monitor_event(void *opaque, int event)
5143 Monitor *mon = opaque;
5145 switch (event) {
5146 case CHR_EVENT_MUX_IN:
5147 qemu_mutex_lock(&mon->out_lock);
5148 mon->mux_out = 0;
5149 qemu_mutex_unlock(&mon->out_lock);
5150 if (mon->reset_seen) {
5151 readline_restart(mon->rs);
5152 monitor_resume(mon);
5153 monitor_flush(mon);
5154 } else {
5155 mon->suspend_cnt = 0;
5157 break;
5159 case CHR_EVENT_MUX_OUT:
5160 if (mon->reset_seen) {
5161 if (mon->suspend_cnt == 0) {
5162 monitor_printf(mon, "\n");
5164 monitor_flush(mon);
5165 monitor_suspend(mon);
5166 } else {
5167 mon->suspend_cnt++;
5169 qemu_mutex_lock(&mon->out_lock);
5170 mon->mux_out = 1;
5171 qemu_mutex_unlock(&mon->out_lock);
5172 break;
5174 case CHR_EVENT_OPENED:
5175 monitor_printf(mon, "QEMU %s monitor - type 'help' for more "
5176 "information\n", QEMU_VERSION);
5177 if (!mon->mux_out) {
5178 readline_restart(mon->rs);
5179 readline_show_prompt(mon->rs);
5181 mon->reset_seen = 1;
5182 mon_refcount++;
5183 break;
5185 case CHR_EVENT_CLOSED:
5186 mon_refcount--;
5187 monitor_fdsets_cleanup();
5188 break;
5192 static int
5193 compare_mon_cmd(const void *a, const void *b)
5195 return strcmp(((const mon_cmd_t *)a)->name,
5196 ((const mon_cmd_t *)b)->name);
5199 static void sortcmdlist(void)
5201 int array_num;
5202 int elem_size = sizeof(mon_cmd_t);
5204 array_num = sizeof(mon_cmds)/elem_size-1;
5205 qsort((void *)mon_cmds, array_num, elem_size, compare_mon_cmd);
5207 array_num = sizeof(info_cmds)/elem_size-1;
5208 qsort((void *)info_cmds, array_num, elem_size, compare_mon_cmd);
5213 * Local variables:
5214 * c-indent-level: 4
5215 * c-basic-offset: 4
5216 * tab-width: 8
5217 * End:
5220 /* These functions just adapt the readline interface in a typesafe way. We
5221 * could cast function pointers but that discards compiler checks.
5223 static void GCC_FMT_ATTR(2, 3) monitor_readline_printf(void *opaque,
5224 const char *fmt, ...)
5226 va_list ap;
5227 va_start(ap, fmt);
5228 monitor_vprintf(opaque, fmt, ap);
5229 va_end(ap);
5232 static void monitor_readline_flush(void *opaque)
5234 monitor_flush(opaque);
5237 static void __attribute__((constructor)) monitor_lock_init(void)
5239 qemu_mutex_init(&monitor_lock);
5242 void monitor_init(CharDriverState *chr, int flags)
5244 static int is_first_init = 1;
5245 Monitor *mon;
5247 if (is_first_init) {
5248 monitor_qapi_event_init();
5249 sortcmdlist();
5250 is_first_init = 0;
5253 mon = g_malloc(sizeof(*mon));
5254 monitor_data_init(mon);
5256 mon->chr = chr;
5257 mon->flags = flags;
5258 if (flags & MONITOR_USE_READLINE) {
5259 mon->rs = readline_init(monitor_readline_printf,
5260 monitor_readline_flush,
5261 mon,
5262 monitor_find_completion);
5263 monitor_read_command(mon, 0);
5266 if (monitor_ctrl_mode(mon)) {
5267 mon->mc = g_malloc0(sizeof(MonitorControl));
5268 /* Control mode requires special handlers */
5269 qemu_chr_add_handlers(chr, monitor_can_read, monitor_control_read,
5270 monitor_control_event, mon);
5271 qemu_chr_fe_set_echo(chr, true);
5273 json_message_parser_init(&mon->mc->parser, handle_qmp_command);
5274 } else {
5275 qemu_chr_add_handlers(chr, monitor_can_read, monitor_read,
5276 monitor_event, mon);
5279 qemu_mutex_lock(&monitor_lock);
5280 QLIST_INSERT_HEAD(&mon_list, mon, entry);
5281 qemu_mutex_unlock(&monitor_lock);
5283 if (!default_mon || (flags & MONITOR_IS_DEFAULT))
5284 default_mon = mon;
5287 static void bdrv_password_cb(void *opaque, const char *password,
5288 void *readline_opaque)
5290 Monitor *mon = opaque;
5291 BlockDriverState *bs = readline_opaque;
5292 int ret = 0;
5293 Error *local_err = NULL;
5295 bdrv_add_key(bs, password, &local_err);
5296 if (local_err) {
5297 monitor_printf(mon, "%s\n", error_get_pretty(local_err));
5298 error_free(local_err);
5299 ret = -EPERM;
5301 if (mon->password_completion_cb)
5302 mon->password_completion_cb(mon->password_opaque, ret);
5304 monitor_read_command(mon, 1);
5307 int monitor_read_bdrv_key_start(Monitor *mon, BlockDriverState *bs,
5308 BlockCompletionFunc *completion_cb,
5309 void *opaque)
5311 int err;
5313 monitor_printf(mon, "%s (%s) is encrypted.\n", bdrv_get_device_name(bs),
5314 bdrv_get_encrypted_filename(bs));
5316 mon->password_completion_cb = completion_cb;
5317 mon->password_opaque = opaque;
5319 err = monitor_read_password(mon, bdrv_password_cb, bs);
5321 if (err && completion_cb)
5322 completion_cb(opaque, err);
5324 return err;
5327 int monitor_read_block_device_key(Monitor *mon, const char *device,
5328 BlockCompletionFunc *completion_cb,
5329 void *opaque)
5331 Error *err = NULL;
5332 BlockBackend *blk;
5334 blk = blk_by_name(device);
5335 if (!blk) {
5336 monitor_printf(mon, "Device not found %s\n", device);
5337 return -1;
5340 bdrv_add_key(blk_bs(blk), NULL, &err);
5341 if (err) {
5342 error_free(err);
5343 return monitor_read_bdrv_key_start(mon, blk_bs(blk), completion_cb, opaque);
5346 if (completion_cb) {
5347 completion_cb(opaque, 0);
5349 return 0;
5352 QemuOptsList qemu_mon_opts = {
5353 .name = "mon",
5354 .implied_opt_name = "chardev",
5355 .head = QTAILQ_HEAD_INITIALIZER(qemu_mon_opts.head),
5356 .desc = {
5358 .name = "mode",
5359 .type = QEMU_OPT_STRING,
5361 .name = "chardev",
5362 .type = QEMU_OPT_STRING,
5364 .name = "default",
5365 .type = QEMU_OPT_BOOL,
5367 .name = "pretty",
5368 .type = QEMU_OPT_BOOL,
5370 { /* end of list */ }
5374 #ifndef TARGET_I386
5375 void qmp_rtc_reset_reinjection(Error **errp)
5377 error_set(errp, QERR_FEATURE_DISABLED, "rtc-reset-reinjection");
5379 #endif