Monitor: Introduce cmd_new_ret()
[qemu.git] / monitor.c
blob63c62fb3aee8435238b8346202e6840cb1f4a231
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 "sysemu.h"
38 #include "monitor.h"
39 #include "readline.h"
40 #include "console.h"
41 #include "block.h"
42 #include "audio/audio.h"
43 #include "disas.h"
44 #include "balloon.h"
45 #include "qemu-timer.h"
46 #include "migration.h"
47 #include "kvm.h"
48 #include "acl.h"
49 #include "qint.h"
50 #include "qfloat.h"
51 #include "qlist.h"
52 #include "qdict.h"
53 #include "qbool.h"
54 #include "qstring.h"
55 #include "qerror.h"
56 #include "qjson.h"
57 #include "json-streamer.h"
58 #include "json-parser.h"
59 #include "osdep.h"
61 //#define DEBUG
62 //#define DEBUG_COMPLETION
65 * Supported types:
67 * 'F' filename
68 * 'B' block device name
69 * 's' string (accept optional quote)
70 * 'i' 32 bit integer
71 * 'l' target long (32 or 64 bit)
72 * 'M' just like 'l', except in user mode the value is
73 * multiplied by 2^20 (think Mebibyte)
74 * 'b' double
75 * user mode accepts an optional G, g, M, m, K, k suffix,
76 * which multiplies the value by 2^30 for suffixes G and
77 * g, 2^20 for M and m, 2^10 for K and k
78 * 'T' double
79 * user mode accepts an optional ms, us, ns suffix,
80 * which divides the value by 1e3, 1e6, 1e9, respectively
81 * '/' optional gdb-like print format (like "/10x")
83 * '?' optional type (for all types, except '/')
84 * '.' other form of optional type (for 'i' and 'l')
85 * '-' optional parameter (eg. '-f')
89 typedef struct MonitorCompletionData MonitorCompletionData;
90 struct MonitorCompletionData {
91 Monitor *mon;
92 void (*user_print)(Monitor *mon, const QObject *data);
95 typedef struct mon_cmd_t {
96 const char *name;
97 const char *args_type;
98 const char *params;
99 const char *help;
100 void (*user_print)(Monitor *mon, const QObject *data);
101 int (*cmd_new_ret)(Monitor *mon, const QDict *params, QObject **ret_data);
102 union {
103 void (*info)(Monitor *mon);
104 void (*info_new)(Monitor *mon, QObject **ret_data);
105 int (*info_async)(Monitor *mon, MonitorCompletion *cb, void *opaque);
106 void (*cmd)(Monitor *mon, const QDict *qdict);
107 void (*cmd_new)(Monitor *mon, const QDict *params, QObject **ret_data);
108 int (*cmd_async)(Monitor *mon, const QDict *params,
109 MonitorCompletion *cb, void *opaque);
110 } mhandler;
111 int async;
112 } mon_cmd_t;
114 /* file descriptors passed via SCM_RIGHTS */
115 typedef struct mon_fd_t mon_fd_t;
116 struct mon_fd_t {
117 char *name;
118 int fd;
119 QLIST_ENTRY(mon_fd_t) next;
122 typedef struct MonitorControl {
123 QObject *id;
124 int print_enabled;
125 JSONMessageParser parser;
126 int command_mode;
127 } MonitorControl;
129 struct Monitor {
130 CharDriverState *chr;
131 int mux_out;
132 int reset_seen;
133 int flags;
134 int suspend_cnt;
135 uint8_t outbuf[1024];
136 int outbuf_index;
137 ReadLineState *rs;
138 MonitorControl *mc;
139 CPUState *mon_cpu;
140 BlockDriverCompletionFunc *password_completion_cb;
141 void *password_opaque;
142 QError *error;
143 QLIST_HEAD(,mon_fd_t) fds;
144 QLIST_ENTRY(Monitor) entry;
147 static QLIST_HEAD(mon_list, Monitor) mon_list;
149 static const mon_cmd_t mon_cmds[];
150 static const mon_cmd_t info_cmds[];
152 Monitor *cur_mon = NULL;
154 static void monitor_command_cb(Monitor *mon, const char *cmdline,
155 void *opaque);
157 static inline int qmp_cmd_mode(const Monitor *mon)
159 return (mon->mc ? mon->mc->command_mode : 0);
162 /* Return true if in control mode, false otherwise */
163 static inline int monitor_ctrl_mode(const Monitor *mon)
165 return (mon->flags & MONITOR_USE_CONTROL);
168 static void monitor_read_command(Monitor *mon, int show_prompt)
170 if (!mon->rs)
171 return;
173 readline_start(mon->rs, "(qemu) ", 0, monitor_command_cb, NULL);
174 if (show_prompt)
175 readline_show_prompt(mon->rs);
178 static int monitor_read_password(Monitor *mon, ReadLineFunc *readline_func,
179 void *opaque)
181 if (monitor_ctrl_mode(mon)) {
182 qemu_error_new(QERR_MISSING_PARAMETER, "password");
183 return -EINVAL;
184 } else if (mon->rs) {
185 readline_start(mon->rs, "Password: ", 1, readline_func, opaque);
186 /* prompt is printed on return from the command handler */
187 return 0;
188 } else {
189 monitor_printf(mon, "terminal does not support password prompting\n");
190 return -ENOTTY;
194 void monitor_flush(Monitor *mon)
196 if (mon && mon->outbuf_index != 0 && !mon->mux_out) {
197 qemu_chr_write(mon->chr, mon->outbuf, mon->outbuf_index);
198 mon->outbuf_index = 0;
202 /* flush at every end of line or if the buffer is full */
203 static void monitor_puts(Monitor *mon, const char *str)
205 char c;
207 for(;;) {
208 c = *str++;
209 if (c == '\0')
210 break;
211 if (c == '\n')
212 mon->outbuf[mon->outbuf_index++] = '\r';
213 mon->outbuf[mon->outbuf_index++] = c;
214 if (mon->outbuf_index >= (sizeof(mon->outbuf) - 1)
215 || c == '\n')
216 monitor_flush(mon);
220 void monitor_vprintf(Monitor *mon, const char *fmt, va_list ap)
222 if (!mon)
223 return;
225 if (mon->mc && !mon->mc->print_enabled) {
226 qemu_error_new(QERR_UNDEFINED_ERROR);
227 } else {
228 char buf[4096];
229 vsnprintf(buf, sizeof(buf), fmt, ap);
230 monitor_puts(mon, buf);
234 void monitor_printf(Monitor *mon, const char *fmt, ...)
236 va_list ap;
237 va_start(ap, fmt);
238 monitor_vprintf(mon, fmt, ap);
239 va_end(ap);
242 void monitor_print_filename(Monitor *mon, const char *filename)
244 int i;
246 for (i = 0; filename[i]; i++) {
247 switch (filename[i]) {
248 case ' ':
249 case '"':
250 case '\\':
251 monitor_printf(mon, "\\%c", filename[i]);
252 break;
253 case '\t':
254 monitor_printf(mon, "\\t");
255 break;
256 case '\r':
257 monitor_printf(mon, "\\r");
258 break;
259 case '\n':
260 monitor_printf(mon, "\\n");
261 break;
262 default:
263 monitor_printf(mon, "%c", filename[i]);
264 break;
269 static int monitor_fprintf(FILE *stream, const char *fmt, ...)
271 va_list ap;
272 va_start(ap, fmt);
273 monitor_vprintf((Monitor *)stream, fmt, ap);
274 va_end(ap);
275 return 0;
278 static void monitor_user_noop(Monitor *mon, const QObject *data) { }
280 static inline int monitor_handler_ported(const mon_cmd_t *cmd)
282 return cmd->user_print != NULL;
285 static inline bool monitor_handler_is_async(const mon_cmd_t *cmd)
287 return cmd->async != 0;
290 static inline int monitor_has_error(const Monitor *mon)
292 return mon->error != NULL;
295 static void monitor_json_emitter(Monitor *mon, const QObject *data)
297 QString *json;
299 json = qobject_to_json(data);
300 assert(json != NULL);
302 mon->mc->print_enabled = 1;
303 monitor_printf(mon, "%s\n", qstring_get_str(json));
304 mon->mc->print_enabled = 0;
306 QDECREF(json);
309 static void monitor_protocol_emitter(Monitor *mon, QObject *data)
311 QDict *qmp;
313 qmp = qdict_new();
315 if (!monitor_has_error(mon)) {
316 /* success response */
317 if (data) {
318 qobject_incref(data);
319 qdict_put_obj(qmp, "return", data);
320 } else {
321 /* return an empty QDict by default */
322 qdict_put(qmp, "return", qdict_new());
324 } else {
325 /* error response */
326 qdict_put(mon->error->error, "desc", qerror_human(mon->error));
327 qdict_put(qmp, "error", mon->error->error);
328 QINCREF(mon->error->error);
329 QDECREF(mon->error);
330 mon->error = NULL;
333 if (mon->mc->id) {
334 qdict_put_obj(qmp, "id", mon->mc->id);
335 mon->mc->id = NULL;
338 monitor_json_emitter(mon, QOBJECT(qmp));
339 QDECREF(qmp);
342 static void timestamp_put(QDict *qdict)
344 int err;
345 QObject *obj;
346 qemu_timeval tv;
348 err = qemu_gettimeofday(&tv);
349 if (err < 0)
350 return;
352 obj = qobject_from_jsonf("{ 'seconds': %" PRId64 ", "
353 "'microseconds': %" PRId64 " }",
354 (int64_t) tv.tv_sec, (int64_t) tv.tv_usec);
355 qdict_put_obj(qdict, "timestamp", obj);
359 * monitor_protocol_event(): Generate a Monitor event
361 * Event-specific data can be emitted through the (optional) 'data' parameter.
363 void monitor_protocol_event(MonitorEvent event, QObject *data)
365 QDict *qmp;
366 const char *event_name;
367 Monitor *mon;
369 assert(event < QEVENT_MAX);
371 switch (event) {
372 case QEVENT_DEBUG:
373 event_name = "DEBUG";
374 break;
375 case QEVENT_SHUTDOWN:
376 event_name = "SHUTDOWN";
377 break;
378 case QEVENT_RESET:
379 event_name = "RESET";
380 break;
381 case QEVENT_POWERDOWN:
382 event_name = "POWERDOWN";
383 break;
384 case QEVENT_STOP:
385 event_name = "STOP";
386 break;
387 case QEVENT_VNC_CONNECTED:
388 event_name = "VNC_CONNECTED";
389 break;
390 case QEVENT_VNC_INITIALIZED:
391 event_name = "VNC_INITIALIZED";
392 break;
393 case QEVENT_VNC_DISCONNECTED:
394 event_name = "VNC_DISCONNECTED";
395 break;
396 case QEVENT_BLOCK_IO_ERROR:
397 event_name = "BLOCK_IO_ERROR";
398 break;
399 default:
400 abort();
401 break;
404 qmp = qdict_new();
405 timestamp_put(qmp);
406 qdict_put(qmp, "event", qstring_from_str(event_name));
407 if (data) {
408 qobject_incref(data);
409 qdict_put_obj(qmp, "data", data);
412 QLIST_FOREACH(mon, &mon_list, entry) {
413 if (monitor_ctrl_mode(mon) && qmp_cmd_mode(mon)) {
414 monitor_json_emitter(mon, QOBJECT(qmp));
417 QDECREF(qmp);
420 static void do_qmp_capabilities(Monitor *mon, const QDict *params,
421 QObject **ret_data)
423 /* Will setup QMP capabilities in the future */
424 if (monitor_ctrl_mode(mon)) {
425 mon->mc->command_mode = 1;
429 static int compare_cmd(const char *name, const char *list)
431 const char *p, *pstart;
432 int len;
433 len = strlen(name);
434 p = list;
435 for(;;) {
436 pstart = p;
437 p = strchr(p, '|');
438 if (!p)
439 p = pstart + strlen(pstart);
440 if ((p - pstart) == len && !memcmp(pstart, name, len))
441 return 1;
442 if (*p == '\0')
443 break;
444 p++;
446 return 0;
449 static void help_cmd_dump(Monitor *mon, const mon_cmd_t *cmds,
450 const char *prefix, const char *name)
452 const mon_cmd_t *cmd;
454 for(cmd = cmds; cmd->name != NULL; cmd++) {
455 if (!name || !strcmp(name, cmd->name))
456 monitor_printf(mon, "%s%s %s -- %s\n", prefix, cmd->name,
457 cmd->params, cmd->help);
461 static void help_cmd(Monitor *mon, const char *name)
463 if (name && !strcmp(name, "info")) {
464 help_cmd_dump(mon, info_cmds, "info ", NULL);
465 } else {
466 help_cmd_dump(mon, mon_cmds, "", name);
467 if (name && !strcmp(name, "log")) {
468 const CPULogItem *item;
469 monitor_printf(mon, "Log items (comma separated):\n");
470 monitor_printf(mon, "%-10s %s\n", "none", "remove all logs");
471 for(item = cpu_log_items; item->mask != 0; item++) {
472 monitor_printf(mon, "%-10s %s\n", item->name, item->help);
478 static void do_help_cmd(Monitor *mon, const QDict *qdict)
480 help_cmd(mon, qdict_get_try_str(qdict, "name"));
483 static void do_commit(Monitor *mon, const QDict *qdict)
485 int all_devices;
486 DriveInfo *dinfo;
487 const char *device = qdict_get_str(qdict, "device");
489 all_devices = !strcmp(device, "all");
490 QTAILQ_FOREACH(dinfo, &drives, next) {
491 if (!all_devices)
492 if (strcmp(bdrv_get_device_name(dinfo->bdrv), device))
493 continue;
494 bdrv_commit(dinfo->bdrv);
498 static void user_monitor_complete(void *opaque, QObject *ret_data)
500 MonitorCompletionData *data = (MonitorCompletionData *)opaque;
502 if (ret_data) {
503 data->user_print(data->mon, ret_data);
505 monitor_resume(data->mon);
506 qemu_free(data);
509 static void qmp_monitor_complete(void *opaque, QObject *ret_data)
511 monitor_protocol_emitter(opaque, ret_data);
514 static void qmp_async_cmd_handler(Monitor *mon, const mon_cmd_t *cmd,
515 const QDict *params)
517 cmd->mhandler.cmd_async(mon, params, qmp_monitor_complete, mon);
520 static void qmp_async_info_handler(Monitor *mon, const mon_cmd_t *cmd)
522 cmd->mhandler.info_async(mon, qmp_monitor_complete, mon);
525 static void user_async_cmd_handler(Monitor *mon, const mon_cmd_t *cmd,
526 const QDict *params)
528 int ret;
530 MonitorCompletionData *cb_data = qemu_malloc(sizeof(*cb_data));
531 cb_data->mon = mon;
532 cb_data->user_print = cmd->user_print;
533 monitor_suspend(mon);
534 ret = cmd->mhandler.cmd_async(mon, params,
535 user_monitor_complete, cb_data);
536 if (ret < 0) {
537 monitor_resume(mon);
538 qemu_free(cb_data);
542 static void user_async_info_handler(Monitor *mon, const mon_cmd_t *cmd)
544 int ret;
546 MonitorCompletionData *cb_data = qemu_malloc(sizeof(*cb_data));
547 cb_data->mon = mon;
548 cb_data->user_print = cmd->user_print;
549 monitor_suspend(mon);
550 ret = cmd->mhandler.info_async(mon, user_monitor_complete, cb_data);
551 if (ret < 0) {
552 monitor_resume(mon);
553 qemu_free(cb_data);
557 static void do_info(Monitor *mon, const QDict *qdict, QObject **ret_data)
559 const mon_cmd_t *cmd;
560 const char *item = qdict_get_try_str(qdict, "item");
562 if (!item) {
563 assert(monitor_ctrl_mode(mon) == 0);
564 goto help;
567 for (cmd = info_cmds; cmd->name != NULL; cmd++) {
568 if (compare_cmd(item, cmd->name))
569 break;
572 if (cmd->name == NULL) {
573 if (monitor_ctrl_mode(mon)) {
574 qemu_error_new(QERR_COMMAND_NOT_FOUND, item);
575 return;
577 goto help;
580 if (monitor_handler_is_async(cmd)) {
581 if (monitor_ctrl_mode(mon)) {
582 qmp_async_info_handler(mon, cmd);
583 } else {
584 user_async_info_handler(mon, cmd);
587 * Indicate that this command is asynchronous and will not return any
588 * data (not even empty). Instead, the data will be returned via a
589 * completion callback.
591 *ret_data = qobject_from_jsonf("{ '__mon_async': 'return' }");
592 } else if (monitor_handler_ported(cmd)) {
593 cmd->mhandler.info_new(mon, ret_data);
595 if (!monitor_ctrl_mode(mon)) {
597 * User Protocol function is called here, Monitor Protocol is
598 * handled by monitor_call_handler()
600 if (*ret_data)
601 cmd->user_print(mon, *ret_data);
603 } else {
604 if (monitor_ctrl_mode(mon)) {
605 /* handler not converted yet */
606 qemu_error_new(QERR_COMMAND_NOT_FOUND, item);
607 } else {
608 cmd->mhandler.info(mon);
612 return;
614 help:
615 help_cmd(mon, "info");
618 static void do_info_version_print(Monitor *mon, const QObject *data)
620 QDict *qdict;
622 qdict = qobject_to_qdict(data);
624 monitor_printf(mon, "%s%s\n", qdict_get_str(qdict, "qemu"),
625 qdict_get_str(qdict, "package"));
629 * do_info_version(): Show QEMU version
631 * Return a QDict with the following information:
633 * - "qemu": QEMU's version
634 * - "package": package's version
636 * Example:
638 * { "qemu": "0.11.50", "package": "" }
640 static void do_info_version(Monitor *mon, QObject **ret_data)
642 *ret_data = qobject_from_jsonf("{ 'qemu': %s, 'package': %s }",
643 QEMU_VERSION, QEMU_PKGVERSION);
646 static void do_info_name_print(Monitor *mon, const QObject *data)
648 QDict *qdict;
650 qdict = qobject_to_qdict(data);
651 if (qdict_size(qdict) == 0) {
652 return;
655 monitor_printf(mon, "%s\n", qdict_get_str(qdict, "name"));
659 * do_info_name(): Show VM name
661 * Return a QDict with the following information:
663 * - "name": VM's name (optional)
665 * Example:
667 * { "name": "qemu-name" }
669 static void do_info_name(Monitor *mon, QObject **ret_data)
671 *ret_data = qemu_name ? qobject_from_jsonf("{'name': %s }", qemu_name) :
672 qobject_from_jsonf("{}");
675 static QObject *get_cmd_dict(const char *name)
677 const char *p;
679 /* Remove '|' from some commands */
680 p = strchr(name, '|');
681 if (p) {
682 p++;
683 } else {
684 p = name;
687 return qobject_from_jsonf("{ 'name': %s }", p);
691 * do_info_commands(): List QMP available commands
693 * Each command is represented by a QDict, the returned QObject is a QList
694 * of all commands.
696 * The QDict contains:
698 * - "name": command's name
700 * Example:
702 * { [ { "name": "query-balloon" }, { "name": "system_powerdown" } ] }
704 static void do_info_commands(Monitor *mon, QObject **ret_data)
706 QList *cmd_list;
707 const mon_cmd_t *cmd;
709 cmd_list = qlist_new();
711 for (cmd = mon_cmds; cmd->name != NULL; cmd++) {
712 if (monitor_handler_ported(cmd) && !compare_cmd(cmd->name, "info")) {
713 qlist_append_obj(cmd_list, get_cmd_dict(cmd->name));
717 for (cmd = info_cmds; cmd->name != NULL; cmd++) {
718 if (monitor_handler_ported(cmd)) {
719 char buf[128];
720 snprintf(buf, sizeof(buf), "query-%s", cmd->name);
721 qlist_append_obj(cmd_list, get_cmd_dict(buf));
725 *ret_data = QOBJECT(cmd_list);
728 #if defined(TARGET_I386)
729 static void do_info_hpet_print(Monitor *mon, const QObject *data)
731 monitor_printf(mon, "HPET is %s by QEMU\n",
732 qdict_get_bool(qobject_to_qdict(data), "enabled") ?
733 "enabled" : "disabled");
737 * do_info_hpet(): Show HPET state
739 * Return a QDict with the following information:
741 * - "enabled": true if hpet if enabled, false otherwise
743 * Example:
745 * { "enabled": true }
747 static void do_info_hpet(Monitor *mon, QObject **ret_data)
749 *ret_data = qobject_from_jsonf("{ 'enabled': %i }", !no_hpet);
751 #endif
753 static void do_info_uuid_print(Monitor *mon, const QObject *data)
755 monitor_printf(mon, "%s\n", qdict_get_str(qobject_to_qdict(data), "UUID"));
759 * do_info_uuid(): Show VM UUID
761 * Return a QDict with the following information:
763 * - "UUID": Universally Unique Identifier
765 * Example:
767 * { "UUID": "550e8400-e29b-41d4-a716-446655440000" }
769 static void do_info_uuid(Monitor *mon, QObject **ret_data)
771 char uuid[64];
773 snprintf(uuid, sizeof(uuid), UUID_FMT, qemu_uuid[0], qemu_uuid[1],
774 qemu_uuid[2], qemu_uuid[3], qemu_uuid[4], qemu_uuid[5],
775 qemu_uuid[6], qemu_uuid[7], qemu_uuid[8], qemu_uuid[9],
776 qemu_uuid[10], qemu_uuid[11], qemu_uuid[12], qemu_uuid[13],
777 qemu_uuid[14], qemu_uuid[15]);
778 *ret_data = qobject_from_jsonf("{ 'UUID': %s }", uuid);
781 /* get the current CPU defined by the user */
782 static int mon_set_cpu(int cpu_index)
784 CPUState *env;
786 for(env = first_cpu; env != NULL; env = env->next_cpu) {
787 if (env->cpu_index == cpu_index) {
788 cur_mon->mon_cpu = env;
789 return 0;
792 return -1;
795 static CPUState *mon_get_cpu(void)
797 if (!cur_mon->mon_cpu) {
798 mon_set_cpu(0);
800 cpu_synchronize_state(cur_mon->mon_cpu);
801 return cur_mon->mon_cpu;
804 static void do_info_registers(Monitor *mon)
806 CPUState *env;
807 env = mon_get_cpu();
808 #ifdef TARGET_I386
809 cpu_dump_state(env, (FILE *)mon, monitor_fprintf,
810 X86_DUMP_FPU);
811 #else
812 cpu_dump_state(env, (FILE *)mon, monitor_fprintf,
814 #endif
817 static void print_cpu_iter(QObject *obj, void *opaque)
819 QDict *cpu;
820 int active = ' ';
821 Monitor *mon = opaque;
823 assert(qobject_type(obj) == QTYPE_QDICT);
824 cpu = qobject_to_qdict(obj);
826 if (qdict_get_bool(cpu, "current")) {
827 active = '*';
830 monitor_printf(mon, "%c CPU #%d: ", active, (int)qdict_get_int(cpu, "CPU"));
832 #if defined(TARGET_I386)
833 monitor_printf(mon, "pc=0x" TARGET_FMT_lx,
834 (target_ulong) qdict_get_int(cpu, "pc"));
835 #elif defined(TARGET_PPC)
836 monitor_printf(mon, "nip=0x" TARGET_FMT_lx,
837 (target_long) qdict_get_int(cpu, "nip"));
838 #elif defined(TARGET_SPARC)
839 monitor_printf(mon, "pc=0x " TARGET_FMT_lx,
840 (target_long) qdict_get_int(cpu, "pc"));
841 monitor_printf(mon, "npc=0x" TARGET_FMT_lx,
842 (target_long) qdict_get_int(cpu, "npc"));
843 #elif defined(TARGET_MIPS)
844 monitor_printf(mon, "PC=0x" TARGET_FMT_lx,
845 (target_long) qdict_get_int(cpu, "PC"));
846 #endif
848 if (qdict_get_bool(cpu, "halted")) {
849 monitor_printf(mon, " (halted)");
852 monitor_printf(mon, "\n");
855 static void monitor_print_cpus(Monitor *mon, const QObject *data)
857 QList *cpu_list;
859 assert(qobject_type(data) == QTYPE_QLIST);
860 cpu_list = qobject_to_qlist(data);
861 qlist_iter(cpu_list, print_cpu_iter, mon);
865 * do_info_cpus(): Show CPU information
867 * Return a QList. Each CPU is represented by a QDict, which contains:
869 * - "cpu": CPU index
870 * - "current": true if this is the current CPU, false otherwise
871 * - "halted": true if the cpu is halted, false otherwise
872 * - Current program counter. The key's name depends on the architecture:
873 * "pc": i386/x86)64
874 * "nip": PPC
875 * "pc" and "npc": sparc
876 * "PC": mips
878 * Example:
880 * [ { "CPU": 0, "current": true, "halted": false, "pc": 3227107138 },
881 * { "CPU": 1, "current": false, "halted": true, "pc": 7108165 } ]
883 static void do_info_cpus(Monitor *mon, QObject **ret_data)
885 CPUState *env;
886 QList *cpu_list;
888 cpu_list = qlist_new();
890 /* just to set the default cpu if not already done */
891 mon_get_cpu();
893 for(env = first_cpu; env != NULL; env = env->next_cpu) {
894 QDict *cpu;
895 QObject *obj;
897 cpu_synchronize_state(env);
899 obj = qobject_from_jsonf("{ 'CPU': %d, 'current': %i, 'halted': %i }",
900 env->cpu_index, env == mon->mon_cpu,
901 env->halted);
903 cpu = qobject_to_qdict(obj);
905 #if defined(TARGET_I386)
906 qdict_put(cpu, "pc", qint_from_int(env->eip + env->segs[R_CS].base));
907 #elif defined(TARGET_PPC)
908 qdict_put(cpu, "nip", qint_from_int(env->nip));
909 #elif defined(TARGET_SPARC)
910 qdict_put(cpu, "pc", qint_from_int(env->pc));
911 qdict_put(cpu, "npc", qint_from_int(env->npc));
912 #elif defined(TARGET_MIPS)
913 qdict_put(cpu, "PC", qint_from_int(env->active_tc.PC));
914 #endif
916 qlist_append(cpu_list, cpu);
919 *ret_data = QOBJECT(cpu_list);
922 static void do_cpu_set(Monitor *mon, const QDict *qdict, QObject **ret_data)
924 int index = qdict_get_int(qdict, "index");
925 if (mon_set_cpu(index) < 0)
926 qemu_error_new(QERR_INVALID_PARAMETER, "index");
929 static void do_info_jit(Monitor *mon)
931 dump_exec_info((FILE *)mon, monitor_fprintf);
934 static void do_info_history(Monitor *mon)
936 int i;
937 const char *str;
939 if (!mon->rs)
940 return;
941 i = 0;
942 for(;;) {
943 str = readline_get_history(mon->rs, i);
944 if (!str)
945 break;
946 monitor_printf(mon, "%d: '%s'\n", i, str);
947 i++;
951 #if defined(TARGET_PPC)
952 /* XXX: not implemented in other targets */
953 static void do_info_cpu_stats(Monitor *mon)
955 CPUState *env;
957 env = mon_get_cpu();
958 cpu_dump_statistics(env, (FILE *)mon, &monitor_fprintf, 0);
960 #endif
963 * do_quit(): Quit QEMU execution
965 static void do_quit(Monitor *mon, const QDict *qdict, QObject **ret_data)
967 exit(0);
970 static int eject_device(Monitor *mon, BlockDriverState *bs, int force)
972 if (bdrv_is_inserted(bs)) {
973 if (!force) {
974 if (!bdrv_is_removable(bs)) {
975 qemu_error_new(QERR_DEVICE_NOT_REMOVABLE,
976 bdrv_get_device_name(bs));
977 return -1;
979 if (bdrv_is_locked(bs)) {
980 qemu_error_new(QERR_DEVICE_LOCKED, bdrv_get_device_name(bs));
981 return -1;
984 bdrv_close(bs);
986 return 0;
989 static void do_eject(Monitor *mon, const QDict *qdict, QObject **ret_data)
991 BlockDriverState *bs;
992 int force = qdict_get_int(qdict, "force");
993 const char *filename = qdict_get_str(qdict, "device");
995 bs = bdrv_find(filename);
996 if (!bs) {
997 qemu_error_new(QERR_DEVICE_NOT_FOUND, filename);
998 return;
1000 eject_device(mon, bs, force);
1003 static void do_block_set_passwd(Monitor *mon, const QDict *qdict,
1004 QObject **ret_data)
1006 BlockDriverState *bs;
1008 bs = bdrv_find(qdict_get_str(qdict, "device"));
1009 if (!bs) {
1010 qemu_error_new(QERR_DEVICE_NOT_FOUND, qdict_get_str(qdict, "device"));
1011 return;
1014 if (bdrv_set_key(bs, qdict_get_str(qdict, "password")) < 0) {
1015 qemu_error_new(QERR_INVALID_PASSWORD);
1019 static void do_change_block(Monitor *mon, const char *device,
1020 const char *filename, const char *fmt)
1022 BlockDriverState *bs;
1023 BlockDriver *drv = NULL;
1025 bs = bdrv_find(device);
1026 if (!bs) {
1027 qemu_error_new(QERR_DEVICE_NOT_FOUND, device);
1028 return;
1030 if (fmt) {
1031 drv = bdrv_find_whitelisted_format(fmt);
1032 if (!drv) {
1033 qemu_error_new(QERR_INVALID_BLOCK_FORMAT, fmt);
1034 return;
1037 if (eject_device(mon, bs, 0) < 0)
1038 return;
1039 bdrv_open2(bs, filename, BDRV_O_RDWR, drv);
1040 monitor_read_bdrv_key_start(mon, bs, NULL, NULL);
1043 static void change_vnc_password(const char *password)
1045 if (vnc_display_password(NULL, password) < 0)
1046 qemu_error_new(QERR_SET_PASSWD_FAILED);
1050 static void change_vnc_password_cb(Monitor *mon, const char *password,
1051 void *opaque)
1053 change_vnc_password(password);
1054 monitor_read_command(mon, 1);
1057 static void do_change_vnc(Monitor *mon, const char *target, const char *arg)
1059 if (strcmp(target, "passwd") == 0 ||
1060 strcmp(target, "password") == 0) {
1061 if (arg) {
1062 char password[9];
1063 strncpy(password, arg, sizeof(password));
1064 password[sizeof(password) - 1] = '\0';
1065 change_vnc_password(password);
1066 } else {
1067 monitor_read_password(mon, change_vnc_password_cb, NULL);
1069 } else {
1070 if (vnc_display_open(NULL, target) < 0)
1071 qemu_error_new(QERR_VNC_SERVER_FAILED, target);
1076 * do_change(): Change a removable medium, or VNC configuration
1078 static void do_change(Monitor *mon, const QDict *qdict, QObject **ret_data)
1080 const char *device = qdict_get_str(qdict, "device");
1081 const char *target = qdict_get_str(qdict, "target");
1082 const char *arg = qdict_get_try_str(qdict, "arg");
1083 if (strcmp(device, "vnc") == 0) {
1084 do_change_vnc(mon, target, arg);
1085 } else {
1086 do_change_block(mon, device, target, arg);
1090 static void do_screen_dump(Monitor *mon, const QDict *qdict)
1092 vga_hw_screen_dump(qdict_get_str(qdict, "filename"));
1095 static void do_logfile(Monitor *mon, const QDict *qdict)
1097 cpu_set_log_filename(qdict_get_str(qdict, "filename"));
1100 static void do_log(Monitor *mon, const QDict *qdict)
1102 int mask;
1103 const char *items = qdict_get_str(qdict, "items");
1105 if (!strcmp(items, "none")) {
1106 mask = 0;
1107 } else {
1108 mask = cpu_str_to_log_mask(items);
1109 if (!mask) {
1110 help_cmd(mon, "log");
1111 return;
1114 cpu_set_log(mask);
1117 static void do_singlestep(Monitor *mon, const QDict *qdict)
1119 const char *option = qdict_get_try_str(qdict, "option");
1120 if (!option || !strcmp(option, "on")) {
1121 singlestep = 1;
1122 } else if (!strcmp(option, "off")) {
1123 singlestep = 0;
1124 } else {
1125 monitor_printf(mon, "unexpected option %s\n", option);
1130 * do_stop(): Stop VM execution
1132 static void do_stop(Monitor *mon, const QDict *qdict, QObject **ret_data)
1134 vm_stop(EXCP_INTERRUPT);
1137 static void encrypted_bdrv_it(void *opaque, BlockDriverState *bs);
1139 struct bdrv_iterate_context {
1140 Monitor *mon;
1141 int err;
1145 * do_cont(): Resume emulation.
1147 static void do_cont(Monitor *mon, const QDict *qdict, QObject **ret_data)
1149 struct bdrv_iterate_context context = { mon, 0 };
1151 bdrv_iterate(encrypted_bdrv_it, &context);
1152 /* only resume the vm if all keys are set and valid */
1153 if (!context.err)
1154 vm_start();
1157 static void bdrv_key_cb(void *opaque, int err)
1159 Monitor *mon = opaque;
1161 /* another key was set successfully, retry to continue */
1162 if (!err)
1163 do_cont(mon, NULL, NULL);
1166 static void encrypted_bdrv_it(void *opaque, BlockDriverState *bs)
1168 struct bdrv_iterate_context *context = opaque;
1170 if (!context->err && bdrv_key_required(bs)) {
1171 context->err = -EBUSY;
1172 monitor_read_bdrv_key_start(context->mon, bs, bdrv_key_cb,
1173 context->mon);
1177 static void do_gdbserver(Monitor *mon, const QDict *qdict)
1179 const char *device = qdict_get_try_str(qdict, "device");
1180 if (!device)
1181 device = "tcp::" DEFAULT_GDBSTUB_PORT;
1182 if (gdbserver_start(device) < 0) {
1183 monitor_printf(mon, "Could not open gdbserver on device '%s'\n",
1184 device);
1185 } else if (strcmp(device, "none") == 0) {
1186 monitor_printf(mon, "Disabled gdbserver\n");
1187 } else {
1188 monitor_printf(mon, "Waiting for gdb connection on device '%s'\n",
1189 device);
1193 static void do_watchdog_action(Monitor *mon, const QDict *qdict)
1195 const char *action = qdict_get_str(qdict, "action");
1196 if (select_watchdog_action(action) == -1) {
1197 monitor_printf(mon, "Unknown watchdog action '%s'\n", action);
1201 static void monitor_printc(Monitor *mon, int c)
1203 monitor_printf(mon, "'");
1204 switch(c) {
1205 case '\'':
1206 monitor_printf(mon, "\\'");
1207 break;
1208 case '\\':
1209 monitor_printf(mon, "\\\\");
1210 break;
1211 case '\n':
1212 monitor_printf(mon, "\\n");
1213 break;
1214 case '\r':
1215 monitor_printf(mon, "\\r");
1216 break;
1217 default:
1218 if (c >= 32 && c <= 126) {
1219 monitor_printf(mon, "%c", c);
1220 } else {
1221 monitor_printf(mon, "\\x%02x", c);
1223 break;
1225 monitor_printf(mon, "'");
1228 static void memory_dump(Monitor *mon, int count, int format, int wsize,
1229 target_phys_addr_t addr, int is_physical)
1231 CPUState *env;
1232 int l, line_size, i, max_digits, len;
1233 uint8_t buf[16];
1234 uint64_t v;
1236 if (format == 'i') {
1237 int flags;
1238 flags = 0;
1239 env = mon_get_cpu();
1240 if (!is_physical)
1241 return;
1242 #ifdef TARGET_I386
1243 if (wsize == 2) {
1244 flags = 1;
1245 } else if (wsize == 4) {
1246 flags = 0;
1247 } else {
1248 /* as default we use the current CS size */
1249 flags = 0;
1250 if (env) {
1251 #ifdef TARGET_X86_64
1252 if ((env->efer & MSR_EFER_LMA) &&
1253 (env->segs[R_CS].flags & DESC_L_MASK))
1254 flags = 2;
1255 else
1256 #endif
1257 if (!(env->segs[R_CS].flags & DESC_B_MASK))
1258 flags = 1;
1261 #endif
1262 monitor_disas(mon, env, addr, count, is_physical, flags);
1263 return;
1266 len = wsize * count;
1267 if (wsize == 1)
1268 line_size = 8;
1269 else
1270 line_size = 16;
1271 max_digits = 0;
1273 switch(format) {
1274 case 'o':
1275 max_digits = (wsize * 8 + 2) / 3;
1276 break;
1277 default:
1278 case 'x':
1279 max_digits = (wsize * 8) / 4;
1280 break;
1281 case 'u':
1282 case 'd':
1283 max_digits = (wsize * 8 * 10 + 32) / 33;
1284 break;
1285 case 'c':
1286 wsize = 1;
1287 break;
1290 while (len > 0) {
1291 if (is_physical)
1292 monitor_printf(mon, TARGET_FMT_plx ":", addr);
1293 else
1294 monitor_printf(mon, TARGET_FMT_lx ":", (target_ulong)addr);
1295 l = len;
1296 if (l > line_size)
1297 l = line_size;
1298 if (is_physical) {
1299 cpu_physical_memory_rw(addr, buf, l, 0);
1300 } else {
1301 env = mon_get_cpu();
1302 if (cpu_memory_rw_debug(env, addr, buf, l, 0) < 0) {
1303 monitor_printf(mon, " Cannot access memory\n");
1304 break;
1307 i = 0;
1308 while (i < l) {
1309 switch(wsize) {
1310 default:
1311 case 1:
1312 v = ldub_raw(buf + i);
1313 break;
1314 case 2:
1315 v = lduw_raw(buf + i);
1316 break;
1317 case 4:
1318 v = (uint32_t)ldl_raw(buf + i);
1319 break;
1320 case 8:
1321 v = ldq_raw(buf + i);
1322 break;
1324 monitor_printf(mon, " ");
1325 switch(format) {
1326 case 'o':
1327 monitor_printf(mon, "%#*" PRIo64, max_digits, v);
1328 break;
1329 case 'x':
1330 monitor_printf(mon, "0x%0*" PRIx64, max_digits, v);
1331 break;
1332 case 'u':
1333 monitor_printf(mon, "%*" PRIu64, max_digits, v);
1334 break;
1335 case 'd':
1336 monitor_printf(mon, "%*" PRId64, max_digits, v);
1337 break;
1338 case 'c':
1339 monitor_printc(mon, v);
1340 break;
1342 i += wsize;
1344 monitor_printf(mon, "\n");
1345 addr += l;
1346 len -= l;
1350 static void do_memory_dump(Monitor *mon, const QDict *qdict)
1352 int count = qdict_get_int(qdict, "count");
1353 int format = qdict_get_int(qdict, "format");
1354 int size = qdict_get_int(qdict, "size");
1355 target_long addr = qdict_get_int(qdict, "addr");
1357 memory_dump(mon, count, format, size, addr, 0);
1360 static void do_physical_memory_dump(Monitor *mon, const QDict *qdict)
1362 int count = qdict_get_int(qdict, "count");
1363 int format = qdict_get_int(qdict, "format");
1364 int size = qdict_get_int(qdict, "size");
1365 target_phys_addr_t addr = qdict_get_int(qdict, "addr");
1367 memory_dump(mon, count, format, size, addr, 1);
1370 static void do_print(Monitor *mon, const QDict *qdict)
1372 int format = qdict_get_int(qdict, "format");
1373 target_phys_addr_t val = qdict_get_int(qdict, "val");
1375 #if TARGET_PHYS_ADDR_BITS == 32
1376 switch(format) {
1377 case 'o':
1378 monitor_printf(mon, "%#o", val);
1379 break;
1380 case 'x':
1381 monitor_printf(mon, "%#x", val);
1382 break;
1383 case 'u':
1384 monitor_printf(mon, "%u", val);
1385 break;
1386 default:
1387 case 'd':
1388 monitor_printf(mon, "%d", val);
1389 break;
1390 case 'c':
1391 monitor_printc(mon, val);
1392 break;
1394 #else
1395 switch(format) {
1396 case 'o':
1397 monitor_printf(mon, "%#" PRIo64, val);
1398 break;
1399 case 'x':
1400 monitor_printf(mon, "%#" PRIx64, val);
1401 break;
1402 case 'u':
1403 monitor_printf(mon, "%" PRIu64, val);
1404 break;
1405 default:
1406 case 'd':
1407 monitor_printf(mon, "%" PRId64, val);
1408 break;
1409 case 'c':
1410 monitor_printc(mon, val);
1411 break;
1413 #endif
1414 monitor_printf(mon, "\n");
1417 static void do_memory_save(Monitor *mon, const QDict *qdict, QObject **ret_data)
1419 FILE *f;
1420 uint32_t size = qdict_get_int(qdict, "size");
1421 const char *filename = qdict_get_str(qdict, "filename");
1422 target_long addr = qdict_get_int(qdict, "val");
1423 uint32_t l;
1424 CPUState *env;
1425 uint8_t buf[1024];
1427 env = mon_get_cpu();
1429 f = fopen(filename, "wb");
1430 if (!f) {
1431 qemu_error_new(QERR_OPEN_FILE_FAILED, filename);
1432 return;
1434 while (size != 0) {
1435 l = sizeof(buf);
1436 if (l > size)
1437 l = size;
1438 cpu_memory_rw_debug(env, addr, buf, l, 0);
1439 if (fwrite(buf, 1, l, f) != l) {
1440 monitor_printf(mon, "fwrite() error in do_memory_save\n");
1441 goto exit;
1443 addr += l;
1444 size -= l;
1446 exit:
1447 fclose(f);
1450 static void do_physical_memory_save(Monitor *mon, const QDict *qdict,
1451 QObject **ret_data)
1453 FILE *f;
1454 uint32_t l;
1455 uint8_t buf[1024];
1456 uint32_t size = qdict_get_int(qdict, "size");
1457 const char *filename = qdict_get_str(qdict, "filename");
1458 target_phys_addr_t addr = qdict_get_int(qdict, "val");
1460 f = fopen(filename, "wb");
1461 if (!f) {
1462 qemu_error_new(QERR_OPEN_FILE_FAILED, filename);
1463 return;
1465 while (size != 0) {
1466 l = sizeof(buf);
1467 if (l > size)
1468 l = size;
1469 cpu_physical_memory_rw(addr, buf, l, 0);
1470 if (fwrite(buf, 1, l, f) != l) {
1471 monitor_printf(mon, "fwrite() error in do_physical_memory_save\n");
1472 goto exit;
1474 fflush(f);
1475 addr += l;
1476 size -= l;
1478 exit:
1479 fclose(f);
1482 static void do_sum(Monitor *mon, const QDict *qdict)
1484 uint32_t addr;
1485 uint8_t buf[1];
1486 uint16_t sum;
1487 uint32_t start = qdict_get_int(qdict, "start");
1488 uint32_t size = qdict_get_int(qdict, "size");
1490 sum = 0;
1491 for(addr = start; addr < (start + size); addr++) {
1492 cpu_physical_memory_rw(addr, buf, 1, 0);
1493 /* BSD sum algorithm ('sum' Unix command) */
1494 sum = (sum >> 1) | (sum << 15);
1495 sum += buf[0];
1497 monitor_printf(mon, "%05d\n", sum);
1500 typedef struct {
1501 int keycode;
1502 const char *name;
1503 } KeyDef;
1505 static const KeyDef key_defs[] = {
1506 { 0x2a, "shift" },
1507 { 0x36, "shift_r" },
1509 { 0x38, "alt" },
1510 { 0xb8, "alt_r" },
1511 { 0x64, "altgr" },
1512 { 0xe4, "altgr_r" },
1513 { 0x1d, "ctrl" },
1514 { 0x9d, "ctrl_r" },
1516 { 0xdd, "menu" },
1518 { 0x01, "esc" },
1520 { 0x02, "1" },
1521 { 0x03, "2" },
1522 { 0x04, "3" },
1523 { 0x05, "4" },
1524 { 0x06, "5" },
1525 { 0x07, "6" },
1526 { 0x08, "7" },
1527 { 0x09, "8" },
1528 { 0x0a, "9" },
1529 { 0x0b, "0" },
1530 { 0x0c, "minus" },
1531 { 0x0d, "equal" },
1532 { 0x0e, "backspace" },
1534 { 0x0f, "tab" },
1535 { 0x10, "q" },
1536 { 0x11, "w" },
1537 { 0x12, "e" },
1538 { 0x13, "r" },
1539 { 0x14, "t" },
1540 { 0x15, "y" },
1541 { 0x16, "u" },
1542 { 0x17, "i" },
1543 { 0x18, "o" },
1544 { 0x19, "p" },
1546 { 0x1c, "ret" },
1548 { 0x1e, "a" },
1549 { 0x1f, "s" },
1550 { 0x20, "d" },
1551 { 0x21, "f" },
1552 { 0x22, "g" },
1553 { 0x23, "h" },
1554 { 0x24, "j" },
1555 { 0x25, "k" },
1556 { 0x26, "l" },
1558 { 0x2c, "z" },
1559 { 0x2d, "x" },
1560 { 0x2e, "c" },
1561 { 0x2f, "v" },
1562 { 0x30, "b" },
1563 { 0x31, "n" },
1564 { 0x32, "m" },
1565 { 0x33, "comma" },
1566 { 0x34, "dot" },
1567 { 0x35, "slash" },
1569 { 0x37, "asterisk" },
1571 { 0x39, "spc" },
1572 { 0x3a, "caps_lock" },
1573 { 0x3b, "f1" },
1574 { 0x3c, "f2" },
1575 { 0x3d, "f3" },
1576 { 0x3e, "f4" },
1577 { 0x3f, "f5" },
1578 { 0x40, "f6" },
1579 { 0x41, "f7" },
1580 { 0x42, "f8" },
1581 { 0x43, "f9" },
1582 { 0x44, "f10" },
1583 { 0x45, "num_lock" },
1584 { 0x46, "scroll_lock" },
1586 { 0xb5, "kp_divide" },
1587 { 0x37, "kp_multiply" },
1588 { 0x4a, "kp_subtract" },
1589 { 0x4e, "kp_add" },
1590 { 0x9c, "kp_enter" },
1591 { 0x53, "kp_decimal" },
1592 { 0x54, "sysrq" },
1594 { 0x52, "kp_0" },
1595 { 0x4f, "kp_1" },
1596 { 0x50, "kp_2" },
1597 { 0x51, "kp_3" },
1598 { 0x4b, "kp_4" },
1599 { 0x4c, "kp_5" },
1600 { 0x4d, "kp_6" },
1601 { 0x47, "kp_7" },
1602 { 0x48, "kp_8" },
1603 { 0x49, "kp_9" },
1605 { 0x56, "<" },
1607 { 0x57, "f11" },
1608 { 0x58, "f12" },
1610 { 0xb7, "print" },
1612 { 0xc7, "home" },
1613 { 0xc9, "pgup" },
1614 { 0xd1, "pgdn" },
1615 { 0xcf, "end" },
1617 { 0xcb, "left" },
1618 { 0xc8, "up" },
1619 { 0xd0, "down" },
1620 { 0xcd, "right" },
1622 { 0xd2, "insert" },
1623 { 0xd3, "delete" },
1624 #if defined(TARGET_SPARC) && !defined(TARGET_SPARC64)
1625 { 0xf0, "stop" },
1626 { 0xf1, "again" },
1627 { 0xf2, "props" },
1628 { 0xf3, "undo" },
1629 { 0xf4, "front" },
1630 { 0xf5, "copy" },
1631 { 0xf6, "open" },
1632 { 0xf7, "paste" },
1633 { 0xf8, "find" },
1634 { 0xf9, "cut" },
1635 { 0xfa, "lf" },
1636 { 0xfb, "help" },
1637 { 0xfc, "meta_l" },
1638 { 0xfd, "meta_r" },
1639 { 0xfe, "compose" },
1640 #endif
1641 { 0, NULL },
1644 static int get_keycode(const char *key)
1646 const KeyDef *p;
1647 char *endp;
1648 int ret;
1650 for(p = key_defs; p->name != NULL; p++) {
1651 if (!strcmp(key, p->name))
1652 return p->keycode;
1654 if (strstart(key, "0x", NULL)) {
1655 ret = strtoul(key, &endp, 0);
1656 if (*endp == '\0' && ret >= 0x01 && ret <= 0xff)
1657 return ret;
1659 return -1;
1662 #define MAX_KEYCODES 16
1663 static uint8_t keycodes[MAX_KEYCODES];
1664 static int nb_pending_keycodes;
1665 static QEMUTimer *key_timer;
1667 static void release_keys(void *opaque)
1669 int keycode;
1671 while (nb_pending_keycodes > 0) {
1672 nb_pending_keycodes--;
1673 keycode = keycodes[nb_pending_keycodes];
1674 if (keycode & 0x80)
1675 kbd_put_keycode(0xe0);
1676 kbd_put_keycode(keycode | 0x80);
1680 static void do_sendkey(Monitor *mon, const QDict *qdict)
1682 char keyname_buf[16];
1683 char *separator;
1684 int keyname_len, keycode, i;
1685 const char *string = qdict_get_str(qdict, "string");
1686 int has_hold_time = qdict_haskey(qdict, "hold_time");
1687 int hold_time = qdict_get_try_int(qdict, "hold_time", -1);
1689 if (nb_pending_keycodes > 0) {
1690 qemu_del_timer(key_timer);
1691 release_keys(NULL);
1693 if (!has_hold_time)
1694 hold_time = 100;
1695 i = 0;
1696 while (1) {
1697 separator = strchr(string, '-');
1698 keyname_len = separator ? separator - string : strlen(string);
1699 if (keyname_len > 0) {
1700 pstrcpy(keyname_buf, sizeof(keyname_buf), string);
1701 if (keyname_len > sizeof(keyname_buf) - 1) {
1702 monitor_printf(mon, "invalid key: '%s...'\n", keyname_buf);
1703 return;
1705 if (i == MAX_KEYCODES) {
1706 monitor_printf(mon, "too many keys\n");
1707 return;
1709 keyname_buf[keyname_len] = 0;
1710 keycode = get_keycode(keyname_buf);
1711 if (keycode < 0) {
1712 monitor_printf(mon, "unknown key: '%s'\n", keyname_buf);
1713 return;
1715 keycodes[i++] = keycode;
1717 if (!separator)
1718 break;
1719 string = separator + 1;
1721 nb_pending_keycodes = i;
1722 /* key down events */
1723 for (i = 0; i < nb_pending_keycodes; i++) {
1724 keycode = keycodes[i];
1725 if (keycode & 0x80)
1726 kbd_put_keycode(0xe0);
1727 kbd_put_keycode(keycode & 0x7f);
1729 /* delayed key up events */
1730 qemu_mod_timer(key_timer, qemu_get_clock(vm_clock) +
1731 muldiv64(get_ticks_per_sec(), hold_time, 1000));
1734 static int mouse_button_state;
1736 static void do_mouse_move(Monitor *mon, const QDict *qdict)
1738 int dx, dy, dz;
1739 const char *dx_str = qdict_get_str(qdict, "dx_str");
1740 const char *dy_str = qdict_get_str(qdict, "dy_str");
1741 const char *dz_str = qdict_get_try_str(qdict, "dz_str");
1742 dx = strtol(dx_str, NULL, 0);
1743 dy = strtol(dy_str, NULL, 0);
1744 dz = 0;
1745 if (dz_str)
1746 dz = strtol(dz_str, NULL, 0);
1747 kbd_mouse_event(dx, dy, dz, mouse_button_state);
1750 static void do_mouse_button(Monitor *mon, const QDict *qdict)
1752 int button_state = qdict_get_int(qdict, "button_state");
1753 mouse_button_state = button_state;
1754 kbd_mouse_event(0, 0, 0, mouse_button_state);
1757 static void do_ioport_read(Monitor *mon, const QDict *qdict)
1759 int size = qdict_get_int(qdict, "size");
1760 int addr = qdict_get_int(qdict, "addr");
1761 int has_index = qdict_haskey(qdict, "index");
1762 uint32_t val;
1763 int suffix;
1765 if (has_index) {
1766 int index = qdict_get_int(qdict, "index");
1767 cpu_outb(addr & IOPORTS_MASK, index & 0xff);
1768 addr++;
1770 addr &= 0xffff;
1772 switch(size) {
1773 default:
1774 case 1:
1775 val = cpu_inb(addr);
1776 suffix = 'b';
1777 break;
1778 case 2:
1779 val = cpu_inw(addr);
1780 suffix = 'w';
1781 break;
1782 case 4:
1783 val = cpu_inl(addr);
1784 suffix = 'l';
1785 break;
1787 monitor_printf(mon, "port%c[0x%04x] = %#0*x\n",
1788 suffix, addr, size * 2, val);
1791 static void do_ioport_write(Monitor *mon, const QDict *qdict)
1793 int size = qdict_get_int(qdict, "size");
1794 int addr = qdict_get_int(qdict, "addr");
1795 int val = qdict_get_int(qdict, "val");
1797 addr &= IOPORTS_MASK;
1799 switch (size) {
1800 default:
1801 case 1:
1802 cpu_outb(addr, val);
1803 break;
1804 case 2:
1805 cpu_outw(addr, val);
1806 break;
1807 case 4:
1808 cpu_outl(addr, val);
1809 break;
1813 static void do_boot_set(Monitor *mon, const QDict *qdict)
1815 int res;
1816 const char *bootdevice = qdict_get_str(qdict, "bootdevice");
1818 res = qemu_boot_set(bootdevice);
1819 if (res == 0) {
1820 monitor_printf(mon, "boot device list now set to %s\n", bootdevice);
1821 } else if (res > 0) {
1822 monitor_printf(mon, "setting boot device list failed\n");
1823 } else {
1824 monitor_printf(mon, "no function defined to set boot device list for "
1825 "this architecture\n");
1830 * do_system_reset(): Issue a machine reset
1832 static void do_system_reset(Monitor *mon, const QDict *qdict,
1833 QObject **ret_data)
1835 qemu_system_reset_request();
1839 * do_system_powerdown(): Issue a machine powerdown
1841 static void do_system_powerdown(Monitor *mon, const QDict *qdict,
1842 QObject **ret_data)
1844 qemu_system_powerdown_request();
1847 #if defined(TARGET_I386)
1848 static void print_pte(Monitor *mon, uint32_t addr, uint32_t pte, uint32_t mask)
1850 monitor_printf(mon, "%08x: %08x %c%c%c%c%c%c%c%c\n",
1851 addr,
1852 pte & mask,
1853 pte & PG_GLOBAL_MASK ? 'G' : '-',
1854 pte & PG_PSE_MASK ? 'P' : '-',
1855 pte & PG_DIRTY_MASK ? 'D' : '-',
1856 pte & PG_ACCESSED_MASK ? 'A' : '-',
1857 pte & PG_PCD_MASK ? 'C' : '-',
1858 pte & PG_PWT_MASK ? 'T' : '-',
1859 pte & PG_USER_MASK ? 'U' : '-',
1860 pte & PG_RW_MASK ? 'W' : '-');
1863 static void tlb_info(Monitor *mon)
1865 CPUState *env;
1866 int l1, l2;
1867 uint32_t pgd, pde, pte;
1869 env = mon_get_cpu();
1871 if (!(env->cr[0] & CR0_PG_MASK)) {
1872 monitor_printf(mon, "PG disabled\n");
1873 return;
1875 pgd = env->cr[3] & ~0xfff;
1876 for(l1 = 0; l1 < 1024; l1++) {
1877 cpu_physical_memory_read(pgd + l1 * 4, (uint8_t *)&pde, 4);
1878 pde = le32_to_cpu(pde);
1879 if (pde & PG_PRESENT_MASK) {
1880 if ((pde & PG_PSE_MASK) && (env->cr[4] & CR4_PSE_MASK)) {
1881 print_pte(mon, (l1 << 22), pde, ~((1 << 20) - 1));
1882 } else {
1883 for(l2 = 0; l2 < 1024; l2++) {
1884 cpu_physical_memory_read((pde & ~0xfff) + l2 * 4,
1885 (uint8_t *)&pte, 4);
1886 pte = le32_to_cpu(pte);
1887 if (pte & PG_PRESENT_MASK) {
1888 print_pte(mon, (l1 << 22) + (l2 << 12),
1889 pte & ~PG_PSE_MASK,
1890 ~0xfff);
1898 static void mem_print(Monitor *mon, uint32_t *pstart, int *plast_prot,
1899 uint32_t end, int prot)
1901 int prot1;
1902 prot1 = *plast_prot;
1903 if (prot != prot1) {
1904 if (*pstart != -1) {
1905 monitor_printf(mon, "%08x-%08x %08x %c%c%c\n",
1906 *pstart, end, end - *pstart,
1907 prot1 & PG_USER_MASK ? 'u' : '-',
1908 'r',
1909 prot1 & PG_RW_MASK ? 'w' : '-');
1911 if (prot != 0)
1912 *pstart = end;
1913 else
1914 *pstart = -1;
1915 *plast_prot = prot;
1919 static void mem_info(Monitor *mon)
1921 CPUState *env;
1922 int l1, l2, prot, last_prot;
1923 uint32_t pgd, pde, pte, start, end;
1925 env = mon_get_cpu();
1927 if (!(env->cr[0] & CR0_PG_MASK)) {
1928 monitor_printf(mon, "PG disabled\n");
1929 return;
1931 pgd = env->cr[3] & ~0xfff;
1932 last_prot = 0;
1933 start = -1;
1934 for(l1 = 0; l1 < 1024; l1++) {
1935 cpu_physical_memory_read(pgd + l1 * 4, (uint8_t *)&pde, 4);
1936 pde = le32_to_cpu(pde);
1937 end = l1 << 22;
1938 if (pde & PG_PRESENT_MASK) {
1939 if ((pde & PG_PSE_MASK) && (env->cr[4] & CR4_PSE_MASK)) {
1940 prot = pde & (PG_USER_MASK | PG_RW_MASK | PG_PRESENT_MASK);
1941 mem_print(mon, &start, &last_prot, end, prot);
1942 } else {
1943 for(l2 = 0; l2 < 1024; l2++) {
1944 cpu_physical_memory_read((pde & ~0xfff) + l2 * 4,
1945 (uint8_t *)&pte, 4);
1946 pte = le32_to_cpu(pte);
1947 end = (l1 << 22) + (l2 << 12);
1948 if (pte & PG_PRESENT_MASK) {
1949 prot = pte & (PG_USER_MASK | PG_RW_MASK | PG_PRESENT_MASK);
1950 } else {
1951 prot = 0;
1953 mem_print(mon, &start, &last_prot, end, prot);
1956 } else {
1957 prot = 0;
1958 mem_print(mon, &start, &last_prot, end, prot);
1962 #endif
1964 #if defined(TARGET_SH4)
1966 static void print_tlb(Monitor *mon, int idx, tlb_t *tlb)
1968 monitor_printf(mon, " tlb%i:\t"
1969 "asid=%hhu vpn=%x\tppn=%x\tsz=%hhu size=%u\t"
1970 "v=%hhu shared=%hhu cached=%hhu prot=%hhu "
1971 "dirty=%hhu writethrough=%hhu\n",
1972 idx,
1973 tlb->asid, tlb->vpn, tlb->ppn, tlb->sz, tlb->size,
1974 tlb->v, tlb->sh, tlb->c, tlb->pr,
1975 tlb->d, tlb->wt);
1978 static void tlb_info(Monitor *mon)
1980 CPUState *env = mon_get_cpu();
1981 int i;
1983 monitor_printf (mon, "ITLB:\n");
1984 for (i = 0 ; i < ITLB_SIZE ; i++)
1985 print_tlb (mon, i, &env->itlb[i]);
1986 monitor_printf (mon, "UTLB:\n");
1987 for (i = 0 ; i < UTLB_SIZE ; i++)
1988 print_tlb (mon, i, &env->utlb[i]);
1991 #endif
1993 static void do_info_kvm_print(Monitor *mon, const QObject *data)
1995 QDict *qdict;
1997 qdict = qobject_to_qdict(data);
1999 monitor_printf(mon, "kvm support: ");
2000 if (qdict_get_bool(qdict, "present")) {
2001 monitor_printf(mon, "%s\n", qdict_get_bool(qdict, "enabled") ?
2002 "enabled" : "disabled");
2003 } else {
2004 monitor_printf(mon, "not compiled\n");
2009 * do_info_kvm(): Show KVM information
2011 * Return a QDict with the following information:
2013 * - "enabled": true if KVM support is enabled, false otherwise
2014 * - "present": true if QEMU has KVM support, false otherwise
2016 * Example:
2018 * { "enabled": true, "present": true }
2020 static void do_info_kvm(Monitor *mon, QObject **ret_data)
2022 #ifdef CONFIG_KVM
2023 *ret_data = qobject_from_jsonf("{ 'enabled': %i, 'present': true }",
2024 kvm_enabled());
2025 #else
2026 *ret_data = qobject_from_jsonf("{ 'enabled': false, 'present': false }");
2027 #endif
2030 static void do_info_numa(Monitor *mon)
2032 int i;
2033 CPUState *env;
2035 monitor_printf(mon, "%d nodes\n", nb_numa_nodes);
2036 for (i = 0; i < nb_numa_nodes; i++) {
2037 monitor_printf(mon, "node %d cpus:", i);
2038 for (env = first_cpu; env != NULL; env = env->next_cpu) {
2039 if (env->numa_node == i) {
2040 monitor_printf(mon, " %d", env->cpu_index);
2043 monitor_printf(mon, "\n");
2044 monitor_printf(mon, "node %d size: %" PRId64 " MB\n", i,
2045 node_mem[i] >> 20);
2049 #ifdef CONFIG_PROFILER
2051 int64_t qemu_time;
2052 int64_t dev_time;
2054 static void do_info_profile(Monitor *mon)
2056 int64_t total;
2057 total = qemu_time;
2058 if (total == 0)
2059 total = 1;
2060 monitor_printf(mon, "async time %" PRId64 " (%0.3f)\n",
2061 dev_time, dev_time / (double)get_ticks_per_sec());
2062 monitor_printf(mon, "qemu time %" PRId64 " (%0.3f)\n",
2063 qemu_time, qemu_time / (double)get_ticks_per_sec());
2064 qemu_time = 0;
2065 dev_time = 0;
2067 #else
2068 static void do_info_profile(Monitor *mon)
2070 monitor_printf(mon, "Internal profiler not compiled\n");
2072 #endif
2074 /* Capture support */
2075 static QLIST_HEAD (capture_list_head, CaptureState) capture_head;
2077 static void do_info_capture(Monitor *mon)
2079 int i;
2080 CaptureState *s;
2082 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
2083 monitor_printf(mon, "[%d]: ", i);
2084 s->ops.info (s->opaque);
2088 #ifdef HAS_AUDIO
2089 static void do_stop_capture(Monitor *mon, const QDict *qdict)
2091 int i;
2092 int n = qdict_get_int(qdict, "n");
2093 CaptureState *s;
2095 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
2096 if (i == n) {
2097 s->ops.destroy (s->opaque);
2098 QLIST_REMOVE (s, entries);
2099 qemu_free (s);
2100 return;
2105 static void do_wav_capture(Monitor *mon, const QDict *qdict)
2107 const char *path = qdict_get_str(qdict, "path");
2108 int has_freq = qdict_haskey(qdict, "freq");
2109 int freq = qdict_get_try_int(qdict, "freq", -1);
2110 int has_bits = qdict_haskey(qdict, "bits");
2111 int bits = qdict_get_try_int(qdict, "bits", -1);
2112 int has_channels = qdict_haskey(qdict, "nchannels");
2113 int nchannels = qdict_get_try_int(qdict, "nchannels", -1);
2114 CaptureState *s;
2116 s = qemu_mallocz (sizeof (*s));
2118 freq = has_freq ? freq : 44100;
2119 bits = has_bits ? bits : 16;
2120 nchannels = has_channels ? nchannels : 2;
2122 if (wav_start_capture (s, path, freq, bits, nchannels)) {
2123 monitor_printf(mon, "Faied to add wave capture\n");
2124 qemu_free (s);
2126 QLIST_INSERT_HEAD (&capture_head, s, entries);
2128 #endif
2130 #if defined(TARGET_I386)
2131 static void do_inject_nmi(Monitor *mon, const QDict *qdict)
2133 CPUState *env;
2134 int cpu_index = qdict_get_int(qdict, "cpu_index");
2136 for (env = first_cpu; env != NULL; env = env->next_cpu)
2137 if (env->cpu_index == cpu_index) {
2138 cpu_interrupt(env, CPU_INTERRUPT_NMI);
2139 break;
2142 #endif
2144 static void do_info_status_print(Monitor *mon, const QObject *data)
2146 QDict *qdict;
2148 qdict = qobject_to_qdict(data);
2150 monitor_printf(mon, "VM status: ");
2151 if (qdict_get_bool(qdict, "running")) {
2152 monitor_printf(mon, "running");
2153 if (qdict_get_bool(qdict, "singlestep")) {
2154 monitor_printf(mon, " (single step mode)");
2156 } else {
2157 monitor_printf(mon, "paused");
2160 monitor_printf(mon, "\n");
2164 * do_info_status(): VM status
2166 * Return a QDict with the following information:
2168 * - "running": true if the VM is running, or false if it is paused
2169 * - "singlestep": true if the VM is in single step mode, false otherwise
2171 * Example:
2173 * { "running": true, "singlestep": false }
2175 static void do_info_status(Monitor *mon, QObject **ret_data)
2177 *ret_data = qobject_from_jsonf("{ 'running': %i, 'singlestep': %i }",
2178 vm_running, singlestep);
2181 static void print_balloon_stat(const char *key, QObject *obj, void *opaque)
2183 Monitor *mon = opaque;
2185 if (strcmp(key, "actual"))
2186 monitor_printf(mon, ",%s=%" PRId64, key,
2187 qint_get_int(qobject_to_qint(obj)));
2190 static void monitor_print_balloon(Monitor *mon, const QObject *data)
2192 QDict *qdict;
2194 qdict = qobject_to_qdict(data);
2195 if (!qdict_haskey(qdict, "actual"))
2196 return;
2198 monitor_printf(mon, "balloon: actual=%" PRId64,
2199 qdict_get_int(qdict, "actual") >> 20);
2200 qdict_iter(qdict, print_balloon_stat, mon);
2201 monitor_printf(mon, "\n");
2205 * do_info_balloon(): Balloon information
2207 * Make an asynchronous request for balloon info. When the request completes
2208 * a QDict will be returned according to the following specification:
2210 * - "actual": current balloon value in bytes
2211 * The following fields may or may not be present:
2212 * - "mem_swapped_in": Amount of memory swapped in (bytes)
2213 * - "mem_swapped_out": Amount of memory swapped out (bytes)
2214 * - "major_page_faults": Number of major faults
2215 * - "minor_page_faults": Number of minor faults
2216 * - "free_mem": Total amount of free and unused memory (bytes)
2217 * - "total_mem": Total amount of available memory (bytes)
2219 * Example:
2221 * { "actual": 1073741824, "mem_swapped_in": 0, "mem_swapped_out": 0,
2222 * "major_page_faults": 142, "minor_page_faults": 239245,
2223 * "free_mem": 1014185984, "total_mem": 1044668416 }
2225 static int do_info_balloon(Monitor *mon, MonitorCompletion cb, void *opaque)
2227 int ret;
2229 if (kvm_enabled() && !kvm_has_sync_mmu()) {
2230 qemu_error_new(QERR_KVM_MISSING_CAP, "synchronous MMU", "balloon");
2231 return -1;
2234 ret = qemu_balloon_status(cb, opaque);
2235 if (!ret) {
2236 qemu_error_new(QERR_DEVICE_NOT_ACTIVE, "balloon");
2237 return -1;
2240 return 0;
2244 * do_balloon(): Request VM to change its memory allocation
2246 static int do_balloon(Monitor *mon, const QDict *params,
2247 MonitorCompletion cb, void *opaque)
2249 int ret;
2251 if (kvm_enabled() && !kvm_has_sync_mmu()) {
2252 qemu_error_new(QERR_KVM_MISSING_CAP, "synchronous MMU", "balloon");
2253 return -1;
2256 ret = qemu_balloon(qdict_get_int(params, "value"), cb, opaque);
2257 if (ret == 0) {
2258 qemu_error_new(QERR_DEVICE_NOT_ACTIVE, "balloon");
2259 return -1;
2262 return 0;
2265 static qemu_acl *find_acl(Monitor *mon, const char *name)
2267 qemu_acl *acl = qemu_acl_find(name);
2269 if (!acl) {
2270 monitor_printf(mon, "acl: unknown list '%s'\n", name);
2272 return acl;
2275 static void do_acl_show(Monitor *mon, const QDict *qdict)
2277 const char *aclname = qdict_get_str(qdict, "aclname");
2278 qemu_acl *acl = find_acl(mon, aclname);
2279 qemu_acl_entry *entry;
2280 int i = 0;
2282 if (acl) {
2283 monitor_printf(mon, "policy: %s\n",
2284 acl->defaultDeny ? "deny" : "allow");
2285 QTAILQ_FOREACH(entry, &acl->entries, next) {
2286 i++;
2287 monitor_printf(mon, "%d: %s %s\n", i,
2288 entry->deny ? "deny" : "allow", entry->match);
2293 static void do_acl_reset(Monitor *mon, const QDict *qdict)
2295 const char *aclname = qdict_get_str(qdict, "aclname");
2296 qemu_acl *acl = find_acl(mon, aclname);
2298 if (acl) {
2299 qemu_acl_reset(acl);
2300 monitor_printf(mon, "acl: removed all rules\n");
2304 static void do_acl_policy(Monitor *mon, const QDict *qdict)
2306 const char *aclname = qdict_get_str(qdict, "aclname");
2307 const char *policy = qdict_get_str(qdict, "policy");
2308 qemu_acl *acl = find_acl(mon, aclname);
2310 if (acl) {
2311 if (strcmp(policy, "allow") == 0) {
2312 acl->defaultDeny = 0;
2313 monitor_printf(mon, "acl: policy set to 'allow'\n");
2314 } else if (strcmp(policy, "deny") == 0) {
2315 acl->defaultDeny = 1;
2316 monitor_printf(mon, "acl: policy set to 'deny'\n");
2317 } else {
2318 monitor_printf(mon, "acl: unknown policy '%s', "
2319 "expected 'deny' or 'allow'\n", policy);
2324 static void do_acl_add(Monitor *mon, const QDict *qdict)
2326 const char *aclname = qdict_get_str(qdict, "aclname");
2327 const char *match = qdict_get_str(qdict, "match");
2328 const char *policy = qdict_get_str(qdict, "policy");
2329 int has_index = qdict_haskey(qdict, "index");
2330 int index = qdict_get_try_int(qdict, "index", -1);
2331 qemu_acl *acl = find_acl(mon, aclname);
2332 int deny, ret;
2334 if (acl) {
2335 if (strcmp(policy, "allow") == 0) {
2336 deny = 0;
2337 } else if (strcmp(policy, "deny") == 0) {
2338 deny = 1;
2339 } else {
2340 monitor_printf(mon, "acl: unknown policy '%s', "
2341 "expected 'deny' or 'allow'\n", policy);
2342 return;
2344 if (has_index)
2345 ret = qemu_acl_insert(acl, deny, match, index);
2346 else
2347 ret = qemu_acl_append(acl, deny, match);
2348 if (ret < 0)
2349 monitor_printf(mon, "acl: unable to add acl entry\n");
2350 else
2351 monitor_printf(mon, "acl: added rule at position %d\n", ret);
2355 static void do_acl_remove(Monitor *mon, const QDict *qdict)
2357 const char *aclname = qdict_get_str(qdict, "aclname");
2358 const char *match = qdict_get_str(qdict, "match");
2359 qemu_acl *acl = find_acl(mon, aclname);
2360 int ret;
2362 if (acl) {
2363 ret = qemu_acl_remove(acl, match);
2364 if (ret < 0)
2365 monitor_printf(mon, "acl: no matching acl entry\n");
2366 else
2367 monitor_printf(mon, "acl: removed rule at position %d\n", ret);
2371 #if defined(TARGET_I386)
2372 static void do_inject_mce(Monitor *mon, const QDict *qdict)
2374 CPUState *cenv;
2375 int cpu_index = qdict_get_int(qdict, "cpu_index");
2376 int bank = qdict_get_int(qdict, "bank");
2377 uint64_t status = qdict_get_int(qdict, "status");
2378 uint64_t mcg_status = qdict_get_int(qdict, "mcg_status");
2379 uint64_t addr = qdict_get_int(qdict, "addr");
2380 uint64_t misc = qdict_get_int(qdict, "misc");
2382 for (cenv = first_cpu; cenv != NULL; cenv = cenv->next_cpu)
2383 if (cenv->cpu_index == cpu_index && cenv->mcg_cap) {
2384 cpu_inject_x86_mce(cenv, bank, status, mcg_status, addr, misc);
2385 break;
2388 #endif
2390 static void do_getfd(Monitor *mon, const QDict *qdict, QObject **ret_data)
2392 const char *fdname = qdict_get_str(qdict, "fdname");
2393 mon_fd_t *monfd;
2394 int fd;
2396 fd = qemu_chr_get_msgfd(mon->chr);
2397 if (fd == -1) {
2398 qemu_error_new(QERR_FD_NOT_SUPPLIED);
2399 return;
2402 if (qemu_isdigit(fdname[0])) {
2403 qemu_error_new(QERR_INVALID_PARAMETER, "fdname");
2404 return;
2407 fd = dup(fd);
2408 if (fd == -1) {
2409 if (errno == EMFILE)
2410 qemu_error_new(QERR_TOO_MANY_FILES);
2411 else
2412 qemu_error_new(QERR_UNDEFINED_ERROR);
2413 return;
2416 QLIST_FOREACH(monfd, &mon->fds, next) {
2417 if (strcmp(monfd->name, fdname) != 0) {
2418 continue;
2421 close(monfd->fd);
2422 monfd->fd = fd;
2423 return;
2426 monfd = qemu_mallocz(sizeof(mon_fd_t));
2427 monfd->name = qemu_strdup(fdname);
2428 monfd->fd = fd;
2430 QLIST_INSERT_HEAD(&mon->fds, monfd, next);
2433 static void do_closefd(Monitor *mon, const QDict *qdict, QObject **ret_data)
2435 const char *fdname = qdict_get_str(qdict, "fdname");
2436 mon_fd_t *monfd;
2438 QLIST_FOREACH(monfd, &mon->fds, next) {
2439 if (strcmp(monfd->name, fdname) != 0) {
2440 continue;
2443 QLIST_REMOVE(monfd, next);
2444 close(monfd->fd);
2445 qemu_free(monfd->name);
2446 qemu_free(monfd);
2447 return;
2450 qemu_error_new(QERR_FD_NOT_FOUND, fdname);
2453 static void do_loadvm(Monitor *mon, const QDict *qdict)
2455 int saved_vm_running = vm_running;
2456 const char *name = qdict_get_str(qdict, "name");
2458 vm_stop(0);
2460 if (load_vmstate(mon, name) >= 0 && saved_vm_running)
2461 vm_start();
2464 int monitor_get_fd(Monitor *mon, const char *fdname)
2466 mon_fd_t *monfd;
2468 QLIST_FOREACH(monfd, &mon->fds, next) {
2469 int fd;
2471 if (strcmp(monfd->name, fdname) != 0) {
2472 continue;
2475 fd = monfd->fd;
2477 /* caller takes ownership of fd */
2478 QLIST_REMOVE(monfd, next);
2479 qemu_free(monfd->name);
2480 qemu_free(monfd);
2482 return fd;
2485 return -1;
2488 static const mon_cmd_t mon_cmds[] = {
2489 #include "qemu-monitor.h"
2490 { NULL, NULL, },
2493 /* Please update qemu-monitor.hx when adding or changing commands */
2494 static const mon_cmd_t info_cmds[] = {
2496 .name = "version",
2497 .args_type = "",
2498 .params = "",
2499 .help = "show the version of QEMU",
2500 .user_print = do_info_version_print,
2501 .mhandler.info_new = do_info_version,
2504 .name = "commands",
2505 .args_type = "",
2506 .params = "",
2507 .help = "list QMP available commands",
2508 .user_print = monitor_user_noop,
2509 .mhandler.info_new = do_info_commands,
2512 .name = "network",
2513 .args_type = "",
2514 .params = "",
2515 .help = "show the network state",
2516 .mhandler.info = do_info_network,
2519 .name = "chardev",
2520 .args_type = "",
2521 .params = "",
2522 .help = "show the character devices",
2523 .user_print = qemu_chr_info_print,
2524 .mhandler.info_new = qemu_chr_info,
2527 .name = "block",
2528 .args_type = "",
2529 .params = "",
2530 .help = "show the block devices",
2531 .user_print = bdrv_info_print,
2532 .mhandler.info_new = bdrv_info,
2535 .name = "blockstats",
2536 .args_type = "",
2537 .params = "",
2538 .help = "show block device statistics",
2539 .user_print = bdrv_stats_print,
2540 .mhandler.info_new = bdrv_info_stats,
2543 .name = "registers",
2544 .args_type = "",
2545 .params = "",
2546 .help = "show the cpu registers",
2547 .mhandler.info = do_info_registers,
2550 .name = "cpus",
2551 .args_type = "",
2552 .params = "",
2553 .help = "show infos for each CPU",
2554 .user_print = monitor_print_cpus,
2555 .mhandler.info_new = do_info_cpus,
2558 .name = "history",
2559 .args_type = "",
2560 .params = "",
2561 .help = "show the command line history",
2562 .mhandler.info = do_info_history,
2565 .name = "irq",
2566 .args_type = "",
2567 .params = "",
2568 .help = "show the interrupts statistics (if available)",
2569 .mhandler.info = irq_info,
2572 .name = "pic",
2573 .args_type = "",
2574 .params = "",
2575 .help = "show i8259 (PIC) state",
2576 .mhandler.info = pic_info,
2579 .name = "pci",
2580 .args_type = "",
2581 .params = "",
2582 .help = "show PCI info",
2583 .user_print = do_pci_info_print,
2584 .mhandler.info_new = do_pci_info,
2586 #if defined(TARGET_I386) || defined(TARGET_SH4)
2588 .name = "tlb",
2589 .args_type = "",
2590 .params = "",
2591 .help = "show virtual to physical memory mappings",
2592 .mhandler.info = tlb_info,
2594 #endif
2595 #if defined(TARGET_I386)
2597 .name = "mem",
2598 .args_type = "",
2599 .params = "",
2600 .help = "show the active virtual memory mappings",
2601 .mhandler.info = mem_info,
2604 .name = "hpet",
2605 .args_type = "",
2606 .params = "",
2607 .help = "show state of HPET",
2608 .user_print = do_info_hpet_print,
2609 .mhandler.info_new = do_info_hpet,
2611 #endif
2613 .name = "jit",
2614 .args_type = "",
2615 .params = "",
2616 .help = "show dynamic compiler info",
2617 .mhandler.info = do_info_jit,
2620 .name = "kvm",
2621 .args_type = "",
2622 .params = "",
2623 .help = "show KVM information",
2624 .user_print = do_info_kvm_print,
2625 .mhandler.info_new = do_info_kvm,
2628 .name = "numa",
2629 .args_type = "",
2630 .params = "",
2631 .help = "show NUMA information",
2632 .mhandler.info = do_info_numa,
2635 .name = "usb",
2636 .args_type = "",
2637 .params = "",
2638 .help = "show guest USB devices",
2639 .mhandler.info = usb_info,
2642 .name = "usbhost",
2643 .args_type = "",
2644 .params = "",
2645 .help = "show host USB devices",
2646 .mhandler.info = usb_host_info,
2649 .name = "profile",
2650 .args_type = "",
2651 .params = "",
2652 .help = "show profiling information",
2653 .mhandler.info = do_info_profile,
2656 .name = "capture",
2657 .args_type = "",
2658 .params = "",
2659 .help = "show capture information",
2660 .mhandler.info = do_info_capture,
2663 .name = "snapshots",
2664 .args_type = "",
2665 .params = "",
2666 .help = "show the currently saved VM snapshots",
2667 .mhandler.info = do_info_snapshots,
2670 .name = "status",
2671 .args_type = "",
2672 .params = "",
2673 .help = "show the current VM status (running|paused)",
2674 .user_print = do_info_status_print,
2675 .mhandler.info_new = do_info_status,
2678 .name = "pcmcia",
2679 .args_type = "",
2680 .params = "",
2681 .help = "show guest PCMCIA status",
2682 .mhandler.info = pcmcia_info,
2685 .name = "mice",
2686 .args_type = "",
2687 .params = "",
2688 .help = "show which guest mouse is receiving events",
2689 .user_print = do_info_mice_print,
2690 .mhandler.info_new = do_info_mice,
2693 .name = "vnc",
2694 .args_type = "",
2695 .params = "",
2696 .help = "show the vnc server status",
2697 .user_print = do_info_vnc_print,
2698 .mhandler.info_new = do_info_vnc,
2701 .name = "name",
2702 .args_type = "",
2703 .params = "",
2704 .help = "show the current VM name",
2705 .user_print = do_info_name_print,
2706 .mhandler.info_new = do_info_name,
2709 .name = "uuid",
2710 .args_type = "",
2711 .params = "",
2712 .help = "show the current VM UUID",
2713 .user_print = do_info_uuid_print,
2714 .mhandler.info_new = do_info_uuid,
2716 #if defined(TARGET_PPC)
2718 .name = "cpustats",
2719 .args_type = "",
2720 .params = "",
2721 .help = "show CPU statistics",
2722 .mhandler.info = do_info_cpu_stats,
2724 #endif
2725 #if defined(CONFIG_SLIRP)
2727 .name = "usernet",
2728 .args_type = "",
2729 .params = "",
2730 .help = "show user network stack connection states",
2731 .mhandler.info = do_info_usernet,
2733 #endif
2735 .name = "migrate",
2736 .args_type = "",
2737 .params = "",
2738 .help = "show migration status",
2739 .user_print = do_info_migrate_print,
2740 .mhandler.info_new = do_info_migrate,
2743 .name = "balloon",
2744 .args_type = "",
2745 .params = "",
2746 .help = "show balloon information",
2747 .user_print = monitor_print_balloon,
2748 .mhandler.info_async = do_info_balloon,
2749 .async = 1,
2752 .name = "qtree",
2753 .args_type = "",
2754 .params = "",
2755 .help = "show device tree",
2756 .mhandler.info = do_info_qtree,
2759 .name = "qdm",
2760 .args_type = "",
2761 .params = "",
2762 .help = "show qdev device model list",
2763 .mhandler.info = do_info_qdm,
2766 .name = "roms",
2767 .args_type = "",
2768 .params = "",
2769 .help = "show roms",
2770 .mhandler.info = do_info_roms,
2773 .name = NULL,
2777 /*******************************************************************/
2779 static const char *pch;
2780 static jmp_buf expr_env;
2782 #define MD_TLONG 0
2783 #define MD_I32 1
2785 typedef struct MonitorDef {
2786 const char *name;
2787 int offset;
2788 target_long (*get_value)(const struct MonitorDef *md, int val);
2789 int type;
2790 } MonitorDef;
2792 #if defined(TARGET_I386)
2793 static target_long monitor_get_pc (const struct MonitorDef *md, int val)
2795 CPUState *env = mon_get_cpu();
2796 return env->eip + env->segs[R_CS].base;
2798 #endif
2800 #if defined(TARGET_PPC)
2801 static target_long monitor_get_ccr (const struct MonitorDef *md, int val)
2803 CPUState *env = mon_get_cpu();
2804 unsigned int u;
2805 int i;
2807 u = 0;
2808 for (i = 0; i < 8; i++)
2809 u |= env->crf[i] << (32 - (4 * i));
2811 return u;
2814 static target_long monitor_get_msr (const struct MonitorDef *md, int val)
2816 CPUState *env = mon_get_cpu();
2817 return env->msr;
2820 static target_long monitor_get_xer (const struct MonitorDef *md, int val)
2822 CPUState *env = mon_get_cpu();
2823 return env->xer;
2826 static target_long monitor_get_decr (const struct MonitorDef *md, int val)
2828 CPUState *env = mon_get_cpu();
2829 return cpu_ppc_load_decr(env);
2832 static target_long monitor_get_tbu (const struct MonitorDef *md, int val)
2834 CPUState *env = mon_get_cpu();
2835 return cpu_ppc_load_tbu(env);
2838 static target_long monitor_get_tbl (const struct MonitorDef *md, int val)
2840 CPUState *env = mon_get_cpu();
2841 return cpu_ppc_load_tbl(env);
2843 #endif
2845 #if defined(TARGET_SPARC)
2846 #ifndef TARGET_SPARC64
2847 static target_long monitor_get_psr (const struct MonitorDef *md, int val)
2849 CPUState *env = mon_get_cpu();
2850 return GET_PSR(env);
2852 #endif
2854 static target_long monitor_get_reg(const struct MonitorDef *md, int val)
2856 CPUState *env = mon_get_cpu();
2857 return env->regwptr[val];
2859 #endif
2861 static const MonitorDef monitor_defs[] = {
2862 #ifdef TARGET_I386
2864 #define SEG(name, seg) \
2865 { name, offsetof(CPUState, segs[seg].selector), NULL, MD_I32 },\
2866 { name ".base", offsetof(CPUState, segs[seg].base) },\
2867 { name ".limit", offsetof(CPUState, segs[seg].limit), NULL, MD_I32 },
2869 { "eax", offsetof(CPUState, regs[0]) },
2870 { "ecx", offsetof(CPUState, regs[1]) },
2871 { "edx", offsetof(CPUState, regs[2]) },
2872 { "ebx", offsetof(CPUState, regs[3]) },
2873 { "esp|sp", offsetof(CPUState, regs[4]) },
2874 { "ebp|fp", offsetof(CPUState, regs[5]) },
2875 { "esi", offsetof(CPUState, regs[6]) },
2876 { "edi", offsetof(CPUState, regs[7]) },
2877 #ifdef TARGET_X86_64
2878 { "r8", offsetof(CPUState, regs[8]) },
2879 { "r9", offsetof(CPUState, regs[9]) },
2880 { "r10", offsetof(CPUState, regs[10]) },
2881 { "r11", offsetof(CPUState, regs[11]) },
2882 { "r12", offsetof(CPUState, regs[12]) },
2883 { "r13", offsetof(CPUState, regs[13]) },
2884 { "r14", offsetof(CPUState, regs[14]) },
2885 { "r15", offsetof(CPUState, regs[15]) },
2886 #endif
2887 { "eflags", offsetof(CPUState, eflags) },
2888 { "eip", offsetof(CPUState, eip) },
2889 SEG("cs", R_CS)
2890 SEG("ds", R_DS)
2891 SEG("es", R_ES)
2892 SEG("ss", R_SS)
2893 SEG("fs", R_FS)
2894 SEG("gs", R_GS)
2895 { "pc", 0, monitor_get_pc, },
2896 #elif defined(TARGET_PPC)
2897 /* General purpose registers */
2898 { "r0", offsetof(CPUState, gpr[0]) },
2899 { "r1", offsetof(CPUState, gpr[1]) },
2900 { "r2", offsetof(CPUState, gpr[2]) },
2901 { "r3", offsetof(CPUState, gpr[3]) },
2902 { "r4", offsetof(CPUState, gpr[4]) },
2903 { "r5", offsetof(CPUState, gpr[5]) },
2904 { "r6", offsetof(CPUState, gpr[6]) },
2905 { "r7", offsetof(CPUState, gpr[7]) },
2906 { "r8", offsetof(CPUState, gpr[8]) },
2907 { "r9", offsetof(CPUState, gpr[9]) },
2908 { "r10", offsetof(CPUState, gpr[10]) },
2909 { "r11", offsetof(CPUState, gpr[11]) },
2910 { "r12", offsetof(CPUState, gpr[12]) },
2911 { "r13", offsetof(CPUState, gpr[13]) },
2912 { "r14", offsetof(CPUState, gpr[14]) },
2913 { "r15", offsetof(CPUState, gpr[15]) },
2914 { "r16", offsetof(CPUState, gpr[16]) },
2915 { "r17", offsetof(CPUState, gpr[17]) },
2916 { "r18", offsetof(CPUState, gpr[18]) },
2917 { "r19", offsetof(CPUState, gpr[19]) },
2918 { "r20", offsetof(CPUState, gpr[20]) },
2919 { "r21", offsetof(CPUState, gpr[21]) },
2920 { "r22", offsetof(CPUState, gpr[22]) },
2921 { "r23", offsetof(CPUState, gpr[23]) },
2922 { "r24", offsetof(CPUState, gpr[24]) },
2923 { "r25", offsetof(CPUState, gpr[25]) },
2924 { "r26", offsetof(CPUState, gpr[26]) },
2925 { "r27", offsetof(CPUState, gpr[27]) },
2926 { "r28", offsetof(CPUState, gpr[28]) },
2927 { "r29", offsetof(CPUState, gpr[29]) },
2928 { "r30", offsetof(CPUState, gpr[30]) },
2929 { "r31", offsetof(CPUState, gpr[31]) },
2930 /* Floating point registers */
2931 { "f0", offsetof(CPUState, fpr[0]) },
2932 { "f1", offsetof(CPUState, fpr[1]) },
2933 { "f2", offsetof(CPUState, fpr[2]) },
2934 { "f3", offsetof(CPUState, fpr[3]) },
2935 { "f4", offsetof(CPUState, fpr[4]) },
2936 { "f5", offsetof(CPUState, fpr[5]) },
2937 { "f6", offsetof(CPUState, fpr[6]) },
2938 { "f7", offsetof(CPUState, fpr[7]) },
2939 { "f8", offsetof(CPUState, fpr[8]) },
2940 { "f9", offsetof(CPUState, fpr[9]) },
2941 { "f10", offsetof(CPUState, fpr[10]) },
2942 { "f11", offsetof(CPUState, fpr[11]) },
2943 { "f12", offsetof(CPUState, fpr[12]) },
2944 { "f13", offsetof(CPUState, fpr[13]) },
2945 { "f14", offsetof(CPUState, fpr[14]) },
2946 { "f15", offsetof(CPUState, fpr[15]) },
2947 { "f16", offsetof(CPUState, fpr[16]) },
2948 { "f17", offsetof(CPUState, fpr[17]) },
2949 { "f18", offsetof(CPUState, fpr[18]) },
2950 { "f19", offsetof(CPUState, fpr[19]) },
2951 { "f20", offsetof(CPUState, fpr[20]) },
2952 { "f21", offsetof(CPUState, fpr[21]) },
2953 { "f22", offsetof(CPUState, fpr[22]) },
2954 { "f23", offsetof(CPUState, fpr[23]) },
2955 { "f24", offsetof(CPUState, fpr[24]) },
2956 { "f25", offsetof(CPUState, fpr[25]) },
2957 { "f26", offsetof(CPUState, fpr[26]) },
2958 { "f27", offsetof(CPUState, fpr[27]) },
2959 { "f28", offsetof(CPUState, fpr[28]) },
2960 { "f29", offsetof(CPUState, fpr[29]) },
2961 { "f30", offsetof(CPUState, fpr[30]) },
2962 { "f31", offsetof(CPUState, fpr[31]) },
2963 { "fpscr", offsetof(CPUState, fpscr) },
2964 /* Next instruction pointer */
2965 { "nip|pc", offsetof(CPUState, nip) },
2966 { "lr", offsetof(CPUState, lr) },
2967 { "ctr", offsetof(CPUState, ctr) },
2968 { "decr", 0, &monitor_get_decr, },
2969 { "ccr", 0, &monitor_get_ccr, },
2970 /* Machine state register */
2971 { "msr", 0, &monitor_get_msr, },
2972 { "xer", 0, &monitor_get_xer, },
2973 { "tbu", 0, &monitor_get_tbu, },
2974 { "tbl", 0, &monitor_get_tbl, },
2975 #if defined(TARGET_PPC64)
2976 /* Address space register */
2977 { "asr", offsetof(CPUState, asr) },
2978 #endif
2979 /* Segment registers */
2980 { "sdr1", offsetof(CPUState, sdr1) },
2981 { "sr0", offsetof(CPUState, sr[0]) },
2982 { "sr1", offsetof(CPUState, sr[1]) },
2983 { "sr2", offsetof(CPUState, sr[2]) },
2984 { "sr3", offsetof(CPUState, sr[3]) },
2985 { "sr4", offsetof(CPUState, sr[4]) },
2986 { "sr5", offsetof(CPUState, sr[5]) },
2987 { "sr6", offsetof(CPUState, sr[6]) },
2988 { "sr7", offsetof(CPUState, sr[7]) },
2989 { "sr8", offsetof(CPUState, sr[8]) },
2990 { "sr9", offsetof(CPUState, sr[9]) },
2991 { "sr10", offsetof(CPUState, sr[10]) },
2992 { "sr11", offsetof(CPUState, sr[11]) },
2993 { "sr12", offsetof(CPUState, sr[12]) },
2994 { "sr13", offsetof(CPUState, sr[13]) },
2995 { "sr14", offsetof(CPUState, sr[14]) },
2996 { "sr15", offsetof(CPUState, sr[15]) },
2997 /* Too lazy to put BATs and SPRs ... */
2998 #elif defined(TARGET_SPARC)
2999 { "g0", offsetof(CPUState, gregs[0]) },
3000 { "g1", offsetof(CPUState, gregs[1]) },
3001 { "g2", offsetof(CPUState, gregs[2]) },
3002 { "g3", offsetof(CPUState, gregs[3]) },
3003 { "g4", offsetof(CPUState, gregs[4]) },
3004 { "g5", offsetof(CPUState, gregs[5]) },
3005 { "g6", offsetof(CPUState, gregs[6]) },
3006 { "g7", offsetof(CPUState, gregs[7]) },
3007 { "o0", 0, monitor_get_reg },
3008 { "o1", 1, monitor_get_reg },
3009 { "o2", 2, monitor_get_reg },
3010 { "o3", 3, monitor_get_reg },
3011 { "o4", 4, monitor_get_reg },
3012 { "o5", 5, monitor_get_reg },
3013 { "o6", 6, monitor_get_reg },
3014 { "o7", 7, monitor_get_reg },
3015 { "l0", 8, monitor_get_reg },
3016 { "l1", 9, monitor_get_reg },
3017 { "l2", 10, monitor_get_reg },
3018 { "l3", 11, monitor_get_reg },
3019 { "l4", 12, monitor_get_reg },
3020 { "l5", 13, monitor_get_reg },
3021 { "l6", 14, monitor_get_reg },
3022 { "l7", 15, monitor_get_reg },
3023 { "i0", 16, monitor_get_reg },
3024 { "i1", 17, monitor_get_reg },
3025 { "i2", 18, monitor_get_reg },
3026 { "i3", 19, monitor_get_reg },
3027 { "i4", 20, monitor_get_reg },
3028 { "i5", 21, monitor_get_reg },
3029 { "i6", 22, monitor_get_reg },
3030 { "i7", 23, monitor_get_reg },
3031 { "pc", offsetof(CPUState, pc) },
3032 { "npc", offsetof(CPUState, npc) },
3033 { "y", offsetof(CPUState, y) },
3034 #ifndef TARGET_SPARC64
3035 { "psr", 0, &monitor_get_psr, },
3036 { "wim", offsetof(CPUState, wim) },
3037 #endif
3038 { "tbr", offsetof(CPUState, tbr) },
3039 { "fsr", offsetof(CPUState, fsr) },
3040 { "f0", offsetof(CPUState, fpr[0]) },
3041 { "f1", offsetof(CPUState, fpr[1]) },
3042 { "f2", offsetof(CPUState, fpr[2]) },
3043 { "f3", offsetof(CPUState, fpr[3]) },
3044 { "f4", offsetof(CPUState, fpr[4]) },
3045 { "f5", offsetof(CPUState, fpr[5]) },
3046 { "f6", offsetof(CPUState, fpr[6]) },
3047 { "f7", offsetof(CPUState, fpr[7]) },
3048 { "f8", offsetof(CPUState, fpr[8]) },
3049 { "f9", offsetof(CPUState, fpr[9]) },
3050 { "f10", offsetof(CPUState, fpr[10]) },
3051 { "f11", offsetof(CPUState, fpr[11]) },
3052 { "f12", offsetof(CPUState, fpr[12]) },
3053 { "f13", offsetof(CPUState, fpr[13]) },
3054 { "f14", offsetof(CPUState, fpr[14]) },
3055 { "f15", offsetof(CPUState, fpr[15]) },
3056 { "f16", offsetof(CPUState, fpr[16]) },
3057 { "f17", offsetof(CPUState, fpr[17]) },
3058 { "f18", offsetof(CPUState, fpr[18]) },
3059 { "f19", offsetof(CPUState, fpr[19]) },
3060 { "f20", offsetof(CPUState, fpr[20]) },
3061 { "f21", offsetof(CPUState, fpr[21]) },
3062 { "f22", offsetof(CPUState, fpr[22]) },
3063 { "f23", offsetof(CPUState, fpr[23]) },
3064 { "f24", offsetof(CPUState, fpr[24]) },
3065 { "f25", offsetof(CPUState, fpr[25]) },
3066 { "f26", offsetof(CPUState, fpr[26]) },
3067 { "f27", offsetof(CPUState, fpr[27]) },
3068 { "f28", offsetof(CPUState, fpr[28]) },
3069 { "f29", offsetof(CPUState, fpr[29]) },
3070 { "f30", offsetof(CPUState, fpr[30]) },
3071 { "f31", offsetof(CPUState, fpr[31]) },
3072 #ifdef TARGET_SPARC64
3073 { "f32", offsetof(CPUState, fpr[32]) },
3074 { "f34", offsetof(CPUState, fpr[34]) },
3075 { "f36", offsetof(CPUState, fpr[36]) },
3076 { "f38", offsetof(CPUState, fpr[38]) },
3077 { "f40", offsetof(CPUState, fpr[40]) },
3078 { "f42", offsetof(CPUState, fpr[42]) },
3079 { "f44", offsetof(CPUState, fpr[44]) },
3080 { "f46", offsetof(CPUState, fpr[46]) },
3081 { "f48", offsetof(CPUState, fpr[48]) },
3082 { "f50", offsetof(CPUState, fpr[50]) },
3083 { "f52", offsetof(CPUState, fpr[52]) },
3084 { "f54", offsetof(CPUState, fpr[54]) },
3085 { "f56", offsetof(CPUState, fpr[56]) },
3086 { "f58", offsetof(CPUState, fpr[58]) },
3087 { "f60", offsetof(CPUState, fpr[60]) },
3088 { "f62", offsetof(CPUState, fpr[62]) },
3089 { "asi", offsetof(CPUState, asi) },
3090 { "pstate", offsetof(CPUState, pstate) },
3091 { "cansave", offsetof(CPUState, cansave) },
3092 { "canrestore", offsetof(CPUState, canrestore) },
3093 { "otherwin", offsetof(CPUState, otherwin) },
3094 { "wstate", offsetof(CPUState, wstate) },
3095 { "cleanwin", offsetof(CPUState, cleanwin) },
3096 { "fprs", offsetof(CPUState, fprs) },
3097 #endif
3098 #endif
3099 { NULL },
3102 static void expr_error(Monitor *mon, const char *msg)
3104 monitor_printf(mon, "%s\n", msg);
3105 longjmp(expr_env, 1);
3108 /* return 0 if OK, -1 if not found */
3109 static int get_monitor_def(target_long *pval, const char *name)
3111 const MonitorDef *md;
3112 void *ptr;
3114 for(md = monitor_defs; md->name != NULL; md++) {
3115 if (compare_cmd(name, md->name)) {
3116 if (md->get_value) {
3117 *pval = md->get_value(md, md->offset);
3118 } else {
3119 CPUState *env = mon_get_cpu();
3120 ptr = (uint8_t *)env + md->offset;
3121 switch(md->type) {
3122 case MD_I32:
3123 *pval = *(int32_t *)ptr;
3124 break;
3125 case MD_TLONG:
3126 *pval = *(target_long *)ptr;
3127 break;
3128 default:
3129 *pval = 0;
3130 break;
3133 return 0;
3136 return -1;
3139 static void next(void)
3141 if (*pch != '\0') {
3142 pch++;
3143 while (qemu_isspace(*pch))
3144 pch++;
3148 static int64_t expr_sum(Monitor *mon);
3150 static int64_t expr_unary(Monitor *mon)
3152 int64_t n;
3153 char *p;
3154 int ret;
3156 switch(*pch) {
3157 case '+':
3158 next();
3159 n = expr_unary(mon);
3160 break;
3161 case '-':
3162 next();
3163 n = -expr_unary(mon);
3164 break;
3165 case '~':
3166 next();
3167 n = ~expr_unary(mon);
3168 break;
3169 case '(':
3170 next();
3171 n = expr_sum(mon);
3172 if (*pch != ')') {
3173 expr_error(mon, "')' expected");
3175 next();
3176 break;
3177 case '\'':
3178 pch++;
3179 if (*pch == '\0')
3180 expr_error(mon, "character constant expected");
3181 n = *pch;
3182 pch++;
3183 if (*pch != '\'')
3184 expr_error(mon, "missing terminating \' character");
3185 next();
3186 break;
3187 case '$':
3189 char buf[128], *q;
3190 target_long reg=0;
3192 pch++;
3193 q = buf;
3194 while ((*pch >= 'a' && *pch <= 'z') ||
3195 (*pch >= 'A' && *pch <= 'Z') ||
3196 (*pch >= '0' && *pch <= '9') ||
3197 *pch == '_' || *pch == '.') {
3198 if ((q - buf) < sizeof(buf) - 1)
3199 *q++ = *pch;
3200 pch++;
3202 while (qemu_isspace(*pch))
3203 pch++;
3204 *q = 0;
3205 ret = get_monitor_def(&reg, buf);
3206 if (ret < 0)
3207 expr_error(mon, "unknown register");
3208 n = reg;
3210 break;
3211 case '\0':
3212 expr_error(mon, "unexpected end of expression");
3213 n = 0;
3214 break;
3215 default:
3216 #if TARGET_PHYS_ADDR_BITS > 32
3217 n = strtoull(pch, &p, 0);
3218 #else
3219 n = strtoul(pch, &p, 0);
3220 #endif
3221 if (pch == p) {
3222 expr_error(mon, "invalid char in expression");
3224 pch = p;
3225 while (qemu_isspace(*pch))
3226 pch++;
3227 break;
3229 return n;
3233 static int64_t expr_prod(Monitor *mon)
3235 int64_t val, val2;
3236 int op;
3238 val = expr_unary(mon);
3239 for(;;) {
3240 op = *pch;
3241 if (op != '*' && op != '/' && op != '%')
3242 break;
3243 next();
3244 val2 = expr_unary(mon);
3245 switch(op) {
3246 default:
3247 case '*':
3248 val *= val2;
3249 break;
3250 case '/':
3251 case '%':
3252 if (val2 == 0)
3253 expr_error(mon, "division by zero");
3254 if (op == '/')
3255 val /= val2;
3256 else
3257 val %= val2;
3258 break;
3261 return val;
3264 static int64_t expr_logic(Monitor *mon)
3266 int64_t val, val2;
3267 int op;
3269 val = expr_prod(mon);
3270 for(;;) {
3271 op = *pch;
3272 if (op != '&' && op != '|' && op != '^')
3273 break;
3274 next();
3275 val2 = expr_prod(mon);
3276 switch(op) {
3277 default:
3278 case '&':
3279 val &= val2;
3280 break;
3281 case '|':
3282 val |= val2;
3283 break;
3284 case '^':
3285 val ^= val2;
3286 break;
3289 return val;
3292 static int64_t expr_sum(Monitor *mon)
3294 int64_t val, val2;
3295 int op;
3297 val = expr_logic(mon);
3298 for(;;) {
3299 op = *pch;
3300 if (op != '+' && op != '-')
3301 break;
3302 next();
3303 val2 = expr_logic(mon);
3304 if (op == '+')
3305 val += val2;
3306 else
3307 val -= val2;
3309 return val;
3312 static int get_expr(Monitor *mon, int64_t *pval, const char **pp)
3314 pch = *pp;
3315 if (setjmp(expr_env)) {
3316 *pp = pch;
3317 return -1;
3319 while (qemu_isspace(*pch))
3320 pch++;
3321 *pval = expr_sum(mon);
3322 *pp = pch;
3323 return 0;
3326 static int get_double(Monitor *mon, double *pval, const char **pp)
3328 const char *p = *pp;
3329 char *tailp;
3330 double d;
3332 d = strtod(p, &tailp);
3333 if (tailp == p) {
3334 monitor_printf(mon, "Number expected\n");
3335 return -1;
3337 if (d != d || d - d != 0) {
3338 /* NaN or infinity */
3339 monitor_printf(mon, "Bad number\n");
3340 return -1;
3342 *pval = d;
3343 *pp = tailp;
3344 return 0;
3347 static int get_str(char *buf, int buf_size, const char **pp)
3349 const char *p;
3350 char *q;
3351 int c;
3353 q = buf;
3354 p = *pp;
3355 while (qemu_isspace(*p))
3356 p++;
3357 if (*p == '\0') {
3358 fail:
3359 *q = '\0';
3360 *pp = p;
3361 return -1;
3363 if (*p == '\"') {
3364 p++;
3365 while (*p != '\0' && *p != '\"') {
3366 if (*p == '\\') {
3367 p++;
3368 c = *p++;
3369 switch(c) {
3370 case 'n':
3371 c = '\n';
3372 break;
3373 case 'r':
3374 c = '\r';
3375 break;
3376 case '\\':
3377 case '\'':
3378 case '\"':
3379 break;
3380 default:
3381 qemu_printf("unsupported escape code: '\\%c'\n", c);
3382 goto fail;
3384 if ((q - buf) < buf_size - 1) {
3385 *q++ = c;
3387 } else {
3388 if ((q - buf) < buf_size - 1) {
3389 *q++ = *p;
3391 p++;
3394 if (*p != '\"') {
3395 qemu_printf("unterminated string\n");
3396 goto fail;
3398 p++;
3399 } else {
3400 while (*p != '\0' && !qemu_isspace(*p)) {
3401 if ((q - buf) < buf_size - 1) {
3402 *q++ = *p;
3404 p++;
3407 *q = '\0';
3408 *pp = p;
3409 return 0;
3413 * Store the command-name in cmdname, and return a pointer to
3414 * the remaining of the command string.
3416 static const char *get_command_name(const char *cmdline,
3417 char *cmdname, size_t nlen)
3419 size_t len;
3420 const char *p, *pstart;
3422 p = cmdline;
3423 while (qemu_isspace(*p))
3424 p++;
3425 if (*p == '\0')
3426 return NULL;
3427 pstart = p;
3428 while (*p != '\0' && *p != '/' && !qemu_isspace(*p))
3429 p++;
3430 len = p - pstart;
3431 if (len > nlen - 1)
3432 len = nlen - 1;
3433 memcpy(cmdname, pstart, len);
3434 cmdname[len] = '\0';
3435 return p;
3439 * Read key of 'type' into 'key' and return the current
3440 * 'type' pointer.
3442 static char *key_get_info(const char *type, char **key)
3444 size_t len;
3445 char *p, *str;
3447 if (*type == ',')
3448 type++;
3450 p = strchr(type, ':');
3451 if (!p) {
3452 *key = NULL;
3453 return NULL;
3455 len = p - type;
3457 str = qemu_malloc(len + 1);
3458 memcpy(str, type, len);
3459 str[len] = '\0';
3461 *key = str;
3462 return ++p;
3465 static int default_fmt_format = 'x';
3466 static int default_fmt_size = 4;
3468 #define MAX_ARGS 16
3470 static int is_valid_option(const char *c, const char *typestr)
3472 char option[3];
3474 option[0] = '-';
3475 option[1] = *c;
3476 option[2] = '\0';
3478 typestr = strstr(typestr, option);
3479 return (typestr != NULL);
3482 static const mon_cmd_t *monitor_find_command(const char *cmdname)
3484 const mon_cmd_t *cmd;
3486 for (cmd = mon_cmds; cmd->name != NULL; cmd++) {
3487 if (compare_cmd(cmdname, cmd->name)) {
3488 return cmd;
3492 return NULL;
3495 static const mon_cmd_t *monitor_parse_command(Monitor *mon,
3496 const char *cmdline,
3497 QDict *qdict)
3499 const char *p, *typestr;
3500 int c;
3501 const mon_cmd_t *cmd;
3502 char cmdname[256];
3503 char buf[1024];
3504 char *key;
3506 #ifdef DEBUG
3507 monitor_printf(mon, "command='%s'\n", cmdline);
3508 #endif
3510 /* extract the command name */
3511 p = get_command_name(cmdline, cmdname, sizeof(cmdname));
3512 if (!p)
3513 return NULL;
3515 cmd = monitor_find_command(cmdname);
3516 if (!cmd) {
3517 monitor_printf(mon, "unknown command: '%s'\n", cmdname);
3518 return NULL;
3521 /* parse the parameters */
3522 typestr = cmd->args_type;
3523 for(;;) {
3524 typestr = key_get_info(typestr, &key);
3525 if (!typestr)
3526 break;
3527 c = *typestr;
3528 typestr++;
3529 switch(c) {
3530 case 'F':
3531 case 'B':
3532 case 's':
3534 int ret;
3536 while (qemu_isspace(*p))
3537 p++;
3538 if (*typestr == '?') {
3539 typestr++;
3540 if (*p == '\0') {
3541 /* no optional string: NULL argument */
3542 break;
3545 ret = get_str(buf, sizeof(buf), &p);
3546 if (ret < 0) {
3547 switch(c) {
3548 case 'F':
3549 monitor_printf(mon, "%s: filename expected\n",
3550 cmdname);
3551 break;
3552 case 'B':
3553 monitor_printf(mon, "%s: block device name expected\n",
3554 cmdname);
3555 break;
3556 default:
3557 monitor_printf(mon, "%s: string expected\n", cmdname);
3558 break;
3560 goto fail;
3562 qdict_put(qdict, key, qstring_from_str(buf));
3564 break;
3565 case '/':
3567 int count, format, size;
3569 while (qemu_isspace(*p))
3570 p++;
3571 if (*p == '/') {
3572 /* format found */
3573 p++;
3574 count = 1;
3575 if (qemu_isdigit(*p)) {
3576 count = 0;
3577 while (qemu_isdigit(*p)) {
3578 count = count * 10 + (*p - '0');
3579 p++;
3582 size = -1;
3583 format = -1;
3584 for(;;) {
3585 switch(*p) {
3586 case 'o':
3587 case 'd':
3588 case 'u':
3589 case 'x':
3590 case 'i':
3591 case 'c':
3592 format = *p++;
3593 break;
3594 case 'b':
3595 size = 1;
3596 p++;
3597 break;
3598 case 'h':
3599 size = 2;
3600 p++;
3601 break;
3602 case 'w':
3603 size = 4;
3604 p++;
3605 break;
3606 case 'g':
3607 case 'L':
3608 size = 8;
3609 p++;
3610 break;
3611 default:
3612 goto next;
3615 next:
3616 if (*p != '\0' && !qemu_isspace(*p)) {
3617 monitor_printf(mon, "invalid char in format: '%c'\n",
3618 *p);
3619 goto fail;
3621 if (format < 0)
3622 format = default_fmt_format;
3623 if (format != 'i') {
3624 /* for 'i', not specifying a size gives -1 as size */
3625 if (size < 0)
3626 size = default_fmt_size;
3627 default_fmt_size = size;
3629 default_fmt_format = format;
3630 } else {
3631 count = 1;
3632 format = default_fmt_format;
3633 if (format != 'i') {
3634 size = default_fmt_size;
3635 } else {
3636 size = -1;
3639 qdict_put(qdict, "count", qint_from_int(count));
3640 qdict_put(qdict, "format", qint_from_int(format));
3641 qdict_put(qdict, "size", qint_from_int(size));
3643 break;
3644 case 'i':
3645 case 'l':
3646 case 'M':
3648 int64_t val;
3650 while (qemu_isspace(*p))
3651 p++;
3652 if (*typestr == '?' || *typestr == '.') {
3653 if (*typestr == '?') {
3654 if (*p == '\0') {
3655 typestr++;
3656 break;
3658 } else {
3659 if (*p == '.') {
3660 p++;
3661 while (qemu_isspace(*p))
3662 p++;
3663 } else {
3664 typestr++;
3665 break;
3668 typestr++;
3670 if (get_expr(mon, &val, &p))
3671 goto fail;
3672 /* Check if 'i' is greater than 32-bit */
3673 if ((c == 'i') && ((val >> 32) & 0xffffffff)) {
3674 monitor_printf(mon, "\'%s\' has failed: ", cmdname);
3675 monitor_printf(mon, "integer is for 32-bit values\n");
3676 goto fail;
3677 } else if (c == 'M') {
3678 val <<= 20;
3680 qdict_put(qdict, key, qint_from_int(val));
3682 break;
3683 case 'b':
3684 case 'T':
3686 double val;
3688 while (qemu_isspace(*p))
3689 p++;
3690 if (*typestr == '?') {
3691 typestr++;
3692 if (*p == '\0') {
3693 break;
3696 if (get_double(mon, &val, &p) < 0) {
3697 goto fail;
3699 if (c == 'b' && *p) {
3700 switch (*p) {
3701 case 'K': case 'k':
3702 val *= 1 << 10; p++; break;
3703 case 'M': case 'm':
3704 val *= 1 << 20; p++; break;
3705 case 'G': case 'g':
3706 val *= 1 << 30; p++; break;
3709 if (c == 'T' && p[0] && p[1] == 's') {
3710 switch (*p) {
3711 case 'm':
3712 val /= 1e3; p += 2; break;
3713 case 'u':
3714 val /= 1e6; p += 2; break;
3715 case 'n':
3716 val /= 1e9; p += 2; break;
3719 if (*p && !qemu_isspace(*p)) {
3720 monitor_printf(mon, "Unknown unit suffix\n");
3721 goto fail;
3723 qdict_put(qdict, key, qfloat_from_double(val));
3725 break;
3726 case '-':
3728 const char *tmp = p;
3729 int has_option, skip_key = 0;
3730 /* option */
3732 c = *typestr++;
3733 if (c == '\0')
3734 goto bad_type;
3735 while (qemu_isspace(*p))
3736 p++;
3737 has_option = 0;
3738 if (*p == '-') {
3739 p++;
3740 if(c != *p) {
3741 if(!is_valid_option(p, typestr)) {
3743 monitor_printf(mon, "%s: unsupported option -%c\n",
3744 cmdname, *p);
3745 goto fail;
3746 } else {
3747 skip_key = 1;
3750 if(skip_key) {
3751 p = tmp;
3752 } else {
3753 p++;
3754 has_option = 1;
3757 qdict_put(qdict, key, qint_from_int(has_option));
3759 break;
3760 default:
3761 bad_type:
3762 monitor_printf(mon, "%s: unknown type '%c'\n", cmdname, c);
3763 goto fail;
3765 qemu_free(key);
3766 key = NULL;
3768 /* check that all arguments were parsed */
3769 while (qemu_isspace(*p))
3770 p++;
3771 if (*p != '\0') {
3772 monitor_printf(mon, "%s: extraneous characters at the end of line\n",
3773 cmdname);
3774 goto fail;
3777 return cmd;
3779 fail:
3780 qemu_free(key);
3781 return NULL;
3784 static void monitor_print_error(Monitor *mon)
3786 qerror_print(mon->error);
3787 QDECREF(mon->error);
3788 mon->error = NULL;
3791 static int is_async_return(const QObject *data)
3793 if (data && qobject_type(data) == QTYPE_QDICT) {
3794 return qdict_haskey(qobject_to_qdict(data), "__mon_async");
3797 return 0;
3800 static void monitor_call_handler(Monitor *mon, const mon_cmd_t *cmd,
3801 const QDict *params)
3803 QObject *data = NULL;
3805 if (cmd->cmd_new_ret) {
3806 cmd->cmd_new_ret(mon, params, &data);
3807 } else {
3808 cmd->mhandler.cmd_new(mon, params, &data);
3811 if (is_async_return(data)) {
3813 * Asynchronous commands have no initial return data but they can
3814 * generate errors. Data is returned via the async completion handler.
3816 if (monitor_ctrl_mode(mon) && monitor_has_error(mon)) {
3817 monitor_protocol_emitter(mon, NULL);
3819 } else if (monitor_ctrl_mode(mon)) {
3820 /* Monitor Protocol */
3821 monitor_protocol_emitter(mon, data);
3822 } else {
3823 /* User Protocol */
3824 if (data)
3825 cmd->user_print(mon, data);
3828 qobject_decref(data);
3831 static void handle_user_command(Monitor *mon, const char *cmdline)
3833 QDict *qdict;
3834 const mon_cmd_t *cmd;
3836 qdict = qdict_new();
3838 cmd = monitor_parse_command(mon, cmdline, qdict);
3839 if (!cmd)
3840 goto out;
3842 qemu_errors_to_mon(mon);
3844 if (monitor_handler_is_async(cmd)) {
3845 user_async_cmd_handler(mon, cmd, qdict);
3846 } else if (monitor_handler_ported(cmd)) {
3847 monitor_call_handler(mon, cmd, qdict);
3848 } else {
3849 cmd->mhandler.cmd(mon, qdict);
3852 if (monitor_has_error(mon))
3853 monitor_print_error(mon);
3855 qemu_errors_to_previous();
3857 out:
3858 QDECREF(qdict);
3861 static void cmd_completion(const char *name, const char *list)
3863 const char *p, *pstart;
3864 char cmd[128];
3865 int len;
3867 p = list;
3868 for(;;) {
3869 pstart = p;
3870 p = strchr(p, '|');
3871 if (!p)
3872 p = pstart + strlen(pstart);
3873 len = p - pstart;
3874 if (len > sizeof(cmd) - 2)
3875 len = sizeof(cmd) - 2;
3876 memcpy(cmd, pstart, len);
3877 cmd[len] = '\0';
3878 if (name[0] == '\0' || !strncmp(name, cmd, strlen(name))) {
3879 readline_add_completion(cur_mon->rs, cmd);
3881 if (*p == '\0')
3882 break;
3883 p++;
3887 static void file_completion(const char *input)
3889 DIR *ffs;
3890 struct dirent *d;
3891 char path[1024];
3892 char file[1024], file_prefix[1024];
3893 int input_path_len;
3894 const char *p;
3896 p = strrchr(input, '/');
3897 if (!p) {
3898 input_path_len = 0;
3899 pstrcpy(file_prefix, sizeof(file_prefix), input);
3900 pstrcpy(path, sizeof(path), ".");
3901 } else {
3902 input_path_len = p - input + 1;
3903 memcpy(path, input, input_path_len);
3904 if (input_path_len > sizeof(path) - 1)
3905 input_path_len = sizeof(path) - 1;
3906 path[input_path_len] = '\0';
3907 pstrcpy(file_prefix, sizeof(file_prefix), p + 1);
3909 #ifdef DEBUG_COMPLETION
3910 monitor_printf(cur_mon, "input='%s' path='%s' prefix='%s'\n",
3911 input, path, file_prefix);
3912 #endif
3913 ffs = opendir(path);
3914 if (!ffs)
3915 return;
3916 for(;;) {
3917 struct stat sb;
3918 d = readdir(ffs);
3919 if (!d)
3920 break;
3921 if (strstart(d->d_name, file_prefix, NULL)) {
3922 memcpy(file, input, input_path_len);
3923 if (input_path_len < sizeof(file))
3924 pstrcpy(file + input_path_len, sizeof(file) - input_path_len,
3925 d->d_name);
3926 /* stat the file to find out if it's a directory.
3927 * In that case add a slash to speed up typing long paths
3929 stat(file, &sb);
3930 if(S_ISDIR(sb.st_mode))
3931 pstrcat(file, sizeof(file), "/");
3932 readline_add_completion(cur_mon->rs, file);
3935 closedir(ffs);
3938 static void block_completion_it(void *opaque, BlockDriverState *bs)
3940 const char *name = bdrv_get_device_name(bs);
3941 const char *input = opaque;
3943 if (input[0] == '\0' ||
3944 !strncmp(name, (char *)input, strlen(input))) {
3945 readline_add_completion(cur_mon->rs, name);
3949 /* NOTE: this parser is an approximate form of the real command parser */
3950 static void parse_cmdline(const char *cmdline,
3951 int *pnb_args, char **args)
3953 const char *p;
3954 int nb_args, ret;
3955 char buf[1024];
3957 p = cmdline;
3958 nb_args = 0;
3959 for(;;) {
3960 while (qemu_isspace(*p))
3961 p++;
3962 if (*p == '\0')
3963 break;
3964 if (nb_args >= MAX_ARGS)
3965 break;
3966 ret = get_str(buf, sizeof(buf), &p);
3967 args[nb_args] = qemu_strdup(buf);
3968 nb_args++;
3969 if (ret < 0)
3970 break;
3972 *pnb_args = nb_args;
3975 static const char *next_arg_type(const char *typestr)
3977 const char *p = strchr(typestr, ':');
3978 return (p != NULL ? ++p : typestr);
3981 static void monitor_find_completion(const char *cmdline)
3983 const char *cmdname;
3984 char *args[MAX_ARGS];
3985 int nb_args, i, len;
3986 const char *ptype, *str;
3987 const mon_cmd_t *cmd;
3988 const KeyDef *key;
3990 parse_cmdline(cmdline, &nb_args, args);
3991 #ifdef DEBUG_COMPLETION
3992 for(i = 0; i < nb_args; i++) {
3993 monitor_printf(cur_mon, "arg%d = '%s'\n", i, (char *)args[i]);
3995 #endif
3997 /* if the line ends with a space, it means we want to complete the
3998 next arg */
3999 len = strlen(cmdline);
4000 if (len > 0 && qemu_isspace(cmdline[len - 1])) {
4001 if (nb_args >= MAX_ARGS)
4002 return;
4003 args[nb_args++] = qemu_strdup("");
4005 if (nb_args <= 1) {
4006 /* command completion */
4007 if (nb_args == 0)
4008 cmdname = "";
4009 else
4010 cmdname = args[0];
4011 readline_set_completion_index(cur_mon->rs, strlen(cmdname));
4012 for(cmd = mon_cmds; cmd->name != NULL; cmd++) {
4013 cmd_completion(cmdname, cmd->name);
4015 } else {
4016 /* find the command */
4017 for(cmd = mon_cmds; cmd->name != NULL; cmd++) {
4018 if (compare_cmd(args[0], cmd->name))
4019 goto found;
4021 return;
4022 found:
4023 ptype = next_arg_type(cmd->args_type);
4024 for(i = 0; i < nb_args - 2; i++) {
4025 if (*ptype != '\0') {
4026 ptype = next_arg_type(ptype);
4027 while (*ptype == '?')
4028 ptype = next_arg_type(ptype);
4031 str = args[nb_args - 1];
4032 if (*ptype == '-' && ptype[1] != '\0') {
4033 ptype += 2;
4035 switch(*ptype) {
4036 case 'F':
4037 /* file completion */
4038 readline_set_completion_index(cur_mon->rs, strlen(str));
4039 file_completion(str);
4040 break;
4041 case 'B':
4042 /* block device name completion */
4043 readline_set_completion_index(cur_mon->rs, strlen(str));
4044 bdrv_iterate(block_completion_it, (void *)str);
4045 break;
4046 case 's':
4047 /* XXX: more generic ? */
4048 if (!strcmp(cmd->name, "info")) {
4049 readline_set_completion_index(cur_mon->rs, strlen(str));
4050 for(cmd = info_cmds; cmd->name != NULL; cmd++) {
4051 cmd_completion(str, cmd->name);
4053 } else if (!strcmp(cmd->name, "sendkey")) {
4054 char *sep = strrchr(str, '-');
4055 if (sep)
4056 str = sep + 1;
4057 readline_set_completion_index(cur_mon->rs, strlen(str));
4058 for(key = key_defs; key->name != NULL; key++) {
4059 cmd_completion(str, key->name);
4061 } else if (!strcmp(cmd->name, "help|?")) {
4062 readline_set_completion_index(cur_mon->rs, strlen(str));
4063 for (cmd = mon_cmds; cmd->name != NULL; cmd++) {
4064 cmd_completion(str, cmd->name);
4067 break;
4068 default:
4069 break;
4072 for(i = 0; i < nb_args; i++)
4073 qemu_free(args[i]);
4076 static int monitor_can_read(void *opaque)
4078 Monitor *mon = opaque;
4080 return (mon->suspend_cnt == 0) ? 1 : 0;
4083 typedef struct CmdArgs {
4084 QString *name;
4085 int type;
4086 int flag;
4087 int optional;
4088 } CmdArgs;
4090 static int check_opt(const CmdArgs *cmd_args, const char *name, QDict *args)
4092 if (!cmd_args->optional) {
4093 qemu_error_new(QERR_MISSING_PARAMETER, name);
4094 return -1;
4097 if (cmd_args->type == '-') {
4098 /* handlers expect a value, they need to be changed */
4099 qdict_put(args, name, qint_from_int(0));
4102 return 0;
4105 static int check_arg(const CmdArgs *cmd_args, QDict *args)
4107 QObject *value;
4108 const char *name;
4110 name = qstring_get_str(cmd_args->name);
4112 if (!args) {
4113 return check_opt(cmd_args, name, args);
4116 value = qdict_get(args, name);
4117 if (!value) {
4118 return check_opt(cmd_args, name, args);
4121 switch (cmd_args->type) {
4122 case 'F':
4123 case 'B':
4124 case 's':
4125 if (qobject_type(value) != QTYPE_QSTRING) {
4126 qemu_error_new(QERR_INVALID_PARAMETER_TYPE, name, "string");
4127 return -1;
4129 break;
4130 case '/': {
4131 int i;
4132 const char *keys[] = { "count", "format", "size", NULL };
4134 for (i = 0; keys[i]; i++) {
4135 QObject *obj = qdict_get(args, keys[i]);
4136 if (!obj) {
4137 qemu_error_new(QERR_MISSING_PARAMETER, name);
4138 return -1;
4140 if (qobject_type(obj) != QTYPE_QINT) {
4141 qemu_error_new(QERR_INVALID_PARAMETER_TYPE, name, "int");
4142 return -1;
4145 break;
4147 case 'i':
4148 case 'l':
4149 case 'M':
4150 if (qobject_type(value) != QTYPE_QINT) {
4151 qemu_error_new(QERR_INVALID_PARAMETER_TYPE, name, "int");
4152 return -1;
4154 break;
4155 case 'b':
4156 case 'T':
4157 if (qobject_type(value) != QTYPE_QINT && qobject_type(value) != QTYPE_QFLOAT) {
4158 qemu_error_new(QERR_INVALID_PARAMETER_TYPE, name, "number");
4159 return -1;
4161 break;
4162 case '-':
4163 if (qobject_type(value) != QTYPE_QINT &&
4164 qobject_type(value) != QTYPE_QBOOL) {
4165 qemu_error_new(QERR_INVALID_PARAMETER_TYPE, name, "bool");
4166 return -1;
4168 if (qobject_type(value) == QTYPE_QBOOL) {
4169 /* handlers expect a QInt, they need to be changed */
4170 qdict_put(args, name,
4171 qint_from_int(qbool_get_int(qobject_to_qbool(value))));
4173 break;
4174 default:
4175 /* impossible */
4176 abort();
4179 return 0;
4182 static void cmd_args_init(CmdArgs *cmd_args)
4184 cmd_args->name = qstring_new();
4185 cmd_args->type = cmd_args->flag = cmd_args->optional = 0;
4189 * This is not trivial, we have to parse Monitor command's argument
4190 * type syntax to be able to check the arguments provided by clients.
4192 * In the near future we will be using an array for that and will be
4193 * able to drop all this parsing...
4195 static int monitor_check_qmp_args(const mon_cmd_t *cmd, QDict *args)
4197 int err;
4198 const char *p;
4199 CmdArgs cmd_args;
4201 if (cmd->args_type == NULL) {
4202 return (qdict_size(args) == 0 ? 0 : -1);
4205 err = 0;
4206 cmd_args_init(&cmd_args);
4208 for (p = cmd->args_type;; p++) {
4209 if (*p == ':') {
4210 cmd_args.type = *++p;
4211 p++;
4212 if (cmd_args.type == '-') {
4213 cmd_args.flag = *p++;
4214 cmd_args.optional = 1;
4215 } else if (*p == '?') {
4216 cmd_args.optional = 1;
4217 p++;
4220 assert(*p == ',' || *p == '\0');
4221 err = check_arg(&cmd_args, args);
4223 QDECREF(cmd_args.name);
4224 cmd_args_init(&cmd_args);
4226 if (err < 0) {
4227 break;
4229 } else {
4230 qstring_append_chr(cmd_args.name, *p);
4233 if (*p == '\0') {
4234 break;
4238 QDECREF(cmd_args.name);
4239 return err;
4242 static int invalid_qmp_mode(const Monitor *mon, const char *cmd_name)
4244 int is_cap = compare_cmd(cmd_name, "qmp_capabilities");
4245 return (qmp_cmd_mode(mon) ? is_cap : !is_cap);
4248 static void handle_qmp_command(JSONMessageParser *parser, QList *tokens)
4250 int err;
4251 QObject *obj;
4252 QDict *input, *args;
4253 const mon_cmd_t *cmd;
4254 Monitor *mon = cur_mon;
4255 const char *cmd_name, *info_item;
4257 args = NULL;
4258 qemu_errors_to_mon(mon);
4260 obj = json_parser_parse(tokens, NULL);
4261 if (!obj) {
4262 // FIXME: should be triggered in json_parser_parse()
4263 qemu_error_new(QERR_JSON_PARSING);
4264 goto err_out;
4265 } else if (qobject_type(obj) != QTYPE_QDICT) {
4266 qemu_error_new(QERR_QMP_BAD_INPUT_OBJECT, "object");
4267 qobject_decref(obj);
4268 goto err_out;
4271 input = qobject_to_qdict(obj);
4273 mon->mc->id = qdict_get(input, "id");
4274 qobject_incref(mon->mc->id);
4276 obj = qdict_get(input, "execute");
4277 if (!obj) {
4278 qemu_error_new(QERR_QMP_BAD_INPUT_OBJECT, "execute");
4279 goto err_input;
4280 } else if (qobject_type(obj) != QTYPE_QSTRING) {
4281 qemu_error_new(QERR_QMP_BAD_INPUT_OBJECT, "string");
4282 goto err_input;
4285 cmd_name = qstring_get_str(qobject_to_qstring(obj));
4287 if (invalid_qmp_mode(mon, cmd_name)) {
4288 qemu_error_new(QERR_COMMAND_NOT_FOUND, cmd_name);
4289 goto err_input;
4293 * XXX: We need this special case until we get info handlers
4294 * converted into 'query-' commands
4296 if (compare_cmd(cmd_name, "info")) {
4297 qemu_error_new(QERR_COMMAND_NOT_FOUND, cmd_name);
4298 goto err_input;
4299 } else if (strstart(cmd_name, "query-", &info_item)) {
4300 cmd = monitor_find_command("info");
4301 qdict_put_obj(input, "arguments",
4302 qobject_from_jsonf("{ 'item': %s }", info_item));
4303 } else {
4304 cmd = monitor_find_command(cmd_name);
4305 if (!cmd || !monitor_handler_ported(cmd)) {
4306 qemu_error_new(QERR_COMMAND_NOT_FOUND, cmd_name);
4307 goto err_input;
4311 obj = qdict_get(input, "arguments");
4312 if (!obj) {
4313 args = qdict_new();
4314 } else {
4315 args = qobject_to_qdict(obj);
4316 QINCREF(args);
4319 QDECREF(input);
4321 err = monitor_check_qmp_args(cmd, args);
4322 if (err < 0) {
4323 goto err_out;
4326 if (monitor_handler_is_async(cmd)) {
4327 qmp_async_cmd_handler(mon, cmd, args);
4328 } else {
4329 monitor_call_handler(mon, cmd, args);
4331 goto out;
4333 err_input:
4334 QDECREF(input);
4335 err_out:
4336 monitor_protocol_emitter(mon, NULL);
4337 out:
4338 QDECREF(args);
4339 qemu_errors_to_previous();
4343 * monitor_control_read(): Read and handle QMP input
4345 static void monitor_control_read(void *opaque, const uint8_t *buf, int size)
4347 Monitor *old_mon = cur_mon;
4349 cur_mon = opaque;
4351 json_message_parser_feed(&cur_mon->mc->parser, (const char *) buf, size);
4353 cur_mon = old_mon;
4356 static void monitor_read(void *opaque, const uint8_t *buf, int size)
4358 Monitor *old_mon = cur_mon;
4359 int i;
4361 cur_mon = opaque;
4363 if (cur_mon->rs) {
4364 for (i = 0; i < size; i++)
4365 readline_handle_byte(cur_mon->rs, buf[i]);
4366 } else {
4367 if (size == 0 || buf[size - 1] != 0)
4368 monitor_printf(cur_mon, "corrupted command\n");
4369 else
4370 handle_user_command(cur_mon, (char *)buf);
4373 cur_mon = old_mon;
4376 static void monitor_command_cb(Monitor *mon, const char *cmdline, void *opaque)
4378 monitor_suspend(mon);
4379 handle_user_command(mon, cmdline);
4380 monitor_resume(mon);
4383 int monitor_suspend(Monitor *mon)
4385 if (!mon->rs)
4386 return -ENOTTY;
4387 mon->suspend_cnt++;
4388 return 0;
4391 void monitor_resume(Monitor *mon)
4393 if (!mon->rs)
4394 return;
4395 if (--mon->suspend_cnt == 0)
4396 readline_show_prompt(mon->rs);
4399 static QObject *get_qmp_greeting(void)
4401 QObject *ver;
4403 do_info_version(NULL, &ver);
4404 return qobject_from_jsonf("{'QMP':{'version': %p,'capabilities': []}}",ver);
4408 * monitor_control_event(): Print QMP gretting
4410 static void monitor_control_event(void *opaque, int event)
4412 QObject *data;
4413 Monitor *mon = opaque;
4415 switch (event) {
4416 case CHR_EVENT_OPENED:
4417 mon->mc->command_mode = 0;
4418 json_message_parser_init(&mon->mc->parser, handle_qmp_command);
4419 data = get_qmp_greeting();
4420 monitor_json_emitter(mon, data);
4421 qobject_decref(data);
4422 break;
4423 case CHR_EVENT_CLOSED:
4424 json_message_parser_destroy(&mon->mc->parser);
4425 break;
4429 static void monitor_event(void *opaque, int event)
4431 Monitor *mon = opaque;
4433 switch (event) {
4434 case CHR_EVENT_MUX_IN:
4435 mon->mux_out = 0;
4436 if (mon->reset_seen) {
4437 readline_restart(mon->rs);
4438 monitor_resume(mon);
4439 monitor_flush(mon);
4440 } else {
4441 mon->suspend_cnt = 0;
4443 break;
4445 case CHR_EVENT_MUX_OUT:
4446 if (mon->reset_seen) {
4447 if (mon->suspend_cnt == 0) {
4448 monitor_printf(mon, "\n");
4450 monitor_flush(mon);
4451 monitor_suspend(mon);
4452 } else {
4453 mon->suspend_cnt++;
4455 mon->mux_out = 1;
4456 break;
4458 case CHR_EVENT_OPENED:
4459 monitor_printf(mon, "QEMU %s monitor - type 'help' for more "
4460 "information\n", QEMU_VERSION);
4461 if (!mon->mux_out) {
4462 readline_show_prompt(mon->rs);
4464 mon->reset_seen = 1;
4465 break;
4471 * Local variables:
4472 * c-indent-level: 4
4473 * c-basic-offset: 4
4474 * tab-width: 8
4475 * End:
4478 void monitor_init(CharDriverState *chr, int flags)
4480 static int is_first_init = 1;
4481 Monitor *mon;
4483 if (is_first_init) {
4484 key_timer = qemu_new_timer(vm_clock, release_keys, NULL);
4485 is_first_init = 0;
4488 mon = qemu_mallocz(sizeof(*mon));
4490 mon->chr = chr;
4491 mon->flags = flags;
4492 if (flags & MONITOR_USE_READLINE) {
4493 mon->rs = readline_init(mon, monitor_find_completion);
4494 monitor_read_command(mon, 0);
4497 if (monitor_ctrl_mode(mon)) {
4498 mon->mc = qemu_mallocz(sizeof(MonitorControl));
4499 /* Control mode requires special handlers */
4500 qemu_chr_add_handlers(chr, monitor_can_read, monitor_control_read,
4501 monitor_control_event, mon);
4502 } else {
4503 qemu_chr_add_handlers(chr, monitor_can_read, monitor_read,
4504 monitor_event, mon);
4507 QLIST_INSERT_HEAD(&mon_list, mon, entry);
4508 if (!cur_mon || (flags & MONITOR_IS_DEFAULT))
4509 cur_mon = mon;
4512 static void bdrv_password_cb(Monitor *mon, const char *password, void *opaque)
4514 BlockDriverState *bs = opaque;
4515 int ret = 0;
4517 if (bdrv_set_key(bs, password) != 0) {
4518 monitor_printf(mon, "invalid password\n");
4519 ret = -EPERM;
4521 if (mon->password_completion_cb)
4522 mon->password_completion_cb(mon->password_opaque, ret);
4524 monitor_read_command(mon, 1);
4527 void monitor_read_bdrv_key_start(Monitor *mon, BlockDriverState *bs,
4528 BlockDriverCompletionFunc *completion_cb,
4529 void *opaque)
4531 int err;
4533 if (!bdrv_key_required(bs)) {
4534 if (completion_cb)
4535 completion_cb(opaque, 0);
4536 return;
4539 if (monitor_ctrl_mode(mon)) {
4540 qemu_error_new(QERR_DEVICE_ENCRYPTED, bdrv_get_device_name(bs));
4541 return;
4544 monitor_printf(mon, "%s (%s) is encrypted.\n", bdrv_get_device_name(bs),
4545 bdrv_get_encrypted_filename(bs));
4547 mon->password_completion_cb = completion_cb;
4548 mon->password_opaque = opaque;
4550 err = monitor_read_password(mon, bdrv_password_cb, bs);
4552 if (err && completion_cb)
4553 completion_cb(opaque, err);
4556 typedef struct QemuErrorSink QemuErrorSink;
4557 struct QemuErrorSink {
4558 enum {
4559 ERR_SINK_FILE,
4560 ERR_SINK_MONITOR,
4561 } dest;
4562 union {
4563 FILE *fp;
4564 Monitor *mon;
4566 QemuErrorSink *previous;
4569 static QemuErrorSink *qemu_error_sink;
4571 void qemu_errors_to_file(FILE *fp)
4573 QemuErrorSink *sink;
4575 sink = qemu_mallocz(sizeof(*sink));
4576 sink->dest = ERR_SINK_FILE;
4577 sink->fp = fp;
4578 sink->previous = qemu_error_sink;
4579 qemu_error_sink = sink;
4582 void qemu_errors_to_mon(Monitor *mon)
4584 QemuErrorSink *sink;
4586 sink = qemu_mallocz(sizeof(*sink));
4587 sink->dest = ERR_SINK_MONITOR;
4588 sink->mon = mon;
4589 sink->previous = qemu_error_sink;
4590 qemu_error_sink = sink;
4593 void qemu_errors_to_previous(void)
4595 QemuErrorSink *sink;
4597 assert(qemu_error_sink != NULL);
4598 sink = qemu_error_sink;
4599 qemu_error_sink = sink->previous;
4600 qemu_free(sink);
4603 void qemu_error(const char *fmt, ...)
4605 va_list args;
4607 assert(qemu_error_sink != NULL);
4608 switch (qemu_error_sink->dest) {
4609 case ERR_SINK_FILE:
4610 va_start(args, fmt);
4611 vfprintf(qemu_error_sink->fp, fmt, args);
4612 va_end(args);
4613 break;
4614 case ERR_SINK_MONITOR:
4615 va_start(args, fmt);
4616 monitor_vprintf(qemu_error_sink->mon, fmt, args);
4617 va_end(args);
4618 break;
4622 void qemu_error_internal(const char *file, int linenr, const char *func,
4623 const char *fmt, ...)
4625 va_list va;
4626 QError *qerror;
4628 assert(qemu_error_sink != NULL);
4630 va_start(va, fmt);
4631 qerror = qerror_from_info(file, linenr, func, fmt, &va);
4632 va_end(va);
4634 switch (qemu_error_sink->dest) {
4635 case ERR_SINK_FILE:
4636 qerror_print(qerror);
4637 QDECREF(qerror);
4638 break;
4639 case ERR_SINK_MONITOR:
4640 /* report only the first error */
4641 if (!qemu_error_sink->mon->error) {
4642 qemu_error_sink->mon->error = qerror;
4643 } else {
4644 /* XXX: warn the programmer */
4645 QDECREF(qerror);
4647 break;