Merge commit '2a4dac835008da7328e61d8596b310c05cab801d' into upstream-merge
[qemu-kvm.git] / monitor.c
blob88c6cbe5a78ccfd1b0edb39331741d88877e720c
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 "hw/qdev.h"
27 #include "hw/usb.h"
28 #include "hw/pcmcia.h"
29 #include "hw/pc.h"
30 #include "hw/pci.h"
31 #include "hw/watchdog.h"
32 #include "hw/loader.h"
33 #include "gdbstub.h"
34 #include "net.h"
35 #include "net/slirp.h"
36 #include "qemu-char.h"
37 #include "ui/qemu-spice.h"
38 #include "sysemu.h"
39 #include "monitor.h"
40 #include "readline.h"
41 #include "console.h"
42 #include "blockdev.h"
43 #include "audio/audio.h"
44 #include "disas.h"
45 #include "balloon.h"
46 #include "qemu-timer.h"
47 #include "migration.h"
48 #include "kvm.h"
49 #include "acl.h"
50 #include "qint.h"
51 #include "qfloat.h"
52 #include "qlist.h"
53 #include "qbool.h"
54 #include "qstring.h"
55 #include "qjson.h"
56 #include "json-streamer.h"
57 #include "json-parser.h"
58 #include "osdep.h"
59 #include "exec-all.h"
60 #ifdef CONFIG_SIMPLE_TRACE
61 #include "trace.h"
62 #endif
63 #include "ui/qemu-spice.h"
65 //#define DEBUG
66 //#define DEBUG_COMPLETION
69 * Supported types:
71 * 'F' filename
72 * 'B' block device name
73 * 's' string (accept optional quote)
74 * 'O' option string of the form NAME=VALUE,...
75 * parsed according to QemuOptsList given by its name
76 * Example: 'device:O' uses qemu_device_opts.
77 * Restriction: only lists with empty desc are supported
78 * TODO lift the restriction
79 * 'i' 32 bit integer
80 * 'l' target long (32 or 64 bit)
81 * 'M' just like 'l', except in user mode the value is
82 * multiplied by 2^20 (think Mebibyte)
83 * 'o' octets (aka bytes)
84 * user mode accepts an optional T, t, G, g, M, m, K, k
85 * suffix, which multiplies the value by 2^40 for
86 * suffixes T and t, 2^30 for suffixes G and g, 2^20 for
87 * M and m, 2^10 for K and k
88 * 'T' double
89 * user mode accepts an optional ms, us, ns suffix,
90 * which divides the value by 1e3, 1e6, 1e9, respectively
91 * '/' optional gdb-like print format (like "/10x")
93 * '?' optional type (for all types, except '/')
94 * '.' other form of optional type (for 'i' and 'l')
95 * 'b' boolean
96 * user mode accepts "on" or "off"
97 * '-' optional parameter (eg. '-f')
101 typedef struct MonitorCompletionData MonitorCompletionData;
102 struct MonitorCompletionData {
103 Monitor *mon;
104 void (*user_print)(Monitor *mon, const QObject *data);
107 typedef struct mon_cmd_t {
108 const char *name;
109 const char *args_type;
110 const char *params;
111 const char *help;
112 void (*user_print)(Monitor *mon, const QObject *data);
113 union {
114 void (*info)(Monitor *mon);
115 void (*info_new)(Monitor *mon, QObject **ret_data);
116 int (*info_async)(Monitor *mon, MonitorCompletion *cb, void *opaque);
117 void (*cmd)(Monitor *mon, const QDict *qdict);
118 int (*cmd_new)(Monitor *mon, const QDict *params, QObject **ret_data);
119 int (*cmd_async)(Monitor *mon, const QDict *params,
120 MonitorCompletion *cb, void *opaque);
121 } mhandler;
122 int flags;
123 } mon_cmd_t;
125 /* file descriptors passed via SCM_RIGHTS */
126 typedef struct mon_fd_t mon_fd_t;
127 struct mon_fd_t {
128 char *name;
129 int fd;
130 QLIST_ENTRY(mon_fd_t) next;
133 typedef struct MonitorControl {
134 QObject *id;
135 JSONMessageParser parser;
136 int command_mode;
137 } MonitorControl;
139 struct Monitor {
140 CharDriverState *chr;
141 int mux_out;
142 int reset_seen;
143 int flags;
144 int suspend_cnt;
145 uint8_t outbuf[1024];
146 int outbuf_index;
147 ReadLineState *rs;
148 MonitorControl *mc;
149 CPUState *mon_cpu;
150 BlockDriverCompletionFunc *password_completion_cb;
151 void *password_opaque;
152 #ifdef CONFIG_DEBUG_MONITOR
153 int print_calls_nr;
154 #endif
155 QError *error;
156 QLIST_HEAD(,mon_fd_t) fds;
157 QLIST_ENTRY(Monitor) entry;
160 #ifdef CONFIG_DEBUG_MONITOR
161 #define MON_DEBUG(fmt, ...) do { \
162 fprintf(stderr, "Monitor: "); \
163 fprintf(stderr, fmt, ## __VA_ARGS__); } while (0)
165 static inline void mon_print_count_inc(Monitor *mon)
167 mon->print_calls_nr++;
170 static inline void mon_print_count_init(Monitor *mon)
172 mon->print_calls_nr = 0;
175 static inline int mon_print_count_get(const Monitor *mon)
177 return mon->print_calls_nr;
180 #else /* !CONFIG_DEBUG_MONITOR */
181 #define MON_DEBUG(fmt, ...) do { } while (0)
182 static inline void mon_print_count_inc(Monitor *mon) { }
183 static inline void mon_print_count_init(Monitor *mon) { }
184 static inline int mon_print_count_get(const Monitor *mon) { return 0; }
185 #endif /* CONFIG_DEBUG_MONITOR */
187 /* QMP checker flags */
188 #define QMP_ACCEPT_UNKNOWNS 1
190 static QLIST_HEAD(mon_list, Monitor) mon_list;
192 static const mon_cmd_t mon_cmds[];
193 static const mon_cmd_t info_cmds[];
195 static const mon_cmd_t qmp_cmds[];
196 static const mon_cmd_t qmp_query_cmds[];
198 Monitor *cur_mon;
199 Monitor *default_mon;
201 static void monitor_command_cb(Monitor *mon, const char *cmdline,
202 void *opaque);
204 static inline int qmp_cmd_mode(const Monitor *mon)
206 return (mon->mc ? mon->mc->command_mode : 0);
209 /* Return true if in control mode, false otherwise */
210 static inline int monitor_ctrl_mode(const Monitor *mon)
212 return (mon->flags & MONITOR_USE_CONTROL);
215 /* Return non-zero iff we have a current monitor, and it is in QMP mode. */
216 int monitor_cur_is_qmp(void)
218 return cur_mon && monitor_ctrl_mode(cur_mon);
221 static void monitor_read_command(Monitor *mon, int show_prompt)
223 if (!mon->rs)
224 return;
226 readline_start(mon->rs, "(qemu) ", 0, monitor_command_cb, NULL);
227 if (show_prompt)
228 readline_show_prompt(mon->rs);
231 static int monitor_read_password(Monitor *mon, ReadLineFunc *readline_func,
232 void *opaque)
234 if (monitor_ctrl_mode(mon)) {
235 qerror_report(QERR_MISSING_PARAMETER, "password");
236 return -EINVAL;
237 } else if (mon->rs) {
238 readline_start(mon->rs, "Password: ", 1, readline_func, opaque);
239 /* prompt is printed on return from the command handler */
240 return 0;
241 } else {
242 monitor_printf(mon, "terminal does not support password prompting\n");
243 return -ENOTTY;
247 void monitor_flush(Monitor *mon)
249 if (mon && mon->outbuf_index != 0 && !mon->mux_out) {
250 qemu_chr_write(mon->chr, mon->outbuf, mon->outbuf_index);
251 mon->outbuf_index = 0;
255 /* flush at every end of line or if the buffer is full */
256 static void monitor_puts(Monitor *mon, const char *str)
258 char c;
260 for(;;) {
261 c = *str++;
262 if (c == '\0')
263 break;
264 if (c == '\n')
265 mon->outbuf[mon->outbuf_index++] = '\r';
266 mon->outbuf[mon->outbuf_index++] = c;
267 if (mon->outbuf_index >= (sizeof(mon->outbuf) - 1)
268 || c == '\n')
269 monitor_flush(mon);
273 void monitor_vprintf(Monitor *mon, const char *fmt, va_list ap)
275 char buf[4096];
277 if (!mon)
278 return;
280 mon_print_count_inc(mon);
282 if (monitor_ctrl_mode(mon)) {
283 return;
286 vsnprintf(buf, sizeof(buf), fmt, ap);
287 monitor_puts(mon, buf);
290 void monitor_printf(Monitor *mon, const char *fmt, ...)
292 va_list ap;
293 va_start(ap, fmt);
294 monitor_vprintf(mon, fmt, ap);
295 va_end(ap);
298 void monitor_print_filename(Monitor *mon, const char *filename)
300 int i;
302 for (i = 0; filename[i]; i++) {
303 switch (filename[i]) {
304 case ' ':
305 case '"':
306 case '\\':
307 monitor_printf(mon, "\\%c", filename[i]);
308 break;
309 case '\t':
310 monitor_printf(mon, "\\t");
311 break;
312 case '\r':
313 monitor_printf(mon, "\\r");
314 break;
315 case '\n':
316 monitor_printf(mon, "\\n");
317 break;
318 default:
319 monitor_printf(mon, "%c", filename[i]);
320 break;
325 static int GCC_FMT_ATTR(2, 3) monitor_fprintf(FILE *stream,
326 const char *fmt, ...)
328 va_list ap;
329 va_start(ap, fmt);
330 monitor_vprintf((Monitor *)stream, fmt, ap);
331 va_end(ap);
332 return 0;
335 static void monitor_user_noop(Monitor *mon, const QObject *data) { }
337 static inline int handler_is_qobject(const mon_cmd_t *cmd)
339 return cmd->user_print != NULL;
342 static inline bool handler_is_async(const mon_cmd_t *cmd)
344 return cmd->flags & MONITOR_CMD_ASYNC;
347 static inline int monitor_has_error(const Monitor *mon)
349 return mon->error != NULL;
352 static void monitor_json_emitter(Monitor *mon, const QObject *data)
354 QString *json;
356 json = mon->flags & MONITOR_USE_PRETTY ? qobject_to_json_pretty(data) :
357 qobject_to_json(data);
358 assert(json != NULL);
360 qstring_append_chr(json, '\n');
361 monitor_puts(mon, qstring_get_str(json));
363 QDECREF(json);
366 static void monitor_protocol_emitter(Monitor *mon, QObject *data)
368 QDict *qmp;
370 qmp = qdict_new();
372 if (!monitor_has_error(mon)) {
373 /* success response */
374 if (data) {
375 qobject_incref(data);
376 qdict_put_obj(qmp, "return", data);
377 } else {
378 /* return an empty QDict by default */
379 qdict_put(qmp, "return", qdict_new());
381 } else {
382 /* error response */
383 qdict_put(mon->error->error, "desc", qerror_human(mon->error));
384 qdict_put(qmp, "error", mon->error->error);
385 QINCREF(mon->error->error);
386 QDECREF(mon->error);
387 mon->error = NULL;
390 if (mon->mc->id) {
391 qdict_put_obj(qmp, "id", mon->mc->id);
392 mon->mc->id = NULL;
395 monitor_json_emitter(mon, QOBJECT(qmp));
396 QDECREF(qmp);
399 static void timestamp_put(QDict *qdict)
401 int err;
402 QObject *obj;
403 qemu_timeval tv;
405 err = qemu_gettimeofday(&tv);
406 if (err < 0)
407 return;
409 obj = qobject_from_jsonf("{ 'seconds': %" PRId64 ", "
410 "'microseconds': %" PRId64 " }",
411 (int64_t) tv.tv_sec, (int64_t) tv.tv_usec);
412 qdict_put_obj(qdict, "timestamp", obj);
416 * monitor_protocol_event(): Generate a Monitor event
418 * Event-specific data can be emitted through the (optional) 'data' parameter.
420 void monitor_protocol_event(MonitorEvent event, QObject *data)
422 QDict *qmp;
423 const char *event_name;
424 Monitor *mon;
426 assert(event < QEVENT_MAX);
428 switch (event) {
429 case QEVENT_SHUTDOWN:
430 event_name = "SHUTDOWN";
431 break;
432 case QEVENT_RESET:
433 event_name = "RESET";
434 break;
435 case QEVENT_POWERDOWN:
436 event_name = "POWERDOWN";
437 break;
438 case QEVENT_STOP:
439 event_name = "STOP";
440 break;
441 case QEVENT_RESUME:
442 event_name = "RESUME";
443 break;
444 case QEVENT_VNC_CONNECTED:
445 event_name = "VNC_CONNECTED";
446 break;
447 case QEVENT_VNC_INITIALIZED:
448 event_name = "VNC_INITIALIZED";
449 break;
450 case QEVENT_VNC_DISCONNECTED:
451 event_name = "VNC_DISCONNECTED";
452 break;
453 case QEVENT_BLOCK_IO_ERROR:
454 event_name = "BLOCK_IO_ERROR";
455 break;
456 case QEVENT_RTC_CHANGE:
457 event_name = "RTC_CHANGE";
458 break;
459 case QEVENT_WATCHDOG:
460 event_name = "WATCHDOG";
461 break;
462 case QEVENT_SPICE_CONNECTED:
463 event_name = "SPICE_CONNECTED";
464 break;
465 case QEVENT_SPICE_INITIALIZED:
466 event_name = "SPICE_INITIALIZED";
467 break;
468 case QEVENT_SPICE_DISCONNECTED:
469 event_name = "SPICE_DISCONNECTED";
470 break;
471 default:
472 abort();
473 break;
476 qmp = qdict_new();
477 timestamp_put(qmp);
478 qdict_put(qmp, "event", qstring_from_str(event_name));
479 if (data) {
480 qobject_incref(data);
481 qdict_put_obj(qmp, "data", data);
484 QLIST_FOREACH(mon, &mon_list, entry) {
485 if (monitor_ctrl_mode(mon) && qmp_cmd_mode(mon)) {
486 monitor_json_emitter(mon, QOBJECT(qmp));
489 QDECREF(qmp);
492 static int do_qmp_capabilities(Monitor *mon, const QDict *params,
493 QObject **ret_data)
495 /* Will setup QMP capabilities in the future */
496 if (monitor_ctrl_mode(mon)) {
497 mon->mc->command_mode = 1;
500 return 0;
503 static int mon_set_cpu(int cpu_index);
504 static void handle_user_command(Monitor *mon, const char *cmdline);
506 static int do_hmp_passthrough(Monitor *mon, const QDict *params,
507 QObject **ret_data)
509 int ret = 0;
510 Monitor *old_mon, hmp;
511 CharDriverState mchar;
513 memset(&hmp, 0, sizeof(hmp));
514 qemu_chr_init_mem(&mchar);
515 hmp.chr = &mchar;
517 old_mon = cur_mon;
518 cur_mon = &hmp;
520 if (qdict_haskey(params, "cpu-index")) {
521 ret = mon_set_cpu(qdict_get_int(params, "cpu-index"));
522 if (ret < 0) {
523 cur_mon = old_mon;
524 qerror_report(QERR_INVALID_PARAMETER_VALUE, "cpu-index", "a CPU number");
525 goto out;
529 handle_user_command(&hmp, qdict_get_str(params, "command-line"));
530 cur_mon = old_mon;
532 if (qemu_chr_mem_osize(hmp.chr) > 0) {
533 *ret_data = QOBJECT(qemu_chr_mem_to_qs(hmp.chr));
536 out:
537 qemu_chr_close_mem(hmp.chr);
538 return ret;
541 static int compare_cmd(const char *name, const char *list)
543 const char *p, *pstart;
544 int len;
545 len = strlen(name);
546 p = list;
547 for(;;) {
548 pstart = p;
549 p = strchr(p, '|');
550 if (!p)
551 p = pstart + strlen(pstart);
552 if ((p - pstart) == len && !memcmp(pstart, name, len))
553 return 1;
554 if (*p == '\0')
555 break;
556 p++;
558 return 0;
561 static void help_cmd_dump(Monitor *mon, const mon_cmd_t *cmds,
562 const char *prefix, const char *name)
564 const mon_cmd_t *cmd;
566 for(cmd = cmds; cmd->name != NULL; cmd++) {
567 if (!name || !strcmp(name, cmd->name))
568 monitor_printf(mon, "%s%s %s -- %s\n", prefix, cmd->name,
569 cmd->params, cmd->help);
573 static void help_cmd(Monitor *mon, const char *name)
575 if (name && !strcmp(name, "info")) {
576 help_cmd_dump(mon, info_cmds, "info ", NULL);
577 } else {
578 help_cmd_dump(mon, mon_cmds, "", name);
579 if (name && !strcmp(name, "log")) {
580 const CPULogItem *item;
581 monitor_printf(mon, "Log items (comma separated):\n");
582 monitor_printf(mon, "%-10s %s\n", "none", "remove all logs");
583 for(item = cpu_log_items; item->mask != 0; item++) {
584 monitor_printf(mon, "%-10s %s\n", item->name, item->help);
590 static void do_help_cmd(Monitor *mon, const QDict *qdict)
592 help_cmd(mon, qdict_get_try_str(qdict, "name"));
595 #ifdef CONFIG_SIMPLE_TRACE
596 static void do_change_trace_event_state(Monitor *mon, const QDict *qdict)
598 const char *tp_name = qdict_get_str(qdict, "name");
599 bool new_state = qdict_get_bool(qdict, "option");
600 int ret = st_change_trace_event_state(tp_name, new_state);
602 if (!ret) {
603 monitor_printf(mon, "unknown event name \"%s\"\n", tp_name);
607 static void do_trace_file(Monitor *mon, const QDict *qdict)
609 const char *op = qdict_get_try_str(qdict, "op");
610 const char *arg = qdict_get_try_str(qdict, "arg");
612 if (!op) {
613 st_print_trace_file_status((FILE *)mon, &monitor_fprintf);
614 } else if (!strcmp(op, "on")) {
615 st_set_trace_file_enabled(true);
616 } else if (!strcmp(op, "off")) {
617 st_set_trace_file_enabled(false);
618 } else if (!strcmp(op, "flush")) {
619 st_flush_trace_buffer();
620 } else if (!strcmp(op, "set")) {
621 if (arg) {
622 st_set_trace_file(arg);
624 } else {
625 monitor_printf(mon, "unexpected argument \"%s\"\n", op);
626 help_cmd(mon, "trace-file");
629 #endif
631 static void user_monitor_complete(void *opaque, QObject *ret_data)
633 MonitorCompletionData *data = (MonitorCompletionData *)opaque;
635 if (ret_data) {
636 data->user_print(data->mon, ret_data);
638 monitor_resume(data->mon);
639 qemu_free(data);
642 static void qmp_monitor_complete(void *opaque, QObject *ret_data)
644 monitor_protocol_emitter(opaque, ret_data);
647 static int qmp_async_cmd_handler(Monitor *mon, const mon_cmd_t *cmd,
648 const QDict *params)
650 return cmd->mhandler.cmd_async(mon, params, qmp_monitor_complete, mon);
653 static void qmp_async_info_handler(Monitor *mon, const mon_cmd_t *cmd)
655 cmd->mhandler.info_async(mon, qmp_monitor_complete, mon);
658 static void user_async_cmd_handler(Monitor *mon, const mon_cmd_t *cmd,
659 const QDict *params)
661 int ret;
663 MonitorCompletionData *cb_data = qemu_malloc(sizeof(*cb_data));
664 cb_data->mon = mon;
665 cb_data->user_print = cmd->user_print;
666 monitor_suspend(mon);
667 ret = cmd->mhandler.cmd_async(mon, params,
668 user_monitor_complete, cb_data);
669 if (ret < 0) {
670 monitor_resume(mon);
671 qemu_free(cb_data);
675 static void user_async_info_handler(Monitor *mon, const mon_cmd_t *cmd)
677 int ret;
679 MonitorCompletionData *cb_data = qemu_malloc(sizeof(*cb_data));
680 cb_data->mon = mon;
681 cb_data->user_print = cmd->user_print;
682 monitor_suspend(mon);
683 ret = cmd->mhandler.info_async(mon, user_monitor_complete, cb_data);
684 if (ret < 0) {
685 monitor_resume(mon);
686 qemu_free(cb_data);
690 static void do_info(Monitor *mon, const QDict *qdict)
692 const mon_cmd_t *cmd;
693 const char *item = qdict_get_try_str(qdict, "item");
695 if (!item) {
696 goto help;
699 for (cmd = info_cmds; cmd->name != NULL; cmd++) {
700 if (compare_cmd(item, cmd->name))
701 break;
704 if (cmd->name == NULL) {
705 goto help;
708 if (handler_is_async(cmd)) {
709 user_async_info_handler(mon, cmd);
710 } else if (handler_is_qobject(cmd)) {
711 QObject *info_data = NULL;
713 cmd->mhandler.info_new(mon, &info_data);
714 if (info_data) {
715 cmd->user_print(mon, info_data);
716 qobject_decref(info_data);
718 } else {
719 cmd->mhandler.info(mon);
722 return;
724 help:
725 help_cmd(mon, "info");
728 static void do_info_version_print(Monitor *mon, const QObject *data)
730 QDict *qdict;
731 QDict *qemu;
733 qdict = qobject_to_qdict(data);
734 qemu = qdict_get_qdict(qdict, "qemu");
736 monitor_printf(mon, "%" PRId64 ".%" PRId64 ".%" PRId64 "%s\n",
737 qdict_get_int(qemu, "major"),
738 qdict_get_int(qemu, "minor"),
739 qdict_get_int(qemu, "micro"),
740 qdict_get_str(qdict, "package"));
743 static void do_info_version(Monitor *mon, QObject **ret_data)
745 const char *version = QEMU_VERSION;
746 int major = 0, minor = 0, micro = 0;
747 char *tmp;
749 major = strtol(version, &tmp, 10);
750 tmp++;
751 minor = strtol(tmp, &tmp, 10);
752 tmp++;
753 micro = strtol(tmp, &tmp, 10);
755 *ret_data = qobject_from_jsonf("{ 'qemu': { 'major': %d, 'minor': %d, \
756 'micro': %d }, 'package': %s }", major, minor, micro, QEMU_PKGVERSION);
759 static void do_info_name_print(Monitor *mon, const QObject *data)
761 QDict *qdict;
763 qdict = qobject_to_qdict(data);
764 if (qdict_size(qdict) == 0) {
765 return;
768 monitor_printf(mon, "%s\n", qdict_get_str(qdict, "name"));
771 static void do_info_name(Monitor *mon, QObject **ret_data)
773 *ret_data = qemu_name ? qobject_from_jsonf("{'name': %s }", qemu_name) :
774 qobject_from_jsonf("{}");
777 static QObject *get_cmd_dict(const char *name)
779 const char *p;
781 /* Remove '|' from some commands */
782 p = strchr(name, '|');
783 if (p) {
784 p++;
785 } else {
786 p = name;
789 return qobject_from_jsonf("{ 'name': %s }", p);
792 static void do_info_commands(Monitor *mon, QObject **ret_data)
794 QList *cmd_list;
795 const mon_cmd_t *cmd;
797 cmd_list = qlist_new();
799 for (cmd = qmp_cmds; cmd->name != NULL; cmd++) {
800 qlist_append_obj(cmd_list, get_cmd_dict(cmd->name));
803 for (cmd = qmp_query_cmds; cmd->name != NULL; cmd++) {
804 char buf[128];
805 snprintf(buf, sizeof(buf), "query-%s", cmd->name);
806 qlist_append_obj(cmd_list, get_cmd_dict(buf));
809 *ret_data = QOBJECT(cmd_list);
812 static void do_info_uuid_print(Monitor *mon, const QObject *data)
814 monitor_printf(mon, "%s\n", qdict_get_str(qobject_to_qdict(data), "UUID"));
817 static void do_info_uuid(Monitor *mon, QObject **ret_data)
819 char uuid[64];
821 snprintf(uuid, sizeof(uuid), UUID_FMT, qemu_uuid[0], qemu_uuid[1],
822 qemu_uuid[2], qemu_uuid[3], qemu_uuid[4], qemu_uuid[5],
823 qemu_uuid[6], qemu_uuid[7], qemu_uuid[8], qemu_uuid[9],
824 qemu_uuid[10], qemu_uuid[11], qemu_uuid[12], qemu_uuid[13],
825 qemu_uuid[14], qemu_uuid[15]);
826 *ret_data = qobject_from_jsonf("{ 'UUID': %s }", uuid);
829 /* get the current CPU defined by the user */
830 static int mon_set_cpu(int cpu_index)
832 CPUState *env;
834 for(env = first_cpu; env != NULL; env = env->next_cpu) {
835 if (env->cpu_index == cpu_index) {
836 cur_mon->mon_cpu = env;
837 return 0;
840 return -1;
843 static CPUState *mon_get_cpu(void)
845 if (!cur_mon->mon_cpu) {
846 mon_set_cpu(0);
848 cpu_synchronize_state(cur_mon->mon_cpu);
849 return cur_mon->mon_cpu;
852 static void do_info_registers(Monitor *mon)
854 CPUState *env;
855 env = mon_get_cpu();
856 #ifdef TARGET_I386
857 cpu_dump_state(env, (FILE *)mon, monitor_fprintf,
858 X86_DUMP_FPU);
859 #else
860 cpu_dump_state(env, (FILE *)mon, monitor_fprintf,
862 #endif
865 static void print_cpu_iter(QObject *obj, void *opaque)
867 QDict *cpu;
868 int active = ' ';
869 Monitor *mon = opaque;
871 assert(qobject_type(obj) == QTYPE_QDICT);
872 cpu = qobject_to_qdict(obj);
874 if (qdict_get_bool(cpu, "current")) {
875 active = '*';
878 monitor_printf(mon, "%c CPU #%d: ", active, (int)qdict_get_int(cpu, "CPU"));
880 #if defined(TARGET_I386)
881 monitor_printf(mon, "pc=0x" TARGET_FMT_lx,
882 (target_ulong) qdict_get_int(cpu, "pc"));
883 #elif defined(TARGET_PPC)
884 monitor_printf(mon, "nip=0x" TARGET_FMT_lx,
885 (target_long) qdict_get_int(cpu, "nip"));
886 #elif defined(TARGET_SPARC)
887 monitor_printf(mon, "pc=0x " TARGET_FMT_lx,
888 (target_long) qdict_get_int(cpu, "pc"));
889 monitor_printf(mon, "npc=0x" TARGET_FMT_lx,
890 (target_long) qdict_get_int(cpu, "npc"));
891 #elif defined(TARGET_MIPS)
892 monitor_printf(mon, "PC=0x" TARGET_FMT_lx,
893 (target_long) qdict_get_int(cpu, "PC"));
894 #endif
896 if (qdict_get_bool(cpu, "halted")) {
897 monitor_printf(mon, " (halted)");
900 monitor_printf(mon, " thread_id=%" PRId64 " ",
901 qdict_get_int(cpu, "thread_id"));
903 monitor_printf(mon, "\n");
906 static void monitor_print_cpus(Monitor *mon, const QObject *data)
908 QList *cpu_list;
910 assert(qobject_type(data) == QTYPE_QLIST);
911 cpu_list = qobject_to_qlist(data);
912 qlist_iter(cpu_list, print_cpu_iter, mon);
915 static void do_info_cpus(Monitor *mon, QObject **ret_data)
917 CPUState *env;
918 QList *cpu_list;
920 cpu_list = qlist_new();
922 /* just to set the default cpu if not already done */
923 mon_get_cpu();
925 for(env = first_cpu; env != NULL; env = env->next_cpu) {
926 QDict *cpu;
927 QObject *obj;
929 cpu_synchronize_state(env);
931 obj = qobject_from_jsonf("{ 'CPU': %d, 'current': %i, 'halted': %i }",
932 env->cpu_index, env == mon->mon_cpu,
933 env->halted);
935 cpu = qobject_to_qdict(obj);
937 #if defined(TARGET_I386)
938 qdict_put(cpu, "pc", qint_from_int(env->eip + env->segs[R_CS].base));
939 #elif defined(TARGET_PPC)
940 qdict_put(cpu, "nip", qint_from_int(env->nip));
941 #elif defined(TARGET_SPARC)
942 qdict_put(cpu, "pc", qint_from_int(env->pc));
943 qdict_put(cpu, "npc", qint_from_int(env->npc));
944 #elif defined(TARGET_MIPS)
945 qdict_put(cpu, "PC", qint_from_int(env->active_tc.PC));
946 #endif
947 qdict_put(cpu, "thread_id", qint_from_int(env->thread_id));
949 qlist_append(cpu_list, cpu);
952 *ret_data = QOBJECT(cpu_list);
955 static int do_cpu_set(Monitor *mon, const QDict *qdict, QObject **ret_data)
957 int index = qdict_get_int(qdict, "index");
958 if (mon_set_cpu(index) < 0) {
959 qerror_report(QERR_INVALID_PARAMETER_VALUE, "index",
960 "a CPU number");
961 return -1;
963 return 0;
966 static void do_cpu_set_nr(Monitor *mon, const QDict *qdict)
968 int state, value;
969 const char *status;
971 status = qdict_get_str(qdict, "state");
972 value = qdict_get_int(qdict, "cpu");
974 if (!strcmp(status, "online"))
975 state = 1;
976 else if (!strcmp(status, "offline"))
977 state = 0;
978 else {
979 monitor_printf(mon, "invalid status: %s\n", status);
980 return;
982 #if defined(TARGET_I386) || defined(TARGET_X86_64)
983 qemu_system_cpu_hot_add(value, state);
984 #endif
987 static void do_info_jit(Monitor *mon)
989 dump_exec_info((FILE *)mon, monitor_fprintf);
992 static void do_info_history(Monitor *mon)
994 int i;
995 const char *str;
997 if (!mon->rs)
998 return;
999 i = 0;
1000 for(;;) {
1001 str = readline_get_history(mon->rs, i);
1002 if (!str)
1003 break;
1004 monitor_printf(mon, "%d: '%s'\n", i, str);
1005 i++;
1009 #if defined(TARGET_PPC)
1010 /* XXX: not implemented in other targets */
1011 static void do_info_cpu_stats(Monitor *mon)
1013 CPUState *env;
1015 env = mon_get_cpu();
1016 cpu_dump_statistics(env, (FILE *)mon, &monitor_fprintf, 0);
1018 #endif
1020 #if defined(CONFIG_SIMPLE_TRACE)
1021 static void do_info_trace(Monitor *mon)
1023 st_print_trace((FILE *)mon, &monitor_fprintf);
1026 static void do_info_trace_events(Monitor *mon)
1028 st_print_trace_events((FILE *)mon, &monitor_fprintf);
1030 #endif
1033 * do_quit(): Quit QEMU execution
1035 static int do_quit(Monitor *mon, const QDict *qdict, QObject **ret_data)
1037 monitor_suspend(mon);
1038 no_shutdown = 0;
1039 qemu_system_shutdown_request();
1041 return 0;
1044 static int change_vnc_password(const char *password)
1046 if (!password || !password[0]) {
1047 if (vnc_display_disable_login(NULL)) {
1048 qerror_report(QERR_SET_PASSWD_FAILED);
1049 return -1;
1051 return 0;
1054 if (vnc_display_password(NULL, password) < 0) {
1055 qerror_report(QERR_SET_PASSWD_FAILED);
1056 return -1;
1059 return 0;
1062 static void change_vnc_password_cb(Monitor *mon, const char *password,
1063 void *opaque)
1065 change_vnc_password(password);
1066 monitor_read_command(mon, 1);
1069 static int do_change_vnc(Monitor *mon, const char *target, const char *arg)
1071 if (strcmp(target, "passwd") == 0 ||
1072 strcmp(target, "password") == 0) {
1073 if (arg) {
1074 char password[9];
1075 strncpy(password, arg, sizeof(password));
1076 password[sizeof(password) - 1] = '\0';
1077 return change_vnc_password(password);
1078 } else {
1079 return monitor_read_password(mon, change_vnc_password_cb, NULL);
1081 } else {
1082 if (vnc_display_open(NULL, target) < 0) {
1083 qerror_report(QERR_VNC_SERVER_FAILED, target);
1084 return -1;
1088 return 0;
1092 * do_change(): Change a removable medium, or VNC configuration
1094 static int do_change(Monitor *mon, const QDict *qdict, QObject **ret_data)
1096 const char *device = qdict_get_str(qdict, "device");
1097 const char *target = qdict_get_str(qdict, "target");
1098 const char *arg = qdict_get_try_str(qdict, "arg");
1099 int ret;
1101 if (strcmp(device, "vnc") == 0) {
1102 ret = do_change_vnc(mon, target, arg);
1103 } else {
1104 ret = do_change_block(mon, device, target, arg);
1107 return ret;
1110 static int set_password(Monitor *mon, const QDict *qdict, QObject **ret_data)
1112 const char *protocol = qdict_get_str(qdict, "protocol");
1113 const char *password = qdict_get_str(qdict, "password");
1114 const char *connected = qdict_get_try_str(qdict, "connected");
1115 int disconnect_if_connected = 0;
1116 int fail_if_connected = 0;
1117 int rc;
1119 if (connected) {
1120 if (strcmp(connected, "fail") == 0) {
1121 fail_if_connected = 1;
1122 } else if (strcmp(connected, "disconnect") == 0) {
1123 disconnect_if_connected = 1;
1124 } else if (strcmp(connected, "keep") == 0) {
1125 /* nothing */
1126 } else {
1127 qerror_report(QERR_INVALID_PARAMETER, "connected");
1128 return -1;
1132 if (strcmp(protocol, "spice") == 0) {
1133 if (!using_spice) {
1134 /* correct one? spice isn't a device ,,, */
1135 qerror_report(QERR_DEVICE_NOT_ACTIVE, "spice");
1136 return -1;
1138 rc = qemu_spice_set_passwd(password, fail_if_connected,
1139 disconnect_if_connected);
1140 if (rc != 0) {
1141 qerror_report(QERR_SET_PASSWD_FAILED);
1142 return -1;
1144 return 0;
1147 if (strcmp(protocol, "vnc") == 0) {
1148 if (fail_if_connected || disconnect_if_connected) {
1149 /* vnc supports "connected=keep" only */
1150 qerror_report(QERR_INVALID_PARAMETER, "connected");
1151 return -1;
1153 /* Note that setting an empty password will not disable login through
1154 * this interface. */
1155 rc = vnc_display_password(NULL, password);
1156 if (rc != 0) {
1157 qerror_report(QERR_SET_PASSWD_FAILED);
1158 return -1;
1160 return 0;
1163 qerror_report(QERR_INVALID_PARAMETER, "protocol");
1164 return -1;
1167 static int expire_password(Monitor *mon, const QDict *qdict, QObject **ret_data)
1169 const char *protocol = qdict_get_str(qdict, "protocol");
1170 const char *whenstr = qdict_get_str(qdict, "time");
1171 time_t when;
1172 int rc;
1174 if (strcmp(whenstr, "now") == 0) {
1175 when = 0;
1176 } else if (strcmp(whenstr, "never") == 0) {
1177 when = TIME_MAX;
1178 } else if (whenstr[0] == '+') {
1179 when = time(NULL) + strtoull(whenstr+1, NULL, 10);
1180 } else {
1181 when = strtoull(whenstr, NULL, 10);
1184 if (strcmp(protocol, "spice") == 0) {
1185 if (!using_spice) {
1186 /* correct one? spice isn't a device ,,, */
1187 qerror_report(QERR_DEVICE_NOT_ACTIVE, "spice");
1188 return -1;
1190 rc = qemu_spice_set_pw_expire(when);
1191 if (rc != 0) {
1192 qerror_report(QERR_SET_PASSWD_FAILED);
1193 return -1;
1195 return 0;
1198 if (strcmp(protocol, "vnc") == 0) {
1199 rc = vnc_display_pw_expire(NULL, when);
1200 if (rc != 0) {
1201 qerror_report(QERR_SET_PASSWD_FAILED);
1202 return -1;
1204 return 0;
1207 qerror_report(QERR_INVALID_PARAMETER, "protocol");
1208 return -1;
1211 static int client_migrate_info(Monitor *mon, const QDict *qdict, QObject **ret_data)
1213 const char *protocol = qdict_get_str(qdict, "protocol");
1214 const char *hostname = qdict_get_str(qdict, "hostname");
1215 const char *subject = qdict_get_try_str(qdict, "cert-subject");
1216 int port = qdict_get_try_int(qdict, "port", -1);
1217 int tls_port = qdict_get_try_int(qdict, "tls-port", -1);
1218 int ret;
1220 if (strcmp(protocol, "spice") == 0) {
1221 if (!using_spice) {
1222 qerror_report(QERR_DEVICE_NOT_ACTIVE, "spice");
1223 return -1;
1226 ret = qemu_spice_migrate_info(hostname, port, tls_port, subject);
1227 if (ret != 0) {
1228 qerror_report(QERR_UNDEFINED_ERROR);
1229 return -1;
1231 return 0;
1234 qerror_report(QERR_INVALID_PARAMETER, "protocol");
1235 return -1;
1238 static int do_screen_dump(Monitor *mon, const QDict *qdict, QObject **ret_data)
1240 vga_hw_screen_dump(qdict_get_str(qdict, "filename"));
1241 return 0;
1244 static void do_logfile(Monitor *mon, const QDict *qdict)
1246 cpu_set_log_filename(qdict_get_str(qdict, "filename"));
1249 static void do_log(Monitor *mon, const QDict *qdict)
1251 int mask;
1252 const char *items = qdict_get_str(qdict, "items");
1254 if (!strcmp(items, "none")) {
1255 mask = 0;
1256 } else {
1257 mask = cpu_str_to_log_mask(items);
1258 if (!mask) {
1259 help_cmd(mon, "log");
1260 return;
1263 cpu_set_log(mask);
1266 static void do_singlestep(Monitor *mon, const QDict *qdict)
1268 const char *option = qdict_get_try_str(qdict, "option");
1269 if (!option || !strcmp(option, "on")) {
1270 singlestep = 1;
1271 } else if (!strcmp(option, "off")) {
1272 singlestep = 0;
1273 } else {
1274 monitor_printf(mon, "unexpected option %s\n", option);
1279 * do_stop(): Stop VM execution
1281 static int do_stop(Monitor *mon, const QDict *qdict, QObject **ret_data)
1283 vm_stop(VMSTOP_USER);
1284 return 0;
1287 static void encrypted_bdrv_it(void *opaque, BlockDriverState *bs);
1289 struct bdrv_iterate_context {
1290 Monitor *mon;
1291 int err;
1295 * do_cont(): Resume emulation.
1297 static int do_cont(Monitor *mon, const QDict *qdict, QObject **ret_data)
1299 struct bdrv_iterate_context context = { mon, 0 };
1301 if (incoming_expected) {
1302 qerror_report(QERR_MIGRATION_EXPECTED);
1303 return -1;
1305 bdrv_iterate(encrypted_bdrv_it, &context);
1306 /* only resume the vm if all keys are set and valid */
1307 if (!context.err) {
1308 vm_start();
1309 return 0;
1310 } else {
1311 return -1;
1315 static void bdrv_key_cb(void *opaque, int err)
1317 Monitor *mon = opaque;
1319 /* another key was set successfully, retry to continue */
1320 if (!err)
1321 do_cont(mon, NULL, NULL);
1324 static void encrypted_bdrv_it(void *opaque, BlockDriverState *bs)
1326 struct bdrv_iterate_context *context = opaque;
1328 if (!context->err && bdrv_key_required(bs)) {
1329 context->err = -EBUSY;
1330 monitor_read_bdrv_key_start(context->mon, bs, bdrv_key_cb,
1331 context->mon);
1335 static void do_gdbserver(Monitor *mon, const QDict *qdict)
1337 const char *device = qdict_get_try_str(qdict, "device");
1338 if (!device)
1339 device = "tcp::" DEFAULT_GDBSTUB_PORT;
1340 if (gdbserver_start(device) < 0) {
1341 monitor_printf(mon, "Could not open gdbserver on device '%s'\n",
1342 device);
1343 } else if (strcmp(device, "none") == 0) {
1344 monitor_printf(mon, "Disabled gdbserver\n");
1345 } else {
1346 monitor_printf(mon, "Waiting for gdb connection on device '%s'\n",
1347 device);
1351 static void do_watchdog_action(Monitor *mon, const QDict *qdict)
1353 const char *action = qdict_get_str(qdict, "action");
1354 if (select_watchdog_action(action) == -1) {
1355 monitor_printf(mon, "Unknown watchdog action '%s'\n", action);
1359 static void monitor_printc(Monitor *mon, int c)
1361 monitor_printf(mon, "'");
1362 switch(c) {
1363 case '\'':
1364 monitor_printf(mon, "\\'");
1365 break;
1366 case '\\':
1367 monitor_printf(mon, "\\\\");
1368 break;
1369 case '\n':
1370 monitor_printf(mon, "\\n");
1371 break;
1372 case '\r':
1373 monitor_printf(mon, "\\r");
1374 break;
1375 default:
1376 if (c >= 32 && c <= 126) {
1377 monitor_printf(mon, "%c", c);
1378 } else {
1379 monitor_printf(mon, "\\x%02x", c);
1381 break;
1383 monitor_printf(mon, "'");
1386 static void memory_dump(Monitor *mon, int count, int format, int wsize,
1387 target_phys_addr_t addr, int is_physical)
1389 CPUState *env;
1390 int l, line_size, i, max_digits, len;
1391 uint8_t buf[16];
1392 uint64_t v;
1394 if (format == 'i') {
1395 int flags;
1396 flags = 0;
1397 env = mon_get_cpu();
1398 #ifdef TARGET_I386
1399 if (wsize == 2) {
1400 flags = 1;
1401 } else if (wsize == 4) {
1402 flags = 0;
1403 } else {
1404 /* as default we use the current CS size */
1405 flags = 0;
1406 if (env) {
1407 #ifdef TARGET_X86_64
1408 if ((env->efer & MSR_EFER_LMA) &&
1409 (env->segs[R_CS].flags & DESC_L_MASK))
1410 flags = 2;
1411 else
1412 #endif
1413 if (!(env->segs[R_CS].flags & DESC_B_MASK))
1414 flags = 1;
1417 #endif
1418 monitor_disas(mon, env, addr, count, is_physical, flags);
1419 return;
1422 len = wsize * count;
1423 if (wsize == 1)
1424 line_size = 8;
1425 else
1426 line_size = 16;
1427 max_digits = 0;
1429 switch(format) {
1430 case 'o':
1431 max_digits = (wsize * 8 + 2) / 3;
1432 break;
1433 default:
1434 case 'x':
1435 max_digits = (wsize * 8) / 4;
1436 break;
1437 case 'u':
1438 case 'd':
1439 max_digits = (wsize * 8 * 10 + 32) / 33;
1440 break;
1441 case 'c':
1442 wsize = 1;
1443 break;
1446 while (len > 0) {
1447 if (is_physical)
1448 monitor_printf(mon, TARGET_FMT_plx ":", addr);
1449 else
1450 monitor_printf(mon, TARGET_FMT_lx ":", (target_ulong)addr);
1451 l = len;
1452 if (l > line_size)
1453 l = line_size;
1454 if (is_physical) {
1455 cpu_physical_memory_rw(addr, buf, l, 0);
1456 } else {
1457 env = mon_get_cpu();
1458 if (cpu_memory_rw_debug(env, addr, buf, l, 0) < 0) {
1459 monitor_printf(mon, " Cannot access memory\n");
1460 break;
1463 i = 0;
1464 while (i < l) {
1465 switch(wsize) {
1466 default:
1467 case 1:
1468 v = ldub_raw(buf + i);
1469 break;
1470 case 2:
1471 v = lduw_raw(buf + i);
1472 break;
1473 case 4:
1474 v = (uint32_t)ldl_raw(buf + i);
1475 break;
1476 case 8:
1477 v = ldq_raw(buf + i);
1478 break;
1480 monitor_printf(mon, " ");
1481 switch(format) {
1482 case 'o':
1483 monitor_printf(mon, "%#*" PRIo64, max_digits, v);
1484 break;
1485 case 'x':
1486 monitor_printf(mon, "0x%0*" PRIx64, max_digits, v);
1487 break;
1488 case 'u':
1489 monitor_printf(mon, "%*" PRIu64, max_digits, v);
1490 break;
1491 case 'd':
1492 monitor_printf(mon, "%*" PRId64, max_digits, v);
1493 break;
1494 case 'c':
1495 monitor_printc(mon, v);
1496 break;
1498 i += wsize;
1500 monitor_printf(mon, "\n");
1501 addr += l;
1502 len -= l;
1506 static void do_memory_dump(Monitor *mon, const QDict *qdict)
1508 int count = qdict_get_int(qdict, "count");
1509 int format = qdict_get_int(qdict, "format");
1510 int size = qdict_get_int(qdict, "size");
1511 target_long addr = qdict_get_int(qdict, "addr");
1513 memory_dump(mon, count, format, size, addr, 0);
1516 static void do_physical_memory_dump(Monitor *mon, const QDict *qdict)
1518 int count = qdict_get_int(qdict, "count");
1519 int format = qdict_get_int(qdict, "format");
1520 int size = qdict_get_int(qdict, "size");
1521 target_phys_addr_t addr = qdict_get_int(qdict, "addr");
1523 memory_dump(mon, count, format, size, addr, 1);
1526 static void do_print(Monitor *mon, const QDict *qdict)
1528 int format = qdict_get_int(qdict, "format");
1529 target_phys_addr_t val = qdict_get_int(qdict, "val");
1531 #if TARGET_PHYS_ADDR_BITS == 32
1532 switch(format) {
1533 case 'o':
1534 monitor_printf(mon, "%#o", val);
1535 break;
1536 case 'x':
1537 monitor_printf(mon, "%#x", val);
1538 break;
1539 case 'u':
1540 monitor_printf(mon, "%u", val);
1541 break;
1542 default:
1543 case 'd':
1544 monitor_printf(mon, "%d", val);
1545 break;
1546 case 'c':
1547 monitor_printc(mon, val);
1548 break;
1550 #else
1551 switch(format) {
1552 case 'o':
1553 monitor_printf(mon, "%#" PRIo64, val);
1554 break;
1555 case 'x':
1556 monitor_printf(mon, "%#" PRIx64, val);
1557 break;
1558 case 'u':
1559 monitor_printf(mon, "%" PRIu64, val);
1560 break;
1561 default:
1562 case 'd':
1563 monitor_printf(mon, "%" PRId64, val);
1564 break;
1565 case 'c':
1566 monitor_printc(mon, val);
1567 break;
1569 #endif
1570 monitor_printf(mon, "\n");
1573 static int do_memory_save(Monitor *mon, const QDict *qdict, QObject **ret_data)
1575 FILE *f;
1576 uint32_t size = qdict_get_int(qdict, "size");
1577 const char *filename = qdict_get_str(qdict, "filename");
1578 target_long addr = qdict_get_int(qdict, "val");
1579 uint32_t l;
1580 CPUState *env;
1581 uint8_t buf[1024];
1582 int ret = -1;
1584 env = mon_get_cpu();
1586 f = fopen(filename, "wb");
1587 if (!f) {
1588 qerror_report(QERR_OPEN_FILE_FAILED, filename);
1589 return -1;
1591 while (size != 0) {
1592 l = sizeof(buf);
1593 if (l > size)
1594 l = size;
1595 cpu_memory_rw_debug(env, addr, buf, l, 0);
1596 if (fwrite(buf, 1, l, f) != l) {
1597 monitor_printf(mon, "fwrite() error in do_memory_save\n");
1598 goto exit;
1600 addr += l;
1601 size -= l;
1604 ret = 0;
1606 exit:
1607 fclose(f);
1608 return ret;
1611 static int do_physical_memory_save(Monitor *mon, const QDict *qdict,
1612 QObject **ret_data)
1614 FILE *f;
1615 uint32_t l;
1616 uint8_t buf[1024];
1617 uint32_t size = qdict_get_int(qdict, "size");
1618 const char *filename = qdict_get_str(qdict, "filename");
1619 target_phys_addr_t addr = qdict_get_int(qdict, "val");
1620 int ret = -1;
1622 f = fopen(filename, "wb");
1623 if (!f) {
1624 qerror_report(QERR_OPEN_FILE_FAILED, filename);
1625 return -1;
1627 while (size != 0) {
1628 l = sizeof(buf);
1629 if (l > size)
1630 l = size;
1631 cpu_physical_memory_rw(addr, buf, l, 0);
1632 if (fwrite(buf, 1, l, f) != l) {
1633 monitor_printf(mon, "fwrite() error in do_physical_memory_save\n");
1634 goto exit;
1636 fflush(f);
1637 addr += l;
1638 size -= l;
1641 ret = 0;
1643 exit:
1644 fclose(f);
1645 return ret;
1648 static void do_sum(Monitor *mon, const QDict *qdict)
1650 uint32_t addr;
1651 uint8_t buf[1];
1652 uint16_t sum;
1653 uint32_t start = qdict_get_int(qdict, "start");
1654 uint32_t size = qdict_get_int(qdict, "size");
1656 sum = 0;
1657 for(addr = start; addr < (start + size); addr++) {
1658 cpu_physical_memory_rw(addr, buf, 1, 0);
1659 /* BSD sum algorithm ('sum' Unix command) */
1660 sum = (sum >> 1) | (sum << 15);
1661 sum += buf[0];
1663 monitor_printf(mon, "%05d\n", sum);
1666 typedef struct {
1667 int keycode;
1668 const char *name;
1669 } KeyDef;
1671 static const KeyDef key_defs[] = {
1672 { 0x2a, "shift" },
1673 { 0x36, "shift_r" },
1675 { 0x38, "alt" },
1676 { 0xb8, "alt_r" },
1677 { 0x64, "altgr" },
1678 { 0xe4, "altgr_r" },
1679 { 0x1d, "ctrl" },
1680 { 0x9d, "ctrl_r" },
1682 { 0xdd, "menu" },
1684 { 0x01, "esc" },
1686 { 0x02, "1" },
1687 { 0x03, "2" },
1688 { 0x04, "3" },
1689 { 0x05, "4" },
1690 { 0x06, "5" },
1691 { 0x07, "6" },
1692 { 0x08, "7" },
1693 { 0x09, "8" },
1694 { 0x0a, "9" },
1695 { 0x0b, "0" },
1696 { 0x0c, "minus" },
1697 { 0x0d, "equal" },
1698 { 0x0e, "backspace" },
1700 { 0x0f, "tab" },
1701 { 0x10, "q" },
1702 { 0x11, "w" },
1703 { 0x12, "e" },
1704 { 0x13, "r" },
1705 { 0x14, "t" },
1706 { 0x15, "y" },
1707 { 0x16, "u" },
1708 { 0x17, "i" },
1709 { 0x18, "o" },
1710 { 0x19, "p" },
1711 { 0x1a, "bracket_left" },
1712 { 0x1b, "bracket_right" },
1713 { 0x1c, "ret" },
1715 { 0x1e, "a" },
1716 { 0x1f, "s" },
1717 { 0x20, "d" },
1718 { 0x21, "f" },
1719 { 0x22, "g" },
1720 { 0x23, "h" },
1721 { 0x24, "j" },
1722 { 0x25, "k" },
1723 { 0x26, "l" },
1724 { 0x27, "semicolon" },
1725 { 0x28, "apostrophe" },
1726 { 0x29, "grave_accent" },
1728 { 0x2b, "backslash" },
1729 { 0x2c, "z" },
1730 { 0x2d, "x" },
1731 { 0x2e, "c" },
1732 { 0x2f, "v" },
1733 { 0x30, "b" },
1734 { 0x31, "n" },
1735 { 0x32, "m" },
1736 { 0x33, "comma" },
1737 { 0x34, "dot" },
1738 { 0x35, "slash" },
1740 { 0x37, "asterisk" },
1742 { 0x39, "spc" },
1743 { 0x3a, "caps_lock" },
1744 { 0x3b, "f1" },
1745 { 0x3c, "f2" },
1746 { 0x3d, "f3" },
1747 { 0x3e, "f4" },
1748 { 0x3f, "f5" },
1749 { 0x40, "f6" },
1750 { 0x41, "f7" },
1751 { 0x42, "f8" },
1752 { 0x43, "f9" },
1753 { 0x44, "f10" },
1754 { 0x45, "num_lock" },
1755 { 0x46, "scroll_lock" },
1757 { 0xb5, "kp_divide" },
1758 { 0x37, "kp_multiply" },
1759 { 0x4a, "kp_subtract" },
1760 { 0x4e, "kp_add" },
1761 { 0x9c, "kp_enter" },
1762 { 0x53, "kp_decimal" },
1763 { 0x54, "sysrq" },
1765 { 0x52, "kp_0" },
1766 { 0x4f, "kp_1" },
1767 { 0x50, "kp_2" },
1768 { 0x51, "kp_3" },
1769 { 0x4b, "kp_4" },
1770 { 0x4c, "kp_5" },
1771 { 0x4d, "kp_6" },
1772 { 0x47, "kp_7" },
1773 { 0x48, "kp_8" },
1774 { 0x49, "kp_9" },
1776 { 0x56, "<" },
1778 { 0x57, "f11" },
1779 { 0x58, "f12" },
1781 { 0xb7, "print" },
1783 { 0xc7, "home" },
1784 { 0xc9, "pgup" },
1785 { 0xd1, "pgdn" },
1786 { 0xcf, "end" },
1788 { 0xcb, "left" },
1789 { 0xc8, "up" },
1790 { 0xd0, "down" },
1791 { 0xcd, "right" },
1793 { 0xd2, "insert" },
1794 { 0xd3, "delete" },
1795 #if defined(TARGET_SPARC) && !defined(TARGET_SPARC64)
1796 { 0xf0, "stop" },
1797 { 0xf1, "again" },
1798 { 0xf2, "props" },
1799 { 0xf3, "undo" },
1800 { 0xf4, "front" },
1801 { 0xf5, "copy" },
1802 { 0xf6, "open" },
1803 { 0xf7, "paste" },
1804 { 0xf8, "find" },
1805 { 0xf9, "cut" },
1806 { 0xfa, "lf" },
1807 { 0xfb, "help" },
1808 { 0xfc, "meta_l" },
1809 { 0xfd, "meta_r" },
1810 { 0xfe, "compose" },
1811 #endif
1812 { 0, NULL },
1815 static int get_keycode(const char *key)
1817 const KeyDef *p;
1818 char *endp;
1819 int ret;
1821 for(p = key_defs; p->name != NULL; p++) {
1822 if (!strcmp(key, p->name))
1823 return p->keycode;
1825 if (strstart(key, "0x", NULL)) {
1826 ret = strtoul(key, &endp, 0);
1827 if (*endp == '\0' && ret >= 0x01 && ret <= 0xff)
1828 return ret;
1830 return -1;
1833 #define MAX_KEYCODES 16
1834 static uint8_t keycodes[MAX_KEYCODES];
1835 static int nb_pending_keycodes;
1836 static QEMUTimer *key_timer;
1838 static void release_keys(void *opaque)
1840 int keycode;
1842 while (nb_pending_keycodes > 0) {
1843 nb_pending_keycodes--;
1844 keycode = keycodes[nb_pending_keycodes];
1845 if (keycode & 0x80)
1846 kbd_put_keycode(0xe0);
1847 kbd_put_keycode(keycode | 0x80);
1851 static void do_sendkey(Monitor *mon, const QDict *qdict)
1853 char keyname_buf[16];
1854 char *separator;
1855 int keyname_len, keycode, i;
1856 const char *string = qdict_get_str(qdict, "string");
1857 int has_hold_time = qdict_haskey(qdict, "hold_time");
1858 int hold_time = qdict_get_try_int(qdict, "hold_time", -1);
1860 if (nb_pending_keycodes > 0) {
1861 qemu_del_timer(key_timer);
1862 release_keys(NULL);
1864 if (!has_hold_time)
1865 hold_time = 100;
1866 i = 0;
1867 while (1) {
1868 separator = strchr(string, '-');
1869 keyname_len = separator ? separator - string : strlen(string);
1870 if (keyname_len > 0) {
1871 pstrcpy(keyname_buf, sizeof(keyname_buf), string);
1872 if (keyname_len > sizeof(keyname_buf) - 1) {
1873 monitor_printf(mon, "invalid key: '%s...'\n", keyname_buf);
1874 return;
1876 if (i == MAX_KEYCODES) {
1877 monitor_printf(mon, "too many keys\n");
1878 return;
1880 keyname_buf[keyname_len] = 0;
1881 keycode = get_keycode(keyname_buf);
1882 if (keycode < 0) {
1883 monitor_printf(mon, "unknown key: '%s'\n", keyname_buf);
1884 return;
1886 keycodes[i++] = keycode;
1888 if (!separator)
1889 break;
1890 string = separator + 1;
1892 nb_pending_keycodes = i;
1893 /* key down events */
1894 for (i = 0; i < nb_pending_keycodes; i++) {
1895 keycode = keycodes[i];
1896 if (keycode & 0x80)
1897 kbd_put_keycode(0xe0);
1898 kbd_put_keycode(keycode & 0x7f);
1900 /* delayed key up events */
1901 qemu_mod_timer(key_timer, qemu_get_clock_ns(vm_clock) +
1902 muldiv64(get_ticks_per_sec(), hold_time, 1000));
1905 static int mouse_button_state;
1907 static void do_mouse_move(Monitor *mon, const QDict *qdict)
1909 int dx, dy, dz;
1910 const char *dx_str = qdict_get_str(qdict, "dx_str");
1911 const char *dy_str = qdict_get_str(qdict, "dy_str");
1912 const char *dz_str = qdict_get_try_str(qdict, "dz_str");
1913 dx = strtol(dx_str, NULL, 0);
1914 dy = strtol(dy_str, NULL, 0);
1915 dz = 0;
1916 if (dz_str)
1917 dz = strtol(dz_str, NULL, 0);
1918 kbd_mouse_event(dx, dy, dz, mouse_button_state);
1921 static void do_mouse_button(Monitor *mon, const QDict *qdict)
1923 int button_state = qdict_get_int(qdict, "button_state");
1924 mouse_button_state = button_state;
1925 kbd_mouse_event(0, 0, 0, mouse_button_state);
1928 static void do_ioport_read(Monitor *mon, const QDict *qdict)
1930 int size = qdict_get_int(qdict, "size");
1931 int addr = qdict_get_int(qdict, "addr");
1932 int has_index = qdict_haskey(qdict, "index");
1933 uint32_t val;
1934 int suffix;
1936 if (has_index) {
1937 int index = qdict_get_int(qdict, "index");
1938 cpu_outb(addr & IOPORTS_MASK, index & 0xff);
1939 addr++;
1941 addr &= 0xffff;
1943 switch(size) {
1944 default:
1945 case 1:
1946 val = cpu_inb(addr);
1947 suffix = 'b';
1948 break;
1949 case 2:
1950 val = cpu_inw(addr);
1951 suffix = 'w';
1952 break;
1953 case 4:
1954 val = cpu_inl(addr);
1955 suffix = 'l';
1956 break;
1958 monitor_printf(mon, "port%c[0x%04x] = %#0*x\n",
1959 suffix, addr, size * 2, val);
1962 static void do_ioport_write(Monitor *mon, const QDict *qdict)
1964 int size = qdict_get_int(qdict, "size");
1965 int addr = qdict_get_int(qdict, "addr");
1966 int val = qdict_get_int(qdict, "val");
1968 addr &= IOPORTS_MASK;
1970 switch (size) {
1971 default:
1972 case 1:
1973 cpu_outb(addr, val);
1974 break;
1975 case 2:
1976 cpu_outw(addr, val);
1977 break;
1978 case 4:
1979 cpu_outl(addr, val);
1980 break;
1984 static void do_boot_set(Monitor *mon, const QDict *qdict)
1986 int res;
1987 const char *bootdevice = qdict_get_str(qdict, "bootdevice");
1989 res = qemu_boot_set(bootdevice);
1990 if (res == 0) {
1991 monitor_printf(mon, "boot device list now set to %s\n", bootdevice);
1992 } else if (res > 0) {
1993 monitor_printf(mon, "setting boot device list failed\n");
1994 } else {
1995 monitor_printf(mon, "no function defined to set boot device list for "
1996 "this architecture\n");
2001 * do_system_reset(): Issue a machine reset
2003 static int do_system_reset(Monitor *mon, const QDict *qdict,
2004 QObject **ret_data)
2006 qemu_system_reset_request();
2007 return 0;
2011 * do_system_powerdown(): Issue a machine powerdown
2013 static int do_system_powerdown(Monitor *mon, const QDict *qdict,
2014 QObject **ret_data)
2016 qemu_system_powerdown_request();
2017 return 0;
2020 #if defined(TARGET_I386)
2021 static void print_pte(Monitor *mon, target_phys_addr_t addr,
2022 target_phys_addr_t pte,
2023 target_phys_addr_t mask)
2025 #ifdef TARGET_X86_64
2026 if (addr & (1ULL << 47)) {
2027 addr |= -1LL << 48;
2029 #endif
2030 monitor_printf(mon, TARGET_FMT_plx ": " TARGET_FMT_plx
2031 " %c%c%c%c%c%c%c%c%c\n",
2032 addr,
2033 pte & mask,
2034 pte & PG_NX_MASK ? 'X' : '-',
2035 pte & PG_GLOBAL_MASK ? 'G' : '-',
2036 pte & PG_PSE_MASK ? 'P' : '-',
2037 pte & PG_DIRTY_MASK ? 'D' : '-',
2038 pte & PG_ACCESSED_MASK ? 'A' : '-',
2039 pte & PG_PCD_MASK ? 'C' : '-',
2040 pte & PG_PWT_MASK ? 'T' : '-',
2041 pte & PG_USER_MASK ? 'U' : '-',
2042 pte & PG_RW_MASK ? 'W' : '-');
2045 static void tlb_info_32(Monitor *mon, CPUState *env)
2047 int l1, l2;
2048 uint32_t pgd, pde, pte;
2050 pgd = env->cr[3] & ~0xfff;
2051 for(l1 = 0; l1 < 1024; l1++) {
2052 cpu_physical_memory_read(pgd + l1 * 4, (uint8_t *)&pde, 4);
2053 pde = le32_to_cpu(pde);
2054 if (pde & PG_PRESENT_MASK) {
2055 if ((pde & PG_PSE_MASK) && (env->cr[4] & CR4_PSE_MASK)) {
2056 /* 4M pages */
2057 print_pte(mon, (l1 << 22), pde, ~((1 << 21) - 1));
2058 } else {
2059 for(l2 = 0; l2 < 1024; l2++) {
2060 cpu_physical_memory_read((pde & ~0xfff) + l2 * 4,
2061 (uint8_t *)&pte, 4);
2062 pte = le32_to_cpu(pte);
2063 if (pte & PG_PRESENT_MASK) {
2064 print_pte(mon, (l1 << 22) + (l2 << 12),
2065 pte & ~PG_PSE_MASK,
2066 ~0xfff);
2074 static void tlb_info_pae32(Monitor *mon, CPUState *env)
2076 int l1, l2, l3;
2077 uint64_t pdpe, pde, pte;
2078 uint64_t pdp_addr, pd_addr, pt_addr;
2080 pdp_addr = env->cr[3] & ~0x1f;
2081 for (l1 = 0; l1 < 4; l1++) {
2082 cpu_physical_memory_read(pdp_addr + l1 * 8, (uint8_t *)&pdpe, 8);
2083 pdpe = le64_to_cpu(pdpe);
2084 if (pdpe & PG_PRESENT_MASK) {
2085 pd_addr = pdpe & 0x3fffffffff000ULL;
2086 for (l2 = 0; l2 < 512; l2++) {
2087 cpu_physical_memory_read(pd_addr + l2 * 8,
2088 (uint8_t *)&pde, 8);
2089 pde = le64_to_cpu(pde);
2090 if (pde & PG_PRESENT_MASK) {
2091 if (pde & PG_PSE_MASK) {
2092 /* 2M pages with PAE, CR4.PSE is ignored */
2093 print_pte(mon, (l1 << 30 ) + (l2 << 21), pde,
2094 ~((target_phys_addr_t)(1 << 20) - 1));
2095 } else {
2096 pt_addr = pde & 0x3fffffffff000ULL;
2097 for (l3 = 0; l3 < 512; l3++) {
2098 cpu_physical_memory_read(pt_addr + l3 * 8,
2099 (uint8_t *)&pte, 8);
2100 pte = le64_to_cpu(pte);
2101 if (pte & PG_PRESENT_MASK) {
2102 print_pte(mon, (l1 << 30 ) + (l2 << 21)
2103 + (l3 << 12),
2104 pte & ~PG_PSE_MASK,
2105 ~(target_phys_addr_t)0xfff);
2115 #ifdef TARGET_X86_64
2116 static void tlb_info_64(Monitor *mon, CPUState *env)
2118 uint64_t l1, l2, l3, l4;
2119 uint64_t pml4e, pdpe, pde, pte;
2120 uint64_t pml4_addr, pdp_addr, pd_addr, pt_addr;
2122 pml4_addr = env->cr[3] & 0x3fffffffff000ULL;
2123 for (l1 = 0; l1 < 512; l1++) {
2124 cpu_physical_memory_read(pml4_addr + l1 * 8, (uint8_t *)&pml4e, 8);
2125 pml4e = le64_to_cpu(pml4e);
2126 if (pml4e & PG_PRESENT_MASK) {
2127 pdp_addr = pml4e & 0x3fffffffff000ULL;
2128 for (l2 = 0; l2 < 512; l2++) {
2129 cpu_physical_memory_read(pdp_addr + l2 * 8, (uint8_t *)&pdpe,
2131 pdpe = le64_to_cpu(pdpe);
2132 if (pdpe & PG_PRESENT_MASK) {
2133 if (pdpe & PG_PSE_MASK) {
2134 /* 1G pages, CR4.PSE is ignored */
2135 print_pte(mon, (l1 << 39) + (l2 << 30), pdpe,
2136 0x3ffffc0000000ULL);
2137 } else {
2138 pd_addr = pdpe & 0x3fffffffff000ULL;
2139 for (l3 = 0; l3 < 512; l3++) {
2140 cpu_physical_memory_read(pd_addr + l3 * 8,
2141 (uint8_t *)&pde, 8);
2142 pde = le64_to_cpu(pde);
2143 if (pde & PG_PRESENT_MASK) {
2144 if (pde & PG_PSE_MASK) {
2145 /* 2M pages, CR4.PSE is ignored */
2146 print_pte(mon, (l1 << 39) + (l2 << 30) +
2147 (l3 << 21), pde,
2148 0x3ffffffe00000ULL);
2149 } else {
2150 pt_addr = pde & 0x3fffffffff000ULL;
2151 for (l4 = 0; l4 < 512; l4++) {
2152 cpu_physical_memory_read(pt_addr
2153 + l4 * 8,
2154 (uint8_t *)&pte,
2156 pte = le64_to_cpu(pte);
2157 if (pte & PG_PRESENT_MASK) {
2158 print_pte(mon, (l1 << 39) +
2159 (l2 << 30) +
2160 (l3 << 21) + (l4 << 12),
2161 pte & ~PG_PSE_MASK,
2162 0x3fffffffff000ULL);
2174 #endif
2176 static void tlb_info(Monitor *mon)
2178 CPUState *env;
2180 env = mon_get_cpu();
2182 if (!(env->cr[0] & CR0_PG_MASK)) {
2183 monitor_printf(mon, "PG disabled\n");
2184 return;
2186 if (env->cr[4] & CR4_PAE_MASK) {
2187 #ifdef TARGET_X86_64
2188 if (env->hflags & HF_LMA_MASK) {
2189 tlb_info_64(mon, env);
2190 } else
2191 #endif
2193 tlb_info_pae32(mon, env);
2195 } else {
2196 tlb_info_32(mon, env);
2200 static void mem_print(Monitor *mon, target_phys_addr_t *pstart,
2201 int *plast_prot,
2202 target_phys_addr_t end, int prot)
2204 int prot1;
2205 prot1 = *plast_prot;
2206 if (prot != prot1) {
2207 if (*pstart != -1) {
2208 monitor_printf(mon, TARGET_FMT_plx "-" TARGET_FMT_plx " "
2209 TARGET_FMT_plx " %c%c%c\n",
2210 *pstart, end, end - *pstart,
2211 prot1 & PG_USER_MASK ? 'u' : '-',
2212 'r',
2213 prot1 & PG_RW_MASK ? 'w' : '-');
2215 if (prot != 0)
2216 *pstart = end;
2217 else
2218 *pstart = -1;
2219 *plast_prot = prot;
2223 static void mem_info_32(Monitor *mon, CPUState *env)
2225 int l1, l2, prot, last_prot;
2226 uint32_t pgd, pde, pte;
2227 target_phys_addr_t start, end;
2229 pgd = env->cr[3] & ~0xfff;
2230 last_prot = 0;
2231 start = -1;
2232 for(l1 = 0; l1 < 1024; l1++) {
2233 cpu_physical_memory_read(pgd + l1 * 4, (uint8_t *)&pde, 4);
2234 pde = le32_to_cpu(pde);
2235 end = l1 << 22;
2236 if (pde & PG_PRESENT_MASK) {
2237 if ((pde & PG_PSE_MASK) && (env->cr[4] & CR4_PSE_MASK)) {
2238 prot = pde & (PG_USER_MASK | PG_RW_MASK | PG_PRESENT_MASK);
2239 mem_print(mon, &start, &last_prot, end, prot);
2240 } else {
2241 for(l2 = 0; l2 < 1024; l2++) {
2242 cpu_physical_memory_read((pde & ~0xfff) + l2 * 4,
2243 (uint8_t *)&pte, 4);
2244 pte = le32_to_cpu(pte);
2245 end = (l1 << 22) + (l2 << 12);
2246 if (pte & PG_PRESENT_MASK) {
2247 prot = pte & (PG_USER_MASK | PG_RW_MASK | PG_PRESENT_MASK);
2248 } else {
2249 prot = 0;
2251 mem_print(mon, &start, &last_prot, end, prot);
2254 } else {
2255 prot = 0;
2256 mem_print(mon, &start, &last_prot, end, prot);
2261 static void mem_info_pae32(Monitor *mon, CPUState *env)
2263 int l1, l2, l3, prot, last_prot;
2264 uint64_t pdpe, pde, pte;
2265 uint64_t pdp_addr, pd_addr, pt_addr;
2266 target_phys_addr_t start, end;
2268 pdp_addr = env->cr[3] & ~0x1f;
2269 last_prot = 0;
2270 start = -1;
2271 for (l1 = 0; l1 < 4; l1++) {
2272 cpu_physical_memory_read(pdp_addr + l1 * 8, (uint8_t *)&pdpe, 8);
2273 pdpe = le64_to_cpu(pdpe);
2274 end = l1 << 30;
2275 if (pdpe & PG_PRESENT_MASK) {
2276 pd_addr = pdpe & 0x3fffffffff000ULL;
2277 for (l2 = 0; l2 < 512; l2++) {
2278 cpu_physical_memory_read(pd_addr + l2 * 8,
2279 (uint8_t *)&pde, 8);
2280 pde = le64_to_cpu(pde);
2281 end = (l1 << 30) + (l2 << 21);
2282 if (pde & PG_PRESENT_MASK) {
2283 if (pde & PG_PSE_MASK) {
2284 prot = pde & (PG_USER_MASK | PG_RW_MASK |
2285 PG_PRESENT_MASK);
2286 mem_print(mon, &start, &last_prot, end, prot);
2287 } else {
2288 pt_addr = pde & 0x3fffffffff000ULL;
2289 for (l3 = 0; l3 < 512; l3++) {
2290 cpu_physical_memory_read(pt_addr + l3 * 8,
2291 (uint8_t *)&pte, 8);
2292 pte = le64_to_cpu(pte);
2293 end = (l1 << 30) + (l2 << 21) + (l3 << 12);
2294 if (pte & PG_PRESENT_MASK) {
2295 prot = pte & (PG_USER_MASK | PG_RW_MASK |
2296 PG_PRESENT_MASK);
2297 } else {
2298 prot = 0;
2300 mem_print(mon, &start, &last_prot, end, prot);
2303 } else {
2304 prot = 0;
2305 mem_print(mon, &start, &last_prot, end, prot);
2308 } else {
2309 prot = 0;
2310 mem_print(mon, &start, &last_prot, end, prot);
2316 #ifdef TARGET_X86_64
2317 static void mem_info_64(Monitor *mon, CPUState *env)
2319 int prot, last_prot;
2320 uint64_t l1, l2, l3, l4;
2321 uint64_t pml4e, pdpe, pde, pte;
2322 uint64_t pml4_addr, pdp_addr, pd_addr, pt_addr, start, end;
2324 pml4_addr = env->cr[3] & 0x3fffffffff000ULL;
2325 last_prot = 0;
2326 start = -1;
2327 for (l1 = 0; l1 < 512; l1++) {
2328 cpu_physical_memory_read(pml4_addr + l1 * 8, (uint8_t *)&pml4e, 8);
2329 pml4e = le64_to_cpu(pml4e);
2330 end = l1 << 39;
2331 if (pml4e & PG_PRESENT_MASK) {
2332 pdp_addr = pml4e & 0x3fffffffff000ULL;
2333 for (l2 = 0; l2 < 512; l2++) {
2334 cpu_physical_memory_read(pdp_addr + l2 * 8, (uint8_t *)&pdpe,
2336 pdpe = le64_to_cpu(pdpe);
2337 end = (l1 << 39) + (l2 << 30);
2338 if (pdpe & PG_PRESENT_MASK) {
2339 if (pdpe & PG_PSE_MASK) {
2340 prot = pdpe & (PG_USER_MASK | PG_RW_MASK |
2341 PG_PRESENT_MASK);
2342 mem_print(mon, &start, &last_prot, end, prot);
2343 } else {
2344 pd_addr = pdpe & 0x3fffffffff000ULL;
2345 for (l3 = 0; l3 < 512; l3++) {
2346 cpu_physical_memory_read(pd_addr + l3 * 8,
2347 (uint8_t *)&pde, 8);
2348 pde = le64_to_cpu(pde);
2349 end = (l1 << 39) + (l2 << 30) + (l3 << 21);
2350 if (pde & PG_PRESENT_MASK) {
2351 if (pde & PG_PSE_MASK) {
2352 prot = pde & (PG_USER_MASK | PG_RW_MASK |
2353 PG_PRESENT_MASK);
2354 mem_print(mon, &start, &last_prot, end, prot);
2355 } else {
2356 pt_addr = pde & 0x3fffffffff000ULL;
2357 for (l4 = 0; l4 < 512; l4++) {
2358 cpu_physical_memory_read(pt_addr
2359 + l4 * 8,
2360 (uint8_t *)&pte,
2362 pte = le64_to_cpu(pte);
2363 end = (l1 << 39) + (l2 << 30) +
2364 (l3 << 21) + (l4 << 12);
2365 if (pte & PG_PRESENT_MASK) {
2366 prot = pte & (PG_USER_MASK | PG_RW_MASK |
2367 PG_PRESENT_MASK);
2368 } else {
2369 prot = 0;
2371 mem_print(mon, &start, &last_prot, end, prot);
2374 } else {
2375 prot = 0;
2376 mem_print(mon, &start, &last_prot, end, prot);
2380 } else {
2381 prot = 0;
2382 mem_print(mon, &start, &last_prot, end, prot);
2385 } else {
2386 prot = 0;
2387 mem_print(mon, &start, &last_prot, end, prot);
2391 #endif
2393 static void mem_info(Monitor *mon)
2395 CPUState *env;
2397 env = mon_get_cpu();
2399 if (!(env->cr[0] & CR0_PG_MASK)) {
2400 monitor_printf(mon, "PG disabled\n");
2401 return;
2403 if (env->cr[4] & CR4_PAE_MASK) {
2404 #ifdef TARGET_X86_64
2405 if (env->hflags & HF_LMA_MASK) {
2406 mem_info_64(mon, env);
2407 } else
2408 #endif
2410 mem_info_pae32(mon, env);
2412 } else {
2413 mem_info_32(mon, env);
2416 #endif
2418 #if defined(TARGET_SH4)
2420 static void print_tlb(Monitor *mon, int idx, tlb_t *tlb)
2422 monitor_printf(mon, " tlb%i:\t"
2423 "asid=%hhu vpn=%x\tppn=%x\tsz=%hhu size=%u\t"
2424 "v=%hhu shared=%hhu cached=%hhu prot=%hhu "
2425 "dirty=%hhu writethrough=%hhu\n",
2426 idx,
2427 tlb->asid, tlb->vpn, tlb->ppn, tlb->sz, tlb->size,
2428 tlb->v, tlb->sh, tlb->c, tlb->pr,
2429 tlb->d, tlb->wt);
2432 static void tlb_info(Monitor *mon)
2434 CPUState *env = mon_get_cpu();
2435 int i;
2437 monitor_printf (mon, "ITLB:\n");
2438 for (i = 0 ; i < ITLB_SIZE ; i++)
2439 print_tlb (mon, i, &env->itlb[i]);
2440 monitor_printf (mon, "UTLB:\n");
2441 for (i = 0 ; i < UTLB_SIZE ; i++)
2442 print_tlb (mon, i, &env->utlb[i]);
2445 #endif
2447 #if defined(TARGET_SPARC)
2448 static void tlb_info(Monitor *mon)
2450 CPUState *env1 = mon_get_cpu();
2452 dump_mmu((FILE*)mon, (fprintf_function)monitor_printf, env1);
2454 #endif
2456 static void do_info_kvm_print(Monitor *mon, const QObject *data)
2458 QDict *qdict;
2460 qdict = qobject_to_qdict(data);
2462 monitor_printf(mon, "kvm support: ");
2463 if (qdict_get_bool(qdict, "present")) {
2464 monitor_printf(mon, "%s\n", qdict_get_bool(qdict, "enabled") ?
2465 "enabled" : "disabled");
2466 } else {
2467 monitor_printf(mon, "not compiled\n");
2471 static void do_info_kvm(Monitor *mon, QObject **ret_data)
2473 #ifdef CONFIG_KVM
2474 *ret_data = qobject_from_jsonf("{ 'enabled': %i, 'present': true }",
2475 kvm_enabled());
2476 #else
2477 *ret_data = qobject_from_jsonf("{ 'enabled': false, 'present': false }");
2478 #endif
2481 static void do_info_numa(Monitor *mon)
2483 int i;
2484 CPUState *env;
2486 monitor_printf(mon, "%d nodes\n", nb_numa_nodes);
2487 for (i = 0; i < nb_numa_nodes; i++) {
2488 monitor_printf(mon, "node %d cpus:", i);
2489 for (env = first_cpu; env != NULL; env = env->next_cpu) {
2490 if (env->numa_node == i) {
2491 monitor_printf(mon, " %d", env->cpu_index);
2494 monitor_printf(mon, "\n");
2495 monitor_printf(mon, "node %d size: %" PRId64 " MB\n", i,
2496 node_mem[i] >> 20);
2500 #ifdef CONFIG_PROFILER
2502 int64_t qemu_time;
2503 int64_t dev_time;
2505 static void do_info_profile(Monitor *mon)
2507 int64_t total;
2508 total = qemu_time;
2509 if (total == 0)
2510 total = 1;
2511 monitor_printf(mon, "async time %" PRId64 " (%0.3f)\n",
2512 dev_time, dev_time / (double)get_ticks_per_sec());
2513 monitor_printf(mon, "qemu time %" PRId64 " (%0.3f)\n",
2514 qemu_time, qemu_time / (double)get_ticks_per_sec());
2515 qemu_time = 0;
2516 dev_time = 0;
2518 #else
2519 static void do_info_profile(Monitor *mon)
2521 monitor_printf(mon, "Internal profiler not compiled\n");
2523 #endif
2525 /* Capture support */
2526 static QLIST_HEAD (capture_list_head, CaptureState) capture_head;
2528 static void do_info_capture(Monitor *mon)
2530 int i;
2531 CaptureState *s;
2533 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
2534 monitor_printf(mon, "[%d]: ", i);
2535 s->ops.info (s->opaque);
2539 #ifdef HAS_AUDIO
2540 static void do_stop_capture(Monitor *mon, const QDict *qdict)
2542 int i;
2543 int n = qdict_get_int(qdict, "n");
2544 CaptureState *s;
2546 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
2547 if (i == n) {
2548 s->ops.destroy (s->opaque);
2549 QLIST_REMOVE (s, entries);
2550 qemu_free (s);
2551 return;
2556 static void do_wav_capture(Monitor *mon, const QDict *qdict)
2558 const char *path = qdict_get_str(qdict, "path");
2559 int has_freq = qdict_haskey(qdict, "freq");
2560 int freq = qdict_get_try_int(qdict, "freq", -1);
2561 int has_bits = qdict_haskey(qdict, "bits");
2562 int bits = qdict_get_try_int(qdict, "bits", -1);
2563 int has_channels = qdict_haskey(qdict, "nchannels");
2564 int nchannels = qdict_get_try_int(qdict, "nchannels", -1);
2565 CaptureState *s;
2567 s = qemu_mallocz (sizeof (*s));
2569 freq = has_freq ? freq : 44100;
2570 bits = has_bits ? bits : 16;
2571 nchannels = has_channels ? nchannels : 2;
2573 if (wav_start_capture (s, path, freq, bits, nchannels)) {
2574 monitor_printf(mon, "Failed to add wave capture\n");
2575 qemu_free (s);
2576 return;
2578 QLIST_INSERT_HEAD (&capture_head, s, entries);
2580 #endif
2582 #if defined(TARGET_I386)
2583 static void do_inject_nmi(Monitor *mon, const QDict *qdict)
2585 CPUState *env;
2586 int cpu_index = qdict_get_int(qdict, "cpu_index");
2588 for (env = first_cpu; env != NULL; env = env->next_cpu)
2589 if (env->cpu_index == cpu_index) {
2590 if (kvm_enabled())
2591 kvm_inject_interrupt(env, CPU_INTERRUPT_NMI);
2592 else
2593 cpu_interrupt(env, CPU_INTERRUPT_NMI);
2594 break;
2597 #endif
2599 static void do_info_status_print(Monitor *mon, const QObject *data)
2601 QDict *qdict;
2603 qdict = qobject_to_qdict(data);
2605 monitor_printf(mon, "VM status: ");
2606 if (qdict_get_bool(qdict, "running")) {
2607 monitor_printf(mon, "running");
2608 if (qdict_get_bool(qdict, "singlestep")) {
2609 monitor_printf(mon, " (single step mode)");
2611 } else {
2612 monitor_printf(mon, "paused");
2615 monitor_printf(mon, "\n");
2618 static void do_info_status(Monitor *mon, QObject **ret_data)
2620 *ret_data = qobject_from_jsonf("{ 'running': %i, 'singlestep': %i }",
2621 vm_running, singlestep);
2624 static qemu_acl *find_acl(Monitor *mon, const char *name)
2626 qemu_acl *acl = qemu_acl_find(name);
2628 if (!acl) {
2629 monitor_printf(mon, "acl: unknown list '%s'\n", name);
2631 return acl;
2634 static void do_acl_show(Monitor *mon, const QDict *qdict)
2636 const char *aclname = qdict_get_str(qdict, "aclname");
2637 qemu_acl *acl = find_acl(mon, aclname);
2638 qemu_acl_entry *entry;
2639 int i = 0;
2641 if (acl) {
2642 monitor_printf(mon, "policy: %s\n",
2643 acl->defaultDeny ? "deny" : "allow");
2644 QTAILQ_FOREACH(entry, &acl->entries, next) {
2645 i++;
2646 monitor_printf(mon, "%d: %s %s\n", i,
2647 entry->deny ? "deny" : "allow", entry->match);
2652 static void do_acl_reset(Monitor *mon, const QDict *qdict)
2654 const char *aclname = qdict_get_str(qdict, "aclname");
2655 qemu_acl *acl = find_acl(mon, aclname);
2657 if (acl) {
2658 qemu_acl_reset(acl);
2659 monitor_printf(mon, "acl: removed all rules\n");
2663 static void do_acl_policy(Monitor *mon, const QDict *qdict)
2665 const char *aclname = qdict_get_str(qdict, "aclname");
2666 const char *policy = qdict_get_str(qdict, "policy");
2667 qemu_acl *acl = find_acl(mon, aclname);
2669 if (acl) {
2670 if (strcmp(policy, "allow") == 0) {
2671 acl->defaultDeny = 0;
2672 monitor_printf(mon, "acl: policy set to 'allow'\n");
2673 } else if (strcmp(policy, "deny") == 0) {
2674 acl->defaultDeny = 1;
2675 monitor_printf(mon, "acl: policy set to 'deny'\n");
2676 } else {
2677 monitor_printf(mon, "acl: unknown policy '%s', "
2678 "expected 'deny' or 'allow'\n", policy);
2683 static void do_acl_add(Monitor *mon, const QDict *qdict)
2685 const char *aclname = qdict_get_str(qdict, "aclname");
2686 const char *match = qdict_get_str(qdict, "match");
2687 const char *policy = qdict_get_str(qdict, "policy");
2688 int has_index = qdict_haskey(qdict, "index");
2689 int index = qdict_get_try_int(qdict, "index", -1);
2690 qemu_acl *acl = find_acl(mon, aclname);
2691 int deny, ret;
2693 if (acl) {
2694 if (strcmp(policy, "allow") == 0) {
2695 deny = 0;
2696 } else if (strcmp(policy, "deny") == 0) {
2697 deny = 1;
2698 } else {
2699 monitor_printf(mon, "acl: unknown policy '%s', "
2700 "expected 'deny' or 'allow'\n", policy);
2701 return;
2703 if (has_index)
2704 ret = qemu_acl_insert(acl, deny, match, index);
2705 else
2706 ret = qemu_acl_append(acl, deny, match);
2707 if (ret < 0)
2708 monitor_printf(mon, "acl: unable to add acl entry\n");
2709 else
2710 monitor_printf(mon, "acl: added rule at position %d\n", ret);
2714 static void do_acl_remove(Monitor *mon, const QDict *qdict)
2716 const char *aclname = qdict_get_str(qdict, "aclname");
2717 const char *match = qdict_get_str(qdict, "match");
2718 qemu_acl *acl = find_acl(mon, aclname);
2719 int ret;
2721 if (acl) {
2722 ret = qemu_acl_remove(acl, match);
2723 if (ret < 0)
2724 monitor_printf(mon, "acl: no matching acl entry\n");
2725 else
2726 monitor_printf(mon, "acl: removed rule at position %d\n", ret);
2730 #if defined(TARGET_I386)
2731 static void do_inject_mce(Monitor *mon, const QDict *qdict)
2733 CPUState *cenv;
2734 int cpu_index = qdict_get_int(qdict, "cpu_index");
2735 int bank = qdict_get_int(qdict, "bank");
2736 uint64_t status = qdict_get_int(qdict, "status");
2737 uint64_t mcg_status = qdict_get_int(qdict, "mcg_status");
2738 uint64_t addr = qdict_get_int(qdict, "addr");
2739 uint64_t misc = qdict_get_int(qdict, "misc");
2740 int flags = MCE_INJECT_UNCOND_AO;
2742 if (qdict_get_try_bool(qdict, "broadcast", 0)) {
2743 flags |= MCE_INJECT_BROADCAST;
2745 for (cenv = first_cpu; cenv != NULL; cenv = cenv->next_cpu) {
2746 if (cenv->cpu_index == cpu_index) {
2747 cpu_x86_inject_mce(mon, cenv, bank, status, mcg_status, addr, misc,
2748 flags);
2749 break;
2753 #endif
2755 static int do_getfd(Monitor *mon, const QDict *qdict, QObject **ret_data)
2757 const char *fdname = qdict_get_str(qdict, "fdname");
2758 mon_fd_t *monfd;
2759 int fd;
2761 fd = qemu_chr_get_msgfd(mon->chr);
2762 if (fd == -1) {
2763 qerror_report(QERR_FD_NOT_SUPPLIED);
2764 return -1;
2767 if (qemu_isdigit(fdname[0])) {
2768 qerror_report(QERR_INVALID_PARAMETER_VALUE, "fdname",
2769 "a name not starting with a digit");
2770 return -1;
2773 QLIST_FOREACH(monfd, &mon->fds, next) {
2774 if (strcmp(monfd->name, fdname) != 0) {
2775 continue;
2778 close(monfd->fd);
2779 monfd->fd = fd;
2780 return 0;
2783 monfd = qemu_mallocz(sizeof(mon_fd_t));
2784 monfd->name = qemu_strdup(fdname);
2785 monfd->fd = fd;
2787 QLIST_INSERT_HEAD(&mon->fds, monfd, next);
2788 return 0;
2791 static int do_closefd(Monitor *mon, const QDict *qdict, QObject **ret_data)
2793 const char *fdname = qdict_get_str(qdict, "fdname");
2794 mon_fd_t *monfd;
2796 QLIST_FOREACH(monfd, &mon->fds, next) {
2797 if (strcmp(monfd->name, fdname) != 0) {
2798 continue;
2801 QLIST_REMOVE(monfd, next);
2802 close(monfd->fd);
2803 qemu_free(monfd->name);
2804 qemu_free(monfd);
2805 return 0;
2808 qerror_report(QERR_FD_NOT_FOUND, fdname);
2809 return -1;
2812 static void do_loadvm(Monitor *mon, const QDict *qdict)
2814 int saved_vm_running = vm_running;
2815 const char *name = qdict_get_str(qdict, "name");
2817 vm_stop(VMSTOP_LOADVM);
2819 if (load_vmstate(name) == 0 && saved_vm_running) {
2820 vm_start();
2824 int monitor_get_fd(Monitor *mon, const char *fdname)
2826 mon_fd_t *monfd;
2828 QLIST_FOREACH(monfd, &mon->fds, next) {
2829 int fd;
2831 if (strcmp(monfd->name, fdname) != 0) {
2832 continue;
2835 fd = monfd->fd;
2837 /* caller takes ownership of fd */
2838 QLIST_REMOVE(monfd, next);
2839 qemu_free(monfd->name);
2840 qemu_free(monfd);
2842 return fd;
2845 return -1;
2848 static const mon_cmd_t mon_cmds[] = {
2849 #include "hmp-commands.h"
2850 { NULL, NULL, },
2853 /* Please update hmp-commands.hx when adding or changing commands */
2854 static const mon_cmd_t info_cmds[] = {
2856 .name = "version",
2857 .args_type = "",
2858 .params = "",
2859 .help = "show the version of QEMU",
2860 .user_print = do_info_version_print,
2861 .mhandler.info_new = do_info_version,
2864 .name = "network",
2865 .args_type = "",
2866 .params = "",
2867 .help = "show the network state",
2868 .mhandler.info = do_info_network,
2871 .name = "chardev",
2872 .args_type = "",
2873 .params = "",
2874 .help = "show the character devices",
2875 .user_print = qemu_chr_info_print,
2876 .mhandler.info_new = qemu_chr_info,
2879 .name = "block",
2880 .args_type = "",
2881 .params = "",
2882 .help = "show the block devices",
2883 .user_print = bdrv_info_print,
2884 .mhandler.info_new = bdrv_info,
2887 .name = "blockstats",
2888 .args_type = "",
2889 .params = "",
2890 .help = "show block device statistics",
2891 .user_print = bdrv_stats_print,
2892 .mhandler.info_new = bdrv_info_stats,
2895 .name = "registers",
2896 .args_type = "",
2897 .params = "",
2898 .help = "show the cpu registers",
2899 .mhandler.info = do_info_registers,
2902 .name = "cpus",
2903 .args_type = "",
2904 .params = "",
2905 .help = "show infos for each CPU",
2906 .user_print = monitor_print_cpus,
2907 .mhandler.info_new = do_info_cpus,
2910 .name = "history",
2911 .args_type = "",
2912 .params = "",
2913 .help = "show the command line history",
2914 .mhandler.info = do_info_history,
2917 .name = "irq",
2918 .args_type = "",
2919 .params = "",
2920 .help = "show the interrupts statistics (if available)",
2921 .mhandler.info = irq_info,
2924 .name = "pic",
2925 .args_type = "",
2926 .params = "",
2927 .help = "show i8259 (PIC) state",
2928 .mhandler.info = pic_info,
2931 .name = "pci",
2932 .args_type = "",
2933 .params = "",
2934 .help = "show PCI info",
2935 .user_print = do_pci_info_print,
2936 .mhandler.info_new = do_pci_info,
2938 #if defined(TARGET_I386) || defined(TARGET_SH4) || defined(TARGET_SPARC)
2940 .name = "tlb",
2941 .args_type = "",
2942 .params = "",
2943 .help = "show virtual to physical memory mappings",
2944 .mhandler.info = tlb_info,
2946 #endif
2947 #if defined(TARGET_I386)
2949 .name = "mem",
2950 .args_type = "",
2951 .params = "",
2952 .help = "show the active virtual memory mappings",
2953 .mhandler.info = mem_info,
2955 #endif
2957 .name = "jit",
2958 .args_type = "",
2959 .params = "",
2960 .help = "show dynamic compiler info",
2961 .mhandler.info = do_info_jit,
2964 .name = "kvm",
2965 .args_type = "",
2966 .params = "",
2967 .help = "show KVM information",
2968 .user_print = do_info_kvm_print,
2969 .mhandler.info_new = do_info_kvm,
2972 .name = "numa",
2973 .args_type = "",
2974 .params = "",
2975 .help = "show NUMA information",
2976 .mhandler.info = do_info_numa,
2979 .name = "usb",
2980 .args_type = "",
2981 .params = "",
2982 .help = "show guest USB devices",
2983 .mhandler.info = usb_info,
2986 .name = "usbhost",
2987 .args_type = "",
2988 .params = "",
2989 .help = "show host USB devices",
2990 .mhandler.info = usb_host_info,
2993 .name = "profile",
2994 .args_type = "",
2995 .params = "",
2996 .help = "show profiling information",
2997 .mhandler.info = do_info_profile,
3000 .name = "capture",
3001 .args_type = "",
3002 .params = "",
3003 .help = "show capture information",
3004 .mhandler.info = do_info_capture,
3007 .name = "snapshots",
3008 .args_type = "",
3009 .params = "",
3010 .help = "show the currently saved VM snapshots",
3011 .mhandler.info = do_info_snapshots,
3014 .name = "status",
3015 .args_type = "",
3016 .params = "",
3017 .help = "show the current VM status (running|paused)",
3018 .user_print = do_info_status_print,
3019 .mhandler.info_new = do_info_status,
3022 .name = "pcmcia",
3023 .args_type = "",
3024 .params = "",
3025 .help = "show guest PCMCIA status",
3026 .mhandler.info = pcmcia_info,
3029 .name = "mice",
3030 .args_type = "",
3031 .params = "",
3032 .help = "show which guest mouse is receiving events",
3033 .user_print = do_info_mice_print,
3034 .mhandler.info_new = do_info_mice,
3037 .name = "vnc",
3038 .args_type = "",
3039 .params = "",
3040 .help = "show the vnc server status",
3041 .user_print = do_info_vnc_print,
3042 .mhandler.info_new = do_info_vnc,
3044 #if defined(CONFIG_SPICE)
3046 .name = "spice",
3047 .args_type = "",
3048 .params = "",
3049 .help = "show the spice server status",
3050 .user_print = do_info_spice_print,
3051 .mhandler.info_new = do_info_spice,
3053 #endif
3055 .name = "name",
3056 .args_type = "",
3057 .params = "",
3058 .help = "show the current VM name",
3059 .user_print = do_info_name_print,
3060 .mhandler.info_new = do_info_name,
3063 .name = "uuid",
3064 .args_type = "",
3065 .params = "",
3066 .help = "show the current VM UUID",
3067 .user_print = do_info_uuid_print,
3068 .mhandler.info_new = do_info_uuid,
3070 #if defined(TARGET_PPC)
3072 .name = "cpustats",
3073 .args_type = "",
3074 .params = "",
3075 .help = "show CPU statistics",
3076 .mhandler.info = do_info_cpu_stats,
3078 #endif
3079 #if defined(CONFIG_SLIRP)
3081 .name = "usernet",
3082 .args_type = "",
3083 .params = "",
3084 .help = "show user network stack connection states",
3085 .mhandler.info = do_info_usernet,
3087 #endif
3089 .name = "migrate",
3090 .args_type = "",
3091 .params = "",
3092 .help = "show migration status",
3093 .user_print = do_info_migrate_print,
3094 .mhandler.info_new = do_info_migrate,
3097 .name = "balloon",
3098 .args_type = "",
3099 .params = "",
3100 .help = "show balloon information",
3101 .user_print = monitor_print_balloon,
3102 .mhandler.info_async = do_info_balloon,
3103 .flags = MONITOR_CMD_ASYNC,
3106 .name = "qtree",
3107 .args_type = "",
3108 .params = "",
3109 .help = "show device tree",
3110 .mhandler.info = do_info_qtree,
3113 .name = "qdm",
3114 .args_type = "",
3115 .params = "",
3116 .help = "show qdev device model list",
3117 .mhandler.info = do_info_qdm,
3120 .name = "roms",
3121 .args_type = "",
3122 .params = "",
3123 .help = "show roms",
3124 .mhandler.info = do_info_roms,
3126 #if defined(CONFIG_SIMPLE_TRACE)
3128 .name = "trace",
3129 .args_type = "",
3130 .params = "",
3131 .help = "show current contents of trace buffer",
3132 .mhandler.info = do_info_trace,
3135 .name = "trace-events",
3136 .args_type = "",
3137 .params = "",
3138 .help = "show available trace-events & their state",
3139 .mhandler.info = do_info_trace_events,
3141 #endif
3143 .name = NULL,
3147 static const mon_cmd_t qmp_cmds[] = {
3148 #include "qmp-commands.h"
3149 { /* NULL */ },
3152 static const mon_cmd_t qmp_query_cmds[] = {
3154 .name = "version",
3155 .args_type = "",
3156 .params = "",
3157 .help = "show the version of QEMU",
3158 .user_print = do_info_version_print,
3159 .mhandler.info_new = do_info_version,
3162 .name = "commands",
3163 .args_type = "",
3164 .params = "",
3165 .help = "list QMP available commands",
3166 .user_print = monitor_user_noop,
3167 .mhandler.info_new = do_info_commands,
3170 .name = "chardev",
3171 .args_type = "",
3172 .params = "",
3173 .help = "show the character devices",
3174 .user_print = qemu_chr_info_print,
3175 .mhandler.info_new = qemu_chr_info,
3178 .name = "block",
3179 .args_type = "",
3180 .params = "",
3181 .help = "show the block devices",
3182 .user_print = bdrv_info_print,
3183 .mhandler.info_new = bdrv_info,
3186 .name = "blockstats",
3187 .args_type = "",
3188 .params = "",
3189 .help = "show block device statistics",
3190 .user_print = bdrv_stats_print,
3191 .mhandler.info_new = bdrv_info_stats,
3194 .name = "cpus",
3195 .args_type = "",
3196 .params = "",
3197 .help = "show infos for each CPU",
3198 .user_print = monitor_print_cpus,
3199 .mhandler.info_new = do_info_cpus,
3202 .name = "pci",
3203 .args_type = "",
3204 .params = "",
3205 .help = "show PCI info",
3206 .user_print = do_pci_info_print,
3207 .mhandler.info_new = do_pci_info,
3210 .name = "kvm",
3211 .args_type = "",
3212 .params = "",
3213 .help = "show KVM information",
3214 .user_print = do_info_kvm_print,
3215 .mhandler.info_new = do_info_kvm,
3218 .name = "status",
3219 .args_type = "",
3220 .params = "",
3221 .help = "show the current VM status (running|paused)",
3222 .user_print = do_info_status_print,
3223 .mhandler.info_new = do_info_status,
3226 .name = "mice",
3227 .args_type = "",
3228 .params = "",
3229 .help = "show which guest mouse is receiving events",
3230 .user_print = do_info_mice_print,
3231 .mhandler.info_new = do_info_mice,
3234 .name = "vnc",
3235 .args_type = "",
3236 .params = "",
3237 .help = "show the vnc server status",
3238 .user_print = do_info_vnc_print,
3239 .mhandler.info_new = do_info_vnc,
3241 #if defined(CONFIG_SPICE)
3243 .name = "spice",
3244 .args_type = "",
3245 .params = "",
3246 .help = "show the spice server status",
3247 .user_print = do_info_spice_print,
3248 .mhandler.info_new = do_info_spice,
3250 #endif
3252 .name = "name",
3253 .args_type = "",
3254 .params = "",
3255 .help = "show the current VM name",
3256 .user_print = do_info_name_print,
3257 .mhandler.info_new = do_info_name,
3260 .name = "uuid",
3261 .args_type = "",
3262 .params = "",
3263 .help = "show the current VM UUID",
3264 .user_print = do_info_uuid_print,
3265 .mhandler.info_new = do_info_uuid,
3268 .name = "migrate",
3269 .args_type = "",
3270 .params = "",
3271 .help = "show migration status",
3272 .user_print = do_info_migrate_print,
3273 .mhandler.info_new = do_info_migrate,
3276 .name = "balloon",
3277 .args_type = "",
3278 .params = "",
3279 .help = "show balloon information",
3280 .user_print = monitor_print_balloon,
3281 .mhandler.info_async = do_info_balloon,
3282 .flags = MONITOR_CMD_ASYNC,
3284 { /* NULL */ },
3287 /*******************************************************************/
3289 static const char *pch;
3290 static jmp_buf expr_env;
3292 #define MD_TLONG 0
3293 #define MD_I32 1
3295 typedef struct MonitorDef {
3296 const char *name;
3297 int offset;
3298 target_long (*get_value)(const struct MonitorDef *md, int val);
3299 int type;
3300 } MonitorDef;
3302 #if defined(TARGET_I386)
3303 static target_long monitor_get_pc (const struct MonitorDef *md, int val)
3305 CPUState *env = mon_get_cpu();
3306 return env->eip + env->segs[R_CS].base;
3308 #endif
3310 #if defined(TARGET_PPC)
3311 static target_long monitor_get_ccr (const struct MonitorDef *md, int val)
3313 CPUState *env = mon_get_cpu();
3314 unsigned int u;
3315 int i;
3317 u = 0;
3318 for (i = 0; i < 8; i++)
3319 u |= env->crf[i] << (32 - (4 * i));
3321 return u;
3324 static target_long monitor_get_msr (const struct MonitorDef *md, int val)
3326 CPUState *env = mon_get_cpu();
3327 return env->msr;
3330 static target_long monitor_get_xer (const struct MonitorDef *md, int val)
3332 CPUState *env = mon_get_cpu();
3333 return env->xer;
3336 static target_long monitor_get_decr (const struct MonitorDef *md, int val)
3338 CPUState *env = mon_get_cpu();
3339 return cpu_ppc_load_decr(env);
3342 static target_long monitor_get_tbu (const struct MonitorDef *md, int val)
3344 CPUState *env = mon_get_cpu();
3345 return cpu_ppc_load_tbu(env);
3348 static target_long monitor_get_tbl (const struct MonitorDef *md, int val)
3350 CPUState *env = mon_get_cpu();
3351 return cpu_ppc_load_tbl(env);
3353 #endif
3355 #if defined(TARGET_SPARC)
3356 #ifndef TARGET_SPARC64
3357 static target_long monitor_get_psr (const struct MonitorDef *md, int val)
3359 CPUState *env = mon_get_cpu();
3361 return cpu_get_psr(env);
3363 #endif
3365 static target_long monitor_get_reg(const struct MonitorDef *md, int val)
3367 CPUState *env = mon_get_cpu();
3368 return env->regwptr[val];
3370 #endif
3372 static const MonitorDef monitor_defs[] = {
3373 #ifdef TARGET_I386
3375 #define SEG(name, seg) \
3376 { name, offsetof(CPUState, segs[seg].selector), NULL, MD_I32 },\
3377 { name ".base", offsetof(CPUState, segs[seg].base) },\
3378 { name ".limit", offsetof(CPUState, segs[seg].limit), NULL, MD_I32 },
3380 { "eax", offsetof(CPUState, regs[0]) },
3381 { "ecx", offsetof(CPUState, regs[1]) },
3382 { "edx", offsetof(CPUState, regs[2]) },
3383 { "ebx", offsetof(CPUState, regs[3]) },
3384 { "esp|sp", offsetof(CPUState, regs[4]) },
3385 { "ebp|fp", offsetof(CPUState, regs[5]) },
3386 { "esi", offsetof(CPUState, regs[6]) },
3387 { "edi", offsetof(CPUState, regs[7]) },
3388 #ifdef TARGET_X86_64
3389 { "r8", offsetof(CPUState, regs[8]) },
3390 { "r9", offsetof(CPUState, regs[9]) },
3391 { "r10", offsetof(CPUState, regs[10]) },
3392 { "r11", offsetof(CPUState, regs[11]) },
3393 { "r12", offsetof(CPUState, regs[12]) },
3394 { "r13", offsetof(CPUState, regs[13]) },
3395 { "r14", offsetof(CPUState, regs[14]) },
3396 { "r15", offsetof(CPUState, regs[15]) },
3397 #endif
3398 { "eflags", offsetof(CPUState, eflags) },
3399 { "eip", offsetof(CPUState, eip) },
3400 SEG("cs", R_CS)
3401 SEG("ds", R_DS)
3402 SEG("es", R_ES)
3403 SEG("ss", R_SS)
3404 SEG("fs", R_FS)
3405 SEG("gs", R_GS)
3406 { "pc", 0, monitor_get_pc, },
3407 #elif defined(TARGET_PPC)
3408 /* General purpose registers */
3409 { "r0", offsetof(CPUState, gpr[0]) },
3410 { "r1", offsetof(CPUState, gpr[1]) },
3411 { "r2", offsetof(CPUState, gpr[2]) },
3412 { "r3", offsetof(CPUState, gpr[3]) },
3413 { "r4", offsetof(CPUState, gpr[4]) },
3414 { "r5", offsetof(CPUState, gpr[5]) },
3415 { "r6", offsetof(CPUState, gpr[6]) },
3416 { "r7", offsetof(CPUState, gpr[7]) },
3417 { "r8", offsetof(CPUState, gpr[8]) },
3418 { "r9", offsetof(CPUState, gpr[9]) },
3419 { "r10", offsetof(CPUState, gpr[10]) },
3420 { "r11", offsetof(CPUState, gpr[11]) },
3421 { "r12", offsetof(CPUState, gpr[12]) },
3422 { "r13", offsetof(CPUState, gpr[13]) },
3423 { "r14", offsetof(CPUState, gpr[14]) },
3424 { "r15", offsetof(CPUState, gpr[15]) },
3425 { "r16", offsetof(CPUState, gpr[16]) },
3426 { "r17", offsetof(CPUState, gpr[17]) },
3427 { "r18", offsetof(CPUState, gpr[18]) },
3428 { "r19", offsetof(CPUState, gpr[19]) },
3429 { "r20", offsetof(CPUState, gpr[20]) },
3430 { "r21", offsetof(CPUState, gpr[21]) },
3431 { "r22", offsetof(CPUState, gpr[22]) },
3432 { "r23", offsetof(CPUState, gpr[23]) },
3433 { "r24", offsetof(CPUState, gpr[24]) },
3434 { "r25", offsetof(CPUState, gpr[25]) },
3435 { "r26", offsetof(CPUState, gpr[26]) },
3436 { "r27", offsetof(CPUState, gpr[27]) },
3437 { "r28", offsetof(CPUState, gpr[28]) },
3438 { "r29", offsetof(CPUState, gpr[29]) },
3439 { "r30", offsetof(CPUState, gpr[30]) },
3440 { "r31", offsetof(CPUState, gpr[31]) },
3441 /* Floating point registers */
3442 { "f0", offsetof(CPUState, fpr[0]) },
3443 { "f1", offsetof(CPUState, fpr[1]) },
3444 { "f2", offsetof(CPUState, fpr[2]) },
3445 { "f3", offsetof(CPUState, fpr[3]) },
3446 { "f4", offsetof(CPUState, fpr[4]) },
3447 { "f5", offsetof(CPUState, fpr[5]) },
3448 { "f6", offsetof(CPUState, fpr[6]) },
3449 { "f7", offsetof(CPUState, fpr[7]) },
3450 { "f8", offsetof(CPUState, fpr[8]) },
3451 { "f9", offsetof(CPUState, fpr[9]) },
3452 { "f10", offsetof(CPUState, fpr[10]) },
3453 { "f11", offsetof(CPUState, fpr[11]) },
3454 { "f12", offsetof(CPUState, fpr[12]) },
3455 { "f13", offsetof(CPUState, fpr[13]) },
3456 { "f14", offsetof(CPUState, fpr[14]) },
3457 { "f15", offsetof(CPUState, fpr[15]) },
3458 { "f16", offsetof(CPUState, fpr[16]) },
3459 { "f17", offsetof(CPUState, fpr[17]) },
3460 { "f18", offsetof(CPUState, fpr[18]) },
3461 { "f19", offsetof(CPUState, fpr[19]) },
3462 { "f20", offsetof(CPUState, fpr[20]) },
3463 { "f21", offsetof(CPUState, fpr[21]) },
3464 { "f22", offsetof(CPUState, fpr[22]) },
3465 { "f23", offsetof(CPUState, fpr[23]) },
3466 { "f24", offsetof(CPUState, fpr[24]) },
3467 { "f25", offsetof(CPUState, fpr[25]) },
3468 { "f26", offsetof(CPUState, fpr[26]) },
3469 { "f27", offsetof(CPUState, fpr[27]) },
3470 { "f28", offsetof(CPUState, fpr[28]) },
3471 { "f29", offsetof(CPUState, fpr[29]) },
3472 { "f30", offsetof(CPUState, fpr[30]) },
3473 { "f31", offsetof(CPUState, fpr[31]) },
3474 { "fpscr", offsetof(CPUState, fpscr) },
3475 /* Next instruction pointer */
3476 { "nip|pc", offsetof(CPUState, nip) },
3477 { "lr", offsetof(CPUState, lr) },
3478 { "ctr", offsetof(CPUState, ctr) },
3479 { "decr", 0, &monitor_get_decr, },
3480 { "ccr", 0, &monitor_get_ccr, },
3481 /* Machine state register */
3482 { "msr", 0, &monitor_get_msr, },
3483 { "xer", 0, &monitor_get_xer, },
3484 { "tbu", 0, &monitor_get_tbu, },
3485 { "tbl", 0, &monitor_get_tbl, },
3486 #if defined(TARGET_PPC64)
3487 /* Address space register */
3488 { "asr", offsetof(CPUState, asr) },
3489 #endif
3490 /* Segment registers */
3491 { "sdr1", offsetof(CPUState, sdr1) },
3492 { "sr0", offsetof(CPUState, sr[0]) },
3493 { "sr1", offsetof(CPUState, sr[1]) },
3494 { "sr2", offsetof(CPUState, sr[2]) },
3495 { "sr3", offsetof(CPUState, sr[3]) },
3496 { "sr4", offsetof(CPUState, sr[4]) },
3497 { "sr5", offsetof(CPUState, sr[5]) },
3498 { "sr6", offsetof(CPUState, sr[6]) },
3499 { "sr7", offsetof(CPUState, sr[7]) },
3500 { "sr8", offsetof(CPUState, sr[8]) },
3501 { "sr9", offsetof(CPUState, sr[9]) },
3502 { "sr10", offsetof(CPUState, sr[10]) },
3503 { "sr11", offsetof(CPUState, sr[11]) },
3504 { "sr12", offsetof(CPUState, sr[12]) },
3505 { "sr13", offsetof(CPUState, sr[13]) },
3506 { "sr14", offsetof(CPUState, sr[14]) },
3507 { "sr15", offsetof(CPUState, sr[15]) },
3508 /* Too lazy to put BATs and SPRs ... */
3509 #elif defined(TARGET_SPARC)
3510 { "g0", offsetof(CPUState, gregs[0]) },
3511 { "g1", offsetof(CPUState, gregs[1]) },
3512 { "g2", offsetof(CPUState, gregs[2]) },
3513 { "g3", offsetof(CPUState, gregs[3]) },
3514 { "g4", offsetof(CPUState, gregs[4]) },
3515 { "g5", offsetof(CPUState, gregs[5]) },
3516 { "g6", offsetof(CPUState, gregs[6]) },
3517 { "g7", offsetof(CPUState, gregs[7]) },
3518 { "o0", 0, monitor_get_reg },
3519 { "o1", 1, monitor_get_reg },
3520 { "o2", 2, monitor_get_reg },
3521 { "o3", 3, monitor_get_reg },
3522 { "o4", 4, monitor_get_reg },
3523 { "o5", 5, monitor_get_reg },
3524 { "o6", 6, monitor_get_reg },
3525 { "o7", 7, monitor_get_reg },
3526 { "l0", 8, monitor_get_reg },
3527 { "l1", 9, monitor_get_reg },
3528 { "l2", 10, monitor_get_reg },
3529 { "l3", 11, monitor_get_reg },
3530 { "l4", 12, monitor_get_reg },
3531 { "l5", 13, monitor_get_reg },
3532 { "l6", 14, monitor_get_reg },
3533 { "l7", 15, monitor_get_reg },
3534 { "i0", 16, monitor_get_reg },
3535 { "i1", 17, monitor_get_reg },
3536 { "i2", 18, monitor_get_reg },
3537 { "i3", 19, monitor_get_reg },
3538 { "i4", 20, monitor_get_reg },
3539 { "i5", 21, monitor_get_reg },
3540 { "i6", 22, monitor_get_reg },
3541 { "i7", 23, monitor_get_reg },
3542 { "pc", offsetof(CPUState, pc) },
3543 { "npc", offsetof(CPUState, npc) },
3544 { "y", offsetof(CPUState, y) },
3545 #ifndef TARGET_SPARC64
3546 { "psr", 0, &monitor_get_psr, },
3547 { "wim", offsetof(CPUState, wim) },
3548 #endif
3549 { "tbr", offsetof(CPUState, tbr) },
3550 { "fsr", offsetof(CPUState, fsr) },
3551 { "f0", offsetof(CPUState, fpr[0]) },
3552 { "f1", offsetof(CPUState, fpr[1]) },
3553 { "f2", offsetof(CPUState, fpr[2]) },
3554 { "f3", offsetof(CPUState, fpr[3]) },
3555 { "f4", offsetof(CPUState, fpr[4]) },
3556 { "f5", offsetof(CPUState, fpr[5]) },
3557 { "f6", offsetof(CPUState, fpr[6]) },
3558 { "f7", offsetof(CPUState, fpr[7]) },
3559 { "f8", offsetof(CPUState, fpr[8]) },
3560 { "f9", offsetof(CPUState, fpr[9]) },
3561 { "f10", offsetof(CPUState, fpr[10]) },
3562 { "f11", offsetof(CPUState, fpr[11]) },
3563 { "f12", offsetof(CPUState, fpr[12]) },
3564 { "f13", offsetof(CPUState, fpr[13]) },
3565 { "f14", offsetof(CPUState, fpr[14]) },
3566 { "f15", offsetof(CPUState, fpr[15]) },
3567 { "f16", offsetof(CPUState, fpr[16]) },
3568 { "f17", offsetof(CPUState, fpr[17]) },
3569 { "f18", offsetof(CPUState, fpr[18]) },
3570 { "f19", offsetof(CPUState, fpr[19]) },
3571 { "f20", offsetof(CPUState, fpr[20]) },
3572 { "f21", offsetof(CPUState, fpr[21]) },
3573 { "f22", offsetof(CPUState, fpr[22]) },
3574 { "f23", offsetof(CPUState, fpr[23]) },
3575 { "f24", offsetof(CPUState, fpr[24]) },
3576 { "f25", offsetof(CPUState, fpr[25]) },
3577 { "f26", offsetof(CPUState, fpr[26]) },
3578 { "f27", offsetof(CPUState, fpr[27]) },
3579 { "f28", offsetof(CPUState, fpr[28]) },
3580 { "f29", offsetof(CPUState, fpr[29]) },
3581 { "f30", offsetof(CPUState, fpr[30]) },
3582 { "f31", offsetof(CPUState, fpr[31]) },
3583 #ifdef TARGET_SPARC64
3584 { "f32", offsetof(CPUState, fpr[32]) },
3585 { "f34", offsetof(CPUState, fpr[34]) },
3586 { "f36", offsetof(CPUState, fpr[36]) },
3587 { "f38", offsetof(CPUState, fpr[38]) },
3588 { "f40", offsetof(CPUState, fpr[40]) },
3589 { "f42", offsetof(CPUState, fpr[42]) },
3590 { "f44", offsetof(CPUState, fpr[44]) },
3591 { "f46", offsetof(CPUState, fpr[46]) },
3592 { "f48", offsetof(CPUState, fpr[48]) },
3593 { "f50", offsetof(CPUState, fpr[50]) },
3594 { "f52", offsetof(CPUState, fpr[52]) },
3595 { "f54", offsetof(CPUState, fpr[54]) },
3596 { "f56", offsetof(CPUState, fpr[56]) },
3597 { "f58", offsetof(CPUState, fpr[58]) },
3598 { "f60", offsetof(CPUState, fpr[60]) },
3599 { "f62", offsetof(CPUState, fpr[62]) },
3600 { "asi", offsetof(CPUState, asi) },
3601 { "pstate", offsetof(CPUState, pstate) },
3602 { "cansave", offsetof(CPUState, cansave) },
3603 { "canrestore", offsetof(CPUState, canrestore) },
3604 { "otherwin", offsetof(CPUState, otherwin) },
3605 { "wstate", offsetof(CPUState, wstate) },
3606 { "cleanwin", offsetof(CPUState, cleanwin) },
3607 { "fprs", offsetof(CPUState, fprs) },
3608 #endif
3609 #endif
3610 { NULL },
3613 static void expr_error(Monitor *mon, const char *msg)
3615 monitor_printf(mon, "%s\n", msg);
3616 longjmp(expr_env, 1);
3619 /* return 0 if OK, -1 if not found */
3620 static int get_monitor_def(target_long *pval, const char *name)
3622 const MonitorDef *md;
3623 void *ptr;
3625 for(md = monitor_defs; md->name != NULL; md++) {
3626 if (compare_cmd(name, md->name)) {
3627 if (md->get_value) {
3628 *pval = md->get_value(md, md->offset);
3629 } else {
3630 CPUState *env = mon_get_cpu();
3631 ptr = (uint8_t *)env + md->offset;
3632 switch(md->type) {
3633 case MD_I32:
3634 *pval = *(int32_t *)ptr;
3635 break;
3636 case MD_TLONG:
3637 *pval = *(target_long *)ptr;
3638 break;
3639 default:
3640 *pval = 0;
3641 break;
3644 return 0;
3647 return -1;
3650 static void next(void)
3652 if (*pch != '\0') {
3653 pch++;
3654 while (qemu_isspace(*pch))
3655 pch++;
3659 static int64_t expr_sum(Monitor *mon);
3661 static int64_t expr_unary(Monitor *mon)
3663 int64_t n;
3664 char *p;
3665 int ret;
3667 switch(*pch) {
3668 case '+':
3669 next();
3670 n = expr_unary(mon);
3671 break;
3672 case '-':
3673 next();
3674 n = -expr_unary(mon);
3675 break;
3676 case '~':
3677 next();
3678 n = ~expr_unary(mon);
3679 break;
3680 case '(':
3681 next();
3682 n = expr_sum(mon);
3683 if (*pch != ')') {
3684 expr_error(mon, "')' expected");
3686 next();
3687 break;
3688 case '\'':
3689 pch++;
3690 if (*pch == '\0')
3691 expr_error(mon, "character constant expected");
3692 n = *pch;
3693 pch++;
3694 if (*pch != '\'')
3695 expr_error(mon, "missing terminating \' character");
3696 next();
3697 break;
3698 case '$':
3700 char buf[128], *q;
3701 target_long reg=0;
3703 pch++;
3704 q = buf;
3705 while ((*pch >= 'a' && *pch <= 'z') ||
3706 (*pch >= 'A' && *pch <= 'Z') ||
3707 (*pch >= '0' && *pch <= '9') ||
3708 *pch == '_' || *pch == '.') {
3709 if ((q - buf) < sizeof(buf) - 1)
3710 *q++ = *pch;
3711 pch++;
3713 while (qemu_isspace(*pch))
3714 pch++;
3715 *q = 0;
3716 ret = get_monitor_def(&reg, buf);
3717 if (ret < 0)
3718 expr_error(mon, "unknown register");
3719 n = reg;
3721 break;
3722 case '\0':
3723 expr_error(mon, "unexpected end of expression");
3724 n = 0;
3725 break;
3726 default:
3727 #if TARGET_PHYS_ADDR_BITS > 32
3728 n = strtoull(pch, &p, 0);
3729 #else
3730 n = strtoul(pch, &p, 0);
3731 #endif
3732 if (pch == p) {
3733 expr_error(mon, "invalid char in expression");
3735 pch = p;
3736 while (qemu_isspace(*pch))
3737 pch++;
3738 break;
3740 return n;
3744 static int64_t expr_prod(Monitor *mon)
3746 int64_t val, val2;
3747 int op;
3749 val = expr_unary(mon);
3750 for(;;) {
3751 op = *pch;
3752 if (op != '*' && op != '/' && op != '%')
3753 break;
3754 next();
3755 val2 = expr_unary(mon);
3756 switch(op) {
3757 default:
3758 case '*':
3759 val *= val2;
3760 break;
3761 case '/':
3762 case '%':
3763 if (val2 == 0)
3764 expr_error(mon, "division by zero");
3765 if (op == '/')
3766 val /= val2;
3767 else
3768 val %= val2;
3769 break;
3772 return val;
3775 static int64_t expr_logic(Monitor *mon)
3777 int64_t val, val2;
3778 int op;
3780 val = expr_prod(mon);
3781 for(;;) {
3782 op = *pch;
3783 if (op != '&' && op != '|' && op != '^')
3784 break;
3785 next();
3786 val2 = expr_prod(mon);
3787 switch(op) {
3788 default:
3789 case '&':
3790 val &= val2;
3791 break;
3792 case '|':
3793 val |= val2;
3794 break;
3795 case '^':
3796 val ^= val2;
3797 break;
3800 return val;
3803 static int64_t expr_sum(Monitor *mon)
3805 int64_t val, val2;
3806 int op;
3808 val = expr_logic(mon);
3809 for(;;) {
3810 op = *pch;
3811 if (op != '+' && op != '-')
3812 break;
3813 next();
3814 val2 = expr_logic(mon);
3815 if (op == '+')
3816 val += val2;
3817 else
3818 val -= val2;
3820 return val;
3823 static int get_expr(Monitor *mon, int64_t *pval, const char **pp)
3825 pch = *pp;
3826 if (setjmp(expr_env)) {
3827 *pp = pch;
3828 return -1;
3830 while (qemu_isspace(*pch))
3831 pch++;
3832 *pval = expr_sum(mon);
3833 *pp = pch;
3834 return 0;
3837 static int get_double(Monitor *mon, double *pval, const char **pp)
3839 const char *p = *pp;
3840 char *tailp;
3841 double d;
3843 d = strtod(p, &tailp);
3844 if (tailp == p) {
3845 monitor_printf(mon, "Number expected\n");
3846 return -1;
3848 if (d != d || d - d != 0) {
3849 /* NaN or infinity */
3850 monitor_printf(mon, "Bad number\n");
3851 return -1;
3853 *pval = d;
3854 *pp = tailp;
3855 return 0;
3858 static int get_str(char *buf, int buf_size, const char **pp)
3860 const char *p;
3861 char *q;
3862 int c;
3864 q = buf;
3865 p = *pp;
3866 while (qemu_isspace(*p))
3867 p++;
3868 if (*p == '\0') {
3869 fail:
3870 *q = '\0';
3871 *pp = p;
3872 return -1;
3874 if (*p == '\"') {
3875 p++;
3876 while (*p != '\0' && *p != '\"') {
3877 if (*p == '\\') {
3878 p++;
3879 c = *p++;
3880 switch(c) {
3881 case 'n':
3882 c = '\n';
3883 break;
3884 case 'r':
3885 c = '\r';
3886 break;
3887 case '\\':
3888 case '\'':
3889 case '\"':
3890 break;
3891 default:
3892 qemu_printf("unsupported escape code: '\\%c'\n", c);
3893 goto fail;
3895 if ((q - buf) < buf_size - 1) {
3896 *q++ = c;
3898 } else {
3899 if ((q - buf) < buf_size - 1) {
3900 *q++ = *p;
3902 p++;
3905 if (*p != '\"') {
3906 qemu_printf("unterminated string\n");
3907 goto fail;
3909 p++;
3910 } else {
3911 while (*p != '\0' && !qemu_isspace(*p)) {
3912 if ((q - buf) < buf_size - 1) {
3913 *q++ = *p;
3915 p++;
3918 *q = '\0';
3919 *pp = p;
3920 return 0;
3924 * Store the command-name in cmdname, and return a pointer to
3925 * the remaining of the command string.
3927 static const char *get_command_name(const char *cmdline,
3928 char *cmdname, size_t nlen)
3930 size_t len;
3931 const char *p, *pstart;
3933 p = cmdline;
3934 while (qemu_isspace(*p))
3935 p++;
3936 if (*p == '\0')
3937 return NULL;
3938 pstart = p;
3939 while (*p != '\0' && *p != '/' && !qemu_isspace(*p))
3940 p++;
3941 len = p - pstart;
3942 if (len > nlen - 1)
3943 len = nlen - 1;
3944 memcpy(cmdname, pstart, len);
3945 cmdname[len] = '\0';
3946 return p;
3950 * Read key of 'type' into 'key' and return the current
3951 * 'type' pointer.
3953 static char *key_get_info(const char *type, char **key)
3955 size_t len;
3956 char *p, *str;
3958 if (*type == ',')
3959 type++;
3961 p = strchr(type, ':');
3962 if (!p) {
3963 *key = NULL;
3964 return NULL;
3966 len = p - type;
3968 str = qemu_malloc(len + 1);
3969 memcpy(str, type, len);
3970 str[len] = '\0';
3972 *key = str;
3973 return ++p;
3976 static int default_fmt_format = 'x';
3977 static int default_fmt_size = 4;
3979 #define MAX_ARGS 16
3981 static int is_valid_option(const char *c, const char *typestr)
3983 char option[3];
3985 option[0] = '-';
3986 option[1] = *c;
3987 option[2] = '\0';
3989 typestr = strstr(typestr, option);
3990 return (typestr != NULL);
3993 static const mon_cmd_t *search_dispatch_table(const mon_cmd_t *disp_table,
3994 const char *cmdname)
3996 const mon_cmd_t *cmd;
3998 for (cmd = disp_table; cmd->name != NULL; cmd++) {
3999 if (compare_cmd(cmdname, cmd->name)) {
4000 return cmd;
4004 return NULL;
4007 static const mon_cmd_t *monitor_find_command(const char *cmdname)
4009 return search_dispatch_table(mon_cmds, cmdname);
4012 static const mon_cmd_t *qmp_find_query_cmd(const char *info_item)
4014 return search_dispatch_table(qmp_query_cmds, info_item);
4017 static const mon_cmd_t *qmp_find_cmd(const char *cmdname)
4019 return search_dispatch_table(qmp_cmds, cmdname);
4022 static const mon_cmd_t *monitor_parse_command(Monitor *mon,
4023 const char *cmdline,
4024 QDict *qdict)
4026 const char *p, *typestr;
4027 int c;
4028 const mon_cmd_t *cmd;
4029 char cmdname[256];
4030 char buf[1024];
4031 char *key;
4033 #ifdef DEBUG
4034 monitor_printf(mon, "command='%s'\n", cmdline);
4035 #endif
4037 /* extract the command name */
4038 p = get_command_name(cmdline, cmdname, sizeof(cmdname));
4039 if (!p)
4040 return NULL;
4042 cmd = monitor_find_command(cmdname);
4043 if (!cmd) {
4044 monitor_printf(mon, "unknown command: '%s'\n", cmdname);
4045 return NULL;
4048 /* parse the parameters */
4049 typestr = cmd->args_type;
4050 for(;;) {
4051 typestr = key_get_info(typestr, &key);
4052 if (!typestr)
4053 break;
4054 c = *typestr;
4055 typestr++;
4056 switch(c) {
4057 case 'F':
4058 case 'B':
4059 case 's':
4061 int ret;
4063 while (qemu_isspace(*p))
4064 p++;
4065 if (*typestr == '?') {
4066 typestr++;
4067 if (*p == '\0') {
4068 /* no optional string: NULL argument */
4069 break;
4072 ret = get_str(buf, sizeof(buf), &p);
4073 if (ret < 0) {
4074 switch(c) {
4075 case 'F':
4076 monitor_printf(mon, "%s: filename expected\n",
4077 cmdname);
4078 break;
4079 case 'B':
4080 monitor_printf(mon, "%s: block device name expected\n",
4081 cmdname);
4082 break;
4083 default:
4084 monitor_printf(mon, "%s: string expected\n", cmdname);
4085 break;
4087 goto fail;
4089 qdict_put(qdict, key, qstring_from_str(buf));
4091 break;
4092 case 'O':
4094 QemuOptsList *opts_list;
4095 QemuOpts *opts;
4097 opts_list = qemu_find_opts(key);
4098 if (!opts_list || opts_list->desc->name) {
4099 goto bad_type;
4101 while (qemu_isspace(*p)) {
4102 p++;
4104 if (!*p)
4105 break;
4106 if (get_str(buf, sizeof(buf), &p) < 0) {
4107 goto fail;
4109 opts = qemu_opts_parse(opts_list, buf, 1);
4110 if (!opts) {
4111 goto fail;
4113 qemu_opts_to_qdict(opts, qdict);
4114 qemu_opts_del(opts);
4116 break;
4117 case '/':
4119 int count, format, size;
4121 while (qemu_isspace(*p))
4122 p++;
4123 if (*p == '/') {
4124 /* format found */
4125 p++;
4126 count = 1;
4127 if (qemu_isdigit(*p)) {
4128 count = 0;
4129 while (qemu_isdigit(*p)) {
4130 count = count * 10 + (*p - '0');
4131 p++;
4134 size = -1;
4135 format = -1;
4136 for(;;) {
4137 switch(*p) {
4138 case 'o':
4139 case 'd':
4140 case 'u':
4141 case 'x':
4142 case 'i':
4143 case 'c':
4144 format = *p++;
4145 break;
4146 case 'b':
4147 size = 1;
4148 p++;
4149 break;
4150 case 'h':
4151 size = 2;
4152 p++;
4153 break;
4154 case 'w':
4155 size = 4;
4156 p++;
4157 break;
4158 case 'g':
4159 case 'L':
4160 size = 8;
4161 p++;
4162 break;
4163 default:
4164 goto next;
4167 next:
4168 if (*p != '\0' && !qemu_isspace(*p)) {
4169 monitor_printf(mon, "invalid char in format: '%c'\n",
4170 *p);
4171 goto fail;
4173 if (format < 0)
4174 format = default_fmt_format;
4175 if (format != 'i') {
4176 /* for 'i', not specifying a size gives -1 as size */
4177 if (size < 0)
4178 size = default_fmt_size;
4179 default_fmt_size = size;
4181 default_fmt_format = format;
4182 } else {
4183 count = 1;
4184 format = default_fmt_format;
4185 if (format != 'i') {
4186 size = default_fmt_size;
4187 } else {
4188 size = -1;
4191 qdict_put(qdict, "count", qint_from_int(count));
4192 qdict_put(qdict, "format", qint_from_int(format));
4193 qdict_put(qdict, "size", qint_from_int(size));
4195 break;
4196 case 'i':
4197 case 'l':
4198 case 'M':
4200 int64_t val;
4202 while (qemu_isspace(*p))
4203 p++;
4204 if (*typestr == '?' || *typestr == '.') {
4205 if (*typestr == '?') {
4206 if (*p == '\0') {
4207 typestr++;
4208 break;
4210 } else {
4211 if (*p == '.') {
4212 p++;
4213 while (qemu_isspace(*p))
4214 p++;
4215 } else {
4216 typestr++;
4217 break;
4220 typestr++;
4222 if (get_expr(mon, &val, &p))
4223 goto fail;
4224 /* Check if 'i' is greater than 32-bit */
4225 if ((c == 'i') && ((val >> 32) & 0xffffffff)) {
4226 monitor_printf(mon, "\'%s\' has failed: ", cmdname);
4227 monitor_printf(mon, "integer is for 32-bit values\n");
4228 goto fail;
4229 } else if (c == 'M') {
4230 val <<= 20;
4232 qdict_put(qdict, key, qint_from_int(val));
4234 break;
4235 case 'o':
4237 int64_t val;
4238 char *end;
4240 while (qemu_isspace(*p)) {
4241 p++;
4243 if (*typestr == '?') {
4244 typestr++;
4245 if (*p == '\0') {
4246 break;
4249 val = strtosz(p, &end);
4250 if (val < 0) {
4251 monitor_printf(mon, "invalid size\n");
4252 goto fail;
4254 qdict_put(qdict, key, qint_from_int(val));
4255 p = end;
4257 break;
4258 case 'T':
4260 double val;
4262 while (qemu_isspace(*p))
4263 p++;
4264 if (*typestr == '?') {
4265 typestr++;
4266 if (*p == '\0') {
4267 break;
4270 if (get_double(mon, &val, &p) < 0) {
4271 goto fail;
4273 if (p[0] && p[1] == 's') {
4274 switch (*p) {
4275 case 'm':
4276 val /= 1e3; p += 2; break;
4277 case 'u':
4278 val /= 1e6; p += 2; break;
4279 case 'n':
4280 val /= 1e9; p += 2; break;
4283 if (*p && !qemu_isspace(*p)) {
4284 monitor_printf(mon, "Unknown unit suffix\n");
4285 goto fail;
4287 qdict_put(qdict, key, qfloat_from_double(val));
4289 break;
4290 case 'b':
4292 const char *beg;
4293 int val;
4295 while (qemu_isspace(*p)) {
4296 p++;
4298 beg = p;
4299 while (qemu_isgraph(*p)) {
4300 p++;
4302 if (p - beg == 2 && !memcmp(beg, "on", p - beg)) {
4303 val = 1;
4304 } else if (p - beg == 3 && !memcmp(beg, "off", p - beg)) {
4305 val = 0;
4306 } else {
4307 monitor_printf(mon, "Expected 'on' or 'off'\n");
4308 goto fail;
4310 qdict_put(qdict, key, qbool_from_int(val));
4312 break;
4313 case '-':
4315 const char *tmp = p;
4316 int skip_key = 0;
4317 /* option */
4319 c = *typestr++;
4320 if (c == '\0')
4321 goto bad_type;
4322 while (qemu_isspace(*p))
4323 p++;
4324 if (*p == '-') {
4325 p++;
4326 if(c != *p) {
4327 if(!is_valid_option(p, typestr)) {
4329 monitor_printf(mon, "%s: unsupported option -%c\n",
4330 cmdname, *p);
4331 goto fail;
4332 } else {
4333 skip_key = 1;
4336 if(skip_key) {
4337 p = tmp;
4338 } else {
4339 /* has option */
4340 p++;
4341 qdict_put(qdict, key, qbool_from_int(1));
4345 break;
4346 default:
4347 bad_type:
4348 monitor_printf(mon, "%s: unknown type '%c'\n", cmdname, c);
4349 goto fail;
4351 qemu_free(key);
4352 key = NULL;
4354 /* check that all arguments were parsed */
4355 while (qemu_isspace(*p))
4356 p++;
4357 if (*p != '\0') {
4358 monitor_printf(mon, "%s: extraneous characters at the end of line\n",
4359 cmdname);
4360 goto fail;
4363 return cmd;
4365 fail:
4366 qemu_free(key);
4367 return NULL;
4370 void monitor_set_error(Monitor *mon, QError *qerror)
4372 /* report only the first error */
4373 if (!mon->error) {
4374 mon->error = qerror;
4375 } else {
4376 MON_DEBUG("Additional error report at %s:%d\n",
4377 qerror->file, qerror->linenr);
4378 QDECREF(qerror);
4382 static void handler_audit(Monitor *mon, const mon_cmd_t *cmd, int ret)
4384 if (ret && !monitor_has_error(mon)) {
4386 * If it returns failure, it must have passed on error.
4388 * Action: Report an internal error to the client if in QMP.
4390 qerror_report(QERR_UNDEFINED_ERROR);
4391 MON_DEBUG("command '%s' returned failure but did not pass an error\n",
4392 cmd->name);
4395 #ifdef CONFIG_DEBUG_MONITOR
4396 if (!ret && monitor_has_error(mon)) {
4398 * If it returns success, it must not have passed an error.
4400 * Action: Report the passed error to the client.
4402 MON_DEBUG("command '%s' returned success but passed an error\n",
4403 cmd->name);
4406 if (mon_print_count_get(mon) > 0 && strcmp(cmd->name, "info") != 0) {
4408 * Handlers should not call Monitor print functions.
4410 * Action: Ignore them in QMP.
4412 * (XXX: we don't check any 'info' or 'query' command here
4413 * because the user print function _is_ called by do_info(), hence
4414 * we will trigger this check. This problem will go away when we
4415 * make 'query' commands real and kill do_info())
4417 MON_DEBUG("command '%s' called print functions %d time(s)\n",
4418 cmd->name, mon_print_count_get(mon));
4420 #endif
4423 static void handle_user_command(Monitor *mon, const char *cmdline)
4425 QDict *qdict;
4426 const mon_cmd_t *cmd;
4428 qdict = qdict_new();
4430 cmd = monitor_parse_command(mon, cmdline, qdict);
4431 if (!cmd)
4432 goto out;
4434 if (handler_is_async(cmd)) {
4435 user_async_cmd_handler(mon, cmd, qdict);
4436 } else if (handler_is_qobject(cmd)) {
4437 QObject *data = NULL;
4439 /* XXX: ignores the error code */
4440 cmd->mhandler.cmd_new(mon, qdict, &data);
4441 assert(!monitor_has_error(mon));
4442 if (data) {
4443 cmd->user_print(mon, data);
4444 qobject_decref(data);
4446 } else {
4447 cmd->mhandler.cmd(mon, qdict);
4450 out:
4451 QDECREF(qdict);
4454 static void cmd_completion(const char *name, const char *list)
4456 const char *p, *pstart;
4457 char cmd[128];
4458 int len;
4460 p = list;
4461 for(;;) {
4462 pstart = p;
4463 p = strchr(p, '|');
4464 if (!p)
4465 p = pstart + strlen(pstart);
4466 len = p - pstart;
4467 if (len > sizeof(cmd) - 2)
4468 len = sizeof(cmd) - 2;
4469 memcpy(cmd, pstart, len);
4470 cmd[len] = '\0';
4471 if (name[0] == '\0' || !strncmp(name, cmd, strlen(name))) {
4472 readline_add_completion(cur_mon->rs, cmd);
4474 if (*p == '\0')
4475 break;
4476 p++;
4480 static void file_completion(const char *input)
4482 DIR *ffs;
4483 struct dirent *d;
4484 char path[1024];
4485 char file[1024], file_prefix[1024];
4486 int input_path_len;
4487 const char *p;
4489 p = strrchr(input, '/');
4490 if (!p) {
4491 input_path_len = 0;
4492 pstrcpy(file_prefix, sizeof(file_prefix), input);
4493 pstrcpy(path, sizeof(path), ".");
4494 } else {
4495 input_path_len = p - input + 1;
4496 memcpy(path, input, input_path_len);
4497 if (input_path_len > sizeof(path) - 1)
4498 input_path_len = sizeof(path) - 1;
4499 path[input_path_len] = '\0';
4500 pstrcpy(file_prefix, sizeof(file_prefix), p + 1);
4502 #ifdef DEBUG_COMPLETION
4503 monitor_printf(cur_mon, "input='%s' path='%s' prefix='%s'\n",
4504 input, path, file_prefix);
4505 #endif
4506 ffs = opendir(path);
4507 if (!ffs)
4508 return;
4509 for(;;) {
4510 struct stat sb;
4511 d = readdir(ffs);
4512 if (!d)
4513 break;
4515 if (strcmp(d->d_name, ".") == 0 || strcmp(d->d_name, "..") == 0) {
4516 continue;
4519 if (strstart(d->d_name, file_prefix, NULL)) {
4520 memcpy(file, input, input_path_len);
4521 if (input_path_len < sizeof(file))
4522 pstrcpy(file + input_path_len, sizeof(file) - input_path_len,
4523 d->d_name);
4524 /* stat the file to find out if it's a directory.
4525 * In that case add a slash to speed up typing long paths
4527 stat(file, &sb);
4528 if(S_ISDIR(sb.st_mode))
4529 pstrcat(file, sizeof(file), "/");
4530 readline_add_completion(cur_mon->rs, file);
4533 closedir(ffs);
4536 static void block_completion_it(void *opaque, BlockDriverState *bs)
4538 const char *name = bdrv_get_device_name(bs);
4539 const char *input = opaque;
4541 if (input[0] == '\0' ||
4542 !strncmp(name, (char *)input, strlen(input))) {
4543 readline_add_completion(cur_mon->rs, name);
4547 /* NOTE: this parser is an approximate form of the real command parser */
4548 static void parse_cmdline(const char *cmdline,
4549 int *pnb_args, char **args)
4551 const char *p;
4552 int nb_args, ret;
4553 char buf[1024];
4555 p = cmdline;
4556 nb_args = 0;
4557 for(;;) {
4558 while (qemu_isspace(*p))
4559 p++;
4560 if (*p == '\0')
4561 break;
4562 if (nb_args >= MAX_ARGS)
4563 break;
4564 ret = get_str(buf, sizeof(buf), &p);
4565 args[nb_args] = qemu_strdup(buf);
4566 nb_args++;
4567 if (ret < 0)
4568 break;
4570 *pnb_args = nb_args;
4573 static const char *next_arg_type(const char *typestr)
4575 const char *p = strchr(typestr, ':');
4576 return (p != NULL ? ++p : typestr);
4579 static void monitor_find_completion(const char *cmdline)
4581 const char *cmdname;
4582 char *args[MAX_ARGS];
4583 int nb_args, i, len;
4584 const char *ptype, *str;
4585 const mon_cmd_t *cmd;
4586 const KeyDef *key;
4588 parse_cmdline(cmdline, &nb_args, args);
4589 #ifdef DEBUG_COMPLETION
4590 for(i = 0; i < nb_args; i++) {
4591 monitor_printf(cur_mon, "arg%d = '%s'\n", i, (char *)args[i]);
4593 #endif
4595 /* if the line ends with a space, it means we want to complete the
4596 next arg */
4597 len = strlen(cmdline);
4598 if (len > 0 && qemu_isspace(cmdline[len - 1])) {
4599 if (nb_args >= MAX_ARGS) {
4600 goto cleanup;
4602 args[nb_args++] = qemu_strdup("");
4604 if (nb_args <= 1) {
4605 /* command completion */
4606 if (nb_args == 0)
4607 cmdname = "";
4608 else
4609 cmdname = args[0];
4610 readline_set_completion_index(cur_mon->rs, strlen(cmdname));
4611 for(cmd = mon_cmds; cmd->name != NULL; cmd++) {
4612 cmd_completion(cmdname, cmd->name);
4614 } else {
4615 /* find the command */
4616 for (cmd = mon_cmds; cmd->name != NULL; cmd++) {
4617 if (compare_cmd(args[0], cmd->name)) {
4618 break;
4621 if (!cmd->name) {
4622 goto cleanup;
4625 ptype = next_arg_type(cmd->args_type);
4626 for(i = 0; i < nb_args - 2; i++) {
4627 if (*ptype != '\0') {
4628 ptype = next_arg_type(ptype);
4629 while (*ptype == '?')
4630 ptype = next_arg_type(ptype);
4633 str = args[nb_args - 1];
4634 if (*ptype == '-' && ptype[1] != '\0') {
4635 ptype = next_arg_type(ptype);
4637 switch(*ptype) {
4638 case 'F':
4639 /* file completion */
4640 readline_set_completion_index(cur_mon->rs, strlen(str));
4641 file_completion(str);
4642 break;
4643 case 'B':
4644 /* block device name completion */
4645 readline_set_completion_index(cur_mon->rs, strlen(str));
4646 bdrv_iterate(block_completion_it, (void *)str);
4647 break;
4648 case 's':
4649 /* XXX: more generic ? */
4650 if (!strcmp(cmd->name, "info")) {
4651 readline_set_completion_index(cur_mon->rs, strlen(str));
4652 for(cmd = info_cmds; cmd->name != NULL; cmd++) {
4653 cmd_completion(str, cmd->name);
4655 } else if (!strcmp(cmd->name, "sendkey")) {
4656 char *sep = strrchr(str, '-');
4657 if (sep)
4658 str = sep + 1;
4659 readline_set_completion_index(cur_mon->rs, strlen(str));
4660 for(key = key_defs; key->name != NULL; key++) {
4661 cmd_completion(str, key->name);
4663 } else if (!strcmp(cmd->name, "help|?")) {
4664 readline_set_completion_index(cur_mon->rs, strlen(str));
4665 for (cmd = mon_cmds; cmd->name != NULL; cmd++) {
4666 cmd_completion(str, cmd->name);
4669 break;
4670 default:
4671 break;
4675 cleanup:
4676 for (i = 0; i < nb_args; i++) {
4677 qemu_free(args[i]);
4681 static int monitor_can_read(void *opaque)
4683 Monitor *mon = opaque;
4685 return (mon->suspend_cnt == 0) ? 1 : 0;
4688 static int invalid_qmp_mode(const Monitor *mon, const char *cmd_name)
4690 int is_cap = compare_cmd(cmd_name, "qmp_capabilities");
4691 return (qmp_cmd_mode(mon) ? is_cap : !is_cap);
4695 * Argument validation rules:
4697 * 1. The argument must exist in cmd_args qdict
4698 * 2. The argument type must be the expected one
4700 * Special case: If the argument doesn't exist in cmd_args and
4701 * the QMP_ACCEPT_UNKNOWNS flag is set, then the
4702 * checking is skipped for it.
4704 static int check_client_args_type(const QDict *client_args,
4705 const QDict *cmd_args, int flags)
4707 const QDictEntry *ent;
4709 for (ent = qdict_first(client_args); ent;ent = qdict_next(client_args,ent)){
4710 QObject *obj;
4711 QString *arg_type;
4712 const QObject *client_arg = qdict_entry_value(ent);
4713 const char *client_arg_name = qdict_entry_key(ent);
4715 obj = qdict_get(cmd_args, client_arg_name);
4716 if (!obj) {
4717 if (flags & QMP_ACCEPT_UNKNOWNS) {
4718 /* handler accepts unknowns */
4719 continue;
4721 /* client arg doesn't exist */
4722 qerror_report(QERR_INVALID_PARAMETER, client_arg_name);
4723 return -1;
4726 arg_type = qobject_to_qstring(obj);
4727 assert(arg_type != NULL);
4729 /* check if argument's type is correct */
4730 switch (qstring_get_str(arg_type)[0]) {
4731 case 'F':
4732 case 'B':
4733 case 's':
4734 if (qobject_type(client_arg) != QTYPE_QSTRING) {
4735 qerror_report(QERR_INVALID_PARAMETER_TYPE, client_arg_name,
4736 "string");
4737 return -1;
4739 break;
4740 case 'i':
4741 case 'l':
4742 case 'M':
4743 case 'o':
4744 if (qobject_type(client_arg) != QTYPE_QINT) {
4745 qerror_report(QERR_INVALID_PARAMETER_TYPE, client_arg_name,
4746 "int");
4747 return -1;
4749 break;
4750 case 'T':
4751 if (qobject_type(client_arg) != QTYPE_QINT &&
4752 qobject_type(client_arg) != QTYPE_QFLOAT) {
4753 qerror_report(QERR_INVALID_PARAMETER_TYPE, client_arg_name,
4754 "number");
4755 return -1;
4757 break;
4758 case 'b':
4759 case '-':
4760 if (qobject_type(client_arg) != QTYPE_QBOOL) {
4761 qerror_report(QERR_INVALID_PARAMETER_TYPE, client_arg_name,
4762 "bool");
4763 return -1;
4765 break;
4766 case 'O':
4767 assert(flags & QMP_ACCEPT_UNKNOWNS);
4768 break;
4769 case '/':
4770 case '.':
4772 * These types are not supported by QMP and thus are not
4773 * handled here. Fall through.
4775 default:
4776 abort();
4780 return 0;
4784 * - Check if the client has passed all mandatory args
4785 * - Set special flags for argument validation
4787 static int check_mandatory_args(const QDict *cmd_args,
4788 const QDict *client_args, int *flags)
4790 const QDictEntry *ent;
4792 for (ent = qdict_first(cmd_args); ent; ent = qdict_next(cmd_args, ent)) {
4793 const char *cmd_arg_name = qdict_entry_key(ent);
4794 QString *type = qobject_to_qstring(qdict_entry_value(ent));
4795 assert(type != NULL);
4797 if (qstring_get_str(type)[0] == 'O') {
4798 assert((*flags & QMP_ACCEPT_UNKNOWNS) == 0);
4799 *flags |= QMP_ACCEPT_UNKNOWNS;
4800 } else if (qstring_get_str(type)[0] != '-' &&
4801 qstring_get_str(type)[1] != '?' &&
4802 !qdict_haskey(client_args, cmd_arg_name)) {
4803 qerror_report(QERR_MISSING_PARAMETER, cmd_arg_name);
4804 return -1;
4808 return 0;
4811 static QDict *qdict_from_args_type(const char *args_type)
4813 int i;
4814 QDict *qdict;
4815 QString *key, *type, *cur_qs;
4817 assert(args_type != NULL);
4819 qdict = qdict_new();
4821 if (args_type == NULL || args_type[0] == '\0') {
4822 /* no args, empty qdict */
4823 goto out;
4826 key = qstring_new();
4827 type = qstring_new();
4829 cur_qs = key;
4831 for (i = 0;; i++) {
4832 switch (args_type[i]) {
4833 case ',':
4834 case '\0':
4835 qdict_put(qdict, qstring_get_str(key), type);
4836 QDECREF(key);
4837 if (args_type[i] == '\0') {
4838 goto out;
4840 type = qstring_new(); /* qdict has ref */
4841 cur_qs = key = qstring_new();
4842 break;
4843 case ':':
4844 cur_qs = type;
4845 break;
4846 default:
4847 qstring_append_chr(cur_qs, args_type[i]);
4848 break;
4852 out:
4853 return qdict;
4857 * Client argument checking rules:
4859 * 1. Client must provide all mandatory arguments
4860 * 2. Each argument provided by the client must be expected
4861 * 3. Each argument provided by the client must have the type expected
4862 * by the command
4864 static int qmp_check_client_args(const mon_cmd_t *cmd, QDict *client_args)
4866 int flags, err;
4867 QDict *cmd_args;
4869 cmd_args = qdict_from_args_type(cmd->args_type);
4871 flags = 0;
4872 err = check_mandatory_args(cmd_args, client_args, &flags);
4873 if (err) {
4874 goto out;
4877 err = check_client_args_type(client_args, cmd_args, flags);
4879 out:
4880 QDECREF(cmd_args);
4881 return err;
4885 * Input object checking rules
4887 * 1. Input object must be a dict
4888 * 2. The "execute" key must exist
4889 * 3. The "execute" key must be a string
4890 * 4. If the "arguments" key exists, it must be a dict
4891 * 5. If the "id" key exists, it can be anything (ie. json-value)
4892 * 6. Any argument not listed above is considered invalid
4894 static QDict *qmp_check_input_obj(QObject *input_obj)
4896 const QDictEntry *ent;
4897 int has_exec_key = 0;
4898 QDict *input_dict;
4900 if (qobject_type(input_obj) != QTYPE_QDICT) {
4901 qerror_report(QERR_QMP_BAD_INPUT_OBJECT, "object");
4902 return NULL;
4905 input_dict = qobject_to_qdict(input_obj);
4907 for (ent = qdict_first(input_dict); ent; ent = qdict_next(input_dict, ent)){
4908 const char *arg_name = qdict_entry_key(ent);
4909 const QObject *arg_obj = qdict_entry_value(ent);
4911 if (!strcmp(arg_name, "execute")) {
4912 if (qobject_type(arg_obj) != QTYPE_QSTRING) {
4913 qerror_report(QERR_QMP_BAD_INPUT_OBJECT_MEMBER, "execute",
4914 "string");
4915 return NULL;
4917 has_exec_key = 1;
4918 } else if (!strcmp(arg_name, "arguments")) {
4919 if (qobject_type(arg_obj) != QTYPE_QDICT) {
4920 qerror_report(QERR_QMP_BAD_INPUT_OBJECT_MEMBER, "arguments",
4921 "object");
4922 return NULL;
4924 } else if (!strcmp(arg_name, "id")) {
4925 /* FIXME: check duplicated IDs for async commands */
4926 } else {
4927 qerror_report(QERR_QMP_EXTRA_MEMBER, arg_name);
4928 return NULL;
4932 if (!has_exec_key) {
4933 qerror_report(QERR_QMP_BAD_INPUT_OBJECT, "execute");
4934 return NULL;
4937 return input_dict;
4940 static void qmp_call_query_cmd(Monitor *mon, const mon_cmd_t *cmd)
4942 QObject *ret_data = NULL;
4944 if (handler_is_async(cmd)) {
4945 qmp_async_info_handler(mon, cmd);
4946 if (monitor_has_error(mon)) {
4947 monitor_protocol_emitter(mon, NULL);
4949 } else {
4950 cmd->mhandler.info_new(mon, &ret_data);
4951 monitor_protocol_emitter(mon, ret_data);
4952 qobject_decref(ret_data);
4956 static void qmp_call_cmd(Monitor *mon, const mon_cmd_t *cmd,
4957 const QDict *params)
4959 int ret;
4960 QObject *data = NULL;
4962 mon_print_count_init(mon);
4964 ret = cmd->mhandler.cmd_new(mon, params, &data);
4965 handler_audit(mon, cmd, ret);
4966 monitor_protocol_emitter(mon, data);
4967 qobject_decref(data);
4970 static void handle_qmp_command(JSONMessageParser *parser, QList *tokens)
4972 int err;
4973 QObject *obj;
4974 QDict *input, *args;
4975 const mon_cmd_t *cmd;
4976 Monitor *mon = cur_mon;
4977 const char *cmd_name, *query_cmd;
4979 query_cmd = NULL;
4980 args = input = NULL;
4982 obj = json_parser_parse(tokens, NULL);
4983 if (!obj) {
4984 // FIXME: should be triggered in json_parser_parse()
4985 qerror_report(QERR_JSON_PARSING);
4986 goto err_out;
4989 input = qmp_check_input_obj(obj);
4990 if (!input) {
4991 qobject_decref(obj);
4992 goto err_out;
4995 mon->mc->id = qdict_get(input, "id");
4996 qobject_incref(mon->mc->id);
4998 cmd_name = qdict_get_str(input, "execute");
4999 if (invalid_qmp_mode(mon, cmd_name)) {
5000 qerror_report(QERR_COMMAND_NOT_FOUND, cmd_name);
5001 goto err_out;
5004 if (strstart(cmd_name, "query-", &query_cmd)) {
5005 cmd = qmp_find_query_cmd(query_cmd);
5006 } else {
5007 cmd = qmp_find_cmd(cmd_name);
5010 if (!cmd) {
5011 qerror_report(QERR_COMMAND_NOT_FOUND, cmd_name);
5012 goto err_out;
5015 obj = qdict_get(input, "arguments");
5016 if (!obj) {
5017 args = qdict_new();
5018 } else {
5019 args = qobject_to_qdict(obj);
5020 QINCREF(args);
5023 err = qmp_check_client_args(cmd, args);
5024 if (err < 0) {
5025 goto err_out;
5028 if (query_cmd) {
5029 qmp_call_query_cmd(mon, cmd);
5030 } else if (handler_is_async(cmd)) {
5031 err = qmp_async_cmd_handler(mon, cmd, args);
5032 if (err) {
5033 /* emit the error response */
5034 goto err_out;
5036 } else {
5037 qmp_call_cmd(mon, cmd, args);
5040 goto out;
5042 err_out:
5043 monitor_protocol_emitter(mon, NULL);
5044 out:
5045 QDECREF(input);
5046 QDECREF(args);
5050 * monitor_control_read(): Read and handle QMP input
5052 static void monitor_control_read(void *opaque, const uint8_t *buf, int size)
5054 Monitor *old_mon = cur_mon;
5056 cur_mon = opaque;
5058 json_message_parser_feed(&cur_mon->mc->parser, (const char *) buf, size);
5060 cur_mon = old_mon;
5063 static void monitor_read(void *opaque, const uint8_t *buf, int size)
5065 Monitor *old_mon = cur_mon;
5066 int i;
5068 cur_mon = opaque;
5070 if (cur_mon->rs) {
5071 for (i = 0; i < size; i++)
5072 readline_handle_byte(cur_mon->rs, buf[i]);
5073 } else {
5074 if (size == 0 || buf[size - 1] != 0)
5075 monitor_printf(cur_mon, "corrupted command\n");
5076 else
5077 handle_user_command(cur_mon, (char *)buf);
5080 cur_mon = old_mon;
5083 static void monitor_command_cb(Monitor *mon, const char *cmdline, void *opaque)
5085 monitor_suspend(mon);
5086 handle_user_command(mon, cmdline);
5087 monitor_resume(mon);
5090 int monitor_suspend(Monitor *mon)
5092 if (!mon->rs)
5093 return -ENOTTY;
5094 mon->suspend_cnt++;
5095 return 0;
5098 void monitor_resume(Monitor *mon)
5100 if (!mon->rs)
5101 return;
5102 if (--mon->suspend_cnt == 0)
5103 readline_show_prompt(mon->rs);
5106 static QObject *get_qmp_greeting(void)
5108 QObject *ver;
5110 do_info_version(NULL, &ver);
5111 return qobject_from_jsonf("{'QMP':{'version': %p,'capabilities': []}}",ver);
5115 * monitor_control_event(): Print QMP gretting
5117 static void monitor_control_event(void *opaque, int event)
5119 QObject *data;
5120 Monitor *mon = opaque;
5122 switch (event) {
5123 case CHR_EVENT_OPENED:
5124 mon->mc->command_mode = 0;
5125 json_message_parser_init(&mon->mc->parser, handle_qmp_command);
5126 data = get_qmp_greeting();
5127 monitor_json_emitter(mon, data);
5128 qobject_decref(data);
5129 break;
5130 case CHR_EVENT_CLOSED:
5131 json_message_parser_destroy(&mon->mc->parser);
5132 break;
5136 static void monitor_event(void *opaque, int event)
5138 Monitor *mon = opaque;
5140 switch (event) {
5141 case CHR_EVENT_MUX_IN:
5142 mon->mux_out = 0;
5143 if (mon->reset_seen) {
5144 readline_restart(mon->rs);
5145 monitor_resume(mon);
5146 monitor_flush(mon);
5147 } else {
5148 mon->suspend_cnt = 0;
5150 break;
5152 case CHR_EVENT_MUX_OUT:
5153 if (mon->reset_seen) {
5154 if (mon->suspend_cnt == 0) {
5155 monitor_printf(mon, "\n");
5157 monitor_flush(mon);
5158 monitor_suspend(mon);
5159 } else {
5160 mon->suspend_cnt++;
5162 mon->mux_out = 1;
5163 break;
5165 case CHR_EVENT_OPENED:
5166 monitor_printf(mon, "QEMU %s monitor - type 'help' for more "
5167 "information\n", QEMU_VERSION);
5168 if (!mon->mux_out) {
5169 readline_show_prompt(mon->rs);
5171 mon->reset_seen = 1;
5172 break;
5178 * Local variables:
5179 * c-indent-level: 4
5180 * c-basic-offset: 4
5181 * tab-width: 8
5182 * End:
5185 void monitor_init(CharDriverState *chr, int flags)
5187 static int is_first_init = 1;
5188 Monitor *mon;
5190 if (is_first_init) {
5191 key_timer = qemu_new_timer_ns(vm_clock, release_keys, NULL);
5192 is_first_init = 0;
5195 mon = qemu_mallocz(sizeof(*mon));
5197 mon->chr = chr;
5198 mon->flags = flags;
5199 if (flags & MONITOR_USE_READLINE) {
5200 mon->rs = readline_init(mon, monitor_find_completion);
5201 monitor_read_command(mon, 0);
5204 if (monitor_ctrl_mode(mon)) {
5205 mon->mc = qemu_mallocz(sizeof(MonitorControl));
5206 /* Control mode requires special handlers */
5207 qemu_chr_add_handlers(chr, monitor_can_read, monitor_control_read,
5208 monitor_control_event, mon);
5209 qemu_chr_set_echo(chr, true);
5210 } else {
5211 qemu_chr_add_handlers(chr, monitor_can_read, monitor_read,
5212 monitor_event, mon);
5215 QLIST_INSERT_HEAD(&mon_list, mon, entry);
5216 if (!default_mon || (flags & MONITOR_IS_DEFAULT))
5217 default_mon = mon;
5220 static void bdrv_password_cb(Monitor *mon, const char *password, void *opaque)
5222 BlockDriverState *bs = opaque;
5223 int ret = 0;
5225 if (bdrv_set_key(bs, password) != 0) {
5226 monitor_printf(mon, "invalid password\n");
5227 ret = -EPERM;
5229 if (mon->password_completion_cb)
5230 mon->password_completion_cb(mon->password_opaque, ret);
5232 monitor_read_command(mon, 1);
5235 int monitor_read_bdrv_key_start(Monitor *mon, BlockDriverState *bs,
5236 BlockDriverCompletionFunc *completion_cb,
5237 void *opaque)
5239 int err;
5241 if (!bdrv_key_required(bs)) {
5242 if (completion_cb)
5243 completion_cb(opaque, 0);
5244 return 0;
5247 if (monitor_ctrl_mode(mon)) {
5248 qerror_report(QERR_DEVICE_ENCRYPTED, bdrv_get_device_name(bs));
5249 return -1;
5252 monitor_printf(mon, "%s (%s) is encrypted.\n", bdrv_get_device_name(bs),
5253 bdrv_get_encrypted_filename(bs));
5255 mon->password_completion_cb = completion_cb;
5256 mon->password_opaque = opaque;
5258 err = monitor_read_password(mon, bdrv_password_cb, bs);
5260 if (err && completion_cb)
5261 completion_cb(opaque, err);
5263 return err;