Merge remote-tracking branch 'remotes/borntraeger/tags/s390x-20150615' into staging
[qemu.git] / monitor.c
blob6a4642493a438638e32415b70625a7fea5425586
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 {
165 QObject *id;
166 JSONMessageParser parser;
168 * When a client connects, we're in capabilities negotiation mode.
169 * When command qmp_capabilities succeeds, we go into command
170 * mode.
172 bool in_command_mode; /* are we in command mode? */
173 } MonitorQMP;
176 * To prevent flooding clients, events can be throttled. The
177 * throttling is calculated globally, rather than per-Monitor
178 * instance.
180 typedef struct MonitorQAPIEventState {
181 QAPIEvent event; /* Event being tracked */
182 int64_t rate; /* Minimum time (in ns) between two events */
183 int64_t last; /* QEMU_CLOCK_REALTIME value at last emission */
184 QEMUTimer *timer; /* Timer for handling delayed events */
185 QObject *data; /* Event pending delayed dispatch */
186 } MonitorQAPIEventState;
188 struct Monitor {
189 CharDriverState *chr;
190 int reset_seen;
191 int flags;
192 int suspend_cnt;
193 bool skip_flush;
195 QemuMutex out_lock;
196 QString *outbuf;
197 guint out_watch;
199 /* Read under either BQL or out_lock, written with BQL+out_lock. */
200 int mux_out;
202 ReadLineState *rs;
203 MonitorQMP qmp;
204 CPUState *mon_cpu;
205 BlockCompletionFunc *password_completion_cb;
206 void *password_opaque;
207 mon_cmd_t *cmd_table;
208 QError *error;
209 QLIST_HEAD(,mon_fd_t) fds;
210 QLIST_ENTRY(Monitor) entry;
213 /* QMP checker flags */
214 #define QMP_ACCEPT_UNKNOWNS 1
216 /* Protects mon_list, monitor_event_state. */
217 static QemuMutex monitor_lock;
219 static QLIST_HEAD(mon_list, Monitor) mon_list;
220 static QLIST_HEAD(mon_fdsets, MonFdset) mon_fdsets;
221 static int mon_refcount;
223 static mon_cmd_t mon_cmds[];
224 static mon_cmd_t info_cmds[];
226 static const mon_cmd_t qmp_cmds[];
228 Monitor *cur_mon;
229 Monitor *default_mon;
231 static void monitor_command_cb(void *opaque, const char *cmdline,
232 void *readline_opaque);
235 * Is @mon a QMP monitor?
237 static inline bool monitor_is_qmp(const Monitor *mon)
239 return (mon->flags & MONITOR_USE_CONTROL);
243 * Is the current monitor, if any, a QMP monitor?
245 bool monitor_cur_is_qmp(void)
247 return cur_mon && monitor_is_qmp(cur_mon);
250 void monitor_read_command(Monitor *mon, int show_prompt)
252 if (!mon->rs)
253 return;
255 readline_start(mon->rs, "(qemu) ", 0, monitor_command_cb, NULL);
256 if (show_prompt)
257 readline_show_prompt(mon->rs);
260 int monitor_read_password(Monitor *mon, ReadLineFunc *readline_func,
261 void *opaque)
263 if (mon->rs) {
264 readline_start(mon->rs, "Password: ", 1, readline_func, opaque);
265 /* prompt is printed on return from the command handler */
266 return 0;
267 } else {
268 monitor_printf(mon, "terminal does not support password prompting\n");
269 return -ENOTTY;
273 static void monitor_flush_locked(Monitor *mon);
275 static gboolean monitor_unblocked(GIOChannel *chan, GIOCondition cond,
276 void *opaque)
278 Monitor *mon = opaque;
280 qemu_mutex_lock(&mon->out_lock);
281 mon->out_watch = 0;
282 monitor_flush_locked(mon);
283 qemu_mutex_unlock(&mon->out_lock);
284 return FALSE;
287 /* Called with mon->out_lock held. */
288 static void monitor_flush_locked(Monitor *mon)
290 int rc;
291 size_t len;
292 const char *buf;
294 if (mon->skip_flush) {
295 return;
298 buf = qstring_get_str(mon->outbuf);
299 len = qstring_get_length(mon->outbuf);
301 if (len && !mon->mux_out) {
302 rc = qemu_chr_fe_write(mon->chr, (const uint8_t *) buf, len);
303 if ((rc < 0 && errno != EAGAIN) || (rc == len)) {
304 /* all flushed or error */
305 QDECREF(mon->outbuf);
306 mon->outbuf = qstring_new();
307 return;
309 if (rc > 0) {
310 /* partinal write */
311 QString *tmp = qstring_from_str(buf + rc);
312 QDECREF(mon->outbuf);
313 mon->outbuf = tmp;
315 if (mon->out_watch == 0) {
316 mon->out_watch = qemu_chr_fe_add_watch(mon->chr, G_IO_OUT|G_IO_HUP,
317 monitor_unblocked, mon);
322 void monitor_flush(Monitor *mon)
324 qemu_mutex_lock(&mon->out_lock);
325 monitor_flush_locked(mon);
326 qemu_mutex_unlock(&mon->out_lock);
329 /* flush at every end of line */
330 static void monitor_puts(Monitor *mon, const char *str)
332 char c;
334 qemu_mutex_lock(&mon->out_lock);
335 for(;;) {
336 c = *str++;
337 if (c == '\0')
338 break;
339 if (c == '\n') {
340 qstring_append_chr(mon->outbuf, '\r');
342 qstring_append_chr(mon->outbuf, c);
343 if (c == '\n') {
344 monitor_flush_locked(mon);
347 qemu_mutex_unlock(&mon->out_lock);
350 void monitor_vprintf(Monitor *mon, const char *fmt, va_list ap)
352 char *buf;
354 if (!mon)
355 return;
357 if (monitor_is_qmp(mon)) {
358 return;
361 buf = g_strdup_vprintf(fmt, ap);
362 monitor_puts(mon, buf);
363 g_free(buf);
366 void monitor_printf(Monitor *mon, const char *fmt, ...)
368 va_list ap;
369 va_start(ap, fmt);
370 monitor_vprintf(mon, fmt, ap);
371 va_end(ap);
374 static int GCC_FMT_ATTR(2, 3) monitor_fprintf(FILE *stream,
375 const char *fmt, ...)
377 va_list ap;
378 va_start(ap, fmt);
379 monitor_vprintf((Monitor *)stream, fmt, ap);
380 va_end(ap);
381 return 0;
384 static void monitor_json_emitter(Monitor *mon, const QObject *data)
386 QString *json;
388 json = mon->flags & MONITOR_USE_PRETTY ? qobject_to_json_pretty(data) :
389 qobject_to_json(data);
390 assert(json != NULL);
392 qstring_append_chr(json, '\n');
393 monitor_puts(mon, qstring_get_str(json));
395 QDECREF(json);
398 static QDict *build_qmp_error_dict(Error *err)
400 QObject *obj;
402 obj = qobject_from_jsonf("{ 'error': { 'class': %s, 'desc': %s } }",
403 ErrorClass_lookup[error_get_class(err)],
404 error_get_pretty(err));
406 return qobject_to_qdict(obj);
409 static void monitor_protocol_emitter(Monitor *mon, QObject *data,
410 Error *err)
412 QDict *qmp;
414 trace_monitor_protocol_emitter(mon);
416 if (!err) {
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(err);
431 if (mon->qmp.id) {
432 qdict_put_obj(qmp, "id", mon->qmp.id);
433 mon->qmp.id = NULL;
436 monitor_json_emitter(mon, QOBJECT(qmp));
437 QDECREF(qmp);
441 static MonitorQAPIEventState monitor_qapi_event_state[QAPI_EVENT_MAX];
444 * Emits the event to every monitor instance, @event is only used for trace
445 * Called with monitor_lock held.
447 static void monitor_qapi_event_emit(QAPIEvent event, QObject *data)
449 Monitor *mon;
451 trace_monitor_protocol_event_emit(event, data);
452 QLIST_FOREACH(mon, &mon_list, entry) {
453 if (monitor_is_qmp(mon) && mon->qmp.in_command_mode) {
454 monitor_json_emitter(mon, data);
460 * Queue a new event for emission to Monitor instances,
461 * applying any rate limiting if required.
463 static void
464 monitor_qapi_event_queue(QAPIEvent event, QDict *data, Error **errp)
466 MonitorQAPIEventState *evstate;
467 assert(event < QAPI_EVENT_MAX);
468 int64_t now = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
470 evstate = &(monitor_qapi_event_state[event]);
471 trace_monitor_protocol_event_queue(event,
472 data,
473 evstate->rate,
474 evstate->last,
475 now);
477 /* Rate limit of 0 indicates no throttling */
478 qemu_mutex_lock(&monitor_lock);
479 if (!evstate->rate) {
480 monitor_qapi_event_emit(event, QOBJECT(data));
481 evstate->last = now;
482 } else {
483 int64_t delta = now - evstate->last;
484 if (evstate->data ||
485 delta < evstate->rate) {
486 /* If there's an existing event pending, replace
487 * it with the new event, otherwise schedule a
488 * timer for delayed emission
490 if (evstate->data) {
491 qobject_decref(evstate->data);
492 } else {
493 int64_t then = evstate->last + evstate->rate;
494 timer_mod_ns(evstate->timer, then);
496 evstate->data = QOBJECT(data);
497 qobject_incref(evstate->data);
498 } else {
499 monitor_qapi_event_emit(event, QOBJECT(data));
500 evstate->last = now;
503 qemu_mutex_unlock(&monitor_lock);
507 * The callback invoked by QemuTimer when a delayed
508 * event is ready to be emitted
510 static void monitor_qapi_event_handler(void *opaque)
512 MonitorQAPIEventState *evstate = opaque;
513 int64_t now = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
515 trace_monitor_protocol_event_handler(evstate->event,
516 evstate->data,
517 evstate->last,
518 now);
519 qemu_mutex_lock(&monitor_lock);
520 if (evstate->data) {
521 monitor_qapi_event_emit(evstate->event, evstate->data);
522 qobject_decref(evstate->data);
523 evstate->data = NULL;
525 evstate->last = now;
526 qemu_mutex_unlock(&monitor_lock);
530 * @event: the event ID to be limited
531 * @rate: the rate limit in milliseconds
533 * Sets a rate limit on a particular event, so no
534 * more than 1 event will be emitted within @rate
535 * milliseconds
537 static void
538 monitor_qapi_event_throttle(QAPIEvent event, int64_t rate)
540 MonitorQAPIEventState *evstate;
541 assert(event < QAPI_EVENT_MAX);
543 evstate = &(monitor_qapi_event_state[event]);
545 trace_monitor_protocol_event_throttle(event, rate);
546 evstate->event = event;
547 assert(rate * SCALE_MS <= INT64_MAX);
548 evstate->rate = rate * SCALE_MS;
549 evstate->last = 0;
550 evstate->data = NULL;
551 evstate->timer = timer_new(QEMU_CLOCK_REALTIME,
552 SCALE_MS,
553 monitor_qapi_event_handler,
554 evstate);
557 static void monitor_qapi_event_init(void)
559 /* Limit guest-triggerable events to 1 per second */
560 monitor_qapi_event_throttle(QAPI_EVENT_RTC_CHANGE, 1000);
561 monitor_qapi_event_throttle(QAPI_EVENT_WATCHDOG, 1000);
562 monitor_qapi_event_throttle(QAPI_EVENT_BALLOON_CHANGE, 1000);
563 monitor_qapi_event_throttle(QAPI_EVENT_QUORUM_REPORT_BAD, 1000);
564 monitor_qapi_event_throttle(QAPI_EVENT_QUORUM_FAILURE, 1000);
565 monitor_qapi_event_throttle(QAPI_EVENT_VSERPORT_CHANGE, 1000);
567 qmp_event_set_func_emit(monitor_qapi_event_queue);
570 static int do_qmp_capabilities(Monitor *mon, const QDict *params,
571 QObject **ret_data)
573 mon->qmp.in_command_mode = true;
574 return 0;
577 static void handle_hmp_command(Monitor *mon, const char *cmdline);
579 static void monitor_data_init(Monitor *mon)
581 memset(mon, 0, sizeof(Monitor));
582 qemu_mutex_init(&mon->out_lock);
583 mon->outbuf = qstring_new();
584 /* Use *mon_cmds by default. */
585 mon->cmd_table = mon_cmds;
588 static void monitor_data_destroy(Monitor *mon)
590 QDECREF(mon->outbuf);
591 qemu_mutex_destroy(&mon->out_lock);
594 char *qmp_human_monitor_command(const char *command_line, bool has_cpu_index,
595 int64_t cpu_index, Error **errp)
597 char *output = NULL;
598 Monitor *old_mon, hmp;
600 monitor_data_init(&hmp);
601 hmp.skip_flush = true;
603 old_mon = cur_mon;
604 cur_mon = &hmp;
606 if (has_cpu_index) {
607 int ret = monitor_set_cpu(cpu_index);
608 if (ret < 0) {
609 cur_mon = old_mon;
610 error_set(errp, QERR_INVALID_PARAMETER_VALUE, "cpu-index",
611 "a CPU number");
612 goto out;
616 handle_hmp_command(&hmp, command_line);
617 cur_mon = old_mon;
619 qemu_mutex_lock(&hmp.out_lock);
620 if (qstring_get_length(hmp.outbuf) > 0) {
621 output = g_strdup(qstring_get_str(hmp.outbuf));
622 } else {
623 output = g_strdup("");
625 qemu_mutex_unlock(&hmp.out_lock);
627 out:
628 monitor_data_destroy(&hmp);
629 return output;
632 static int compare_cmd(const char *name, const char *list)
634 const char *p, *pstart;
635 int len;
636 len = strlen(name);
637 p = list;
638 for(;;) {
639 pstart = p;
640 p = strchr(p, '|');
641 if (!p)
642 p = pstart + strlen(pstart);
643 if ((p - pstart) == len && !memcmp(pstart, name, len))
644 return 1;
645 if (*p == '\0')
646 break;
647 p++;
649 return 0;
652 static int get_str(char *buf, int buf_size, const char **pp)
654 const char *p;
655 char *q;
656 int c;
658 q = buf;
659 p = *pp;
660 while (qemu_isspace(*p)) {
661 p++;
663 if (*p == '\0') {
664 fail:
665 *q = '\0';
666 *pp = p;
667 return -1;
669 if (*p == '\"') {
670 p++;
671 while (*p != '\0' && *p != '\"') {
672 if (*p == '\\') {
673 p++;
674 c = *p++;
675 switch (c) {
676 case 'n':
677 c = '\n';
678 break;
679 case 'r':
680 c = '\r';
681 break;
682 case '\\':
683 case '\'':
684 case '\"':
685 break;
686 default:
687 qemu_printf("unsupported escape code: '\\%c'\n", c);
688 goto fail;
690 if ((q - buf) < buf_size - 1) {
691 *q++ = c;
693 } else {
694 if ((q - buf) < buf_size - 1) {
695 *q++ = *p;
697 p++;
700 if (*p != '\"') {
701 qemu_printf("unterminated string\n");
702 goto fail;
704 p++;
705 } else {
706 while (*p != '\0' && !qemu_isspace(*p)) {
707 if ((q - buf) < buf_size - 1) {
708 *q++ = *p;
710 p++;
713 *q = '\0';
714 *pp = p;
715 return 0;
718 #define MAX_ARGS 16
720 static void free_cmdline_args(char **args, int nb_args)
722 int i;
724 assert(nb_args <= MAX_ARGS);
726 for (i = 0; i < nb_args; i++) {
727 g_free(args[i]);
733 * Parse the command line to get valid args.
734 * @cmdline: command line to be parsed.
735 * @pnb_args: location to store the number of args, must NOT be NULL.
736 * @args: location to store the args, which should be freed by caller, must
737 * NOT be NULL.
739 * Returns 0 on success, negative on failure.
741 * NOTE: this parser is an approximate form of the real command parser. Number
742 * of args have a limit of MAX_ARGS. If cmdline contains more, it will
743 * return with failure.
745 static int parse_cmdline(const char *cmdline,
746 int *pnb_args, char **args)
748 const char *p;
749 int nb_args, ret;
750 char buf[1024];
752 p = cmdline;
753 nb_args = 0;
754 for (;;) {
755 while (qemu_isspace(*p)) {
756 p++;
758 if (*p == '\0') {
759 break;
761 if (nb_args >= MAX_ARGS) {
762 goto fail;
764 ret = get_str(buf, sizeof(buf), &p);
765 if (ret < 0) {
766 goto fail;
768 args[nb_args] = g_strdup(buf);
769 nb_args++;
771 *pnb_args = nb_args;
772 return 0;
774 fail:
775 free_cmdline_args(args, nb_args);
776 return -1;
779 static void help_cmd_dump_one(Monitor *mon,
780 const mon_cmd_t *cmd,
781 char **prefix_args,
782 int prefix_args_nb)
784 int i;
786 for (i = 0; i < prefix_args_nb; i++) {
787 monitor_printf(mon, "%s ", prefix_args[i]);
789 monitor_printf(mon, "%s %s -- %s\n", cmd->name, cmd->params, cmd->help);
792 /* @args[@arg_index] is the valid command need to find in @cmds */
793 static void help_cmd_dump(Monitor *mon, const mon_cmd_t *cmds,
794 char **args, int nb_args, int arg_index)
796 const mon_cmd_t *cmd;
798 /* No valid arg need to compare with, dump all in *cmds */
799 if (arg_index >= nb_args) {
800 for (cmd = cmds; cmd->name != NULL; cmd++) {
801 help_cmd_dump_one(mon, cmd, args, arg_index);
803 return;
806 /* Find one entry to dump */
807 for (cmd = cmds; cmd->name != NULL; cmd++) {
808 if (compare_cmd(args[arg_index], cmd->name)) {
809 if (cmd->sub_table) {
810 /* continue with next arg */
811 help_cmd_dump(mon, cmd->sub_table,
812 args, nb_args, arg_index + 1);
813 } else {
814 help_cmd_dump_one(mon, cmd, args, arg_index);
816 break;
821 static void help_cmd(Monitor *mon, const char *name)
823 char *args[MAX_ARGS];
824 int nb_args = 0;
826 /* 1. parse user input */
827 if (name) {
828 /* special case for log, directly dump and return */
829 if (!strcmp(name, "log")) {
830 const QEMULogItem *item;
831 monitor_printf(mon, "Log items (comma separated):\n");
832 monitor_printf(mon, "%-10s %s\n", "none", "remove all logs");
833 for (item = qemu_log_items; item->mask != 0; item++) {
834 monitor_printf(mon, "%-10s %s\n", item->name, item->help);
836 return;
839 if (parse_cmdline(name, &nb_args, args) < 0) {
840 return;
844 /* 2. dump the contents according to parsed args */
845 help_cmd_dump(mon, mon->cmd_table, args, nb_args, 0);
847 free_cmdline_args(args, nb_args);
850 static void do_help_cmd(Monitor *mon, const QDict *qdict)
852 help_cmd(mon, qdict_get_try_str(qdict, "name"));
855 static void hmp_trace_event(Monitor *mon, const QDict *qdict)
857 const char *tp_name = qdict_get_str(qdict, "name");
858 bool new_state = qdict_get_bool(qdict, "option");
859 Error *local_err = NULL;
861 qmp_trace_event_set_state(tp_name, new_state, true, true, &local_err);
862 if (local_err) {
863 error_report_err(local_err);
867 #ifdef CONFIG_TRACE_SIMPLE
868 static void hmp_trace_file(Monitor *mon, const QDict *qdict)
870 const char *op = qdict_get_try_str(qdict, "op");
871 const char *arg = qdict_get_try_str(qdict, "arg");
873 if (!op) {
874 st_print_trace_file_status((FILE *)mon, &monitor_fprintf);
875 } else if (!strcmp(op, "on")) {
876 st_set_trace_file_enabled(true);
877 } else if (!strcmp(op, "off")) {
878 st_set_trace_file_enabled(false);
879 } else if (!strcmp(op, "flush")) {
880 st_flush_trace_buffer();
881 } else if (!strcmp(op, "set")) {
882 if (arg) {
883 st_set_trace_file(arg);
885 } else {
886 monitor_printf(mon, "unexpected argument \"%s\"\n", op);
887 help_cmd(mon, "trace-file");
890 #endif
892 static void hmp_info_help(Monitor *mon, const QDict *qdict)
894 help_cmd(mon, "info");
897 CommandInfoList *qmp_query_commands(Error **errp)
899 CommandInfoList *info, *cmd_list = NULL;
900 const mon_cmd_t *cmd;
902 for (cmd = qmp_cmds; cmd->name != NULL; cmd++) {
903 info = g_malloc0(sizeof(*info));
904 info->value = g_malloc0(sizeof(*info->value));
905 info->value->name = g_strdup(cmd->name);
907 info->next = cmd_list;
908 cmd_list = info;
911 return cmd_list;
914 EventInfoList *qmp_query_events(Error **errp)
916 EventInfoList *info, *ev_list = NULL;
917 QAPIEvent e;
919 for (e = 0 ; e < QAPI_EVENT_MAX ; e++) {
920 const char *event_name = QAPIEvent_lookup[e];
921 assert(event_name != NULL);
922 info = g_malloc0(sizeof(*info));
923 info->value = g_malloc0(sizeof(*info->value));
924 info->value->name = g_strdup(event_name);
926 info->next = ev_list;
927 ev_list = info;
930 return ev_list;
933 /* set the current CPU defined by the user */
934 int monitor_set_cpu(int cpu_index)
936 CPUState *cpu;
938 cpu = qemu_get_cpu(cpu_index);
939 if (cpu == NULL) {
940 return -1;
942 cur_mon->mon_cpu = cpu;
943 return 0;
946 static CPUArchState *mon_get_cpu(void)
948 if (!cur_mon->mon_cpu) {
949 monitor_set_cpu(0);
951 cpu_synchronize_state(cur_mon->mon_cpu);
952 return cur_mon->mon_cpu->env_ptr;
955 int monitor_get_cpu_index(void)
957 CPUState *cpu = ENV_GET_CPU(mon_get_cpu());
958 return cpu->cpu_index;
961 static void hmp_info_registers(Monitor *mon, const QDict *qdict)
963 CPUState *cpu;
964 CPUArchState *env;
965 env = mon_get_cpu();
966 cpu = ENV_GET_CPU(env);
967 cpu_dump_state(cpu, (FILE *)mon, monitor_fprintf, CPU_DUMP_FPU);
970 static void hmp_info_jit(Monitor *mon, const QDict *qdict)
972 dump_exec_info((FILE *)mon, monitor_fprintf);
973 dump_drift_info((FILE *)mon, monitor_fprintf);
976 static void hmp_info_opcount(Monitor *mon, const QDict *qdict)
978 dump_opcount_info((FILE *)mon, monitor_fprintf);
981 static void hmp_info_history(Monitor *mon, const QDict *qdict)
983 int i;
984 const char *str;
986 if (!mon->rs)
987 return;
988 i = 0;
989 for(;;) {
990 str = readline_get_history(mon->rs, i);
991 if (!str)
992 break;
993 monitor_printf(mon, "%d: '%s'\n", i, str);
994 i++;
998 static void hmp_info_cpustats(Monitor *mon, const QDict *qdict)
1000 CPUState *cpu;
1001 CPUArchState *env;
1003 env = mon_get_cpu();
1004 cpu = ENV_GET_CPU(env);
1005 cpu_dump_statistics(cpu, (FILE *)mon, &monitor_fprintf, 0);
1008 static void hmp_info_trace_events(Monitor *mon, const QDict *qdict)
1010 TraceEventInfoList *events = qmp_trace_event_get_state("*", NULL);
1011 TraceEventInfoList *elem;
1013 for (elem = events; elem != NULL; elem = elem->next) {
1014 monitor_printf(mon, "%s : state %u\n",
1015 elem->value->name,
1016 elem->value->state == TRACE_EVENT_STATE_ENABLED ? 1 : 0);
1018 qapi_free_TraceEventInfoList(events);
1021 void qmp_client_migrate_info(const char *protocol, const char *hostname,
1022 bool has_port, int64_t port,
1023 bool has_tls_port, int64_t tls_port,
1024 bool has_cert_subject, const char *cert_subject,
1025 Error **errp)
1027 if (strcmp(protocol, "spice") == 0) {
1028 if (!qemu_using_spice(errp)) {
1029 return;
1032 if (!has_port && !has_tls_port) {
1033 error_set(errp, QERR_MISSING_PARAMETER, "port/tls-port");
1034 return;
1037 if (qemu_spice_migrate_info(hostname,
1038 has_port ? port : -1,
1039 has_tls_port ? tls_port : -1,
1040 cert_subject)) {
1041 error_set(errp, QERR_UNDEFINED_ERROR);
1042 return;
1044 return;
1047 error_set(errp, QERR_INVALID_PARAMETER_VALUE, "protocol", "spice");
1050 static void hmp_logfile(Monitor *mon, const QDict *qdict)
1052 qemu_set_log_filename(qdict_get_str(qdict, "filename"));
1055 static void hmp_log(Monitor *mon, const QDict *qdict)
1057 int mask;
1058 const char *items = qdict_get_str(qdict, "items");
1060 if (!strcmp(items, "none")) {
1061 mask = 0;
1062 } else {
1063 mask = qemu_str_to_log_mask(items);
1064 if (!mask) {
1065 help_cmd(mon, "log");
1066 return;
1069 qemu_set_log(mask);
1072 static void hmp_singlestep(Monitor *mon, const QDict *qdict)
1074 const char *option = qdict_get_try_str(qdict, "option");
1075 if (!option || !strcmp(option, "on")) {
1076 singlestep = 1;
1077 } else if (!strcmp(option, "off")) {
1078 singlestep = 0;
1079 } else {
1080 monitor_printf(mon, "unexpected option %s\n", option);
1084 static void hmp_gdbserver(Monitor *mon, const QDict *qdict)
1086 const char *device = qdict_get_try_str(qdict, "device");
1087 if (!device)
1088 device = "tcp::" DEFAULT_GDBSTUB_PORT;
1089 if (gdbserver_start(device) < 0) {
1090 monitor_printf(mon, "Could not open gdbserver on device '%s'\n",
1091 device);
1092 } else if (strcmp(device, "none") == 0) {
1093 monitor_printf(mon, "Disabled gdbserver\n");
1094 } else {
1095 monitor_printf(mon, "Waiting for gdb connection on device '%s'\n",
1096 device);
1100 static void hmp_watchdog_action(Monitor *mon, const QDict *qdict)
1102 const char *action = qdict_get_str(qdict, "action");
1103 if (select_watchdog_action(action) == -1) {
1104 monitor_printf(mon, "Unknown watchdog action '%s'\n", action);
1108 static void monitor_printc(Monitor *mon, int c)
1110 monitor_printf(mon, "'");
1111 switch(c) {
1112 case '\'':
1113 monitor_printf(mon, "\\'");
1114 break;
1115 case '\\':
1116 monitor_printf(mon, "\\\\");
1117 break;
1118 case '\n':
1119 monitor_printf(mon, "\\n");
1120 break;
1121 case '\r':
1122 monitor_printf(mon, "\\r");
1123 break;
1124 default:
1125 if (c >= 32 && c <= 126) {
1126 monitor_printf(mon, "%c", c);
1127 } else {
1128 monitor_printf(mon, "\\x%02x", c);
1130 break;
1132 monitor_printf(mon, "'");
1135 static void memory_dump(Monitor *mon, int count, int format, int wsize,
1136 hwaddr addr, int is_physical)
1138 CPUArchState *env;
1139 int l, line_size, i, max_digits, len;
1140 uint8_t buf[16];
1141 uint64_t v;
1143 if (format == 'i') {
1144 int flags;
1145 flags = 0;
1146 env = mon_get_cpu();
1147 #ifdef TARGET_I386
1148 if (wsize == 2) {
1149 flags = 1;
1150 } else if (wsize == 4) {
1151 flags = 0;
1152 } else {
1153 /* as default we use the current CS size */
1154 flags = 0;
1155 if (env) {
1156 #ifdef TARGET_X86_64
1157 if ((env->efer & MSR_EFER_LMA) &&
1158 (env->segs[R_CS].flags & DESC_L_MASK))
1159 flags = 2;
1160 else
1161 #endif
1162 if (!(env->segs[R_CS].flags & DESC_B_MASK))
1163 flags = 1;
1166 #endif
1167 #ifdef TARGET_PPC
1168 flags = msr_le << 16;
1169 flags |= env->bfd_mach;
1170 #endif
1171 monitor_disas(mon, env, addr, count, is_physical, flags);
1172 return;
1175 len = wsize * count;
1176 if (wsize == 1)
1177 line_size = 8;
1178 else
1179 line_size = 16;
1180 max_digits = 0;
1182 switch(format) {
1183 case 'o':
1184 max_digits = (wsize * 8 + 2) / 3;
1185 break;
1186 default:
1187 case 'x':
1188 max_digits = (wsize * 8) / 4;
1189 break;
1190 case 'u':
1191 case 'd':
1192 max_digits = (wsize * 8 * 10 + 32) / 33;
1193 break;
1194 case 'c':
1195 wsize = 1;
1196 break;
1199 while (len > 0) {
1200 if (is_physical)
1201 monitor_printf(mon, TARGET_FMT_plx ":", addr);
1202 else
1203 monitor_printf(mon, TARGET_FMT_lx ":", (target_ulong)addr);
1204 l = len;
1205 if (l > line_size)
1206 l = line_size;
1207 if (is_physical) {
1208 cpu_physical_memory_read(addr, buf, l);
1209 } else {
1210 env = mon_get_cpu();
1211 if (cpu_memory_rw_debug(ENV_GET_CPU(env), addr, buf, l, 0) < 0) {
1212 monitor_printf(mon, " Cannot access memory\n");
1213 break;
1216 i = 0;
1217 while (i < l) {
1218 switch(wsize) {
1219 default:
1220 case 1:
1221 v = ldub_p(buf + i);
1222 break;
1223 case 2:
1224 v = lduw_p(buf + i);
1225 break;
1226 case 4:
1227 v = (uint32_t)ldl_p(buf + i);
1228 break;
1229 case 8:
1230 v = ldq_p(buf + i);
1231 break;
1233 monitor_printf(mon, " ");
1234 switch(format) {
1235 case 'o':
1236 monitor_printf(mon, "%#*" PRIo64, max_digits, v);
1237 break;
1238 case 'x':
1239 monitor_printf(mon, "0x%0*" PRIx64, max_digits, v);
1240 break;
1241 case 'u':
1242 monitor_printf(mon, "%*" PRIu64, max_digits, v);
1243 break;
1244 case 'd':
1245 monitor_printf(mon, "%*" PRId64, max_digits, v);
1246 break;
1247 case 'c':
1248 monitor_printc(mon, v);
1249 break;
1251 i += wsize;
1253 monitor_printf(mon, "\n");
1254 addr += l;
1255 len -= l;
1259 static void hmp_memory_dump(Monitor *mon, const QDict *qdict)
1261 int count = qdict_get_int(qdict, "count");
1262 int format = qdict_get_int(qdict, "format");
1263 int size = qdict_get_int(qdict, "size");
1264 target_long addr = qdict_get_int(qdict, "addr");
1266 memory_dump(mon, count, format, size, addr, 0);
1269 static void hmp_physical_memory_dump(Monitor *mon, const QDict *qdict)
1271 int count = qdict_get_int(qdict, "count");
1272 int format = qdict_get_int(qdict, "format");
1273 int size = qdict_get_int(qdict, "size");
1274 hwaddr addr = qdict_get_int(qdict, "addr");
1276 memory_dump(mon, count, format, size, addr, 1);
1279 static void do_print(Monitor *mon, const QDict *qdict)
1281 int format = qdict_get_int(qdict, "format");
1282 hwaddr val = qdict_get_int(qdict, "val");
1284 switch(format) {
1285 case 'o':
1286 monitor_printf(mon, "%#" HWADDR_PRIo, val);
1287 break;
1288 case 'x':
1289 monitor_printf(mon, "%#" HWADDR_PRIx, val);
1290 break;
1291 case 'u':
1292 monitor_printf(mon, "%" HWADDR_PRIu, val);
1293 break;
1294 default:
1295 case 'd':
1296 monitor_printf(mon, "%" HWADDR_PRId, val);
1297 break;
1298 case 'c':
1299 monitor_printc(mon, val);
1300 break;
1302 monitor_printf(mon, "\n");
1305 static void hmp_sum(Monitor *mon, const QDict *qdict)
1307 uint32_t addr;
1308 uint16_t sum;
1309 uint32_t start = qdict_get_int(qdict, "start");
1310 uint32_t size = qdict_get_int(qdict, "size");
1312 sum = 0;
1313 for(addr = start; addr < (start + size); addr++) {
1314 uint8_t val = address_space_ldub(&address_space_memory, addr,
1315 MEMTXATTRS_UNSPECIFIED, NULL);
1316 /* BSD sum algorithm ('sum' Unix command) */
1317 sum = (sum >> 1) | (sum << 15);
1318 sum += val;
1320 monitor_printf(mon, "%05d\n", sum);
1323 static int mouse_button_state;
1325 static void hmp_mouse_move(Monitor *mon, const QDict *qdict)
1327 int dx, dy, dz, button;
1328 const char *dx_str = qdict_get_str(qdict, "dx_str");
1329 const char *dy_str = qdict_get_str(qdict, "dy_str");
1330 const char *dz_str = qdict_get_try_str(qdict, "dz_str");
1332 dx = strtol(dx_str, NULL, 0);
1333 dy = strtol(dy_str, NULL, 0);
1334 qemu_input_queue_rel(NULL, INPUT_AXIS_X, dx);
1335 qemu_input_queue_rel(NULL, INPUT_AXIS_Y, dy);
1337 if (dz_str) {
1338 dz = strtol(dz_str, NULL, 0);
1339 if (dz != 0) {
1340 button = (dz > 0) ? INPUT_BUTTON_WHEEL_UP : INPUT_BUTTON_WHEEL_DOWN;
1341 qemu_input_queue_btn(NULL, button, true);
1342 qemu_input_event_sync();
1343 qemu_input_queue_btn(NULL, button, false);
1346 qemu_input_event_sync();
1349 static void hmp_mouse_button(Monitor *mon, const QDict *qdict)
1351 static uint32_t bmap[INPUT_BUTTON_MAX] = {
1352 [INPUT_BUTTON_LEFT] = MOUSE_EVENT_LBUTTON,
1353 [INPUT_BUTTON_MIDDLE] = MOUSE_EVENT_MBUTTON,
1354 [INPUT_BUTTON_RIGHT] = MOUSE_EVENT_RBUTTON,
1356 int button_state = qdict_get_int(qdict, "button_state");
1358 if (mouse_button_state == button_state) {
1359 return;
1361 qemu_input_update_buttons(NULL, bmap, mouse_button_state, button_state);
1362 qemu_input_event_sync();
1363 mouse_button_state = button_state;
1366 static void hmp_ioport_read(Monitor *mon, const QDict *qdict)
1368 int size = qdict_get_int(qdict, "size");
1369 int addr = qdict_get_int(qdict, "addr");
1370 int has_index = qdict_haskey(qdict, "index");
1371 uint32_t val;
1372 int suffix;
1374 if (has_index) {
1375 int index = qdict_get_int(qdict, "index");
1376 cpu_outb(addr & IOPORTS_MASK, index & 0xff);
1377 addr++;
1379 addr &= 0xffff;
1381 switch(size) {
1382 default:
1383 case 1:
1384 val = cpu_inb(addr);
1385 suffix = 'b';
1386 break;
1387 case 2:
1388 val = cpu_inw(addr);
1389 suffix = 'w';
1390 break;
1391 case 4:
1392 val = cpu_inl(addr);
1393 suffix = 'l';
1394 break;
1396 monitor_printf(mon, "port%c[0x%04x] = %#0*x\n",
1397 suffix, addr, size * 2, val);
1400 static void hmp_ioport_write(Monitor *mon, const QDict *qdict)
1402 int size = qdict_get_int(qdict, "size");
1403 int addr = qdict_get_int(qdict, "addr");
1404 int val = qdict_get_int(qdict, "val");
1406 addr &= IOPORTS_MASK;
1408 switch (size) {
1409 default:
1410 case 1:
1411 cpu_outb(addr, val);
1412 break;
1413 case 2:
1414 cpu_outw(addr, val);
1415 break;
1416 case 4:
1417 cpu_outl(addr, val);
1418 break;
1422 static void hmp_boot_set(Monitor *mon, const QDict *qdict)
1424 Error *local_err = NULL;
1425 const char *bootdevice = qdict_get_str(qdict, "bootdevice");
1427 qemu_boot_set(bootdevice, &local_err);
1428 if (local_err) {
1429 monitor_printf(mon, "%s\n", error_get_pretty(local_err));
1430 error_free(local_err);
1431 } else {
1432 monitor_printf(mon, "boot device list now set to %s\n", bootdevice);
1436 #if defined(TARGET_I386)
1437 static void print_pte(Monitor *mon, hwaddr addr,
1438 hwaddr pte,
1439 hwaddr mask)
1441 #ifdef TARGET_X86_64
1442 if (addr & (1ULL << 47)) {
1443 addr |= -1LL << 48;
1445 #endif
1446 monitor_printf(mon, TARGET_FMT_plx ": " TARGET_FMT_plx
1447 " %c%c%c%c%c%c%c%c%c\n",
1448 addr,
1449 pte & mask,
1450 pte & PG_NX_MASK ? 'X' : '-',
1451 pte & PG_GLOBAL_MASK ? 'G' : '-',
1452 pte & PG_PSE_MASK ? 'P' : '-',
1453 pte & PG_DIRTY_MASK ? 'D' : '-',
1454 pte & PG_ACCESSED_MASK ? 'A' : '-',
1455 pte & PG_PCD_MASK ? 'C' : '-',
1456 pte & PG_PWT_MASK ? 'T' : '-',
1457 pte & PG_USER_MASK ? 'U' : '-',
1458 pte & PG_RW_MASK ? 'W' : '-');
1461 static void tlb_info_32(Monitor *mon, CPUArchState *env)
1463 unsigned int l1, l2;
1464 uint32_t pgd, pde, pte;
1466 pgd = env->cr[3] & ~0xfff;
1467 for(l1 = 0; l1 < 1024; l1++) {
1468 cpu_physical_memory_read(pgd + l1 * 4, &pde, 4);
1469 pde = le32_to_cpu(pde);
1470 if (pde & PG_PRESENT_MASK) {
1471 if ((pde & PG_PSE_MASK) && (env->cr[4] & CR4_PSE_MASK)) {
1472 /* 4M pages */
1473 print_pte(mon, (l1 << 22), pde, ~((1 << 21) - 1));
1474 } else {
1475 for(l2 = 0; l2 < 1024; l2++) {
1476 cpu_physical_memory_read((pde & ~0xfff) + l2 * 4, &pte, 4);
1477 pte = le32_to_cpu(pte);
1478 if (pte & PG_PRESENT_MASK) {
1479 print_pte(mon, (l1 << 22) + (l2 << 12),
1480 pte & ~PG_PSE_MASK,
1481 ~0xfff);
1489 static void tlb_info_pae32(Monitor *mon, CPUArchState *env)
1491 unsigned int l1, l2, l3;
1492 uint64_t pdpe, pde, pte;
1493 uint64_t pdp_addr, pd_addr, pt_addr;
1495 pdp_addr = env->cr[3] & ~0x1f;
1496 for (l1 = 0; l1 < 4; l1++) {
1497 cpu_physical_memory_read(pdp_addr + l1 * 8, &pdpe, 8);
1498 pdpe = le64_to_cpu(pdpe);
1499 if (pdpe & PG_PRESENT_MASK) {
1500 pd_addr = pdpe & 0x3fffffffff000ULL;
1501 for (l2 = 0; l2 < 512; l2++) {
1502 cpu_physical_memory_read(pd_addr + l2 * 8, &pde, 8);
1503 pde = le64_to_cpu(pde);
1504 if (pde & PG_PRESENT_MASK) {
1505 if (pde & PG_PSE_MASK) {
1506 /* 2M pages with PAE, CR4.PSE is ignored */
1507 print_pte(mon, (l1 << 30 ) + (l2 << 21), pde,
1508 ~((hwaddr)(1 << 20) - 1));
1509 } else {
1510 pt_addr = pde & 0x3fffffffff000ULL;
1511 for (l3 = 0; l3 < 512; l3++) {
1512 cpu_physical_memory_read(pt_addr + l3 * 8, &pte, 8);
1513 pte = le64_to_cpu(pte);
1514 if (pte & PG_PRESENT_MASK) {
1515 print_pte(mon, (l1 << 30 ) + (l2 << 21)
1516 + (l3 << 12),
1517 pte & ~PG_PSE_MASK,
1518 ~(hwaddr)0xfff);
1528 #ifdef TARGET_X86_64
1529 static void tlb_info_64(Monitor *mon, CPUArchState *env)
1531 uint64_t l1, l2, l3, l4;
1532 uint64_t pml4e, pdpe, pde, pte;
1533 uint64_t pml4_addr, pdp_addr, pd_addr, pt_addr;
1535 pml4_addr = env->cr[3] & 0x3fffffffff000ULL;
1536 for (l1 = 0; l1 < 512; l1++) {
1537 cpu_physical_memory_read(pml4_addr + l1 * 8, &pml4e, 8);
1538 pml4e = le64_to_cpu(pml4e);
1539 if (pml4e & PG_PRESENT_MASK) {
1540 pdp_addr = pml4e & 0x3fffffffff000ULL;
1541 for (l2 = 0; l2 < 512; l2++) {
1542 cpu_physical_memory_read(pdp_addr + l2 * 8, &pdpe, 8);
1543 pdpe = le64_to_cpu(pdpe);
1544 if (pdpe & PG_PRESENT_MASK) {
1545 if (pdpe & PG_PSE_MASK) {
1546 /* 1G pages, CR4.PSE is ignored */
1547 print_pte(mon, (l1 << 39) + (l2 << 30), pdpe,
1548 0x3ffffc0000000ULL);
1549 } else {
1550 pd_addr = pdpe & 0x3fffffffff000ULL;
1551 for (l3 = 0; l3 < 512; l3++) {
1552 cpu_physical_memory_read(pd_addr + l3 * 8, &pde, 8);
1553 pde = le64_to_cpu(pde);
1554 if (pde & PG_PRESENT_MASK) {
1555 if (pde & PG_PSE_MASK) {
1556 /* 2M pages, CR4.PSE is ignored */
1557 print_pte(mon, (l1 << 39) + (l2 << 30) +
1558 (l3 << 21), pde,
1559 0x3ffffffe00000ULL);
1560 } else {
1561 pt_addr = pde & 0x3fffffffff000ULL;
1562 for (l4 = 0; l4 < 512; l4++) {
1563 cpu_physical_memory_read(pt_addr
1564 + l4 * 8,
1565 &pte, 8);
1566 pte = le64_to_cpu(pte);
1567 if (pte & PG_PRESENT_MASK) {
1568 print_pte(mon, (l1 << 39) +
1569 (l2 << 30) +
1570 (l3 << 21) + (l4 << 12),
1571 pte & ~PG_PSE_MASK,
1572 0x3fffffffff000ULL);
1584 #endif
1586 static void hmp_info_tlb(Monitor *mon, const QDict *qdict)
1588 CPUArchState *env;
1590 env = mon_get_cpu();
1592 if (!(env->cr[0] & CR0_PG_MASK)) {
1593 monitor_printf(mon, "PG disabled\n");
1594 return;
1596 if (env->cr[4] & CR4_PAE_MASK) {
1597 #ifdef TARGET_X86_64
1598 if (env->hflags & HF_LMA_MASK) {
1599 tlb_info_64(mon, env);
1600 } else
1601 #endif
1603 tlb_info_pae32(mon, env);
1605 } else {
1606 tlb_info_32(mon, env);
1610 static void mem_print(Monitor *mon, hwaddr *pstart,
1611 int *plast_prot,
1612 hwaddr end, int prot)
1614 int prot1;
1615 prot1 = *plast_prot;
1616 if (prot != prot1) {
1617 if (*pstart != -1) {
1618 monitor_printf(mon, TARGET_FMT_plx "-" TARGET_FMT_plx " "
1619 TARGET_FMT_plx " %c%c%c\n",
1620 *pstart, end, end - *pstart,
1621 prot1 & PG_USER_MASK ? 'u' : '-',
1622 'r',
1623 prot1 & PG_RW_MASK ? 'w' : '-');
1625 if (prot != 0)
1626 *pstart = end;
1627 else
1628 *pstart = -1;
1629 *plast_prot = prot;
1633 static void mem_info_32(Monitor *mon, CPUArchState *env)
1635 unsigned int l1, l2;
1636 int prot, last_prot;
1637 uint32_t pgd, pde, pte;
1638 hwaddr start, end;
1640 pgd = env->cr[3] & ~0xfff;
1641 last_prot = 0;
1642 start = -1;
1643 for(l1 = 0; l1 < 1024; l1++) {
1644 cpu_physical_memory_read(pgd + l1 * 4, &pde, 4);
1645 pde = le32_to_cpu(pde);
1646 end = l1 << 22;
1647 if (pde & PG_PRESENT_MASK) {
1648 if ((pde & PG_PSE_MASK) && (env->cr[4] & CR4_PSE_MASK)) {
1649 prot = pde & (PG_USER_MASK | PG_RW_MASK | PG_PRESENT_MASK);
1650 mem_print(mon, &start, &last_prot, end, prot);
1651 } else {
1652 for(l2 = 0; l2 < 1024; l2++) {
1653 cpu_physical_memory_read((pde & ~0xfff) + l2 * 4, &pte, 4);
1654 pte = le32_to_cpu(pte);
1655 end = (l1 << 22) + (l2 << 12);
1656 if (pte & PG_PRESENT_MASK) {
1657 prot = pte & pde &
1658 (PG_USER_MASK | PG_RW_MASK | PG_PRESENT_MASK);
1659 } else {
1660 prot = 0;
1662 mem_print(mon, &start, &last_prot, end, prot);
1665 } else {
1666 prot = 0;
1667 mem_print(mon, &start, &last_prot, end, prot);
1670 /* Flush last range */
1671 mem_print(mon, &start, &last_prot, (hwaddr)1 << 32, 0);
1674 static void mem_info_pae32(Monitor *mon, CPUArchState *env)
1676 unsigned int l1, l2, l3;
1677 int prot, last_prot;
1678 uint64_t pdpe, pde, pte;
1679 uint64_t pdp_addr, pd_addr, pt_addr;
1680 hwaddr start, end;
1682 pdp_addr = env->cr[3] & ~0x1f;
1683 last_prot = 0;
1684 start = -1;
1685 for (l1 = 0; l1 < 4; l1++) {
1686 cpu_physical_memory_read(pdp_addr + l1 * 8, &pdpe, 8);
1687 pdpe = le64_to_cpu(pdpe);
1688 end = l1 << 30;
1689 if (pdpe & PG_PRESENT_MASK) {
1690 pd_addr = pdpe & 0x3fffffffff000ULL;
1691 for (l2 = 0; l2 < 512; l2++) {
1692 cpu_physical_memory_read(pd_addr + l2 * 8, &pde, 8);
1693 pde = le64_to_cpu(pde);
1694 end = (l1 << 30) + (l2 << 21);
1695 if (pde & PG_PRESENT_MASK) {
1696 if (pde & PG_PSE_MASK) {
1697 prot = pde & (PG_USER_MASK | PG_RW_MASK |
1698 PG_PRESENT_MASK);
1699 mem_print(mon, &start, &last_prot, end, prot);
1700 } else {
1701 pt_addr = pde & 0x3fffffffff000ULL;
1702 for (l3 = 0; l3 < 512; l3++) {
1703 cpu_physical_memory_read(pt_addr + l3 * 8, &pte, 8);
1704 pte = le64_to_cpu(pte);
1705 end = (l1 << 30) + (l2 << 21) + (l3 << 12);
1706 if (pte & PG_PRESENT_MASK) {
1707 prot = pte & pde & (PG_USER_MASK | PG_RW_MASK |
1708 PG_PRESENT_MASK);
1709 } else {
1710 prot = 0;
1712 mem_print(mon, &start, &last_prot, end, prot);
1715 } else {
1716 prot = 0;
1717 mem_print(mon, &start, &last_prot, end, prot);
1720 } else {
1721 prot = 0;
1722 mem_print(mon, &start, &last_prot, end, prot);
1725 /* Flush last range */
1726 mem_print(mon, &start, &last_prot, (hwaddr)1 << 32, 0);
1730 #ifdef TARGET_X86_64
1731 static void mem_info_64(Monitor *mon, CPUArchState *env)
1733 int prot, last_prot;
1734 uint64_t l1, l2, l3, l4;
1735 uint64_t pml4e, pdpe, pde, pte;
1736 uint64_t pml4_addr, pdp_addr, pd_addr, pt_addr, start, end;
1738 pml4_addr = env->cr[3] & 0x3fffffffff000ULL;
1739 last_prot = 0;
1740 start = -1;
1741 for (l1 = 0; l1 < 512; l1++) {
1742 cpu_physical_memory_read(pml4_addr + l1 * 8, &pml4e, 8);
1743 pml4e = le64_to_cpu(pml4e);
1744 end = l1 << 39;
1745 if (pml4e & PG_PRESENT_MASK) {
1746 pdp_addr = pml4e & 0x3fffffffff000ULL;
1747 for (l2 = 0; l2 < 512; l2++) {
1748 cpu_physical_memory_read(pdp_addr + l2 * 8, &pdpe, 8);
1749 pdpe = le64_to_cpu(pdpe);
1750 end = (l1 << 39) + (l2 << 30);
1751 if (pdpe & PG_PRESENT_MASK) {
1752 if (pdpe & PG_PSE_MASK) {
1753 prot = pdpe & (PG_USER_MASK | PG_RW_MASK |
1754 PG_PRESENT_MASK);
1755 prot &= pml4e;
1756 mem_print(mon, &start, &last_prot, end, prot);
1757 } else {
1758 pd_addr = pdpe & 0x3fffffffff000ULL;
1759 for (l3 = 0; l3 < 512; l3++) {
1760 cpu_physical_memory_read(pd_addr + l3 * 8, &pde, 8);
1761 pde = le64_to_cpu(pde);
1762 end = (l1 << 39) + (l2 << 30) + (l3 << 21);
1763 if (pde & PG_PRESENT_MASK) {
1764 if (pde & PG_PSE_MASK) {
1765 prot = pde & (PG_USER_MASK | PG_RW_MASK |
1766 PG_PRESENT_MASK);
1767 prot &= pml4e & pdpe;
1768 mem_print(mon, &start, &last_prot, end, prot);
1769 } else {
1770 pt_addr = pde & 0x3fffffffff000ULL;
1771 for (l4 = 0; l4 < 512; l4++) {
1772 cpu_physical_memory_read(pt_addr
1773 + l4 * 8,
1774 &pte, 8);
1775 pte = le64_to_cpu(pte);
1776 end = (l1 << 39) + (l2 << 30) +
1777 (l3 << 21) + (l4 << 12);
1778 if (pte & PG_PRESENT_MASK) {
1779 prot = pte & (PG_USER_MASK | PG_RW_MASK |
1780 PG_PRESENT_MASK);
1781 prot &= pml4e & pdpe & pde;
1782 } else {
1783 prot = 0;
1785 mem_print(mon, &start, &last_prot, end, prot);
1788 } else {
1789 prot = 0;
1790 mem_print(mon, &start, &last_prot, end, prot);
1794 } else {
1795 prot = 0;
1796 mem_print(mon, &start, &last_prot, end, prot);
1799 } else {
1800 prot = 0;
1801 mem_print(mon, &start, &last_prot, end, prot);
1804 /* Flush last range */
1805 mem_print(mon, &start, &last_prot, (hwaddr)1 << 48, 0);
1807 #endif
1809 static void hmp_info_mem(Monitor *mon, const QDict *qdict)
1811 CPUArchState *env;
1813 env = mon_get_cpu();
1815 if (!(env->cr[0] & CR0_PG_MASK)) {
1816 monitor_printf(mon, "PG disabled\n");
1817 return;
1819 if (env->cr[4] & CR4_PAE_MASK) {
1820 #ifdef TARGET_X86_64
1821 if (env->hflags & HF_LMA_MASK) {
1822 mem_info_64(mon, env);
1823 } else
1824 #endif
1826 mem_info_pae32(mon, env);
1828 } else {
1829 mem_info_32(mon, env);
1832 #endif
1834 #if defined(TARGET_SH4)
1836 static void print_tlb(Monitor *mon, int idx, tlb_t *tlb)
1838 monitor_printf(mon, " tlb%i:\t"
1839 "asid=%hhu vpn=%x\tppn=%x\tsz=%hhu size=%u\t"
1840 "v=%hhu shared=%hhu cached=%hhu prot=%hhu "
1841 "dirty=%hhu writethrough=%hhu\n",
1842 idx,
1843 tlb->asid, tlb->vpn, tlb->ppn, tlb->sz, tlb->size,
1844 tlb->v, tlb->sh, tlb->c, tlb->pr,
1845 tlb->d, tlb->wt);
1848 static void hmp_info_tlb(Monitor *mon, const QDict *qdict)
1850 CPUArchState *env = mon_get_cpu();
1851 int i;
1853 monitor_printf (mon, "ITLB:\n");
1854 for (i = 0 ; i < ITLB_SIZE ; i++)
1855 print_tlb (mon, i, &env->itlb[i]);
1856 monitor_printf (mon, "UTLB:\n");
1857 for (i = 0 ; i < UTLB_SIZE ; i++)
1858 print_tlb (mon, i, &env->utlb[i]);
1861 #endif
1863 #if defined(TARGET_SPARC) || defined(TARGET_PPC) || defined(TARGET_XTENSA)
1864 static void hmp_info_tlb(Monitor *mon, const QDict *qdict)
1866 CPUArchState *env1 = mon_get_cpu();
1868 dump_mmu((FILE*)mon, (fprintf_function)monitor_printf, env1);
1870 #endif
1872 static void hmp_info_mtree(Monitor *mon, const QDict *qdict)
1874 mtree_info((fprintf_function)monitor_printf, mon);
1877 static void hmp_info_numa(Monitor *mon, const QDict *qdict)
1879 int i;
1880 CPUState *cpu;
1881 uint64_t *node_mem;
1883 node_mem = g_new0(uint64_t, nb_numa_nodes);
1884 query_numa_node_mem(node_mem);
1885 monitor_printf(mon, "%d nodes\n", nb_numa_nodes);
1886 for (i = 0; i < nb_numa_nodes; i++) {
1887 monitor_printf(mon, "node %d cpus:", i);
1888 CPU_FOREACH(cpu) {
1889 if (cpu->numa_node == i) {
1890 monitor_printf(mon, " %d", cpu->cpu_index);
1893 monitor_printf(mon, "\n");
1894 monitor_printf(mon, "node %d size: %" PRId64 " MB\n", i,
1895 node_mem[i] >> 20);
1897 g_free(node_mem);
1900 #ifdef CONFIG_PROFILER
1902 int64_t tcg_time;
1903 int64_t dev_time;
1905 static void hmp_info_profile(Monitor *mon, const QDict *qdict)
1907 monitor_printf(mon, "async time %" PRId64 " (%0.3f)\n",
1908 dev_time, dev_time / (double)get_ticks_per_sec());
1909 monitor_printf(mon, "qemu time %" PRId64 " (%0.3f)\n",
1910 tcg_time, tcg_time / (double)get_ticks_per_sec());
1911 tcg_time = 0;
1912 dev_time = 0;
1914 #else
1915 static void hmp_info_profile(Monitor *mon, const QDict *qdict)
1917 monitor_printf(mon, "Internal profiler not compiled\n");
1919 #endif
1921 /* Capture support */
1922 static QLIST_HEAD (capture_list_head, CaptureState) capture_head;
1924 static void hmp_info_capture(Monitor *mon, const QDict *qdict)
1926 int i;
1927 CaptureState *s;
1929 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
1930 monitor_printf(mon, "[%d]: ", i);
1931 s->ops.info (s->opaque);
1935 static void hmp_stopcapture(Monitor *mon, const QDict *qdict)
1937 int i;
1938 int n = qdict_get_int(qdict, "n");
1939 CaptureState *s;
1941 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
1942 if (i == n) {
1943 s->ops.destroy (s->opaque);
1944 QLIST_REMOVE (s, entries);
1945 g_free (s);
1946 return;
1951 static void hmp_wavcapture(Monitor *mon, const QDict *qdict)
1953 const char *path = qdict_get_str(qdict, "path");
1954 int has_freq = qdict_haskey(qdict, "freq");
1955 int freq = qdict_get_try_int(qdict, "freq", -1);
1956 int has_bits = qdict_haskey(qdict, "bits");
1957 int bits = qdict_get_try_int(qdict, "bits", -1);
1958 int has_channels = qdict_haskey(qdict, "nchannels");
1959 int nchannels = qdict_get_try_int(qdict, "nchannels", -1);
1960 CaptureState *s;
1962 s = g_malloc0 (sizeof (*s));
1964 freq = has_freq ? freq : 44100;
1965 bits = has_bits ? bits : 16;
1966 nchannels = has_channels ? nchannels : 2;
1968 if (wav_start_capture (s, path, freq, bits, nchannels)) {
1969 monitor_printf(mon, "Failed to add wave capture\n");
1970 g_free (s);
1971 return;
1973 QLIST_INSERT_HEAD (&capture_head, s, entries);
1976 static qemu_acl *find_acl(Monitor *mon, const char *name)
1978 qemu_acl *acl = qemu_acl_find(name);
1980 if (!acl) {
1981 monitor_printf(mon, "acl: unknown list '%s'\n", name);
1983 return acl;
1986 static void hmp_acl_show(Monitor *mon, const QDict *qdict)
1988 const char *aclname = qdict_get_str(qdict, "aclname");
1989 qemu_acl *acl = find_acl(mon, aclname);
1990 qemu_acl_entry *entry;
1991 int i = 0;
1993 if (acl) {
1994 monitor_printf(mon, "policy: %s\n",
1995 acl->defaultDeny ? "deny" : "allow");
1996 QTAILQ_FOREACH(entry, &acl->entries, next) {
1997 i++;
1998 monitor_printf(mon, "%d: %s %s\n", i,
1999 entry->deny ? "deny" : "allow", entry->match);
2004 static void hmp_acl_reset(Monitor *mon, const QDict *qdict)
2006 const char *aclname = qdict_get_str(qdict, "aclname");
2007 qemu_acl *acl = find_acl(mon, aclname);
2009 if (acl) {
2010 qemu_acl_reset(acl);
2011 monitor_printf(mon, "acl: removed all rules\n");
2015 static void hmp_acl_policy(Monitor *mon, const QDict *qdict)
2017 const char *aclname = qdict_get_str(qdict, "aclname");
2018 const char *policy = qdict_get_str(qdict, "policy");
2019 qemu_acl *acl = find_acl(mon, aclname);
2021 if (acl) {
2022 if (strcmp(policy, "allow") == 0) {
2023 acl->defaultDeny = 0;
2024 monitor_printf(mon, "acl: policy set to 'allow'\n");
2025 } else if (strcmp(policy, "deny") == 0) {
2026 acl->defaultDeny = 1;
2027 monitor_printf(mon, "acl: policy set to 'deny'\n");
2028 } else {
2029 monitor_printf(mon, "acl: unknown policy '%s', "
2030 "expected 'deny' or 'allow'\n", policy);
2035 static void hmp_acl_add(Monitor *mon, const QDict *qdict)
2037 const char *aclname = qdict_get_str(qdict, "aclname");
2038 const char *match = qdict_get_str(qdict, "match");
2039 const char *policy = qdict_get_str(qdict, "policy");
2040 int has_index = qdict_haskey(qdict, "index");
2041 int index = qdict_get_try_int(qdict, "index", -1);
2042 qemu_acl *acl = find_acl(mon, aclname);
2043 int deny, ret;
2045 if (acl) {
2046 if (strcmp(policy, "allow") == 0) {
2047 deny = 0;
2048 } else if (strcmp(policy, "deny") == 0) {
2049 deny = 1;
2050 } else {
2051 monitor_printf(mon, "acl: unknown policy '%s', "
2052 "expected 'deny' or 'allow'\n", policy);
2053 return;
2055 if (has_index)
2056 ret = qemu_acl_insert(acl, deny, match, index);
2057 else
2058 ret = qemu_acl_append(acl, deny, match);
2059 if (ret < 0)
2060 monitor_printf(mon, "acl: unable to add acl entry\n");
2061 else
2062 monitor_printf(mon, "acl: added rule at position %d\n", ret);
2066 static void hmp_acl_remove(Monitor *mon, const QDict *qdict)
2068 const char *aclname = qdict_get_str(qdict, "aclname");
2069 const char *match = qdict_get_str(qdict, "match");
2070 qemu_acl *acl = find_acl(mon, aclname);
2071 int ret;
2073 if (acl) {
2074 ret = qemu_acl_remove(acl, match);
2075 if (ret < 0)
2076 monitor_printf(mon, "acl: no matching acl entry\n");
2077 else
2078 monitor_printf(mon, "acl: removed rule at position %d\n", ret);
2082 #if defined(TARGET_I386)
2083 static void hmp_mce(Monitor *mon, const QDict *qdict)
2085 X86CPU *cpu;
2086 CPUState *cs;
2087 int cpu_index = qdict_get_int(qdict, "cpu_index");
2088 int bank = qdict_get_int(qdict, "bank");
2089 uint64_t status = qdict_get_int(qdict, "status");
2090 uint64_t mcg_status = qdict_get_int(qdict, "mcg_status");
2091 uint64_t addr = qdict_get_int(qdict, "addr");
2092 uint64_t misc = qdict_get_int(qdict, "misc");
2093 int flags = MCE_INJECT_UNCOND_AO;
2095 if (qdict_get_try_bool(qdict, "broadcast", 0)) {
2096 flags |= MCE_INJECT_BROADCAST;
2098 cs = qemu_get_cpu(cpu_index);
2099 if (cs != NULL) {
2100 cpu = X86_CPU(cs);
2101 cpu_x86_inject_mce(mon, cpu, bank, status, mcg_status, addr, misc,
2102 flags);
2105 #endif
2107 void qmp_getfd(const char *fdname, Error **errp)
2109 mon_fd_t *monfd;
2110 int fd;
2112 fd = qemu_chr_fe_get_msgfd(cur_mon->chr);
2113 if (fd == -1) {
2114 error_set(errp, QERR_FD_NOT_SUPPLIED);
2115 return;
2118 if (qemu_isdigit(fdname[0])) {
2119 close(fd);
2120 error_set(errp, QERR_INVALID_PARAMETER_VALUE, "fdname",
2121 "a name not starting with a digit");
2122 return;
2125 QLIST_FOREACH(monfd, &cur_mon->fds, next) {
2126 if (strcmp(monfd->name, fdname) != 0) {
2127 continue;
2130 close(monfd->fd);
2131 monfd->fd = fd;
2132 return;
2135 monfd = g_malloc0(sizeof(mon_fd_t));
2136 monfd->name = g_strdup(fdname);
2137 monfd->fd = fd;
2139 QLIST_INSERT_HEAD(&cur_mon->fds, monfd, next);
2142 void qmp_closefd(const char *fdname, Error **errp)
2144 mon_fd_t *monfd;
2146 QLIST_FOREACH(monfd, &cur_mon->fds, next) {
2147 if (strcmp(monfd->name, fdname) != 0) {
2148 continue;
2151 QLIST_REMOVE(monfd, next);
2152 close(monfd->fd);
2153 g_free(monfd->name);
2154 g_free(monfd);
2155 return;
2158 error_set(errp, QERR_FD_NOT_FOUND, fdname);
2161 static void hmp_loadvm(Monitor *mon, const QDict *qdict)
2163 int saved_vm_running = runstate_is_running();
2164 const char *name = qdict_get_str(qdict, "name");
2166 vm_stop(RUN_STATE_RESTORE_VM);
2168 if (load_vmstate(name) == 0 && saved_vm_running) {
2169 vm_start();
2173 int monitor_get_fd(Monitor *mon, const char *fdname, Error **errp)
2175 mon_fd_t *monfd;
2177 QLIST_FOREACH(monfd, &mon->fds, next) {
2178 int fd;
2180 if (strcmp(monfd->name, fdname) != 0) {
2181 continue;
2184 fd = monfd->fd;
2186 /* caller takes ownership of fd */
2187 QLIST_REMOVE(monfd, next);
2188 g_free(monfd->name);
2189 g_free(monfd);
2191 return fd;
2194 error_setg(errp, "File descriptor named '%s' has not been found", fdname);
2195 return -1;
2198 static void monitor_fdset_cleanup(MonFdset *mon_fdset)
2200 MonFdsetFd *mon_fdset_fd;
2201 MonFdsetFd *mon_fdset_fd_next;
2203 QLIST_FOREACH_SAFE(mon_fdset_fd, &mon_fdset->fds, next, mon_fdset_fd_next) {
2204 if ((mon_fdset_fd->removed ||
2205 (QLIST_EMPTY(&mon_fdset->dup_fds) && mon_refcount == 0)) &&
2206 runstate_is_running()) {
2207 close(mon_fdset_fd->fd);
2208 g_free(mon_fdset_fd->opaque);
2209 QLIST_REMOVE(mon_fdset_fd, next);
2210 g_free(mon_fdset_fd);
2214 if (QLIST_EMPTY(&mon_fdset->fds) && QLIST_EMPTY(&mon_fdset->dup_fds)) {
2215 QLIST_REMOVE(mon_fdset, next);
2216 g_free(mon_fdset);
2220 static void monitor_fdsets_cleanup(void)
2222 MonFdset *mon_fdset;
2223 MonFdset *mon_fdset_next;
2225 QLIST_FOREACH_SAFE(mon_fdset, &mon_fdsets, next, mon_fdset_next) {
2226 monitor_fdset_cleanup(mon_fdset);
2230 AddfdInfo *qmp_add_fd(bool has_fdset_id, int64_t fdset_id, bool has_opaque,
2231 const char *opaque, Error **errp)
2233 int fd;
2234 Monitor *mon = cur_mon;
2235 AddfdInfo *fdinfo;
2237 fd = qemu_chr_fe_get_msgfd(mon->chr);
2238 if (fd == -1) {
2239 error_set(errp, QERR_FD_NOT_SUPPLIED);
2240 goto error;
2243 fdinfo = monitor_fdset_add_fd(fd, has_fdset_id, fdset_id,
2244 has_opaque, opaque, errp);
2245 if (fdinfo) {
2246 return fdinfo;
2249 error:
2250 if (fd != -1) {
2251 close(fd);
2253 return NULL;
2256 void qmp_remove_fd(int64_t fdset_id, bool has_fd, int64_t fd, Error **errp)
2258 MonFdset *mon_fdset;
2259 MonFdsetFd *mon_fdset_fd;
2260 char fd_str[60];
2262 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2263 if (mon_fdset->id != fdset_id) {
2264 continue;
2266 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2267 if (has_fd) {
2268 if (mon_fdset_fd->fd != fd) {
2269 continue;
2271 mon_fdset_fd->removed = true;
2272 break;
2273 } else {
2274 mon_fdset_fd->removed = true;
2277 if (has_fd && !mon_fdset_fd) {
2278 goto error;
2280 monitor_fdset_cleanup(mon_fdset);
2281 return;
2284 error:
2285 if (has_fd) {
2286 snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64 ", fd:%" PRId64,
2287 fdset_id, fd);
2288 } else {
2289 snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64, fdset_id);
2291 error_set(errp, QERR_FD_NOT_FOUND, fd_str);
2294 FdsetInfoList *qmp_query_fdsets(Error **errp)
2296 MonFdset *mon_fdset;
2297 MonFdsetFd *mon_fdset_fd;
2298 FdsetInfoList *fdset_list = NULL;
2300 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2301 FdsetInfoList *fdset_info = g_malloc0(sizeof(*fdset_info));
2302 FdsetFdInfoList *fdsetfd_list = NULL;
2304 fdset_info->value = g_malloc0(sizeof(*fdset_info->value));
2305 fdset_info->value->fdset_id = mon_fdset->id;
2307 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2308 FdsetFdInfoList *fdsetfd_info;
2310 fdsetfd_info = g_malloc0(sizeof(*fdsetfd_info));
2311 fdsetfd_info->value = g_malloc0(sizeof(*fdsetfd_info->value));
2312 fdsetfd_info->value->fd = mon_fdset_fd->fd;
2313 if (mon_fdset_fd->opaque) {
2314 fdsetfd_info->value->has_opaque = true;
2315 fdsetfd_info->value->opaque = g_strdup(mon_fdset_fd->opaque);
2316 } else {
2317 fdsetfd_info->value->has_opaque = false;
2320 fdsetfd_info->next = fdsetfd_list;
2321 fdsetfd_list = fdsetfd_info;
2324 fdset_info->value->fds = fdsetfd_list;
2326 fdset_info->next = fdset_list;
2327 fdset_list = fdset_info;
2330 return fdset_list;
2333 AddfdInfo *monitor_fdset_add_fd(int fd, bool has_fdset_id, int64_t fdset_id,
2334 bool has_opaque, const char *opaque,
2335 Error **errp)
2337 MonFdset *mon_fdset = NULL;
2338 MonFdsetFd *mon_fdset_fd;
2339 AddfdInfo *fdinfo;
2341 if (has_fdset_id) {
2342 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2343 /* Break if match found or match impossible due to ordering by ID */
2344 if (fdset_id <= mon_fdset->id) {
2345 if (fdset_id < mon_fdset->id) {
2346 mon_fdset = NULL;
2348 break;
2353 if (mon_fdset == NULL) {
2354 int64_t fdset_id_prev = -1;
2355 MonFdset *mon_fdset_cur = QLIST_FIRST(&mon_fdsets);
2357 if (has_fdset_id) {
2358 if (fdset_id < 0) {
2359 error_set(errp, QERR_INVALID_PARAMETER_VALUE, "fdset-id",
2360 "a non-negative value");
2361 return NULL;
2363 /* Use specified fdset ID */
2364 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2365 mon_fdset_cur = mon_fdset;
2366 if (fdset_id < mon_fdset_cur->id) {
2367 break;
2370 } else {
2371 /* Use first available fdset ID */
2372 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2373 mon_fdset_cur = mon_fdset;
2374 if (fdset_id_prev == mon_fdset_cur->id - 1) {
2375 fdset_id_prev = mon_fdset_cur->id;
2376 continue;
2378 break;
2382 mon_fdset = g_malloc0(sizeof(*mon_fdset));
2383 if (has_fdset_id) {
2384 mon_fdset->id = fdset_id;
2385 } else {
2386 mon_fdset->id = fdset_id_prev + 1;
2389 /* The fdset list is ordered by fdset ID */
2390 if (!mon_fdset_cur) {
2391 QLIST_INSERT_HEAD(&mon_fdsets, mon_fdset, next);
2392 } else if (mon_fdset->id < mon_fdset_cur->id) {
2393 QLIST_INSERT_BEFORE(mon_fdset_cur, mon_fdset, next);
2394 } else {
2395 QLIST_INSERT_AFTER(mon_fdset_cur, mon_fdset, next);
2399 mon_fdset_fd = g_malloc0(sizeof(*mon_fdset_fd));
2400 mon_fdset_fd->fd = fd;
2401 mon_fdset_fd->removed = false;
2402 if (has_opaque) {
2403 mon_fdset_fd->opaque = g_strdup(opaque);
2405 QLIST_INSERT_HEAD(&mon_fdset->fds, mon_fdset_fd, next);
2407 fdinfo = g_malloc0(sizeof(*fdinfo));
2408 fdinfo->fdset_id = mon_fdset->id;
2409 fdinfo->fd = mon_fdset_fd->fd;
2411 return fdinfo;
2414 int monitor_fdset_get_fd(int64_t fdset_id, int flags)
2416 #ifndef _WIN32
2417 MonFdset *mon_fdset;
2418 MonFdsetFd *mon_fdset_fd;
2419 int mon_fd_flags;
2421 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2422 if (mon_fdset->id != fdset_id) {
2423 continue;
2425 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2426 mon_fd_flags = fcntl(mon_fdset_fd->fd, F_GETFL);
2427 if (mon_fd_flags == -1) {
2428 return -1;
2431 if ((flags & O_ACCMODE) == (mon_fd_flags & O_ACCMODE)) {
2432 return mon_fdset_fd->fd;
2435 errno = EACCES;
2436 return -1;
2438 #endif
2440 errno = ENOENT;
2441 return -1;
2444 int monitor_fdset_dup_fd_add(int64_t fdset_id, int dup_fd)
2446 MonFdset *mon_fdset;
2447 MonFdsetFd *mon_fdset_fd_dup;
2449 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2450 if (mon_fdset->id != fdset_id) {
2451 continue;
2453 QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
2454 if (mon_fdset_fd_dup->fd == dup_fd) {
2455 return -1;
2458 mon_fdset_fd_dup = g_malloc0(sizeof(*mon_fdset_fd_dup));
2459 mon_fdset_fd_dup->fd = dup_fd;
2460 QLIST_INSERT_HEAD(&mon_fdset->dup_fds, mon_fdset_fd_dup, next);
2461 return 0;
2463 return -1;
2466 static int monitor_fdset_dup_fd_find_remove(int dup_fd, bool remove)
2468 MonFdset *mon_fdset;
2469 MonFdsetFd *mon_fdset_fd_dup;
2471 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2472 QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
2473 if (mon_fdset_fd_dup->fd == dup_fd) {
2474 if (remove) {
2475 QLIST_REMOVE(mon_fdset_fd_dup, next);
2476 if (QLIST_EMPTY(&mon_fdset->dup_fds)) {
2477 monitor_fdset_cleanup(mon_fdset);
2479 return -1;
2480 } else {
2481 return mon_fdset->id;
2486 return -1;
2489 int monitor_fdset_dup_fd_find(int dup_fd)
2491 return monitor_fdset_dup_fd_find_remove(dup_fd, false);
2494 void monitor_fdset_dup_fd_remove(int dup_fd)
2496 monitor_fdset_dup_fd_find_remove(dup_fd, true);
2499 int monitor_fd_param(Monitor *mon, const char *fdname, Error **errp)
2501 int fd;
2502 Error *local_err = NULL;
2504 if (!qemu_isdigit(fdname[0]) && mon) {
2505 fd = monitor_get_fd(mon, fdname, &local_err);
2506 } else {
2507 fd = qemu_parse_fd(fdname);
2508 if (fd == -1) {
2509 error_setg(&local_err, "Invalid file descriptor number '%s'",
2510 fdname);
2513 if (local_err) {
2514 error_propagate(errp, local_err);
2515 assert(fd == -1);
2516 } else {
2517 assert(fd != -1);
2520 return fd;
2523 /* Please update hmp-commands.hx when adding or changing commands */
2524 static mon_cmd_t info_cmds[] = {
2526 .name = "version",
2527 .args_type = "",
2528 .params = "",
2529 .help = "show the version of QEMU",
2530 .mhandler.cmd = hmp_info_version,
2533 .name = "network",
2534 .args_type = "",
2535 .params = "",
2536 .help = "show the network state",
2537 .mhandler.cmd = hmp_info_network,
2540 .name = "chardev",
2541 .args_type = "",
2542 .params = "",
2543 .help = "show the character devices",
2544 .mhandler.cmd = hmp_info_chardev,
2547 .name = "block",
2548 .args_type = "nodes:-n,verbose:-v,device:B?",
2549 .params = "[-n] [-v] [device]",
2550 .help = "show info of one block device or all block devices "
2551 "(-n: show named nodes; -v: show details)",
2552 .mhandler.cmd = hmp_info_block,
2555 .name = "blockstats",
2556 .args_type = "",
2557 .params = "",
2558 .help = "show block device statistics",
2559 .mhandler.cmd = hmp_info_blockstats,
2562 .name = "block-jobs",
2563 .args_type = "",
2564 .params = "",
2565 .help = "show progress of ongoing block device operations",
2566 .mhandler.cmd = hmp_info_block_jobs,
2569 .name = "registers",
2570 .args_type = "",
2571 .params = "",
2572 .help = "show the cpu registers",
2573 .mhandler.cmd = hmp_info_registers,
2576 .name = "cpus",
2577 .args_type = "",
2578 .params = "",
2579 .help = "show infos for each CPU",
2580 .mhandler.cmd = hmp_info_cpus,
2583 .name = "history",
2584 .args_type = "",
2585 .params = "",
2586 .help = "show the command line history",
2587 .mhandler.cmd = hmp_info_history,
2589 #if defined(TARGET_I386) || defined(TARGET_PPC) || defined(TARGET_MIPS) || \
2590 defined(TARGET_LM32) || (defined(TARGET_SPARC) && !defined(TARGET_SPARC64))
2592 .name = "irq",
2593 .args_type = "",
2594 .params = "",
2595 .help = "show the interrupts statistics (if available)",
2596 #ifdef TARGET_SPARC
2597 .mhandler.cmd = sun4m_hmp_info_irq,
2598 #elif defined(TARGET_LM32)
2599 .mhandler.cmd = lm32_hmp_info_irq,
2600 #else
2601 .mhandler.cmd = hmp_info_irq,
2602 #endif
2605 .name = "pic",
2606 .args_type = "",
2607 .params = "",
2608 .help = "show i8259 (PIC) state",
2609 #ifdef TARGET_SPARC
2610 .mhandler.cmd = sun4m_hmp_info_pic,
2611 #elif defined(TARGET_LM32)
2612 .mhandler.cmd = lm32_hmp_info_pic,
2613 #else
2614 .mhandler.cmd = hmp_info_pic,
2615 #endif
2617 #endif
2619 .name = "pci",
2620 .args_type = "",
2621 .params = "",
2622 .help = "show PCI info",
2623 .mhandler.cmd = hmp_info_pci,
2625 #if defined(TARGET_I386) || defined(TARGET_SH4) || defined(TARGET_SPARC) || \
2626 defined(TARGET_PPC) || defined(TARGET_XTENSA)
2628 .name = "tlb",
2629 .args_type = "",
2630 .params = "",
2631 .help = "show virtual to physical memory mappings",
2632 .mhandler.cmd = hmp_info_tlb,
2634 #endif
2635 #if defined(TARGET_I386)
2637 .name = "mem",
2638 .args_type = "",
2639 .params = "",
2640 .help = "show the active virtual memory mappings",
2641 .mhandler.cmd = hmp_info_mem,
2643 #endif
2645 .name = "mtree",
2646 .args_type = "",
2647 .params = "",
2648 .help = "show memory tree",
2649 .mhandler.cmd = hmp_info_mtree,
2652 .name = "jit",
2653 .args_type = "",
2654 .params = "",
2655 .help = "show dynamic compiler info",
2656 .mhandler.cmd = hmp_info_jit,
2659 .name = "opcount",
2660 .args_type = "",
2661 .params = "",
2662 .help = "show dynamic compiler opcode counters",
2663 .mhandler.cmd = hmp_info_opcount,
2666 .name = "kvm",
2667 .args_type = "",
2668 .params = "",
2669 .help = "show KVM information",
2670 .mhandler.cmd = hmp_info_kvm,
2673 .name = "numa",
2674 .args_type = "",
2675 .params = "",
2676 .help = "show NUMA information",
2677 .mhandler.cmd = hmp_info_numa,
2680 .name = "usb",
2681 .args_type = "",
2682 .params = "",
2683 .help = "show guest USB devices",
2684 .mhandler.cmd = hmp_info_usb,
2687 .name = "usbhost",
2688 .args_type = "",
2689 .params = "",
2690 .help = "show host USB devices",
2691 .mhandler.cmd = hmp_info_usbhost,
2694 .name = "profile",
2695 .args_type = "",
2696 .params = "",
2697 .help = "show profiling information",
2698 .mhandler.cmd = hmp_info_profile,
2701 .name = "capture",
2702 .args_type = "",
2703 .params = "",
2704 .help = "show capture information",
2705 .mhandler.cmd = hmp_info_capture,
2708 .name = "snapshots",
2709 .args_type = "",
2710 .params = "",
2711 .help = "show the currently saved VM snapshots",
2712 .mhandler.cmd = hmp_info_snapshots,
2715 .name = "status",
2716 .args_type = "",
2717 .params = "",
2718 .help = "show the current VM status (running|paused)",
2719 .mhandler.cmd = hmp_info_status,
2722 .name = "mice",
2723 .args_type = "",
2724 .params = "",
2725 .help = "show which guest mouse is receiving events",
2726 .mhandler.cmd = hmp_info_mice,
2729 .name = "vnc",
2730 .args_type = "",
2731 .params = "",
2732 .help = "show the vnc server status",
2733 .mhandler.cmd = hmp_info_vnc,
2735 #if defined(CONFIG_SPICE)
2737 .name = "spice",
2738 .args_type = "",
2739 .params = "",
2740 .help = "show the spice server status",
2741 .mhandler.cmd = hmp_info_spice,
2743 #endif
2745 .name = "name",
2746 .args_type = "",
2747 .params = "",
2748 .help = "show the current VM name",
2749 .mhandler.cmd = hmp_info_name,
2752 .name = "uuid",
2753 .args_type = "",
2754 .params = "",
2755 .help = "show the current VM UUID",
2756 .mhandler.cmd = hmp_info_uuid,
2759 .name = "cpustats",
2760 .args_type = "",
2761 .params = "",
2762 .help = "show CPU statistics",
2763 .mhandler.cmd = hmp_info_cpustats,
2765 #if defined(CONFIG_SLIRP)
2767 .name = "usernet",
2768 .args_type = "",
2769 .params = "",
2770 .help = "show user network stack connection states",
2771 .mhandler.cmd = hmp_info_usernet,
2773 #endif
2775 .name = "migrate",
2776 .args_type = "",
2777 .params = "",
2778 .help = "show migration status",
2779 .mhandler.cmd = hmp_info_migrate,
2782 .name = "migrate_capabilities",
2783 .args_type = "",
2784 .params = "",
2785 .help = "show current migration capabilities",
2786 .mhandler.cmd = hmp_info_migrate_capabilities,
2789 .name = "migrate_parameters",
2790 .args_type = "",
2791 .params = "",
2792 .help = "show current migration parameters",
2793 .mhandler.cmd = hmp_info_migrate_parameters,
2796 .name = "migrate_cache_size",
2797 .args_type = "",
2798 .params = "",
2799 .help = "show current migration xbzrle cache size",
2800 .mhandler.cmd = hmp_info_migrate_cache_size,
2803 .name = "balloon",
2804 .args_type = "",
2805 .params = "",
2806 .help = "show balloon information",
2807 .mhandler.cmd = hmp_info_balloon,
2810 .name = "qtree",
2811 .args_type = "",
2812 .params = "",
2813 .help = "show device tree",
2814 .mhandler.cmd = hmp_info_qtree,
2817 .name = "qdm",
2818 .args_type = "",
2819 .params = "",
2820 .help = "show qdev device model list",
2821 .mhandler.cmd = hmp_info_qdm,
2824 .name = "qom-tree",
2825 .args_type = "path:s?",
2826 .params = "[path]",
2827 .help = "show QOM composition tree",
2828 .mhandler.cmd = hmp_info_qom_tree,
2831 .name = "roms",
2832 .args_type = "",
2833 .params = "",
2834 .help = "show roms",
2835 .mhandler.cmd = hmp_info_roms,
2838 .name = "trace-events",
2839 .args_type = "",
2840 .params = "",
2841 .help = "show available trace-events & their state",
2842 .mhandler.cmd = hmp_info_trace_events,
2845 .name = "tpm",
2846 .args_type = "",
2847 .params = "",
2848 .help = "show the TPM device",
2849 .mhandler.cmd = hmp_info_tpm,
2852 .name = "memdev",
2853 .args_type = "",
2854 .params = "",
2855 .help = "show memory backends",
2856 .mhandler.cmd = hmp_info_memdev,
2859 .name = "memory-devices",
2860 .args_type = "",
2861 .params = "",
2862 .help = "show memory devices",
2863 .mhandler.cmd = hmp_info_memory_devices,
2866 .name = "rocker",
2867 .args_type = "name:s",
2868 .params = "name",
2869 .help = "Show rocker switch",
2870 .mhandler.cmd = hmp_rocker,
2873 .name = "rocker-ports",
2874 .args_type = "name:s",
2875 .params = "name",
2876 .help = "Show rocker ports",
2877 .mhandler.cmd = hmp_rocker_ports,
2880 .name = "rocker-of-dpa-flows",
2881 .args_type = "name:s,tbl_id:i?",
2882 .params = "name [tbl_id]",
2883 .help = "Show rocker OF-DPA flow tables",
2884 .mhandler.cmd = hmp_rocker_of_dpa_flows,
2887 .name = "rocker-of-dpa-groups",
2888 .args_type = "name:s,type:i?",
2889 .params = "name [type]",
2890 .help = "Show rocker OF-DPA groups",
2891 .mhandler.cmd = hmp_rocker_of_dpa_groups,
2894 .name = NULL,
2898 /* mon_cmds and info_cmds would be sorted at runtime */
2899 static mon_cmd_t mon_cmds[] = {
2900 #include "hmp-commands.h"
2901 { NULL, NULL, },
2904 static const mon_cmd_t qmp_cmds[] = {
2905 #include "qmp-commands-old.h"
2906 { /* NULL */ },
2909 /*******************************************************************/
2911 static const char *pch;
2912 static sigjmp_buf expr_env;
2914 #define MD_TLONG 0
2915 #define MD_I32 1
2917 typedef struct MonitorDef {
2918 const char *name;
2919 int offset;
2920 target_long (*get_value)(const struct MonitorDef *md, int val);
2921 int type;
2922 } MonitorDef;
2924 #if defined(TARGET_I386)
2925 static target_long monitor_get_pc (const struct MonitorDef *md, int val)
2927 CPUArchState *env = mon_get_cpu();
2928 return env->eip + env->segs[R_CS].base;
2930 #endif
2932 #if defined(TARGET_PPC)
2933 static target_long monitor_get_ccr (const struct MonitorDef *md, int val)
2935 CPUArchState *env = mon_get_cpu();
2936 unsigned int u;
2937 int i;
2939 u = 0;
2940 for (i = 0; i < 8; i++)
2941 u |= env->crf[i] << (32 - (4 * (i + 1)));
2943 return u;
2946 static target_long monitor_get_msr (const struct MonitorDef *md, int val)
2948 CPUArchState *env = mon_get_cpu();
2949 return env->msr;
2952 static target_long monitor_get_xer (const struct MonitorDef *md, int val)
2954 CPUArchState *env = mon_get_cpu();
2955 return env->xer;
2958 static target_long monitor_get_decr (const struct MonitorDef *md, int val)
2960 CPUArchState *env = mon_get_cpu();
2961 return cpu_ppc_load_decr(env);
2964 static target_long monitor_get_tbu (const struct MonitorDef *md, int val)
2966 CPUArchState *env = mon_get_cpu();
2967 return cpu_ppc_load_tbu(env);
2970 static target_long monitor_get_tbl (const struct MonitorDef *md, int val)
2972 CPUArchState *env = mon_get_cpu();
2973 return cpu_ppc_load_tbl(env);
2975 #endif
2977 #if defined(TARGET_SPARC)
2978 #ifndef TARGET_SPARC64
2979 static target_long monitor_get_psr (const struct MonitorDef *md, int val)
2981 CPUArchState *env = mon_get_cpu();
2983 return cpu_get_psr(env);
2985 #endif
2987 static target_long monitor_get_reg(const struct MonitorDef *md, int val)
2989 CPUArchState *env = mon_get_cpu();
2990 return env->regwptr[val];
2992 #endif
2994 static const MonitorDef monitor_defs[] = {
2995 #ifdef TARGET_I386
2997 #define SEG(name, seg) \
2998 { name, offsetof(CPUX86State, segs[seg].selector), NULL, MD_I32 },\
2999 { name ".base", offsetof(CPUX86State, segs[seg].base) },\
3000 { name ".limit", offsetof(CPUX86State, segs[seg].limit), NULL, MD_I32 },
3002 { "eax", offsetof(CPUX86State, regs[0]) },
3003 { "ecx", offsetof(CPUX86State, regs[1]) },
3004 { "edx", offsetof(CPUX86State, regs[2]) },
3005 { "ebx", offsetof(CPUX86State, regs[3]) },
3006 { "esp|sp", offsetof(CPUX86State, regs[4]) },
3007 { "ebp|fp", offsetof(CPUX86State, regs[5]) },
3008 { "esi", offsetof(CPUX86State, regs[6]) },
3009 { "edi", offsetof(CPUX86State, regs[7]) },
3010 #ifdef TARGET_X86_64
3011 { "r8", offsetof(CPUX86State, regs[8]) },
3012 { "r9", offsetof(CPUX86State, regs[9]) },
3013 { "r10", offsetof(CPUX86State, regs[10]) },
3014 { "r11", offsetof(CPUX86State, regs[11]) },
3015 { "r12", offsetof(CPUX86State, regs[12]) },
3016 { "r13", offsetof(CPUX86State, regs[13]) },
3017 { "r14", offsetof(CPUX86State, regs[14]) },
3018 { "r15", offsetof(CPUX86State, regs[15]) },
3019 #endif
3020 { "eflags", offsetof(CPUX86State, eflags) },
3021 { "eip", offsetof(CPUX86State, eip) },
3022 SEG("cs", R_CS)
3023 SEG("ds", R_DS)
3024 SEG("es", R_ES)
3025 SEG("ss", R_SS)
3026 SEG("fs", R_FS)
3027 SEG("gs", R_GS)
3028 { "pc", 0, monitor_get_pc, },
3029 #elif defined(TARGET_PPC)
3030 /* General purpose registers */
3031 { "r0", offsetof(CPUPPCState, gpr[0]) },
3032 { "r1", offsetof(CPUPPCState, gpr[1]) },
3033 { "r2", offsetof(CPUPPCState, gpr[2]) },
3034 { "r3", offsetof(CPUPPCState, gpr[3]) },
3035 { "r4", offsetof(CPUPPCState, gpr[4]) },
3036 { "r5", offsetof(CPUPPCState, gpr[5]) },
3037 { "r6", offsetof(CPUPPCState, gpr[6]) },
3038 { "r7", offsetof(CPUPPCState, gpr[7]) },
3039 { "r8", offsetof(CPUPPCState, gpr[8]) },
3040 { "r9", offsetof(CPUPPCState, gpr[9]) },
3041 { "r10", offsetof(CPUPPCState, gpr[10]) },
3042 { "r11", offsetof(CPUPPCState, gpr[11]) },
3043 { "r12", offsetof(CPUPPCState, gpr[12]) },
3044 { "r13", offsetof(CPUPPCState, gpr[13]) },
3045 { "r14", offsetof(CPUPPCState, gpr[14]) },
3046 { "r15", offsetof(CPUPPCState, gpr[15]) },
3047 { "r16", offsetof(CPUPPCState, gpr[16]) },
3048 { "r17", offsetof(CPUPPCState, gpr[17]) },
3049 { "r18", offsetof(CPUPPCState, gpr[18]) },
3050 { "r19", offsetof(CPUPPCState, gpr[19]) },
3051 { "r20", offsetof(CPUPPCState, gpr[20]) },
3052 { "r21", offsetof(CPUPPCState, gpr[21]) },
3053 { "r22", offsetof(CPUPPCState, gpr[22]) },
3054 { "r23", offsetof(CPUPPCState, gpr[23]) },
3055 { "r24", offsetof(CPUPPCState, gpr[24]) },
3056 { "r25", offsetof(CPUPPCState, gpr[25]) },
3057 { "r26", offsetof(CPUPPCState, gpr[26]) },
3058 { "r27", offsetof(CPUPPCState, gpr[27]) },
3059 { "r28", offsetof(CPUPPCState, gpr[28]) },
3060 { "r29", offsetof(CPUPPCState, gpr[29]) },
3061 { "r30", offsetof(CPUPPCState, gpr[30]) },
3062 { "r31", offsetof(CPUPPCState, gpr[31]) },
3063 /* Floating point registers */
3064 { "f0", offsetof(CPUPPCState, fpr[0]) },
3065 { "f1", offsetof(CPUPPCState, fpr[1]) },
3066 { "f2", offsetof(CPUPPCState, fpr[2]) },
3067 { "f3", offsetof(CPUPPCState, fpr[3]) },
3068 { "f4", offsetof(CPUPPCState, fpr[4]) },
3069 { "f5", offsetof(CPUPPCState, fpr[5]) },
3070 { "f6", offsetof(CPUPPCState, fpr[6]) },
3071 { "f7", offsetof(CPUPPCState, fpr[7]) },
3072 { "f8", offsetof(CPUPPCState, fpr[8]) },
3073 { "f9", offsetof(CPUPPCState, fpr[9]) },
3074 { "f10", offsetof(CPUPPCState, fpr[10]) },
3075 { "f11", offsetof(CPUPPCState, fpr[11]) },
3076 { "f12", offsetof(CPUPPCState, fpr[12]) },
3077 { "f13", offsetof(CPUPPCState, fpr[13]) },
3078 { "f14", offsetof(CPUPPCState, fpr[14]) },
3079 { "f15", offsetof(CPUPPCState, fpr[15]) },
3080 { "f16", offsetof(CPUPPCState, fpr[16]) },
3081 { "f17", offsetof(CPUPPCState, fpr[17]) },
3082 { "f18", offsetof(CPUPPCState, fpr[18]) },
3083 { "f19", offsetof(CPUPPCState, fpr[19]) },
3084 { "f20", offsetof(CPUPPCState, fpr[20]) },
3085 { "f21", offsetof(CPUPPCState, fpr[21]) },
3086 { "f22", offsetof(CPUPPCState, fpr[22]) },
3087 { "f23", offsetof(CPUPPCState, fpr[23]) },
3088 { "f24", offsetof(CPUPPCState, fpr[24]) },
3089 { "f25", offsetof(CPUPPCState, fpr[25]) },
3090 { "f26", offsetof(CPUPPCState, fpr[26]) },
3091 { "f27", offsetof(CPUPPCState, fpr[27]) },
3092 { "f28", offsetof(CPUPPCState, fpr[28]) },
3093 { "f29", offsetof(CPUPPCState, fpr[29]) },
3094 { "f30", offsetof(CPUPPCState, fpr[30]) },
3095 { "f31", offsetof(CPUPPCState, fpr[31]) },
3096 { "fpscr", offsetof(CPUPPCState, fpscr) },
3097 /* Next instruction pointer */
3098 { "nip|pc", offsetof(CPUPPCState, nip) },
3099 { "lr", offsetof(CPUPPCState, lr) },
3100 { "ctr", offsetof(CPUPPCState, ctr) },
3101 { "decr", 0, &monitor_get_decr, },
3102 { "ccr", 0, &monitor_get_ccr, },
3103 /* Machine state register */
3104 { "msr", 0, &monitor_get_msr, },
3105 { "xer", 0, &monitor_get_xer, },
3106 { "tbu", 0, &monitor_get_tbu, },
3107 { "tbl", 0, &monitor_get_tbl, },
3108 /* Segment registers */
3109 { "sdr1", offsetof(CPUPPCState, spr[SPR_SDR1]) },
3110 { "sr0", offsetof(CPUPPCState, sr[0]) },
3111 { "sr1", offsetof(CPUPPCState, sr[1]) },
3112 { "sr2", offsetof(CPUPPCState, sr[2]) },
3113 { "sr3", offsetof(CPUPPCState, sr[3]) },
3114 { "sr4", offsetof(CPUPPCState, sr[4]) },
3115 { "sr5", offsetof(CPUPPCState, sr[5]) },
3116 { "sr6", offsetof(CPUPPCState, sr[6]) },
3117 { "sr7", offsetof(CPUPPCState, sr[7]) },
3118 { "sr8", offsetof(CPUPPCState, sr[8]) },
3119 { "sr9", offsetof(CPUPPCState, sr[9]) },
3120 { "sr10", offsetof(CPUPPCState, sr[10]) },
3121 { "sr11", offsetof(CPUPPCState, sr[11]) },
3122 { "sr12", offsetof(CPUPPCState, sr[12]) },
3123 { "sr13", offsetof(CPUPPCState, sr[13]) },
3124 { "sr14", offsetof(CPUPPCState, sr[14]) },
3125 { "sr15", offsetof(CPUPPCState, sr[15]) },
3126 /* Too lazy to put BATs... */
3127 { "pvr", offsetof(CPUPPCState, spr[SPR_PVR]) },
3129 { "srr0", offsetof(CPUPPCState, spr[SPR_SRR0]) },
3130 { "srr1", offsetof(CPUPPCState, spr[SPR_SRR1]) },
3131 { "dar", offsetof(CPUPPCState, spr[SPR_DAR]) },
3132 { "dsisr", offsetof(CPUPPCState, spr[SPR_DSISR]) },
3133 { "cfar", offsetof(CPUPPCState, spr[SPR_CFAR]) },
3134 { "sprg0", offsetof(CPUPPCState, spr[SPR_SPRG0]) },
3135 { "sprg1", offsetof(CPUPPCState, spr[SPR_SPRG1]) },
3136 { "sprg2", offsetof(CPUPPCState, spr[SPR_SPRG2]) },
3137 { "sprg3", offsetof(CPUPPCState, spr[SPR_SPRG3]) },
3138 { "sprg4", offsetof(CPUPPCState, spr[SPR_SPRG4]) },
3139 { "sprg5", offsetof(CPUPPCState, spr[SPR_SPRG5]) },
3140 { "sprg6", offsetof(CPUPPCState, spr[SPR_SPRG6]) },
3141 { "sprg7", offsetof(CPUPPCState, spr[SPR_SPRG7]) },
3142 { "pid", offsetof(CPUPPCState, spr[SPR_BOOKE_PID]) },
3143 { "csrr0", offsetof(CPUPPCState, spr[SPR_BOOKE_CSRR0]) },
3144 { "csrr1", offsetof(CPUPPCState, spr[SPR_BOOKE_CSRR1]) },
3145 { "esr", offsetof(CPUPPCState, spr[SPR_BOOKE_ESR]) },
3146 { "dear", offsetof(CPUPPCState, spr[SPR_BOOKE_DEAR]) },
3147 { "mcsr", offsetof(CPUPPCState, spr[SPR_BOOKE_MCSR]) },
3148 { "tsr", offsetof(CPUPPCState, spr[SPR_BOOKE_TSR]) },
3149 { "tcr", offsetof(CPUPPCState, spr[SPR_BOOKE_TCR]) },
3150 { "vrsave", offsetof(CPUPPCState, spr[SPR_VRSAVE]) },
3151 { "pir", offsetof(CPUPPCState, spr[SPR_BOOKE_PIR]) },
3152 { "mcsrr0", offsetof(CPUPPCState, spr[SPR_BOOKE_MCSRR0]) },
3153 { "mcsrr1", offsetof(CPUPPCState, spr[SPR_BOOKE_MCSRR1]) },
3154 { "decar", offsetof(CPUPPCState, spr[SPR_BOOKE_DECAR]) },
3155 { "ivpr", offsetof(CPUPPCState, spr[SPR_BOOKE_IVPR]) },
3156 { "epcr", offsetof(CPUPPCState, spr[SPR_BOOKE_EPCR]) },
3157 { "sprg8", offsetof(CPUPPCState, spr[SPR_BOOKE_SPRG8]) },
3158 { "ivor0", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR0]) },
3159 { "ivor1", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR1]) },
3160 { "ivor2", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR2]) },
3161 { "ivor3", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR3]) },
3162 { "ivor4", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR4]) },
3163 { "ivor5", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR5]) },
3164 { "ivor6", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR6]) },
3165 { "ivor7", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR7]) },
3166 { "ivor8", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR8]) },
3167 { "ivor9", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR9]) },
3168 { "ivor10", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR10]) },
3169 { "ivor11", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR11]) },
3170 { "ivor12", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR12]) },
3171 { "ivor13", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR13]) },
3172 { "ivor14", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR14]) },
3173 { "ivor15", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR15]) },
3174 { "ivor32", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR32]) },
3175 { "ivor33", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR33]) },
3176 { "ivor34", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR34]) },
3177 { "ivor35", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR35]) },
3178 { "ivor36", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR36]) },
3179 { "ivor37", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR37]) },
3180 { "mas0", offsetof(CPUPPCState, spr[SPR_BOOKE_MAS0]) },
3181 { "mas1", offsetof(CPUPPCState, spr[SPR_BOOKE_MAS1]) },
3182 { "mas2", offsetof(CPUPPCState, spr[SPR_BOOKE_MAS2]) },
3183 { "mas3", offsetof(CPUPPCState, spr[SPR_BOOKE_MAS3]) },
3184 { "mas4", offsetof(CPUPPCState, spr[SPR_BOOKE_MAS4]) },
3185 { "mas6", offsetof(CPUPPCState, spr[SPR_BOOKE_MAS6]) },
3186 { "mas7", offsetof(CPUPPCState, spr[SPR_BOOKE_MAS7]) },
3187 { "mmucfg", offsetof(CPUPPCState, spr[SPR_MMUCFG]) },
3188 { "tlb0cfg", offsetof(CPUPPCState, spr[SPR_BOOKE_TLB0CFG]) },
3189 { "tlb1cfg", offsetof(CPUPPCState, spr[SPR_BOOKE_TLB1CFG]) },
3190 { "epr", offsetof(CPUPPCState, spr[SPR_BOOKE_EPR]) },
3191 { "eplc", offsetof(CPUPPCState, spr[SPR_BOOKE_EPLC]) },
3192 { "epsc", offsetof(CPUPPCState, spr[SPR_BOOKE_EPSC]) },
3193 { "svr", offsetof(CPUPPCState, spr[SPR_E500_SVR]) },
3194 { "mcar", offsetof(CPUPPCState, spr[SPR_Exxx_MCAR]) },
3195 { "pid1", offsetof(CPUPPCState, spr[SPR_BOOKE_PID1]) },
3196 { "pid2", offsetof(CPUPPCState, spr[SPR_BOOKE_PID2]) },
3197 { "hid0", offsetof(CPUPPCState, spr[SPR_HID0]) },
3199 #elif defined(TARGET_SPARC)
3200 { "g0", offsetof(CPUSPARCState, gregs[0]) },
3201 { "g1", offsetof(CPUSPARCState, gregs[1]) },
3202 { "g2", offsetof(CPUSPARCState, gregs[2]) },
3203 { "g3", offsetof(CPUSPARCState, gregs[3]) },
3204 { "g4", offsetof(CPUSPARCState, gregs[4]) },
3205 { "g5", offsetof(CPUSPARCState, gregs[5]) },
3206 { "g6", offsetof(CPUSPARCState, gregs[6]) },
3207 { "g7", offsetof(CPUSPARCState, gregs[7]) },
3208 { "o0", 0, monitor_get_reg },
3209 { "o1", 1, monitor_get_reg },
3210 { "o2", 2, monitor_get_reg },
3211 { "o3", 3, monitor_get_reg },
3212 { "o4", 4, monitor_get_reg },
3213 { "o5", 5, monitor_get_reg },
3214 { "o6", 6, monitor_get_reg },
3215 { "o7", 7, monitor_get_reg },
3216 { "l0", 8, monitor_get_reg },
3217 { "l1", 9, monitor_get_reg },
3218 { "l2", 10, monitor_get_reg },
3219 { "l3", 11, monitor_get_reg },
3220 { "l4", 12, monitor_get_reg },
3221 { "l5", 13, monitor_get_reg },
3222 { "l6", 14, monitor_get_reg },
3223 { "l7", 15, monitor_get_reg },
3224 { "i0", 16, monitor_get_reg },
3225 { "i1", 17, monitor_get_reg },
3226 { "i2", 18, monitor_get_reg },
3227 { "i3", 19, monitor_get_reg },
3228 { "i4", 20, monitor_get_reg },
3229 { "i5", 21, monitor_get_reg },
3230 { "i6", 22, monitor_get_reg },
3231 { "i7", 23, monitor_get_reg },
3232 { "pc", offsetof(CPUSPARCState, pc) },
3233 { "npc", offsetof(CPUSPARCState, npc) },
3234 { "y", offsetof(CPUSPARCState, y) },
3235 #ifndef TARGET_SPARC64
3236 { "psr", 0, &monitor_get_psr, },
3237 { "wim", offsetof(CPUSPARCState, wim) },
3238 #endif
3239 { "tbr", offsetof(CPUSPARCState, tbr) },
3240 { "fsr", offsetof(CPUSPARCState, fsr) },
3241 { "f0", offsetof(CPUSPARCState, fpr[0].l.upper) },
3242 { "f1", offsetof(CPUSPARCState, fpr[0].l.lower) },
3243 { "f2", offsetof(CPUSPARCState, fpr[1].l.upper) },
3244 { "f3", offsetof(CPUSPARCState, fpr[1].l.lower) },
3245 { "f4", offsetof(CPUSPARCState, fpr[2].l.upper) },
3246 { "f5", offsetof(CPUSPARCState, fpr[2].l.lower) },
3247 { "f6", offsetof(CPUSPARCState, fpr[3].l.upper) },
3248 { "f7", offsetof(CPUSPARCState, fpr[3].l.lower) },
3249 { "f8", offsetof(CPUSPARCState, fpr[4].l.upper) },
3250 { "f9", offsetof(CPUSPARCState, fpr[4].l.lower) },
3251 { "f10", offsetof(CPUSPARCState, fpr[5].l.upper) },
3252 { "f11", offsetof(CPUSPARCState, fpr[5].l.lower) },
3253 { "f12", offsetof(CPUSPARCState, fpr[6].l.upper) },
3254 { "f13", offsetof(CPUSPARCState, fpr[6].l.lower) },
3255 { "f14", offsetof(CPUSPARCState, fpr[7].l.upper) },
3256 { "f15", offsetof(CPUSPARCState, fpr[7].l.lower) },
3257 { "f16", offsetof(CPUSPARCState, fpr[8].l.upper) },
3258 { "f17", offsetof(CPUSPARCState, fpr[8].l.lower) },
3259 { "f18", offsetof(CPUSPARCState, fpr[9].l.upper) },
3260 { "f19", offsetof(CPUSPARCState, fpr[9].l.lower) },
3261 { "f20", offsetof(CPUSPARCState, fpr[10].l.upper) },
3262 { "f21", offsetof(CPUSPARCState, fpr[10].l.lower) },
3263 { "f22", offsetof(CPUSPARCState, fpr[11].l.upper) },
3264 { "f23", offsetof(CPUSPARCState, fpr[11].l.lower) },
3265 { "f24", offsetof(CPUSPARCState, fpr[12].l.upper) },
3266 { "f25", offsetof(CPUSPARCState, fpr[12].l.lower) },
3267 { "f26", offsetof(CPUSPARCState, fpr[13].l.upper) },
3268 { "f27", offsetof(CPUSPARCState, fpr[13].l.lower) },
3269 { "f28", offsetof(CPUSPARCState, fpr[14].l.upper) },
3270 { "f29", offsetof(CPUSPARCState, fpr[14].l.lower) },
3271 { "f30", offsetof(CPUSPARCState, fpr[15].l.upper) },
3272 { "f31", offsetof(CPUSPARCState, fpr[15].l.lower) },
3273 #ifdef TARGET_SPARC64
3274 { "f32", offsetof(CPUSPARCState, fpr[16]) },
3275 { "f34", offsetof(CPUSPARCState, fpr[17]) },
3276 { "f36", offsetof(CPUSPARCState, fpr[18]) },
3277 { "f38", offsetof(CPUSPARCState, fpr[19]) },
3278 { "f40", offsetof(CPUSPARCState, fpr[20]) },
3279 { "f42", offsetof(CPUSPARCState, fpr[21]) },
3280 { "f44", offsetof(CPUSPARCState, fpr[22]) },
3281 { "f46", offsetof(CPUSPARCState, fpr[23]) },
3282 { "f48", offsetof(CPUSPARCState, fpr[24]) },
3283 { "f50", offsetof(CPUSPARCState, fpr[25]) },
3284 { "f52", offsetof(CPUSPARCState, fpr[26]) },
3285 { "f54", offsetof(CPUSPARCState, fpr[27]) },
3286 { "f56", offsetof(CPUSPARCState, fpr[28]) },
3287 { "f58", offsetof(CPUSPARCState, fpr[29]) },
3288 { "f60", offsetof(CPUSPARCState, fpr[30]) },
3289 { "f62", offsetof(CPUSPARCState, fpr[31]) },
3290 { "asi", offsetof(CPUSPARCState, asi) },
3291 { "pstate", offsetof(CPUSPARCState, pstate) },
3292 { "cansave", offsetof(CPUSPARCState, cansave) },
3293 { "canrestore", offsetof(CPUSPARCState, canrestore) },
3294 { "otherwin", offsetof(CPUSPARCState, otherwin) },
3295 { "wstate", offsetof(CPUSPARCState, wstate) },
3296 { "cleanwin", offsetof(CPUSPARCState, cleanwin) },
3297 { "fprs", offsetof(CPUSPARCState, fprs) },
3298 #endif
3299 #endif
3300 { NULL },
3303 static void GCC_FMT_ATTR(2, 3) QEMU_NORETURN
3304 expr_error(Monitor *mon, const char *fmt, ...)
3306 va_list ap;
3307 va_start(ap, fmt);
3308 monitor_vprintf(mon, fmt, ap);
3309 monitor_printf(mon, "\n");
3310 va_end(ap);
3311 siglongjmp(expr_env, 1);
3314 /* return 0 if OK, -1 if not found */
3315 static int get_monitor_def(target_long *pval, const char *name)
3317 const MonitorDef *md;
3318 void *ptr;
3320 for(md = monitor_defs; md->name != NULL; md++) {
3321 if (compare_cmd(name, md->name)) {
3322 if (md->get_value) {
3323 *pval = md->get_value(md, md->offset);
3324 } else {
3325 CPUArchState *env = mon_get_cpu();
3326 ptr = (uint8_t *)env + md->offset;
3327 switch(md->type) {
3328 case MD_I32:
3329 *pval = *(int32_t *)ptr;
3330 break;
3331 case MD_TLONG:
3332 *pval = *(target_long *)ptr;
3333 break;
3334 default:
3335 *pval = 0;
3336 break;
3339 return 0;
3342 return -1;
3345 static void next(void)
3347 if (*pch != '\0') {
3348 pch++;
3349 while (qemu_isspace(*pch))
3350 pch++;
3354 static int64_t expr_sum(Monitor *mon);
3356 static int64_t expr_unary(Monitor *mon)
3358 int64_t n;
3359 char *p;
3360 int ret;
3362 switch(*pch) {
3363 case '+':
3364 next();
3365 n = expr_unary(mon);
3366 break;
3367 case '-':
3368 next();
3369 n = -expr_unary(mon);
3370 break;
3371 case '~':
3372 next();
3373 n = ~expr_unary(mon);
3374 break;
3375 case '(':
3376 next();
3377 n = expr_sum(mon);
3378 if (*pch != ')') {
3379 expr_error(mon, "')' expected");
3381 next();
3382 break;
3383 case '\'':
3384 pch++;
3385 if (*pch == '\0')
3386 expr_error(mon, "character constant expected");
3387 n = *pch;
3388 pch++;
3389 if (*pch != '\'')
3390 expr_error(mon, "missing terminating \' character");
3391 next();
3392 break;
3393 case '$':
3395 char buf[128], *q;
3396 target_long reg=0;
3398 pch++;
3399 q = buf;
3400 while ((*pch >= 'a' && *pch <= 'z') ||
3401 (*pch >= 'A' && *pch <= 'Z') ||
3402 (*pch >= '0' && *pch <= '9') ||
3403 *pch == '_' || *pch == '.') {
3404 if ((q - buf) < sizeof(buf) - 1)
3405 *q++ = *pch;
3406 pch++;
3408 while (qemu_isspace(*pch))
3409 pch++;
3410 *q = 0;
3411 ret = get_monitor_def(&reg, buf);
3412 if (ret < 0)
3413 expr_error(mon, "unknown register");
3414 n = reg;
3416 break;
3417 case '\0':
3418 expr_error(mon, "unexpected end of expression");
3419 n = 0;
3420 break;
3421 default:
3422 errno = 0;
3423 n = strtoull(pch, &p, 0);
3424 if (errno == ERANGE) {
3425 expr_error(mon, "number too large");
3427 if (pch == p) {
3428 expr_error(mon, "invalid char '%c' in expression", *p);
3430 pch = p;
3431 while (qemu_isspace(*pch))
3432 pch++;
3433 break;
3435 return n;
3439 static int64_t expr_prod(Monitor *mon)
3441 int64_t val, val2;
3442 int op;
3444 val = expr_unary(mon);
3445 for(;;) {
3446 op = *pch;
3447 if (op != '*' && op != '/' && op != '%')
3448 break;
3449 next();
3450 val2 = expr_unary(mon);
3451 switch(op) {
3452 default:
3453 case '*':
3454 val *= val2;
3455 break;
3456 case '/':
3457 case '%':
3458 if (val2 == 0)
3459 expr_error(mon, "division by zero");
3460 if (op == '/')
3461 val /= val2;
3462 else
3463 val %= val2;
3464 break;
3467 return val;
3470 static int64_t expr_logic(Monitor *mon)
3472 int64_t val, val2;
3473 int op;
3475 val = expr_prod(mon);
3476 for(;;) {
3477 op = *pch;
3478 if (op != '&' && op != '|' && op != '^')
3479 break;
3480 next();
3481 val2 = expr_prod(mon);
3482 switch(op) {
3483 default:
3484 case '&':
3485 val &= val2;
3486 break;
3487 case '|':
3488 val |= val2;
3489 break;
3490 case '^':
3491 val ^= val2;
3492 break;
3495 return val;
3498 static int64_t expr_sum(Monitor *mon)
3500 int64_t val, val2;
3501 int op;
3503 val = expr_logic(mon);
3504 for(;;) {
3505 op = *pch;
3506 if (op != '+' && op != '-')
3507 break;
3508 next();
3509 val2 = expr_logic(mon);
3510 if (op == '+')
3511 val += val2;
3512 else
3513 val -= val2;
3515 return val;
3518 static int get_expr(Monitor *mon, int64_t *pval, const char **pp)
3520 pch = *pp;
3521 if (sigsetjmp(expr_env, 0)) {
3522 *pp = pch;
3523 return -1;
3525 while (qemu_isspace(*pch))
3526 pch++;
3527 *pval = expr_sum(mon);
3528 *pp = pch;
3529 return 0;
3532 static int get_double(Monitor *mon, double *pval, const char **pp)
3534 const char *p = *pp;
3535 char *tailp;
3536 double d;
3538 d = strtod(p, &tailp);
3539 if (tailp == p) {
3540 monitor_printf(mon, "Number expected\n");
3541 return -1;
3543 if (d != d || d - d != 0) {
3544 /* NaN or infinity */
3545 monitor_printf(mon, "Bad number\n");
3546 return -1;
3548 *pval = d;
3549 *pp = tailp;
3550 return 0;
3554 * Store the command-name in cmdname, and return a pointer to
3555 * the remaining of the command string.
3557 static const char *get_command_name(const char *cmdline,
3558 char *cmdname, size_t nlen)
3560 size_t len;
3561 const char *p, *pstart;
3563 p = cmdline;
3564 while (qemu_isspace(*p))
3565 p++;
3566 if (*p == '\0')
3567 return NULL;
3568 pstart = p;
3569 while (*p != '\0' && *p != '/' && !qemu_isspace(*p))
3570 p++;
3571 len = p - pstart;
3572 if (len > nlen - 1)
3573 len = nlen - 1;
3574 memcpy(cmdname, pstart, len);
3575 cmdname[len] = '\0';
3576 return p;
3580 * Read key of 'type' into 'key' and return the current
3581 * 'type' pointer.
3583 static char *key_get_info(const char *type, char **key)
3585 size_t len;
3586 char *p, *str;
3588 if (*type == ',')
3589 type++;
3591 p = strchr(type, ':');
3592 if (!p) {
3593 *key = NULL;
3594 return NULL;
3596 len = p - type;
3598 str = g_malloc(len + 1);
3599 memcpy(str, type, len);
3600 str[len] = '\0';
3602 *key = str;
3603 return ++p;
3606 static int default_fmt_format = 'x';
3607 static int default_fmt_size = 4;
3609 static int is_valid_option(const char *c, const char *typestr)
3611 char option[3];
3613 option[0] = '-';
3614 option[1] = *c;
3615 option[2] = '\0';
3617 typestr = strstr(typestr, option);
3618 return (typestr != NULL);
3621 static const mon_cmd_t *search_dispatch_table(const mon_cmd_t *disp_table,
3622 const char *cmdname)
3624 const mon_cmd_t *cmd;
3626 for (cmd = disp_table; cmd->name != NULL; cmd++) {
3627 if (compare_cmd(cmdname, cmd->name)) {
3628 return cmd;
3632 return NULL;
3635 static const mon_cmd_t *qmp_find_cmd(const char *cmdname)
3637 return search_dispatch_table(qmp_cmds, cmdname);
3641 * Parse @cmdline according to command table @table.
3642 * If @cmdline is blank, return NULL.
3643 * If it can't be parsed, report to @mon, and return NULL.
3644 * Else, insert command arguments into @qdict, and return the command.
3645 * If a sub-command table exists, and if @cmdline contains an additional string
3646 * for a sub-command, this function will try to search the sub-command table.
3647 * If no additional string for a sub-command is present, this function will
3648 * return the command found in @table.
3649 * Do not assume the returned command points into @table! It doesn't
3650 * when the command is a sub-command.
3652 static const mon_cmd_t *monitor_parse_command(Monitor *mon,
3653 const char *cmdline,
3654 int start,
3655 mon_cmd_t *table,
3656 QDict *qdict)
3658 const char *p, *typestr;
3659 int c;
3660 const mon_cmd_t *cmd;
3661 char cmdname[256];
3662 char buf[1024];
3663 char *key;
3665 #ifdef DEBUG
3666 monitor_printf(mon, "command='%s', start='%d'\n", cmdline, start);
3667 #endif
3669 /* extract the command name */
3670 p = get_command_name(cmdline + start, cmdname, sizeof(cmdname));
3671 if (!p)
3672 return NULL;
3674 cmd = search_dispatch_table(table, cmdname);
3675 if (!cmd) {
3676 monitor_printf(mon, "unknown command: '%.*s'\n",
3677 (int)(p - cmdline), cmdline);
3678 return NULL;
3681 /* filter out following useless space */
3682 while (qemu_isspace(*p)) {
3683 p++;
3685 /* search sub command */
3686 if (cmd->sub_table != NULL) {
3687 /* check if user set additional command */
3688 if (*p == '\0') {
3689 return cmd;
3691 return monitor_parse_command(mon, cmdline, p - cmdline,
3692 cmd->sub_table, qdict);
3695 /* parse the parameters */
3696 typestr = cmd->args_type;
3697 for(;;) {
3698 typestr = key_get_info(typestr, &key);
3699 if (!typestr)
3700 break;
3701 c = *typestr;
3702 typestr++;
3703 switch(c) {
3704 case 'F':
3705 case 'B':
3706 case 's':
3708 int ret;
3710 while (qemu_isspace(*p))
3711 p++;
3712 if (*typestr == '?') {
3713 typestr++;
3714 if (*p == '\0') {
3715 /* no optional string: NULL argument */
3716 break;
3719 ret = get_str(buf, sizeof(buf), &p);
3720 if (ret < 0) {
3721 switch(c) {
3722 case 'F':
3723 monitor_printf(mon, "%s: filename expected\n",
3724 cmdname);
3725 break;
3726 case 'B':
3727 monitor_printf(mon, "%s: block device name expected\n",
3728 cmdname);
3729 break;
3730 default:
3731 monitor_printf(mon, "%s: string expected\n", cmdname);
3732 break;
3734 goto fail;
3736 qdict_put(qdict, key, qstring_from_str(buf));
3738 break;
3739 case 'O':
3741 QemuOptsList *opts_list;
3742 QemuOpts *opts;
3744 opts_list = qemu_find_opts(key);
3745 if (!opts_list || opts_list->desc->name) {
3746 goto bad_type;
3748 while (qemu_isspace(*p)) {
3749 p++;
3751 if (!*p)
3752 break;
3753 if (get_str(buf, sizeof(buf), &p) < 0) {
3754 goto fail;
3756 opts = qemu_opts_parse(opts_list, buf, 1);
3757 if (!opts) {
3758 goto fail;
3760 qemu_opts_to_qdict(opts, qdict);
3761 qemu_opts_del(opts);
3763 break;
3764 case '/':
3766 int count, format, size;
3768 while (qemu_isspace(*p))
3769 p++;
3770 if (*p == '/') {
3771 /* format found */
3772 p++;
3773 count = 1;
3774 if (qemu_isdigit(*p)) {
3775 count = 0;
3776 while (qemu_isdigit(*p)) {
3777 count = count * 10 + (*p - '0');
3778 p++;
3781 size = -1;
3782 format = -1;
3783 for(;;) {
3784 switch(*p) {
3785 case 'o':
3786 case 'd':
3787 case 'u':
3788 case 'x':
3789 case 'i':
3790 case 'c':
3791 format = *p++;
3792 break;
3793 case 'b':
3794 size = 1;
3795 p++;
3796 break;
3797 case 'h':
3798 size = 2;
3799 p++;
3800 break;
3801 case 'w':
3802 size = 4;
3803 p++;
3804 break;
3805 case 'g':
3806 case 'L':
3807 size = 8;
3808 p++;
3809 break;
3810 default:
3811 goto next;
3814 next:
3815 if (*p != '\0' && !qemu_isspace(*p)) {
3816 monitor_printf(mon, "invalid char in format: '%c'\n",
3817 *p);
3818 goto fail;
3820 if (format < 0)
3821 format = default_fmt_format;
3822 if (format != 'i') {
3823 /* for 'i', not specifying a size gives -1 as size */
3824 if (size < 0)
3825 size = default_fmt_size;
3826 default_fmt_size = size;
3828 default_fmt_format = format;
3829 } else {
3830 count = 1;
3831 format = default_fmt_format;
3832 if (format != 'i') {
3833 size = default_fmt_size;
3834 } else {
3835 size = -1;
3838 qdict_put(qdict, "count", qint_from_int(count));
3839 qdict_put(qdict, "format", qint_from_int(format));
3840 qdict_put(qdict, "size", qint_from_int(size));
3842 break;
3843 case 'i':
3844 case 'l':
3845 case 'M':
3847 int64_t val;
3849 while (qemu_isspace(*p))
3850 p++;
3851 if (*typestr == '?' || *typestr == '.') {
3852 if (*typestr == '?') {
3853 if (*p == '\0') {
3854 typestr++;
3855 break;
3857 } else {
3858 if (*p == '.') {
3859 p++;
3860 while (qemu_isspace(*p))
3861 p++;
3862 } else {
3863 typestr++;
3864 break;
3867 typestr++;
3869 if (get_expr(mon, &val, &p))
3870 goto fail;
3871 /* Check if 'i' is greater than 32-bit */
3872 if ((c == 'i') && ((val >> 32) & 0xffffffff)) {
3873 monitor_printf(mon, "\'%s\' has failed: ", cmdname);
3874 monitor_printf(mon, "integer is for 32-bit values\n");
3875 goto fail;
3876 } else if (c == 'M') {
3877 if (val < 0) {
3878 monitor_printf(mon, "enter a positive value\n");
3879 goto fail;
3881 val <<= 20;
3883 qdict_put(qdict, key, qint_from_int(val));
3885 break;
3886 case 'o':
3888 int64_t val;
3889 char *end;
3891 while (qemu_isspace(*p)) {
3892 p++;
3894 if (*typestr == '?') {
3895 typestr++;
3896 if (*p == '\0') {
3897 break;
3900 val = strtosz(p, &end);
3901 if (val < 0) {
3902 monitor_printf(mon, "invalid size\n");
3903 goto fail;
3905 qdict_put(qdict, key, qint_from_int(val));
3906 p = end;
3908 break;
3909 case 'T':
3911 double val;
3913 while (qemu_isspace(*p))
3914 p++;
3915 if (*typestr == '?') {
3916 typestr++;
3917 if (*p == '\0') {
3918 break;
3921 if (get_double(mon, &val, &p) < 0) {
3922 goto fail;
3924 if (p[0] && p[1] == 's') {
3925 switch (*p) {
3926 case 'm':
3927 val /= 1e3; p += 2; break;
3928 case 'u':
3929 val /= 1e6; p += 2; break;
3930 case 'n':
3931 val /= 1e9; p += 2; break;
3934 if (*p && !qemu_isspace(*p)) {
3935 monitor_printf(mon, "Unknown unit suffix\n");
3936 goto fail;
3938 qdict_put(qdict, key, qfloat_from_double(val));
3940 break;
3941 case 'b':
3943 const char *beg;
3944 int val;
3946 while (qemu_isspace(*p)) {
3947 p++;
3949 beg = p;
3950 while (qemu_isgraph(*p)) {
3951 p++;
3953 if (p - beg == 2 && !memcmp(beg, "on", p - beg)) {
3954 val = 1;
3955 } else if (p - beg == 3 && !memcmp(beg, "off", p - beg)) {
3956 val = 0;
3957 } else {
3958 monitor_printf(mon, "Expected 'on' or 'off'\n");
3959 goto fail;
3961 qdict_put(qdict, key, qbool_from_int(val));
3963 break;
3964 case '-':
3966 const char *tmp = p;
3967 int skip_key = 0;
3968 /* option */
3970 c = *typestr++;
3971 if (c == '\0')
3972 goto bad_type;
3973 while (qemu_isspace(*p))
3974 p++;
3975 if (*p == '-') {
3976 p++;
3977 if(c != *p) {
3978 if(!is_valid_option(p, typestr)) {
3980 monitor_printf(mon, "%s: unsupported option -%c\n",
3981 cmdname, *p);
3982 goto fail;
3983 } else {
3984 skip_key = 1;
3987 if(skip_key) {
3988 p = tmp;
3989 } else {
3990 /* has option */
3991 p++;
3992 qdict_put(qdict, key, qbool_from_int(1));
3996 break;
3997 case 'S':
3999 /* package all remaining string */
4000 int len;
4002 while (qemu_isspace(*p)) {
4003 p++;
4005 if (*typestr == '?') {
4006 typestr++;
4007 if (*p == '\0') {
4008 /* no remaining string: NULL argument */
4009 break;
4012 len = strlen(p);
4013 if (len <= 0) {
4014 monitor_printf(mon, "%s: string expected\n",
4015 cmdname);
4016 break;
4018 qdict_put(qdict, key, qstring_from_str(p));
4019 p += len;
4021 break;
4022 default:
4023 bad_type:
4024 monitor_printf(mon, "%s: unknown type '%c'\n", cmdname, c);
4025 goto fail;
4027 g_free(key);
4028 key = NULL;
4030 /* check that all arguments were parsed */
4031 while (qemu_isspace(*p))
4032 p++;
4033 if (*p != '\0') {
4034 monitor_printf(mon, "%s: extraneous characters at the end of line\n",
4035 cmdname);
4036 goto fail;
4039 return cmd;
4041 fail:
4042 g_free(key);
4043 return NULL;
4046 void monitor_set_error(Monitor *mon, QError *qerror)
4048 /* report only the first error */
4049 if (!mon->error) {
4050 mon->error = qerror;
4051 } else {
4052 QDECREF(qerror);
4056 static void handle_hmp_command(Monitor *mon, const char *cmdline)
4058 QDict *qdict;
4059 const mon_cmd_t *cmd;
4061 qdict = qdict_new();
4063 cmd = monitor_parse_command(mon, cmdline, 0, mon->cmd_table, qdict);
4064 if (cmd) {
4065 cmd->mhandler.cmd(mon, qdict);
4068 QDECREF(qdict);
4071 static void cmd_completion(Monitor *mon, const char *name, const char *list)
4073 const char *p, *pstart;
4074 char cmd[128];
4075 int len;
4077 p = list;
4078 for(;;) {
4079 pstart = p;
4080 p = strchr(p, '|');
4081 if (!p)
4082 p = pstart + strlen(pstart);
4083 len = p - pstart;
4084 if (len > sizeof(cmd) - 2)
4085 len = sizeof(cmd) - 2;
4086 memcpy(cmd, pstart, len);
4087 cmd[len] = '\0';
4088 if (name[0] == '\0' || !strncmp(name, cmd, strlen(name))) {
4089 readline_add_completion(mon->rs, cmd);
4091 if (*p == '\0')
4092 break;
4093 p++;
4097 static void file_completion(Monitor *mon, const char *input)
4099 DIR *ffs;
4100 struct dirent *d;
4101 char path[1024];
4102 char file[1024], file_prefix[1024];
4103 int input_path_len;
4104 const char *p;
4106 p = strrchr(input, '/');
4107 if (!p) {
4108 input_path_len = 0;
4109 pstrcpy(file_prefix, sizeof(file_prefix), input);
4110 pstrcpy(path, sizeof(path), ".");
4111 } else {
4112 input_path_len = p - input + 1;
4113 memcpy(path, input, input_path_len);
4114 if (input_path_len > sizeof(path) - 1)
4115 input_path_len = sizeof(path) - 1;
4116 path[input_path_len] = '\0';
4117 pstrcpy(file_prefix, sizeof(file_prefix), p + 1);
4119 #ifdef DEBUG_COMPLETION
4120 monitor_printf(mon, "input='%s' path='%s' prefix='%s'\n",
4121 input, path, file_prefix);
4122 #endif
4123 ffs = opendir(path);
4124 if (!ffs)
4125 return;
4126 for(;;) {
4127 struct stat sb;
4128 d = readdir(ffs);
4129 if (!d)
4130 break;
4132 if (strcmp(d->d_name, ".") == 0 || strcmp(d->d_name, "..") == 0) {
4133 continue;
4136 if (strstart(d->d_name, file_prefix, NULL)) {
4137 memcpy(file, input, input_path_len);
4138 if (input_path_len < sizeof(file))
4139 pstrcpy(file + input_path_len, sizeof(file) - input_path_len,
4140 d->d_name);
4141 /* stat the file to find out if it's a directory.
4142 * In that case add a slash to speed up typing long paths
4144 if (stat(file, &sb) == 0 && S_ISDIR(sb.st_mode)) {
4145 pstrcat(file, sizeof(file), "/");
4147 readline_add_completion(mon->rs, file);
4150 closedir(ffs);
4153 static const char *next_arg_type(const char *typestr)
4155 const char *p = strchr(typestr, ':');
4156 return (p != NULL ? ++p : typestr);
4159 static void add_completion_option(ReadLineState *rs, const char *str,
4160 const char *option)
4162 if (!str || !option) {
4163 return;
4165 if (!strncmp(option, str, strlen(str))) {
4166 readline_add_completion(rs, option);
4170 void chardev_add_completion(ReadLineState *rs, int nb_args, const char *str)
4172 size_t len;
4173 ChardevBackendInfoList *list, *start;
4175 if (nb_args != 2) {
4176 return;
4178 len = strlen(str);
4179 readline_set_completion_index(rs, len);
4181 start = list = qmp_query_chardev_backends(NULL);
4182 while (list) {
4183 const char *chr_name = list->value->name;
4185 if (!strncmp(chr_name, str, len)) {
4186 readline_add_completion(rs, chr_name);
4188 list = list->next;
4190 qapi_free_ChardevBackendInfoList(start);
4193 void netdev_add_completion(ReadLineState *rs, int nb_args, const char *str)
4195 size_t len;
4196 int i;
4198 if (nb_args != 2) {
4199 return;
4201 len = strlen(str);
4202 readline_set_completion_index(rs, len);
4203 for (i = 0; NetClientOptionsKind_lookup[i]; i++) {
4204 add_completion_option(rs, str, NetClientOptionsKind_lookup[i]);
4208 void device_add_completion(ReadLineState *rs, int nb_args, const char *str)
4210 GSList *list, *elt;
4211 size_t len;
4213 if (nb_args != 2) {
4214 return;
4217 len = strlen(str);
4218 readline_set_completion_index(rs, len);
4219 list = elt = object_class_get_list(TYPE_DEVICE, false);
4220 while (elt) {
4221 const char *name;
4222 DeviceClass *dc = OBJECT_CLASS_CHECK(DeviceClass, elt->data,
4223 TYPE_DEVICE);
4224 name = object_class_get_name(OBJECT_CLASS(dc));
4226 if (!dc->cannot_instantiate_with_device_add_yet
4227 && !strncmp(name, str, len)) {
4228 readline_add_completion(rs, name);
4230 elt = elt->next;
4232 g_slist_free(list);
4235 void object_add_completion(ReadLineState *rs, int nb_args, const char *str)
4237 GSList *list, *elt;
4238 size_t len;
4240 if (nb_args != 2) {
4241 return;
4244 len = strlen(str);
4245 readline_set_completion_index(rs, len);
4246 list = elt = object_class_get_list(TYPE_USER_CREATABLE, false);
4247 while (elt) {
4248 const char *name;
4250 name = object_class_get_name(OBJECT_CLASS(elt->data));
4251 if (!strncmp(name, str, len) && strcmp(name, TYPE_USER_CREATABLE)) {
4252 readline_add_completion(rs, name);
4254 elt = elt->next;
4256 g_slist_free(list);
4259 static void peripheral_device_del_completion(ReadLineState *rs,
4260 const char *str, size_t len)
4262 Object *peripheral = container_get(qdev_get_machine(), "/peripheral");
4263 GSList *list, *item;
4265 list = qdev_build_hotpluggable_device_list(peripheral);
4266 if (!list) {
4267 return;
4270 for (item = list; item; item = g_slist_next(item)) {
4271 DeviceState *dev = item->data;
4273 if (dev->id && !strncmp(str, dev->id, len)) {
4274 readline_add_completion(rs, dev->id);
4278 g_slist_free(list);
4281 void chardev_remove_completion(ReadLineState *rs, int nb_args, const char *str)
4283 size_t len;
4284 ChardevInfoList *list, *start;
4286 if (nb_args != 2) {
4287 return;
4289 len = strlen(str);
4290 readline_set_completion_index(rs, len);
4292 start = list = qmp_query_chardev(NULL);
4293 while (list) {
4294 ChardevInfo *chr = list->value;
4296 if (!strncmp(chr->label, str, len)) {
4297 readline_add_completion(rs, chr->label);
4299 list = list->next;
4301 qapi_free_ChardevInfoList(start);
4304 static void ringbuf_completion(ReadLineState *rs, const char *str)
4306 size_t len;
4307 ChardevInfoList *list, *start;
4309 len = strlen(str);
4310 readline_set_completion_index(rs, len);
4312 start = list = qmp_query_chardev(NULL);
4313 while (list) {
4314 ChardevInfo *chr_info = list->value;
4316 if (!strncmp(chr_info->label, str, len)) {
4317 CharDriverState *chr = qemu_chr_find(chr_info->label);
4318 if (chr && chr_is_ringbuf(chr)) {
4319 readline_add_completion(rs, chr_info->label);
4322 list = list->next;
4324 qapi_free_ChardevInfoList(start);
4327 void ringbuf_write_completion(ReadLineState *rs, int nb_args, const char *str)
4329 if (nb_args != 2) {
4330 return;
4332 ringbuf_completion(rs, str);
4335 void device_del_completion(ReadLineState *rs, int nb_args, const char *str)
4337 size_t len;
4339 if (nb_args != 2) {
4340 return;
4343 len = strlen(str);
4344 readline_set_completion_index(rs, len);
4345 peripheral_device_del_completion(rs, str, len);
4348 void object_del_completion(ReadLineState *rs, int nb_args, const char *str)
4350 ObjectPropertyInfoList *list, *start;
4351 size_t len;
4353 if (nb_args != 2) {
4354 return;
4356 len = strlen(str);
4357 readline_set_completion_index(rs, len);
4359 start = list = qmp_qom_list("/objects", NULL);
4360 while (list) {
4361 ObjectPropertyInfo *info = list->value;
4363 if (!strncmp(info->type, "child<", 5)
4364 && !strncmp(info->name, str, len)) {
4365 readline_add_completion(rs, info->name);
4367 list = list->next;
4369 qapi_free_ObjectPropertyInfoList(start);
4372 void sendkey_completion(ReadLineState *rs, int nb_args, const char *str)
4374 int i;
4375 char *sep;
4376 size_t len;
4378 if (nb_args != 2) {
4379 return;
4381 sep = strrchr(str, '-');
4382 if (sep) {
4383 str = sep + 1;
4385 len = strlen(str);
4386 readline_set_completion_index(rs, len);
4387 for (i = 0; i < Q_KEY_CODE_MAX; i++) {
4388 if (!strncmp(str, QKeyCode_lookup[i], len)) {
4389 readline_add_completion(rs, QKeyCode_lookup[i]);
4394 void set_link_completion(ReadLineState *rs, int nb_args, const char *str)
4396 size_t len;
4398 len = strlen(str);
4399 readline_set_completion_index(rs, len);
4400 if (nb_args == 2) {
4401 NetClientState *ncs[MAX_QUEUE_NUM];
4402 int count, i;
4403 count = qemu_find_net_clients_except(NULL, ncs,
4404 NET_CLIENT_OPTIONS_KIND_NONE,
4405 MAX_QUEUE_NUM);
4406 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
4407 const char *name = ncs[i]->name;
4408 if (!strncmp(str, name, len)) {
4409 readline_add_completion(rs, name);
4412 } else if (nb_args == 3) {
4413 add_completion_option(rs, str, "on");
4414 add_completion_option(rs, str, "off");
4418 void netdev_del_completion(ReadLineState *rs, int nb_args, const char *str)
4420 int len, count, i;
4421 NetClientState *ncs[MAX_QUEUE_NUM];
4423 if (nb_args != 2) {
4424 return;
4427 len = strlen(str);
4428 readline_set_completion_index(rs, len);
4429 count = qemu_find_net_clients_except(NULL, ncs, NET_CLIENT_OPTIONS_KIND_NIC,
4430 MAX_QUEUE_NUM);
4431 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
4432 QemuOpts *opts;
4433 const char *name = ncs[i]->name;
4434 if (strncmp(str, name, len)) {
4435 continue;
4437 opts = qemu_opts_find(qemu_find_opts_err("netdev", NULL), name);
4438 if (opts) {
4439 readline_add_completion(rs, name);
4444 void watchdog_action_completion(ReadLineState *rs, int nb_args, const char *str)
4446 int i;
4448 if (nb_args != 2) {
4449 return;
4451 readline_set_completion_index(rs, strlen(str));
4452 for (i = 0; WatchdogExpirationAction_lookup[i]; i++) {
4453 add_completion_option(rs, str, WatchdogExpirationAction_lookup[i]);
4457 void migrate_set_capability_completion(ReadLineState *rs, int nb_args,
4458 const char *str)
4460 size_t len;
4462 len = strlen(str);
4463 readline_set_completion_index(rs, len);
4464 if (nb_args == 2) {
4465 int i;
4466 for (i = 0; i < MIGRATION_CAPABILITY_MAX; i++) {
4467 const char *name = MigrationCapability_lookup[i];
4468 if (!strncmp(str, name, len)) {
4469 readline_add_completion(rs, name);
4472 } else if (nb_args == 3) {
4473 add_completion_option(rs, str, "on");
4474 add_completion_option(rs, str, "off");
4478 void migrate_set_parameter_completion(ReadLineState *rs, int nb_args,
4479 const char *str)
4481 size_t len;
4483 len = strlen(str);
4484 readline_set_completion_index(rs, len);
4485 if (nb_args == 2) {
4486 int i;
4487 for (i = 0; i < MIGRATION_PARAMETER_MAX; i++) {
4488 const char *name = MigrationParameter_lookup[i];
4489 if (!strncmp(str, name, len)) {
4490 readline_add_completion(rs, name);
4496 void host_net_add_completion(ReadLineState *rs, int nb_args, const char *str)
4498 int i;
4499 size_t len;
4500 if (nb_args != 2) {
4501 return;
4503 len = strlen(str);
4504 readline_set_completion_index(rs, len);
4505 for (i = 0; host_net_devices[i]; i++) {
4506 if (!strncmp(host_net_devices[i], str, len)) {
4507 readline_add_completion(rs, host_net_devices[i]);
4512 void host_net_remove_completion(ReadLineState *rs, int nb_args, const char *str)
4514 NetClientState *ncs[MAX_QUEUE_NUM];
4515 int count, i, len;
4517 len = strlen(str);
4518 readline_set_completion_index(rs, len);
4519 if (nb_args == 2) {
4520 count = qemu_find_net_clients_except(NULL, ncs,
4521 NET_CLIENT_OPTIONS_KIND_NONE,
4522 MAX_QUEUE_NUM);
4523 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
4524 int id;
4525 char name[16];
4527 if (net_hub_id_for_client(ncs[i], &id)) {
4528 continue;
4530 snprintf(name, sizeof(name), "%d", id);
4531 if (!strncmp(str, name, len)) {
4532 readline_add_completion(rs, name);
4535 return;
4536 } else if (nb_args == 3) {
4537 count = qemu_find_net_clients_except(NULL, ncs,
4538 NET_CLIENT_OPTIONS_KIND_NIC,
4539 MAX_QUEUE_NUM);
4540 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
4541 int id;
4542 const char *name;
4544 if (ncs[i]->info->type == NET_CLIENT_OPTIONS_KIND_HUBPORT ||
4545 net_hub_id_for_client(ncs[i], &id)) {
4546 continue;
4548 name = ncs[i]->name;
4549 if (!strncmp(str, name, len)) {
4550 readline_add_completion(rs, name);
4553 return;
4557 static void vm_completion(ReadLineState *rs, const char *str)
4559 size_t len;
4560 BlockDriverState *bs = NULL;
4562 len = strlen(str);
4563 readline_set_completion_index(rs, len);
4564 while ((bs = bdrv_next(bs))) {
4565 SnapshotInfoList *snapshots, *snapshot;
4567 if (!bdrv_can_snapshot(bs)) {
4568 continue;
4570 if (bdrv_query_snapshot_info_list(bs, &snapshots, NULL)) {
4571 continue;
4573 snapshot = snapshots;
4574 while (snapshot) {
4575 char *completion = snapshot->value->name;
4576 if (!strncmp(str, completion, len)) {
4577 readline_add_completion(rs, completion);
4579 completion = snapshot->value->id;
4580 if (!strncmp(str, completion, len)) {
4581 readline_add_completion(rs, completion);
4583 snapshot = snapshot->next;
4585 qapi_free_SnapshotInfoList(snapshots);
4590 void delvm_completion(ReadLineState *rs, int nb_args, const char *str)
4592 if (nb_args == 2) {
4593 vm_completion(rs, str);
4597 void loadvm_completion(ReadLineState *rs, int nb_args, const char *str)
4599 if (nb_args == 2) {
4600 vm_completion(rs, str);
4604 static void monitor_find_completion_by_table(Monitor *mon,
4605 const mon_cmd_t *cmd_table,
4606 char **args,
4607 int nb_args)
4609 const char *cmdname;
4610 int i;
4611 const char *ptype, *str, *name;
4612 const mon_cmd_t *cmd;
4613 BlockDriverState *bs;
4615 if (nb_args <= 1) {
4616 /* command completion */
4617 if (nb_args == 0)
4618 cmdname = "";
4619 else
4620 cmdname = args[0];
4621 readline_set_completion_index(mon->rs, strlen(cmdname));
4622 for (cmd = cmd_table; cmd->name != NULL; cmd++) {
4623 cmd_completion(mon, cmdname, cmd->name);
4625 } else {
4626 /* find the command */
4627 for (cmd = cmd_table; cmd->name != NULL; cmd++) {
4628 if (compare_cmd(args[0], cmd->name)) {
4629 break;
4632 if (!cmd->name) {
4633 return;
4636 if (cmd->sub_table) {
4637 /* do the job again */
4638 monitor_find_completion_by_table(mon, cmd->sub_table,
4639 &args[1], nb_args - 1);
4640 return;
4642 if (cmd->command_completion) {
4643 cmd->command_completion(mon->rs, nb_args, args[nb_args - 1]);
4644 return;
4647 ptype = next_arg_type(cmd->args_type);
4648 for(i = 0; i < nb_args - 2; i++) {
4649 if (*ptype != '\0') {
4650 ptype = next_arg_type(ptype);
4651 while (*ptype == '?')
4652 ptype = next_arg_type(ptype);
4655 str = args[nb_args - 1];
4656 while (*ptype == '-' && ptype[1] != '\0') {
4657 ptype = next_arg_type(ptype);
4659 switch(*ptype) {
4660 case 'F':
4661 /* file completion */
4662 readline_set_completion_index(mon->rs, strlen(str));
4663 file_completion(mon, str);
4664 break;
4665 case 'B':
4666 /* block device name completion */
4667 readline_set_completion_index(mon->rs, strlen(str));
4668 for (bs = bdrv_next(NULL); bs; bs = bdrv_next(bs)) {
4669 name = bdrv_get_device_name(bs);
4670 if (str[0] == '\0' ||
4671 !strncmp(name, str, strlen(str))) {
4672 readline_add_completion(mon->rs, name);
4675 break;
4676 case 's':
4677 case 'S':
4678 if (!strcmp(cmd->name, "help|?")) {
4679 monitor_find_completion_by_table(mon, cmd_table,
4680 &args[1], nb_args - 1);
4682 break;
4683 default:
4684 break;
4689 static void monitor_find_completion(void *opaque,
4690 const char *cmdline)
4692 Monitor *mon = opaque;
4693 char *args[MAX_ARGS];
4694 int nb_args, len;
4696 /* 1. parse the cmdline */
4697 if (parse_cmdline(cmdline, &nb_args, args) < 0) {
4698 return;
4700 #ifdef DEBUG_COMPLETION
4702 int i;
4703 for (i = 0; i < nb_args; i++) {
4704 monitor_printf(mon, "arg%d = '%s'\n", i, args[i]);
4707 #endif
4709 /* if the line ends with a space, it means we want to complete the
4710 next arg */
4711 len = strlen(cmdline);
4712 if (len > 0 && qemu_isspace(cmdline[len - 1])) {
4713 if (nb_args >= MAX_ARGS) {
4714 goto cleanup;
4716 args[nb_args++] = g_strdup("");
4719 /* 2. auto complete according to args */
4720 monitor_find_completion_by_table(mon, mon->cmd_table, args, nb_args);
4722 cleanup:
4723 free_cmdline_args(args, nb_args);
4726 static int monitor_can_read(void *opaque)
4728 Monitor *mon = opaque;
4730 return (mon->suspend_cnt == 0) ? 1 : 0;
4733 static bool invalid_qmp_mode(const Monitor *mon, const mon_cmd_t *cmd,
4734 Error **errp)
4736 bool is_cap = cmd->mhandler.cmd_new == do_qmp_capabilities;
4738 if (is_cap && mon->qmp.in_command_mode) {
4739 error_set(errp, ERROR_CLASS_COMMAND_NOT_FOUND,
4740 "Capabilities negotiation is already complete, command "
4741 "'%s' ignored", cmd->name);
4742 return true;
4744 if (!is_cap && !mon->qmp.in_command_mode) {
4745 error_set(errp, ERROR_CLASS_COMMAND_NOT_FOUND,
4746 "Expecting capabilities negotiation with "
4747 "'qmp_capabilities' before command '%s'", cmd->name);
4748 return true;
4750 return false;
4754 * Argument validation rules:
4756 * 1. The argument must exist in cmd_args qdict
4757 * 2. The argument type must be the expected one
4759 * Special case: If the argument doesn't exist in cmd_args and
4760 * the QMP_ACCEPT_UNKNOWNS flag is set, then the
4761 * checking is skipped for it.
4763 static void check_client_args_type(const QDict *client_args,
4764 const QDict *cmd_args, int flags,
4765 Error **errp)
4767 const QDictEntry *ent;
4769 for (ent = qdict_first(client_args); ent;ent = qdict_next(client_args,ent)){
4770 QObject *obj;
4771 QString *arg_type;
4772 const QObject *client_arg = qdict_entry_value(ent);
4773 const char *client_arg_name = qdict_entry_key(ent);
4775 obj = qdict_get(cmd_args, client_arg_name);
4776 if (!obj) {
4777 if (flags & QMP_ACCEPT_UNKNOWNS) {
4778 /* handler accepts unknowns */
4779 continue;
4781 /* client arg doesn't exist */
4782 error_set(errp, QERR_INVALID_PARAMETER, client_arg_name);
4783 return;
4786 arg_type = qobject_to_qstring(obj);
4787 assert(arg_type != NULL);
4789 /* check if argument's type is correct */
4790 switch (qstring_get_str(arg_type)[0]) {
4791 case 'F':
4792 case 'B':
4793 case 's':
4794 if (qobject_type(client_arg) != QTYPE_QSTRING) {
4795 error_set(errp, QERR_INVALID_PARAMETER_TYPE,
4796 client_arg_name, "string");
4797 return;
4799 break;
4800 case 'i':
4801 case 'l':
4802 case 'M':
4803 case 'o':
4804 if (qobject_type(client_arg) != QTYPE_QINT) {
4805 error_set(errp, QERR_INVALID_PARAMETER_TYPE,
4806 client_arg_name, "int");
4807 return;
4809 break;
4810 case 'T':
4811 if (qobject_type(client_arg) != QTYPE_QINT &&
4812 qobject_type(client_arg) != QTYPE_QFLOAT) {
4813 error_set(errp, QERR_INVALID_PARAMETER_TYPE,
4814 client_arg_name, "number");
4815 return;
4817 break;
4818 case 'b':
4819 case '-':
4820 if (qobject_type(client_arg) != QTYPE_QBOOL) {
4821 error_set(errp, QERR_INVALID_PARAMETER_TYPE,
4822 client_arg_name, "bool");
4823 return;
4825 break;
4826 case 'O':
4827 assert(flags & QMP_ACCEPT_UNKNOWNS);
4828 break;
4829 case 'q':
4830 /* Any QObject can be passed. */
4831 break;
4832 case '/':
4833 case '.':
4835 * These types are not supported by QMP and thus are not
4836 * handled here. Fall through.
4838 default:
4839 abort();
4845 * - Check if the client has passed all mandatory args
4846 * - Set special flags for argument validation
4848 static void check_mandatory_args(const QDict *cmd_args,
4849 const QDict *client_args, int *flags,
4850 Error **errp)
4852 const QDictEntry *ent;
4854 for (ent = qdict_first(cmd_args); ent; ent = qdict_next(cmd_args, ent)) {
4855 const char *cmd_arg_name = qdict_entry_key(ent);
4856 QString *type = qobject_to_qstring(qdict_entry_value(ent));
4857 assert(type != NULL);
4859 if (qstring_get_str(type)[0] == 'O') {
4860 assert((*flags & QMP_ACCEPT_UNKNOWNS) == 0);
4861 *flags |= QMP_ACCEPT_UNKNOWNS;
4862 } else if (qstring_get_str(type)[0] != '-' &&
4863 qstring_get_str(type)[1] != '?' &&
4864 !qdict_haskey(client_args, cmd_arg_name)) {
4865 error_set(errp, QERR_MISSING_PARAMETER, cmd_arg_name);
4866 return;
4871 static QDict *qdict_from_args_type(const char *args_type)
4873 int i;
4874 QDict *qdict;
4875 QString *key, *type, *cur_qs;
4877 assert(args_type != NULL);
4879 qdict = qdict_new();
4881 if (args_type == NULL || args_type[0] == '\0') {
4882 /* no args, empty qdict */
4883 goto out;
4886 key = qstring_new();
4887 type = qstring_new();
4889 cur_qs = key;
4891 for (i = 0;; i++) {
4892 switch (args_type[i]) {
4893 case ',':
4894 case '\0':
4895 qdict_put(qdict, qstring_get_str(key), type);
4896 QDECREF(key);
4897 if (args_type[i] == '\0') {
4898 goto out;
4900 type = qstring_new(); /* qdict has ref */
4901 cur_qs = key = qstring_new();
4902 break;
4903 case ':':
4904 cur_qs = type;
4905 break;
4906 default:
4907 qstring_append_chr(cur_qs, args_type[i]);
4908 break;
4912 out:
4913 return qdict;
4917 * Client argument checking rules:
4919 * 1. Client must provide all mandatory arguments
4920 * 2. Each argument provided by the client must be expected
4921 * 3. Each argument provided by the client must have the type expected
4922 * by the command
4924 static void qmp_check_client_args(const mon_cmd_t *cmd, QDict *client_args,
4925 Error **errp)
4927 Error *err = NULL;
4928 int flags;
4929 QDict *cmd_args;
4931 cmd_args = qdict_from_args_type(cmd->args_type);
4933 flags = 0;
4934 check_mandatory_args(cmd_args, client_args, &flags, &err);
4935 if (err) {
4936 goto out;
4939 check_client_args_type(client_args, cmd_args, flags, &err);
4941 out:
4942 error_propagate(errp, err);
4943 QDECREF(cmd_args);
4947 * Input object checking rules
4949 * 1. Input object must be a dict
4950 * 2. The "execute" key must exist
4951 * 3. The "execute" key must be a string
4952 * 4. If the "arguments" key exists, it must be a dict
4953 * 5. If the "id" key exists, it can be anything (ie. json-value)
4954 * 6. Any argument not listed above is considered invalid
4956 static QDict *qmp_check_input_obj(QObject *input_obj, Error **errp)
4958 const QDictEntry *ent;
4959 int has_exec_key = 0;
4960 QDict *input_dict;
4962 if (qobject_type(input_obj) != QTYPE_QDICT) {
4963 error_set(errp, QERR_QMP_BAD_INPUT_OBJECT, "object");
4964 return NULL;
4967 input_dict = qobject_to_qdict(input_obj);
4969 for (ent = qdict_first(input_dict); ent; ent = qdict_next(input_dict, ent)){
4970 const char *arg_name = qdict_entry_key(ent);
4971 const QObject *arg_obj = qdict_entry_value(ent);
4973 if (!strcmp(arg_name, "execute")) {
4974 if (qobject_type(arg_obj) != QTYPE_QSTRING) {
4975 error_set(errp, QERR_QMP_BAD_INPUT_OBJECT_MEMBER,
4976 "execute", "string");
4977 return NULL;
4979 has_exec_key = 1;
4980 } else if (!strcmp(arg_name, "arguments")) {
4981 if (qobject_type(arg_obj) != QTYPE_QDICT) {
4982 error_set(errp, QERR_QMP_BAD_INPUT_OBJECT_MEMBER,
4983 "arguments", "object");
4984 return NULL;
4986 } else if (!strcmp(arg_name, "id")) {
4987 /* Any string is acceptable as "id", so nothing to check */
4988 } else {
4989 error_set(errp, QERR_QMP_EXTRA_MEMBER, arg_name);
4990 return NULL;
4994 if (!has_exec_key) {
4995 error_set(errp, QERR_QMP_BAD_INPUT_OBJECT, "execute");
4996 return NULL;
4999 return input_dict;
5002 static void handle_qmp_command(JSONMessageParser *parser, QList *tokens)
5004 Error *local_err = NULL;
5005 QObject *obj, *data;
5006 QDict *input, *args;
5007 const mon_cmd_t *cmd;
5008 const char *cmd_name;
5009 Monitor *mon = cur_mon;
5011 args = input = NULL;
5012 data = NULL;
5014 obj = json_parser_parse(tokens, NULL);
5015 if (!obj) {
5016 // FIXME: should be triggered in json_parser_parse()
5017 error_set(&local_err, QERR_JSON_PARSING);
5018 goto err_out;
5021 input = qmp_check_input_obj(obj, &local_err);
5022 if (!input) {
5023 qobject_decref(obj);
5024 goto err_out;
5027 mon->qmp.id = qdict_get(input, "id");
5028 qobject_incref(mon->qmp.id);
5030 cmd_name = qdict_get_str(input, "execute");
5031 trace_handle_qmp_command(mon, cmd_name);
5032 cmd = qmp_find_cmd(cmd_name);
5033 if (!cmd) {
5034 error_set(&local_err, ERROR_CLASS_COMMAND_NOT_FOUND,
5035 "The command %s has not been found", cmd_name);
5036 goto err_out;
5038 if (invalid_qmp_mode(mon, cmd, &local_err)) {
5039 goto err_out;
5042 obj = qdict_get(input, "arguments");
5043 if (!obj) {
5044 args = qdict_new();
5045 } else {
5046 args = qobject_to_qdict(obj);
5047 QINCREF(args);
5050 qmp_check_client_args(cmd, args, &local_err);
5051 if (local_err) {
5052 goto err_out;
5055 if (cmd->mhandler.cmd_new(mon, args, &data)) {
5056 /* Command failed... */
5057 if (!mon->error) {
5058 /* ... without setting an error, so make one up */
5059 error_set(&local_err, QERR_UNDEFINED_ERROR);
5062 if (mon->error) {
5063 error_set(&local_err, mon->error->err_class, "%s",
5064 mon->error->err_msg);
5067 err_out:
5068 monitor_protocol_emitter(mon, data, local_err);
5069 qobject_decref(data);
5070 QDECREF(mon->error);
5071 mon->error = NULL;
5072 QDECREF(input);
5073 QDECREF(args);
5076 static void monitor_qmp_read(void *opaque, const uint8_t *buf, int size)
5078 Monitor *old_mon = cur_mon;
5080 cur_mon = opaque;
5082 json_message_parser_feed(&cur_mon->qmp.parser, (const char *) buf, size);
5084 cur_mon = old_mon;
5087 static void monitor_read(void *opaque, const uint8_t *buf, int size)
5089 Monitor *old_mon = cur_mon;
5090 int i;
5092 cur_mon = opaque;
5094 if (cur_mon->rs) {
5095 for (i = 0; i < size; i++)
5096 readline_handle_byte(cur_mon->rs, buf[i]);
5097 } else {
5098 if (size == 0 || buf[size - 1] != 0)
5099 monitor_printf(cur_mon, "corrupted command\n");
5100 else
5101 handle_hmp_command(cur_mon, (char *)buf);
5104 cur_mon = old_mon;
5107 static void monitor_command_cb(void *opaque, const char *cmdline,
5108 void *readline_opaque)
5110 Monitor *mon = opaque;
5112 monitor_suspend(mon);
5113 handle_hmp_command(mon, cmdline);
5114 monitor_resume(mon);
5117 int monitor_suspend(Monitor *mon)
5119 if (!mon->rs)
5120 return -ENOTTY;
5121 mon->suspend_cnt++;
5122 return 0;
5125 void monitor_resume(Monitor *mon)
5127 if (!mon->rs)
5128 return;
5129 if (--mon->suspend_cnt == 0)
5130 readline_show_prompt(mon->rs);
5133 static QObject *get_qmp_greeting(void)
5135 QObject *ver = NULL;
5137 qmp_marshal_input_query_version(NULL, NULL, &ver);
5138 return qobject_from_jsonf("{'QMP':{'version': %p,'capabilities': []}}",ver);
5141 static void monitor_qmp_event(void *opaque, int event)
5143 QObject *data;
5144 Monitor *mon = opaque;
5146 switch (event) {
5147 case CHR_EVENT_OPENED:
5148 mon->qmp.in_command_mode = false;
5149 data = get_qmp_greeting();
5150 monitor_json_emitter(mon, data);
5151 qobject_decref(data);
5152 mon_refcount++;
5153 break;
5154 case CHR_EVENT_CLOSED:
5155 json_message_parser_destroy(&mon->qmp.parser);
5156 json_message_parser_init(&mon->qmp.parser, handle_qmp_command);
5157 mon_refcount--;
5158 monitor_fdsets_cleanup();
5159 break;
5163 static void monitor_event(void *opaque, int event)
5165 Monitor *mon = opaque;
5167 switch (event) {
5168 case CHR_EVENT_MUX_IN:
5169 qemu_mutex_lock(&mon->out_lock);
5170 mon->mux_out = 0;
5171 qemu_mutex_unlock(&mon->out_lock);
5172 if (mon->reset_seen) {
5173 readline_restart(mon->rs);
5174 monitor_resume(mon);
5175 monitor_flush(mon);
5176 } else {
5177 mon->suspend_cnt = 0;
5179 break;
5181 case CHR_EVENT_MUX_OUT:
5182 if (mon->reset_seen) {
5183 if (mon->suspend_cnt == 0) {
5184 monitor_printf(mon, "\n");
5186 monitor_flush(mon);
5187 monitor_suspend(mon);
5188 } else {
5189 mon->suspend_cnt++;
5191 qemu_mutex_lock(&mon->out_lock);
5192 mon->mux_out = 1;
5193 qemu_mutex_unlock(&mon->out_lock);
5194 break;
5196 case CHR_EVENT_OPENED:
5197 monitor_printf(mon, "QEMU %s monitor - type 'help' for more "
5198 "information\n", QEMU_VERSION);
5199 if (!mon->mux_out) {
5200 readline_restart(mon->rs);
5201 readline_show_prompt(mon->rs);
5203 mon->reset_seen = 1;
5204 mon_refcount++;
5205 break;
5207 case CHR_EVENT_CLOSED:
5208 mon_refcount--;
5209 monitor_fdsets_cleanup();
5210 break;
5214 static int
5215 compare_mon_cmd(const void *a, const void *b)
5217 return strcmp(((const mon_cmd_t *)a)->name,
5218 ((const mon_cmd_t *)b)->name);
5221 static void sortcmdlist(void)
5223 int array_num;
5224 int elem_size = sizeof(mon_cmd_t);
5226 array_num = sizeof(mon_cmds)/elem_size-1;
5227 qsort((void *)mon_cmds, array_num, elem_size, compare_mon_cmd);
5229 array_num = sizeof(info_cmds)/elem_size-1;
5230 qsort((void *)info_cmds, array_num, elem_size, compare_mon_cmd);
5235 * Local variables:
5236 * c-indent-level: 4
5237 * c-basic-offset: 4
5238 * tab-width: 8
5239 * End:
5242 /* These functions just adapt the readline interface in a typesafe way. We
5243 * could cast function pointers but that discards compiler checks.
5245 static void GCC_FMT_ATTR(2, 3) monitor_readline_printf(void *opaque,
5246 const char *fmt, ...)
5248 va_list ap;
5249 va_start(ap, fmt);
5250 monitor_vprintf(opaque, fmt, ap);
5251 va_end(ap);
5254 static void monitor_readline_flush(void *opaque)
5256 monitor_flush(opaque);
5259 static void __attribute__((constructor)) monitor_lock_init(void)
5261 qemu_mutex_init(&monitor_lock);
5264 void monitor_init(CharDriverState *chr, int flags)
5266 static int is_first_init = 1;
5267 Monitor *mon;
5269 if (is_first_init) {
5270 monitor_qapi_event_init();
5271 sortcmdlist();
5272 is_first_init = 0;
5275 mon = g_malloc(sizeof(*mon));
5276 monitor_data_init(mon);
5278 mon->chr = chr;
5279 mon->flags = flags;
5280 if (flags & MONITOR_USE_READLINE) {
5281 mon->rs = readline_init(monitor_readline_printf,
5282 monitor_readline_flush,
5283 mon,
5284 monitor_find_completion);
5285 monitor_read_command(mon, 0);
5288 if (monitor_is_qmp(mon)) {
5289 qemu_chr_add_handlers(chr, monitor_can_read, monitor_qmp_read,
5290 monitor_qmp_event, mon);
5291 qemu_chr_fe_set_echo(chr, true);
5292 json_message_parser_init(&mon->qmp.parser, handle_qmp_command);
5293 } else {
5294 qemu_chr_add_handlers(chr, monitor_can_read, monitor_read,
5295 monitor_event, mon);
5298 qemu_mutex_lock(&monitor_lock);
5299 QLIST_INSERT_HEAD(&mon_list, mon, entry);
5300 qemu_mutex_unlock(&monitor_lock);
5302 if (!default_mon || (flags & MONITOR_IS_DEFAULT))
5303 default_mon = mon;
5306 static void bdrv_password_cb(void *opaque, const char *password,
5307 void *readline_opaque)
5309 Monitor *mon = opaque;
5310 BlockDriverState *bs = readline_opaque;
5311 int ret = 0;
5312 Error *local_err = NULL;
5314 bdrv_add_key(bs, password, &local_err);
5315 if (local_err) {
5316 monitor_printf(mon, "%s\n", error_get_pretty(local_err));
5317 error_free(local_err);
5318 ret = -EPERM;
5320 if (mon->password_completion_cb)
5321 mon->password_completion_cb(mon->password_opaque, ret);
5323 monitor_read_command(mon, 1);
5326 int monitor_read_bdrv_key_start(Monitor *mon, BlockDriverState *bs,
5327 BlockCompletionFunc *completion_cb,
5328 void *opaque)
5330 int err;
5332 monitor_printf(mon, "%s (%s) is encrypted.\n", bdrv_get_device_name(bs),
5333 bdrv_get_encrypted_filename(bs));
5335 mon->password_completion_cb = completion_cb;
5336 mon->password_opaque = opaque;
5338 err = monitor_read_password(mon, bdrv_password_cb, bs);
5340 if (err && completion_cb)
5341 completion_cb(opaque, err);
5343 return err;
5346 int monitor_read_block_device_key(Monitor *mon, const char *device,
5347 BlockCompletionFunc *completion_cb,
5348 void *opaque)
5350 Error *err = NULL;
5351 BlockBackend *blk;
5353 blk = blk_by_name(device);
5354 if (!blk) {
5355 monitor_printf(mon, "Device not found %s\n", device);
5356 return -1;
5359 bdrv_add_key(blk_bs(blk), NULL, &err);
5360 if (err) {
5361 error_free(err);
5362 return monitor_read_bdrv_key_start(mon, blk_bs(blk), completion_cb, opaque);
5365 if (completion_cb) {
5366 completion_cb(opaque, 0);
5368 return 0;
5371 QemuOptsList qemu_mon_opts = {
5372 .name = "mon",
5373 .implied_opt_name = "chardev",
5374 .head = QTAILQ_HEAD_INITIALIZER(qemu_mon_opts.head),
5375 .desc = {
5377 .name = "mode",
5378 .type = QEMU_OPT_STRING,
5380 .name = "chardev",
5381 .type = QEMU_OPT_STRING,
5383 .name = "default",
5384 .type = QEMU_OPT_BOOL,
5386 .name = "pretty",
5387 .type = QEMU_OPT_BOOL,
5389 { /* end of list */ }
5393 #ifndef TARGET_I386
5394 void qmp_rtc_reset_reinjection(Error **errp)
5396 error_set(errp, QERR_FEATURE_DISABLED, "rtc-reset-reinjection");
5398 #endif