cpu: Move can_do_io field from CPU_COMMON to CPUState
[qemu/ar7.git] / monitor.c
blob342e83baea8bedf89ee19e832e7d47f3aebaebc3
1 /*
2 * QEMU monitor
4 * Copyright (c) 2003-2004 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
24 #include <dirent.h>
25 #include "hw/hw.h"
26 #include "monitor/qdev.h"
27 #include "hw/usb.h"
28 #include "hw/pcmcia.h"
29 #include "hw/i386/pc.h"
30 #include "hw/pci/pci.h"
31 #include "sysemu/watchdog.h"
32 #include "hw/loader.h"
33 #include "exec/gdbstub.h"
34 #include "net/net.h"
35 #include "net/slirp.h"
36 #include "sysemu/char.h"
37 #include "ui/qemu-spice.h"
38 #include "sysemu/sysemu.h"
39 #include "monitor/monitor.h"
40 #include "qemu/readline.h"
41 #include "ui/console.h"
42 #include "ui/input.h"
43 #include "sysemu/blockdev.h"
44 #include "audio/audio.h"
45 #include "disas/disas.h"
46 #include "sysemu/balloon.h"
47 #include "qemu/timer.h"
48 #include "migration/migration.h"
49 #include "sysemu/kvm.h"
50 #include "qemu/acl.h"
51 #include "sysemu/tpm.h"
52 #include "qapi/qmp/qint.h"
53 #include "qapi/qmp/qfloat.h"
54 #include "qapi/qmp/qlist.h"
55 #include "qapi/qmp/qbool.h"
56 #include "qapi/qmp/qstring.h"
57 #include "qapi/qmp/qjson.h"
58 #include "qapi/qmp/json-streamer.h"
59 #include "qapi/qmp/json-parser.h"
60 #include <qom/object_interfaces.h>
61 #include "qemu/osdep.h"
62 #include "cpu.h"
63 #include "trace.h"
64 #include "trace/control.h"
65 #ifdef CONFIG_TRACE_SIMPLE
66 #include "trace/simple.h"
67 #endif
68 #include "exec/memory.h"
69 #include "qmp-commands.h"
70 #include "hmp.h"
71 #include "qemu/thread.h"
73 /* for pic/irq_info */
74 #if defined(TARGET_SPARC)
75 #include "hw/sparc/sun4m.h"
76 #endif
77 #include "hw/lm32/lm32_pic.h"
79 //#define DEBUG
80 //#define DEBUG_COMPLETION
83 * Supported types:
85 * 'F' filename
86 * 'B' block device name
87 * 's' string (accept optional quote)
88 * 'S' it just appends the rest of the string (accept optional quote)
89 * 'O' option string of the form NAME=VALUE,...
90 * parsed according to QemuOptsList given by its name
91 * Example: 'device:O' uses qemu_device_opts.
92 * Restriction: only lists with empty desc are supported
93 * TODO lift the restriction
94 * 'i' 32 bit integer
95 * 'l' target long (32 or 64 bit)
96 * 'M' Non-negative target long (32 or 64 bit), in user mode the
97 * value is multiplied by 2^20 (think Mebibyte)
98 * 'o' octets (aka bytes)
99 * user mode accepts an optional E, e, P, p, T, t, G, g, M, m,
100 * K, k suffix, which multiplies the value by 2^60 for suffixes E
101 * and e, 2^50 for suffixes P and p, 2^40 for suffixes T and t,
102 * 2^30 for suffixes G and g, 2^20 for M and m, 2^10 for K and k
103 * 'T' double
104 * user mode accepts an optional ms, us, ns suffix,
105 * which divides the value by 1e3, 1e6, 1e9, respectively
106 * '/' optional gdb-like print format (like "/10x")
108 * '?' optional type (for all types, except '/')
109 * '.' other form of optional type (for 'i' and 'l')
110 * 'b' boolean
111 * user mode accepts "on" or "off"
112 * '-' optional parameter (eg. '-f')
116 typedef struct MonitorCompletionData MonitorCompletionData;
117 struct MonitorCompletionData {
118 Monitor *mon;
119 void (*user_print)(Monitor *mon, const QObject *data);
122 typedef struct mon_cmd_t {
123 const char *name;
124 const char *args_type;
125 const char *params;
126 const char *help;
127 void (*user_print)(Monitor *mon, const QObject *data);
128 union {
129 void (*cmd)(Monitor *mon, const QDict *qdict);
130 int (*cmd_new)(Monitor *mon, const QDict *params, QObject **ret_data);
131 int (*cmd_async)(Monitor *mon, const QDict *params,
132 MonitorCompletion *cb, void *opaque);
133 } mhandler;
134 int flags;
135 /* @sub_table is a list of 2nd level of commands. If it do not exist,
136 * mhandler should be used. If it exist, sub_table[?].mhandler should be
137 * used, and mhandler of 1st level plays the role of help function.
139 struct mon_cmd_t *sub_table;
140 } mon_cmd_t;
142 /* file descriptors passed via SCM_RIGHTS */
143 typedef struct mon_fd_t mon_fd_t;
144 struct mon_fd_t {
145 char *name;
146 int fd;
147 QLIST_ENTRY(mon_fd_t) next;
150 /* file descriptor associated with a file descriptor set */
151 typedef struct MonFdsetFd MonFdsetFd;
152 struct MonFdsetFd {
153 int fd;
154 bool removed;
155 char *opaque;
156 QLIST_ENTRY(MonFdsetFd) next;
159 /* file descriptor set containing fds passed via SCM_RIGHTS */
160 typedef struct MonFdset MonFdset;
161 struct MonFdset {
162 int64_t id;
163 QLIST_HEAD(, MonFdsetFd) fds;
164 QLIST_HEAD(, MonFdsetFd) dup_fds;
165 QLIST_ENTRY(MonFdset) next;
168 typedef struct MonitorControl {
169 QObject *id;
170 JSONMessageParser parser;
171 int command_mode;
172 } MonitorControl;
175 * To prevent flooding clients, events can be throttled. The
176 * throttling is calculated globally, rather than per-Monitor
177 * instance.
179 typedef struct MonitorEventState {
180 MonitorEvent event; /* Event being tracked */
181 int64_t rate; /* Period over which to throttle. 0 to disable */
182 int64_t last; /* Time at which event was last emitted */
183 QEMUTimer *timer; /* Timer for handling delayed events */
184 QObject *data; /* Event pending delayed dispatch */
185 } MonitorEventState;
187 struct Monitor {
188 CharDriverState *chr;
189 int mux_out;
190 int reset_seen;
191 int flags;
192 int suspend_cnt;
193 bool skip_flush;
194 QString *outbuf;
195 guint watch;
196 ReadLineState *rs;
197 MonitorControl *mc;
198 CPUState *mon_cpu;
199 BlockDriverCompletionFunc *password_completion_cb;
200 void *password_opaque;
201 mon_cmd_t *cmd_table;
202 QError *error;
203 QLIST_HEAD(,mon_fd_t) fds;
204 QLIST_ENTRY(Monitor) entry;
207 /* QMP checker flags */
208 #define QMP_ACCEPT_UNKNOWNS 1
210 static QLIST_HEAD(mon_list, Monitor) mon_list;
211 static QLIST_HEAD(mon_fdsets, MonFdset) mon_fdsets;
212 static int mon_refcount;
214 static mon_cmd_t mon_cmds[];
215 static mon_cmd_t info_cmds[];
217 static const mon_cmd_t qmp_cmds[];
219 Monitor *cur_mon;
220 Monitor *default_mon;
222 static void monitor_command_cb(void *opaque, const char *cmdline,
223 void *readline_opaque);
225 static inline int qmp_cmd_mode(const Monitor *mon)
227 return (mon->mc ? mon->mc->command_mode : 0);
230 /* Return true if in control mode, false otherwise */
231 static inline int monitor_ctrl_mode(const Monitor *mon)
233 return (mon->flags & MONITOR_USE_CONTROL);
236 /* Return non-zero iff we have a current monitor, and it is in QMP mode. */
237 int monitor_cur_is_qmp(void)
239 return cur_mon && monitor_ctrl_mode(cur_mon);
242 void monitor_read_command(Monitor *mon, int show_prompt)
244 if (!mon->rs)
245 return;
247 readline_start(mon->rs, "(qemu) ", 0, monitor_command_cb, NULL);
248 if (show_prompt)
249 readline_show_prompt(mon->rs);
252 int monitor_read_password(Monitor *mon, ReadLineFunc *readline_func,
253 void *opaque)
255 if (monitor_ctrl_mode(mon)) {
256 qerror_report(QERR_MISSING_PARAMETER, "password");
257 return -EINVAL;
258 } else if (mon->rs) {
259 readline_start(mon->rs, "Password: ", 1, readline_func, opaque);
260 /* prompt is printed on return from the command handler */
261 return 0;
262 } else {
263 monitor_printf(mon, "terminal does not support password prompting\n");
264 return -ENOTTY;
268 static gboolean monitor_unblocked(GIOChannel *chan, GIOCondition cond,
269 void *opaque)
271 Monitor *mon = opaque;
273 mon->watch = 0;
274 monitor_flush(mon);
275 return FALSE;
278 void monitor_flush(Monitor *mon)
280 int rc;
281 size_t len;
282 const char *buf;
284 if (mon->skip_flush) {
285 return;
288 buf = qstring_get_str(mon->outbuf);
289 len = qstring_get_length(mon->outbuf);
291 if (len && !mon->mux_out) {
292 rc = qemu_chr_fe_write(mon->chr, (const uint8_t *) buf, len);
293 if ((rc < 0 && errno != EAGAIN) || (rc == len)) {
294 /* all flushed or error */
295 QDECREF(mon->outbuf);
296 mon->outbuf = qstring_new();
297 return;
299 if (rc > 0) {
300 /* partinal write */
301 QString *tmp = qstring_from_str(buf + rc);
302 QDECREF(mon->outbuf);
303 mon->outbuf = tmp;
305 if (mon->watch == 0) {
306 mon->watch = qemu_chr_fe_add_watch(mon->chr, G_IO_OUT,
307 monitor_unblocked, mon);
312 /* flush at every end of line */
313 static void monitor_puts(Monitor *mon, const char *str)
315 char c;
317 for(;;) {
318 c = *str++;
319 if (c == '\0')
320 break;
321 if (c == '\n') {
322 qstring_append_chr(mon->outbuf, '\r');
324 qstring_append_chr(mon->outbuf, c);
325 if (c == '\n') {
326 monitor_flush(mon);
331 void monitor_vprintf(Monitor *mon, const char *fmt, va_list ap)
333 char *buf;
335 if (!mon)
336 return;
338 if (monitor_ctrl_mode(mon)) {
339 return;
342 buf = g_strdup_vprintf(fmt, ap);
343 monitor_puts(mon, buf);
344 g_free(buf);
347 void monitor_printf(Monitor *mon, const char *fmt, ...)
349 va_list ap;
350 va_start(ap, fmt);
351 monitor_vprintf(mon, fmt, ap);
352 va_end(ap);
355 void monitor_print_filename(Monitor *mon, const char *filename)
357 int i;
359 for (i = 0; filename[i]; i++) {
360 switch (filename[i]) {
361 case ' ':
362 case '"':
363 case '\\':
364 monitor_printf(mon, "\\%c", filename[i]);
365 break;
366 case '\t':
367 monitor_printf(mon, "\\t");
368 break;
369 case '\r':
370 monitor_printf(mon, "\\r");
371 break;
372 case '\n':
373 monitor_printf(mon, "\\n");
374 break;
375 default:
376 monitor_printf(mon, "%c", filename[i]);
377 break;
382 static int GCC_FMT_ATTR(2, 3) monitor_fprintf(FILE *stream,
383 const char *fmt, ...)
385 va_list ap;
386 va_start(ap, fmt);
387 monitor_vprintf((Monitor *)stream, fmt, ap);
388 va_end(ap);
389 return 0;
392 static void monitor_user_noop(Monitor *mon, const QObject *data) { }
394 static inline int handler_is_qobject(const mon_cmd_t *cmd)
396 return cmd->user_print != NULL;
399 static inline bool handler_is_async(const mon_cmd_t *cmd)
401 return cmd->flags & MONITOR_CMD_ASYNC;
404 static inline int monitor_has_error(const Monitor *mon)
406 return mon->error != NULL;
409 static void monitor_json_emitter(Monitor *mon, const QObject *data)
411 QString *json;
413 json = mon->flags & MONITOR_USE_PRETTY ? qobject_to_json_pretty(data) :
414 qobject_to_json(data);
415 assert(json != NULL);
417 qstring_append_chr(json, '\n');
418 monitor_puts(mon, qstring_get_str(json));
420 QDECREF(json);
423 static QDict *build_qmp_error_dict(const QError *err)
425 QObject *obj;
427 obj = qobject_from_jsonf("{ 'error': { 'class': %s, 'desc': %p } }",
428 ErrorClass_lookup[err->err_class],
429 qerror_human(err));
431 return qobject_to_qdict(obj);
434 static void monitor_protocol_emitter(Monitor *mon, QObject *data)
436 QDict *qmp;
438 trace_monitor_protocol_emitter(mon);
440 if (!monitor_has_error(mon)) {
441 /* success response */
442 qmp = qdict_new();
443 if (data) {
444 qobject_incref(data);
445 qdict_put_obj(qmp, "return", data);
446 } else {
447 /* return an empty QDict by default */
448 qdict_put(qmp, "return", qdict_new());
450 } else {
451 /* error response */
452 qmp = build_qmp_error_dict(mon->error);
453 QDECREF(mon->error);
454 mon->error = NULL;
457 if (mon->mc->id) {
458 qdict_put_obj(qmp, "id", mon->mc->id);
459 mon->mc->id = NULL;
462 monitor_json_emitter(mon, QOBJECT(qmp));
463 QDECREF(qmp);
466 static void timestamp_put(QDict *qdict)
468 int err;
469 QObject *obj;
470 qemu_timeval tv;
472 err = qemu_gettimeofday(&tv);
473 if (err < 0)
474 return;
476 obj = qobject_from_jsonf("{ 'seconds': %" PRId64 ", "
477 "'microseconds': %" PRId64 " }",
478 (int64_t) tv.tv_sec, (int64_t) tv.tv_usec);
479 qdict_put_obj(qdict, "timestamp", obj);
483 static const char *monitor_event_names[] = {
484 [QEVENT_SHUTDOWN] = "SHUTDOWN",
485 [QEVENT_RESET] = "RESET",
486 [QEVENT_POWERDOWN] = "POWERDOWN",
487 [QEVENT_STOP] = "STOP",
488 [QEVENT_RESUME] = "RESUME",
489 [QEVENT_VNC_CONNECTED] = "VNC_CONNECTED",
490 [QEVENT_VNC_INITIALIZED] = "VNC_INITIALIZED",
491 [QEVENT_VNC_DISCONNECTED] = "VNC_DISCONNECTED",
492 [QEVENT_BLOCK_IO_ERROR] = "BLOCK_IO_ERROR",
493 [QEVENT_RTC_CHANGE] = "RTC_CHANGE",
494 [QEVENT_WATCHDOG] = "WATCHDOG",
495 [QEVENT_SPICE_CONNECTED] = "SPICE_CONNECTED",
496 [QEVENT_SPICE_INITIALIZED] = "SPICE_INITIALIZED",
497 [QEVENT_SPICE_DISCONNECTED] = "SPICE_DISCONNECTED",
498 [QEVENT_BLOCK_JOB_COMPLETED] = "BLOCK_JOB_COMPLETED",
499 [QEVENT_BLOCK_JOB_CANCELLED] = "BLOCK_JOB_CANCELLED",
500 [QEVENT_BLOCK_JOB_ERROR] = "BLOCK_JOB_ERROR",
501 [QEVENT_BLOCK_JOB_READY] = "BLOCK_JOB_READY",
502 [QEVENT_DEVICE_DELETED] = "DEVICE_DELETED",
503 [QEVENT_DEVICE_TRAY_MOVED] = "DEVICE_TRAY_MOVED",
504 [QEVENT_NIC_RX_FILTER_CHANGED] = "NIC_RX_FILTER_CHANGED",
505 [QEVENT_SUSPEND] = "SUSPEND",
506 [QEVENT_SUSPEND_DISK] = "SUSPEND_DISK",
507 [QEVENT_WAKEUP] = "WAKEUP",
508 [QEVENT_BALLOON_CHANGE] = "BALLOON_CHANGE",
509 [QEVENT_SPICE_MIGRATE_COMPLETED] = "SPICE_MIGRATE_COMPLETED",
510 [QEVENT_GUEST_PANICKED] = "GUEST_PANICKED",
511 [QEVENT_BLOCK_IMAGE_CORRUPTED] = "BLOCK_IMAGE_CORRUPTED",
512 [QEVENT_QUORUM_FAILURE] = "QUORUM_FAILURE",
513 [QEVENT_QUORUM_REPORT_BAD] = "QUORUM_REPORT_BAD",
515 QEMU_BUILD_BUG_ON(ARRAY_SIZE(monitor_event_names) != QEVENT_MAX)
517 MonitorEventState monitor_event_state[QEVENT_MAX];
520 * Emits the event to every monitor instance
522 static void
523 monitor_protocol_event_emit(MonitorEvent event,
524 QObject *data)
526 Monitor *mon;
528 trace_monitor_protocol_event_emit(event, data);
529 QLIST_FOREACH(mon, &mon_list, entry) {
530 if (monitor_ctrl_mode(mon) && qmp_cmd_mode(mon)) {
531 monitor_json_emitter(mon, data);
538 * Queue a new event for emission to Monitor instances,
539 * applying any rate limiting if required.
541 static void
542 monitor_protocol_event_queue(MonitorEvent event,
543 QObject *data)
545 MonitorEventState *evstate;
546 int64_t now = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
547 assert(event < QEVENT_MAX);
549 evstate = &(monitor_event_state[event]);
550 trace_monitor_protocol_event_queue(event,
551 data,
552 evstate->rate,
553 evstate->last,
554 now);
556 /* Rate limit of 0 indicates no throttling */
557 if (!evstate->rate) {
558 monitor_protocol_event_emit(event, data);
559 evstate->last = now;
560 } else {
561 int64_t delta = now - evstate->last;
562 if (evstate->data ||
563 delta < evstate->rate) {
564 /* If there's an existing event pending, replace
565 * it with the new event, otherwise schedule a
566 * timer for delayed emission
568 if (evstate->data) {
569 qobject_decref(evstate->data);
570 } else {
571 int64_t then = evstate->last + evstate->rate;
572 timer_mod_ns(evstate->timer, then);
574 evstate->data = data;
575 qobject_incref(evstate->data);
576 } else {
577 monitor_protocol_event_emit(event, data);
578 evstate->last = now;
585 * The callback invoked by QemuTimer when a delayed
586 * event is ready to be emitted
588 static void monitor_protocol_event_handler(void *opaque)
590 MonitorEventState *evstate = opaque;
591 int64_t now = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
594 trace_monitor_protocol_event_handler(evstate->event,
595 evstate->data,
596 evstate->last,
597 now);
598 if (evstate->data) {
599 monitor_protocol_event_emit(evstate->event, evstate->data);
600 qobject_decref(evstate->data);
601 evstate->data = NULL;
603 evstate->last = now;
608 * @event: the event ID to be limited
609 * @rate: the rate limit in milliseconds
611 * Sets a rate limit on a particular event, so no
612 * more than 1 event will be emitted within @rate
613 * milliseconds
615 static void
616 monitor_protocol_event_throttle(MonitorEvent event,
617 int64_t rate)
619 MonitorEventState *evstate;
620 assert(event < QEVENT_MAX);
622 evstate = &(monitor_event_state[event]);
624 trace_monitor_protocol_event_throttle(event, rate);
625 evstate->event = event;
626 evstate->rate = rate * SCALE_MS;
627 evstate->timer = timer_new(QEMU_CLOCK_REALTIME,
628 SCALE_MS,
629 monitor_protocol_event_handler,
630 evstate);
631 evstate->last = 0;
632 evstate->data = NULL;
636 /* Global, one-time initializer to configure the rate limiting
637 * and initialize state */
638 static void monitor_protocol_event_init(void)
640 /* Limit RTC & BALLOON events to 1 per second */
641 monitor_protocol_event_throttle(QEVENT_RTC_CHANGE, 1000);
642 monitor_protocol_event_throttle(QEVENT_BALLOON_CHANGE, 1000);
643 monitor_protocol_event_throttle(QEVENT_WATCHDOG, 1000);
644 /* limit the rate of quorum events to avoid hammering the management */
645 monitor_protocol_event_throttle(QEVENT_QUORUM_REPORT_BAD, 1000);
646 monitor_protocol_event_throttle(QEVENT_QUORUM_FAILURE, 1000);
650 * monitor_protocol_event(): Generate a Monitor event
652 * Event-specific data can be emitted through the (optional) 'data' parameter.
654 void monitor_protocol_event(MonitorEvent event, QObject *data)
656 QDict *qmp;
657 const char *event_name;
659 assert(event < QEVENT_MAX);
661 event_name = monitor_event_names[event];
662 assert(event_name != NULL);
664 qmp = qdict_new();
665 timestamp_put(qmp);
666 qdict_put(qmp, "event", qstring_from_str(event_name));
667 if (data) {
668 qobject_incref(data);
669 qdict_put_obj(qmp, "data", data);
672 trace_monitor_protocol_event(event, event_name, qmp);
673 monitor_protocol_event_queue(event, QOBJECT(qmp));
674 QDECREF(qmp);
677 static int do_qmp_capabilities(Monitor *mon, const QDict *params,
678 QObject **ret_data)
680 /* Will setup QMP capabilities in the future */
681 if (monitor_ctrl_mode(mon)) {
682 mon->mc->command_mode = 1;
685 return 0;
688 static void handle_user_command(Monitor *mon, const char *cmdline);
690 static void monitor_data_init(Monitor *mon)
692 memset(mon, 0, sizeof(Monitor));
693 mon->outbuf = qstring_new();
694 /* Use *mon_cmds by default. */
695 mon->cmd_table = mon_cmds;
698 static void monitor_data_destroy(Monitor *mon)
700 QDECREF(mon->outbuf);
703 char *qmp_human_monitor_command(const char *command_line, bool has_cpu_index,
704 int64_t cpu_index, Error **errp)
706 char *output = NULL;
707 Monitor *old_mon, hmp;
709 monitor_data_init(&hmp);
710 hmp.skip_flush = true;
712 old_mon = cur_mon;
713 cur_mon = &hmp;
715 if (has_cpu_index) {
716 int ret = monitor_set_cpu(cpu_index);
717 if (ret < 0) {
718 cur_mon = old_mon;
719 error_set(errp, QERR_INVALID_PARAMETER_VALUE, "cpu-index",
720 "a CPU number");
721 goto out;
725 handle_user_command(&hmp, command_line);
726 cur_mon = old_mon;
728 if (qstring_get_length(hmp.outbuf) > 0) {
729 output = g_strdup(qstring_get_str(hmp.outbuf));
730 } else {
731 output = g_strdup("");
734 out:
735 monitor_data_destroy(&hmp);
736 return output;
739 static int compare_cmd(const char *name, const char *list)
741 const char *p, *pstart;
742 int len;
743 len = strlen(name);
744 p = list;
745 for(;;) {
746 pstart = p;
747 p = strchr(p, '|');
748 if (!p)
749 p = pstart + strlen(pstart);
750 if ((p - pstart) == len && !memcmp(pstart, name, len))
751 return 1;
752 if (*p == '\0')
753 break;
754 p++;
756 return 0;
759 static int get_str(char *buf, int buf_size, const char **pp)
761 const char *p;
762 char *q;
763 int c;
765 q = buf;
766 p = *pp;
767 while (qemu_isspace(*p)) {
768 p++;
770 if (*p == '\0') {
771 fail:
772 *q = '\0';
773 *pp = p;
774 return -1;
776 if (*p == '\"') {
777 p++;
778 while (*p != '\0' && *p != '\"') {
779 if (*p == '\\') {
780 p++;
781 c = *p++;
782 switch (c) {
783 case 'n':
784 c = '\n';
785 break;
786 case 'r':
787 c = '\r';
788 break;
789 case '\\':
790 case '\'':
791 case '\"':
792 break;
793 default:
794 qemu_printf("unsupported escape code: '\\%c'\n", c);
795 goto fail;
797 if ((q - buf) < buf_size - 1) {
798 *q++ = c;
800 } else {
801 if ((q - buf) < buf_size - 1) {
802 *q++ = *p;
804 p++;
807 if (*p != '\"') {
808 qemu_printf("unterminated string\n");
809 goto fail;
811 p++;
812 } else {
813 while (*p != '\0' && !qemu_isspace(*p)) {
814 if ((q - buf) < buf_size - 1) {
815 *q++ = *p;
817 p++;
820 *q = '\0';
821 *pp = p;
822 return 0;
825 #define MAX_ARGS 16
827 static void free_cmdline_args(char **args, int nb_args)
829 int i;
831 assert(nb_args <= MAX_ARGS);
833 for (i = 0; i < nb_args; i++) {
834 g_free(args[i]);
840 * Parse the command line to get valid args.
841 * @cmdline: command line to be parsed.
842 * @pnb_args: location to store the number of args, must NOT be NULL.
843 * @args: location to store the args, which should be freed by caller, must
844 * NOT be NULL.
846 * Returns 0 on success, negative on failure.
848 * NOTE: this parser is an approximate form of the real command parser. Number
849 * of args have a limit of MAX_ARGS. If cmdline contains more, it will
850 * return with failure.
852 static int parse_cmdline(const char *cmdline,
853 int *pnb_args, char **args)
855 const char *p;
856 int nb_args, ret;
857 char buf[1024];
859 p = cmdline;
860 nb_args = 0;
861 for (;;) {
862 while (qemu_isspace(*p)) {
863 p++;
865 if (*p == '\0') {
866 break;
868 if (nb_args >= MAX_ARGS) {
869 goto fail;
871 ret = get_str(buf, sizeof(buf), &p);
872 if (ret < 0) {
873 goto fail;
875 args[nb_args] = g_strdup(buf);
876 nb_args++;
878 *pnb_args = nb_args;
879 return 0;
881 fail:
882 free_cmdline_args(args, nb_args);
883 return -1;
886 static void help_cmd_dump_one(Monitor *mon,
887 const mon_cmd_t *cmd,
888 char **prefix_args,
889 int prefix_args_nb)
891 int i;
893 for (i = 0; i < prefix_args_nb; i++) {
894 monitor_printf(mon, "%s ", prefix_args[i]);
896 monitor_printf(mon, "%s %s -- %s\n", cmd->name, cmd->params, cmd->help);
899 /* @args[@arg_index] is the valid command need to find in @cmds */
900 static void help_cmd_dump(Monitor *mon, const mon_cmd_t *cmds,
901 char **args, int nb_args, int arg_index)
903 const mon_cmd_t *cmd;
905 /* No valid arg need to compare with, dump all in *cmds */
906 if (arg_index >= nb_args) {
907 for (cmd = cmds; cmd->name != NULL; cmd++) {
908 help_cmd_dump_one(mon, cmd, args, arg_index);
910 return;
913 /* Find one entry to dump */
914 for (cmd = cmds; cmd->name != NULL; cmd++) {
915 if (compare_cmd(args[arg_index], cmd->name)) {
916 if (cmd->sub_table) {
917 /* continue with next arg */
918 help_cmd_dump(mon, cmd->sub_table,
919 args, nb_args, arg_index + 1);
920 } else {
921 help_cmd_dump_one(mon, cmd, args, arg_index);
923 break;
928 static void help_cmd(Monitor *mon, const char *name)
930 char *args[MAX_ARGS];
931 int nb_args = 0;
933 /* 1. parse user input */
934 if (name) {
935 /* special case for log, directly dump and return */
936 if (!strcmp(name, "log")) {
937 const QEMULogItem *item;
938 monitor_printf(mon, "Log items (comma separated):\n");
939 monitor_printf(mon, "%-10s %s\n", "none", "remove all logs");
940 for (item = qemu_log_items; item->mask != 0; item++) {
941 monitor_printf(mon, "%-10s %s\n", item->name, item->help);
943 return;
946 if (parse_cmdline(name, &nb_args, args) < 0) {
947 return;
951 /* 2. dump the contents according to parsed args */
952 help_cmd_dump(mon, mon->cmd_table, args, nb_args, 0);
954 free_cmdline_args(args, nb_args);
957 static void do_help_cmd(Monitor *mon, const QDict *qdict)
959 help_cmd(mon, qdict_get_try_str(qdict, "name"));
962 static void do_trace_event_set_state(Monitor *mon, const QDict *qdict)
964 const char *tp_name = qdict_get_str(qdict, "name");
965 bool new_state = qdict_get_bool(qdict, "option");
967 bool found = false;
968 TraceEvent *ev = NULL;
969 while ((ev = trace_event_pattern(tp_name, ev)) != NULL) {
970 found = true;
971 if (!trace_event_get_state_static(ev)) {
972 monitor_printf(mon, "event \"%s\" is not traceable\n", tp_name);
973 } else {
974 trace_event_set_state_dynamic(ev, new_state);
977 if (!trace_event_is_pattern(tp_name) && !found) {
978 monitor_printf(mon, "unknown event name \"%s\"\n", tp_name);
982 #ifdef CONFIG_TRACE_SIMPLE
983 static void do_trace_file(Monitor *mon, const QDict *qdict)
985 const char *op = qdict_get_try_str(qdict, "op");
986 const char *arg = qdict_get_try_str(qdict, "arg");
988 if (!op) {
989 st_print_trace_file_status((FILE *)mon, &monitor_fprintf);
990 } else if (!strcmp(op, "on")) {
991 st_set_trace_file_enabled(true);
992 } else if (!strcmp(op, "off")) {
993 st_set_trace_file_enabled(false);
994 } else if (!strcmp(op, "flush")) {
995 st_flush_trace_buffer();
996 } else if (!strcmp(op, "set")) {
997 if (arg) {
998 st_set_trace_file(arg);
1000 } else {
1001 monitor_printf(mon, "unexpected argument \"%s\"\n", op);
1002 help_cmd(mon, "trace-file");
1005 #endif
1007 static void user_monitor_complete(void *opaque, QObject *ret_data)
1009 MonitorCompletionData *data = (MonitorCompletionData *)opaque;
1011 if (ret_data) {
1012 data->user_print(data->mon, ret_data);
1014 monitor_resume(data->mon);
1015 g_free(data);
1018 static void qmp_monitor_complete(void *opaque, QObject *ret_data)
1020 monitor_protocol_emitter(opaque, ret_data);
1023 static int qmp_async_cmd_handler(Monitor *mon, const mon_cmd_t *cmd,
1024 const QDict *params)
1026 return cmd->mhandler.cmd_async(mon, params, qmp_monitor_complete, mon);
1029 static void user_async_cmd_handler(Monitor *mon, const mon_cmd_t *cmd,
1030 const QDict *params)
1032 int ret;
1034 MonitorCompletionData *cb_data = g_malloc(sizeof(*cb_data));
1035 cb_data->mon = mon;
1036 cb_data->user_print = cmd->user_print;
1037 monitor_suspend(mon);
1038 ret = cmd->mhandler.cmd_async(mon, params,
1039 user_monitor_complete, cb_data);
1040 if (ret < 0) {
1041 monitor_resume(mon);
1042 g_free(cb_data);
1046 static void do_info_help(Monitor *mon, const QDict *qdict)
1048 help_cmd(mon, "info");
1051 CommandInfoList *qmp_query_commands(Error **errp)
1053 CommandInfoList *info, *cmd_list = NULL;
1054 const mon_cmd_t *cmd;
1056 for (cmd = qmp_cmds; cmd->name != NULL; cmd++) {
1057 info = g_malloc0(sizeof(*info));
1058 info->value = g_malloc0(sizeof(*info->value));
1059 info->value->name = g_strdup(cmd->name);
1061 info->next = cmd_list;
1062 cmd_list = info;
1065 return cmd_list;
1068 EventInfoList *qmp_query_events(Error **errp)
1070 EventInfoList *info, *ev_list = NULL;
1071 MonitorEvent e;
1073 for (e = 0 ; e < QEVENT_MAX ; e++) {
1074 const char *event_name = monitor_event_names[e];
1075 assert(event_name != NULL);
1076 info = g_malloc0(sizeof(*info));
1077 info->value = g_malloc0(sizeof(*info->value));
1078 info->value->name = g_strdup(event_name);
1080 info->next = ev_list;
1081 ev_list = info;
1084 return ev_list;
1087 /* set the current CPU defined by the user */
1088 int monitor_set_cpu(int cpu_index)
1090 CPUState *cpu;
1092 cpu = qemu_get_cpu(cpu_index);
1093 if (cpu == NULL) {
1094 return -1;
1096 cur_mon->mon_cpu = cpu;
1097 return 0;
1100 static CPUArchState *mon_get_cpu(void)
1102 if (!cur_mon->mon_cpu) {
1103 monitor_set_cpu(0);
1105 cpu_synchronize_state(cur_mon->mon_cpu);
1106 return cur_mon->mon_cpu->env_ptr;
1109 int monitor_get_cpu_index(void)
1111 CPUState *cpu = ENV_GET_CPU(mon_get_cpu());
1112 return cpu->cpu_index;
1115 static void do_info_registers(Monitor *mon, const QDict *qdict)
1117 CPUState *cpu;
1118 CPUArchState *env;
1119 env = mon_get_cpu();
1120 cpu = ENV_GET_CPU(env);
1121 cpu_dump_state(cpu, (FILE *)mon, monitor_fprintf, CPU_DUMP_FPU);
1124 static void do_info_jit(Monitor *mon, const QDict *qdict)
1126 dump_exec_info((FILE *)mon, monitor_fprintf);
1129 static void do_info_history(Monitor *mon, const QDict *qdict)
1131 int i;
1132 const char *str;
1134 if (!mon->rs)
1135 return;
1136 i = 0;
1137 for(;;) {
1138 str = readline_get_history(mon->rs, i);
1139 if (!str)
1140 break;
1141 monitor_printf(mon, "%d: '%s'\n", i, str);
1142 i++;
1146 static void do_info_cpu_stats(Monitor *mon, const QDict *qdict)
1148 CPUState *cpu;
1149 CPUArchState *env;
1151 env = mon_get_cpu();
1152 cpu = ENV_GET_CPU(env);
1153 cpu_dump_statistics(cpu, (FILE *)mon, &monitor_fprintf, 0);
1156 static void do_trace_print_events(Monitor *mon, const QDict *qdict)
1158 trace_print_events((FILE *)mon, &monitor_fprintf);
1161 static int client_migrate_info(Monitor *mon, const QDict *qdict,
1162 MonitorCompletion cb, void *opaque)
1164 const char *protocol = qdict_get_str(qdict, "protocol");
1165 const char *hostname = qdict_get_str(qdict, "hostname");
1166 const char *subject = qdict_get_try_str(qdict, "cert-subject");
1167 int port = qdict_get_try_int(qdict, "port", -1);
1168 int tls_port = qdict_get_try_int(qdict, "tls-port", -1);
1169 int ret;
1171 if (strcmp(protocol, "spice") == 0) {
1172 if (!using_spice) {
1173 qerror_report(QERR_DEVICE_NOT_ACTIVE, "spice");
1174 return -1;
1177 if (port == -1 && tls_port == -1) {
1178 qerror_report(QERR_MISSING_PARAMETER, "port/tls-port");
1179 return -1;
1182 ret = qemu_spice_migrate_info(hostname, port, tls_port, subject,
1183 cb, opaque);
1184 if (ret != 0) {
1185 qerror_report(QERR_UNDEFINED_ERROR);
1186 return -1;
1188 return 0;
1191 qerror_report(QERR_INVALID_PARAMETER, "protocol");
1192 return -1;
1195 static void do_logfile(Monitor *mon, const QDict *qdict)
1197 qemu_set_log_filename(qdict_get_str(qdict, "filename"));
1200 static void do_log(Monitor *mon, const QDict *qdict)
1202 int mask;
1203 const char *items = qdict_get_str(qdict, "items");
1205 if (!strcmp(items, "none")) {
1206 mask = 0;
1207 } else {
1208 mask = qemu_str_to_log_mask(items);
1209 if (!mask) {
1210 help_cmd(mon, "log");
1211 return;
1214 qemu_set_log(mask);
1217 static void do_singlestep(Monitor *mon, const QDict *qdict)
1219 const char *option = qdict_get_try_str(qdict, "option");
1220 if (!option || !strcmp(option, "on")) {
1221 singlestep = 1;
1222 } else if (!strcmp(option, "off")) {
1223 singlestep = 0;
1224 } else {
1225 monitor_printf(mon, "unexpected option %s\n", option);
1229 static void do_gdbserver(Monitor *mon, const QDict *qdict)
1231 const char *device = qdict_get_try_str(qdict, "device");
1232 if (!device)
1233 device = "tcp::" DEFAULT_GDBSTUB_PORT;
1234 if (gdbserver_start(device) < 0) {
1235 monitor_printf(mon, "Could not open gdbserver on device '%s'\n",
1236 device);
1237 } else if (strcmp(device, "none") == 0) {
1238 monitor_printf(mon, "Disabled gdbserver\n");
1239 } else {
1240 monitor_printf(mon, "Waiting for gdb connection on device '%s'\n",
1241 device);
1245 static void do_watchdog_action(Monitor *mon, const QDict *qdict)
1247 const char *action = qdict_get_str(qdict, "action");
1248 if (select_watchdog_action(action) == -1) {
1249 monitor_printf(mon, "Unknown watchdog action '%s'\n", action);
1253 static void monitor_printc(Monitor *mon, int c)
1255 monitor_printf(mon, "'");
1256 switch(c) {
1257 case '\'':
1258 monitor_printf(mon, "\\'");
1259 break;
1260 case '\\':
1261 monitor_printf(mon, "\\\\");
1262 break;
1263 case '\n':
1264 monitor_printf(mon, "\\n");
1265 break;
1266 case '\r':
1267 monitor_printf(mon, "\\r");
1268 break;
1269 default:
1270 if (c >= 32 && c <= 126) {
1271 monitor_printf(mon, "%c", c);
1272 } else {
1273 monitor_printf(mon, "\\x%02x", c);
1275 break;
1277 monitor_printf(mon, "'");
1280 static void memory_dump(Monitor *mon, int count, int format, int wsize,
1281 hwaddr addr, int is_physical)
1283 CPUArchState *env;
1284 int l, line_size, i, max_digits, len;
1285 uint8_t buf[16];
1286 uint64_t v;
1288 if (format == 'i') {
1289 int flags;
1290 flags = 0;
1291 env = mon_get_cpu();
1292 #ifdef TARGET_I386
1293 if (wsize == 2) {
1294 flags = 1;
1295 } else if (wsize == 4) {
1296 flags = 0;
1297 } else {
1298 /* as default we use the current CS size */
1299 flags = 0;
1300 if (env) {
1301 #ifdef TARGET_X86_64
1302 if ((env->efer & MSR_EFER_LMA) &&
1303 (env->segs[R_CS].flags & DESC_L_MASK))
1304 flags = 2;
1305 else
1306 #endif
1307 if (!(env->segs[R_CS].flags & DESC_B_MASK))
1308 flags = 1;
1311 #endif
1312 monitor_disas(mon, env, addr, count, is_physical, flags);
1313 return;
1316 len = wsize * count;
1317 if (wsize == 1)
1318 line_size = 8;
1319 else
1320 line_size = 16;
1321 max_digits = 0;
1323 switch(format) {
1324 case 'o':
1325 max_digits = (wsize * 8 + 2) / 3;
1326 break;
1327 default:
1328 case 'x':
1329 max_digits = (wsize * 8) / 4;
1330 break;
1331 case 'u':
1332 case 'd':
1333 max_digits = (wsize * 8 * 10 + 32) / 33;
1334 break;
1335 case 'c':
1336 wsize = 1;
1337 break;
1340 while (len > 0) {
1341 if (is_physical)
1342 monitor_printf(mon, TARGET_FMT_plx ":", addr);
1343 else
1344 monitor_printf(mon, TARGET_FMT_lx ":", (target_ulong)addr);
1345 l = len;
1346 if (l > line_size)
1347 l = line_size;
1348 if (is_physical) {
1349 cpu_physical_memory_read(addr, buf, l);
1350 } else {
1351 env = mon_get_cpu();
1352 if (cpu_memory_rw_debug(ENV_GET_CPU(env), addr, buf, l, 0) < 0) {
1353 monitor_printf(mon, " Cannot access memory\n");
1354 break;
1357 i = 0;
1358 while (i < l) {
1359 switch(wsize) {
1360 default:
1361 case 1:
1362 v = ldub_raw(buf + i);
1363 break;
1364 case 2:
1365 v = lduw_raw(buf + i);
1366 break;
1367 case 4:
1368 v = (uint32_t)ldl_raw(buf + i);
1369 break;
1370 case 8:
1371 v = ldq_raw(buf + i);
1372 break;
1374 monitor_printf(mon, " ");
1375 switch(format) {
1376 case 'o':
1377 monitor_printf(mon, "%#*" PRIo64, max_digits, v);
1378 break;
1379 case 'x':
1380 monitor_printf(mon, "0x%0*" PRIx64, max_digits, v);
1381 break;
1382 case 'u':
1383 monitor_printf(mon, "%*" PRIu64, max_digits, v);
1384 break;
1385 case 'd':
1386 monitor_printf(mon, "%*" PRId64, max_digits, v);
1387 break;
1388 case 'c':
1389 monitor_printc(mon, v);
1390 break;
1392 i += wsize;
1394 monitor_printf(mon, "\n");
1395 addr += l;
1396 len -= l;
1400 static void do_memory_dump(Monitor *mon, const QDict *qdict)
1402 int count = qdict_get_int(qdict, "count");
1403 int format = qdict_get_int(qdict, "format");
1404 int size = qdict_get_int(qdict, "size");
1405 target_long addr = qdict_get_int(qdict, "addr");
1407 memory_dump(mon, count, format, size, addr, 0);
1410 static void do_physical_memory_dump(Monitor *mon, const QDict *qdict)
1412 int count = qdict_get_int(qdict, "count");
1413 int format = qdict_get_int(qdict, "format");
1414 int size = qdict_get_int(qdict, "size");
1415 hwaddr addr = qdict_get_int(qdict, "addr");
1417 memory_dump(mon, count, format, size, addr, 1);
1420 static void do_print(Monitor *mon, const QDict *qdict)
1422 int format = qdict_get_int(qdict, "format");
1423 hwaddr val = qdict_get_int(qdict, "val");
1425 switch(format) {
1426 case 'o':
1427 monitor_printf(mon, "%#" HWADDR_PRIo, val);
1428 break;
1429 case 'x':
1430 monitor_printf(mon, "%#" HWADDR_PRIx, val);
1431 break;
1432 case 'u':
1433 monitor_printf(mon, "%" HWADDR_PRIu, val);
1434 break;
1435 default:
1436 case 'd':
1437 monitor_printf(mon, "%" HWADDR_PRId, val);
1438 break;
1439 case 'c':
1440 monitor_printc(mon, val);
1441 break;
1443 monitor_printf(mon, "\n");
1446 static void do_sum(Monitor *mon, const QDict *qdict)
1448 uint32_t addr;
1449 uint16_t sum;
1450 uint32_t start = qdict_get_int(qdict, "start");
1451 uint32_t size = qdict_get_int(qdict, "size");
1453 sum = 0;
1454 for(addr = start; addr < (start + size); addr++) {
1455 uint8_t val = ldub_phys(&address_space_memory, addr);
1456 /* BSD sum algorithm ('sum' Unix command) */
1457 sum = (sum >> 1) | (sum << 15);
1458 sum += val;
1460 monitor_printf(mon, "%05d\n", sum);
1463 static int mouse_button_state;
1465 static void do_mouse_move(Monitor *mon, const QDict *qdict)
1467 int dx, dy, dz, button;
1468 const char *dx_str = qdict_get_str(qdict, "dx_str");
1469 const char *dy_str = qdict_get_str(qdict, "dy_str");
1470 const char *dz_str = qdict_get_try_str(qdict, "dz_str");
1472 dx = strtol(dx_str, NULL, 0);
1473 dy = strtol(dy_str, NULL, 0);
1474 qemu_input_queue_rel(NULL, INPUT_AXIS_X, dx);
1475 qemu_input_queue_rel(NULL, INPUT_AXIS_Y, dy);
1477 if (dz_str) {
1478 dz = strtol(dz_str, NULL, 0);
1479 if (dz != 0) {
1480 button = (dz > 0) ? INPUT_BUTTON_WHEEL_UP : INPUT_BUTTON_WHEEL_DOWN;
1481 qemu_input_queue_btn(NULL, button, true);
1482 qemu_input_event_sync();
1483 qemu_input_queue_btn(NULL, button, false);
1486 qemu_input_event_sync();
1489 static void do_mouse_button(Monitor *mon, const QDict *qdict)
1491 static uint32_t bmap[INPUT_BUTTON_MAX] = {
1492 [INPUT_BUTTON_LEFT] = MOUSE_EVENT_LBUTTON,
1493 [INPUT_BUTTON_MIDDLE] = MOUSE_EVENT_MBUTTON,
1494 [INPUT_BUTTON_RIGHT] = MOUSE_EVENT_RBUTTON,
1496 int button_state = qdict_get_int(qdict, "button_state");
1498 if (mouse_button_state == button_state) {
1499 return;
1501 qemu_input_update_buttons(NULL, bmap, mouse_button_state, button_state);
1502 qemu_input_event_sync();
1503 mouse_button_state = button_state;
1506 static void do_ioport_read(Monitor *mon, const QDict *qdict)
1508 int size = qdict_get_int(qdict, "size");
1509 int addr = qdict_get_int(qdict, "addr");
1510 int has_index = qdict_haskey(qdict, "index");
1511 uint32_t val;
1512 int suffix;
1514 if (has_index) {
1515 int index = qdict_get_int(qdict, "index");
1516 cpu_outb(addr & IOPORTS_MASK, index & 0xff);
1517 addr++;
1519 addr &= 0xffff;
1521 switch(size) {
1522 default:
1523 case 1:
1524 val = cpu_inb(addr);
1525 suffix = 'b';
1526 break;
1527 case 2:
1528 val = cpu_inw(addr);
1529 suffix = 'w';
1530 break;
1531 case 4:
1532 val = cpu_inl(addr);
1533 suffix = 'l';
1534 break;
1536 monitor_printf(mon, "port%c[0x%04x] = %#0*x\n",
1537 suffix, addr, size * 2, val);
1540 static void do_ioport_write(Monitor *mon, const QDict *qdict)
1542 int size = qdict_get_int(qdict, "size");
1543 int addr = qdict_get_int(qdict, "addr");
1544 int val = qdict_get_int(qdict, "val");
1546 addr &= IOPORTS_MASK;
1548 switch (size) {
1549 default:
1550 case 1:
1551 cpu_outb(addr, val);
1552 break;
1553 case 2:
1554 cpu_outw(addr, val);
1555 break;
1556 case 4:
1557 cpu_outl(addr, val);
1558 break;
1562 static void do_boot_set(Monitor *mon, const QDict *qdict)
1564 int res;
1565 const char *bootdevice = qdict_get_str(qdict, "bootdevice");
1567 res = qemu_boot_set(bootdevice);
1568 if (res == 0) {
1569 monitor_printf(mon, "boot device list now set to %s\n", bootdevice);
1570 } else if (res > 0) {
1571 monitor_printf(mon, "setting boot device list failed\n");
1572 } else {
1573 monitor_printf(mon, "no function defined to set boot device list for "
1574 "this architecture\n");
1578 #if defined(TARGET_I386)
1579 static void print_pte(Monitor *mon, hwaddr addr,
1580 hwaddr pte,
1581 hwaddr mask)
1583 #ifdef TARGET_X86_64
1584 if (addr & (1ULL << 47)) {
1585 addr |= -1LL << 48;
1587 #endif
1588 monitor_printf(mon, TARGET_FMT_plx ": " TARGET_FMT_plx
1589 " %c%c%c%c%c%c%c%c%c\n",
1590 addr,
1591 pte & mask,
1592 pte & PG_NX_MASK ? 'X' : '-',
1593 pte & PG_GLOBAL_MASK ? 'G' : '-',
1594 pte & PG_PSE_MASK ? 'P' : '-',
1595 pte & PG_DIRTY_MASK ? 'D' : '-',
1596 pte & PG_ACCESSED_MASK ? 'A' : '-',
1597 pte & PG_PCD_MASK ? 'C' : '-',
1598 pte & PG_PWT_MASK ? 'T' : '-',
1599 pte & PG_USER_MASK ? 'U' : '-',
1600 pte & PG_RW_MASK ? 'W' : '-');
1603 static void tlb_info_32(Monitor *mon, CPUArchState *env)
1605 unsigned int l1, l2;
1606 uint32_t pgd, pde, pte;
1608 pgd = env->cr[3] & ~0xfff;
1609 for(l1 = 0; l1 < 1024; l1++) {
1610 cpu_physical_memory_read(pgd + l1 * 4, &pde, 4);
1611 pde = le32_to_cpu(pde);
1612 if (pde & PG_PRESENT_MASK) {
1613 if ((pde & PG_PSE_MASK) && (env->cr[4] & CR4_PSE_MASK)) {
1614 /* 4M pages */
1615 print_pte(mon, (l1 << 22), pde, ~((1 << 21) - 1));
1616 } else {
1617 for(l2 = 0; l2 < 1024; l2++) {
1618 cpu_physical_memory_read((pde & ~0xfff) + l2 * 4, &pte, 4);
1619 pte = le32_to_cpu(pte);
1620 if (pte & PG_PRESENT_MASK) {
1621 print_pte(mon, (l1 << 22) + (l2 << 12),
1622 pte & ~PG_PSE_MASK,
1623 ~0xfff);
1631 static void tlb_info_pae32(Monitor *mon, CPUArchState *env)
1633 unsigned int l1, l2, l3;
1634 uint64_t pdpe, pde, pte;
1635 uint64_t pdp_addr, pd_addr, pt_addr;
1637 pdp_addr = env->cr[3] & ~0x1f;
1638 for (l1 = 0; l1 < 4; l1++) {
1639 cpu_physical_memory_read(pdp_addr + l1 * 8, &pdpe, 8);
1640 pdpe = le64_to_cpu(pdpe);
1641 if (pdpe & PG_PRESENT_MASK) {
1642 pd_addr = pdpe & 0x3fffffffff000ULL;
1643 for (l2 = 0; l2 < 512; l2++) {
1644 cpu_physical_memory_read(pd_addr + l2 * 8, &pde, 8);
1645 pde = le64_to_cpu(pde);
1646 if (pde & PG_PRESENT_MASK) {
1647 if (pde & PG_PSE_MASK) {
1648 /* 2M pages with PAE, CR4.PSE is ignored */
1649 print_pte(mon, (l1 << 30 ) + (l2 << 21), pde,
1650 ~((hwaddr)(1 << 20) - 1));
1651 } else {
1652 pt_addr = pde & 0x3fffffffff000ULL;
1653 for (l3 = 0; l3 < 512; l3++) {
1654 cpu_physical_memory_read(pt_addr + l3 * 8, &pte, 8);
1655 pte = le64_to_cpu(pte);
1656 if (pte & PG_PRESENT_MASK) {
1657 print_pte(mon, (l1 << 30 ) + (l2 << 21)
1658 + (l3 << 12),
1659 pte & ~PG_PSE_MASK,
1660 ~(hwaddr)0xfff);
1670 #ifdef TARGET_X86_64
1671 static void tlb_info_64(Monitor *mon, CPUArchState *env)
1673 uint64_t l1, l2, l3, l4;
1674 uint64_t pml4e, pdpe, pde, pte;
1675 uint64_t pml4_addr, pdp_addr, pd_addr, pt_addr;
1677 pml4_addr = env->cr[3] & 0x3fffffffff000ULL;
1678 for (l1 = 0; l1 < 512; l1++) {
1679 cpu_physical_memory_read(pml4_addr + l1 * 8, &pml4e, 8);
1680 pml4e = le64_to_cpu(pml4e);
1681 if (pml4e & PG_PRESENT_MASK) {
1682 pdp_addr = pml4e & 0x3fffffffff000ULL;
1683 for (l2 = 0; l2 < 512; l2++) {
1684 cpu_physical_memory_read(pdp_addr + l2 * 8, &pdpe, 8);
1685 pdpe = le64_to_cpu(pdpe);
1686 if (pdpe & PG_PRESENT_MASK) {
1687 if (pdpe & PG_PSE_MASK) {
1688 /* 1G pages, CR4.PSE is ignored */
1689 print_pte(mon, (l1 << 39) + (l2 << 30), pdpe,
1690 0x3ffffc0000000ULL);
1691 } else {
1692 pd_addr = pdpe & 0x3fffffffff000ULL;
1693 for (l3 = 0; l3 < 512; l3++) {
1694 cpu_physical_memory_read(pd_addr + l3 * 8, &pde, 8);
1695 pde = le64_to_cpu(pde);
1696 if (pde & PG_PRESENT_MASK) {
1697 if (pde & PG_PSE_MASK) {
1698 /* 2M pages, CR4.PSE is ignored */
1699 print_pte(mon, (l1 << 39) + (l2 << 30) +
1700 (l3 << 21), pde,
1701 0x3ffffffe00000ULL);
1702 } else {
1703 pt_addr = pde & 0x3fffffffff000ULL;
1704 for (l4 = 0; l4 < 512; l4++) {
1705 cpu_physical_memory_read(pt_addr
1706 + l4 * 8,
1707 &pte, 8);
1708 pte = le64_to_cpu(pte);
1709 if (pte & PG_PRESENT_MASK) {
1710 print_pte(mon, (l1 << 39) +
1711 (l2 << 30) +
1712 (l3 << 21) + (l4 << 12),
1713 pte & ~PG_PSE_MASK,
1714 0x3fffffffff000ULL);
1726 #endif
1728 static void tlb_info(Monitor *mon, const QDict *qdict)
1730 CPUArchState *env;
1732 env = mon_get_cpu();
1734 if (!(env->cr[0] & CR0_PG_MASK)) {
1735 monitor_printf(mon, "PG disabled\n");
1736 return;
1738 if (env->cr[4] & CR4_PAE_MASK) {
1739 #ifdef TARGET_X86_64
1740 if (env->hflags & HF_LMA_MASK) {
1741 tlb_info_64(mon, env);
1742 } else
1743 #endif
1745 tlb_info_pae32(mon, env);
1747 } else {
1748 tlb_info_32(mon, env);
1752 static void mem_print(Monitor *mon, hwaddr *pstart,
1753 int *plast_prot,
1754 hwaddr end, int prot)
1756 int prot1;
1757 prot1 = *plast_prot;
1758 if (prot != prot1) {
1759 if (*pstart != -1) {
1760 monitor_printf(mon, TARGET_FMT_plx "-" TARGET_FMT_plx " "
1761 TARGET_FMT_plx " %c%c%c\n",
1762 *pstart, end, end - *pstart,
1763 prot1 & PG_USER_MASK ? 'u' : '-',
1764 'r',
1765 prot1 & PG_RW_MASK ? 'w' : '-');
1767 if (prot != 0)
1768 *pstart = end;
1769 else
1770 *pstart = -1;
1771 *plast_prot = prot;
1775 static void mem_info_32(Monitor *mon, CPUArchState *env)
1777 unsigned int l1, l2;
1778 int prot, last_prot;
1779 uint32_t pgd, pde, pte;
1780 hwaddr start, end;
1782 pgd = env->cr[3] & ~0xfff;
1783 last_prot = 0;
1784 start = -1;
1785 for(l1 = 0; l1 < 1024; l1++) {
1786 cpu_physical_memory_read(pgd + l1 * 4, &pde, 4);
1787 pde = le32_to_cpu(pde);
1788 end = l1 << 22;
1789 if (pde & PG_PRESENT_MASK) {
1790 if ((pde & PG_PSE_MASK) && (env->cr[4] & CR4_PSE_MASK)) {
1791 prot = pde & (PG_USER_MASK | PG_RW_MASK | PG_PRESENT_MASK);
1792 mem_print(mon, &start, &last_prot, end, prot);
1793 } else {
1794 for(l2 = 0; l2 < 1024; l2++) {
1795 cpu_physical_memory_read((pde & ~0xfff) + l2 * 4, &pte, 4);
1796 pte = le32_to_cpu(pte);
1797 end = (l1 << 22) + (l2 << 12);
1798 if (pte & PG_PRESENT_MASK) {
1799 prot = pte & pde &
1800 (PG_USER_MASK | PG_RW_MASK | PG_PRESENT_MASK);
1801 } else {
1802 prot = 0;
1804 mem_print(mon, &start, &last_prot, end, prot);
1807 } else {
1808 prot = 0;
1809 mem_print(mon, &start, &last_prot, end, prot);
1812 /* Flush last range */
1813 mem_print(mon, &start, &last_prot, (hwaddr)1 << 32, 0);
1816 static void mem_info_pae32(Monitor *mon, CPUArchState *env)
1818 unsigned int l1, l2, l3;
1819 int prot, last_prot;
1820 uint64_t pdpe, pde, pte;
1821 uint64_t pdp_addr, pd_addr, pt_addr;
1822 hwaddr start, end;
1824 pdp_addr = env->cr[3] & ~0x1f;
1825 last_prot = 0;
1826 start = -1;
1827 for (l1 = 0; l1 < 4; l1++) {
1828 cpu_physical_memory_read(pdp_addr + l1 * 8, &pdpe, 8);
1829 pdpe = le64_to_cpu(pdpe);
1830 end = l1 << 30;
1831 if (pdpe & PG_PRESENT_MASK) {
1832 pd_addr = pdpe & 0x3fffffffff000ULL;
1833 for (l2 = 0; l2 < 512; l2++) {
1834 cpu_physical_memory_read(pd_addr + l2 * 8, &pde, 8);
1835 pde = le64_to_cpu(pde);
1836 end = (l1 << 30) + (l2 << 21);
1837 if (pde & PG_PRESENT_MASK) {
1838 if (pde & PG_PSE_MASK) {
1839 prot = pde & (PG_USER_MASK | PG_RW_MASK |
1840 PG_PRESENT_MASK);
1841 mem_print(mon, &start, &last_prot, end, prot);
1842 } else {
1843 pt_addr = pde & 0x3fffffffff000ULL;
1844 for (l3 = 0; l3 < 512; l3++) {
1845 cpu_physical_memory_read(pt_addr + l3 * 8, &pte, 8);
1846 pte = le64_to_cpu(pte);
1847 end = (l1 << 30) + (l2 << 21) + (l3 << 12);
1848 if (pte & PG_PRESENT_MASK) {
1849 prot = pte & pde & (PG_USER_MASK | PG_RW_MASK |
1850 PG_PRESENT_MASK);
1851 } else {
1852 prot = 0;
1854 mem_print(mon, &start, &last_prot, end, prot);
1857 } else {
1858 prot = 0;
1859 mem_print(mon, &start, &last_prot, end, prot);
1862 } else {
1863 prot = 0;
1864 mem_print(mon, &start, &last_prot, end, prot);
1867 /* Flush last range */
1868 mem_print(mon, &start, &last_prot, (hwaddr)1 << 32, 0);
1872 #ifdef TARGET_X86_64
1873 static void mem_info_64(Monitor *mon, CPUArchState *env)
1875 int prot, last_prot;
1876 uint64_t l1, l2, l3, l4;
1877 uint64_t pml4e, pdpe, pde, pte;
1878 uint64_t pml4_addr, pdp_addr, pd_addr, pt_addr, start, end;
1880 pml4_addr = env->cr[3] & 0x3fffffffff000ULL;
1881 last_prot = 0;
1882 start = -1;
1883 for (l1 = 0; l1 < 512; l1++) {
1884 cpu_physical_memory_read(pml4_addr + l1 * 8, &pml4e, 8);
1885 pml4e = le64_to_cpu(pml4e);
1886 end = l1 << 39;
1887 if (pml4e & PG_PRESENT_MASK) {
1888 pdp_addr = pml4e & 0x3fffffffff000ULL;
1889 for (l2 = 0; l2 < 512; l2++) {
1890 cpu_physical_memory_read(pdp_addr + l2 * 8, &pdpe, 8);
1891 pdpe = le64_to_cpu(pdpe);
1892 end = (l1 << 39) + (l2 << 30);
1893 if (pdpe & PG_PRESENT_MASK) {
1894 if (pdpe & PG_PSE_MASK) {
1895 prot = pdpe & (PG_USER_MASK | PG_RW_MASK |
1896 PG_PRESENT_MASK);
1897 prot &= pml4e;
1898 mem_print(mon, &start, &last_prot, end, prot);
1899 } else {
1900 pd_addr = pdpe & 0x3fffffffff000ULL;
1901 for (l3 = 0; l3 < 512; l3++) {
1902 cpu_physical_memory_read(pd_addr + l3 * 8, &pde, 8);
1903 pde = le64_to_cpu(pde);
1904 end = (l1 << 39) + (l2 << 30) + (l3 << 21);
1905 if (pde & PG_PRESENT_MASK) {
1906 if (pde & PG_PSE_MASK) {
1907 prot = pde & (PG_USER_MASK | PG_RW_MASK |
1908 PG_PRESENT_MASK);
1909 prot &= pml4e & pdpe;
1910 mem_print(mon, &start, &last_prot, end, prot);
1911 } else {
1912 pt_addr = pde & 0x3fffffffff000ULL;
1913 for (l4 = 0; l4 < 512; l4++) {
1914 cpu_physical_memory_read(pt_addr
1915 + l4 * 8,
1916 &pte, 8);
1917 pte = le64_to_cpu(pte);
1918 end = (l1 << 39) + (l2 << 30) +
1919 (l3 << 21) + (l4 << 12);
1920 if (pte & PG_PRESENT_MASK) {
1921 prot = pte & (PG_USER_MASK | PG_RW_MASK |
1922 PG_PRESENT_MASK);
1923 prot &= pml4e & pdpe & pde;
1924 } else {
1925 prot = 0;
1927 mem_print(mon, &start, &last_prot, end, prot);
1930 } else {
1931 prot = 0;
1932 mem_print(mon, &start, &last_prot, end, prot);
1936 } else {
1937 prot = 0;
1938 mem_print(mon, &start, &last_prot, end, prot);
1941 } else {
1942 prot = 0;
1943 mem_print(mon, &start, &last_prot, end, prot);
1946 /* Flush last range */
1947 mem_print(mon, &start, &last_prot, (hwaddr)1 << 48, 0);
1949 #endif
1951 static void mem_info(Monitor *mon, const QDict *qdict)
1953 CPUArchState *env;
1955 env = mon_get_cpu();
1957 if (!(env->cr[0] & CR0_PG_MASK)) {
1958 monitor_printf(mon, "PG disabled\n");
1959 return;
1961 if (env->cr[4] & CR4_PAE_MASK) {
1962 #ifdef TARGET_X86_64
1963 if (env->hflags & HF_LMA_MASK) {
1964 mem_info_64(mon, env);
1965 } else
1966 #endif
1968 mem_info_pae32(mon, env);
1970 } else {
1971 mem_info_32(mon, env);
1974 #endif
1976 #if defined(TARGET_SH4)
1978 static void print_tlb(Monitor *mon, int idx, tlb_t *tlb)
1980 monitor_printf(mon, " tlb%i:\t"
1981 "asid=%hhu vpn=%x\tppn=%x\tsz=%hhu size=%u\t"
1982 "v=%hhu shared=%hhu cached=%hhu prot=%hhu "
1983 "dirty=%hhu writethrough=%hhu\n",
1984 idx,
1985 tlb->asid, tlb->vpn, tlb->ppn, tlb->sz, tlb->size,
1986 tlb->v, tlb->sh, tlb->c, tlb->pr,
1987 tlb->d, tlb->wt);
1990 static void tlb_info(Monitor *mon, const QDict *qdict)
1992 CPUArchState *env = mon_get_cpu();
1993 int i;
1995 monitor_printf (mon, "ITLB:\n");
1996 for (i = 0 ; i < ITLB_SIZE ; i++)
1997 print_tlb (mon, i, &env->itlb[i]);
1998 monitor_printf (mon, "UTLB:\n");
1999 for (i = 0 ; i < UTLB_SIZE ; i++)
2000 print_tlb (mon, i, &env->utlb[i]);
2003 #endif
2005 #if defined(TARGET_SPARC) || defined(TARGET_PPC) || defined(TARGET_XTENSA)
2006 static void tlb_info(Monitor *mon, const QDict *qdict)
2008 CPUArchState *env1 = mon_get_cpu();
2010 dump_mmu((FILE*)mon, (fprintf_function)monitor_printf, env1);
2012 #endif
2014 static void do_info_mtree(Monitor *mon, const QDict *qdict)
2016 mtree_info((fprintf_function)monitor_printf, mon);
2019 static void do_info_numa(Monitor *mon, const QDict *qdict)
2021 int i;
2022 CPUState *cpu;
2024 monitor_printf(mon, "%d nodes\n", nb_numa_nodes);
2025 for (i = 0; i < nb_numa_nodes; i++) {
2026 monitor_printf(mon, "node %d cpus:", i);
2027 CPU_FOREACH(cpu) {
2028 if (cpu->numa_node == i) {
2029 monitor_printf(mon, " %d", cpu->cpu_index);
2032 monitor_printf(mon, "\n");
2033 monitor_printf(mon, "node %d size: %" PRId64 " MB\n", i,
2034 node_mem[i] >> 20);
2038 #ifdef CONFIG_PROFILER
2040 int64_t qemu_time;
2041 int64_t dev_time;
2043 static void do_info_profile(Monitor *mon, const QDict *qdict)
2045 monitor_printf(mon, "async time %" PRId64 " (%0.3f)\n",
2046 dev_time, dev_time / (double)get_ticks_per_sec());
2047 monitor_printf(mon, "qemu time %" PRId64 " (%0.3f)\n",
2048 qemu_time, qemu_time / (double)get_ticks_per_sec());
2049 qemu_time = 0;
2050 dev_time = 0;
2052 #else
2053 static void do_info_profile(Monitor *mon, const QDict *qdict)
2055 monitor_printf(mon, "Internal profiler not compiled\n");
2057 #endif
2059 /* Capture support */
2060 static QLIST_HEAD (capture_list_head, CaptureState) capture_head;
2062 static void do_info_capture(Monitor *mon, const QDict *qdict)
2064 int i;
2065 CaptureState *s;
2067 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
2068 monitor_printf(mon, "[%d]: ", i);
2069 s->ops.info (s->opaque);
2073 static void do_stop_capture(Monitor *mon, const QDict *qdict)
2075 int i;
2076 int n = qdict_get_int(qdict, "n");
2077 CaptureState *s;
2079 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
2080 if (i == n) {
2081 s->ops.destroy (s->opaque);
2082 QLIST_REMOVE (s, entries);
2083 g_free (s);
2084 return;
2089 static void do_wav_capture(Monitor *mon, const QDict *qdict)
2091 const char *path = qdict_get_str(qdict, "path");
2092 int has_freq = qdict_haskey(qdict, "freq");
2093 int freq = qdict_get_try_int(qdict, "freq", -1);
2094 int has_bits = qdict_haskey(qdict, "bits");
2095 int bits = qdict_get_try_int(qdict, "bits", -1);
2096 int has_channels = qdict_haskey(qdict, "nchannels");
2097 int nchannels = qdict_get_try_int(qdict, "nchannels", -1);
2098 CaptureState *s;
2100 s = g_malloc0 (sizeof (*s));
2102 freq = has_freq ? freq : 44100;
2103 bits = has_bits ? bits : 16;
2104 nchannels = has_channels ? nchannels : 2;
2106 if (wav_start_capture (s, path, freq, bits, nchannels)) {
2107 monitor_printf(mon, "Failed to add wave capture\n");
2108 g_free (s);
2109 return;
2111 QLIST_INSERT_HEAD (&capture_head, s, entries);
2114 static qemu_acl *find_acl(Monitor *mon, const char *name)
2116 qemu_acl *acl = qemu_acl_find(name);
2118 if (!acl) {
2119 monitor_printf(mon, "acl: unknown list '%s'\n", name);
2121 return acl;
2124 static void do_acl_show(Monitor *mon, const QDict *qdict)
2126 const char *aclname = qdict_get_str(qdict, "aclname");
2127 qemu_acl *acl = find_acl(mon, aclname);
2128 qemu_acl_entry *entry;
2129 int i = 0;
2131 if (acl) {
2132 monitor_printf(mon, "policy: %s\n",
2133 acl->defaultDeny ? "deny" : "allow");
2134 QTAILQ_FOREACH(entry, &acl->entries, next) {
2135 i++;
2136 monitor_printf(mon, "%d: %s %s\n", i,
2137 entry->deny ? "deny" : "allow", entry->match);
2142 static void do_acl_reset(Monitor *mon, const QDict *qdict)
2144 const char *aclname = qdict_get_str(qdict, "aclname");
2145 qemu_acl *acl = find_acl(mon, aclname);
2147 if (acl) {
2148 qemu_acl_reset(acl);
2149 monitor_printf(mon, "acl: removed all rules\n");
2153 static void do_acl_policy(Monitor *mon, const QDict *qdict)
2155 const char *aclname = qdict_get_str(qdict, "aclname");
2156 const char *policy = qdict_get_str(qdict, "policy");
2157 qemu_acl *acl = find_acl(mon, aclname);
2159 if (acl) {
2160 if (strcmp(policy, "allow") == 0) {
2161 acl->defaultDeny = 0;
2162 monitor_printf(mon, "acl: policy set to 'allow'\n");
2163 } else if (strcmp(policy, "deny") == 0) {
2164 acl->defaultDeny = 1;
2165 monitor_printf(mon, "acl: policy set to 'deny'\n");
2166 } else {
2167 monitor_printf(mon, "acl: unknown policy '%s', "
2168 "expected 'deny' or 'allow'\n", policy);
2173 static void do_acl_add(Monitor *mon, const QDict *qdict)
2175 const char *aclname = qdict_get_str(qdict, "aclname");
2176 const char *match = qdict_get_str(qdict, "match");
2177 const char *policy = qdict_get_str(qdict, "policy");
2178 int has_index = qdict_haskey(qdict, "index");
2179 int index = qdict_get_try_int(qdict, "index", -1);
2180 qemu_acl *acl = find_acl(mon, aclname);
2181 int deny, ret;
2183 if (acl) {
2184 if (strcmp(policy, "allow") == 0) {
2185 deny = 0;
2186 } else if (strcmp(policy, "deny") == 0) {
2187 deny = 1;
2188 } else {
2189 monitor_printf(mon, "acl: unknown policy '%s', "
2190 "expected 'deny' or 'allow'\n", policy);
2191 return;
2193 if (has_index)
2194 ret = qemu_acl_insert(acl, deny, match, index);
2195 else
2196 ret = qemu_acl_append(acl, deny, match);
2197 if (ret < 0)
2198 monitor_printf(mon, "acl: unable to add acl entry\n");
2199 else
2200 monitor_printf(mon, "acl: added rule at position %d\n", ret);
2204 static void do_acl_remove(Monitor *mon, const QDict *qdict)
2206 const char *aclname = qdict_get_str(qdict, "aclname");
2207 const char *match = qdict_get_str(qdict, "match");
2208 qemu_acl *acl = find_acl(mon, aclname);
2209 int ret;
2211 if (acl) {
2212 ret = qemu_acl_remove(acl, match);
2213 if (ret < 0)
2214 monitor_printf(mon, "acl: no matching acl entry\n");
2215 else
2216 monitor_printf(mon, "acl: removed rule at position %d\n", ret);
2220 #if defined(TARGET_I386)
2221 static void do_inject_mce(Monitor *mon, const QDict *qdict)
2223 X86CPU *cpu;
2224 CPUState *cs;
2225 int cpu_index = qdict_get_int(qdict, "cpu_index");
2226 int bank = qdict_get_int(qdict, "bank");
2227 uint64_t status = qdict_get_int(qdict, "status");
2228 uint64_t mcg_status = qdict_get_int(qdict, "mcg_status");
2229 uint64_t addr = qdict_get_int(qdict, "addr");
2230 uint64_t misc = qdict_get_int(qdict, "misc");
2231 int flags = MCE_INJECT_UNCOND_AO;
2233 if (qdict_get_try_bool(qdict, "broadcast", 0)) {
2234 flags |= MCE_INJECT_BROADCAST;
2236 cs = qemu_get_cpu(cpu_index);
2237 if (cs != NULL) {
2238 cpu = X86_CPU(cs);
2239 cpu_x86_inject_mce(mon, cpu, bank, status, mcg_status, addr, misc,
2240 flags);
2243 #endif
2245 void qmp_getfd(const char *fdname, Error **errp)
2247 mon_fd_t *monfd;
2248 int fd;
2250 fd = qemu_chr_fe_get_msgfd(cur_mon->chr);
2251 if (fd == -1) {
2252 error_set(errp, QERR_FD_NOT_SUPPLIED);
2253 return;
2256 if (qemu_isdigit(fdname[0])) {
2257 error_set(errp, QERR_INVALID_PARAMETER_VALUE, "fdname",
2258 "a name not starting with a digit");
2259 return;
2262 QLIST_FOREACH(monfd, &cur_mon->fds, next) {
2263 if (strcmp(monfd->name, fdname) != 0) {
2264 continue;
2267 close(monfd->fd);
2268 monfd->fd = fd;
2269 return;
2272 monfd = g_malloc0(sizeof(mon_fd_t));
2273 monfd->name = g_strdup(fdname);
2274 monfd->fd = fd;
2276 QLIST_INSERT_HEAD(&cur_mon->fds, monfd, next);
2279 void qmp_closefd(const char *fdname, Error **errp)
2281 mon_fd_t *monfd;
2283 QLIST_FOREACH(monfd, &cur_mon->fds, next) {
2284 if (strcmp(monfd->name, fdname) != 0) {
2285 continue;
2288 QLIST_REMOVE(monfd, next);
2289 close(monfd->fd);
2290 g_free(monfd->name);
2291 g_free(monfd);
2292 return;
2295 error_set(errp, QERR_FD_NOT_FOUND, fdname);
2298 static void do_loadvm(Monitor *mon, const QDict *qdict)
2300 int saved_vm_running = runstate_is_running();
2301 const char *name = qdict_get_str(qdict, "name");
2303 vm_stop(RUN_STATE_RESTORE_VM);
2305 if (load_vmstate(name) == 0 && saved_vm_running) {
2306 vm_start();
2310 int monitor_get_fd(Monitor *mon, const char *fdname, Error **errp)
2312 mon_fd_t *monfd;
2314 QLIST_FOREACH(monfd, &mon->fds, next) {
2315 int fd;
2317 if (strcmp(monfd->name, fdname) != 0) {
2318 continue;
2321 fd = monfd->fd;
2323 /* caller takes ownership of fd */
2324 QLIST_REMOVE(monfd, next);
2325 g_free(monfd->name);
2326 g_free(monfd);
2328 return fd;
2331 error_setg(errp, "File descriptor named '%s' has not been found", fdname);
2332 return -1;
2335 static void monitor_fdset_cleanup(MonFdset *mon_fdset)
2337 MonFdsetFd *mon_fdset_fd;
2338 MonFdsetFd *mon_fdset_fd_next;
2340 QLIST_FOREACH_SAFE(mon_fdset_fd, &mon_fdset->fds, next, mon_fdset_fd_next) {
2341 if ((mon_fdset_fd->removed ||
2342 (QLIST_EMPTY(&mon_fdset->dup_fds) && mon_refcount == 0)) &&
2343 runstate_is_running()) {
2344 close(mon_fdset_fd->fd);
2345 g_free(mon_fdset_fd->opaque);
2346 QLIST_REMOVE(mon_fdset_fd, next);
2347 g_free(mon_fdset_fd);
2351 if (QLIST_EMPTY(&mon_fdset->fds) && QLIST_EMPTY(&mon_fdset->dup_fds)) {
2352 QLIST_REMOVE(mon_fdset, next);
2353 g_free(mon_fdset);
2357 static void monitor_fdsets_cleanup(void)
2359 MonFdset *mon_fdset;
2360 MonFdset *mon_fdset_next;
2362 QLIST_FOREACH_SAFE(mon_fdset, &mon_fdsets, next, mon_fdset_next) {
2363 monitor_fdset_cleanup(mon_fdset);
2367 AddfdInfo *qmp_add_fd(bool has_fdset_id, int64_t fdset_id, bool has_opaque,
2368 const char *opaque, Error **errp)
2370 int fd;
2371 Monitor *mon = cur_mon;
2372 AddfdInfo *fdinfo;
2374 fd = qemu_chr_fe_get_msgfd(mon->chr);
2375 if (fd == -1) {
2376 error_set(errp, QERR_FD_NOT_SUPPLIED);
2377 goto error;
2380 fdinfo = monitor_fdset_add_fd(fd, has_fdset_id, fdset_id,
2381 has_opaque, opaque, errp);
2382 if (fdinfo) {
2383 return fdinfo;
2386 error:
2387 if (fd != -1) {
2388 close(fd);
2390 return NULL;
2393 void qmp_remove_fd(int64_t fdset_id, bool has_fd, int64_t fd, Error **errp)
2395 MonFdset *mon_fdset;
2396 MonFdsetFd *mon_fdset_fd;
2397 char fd_str[60];
2399 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2400 if (mon_fdset->id != fdset_id) {
2401 continue;
2403 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2404 if (has_fd) {
2405 if (mon_fdset_fd->fd != fd) {
2406 continue;
2408 mon_fdset_fd->removed = true;
2409 break;
2410 } else {
2411 mon_fdset_fd->removed = true;
2414 if (has_fd && !mon_fdset_fd) {
2415 goto error;
2417 monitor_fdset_cleanup(mon_fdset);
2418 return;
2421 error:
2422 if (has_fd) {
2423 snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64 ", fd:%" PRId64,
2424 fdset_id, fd);
2425 } else {
2426 snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64, fdset_id);
2428 error_set(errp, QERR_FD_NOT_FOUND, fd_str);
2431 FdsetInfoList *qmp_query_fdsets(Error **errp)
2433 MonFdset *mon_fdset;
2434 MonFdsetFd *mon_fdset_fd;
2435 FdsetInfoList *fdset_list = NULL;
2437 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2438 FdsetInfoList *fdset_info = g_malloc0(sizeof(*fdset_info));
2439 FdsetFdInfoList *fdsetfd_list = NULL;
2441 fdset_info->value = g_malloc0(sizeof(*fdset_info->value));
2442 fdset_info->value->fdset_id = mon_fdset->id;
2444 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2445 FdsetFdInfoList *fdsetfd_info;
2447 fdsetfd_info = g_malloc0(sizeof(*fdsetfd_info));
2448 fdsetfd_info->value = g_malloc0(sizeof(*fdsetfd_info->value));
2449 fdsetfd_info->value->fd = mon_fdset_fd->fd;
2450 if (mon_fdset_fd->opaque) {
2451 fdsetfd_info->value->has_opaque = true;
2452 fdsetfd_info->value->opaque = g_strdup(mon_fdset_fd->opaque);
2453 } else {
2454 fdsetfd_info->value->has_opaque = false;
2457 fdsetfd_info->next = fdsetfd_list;
2458 fdsetfd_list = fdsetfd_info;
2461 fdset_info->value->fds = fdsetfd_list;
2463 fdset_info->next = fdset_list;
2464 fdset_list = fdset_info;
2467 return fdset_list;
2470 AddfdInfo *monitor_fdset_add_fd(int fd, bool has_fdset_id, int64_t fdset_id,
2471 bool has_opaque, const char *opaque,
2472 Error **errp)
2474 MonFdset *mon_fdset = NULL;
2475 MonFdsetFd *mon_fdset_fd;
2476 AddfdInfo *fdinfo;
2478 if (has_fdset_id) {
2479 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2480 /* Break if match found or match impossible due to ordering by ID */
2481 if (fdset_id <= mon_fdset->id) {
2482 if (fdset_id < mon_fdset->id) {
2483 mon_fdset = NULL;
2485 break;
2490 if (mon_fdset == NULL) {
2491 int64_t fdset_id_prev = -1;
2492 MonFdset *mon_fdset_cur = QLIST_FIRST(&mon_fdsets);
2494 if (has_fdset_id) {
2495 if (fdset_id < 0) {
2496 error_set(errp, QERR_INVALID_PARAMETER_VALUE, "fdset-id",
2497 "a non-negative value");
2498 return NULL;
2500 /* Use specified fdset ID */
2501 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2502 mon_fdset_cur = mon_fdset;
2503 if (fdset_id < mon_fdset_cur->id) {
2504 break;
2507 } else {
2508 /* Use first available fdset ID */
2509 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2510 mon_fdset_cur = mon_fdset;
2511 if (fdset_id_prev == mon_fdset_cur->id - 1) {
2512 fdset_id_prev = mon_fdset_cur->id;
2513 continue;
2515 break;
2519 mon_fdset = g_malloc0(sizeof(*mon_fdset));
2520 if (has_fdset_id) {
2521 mon_fdset->id = fdset_id;
2522 } else {
2523 mon_fdset->id = fdset_id_prev + 1;
2526 /* The fdset list is ordered by fdset ID */
2527 if (!mon_fdset_cur) {
2528 QLIST_INSERT_HEAD(&mon_fdsets, mon_fdset, next);
2529 } else if (mon_fdset->id < mon_fdset_cur->id) {
2530 QLIST_INSERT_BEFORE(mon_fdset_cur, mon_fdset, next);
2531 } else {
2532 QLIST_INSERT_AFTER(mon_fdset_cur, mon_fdset, next);
2536 mon_fdset_fd = g_malloc0(sizeof(*mon_fdset_fd));
2537 mon_fdset_fd->fd = fd;
2538 mon_fdset_fd->removed = false;
2539 if (has_opaque) {
2540 mon_fdset_fd->opaque = g_strdup(opaque);
2542 QLIST_INSERT_HEAD(&mon_fdset->fds, mon_fdset_fd, next);
2544 fdinfo = g_malloc0(sizeof(*fdinfo));
2545 fdinfo->fdset_id = mon_fdset->id;
2546 fdinfo->fd = mon_fdset_fd->fd;
2548 return fdinfo;
2551 int monitor_fdset_get_fd(int64_t fdset_id, int flags)
2553 #ifndef _WIN32
2554 MonFdset *mon_fdset;
2555 MonFdsetFd *mon_fdset_fd;
2556 int mon_fd_flags;
2558 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2559 if (mon_fdset->id != fdset_id) {
2560 continue;
2562 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2563 mon_fd_flags = fcntl(mon_fdset_fd->fd, F_GETFL);
2564 if (mon_fd_flags == -1) {
2565 return -1;
2568 if ((flags & O_ACCMODE) == (mon_fd_flags & O_ACCMODE)) {
2569 return mon_fdset_fd->fd;
2572 errno = EACCES;
2573 return -1;
2575 #endif
2577 errno = ENOENT;
2578 return -1;
2581 int monitor_fdset_dup_fd_add(int64_t fdset_id, int dup_fd)
2583 MonFdset *mon_fdset;
2584 MonFdsetFd *mon_fdset_fd_dup;
2586 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2587 if (mon_fdset->id != fdset_id) {
2588 continue;
2590 QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
2591 if (mon_fdset_fd_dup->fd == dup_fd) {
2592 return -1;
2595 mon_fdset_fd_dup = g_malloc0(sizeof(*mon_fdset_fd_dup));
2596 mon_fdset_fd_dup->fd = dup_fd;
2597 QLIST_INSERT_HEAD(&mon_fdset->dup_fds, mon_fdset_fd_dup, next);
2598 return 0;
2600 return -1;
2603 static int monitor_fdset_dup_fd_find_remove(int dup_fd, bool remove)
2605 MonFdset *mon_fdset;
2606 MonFdsetFd *mon_fdset_fd_dup;
2608 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2609 QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
2610 if (mon_fdset_fd_dup->fd == dup_fd) {
2611 if (remove) {
2612 QLIST_REMOVE(mon_fdset_fd_dup, next);
2613 if (QLIST_EMPTY(&mon_fdset->dup_fds)) {
2614 monitor_fdset_cleanup(mon_fdset);
2617 return mon_fdset->id;
2621 return -1;
2624 int monitor_fdset_dup_fd_find(int dup_fd)
2626 return monitor_fdset_dup_fd_find_remove(dup_fd, false);
2629 int monitor_fdset_dup_fd_remove(int dup_fd)
2631 return monitor_fdset_dup_fd_find_remove(dup_fd, true);
2634 int monitor_handle_fd_param(Monitor *mon, const char *fdname)
2636 int fd;
2637 Error *local_err = NULL;
2639 if (!qemu_isdigit(fdname[0]) && mon) {
2641 fd = monitor_get_fd(mon, fdname, &local_err);
2642 if (fd == -1) {
2643 qerror_report_err(local_err);
2644 error_free(local_err);
2645 return -1;
2647 } else {
2648 fd = qemu_parse_fd(fdname);
2651 return fd;
2654 /* Please update hmp-commands.hx when adding or changing commands */
2655 static mon_cmd_t info_cmds[] = {
2657 .name = "version",
2658 .args_type = "",
2659 .params = "",
2660 .help = "show the version of QEMU",
2661 .mhandler.cmd = hmp_info_version,
2664 .name = "network",
2665 .args_type = "",
2666 .params = "",
2667 .help = "show the network state",
2668 .mhandler.cmd = do_info_network,
2671 .name = "chardev",
2672 .args_type = "",
2673 .params = "",
2674 .help = "show the character devices",
2675 .mhandler.cmd = hmp_info_chardev,
2678 .name = "block",
2679 .args_type = "verbose:-v,device:B?",
2680 .params = "[-v] [device]",
2681 .help = "show info of one block device or all block devices "
2682 "(and details of images with -v option)",
2683 .mhandler.cmd = hmp_info_block,
2686 .name = "blockstats",
2687 .args_type = "",
2688 .params = "",
2689 .help = "show block device statistics",
2690 .mhandler.cmd = hmp_info_blockstats,
2693 .name = "block-jobs",
2694 .args_type = "",
2695 .params = "",
2696 .help = "show progress of ongoing block device operations",
2697 .mhandler.cmd = hmp_info_block_jobs,
2700 .name = "registers",
2701 .args_type = "",
2702 .params = "",
2703 .help = "show the cpu registers",
2704 .mhandler.cmd = do_info_registers,
2707 .name = "cpus",
2708 .args_type = "",
2709 .params = "",
2710 .help = "show infos for each CPU",
2711 .mhandler.cmd = hmp_info_cpus,
2714 .name = "history",
2715 .args_type = "",
2716 .params = "",
2717 .help = "show the command line history",
2718 .mhandler.cmd = do_info_history,
2720 #if defined(TARGET_I386) || defined(TARGET_PPC) || defined(TARGET_MIPS) || \
2721 defined(TARGET_LM32) || (defined(TARGET_SPARC) && !defined(TARGET_SPARC64))
2723 .name = "irq",
2724 .args_type = "",
2725 .params = "",
2726 .help = "show the interrupts statistics (if available)",
2727 #ifdef TARGET_SPARC
2728 .mhandler.cmd = sun4m_irq_info,
2729 #elif defined(TARGET_LM32)
2730 .mhandler.cmd = lm32_irq_info,
2731 #else
2732 .mhandler.cmd = irq_info,
2733 #endif
2736 .name = "pic",
2737 .args_type = "",
2738 .params = "",
2739 .help = "show i8259 (PIC) state",
2740 #ifdef TARGET_SPARC
2741 .mhandler.cmd = sun4m_pic_info,
2742 #elif defined(TARGET_LM32)
2743 .mhandler.cmd = lm32_do_pic_info,
2744 #else
2745 .mhandler.cmd = pic_info,
2746 #endif
2748 #endif
2750 .name = "pci",
2751 .args_type = "",
2752 .params = "",
2753 .help = "show PCI info",
2754 .mhandler.cmd = hmp_info_pci,
2756 #if defined(TARGET_I386) || defined(TARGET_SH4) || defined(TARGET_SPARC) || \
2757 defined(TARGET_PPC) || defined(TARGET_XTENSA)
2759 .name = "tlb",
2760 .args_type = "",
2761 .params = "",
2762 .help = "show virtual to physical memory mappings",
2763 .mhandler.cmd = tlb_info,
2765 #endif
2766 #if defined(TARGET_I386)
2768 .name = "mem",
2769 .args_type = "",
2770 .params = "",
2771 .help = "show the active virtual memory mappings",
2772 .mhandler.cmd = mem_info,
2774 #endif
2776 .name = "mtree",
2777 .args_type = "",
2778 .params = "",
2779 .help = "show memory tree",
2780 .mhandler.cmd = do_info_mtree,
2783 .name = "jit",
2784 .args_type = "",
2785 .params = "",
2786 .help = "show dynamic compiler info",
2787 .mhandler.cmd = do_info_jit,
2790 .name = "kvm",
2791 .args_type = "",
2792 .params = "",
2793 .help = "show KVM information",
2794 .mhandler.cmd = hmp_info_kvm,
2797 .name = "numa",
2798 .args_type = "",
2799 .params = "",
2800 .help = "show NUMA information",
2801 .mhandler.cmd = do_info_numa,
2804 .name = "usb",
2805 .args_type = "",
2806 .params = "",
2807 .help = "show guest USB devices",
2808 .mhandler.cmd = usb_info,
2811 .name = "usbhost",
2812 .args_type = "",
2813 .params = "",
2814 .help = "show host USB devices",
2815 .mhandler.cmd = usb_host_info,
2818 .name = "profile",
2819 .args_type = "",
2820 .params = "",
2821 .help = "show profiling information",
2822 .mhandler.cmd = do_info_profile,
2825 .name = "capture",
2826 .args_type = "",
2827 .params = "",
2828 .help = "show capture information",
2829 .mhandler.cmd = do_info_capture,
2832 .name = "snapshots",
2833 .args_type = "",
2834 .params = "",
2835 .help = "show the currently saved VM snapshots",
2836 .mhandler.cmd = do_info_snapshots,
2839 .name = "status",
2840 .args_type = "",
2841 .params = "",
2842 .help = "show the current VM status (running|paused)",
2843 .mhandler.cmd = hmp_info_status,
2846 .name = "pcmcia",
2847 .args_type = "",
2848 .params = "",
2849 .help = "show guest PCMCIA status",
2850 .mhandler.cmd = pcmcia_info,
2853 .name = "mice",
2854 .args_type = "",
2855 .params = "",
2856 .help = "show which guest mouse is receiving events",
2857 .mhandler.cmd = hmp_info_mice,
2860 .name = "vnc",
2861 .args_type = "",
2862 .params = "",
2863 .help = "show the vnc server status",
2864 .mhandler.cmd = hmp_info_vnc,
2866 #if defined(CONFIG_SPICE)
2868 .name = "spice",
2869 .args_type = "",
2870 .params = "",
2871 .help = "show the spice server status",
2872 .mhandler.cmd = hmp_info_spice,
2874 #endif
2876 .name = "name",
2877 .args_type = "",
2878 .params = "",
2879 .help = "show the current VM name",
2880 .mhandler.cmd = hmp_info_name,
2883 .name = "uuid",
2884 .args_type = "",
2885 .params = "",
2886 .help = "show the current VM UUID",
2887 .mhandler.cmd = hmp_info_uuid,
2890 .name = "cpustats",
2891 .args_type = "",
2892 .params = "",
2893 .help = "show CPU statistics",
2894 .mhandler.cmd = do_info_cpu_stats,
2896 #if defined(CONFIG_SLIRP)
2898 .name = "usernet",
2899 .args_type = "",
2900 .params = "",
2901 .help = "show user network stack connection states",
2902 .mhandler.cmd = do_info_usernet,
2904 #endif
2906 .name = "migrate",
2907 .args_type = "",
2908 .params = "",
2909 .help = "show migration status",
2910 .mhandler.cmd = hmp_info_migrate,
2913 .name = "migrate_capabilities",
2914 .args_type = "",
2915 .params = "",
2916 .help = "show current migration capabilities",
2917 .mhandler.cmd = hmp_info_migrate_capabilities,
2920 .name = "migrate_cache_size",
2921 .args_type = "",
2922 .params = "",
2923 .help = "show current migration xbzrle cache size",
2924 .mhandler.cmd = hmp_info_migrate_cache_size,
2927 .name = "balloon",
2928 .args_type = "",
2929 .params = "",
2930 .help = "show balloon information",
2931 .mhandler.cmd = hmp_info_balloon,
2934 .name = "qtree",
2935 .args_type = "",
2936 .params = "",
2937 .help = "show device tree",
2938 .mhandler.cmd = do_info_qtree,
2941 .name = "qdm",
2942 .args_type = "",
2943 .params = "",
2944 .help = "show qdev device model list",
2945 .mhandler.cmd = do_info_qdm,
2948 .name = "roms",
2949 .args_type = "",
2950 .params = "",
2951 .help = "show roms",
2952 .mhandler.cmd = do_info_roms,
2955 .name = "trace-events",
2956 .args_type = "",
2957 .params = "",
2958 .help = "show available trace-events & their state",
2959 .mhandler.cmd = do_trace_print_events,
2962 .name = "tpm",
2963 .args_type = "",
2964 .params = "",
2965 .help = "show the TPM device",
2966 .mhandler.cmd = hmp_info_tpm,
2969 .name = NULL,
2973 /* mon_cmds and info_cmds would be sorted at runtime */
2974 static mon_cmd_t mon_cmds[] = {
2975 #include "hmp-commands.h"
2976 { NULL, NULL, },
2979 static const mon_cmd_t qmp_cmds[] = {
2980 #include "qmp-commands-old.h"
2981 { /* NULL */ },
2984 /*******************************************************************/
2986 static const char *pch;
2987 static sigjmp_buf expr_env;
2989 #define MD_TLONG 0
2990 #define MD_I32 1
2992 typedef struct MonitorDef {
2993 const char *name;
2994 int offset;
2995 target_long (*get_value)(const struct MonitorDef *md, int val);
2996 int type;
2997 } MonitorDef;
2999 #if defined(TARGET_I386)
3000 static target_long monitor_get_pc (const struct MonitorDef *md, int val)
3002 CPUArchState *env = mon_get_cpu();
3003 return env->eip + env->segs[R_CS].base;
3005 #endif
3007 #if defined(TARGET_PPC)
3008 static target_long monitor_get_ccr (const struct MonitorDef *md, int val)
3010 CPUArchState *env = mon_get_cpu();
3011 unsigned int u;
3012 int i;
3014 u = 0;
3015 for (i = 0; i < 8; i++)
3016 u |= env->crf[i] << (32 - (4 * i));
3018 return u;
3021 static target_long monitor_get_msr (const struct MonitorDef *md, int val)
3023 CPUArchState *env = mon_get_cpu();
3024 return env->msr;
3027 static target_long monitor_get_xer (const struct MonitorDef *md, int val)
3029 CPUArchState *env = mon_get_cpu();
3030 return env->xer;
3033 static target_long monitor_get_decr (const struct MonitorDef *md, int val)
3035 CPUArchState *env = mon_get_cpu();
3036 return cpu_ppc_load_decr(env);
3039 static target_long monitor_get_tbu (const struct MonitorDef *md, int val)
3041 CPUArchState *env = mon_get_cpu();
3042 return cpu_ppc_load_tbu(env);
3045 static target_long monitor_get_tbl (const struct MonitorDef *md, int val)
3047 CPUArchState *env = mon_get_cpu();
3048 return cpu_ppc_load_tbl(env);
3050 #endif
3052 #if defined(TARGET_SPARC)
3053 #ifndef TARGET_SPARC64
3054 static target_long monitor_get_psr (const struct MonitorDef *md, int val)
3056 CPUArchState *env = mon_get_cpu();
3058 return cpu_get_psr(env);
3060 #endif
3062 static target_long monitor_get_reg(const struct MonitorDef *md, int val)
3064 CPUArchState *env = mon_get_cpu();
3065 return env->regwptr[val];
3067 #endif
3069 static const MonitorDef monitor_defs[] = {
3070 #ifdef TARGET_I386
3072 #define SEG(name, seg) \
3073 { name, offsetof(CPUX86State, segs[seg].selector), NULL, MD_I32 },\
3074 { name ".base", offsetof(CPUX86State, segs[seg].base) },\
3075 { name ".limit", offsetof(CPUX86State, segs[seg].limit), NULL, MD_I32 },
3077 { "eax", offsetof(CPUX86State, regs[0]) },
3078 { "ecx", offsetof(CPUX86State, regs[1]) },
3079 { "edx", offsetof(CPUX86State, regs[2]) },
3080 { "ebx", offsetof(CPUX86State, regs[3]) },
3081 { "esp|sp", offsetof(CPUX86State, regs[4]) },
3082 { "ebp|fp", offsetof(CPUX86State, regs[5]) },
3083 { "esi", offsetof(CPUX86State, regs[6]) },
3084 { "edi", offsetof(CPUX86State, regs[7]) },
3085 #ifdef TARGET_X86_64
3086 { "r8", offsetof(CPUX86State, regs[8]) },
3087 { "r9", offsetof(CPUX86State, regs[9]) },
3088 { "r10", offsetof(CPUX86State, regs[10]) },
3089 { "r11", offsetof(CPUX86State, regs[11]) },
3090 { "r12", offsetof(CPUX86State, regs[12]) },
3091 { "r13", offsetof(CPUX86State, regs[13]) },
3092 { "r14", offsetof(CPUX86State, regs[14]) },
3093 { "r15", offsetof(CPUX86State, regs[15]) },
3094 #endif
3095 { "eflags", offsetof(CPUX86State, eflags) },
3096 { "eip", offsetof(CPUX86State, eip) },
3097 SEG("cs", R_CS)
3098 SEG("ds", R_DS)
3099 SEG("es", R_ES)
3100 SEG("ss", R_SS)
3101 SEG("fs", R_FS)
3102 SEG("gs", R_GS)
3103 { "pc", 0, monitor_get_pc, },
3104 #elif defined(TARGET_PPC)
3105 /* General purpose registers */
3106 { "r0", offsetof(CPUPPCState, gpr[0]) },
3107 { "r1", offsetof(CPUPPCState, gpr[1]) },
3108 { "r2", offsetof(CPUPPCState, gpr[2]) },
3109 { "r3", offsetof(CPUPPCState, gpr[3]) },
3110 { "r4", offsetof(CPUPPCState, gpr[4]) },
3111 { "r5", offsetof(CPUPPCState, gpr[5]) },
3112 { "r6", offsetof(CPUPPCState, gpr[6]) },
3113 { "r7", offsetof(CPUPPCState, gpr[7]) },
3114 { "r8", offsetof(CPUPPCState, gpr[8]) },
3115 { "r9", offsetof(CPUPPCState, gpr[9]) },
3116 { "r10", offsetof(CPUPPCState, gpr[10]) },
3117 { "r11", offsetof(CPUPPCState, gpr[11]) },
3118 { "r12", offsetof(CPUPPCState, gpr[12]) },
3119 { "r13", offsetof(CPUPPCState, gpr[13]) },
3120 { "r14", offsetof(CPUPPCState, gpr[14]) },
3121 { "r15", offsetof(CPUPPCState, gpr[15]) },
3122 { "r16", offsetof(CPUPPCState, gpr[16]) },
3123 { "r17", offsetof(CPUPPCState, gpr[17]) },
3124 { "r18", offsetof(CPUPPCState, gpr[18]) },
3125 { "r19", offsetof(CPUPPCState, gpr[19]) },
3126 { "r20", offsetof(CPUPPCState, gpr[20]) },
3127 { "r21", offsetof(CPUPPCState, gpr[21]) },
3128 { "r22", offsetof(CPUPPCState, gpr[22]) },
3129 { "r23", offsetof(CPUPPCState, gpr[23]) },
3130 { "r24", offsetof(CPUPPCState, gpr[24]) },
3131 { "r25", offsetof(CPUPPCState, gpr[25]) },
3132 { "r26", offsetof(CPUPPCState, gpr[26]) },
3133 { "r27", offsetof(CPUPPCState, gpr[27]) },
3134 { "r28", offsetof(CPUPPCState, gpr[28]) },
3135 { "r29", offsetof(CPUPPCState, gpr[29]) },
3136 { "r30", offsetof(CPUPPCState, gpr[30]) },
3137 { "r31", offsetof(CPUPPCState, gpr[31]) },
3138 /* Floating point registers */
3139 { "f0", offsetof(CPUPPCState, fpr[0]) },
3140 { "f1", offsetof(CPUPPCState, fpr[1]) },
3141 { "f2", offsetof(CPUPPCState, fpr[2]) },
3142 { "f3", offsetof(CPUPPCState, fpr[3]) },
3143 { "f4", offsetof(CPUPPCState, fpr[4]) },
3144 { "f5", offsetof(CPUPPCState, fpr[5]) },
3145 { "f6", offsetof(CPUPPCState, fpr[6]) },
3146 { "f7", offsetof(CPUPPCState, fpr[7]) },
3147 { "f8", offsetof(CPUPPCState, fpr[8]) },
3148 { "f9", offsetof(CPUPPCState, fpr[9]) },
3149 { "f10", offsetof(CPUPPCState, fpr[10]) },
3150 { "f11", offsetof(CPUPPCState, fpr[11]) },
3151 { "f12", offsetof(CPUPPCState, fpr[12]) },
3152 { "f13", offsetof(CPUPPCState, fpr[13]) },
3153 { "f14", offsetof(CPUPPCState, fpr[14]) },
3154 { "f15", offsetof(CPUPPCState, fpr[15]) },
3155 { "f16", offsetof(CPUPPCState, fpr[16]) },
3156 { "f17", offsetof(CPUPPCState, fpr[17]) },
3157 { "f18", offsetof(CPUPPCState, fpr[18]) },
3158 { "f19", offsetof(CPUPPCState, fpr[19]) },
3159 { "f20", offsetof(CPUPPCState, fpr[20]) },
3160 { "f21", offsetof(CPUPPCState, fpr[21]) },
3161 { "f22", offsetof(CPUPPCState, fpr[22]) },
3162 { "f23", offsetof(CPUPPCState, fpr[23]) },
3163 { "f24", offsetof(CPUPPCState, fpr[24]) },
3164 { "f25", offsetof(CPUPPCState, fpr[25]) },
3165 { "f26", offsetof(CPUPPCState, fpr[26]) },
3166 { "f27", offsetof(CPUPPCState, fpr[27]) },
3167 { "f28", offsetof(CPUPPCState, fpr[28]) },
3168 { "f29", offsetof(CPUPPCState, fpr[29]) },
3169 { "f30", offsetof(CPUPPCState, fpr[30]) },
3170 { "f31", offsetof(CPUPPCState, fpr[31]) },
3171 { "fpscr", offsetof(CPUPPCState, fpscr) },
3172 /* Next instruction pointer */
3173 { "nip|pc", offsetof(CPUPPCState, nip) },
3174 { "lr", offsetof(CPUPPCState, lr) },
3175 { "ctr", offsetof(CPUPPCState, ctr) },
3176 { "decr", 0, &monitor_get_decr, },
3177 { "ccr", 0, &monitor_get_ccr, },
3178 /* Machine state register */
3179 { "msr", 0, &monitor_get_msr, },
3180 { "xer", 0, &monitor_get_xer, },
3181 { "tbu", 0, &monitor_get_tbu, },
3182 { "tbl", 0, &monitor_get_tbl, },
3183 /* Segment registers */
3184 { "sdr1", offsetof(CPUPPCState, spr[SPR_SDR1]) },
3185 { "sr0", offsetof(CPUPPCState, sr[0]) },
3186 { "sr1", offsetof(CPUPPCState, sr[1]) },
3187 { "sr2", offsetof(CPUPPCState, sr[2]) },
3188 { "sr3", offsetof(CPUPPCState, sr[3]) },
3189 { "sr4", offsetof(CPUPPCState, sr[4]) },
3190 { "sr5", offsetof(CPUPPCState, sr[5]) },
3191 { "sr6", offsetof(CPUPPCState, sr[6]) },
3192 { "sr7", offsetof(CPUPPCState, sr[7]) },
3193 { "sr8", offsetof(CPUPPCState, sr[8]) },
3194 { "sr9", offsetof(CPUPPCState, sr[9]) },
3195 { "sr10", offsetof(CPUPPCState, sr[10]) },
3196 { "sr11", offsetof(CPUPPCState, sr[11]) },
3197 { "sr12", offsetof(CPUPPCState, sr[12]) },
3198 { "sr13", offsetof(CPUPPCState, sr[13]) },
3199 { "sr14", offsetof(CPUPPCState, sr[14]) },
3200 { "sr15", offsetof(CPUPPCState, sr[15]) },
3201 /* Too lazy to put BATs... */
3202 { "pvr", offsetof(CPUPPCState, spr[SPR_PVR]) },
3204 { "srr0", offsetof(CPUPPCState, spr[SPR_SRR0]) },
3205 { "srr1", offsetof(CPUPPCState, spr[SPR_SRR1]) },
3206 { "dar", offsetof(CPUPPCState, spr[SPR_DAR]) },
3207 { "dsisr", offsetof(CPUPPCState, spr[SPR_DSISR]) },
3208 { "cfar", offsetof(CPUPPCState, spr[SPR_CFAR]) },
3209 { "sprg0", offsetof(CPUPPCState, spr[SPR_SPRG0]) },
3210 { "sprg1", offsetof(CPUPPCState, spr[SPR_SPRG1]) },
3211 { "sprg2", offsetof(CPUPPCState, spr[SPR_SPRG2]) },
3212 { "sprg3", offsetof(CPUPPCState, spr[SPR_SPRG3]) },
3213 { "sprg4", offsetof(CPUPPCState, spr[SPR_SPRG4]) },
3214 { "sprg5", offsetof(CPUPPCState, spr[SPR_SPRG5]) },
3215 { "sprg6", offsetof(CPUPPCState, spr[SPR_SPRG6]) },
3216 { "sprg7", offsetof(CPUPPCState, spr[SPR_SPRG7]) },
3217 { "pid", offsetof(CPUPPCState, spr[SPR_BOOKE_PID]) },
3218 { "csrr0", offsetof(CPUPPCState, spr[SPR_BOOKE_CSRR0]) },
3219 { "csrr1", offsetof(CPUPPCState, spr[SPR_BOOKE_CSRR1]) },
3220 { "esr", offsetof(CPUPPCState, spr[SPR_BOOKE_ESR]) },
3221 { "dear", offsetof(CPUPPCState, spr[SPR_BOOKE_DEAR]) },
3222 { "mcsr", offsetof(CPUPPCState, spr[SPR_BOOKE_MCSR]) },
3223 { "tsr", offsetof(CPUPPCState, spr[SPR_BOOKE_TSR]) },
3224 { "tcr", offsetof(CPUPPCState, spr[SPR_BOOKE_TCR]) },
3225 { "vrsave", offsetof(CPUPPCState, spr[SPR_VRSAVE]) },
3226 { "pir", offsetof(CPUPPCState, spr[SPR_BOOKE_PIR]) },
3227 { "mcsrr0", offsetof(CPUPPCState, spr[SPR_BOOKE_MCSRR0]) },
3228 { "mcsrr1", offsetof(CPUPPCState, spr[SPR_BOOKE_MCSRR1]) },
3229 { "decar", offsetof(CPUPPCState, spr[SPR_BOOKE_DECAR]) },
3230 { "ivpr", offsetof(CPUPPCState, spr[SPR_BOOKE_IVPR]) },
3231 { "epcr", offsetof(CPUPPCState, spr[SPR_BOOKE_EPCR]) },
3232 { "sprg8", offsetof(CPUPPCState, spr[SPR_BOOKE_SPRG8]) },
3233 { "ivor0", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR0]) },
3234 { "ivor1", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR1]) },
3235 { "ivor2", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR2]) },
3236 { "ivor3", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR3]) },
3237 { "ivor4", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR4]) },
3238 { "ivor5", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR5]) },
3239 { "ivor6", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR6]) },
3240 { "ivor7", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR7]) },
3241 { "ivor8", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR8]) },
3242 { "ivor9", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR9]) },
3243 { "ivor10", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR10]) },
3244 { "ivor11", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR11]) },
3245 { "ivor12", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR12]) },
3246 { "ivor13", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR13]) },
3247 { "ivor14", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR14]) },
3248 { "ivor15", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR15]) },
3249 { "ivor32", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR32]) },
3250 { "ivor33", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR33]) },
3251 { "ivor34", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR34]) },
3252 { "ivor35", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR35]) },
3253 { "ivor36", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR36]) },
3254 { "ivor37", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR37]) },
3255 { "mas0", offsetof(CPUPPCState, spr[SPR_BOOKE_MAS0]) },
3256 { "mas1", offsetof(CPUPPCState, spr[SPR_BOOKE_MAS1]) },
3257 { "mas2", offsetof(CPUPPCState, spr[SPR_BOOKE_MAS2]) },
3258 { "mas3", offsetof(CPUPPCState, spr[SPR_BOOKE_MAS3]) },
3259 { "mas4", offsetof(CPUPPCState, spr[SPR_BOOKE_MAS4]) },
3260 { "mas6", offsetof(CPUPPCState, spr[SPR_BOOKE_MAS6]) },
3261 { "mas7", offsetof(CPUPPCState, spr[SPR_BOOKE_MAS7]) },
3262 { "mmucfg", offsetof(CPUPPCState, spr[SPR_MMUCFG]) },
3263 { "tlb0cfg", offsetof(CPUPPCState, spr[SPR_BOOKE_TLB0CFG]) },
3264 { "tlb1cfg", offsetof(CPUPPCState, spr[SPR_BOOKE_TLB1CFG]) },
3265 { "epr", offsetof(CPUPPCState, spr[SPR_BOOKE_EPR]) },
3266 { "eplc", offsetof(CPUPPCState, spr[SPR_BOOKE_EPLC]) },
3267 { "epsc", offsetof(CPUPPCState, spr[SPR_BOOKE_EPSC]) },
3268 { "svr", offsetof(CPUPPCState, spr[SPR_E500_SVR]) },
3269 { "mcar", offsetof(CPUPPCState, spr[SPR_Exxx_MCAR]) },
3270 { "pid1", offsetof(CPUPPCState, spr[SPR_BOOKE_PID1]) },
3271 { "pid2", offsetof(CPUPPCState, spr[SPR_BOOKE_PID2]) },
3272 { "hid0", offsetof(CPUPPCState, spr[SPR_HID0]) },
3274 #elif defined(TARGET_SPARC)
3275 { "g0", offsetof(CPUSPARCState, gregs[0]) },
3276 { "g1", offsetof(CPUSPARCState, gregs[1]) },
3277 { "g2", offsetof(CPUSPARCState, gregs[2]) },
3278 { "g3", offsetof(CPUSPARCState, gregs[3]) },
3279 { "g4", offsetof(CPUSPARCState, gregs[4]) },
3280 { "g5", offsetof(CPUSPARCState, gregs[5]) },
3281 { "g6", offsetof(CPUSPARCState, gregs[6]) },
3282 { "g7", offsetof(CPUSPARCState, gregs[7]) },
3283 { "o0", 0, monitor_get_reg },
3284 { "o1", 1, monitor_get_reg },
3285 { "o2", 2, monitor_get_reg },
3286 { "o3", 3, monitor_get_reg },
3287 { "o4", 4, monitor_get_reg },
3288 { "o5", 5, monitor_get_reg },
3289 { "o6", 6, monitor_get_reg },
3290 { "o7", 7, monitor_get_reg },
3291 { "l0", 8, monitor_get_reg },
3292 { "l1", 9, monitor_get_reg },
3293 { "l2", 10, monitor_get_reg },
3294 { "l3", 11, monitor_get_reg },
3295 { "l4", 12, monitor_get_reg },
3296 { "l5", 13, monitor_get_reg },
3297 { "l6", 14, monitor_get_reg },
3298 { "l7", 15, monitor_get_reg },
3299 { "i0", 16, monitor_get_reg },
3300 { "i1", 17, monitor_get_reg },
3301 { "i2", 18, monitor_get_reg },
3302 { "i3", 19, monitor_get_reg },
3303 { "i4", 20, monitor_get_reg },
3304 { "i5", 21, monitor_get_reg },
3305 { "i6", 22, monitor_get_reg },
3306 { "i7", 23, monitor_get_reg },
3307 { "pc", offsetof(CPUSPARCState, pc) },
3308 { "npc", offsetof(CPUSPARCState, npc) },
3309 { "y", offsetof(CPUSPARCState, y) },
3310 #ifndef TARGET_SPARC64
3311 { "psr", 0, &monitor_get_psr, },
3312 { "wim", offsetof(CPUSPARCState, wim) },
3313 #endif
3314 { "tbr", offsetof(CPUSPARCState, tbr) },
3315 { "fsr", offsetof(CPUSPARCState, fsr) },
3316 { "f0", offsetof(CPUSPARCState, fpr[0].l.upper) },
3317 { "f1", offsetof(CPUSPARCState, fpr[0].l.lower) },
3318 { "f2", offsetof(CPUSPARCState, fpr[1].l.upper) },
3319 { "f3", offsetof(CPUSPARCState, fpr[1].l.lower) },
3320 { "f4", offsetof(CPUSPARCState, fpr[2].l.upper) },
3321 { "f5", offsetof(CPUSPARCState, fpr[2].l.lower) },
3322 { "f6", offsetof(CPUSPARCState, fpr[3].l.upper) },
3323 { "f7", offsetof(CPUSPARCState, fpr[3].l.lower) },
3324 { "f8", offsetof(CPUSPARCState, fpr[4].l.upper) },
3325 { "f9", offsetof(CPUSPARCState, fpr[4].l.lower) },
3326 { "f10", offsetof(CPUSPARCState, fpr[5].l.upper) },
3327 { "f11", offsetof(CPUSPARCState, fpr[5].l.lower) },
3328 { "f12", offsetof(CPUSPARCState, fpr[6].l.upper) },
3329 { "f13", offsetof(CPUSPARCState, fpr[6].l.lower) },
3330 { "f14", offsetof(CPUSPARCState, fpr[7].l.upper) },
3331 { "f15", offsetof(CPUSPARCState, fpr[7].l.lower) },
3332 { "f16", offsetof(CPUSPARCState, fpr[8].l.upper) },
3333 { "f17", offsetof(CPUSPARCState, fpr[8].l.lower) },
3334 { "f18", offsetof(CPUSPARCState, fpr[9].l.upper) },
3335 { "f19", offsetof(CPUSPARCState, fpr[9].l.lower) },
3336 { "f20", offsetof(CPUSPARCState, fpr[10].l.upper) },
3337 { "f21", offsetof(CPUSPARCState, fpr[10].l.lower) },
3338 { "f22", offsetof(CPUSPARCState, fpr[11].l.upper) },
3339 { "f23", offsetof(CPUSPARCState, fpr[11].l.lower) },
3340 { "f24", offsetof(CPUSPARCState, fpr[12].l.upper) },
3341 { "f25", offsetof(CPUSPARCState, fpr[12].l.lower) },
3342 { "f26", offsetof(CPUSPARCState, fpr[13].l.upper) },
3343 { "f27", offsetof(CPUSPARCState, fpr[13].l.lower) },
3344 { "f28", offsetof(CPUSPARCState, fpr[14].l.upper) },
3345 { "f29", offsetof(CPUSPARCState, fpr[14].l.lower) },
3346 { "f30", offsetof(CPUSPARCState, fpr[15].l.upper) },
3347 { "f31", offsetof(CPUSPARCState, fpr[15].l.lower) },
3348 #ifdef TARGET_SPARC64
3349 { "f32", offsetof(CPUSPARCState, fpr[16]) },
3350 { "f34", offsetof(CPUSPARCState, fpr[17]) },
3351 { "f36", offsetof(CPUSPARCState, fpr[18]) },
3352 { "f38", offsetof(CPUSPARCState, fpr[19]) },
3353 { "f40", offsetof(CPUSPARCState, fpr[20]) },
3354 { "f42", offsetof(CPUSPARCState, fpr[21]) },
3355 { "f44", offsetof(CPUSPARCState, fpr[22]) },
3356 { "f46", offsetof(CPUSPARCState, fpr[23]) },
3357 { "f48", offsetof(CPUSPARCState, fpr[24]) },
3358 { "f50", offsetof(CPUSPARCState, fpr[25]) },
3359 { "f52", offsetof(CPUSPARCState, fpr[26]) },
3360 { "f54", offsetof(CPUSPARCState, fpr[27]) },
3361 { "f56", offsetof(CPUSPARCState, fpr[28]) },
3362 { "f58", offsetof(CPUSPARCState, fpr[29]) },
3363 { "f60", offsetof(CPUSPARCState, fpr[30]) },
3364 { "f62", offsetof(CPUSPARCState, fpr[31]) },
3365 { "asi", offsetof(CPUSPARCState, asi) },
3366 { "pstate", offsetof(CPUSPARCState, pstate) },
3367 { "cansave", offsetof(CPUSPARCState, cansave) },
3368 { "canrestore", offsetof(CPUSPARCState, canrestore) },
3369 { "otherwin", offsetof(CPUSPARCState, otherwin) },
3370 { "wstate", offsetof(CPUSPARCState, wstate) },
3371 { "cleanwin", offsetof(CPUSPARCState, cleanwin) },
3372 { "fprs", offsetof(CPUSPARCState, fprs) },
3373 #endif
3374 #endif
3375 { NULL },
3378 static void GCC_FMT_ATTR(2, 3) QEMU_NORETURN
3379 expr_error(Monitor *mon, const char *fmt, ...)
3381 va_list ap;
3382 va_start(ap, fmt);
3383 monitor_vprintf(mon, fmt, ap);
3384 monitor_printf(mon, "\n");
3385 va_end(ap);
3386 siglongjmp(expr_env, 1);
3389 /* return 0 if OK, -1 if not found */
3390 static int get_monitor_def(target_long *pval, const char *name)
3392 const MonitorDef *md;
3393 void *ptr;
3395 for(md = monitor_defs; md->name != NULL; md++) {
3396 if (compare_cmd(name, md->name)) {
3397 if (md->get_value) {
3398 *pval = md->get_value(md, md->offset);
3399 } else {
3400 CPUArchState *env = mon_get_cpu();
3401 ptr = (uint8_t *)env + md->offset;
3402 switch(md->type) {
3403 case MD_I32:
3404 *pval = *(int32_t *)ptr;
3405 break;
3406 case MD_TLONG:
3407 *pval = *(target_long *)ptr;
3408 break;
3409 default:
3410 *pval = 0;
3411 break;
3414 return 0;
3417 return -1;
3420 static void next(void)
3422 if (*pch != '\0') {
3423 pch++;
3424 while (qemu_isspace(*pch))
3425 pch++;
3429 static int64_t expr_sum(Monitor *mon);
3431 static int64_t expr_unary(Monitor *mon)
3433 int64_t n;
3434 char *p;
3435 int ret;
3437 switch(*pch) {
3438 case '+':
3439 next();
3440 n = expr_unary(mon);
3441 break;
3442 case '-':
3443 next();
3444 n = -expr_unary(mon);
3445 break;
3446 case '~':
3447 next();
3448 n = ~expr_unary(mon);
3449 break;
3450 case '(':
3451 next();
3452 n = expr_sum(mon);
3453 if (*pch != ')') {
3454 expr_error(mon, "')' expected");
3456 next();
3457 break;
3458 case '\'':
3459 pch++;
3460 if (*pch == '\0')
3461 expr_error(mon, "character constant expected");
3462 n = *pch;
3463 pch++;
3464 if (*pch != '\'')
3465 expr_error(mon, "missing terminating \' character");
3466 next();
3467 break;
3468 case '$':
3470 char buf[128], *q;
3471 target_long reg=0;
3473 pch++;
3474 q = buf;
3475 while ((*pch >= 'a' && *pch <= 'z') ||
3476 (*pch >= 'A' && *pch <= 'Z') ||
3477 (*pch >= '0' && *pch <= '9') ||
3478 *pch == '_' || *pch == '.') {
3479 if ((q - buf) < sizeof(buf) - 1)
3480 *q++ = *pch;
3481 pch++;
3483 while (qemu_isspace(*pch))
3484 pch++;
3485 *q = 0;
3486 ret = get_monitor_def(&reg, buf);
3487 if (ret < 0)
3488 expr_error(mon, "unknown register");
3489 n = reg;
3491 break;
3492 case '\0':
3493 expr_error(mon, "unexpected end of expression");
3494 n = 0;
3495 break;
3496 default:
3497 errno = 0;
3498 n = strtoull(pch, &p, 0);
3499 if (errno == ERANGE) {
3500 expr_error(mon, "number too large");
3502 if (pch == p) {
3503 expr_error(mon, "invalid char '%c' in expression", *p);
3505 pch = p;
3506 while (qemu_isspace(*pch))
3507 pch++;
3508 break;
3510 return n;
3514 static int64_t expr_prod(Monitor *mon)
3516 int64_t val, val2;
3517 int op;
3519 val = expr_unary(mon);
3520 for(;;) {
3521 op = *pch;
3522 if (op != '*' && op != '/' && op != '%')
3523 break;
3524 next();
3525 val2 = expr_unary(mon);
3526 switch(op) {
3527 default:
3528 case '*':
3529 val *= val2;
3530 break;
3531 case '/':
3532 case '%':
3533 if (val2 == 0)
3534 expr_error(mon, "division by zero");
3535 if (op == '/')
3536 val /= val2;
3537 else
3538 val %= val2;
3539 break;
3542 return val;
3545 static int64_t expr_logic(Monitor *mon)
3547 int64_t val, val2;
3548 int op;
3550 val = expr_prod(mon);
3551 for(;;) {
3552 op = *pch;
3553 if (op != '&' && op != '|' && op != '^')
3554 break;
3555 next();
3556 val2 = expr_prod(mon);
3557 switch(op) {
3558 default:
3559 case '&':
3560 val &= val2;
3561 break;
3562 case '|':
3563 val |= val2;
3564 break;
3565 case '^':
3566 val ^= val2;
3567 break;
3570 return val;
3573 static int64_t expr_sum(Monitor *mon)
3575 int64_t val, val2;
3576 int op;
3578 val = expr_logic(mon);
3579 for(;;) {
3580 op = *pch;
3581 if (op != '+' && op != '-')
3582 break;
3583 next();
3584 val2 = expr_logic(mon);
3585 if (op == '+')
3586 val += val2;
3587 else
3588 val -= val2;
3590 return val;
3593 static int get_expr(Monitor *mon, int64_t *pval, const char **pp)
3595 pch = *pp;
3596 if (sigsetjmp(expr_env, 0)) {
3597 *pp = pch;
3598 return -1;
3600 while (qemu_isspace(*pch))
3601 pch++;
3602 *pval = expr_sum(mon);
3603 *pp = pch;
3604 return 0;
3607 static int get_double(Monitor *mon, double *pval, const char **pp)
3609 const char *p = *pp;
3610 char *tailp;
3611 double d;
3613 d = strtod(p, &tailp);
3614 if (tailp == p) {
3615 monitor_printf(mon, "Number expected\n");
3616 return -1;
3618 if (d != d || d - d != 0) {
3619 /* NaN or infinity */
3620 monitor_printf(mon, "Bad number\n");
3621 return -1;
3623 *pval = d;
3624 *pp = tailp;
3625 return 0;
3629 * Store the command-name in cmdname, and return a pointer to
3630 * the remaining of the command string.
3632 static const char *get_command_name(const char *cmdline,
3633 char *cmdname, size_t nlen)
3635 size_t len;
3636 const char *p, *pstart;
3638 p = cmdline;
3639 while (qemu_isspace(*p))
3640 p++;
3641 if (*p == '\0')
3642 return NULL;
3643 pstart = p;
3644 while (*p != '\0' && *p != '/' && !qemu_isspace(*p))
3645 p++;
3646 len = p - pstart;
3647 if (len > nlen - 1)
3648 len = nlen - 1;
3649 memcpy(cmdname, pstart, len);
3650 cmdname[len] = '\0';
3651 return p;
3655 * Read key of 'type' into 'key' and return the current
3656 * 'type' pointer.
3658 static char *key_get_info(const char *type, char **key)
3660 size_t len;
3661 char *p, *str;
3663 if (*type == ',')
3664 type++;
3666 p = strchr(type, ':');
3667 if (!p) {
3668 *key = NULL;
3669 return NULL;
3671 len = p - type;
3673 str = g_malloc(len + 1);
3674 memcpy(str, type, len);
3675 str[len] = '\0';
3677 *key = str;
3678 return ++p;
3681 static int default_fmt_format = 'x';
3682 static int default_fmt_size = 4;
3684 static int is_valid_option(const char *c, const char *typestr)
3686 char option[3];
3688 option[0] = '-';
3689 option[1] = *c;
3690 option[2] = '\0';
3692 typestr = strstr(typestr, option);
3693 return (typestr != NULL);
3696 static const mon_cmd_t *search_dispatch_table(const mon_cmd_t *disp_table,
3697 const char *cmdname)
3699 const mon_cmd_t *cmd;
3701 for (cmd = disp_table; cmd->name != NULL; cmd++) {
3702 if (compare_cmd(cmdname, cmd->name)) {
3703 return cmd;
3707 return NULL;
3710 static const mon_cmd_t *qmp_find_cmd(const char *cmdname)
3712 return search_dispatch_table(qmp_cmds, cmdname);
3716 * Parse @cmdline according to command table @table.
3717 * If @cmdline is blank, return NULL.
3718 * If it can't be parsed, report to @mon, and return NULL.
3719 * Else, insert command arguments into @qdict, and return the command.
3720 * If a sub-command table exists, and if @cmdline contains an additional string
3721 * for a sub-command, this function will try to search the sub-command table.
3722 * If no additional string for a sub-command is present, this function will
3723 * return the command found in @table.
3724 * Do not assume the returned command points into @table! It doesn't
3725 * when the command is a sub-command.
3727 static const mon_cmd_t *monitor_parse_command(Monitor *mon,
3728 const char *cmdline,
3729 int start,
3730 mon_cmd_t *table,
3731 QDict *qdict)
3733 const char *p, *typestr;
3734 int c;
3735 const mon_cmd_t *cmd;
3736 char cmdname[256];
3737 char buf[1024];
3738 char *key;
3740 #ifdef DEBUG
3741 monitor_printf(mon, "command='%s', start='%d'\n", cmdline, start);
3742 #endif
3744 /* extract the command name */
3745 p = get_command_name(cmdline + start, cmdname, sizeof(cmdname));
3746 if (!p)
3747 return NULL;
3749 cmd = search_dispatch_table(table, cmdname);
3750 if (!cmd) {
3751 monitor_printf(mon, "unknown command: '%.*s'\n",
3752 (int)(p - cmdline), cmdline);
3753 return NULL;
3756 /* filter out following useless space */
3757 while (qemu_isspace(*p)) {
3758 p++;
3760 /* search sub command */
3761 if (cmd->sub_table != NULL) {
3762 /* check if user set additional command */
3763 if (*p == '\0') {
3764 return cmd;
3766 return monitor_parse_command(mon, cmdline, p - cmdline,
3767 cmd->sub_table, qdict);
3770 /* parse the parameters */
3771 typestr = cmd->args_type;
3772 for(;;) {
3773 typestr = key_get_info(typestr, &key);
3774 if (!typestr)
3775 break;
3776 c = *typestr;
3777 typestr++;
3778 switch(c) {
3779 case 'F':
3780 case 'B':
3781 case 's':
3783 int ret;
3785 while (qemu_isspace(*p))
3786 p++;
3787 if (*typestr == '?') {
3788 typestr++;
3789 if (*p == '\0') {
3790 /* no optional string: NULL argument */
3791 break;
3794 ret = get_str(buf, sizeof(buf), &p);
3795 if (ret < 0) {
3796 switch(c) {
3797 case 'F':
3798 monitor_printf(mon, "%s: filename expected\n",
3799 cmdname);
3800 break;
3801 case 'B':
3802 monitor_printf(mon, "%s: block device name expected\n",
3803 cmdname);
3804 break;
3805 default:
3806 monitor_printf(mon, "%s: string expected\n", cmdname);
3807 break;
3809 goto fail;
3811 qdict_put(qdict, key, qstring_from_str(buf));
3813 break;
3814 case 'O':
3816 QemuOptsList *opts_list;
3817 QemuOpts *opts;
3819 opts_list = qemu_find_opts(key);
3820 if (!opts_list || opts_list->desc->name) {
3821 goto bad_type;
3823 while (qemu_isspace(*p)) {
3824 p++;
3826 if (!*p)
3827 break;
3828 if (get_str(buf, sizeof(buf), &p) < 0) {
3829 goto fail;
3831 opts = qemu_opts_parse(opts_list, buf, 1);
3832 if (!opts) {
3833 goto fail;
3835 qemu_opts_to_qdict(opts, qdict);
3836 qemu_opts_del(opts);
3838 break;
3839 case '/':
3841 int count, format, size;
3843 while (qemu_isspace(*p))
3844 p++;
3845 if (*p == '/') {
3846 /* format found */
3847 p++;
3848 count = 1;
3849 if (qemu_isdigit(*p)) {
3850 count = 0;
3851 while (qemu_isdigit(*p)) {
3852 count = count * 10 + (*p - '0');
3853 p++;
3856 size = -1;
3857 format = -1;
3858 for(;;) {
3859 switch(*p) {
3860 case 'o':
3861 case 'd':
3862 case 'u':
3863 case 'x':
3864 case 'i':
3865 case 'c':
3866 format = *p++;
3867 break;
3868 case 'b':
3869 size = 1;
3870 p++;
3871 break;
3872 case 'h':
3873 size = 2;
3874 p++;
3875 break;
3876 case 'w':
3877 size = 4;
3878 p++;
3879 break;
3880 case 'g':
3881 case 'L':
3882 size = 8;
3883 p++;
3884 break;
3885 default:
3886 goto next;
3889 next:
3890 if (*p != '\0' && !qemu_isspace(*p)) {
3891 monitor_printf(mon, "invalid char in format: '%c'\n",
3892 *p);
3893 goto fail;
3895 if (format < 0)
3896 format = default_fmt_format;
3897 if (format != 'i') {
3898 /* for 'i', not specifying a size gives -1 as size */
3899 if (size < 0)
3900 size = default_fmt_size;
3901 default_fmt_size = size;
3903 default_fmt_format = format;
3904 } else {
3905 count = 1;
3906 format = default_fmt_format;
3907 if (format != 'i') {
3908 size = default_fmt_size;
3909 } else {
3910 size = -1;
3913 qdict_put(qdict, "count", qint_from_int(count));
3914 qdict_put(qdict, "format", qint_from_int(format));
3915 qdict_put(qdict, "size", qint_from_int(size));
3917 break;
3918 case 'i':
3919 case 'l':
3920 case 'M':
3922 int64_t val;
3924 while (qemu_isspace(*p))
3925 p++;
3926 if (*typestr == '?' || *typestr == '.') {
3927 if (*typestr == '?') {
3928 if (*p == '\0') {
3929 typestr++;
3930 break;
3932 } else {
3933 if (*p == '.') {
3934 p++;
3935 while (qemu_isspace(*p))
3936 p++;
3937 } else {
3938 typestr++;
3939 break;
3942 typestr++;
3944 if (get_expr(mon, &val, &p))
3945 goto fail;
3946 /* Check if 'i' is greater than 32-bit */
3947 if ((c == 'i') && ((val >> 32) & 0xffffffff)) {
3948 monitor_printf(mon, "\'%s\' has failed: ", cmdname);
3949 monitor_printf(mon, "integer is for 32-bit values\n");
3950 goto fail;
3951 } else if (c == 'M') {
3952 if (val < 0) {
3953 monitor_printf(mon, "enter a positive value\n");
3954 goto fail;
3956 val <<= 20;
3958 qdict_put(qdict, key, qint_from_int(val));
3960 break;
3961 case 'o':
3963 int64_t val;
3964 char *end;
3966 while (qemu_isspace(*p)) {
3967 p++;
3969 if (*typestr == '?') {
3970 typestr++;
3971 if (*p == '\0') {
3972 break;
3975 val = strtosz(p, &end);
3976 if (val < 0) {
3977 monitor_printf(mon, "invalid size\n");
3978 goto fail;
3980 qdict_put(qdict, key, qint_from_int(val));
3981 p = end;
3983 break;
3984 case 'T':
3986 double val;
3988 while (qemu_isspace(*p))
3989 p++;
3990 if (*typestr == '?') {
3991 typestr++;
3992 if (*p == '\0') {
3993 break;
3996 if (get_double(mon, &val, &p) < 0) {
3997 goto fail;
3999 if (p[0] && p[1] == 's') {
4000 switch (*p) {
4001 case 'm':
4002 val /= 1e3; p += 2; break;
4003 case 'u':
4004 val /= 1e6; p += 2; break;
4005 case 'n':
4006 val /= 1e9; p += 2; break;
4009 if (*p && !qemu_isspace(*p)) {
4010 monitor_printf(mon, "Unknown unit suffix\n");
4011 goto fail;
4013 qdict_put(qdict, key, qfloat_from_double(val));
4015 break;
4016 case 'b':
4018 const char *beg;
4019 int val;
4021 while (qemu_isspace(*p)) {
4022 p++;
4024 beg = p;
4025 while (qemu_isgraph(*p)) {
4026 p++;
4028 if (p - beg == 2 && !memcmp(beg, "on", p - beg)) {
4029 val = 1;
4030 } else if (p - beg == 3 && !memcmp(beg, "off", p - beg)) {
4031 val = 0;
4032 } else {
4033 monitor_printf(mon, "Expected 'on' or 'off'\n");
4034 goto fail;
4036 qdict_put(qdict, key, qbool_from_int(val));
4038 break;
4039 case '-':
4041 const char *tmp = p;
4042 int skip_key = 0;
4043 /* option */
4045 c = *typestr++;
4046 if (c == '\0')
4047 goto bad_type;
4048 while (qemu_isspace(*p))
4049 p++;
4050 if (*p == '-') {
4051 p++;
4052 if(c != *p) {
4053 if(!is_valid_option(p, typestr)) {
4055 monitor_printf(mon, "%s: unsupported option -%c\n",
4056 cmdname, *p);
4057 goto fail;
4058 } else {
4059 skip_key = 1;
4062 if(skip_key) {
4063 p = tmp;
4064 } else {
4065 /* has option */
4066 p++;
4067 qdict_put(qdict, key, qbool_from_int(1));
4071 break;
4072 case 'S':
4074 /* package all remaining string */
4075 int len;
4077 while (qemu_isspace(*p)) {
4078 p++;
4080 if (*typestr == '?') {
4081 typestr++;
4082 if (*p == '\0') {
4083 /* no remaining string: NULL argument */
4084 break;
4087 len = strlen(p);
4088 if (len <= 0) {
4089 monitor_printf(mon, "%s: string expected\n",
4090 cmdname);
4091 break;
4093 qdict_put(qdict, key, qstring_from_str(p));
4094 p += len;
4096 break;
4097 default:
4098 bad_type:
4099 monitor_printf(mon, "%s: unknown type '%c'\n", cmdname, c);
4100 goto fail;
4102 g_free(key);
4103 key = NULL;
4105 /* check that all arguments were parsed */
4106 while (qemu_isspace(*p))
4107 p++;
4108 if (*p != '\0') {
4109 monitor_printf(mon, "%s: extraneous characters at the end of line\n",
4110 cmdname);
4111 goto fail;
4114 return cmd;
4116 fail:
4117 g_free(key);
4118 return NULL;
4121 void monitor_set_error(Monitor *mon, QError *qerror)
4123 /* report only the first error */
4124 if (!mon->error) {
4125 mon->error = qerror;
4126 } else {
4127 QDECREF(qerror);
4131 static void handler_audit(Monitor *mon, const mon_cmd_t *cmd, int ret)
4133 if (ret && !monitor_has_error(mon)) {
4135 * If it returns failure, it must have passed on error.
4137 * Action: Report an internal error to the client if in QMP.
4139 qerror_report(QERR_UNDEFINED_ERROR);
4143 static void handle_user_command(Monitor *mon, const char *cmdline)
4145 QDict *qdict;
4146 const mon_cmd_t *cmd;
4148 qdict = qdict_new();
4150 cmd = monitor_parse_command(mon, cmdline, 0, mon->cmd_table, qdict);
4151 if (!cmd)
4152 goto out;
4154 if (handler_is_async(cmd)) {
4155 user_async_cmd_handler(mon, cmd, qdict);
4156 } else if (handler_is_qobject(cmd)) {
4157 QObject *data = NULL;
4159 /* XXX: ignores the error code */
4160 cmd->mhandler.cmd_new(mon, qdict, &data);
4161 assert(!monitor_has_error(mon));
4162 if (data) {
4163 cmd->user_print(mon, data);
4164 qobject_decref(data);
4166 } else {
4167 cmd->mhandler.cmd(mon, qdict);
4170 out:
4171 QDECREF(qdict);
4174 static void cmd_completion(Monitor *mon, const char *name, const char *list)
4176 const char *p, *pstart;
4177 char cmd[128];
4178 int len;
4180 p = list;
4181 for(;;) {
4182 pstart = p;
4183 p = strchr(p, '|');
4184 if (!p)
4185 p = pstart + strlen(pstart);
4186 len = p - pstart;
4187 if (len > sizeof(cmd) - 2)
4188 len = sizeof(cmd) - 2;
4189 memcpy(cmd, pstart, len);
4190 cmd[len] = '\0';
4191 if (name[0] == '\0' || !strncmp(name, cmd, strlen(name))) {
4192 readline_add_completion(mon->rs, cmd);
4194 if (*p == '\0')
4195 break;
4196 p++;
4200 static void file_completion(Monitor *mon, const char *input)
4202 DIR *ffs;
4203 struct dirent *d;
4204 char path[1024];
4205 char file[1024], file_prefix[1024];
4206 int input_path_len;
4207 const char *p;
4209 p = strrchr(input, '/');
4210 if (!p) {
4211 input_path_len = 0;
4212 pstrcpy(file_prefix, sizeof(file_prefix), input);
4213 pstrcpy(path, sizeof(path), ".");
4214 } else {
4215 input_path_len = p - input + 1;
4216 memcpy(path, input, input_path_len);
4217 if (input_path_len > sizeof(path) - 1)
4218 input_path_len = sizeof(path) - 1;
4219 path[input_path_len] = '\0';
4220 pstrcpy(file_prefix, sizeof(file_prefix), p + 1);
4222 #ifdef DEBUG_COMPLETION
4223 monitor_printf(mon, "input='%s' path='%s' prefix='%s'\n",
4224 input, path, file_prefix);
4225 #endif
4226 ffs = opendir(path);
4227 if (!ffs)
4228 return;
4229 for(;;) {
4230 struct stat sb;
4231 d = readdir(ffs);
4232 if (!d)
4233 break;
4235 if (strcmp(d->d_name, ".") == 0 || strcmp(d->d_name, "..") == 0) {
4236 continue;
4239 if (strstart(d->d_name, file_prefix, NULL)) {
4240 memcpy(file, input, input_path_len);
4241 if (input_path_len < sizeof(file))
4242 pstrcpy(file + input_path_len, sizeof(file) - input_path_len,
4243 d->d_name);
4244 /* stat the file to find out if it's a directory.
4245 * In that case add a slash to speed up typing long paths
4247 if (stat(file, &sb) == 0 && S_ISDIR(sb.st_mode)) {
4248 pstrcat(file, sizeof(file), "/");
4250 readline_add_completion(mon->rs, file);
4253 closedir(ffs);
4256 typedef struct MonitorBlockComplete {
4257 Monitor *mon;
4258 const char *input;
4259 } MonitorBlockComplete;
4261 static void block_completion_it(void *opaque, BlockDriverState *bs)
4263 const char *name = bdrv_get_device_name(bs);
4264 MonitorBlockComplete *mbc = opaque;
4265 Monitor *mon = mbc->mon;
4266 const char *input = mbc->input;
4268 if (input[0] == '\0' ||
4269 !strncmp(name, (char *)input, strlen(input))) {
4270 readline_add_completion(mon->rs, name);
4274 static const char *next_arg_type(const char *typestr)
4276 const char *p = strchr(typestr, ':');
4277 return (p != NULL ? ++p : typestr);
4280 static void device_add_completion(ReadLineState *rs, const char *str)
4282 GSList *list, *elt;
4283 size_t len;
4285 len = strlen(str);
4286 readline_set_completion_index(rs, len);
4287 list = elt = object_class_get_list(TYPE_DEVICE, false);
4288 while (elt) {
4289 const char *name;
4290 DeviceClass *dc = OBJECT_CLASS_CHECK(DeviceClass, elt->data,
4291 TYPE_DEVICE);
4292 name = object_class_get_name(OBJECT_CLASS(dc));
4293 if (!strncmp(name, str, len)) {
4294 readline_add_completion(rs, name);
4296 elt = elt->next;
4298 g_slist_free(list);
4301 static void object_add_completion(ReadLineState *rs, const char *str)
4303 GSList *list, *elt;
4304 size_t len;
4306 len = strlen(str);
4307 readline_set_completion_index(rs, len);
4308 list = elt = object_class_get_list(TYPE_USER_CREATABLE, false);
4309 while (elt) {
4310 const char *name;
4312 name = object_class_get_name(OBJECT_CLASS(elt->data));
4313 if (!strncmp(name, str, len) && strcmp(name, TYPE_USER_CREATABLE)) {
4314 readline_add_completion(rs, name);
4316 elt = elt->next;
4318 g_slist_free(list);
4321 static void device_del_completion(ReadLineState *rs, BusState *bus,
4322 const char *str, size_t len)
4324 BusChild *kid;
4326 QTAILQ_FOREACH(kid, &bus->children, sibling) {
4327 DeviceState *dev = kid->child;
4328 BusState *dev_child;
4330 if (dev->id && !strncmp(str, dev->id, len)) {
4331 readline_add_completion(rs, dev->id);
4334 QLIST_FOREACH(dev_child, &dev->child_bus, sibling) {
4335 device_del_completion(rs, dev_child, str, len);
4340 static void object_del_completion(ReadLineState *rs, const char *str)
4342 ObjectPropertyInfoList *list, *start;
4343 size_t len;
4345 len = strlen(str);
4346 readline_set_completion_index(rs, len);
4348 start = list = qmp_qom_list("/objects", NULL);
4349 while (list) {
4350 ObjectPropertyInfo *info = list->value;
4352 if (!strncmp(info->type, "child<", 5)
4353 && !strncmp(info->name, str, len)) {
4354 readline_add_completion(rs, info->name);
4356 list = list->next;
4358 qapi_free_ObjectPropertyInfoList(start);
4361 static void monitor_find_completion_by_table(Monitor *mon,
4362 const mon_cmd_t *cmd_table,
4363 char **args,
4364 int nb_args)
4366 const char *cmdname;
4367 int i;
4368 const char *ptype, *str;
4369 const mon_cmd_t *cmd;
4370 MonitorBlockComplete mbs;
4372 if (nb_args <= 1) {
4373 /* command completion */
4374 if (nb_args == 0)
4375 cmdname = "";
4376 else
4377 cmdname = args[0];
4378 readline_set_completion_index(mon->rs, strlen(cmdname));
4379 for (cmd = cmd_table; cmd->name != NULL; cmd++) {
4380 cmd_completion(mon, cmdname, cmd->name);
4382 } else {
4383 /* find the command */
4384 for (cmd = cmd_table; cmd->name != NULL; cmd++) {
4385 if (compare_cmd(args[0], cmd->name)) {
4386 break;
4389 if (!cmd->name) {
4390 return;
4393 if (cmd->sub_table) {
4394 /* do the job again */
4395 return monitor_find_completion_by_table(mon, cmd->sub_table,
4396 &args[1], nb_args - 1);
4399 ptype = next_arg_type(cmd->args_type);
4400 for(i = 0; i < nb_args - 2; i++) {
4401 if (*ptype != '\0') {
4402 ptype = next_arg_type(ptype);
4403 while (*ptype == '?')
4404 ptype = next_arg_type(ptype);
4407 str = args[nb_args - 1];
4408 if (*ptype == '-' && ptype[1] != '\0') {
4409 ptype = next_arg_type(ptype);
4411 switch(*ptype) {
4412 case 'F':
4413 /* file completion */
4414 readline_set_completion_index(mon->rs, strlen(str));
4415 file_completion(mon, str);
4416 break;
4417 case 'B':
4418 /* block device name completion */
4419 mbs.mon = mon;
4420 mbs.input = str;
4421 readline_set_completion_index(mon->rs, strlen(str));
4422 bdrv_iterate(block_completion_it, &mbs);
4423 break;
4424 case 'O':
4425 if (!strcmp(cmd->name, "device_add") && nb_args == 2) {
4426 device_add_completion(mon->rs, str);
4427 } else if (!strcmp(cmd->name, "object_add") && nb_args == 2) {
4428 object_add_completion(mon->rs, str);
4430 break;
4431 case 's':
4432 case 'S':
4433 if (!strcmp(cmd->name, "sendkey")) {
4434 char *sep = strrchr(str, '-');
4435 if (sep)
4436 str = sep + 1;
4437 readline_set_completion_index(mon->rs, strlen(str));
4438 for (i = 0; i < Q_KEY_CODE_MAX; i++) {
4439 cmd_completion(mon, str, QKeyCode_lookup[i]);
4441 } else if (!strcmp(cmd->name, "help|?")) {
4442 monitor_find_completion_by_table(mon, cmd_table,
4443 &args[1], nb_args - 1);
4444 } else if (!strcmp(cmd->name, "device_del") && nb_args == 2) {
4445 size_t len = strlen(str);
4446 readline_set_completion_index(mon->rs, len);
4447 device_del_completion(mon->rs, sysbus_get_default(), str, len);
4448 } else if (!strcmp(cmd->name, "object_del") && nb_args == 2) {
4449 object_del_completion(mon->rs, str);
4451 break;
4452 default:
4453 break;
4458 static void monitor_find_completion(void *opaque,
4459 const char *cmdline)
4461 Monitor *mon = opaque;
4462 char *args[MAX_ARGS];
4463 int nb_args, len;
4465 /* 1. parse the cmdline */
4466 if (parse_cmdline(cmdline, &nb_args, args) < 0) {
4467 return;
4469 #ifdef DEBUG_COMPLETION
4470 for (i = 0; i < nb_args; i++) {
4471 monitor_printf(mon, "arg%d = '%s'\n", i, args[i]);
4473 #endif
4475 /* if the line ends with a space, it means we want to complete the
4476 next arg */
4477 len = strlen(cmdline);
4478 if (len > 0 && qemu_isspace(cmdline[len - 1])) {
4479 if (nb_args >= MAX_ARGS) {
4480 goto cleanup;
4482 args[nb_args++] = g_strdup("");
4485 /* 2. auto complete according to args */
4486 monitor_find_completion_by_table(mon, mon->cmd_table, args, nb_args);
4488 cleanup:
4489 free_cmdline_args(args, nb_args);
4492 static int monitor_can_read(void *opaque)
4494 Monitor *mon = opaque;
4496 return (mon->suspend_cnt == 0) ? 1 : 0;
4499 static int invalid_qmp_mode(const Monitor *mon, const char *cmd_name)
4501 int is_cap = compare_cmd(cmd_name, "qmp_capabilities");
4502 return (qmp_cmd_mode(mon) ? is_cap : !is_cap);
4506 * Argument validation rules:
4508 * 1. The argument must exist in cmd_args qdict
4509 * 2. The argument type must be the expected one
4511 * Special case: If the argument doesn't exist in cmd_args and
4512 * the QMP_ACCEPT_UNKNOWNS flag is set, then the
4513 * checking is skipped for it.
4515 static int check_client_args_type(const QDict *client_args,
4516 const QDict *cmd_args, int flags)
4518 const QDictEntry *ent;
4520 for (ent = qdict_first(client_args); ent;ent = qdict_next(client_args,ent)){
4521 QObject *obj;
4522 QString *arg_type;
4523 const QObject *client_arg = qdict_entry_value(ent);
4524 const char *client_arg_name = qdict_entry_key(ent);
4526 obj = qdict_get(cmd_args, client_arg_name);
4527 if (!obj) {
4528 if (flags & QMP_ACCEPT_UNKNOWNS) {
4529 /* handler accepts unknowns */
4530 continue;
4532 /* client arg doesn't exist */
4533 qerror_report(QERR_INVALID_PARAMETER, client_arg_name);
4534 return -1;
4537 arg_type = qobject_to_qstring(obj);
4538 assert(arg_type != NULL);
4540 /* check if argument's type is correct */
4541 switch (qstring_get_str(arg_type)[0]) {
4542 case 'F':
4543 case 'B':
4544 case 's':
4545 if (qobject_type(client_arg) != QTYPE_QSTRING) {
4546 qerror_report(QERR_INVALID_PARAMETER_TYPE, client_arg_name,
4547 "string");
4548 return -1;
4550 break;
4551 case 'i':
4552 case 'l':
4553 case 'M':
4554 case 'o':
4555 if (qobject_type(client_arg) != QTYPE_QINT) {
4556 qerror_report(QERR_INVALID_PARAMETER_TYPE, client_arg_name,
4557 "int");
4558 return -1;
4560 break;
4561 case 'T':
4562 if (qobject_type(client_arg) != QTYPE_QINT &&
4563 qobject_type(client_arg) != QTYPE_QFLOAT) {
4564 qerror_report(QERR_INVALID_PARAMETER_TYPE, client_arg_name,
4565 "number");
4566 return -1;
4568 break;
4569 case 'b':
4570 case '-':
4571 if (qobject_type(client_arg) != QTYPE_QBOOL) {
4572 qerror_report(QERR_INVALID_PARAMETER_TYPE, client_arg_name,
4573 "bool");
4574 return -1;
4576 break;
4577 case 'O':
4578 assert(flags & QMP_ACCEPT_UNKNOWNS);
4579 break;
4580 case 'q':
4581 /* Any QObject can be passed. */
4582 break;
4583 case '/':
4584 case '.':
4586 * These types are not supported by QMP and thus are not
4587 * handled here. Fall through.
4589 default:
4590 abort();
4594 return 0;
4598 * - Check if the client has passed all mandatory args
4599 * - Set special flags for argument validation
4601 static int check_mandatory_args(const QDict *cmd_args,
4602 const QDict *client_args, int *flags)
4604 const QDictEntry *ent;
4606 for (ent = qdict_first(cmd_args); ent; ent = qdict_next(cmd_args, ent)) {
4607 const char *cmd_arg_name = qdict_entry_key(ent);
4608 QString *type = qobject_to_qstring(qdict_entry_value(ent));
4609 assert(type != NULL);
4611 if (qstring_get_str(type)[0] == 'O') {
4612 assert((*flags & QMP_ACCEPT_UNKNOWNS) == 0);
4613 *flags |= QMP_ACCEPT_UNKNOWNS;
4614 } else if (qstring_get_str(type)[0] != '-' &&
4615 qstring_get_str(type)[1] != '?' &&
4616 !qdict_haskey(client_args, cmd_arg_name)) {
4617 qerror_report(QERR_MISSING_PARAMETER, cmd_arg_name);
4618 return -1;
4622 return 0;
4625 static QDict *qdict_from_args_type(const char *args_type)
4627 int i;
4628 QDict *qdict;
4629 QString *key, *type, *cur_qs;
4631 assert(args_type != NULL);
4633 qdict = qdict_new();
4635 if (args_type == NULL || args_type[0] == '\0') {
4636 /* no args, empty qdict */
4637 goto out;
4640 key = qstring_new();
4641 type = qstring_new();
4643 cur_qs = key;
4645 for (i = 0;; i++) {
4646 switch (args_type[i]) {
4647 case ',':
4648 case '\0':
4649 qdict_put(qdict, qstring_get_str(key), type);
4650 QDECREF(key);
4651 if (args_type[i] == '\0') {
4652 goto out;
4654 type = qstring_new(); /* qdict has ref */
4655 cur_qs = key = qstring_new();
4656 break;
4657 case ':':
4658 cur_qs = type;
4659 break;
4660 default:
4661 qstring_append_chr(cur_qs, args_type[i]);
4662 break;
4666 out:
4667 return qdict;
4671 * Client argument checking rules:
4673 * 1. Client must provide all mandatory arguments
4674 * 2. Each argument provided by the client must be expected
4675 * 3. Each argument provided by the client must have the type expected
4676 * by the command
4678 static int qmp_check_client_args(const mon_cmd_t *cmd, QDict *client_args)
4680 int flags, err;
4681 QDict *cmd_args;
4683 cmd_args = qdict_from_args_type(cmd->args_type);
4685 flags = 0;
4686 err = check_mandatory_args(cmd_args, client_args, &flags);
4687 if (err) {
4688 goto out;
4691 err = check_client_args_type(client_args, cmd_args, flags);
4693 out:
4694 QDECREF(cmd_args);
4695 return err;
4699 * Input object checking rules
4701 * 1. Input object must be a dict
4702 * 2. The "execute" key must exist
4703 * 3. The "execute" key must be a string
4704 * 4. If the "arguments" key exists, it must be a dict
4705 * 5. If the "id" key exists, it can be anything (ie. json-value)
4706 * 6. Any argument not listed above is considered invalid
4708 static QDict *qmp_check_input_obj(QObject *input_obj)
4710 const QDictEntry *ent;
4711 int has_exec_key = 0;
4712 QDict *input_dict;
4714 if (qobject_type(input_obj) != QTYPE_QDICT) {
4715 qerror_report(QERR_QMP_BAD_INPUT_OBJECT, "object");
4716 return NULL;
4719 input_dict = qobject_to_qdict(input_obj);
4721 for (ent = qdict_first(input_dict); ent; ent = qdict_next(input_dict, ent)){
4722 const char *arg_name = qdict_entry_key(ent);
4723 const QObject *arg_obj = qdict_entry_value(ent);
4725 if (!strcmp(arg_name, "execute")) {
4726 if (qobject_type(arg_obj) != QTYPE_QSTRING) {
4727 qerror_report(QERR_QMP_BAD_INPUT_OBJECT_MEMBER, "execute",
4728 "string");
4729 return NULL;
4731 has_exec_key = 1;
4732 } else if (!strcmp(arg_name, "arguments")) {
4733 if (qobject_type(arg_obj) != QTYPE_QDICT) {
4734 qerror_report(QERR_QMP_BAD_INPUT_OBJECT_MEMBER, "arguments",
4735 "object");
4736 return NULL;
4738 } else if (!strcmp(arg_name, "id")) {
4739 /* FIXME: check duplicated IDs for async commands */
4740 } else {
4741 qerror_report(QERR_QMP_EXTRA_MEMBER, arg_name);
4742 return NULL;
4746 if (!has_exec_key) {
4747 qerror_report(QERR_QMP_BAD_INPUT_OBJECT, "execute");
4748 return NULL;
4751 return input_dict;
4754 static void qmp_call_cmd(Monitor *mon, const mon_cmd_t *cmd,
4755 const QDict *params)
4757 int ret;
4758 QObject *data = NULL;
4760 ret = cmd->mhandler.cmd_new(mon, params, &data);
4761 handler_audit(mon, cmd, ret);
4762 monitor_protocol_emitter(mon, data);
4763 qobject_decref(data);
4766 static void handle_qmp_command(JSONMessageParser *parser, QList *tokens)
4768 int err;
4769 QObject *obj;
4770 QDict *input, *args;
4771 const mon_cmd_t *cmd;
4772 const char *cmd_name;
4773 Monitor *mon = cur_mon;
4775 args = input = NULL;
4777 obj = json_parser_parse(tokens, NULL);
4778 if (!obj) {
4779 // FIXME: should be triggered in json_parser_parse()
4780 qerror_report(QERR_JSON_PARSING);
4781 goto err_out;
4784 input = qmp_check_input_obj(obj);
4785 if (!input) {
4786 qobject_decref(obj);
4787 goto err_out;
4790 mon->mc->id = qdict_get(input, "id");
4791 qobject_incref(mon->mc->id);
4793 cmd_name = qdict_get_str(input, "execute");
4794 trace_handle_qmp_command(mon, cmd_name);
4795 if (invalid_qmp_mode(mon, cmd_name)) {
4796 qerror_report(QERR_COMMAND_NOT_FOUND, cmd_name);
4797 goto err_out;
4800 cmd = qmp_find_cmd(cmd_name);
4801 if (!cmd) {
4802 qerror_report(QERR_COMMAND_NOT_FOUND, cmd_name);
4803 goto err_out;
4806 obj = qdict_get(input, "arguments");
4807 if (!obj) {
4808 args = qdict_new();
4809 } else {
4810 args = qobject_to_qdict(obj);
4811 QINCREF(args);
4814 err = qmp_check_client_args(cmd, args);
4815 if (err < 0) {
4816 goto err_out;
4819 if (handler_is_async(cmd)) {
4820 err = qmp_async_cmd_handler(mon, cmd, args);
4821 if (err) {
4822 /* emit the error response */
4823 goto err_out;
4825 } else {
4826 qmp_call_cmd(mon, cmd, args);
4829 goto out;
4831 err_out:
4832 monitor_protocol_emitter(mon, NULL);
4833 out:
4834 QDECREF(input);
4835 QDECREF(args);
4839 * monitor_control_read(): Read and handle QMP input
4841 static void monitor_control_read(void *opaque, const uint8_t *buf, int size)
4843 Monitor *old_mon = cur_mon;
4845 cur_mon = opaque;
4847 json_message_parser_feed(&cur_mon->mc->parser, (const char *) buf, size);
4849 cur_mon = old_mon;
4852 static void monitor_read(void *opaque, const uint8_t *buf, int size)
4854 Monitor *old_mon = cur_mon;
4855 int i;
4857 cur_mon = opaque;
4859 if (cur_mon->rs) {
4860 for (i = 0; i < size; i++)
4861 readline_handle_byte(cur_mon->rs, buf[i]);
4862 } else {
4863 if (size == 0 || buf[size - 1] != 0)
4864 monitor_printf(cur_mon, "corrupted command\n");
4865 else
4866 handle_user_command(cur_mon, (char *)buf);
4869 cur_mon = old_mon;
4872 static void monitor_command_cb(void *opaque, const char *cmdline,
4873 void *readline_opaque)
4875 Monitor *mon = opaque;
4877 monitor_suspend(mon);
4878 handle_user_command(mon, cmdline);
4879 monitor_resume(mon);
4882 int monitor_suspend(Monitor *mon)
4884 if (!mon->rs)
4885 return -ENOTTY;
4886 mon->suspend_cnt++;
4887 return 0;
4890 void monitor_resume(Monitor *mon)
4892 if (!mon->rs)
4893 return;
4894 if (--mon->suspend_cnt == 0)
4895 readline_show_prompt(mon->rs);
4898 static QObject *get_qmp_greeting(void)
4900 QObject *ver = NULL;
4902 qmp_marshal_input_query_version(NULL, NULL, &ver);
4903 return qobject_from_jsonf("{'QMP':{'version': %p,'capabilities': []}}",ver);
4907 * monitor_control_event(): Print QMP gretting
4909 static void monitor_control_event(void *opaque, int event)
4911 QObject *data;
4912 Monitor *mon = opaque;
4914 switch (event) {
4915 case CHR_EVENT_OPENED:
4916 mon->mc->command_mode = 0;
4917 data = get_qmp_greeting();
4918 monitor_json_emitter(mon, data);
4919 qobject_decref(data);
4920 mon_refcount++;
4921 break;
4922 case CHR_EVENT_CLOSED:
4923 json_message_parser_destroy(&mon->mc->parser);
4924 json_message_parser_init(&mon->mc->parser, handle_qmp_command);
4925 mon_refcount--;
4926 monitor_fdsets_cleanup();
4927 break;
4931 static void monitor_event(void *opaque, int event)
4933 Monitor *mon = opaque;
4935 switch (event) {
4936 case CHR_EVENT_MUX_IN:
4937 mon->mux_out = 0;
4938 if (mon->reset_seen) {
4939 readline_restart(mon->rs);
4940 monitor_resume(mon);
4941 monitor_flush(mon);
4942 } else {
4943 mon->suspend_cnt = 0;
4945 break;
4947 case CHR_EVENT_MUX_OUT:
4948 if (mon->reset_seen) {
4949 if (mon->suspend_cnt == 0) {
4950 monitor_printf(mon, "\n");
4952 monitor_flush(mon);
4953 monitor_suspend(mon);
4954 } else {
4955 mon->suspend_cnt++;
4957 mon->mux_out = 1;
4958 break;
4960 case CHR_EVENT_OPENED:
4961 monitor_printf(mon, "QEMU %s monitor - type 'help' for more "
4962 "information\n", QEMU_VERSION);
4963 if (!mon->mux_out) {
4964 readline_show_prompt(mon->rs);
4966 mon->reset_seen = 1;
4967 mon_refcount++;
4968 break;
4970 case CHR_EVENT_CLOSED:
4971 mon_refcount--;
4972 monitor_fdsets_cleanup();
4973 break;
4977 static int
4978 compare_mon_cmd(const void *a, const void *b)
4980 return strcmp(((const mon_cmd_t *)a)->name,
4981 ((const mon_cmd_t *)b)->name);
4984 static void sortcmdlist(void)
4986 int array_num;
4987 int elem_size = sizeof(mon_cmd_t);
4989 array_num = sizeof(mon_cmds)/elem_size-1;
4990 qsort((void *)mon_cmds, array_num, elem_size, compare_mon_cmd);
4992 array_num = sizeof(info_cmds)/elem_size-1;
4993 qsort((void *)info_cmds, array_num, elem_size, compare_mon_cmd);
4998 * Local variables:
4999 * c-indent-level: 4
5000 * c-basic-offset: 4
5001 * tab-width: 8
5002 * End:
5005 /* These functions just adapt the readline interface in a typesafe way. We
5006 * could cast function pointers but that discards compiler checks.
5008 static void GCC_FMT_ATTR(2, 3) monitor_readline_printf(void *opaque,
5009 const char *fmt, ...)
5011 va_list ap;
5012 va_start(ap, fmt);
5013 monitor_vprintf(opaque, fmt, ap);
5014 va_end(ap);
5017 static void monitor_readline_flush(void *opaque)
5019 monitor_flush(opaque);
5022 void monitor_init(CharDriverState *chr, int flags)
5024 static int is_first_init = 1;
5025 Monitor *mon;
5027 if (is_first_init) {
5028 monitor_protocol_event_init();
5029 sortcmdlist();
5030 is_first_init = 0;
5033 mon = g_malloc(sizeof(*mon));
5034 monitor_data_init(mon);
5036 mon->chr = chr;
5037 mon->flags = flags;
5038 if (flags & MONITOR_USE_READLINE) {
5039 mon->rs = readline_init(monitor_readline_printf,
5040 monitor_readline_flush,
5041 mon,
5042 monitor_find_completion);
5043 monitor_read_command(mon, 0);
5046 if (monitor_ctrl_mode(mon)) {
5047 mon->mc = g_malloc0(sizeof(MonitorControl));
5048 /* Control mode requires special handlers */
5049 qemu_chr_add_handlers(chr, monitor_can_read, monitor_control_read,
5050 monitor_control_event, mon);
5051 qemu_chr_fe_set_echo(chr, true);
5053 json_message_parser_init(&mon->mc->parser, handle_qmp_command);
5054 } else {
5055 qemu_chr_add_handlers(chr, monitor_can_read, monitor_read,
5056 monitor_event, mon);
5059 QLIST_INSERT_HEAD(&mon_list, mon, entry);
5060 if (!default_mon || (flags & MONITOR_IS_DEFAULT))
5061 default_mon = mon;
5064 static void bdrv_password_cb(void *opaque, const char *password,
5065 void *readline_opaque)
5067 Monitor *mon = opaque;
5068 BlockDriverState *bs = readline_opaque;
5069 int ret = 0;
5071 if (bdrv_set_key(bs, password) != 0) {
5072 monitor_printf(mon, "invalid password\n");
5073 ret = -EPERM;
5075 if (mon->password_completion_cb)
5076 mon->password_completion_cb(mon->password_opaque, ret);
5078 monitor_read_command(mon, 1);
5081 ReadLineState *monitor_get_rs(Monitor *mon)
5083 return mon->rs;
5086 int monitor_read_bdrv_key_start(Monitor *mon, BlockDriverState *bs,
5087 BlockDriverCompletionFunc *completion_cb,
5088 void *opaque)
5090 int err;
5092 if (!bdrv_key_required(bs)) {
5093 if (completion_cb)
5094 completion_cb(opaque, 0);
5095 return 0;
5098 if (monitor_ctrl_mode(mon)) {
5099 qerror_report(QERR_DEVICE_ENCRYPTED, bdrv_get_device_name(bs),
5100 bdrv_get_encrypted_filename(bs));
5101 return -1;
5104 monitor_printf(mon, "%s (%s) is encrypted.\n", bdrv_get_device_name(bs),
5105 bdrv_get_encrypted_filename(bs));
5107 mon->password_completion_cb = completion_cb;
5108 mon->password_opaque = opaque;
5110 err = monitor_read_password(mon, bdrv_password_cb, bs);
5112 if (err && completion_cb)
5113 completion_cb(opaque, err);
5115 return err;
5118 int monitor_read_block_device_key(Monitor *mon, const char *device,
5119 BlockDriverCompletionFunc *completion_cb,
5120 void *opaque)
5122 BlockDriverState *bs;
5124 bs = bdrv_find(device);
5125 if (!bs) {
5126 monitor_printf(mon, "Device not found %s\n", device);
5127 return -1;
5130 return monitor_read_bdrv_key_start(mon, bs, completion_cb, opaque);
5133 QemuOptsList qemu_mon_opts = {
5134 .name = "mon",
5135 .implied_opt_name = "chardev",
5136 .head = QTAILQ_HEAD_INITIALIZER(qemu_mon_opts.head),
5137 .desc = {
5139 .name = "mode",
5140 .type = QEMU_OPT_STRING,
5142 .name = "chardev",
5143 .type = QEMU_OPT_STRING,
5145 .name = "default",
5146 .type = QEMU_OPT_BOOL,
5148 .name = "pretty",
5149 .type = QEMU_OPT_BOOL,
5151 { /* end of list */ }