versatile_pci: convert to symbolic names
[qemu.git] / monitor.c
blobae125b8230ad96573253e0edbde0bfa38667f81d
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 union {
102 void (*info)(Monitor *mon);
103 void (*info_new)(Monitor *mon, QObject **ret_data);
104 int (*info_async)(Monitor *mon, MonitorCompletion *cb, void *opaque);
105 void (*cmd)(Monitor *mon, const QDict *qdict);
106 void (*cmd_new)(Monitor *mon, const QDict *params, QObject **ret_data);
107 int (*cmd_async)(Monitor *mon, const QDict *params,
108 MonitorCompletion *cb, void *opaque);
109 } mhandler;
110 int async;
111 } mon_cmd_t;
113 /* file descriptors passed via SCM_RIGHTS */
114 typedef struct mon_fd_t mon_fd_t;
115 struct mon_fd_t {
116 char *name;
117 int fd;
118 QLIST_ENTRY(mon_fd_t) next;
121 typedef struct MonitorControl {
122 QObject *id;
123 int print_enabled;
124 JSONMessageParser parser;
125 int command_mode;
126 } MonitorControl;
128 struct Monitor {
129 CharDriverState *chr;
130 int mux_out;
131 int reset_seen;
132 int flags;
133 int suspend_cnt;
134 uint8_t outbuf[1024];
135 int outbuf_index;
136 ReadLineState *rs;
137 MonitorControl *mc;
138 CPUState *mon_cpu;
139 BlockDriverCompletionFunc *password_completion_cb;
140 void *password_opaque;
141 QError *error;
142 QLIST_HEAD(,mon_fd_t) fds;
143 QLIST_ENTRY(Monitor) entry;
146 static QLIST_HEAD(mon_list, Monitor) mon_list;
148 static const mon_cmd_t mon_cmds[];
149 static const mon_cmd_t info_cmds[];
151 Monitor *cur_mon = NULL;
153 static void monitor_command_cb(Monitor *mon, const char *cmdline,
154 void *opaque);
156 static inline int qmp_cmd_mode(const Monitor *mon)
158 return (mon->mc ? mon->mc->command_mode : 0);
161 /* Return true if in control mode, false otherwise */
162 static inline int monitor_ctrl_mode(const Monitor *mon)
164 return (mon->flags & MONITOR_USE_CONTROL);
167 static void monitor_read_command(Monitor *mon, int show_prompt)
169 if (!mon->rs)
170 return;
172 readline_start(mon->rs, "(qemu) ", 0, monitor_command_cb, NULL);
173 if (show_prompt)
174 readline_show_prompt(mon->rs);
177 static int monitor_read_password(Monitor *mon, ReadLineFunc *readline_func,
178 void *opaque)
180 if (monitor_ctrl_mode(mon)) {
181 qemu_error_new(QERR_MISSING_PARAMETER, "password");
182 return -EINVAL;
183 } else if (mon->rs) {
184 readline_start(mon->rs, "Password: ", 1, readline_func, opaque);
185 /* prompt is printed on return from the command handler */
186 return 0;
187 } else {
188 monitor_printf(mon, "terminal does not support password prompting\n");
189 return -ENOTTY;
193 void monitor_flush(Monitor *mon)
195 if (mon && mon->outbuf_index != 0 && !mon->mux_out) {
196 qemu_chr_write(mon->chr, mon->outbuf, mon->outbuf_index);
197 mon->outbuf_index = 0;
201 /* flush at every end of line or if the buffer is full */
202 static void monitor_puts(Monitor *mon, const char *str)
204 char c;
206 for(;;) {
207 c = *str++;
208 if (c == '\0')
209 break;
210 if (c == '\n')
211 mon->outbuf[mon->outbuf_index++] = '\r';
212 mon->outbuf[mon->outbuf_index++] = c;
213 if (mon->outbuf_index >= (sizeof(mon->outbuf) - 1)
214 || c == '\n')
215 monitor_flush(mon);
219 void monitor_vprintf(Monitor *mon, const char *fmt, va_list ap)
221 if (!mon)
222 return;
224 if (mon->mc && !mon->mc->print_enabled) {
225 qemu_error_new(QERR_UNDEFINED_ERROR);
226 } else {
227 char buf[4096];
228 vsnprintf(buf, sizeof(buf), fmt, ap);
229 monitor_puts(mon, buf);
233 void monitor_printf(Monitor *mon, const char *fmt, ...)
235 va_list ap;
236 va_start(ap, fmt);
237 monitor_vprintf(mon, fmt, ap);
238 va_end(ap);
241 void monitor_print_filename(Monitor *mon, const char *filename)
243 int i;
245 for (i = 0; filename[i]; i++) {
246 switch (filename[i]) {
247 case ' ':
248 case '"':
249 case '\\':
250 monitor_printf(mon, "\\%c", filename[i]);
251 break;
252 case '\t':
253 monitor_printf(mon, "\\t");
254 break;
255 case '\r':
256 monitor_printf(mon, "\\r");
257 break;
258 case '\n':
259 monitor_printf(mon, "\\n");
260 break;
261 default:
262 monitor_printf(mon, "%c", filename[i]);
263 break;
268 static int monitor_fprintf(FILE *stream, const char *fmt, ...)
270 va_list ap;
271 va_start(ap, fmt);
272 monitor_vprintf((Monitor *)stream, fmt, ap);
273 va_end(ap);
274 return 0;
277 static void monitor_user_noop(Monitor *mon, const QObject *data) { }
279 static inline int monitor_handler_ported(const mon_cmd_t *cmd)
281 return cmd->user_print != NULL;
284 static inline bool monitor_handler_is_async(const mon_cmd_t *cmd)
286 return cmd->async != 0;
289 static inline int monitor_has_error(const Monitor *mon)
291 return mon->error != NULL;
294 static void monitor_json_emitter(Monitor *mon, const QObject *data)
296 QString *json;
298 json = qobject_to_json(data);
299 assert(json != NULL);
301 mon->mc->print_enabled = 1;
302 monitor_printf(mon, "%s\n", qstring_get_str(json));
303 mon->mc->print_enabled = 0;
305 QDECREF(json);
308 static void monitor_protocol_emitter(Monitor *mon, QObject *data)
310 QDict *qmp;
312 qmp = qdict_new();
314 if (!monitor_has_error(mon)) {
315 /* success response */
316 if (data) {
317 qobject_incref(data);
318 qdict_put_obj(qmp, "return", data);
319 } else {
320 /* return an empty QDict by default */
321 qdict_put(qmp, "return", qdict_new());
323 } else {
324 /* error response */
325 qdict_put(mon->error->error, "desc", qerror_human(mon->error));
326 qdict_put(qmp, "error", mon->error->error);
327 QINCREF(mon->error->error);
328 QDECREF(mon->error);
329 mon->error = NULL;
332 if (mon->mc->id) {
333 qdict_put_obj(qmp, "id", mon->mc->id);
334 mon->mc->id = NULL;
337 monitor_json_emitter(mon, QOBJECT(qmp));
338 QDECREF(qmp);
341 static void timestamp_put(QDict *qdict)
343 int err;
344 QObject *obj;
345 qemu_timeval tv;
347 err = qemu_gettimeofday(&tv);
348 if (err < 0)
349 return;
351 obj = qobject_from_jsonf("{ 'seconds': %" PRId64 ", "
352 "'microseconds': %" PRId64 " }",
353 (int64_t) tv.tv_sec, (int64_t) tv.tv_usec);
354 qdict_put_obj(qdict, "timestamp", obj);
358 * monitor_protocol_event(): Generate a Monitor event
360 * Event-specific data can be emitted through the (optional) 'data' parameter.
362 void monitor_protocol_event(MonitorEvent event, QObject *data)
364 QDict *qmp;
365 const char *event_name;
366 Monitor *mon;
368 assert(event < QEVENT_MAX);
370 switch (event) {
371 case QEVENT_DEBUG:
372 event_name = "DEBUG";
373 break;
374 case QEVENT_SHUTDOWN:
375 event_name = "SHUTDOWN";
376 break;
377 case QEVENT_RESET:
378 event_name = "RESET";
379 break;
380 case QEVENT_POWERDOWN:
381 event_name = "POWERDOWN";
382 break;
383 case QEVENT_STOP:
384 event_name = "STOP";
385 break;
386 case QEVENT_VNC_CONNECTED:
387 event_name = "VNC_CONNECTED";
388 break;
389 case QEVENT_VNC_INITIALIZED:
390 event_name = "VNC_INITIALIZED";
391 break;
392 case QEVENT_VNC_DISCONNECTED:
393 event_name = "VNC_DISCONNECTED";
394 break;
395 case QEVENT_BLOCK_IO_ERROR:
396 event_name = "BLOCK_IO_ERROR";
397 break;
398 default:
399 abort();
400 break;
403 qmp = qdict_new();
404 timestamp_put(qmp);
405 qdict_put(qmp, "event", qstring_from_str(event_name));
406 if (data) {
407 qobject_incref(data);
408 qdict_put_obj(qmp, "data", data);
411 QLIST_FOREACH(mon, &mon_list, entry) {
412 if (monitor_ctrl_mode(mon) && qmp_cmd_mode(mon)) {
413 monitor_json_emitter(mon, QOBJECT(qmp));
416 QDECREF(qmp);
419 static void do_qmp_capabilities(Monitor *mon, const QDict *params,
420 QObject **ret_data)
422 /* Will setup QMP capabilities in the future */
423 if (monitor_ctrl_mode(mon)) {
424 mon->mc->command_mode = 1;
428 static int compare_cmd(const char *name, const char *list)
430 const char *p, *pstart;
431 int len;
432 len = strlen(name);
433 p = list;
434 for(;;) {
435 pstart = p;
436 p = strchr(p, '|');
437 if (!p)
438 p = pstart + strlen(pstart);
439 if ((p - pstart) == len && !memcmp(pstart, name, len))
440 return 1;
441 if (*p == '\0')
442 break;
443 p++;
445 return 0;
448 static void help_cmd_dump(Monitor *mon, const mon_cmd_t *cmds,
449 const char *prefix, const char *name)
451 const mon_cmd_t *cmd;
453 for(cmd = cmds; cmd->name != NULL; cmd++) {
454 if (!name || !strcmp(name, cmd->name))
455 monitor_printf(mon, "%s%s %s -- %s\n", prefix, cmd->name,
456 cmd->params, cmd->help);
460 static void help_cmd(Monitor *mon, const char *name)
462 if (name && !strcmp(name, "info")) {
463 help_cmd_dump(mon, info_cmds, "info ", NULL);
464 } else {
465 help_cmd_dump(mon, mon_cmds, "", name);
466 if (name && !strcmp(name, "log")) {
467 const CPULogItem *item;
468 monitor_printf(mon, "Log items (comma separated):\n");
469 monitor_printf(mon, "%-10s %s\n", "none", "remove all logs");
470 for(item = cpu_log_items; item->mask != 0; item++) {
471 monitor_printf(mon, "%-10s %s\n", item->name, item->help);
477 static void do_help_cmd(Monitor *mon, const QDict *qdict)
479 help_cmd(mon, qdict_get_try_str(qdict, "name"));
482 static void do_commit(Monitor *mon, const QDict *qdict)
484 int all_devices;
485 DriveInfo *dinfo;
486 const char *device = qdict_get_str(qdict, "device");
488 all_devices = !strcmp(device, "all");
489 QTAILQ_FOREACH(dinfo, &drives, next) {
490 if (!all_devices)
491 if (strcmp(bdrv_get_device_name(dinfo->bdrv), device))
492 continue;
493 bdrv_commit(dinfo->bdrv);
497 static void user_monitor_complete(void *opaque, QObject *ret_data)
499 MonitorCompletionData *data = (MonitorCompletionData *)opaque;
501 if (ret_data) {
502 data->user_print(data->mon, ret_data);
504 monitor_resume(data->mon);
505 qemu_free(data);
508 static void qmp_monitor_complete(void *opaque, QObject *ret_data)
510 monitor_protocol_emitter(opaque, ret_data);
513 static void qmp_async_cmd_handler(Monitor *mon, const mon_cmd_t *cmd,
514 const QDict *params)
516 cmd->mhandler.cmd_async(mon, params, qmp_monitor_complete, mon);
519 static void qmp_async_info_handler(Monitor *mon, const mon_cmd_t *cmd)
521 cmd->mhandler.info_async(mon, qmp_monitor_complete, mon);
524 static void user_async_cmd_handler(Monitor *mon, const mon_cmd_t *cmd,
525 const QDict *params)
527 int ret;
529 MonitorCompletionData *cb_data = qemu_malloc(sizeof(*cb_data));
530 cb_data->mon = mon;
531 cb_data->user_print = cmd->user_print;
532 monitor_suspend(mon);
533 ret = cmd->mhandler.cmd_async(mon, params,
534 user_monitor_complete, cb_data);
535 if (ret < 0) {
536 monitor_resume(mon);
537 qemu_free(cb_data);
541 static void user_async_info_handler(Monitor *mon, const mon_cmd_t *cmd)
543 int ret;
545 MonitorCompletionData *cb_data = qemu_malloc(sizeof(*cb_data));
546 cb_data->mon = mon;
547 cb_data->user_print = cmd->user_print;
548 monitor_suspend(mon);
549 ret = cmd->mhandler.info_async(mon, user_monitor_complete, cb_data);
550 if (ret < 0) {
551 monitor_resume(mon);
552 qemu_free(cb_data);
556 static void do_info(Monitor *mon, const QDict *qdict, QObject **ret_data)
558 const mon_cmd_t *cmd;
559 const char *item = qdict_get_try_str(qdict, "item");
561 if (!item) {
562 assert(monitor_ctrl_mode(mon) == 0);
563 goto help;
566 for (cmd = info_cmds; cmd->name != NULL; cmd++) {
567 if (compare_cmd(item, cmd->name))
568 break;
571 if (cmd->name == NULL) {
572 if (monitor_ctrl_mode(mon)) {
573 qemu_error_new(QERR_COMMAND_NOT_FOUND, item);
574 return;
576 goto help;
579 if (monitor_handler_is_async(cmd)) {
580 if (monitor_ctrl_mode(mon)) {
581 qmp_async_info_handler(mon, cmd);
582 } else {
583 user_async_info_handler(mon, cmd);
586 * Indicate that this command is asynchronous and will not return any
587 * data (not even empty). Instead, the data will be returned via a
588 * completion callback.
590 *ret_data = qobject_from_jsonf("{ '__mon_async': 'return' }");
591 } else if (monitor_handler_ported(cmd)) {
592 cmd->mhandler.info_new(mon, ret_data);
594 if (!monitor_ctrl_mode(mon)) {
596 * User Protocol function is called here, Monitor Protocol is
597 * handled by monitor_call_handler()
599 if (*ret_data)
600 cmd->user_print(mon, *ret_data);
602 } else {
603 if (monitor_ctrl_mode(mon)) {
604 /* handler not converted yet */
605 qemu_error_new(QERR_COMMAND_NOT_FOUND, item);
606 } else {
607 cmd->mhandler.info(mon);
611 return;
613 help:
614 help_cmd(mon, "info");
617 static void do_info_version_print(Monitor *mon, const QObject *data)
619 QDict *qdict;
621 qdict = qobject_to_qdict(data);
623 monitor_printf(mon, "%s%s\n", qdict_get_str(qdict, "qemu"),
624 qdict_get_str(qdict, "package"));
628 * do_info_version(): Show QEMU version
630 * Return a QDict with the following information:
632 * - "qemu": QEMU's version
633 * - "package": package's version
635 * Example:
637 * { "qemu": "0.11.50", "package": "" }
639 static void do_info_version(Monitor *mon, QObject **ret_data)
641 *ret_data = qobject_from_jsonf("{ 'qemu': %s, 'package': %s }",
642 QEMU_VERSION, QEMU_PKGVERSION);
645 static void do_info_name_print(Monitor *mon, const QObject *data)
647 QDict *qdict;
649 qdict = qobject_to_qdict(data);
650 if (qdict_size(qdict) == 0) {
651 return;
654 monitor_printf(mon, "%s\n", qdict_get_str(qdict, "name"));
658 * do_info_name(): Show VM name
660 * Return a QDict with the following information:
662 * - "name": VM's name (optional)
664 * Example:
666 * { "name": "qemu-name" }
668 static void do_info_name(Monitor *mon, QObject **ret_data)
670 *ret_data = qemu_name ? qobject_from_jsonf("{'name': %s }", qemu_name) :
671 qobject_from_jsonf("{}");
674 static QObject *get_cmd_dict(const char *name)
676 const char *p;
678 /* Remove '|' from some commands */
679 p = strchr(name, '|');
680 if (p) {
681 p++;
682 } else {
683 p = name;
686 return qobject_from_jsonf("{ 'name': %s }", p);
690 * do_info_commands(): List QMP available commands
692 * Each command is represented by a QDict, the returned QObject is a QList
693 * of all commands.
695 * The QDict contains:
697 * - "name": command's name
699 * Example:
701 * { [ { "name": "query-balloon" }, { "name": "system_powerdown" } ] }
703 static void do_info_commands(Monitor *mon, QObject **ret_data)
705 QList *cmd_list;
706 const mon_cmd_t *cmd;
708 cmd_list = qlist_new();
710 for (cmd = mon_cmds; cmd->name != NULL; cmd++) {
711 if (monitor_handler_ported(cmd) && !compare_cmd(cmd->name, "info")) {
712 qlist_append_obj(cmd_list, get_cmd_dict(cmd->name));
716 for (cmd = info_cmds; cmd->name != NULL; cmd++) {
717 if (monitor_handler_ported(cmd)) {
718 char buf[128];
719 snprintf(buf, sizeof(buf), "query-%s", cmd->name);
720 qlist_append_obj(cmd_list, get_cmd_dict(buf));
724 *ret_data = QOBJECT(cmd_list);
727 #if defined(TARGET_I386)
728 static void do_info_hpet_print(Monitor *mon, const QObject *data)
730 monitor_printf(mon, "HPET is %s by QEMU\n",
731 qdict_get_bool(qobject_to_qdict(data), "enabled") ?
732 "enabled" : "disabled");
736 * do_info_hpet(): Show HPET state
738 * Return a QDict with the following information:
740 * - "enabled": true if hpet if enabled, false otherwise
742 * Example:
744 * { "enabled": true }
746 static void do_info_hpet(Monitor *mon, QObject **ret_data)
748 *ret_data = qobject_from_jsonf("{ 'enabled': %i }", !no_hpet);
750 #endif
752 static void do_info_uuid_print(Monitor *mon, const QObject *data)
754 monitor_printf(mon, "%s\n", qdict_get_str(qobject_to_qdict(data), "UUID"));
758 * do_info_uuid(): Show VM UUID
760 * Return a QDict with the following information:
762 * - "UUID": Universally Unique Identifier
764 * Example:
766 * { "UUID": "550e8400-e29b-41d4-a716-446655440000" }
768 static void do_info_uuid(Monitor *mon, QObject **ret_data)
770 char uuid[64];
772 snprintf(uuid, sizeof(uuid), UUID_FMT, qemu_uuid[0], qemu_uuid[1],
773 qemu_uuid[2], qemu_uuid[3], qemu_uuid[4], qemu_uuid[5],
774 qemu_uuid[6], qemu_uuid[7], qemu_uuid[8], qemu_uuid[9],
775 qemu_uuid[10], qemu_uuid[11], qemu_uuid[12], qemu_uuid[13],
776 qemu_uuid[14], qemu_uuid[15]);
777 *ret_data = qobject_from_jsonf("{ 'UUID': %s }", uuid);
780 /* get the current CPU defined by the user */
781 static int mon_set_cpu(int cpu_index)
783 CPUState *env;
785 for(env = first_cpu; env != NULL; env = env->next_cpu) {
786 if (env->cpu_index == cpu_index) {
787 cur_mon->mon_cpu = env;
788 return 0;
791 return -1;
794 static CPUState *mon_get_cpu(void)
796 if (!cur_mon->mon_cpu) {
797 mon_set_cpu(0);
799 cpu_synchronize_state(cur_mon->mon_cpu);
800 return cur_mon->mon_cpu;
803 static void do_info_registers(Monitor *mon)
805 CPUState *env;
806 env = mon_get_cpu();
807 #ifdef TARGET_I386
808 cpu_dump_state(env, (FILE *)mon, monitor_fprintf,
809 X86_DUMP_FPU);
810 #else
811 cpu_dump_state(env, (FILE *)mon, monitor_fprintf,
813 #endif
816 static void print_cpu_iter(QObject *obj, void *opaque)
818 QDict *cpu;
819 int active = ' ';
820 Monitor *mon = opaque;
822 assert(qobject_type(obj) == QTYPE_QDICT);
823 cpu = qobject_to_qdict(obj);
825 if (qdict_get_bool(cpu, "current")) {
826 active = '*';
829 monitor_printf(mon, "%c CPU #%d: ", active, (int)qdict_get_int(cpu, "CPU"));
831 #if defined(TARGET_I386)
832 monitor_printf(mon, "pc=0x" TARGET_FMT_lx,
833 (target_ulong) qdict_get_int(cpu, "pc"));
834 #elif defined(TARGET_PPC)
835 monitor_printf(mon, "nip=0x" TARGET_FMT_lx,
836 (target_long) qdict_get_int(cpu, "nip"));
837 #elif defined(TARGET_SPARC)
838 monitor_printf(mon, "pc=0x " TARGET_FMT_lx,
839 (target_long) qdict_get_int(cpu, "pc"));
840 monitor_printf(mon, "npc=0x" TARGET_FMT_lx,
841 (target_long) qdict_get_int(cpu, "npc"));
842 #elif defined(TARGET_MIPS)
843 monitor_printf(mon, "PC=0x" TARGET_FMT_lx,
844 (target_long) qdict_get_int(cpu, "PC"));
845 #endif
847 if (qdict_get_bool(cpu, "halted")) {
848 monitor_printf(mon, " (halted)");
851 monitor_printf(mon, "\n");
854 static void monitor_print_cpus(Monitor *mon, const QObject *data)
856 QList *cpu_list;
858 assert(qobject_type(data) == QTYPE_QLIST);
859 cpu_list = qobject_to_qlist(data);
860 qlist_iter(cpu_list, print_cpu_iter, mon);
864 * do_info_cpus(): Show CPU information
866 * Return a QList. Each CPU is represented by a QDict, which contains:
868 * - "cpu": CPU index
869 * - "current": true if this is the current CPU, false otherwise
870 * - "halted": true if the cpu is halted, false otherwise
871 * - Current program counter. The key's name depends on the architecture:
872 * "pc": i386/x86)64
873 * "nip": PPC
874 * "pc" and "npc": sparc
875 * "PC": mips
877 * Example:
879 * [ { "CPU": 0, "current": true, "halted": false, "pc": 3227107138 },
880 * { "CPU": 1, "current": false, "halted": true, "pc": 7108165 } ]
882 static void do_info_cpus(Monitor *mon, QObject **ret_data)
884 CPUState *env;
885 QList *cpu_list;
887 cpu_list = qlist_new();
889 /* just to set the default cpu if not already done */
890 mon_get_cpu();
892 for(env = first_cpu; env != NULL; env = env->next_cpu) {
893 QDict *cpu;
894 QObject *obj;
896 cpu_synchronize_state(env);
898 obj = qobject_from_jsonf("{ 'CPU': %d, 'current': %i, 'halted': %i }",
899 env->cpu_index, env == mon->mon_cpu,
900 env->halted);
902 cpu = qobject_to_qdict(obj);
904 #if defined(TARGET_I386)
905 qdict_put(cpu, "pc", qint_from_int(env->eip + env->segs[R_CS].base));
906 #elif defined(TARGET_PPC)
907 qdict_put(cpu, "nip", qint_from_int(env->nip));
908 #elif defined(TARGET_SPARC)
909 qdict_put(cpu, "pc", qint_from_int(env->pc));
910 qdict_put(cpu, "npc", qint_from_int(env->npc));
911 #elif defined(TARGET_MIPS)
912 qdict_put(cpu, "PC", qint_from_int(env->active_tc.PC));
913 #endif
915 qlist_append(cpu_list, cpu);
918 *ret_data = QOBJECT(cpu_list);
921 static void do_cpu_set(Monitor *mon, const QDict *qdict, QObject **ret_data)
923 int index = qdict_get_int(qdict, "index");
924 if (mon_set_cpu(index) < 0)
925 qemu_error_new(QERR_INVALID_PARAMETER, "index");
928 static void do_info_jit(Monitor *mon)
930 dump_exec_info((FILE *)mon, monitor_fprintf);
933 static void do_info_history(Monitor *mon)
935 int i;
936 const char *str;
938 if (!mon->rs)
939 return;
940 i = 0;
941 for(;;) {
942 str = readline_get_history(mon->rs, i);
943 if (!str)
944 break;
945 monitor_printf(mon, "%d: '%s'\n", i, str);
946 i++;
950 #if defined(TARGET_PPC)
951 /* XXX: not implemented in other targets */
952 static void do_info_cpu_stats(Monitor *mon)
954 CPUState *env;
956 env = mon_get_cpu();
957 cpu_dump_statistics(env, (FILE *)mon, &monitor_fprintf, 0);
959 #endif
962 * do_quit(): Quit QEMU execution
964 static void do_quit(Monitor *mon, const QDict *qdict, QObject **ret_data)
966 exit(0);
969 static int eject_device(Monitor *mon, BlockDriverState *bs, int force)
971 if (bdrv_is_inserted(bs)) {
972 if (!force) {
973 if (!bdrv_is_removable(bs)) {
974 qemu_error_new(QERR_DEVICE_NOT_REMOVABLE,
975 bdrv_get_device_name(bs));
976 return -1;
978 if (bdrv_is_locked(bs)) {
979 qemu_error_new(QERR_DEVICE_LOCKED, bdrv_get_device_name(bs));
980 return -1;
983 bdrv_close(bs);
985 return 0;
988 static void do_eject(Monitor *mon, const QDict *qdict, QObject **ret_data)
990 BlockDriverState *bs;
991 int force = qdict_get_int(qdict, "force");
992 const char *filename = qdict_get_str(qdict, "device");
994 bs = bdrv_find(filename);
995 if (!bs) {
996 qemu_error_new(QERR_DEVICE_NOT_FOUND, filename);
997 return;
999 eject_device(mon, bs, force);
1002 static void do_block_set_passwd(Monitor *mon, const QDict *qdict,
1003 QObject **ret_data)
1005 BlockDriverState *bs;
1007 bs = bdrv_find(qdict_get_str(qdict, "device"));
1008 if (!bs) {
1009 qemu_error_new(QERR_DEVICE_NOT_FOUND, qdict_get_str(qdict, "device"));
1010 return;
1013 if (bdrv_set_key(bs, qdict_get_str(qdict, "password")) < 0) {
1014 qemu_error_new(QERR_INVALID_PASSWORD);
1018 static void do_change_block(Monitor *mon, const char *device,
1019 const char *filename, const char *fmt)
1021 BlockDriverState *bs;
1022 BlockDriver *drv = NULL;
1024 bs = bdrv_find(device);
1025 if (!bs) {
1026 qemu_error_new(QERR_DEVICE_NOT_FOUND, device);
1027 return;
1029 if (fmt) {
1030 drv = bdrv_find_whitelisted_format(fmt);
1031 if (!drv) {
1032 qemu_error_new(QERR_INVALID_BLOCK_FORMAT, fmt);
1033 return;
1036 if (eject_device(mon, bs, 0) < 0)
1037 return;
1038 bdrv_open2(bs, filename, BDRV_O_RDWR, drv);
1039 monitor_read_bdrv_key_start(mon, bs, NULL, NULL);
1042 static void change_vnc_password(const char *password)
1044 if (vnc_display_password(NULL, password) < 0)
1045 qemu_error_new(QERR_SET_PASSWD_FAILED);
1049 static void change_vnc_password_cb(Monitor *mon, const char *password,
1050 void *opaque)
1052 change_vnc_password(password);
1053 monitor_read_command(mon, 1);
1056 static void do_change_vnc(Monitor *mon, const char *target, const char *arg)
1058 if (strcmp(target, "passwd") == 0 ||
1059 strcmp(target, "password") == 0) {
1060 if (arg) {
1061 char password[9];
1062 strncpy(password, arg, sizeof(password));
1063 password[sizeof(password) - 1] = '\0';
1064 change_vnc_password(password);
1065 } else {
1066 monitor_read_password(mon, change_vnc_password_cb, NULL);
1068 } else {
1069 if (vnc_display_open(NULL, target) < 0)
1070 qemu_error_new(QERR_VNC_SERVER_FAILED, target);
1075 * do_change(): Change a removable medium, or VNC configuration
1077 static void do_change(Monitor *mon, const QDict *qdict, QObject **ret_data)
1079 const char *device = qdict_get_str(qdict, "device");
1080 const char *target = qdict_get_str(qdict, "target");
1081 const char *arg = qdict_get_try_str(qdict, "arg");
1082 if (strcmp(device, "vnc") == 0) {
1083 do_change_vnc(mon, target, arg);
1084 } else {
1085 do_change_block(mon, device, target, arg);
1089 static void do_screen_dump(Monitor *mon, const QDict *qdict)
1091 vga_hw_screen_dump(qdict_get_str(qdict, "filename"));
1094 static void do_logfile(Monitor *mon, const QDict *qdict)
1096 cpu_set_log_filename(qdict_get_str(qdict, "filename"));
1099 static void do_log(Monitor *mon, const QDict *qdict)
1101 int mask;
1102 const char *items = qdict_get_str(qdict, "items");
1104 if (!strcmp(items, "none")) {
1105 mask = 0;
1106 } else {
1107 mask = cpu_str_to_log_mask(items);
1108 if (!mask) {
1109 help_cmd(mon, "log");
1110 return;
1113 cpu_set_log(mask);
1116 static void do_singlestep(Monitor *mon, const QDict *qdict)
1118 const char *option = qdict_get_try_str(qdict, "option");
1119 if (!option || !strcmp(option, "on")) {
1120 singlestep = 1;
1121 } else if (!strcmp(option, "off")) {
1122 singlestep = 0;
1123 } else {
1124 monitor_printf(mon, "unexpected option %s\n", option);
1129 * do_stop(): Stop VM execution
1131 static void do_stop(Monitor *mon, const QDict *qdict, QObject **ret_data)
1133 vm_stop(EXCP_INTERRUPT);
1136 static void encrypted_bdrv_it(void *opaque, BlockDriverState *bs);
1138 struct bdrv_iterate_context {
1139 Monitor *mon;
1140 int err;
1144 * do_cont(): Resume emulation.
1146 static void do_cont(Monitor *mon, const QDict *qdict, QObject **ret_data)
1148 struct bdrv_iterate_context context = { mon, 0 };
1150 bdrv_iterate(encrypted_bdrv_it, &context);
1151 /* only resume the vm if all keys are set and valid */
1152 if (!context.err)
1153 vm_start();
1156 static void bdrv_key_cb(void *opaque, int err)
1158 Monitor *mon = opaque;
1160 /* another key was set successfully, retry to continue */
1161 if (!err)
1162 do_cont(mon, NULL, NULL);
1165 static void encrypted_bdrv_it(void *opaque, BlockDriverState *bs)
1167 struct bdrv_iterate_context *context = opaque;
1169 if (!context->err && bdrv_key_required(bs)) {
1170 context->err = -EBUSY;
1171 monitor_read_bdrv_key_start(context->mon, bs, bdrv_key_cb,
1172 context->mon);
1176 static void do_gdbserver(Monitor *mon, const QDict *qdict)
1178 const char *device = qdict_get_try_str(qdict, "device");
1179 if (!device)
1180 device = "tcp::" DEFAULT_GDBSTUB_PORT;
1181 if (gdbserver_start(device) < 0) {
1182 monitor_printf(mon, "Could not open gdbserver on device '%s'\n",
1183 device);
1184 } else if (strcmp(device, "none") == 0) {
1185 monitor_printf(mon, "Disabled gdbserver\n");
1186 } else {
1187 monitor_printf(mon, "Waiting for gdb connection on device '%s'\n",
1188 device);
1192 static void do_watchdog_action(Monitor *mon, const QDict *qdict)
1194 const char *action = qdict_get_str(qdict, "action");
1195 if (select_watchdog_action(action) == -1) {
1196 monitor_printf(mon, "Unknown watchdog action '%s'\n", action);
1200 static void monitor_printc(Monitor *mon, int c)
1202 monitor_printf(mon, "'");
1203 switch(c) {
1204 case '\'':
1205 monitor_printf(mon, "\\'");
1206 break;
1207 case '\\':
1208 monitor_printf(mon, "\\\\");
1209 break;
1210 case '\n':
1211 monitor_printf(mon, "\\n");
1212 break;
1213 case '\r':
1214 monitor_printf(mon, "\\r");
1215 break;
1216 default:
1217 if (c >= 32 && c <= 126) {
1218 monitor_printf(mon, "%c", c);
1219 } else {
1220 monitor_printf(mon, "\\x%02x", c);
1222 break;
1224 monitor_printf(mon, "'");
1227 static void memory_dump(Monitor *mon, int count, int format, int wsize,
1228 target_phys_addr_t addr, int is_physical)
1230 CPUState *env;
1231 int l, line_size, i, max_digits, len;
1232 uint8_t buf[16];
1233 uint64_t v;
1235 if (format == 'i') {
1236 int flags;
1237 flags = 0;
1238 env = mon_get_cpu();
1239 if (!is_physical)
1240 return;
1241 #ifdef TARGET_I386
1242 if (wsize == 2) {
1243 flags = 1;
1244 } else if (wsize == 4) {
1245 flags = 0;
1246 } else {
1247 /* as default we use the current CS size */
1248 flags = 0;
1249 if (env) {
1250 #ifdef TARGET_X86_64
1251 if ((env->efer & MSR_EFER_LMA) &&
1252 (env->segs[R_CS].flags & DESC_L_MASK))
1253 flags = 2;
1254 else
1255 #endif
1256 if (!(env->segs[R_CS].flags & DESC_B_MASK))
1257 flags = 1;
1260 #endif
1261 monitor_disas(mon, env, addr, count, is_physical, flags);
1262 return;
1265 len = wsize * count;
1266 if (wsize == 1)
1267 line_size = 8;
1268 else
1269 line_size = 16;
1270 max_digits = 0;
1272 switch(format) {
1273 case 'o':
1274 max_digits = (wsize * 8 + 2) / 3;
1275 break;
1276 default:
1277 case 'x':
1278 max_digits = (wsize * 8) / 4;
1279 break;
1280 case 'u':
1281 case 'd':
1282 max_digits = (wsize * 8 * 10 + 32) / 33;
1283 break;
1284 case 'c':
1285 wsize = 1;
1286 break;
1289 while (len > 0) {
1290 if (is_physical)
1291 monitor_printf(mon, TARGET_FMT_plx ":", addr);
1292 else
1293 monitor_printf(mon, TARGET_FMT_lx ":", (target_ulong)addr);
1294 l = len;
1295 if (l > line_size)
1296 l = line_size;
1297 if (is_physical) {
1298 cpu_physical_memory_rw(addr, buf, l, 0);
1299 } else {
1300 env = mon_get_cpu();
1301 if (cpu_memory_rw_debug(env, addr, buf, l, 0) < 0) {
1302 monitor_printf(mon, " Cannot access memory\n");
1303 break;
1306 i = 0;
1307 while (i < l) {
1308 switch(wsize) {
1309 default:
1310 case 1:
1311 v = ldub_raw(buf + i);
1312 break;
1313 case 2:
1314 v = lduw_raw(buf + i);
1315 break;
1316 case 4:
1317 v = (uint32_t)ldl_raw(buf + i);
1318 break;
1319 case 8:
1320 v = ldq_raw(buf + i);
1321 break;
1323 monitor_printf(mon, " ");
1324 switch(format) {
1325 case 'o':
1326 monitor_printf(mon, "%#*" PRIo64, max_digits, v);
1327 break;
1328 case 'x':
1329 monitor_printf(mon, "0x%0*" PRIx64, max_digits, v);
1330 break;
1331 case 'u':
1332 monitor_printf(mon, "%*" PRIu64, max_digits, v);
1333 break;
1334 case 'd':
1335 monitor_printf(mon, "%*" PRId64, max_digits, v);
1336 break;
1337 case 'c':
1338 monitor_printc(mon, v);
1339 break;
1341 i += wsize;
1343 monitor_printf(mon, "\n");
1344 addr += l;
1345 len -= l;
1349 static void do_memory_dump(Monitor *mon, const QDict *qdict)
1351 int count = qdict_get_int(qdict, "count");
1352 int format = qdict_get_int(qdict, "format");
1353 int size = qdict_get_int(qdict, "size");
1354 target_long addr = qdict_get_int(qdict, "addr");
1356 memory_dump(mon, count, format, size, addr, 0);
1359 static void do_physical_memory_dump(Monitor *mon, const QDict *qdict)
1361 int count = qdict_get_int(qdict, "count");
1362 int format = qdict_get_int(qdict, "format");
1363 int size = qdict_get_int(qdict, "size");
1364 target_phys_addr_t addr = qdict_get_int(qdict, "addr");
1366 memory_dump(mon, count, format, size, addr, 1);
1369 static void do_print(Monitor *mon, const QDict *qdict)
1371 int format = qdict_get_int(qdict, "format");
1372 target_phys_addr_t val = qdict_get_int(qdict, "val");
1374 #if TARGET_PHYS_ADDR_BITS == 32
1375 switch(format) {
1376 case 'o':
1377 monitor_printf(mon, "%#o", val);
1378 break;
1379 case 'x':
1380 monitor_printf(mon, "%#x", val);
1381 break;
1382 case 'u':
1383 monitor_printf(mon, "%u", val);
1384 break;
1385 default:
1386 case 'd':
1387 monitor_printf(mon, "%d", val);
1388 break;
1389 case 'c':
1390 monitor_printc(mon, val);
1391 break;
1393 #else
1394 switch(format) {
1395 case 'o':
1396 monitor_printf(mon, "%#" PRIo64, val);
1397 break;
1398 case 'x':
1399 monitor_printf(mon, "%#" PRIx64, val);
1400 break;
1401 case 'u':
1402 monitor_printf(mon, "%" PRIu64, val);
1403 break;
1404 default:
1405 case 'd':
1406 monitor_printf(mon, "%" PRId64, val);
1407 break;
1408 case 'c':
1409 monitor_printc(mon, val);
1410 break;
1412 #endif
1413 monitor_printf(mon, "\n");
1416 static void do_memory_save(Monitor *mon, const QDict *qdict, QObject **ret_data)
1418 FILE *f;
1419 uint32_t size = qdict_get_int(qdict, "size");
1420 const char *filename = qdict_get_str(qdict, "filename");
1421 target_long addr = qdict_get_int(qdict, "val");
1422 uint32_t l;
1423 CPUState *env;
1424 uint8_t buf[1024];
1426 env = mon_get_cpu();
1428 f = fopen(filename, "wb");
1429 if (!f) {
1430 qemu_error_new(QERR_OPEN_FILE_FAILED, filename);
1431 return;
1433 while (size != 0) {
1434 l = sizeof(buf);
1435 if (l > size)
1436 l = size;
1437 cpu_memory_rw_debug(env, addr, buf, l, 0);
1438 if (fwrite(buf, 1, l, f) != l) {
1439 monitor_printf(mon, "fwrite() error in do_memory_save\n");
1440 goto exit;
1442 addr += l;
1443 size -= l;
1445 exit:
1446 fclose(f);
1449 static void do_physical_memory_save(Monitor *mon, const QDict *qdict,
1450 QObject **ret_data)
1452 FILE *f;
1453 uint32_t l;
1454 uint8_t buf[1024];
1455 uint32_t size = qdict_get_int(qdict, "size");
1456 const char *filename = qdict_get_str(qdict, "filename");
1457 target_phys_addr_t addr = qdict_get_int(qdict, "val");
1459 f = fopen(filename, "wb");
1460 if (!f) {
1461 qemu_error_new(QERR_OPEN_FILE_FAILED, filename);
1462 return;
1464 while (size != 0) {
1465 l = sizeof(buf);
1466 if (l > size)
1467 l = size;
1468 cpu_physical_memory_rw(addr, buf, l, 0);
1469 if (fwrite(buf, 1, l, f) != l) {
1470 monitor_printf(mon, "fwrite() error in do_physical_memory_save\n");
1471 goto exit;
1473 fflush(f);
1474 addr += l;
1475 size -= l;
1477 exit:
1478 fclose(f);
1481 static void do_sum(Monitor *mon, const QDict *qdict)
1483 uint32_t addr;
1484 uint8_t buf[1];
1485 uint16_t sum;
1486 uint32_t start = qdict_get_int(qdict, "start");
1487 uint32_t size = qdict_get_int(qdict, "size");
1489 sum = 0;
1490 for(addr = start; addr < (start + size); addr++) {
1491 cpu_physical_memory_rw(addr, buf, 1, 0);
1492 /* BSD sum algorithm ('sum' Unix command) */
1493 sum = (sum >> 1) | (sum << 15);
1494 sum += buf[0];
1496 monitor_printf(mon, "%05d\n", sum);
1499 typedef struct {
1500 int keycode;
1501 const char *name;
1502 } KeyDef;
1504 static const KeyDef key_defs[] = {
1505 { 0x2a, "shift" },
1506 { 0x36, "shift_r" },
1508 { 0x38, "alt" },
1509 { 0xb8, "alt_r" },
1510 { 0x64, "altgr" },
1511 { 0xe4, "altgr_r" },
1512 { 0x1d, "ctrl" },
1513 { 0x9d, "ctrl_r" },
1515 { 0xdd, "menu" },
1517 { 0x01, "esc" },
1519 { 0x02, "1" },
1520 { 0x03, "2" },
1521 { 0x04, "3" },
1522 { 0x05, "4" },
1523 { 0x06, "5" },
1524 { 0x07, "6" },
1525 { 0x08, "7" },
1526 { 0x09, "8" },
1527 { 0x0a, "9" },
1528 { 0x0b, "0" },
1529 { 0x0c, "minus" },
1530 { 0x0d, "equal" },
1531 { 0x0e, "backspace" },
1533 { 0x0f, "tab" },
1534 { 0x10, "q" },
1535 { 0x11, "w" },
1536 { 0x12, "e" },
1537 { 0x13, "r" },
1538 { 0x14, "t" },
1539 { 0x15, "y" },
1540 { 0x16, "u" },
1541 { 0x17, "i" },
1542 { 0x18, "o" },
1543 { 0x19, "p" },
1545 { 0x1c, "ret" },
1547 { 0x1e, "a" },
1548 { 0x1f, "s" },
1549 { 0x20, "d" },
1550 { 0x21, "f" },
1551 { 0x22, "g" },
1552 { 0x23, "h" },
1553 { 0x24, "j" },
1554 { 0x25, "k" },
1555 { 0x26, "l" },
1557 { 0x2c, "z" },
1558 { 0x2d, "x" },
1559 { 0x2e, "c" },
1560 { 0x2f, "v" },
1561 { 0x30, "b" },
1562 { 0x31, "n" },
1563 { 0x32, "m" },
1564 { 0x33, "comma" },
1565 { 0x34, "dot" },
1566 { 0x35, "slash" },
1568 { 0x37, "asterisk" },
1570 { 0x39, "spc" },
1571 { 0x3a, "caps_lock" },
1572 { 0x3b, "f1" },
1573 { 0x3c, "f2" },
1574 { 0x3d, "f3" },
1575 { 0x3e, "f4" },
1576 { 0x3f, "f5" },
1577 { 0x40, "f6" },
1578 { 0x41, "f7" },
1579 { 0x42, "f8" },
1580 { 0x43, "f9" },
1581 { 0x44, "f10" },
1582 { 0x45, "num_lock" },
1583 { 0x46, "scroll_lock" },
1585 { 0xb5, "kp_divide" },
1586 { 0x37, "kp_multiply" },
1587 { 0x4a, "kp_subtract" },
1588 { 0x4e, "kp_add" },
1589 { 0x9c, "kp_enter" },
1590 { 0x53, "kp_decimal" },
1591 { 0x54, "sysrq" },
1593 { 0x52, "kp_0" },
1594 { 0x4f, "kp_1" },
1595 { 0x50, "kp_2" },
1596 { 0x51, "kp_3" },
1597 { 0x4b, "kp_4" },
1598 { 0x4c, "kp_5" },
1599 { 0x4d, "kp_6" },
1600 { 0x47, "kp_7" },
1601 { 0x48, "kp_8" },
1602 { 0x49, "kp_9" },
1604 { 0x56, "<" },
1606 { 0x57, "f11" },
1607 { 0x58, "f12" },
1609 { 0xb7, "print" },
1611 { 0xc7, "home" },
1612 { 0xc9, "pgup" },
1613 { 0xd1, "pgdn" },
1614 { 0xcf, "end" },
1616 { 0xcb, "left" },
1617 { 0xc8, "up" },
1618 { 0xd0, "down" },
1619 { 0xcd, "right" },
1621 { 0xd2, "insert" },
1622 { 0xd3, "delete" },
1623 #if defined(TARGET_SPARC) && !defined(TARGET_SPARC64)
1624 { 0xf0, "stop" },
1625 { 0xf1, "again" },
1626 { 0xf2, "props" },
1627 { 0xf3, "undo" },
1628 { 0xf4, "front" },
1629 { 0xf5, "copy" },
1630 { 0xf6, "open" },
1631 { 0xf7, "paste" },
1632 { 0xf8, "find" },
1633 { 0xf9, "cut" },
1634 { 0xfa, "lf" },
1635 { 0xfb, "help" },
1636 { 0xfc, "meta_l" },
1637 { 0xfd, "meta_r" },
1638 { 0xfe, "compose" },
1639 #endif
1640 { 0, NULL },
1643 static int get_keycode(const char *key)
1645 const KeyDef *p;
1646 char *endp;
1647 int ret;
1649 for(p = key_defs; p->name != NULL; p++) {
1650 if (!strcmp(key, p->name))
1651 return p->keycode;
1653 if (strstart(key, "0x", NULL)) {
1654 ret = strtoul(key, &endp, 0);
1655 if (*endp == '\0' && ret >= 0x01 && ret <= 0xff)
1656 return ret;
1658 return -1;
1661 #define MAX_KEYCODES 16
1662 static uint8_t keycodes[MAX_KEYCODES];
1663 static int nb_pending_keycodes;
1664 static QEMUTimer *key_timer;
1666 static void release_keys(void *opaque)
1668 int keycode;
1670 while (nb_pending_keycodes > 0) {
1671 nb_pending_keycodes--;
1672 keycode = keycodes[nb_pending_keycodes];
1673 if (keycode & 0x80)
1674 kbd_put_keycode(0xe0);
1675 kbd_put_keycode(keycode | 0x80);
1679 static void do_sendkey(Monitor *mon, const QDict *qdict)
1681 char keyname_buf[16];
1682 char *separator;
1683 int keyname_len, keycode, i;
1684 const char *string = qdict_get_str(qdict, "string");
1685 int has_hold_time = qdict_haskey(qdict, "hold_time");
1686 int hold_time = qdict_get_try_int(qdict, "hold_time", -1);
1688 if (nb_pending_keycodes > 0) {
1689 qemu_del_timer(key_timer);
1690 release_keys(NULL);
1692 if (!has_hold_time)
1693 hold_time = 100;
1694 i = 0;
1695 while (1) {
1696 separator = strchr(string, '-');
1697 keyname_len = separator ? separator - string : strlen(string);
1698 if (keyname_len > 0) {
1699 pstrcpy(keyname_buf, sizeof(keyname_buf), string);
1700 if (keyname_len > sizeof(keyname_buf) - 1) {
1701 monitor_printf(mon, "invalid key: '%s...'\n", keyname_buf);
1702 return;
1704 if (i == MAX_KEYCODES) {
1705 monitor_printf(mon, "too many keys\n");
1706 return;
1708 keyname_buf[keyname_len] = 0;
1709 keycode = get_keycode(keyname_buf);
1710 if (keycode < 0) {
1711 monitor_printf(mon, "unknown key: '%s'\n", keyname_buf);
1712 return;
1714 keycodes[i++] = keycode;
1716 if (!separator)
1717 break;
1718 string = separator + 1;
1720 nb_pending_keycodes = i;
1721 /* key down events */
1722 for (i = 0; i < nb_pending_keycodes; i++) {
1723 keycode = keycodes[i];
1724 if (keycode & 0x80)
1725 kbd_put_keycode(0xe0);
1726 kbd_put_keycode(keycode & 0x7f);
1728 /* delayed key up events */
1729 qemu_mod_timer(key_timer, qemu_get_clock(vm_clock) +
1730 muldiv64(get_ticks_per_sec(), hold_time, 1000));
1733 static int mouse_button_state;
1735 static void do_mouse_move(Monitor *mon, const QDict *qdict)
1737 int dx, dy, dz;
1738 const char *dx_str = qdict_get_str(qdict, "dx_str");
1739 const char *dy_str = qdict_get_str(qdict, "dy_str");
1740 const char *dz_str = qdict_get_try_str(qdict, "dz_str");
1741 dx = strtol(dx_str, NULL, 0);
1742 dy = strtol(dy_str, NULL, 0);
1743 dz = 0;
1744 if (dz_str)
1745 dz = strtol(dz_str, NULL, 0);
1746 kbd_mouse_event(dx, dy, dz, mouse_button_state);
1749 static void do_mouse_button(Monitor *mon, const QDict *qdict)
1751 int button_state = qdict_get_int(qdict, "button_state");
1752 mouse_button_state = button_state;
1753 kbd_mouse_event(0, 0, 0, mouse_button_state);
1756 static void do_ioport_read(Monitor *mon, const QDict *qdict)
1758 int size = qdict_get_int(qdict, "size");
1759 int addr = qdict_get_int(qdict, "addr");
1760 int has_index = qdict_haskey(qdict, "index");
1761 uint32_t val;
1762 int suffix;
1764 if (has_index) {
1765 int index = qdict_get_int(qdict, "index");
1766 cpu_outb(addr & IOPORTS_MASK, index & 0xff);
1767 addr++;
1769 addr &= 0xffff;
1771 switch(size) {
1772 default:
1773 case 1:
1774 val = cpu_inb(addr);
1775 suffix = 'b';
1776 break;
1777 case 2:
1778 val = cpu_inw(addr);
1779 suffix = 'w';
1780 break;
1781 case 4:
1782 val = cpu_inl(addr);
1783 suffix = 'l';
1784 break;
1786 monitor_printf(mon, "port%c[0x%04x] = %#0*x\n",
1787 suffix, addr, size * 2, val);
1790 static void do_ioport_write(Monitor *mon, const QDict *qdict)
1792 int size = qdict_get_int(qdict, "size");
1793 int addr = qdict_get_int(qdict, "addr");
1794 int val = qdict_get_int(qdict, "val");
1796 addr &= IOPORTS_MASK;
1798 switch (size) {
1799 default:
1800 case 1:
1801 cpu_outb(addr, val);
1802 break;
1803 case 2:
1804 cpu_outw(addr, val);
1805 break;
1806 case 4:
1807 cpu_outl(addr, val);
1808 break;
1812 static void do_boot_set(Monitor *mon, const QDict *qdict)
1814 int res;
1815 const char *bootdevice = qdict_get_str(qdict, "bootdevice");
1817 res = qemu_boot_set(bootdevice);
1818 if (res == 0) {
1819 monitor_printf(mon, "boot device list now set to %s\n", bootdevice);
1820 } else if (res > 0) {
1821 monitor_printf(mon, "setting boot device list failed\n");
1822 } else {
1823 monitor_printf(mon, "no function defined to set boot device list for "
1824 "this architecture\n");
1829 * do_system_reset(): Issue a machine reset
1831 static void do_system_reset(Monitor *mon, const QDict *qdict,
1832 QObject **ret_data)
1834 qemu_system_reset_request();
1838 * do_system_powerdown(): Issue a machine powerdown
1840 static void do_system_powerdown(Monitor *mon, const QDict *qdict,
1841 QObject **ret_data)
1843 qemu_system_powerdown_request();
1846 #if defined(TARGET_I386)
1847 static void print_pte(Monitor *mon, uint32_t addr, uint32_t pte, uint32_t mask)
1849 monitor_printf(mon, "%08x: %08x %c%c%c%c%c%c%c%c\n",
1850 addr,
1851 pte & mask,
1852 pte & PG_GLOBAL_MASK ? 'G' : '-',
1853 pte & PG_PSE_MASK ? 'P' : '-',
1854 pte & PG_DIRTY_MASK ? 'D' : '-',
1855 pte & PG_ACCESSED_MASK ? 'A' : '-',
1856 pte & PG_PCD_MASK ? 'C' : '-',
1857 pte & PG_PWT_MASK ? 'T' : '-',
1858 pte & PG_USER_MASK ? 'U' : '-',
1859 pte & PG_RW_MASK ? 'W' : '-');
1862 static void tlb_info(Monitor *mon)
1864 CPUState *env;
1865 int l1, l2;
1866 uint32_t pgd, pde, pte;
1868 env = mon_get_cpu();
1870 if (!(env->cr[0] & CR0_PG_MASK)) {
1871 monitor_printf(mon, "PG disabled\n");
1872 return;
1874 pgd = env->cr[3] & ~0xfff;
1875 for(l1 = 0; l1 < 1024; l1++) {
1876 cpu_physical_memory_read(pgd + l1 * 4, (uint8_t *)&pde, 4);
1877 pde = le32_to_cpu(pde);
1878 if (pde & PG_PRESENT_MASK) {
1879 if ((pde & PG_PSE_MASK) && (env->cr[4] & CR4_PSE_MASK)) {
1880 print_pte(mon, (l1 << 22), pde, ~((1 << 20) - 1));
1881 } else {
1882 for(l2 = 0; l2 < 1024; l2++) {
1883 cpu_physical_memory_read((pde & ~0xfff) + l2 * 4,
1884 (uint8_t *)&pte, 4);
1885 pte = le32_to_cpu(pte);
1886 if (pte & PG_PRESENT_MASK) {
1887 print_pte(mon, (l1 << 22) + (l2 << 12),
1888 pte & ~PG_PSE_MASK,
1889 ~0xfff);
1897 static void mem_print(Monitor *mon, uint32_t *pstart, int *plast_prot,
1898 uint32_t end, int prot)
1900 int prot1;
1901 prot1 = *plast_prot;
1902 if (prot != prot1) {
1903 if (*pstart != -1) {
1904 monitor_printf(mon, "%08x-%08x %08x %c%c%c\n",
1905 *pstart, end, end - *pstart,
1906 prot1 & PG_USER_MASK ? 'u' : '-',
1907 'r',
1908 prot1 & PG_RW_MASK ? 'w' : '-');
1910 if (prot != 0)
1911 *pstart = end;
1912 else
1913 *pstart = -1;
1914 *plast_prot = prot;
1918 static void mem_info(Monitor *mon)
1920 CPUState *env;
1921 int l1, l2, prot, last_prot;
1922 uint32_t pgd, pde, pte, start, end;
1924 env = mon_get_cpu();
1926 if (!(env->cr[0] & CR0_PG_MASK)) {
1927 monitor_printf(mon, "PG disabled\n");
1928 return;
1930 pgd = env->cr[3] & ~0xfff;
1931 last_prot = 0;
1932 start = -1;
1933 for(l1 = 0; l1 < 1024; l1++) {
1934 cpu_physical_memory_read(pgd + l1 * 4, (uint8_t *)&pde, 4);
1935 pde = le32_to_cpu(pde);
1936 end = l1 << 22;
1937 if (pde & PG_PRESENT_MASK) {
1938 if ((pde & PG_PSE_MASK) && (env->cr[4] & CR4_PSE_MASK)) {
1939 prot = pde & (PG_USER_MASK | PG_RW_MASK | PG_PRESENT_MASK);
1940 mem_print(mon, &start, &last_prot, end, prot);
1941 } else {
1942 for(l2 = 0; l2 < 1024; l2++) {
1943 cpu_physical_memory_read((pde & ~0xfff) + l2 * 4,
1944 (uint8_t *)&pte, 4);
1945 pte = le32_to_cpu(pte);
1946 end = (l1 << 22) + (l2 << 12);
1947 if (pte & PG_PRESENT_MASK) {
1948 prot = pte & (PG_USER_MASK | PG_RW_MASK | PG_PRESENT_MASK);
1949 } else {
1950 prot = 0;
1952 mem_print(mon, &start, &last_prot, end, prot);
1955 } else {
1956 prot = 0;
1957 mem_print(mon, &start, &last_prot, end, prot);
1961 #endif
1963 #if defined(TARGET_SH4)
1965 static void print_tlb(Monitor *mon, int idx, tlb_t *tlb)
1967 monitor_printf(mon, " tlb%i:\t"
1968 "asid=%hhu vpn=%x\tppn=%x\tsz=%hhu size=%u\t"
1969 "v=%hhu shared=%hhu cached=%hhu prot=%hhu "
1970 "dirty=%hhu writethrough=%hhu\n",
1971 idx,
1972 tlb->asid, tlb->vpn, tlb->ppn, tlb->sz, tlb->size,
1973 tlb->v, tlb->sh, tlb->c, tlb->pr,
1974 tlb->d, tlb->wt);
1977 static void tlb_info(Monitor *mon)
1979 CPUState *env = mon_get_cpu();
1980 int i;
1982 monitor_printf (mon, "ITLB:\n");
1983 for (i = 0 ; i < ITLB_SIZE ; i++)
1984 print_tlb (mon, i, &env->itlb[i]);
1985 monitor_printf (mon, "UTLB:\n");
1986 for (i = 0 ; i < UTLB_SIZE ; i++)
1987 print_tlb (mon, i, &env->utlb[i]);
1990 #endif
1992 static void do_info_kvm_print(Monitor *mon, const QObject *data)
1994 QDict *qdict;
1996 qdict = qobject_to_qdict(data);
1998 monitor_printf(mon, "kvm support: ");
1999 if (qdict_get_bool(qdict, "present")) {
2000 monitor_printf(mon, "%s\n", qdict_get_bool(qdict, "enabled") ?
2001 "enabled" : "disabled");
2002 } else {
2003 monitor_printf(mon, "not compiled\n");
2008 * do_info_kvm(): Show KVM information
2010 * Return a QDict with the following information:
2012 * - "enabled": true if KVM support is enabled, false otherwise
2013 * - "present": true if QEMU has KVM support, false otherwise
2015 * Example:
2017 * { "enabled": true, "present": true }
2019 static void do_info_kvm(Monitor *mon, QObject **ret_data)
2021 #ifdef CONFIG_KVM
2022 *ret_data = qobject_from_jsonf("{ 'enabled': %i, 'present': true }",
2023 kvm_enabled());
2024 #else
2025 *ret_data = qobject_from_jsonf("{ 'enabled': false, 'present': false }");
2026 #endif
2029 static void do_info_numa(Monitor *mon)
2031 int i;
2032 CPUState *env;
2034 monitor_printf(mon, "%d nodes\n", nb_numa_nodes);
2035 for (i = 0; i < nb_numa_nodes; i++) {
2036 monitor_printf(mon, "node %d cpus:", i);
2037 for (env = first_cpu; env != NULL; env = env->next_cpu) {
2038 if (env->numa_node == i) {
2039 monitor_printf(mon, " %d", env->cpu_index);
2042 monitor_printf(mon, "\n");
2043 monitor_printf(mon, "node %d size: %" PRId64 " MB\n", i,
2044 node_mem[i] >> 20);
2048 #ifdef CONFIG_PROFILER
2050 int64_t qemu_time;
2051 int64_t dev_time;
2053 static void do_info_profile(Monitor *mon)
2055 int64_t total;
2056 total = qemu_time;
2057 if (total == 0)
2058 total = 1;
2059 monitor_printf(mon, "async time %" PRId64 " (%0.3f)\n",
2060 dev_time, dev_time / (double)get_ticks_per_sec());
2061 monitor_printf(mon, "qemu time %" PRId64 " (%0.3f)\n",
2062 qemu_time, qemu_time / (double)get_ticks_per_sec());
2063 qemu_time = 0;
2064 dev_time = 0;
2066 #else
2067 static void do_info_profile(Monitor *mon)
2069 monitor_printf(mon, "Internal profiler not compiled\n");
2071 #endif
2073 /* Capture support */
2074 static QLIST_HEAD (capture_list_head, CaptureState) capture_head;
2076 static void do_info_capture(Monitor *mon)
2078 int i;
2079 CaptureState *s;
2081 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
2082 monitor_printf(mon, "[%d]: ", i);
2083 s->ops.info (s->opaque);
2087 #ifdef HAS_AUDIO
2088 static void do_stop_capture(Monitor *mon, const QDict *qdict)
2090 int i;
2091 int n = qdict_get_int(qdict, "n");
2092 CaptureState *s;
2094 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
2095 if (i == n) {
2096 s->ops.destroy (s->opaque);
2097 QLIST_REMOVE (s, entries);
2098 qemu_free (s);
2099 return;
2104 static void do_wav_capture(Monitor *mon, const QDict *qdict)
2106 const char *path = qdict_get_str(qdict, "path");
2107 int has_freq = qdict_haskey(qdict, "freq");
2108 int freq = qdict_get_try_int(qdict, "freq", -1);
2109 int has_bits = qdict_haskey(qdict, "bits");
2110 int bits = qdict_get_try_int(qdict, "bits", -1);
2111 int has_channels = qdict_haskey(qdict, "nchannels");
2112 int nchannels = qdict_get_try_int(qdict, "nchannels", -1);
2113 CaptureState *s;
2115 s = qemu_mallocz (sizeof (*s));
2117 freq = has_freq ? freq : 44100;
2118 bits = has_bits ? bits : 16;
2119 nchannels = has_channels ? nchannels : 2;
2121 if (wav_start_capture (s, path, freq, bits, nchannels)) {
2122 monitor_printf(mon, "Faied to add wave capture\n");
2123 qemu_free (s);
2125 QLIST_INSERT_HEAD (&capture_head, s, entries);
2127 #endif
2129 #if defined(TARGET_I386)
2130 static void do_inject_nmi(Monitor *mon, const QDict *qdict)
2132 CPUState *env;
2133 int cpu_index = qdict_get_int(qdict, "cpu_index");
2135 for (env = first_cpu; env != NULL; env = env->next_cpu)
2136 if (env->cpu_index == cpu_index) {
2137 cpu_interrupt(env, CPU_INTERRUPT_NMI);
2138 break;
2141 #endif
2143 static void do_info_status_print(Monitor *mon, const QObject *data)
2145 QDict *qdict;
2147 qdict = qobject_to_qdict(data);
2149 monitor_printf(mon, "VM status: ");
2150 if (qdict_get_bool(qdict, "running")) {
2151 monitor_printf(mon, "running");
2152 if (qdict_get_bool(qdict, "singlestep")) {
2153 monitor_printf(mon, " (single step mode)");
2155 } else {
2156 monitor_printf(mon, "paused");
2159 monitor_printf(mon, "\n");
2163 * do_info_status(): VM status
2165 * Return a QDict with the following information:
2167 * - "running": true if the VM is running, or false if it is paused
2168 * - "singlestep": true if the VM is in single step mode, false otherwise
2170 * Example:
2172 * { "running": true, "singlestep": false }
2174 static void do_info_status(Monitor *mon, QObject **ret_data)
2176 *ret_data = qobject_from_jsonf("{ 'running': %i, 'singlestep': %i }",
2177 vm_running, singlestep);
2180 static void print_balloon_stat(const char *key, QObject *obj, void *opaque)
2182 Monitor *mon = opaque;
2184 if (strcmp(key, "actual"))
2185 monitor_printf(mon, ",%s=%" PRId64, key,
2186 qint_get_int(qobject_to_qint(obj)));
2189 static void monitor_print_balloon(Monitor *mon, const QObject *data)
2191 QDict *qdict;
2193 qdict = qobject_to_qdict(data);
2194 if (!qdict_haskey(qdict, "actual"))
2195 return;
2197 monitor_printf(mon, "balloon: actual=%" PRId64,
2198 qdict_get_int(qdict, "actual") >> 20);
2199 qdict_iter(qdict, print_balloon_stat, mon);
2200 monitor_printf(mon, "\n");
2204 * do_info_balloon(): Balloon information
2206 * Make an asynchronous request for balloon info. When the request completes
2207 * a QDict will be returned according to the following specification:
2209 * - "actual": current balloon value in bytes
2210 * The following fields may or may not be present:
2211 * - "mem_swapped_in": Amount of memory swapped in (bytes)
2212 * - "mem_swapped_out": Amount of memory swapped out (bytes)
2213 * - "major_page_faults": Number of major faults
2214 * - "minor_page_faults": Number of minor faults
2215 * - "free_mem": Total amount of free and unused memory (bytes)
2216 * - "total_mem": Total amount of available memory (bytes)
2218 * Example:
2220 * { "actual": 1073741824, "mem_swapped_in": 0, "mem_swapped_out": 0,
2221 * "major_page_faults": 142, "minor_page_faults": 239245,
2222 * "free_mem": 1014185984, "total_mem": 1044668416 }
2224 static int do_info_balloon(Monitor *mon, MonitorCompletion cb, void *opaque)
2226 int ret;
2228 if (kvm_enabled() && !kvm_has_sync_mmu()) {
2229 qemu_error_new(QERR_KVM_MISSING_CAP, "synchronous MMU", "balloon");
2230 return -1;
2233 ret = qemu_balloon_status(cb, opaque);
2234 if (!ret) {
2235 qemu_error_new(QERR_DEVICE_NOT_ACTIVE, "balloon");
2236 return -1;
2239 return 0;
2243 * do_balloon(): Request VM to change its memory allocation
2245 static int do_balloon(Monitor *mon, const QDict *params,
2246 MonitorCompletion cb, void *opaque)
2248 int ret;
2250 if (kvm_enabled() && !kvm_has_sync_mmu()) {
2251 qemu_error_new(QERR_KVM_MISSING_CAP, "synchronous MMU", "balloon");
2252 return -1;
2255 ret = qemu_balloon(qdict_get_int(params, "value"), cb, opaque);
2256 if (ret == 0) {
2257 qemu_error_new(QERR_DEVICE_NOT_ACTIVE, "balloon");
2258 return -1;
2261 return 0;
2264 static qemu_acl *find_acl(Monitor *mon, const char *name)
2266 qemu_acl *acl = qemu_acl_find(name);
2268 if (!acl) {
2269 monitor_printf(mon, "acl: unknown list '%s'\n", name);
2271 return acl;
2274 static void do_acl_show(Monitor *mon, const QDict *qdict)
2276 const char *aclname = qdict_get_str(qdict, "aclname");
2277 qemu_acl *acl = find_acl(mon, aclname);
2278 qemu_acl_entry *entry;
2279 int i = 0;
2281 if (acl) {
2282 monitor_printf(mon, "policy: %s\n",
2283 acl->defaultDeny ? "deny" : "allow");
2284 QTAILQ_FOREACH(entry, &acl->entries, next) {
2285 i++;
2286 monitor_printf(mon, "%d: %s %s\n", i,
2287 entry->deny ? "deny" : "allow", entry->match);
2292 static void do_acl_reset(Monitor *mon, const QDict *qdict)
2294 const char *aclname = qdict_get_str(qdict, "aclname");
2295 qemu_acl *acl = find_acl(mon, aclname);
2297 if (acl) {
2298 qemu_acl_reset(acl);
2299 monitor_printf(mon, "acl: removed all rules\n");
2303 static void do_acl_policy(Monitor *mon, const QDict *qdict)
2305 const char *aclname = qdict_get_str(qdict, "aclname");
2306 const char *policy = qdict_get_str(qdict, "policy");
2307 qemu_acl *acl = find_acl(mon, aclname);
2309 if (acl) {
2310 if (strcmp(policy, "allow") == 0) {
2311 acl->defaultDeny = 0;
2312 monitor_printf(mon, "acl: policy set to 'allow'\n");
2313 } else if (strcmp(policy, "deny") == 0) {
2314 acl->defaultDeny = 1;
2315 monitor_printf(mon, "acl: policy set to 'deny'\n");
2316 } else {
2317 monitor_printf(mon, "acl: unknown policy '%s', "
2318 "expected 'deny' or 'allow'\n", policy);
2323 static void do_acl_add(Monitor *mon, const QDict *qdict)
2325 const char *aclname = qdict_get_str(qdict, "aclname");
2326 const char *match = qdict_get_str(qdict, "match");
2327 const char *policy = qdict_get_str(qdict, "policy");
2328 int has_index = qdict_haskey(qdict, "index");
2329 int index = qdict_get_try_int(qdict, "index", -1);
2330 qemu_acl *acl = find_acl(mon, aclname);
2331 int deny, ret;
2333 if (acl) {
2334 if (strcmp(policy, "allow") == 0) {
2335 deny = 0;
2336 } else if (strcmp(policy, "deny") == 0) {
2337 deny = 1;
2338 } else {
2339 monitor_printf(mon, "acl: unknown policy '%s', "
2340 "expected 'deny' or 'allow'\n", policy);
2341 return;
2343 if (has_index)
2344 ret = qemu_acl_insert(acl, deny, match, index);
2345 else
2346 ret = qemu_acl_append(acl, deny, match);
2347 if (ret < 0)
2348 monitor_printf(mon, "acl: unable to add acl entry\n");
2349 else
2350 monitor_printf(mon, "acl: added rule at position %d\n", ret);
2354 static void do_acl_remove(Monitor *mon, const QDict *qdict)
2356 const char *aclname = qdict_get_str(qdict, "aclname");
2357 const char *match = qdict_get_str(qdict, "match");
2358 qemu_acl *acl = find_acl(mon, aclname);
2359 int ret;
2361 if (acl) {
2362 ret = qemu_acl_remove(acl, match);
2363 if (ret < 0)
2364 monitor_printf(mon, "acl: no matching acl entry\n");
2365 else
2366 monitor_printf(mon, "acl: removed rule at position %d\n", ret);
2370 #if defined(TARGET_I386)
2371 static void do_inject_mce(Monitor *mon, const QDict *qdict)
2373 CPUState *cenv;
2374 int cpu_index = qdict_get_int(qdict, "cpu_index");
2375 int bank = qdict_get_int(qdict, "bank");
2376 uint64_t status = qdict_get_int(qdict, "status");
2377 uint64_t mcg_status = qdict_get_int(qdict, "mcg_status");
2378 uint64_t addr = qdict_get_int(qdict, "addr");
2379 uint64_t misc = qdict_get_int(qdict, "misc");
2381 for (cenv = first_cpu; cenv != NULL; cenv = cenv->next_cpu)
2382 if (cenv->cpu_index == cpu_index && cenv->mcg_cap) {
2383 cpu_inject_x86_mce(cenv, bank, status, mcg_status, addr, misc);
2384 break;
2387 #endif
2389 static void do_getfd(Monitor *mon, const QDict *qdict, QObject **ret_data)
2391 const char *fdname = qdict_get_str(qdict, "fdname");
2392 mon_fd_t *monfd;
2393 int fd;
2395 fd = qemu_chr_get_msgfd(mon->chr);
2396 if (fd == -1) {
2397 qemu_error_new(QERR_FD_NOT_SUPPLIED);
2398 return;
2401 if (qemu_isdigit(fdname[0])) {
2402 qemu_error_new(QERR_INVALID_PARAMETER, "fdname");
2403 return;
2406 fd = dup(fd);
2407 if (fd == -1) {
2408 if (errno == EMFILE)
2409 qemu_error_new(QERR_TOO_MANY_FILES);
2410 else
2411 qemu_error_new(QERR_UNDEFINED_ERROR);
2412 return;
2415 QLIST_FOREACH(monfd, &mon->fds, next) {
2416 if (strcmp(monfd->name, fdname) != 0) {
2417 continue;
2420 close(monfd->fd);
2421 monfd->fd = fd;
2422 return;
2425 monfd = qemu_mallocz(sizeof(mon_fd_t));
2426 monfd->name = qemu_strdup(fdname);
2427 monfd->fd = fd;
2429 QLIST_INSERT_HEAD(&mon->fds, monfd, next);
2432 static void do_closefd(Monitor *mon, const QDict *qdict, QObject **ret_data)
2434 const char *fdname = qdict_get_str(qdict, "fdname");
2435 mon_fd_t *monfd;
2437 QLIST_FOREACH(monfd, &mon->fds, next) {
2438 if (strcmp(monfd->name, fdname) != 0) {
2439 continue;
2442 QLIST_REMOVE(monfd, next);
2443 close(monfd->fd);
2444 qemu_free(monfd->name);
2445 qemu_free(monfd);
2446 return;
2449 qemu_error_new(QERR_FD_NOT_FOUND, fdname);
2452 static void do_loadvm(Monitor *mon, const QDict *qdict)
2454 int saved_vm_running = vm_running;
2455 const char *name = qdict_get_str(qdict, "name");
2457 vm_stop(0);
2459 if (load_vmstate(mon, name) >= 0 && saved_vm_running)
2460 vm_start();
2463 int monitor_get_fd(Monitor *mon, const char *fdname)
2465 mon_fd_t *monfd;
2467 QLIST_FOREACH(monfd, &mon->fds, next) {
2468 int fd;
2470 if (strcmp(monfd->name, fdname) != 0) {
2471 continue;
2474 fd = monfd->fd;
2476 /* caller takes ownership of fd */
2477 QLIST_REMOVE(monfd, next);
2478 qemu_free(monfd->name);
2479 qemu_free(monfd);
2481 return fd;
2484 return -1;
2487 static const mon_cmd_t mon_cmds[] = {
2488 #include "qemu-monitor.h"
2489 { NULL, NULL, },
2492 /* Please update qemu-monitor.hx when adding or changing commands */
2493 static const mon_cmd_t info_cmds[] = {
2495 .name = "version",
2496 .args_type = "",
2497 .params = "",
2498 .help = "show the version of QEMU",
2499 .user_print = do_info_version_print,
2500 .mhandler.info_new = do_info_version,
2503 .name = "commands",
2504 .args_type = "",
2505 .params = "",
2506 .help = "list QMP available commands",
2507 .user_print = monitor_user_noop,
2508 .mhandler.info_new = do_info_commands,
2511 .name = "network",
2512 .args_type = "",
2513 .params = "",
2514 .help = "show the network state",
2515 .mhandler.info = do_info_network,
2518 .name = "chardev",
2519 .args_type = "",
2520 .params = "",
2521 .help = "show the character devices",
2522 .user_print = qemu_chr_info_print,
2523 .mhandler.info_new = qemu_chr_info,
2526 .name = "block",
2527 .args_type = "",
2528 .params = "",
2529 .help = "show the block devices",
2530 .user_print = bdrv_info_print,
2531 .mhandler.info_new = bdrv_info,
2534 .name = "blockstats",
2535 .args_type = "",
2536 .params = "",
2537 .help = "show block device statistics",
2538 .user_print = bdrv_stats_print,
2539 .mhandler.info_new = bdrv_info_stats,
2542 .name = "registers",
2543 .args_type = "",
2544 .params = "",
2545 .help = "show the cpu registers",
2546 .mhandler.info = do_info_registers,
2549 .name = "cpus",
2550 .args_type = "",
2551 .params = "",
2552 .help = "show infos for each CPU",
2553 .user_print = monitor_print_cpus,
2554 .mhandler.info_new = do_info_cpus,
2557 .name = "history",
2558 .args_type = "",
2559 .params = "",
2560 .help = "show the command line history",
2561 .mhandler.info = do_info_history,
2564 .name = "irq",
2565 .args_type = "",
2566 .params = "",
2567 .help = "show the interrupts statistics (if available)",
2568 .mhandler.info = irq_info,
2571 .name = "pic",
2572 .args_type = "",
2573 .params = "",
2574 .help = "show i8259 (PIC) state",
2575 .mhandler.info = pic_info,
2578 .name = "pci",
2579 .args_type = "",
2580 .params = "",
2581 .help = "show PCI info",
2582 .user_print = do_pci_info_print,
2583 .mhandler.info_new = do_pci_info,
2585 #if defined(TARGET_I386) || defined(TARGET_SH4)
2587 .name = "tlb",
2588 .args_type = "",
2589 .params = "",
2590 .help = "show virtual to physical memory mappings",
2591 .mhandler.info = tlb_info,
2593 #endif
2594 #if defined(TARGET_I386)
2596 .name = "mem",
2597 .args_type = "",
2598 .params = "",
2599 .help = "show the active virtual memory mappings",
2600 .mhandler.info = mem_info,
2603 .name = "hpet",
2604 .args_type = "",
2605 .params = "",
2606 .help = "show state of HPET",
2607 .user_print = do_info_hpet_print,
2608 .mhandler.info_new = do_info_hpet,
2610 #endif
2612 .name = "jit",
2613 .args_type = "",
2614 .params = "",
2615 .help = "show dynamic compiler info",
2616 .mhandler.info = do_info_jit,
2619 .name = "kvm",
2620 .args_type = "",
2621 .params = "",
2622 .help = "show KVM information",
2623 .user_print = do_info_kvm_print,
2624 .mhandler.info_new = do_info_kvm,
2627 .name = "numa",
2628 .args_type = "",
2629 .params = "",
2630 .help = "show NUMA information",
2631 .mhandler.info = do_info_numa,
2634 .name = "usb",
2635 .args_type = "",
2636 .params = "",
2637 .help = "show guest USB devices",
2638 .mhandler.info = usb_info,
2641 .name = "usbhost",
2642 .args_type = "",
2643 .params = "",
2644 .help = "show host USB devices",
2645 .mhandler.info = usb_host_info,
2648 .name = "profile",
2649 .args_type = "",
2650 .params = "",
2651 .help = "show profiling information",
2652 .mhandler.info = do_info_profile,
2655 .name = "capture",
2656 .args_type = "",
2657 .params = "",
2658 .help = "show capture information",
2659 .mhandler.info = do_info_capture,
2662 .name = "snapshots",
2663 .args_type = "",
2664 .params = "",
2665 .help = "show the currently saved VM snapshots",
2666 .mhandler.info = do_info_snapshots,
2669 .name = "status",
2670 .args_type = "",
2671 .params = "",
2672 .help = "show the current VM status (running|paused)",
2673 .user_print = do_info_status_print,
2674 .mhandler.info_new = do_info_status,
2677 .name = "pcmcia",
2678 .args_type = "",
2679 .params = "",
2680 .help = "show guest PCMCIA status",
2681 .mhandler.info = pcmcia_info,
2684 .name = "mice",
2685 .args_type = "",
2686 .params = "",
2687 .help = "show which guest mouse is receiving events",
2688 .user_print = do_info_mice_print,
2689 .mhandler.info_new = do_info_mice,
2692 .name = "vnc",
2693 .args_type = "",
2694 .params = "",
2695 .help = "show the vnc server status",
2696 .user_print = do_info_vnc_print,
2697 .mhandler.info_new = do_info_vnc,
2700 .name = "name",
2701 .args_type = "",
2702 .params = "",
2703 .help = "show the current VM name",
2704 .user_print = do_info_name_print,
2705 .mhandler.info_new = do_info_name,
2708 .name = "uuid",
2709 .args_type = "",
2710 .params = "",
2711 .help = "show the current VM UUID",
2712 .user_print = do_info_uuid_print,
2713 .mhandler.info_new = do_info_uuid,
2715 #if defined(TARGET_PPC)
2717 .name = "cpustats",
2718 .args_type = "",
2719 .params = "",
2720 .help = "show CPU statistics",
2721 .mhandler.info = do_info_cpu_stats,
2723 #endif
2724 #if defined(CONFIG_SLIRP)
2726 .name = "usernet",
2727 .args_type = "",
2728 .params = "",
2729 .help = "show user network stack connection states",
2730 .mhandler.info = do_info_usernet,
2732 #endif
2734 .name = "migrate",
2735 .args_type = "",
2736 .params = "",
2737 .help = "show migration status",
2738 .user_print = do_info_migrate_print,
2739 .mhandler.info_new = do_info_migrate,
2742 .name = "balloon",
2743 .args_type = "",
2744 .params = "",
2745 .help = "show balloon information",
2746 .user_print = monitor_print_balloon,
2747 .mhandler.info_async = do_info_balloon,
2748 .async = 1,
2751 .name = "qtree",
2752 .args_type = "",
2753 .params = "",
2754 .help = "show device tree",
2755 .mhandler.info = do_info_qtree,
2758 .name = "qdm",
2759 .args_type = "",
2760 .params = "",
2761 .help = "show qdev device model list",
2762 .mhandler.info = do_info_qdm,
2765 .name = "roms",
2766 .args_type = "",
2767 .params = "",
2768 .help = "show roms",
2769 .mhandler.info = do_info_roms,
2772 .name = NULL,
2776 /*******************************************************************/
2778 static const char *pch;
2779 static jmp_buf expr_env;
2781 #define MD_TLONG 0
2782 #define MD_I32 1
2784 typedef struct MonitorDef {
2785 const char *name;
2786 int offset;
2787 target_long (*get_value)(const struct MonitorDef *md, int val);
2788 int type;
2789 } MonitorDef;
2791 #if defined(TARGET_I386)
2792 static target_long monitor_get_pc (const struct MonitorDef *md, int val)
2794 CPUState *env = mon_get_cpu();
2795 return env->eip + env->segs[R_CS].base;
2797 #endif
2799 #if defined(TARGET_PPC)
2800 static target_long monitor_get_ccr (const struct MonitorDef *md, int val)
2802 CPUState *env = mon_get_cpu();
2803 unsigned int u;
2804 int i;
2806 u = 0;
2807 for (i = 0; i < 8; i++)
2808 u |= env->crf[i] << (32 - (4 * i));
2810 return u;
2813 static target_long monitor_get_msr (const struct MonitorDef *md, int val)
2815 CPUState *env = mon_get_cpu();
2816 return env->msr;
2819 static target_long monitor_get_xer (const struct MonitorDef *md, int val)
2821 CPUState *env = mon_get_cpu();
2822 return env->xer;
2825 static target_long monitor_get_decr (const struct MonitorDef *md, int val)
2827 CPUState *env = mon_get_cpu();
2828 return cpu_ppc_load_decr(env);
2831 static target_long monitor_get_tbu (const struct MonitorDef *md, int val)
2833 CPUState *env = mon_get_cpu();
2834 return cpu_ppc_load_tbu(env);
2837 static target_long monitor_get_tbl (const struct MonitorDef *md, int val)
2839 CPUState *env = mon_get_cpu();
2840 return cpu_ppc_load_tbl(env);
2842 #endif
2844 #if defined(TARGET_SPARC)
2845 #ifndef TARGET_SPARC64
2846 static target_long monitor_get_psr (const struct MonitorDef *md, int val)
2848 CPUState *env = mon_get_cpu();
2849 return GET_PSR(env);
2851 #endif
2853 static target_long monitor_get_reg(const struct MonitorDef *md, int val)
2855 CPUState *env = mon_get_cpu();
2856 return env->regwptr[val];
2858 #endif
2860 static const MonitorDef monitor_defs[] = {
2861 #ifdef TARGET_I386
2863 #define SEG(name, seg) \
2864 { name, offsetof(CPUState, segs[seg].selector), NULL, MD_I32 },\
2865 { name ".base", offsetof(CPUState, segs[seg].base) },\
2866 { name ".limit", offsetof(CPUState, segs[seg].limit), NULL, MD_I32 },
2868 { "eax", offsetof(CPUState, regs[0]) },
2869 { "ecx", offsetof(CPUState, regs[1]) },
2870 { "edx", offsetof(CPUState, regs[2]) },
2871 { "ebx", offsetof(CPUState, regs[3]) },
2872 { "esp|sp", offsetof(CPUState, regs[4]) },
2873 { "ebp|fp", offsetof(CPUState, regs[5]) },
2874 { "esi", offsetof(CPUState, regs[6]) },
2875 { "edi", offsetof(CPUState, regs[7]) },
2876 #ifdef TARGET_X86_64
2877 { "r8", offsetof(CPUState, regs[8]) },
2878 { "r9", offsetof(CPUState, regs[9]) },
2879 { "r10", offsetof(CPUState, regs[10]) },
2880 { "r11", offsetof(CPUState, regs[11]) },
2881 { "r12", offsetof(CPUState, regs[12]) },
2882 { "r13", offsetof(CPUState, regs[13]) },
2883 { "r14", offsetof(CPUState, regs[14]) },
2884 { "r15", offsetof(CPUState, regs[15]) },
2885 #endif
2886 { "eflags", offsetof(CPUState, eflags) },
2887 { "eip", offsetof(CPUState, eip) },
2888 SEG("cs", R_CS)
2889 SEG("ds", R_DS)
2890 SEG("es", R_ES)
2891 SEG("ss", R_SS)
2892 SEG("fs", R_FS)
2893 SEG("gs", R_GS)
2894 { "pc", 0, monitor_get_pc, },
2895 #elif defined(TARGET_PPC)
2896 /* General purpose registers */
2897 { "r0", offsetof(CPUState, gpr[0]) },
2898 { "r1", offsetof(CPUState, gpr[1]) },
2899 { "r2", offsetof(CPUState, gpr[2]) },
2900 { "r3", offsetof(CPUState, gpr[3]) },
2901 { "r4", offsetof(CPUState, gpr[4]) },
2902 { "r5", offsetof(CPUState, gpr[5]) },
2903 { "r6", offsetof(CPUState, gpr[6]) },
2904 { "r7", offsetof(CPUState, gpr[7]) },
2905 { "r8", offsetof(CPUState, gpr[8]) },
2906 { "r9", offsetof(CPUState, gpr[9]) },
2907 { "r10", offsetof(CPUState, gpr[10]) },
2908 { "r11", offsetof(CPUState, gpr[11]) },
2909 { "r12", offsetof(CPUState, gpr[12]) },
2910 { "r13", offsetof(CPUState, gpr[13]) },
2911 { "r14", offsetof(CPUState, gpr[14]) },
2912 { "r15", offsetof(CPUState, gpr[15]) },
2913 { "r16", offsetof(CPUState, gpr[16]) },
2914 { "r17", offsetof(CPUState, gpr[17]) },
2915 { "r18", offsetof(CPUState, gpr[18]) },
2916 { "r19", offsetof(CPUState, gpr[19]) },
2917 { "r20", offsetof(CPUState, gpr[20]) },
2918 { "r21", offsetof(CPUState, gpr[21]) },
2919 { "r22", offsetof(CPUState, gpr[22]) },
2920 { "r23", offsetof(CPUState, gpr[23]) },
2921 { "r24", offsetof(CPUState, gpr[24]) },
2922 { "r25", offsetof(CPUState, gpr[25]) },
2923 { "r26", offsetof(CPUState, gpr[26]) },
2924 { "r27", offsetof(CPUState, gpr[27]) },
2925 { "r28", offsetof(CPUState, gpr[28]) },
2926 { "r29", offsetof(CPUState, gpr[29]) },
2927 { "r30", offsetof(CPUState, gpr[30]) },
2928 { "r31", offsetof(CPUState, gpr[31]) },
2929 /* Floating point registers */
2930 { "f0", offsetof(CPUState, fpr[0]) },
2931 { "f1", offsetof(CPUState, fpr[1]) },
2932 { "f2", offsetof(CPUState, fpr[2]) },
2933 { "f3", offsetof(CPUState, fpr[3]) },
2934 { "f4", offsetof(CPUState, fpr[4]) },
2935 { "f5", offsetof(CPUState, fpr[5]) },
2936 { "f6", offsetof(CPUState, fpr[6]) },
2937 { "f7", offsetof(CPUState, fpr[7]) },
2938 { "f8", offsetof(CPUState, fpr[8]) },
2939 { "f9", offsetof(CPUState, fpr[9]) },
2940 { "f10", offsetof(CPUState, fpr[10]) },
2941 { "f11", offsetof(CPUState, fpr[11]) },
2942 { "f12", offsetof(CPUState, fpr[12]) },
2943 { "f13", offsetof(CPUState, fpr[13]) },
2944 { "f14", offsetof(CPUState, fpr[14]) },
2945 { "f15", offsetof(CPUState, fpr[15]) },
2946 { "f16", offsetof(CPUState, fpr[16]) },
2947 { "f17", offsetof(CPUState, fpr[17]) },
2948 { "f18", offsetof(CPUState, fpr[18]) },
2949 { "f19", offsetof(CPUState, fpr[19]) },
2950 { "f20", offsetof(CPUState, fpr[20]) },
2951 { "f21", offsetof(CPUState, fpr[21]) },
2952 { "f22", offsetof(CPUState, fpr[22]) },
2953 { "f23", offsetof(CPUState, fpr[23]) },
2954 { "f24", offsetof(CPUState, fpr[24]) },
2955 { "f25", offsetof(CPUState, fpr[25]) },
2956 { "f26", offsetof(CPUState, fpr[26]) },
2957 { "f27", offsetof(CPUState, fpr[27]) },
2958 { "f28", offsetof(CPUState, fpr[28]) },
2959 { "f29", offsetof(CPUState, fpr[29]) },
2960 { "f30", offsetof(CPUState, fpr[30]) },
2961 { "f31", offsetof(CPUState, fpr[31]) },
2962 { "fpscr", offsetof(CPUState, fpscr) },
2963 /* Next instruction pointer */
2964 { "nip|pc", offsetof(CPUState, nip) },
2965 { "lr", offsetof(CPUState, lr) },
2966 { "ctr", offsetof(CPUState, ctr) },
2967 { "decr", 0, &monitor_get_decr, },
2968 { "ccr", 0, &monitor_get_ccr, },
2969 /* Machine state register */
2970 { "msr", 0, &monitor_get_msr, },
2971 { "xer", 0, &monitor_get_xer, },
2972 { "tbu", 0, &monitor_get_tbu, },
2973 { "tbl", 0, &monitor_get_tbl, },
2974 #if defined(TARGET_PPC64)
2975 /* Address space register */
2976 { "asr", offsetof(CPUState, asr) },
2977 #endif
2978 /* Segment registers */
2979 { "sdr1", offsetof(CPUState, sdr1) },
2980 { "sr0", offsetof(CPUState, sr[0]) },
2981 { "sr1", offsetof(CPUState, sr[1]) },
2982 { "sr2", offsetof(CPUState, sr[2]) },
2983 { "sr3", offsetof(CPUState, sr[3]) },
2984 { "sr4", offsetof(CPUState, sr[4]) },
2985 { "sr5", offsetof(CPUState, sr[5]) },
2986 { "sr6", offsetof(CPUState, sr[6]) },
2987 { "sr7", offsetof(CPUState, sr[7]) },
2988 { "sr8", offsetof(CPUState, sr[8]) },
2989 { "sr9", offsetof(CPUState, sr[9]) },
2990 { "sr10", offsetof(CPUState, sr[10]) },
2991 { "sr11", offsetof(CPUState, sr[11]) },
2992 { "sr12", offsetof(CPUState, sr[12]) },
2993 { "sr13", offsetof(CPUState, sr[13]) },
2994 { "sr14", offsetof(CPUState, sr[14]) },
2995 { "sr15", offsetof(CPUState, sr[15]) },
2996 /* Too lazy to put BATs and SPRs ... */
2997 #elif defined(TARGET_SPARC)
2998 { "g0", offsetof(CPUState, gregs[0]) },
2999 { "g1", offsetof(CPUState, gregs[1]) },
3000 { "g2", offsetof(CPUState, gregs[2]) },
3001 { "g3", offsetof(CPUState, gregs[3]) },
3002 { "g4", offsetof(CPUState, gregs[4]) },
3003 { "g5", offsetof(CPUState, gregs[5]) },
3004 { "g6", offsetof(CPUState, gregs[6]) },
3005 { "g7", offsetof(CPUState, gregs[7]) },
3006 { "o0", 0, monitor_get_reg },
3007 { "o1", 1, monitor_get_reg },
3008 { "o2", 2, monitor_get_reg },
3009 { "o3", 3, monitor_get_reg },
3010 { "o4", 4, monitor_get_reg },
3011 { "o5", 5, monitor_get_reg },
3012 { "o6", 6, monitor_get_reg },
3013 { "o7", 7, monitor_get_reg },
3014 { "l0", 8, monitor_get_reg },
3015 { "l1", 9, monitor_get_reg },
3016 { "l2", 10, monitor_get_reg },
3017 { "l3", 11, monitor_get_reg },
3018 { "l4", 12, monitor_get_reg },
3019 { "l5", 13, monitor_get_reg },
3020 { "l6", 14, monitor_get_reg },
3021 { "l7", 15, monitor_get_reg },
3022 { "i0", 16, monitor_get_reg },
3023 { "i1", 17, monitor_get_reg },
3024 { "i2", 18, monitor_get_reg },
3025 { "i3", 19, monitor_get_reg },
3026 { "i4", 20, monitor_get_reg },
3027 { "i5", 21, monitor_get_reg },
3028 { "i6", 22, monitor_get_reg },
3029 { "i7", 23, monitor_get_reg },
3030 { "pc", offsetof(CPUState, pc) },
3031 { "npc", offsetof(CPUState, npc) },
3032 { "y", offsetof(CPUState, y) },
3033 #ifndef TARGET_SPARC64
3034 { "psr", 0, &monitor_get_psr, },
3035 { "wim", offsetof(CPUState, wim) },
3036 #endif
3037 { "tbr", offsetof(CPUState, tbr) },
3038 { "fsr", offsetof(CPUState, fsr) },
3039 { "f0", offsetof(CPUState, fpr[0]) },
3040 { "f1", offsetof(CPUState, fpr[1]) },
3041 { "f2", offsetof(CPUState, fpr[2]) },
3042 { "f3", offsetof(CPUState, fpr[3]) },
3043 { "f4", offsetof(CPUState, fpr[4]) },
3044 { "f5", offsetof(CPUState, fpr[5]) },
3045 { "f6", offsetof(CPUState, fpr[6]) },
3046 { "f7", offsetof(CPUState, fpr[7]) },
3047 { "f8", offsetof(CPUState, fpr[8]) },
3048 { "f9", offsetof(CPUState, fpr[9]) },
3049 { "f10", offsetof(CPUState, fpr[10]) },
3050 { "f11", offsetof(CPUState, fpr[11]) },
3051 { "f12", offsetof(CPUState, fpr[12]) },
3052 { "f13", offsetof(CPUState, fpr[13]) },
3053 { "f14", offsetof(CPUState, fpr[14]) },
3054 { "f15", offsetof(CPUState, fpr[15]) },
3055 { "f16", offsetof(CPUState, fpr[16]) },
3056 { "f17", offsetof(CPUState, fpr[17]) },
3057 { "f18", offsetof(CPUState, fpr[18]) },
3058 { "f19", offsetof(CPUState, fpr[19]) },
3059 { "f20", offsetof(CPUState, fpr[20]) },
3060 { "f21", offsetof(CPUState, fpr[21]) },
3061 { "f22", offsetof(CPUState, fpr[22]) },
3062 { "f23", offsetof(CPUState, fpr[23]) },
3063 { "f24", offsetof(CPUState, fpr[24]) },
3064 { "f25", offsetof(CPUState, fpr[25]) },
3065 { "f26", offsetof(CPUState, fpr[26]) },
3066 { "f27", offsetof(CPUState, fpr[27]) },
3067 { "f28", offsetof(CPUState, fpr[28]) },
3068 { "f29", offsetof(CPUState, fpr[29]) },
3069 { "f30", offsetof(CPUState, fpr[30]) },
3070 { "f31", offsetof(CPUState, fpr[31]) },
3071 #ifdef TARGET_SPARC64
3072 { "f32", offsetof(CPUState, fpr[32]) },
3073 { "f34", offsetof(CPUState, fpr[34]) },
3074 { "f36", offsetof(CPUState, fpr[36]) },
3075 { "f38", offsetof(CPUState, fpr[38]) },
3076 { "f40", offsetof(CPUState, fpr[40]) },
3077 { "f42", offsetof(CPUState, fpr[42]) },
3078 { "f44", offsetof(CPUState, fpr[44]) },
3079 { "f46", offsetof(CPUState, fpr[46]) },
3080 { "f48", offsetof(CPUState, fpr[48]) },
3081 { "f50", offsetof(CPUState, fpr[50]) },
3082 { "f52", offsetof(CPUState, fpr[52]) },
3083 { "f54", offsetof(CPUState, fpr[54]) },
3084 { "f56", offsetof(CPUState, fpr[56]) },
3085 { "f58", offsetof(CPUState, fpr[58]) },
3086 { "f60", offsetof(CPUState, fpr[60]) },
3087 { "f62", offsetof(CPUState, fpr[62]) },
3088 { "asi", offsetof(CPUState, asi) },
3089 { "pstate", offsetof(CPUState, pstate) },
3090 { "cansave", offsetof(CPUState, cansave) },
3091 { "canrestore", offsetof(CPUState, canrestore) },
3092 { "otherwin", offsetof(CPUState, otherwin) },
3093 { "wstate", offsetof(CPUState, wstate) },
3094 { "cleanwin", offsetof(CPUState, cleanwin) },
3095 { "fprs", offsetof(CPUState, fprs) },
3096 #endif
3097 #endif
3098 { NULL },
3101 static void expr_error(Monitor *mon, const char *msg)
3103 monitor_printf(mon, "%s\n", msg);
3104 longjmp(expr_env, 1);
3107 /* return 0 if OK, -1 if not found */
3108 static int get_monitor_def(target_long *pval, const char *name)
3110 const MonitorDef *md;
3111 void *ptr;
3113 for(md = monitor_defs; md->name != NULL; md++) {
3114 if (compare_cmd(name, md->name)) {
3115 if (md->get_value) {
3116 *pval = md->get_value(md, md->offset);
3117 } else {
3118 CPUState *env = mon_get_cpu();
3119 ptr = (uint8_t *)env + md->offset;
3120 switch(md->type) {
3121 case MD_I32:
3122 *pval = *(int32_t *)ptr;
3123 break;
3124 case MD_TLONG:
3125 *pval = *(target_long *)ptr;
3126 break;
3127 default:
3128 *pval = 0;
3129 break;
3132 return 0;
3135 return -1;
3138 static void next(void)
3140 if (*pch != '\0') {
3141 pch++;
3142 while (qemu_isspace(*pch))
3143 pch++;
3147 static int64_t expr_sum(Monitor *mon);
3149 static int64_t expr_unary(Monitor *mon)
3151 int64_t n;
3152 char *p;
3153 int ret;
3155 switch(*pch) {
3156 case '+':
3157 next();
3158 n = expr_unary(mon);
3159 break;
3160 case '-':
3161 next();
3162 n = -expr_unary(mon);
3163 break;
3164 case '~':
3165 next();
3166 n = ~expr_unary(mon);
3167 break;
3168 case '(':
3169 next();
3170 n = expr_sum(mon);
3171 if (*pch != ')') {
3172 expr_error(mon, "')' expected");
3174 next();
3175 break;
3176 case '\'':
3177 pch++;
3178 if (*pch == '\0')
3179 expr_error(mon, "character constant expected");
3180 n = *pch;
3181 pch++;
3182 if (*pch != '\'')
3183 expr_error(mon, "missing terminating \' character");
3184 next();
3185 break;
3186 case '$':
3188 char buf[128], *q;
3189 target_long reg=0;
3191 pch++;
3192 q = buf;
3193 while ((*pch >= 'a' && *pch <= 'z') ||
3194 (*pch >= 'A' && *pch <= 'Z') ||
3195 (*pch >= '0' && *pch <= '9') ||
3196 *pch == '_' || *pch == '.') {
3197 if ((q - buf) < sizeof(buf) - 1)
3198 *q++ = *pch;
3199 pch++;
3201 while (qemu_isspace(*pch))
3202 pch++;
3203 *q = 0;
3204 ret = get_monitor_def(&reg, buf);
3205 if (ret < 0)
3206 expr_error(mon, "unknown register");
3207 n = reg;
3209 break;
3210 case '\0':
3211 expr_error(mon, "unexpected end of expression");
3212 n = 0;
3213 break;
3214 default:
3215 #if TARGET_PHYS_ADDR_BITS > 32
3216 n = strtoull(pch, &p, 0);
3217 #else
3218 n = strtoul(pch, &p, 0);
3219 #endif
3220 if (pch == p) {
3221 expr_error(mon, "invalid char in expression");
3223 pch = p;
3224 while (qemu_isspace(*pch))
3225 pch++;
3226 break;
3228 return n;
3232 static int64_t expr_prod(Monitor *mon)
3234 int64_t val, val2;
3235 int op;
3237 val = expr_unary(mon);
3238 for(;;) {
3239 op = *pch;
3240 if (op != '*' && op != '/' && op != '%')
3241 break;
3242 next();
3243 val2 = expr_unary(mon);
3244 switch(op) {
3245 default:
3246 case '*':
3247 val *= val2;
3248 break;
3249 case '/':
3250 case '%':
3251 if (val2 == 0)
3252 expr_error(mon, "division by zero");
3253 if (op == '/')
3254 val /= val2;
3255 else
3256 val %= val2;
3257 break;
3260 return val;
3263 static int64_t expr_logic(Monitor *mon)
3265 int64_t val, val2;
3266 int op;
3268 val = expr_prod(mon);
3269 for(;;) {
3270 op = *pch;
3271 if (op != '&' && op != '|' && op != '^')
3272 break;
3273 next();
3274 val2 = expr_prod(mon);
3275 switch(op) {
3276 default:
3277 case '&':
3278 val &= val2;
3279 break;
3280 case '|':
3281 val |= val2;
3282 break;
3283 case '^':
3284 val ^= val2;
3285 break;
3288 return val;
3291 static int64_t expr_sum(Monitor *mon)
3293 int64_t val, val2;
3294 int op;
3296 val = expr_logic(mon);
3297 for(;;) {
3298 op = *pch;
3299 if (op != '+' && op != '-')
3300 break;
3301 next();
3302 val2 = expr_logic(mon);
3303 if (op == '+')
3304 val += val2;
3305 else
3306 val -= val2;
3308 return val;
3311 static int get_expr(Monitor *mon, int64_t *pval, const char **pp)
3313 pch = *pp;
3314 if (setjmp(expr_env)) {
3315 *pp = pch;
3316 return -1;
3318 while (qemu_isspace(*pch))
3319 pch++;
3320 *pval = expr_sum(mon);
3321 *pp = pch;
3322 return 0;
3325 static int get_double(Monitor *mon, double *pval, const char **pp)
3327 const char *p = *pp;
3328 char *tailp;
3329 double d;
3331 d = strtod(p, &tailp);
3332 if (tailp == p) {
3333 monitor_printf(mon, "Number expected\n");
3334 return -1;
3336 if (d != d || d - d != 0) {
3337 /* NaN or infinity */
3338 monitor_printf(mon, "Bad number\n");
3339 return -1;
3341 *pval = d;
3342 *pp = tailp;
3343 return 0;
3346 static int get_str(char *buf, int buf_size, const char **pp)
3348 const char *p;
3349 char *q;
3350 int c;
3352 q = buf;
3353 p = *pp;
3354 while (qemu_isspace(*p))
3355 p++;
3356 if (*p == '\0') {
3357 fail:
3358 *q = '\0';
3359 *pp = p;
3360 return -1;
3362 if (*p == '\"') {
3363 p++;
3364 while (*p != '\0' && *p != '\"') {
3365 if (*p == '\\') {
3366 p++;
3367 c = *p++;
3368 switch(c) {
3369 case 'n':
3370 c = '\n';
3371 break;
3372 case 'r':
3373 c = '\r';
3374 break;
3375 case '\\':
3376 case '\'':
3377 case '\"':
3378 break;
3379 default:
3380 qemu_printf("unsupported escape code: '\\%c'\n", c);
3381 goto fail;
3383 if ((q - buf) < buf_size - 1) {
3384 *q++ = c;
3386 } else {
3387 if ((q - buf) < buf_size - 1) {
3388 *q++ = *p;
3390 p++;
3393 if (*p != '\"') {
3394 qemu_printf("unterminated string\n");
3395 goto fail;
3397 p++;
3398 } else {
3399 while (*p != '\0' && !qemu_isspace(*p)) {
3400 if ((q - buf) < buf_size - 1) {
3401 *q++ = *p;
3403 p++;
3406 *q = '\0';
3407 *pp = p;
3408 return 0;
3412 * Store the command-name in cmdname, and return a pointer to
3413 * the remaining of the command string.
3415 static const char *get_command_name(const char *cmdline,
3416 char *cmdname, size_t nlen)
3418 size_t len;
3419 const char *p, *pstart;
3421 p = cmdline;
3422 while (qemu_isspace(*p))
3423 p++;
3424 if (*p == '\0')
3425 return NULL;
3426 pstart = p;
3427 while (*p != '\0' && *p != '/' && !qemu_isspace(*p))
3428 p++;
3429 len = p - pstart;
3430 if (len > nlen - 1)
3431 len = nlen - 1;
3432 memcpy(cmdname, pstart, len);
3433 cmdname[len] = '\0';
3434 return p;
3438 * Read key of 'type' into 'key' and return the current
3439 * 'type' pointer.
3441 static char *key_get_info(const char *type, char **key)
3443 size_t len;
3444 char *p, *str;
3446 if (*type == ',')
3447 type++;
3449 p = strchr(type, ':');
3450 if (!p) {
3451 *key = NULL;
3452 return NULL;
3454 len = p - type;
3456 str = qemu_malloc(len + 1);
3457 memcpy(str, type, len);
3458 str[len] = '\0';
3460 *key = str;
3461 return ++p;
3464 static int default_fmt_format = 'x';
3465 static int default_fmt_size = 4;
3467 #define MAX_ARGS 16
3469 static int is_valid_option(const char *c, const char *typestr)
3471 char option[3];
3473 option[0] = '-';
3474 option[1] = *c;
3475 option[2] = '\0';
3477 typestr = strstr(typestr, option);
3478 return (typestr != NULL);
3481 static const mon_cmd_t *monitor_find_command(const char *cmdname)
3483 const mon_cmd_t *cmd;
3485 for (cmd = mon_cmds; cmd->name != NULL; cmd++) {
3486 if (compare_cmd(cmdname, cmd->name)) {
3487 return cmd;
3491 return NULL;
3494 static const mon_cmd_t *monitor_parse_command(Monitor *mon,
3495 const char *cmdline,
3496 QDict *qdict)
3498 const char *p, *typestr;
3499 int c;
3500 const mon_cmd_t *cmd;
3501 char cmdname[256];
3502 char buf[1024];
3503 char *key;
3505 #ifdef DEBUG
3506 monitor_printf(mon, "command='%s'\n", cmdline);
3507 #endif
3509 /* extract the command name */
3510 p = get_command_name(cmdline, cmdname, sizeof(cmdname));
3511 if (!p)
3512 return NULL;
3514 cmd = monitor_find_command(cmdname);
3515 if (!cmd) {
3516 monitor_printf(mon, "unknown command: '%s'\n", cmdname);
3517 return NULL;
3520 /* parse the parameters */
3521 typestr = cmd->args_type;
3522 for(;;) {
3523 typestr = key_get_info(typestr, &key);
3524 if (!typestr)
3525 break;
3526 c = *typestr;
3527 typestr++;
3528 switch(c) {
3529 case 'F':
3530 case 'B':
3531 case 's':
3533 int ret;
3535 while (qemu_isspace(*p))
3536 p++;
3537 if (*typestr == '?') {
3538 typestr++;
3539 if (*p == '\0') {
3540 /* no optional string: NULL argument */
3541 break;
3544 ret = get_str(buf, sizeof(buf), &p);
3545 if (ret < 0) {
3546 switch(c) {
3547 case 'F':
3548 monitor_printf(mon, "%s: filename expected\n",
3549 cmdname);
3550 break;
3551 case 'B':
3552 monitor_printf(mon, "%s: block device name expected\n",
3553 cmdname);
3554 break;
3555 default:
3556 monitor_printf(mon, "%s: string expected\n", cmdname);
3557 break;
3559 goto fail;
3561 qdict_put(qdict, key, qstring_from_str(buf));
3563 break;
3564 case '/':
3566 int count, format, size;
3568 while (qemu_isspace(*p))
3569 p++;
3570 if (*p == '/') {
3571 /* format found */
3572 p++;
3573 count = 1;
3574 if (qemu_isdigit(*p)) {
3575 count = 0;
3576 while (qemu_isdigit(*p)) {
3577 count = count * 10 + (*p - '0');
3578 p++;
3581 size = -1;
3582 format = -1;
3583 for(;;) {
3584 switch(*p) {
3585 case 'o':
3586 case 'd':
3587 case 'u':
3588 case 'x':
3589 case 'i':
3590 case 'c':
3591 format = *p++;
3592 break;
3593 case 'b':
3594 size = 1;
3595 p++;
3596 break;
3597 case 'h':
3598 size = 2;
3599 p++;
3600 break;
3601 case 'w':
3602 size = 4;
3603 p++;
3604 break;
3605 case 'g':
3606 case 'L':
3607 size = 8;
3608 p++;
3609 break;
3610 default:
3611 goto next;
3614 next:
3615 if (*p != '\0' && !qemu_isspace(*p)) {
3616 monitor_printf(mon, "invalid char in format: '%c'\n",
3617 *p);
3618 goto fail;
3620 if (format < 0)
3621 format = default_fmt_format;
3622 if (format != 'i') {
3623 /* for 'i', not specifying a size gives -1 as size */
3624 if (size < 0)
3625 size = default_fmt_size;
3626 default_fmt_size = size;
3628 default_fmt_format = format;
3629 } else {
3630 count = 1;
3631 format = default_fmt_format;
3632 if (format != 'i') {
3633 size = default_fmt_size;
3634 } else {
3635 size = -1;
3638 qdict_put(qdict, "count", qint_from_int(count));
3639 qdict_put(qdict, "format", qint_from_int(format));
3640 qdict_put(qdict, "size", qint_from_int(size));
3642 break;
3643 case 'i':
3644 case 'l':
3645 case 'M':
3647 int64_t val;
3649 while (qemu_isspace(*p))
3650 p++;
3651 if (*typestr == '?' || *typestr == '.') {
3652 if (*typestr == '?') {
3653 if (*p == '\0') {
3654 typestr++;
3655 break;
3657 } else {
3658 if (*p == '.') {
3659 p++;
3660 while (qemu_isspace(*p))
3661 p++;
3662 } else {
3663 typestr++;
3664 break;
3667 typestr++;
3669 if (get_expr(mon, &val, &p))
3670 goto fail;
3671 /* Check if 'i' is greater than 32-bit */
3672 if ((c == 'i') && ((val >> 32) & 0xffffffff)) {
3673 monitor_printf(mon, "\'%s\' has failed: ", cmdname);
3674 monitor_printf(mon, "integer is for 32-bit values\n");
3675 goto fail;
3676 } else if (c == 'M') {
3677 val <<= 20;
3679 qdict_put(qdict, key, qint_from_int(val));
3681 break;
3682 case 'b':
3683 case 'T':
3685 double val;
3687 while (qemu_isspace(*p))
3688 p++;
3689 if (*typestr == '?') {
3690 typestr++;
3691 if (*p == '\0') {
3692 break;
3695 if (get_double(mon, &val, &p) < 0) {
3696 goto fail;
3698 if (c == 'b' && *p) {
3699 switch (*p) {
3700 case 'K': case 'k':
3701 val *= 1 << 10; p++; break;
3702 case 'M': case 'm':
3703 val *= 1 << 20; p++; break;
3704 case 'G': case 'g':
3705 val *= 1 << 30; p++; break;
3708 if (c == 'T' && p[0] && p[1] == 's') {
3709 switch (*p) {
3710 case 'm':
3711 val /= 1e3; p += 2; break;
3712 case 'u':
3713 val /= 1e6; p += 2; break;
3714 case 'n':
3715 val /= 1e9; p += 2; break;
3718 if (*p && !qemu_isspace(*p)) {
3719 monitor_printf(mon, "Unknown unit suffix\n");
3720 goto fail;
3722 qdict_put(qdict, key, qfloat_from_double(val));
3724 break;
3725 case '-':
3727 const char *tmp = p;
3728 int has_option, skip_key = 0;
3729 /* option */
3731 c = *typestr++;
3732 if (c == '\0')
3733 goto bad_type;
3734 while (qemu_isspace(*p))
3735 p++;
3736 has_option = 0;
3737 if (*p == '-') {
3738 p++;
3739 if(c != *p) {
3740 if(!is_valid_option(p, typestr)) {
3742 monitor_printf(mon, "%s: unsupported option -%c\n",
3743 cmdname, *p);
3744 goto fail;
3745 } else {
3746 skip_key = 1;
3749 if(skip_key) {
3750 p = tmp;
3751 } else {
3752 p++;
3753 has_option = 1;
3756 qdict_put(qdict, key, qint_from_int(has_option));
3758 break;
3759 default:
3760 bad_type:
3761 monitor_printf(mon, "%s: unknown type '%c'\n", cmdname, c);
3762 goto fail;
3764 qemu_free(key);
3765 key = NULL;
3767 /* check that all arguments were parsed */
3768 while (qemu_isspace(*p))
3769 p++;
3770 if (*p != '\0') {
3771 monitor_printf(mon, "%s: extraneous characters at the end of line\n",
3772 cmdname);
3773 goto fail;
3776 return cmd;
3778 fail:
3779 qemu_free(key);
3780 return NULL;
3783 static void monitor_print_error(Monitor *mon)
3785 qerror_print(mon->error);
3786 QDECREF(mon->error);
3787 mon->error = NULL;
3790 static int is_async_return(const QObject *data)
3792 if (data && qobject_type(data) == QTYPE_QDICT) {
3793 return qdict_haskey(qobject_to_qdict(data), "__mon_async");
3796 return 0;
3799 static void monitor_call_handler(Monitor *mon, const mon_cmd_t *cmd,
3800 const QDict *params)
3802 QObject *data = NULL;
3804 cmd->mhandler.cmd_new(mon, params, &data);
3806 if (is_async_return(data)) {
3808 * Asynchronous commands have no initial return data but they can
3809 * generate errors. Data is returned via the async completion handler.
3811 if (monitor_ctrl_mode(mon) && monitor_has_error(mon)) {
3812 monitor_protocol_emitter(mon, NULL);
3814 } else if (monitor_ctrl_mode(mon)) {
3815 /* Monitor Protocol */
3816 monitor_protocol_emitter(mon, data);
3817 } else {
3818 /* User Protocol */
3819 if (data)
3820 cmd->user_print(mon, data);
3823 qobject_decref(data);
3826 static void handle_user_command(Monitor *mon, const char *cmdline)
3828 QDict *qdict;
3829 const mon_cmd_t *cmd;
3831 qdict = qdict_new();
3833 cmd = monitor_parse_command(mon, cmdline, qdict);
3834 if (!cmd)
3835 goto out;
3837 qemu_errors_to_mon(mon);
3839 if (monitor_handler_is_async(cmd)) {
3840 user_async_cmd_handler(mon, cmd, qdict);
3841 } else if (monitor_handler_ported(cmd)) {
3842 monitor_call_handler(mon, cmd, qdict);
3843 } else {
3844 cmd->mhandler.cmd(mon, qdict);
3847 if (monitor_has_error(mon))
3848 monitor_print_error(mon);
3850 qemu_errors_to_previous();
3852 out:
3853 QDECREF(qdict);
3856 static void cmd_completion(const char *name, const char *list)
3858 const char *p, *pstart;
3859 char cmd[128];
3860 int len;
3862 p = list;
3863 for(;;) {
3864 pstart = p;
3865 p = strchr(p, '|');
3866 if (!p)
3867 p = pstart + strlen(pstart);
3868 len = p - pstart;
3869 if (len > sizeof(cmd) - 2)
3870 len = sizeof(cmd) - 2;
3871 memcpy(cmd, pstart, len);
3872 cmd[len] = '\0';
3873 if (name[0] == '\0' || !strncmp(name, cmd, strlen(name))) {
3874 readline_add_completion(cur_mon->rs, cmd);
3876 if (*p == '\0')
3877 break;
3878 p++;
3882 static void file_completion(const char *input)
3884 DIR *ffs;
3885 struct dirent *d;
3886 char path[1024];
3887 char file[1024], file_prefix[1024];
3888 int input_path_len;
3889 const char *p;
3891 p = strrchr(input, '/');
3892 if (!p) {
3893 input_path_len = 0;
3894 pstrcpy(file_prefix, sizeof(file_prefix), input);
3895 pstrcpy(path, sizeof(path), ".");
3896 } else {
3897 input_path_len = p - input + 1;
3898 memcpy(path, input, input_path_len);
3899 if (input_path_len > sizeof(path) - 1)
3900 input_path_len = sizeof(path) - 1;
3901 path[input_path_len] = '\0';
3902 pstrcpy(file_prefix, sizeof(file_prefix), p + 1);
3904 #ifdef DEBUG_COMPLETION
3905 monitor_printf(cur_mon, "input='%s' path='%s' prefix='%s'\n",
3906 input, path, file_prefix);
3907 #endif
3908 ffs = opendir(path);
3909 if (!ffs)
3910 return;
3911 for(;;) {
3912 struct stat sb;
3913 d = readdir(ffs);
3914 if (!d)
3915 break;
3916 if (strstart(d->d_name, file_prefix, NULL)) {
3917 memcpy(file, input, input_path_len);
3918 if (input_path_len < sizeof(file))
3919 pstrcpy(file + input_path_len, sizeof(file) - input_path_len,
3920 d->d_name);
3921 /* stat the file to find out if it's a directory.
3922 * In that case add a slash to speed up typing long paths
3924 stat(file, &sb);
3925 if(S_ISDIR(sb.st_mode))
3926 pstrcat(file, sizeof(file), "/");
3927 readline_add_completion(cur_mon->rs, file);
3930 closedir(ffs);
3933 static void block_completion_it(void *opaque, BlockDriverState *bs)
3935 const char *name = bdrv_get_device_name(bs);
3936 const char *input = opaque;
3938 if (input[0] == '\0' ||
3939 !strncmp(name, (char *)input, strlen(input))) {
3940 readline_add_completion(cur_mon->rs, name);
3944 /* NOTE: this parser is an approximate form of the real command parser */
3945 static void parse_cmdline(const char *cmdline,
3946 int *pnb_args, char **args)
3948 const char *p;
3949 int nb_args, ret;
3950 char buf[1024];
3952 p = cmdline;
3953 nb_args = 0;
3954 for(;;) {
3955 while (qemu_isspace(*p))
3956 p++;
3957 if (*p == '\0')
3958 break;
3959 if (nb_args >= MAX_ARGS)
3960 break;
3961 ret = get_str(buf, sizeof(buf), &p);
3962 args[nb_args] = qemu_strdup(buf);
3963 nb_args++;
3964 if (ret < 0)
3965 break;
3967 *pnb_args = nb_args;
3970 static const char *next_arg_type(const char *typestr)
3972 const char *p = strchr(typestr, ':');
3973 return (p != NULL ? ++p : typestr);
3976 static void monitor_find_completion(const char *cmdline)
3978 const char *cmdname;
3979 char *args[MAX_ARGS];
3980 int nb_args, i, len;
3981 const char *ptype, *str;
3982 const mon_cmd_t *cmd;
3983 const KeyDef *key;
3985 parse_cmdline(cmdline, &nb_args, args);
3986 #ifdef DEBUG_COMPLETION
3987 for(i = 0; i < nb_args; i++) {
3988 monitor_printf(cur_mon, "arg%d = '%s'\n", i, (char *)args[i]);
3990 #endif
3992 /* if the line ends with a space, it means we want to complete the
3993 next arg */
3994 len = strlen(cmdline);
3995 if (len > 0 && qemu_isspace(cmdline[len - 1])) {
3996 if (nb_args >= MAX_ARGS)
3997 return;
3998 args[nb_args++] = qemu_strdup("");
4000 if (nb_args <= 1) {
4001 /* command completion */
4002 if (nb_args == 0)
4003 cmdname = "";
4004 else
4005 cmdname = args[0];
4006 readline_set_completion_index(cur_mon->rs, strlen(cmdname));
4007 for(cmd = mon_cmds; cmd->name != NULL; cmd++) {
4008 cmd_completion(cmdname, cmd->name);
4010 } else {
4011 /* find the command */
4012 for(cmd = mon_cmds; cmd->name != NULL; cmd++) {
4013 if (compare_cmd(args[0], cmd->name))
4014 goto found;
4016 return;
4017 found:
4018 ptype = next_arg_type(cmd->args_type);
4019 for(i = 0; i < nb_args - 2; i++) {
4020 if (*ptype != '\0') {
4021 ptype = next_arg_type(ptype);
4022 while (*ptype == '?')
4023 ptype = next_arg_type(ptype);
4026 str = args[nb_args - 1];
4027 if (*ptype == '-' && ptype[1] != '\0') {
4028 ptype += 2;
4030 switch(*ptype) {
4031 case 'F':
4032 /* file completion */
4033 readline_set_completion_index(cur_mon->rs, strlen(str));
4034 file_completion(str);
4035 break;
4036 case 'B':
4037 /* block device name completion */
4038 readline_set_completion_index(cur_mon->rs, strlen(str));
4039 bdrv_iterate(block_completion_it, (void *)str);
4040 break;
4041 case 's':
4042 /* XXX: more generic ? */
4043 if (!strcmp(cmd->name, "info")) {
4044 readline_set_completion_index(cur_mon->rs, strlen(str));
4045 for(cmd = info_cmds; cmd->name != NULL; cmd++) {
4046 cmd_completion(str, cmd->name);
4048 } else if (!strcmp(cmd->name, "sendkey")) {
4049 char *sep = strrchr(str, '-');
4050 if (sep)
4051 str = sep + 1;
4052 readline_set_completion_index(cur_mon->rs, strlen(str));
4053 for(key = key_defs; key->name != NULL; key++) {
4054 cmd_completion(str, key->name);
4056 } else if (!strcmp(cmd->name, "help|?")) {
4057 readline_set_completion_index(cur_mon->rs, strlen(str));
4058 for (cmd = mon_cmds; cmd->name != NULL; cmd++) {
4059 cmd_completion(str, cmd->name);
4062 break;
4063 default:
4064 break;
4067 for(i = 0; i < nb_args; i++)
4068 qemu_free(args[i]);
4071 static int monitor_can_read(void *opaque)
4073 Monitor *mon = opaque;
4075 return (mon->suspend_cnt == 0) ? 1 : 0;
4078 typedef struct CmdArgs {
4079 QString *name;
4080 int type;
4081 int flag;
4082 int optional;
4083 } CmdArgs;
4085 static int check_opt(const CmdArgs *cmd_args, const char *name, QDict *args)
4087 if (!cmd_args->optional) {
4088 qemu_error_new(QERR_MISSING_PARAMETER, name);
4089 return -1;
4092 if (cmd_args->type == '-') {
4093 /* handlers expect a value, they need to be changed */
4094 qdict_put(args, name, qint_from_int(0));
4097 return 0;
4100 static int check_arg(const CmdArgs *cmd_args, QDict *args)
4102 QObject *value;
4103 const char *name;
4105 name = qstring_get_str(cmd_args->name);
4107 if (!args) {
4108 return check_opt(cmd_args, name, args);
4111 value = qdict_get(args, name);
4112 if (!value) {
4113 return check_opt(cmd_args, name, args);
4116 switch (cmd_args->type) {
4117 case 'F':
4118 case 'B':
4119 case 's':
4120 if (qobject_type(value) != QTYPE_QSTRING) {
4121 qemu_error_new(QERR_INVALID_PARAMETER_TYPE, name, "string");
4122 return -1;
4124 break;
4125 case '/': {
4126 int i;
4127 const char *keys[] = { "count", "format", "size", NULL };
4129 for (i = 0; keys[i]; i++) {
4130 QObject *obj = qdict_get(args, keys[i]);
4131 if (!obj) {
4132 qemu_error_new(QERR_MISSING_PARAMETER, name);
4133 return -1;
4135 if (qobject_type(obj) != QTYPE_QINT) {
4136 qemu_error_new(QERR_INVALID_PARAMETER_TYPE, name, "int");
4137 return -1;
4140 break;
4142 case 'i':
4143 case 'l':
4144 case 'M':
4145 if (qobject_type(value) != QTYPE_QINT) {
4146 qemu_error_new(QERR_INVALID_PARAMETER_TYPE, name, "int");
4147 return -1;
4149 break;
4150 case 'b':
4151 case 'T':
4152 if (qobject_type(value) != QTYPE_QINT && qobject_type(value) != QTYPE_QFLOAT) {
4153 qemu_error_new(QERR_INVALID_PARAMETER_TYPE, name, "number");
4154 return -1;
4156 break;
4157 case '-':
4158 if (qobject_type(value) != QTYPE_QINT &&
4159 qobject_type(value) != QTYPE_QBOOL) {
4160 qemu_error_new(QERR_INVALID_PARAMETER_TYPE, name, "bool");
4161 return -1;
4163 if (qobject_type(value) == QTYPE_QBOOL) {
4164 /* handlers expect a QInt, they need to be changed */
4165 qdict_put(args, name,
4166 qint_from_int(qbool_get_int(qobject_to_qbool(value))));
4168 break;
4169 default:
4170 /* impossible */
4171 abort();
4174 return 0;
4177 static void cmd_args_init(CmdArgs *cmd_args)
4179 cmd_args->name = qstring_new();
4180 cmd_args->type = cmd_args->flag = cmd_args->optional = 0;
4184 * This is not trivial, we have to parse Monitor command's argument
4185 * type syntax to be able to check the arguments provided by clients.
4187 * In the near future we will be using an array for that and will be
4188 * able to drop all this parsing...
4190 static int monitor_check_qmp_args(const mon_cmd_t *cmd, QDict *args)
4192 int err;
4193 const char *p;
4194 CmdArgs cmd_args;
4196 if (cmd->args_type == NULL) {
4197 return (qdict_size(args) == 0 ? 0 : -1);
4200 err = 0;
4201 cmd_args_init(&cmd_args);
4203 for (p = cmd->args_type;; p++) {
4204 if (*p == ':') {
4205 cmd_args.type = *++p;
4206 p++;
4207 if (cmd_args.type == '-') {
4208 cmd_args.flag = *p++;
4209 cmd_args.optional = 1;
4210 } else if (*p == '?') {
4211 cmd_args.optional = 1;
4212 p++;
4215 assert(*p == ',' || *p == '\0');
4216 err = check_arg(&cmd_args, args);
4218 QDECREF(cmd_args.name);
4219 cmd_args_init(&cmd_args);
4221 if (err < 0) {
4222 break;
4224 } else {
4225 qstring_append_chr(cmd_args.name, *p);
4228 if (*p == '\0') {
4229 break;
4233 QDECREF(cmd_args.name);
4234 return err;
4237 static int invalid_qmp_mode(const Monitor *mon, const char *cmd_name)
4239 int is_cap = compare_cmd(cmd_name, "qmp_capabilities");
4240 return (qmp_cmd_mode(mon) ? is_cap : !is_cap);
4243 static void handle_qmp_command(JSONMessageParser *parser, QList *tokens)
4245 int err;
4246 QObject *obj;
4247 QDict *input, *args;
4248 const mon_cmd_t *cmd;
4249 Monitor *mon = cur_mon;
4250 const char *cmd_name, *info_item;
4252 args = NULL;
4253 qemu_errors_to_mon(mon);
4255 obj = json_parser_parse(tokens, NULL);
4256 if (!obj) {
4257 // FIXME: should be triggered in json_parser_parse()
4258 qemu_error_new(QERR_JSON_PARSING);
4259 goto err_out;
4260 } else if (qobject_type(obj) != QTYPE_QDICT) {
4261 qemu_error_new(QERR_QMP_BAD_INPUT_OBJECT, "object");
4262 qobject_decref(obj);
4263 goto err_out;
4266 input = qobject_to_qdict(obj);
4268 mon->mc->id = qdict_get(input, "id");
4269 qobject_incref(mon->mc->id);
4271 obj = qdict_get(input, "execute");
4272 if (!obj) {
4273 qemu_error_new(QERR_QMP_BAD_INPUT_OBJECT, "execute");
4274 goto err_input;
4275 } else if (qobject_type(obj) != QTYPE_QSTRING) {
4276 qemu_error_new(QERR_QMP_BAD_INPUT_OBJECT, "string");
4277 goto err_input;
4280 cmd_name = qstring_get_str(qobject_to_qstring(obj));
4282 if (invalid_qmp_mode(mon, cmd_name)) {
4283 qemu_error_new(QERR_COMMAND_NOT_FOUND, cmd_name);
4284 goto err_input;
4288 * XXX: We need this special case until we get info handlers
4289 * converted into 'query-' commands
4291 if (compare_cmd(cmd_name, "info")) {
4292 qemu_error_new(QERR_COMMAND_NOT_FOUND, cmd_name);
4293 goto err_input;
4294 } else if (strstart(cmd_name, "query-", &info_item)) {
4295 cmd = monitor_find_command("info");
4296 qdict_put_obj(input, "arguments",
4297 qobject_from_jsonf("{ 'item': %s }", info_item));
4298 } else {
4299 cmd = monitor_find_command(cmd_name);
4300 if (!cmd || !monitor_handler_ported(cmd)) {
4301 qemu_error_new(QERR_COMMAND_NOT_FOUND, cmd_name);
4302 goto err_input;
4306 obj = qdict_get(input, "arguments");
4307 if (!obj) {
4308 args = qdict_new();
4309 } else {
4310 args = qobject_to_qdict(obj);
4311 QINCREF(args);
4314 QDECREF(input);
4316 err = monitor_check_qmp_args(cmd, args);
4317 if (err < 0) {
4318 goto err_out;
4321 if (monitor_handler_is_async(cmd)) {
4322 qmp_async_cmd_handler(mon, cmd, args);
4323 } else {
4324 monitor_call_handler(mon, cmd, args);
4326 goto out;
4328 err_input:
4329 QDECREF(input);
4330 err_out:
4331 monitor_protocol_emitter(mon, NULL);
4332 out:
4333 QDECREF(args);
4334 qemu_errors_to_previous();
4338 * monitor_control_read(): Read and handle QMP input
4340 static void monitor_control_read(void *opaque, const uint8_t *buf, int size)
4342 Monitor *old_mon = cur_mon;
4344 cur_mon = opaque;
4346 json_message_parser_feed(&cur_mon->mc->parser, (const char *) buf, size);
4348 cur_mon = old_mon;
4351 static void monitor_read(void *opaque, const uint8_t *buf, int size)
4353 Monitor *old_mon = cur_mon;
4354 int i;
4356 cur_mon = opaque;
4358 if (cur_mon->rs) {
4359 for (i = 0; i < size; i++)
4360 readline_handle_byte(cur_mon->rs, buf[i]);
4361 } else {
4362 if (size == 0 || buf[size - 1] != 0)
4363 monitor_printf(cur_mon, "corrupted command\n");
4364 else
4365 handle_user_command(cur_mon, (char *)buf);
4368 cur_mon = old_mon;
4371 static void monitor_command_cb(Monitor *mon, const char *cmdline, void *opaque)
4373 monitor_suspend(mon);
4374 handle_user_command(mon, cmdline);
4375 monitor_resume(mon);
4378 int monitor_suspend(Monitor *mon)
4380 if (!mon->rs)
4381 return -ENOTTY;
4382 mon->suspend_cnt++;
4383 return 0;
4386 void monitor_resume(Monitor *mon)
4388 if (!mon->rs)
4389 return;
4390 if (--mon->suspend_cnt == 0)
4391 readline_show_prompt(mon->rs);
4394 static QObject *get_qmp_greeting(void)
4396 QObject *ver;
4398 do_info_version(NULL, &ver);
4399 return qobject_from_jsonf("{'QMP':{'version': %p,'capabilities': []}}",ver);
4403 * monitor_control_event(): Print QMP gretting
4405 static void monitor_control_event(void *opaque, int event)
4407 QObject *data;
4408 Monitor *mon = opaque;
4410 switch (event) {
4411 case CHR_EVENT_OPENED:
4412 mon->mc->command_mode = 0;
4413 json_message_parser_init(&mon->mc->parser, handle_qmp_command);
4414 data = get_qmp_greeting();
4415 monitor_json_emitter(mon, data);
4416 qobject_decref(data);
4417 break;
4418 case CHR_EVENT_CLOSED:
4419 json_message_parser_destroy(&mon->mc->parser);
4420 break;
4424 static void monitor_event(void *opaque, int event)
4426 Monitor *mon = opaque;
4428 switch (event) {
4429 case CHR_EVENT_MUX_IN:
4430 mon->mux_out = 0;
4431 if (mon->reset_seen) {
4432 readline_restart(mon->rs);
4433 monitor_resume(mon);
4434 monitor_flush(mon);
4435 } else {
4436 mon->suspend_cnt = 0;
4438 break;
4440 case CHR_EVENT_MUX_OUT:
4441 if (mon->reset_seen) {
4442 if (mon->suspend_cnt == 0) {
4443 monitor_printf(mon, "\n");
4445 monitor_flush(mon);
4446 monitor_suspend(mon);
4447 } else {
4448 mon->suspend_cnt++;
4450 mon->mux_out = 1;
4451 break;
4453 case CHR_EVENT_OPENED:
4454 monitor_printf(mon, "QEMU %s monitor - type 'help' for more "
4455 "information\n", QEMU_VERSION);
4456 if (!mon->mux_out) {
4457 readline_show_prompt(mon->rs);
4459 mon->reset_seen = 1;
4460 break;
4466 * Local variables:
4467 * c-indent-level: 4
4468 * c-basic-offset: 4
4469 * tab-width: 8
4470 * End:
4473 void monitor_init(CharDriverState *chr, int flags)
4475 static int is_first_init = 1;
4476 Monitor *mon;
4478 if (is_first_init) {
4479 key_timer = qemu_new_timer(vm_clock, release_keys, NULL);
4480 is_first_init = 0;
4483 mon = qemu_mallocz(sizeof(*mon));
4485 mon->chr = chr;
4486 mon->flags = flags;
4487 if (flags & MONITOR_USE_READLINE) {
4488 mon->rs = readline_init(mon, monitor_find_completion);
4489 monitor_read_command(mon, 0);
4492 if (monitor_ctrl_mode(mon)) {
4493 mon->mc = qemu_mallocz(sizeof(MonitorControl));
4494 /* Control mode requires special handlers */
4495 qemu_chr_add_handlers(chr, monitor_can_read, monitor_control_read,
4496 monitor_control_event, mon);
4497 } else {
4498 qemu_chr_add_handlers(chr, monitor_can_read, monitor_read,
4499 monitor_event, mon);
4502 QLIST_INSERT_HEAD(&mon_list, mon, entry);
4503 if (!cur_mon || (flags & MONITOR_IS_DEFAULT))
4504 cur_mon = mon;
4507 static void bdrv_password_cb(Monitor *mon, const char *password, void *opaque)
4509 BlockDriverState *bs = opaque;
4510 int ret = 0;
4512 if (bdrv_set_key(bs, password) != 0) {
4513 monitor_printf(mon, "invalid password\n");
4514 ret = -EPERM;
4516 if (mon->password_completion_cb)
4517 mon->password_completion_cb(mon->password_opaque, ret);
4519 monitor_read_command(mon, 1);
4522 void monitor_read_bdrv_key_start(Monitor *mon, BlockDriverState *bs,
4523 BlockDriverCompletionFunc *completion_cb,
4524 void *opaque)
4526 int err;
4528 if (!bdrv_key_required(bs)) {
4529 if (completion_cb)
4530 completion_cb(opaque, 0);
4531 return;
4534 if (monitor_ctrl_mode(mon)) {
4535 qemu_error_new(QERR_DEVICE_ENCRYPTED, bdrv_get_device_name(bs));
4536 return;
4539 monitor_printf(mon, "%s (%s) is encrypted.\n", bdrv_get_device_name(bs),
4540 bdrv_get_encrypted_filename(bs));
4542 mon->password_completion_cb = completion_cb;
4543 mon->password_opaque = opaque;
4545 err = monitor_read_password(mon, bdrv_password_cb, bs);
4547 if (err && completion_cb)
4548 completion_cb(opaque, err);
4551 typedef struct QemuErrorSink QemuErrorSink;
4552 struct QemuErrorSink {
4553 enum {
4554 ERR_SINK_FILE,
4555 ERR_SINK_MONITOR,
4556 } dest;
4557 union {
4558 FILE *fp;
4559 Monitor *mon;
4561 QemuErrorSink *previous;
4564 static QemuErrorSink *qemu_error_sink;
4566 void qemu_errors_to_file(FILE *fp)
4568 QemuErrorSink *sink;
4570 sink = qemu_mallocz(sizeof(*sink));
4571 sink->dest = ERR_SINK_FILE;
4572 sink->fp = fp;
4573 sink->previous = qemu_error_sink;
4574 qemu_error_sink = sink;
4577 void qemu_errors_to_mon(Monitor *mon)
4579 QemuErrorSink *sink;
4581 sink = qemu_mallocz(sizeof(*sink));
4582 sink->dest = ERR_SINK_MONITOR;
4583 sink->mon = mon;
4584 sink->previous = qemu_error_sink;
4585 qemu_error_sink = sink;
4588 void qemu_errors_to_previous(void)
4590 QemuErrorSink *sink;
4592 assert(qemu_error_sink != NULL);
4593 sink = qemu_error_sink;
4594 qemu_error_sink = sink->previous;
4595 qemu_free(sink);
4598 void qemu_error(const char *fmt, ...)
4600 va_list args;
4602 assert(qemu_error_sink != NULL);
4603 switch (qemu_error_sink->dest) {
4604 case ERR_SINK_FILE:
4605 va_start(args, fmt);
4606 vfprintf(qemu_error_sink->fp, fmt, args);
4607 va_end(args);
4608 break;
4609 case ERR_SINK_MONITOR:
4610 va_start(args, fmt);
4611 monitor_vprintf(qemu_error_sink->mon, fmt, args);
4612 va_end(args);
4613 break;
4617 void qemu_error_internal(const char *file, int linenr, const char *func,
4618 const char *fmt, ...)
4620 va_list va;
4621 QError *qerror;
4623 assert(qemu_error_sink != NULL);
4625 va_start(va, fmt);
4626 qerror = qerror_from_info(file, linenr, func, fmt, &va);
4627 va_end(va);
4629 switch (qemu_error_sink->dest) {
4630 case ERR_SINK_FILE:
4631 qerror_print(qerror);
4632 QDECREF(qerror);
4633 break;
4634 case ERR_SINK_MONITOR:
4635 /* report only the first error */
4636 if (!qemu_error_sink->mon->error) {
4637 qemu_error_sink->mon->error = qerror;
4638 } else {
4639 /* XXX: warn the programmer */
4640 QDECREF(qerror);
4642 break;