ui/console: Fix non-working backspace key in monitor of gtk UI
[qemu/rayw.git] / monitor.c
blob5c003731e288ba654dd39c44a4d0199a81e36eb6
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 "qemu/osdep.h"
25 #include <dirent.h>
26 #include "qemu-common.h"
27 #include "cpu.h"
28 #include "hw/hw.h"
29 #include "monitor/qdev.h"
30 #include "hw/usb.h"
31 #include "hw/i386/pc.h"
32 #include "hw/pci/pci.h"
33 #include "sysemu/watchdog.h"
34 #include "hw/loader.h"
35 #include "exec/gdbstub.h"
36 #include "net/net.h"
37 #include "net/slirp.h"
38 #include "sysemu/char.h"
39 #include "ui/qemu-spice.h"
40 #include "sysemu/sysemu.h"
41 #include "sysemu/numa.h"
42 #include "monitor/monitor.h"
43 #include "qemu/readline.h"
44 #include "ui/console.h"
45 #include "ui/input.h"
46 #include "sysemu/blockdev.h"
47 #include "sysemu/block-backend.h"
48 #include "audio/audio.h"
49 #include "disas/disas.h"
50 #include "sysemu/balloon.h"
51 #include "qemu/timer.h"
52 #include "migration/migration.h"
53 #include "sysemu/kvm.h"
54 #include "qemu/acl.h"
55 #include "sysemu/tpm.h"
56 #include "qapi/qmp/qerror.h"
57 #include "qapi/qmp/types.h"
58 #include "qapi/qmp/qjson.h"
59 #include "qapi/qmp/json-streamer.h"
60 #include "qapi/qmp/json-parser.h"
61 #include "qom/object_interfaces.h"
62 #include "cpu.h"
63 #include "trace.h"
64 #include "trace/control.h"
65 #include "monitor/hmp-target.h"
66 #ifdef CONFIG_TRACE_SIMPLE
67 #include "trace/simple.h"
68 #endif
69 #include "exec/memory.h"
70 #include "exec/exec-all.h"
71 #include "qemu/log.h"
72 #include "qmp-commands.h"
73 #include "hmp.h"
74 #include "qemu/thread.h"
75 #include "block/qapi.h"
76 #include "qapi/qmp-event.h"
77 #include "qapi-event.h"
78 #include "qmp-introspect.h"
79 #include "sysemu/block-backend.h"
80 #include "sysemu/qtest.h"
81 #include "qemu/cutils.h"
83 /* for hmp_info_irq/pic */
84 #if defined(TARGET_SPARC)
85 #include "hw/sparc/sun4m.h"
86 #endif
87 #include "hw/lm32/lm32_pic.h"
89 #if defined(TARGET_S390X)
90 #include "hw/s390x/storage-keys.h"
91 #endif
94 * Supported types:
96 * 'F' filename
97 * 'B' block device name
98 * 's' string (accept optional quote)
99 * 'S' it just appends the rest of the string (accept optional quote)
100 * 'O' option string of the form NAME=VALUE,...
101 * parsed according to QemuOptsList given by its name
102 * Example: 'device:O' uses qemu_device_opts.
103 * Restriction: only lists with empty desc are supported
104 * TODO lift the restriction
105 * 'i' 32 bit integer
106 * 'l' target long (32 or 64 bit)
107 * 'M' Non-negative target long (32 or 64 bit), in user mode the
108 * value is multiplied by 2^20 (think Mebibyte)
109 * 'o' octets (aka bytes)
110 * user mode accepts an optional E, e, P, p, T, t, G, g, M, m,
111 * K, k suffix, which multiplies the value by 2^60 for suffixes E
112 * and e, 2^50 for suffixes P and p, 2^40 for suffixes T and t,
113 * 2^30 for suffixes G and g, 2^20 for M and m, 2^10 for K and k
114 * 'T' double
115 * user mode accepts an optional ms, us, ns suffix,
116 * which divides the value by 1e3, 1e6, 1e9, respectively
117 * '/' optional gdb-like print format (like "/10x")
119 * '?' optional type (for all types, except '/')
120 * '.' other form of optional type (for 'i' and 'l')
121 * 'b' boolean
122 * user mode accepts "on" or "off"
123 * '-' optional parameter (eg. '-f')
127 typedef struct mon_cmd_t {
128 const char *name;
129 const char *args_type;
130 const char *params;
131 const char *help;
132 union {
133 void (*cmd)(Monitor *mon, const QDict *qdict);
134 void (*cmd_new)(QDict *params, QObject **ret_data, Error **errp);
135 } mhandler;
136 /* @sub_table is a list of 2nd level of commands. If it do not exist,
137 * mhandler should be used. If it exist, sub_table[?].mhandler should be
138 * used, and mhandler of 1st level plays the role of help function.
140 struct mon_cmd_t *sub_table;
141 void (*command_completion)(ReadLineState *rs, int nb_args, const char *str);
142 } mon_cmd_t;
144 /* file descriptors passed via SCM_RIGHTS */
145 typedef struct mon_fd_t mon_fd_t;
146 struct mon_fd_t {
147 char *name;
148 int fd;
149 QLIST_ENTRY(mon_fd_t) next;
152 /* file descriptor associated with a file descriptor set */
153 typedef struct MonFdsetFd MonFdsetFd;
154 struct MonFdsetFd {
155 int fd;
156 bool removed;
157 char *opaque;
158 QLIST_ENTRY(MonFdsetFd) next;
161 /* file descriptor set containing fds passed via SCM_RIGHTS */
162 typedef struct MonFdset MonFdset;
163 struct MonFdset {
164 int64_t id;
165 QLIST_HEAD(, MonFdsetFd) fds;
166 QLIST_HEAD(, MonFdsetFd) dup_fds;
167 QLIST_ENTRY(MonFdset) next;
170 typedef struct {
171 QObject *id;
172 JSONMessageParser parser;
174 * When a client connects, we're in capabilities negotiation mode.
175 * When command qmp_capabilities succeeds, we go into command
176 * mode.
178 bool in_command_mode; /* are we in command mode? */
179 } MonitorQMP;
182 * To prevent flooding clients, events can be throttled. The
183 * throttling is calculated globally, rather than per-Monitor
184 * instance.
186 typedef struct MonitorQAPIEventState {
187 QAPIEvent event; /* Throttling state for this event type and... */
188 QDict *data; /* ... data, see qapi_event_throttle_equal() */
189 QEMUTimer *timer; /* Timer for handling delayed events */
190 QDict *qdict; /* Delayed event (if any) */
191 } MonitorQAPIEventState;
193 typedef struct {
194 int64_t rate; /* Minimum time (in ns) between two events */
195 } MonitorQAPIEventConf;
197 struct Monitor {
198 CharDriverState *chr;
199 int reset_seen;
200 int flags;
201 int suspend_cnt;
202 bool skip_flush;
204 QemuMutex out_lock;
205 QString *outbuf;
206 guint out_watch;
208 /* Read under either BQL or out_lock, written with BQL+out_lock. */
209 int mux_out;
211 ReadLineState *rs;
212 MonitorQMP qmp;
213 CPUState *mon_cpu;
214 BlockCompletionFunc *password_completion_cb;
215 void *password_opaque;
216 mon_cmd_t *cmd_table;
217 QLIST_HEAD(,mon_fd_t) fds;
218 QLIST_ENTRY(Monitor) entry;
221 /* QMP checker flags */
222 #define QMP_ACCEPT_UNKNOWNS 1
224 /* Protects mon_list, monitor_event_state. */
225 static QemuMutex monitor_lock;
227 static QLIST_HEAD(mon_list, Monitor) mon_list;
228 static QLIST_HEAD(mon_fdsets, MonFdset) mon_fdsets;
229 static int mon_refcount;
231 static mon_cmd_t mon_cmds[];
232 static mon_cmd_t info_cmds[];
234 static const mon_cmd_t qmp_cmds[];
236 Monitor *cur_mon;
238 static QEMUClockType event_clock_type = QEMU_CLOCK_REALTIME;
240 static void monitor_command_cb(void *opaque, const char *cmdline,
241 void *readline_opaque);
244 * Is @mon a QMP monitor?
246 static inline bool monitor_is_qmp(const Monitor *mon)
248 return (mon->flags & MONITOR_USE_CONTROL);
252 * Is the current monitor, if any, a QMP monitor?
254 bool monitor_cur_is_qmp(void)
256 return cur_mon && monitor_is_qmp(cur_mon);
259 void monitor_read_command(Monitor *mon, int show_prompt)
261 if (!mon->rs)
262 return;
264 readline_start(mon->rs, "(qemu) ", 0, monitor_command_cb, NULL);
265 if (show_prompt)
266 readline_show_prompt(mon->rs);
269 int monitor_read_password(Monitor *mon, ReadLineFunc *readline_func,
270 void *opaque)
272 if (mon->rs) {
273 readline_start(mon->rs, "Password: ", 1, readline_func, opaque);
274 /* prompt is printed on return from the command handler */
275 return 0;
276 } else {
277 monitor_printf(mon, "terminal does not support password prompting\n");
278 return -ENOTTY;
282 static void monitor_flush_locked(Monitor *mon);
284 static gboolean monitor_unblocked(GIOChannel *chan, GIOCondition cond,
285 void *opaque)
287 Monitor *mon = opaque;
289 qemu_mutex_lock(&mon->out_lock);
290 mon->out_watch = 0;
291 monitor_flush_locked(mon);
292 qemu_mutex_unlock(&mon->out_lock);
293 return FALSE;
296 /* Called with mon->out_lock held. */
297 static void monitor_flush_locked(Monitor *mon)
299 int rc;
300 size_t len;
301 const char *buf;
303 if (mon->skip_flush) {
304 return;
307 buf = qstring_get_str(mon->outbuf);
308 len = qstring_get_length(mon->outbuf);
310 if (len && !mon->mux_out) {
311 rc = qemu_chr_fe_write(mon->chr, (const uint8_t *) buf, len);
312 if ((rc < 0 && errno != EAGAIN) || (rc == len)) {
313 /* all flushed or error */
314 QDECREF(mon->outbuf);
315 mon->outbuf = qstring_new();
316 return;
318 if (rc > 0) {
319 /* partial write */
320 QString *tmp = qstring_from_str(buf + rc);
321 QDECREF(mon->outbuf);
322 mon->outbuf = tmp;
324 if (mon->out_watch == 0) {
325 mon->out_watch = qemu_chr_fe_add_watch(mon->chr, G_IO_OUT|G_IO_HUP,
326 monitor_unblocked, mon);
331 void monitor_flush(Monitor *mon)
333 qemu_mutex_lock(&mon->out_lock);
334 monitor_flush_locked(mon);
335 qemu_mutex_unlock(&mon->out_lock);
338 /* flush at every end of line */
339 static void monitor_puts(Monitor *mon, const char *str)
341 char c;
343 qemu_mutex_lock(&mon->out_lock);
344 for(;;) {
345 c = *str++;
346 if (c == '\0')
347 break;
348 if (c == '\n') {
349 qstring_append_chr(mon->outbuf, '\r');
351 qstring_append_chr(mon->outbuf, c);
352 if (c == '\n') {
353 monitor_flush_locked(mon);
356 qemu_mutex_unlock(&mon->out_lock);
359 void monitor_vprintf(Monitor *mon, const char *fmt, va_list ap)
361 char *buf;
363 if (!mon)
364 return;
366 if (monitor_is_qmp(mon)) {
367 return;
370 buf = g_strdup_vprintf(fmt, ap);
371 monitor_puts(mon, buf);
372 g_free(buf);
375 void monitor_printf(Monitor *mon, const char *fmt, ...)
377 va_list ap;
378 va_start(ap, fmt);
379 monitor_vprintf(mon, fmt, ap);
380 va_end(ap);
383 int monitor_fprintf(FILE *stream, const char *fmt, ...)
385 va_list ap;
386 va_start(ap, fmt);
387 monitor_vprintf((Monitor *)stream, fmt, ap);
388 va_end(ap);
389 return 0;
392 static void monitor_json_emitter(Monitor *mon, const QObject *data)
394 QString *json;
396 json = mon->flags & MONITOR_USE_PRETTY ? qobject_to_json_pretty(data) :
397 qobject_to_json(data);
398 assert(json != NULL);
400 qstring_append_chr(json, '\n');
401 monitor_puts(mon, qstring_get_str(json));
403 QDECREF(json);
406 static QDict *build_qmp_error_dict(Error *err)
408 QObject *obj;
410 obj = qobject_from_jsonf("{ 'error': { 'class': %s, 'desc': %s } }",
411 QapiErrorClass_lookup[error_get_class(err)],
412 error_get_pretty(err));
414 return qobject_to_qdict(obj);
417 static void monitor_protocol_emitter(Monitor *mon, QObject *data,
418 Error *err)
420 QDict *qmp;
422 trace_monitor_protocol_emitter(mon);
424 if (!err) {
425 /* success response */
426 qmp = qdict_new();
427 if (data) {
428 qobject_incref(data);
429 qdict_put_obj(qmp, "return", data);
430 } else {
431 /* return an empty QDict by default */
432 qdict_put(qmp, "return", qdict_new());
434 } else {
435 /* error response */
436 qmp = build_qmp_error_dict(err);
439 if (mon->qmp.id) {
440 qdict_put_obj(qmp, "id", mon->qmp.id);
441 mon->qmp.id = NULL;
444 monitor_json_emitter(mon, QOBJECT(qmp));
445 QDECREF(qmp);
449 static MonitorQAPIEventConf monitor_qapi_event_conf[QAPI_EVENT__MAX] = {
450 /* Limit guest-triggerable events to 1 per second */
451 [QAPI_EVENT_RTC_CHANGE] = { 1000 * SCALE_MS },
452 [QAPI_EVENT_WATCHDOG] = { 1000 * SCALE_MS },
453 [QAPI_EVENT_BALLOON_CHANGE] = { 1000 * SCALE_MS },
454 [QAPI_EVENT_QUORUM_REPORT_BAD] = { 1000 * SCALE_MS },
455 [QAPI_EVENT_QUORUM_FAILURE] = { 1000 * SCALE_MS },
456 [QAPI_EVENT_VSERPORT_CHANGE] = { 1000 * SCALE_MS },
459 GHashTable *monitor_qapi_event_state;
462 * Emits the event to every monitor instance, @event is only used for trace
463 * Called with monitor_lock held.
465 static void monitor_qapi_event_emit(QAPIEvent event, QDict *qdict)
467 Monitor *mon;
469 trace_monitor_protocol_event_emit(event, qdict);
470 QLIST_FOREACH(mon, &mon_list, entry) {
471 if (monitor_is_qmp(mon) && mon->qmp.in_command_mode) {
472 monitor_json_emitter(mon, QOBJECT(qdict));
477 static void monitor_qapi_event_handler(void *opaque);
480 * Queue a new event for emission to Monitor instances,
481 * applying any rate limiting if required.
483 static void
484 monitor_qapi_event_queue(QAPIEvent event, QDict *qdict, Error **errp)
486 MonitorQAPIEventConf *evconf;
487 MonitorQAPIEventState *evstate;
489 assert(event < QAPI_EVENT__MAX);
490 evconf = &monitor_qapi_event_conf[event];
491 trace_monitor_protocol_event_queue(event, qdict, evconf->rate);
493 qemu_mutex_lock(&monitor_lock);
495 if (!evconf->rate) {
496 /* Unthrottled event */
497 monitor_qapi_event_emit(event, qdict);
498 } else {
499 QDict *data = qobject_to_qdict(qdict_get(qdict, "data"));
500 MonitorQAPIEventState key = { .event = event, .data = data };
502 evstate = g_hash_table_lookup(monitor_qapi_event_state, &key);
503 assert(!evstate || timer_pending(evstate->timer));
505 if (evstate) {
507 * Timer is pending for (at least) evconf->rate ns after
508 * last send. Store event for sending when timer fires,
509 * replacing a prior stored event if any.
511 QDECREF(evstate->qdict);
512 evstate->qdict = qdict;
513 QINCREF(evstate->qdict);
514 } else {
516 * Last send was (at least) evconf->rate ns ago.
517 * Send immediately, and arm the timer to call
518 * monitor_qapi_event_handler() in evconf->rate ns. Any
519 * events arriving before then will be delayed until then.
521 int64_t now = qemu_clock_get_ns(event_clock_type);
523 monitor_qapi_event_emit(event, qdict);
525 evstate = g_new(MonitorQAPIEventState, 1);
526 evstate->event = event;
527 evstate->data = data;
528 QINCREF(evstate->data);
529 evstate->qdict = NULL;
530 evstate->timer = timer_new_ns(event_clock_type,
531 monitor_qapi_event_handler,
532 evstate);
533 g_hash_table_add(monitor_qapi_event_state, evstate);
534 timer_mod_ns(evstate->timer, now + evconf->rate);
538 qemu_mutex_unlock(&monitor_lock);
542 * This function runs evconf->rate ns after sending a throttled
543 * event.
544 * If another event has since been stored, send it.
546 static void monitor_qapi_event_handler(void *opaque)
548 MonitorQAPIEventState *evstate = opaque;
549 MonitorQAPIEventConf *evconf = &monitor_qapi_event_conf[evstate->event];
551 trace_monitor_protocol_event_handler(evstate->event, evstate->qdict);
552 qemu_mutex_lock(&monitor_lock);
554 if (evstate->qdict) {
555 int64_t now = qemu_clock_get_ns(event_clock_type);
557 monitor_qapi_event_emit(evstate->event, evstate->qdict);
558 QDECREF(evstate->qdict);
559 evstate->qdict = NULL;
560 timer_mod_ns(evstate->timer, now + evconf->rate);
561 } else {
562 g_hash_table_remove(monitor_qapi_event_state, evstate);
563 QDECREF(evstate->data);
564 timer_free(evstate->timer);
565 g_free(evstate);
568 qemu_mutex_unlock(&monitor_lock);
571 static unsigned int qapi_event_throttle_hash(const void *key)
573 const MonitorQAPIEventState *evstate = key;
574 unsigned int hash = evstate->event * 255;
576 if (evstate->event == QAPI_EVENT_VSERPORT_CHANGE) {
577 hash += g_str_hash(qdict_get_str(evstate->data, "id"));
580 if (evstate->event == QAPI_EVENT_QUORUM_REPORT_BAD) {
581 hash += g_str_hash(qdict_get_str(evstate->data, "node-name"));
584 return hash;
587 static gboolean qapi_event_throttle_equal(const void *a, const void *b)
589 const MonitorQAPIEventState *eva = a;
590 const MonitorQAPIEventState *evb = b;
592 if (eva->event != evb->event) {
593 return FALSE;
596 if (eva->event == QAPI_EVENT_VSERPORT_CHANGE) {
597 return !strcmp(qdict_get_str(eva->data, "id"),
598 qdict_get_str(evb->data, "id"));
601 if (eva->event == QAPI_EVENT_QUORUM_REPORT_BAD) {
602 return !strcmp(qdict_get_str(eva->data, "node-name"),
603 qdict_get_str(evb->data, "node-name"));
606 return TRUE;
609 static void monitor_qapi_event_init(void)
611 if (qtest_enabled()) {
612 event_clock_type = QEMU_CLOCK_VIRTUAL;
615 monitor_qapi_event_state = g_hash_table_new(qapi_event_throttle_hash,
616 qapi_event_throttle_equal);
617 qmp_event_set_func_emit(monitor_qapi_event_queue);
620 static void qmp_capabilities(QDict *params, QObject **ret_data, Error **errp)
622 cur_mon->qmp.in_command_mode = true;
625 static void handle_hmp_command(Monitor *mon, const char *cmdline);
627 static void monitor_data_init(Monitor *mon)
629 memset(mon, 0, sizeof(Monitor));
630 qemu_mutex_init(&mon->out_lock);
631 mon->outbuf = qstring_new();
632 /* Use *mon_cmds by default. */
633 mon->cmd_table = mon_cmds;
636 static void monitor_data_destroy(Monitor *mon)
638 if (mon->chr) {
639 qemu_chr_add_handlers(mon->chr, NULL, NULL, NULL, NULL);
641 if (monitor_is_qmp(mon)) {
642 json_message_parser_destroy(&mon->qmp.parser);
644 g_free(mon->rs);
645 QDECREF(mon->outbuf);
646 qemu_mutex_destroy(&mon->out_lock);
649 char *qmp_human_monitor_command(const char *command_line, bool has_cpu_index,
650 int64_t cpu_index, Error **errp)
652 char *output = NULL;
653 Monitor *old_mon, hmp;
655 monitor_data_init(&hmp);
656 hmp.skip_flush = true;
658 old_mon = cur_mon;
659 cur_mon = &hmp;
661 if (has_cpu_index) {
662 int ret = monitor_set_cpu(cpu_index);
663 if (ret < 0) {
664 cur_mon = old_mon;
665 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cpu-index",
666 "a CPU number");
667 goto out;
671 handle_hmp_command(&hmp, command_line);
672 cur_mon = old_mon;
674 qemu_mutex_lock(&hmp.out_lock);
675 if (qstring_get_length(hmp.outbuf) > 0) {
676 output = g_strdup(qstring_get_str(hmp.outbuf));
677 } else {
678 output = g_strdup("");
680 qemu_mutex_unlock(&hmp.out_lock);
682 out:
683 monitor_data_destroy(&hmp);
684 return output;
687 static int compare_cmd(const char *name, const char *list)
689 const char *p, *pstart;
690 int len;
691 len = strlen(name);
692 p = list;
693 for(;;) {
694 pstart = p;
695 p = strchr(p, '|');
696 if (!p)
697 p = pstart + strlen(pstart);
698 if ((p - pstart) == len && !memcmp(pstart, name, len))
699 return 1;
700 if (*p == '\0')
701 break;
702 p++;
704 return 0;
707 static int get_str(char *buf, int buf_size, const char **pp)
709 const char *p;
710 char *q;
711 int c;
713 q = buf;
714 p = *pp;
715 while (qemu_isspace(*p)) {
716 p++;
718 if (*p == '\0') {
719 fail:
720 *q = '\0';
721 *pp = p;
722 return -1;
724 if (*p == '\"') {
725 p++;
726 while (*p != '\0' && *p != '\"') {
727 if (*p == '\\') {
728 p++;
729 c = *p++;
730 switch (c) {
731 case 'n':
732 c = '\n';
733 break;
734 case 'r':
735 c = '\r';
736 break;
737 case '\\':
738 case '\'':
739 case '\"':
740 break;
741 default:
742 printf("unsupported escape code: '\\%c'\n", c);
743 goto fail;
745 if ((q - buf) < buf_size - 1) {
746 *q++ = c;
748 } else {
749 if ((q - buf) < buf_size - 1) {
750 *q++ = *p;
752 p++;
755 if (*p != '\"') {
756 printf("unterminated string\n");
757 goto fail;
759 p++;
760 } else {
761 while (*p != '\0' && !qemu_isspace(*p)) {
762 if ((q - buf) < buf_size - 1) {
763 *q++ = *p;
765 p++;
768 *q = '\0';
769 *pp = p;
770 return 0;
773 #define MAX_ARGS 16
775 static void free_cmdline_args(char **args, int nb_args)
777 int i;
779 assert(nb_args <= MAX_ARGS);
781 for (i = 0; i < nb_args; i++) {
782 g_free(args[i]);
788 * Parse the command line to get valid args.
789 * @cmdline: command line to be parsed.
790 * @pnb_args: location to store the number of args, must NOT be NULL.
791 * @args: location to store the args, which should be freed by caller, must
792 * NOT be NULL.
794 * Returns 0 on success, negative on failure.
796 * NOTE: this parser is an approximate form of the real command parser. Number
797 * of args have a limit of MAX_ARGS. If cmdline contains more, it will
798 * return with failure.
800 static int parse_cmdline(const char *cmdline,
801 int *pnb_args, char **args)
803 const char *p;
804 int nb_args, ret;
805 char buf[1024];
807 p = cmdline;
808 nb_args = 0;
809 for (;;) {
810 while (qemu_isspace(*p)) {
811 p++;
813 if (*p == '\0') {
814 break;
816 if (nb_args >= MAX_ARGS) {
817 goto fail;
819 ret = get_str(buf, sizeof(buf), &p);
820 if (ret < 0) {
821 goto fail;
823 args[nb_args] = g_strdup(buf);
824 nb_args++;
826 *pnb_args = nb_args;
827 return 0;
829 fail:
830 free_cmdline_args(args, nb_args);
831 return -1;
834 static void help_cmd_dump_one(Monitor *mon,
835 const mon_cmd_t *cmd,
836 char **prefix_args,
837 int prefix_args_nb)
839 int i;
841 for (i = 0; i < prefix_args_nb; i++) {
842 monitor_printf(mon, "%s ", prefix_args[i]);
844 monitor_printf(mon, "%s %s -- %s\n", cmd->name, cmd->params, cmd->help);
847 /* @args[@arg_index] is the valid command need to find in @cmds */
848 static void help_cmd_dump(Monitor *mon, const mon_cmd_t *cmds,
849 char **args, int nb_args, int arg_index)
851 const mon_cmd_t *cmd;
853 /* No valid arg need to compare with, dump all in *cmds */
854 if (arg_index >= nb_args) {
855 for (cmd = cmds; cmd->name != NULL; cmd++) {
856 help_cmd_dump_one(mon, cmd, args, arg_index);
858 return;
861 /* Find one entry to dump */
862 for (cmd = cmds; cmd->name != NULL; cmd++) {
863 if (compare_cmd(args[arg_index], cmd->name)) {
864 if (cmd->sub_table) {
865 /* continue with next arg */
866 help_cmd_dump(mon, cmd->sub_table,
867 args, nb_args, arg_index + 1);
868 } else {
869 help_cmd_dump_one(mon, cmd, args, arg_index);
871 break;
876 static void help_cmd(Monitor *mon, const char *name)
878 char *args[MAX_ARGS];
879 int nb_args = 0;
881 /* 1. parse user input */
882 if (name) {
883 /* special case for log, directly dump and return */
884 if (!strcmp(name, "log")) {
885 const QEMULogItem *item;
886 monitor_printf(mon, "Log items (comma separated):\n");
887 monitor_printf(mon, "%-10s %s\n", "none", "remove all logs");
888 for (item = qemu_log_items; item->mask != 0; item++) {
889 monitor_printf(mon, "%-10s %s\n", item->name, item->help);
891 return;
894 if (parse_cmdline(name, &nb_args, args) < 0) {
895 return;
899 /* 2. dump the contents according to parsed args */
900 help_cmd_dump(mon, mon->cmd_table, args, nb_args, 0);
902 free_cmdline_args(args, nb_args);
905 static void do_help_cmd(Monitor *mon, const QDict *qdict)
907 help_cmd(mon, qdict_get_try_str(qdict, "name"));
910 static void hmp_trace_event(Monitor *mon, const QDict *qdict)
912 const char *tp_name = qdict_get_str(qdict, "name");
913 bool new_state = qdict_get_bool(qdict, "option");
914 bool has_vcpu = qdict_haskey(qdict, "vcpu");
915 int vcpu = qdict_get_try_int(qdict, "vcpu", 0);
916 Error *local_err = NULL;
918 if (vcpu < 0) {
919 monitor_printf(mon, "argument vcpu must be positive");
920 return;
923 qmp_trace_event_set_state(tp_name, new_state, true, true, has_vcpu, vcpu, &local_err);
924 if (local_err) {
925 error_report_err(local_err);
929 #ifdef CONFIG_TRACE_SIMPLE
930 static void hmp_trace_file(Monitor *mon, const QDict *qdict)
932 const char *op = qdict_get_try_str(qdict, "op");
933 const char *arg = qdict_get_try_str(qdict, "arg");
935 if (!op) {
936 st_print_trace_file_status((FILE *)mon, &monitor_fprintf);
937 } else if (!strcmp(op, "on")) {
938 st_set_trace_file_enabled(true);
939 } else if (!strcmp(op, "off")) {
940 st_set_trace_file_enabled(false);
941 } else if (!strcmp(op, "flush")) {
942 st_flush_trace_buffer();
943 } else if (!strcmp(op, "set")) {
944 if (arg) {
945 st_set_trace_file(arg);
947 } else {
948 monitor_printf(mon, "unexpected argument \"%s\"\n", op);
949 help_cmd(mon, "trace-file");
952 #endif
954 static void hmp_info_help(Monitor *mon, const QDict *qdict)
956 help_cmd(mon, "info");
959 CommandInfoList *qmp_query_commands(Error **errp)
961 CommandInfoList *info, *cmd_list = NULL;
962 const mon_cmd_t *cmd;
964 for (cmd = qmp_cmds; cmd->name != NULL; cmd++) {
965 info = g_malloc0(sizeof(*info));
966 info->value = g_malloc0(sizeof(*info->value));
967 info->value->name = g_strdup(cmd->name);
969 info->next = cmd_list;
970 cmd_list = info;
973 return cmd_list;
976 EventInfoList *qmp_query_events(Error **errp)
978 EventInfoList *info, *ev_list = NULL;
979 QAPIEvent e;
981 for (e = 0 ; e < QAPI_EVENT__MAX ; e++) {
982 const char *event_name = QAPIEvent_lookup[e];
983 assert(event_name != NULL);
984 info = g_malloc0(sizeof(*info));
985 info->value = g_malloc0(sizeof(*info->value));
986 info->value->name = g_strdup(event_name);
988 info->next = ev_list;
989 ev_list = info;
992 return ev_list;
996 * Minor hack: generated marshalling suppressed for this command
997 * ('gen': false in the schema) so we can parse the JSON string
998 * directly into QObject instead of first parsing it with
999 * visit_type_SchemaInfoList() into a SchemaInfoList, then marshal it
1000 * to QObject with generated output marshallers, every time. Instead,
1001 * we do it in test-qmp-input-visitor.c, just to make sure
1002 * qapi-introspect.py's output actually conforms to the schema.
1004 static void qmp_query_qmp_schema(QDict *qdict, QObject **ret_data,
1005 Error **errp)
1007 *ret_data = qobject_from_json(qmp_schema_json);
1010 /* set the current CPU defined by the user */
1011 int monitor_set_cpu(int cpu_index)
1013 CPUState *cpu;
1015 cpu = qemu_get_cpu(cpu_index);
1016 if (cpu == NULL) {
1017 return -1;
1019 cur_mon->mon_cpu = cpu;
1020 return 0;
1023 CPUState *mon_get_cpu(void)
1025 if (!cur_mon->mon_cpu) {
1026 monitor_set_cpu(0);
1028 cpu_synchronize_state(cur_mon->mon_cpu);
1029 return cur_mon->mon_cpu;
1032 CPUArchState *mon_get_cpu_env(void)
1034 return mon_get_cpu()->env_ptr;
1037 int monitor_get_cpu_index(void)
1039 return mon_get_cpu()->cpu_index;
1042 static void hmp_info_registers(Monitor *mon, const QDict *qdict)
1044 cpu_dump_state(mon_get_cpu(), (FILE *)mon, monitor_fprintf, CPU_DUMP_FPU);
1047 static void hmp_info_jit(Monitor *mon, const QDict *qdict)
1049 dump_exec_info((FILE *)mon, monitor_fprintf);
1050 dump_drift_info((FILE *)mon, monitor_fprintf);
1053 static void hmp_info_opcount(Monitor *mon, const QDict *qdict)
1055 dump_opcount_info((FILE *)mon, monitor_fprintf);
1058 static void hmp_info_history(Monitor *mon, const QDict *qdict)
1060 int i;
1061 const char *str;
1063 if (!mon->rs)
1064 return;
1065 i = 0;
1066 for(;;) {
1067 str = readline_get_history(mon->rs, i);
1068 if (!str)
1069 break;
1070 monitor_printf(mon, "%d: '%s'\n", i, str);
1071 i++;
1075 static void hmp_info_cpustats(Monitor *mon, const QDict *qdict)
1077 cpu_dump_statistics(mon_get_cpu(), (FILE *)mon, &monitor_fprintf, 0);
1080 static void hmp_info_trace_events(Monitor *mon, const QDict *qdict)
1082 const char *name = qdict_get_try_str(qdict, "name");
1083 bool has_vcpu = qdict_haskey(qdict, "vcpu");
1084 int vcpu = qdict_get_try_int(qdict, "vcpu", 0);
1085 TraceEventInfoList *events;
1086 TraceEventInfoList *elem;
1087 Error *local_err = NULL;
1089 if (name == NULL) {
1090 name = "*";
1092 if (vcpu < 0) {
1093 monitor_printf(mon, "argument vcpu must be positive");
1094 return;
1097 events = qmp_trace_event_get_state(name, has_vcpu, vcpu, &local_err);
1098 if (local_err) {
1099 error_report_err(local_err);
1100 return;
1103 for (elem = events; elem != NULL; elem = elem->next) {
1104 monitor_printf(mon, "%s : state %u\n",
1105 elem->value->name,
1106 elem->value->state == TRACE_EVENT_STATE_ENABLED ? 1 : 0);
1108 qapi_free_TraceEventInfoList(events);
1111 void qmp_client_migrate_info(const char *protocol, const char *hostname,
1112 bool has_port, int64_t port,
1113 bool has_tls_port, int64_t tls_port,
1114 bool has_cert_subject, const char *cert_subject,
1115 Error **errp)
1117 if (strcmp(protocol, "spice") == 0) {
1118 if (!qemu_using_spice(errp)) {
1119 return;
1122 if (!has_port && !has_tls_port) {
1123 error_setg(errp, QERR_MISSING_PARAMETER, "port/tls-port");
1124 return;
1127 if (qemu_spice_migrate_info(hostname,
1128 has_port ? port : -1,
1129 has_tls_port ? tls_port : -1,
1130 cert_subject)) {
1131 error_setg(errp, QERR_UNDEFINED_ERROR);
1132 return;
1134 return;
1137 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "protocol", "spice");
1140 static void hmp_logfile(Monitor *mon, const QDict *qdict)
1142 Error *err = NULL;
1144 qemu_set_log_filename(qdict_get_str(qdict, "filename"), &err);
1145 if (err) {
1146 error_report_err(err);
1150 static void hmp_log(Monitor *mon, const QDict *qdict)
1152 int mask;
1153 const char *items = qdict_get_str(qdict, "items");
1155 if (!strcmp(items, "none")) {
1156 mask = 0;
1157 } else {
1158 mask = qemu_str_to_log_mask(items);
1159 if (!mask) {
1160 help_cmd(mon, "log");
1161 return;
1164 qemu_set_log(mask);
1167 static void hmp_singlestep(Monitor *mon, const QDict *qdict)
1169 const char *option = qdict_get_try_str(qdict, "option");
1170 if (!option || !strcmp(option, "on")) {
1171 singlestep = 1;
1172 } else if (!strcmp(option, "off")) {
1173 singlestep = 0;
1174 } else {
1175 monitor_printf(mon, "unexpected option %s\n", option);
1179 static void hmp_gdbserver(Monitor *mon, const QDict *qdict)
1181 const char *device = qdict_get_try_str(qdict, "device");
1182 if (!device)
1183 device = "tcp::" DEFAULT_GDBSTUB_PORT;
1184 if (gdbserver_start(device) < 0) {
1185 monitor_printf(mon, "Could not open gdbserver on device '%s'\n",
1186 device);
1187 } else if (strcmp(device, "none") == 0) {
1188 monitor_printf(mon, "Disabled gdbserver\n");
1189 } else {
1190 monitor_printf(mon, "Waiting for gdb connection on device '%s'\n",
1191 device);
1195 static void hmp_watchdog_action(Monitor *mon, const QDict *qdict)
1197 const char *action = qdict_get_str(qdict, "action");
1198 if (select_watchdog_action(action) == -1) {
1199 monitor_printf(mon, "Unknown watchdog action '%s'\n", action);
1203 static void monitor_printc(Monitor *mon, int c)
1205 monitor_printf(mon, "'");
1206 switch(c) {
1207 case '\'':
1208 monitor_printf(mon, "\\'");
1209 break;
1210 case '\\':
1211 monitor_printf(mon, "\\\\");
1212 break;
1213 case '\n':
1214 monitor_printf(mon, "\\n");
1215 break;
1216 case '\r':
1217 monitor_printf(mon, "\\r");
1218 break;
1219 default:
1220 if (c >= 32 && c <= 126) {
1221 monitor_printf(mon, "%c", c);
1222 } else {
1223 monitor_printf(mon, "\\x%02x", c);
1225 break;
1227 monitor_printf(mon, "'");
1230 static void memory_dump(Monitor *mon, int count, int format, int wsize,
1231 hwaddr addr, int is_physical)
1233 int l, line_size, i, max_digits, len;
1234 uint8_t buf[16];
1235 uint64_t v;
1237 if (format == 'i') {
1238 int flags = 0;
1239 #ifdef TARGET_I386
1240 CPUArchState *env = mon_get_cpu_env();
1241 if (wsize == 2) {
1242 flags = 1;
1243 } else if (wsize == 4) {
1244 flags = 0;
1245 } else {
1246 /* as default we use the current CS size */
1247 flags = 0;
1248 if (env) {
1249 #ifdef TARGET_X86_64
1250 if ((env->efer & MSR_EFER_LMA) &&
1251 (env->segs[R_CS].flags & DESC_L_MASK))
1252 flags = 2;
1253 else
1254 #endif
1255 if (!(env->segs[R_CS].flags & DESC_B_MASK))
1256 flags = 1;
1259 #endif
1260 #ifdef TARGET_PPC
1261 CPUArchState *env = mon_get_cpu_env();
1262 flags = msr_le << 16;
1263 flags |= env->bfd_mach;
1264 #endif
1265 monitor_disas(mon, mon_get_cpu(), addr, count, is_physical, flags);
1266 return;
1269 len = wsize * count;
1270 if (wsize == 1)
1271 line_size = 8;
1272 else
1273 line_size = 16;
1274 max_digits = 0;
1276 switch(format) {
1277 case 'o':
1278 max_digits = (wsize * 8 + 2) / 3;
1279 break;
1280 default:
1281 case 'x':
1282 max_digits = (wsize * 8) / 4;
1283 break;
1284 case 'u':
1285 case 'd':
1286 max_digits = (wsize * 8 * 10 + 32) / 33;
1287 break;
1288 case 'c':
1289 wsize = 1;
1290 break;
1293 while (len > 0) {
1294 if (is_physical)
1295 monitor_printf(mon, TARGET_FMT_plx ":", addr);
1296 else
1297 monitor_printf(mon, TARGET_FMT_lx ":", (target_ulong)addr);
1298 l = len;
1299 if (l > line_size)
1300 l = line_size;
1301 if (is_physical) {
1302 cpu_physical_memory_read(addr, buf, l);
1303 } else {
1304 if (cpu_memory_rw_debug(mon_get_cpu(), addr, buf, l, 0) < 0) {
1305 monitor_printf(mon, " Cannot access memory\n");
1306 break;
1309 i = 0;
1310 while (i < l) {
1311 switch(wsize) {
1312 default:
1313 case 1:
1314 v = ldub_p(buf + i);
1315 break;
1316 case 2:
1317 v = lduw_p(buf + i);
1318 break;
1319 case 4:
1320 v = (uint32_t)ldl_p(buf + i);
1321 break;
1322 case 8:
1323 v = ldq_p(buf + i);
1324 break;
1326 monitor_printf(mon, " ");
1327 switch(format) {
1328 case 'o':
1329 monitor_printf(mon, "%#*" PRIo64, max_digits, v);
1330 break;
1331 case 'x':
1332 monitor_printf(mon, "0x%0*" PRIx64, max_digits, v);
1333 break;
1334 case 'u':
1335 monitor_printf(mon, "%*" PRIu64, max_digits, v);
1336 break;
1337 case 'd':
1338 monitor_printf(mon, "%*" PRId64, max_digits, v);
1339 break;
1340 case 'c':
1341 monitor_printc(mon, v);
1342 break;
1344 i += wsize;
1346 monitor_printf(mon, "\n");
1347 addr += l;
1348 len -= l;
1352 static void hmp_memory_dump(Monitor *mon, const QDict *qdict)
1354 int count = qdict_get_int(qdict, "count");
1355 int format = qdict_get_int(qdict, "format");
1356 int size = qdict_get_int(qdict, "size");
1357 target_long addr = qdict_get_int(qdict, "addr");
1359 memory_dump(mon, count, format, size, addr, 0);
1362 static void hmp_physical_memory_dump(Monitor *mon, const QDict *qdict)
1364 int count = qdict_get_int(qdict, "count");
1365 int format = qdict_get_int(qdict, "format");
1366 int size = qdict_get_int(qdict, "size");
1367 hwaddr addr = qdict_get_int(qdict, "addr");
1369 memory_dump(mon, count, format, size, addr, 1);
1372 static void do_print(Monitor *mon, const QDict *qdict)
1374 int format = qdict_get_int(qdict, "format");
1375 hwaddr val = qdict_get_int(qdict, "val");
1377 switch(format) {
1378 case 'o':
1379 monitor_printf(mon, "%#" HWADDR_PRIo, val);
1380 break;
1381 case 'x':
1382 monitor_printf(mon, "%#" HWADDR_PRIx, val);
1383 break;
1384 case 'u':
1385 monitor_printf(mon, "%" HWADDR_PRIu, val);
1386 break;
1387 default:
1388 case 'd':
1389 monitor_printf(mon, "%" HWADDR_PRId, val);
1390 break;
1391 case 'c':
1392 monitor_printc(mon, val);
1393 break;
1395 monitor_printf(mon, "\n");
1398 static void hmp_sum(Monitor *mon, const QDict *qdict)
1400 uint32_t addr;
1401 uint16_t sum;
1402 uint32_t start = qdict_get_int(qdict, "start");
1403 uint32_t size = qdict_get_int(qdict, "size");
1405 sum = 0;
1406 for(addr = start; addr < (start + size); addr++) {
1407 uint8_t val = address_space_ldub(&address_space_memory, addr,
1408 MEMTXATTRS_UNSPECIFIED, NULL);
1409 /* BSD sum algorithm ('sum' Unix command) */
1410 sum = (sum >> 1) | (sum << 15);
1411 sum += val;
1413 monitor_printf(mon, "%05d\n", sum);
1416 static int mouse_button_state;
1418 static void hmp_mouse_move(Monitor *mon, const QDict *qdict)
1420 int dx, dy, dz, button;
1421 const char *dx_str = qdict_get_str(qdict, "dx_str");
1422 const char *dy_str = qdict_get_str(qdict, "dy_str");
1423 const char *dz_str = qdict_get_try_str(qdict, "dz_str");
1425 dx = strtol(dx_str, NULL, 0);
1426 dy = strtol(dy_str, NULL, 0);
1427 qemu_input_queue_rel(NULL, INPUT_AXIS_X, dx);
1428 qemu_input_queue_rel(NULL, INPUT_AXIS_Y, dy);
1430 if (dz_str) {
1431 dz = strtol(dz_str, NULL, 0);
1432 if (dz != 0) {
1433 button = (dz > 0) ? INPUT_BUTTON_WHEEL_UP : INPUT_BUTTON_WHEEL_DOWN;
1434 qemu_input_queue_btn(NULL, button, true);
1435 qemu_input_event_sync();
1436 qemu_input_queue_btn(NULL, button, false);
1439 qemu_input_event_sync();
1442 static void hmp_mouse_button(Monitor *mon, const QDict *qdict)
1444 static uint32_t bmap[INPUT_BUTTON__MAX] = {
1445 [INPUT_BUTTON_LEFT] = MOUSE_EVENT_LBUTTON,
1446 [INPUT_BUTTON_MIDDLE] = MOUSE_EVENT_MBUTTON,
1447 [INPUT_BUTTON_RIGHT] = MOUSE_EVENT_RBUTTON,
1449 int button_state = qdict_get_int(qdict, "button_state");
1451 if (mouse_button_state == button_state) {
1452 return;
1454 qemu_input_update_buttons(NULL, bmap, mouse_button_state, button_state);
1455 qemu_input_event_sync();
1456 mouse_button_state = button_state;
1459 static void hmp_ioport_read(Monitor *mon, const QDict *qdict)
1461 int size = qdict_get_int(qdict, "size");
1462 int addr = qdict_get_int(qdict, "addr");
1463 int has_index = qdict_haskey(qdict, "index");
1464 uint32_t val;
1465 int suffix;
1467 if (has_index) {
1468 int index = qdict_get_int(qdict, "index");
1469 cpu_outb(addr & IOPORTS_MASK, index & 0xff);
1470 addr++;
1472 addr &= 0xffff;
1474 switch(size) {
1475 default:
1476 case 1:
1477 val = cpu_inb(addr);
1478 suffix = 'b';
1479 break;
1480 case 2:
1481 val = cpu_inw(addr);
1482 suffix = 'w';
1483 break;
1484 case 4:
1485 val = cpu_inl(addr);
1486 suffix = 'l';
1487 break;
1489 monitor_printf(mon, "port%c[0x%04x] = %#0*x\n",
1490 suffix, addr, size * 2, val);
1493 static void hmp_ioport_write(Monitor *mon, const QDict *qdict)
1495 int size = qdict_get_int(qdict, "size");
1496 int addr = qdict_get_int(qdict, "addr");
1497 int val = qdict_get_int(qdict, "val");
1499 addr &= IOPORTS_MASK;
1501 switch (size) {
1502 default:
1503 case 1:
1504 cpu_outb(addr, val);
1505 break;
1506 case 2:
1507 cpu_outw(addr, val);
1508 break;
1509 case 4:
1510 cpu_outl(addr, val);
1511 break;
1515 static void hmp_boot_set(Monitor *mon, const QDict *qdict)
1517 Error *local_err = NULL;
1518 const char *bootdevice = qdict_get_str(qdict, "bootdevice");
1520 qemu_boot_set(bootdevice, &local_err);
1521 if (local_err) {
1522 error_report_err(local_err);
1523 } else {
1524 monitor_printf(mon, "boot device list now set to %s\n", bootdevice);
1528 static void hmp_info_mtree(Monitor *mon, const QDict *qdict)
1530 mtree_info((fprintf_function)monitor_printf, mon);
1533 static void hmp_info_numa(Monitor *mon, const QDict *qdict)
1535 int i;
1536 CPUState *cpu;
1537 uint64_t *node_mem;
1539 node_mem = g_new0(uint64_t, nb_numa_nodes);
1540 query_numa_node_mem(node_mem);
1541 monitor_printf(mon, "%d nodes\n", nb_numa_nodes);
1542 for (i = 0; i < nb_numa_nodes; i++) {
1543 monitor_printf(mon, "node %d cpus:", i);
1544 CPU_FOREACH(cpu) {
1545 if (cpu->numa_node == i) {
1546 monitor_printf(mon, " %d", cpu->cpu_index);
1549 monitor_printf(mon, "\n");
1550 monitor_printf(mon, "node %d size: %" PRId64 " MB\n", i,
1551 node_mem[i] >> 20);
1553 g_free(node_mem);
1556 #ifdef CONFIG_PROFILER
1558 int64_t tcg_time;
1559 int64_t dev_time;
1561 static void hmp_info_profile(Monitor *mon, const QDict *qdict)
1563 monitor_printf(mon, "async time %" PRId64 " (%0.3f)\n",
1564 dev_time, dev_time / (double)NANOSECONDS_PER_SECOND);
1565 monitor_printf(mon, "qemu time %" PRId64 " (%0.3f)\n",
1566 tcg_time, tcg_time / (double)NANOSECONDS_PER_SECOND);
1567 tcg_time = 0;
1568 dev_time = 0;
1570 #else
1571 static void hmp_info_profile(Monitor *mon, const QDict *qdict)
1573 monitor_printf(mon, "Internal profiler not compiled\n");
1575 #endif
1577 /* Capture support */
1578 static QLIST_HEAD (capture_list_head, CaptureState) capture_head;
1580 static void hmp_info_capture(Monitor *mon, const QDict *qdict)
1582 int i;
1583 CaptureState *s;
1585 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
1586 monitor_printf(mon, "[%d]: ", i);
1587 s->ops.info (s->opaque);
1591 static void hmp_stopcapture(Monitor *mon, const QDict *qdict)
1593 int i;
1594 int n = qdict_get_int(qdict, "n");
1595 CaptureState *s;
1597 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
1598 if (i == n) {
1599 s->ops.destroy (s->opaque);
1600 QLIST_REMOVE (s, entries);
1601 g_free (s);
1602 return;
1607 static void hmp_wavcapture(Monitor *mon, const QDict *qdict)
1609 const char *path = qdict_get_str(qdict, "path");
1610 int has_freq = qdict_haskey(qdict, "freq");
1611 int freq = qdict_get_try_int(qdict, "freq", -1);
1612 int has_bits = qdict_haskey(qdict, "bits");
1613 int bits = qdict_get_try_int(qdict, "bits", -1);
1614 int has_channels = qdict_haskey(qdict, "nchannels");
1615 int nchannels = qdict_get_try_int(qdict, "nchannels", -1);
1616 CaptureState *s;
1618 s = g_malloc0 (sizeof (*s));
1620 freq = has_freq ? freq : 44100;
1621 bits = has_bits ? bits : 16;
1622 nchannels = has_channels ? nchannels : 2;
1624 if (wav_start_capture (s, path, freq, bits, nchannels)) {
1625 monitor_printf(mon, "Failed to add wave capture\n");
1626 g_free (s);
1627 return;
1629 QLIST_INSERT_HEAD (&capture_head, s, entries);
1632 static qemu_acl *find_acl(Monitor *mon, const char *name)
1634 qemu_acl *acl = qemu_acl_find(name);
1636 if (!acl) {
1637 monitor_printf(mon, "acl: unknown list '%s'\n", name);
1639 return acl;
1642 static void hmp_acl_show(Monitor *mon, const QDict *qdict)
1644 const char *aclname = qdict_get_str(qdict, "aclname");
1645 qemu_acl *acl = find_acl(mon, aclname);
1646 qemu_acl_entry *entry;
1647 int i = 0;
1649 if (acl) {
1650 monitor_printf(mon, "policy: %s\n",
1651 acl->defaultDeny ? "deny" : "allow");
1652 QTAILQ_FOREACH(entry, &acl->entries, next) {
1653 i++;
1654 monitor_printf(mon, "%d: %s %s\n", i,
1655 entry->deny ? "deny" : "allow", entry->match);
1660 static void hmp_acl_reset(Monitor *mon, const QDict *qdict)
1662 const char *aclname = qdict_get_str(qdict, "aclname");
1663 qemu_acl *acl = find_acl(mon, aclname);
1665 if (acl) {
1666 qemu_acl_reset(acl);
1667 monitor_printf(mon, "acl: removed all rules\n");
1671 static void hmp_acl_policy(Monitor *mon, const QDict *qdict)
1673 const char *aclname = qdict_get_str(qdict, "aclname");
1674 const char *policy = qdict_get_str(qdict, "policy");
1675 qemu_acl *acl = find_acl(mon, aclname);
1677 if (acl) {
1678 if (strcmp(policy, "allow") == 0) {
1679 acl->defaultDeny = 0;
1680 monitor_printf(mon, "acl: policy set to 'allow'\n");
1681 } else if (strcmp(policy, "deny") == 0) {
1682 acl->defaultDeny = 1;
1683 monitor_printf(mon, "acl: policy set to 'deny'\n");
1684 } else {
1685 monitor_printf(mon, "acl: unknown policy '%s', "
1686 "expected 'deny' or 'allow'\n", policy);
1691 static void hmp_acl_add(Monitor *mon, const QDict *qdict)
1693 const char *aclname = qdict_get_str(qdict, "aclname");
1694 const char *match = qdict_get_str(qdict, "match");
1695 const char *policy = qdict_get_str(qdict, "policy");
1696 int has_index = qdict_haskey(qdict, "index");
1697 int index = qdict_get_try_int(qdict, "index", -1);
1698 qemu_acl *acl = find_acl(mon, aclname);
1699 int deny, ret;
1701 if (acl) {
1702 if (strcmp(policy, "allow") == 0) {
1703 deny = 0;
1704 } else if (strcmp(policy, "deny") == 0) {
1705 deny = 1;
1706 } else {
1707 monitor_printf(mon, "acl: unknown policy '%s', "
1708 "expected 'deny' or 'allow'\n", policy);
1709 return;
1711 if (has_index)
1712 ret = qemu_acl_insert(acl, deny, match, index);
1713 else
1714 ret = qemu_acl_append(acl, deny, match);
1715 if (ret < 0)
1716 monitor_printf(mon, "acl: unable to add acl entry\n");
1717 else
1718 monitor_printf(mon, "acl: added rule at position %d\n", ret);
1722 static void hmp_acl_remove(Monitor *mon, const QDict *qdict)
1724 const char *aclname = qdict_get_str(qdict, "aclname");
1725 const char *match = qdict_get_str(qdict, "match");
1726 qemu_acl *acl = find_acl(mon, aclname);
1727 int ret;
1729 if (acl) {
1730 ret = qemu_acl_remove(acl, match);
1731 if (ret < 0)
1732 monitor_printf(mon, "acl: no matching acl entry\n");
1733 else
1734 monitor_printf(mon, "acl: removed rule at position %d\n", ret);
1738 void qmp_getfd(const char *fdname, Error **errp)
1740 mon_fd_t *monfd;
1741 int fd;
1743 fd = qemu_chr_fe_get_msgfd(cur_mon->chr);
1744 if (fd == -1) {
1745 error_setg(errp, QERR_FD_NOT_SUPPLIED);
1746 return;
1749 if (qemu_isdigit(fdname[0])) {
1750 close(fd);
1751 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "fdname",
1752 "a name not starting with a digit");
1753 return;
1756 QLIST_FOREACH(monfd, &cur_mon->fds, next) {
1757 if (strcmp(monfd->name, fdname) != 0) {
1758 continue;
1761 close(monfd->fd);
1762 monfd->fd = fd;
1763 return;
1766 monfd = g_malloc0(sizeof(mon_fd_t));
1767 monfd->name = g_strdup(fdname);
1768 monfd->fd = fd;
1770 QLIST_INSERT_HEAD(&cur_mon->fds, monfd, next);
1773 void qmp_closefd(const char *fdname, Error **errp)
1775 mon_fd_t *monfd;
1777 QLIST_FOREACH(monfd, &cur_mon->fds, next) {
1778 if (strcmp(monfd->name, fdname) != 0) {
1779 continue;
1782 QLIST_REMOVE(monfd, next);
1783 close(monfd->fd);
1784 g_free(monfd->name);
1785 g_free(monfd);
1786 return;
1789 error_setg(errp, QERR_FD_NOT_FOUND, fdname);
1792 static void hmp_loadvm(Monitor *mon, const QDict *qdict)
1794 int saved_vm_running = runstate_is_running();
1795 const char *name = qdict_get_str(qdict, "name");
1797 vm_stop(RUN_STATE_RESTORE_VM);
1799 if (load_vmstate(name) == 0 && saved_vm_running) {
1800 vm_start();
1804 int monitor_get_fd(Monitor *mon, const char *fdname, Error **errp)
1806 mon_fd_t *monfd;
1808 QLIST_FOREACH(monfd, &mon->fds, next) {
1809 int fd;
1811 if (strcmp(monfd->name, fdname) != 0) {
1812 continue;
1815 fd = monfd->fd;
1817 /* caller takes ownership of fd */
1818 QLIST_REMOVE(monfd, next);
1819 g_free(monfd->name);
1820 g_free(monfd);
1822 return fd;
1825 error_setg(errp, "File descriptor named '%s' has not been found", fdname);
1826 return -1;
1829 static void monitor_fdset_cleanup(MonFdset *mon_fdset)
1831 MonFdsetFd *mon_fdset_fd;
1832 MonFdsetFd *mon_fdset_fd_next;
1834 QLIST_FOREACH_SAFE(mon_fdset_fd, &mon_fdset->fds, next, mon_fdset_fd_next) {
1835 if ((mon_fdset_fd->removed ||
1836 (QLIST_EMPTY(&mon_fdset->dup_fds) && mon_refcount == 0)) &&
1837 runstate_is_running()) {
1838 close(mon_fdset_fd->fd);
1839 g_free(mon_fdset_fd->opaque);
1840 QLIST_REMOVE(mon_fdset_fd, next);
1841 g_free(mon_fdset_fd);
1845 if (QLIST_EMPTY(&mon_fdset->fds) && QLIST_EMPTY(&mon_fdset->dup_fds)) {
1846 QLIST_REMOVE(mon_fdset, next);
1847 g_free(mon_fdset);
1851 static void monitor_fdsets_cleanup(void)
1853 MonFdset *mon_fdset;
1854 MonFdset *mon_fdset_next;
1856 QLIST_FOREACH_SAFE(mon_fdset, &mon_fdsets, next, mon_fdset_next) {
1857 monitor_fdset_cleanup(mon_fdset);
1861 AddfdInfo *qmp_add_fd(bool has_fdset_id, int64_t fdset_id, bool has_opaque,
1862 const char *opaque, Error **errp)
1864 int fd;
1865 Monitor *mon = cur_mon;
1866 AddfdInfo *fdinfo;
1868 fd = qemu_chr_fe_get_msgfd(mon->chr);
1869 if (fd == -1) {
1870 error_setg(errp, QERR_FD_NOT_SUPPLIED);
1871 goto error;
1874 fdinfo = monitor_fdset_add_fd(fd, has_fdset_id, fdset_id,
1875 has_opaque, opaque, errp);
1876 if (fdinfo) {
1877 return fdinfo;
1880 error:
1881 if (fd != -1) {
1882 close(fd);
1884 return NULL;
1887 void qmp_remove_fd(int64_t fdset_id, bool has_fd, int64_t fd, Error **errp)
1889 MonFdset *mon_fdset;
1890 MonFdsetFd *mon_fdset_fd;
1891 char fd_str[60];
1893 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
1894 if (mon_fdset->id != fdset_id) {
1895 continue;
1897 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
1898 if (has_fd) {
1899 if (mon_fdset_fd->fd != fd) {
1900 continue;
1902 mon_fdset_fd->removed = true;
1903 break;
1904 } else {
1905 mon_fdset_fd->removed = true;
1908 if (has_fd && !mon_fdset_fd) {
1909 goto error;
1911 monitor_fdset_cleanup(mon_fdset);
1912 return;
1915 error:
1916 if (has_fd) {
1917 snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64 ", fd:%" PRId64,
1918 fdset_id, fd);
1919 } else {
1920 snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64, fdset_id);
1922 error_setg(errp, QERR_FD_NOT_FOUND, fd_str);
1925 FdsetInfoList *qmp_query_fdsets(Error **errp)
1927 MonFdset *mon_fdset;
1928 MonFdsetFd *mon_fdset_fd;
1929 FdsetInfoList *fdset_list = NULL;
1931 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
1932 FdsetInfoList *fdset_info = g_malloc0(sizeof(*fdset_info));
1933 FdsetFdInfoList *fdsetfd_list = NULL;
1935 fdset_info->value = g_malloc0(sizeof(*fdset_info->value));
1936 fdset_info->value->fdset_id = mon_fdset->id;
1938 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
1939 FdsetFdInfoList *fdsetfd_info;
1941 fdsetfd_info = g_malloc0(sizeof(*fdsetfd_info));
1942 fdsetfd_info->value = g_malloc0(sizeof(*fdsetfd_info->value));
1943 fdsetfd_info->value->fd = mon_fdset_fd->fd;
1944 if (mon_fdset_fd->opaque) {
1945 fdsetfd_info->value->has_opaque = true;
1946 fdsetfd_info->value->opaque = g_strdup(mon_fdset_fd->opaque);
1947 } else {
1948 fdsetfd_info->value->has_opaque = false;
1951 fdsetfd_info->next = fdsetfd_list;
1952 fdsetfd_list = fdsetfd_info;
1955 fdset_info->value->fds = fdsetfd_list;
1957 fdset_info->next = fdset_list;
1958 fdset_list = fdset_info;
1961 return fdset_list;
1964 AddfdInfo *monitor_fdset_add_fd(int fd, bool has_fdset_id, int64_t fdset_id,
1965 bool has_opaque, const char *opaque,
1966 Error **errp)
1968 MonFdset *mon_fdset = NULL;
1969 MonFdsetFd *mon_fdset_fd;
1970 AddfdInfo *fdinfo;
1972 if (has_fdset_id) {
1973 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
1974 /* Break if match found or match impossible due to ordering by ID */
1975 if (fdset_id <= mon_fdset->id) {
1976 if (fdset_id < mon_fdset->id) {
1977 mon_fdset = NULL;
1979 break;
1984 if (mon_fdset == NULL) {
1985 int64_t fdset_id_prev = -1;
1986 MonFdset *mon_fdset_cur = QLIST_FIRST(&mon_fdsets);
1988 if (has_fdset_id) {
1989 if (fdset_id < 0) {
1990 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "fdset-id",
1991 "a non-negative value");
1992 return NULL;
1994 /* Use specified fdset ID */
1995 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
1996 mon_fdset_cur = mon_fdset;
1997 if (fdset_id < mon_fdset_cur->id) {
1998 break;
2001 } else {
2002 /* Use first available fdset ID */
2003 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2004 mon_fdset_cur = mon_fdset;
2005 if (fdset_id_prev == mon_fdset_cur->id - 1) {
2006 fdset_id_prev = mon_fdset_cur->id;
2007 continue;
2009 break;
2013 mon_fdset = g_malloc0(sizeof(*mon_fdset));
2014 if (has_fdset_id) {
2015 mon_fdset->id = fdset_id;
2016 } else {
2017 mon_fdset->id = fdset_id_prev + 1;
2020 /* The fdset list is ordered by fdset ID */
2021 if (!mon_fdset_cur) {
2022 QLIST_INSERT_HEAD(&mon_fdsets, mon_fdset, next);
2023 } else if (mon_fdset->id < mon_fdset_cur->id) {
2024 QLIST_INSERT_BEFORE(mon_fdset_cur, mon_fdset, next);
2025 } else {
2026 QLIST_INSERT_AFTER(mon_fdset_cur, mon_fdset, next);
2030 mon_fdset_fd = g_malloc0(sizeof(*mon_fdset_fd));
2031 mon_fdset_fd->fd = fd;
2032 mon_fdset_fd->removed = false;
2033 if (has_opaque) {
2034 mon_fdset_fd->opaque = g_strdup(opaque);
2036 QLIST_INSERT_HEAD(&mon_fdset->fds, mon_fdset_fd, next);
2038 fdinfo = g_malloc0(sizeof(*fdinfo));
2039 fdinfo->fdset_id = mon_fdset->id;
2040 fdinfo->fd = mon_fdset_fd->fd;
2042 return fdinfo;
2045 int monitor_fdset_get_fd(int64_t fdset_id, int flags)
2047 #ifndef _WIN32
2048 MonFdset *mon_fdset;
2049 MonFdsetFd *mon_fdset_fd;
2050 int mon_fd_flags;
2052 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2053 if (mon_fdset->id != fdset_id) {
2054 continue;
2056 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2057 mon_fd_flags = fcntl(mon_fdset_fd->fd, F_GETFL);
2058 if (mon_fd_flags == -1) {
2059 return -1;
2062 if ((flags & O_ACCMODE) == (mon_fd_flags & O_ACCMODE)) {
2063 return mon_fdset_fd->fd;
2066 errno = EACCES;
2067 return -1;
2069 #endif
2071 errno = ENOENT;
2072 return -1;
2075 int monitor_fdset_dup_fd_add(int64_t fdset_id, int dup_fd)
2077 MonFdset *mon_fdset;
2078 MonFdsetFd *mon_fdset_fd_dup;
2080 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2081 if (mon_fdset->id != fdset_id) {
2082 continue;
2084 QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
2085 if (mon_fdset_fd_dup->fd == dup_fd) {
2086 return -1;
2089 mon_fdset_fd_dup = g_malloc0(sizeof(*mon_fdset_fd_dup));
2090 mon_fdset_fd_dup->fd = dup_fd;
2091 QLIST_INSERT_HEAD(&mon_fdset->dup_fds, mon_fdset_fd_dup, next);
2092 return 0;
2094 return -1;
2097 static int monitor_fdset_dup_fd_find_remove(int dup_fd, bool remove)
2099 MonFdset *mon_fdset;
2100 MonFdsetFd *mon_fdset_fd_dup;
2102 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2103 QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
2104 if (mon_fdset_fd_dup->fd == dup_fd) {
2105 if (remove) {
2106 QLIST_REMOVE(mon_fdset_fd_dup, next);
2107 if (QLIST_EMPTY(&mon_fdset->dup_fds)) {
2108 monitor_fdset_cleanup(mon_fdset);
2110 return -1;
2111 } else {
2112 return mon_fdset->id;
2117 return -1;
2120 int monitor_fdset_dup_fd_find(int dup_fd)
2122 return monitor_fdset_dup_fd_find_remove(dup_fd, false);
2125 void monitor_fdset_dup_fd_remove(int dup_fd)
2127 monitor_fdset_dup_fd_find_remove(dup_fd, true);
2130 int monitor_fd_param(Monitor *mon, const char *fdname, Error **errp)
2132 int fd;
2133 Error *local_err = NULL;
2135 if (!qemu_isdigit(fdname[0]) && mon) {
2136 fd = monitor_get_fd(mon, fdname, &local_err);
2137 } else {
2138 fd = qemu_parse_fd(fdname);
2139 if (fd == -1) {
2140 error_setg(&local_err, "Invalid file descriptor number '%s'",
2141 fdname);
2144 if (local_err) {
2145 error_propagate(errp, local_err);
2146 assert(fd == -1);
2147 } else {
2148 assert(fd != -1);
2151 return fd;
2154 /* Please update hmp-commands.hx when adding or changing commands */
2155 static mon_cmd_t info_cmds[] = {
2156 #include "hmp-commands-info.h"
2157 { NULL, NULL, },
2160 /* mon_cmds and info_cmds would be sorted at runtime */
2161 static mon_cmd_t mon_cmds[] = {
2162 #include "hmp-commands.h"
2163 { NULL, NULL, },
2166 static const mon_cmd_t qmp_cmds[] = {
2167 #include "qmp-commands-old.h"
2168 { /* NULL */ },
2171 /*******************************************************************/
2173 static const char *pch;
2174 static sigjmp_buf expr_env;
2177 static void GCC_FMT_ATTR(2, 3) QEMU_NORETURN
2178 expr_error(Monitor *mon, const char *fmt, ...)
2180 va_list ap;
2181 va_start(ap, fmt);
2182 monitor_vprintf(mon, fmt, ap);
2183 monitor_printf(mon, "\n");
2184 va_end(ap);
2185 siglongjmp(expr_env, 1);
2188 /* return 0 if OK, -1 if not found */
2189 static int get_monitor_def(target_long *pval, const char *name)
2191 const MonitorDef *md = target_monitor_defs();
2192 void *ptr;
2193 uint64_t tmp = 0;
2194 int ret;
2196 if (md == NULL) {
2197 return -1;
2200 for(; md->name != NULL; md++) {
2201 if (compare_cmd(name, md->name)) {
2202 if (md->get_value) {
2203 *pval = md->get_value(md, md->offset);
2204 } else {
2205 CPUArchState *env = mon_get_cpu_env();
2206 ptr = (uint8_t *)env + md->offset;
2207 switch(md->type) {
2208 case MD_I32:
2209 *pval = *(int32_t *)ptr;
2210 break;
2211 case MD_TLONG:
2212 *pval = *(target_long *)ptr;
2213 break;
2214 default:
2215 *pval = 0;
2216 break;
2219 return 0;
2223 ret = target_get_monitor_def(mon_get_cpu(), name, &tmp);
2224 if (!ret) {
2225 *pval = (target_long) tmp;
2228 return ret;
2231 static void next(void)
2233 if (*pch != '\0') {
2234 pch++;
2235 while (qemu_isspace(*pch))
2236 pch++;
2240 static int64_t expr_sum(Monitor *mon);
2242 static int64_t expr_unary(Monitor *mon)
2244 int64_t n;
2245 char *p;
2246 int ret;
2248 switch(*pch) {
2249 case '+':
2250 next();
2251 n = expr_unary(mon);
2252 break;
2253 case '-':
2254 next();
2255 n = -expr_unary(mon);
2256 break;
2257 case '~':
2258 next();
2259 n = ~expr_unary(mon);
2260 break;
2261 case '(':
2262 next();
2263 n = expr_sum(mon);
2264 if (*pch != ')') {
2265 expr_error(mon, "')' expected");
2267 next();
2268 break;
2269 case '\'':
2270 pch++;
2271 if (*pch == '\0')
2272 expr_error(mon, "character constant expected");
2273 n = *pch;
2274 pch++;
2275 if (*pch != '\'')
2276 expr_error(mon, "missing terminating \' character");
2277 next();
2278 break;
2279 case '$':
2281 char buf[128], *q;
2282 target_long reg=0;
2284 pch++;
2285 q = buf;
2286 while ((*pch >= 'a' && *pch <= 'z') ||
2287 (*pch >= 'A' && *pch <= 'Z') ||
2288 (*pch >= '0' && *pch <= '9') ||
2289 *pch == '_' || *pch == '.') {
2290 if ((q - buf) < sizeof(buf) - 1)
2291 *q++ = *pch;
2292 pch++;
2294 while (qemu_isspace(*pch))
2295 pch++;
2296 *q = 0;
2297 ret = get_monitor_def(&reg, buf);
2298 if (ret < 0)
2299 expr_error(mon, "unknown register");
2300 n = reg;
2302 break;
2303 case '\0':
2304 expr_error(mon, "unexpected end of expression");
2305 n = 0;
2306 break;
2307 default:
2308 errno = 0;
2309 n = strtoull(pch, &p, 0);
2310 if (errno == ERANGE) {
2311 expr_error(mon, "number too large");
2313 if (pch == p) {
2314 expr_error(mon, "invalid char '%c' in expression", *p);
2316 pch = p;
2317 while (qemu_isspace(*pch))
2318 pch++;
2319 break;
2321 return n;
2325 static int64_t expr_prod(Monitor *mon)
2327 int64_t val, val2;
2328 int op;
2330 val = expr_unary(mon);
2331 for(;;) {
2332 op = *pch;
2333 if (op != '*' && op != '/' && op != '%')
2334 break;
2335 next();
2336 val2 = expr_unary(mon);
2337 switch(op) {
2338 default:
2339 case '*':
2340 val *= val2;
2341 break;
2342 case '/':
2343 case '%':
2344 if (val2 == 0)
2345 expr_error(mon, "division by zero");
2346 if (op == '/')
2347 val /= val2;
2348 else
2349 val %= val2;
2350 break;
2353 return val;
2356 static int64_t expr_logic(Monitor *mon)
2358 int64_t val, val2;
2359 int op;
2361 val = expr_prod(mon);
2362 for(;;) {
2363 op = *pch;
2364 if (op != '&' && op != '|' && op != '^')
2365 break;
2366 next();
2367 val2 = expr_prod(mon);
2368 switch(op) {
2369 default:
2370 case '&':
2371 val &= val2;
2372 break;
2373 case '|':
2374 val |= val2;
2375 break;
2376 case '^':
2377 val ^= val2;
2378 break;
2381 return val;
2384 static int64_t expr_sum(Monitor *mon)
2386 int64_t val, val2;
2387 int op;
2389 val = expr_logic(mon);
2390 for(;;) {
2391 op = *pch;
2392 if (op != '+' && op != '-')
2393 break;
2394 next();
2395 val2 = expr_logic(mon);
2396 if (op == '+')
2397 val += val2;
2398 else
2399 val -= val2;
2401 return val;
2404 static int get_expr(Monitor *mon, int64_t *pval, const char **pp)
2406 pch = *pp;
2407 if (sigsetjmp(expr_env, 0)) {
2408 *pp = pch;
2409 return -1;
2411 while (qemu_isspace(*pch))
2412 pch++;
2413 *pval = expr_sum(mon);
2414 *pp = pch;
2415 return 0;
2418 static int get_double(Monitor *mon, double *pval, const char **pp)
2420 const char *p = *pp;
2421 char *tailp;
2422 double d;
2424 d = strtod(p, &tailp);
2425 if (tailp == p) {
2426 monitor_printf(mon, "Number expected\n");
2427 return -1;
2429 if (d != d || d - d != 0) {
2430 /* NaN or infinity */
2431 monitor_printf(mon, "Bad number\n");
2432 return -1;
2434 *pval = d;
2435 *pp = tailp;
2436 return 0;
2440 * Store the command-name in cmdname, and return a pointer to
2441 * the remaining of the command string.
2443 static const char *get_command_name(const char *cmdline,
2444 char *cmdname, size_t nlen)
2446 size_t len;
2447 const char *p, *pstart;
2449 p = cmdline;
2450 while (qemu_isspace(*p))
2451 p++;
2452 if (*p == '\0')
2453 return NULL;
2454 pstart = p;
2455 while (*p != '\0' && *p != '/' && !qemu_isspace(*p))
2456 p++;
2457 len = p - pstart;
2458 if (len > nlen - 1)
2459 len = nlen - 1;
2460 memcpy(cmdname, pstart, len);
2461 cmdname[len] = '\0';
2462 return p;
2466 * Read key of 'type' into 'key' and return the current
2467 * 'type' pointer.
2469 static char *key_get_info(const char *type, char **key)
2471 size_t len;
2472 char *p, *str;
2474 if (*type == ',')
2475 type++;
2477 p = strchr(type, ':');
2478 if (!p) {
2479 *key = NULL;
2480 return NULL;
2482 len = p - type;
2484 str = g_malloc(len + 1);
2485 memcpy(str, type, len);
2486 str[len] = '\0';
2488 *key = str;
2489 return ++p;
2492 static int default_fmt_format = 'x';
2493 static int default_fmt_size = 4;
2495 static int is_valid_option(const char *c, const char *typestr)
2497 char option[3];
2499 option[0] = '-';
2500 option[1] = *c;
2501 option[2] = '\0';
2503 typestr = strstr(typestr, option);
2504 return (typestr != NULL);
2507 static const mon_cmd_t *search_dispatch_table(const mon_cmd_t *disp_table,
2508 const char *cmdname)
2510 const mon_cmd_t *cmd;
2512 for (cmd = disp_table; cmd->name != NULL; cmd++) {
2513 if (compare_cmd(cmdname, cmd->name)) {
2514 return cmd;
2518 return NULL;
2521 static const mon_cmd_t *qmp_find_cmd(const char *cmdname)
2523 return search_dispatch_table(qmp_cmds, cmdname);
2527 * Parse command name from @cmdp according to command table @table.
2528 * If blank, return NULL.
2529 * Else, if no valid command can be found, report to @mon, and return
2530 * NULL.
2531 * Else, change @cmdp to point right behind the name, and return its
2532 * command table entry.
2533 * Do not assume the return value points into @table! It doesn't when
2534 * the command is found in a sub-command table.
2536 static const mon_cmd_t *monitor_parse_command(Monitor *mon,
2537 const char **cmdp,
2538 mon_cmd_t *table)
2540 const char *p;
2541 const mon_cmd_t *cmd;
2542 char cmdname[256];
2544 /* extract the command name */
2545 p = get_command_name(*cmdp, cmdname, sizeof(cmdname));
2546 if (!p)
2547 return NULL;
2549 cmd = search_dispatch_table(table, cmdname);
2550 if (!cmd) {
2551 monitor_printf(mon, "unknown command: '%.*s'\n",
2552 (int)(p - *cmdp), *cmdp);
2553 return NULL;
2556 /* filter out following useless space */
2557 while (qemu_isspace(*p)) {
2558 p++;
2561 *cmdp = p;
2562 /* search sub command */
2563 if (cmd->sub_table != NULL && *p != '\0') {
2564 return monitor_parse_command(mon, cmdp, cmd->sub_table);
2567 return cmd;
2571 * Parse arguments for @cmd.
2572 * If it can't be parsed, report to @mon, and return NULL.
2573 * Else, insert command arguments into a QDict, and return it.
2574 * Note: On success, caller has to free the QDict structure.
2577 static QDict *monitor_parse_arguments(Monitor *mon,
2578 const char **endp,
2579 const mon_cmd_t *cmd)
2581 const char *typestr;
2582 char *key;
2583 int c;
2584 const char *p = *endp;
2585 char buf[1024];
2586 QDict *qdict = qdict_new();
2588 /* parse the parameters */
2589 typestr = cmd->args_type;
2590 for(;;) {
2591 typestr = key_get_info(typestr, &key);
2592 if (!typestr)
2593 break;
2594 c = *typestr;
2595 typestr++;
2596 switch(c) {
2597 case 'F':
2598 case 'B':
2599 case 's':
2601 int ret;
2603 while (qemu_isspace(*p))
2604 p++;
2605 if (*typestr == '?') {
2606 typestr++;
2607 if (*p == '\0') {
2608 /* no optional string: NULL argument */
2609 break;
2612 ret = get_str(buf, sizeof(buf), &p);
2613 if (ret < 0) {
2614 switch(c) {
2615 case 'F':
2616 monitor_printf(mon, "%s: filename expected\n",
2617 cmd->name);
2618 break;
2619 case 'B':
2620 monitor_printf(mon, "%s: block device name expected\n",
2621 cmd->name);
2622 break;
2623 default:
2624 monitor_printf(mon, "%s: string expected\n", cmd->name);
2625 break;
2627 goto fail;
2629 qdict_put(qdict, key, qstring_from_str(buf));
2631 break;
2632 case 'O':
2634 QemuOptsList *opts_list;
2635 QemuOpts *opts;
2637 opts_list = qemu_find_opts(key);
2638 if (!opts_list || opts_list->desc->name) {
2639 goto bad_type;
2641 while (qemu_isspace(*p)) {
2642 p++;
2644 if (!*p)
2645 break;
2646 if (get_str(buf, sizeof(buf), &p) < 0) {
2647 goto fail;
2649 opts = qemu_opts_parse_noisily(opts_list, buf, true);
2650 if (!opts) {
2651 goto fail;
2653 qemu_opts_to_qdict(opts, qdict);
2654 qemu_opts_del(opts);
2656 break;
2657 case '/':
2659 int count, format, size;
2661 while (qemu_isspace(*p))
2662 p++;
2663 if (*p == '/') {
2664 /* format found */
2665 p++;
2666 count = 1;
2667 if (qemu_isdigit(*p)) {
2668 count = 0;
2669 while (qemu_isdigit(*p)) {
2670 count = count * 10 + (*p - '0');
2671 p++;
2674 size = -1;
2675 format = -1;
2676 for(;;) {
2677 switch(*p) {
2678 case 'o':
2679 case 'd':
2680 case 'u':
2681 case 'x':
2682 case 'i':
2683 case 'c':
2684 format = *p++;
2685 break;
2686 case 'b':
2687 size = 1;
2688 p++;
2689 break;
2690 case 'h':
2691 size = 2;
2692 p++;
2693 break;
2694 case 'w':
2695 size = 4;
2696 p++;
2697 break;
2698 case 'g':
2699 case 'L':
2700 size = 8;
2701 p++;
2702 break;
2703 default:
2704 goto next;
2707 next:
2708 if (*p != '\0' && !qemu_isspace(*p)) {
2709 monitor_printf(mon, "invalid char in format: '%c'\n",
2710 *p);
2711 goto fail;
2713 if (format < 0)
2714 format = default_fmt_format;
2715 if (format != 'i') {
2716 /* for 'i', not specifying a size gives -1 as size */
2717 if (size < 0)
2718 size = default_fmt_size;
2719 default_fmt_size = size;
2721 default_fmt_format = format;
2722 } else {
2723 count = 1;
2724 format = default_fmt_format;
2725 if (format != 'i') {
2726 size = default_fmt_size;
2727 } else {
2728 size = -1;
2731 qdict_put(qdict, "count", qint_from_int(count));
2732 qdict_put(qdict, "format", qint_from_int(format));
2733 qdict_put(qdict, "size", qint_from_int(size));
2735 break;
2736 case 'i':
2737 case 'l':
2738 case 'M':
2740 int64_t val;
2742 while (qemu_isspace(*p))
2743 p++;
2744 if (*typestr == '?' || *typestr == '.') {
2745 if (*typestr == '?') {
2746 if (*p == '\0') {
2747 typestr++;
2748 break;
2750 } else {
2751 if (*p == '.') {
2752 p++;
2753 while (qemu_isspace(*p))
2754 p++;
2755 } else {
2756 typestr++;
2757 break;
2760 typestr++;
2762 if (get_expr(mon, &val, &p))
2763 goto fail;
2764 /* Check if 'i' is greater than 32-bit */
2765 if ((c == 'i') && ((val >> 32) & 0xffffffff)) {
2766 monitor_printf(mon, "\'%s\' has failed: ", cmd->name);
2767 monitor_printf(mon, "integer is for 32-bit values\n");
2768 goto fail;
2769 } else if (c == 'M') {
2770 if (val < 0) {
2771 monitor_printf(mon, "enter a positive value\n");
2772 goto fail;
2774 val <<= 20;
2776 qdict_put(qdict, key, qint_from_int(val));
2778 break;
2779 case 'o':
2781 int64_t val;
2782 char *end;
2784 while (qemu_isspace(*p)) {
2785 p++;
2787 if (*typestr == '?') {
2788 typestr++;
2789 if (*p == '\0') {
2790 break;
2793 val = qemu_strtosz(p, &end);
2794 if (val < 0) {
2795 monitor_printf(mon, "invalid size\n");
2796 goto fail;
2798 qdict_put(qdict, key, qint_from_int(val));
2799 p = end;
2801 break;
2802 case 'T':
2804 double val;
2806 while (qemu_isspace(*p))
2807 p++;
2808 if (*typestr == '?') {
2809 typestr++;
2810 if (*p == '\0') {
2811 break;
2814 if (get_double(mon, &val, &p) < 0) {
2815 goto fail;
2817 if (p[0] && p[1] == 's') {
2818 switch (*p) {
2819 case 'm':
2820 val /= 1e3; p += 2; break;
2821 case 'u':
2822 val /= 1e6; p += 2; break;
2823 case 'n':
2824 val /= 1e9; p += 2; break;
2827 if (*p && !qemu_isspace(*p)) {
2828 monitor_printf(mon, "Unknown unit suffix\n");
2829 goto fail;
2831 qdict_put(qdict, key, qfloat_from_double(val));
2833 break;
2834 case 'b':
2836 const char *beg;
2837 bool val;
2839 while (qemu_isspace(*p)) {
2840 p++;
2842 beg = p;
2843 while (qemu_isgraph(*p)) {
2844 p++;
2846 if (p - beg == 2 && !memcmp(beg, "on", p - beg)) {
2847 val = true;
2848 } else if (p - beg == 3 && !memcmp(beg, "off", p - beg)) {
2849 val = false;
2850 } else {
2851 monitor_printf(mon, "Expected 'on' or 'off'\n");
2852 goto fail;
2854 qdict_put(qdict, key, qbool_from_bool(val));
2856 break;
2857 case '-':
2859 const char *tmp = p;
2860 int skip_key = 0;
2861 /* option */
2863 c = *typestr++;
2864 if (c == '\0')
2865 goto bad_type;
2866 while (qemu_isspace(*p))
2867 p++;
2868 if (*p == '-') {
2869 p++;
2870 if(c != *p) {
2871 if(!is_valid_option(p, typestr)) {
2873 monitor_printf(mon, "%s: unsupported option -%c\n",
2874 cmd->name, *p);
2875 goto fail;
2876 } else {
2877 skip_key = 1;
2880 if(skip_key) {
2881 p = tmp;
2882 } else {
2883 /* has option */
2884 p++;
2885 qdict_put(qdict, key, qbool_from_bool(true));
2889 break;
2890 case 'S':
2892 /* package all remaining string */
2893 int len;
2895 while (qemu_isspace(*p)) {
2896 p++;
2898 if (*typestr == '?') {
2899 typestr++;
2900 if (*p == '\0') {
2901 /* no remaining string: NULL argument */
2902 break;
2905 len = strlen(p);
2906 if (len <= 0) {
2907 monitor_printf(mon, "%s: string expected\n",
2908 cmd->name);
2909 goto fail;
2911 qdict_put(qdict, key, qstring_from_str(p));
2912 p += len;
2914 break;
2915 default:
2916 bad_type:
2917 monitor_printf(mon, "%s: unknown type '%c'\n", cmd->name, c);
2918 goto fail;
2920 g_free(key);
2921 key = NULL;
2923 /* check that all arguments were parsed */
2924 while (qemu_isspace(*p))
2925 p++;
2926 if (*p != '\0') {
2927 monitor_printf(mon, "%s: extraneous characters at the end of line\n",
2928 cmd->name);
2929 goto fail;
2932 return qdict;
2934 fail:
2935 QDECREF(qdict);
2936 g_free(key);
2937 return NULL;
2940 static void handle_hmp_command(Monitor *mon, const char *cmdline)
2942 QDict *qdict;
2943 const mon_cmd_t *cmd;
2945 cmd = monitor_parse_command(mon, &cmdline, mon->cmd_table);
2946 if (!cmd) {
2947 return;
2950 qdict = monitor_parse_arguments(mon, &cmdline, cmd);
2951 if (!qdict) {
2952 monitor_printf(mon, "Try \"help %s\" for more information\n",
2953 cmd->name);
2954 return;
2957 cmd->mhandler.cmd(mon, qdict);
2958 QDECREF(qdict);
2961 static void cmd_completion(Monitor *mon, const char *name, const char *list)
2963 const char *p, *pstart;
2964 char cmd[128];
2965 int len;
2967 p = list;
2968 for(;;) {
2969 pstart = p;
2970 p = strchr(p, '|');
2971 if (!p)
2972 p = pstart + strlen(pstart);
2973 len = p - pstart;
2974 if (len > sizeof(cmd) - 2)
2975 len = sizeof(cmd) - 2;
2976 memcpy(cmd, pstart, len);
2977 cmd[len] = '\0';
2978 if (name[0] == '\0' || !strncmp(name, cmd, strlen(name))) {
2979 readline_add_completion(mon->rs, cmd);
2981 if (*p == '\0')
2982 break;
2983 p++;
2987 static void file_completion(Monitor *mon, const char *input)
2989 DIR *ffs;
2990 struct dirent *d;
2991 char path[1024];
2992 char file[1024], file_prefix[1024];
2993 int input_path_len;
2994 const char *p;
2996 p = strrchr(input, '/');
2997 if (!p) {
2998 input_path_len = 0;
2999 pstrcpy(file_prefix, sizeof(file_prefix), input);
3000 pstrcpy(path, sizeof(path), ".");
3001 } else {
3002 input_path_len = p - input + 1;
3003 memcpy(path, input, input_path_len);
3004 if (input_path_len > sizeof(path) - 1)
3005 input_path_len = sizeof(path) - 1;
3006 path[input_path_len] = '\0';
3007 pstrcpy(file_prefix, sizeof(file_prefix), p + 1);
3010 ffs = opendir(path);
3011 if (!ffs)
3012 return;
3013 for(;;) {
3014 struct stat sb;
3015 d = readdir(ffs);
3016 if (!d)
3017 break;
3019 if (strcmp(d->d_name, ".") == 0 || strcmp(d->d_name, "..") == 0) {
3020 continue;
3023 if (strstart(d->d_name, file_prefix, NULL)) {
3024 memcpy(file, input, input_path_len);
3025 if (input_path_len < sizeof(file))
3026 pstrcpy(file + input_path_len, sizeof(file) - input_path_len,
3027 d->d_name);
3028 /* stat the file to find out if it's a directory.
3029 * In that case add a slash to speed up typing long paths
3031 if (stat(file, &sb) == 0 && S_ISDIR(sb.st_mode)) {
3032 pstrcat(file, sizeof(file), "/");
3034 readline_add_completion(mon->rs, file);
3037 closedir(ffs);
3040 static const char *next_arg_type(const char *typestr)
3042 const char *p = strchr(typestr, ':');
3043 return (p != NULL ? ++p : typestr);
3046 static void add_completion_option(ReadLineState *rs, const char *str,
3047 const char *option)
3049 if (!str || !option) {
3050 return;
3052 if (!strncmp(option, str, strlen(str))) {
3053 readline_add_completion(rs, option);
3057 void chardev_add_completion(ReadLineState *rs, int nb_args, const char *str)
3059 size_t len;
3060 ChardevBackendInfoList *list, *start;
3062 if (nb_args != 2) {
3063 return;
3065 len = strlen(str);
3066 readline_set_completion_index(rs, len);
3068 start = list = qmp_query_chardev_backends(NULL);
3069 while (list) {
3070 const char *chr_name = list->value->name;
3072 if (!strncmp(chr_name, str, len)) {
3073 readline_add_completion(rs, chr_name);
3075 list = list->next;
3077 qapi_free_ChardevBackendInfoList(start);
3080 void netdev_add_completion(ReadLineState *rs, int nb_args, const char *str)
3082 size_t len;
3083 int i;
3085 if (nb_args != 2) {
3086 return;
3088 len = strlen(str);
3089 readline_set_completion_index(rs, len);
3090 for (i = 0; NetClientDriver_lookup[i]; i++) {
3091 add_completion_option(rs, str, NetClientDriver_lookup[i]);
3095 void device_add_completion(ReadLineState *rs, int nb_args, const char *str)
3097 GSList *list, *elt;
3098 size_t len;
3100 if (nb_args != 2) {
3101 return;
3104 len = strlen(str);
3105 readline_set_completion_index(rs, len);
3106 list = elt = object_class_get_list(TYPE_DEVICE, false);
3107 while (elt) {
3108 const char *name;
3109 DeviceClass *dc = OBJECT_CLASS_CHECK(DeviceClass, elt->data,
3110 TYPE_DEVICE);
3111 name = object_class_get_name(OBJECT_CLASS(dc));
3113 if (!dc->cannot_instantiate_with_device_add_yet
3114 && !strncmp(name, str, len)) {
3115 readline_add_completion(rs, name);
3117 elt = elt->next;
3119 g_slist_free(list);
3122 void object_add_completion(ReadLineState *rs, int nb_args, const char *str)
3124 GSList *list, *elt;
3125 size_t len;
3127 if (nb_args != 2) {
3128 return;
3131 len = strlen(str);
3132 readline_set_completion_index(rs, len);
3133 list = elt = object_class_get_list(TYPE_USER_CREATABLE, false);
3134 while (elt) {
3135 const char *name;
3137 name = object_class_get_name(OBJECT_CLASS(elt->data));
3138 if (!strncmp(name, str, len) && strcmp(name, TYPE_USER_CREATABLE)) {
3139 readline_add_completion(rs, name);
3141 elt = elt->next;
3143 g_slist_free(list);
3146 static void peripheral_device_del_completion(ReadLineState *rs,
3147 const char *str, size_t len)
3149 Object *peripheral = container_get(qdev_get_machine(), "/peripheral");
3150 GSList *list, *item;
3152 list = qdev_build_hotpluggable_device_list(peripheral);
3153 if (!list) {
3154 return;
3157 for (item = list; item; item = g_slist_next(item)) {
3158 DeviceState *dev = item->data;
3160 if (dev->id && !strncmp(str, dev->id, len)) {
3161 readline_add_completion(rs, dev->id);
3165 g_slist_free(list);
3168 void chardev_remove_completion(ReadLineState *rs, int nb_args, const char *str)
3170 size_t len;
3171 ChardevInfoList *list, *start;
3173 if (nb_args != 2) {
3174 return;
3176 len = strlen(str);
3177 readline_set_completion_index(rs, len);
3179 start = list = qmp_query_chardev(NULL);
3180 while (list) {
3181 ChardevInfo *chr = list->value;
3183 if (!strncmp(chr->label, str, len)) {
3184 readline_add_completion(rs, chr->label);
3186 list = list->next;
3188 qapi_free_ChardevInfoList(start);
3191 static void ringbuf_completion(ReadLineState *rs, const char *str)
3193 size_t len;
3194 ChardevInfoList *list, *start;
3196 len = strlen(str);
3197 readline_set_completion_index(rs, len);
3199 start = list = qmp_query_chardev(NULL);
3200 while (list) {
3201 ChardevInfo *chr_info = list->value;
3203 if (!strncmp(chr_info->label, str, len)) {
3204 CharDriverState *chr = qemu_chr_find(chr_info->label);
3205 if (chr && chr_is_ringbuf(chr)) {
3206 readline_add_completion(rs, chr_info->label);
3209 list = list->next;
3211 qapi_free_ChardevInfoList(start);
3214 void ringbuf_write_completion(ReadLineState *rs, int nb_args, const char *str)
3216 if (nb_args != 2) {
3217 return;
3219 ringbuf_completion(rs, str);
3222 void device_del_completion(ReadLineState *rs, int nb_args, const char *str)
3224 size_t len;
3226 if (nb_args != 2) {
3227 return;
3230 len = strlen(str);
3231 readline_set_completion_index(rs, len);
3232 peripheral_device_del_completion(rs, str, len);
3235 void object_del_completion(ReadLineState *rs, int nb_args, const char *str)
3237 ObjectPropertyInfoList *list, *start;
3238 size_t len;
3240 if (nb_args != 2) {
3241 return;
3243 len = strlen(str);
3244 readline_set_completion_index(rs, len);
3246 start = list = qmp_qom_list("/objects", NULL);
3247 while (list) {
3248 ObjectPropertyInfo *info = list->value;
3250 if (!strncmp(info->type, "child<", 5)
3251 && !strncmp(info->name, str, len)) {
3252 readline_add_completion(rs, info->name);
3254 list = list->next;
3256 qapi_free_ObjectPropertyInfoList(start);
3259 void sendkey_completion(ReadLineState *rs, int nb_args, const char *str)
3261 int i;
3262 char *sep;
3263 size_t len;
3265 if (nb_args != 2) {
3266 return;
3268 sep = strrchr(str, '-');
3269 if (sep) {
3270 str = sep + 1;
3272 len = strlen(str);
3273 readline_set_completion_index(rs, len);
3274 for (i = 0; i < Q_KEY_CODE__MAX; i++) {
3275 if (!strncmp(str, QKeyCode_lookup[i], len)) {
3276 readline_add_completion(rs, QKeyCode_lookup[i]);
3281 void set_link_completion(ReadLineState *rs, int nb_args, const char *str)
3283 size_t len;
3285 len = strlen(str);
3286 readline_set_completion_index(rs, len);
3287 if (nb_args == 2) {
3288 NetClientState *ncs[MAX_QUEUE_NUM];
3289 int count, i;
3290 count = qemu_find_net_clients_except(NULL, ncs,
3291 NET_CLIENT_DRIVER_NONE,
3292 MAX_QUEUE_NUM);
3293 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3294 const char *name = ncs[i]->name;
3295 if (!strncmp(str, name, len)) {
3296 readline_add_completion(rs, name);
3299 } else if (nb_args == 3) {
3300 add_completion_option(rs, str, "on");
3301 add_completion_option(rs, str, "off");
3305 void netdev_del_completion(ReadLineState *rs, int nb_args, const char *str)
3307 int len, count, i;
3308 NetClientState *ncs[MAX_QUEUE_NUM];
3310 if (nb_args != 2) {
3311 return;
3314 len = strlen(str);
3315 readline_set_completion_index(rs, len);
3316 count = qemu_find_net_clients_except(NULL, ncs, NET_CLIENT_DRIVER_NIC,
3317 MAX_QUEUE_NUM);
3318 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3319 QemuOpts *opts;
3320 const char *name = ncs[i]->name;
3321 if (strncmp(str, name, len)) {
3322 continue;
3324 opts = qemu_opts_find(qemu_find_opts_err("netdev", NULL), name);
3325 if (opts) {
3326 readline_add_completion(rs, name);
3331 void info_trace_events_completion(ReadLineState *rs, int nb_args, const char *str)
3333 size_t len;
3335 len = strlen(str);
3336 readline_set_completion_index(rs, len);
3337 if (nb_args == 2) {
3338 TraceEventID id;
3339 for (id = 0; id < trace_event_count(); id++) {
3340 const char *event_name = trace_event_get_name(trace_event_id(id));
3341 if (!strncmp(str, event_name, len)) {
3342 readline_add_completion(rs, event_name);
3348 void trace_event_completion(ReadLineState *rs, int nb_args, const char *str)
3350 size_t len;
3352 len = strlen(str);
3353 readline_set_completion_index(rs, len);
3354 if (nb_args == 2) {
3355 TraceEventID id;
3356 for (id = 0; id < trace_event_count(); id++) {
3357 const char *event_name = trace_event_get_name(trace_event_id(id));
3358 if (!strncmp(str, event_name, len)) {
3359 readline_add_completion(rs, event_name);
3362 } else if (nb_args == 3) {
3363 add_completion_option(rs, str, "on");
3364 add_completion_option(rs, str, "off");
3368 void watchdog_action_completion(ReadLineState *rs, int nb_args, const char *str)
3370 int i;
3372 if (nb_args != 2) {
3373 return;
3375 readline_set_completion_index(rs, strlen(str));
3376 for (i = 0; WatchdogExpirationAction_lookup[i]; i++) {
3377 add_completion_option(rs, str, WatchdogExpirationAction_lookup[i]);
3381 void migrate_set_capability_completion(ReadLineState *rs, int nb_args,
3382 const char *str)
3384 size_t len;
3386 len = strlen(str);
3387 readline_set_completion_index(rs, len);
3388 if (nb_args == 2) {
3389 int i;
3390 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
3391 const char *name = MigrationCapability_lookup[i];
3392 if (!strncmp(str, name, len)) {
3393 readline_add_completion(rs, name);
3396 } else if (nb_args == 3) {
3397 add_completion_option(rs, str, "on");
3398 add_completion_option(rs, str, "off");
3402 void migrate_set_parameter_completion(ReadLineState *rs, int nb_args,
3403 const char *str)
3405 size_t len;
3407 len = strlen(str);
3408 readline_set_completion_index(rs, len);
3409 if (nb_args == 2) {
3410 int i;
3411 for (i = 0; i < MIGRATION_PARAMETER__MAX; i++) {
3412 const char *name = MigrationParameter_lookup[i];
3413 if (!strncmp(str, name, len)) {
3414 readline_add_completion(rs, name);
3420 void host_net_add_completion(ReadLineState *rs, int nb_args, const char *str)
3422 int i;
3423 size_t len;
3424 if (nb_args != 2) {
3425 return;
3427 len = strlen(str);
3428 readline_set_completion_index(rs, len);
3429 for (i = 0; host_net_devices[i]; i++) {
3430 if (!strncmp(host_net_devices[i], str, len)) {
3431 readline_add_completion(rs, host_net_devices[i]);
3436 void host_net_remove_completion(ReadLineState *rs, int nb_args, const char *str)
3438 NetClientState *ncs[MAX_QUEUE_NUM];
3439 int count, i, len;
3441 len = strlen(str);
3442 readline_set_completion_index(rs, len);
3443 if (nb_args == 2) {
3444 count = qemu_find_net_clients_except(NULL, ncs,
3445 NET_CLIENT_DRIVER_NONE,
3446 MAX_QUEUE_NUM);
3447 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3448 int id;
3449 char name[16];
3451 if (net_hub_id_for_client(ncs[i], &id)) {
3452 continue;
3454 snprintf(name, sizeof(name), "%d", id);
3455 if (!strncmp(str, name, len)) {
3456 readline_add_completion(rs, name);
3459 return;
3460 } else if (nb_args == 3) {
3461 count = qemu_find_net_clients_except(NULL, ncs,
3462 NET_CLIENT_DRIVER_NIC,
3463 MAX_QUEUE_NUM);
3464 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3465 int id;
3466 const char *name;
3468 if (ncs[i]->info->type == NET_CLIENT_DRIVER_HUBPORT ||
3469 net_hub_id_for_client(ncs[i], &id)) {
3470 continue;
3472 name = ncs[i]->name;
3473 if (!strncmp(str, name, len)) {
3474 readline_add_completion(rs, name);
3477 return;
3481 static void vm_completion(ReadLineState *rs, const char *str)
3483 size_t len;
3484 BlockDriverState *bs;
3485 BdrvNextIterator it;
3487 len = strlen(str);
3488 readline_set_completion_index(rs, len);
3490 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
3491 SnapshotInfoList *snapshots, *snapshot;
3492 AioContext *ctx = bdrv_get_aio_context(bs);
3493 bool ok = false;
3495 aio_context_acquire(ctx);
3496 if (bdrv_can_snapshot(bs)) {
3497 ok = bdrv_query_snapshot_info_list(bs, &snapshots, NULL) == 0;
3499 aio_context_release(ctx);
3500 if (!ok) {
3501 continue;
3504 snapshot = snapshots;
3505 while (snapshot) {
3506 char *completion = snapshot->value->name;
3507 if (!strncmp(str, completion, len)) {
3508 readline_add_completion(rs, completion);
3510 completion = snapshot->value->id;
3511 if (!strncmp(str, completion, len)) {
3512 readline_add_completion(rs, completion);
3514 snapshot = snapshot->next;
3516 qapi_free_SnapshotInfoList(snapshots);
3521 void delvm_completion(ReadLineState *rs, int nb_args, const char *str)
3523 if (nb_args == 2) {
3524 vm_completion(rs, str);
3528 void loadvm_completion(ReadLineState *rs, int nb_args, const char *str)
3530 if (nb_args == 2) {
3531 vm_completion(rs, str);
3535 static void monitor_find_completion_by_table(Monitor *mon,
3536 const mon_cmd_t *cmd_table,
3537 char **args,
3538 int nb_args)
3540 const char *cmdname;
3541 int i;
3542 const char *ptype, *str, *name;
3543 const mon_cmd_t *cmd;
3544 BlockBackend *blk = NULL;
3546 if (nb_args <= 1) {
3547 /* command completion */
3548 if (nb_args == 0)
3549 cmdname = "";
3550 else
3551 cmdname = args[0];
3552 readline_set_completion_index(mon->rs, strlen(cmdname));
3553 for (cmd = cmd_table; cmd->name != NULL; cmd++) {
3554 cmd_completion(mon, cmdname, cmd->name);
3556 } else {
3557 /* find the command */
3558 for (cmd = cmd_table; cmd->name != NULL; cmd++) {
3559 if (compare_cmd(args[0], cmd->name)) {
3560 break;
3563 if (!cmd->name) {
3564 return;
3567 if (cmd->sub_table) {
3568 /* do the job again */
3569 monitor_find_completion_by_table(mon, cmd->sub_table,
3570 &args[1], nb_args - 1);
3571 return;
3573 if (cmd->command_completion) {
3574 cmd->command_completion(mon->rs, nb_args, args[nb_args - 1]);
3575 return;
3578 ptype = next_arg_type(cmd->args_type);
3579 for(i = 0; i < nb_args - 2; i++) {
3580 if (*ptype != '\0') {
3581 ptype = next_arg_type(ptype);
3582 while (*ptype == '?')
3583 ptype = next_arg_type(ptype);
3586 str = args[nb_args - 1];
3587 while (*ptype == '-' && ptype[1] != '\0') {
3588 ptype = next_arg_type(ptype);
3590 switch(*ptype) {
3591 case 'F':
3592 /* file completion */
3593 readline_set_completion_index(mon->rs, strlen(str));
3594 file_completion(mon, str);
3595 break;
3596 case 'B':
3597 /* block device name completion */
3598 readline_set_completion_index(mon->rs, strlen(str));
3599 while ((blk = blk_next(blk)) != NULL) {
3600 name = blk_name(blk);
3601 if (str[0] == '\0' ||
3602 !strncmp(name, str, strlen(str))) {
3603 readline_add_completion(mon->rs, name);
3606 break;
3607 case 's':
3608 case 'S':
3609 if (!strcmp(cmd->name, "help|?")) {
3610 monitor_find_completion_by_table(mon, cmd_table,
3611 &args[1], nb_args - 1);
3613 break;
3614 default:
3615 break;
3620 static void monitor_find_completion(void *opaque,
3621 const char *cmdline)
3623 Monitor *mon = opaque;
3624 char *args[MAX_ARGS];
3625 int nb_args, len;
3627 /* 1. parse the cmdline */
3628 if (parse_cmdline(cmdline, &nb_args, args) < 0) {
3629 return;
3632 /* if the line ends with a space, it means we want to complete the
3633 next arg */
3634 len = strlen(cmdline);
3635 if (len > 0 && qemu_isspace(cmdline[len - 1])) {
3636 if (nb_args >= MAX_ARGS) {
3637 goto cleanup;
3639 args[nb_args++] = g_strdup("");
3642 /* 2. auto complete according to args */
3643 monitor_find_completion_by_table(mon, mon->cmd_table, args, nb_args);
3645 cleanup:
3646 free_cmdline_args(args, nb_args);
3649 static int monitor_can_read(void *opaque)
3651 Monitor *mon = opaque;
3653 return (mon->suspend_cnt == 0) ? 1 : 0;
3656 static bool invalid_qmp_mode(const Monitor *mon, const mon_cmd_t *cmd,
3657 Error **errp)
3659 bool is_cap = cmd->mhandler.cmd_new == qmp_capabilities;
3661 if (is_cap && mon->qmp.in_command_mode) {
3662 error_set(errp, ERROR_CLASS_COMMAND_NOT_FOUND,
3663 "Capabilities negotiation is already complete, command "
3664 "'%s' ignored", cmd->name);
3665 return true;
3667 if (!is_cap && !mon->qmp.in_command_mode) {
3668 error_set(errp, ERROR_CLASS_COMMAND_NOT_FOUND,
3669 "Expecting capabilities negotiation with "
3670 "'qmp_capabilities' before command '%s'", cmd->name);
3671 return true;
3673 return false;
3677 * Argument validation rules:
3679 * 1. The argument must exist in cmd_args qdict
3680 * 2. The argument type must be the expected one
3682 * Special case: If the argument doesn't exist in cmd_args and
3683 * the QMP_ACCEPT_UNKNOWNS flag is set, then the
3684 * checking is skipped for it.
3686 static void check_client_args_type(const QDict *client_args,
3687 const QDict *cmd_args, int flags,
3688 Error **errp)
3690 const QDictEntry *ent;
3692 for (ent = qdict_first(client_args); ent;ent = qdict_next(client_args,ent)){
3693 QObject *obj;
3694 QString *arg_type;
3695 const QObject *client_arg = qdict_entry_value(ent);
3696 const char *client_arg_name = qdict_entry_key(ent);
3698 obj = qdict_get(cmd_args, client_arg_name);
3699 if (!obj) {
3700 if (flags & QMP_ACCEPT_UNKNOWNS) {
3701 /* handler accepts unknowns */
3702 continue;
3704 /* client arg doesn't exist */
3705 error_setg(errp, QERR_INVALID_PARAMETER, client_arg_name);
3706 return;
3709 arg_type = qobject_to_qstring(obj);
3710 assert(arg_type != NULL);
3712 /* check if argument's type is correct */
3713 switch (qstring_get_str(arg_type)[0]) {
3714 case 'F':
3715 case 'B':
3716 case 's':
3717 if (qobject_type(client_arg) != QTYPE_QSTRING) {
3718 error_setg(errp, QERR_INVALID_PARAMETER_TYPE,
3719 client_arg_name, "string");
3720 return;
3722 break;
3723 case 'i':
3724 case 'l':
3725 case 'M':
3726 case 'o':
3727 if (qobject_type(client_arg) != QTYPE_QINT) {
3728 error_setg(errp, QERR_INVALID_PARAMETER_TYPE,
3729 client_arg_name, "int");
3730 return;
3732 break;
3733 case 'T':
3734 if (qobject_type(client_arg) != QTYPE_QINT &&
3735 qobject_type(client_arg) != QTYPE_QFLOAT) {
3736 error_setg(errp, QERR_INVALID_PARAMETER_TYPE,
3737 client_arg_name, "number");
3738 return;
3740 break;
3741 case 'b':
3742 case '-':
3743 if (qobject_type(client_arg) != QTYPE_QBOOL) {
3744 error_setg(errp, QERR_INVALID_PARAMETER_TYPE,
3745 client_arg_name, "bool");
3746 return;
3748 break;
3749 case 'O':
3750 assert(flags & QMP_ACCEPT_UNKNOWNS);
3751 break;
3752 case 'q':
3753 /* Any QObject can be passed. */
3754 break;
3755 case '/':
3756 case '.':
3758 * These types are not supported by QMP and thus are not
3759 * handled here. Fall through.
3761 default:
3762 abort();
3768 * - Check if the client has passed all mandatory args
3769 * - Set special flags for argument validation
3771 static void check_mandatory_args(const QDict *cmd_args,
3772 const QDict *client_args, int *flags,
3773 Error **errp)
3775 const QDictEntry *ent;
3777 for (ent = qdict_first(cmd_args); ent; ent = qdict_next(cmd_args, ent)) {
3778 const char *cmd_arg_name = qdict_entry_key(ent);
3779 QString *type = qobject_to_qstring(qdict_entry_value(ent));
3780 assert(type != NULL);
3782 if (qstring_get_str(type)[0] == 'O') {
3783 assert((*flags & QMP_ACCEPT_UNKNOWNS) == 0);
3784 *flags |= QMP_ACCEPT_UNKNOWNS;
3785 } else if (qstring_get_str(type)[0] != '-' &&
3786 qstring_get_str(type)[1] != '?' &&
3787 !qdict_haskey(client_args, cmd_arg_name)) {
3788 error_setg(errp, QERR_MISSING_PARAMETER, cmd_arg_name);
3789 return;
3794 static QDict *qdict_from_args_type(const char *args_type)
3796 int i;
3797 QDict *qdict;
3798 QString *key, *type, *cur_qs;
3800 assert(args_type != NULL);
3802 qdict = qdict_new();
3804 if (args_type == NULL || args_type[0] == '\0') {
3805 /* no args, empty qdict */
3806 goto out;
3809 key = qstring_new();
3810 type = qstring_new();
3812 cur_qs = key;
3814 for (i = 0;; i++) {
3815 switch (args_type[i]) {
3816 case ',':
3817 case '\0':
3818 qdict_put(qdict, qstring_get_str(key), type);
3819 QDECREF(key);
3820 if (args_type[i] == '\0') {
3821 goto out;
3823 type = qstring_new(); /* qdict has ref */
3824 cur_qs = key = qstring_new();
3825 break;
3826 case ':':
3827 cur_qs = type;
3828 break;
3829 default:
3830 qstring_append_chr(cur_qs, args_type[i]);
3831 break;
3835 out:
3836 return qdict;
3840 * Client argument checking rules:
3842 * 1. Client must provide all mandatory arguments
3843 * 2. Each argument provided by the client must be expected
3844 * 3. Each argument provided by the client must have the type expected
3845 * by the command
3847 static void qmp_check_client_args(const mon_cmd_t *cmd, QDict *client_args,
3848 Error **errp)
3850 Error *err = NULL;
3851 int flags;
3852 QDict *cmd_args;
3854 cmd_args = qdict_from_args_type(cmd->args_type);
3856 flags = 0;
3857 check_mandatory_args(cmd_args, client_args, &flags, &err);
3858 if (err) {
3859 goto out;
3862 check_client_args_type(client_args, cmd_args, flags, &err);
3864 out:
3865 error_propagate(errp, err);
3866 QDECREF(cmd_args);
3870 * Input object checking rules
3872 * 1. Input object must be a dict
3873 * 2. The "execute" key must exist
3874 * 3. The "execute" key must be a string
3875 * 4. If the "arguments" key exists, it must be a dict
3876 * 5. If the "id" key exists, it can be anything (ie. json-value)
3877 * 6. Any argument not listed above is considered invalid
3879 static QDict *qmp_check_input_obj(QObject *input_obj, Error **errp)
3881 const QDictEntry *ent;
3882 int has_exec_key = 0;
3883 QDict *input_dict;
3885 if (qobject_type(input_obj) != QTYPE_QDICT) {
3886 error_setg(errp, QERR_QMP_BAD_INPUT_OBJECT, "object");
3887 return NULL;
3890 input_dict = qobject_to_qdict(input_obj);
3892 for (ent = qdict_first(input_dict); ent; ent = qdict_next(input_dict, ent)){
3893 const char *arg_name = qdict_entry_key(ent);
3894 const QObject *arg_obj = qdict_entry_value(ent);
3896 if (!strcmp(arg_name, "execute")) {
3897 if (qobject_type(arg_obj) != QTYPE_QSTRING) {
3898 error_setg(errp, QERR_QMP_BAD_INPUT_OBJECT_MEMBER,
3899 "execute", "string");
3900 return NULL;
3902 has_exec_key = 1;
3903 } else if (!strcmp(arg_name, "arguments")) {
3904 if (qobject_type(arg_obj) != QTYPE_QDICT) {
3905 error_setg(errp, QERR_QMP_BAD_INPUT_OBJECT_MEMBER,
3906 "arguments", "object");
3907 return NULL;
3909 } else if (!strcmp(arg_name, "id")) {
3910 /* Any string is acceptable as "id", so nothing to check */
3911 } else {
3912 error_setg(errp, QERR_QMP_EXTRA_MEMBER, arg_name);
3913 return NULL;
3917 if (!has_exec_key) {
3918 error_setg(errp, QERR_QMP_BAD_INPUT_OBJECT, "execute");
3919 return NULL;
3922 return input_dict;
3925 static void handle_qmp_command(JSONMessageParser *parser, GQueue *tokens)
3927 Error *local_err = NULL;
3928 QObject *obj, *data;
3929 QDict *input, *args;
3930 const mon_cmd_t *cmd;
3931 const char *cmd_name;
3932 Monitor *mon = cur_mon;
3934 args = input = NULL;
3935 data = NULL;
3937 obj = json_parser_parse(tokens, NULL);
3938 if (!obj) {
3939 // FIXME: should be triggered in json_parser_parse()
3940 error_setg(&local_err, QERR_JSON_PARSING);
3941 goto err_out;
3944 input = qmp_check_input_obj(obj, &local_err);
3945 if (!input) {
3946 qobject_decref(obj);
3947 goto err_out;
3950 mon->qmp.id = qdict_get(input, "id");
3951 qobject_incref(mon->qmp.id);
3953 cmd_name = qdict_get_str(input, "execute");
3954 trace_handle_qmp_command(mon, cmd_name);
3955 cmd = qmp_find_cmd(cmd_name);
3956 if (!cmd) {
3957 error_set(&local_err, ERROR_CLASS_COMMAND_NOT_FOUND,
3958 "The command %s has not been found", cmd_name);
3959 goto err_out;
3961 if (invalid_qmp_mode(mon, cmd, &local_err)) {
3962 goto err_out;
3965 obj = qdict_get(input, "arguments");
3966 if (!obj) {
3967 args = qdict_new();
3968 } else {
3969 args = qobject_to_qdict(obj);
3970 QINCREF(args);
3973 qmp_check_client_args(cmd, args, &local_err);
3974 if (local_err) {
3975 goto err_out;
3978 cmd->mhandler.cmd_new(args, &data, &local_err);
3980 err_out:
3981 monitor_protocol_emitter(mon, data, local_err);
3982 qobject_decref(data);
3983 error_free(local_err);
3984 QDECREF(input);
3985 QDECREF(args);
3988 static void monitor_qmp_read(void *opaque, const uint8_t *buf, int size)
3990 Monitor *old_mon = cur_mon;
3992 cur_mon = opaque;
3994 json_message_parser_feed(&cur_mon->qmp.parser, (const char *) buf, size);
3996 cur_mon = old_mon;
3999 static void monitor_read(void *opaque, const uint8_t *buf, int size)
4001 Monitor *old_mon = cur_mon;
4002 int i;
4004 cur_mon = opaque;
4006 if (cur_mon->rs) {
4007 for (i = 0; i < size; i++)
4008 readline_handle_byte(cur_mon->rs, buf[i]);
4009 } else {
4010 if (size == 0 || buf[size - 1] != 0)
4011 monitor_printf(cur_mon, "corrupted command\n");
4012 else
4013 handle_hmp_command(cur_mon, (char *)buf);
4016 cur_mon = old_mon;
4019 static void monitor_command_cb(void *opaque, const char *cmdline,
4020 void *readline_opaque)
4022 Monitor *mon = opaque;
4024 monitor_suspend(mon);
4025 handle_hmp_command(mon, cmdline);
4026 monitor_resume(mon);
4029 int monitor_suspend(Monitor *mon)
4031 if (!mon->rs)
4032 return -ENOTTY;
4033 mon->suspend_cnt++;
4034 return 0;
4037 void monitor_resume(Monitor *mon)
4039 if (!mon->rs)
4040 return;
4041 if (--mon->suspend_cnt == 0)
4042 readline_show_prompt(mon->rs);
4045 static QObject *get_qmp_greeting(void)
4047 QObject *ver = NULL;
4049 qmp_marshal_query_version(NULL, &ver, NULL);
4050 return qobject_from_jsonf("{'QMP':{'version': %p,'capabilities': []}}",ver);
4053 static void monitor_qmp_event(void *opaque, int event)
4055 QObject *data;
4056 Monitor *mon = opaque;
4058 switch (event) {
4059 case CHR_EVENT_OPENED:
4060 mon->qmp.in_command_mode = false;
4061 data = get_qmp_greeting();
4062 monitor_json_emitter(mon, data);
4063 qobject_decref(data);
4064 mon_refcount++;
4065 break;
4066 case CHR_EVENT_CLOSED:
4067 json_message_parser_destroy(&mon->qmp.parser);
4068 json_message_parser_init(&mon->qmp.parser, handle_qmp_command);
4069 mon_refcount--;
4070 monitor_fdsets_cleanup();
4071 break;
4075 static void monitor_event(void *opaque, int event)
4077 Monitor *mon = opaque;
4079 switch (event) {
4080 case CHR_EVENT_MUX_IN:
4081 qemu_mutex_lock(&mon->out_lock);
4082 mon->mux_out = 0;
4083 qemu_mutex_unlock(&mon->out_lock);
4084 if (mon->reset_seen) {
4085 readline_restart(mon->rs);
4086 monitor_resume(mon);
4087 monitor_flush(mon);
4088 } else {
4089 mon->suspend_cnt = 0;
4091 break;
4093 case CHR_EVENT_MUX_OUT:
4094 if (mon->reset_seen) {
4095 if (mon->suspend_cnt == 0) {
4096 monitor_printf(mon, "\n");
4098 monitor_flush(mon);
4099 monitor_suspend(mon);
4100 } else {
4101 mon->suspend_cnt++;
4103 qemu_mutex_lock(&mon->out_lock);
4104 mon->mux_out = 1;
4105 qemu_mutex_unlock(&mon->out_lock);
4106 break;
4108 case CHR_EVENT_OPENED:
4109 monitor_printf(mon, "QEMU %s monitor - type 'help' for more "
4110 "information\n", QEMU_VERSION);
4111 if (!mon->mux_out) {
4112 readline_restart(mon->rs);
4113 readline_show_prompt(mon->rs);
4115 mon->reset_seen = 1;
4116 mon_refcount++;
4117 break;
4119 case CHR_EVENT_CLOSED:
4120 mon_refcount--;
4121 monitor_fdsets_cleanup();
4122 break;
4126 static int
4127 compare_mon_cmd(const void *a, const void *b)
4129 return strcmp(((const mon_cmd_t *)a)->name,
4130 ((const mon_cmd_t *)b)->name);
4133 static void sortcmdlist(void)
4135 int array_num;
4136 int elem_size = sizeof(mon_cmd_t);
4138 array_num = sizeof(mon_cmds)/elem_size-1;
4139 qsort((void *)mon_cmds, array_num, elem_size, compare_mon_cmd);
4141 array_num = sizeof(info_cmds)/elem_size-1;
4142 qsort((void *)info_cmds, array_num, elem_size, compare_mon_cmd);
4145 /* These functions just adapt the readline interface in a typesafe way. We
4146 * could cast function pointers but that discards compiler checks.
4148 static void GCC_FMT_ATTR(2, 3) monitor_readline_printf(void *opaque,
4149 const char *fmt, ...)
4151 va_list ap;
4152 va_start(ap, fmt);
4153 monitor_vprintf(opaque, fmt, ap);
4154 va_end(ap);
4157 static void monitor_readline_flush(void *opaque)
4159 monitor_flush(opaque);
4162 static void __attribute__((constructor)) monitor_lock_init(void)
4164 qemu_mutex_init(&monitor_lock);
4167 void monitor_init(CharDriverState *chr, int flags)
4169 static int is_first_init = 1;
4170 Monitor *mon;
4172 if (is_first_init) {
4173 monitor_qapi_event_init();
4174 sortcmdlist();
4175 is_first_init = 0;
4178 mon = g_malloc(sizeof(*mon));
4179 monitor_data_init(mon);
4181 mon->chr = chr;
4182 mon->flags = flags;
4183 if (flags & MONITOR_USE_READLINE) {
4184 mon->rs = readline_init(monitor_readline_printf,
4185 monitor_readline_flush,
4186 mon,
4187 monitor_find_completion);
4188 monitor_read_command(mon, 0);
4191 if (monitor_is_qmp(mon)) {
4192 qemu_chr_add_handlers(chr, monitor_can_read, monitor_qmp_read,
4193 monitor_qmp_event, mon);
4194 qemu_chr_fe_set_echo(chr, true);
4195 json_message_parser_init(&mon->qmp.parser, handle_qmp_command);
4196 } else {
4197 qemu_chr_add_handlers(chr, monitor_can_read, monitor_read,
4198 monitor_event, mon);
4201 qemu_mutex_lock(&monitor_lock);
4202 QLIST_INSERT_HEAD(&mon_list, mon, entry);
4203 qemu_mutex_unlock(&monitor_lock);
4206 void monitor_cleanup(void)
4208 Monitor *mon, *next;
4210 qemu_mutex_lock(&monitor_lock);
4211 QLIST_FOREACH_SAFE(mon, &mon_list, entry, next) {
4212 QLIST_REMOVE(mon, entry);
4213 monitor_data_destroy(mon);
4214 g_free(mon);
4216 qemu_mutex_unlock(&monitor_lock);
4219 static void bdrv_password_cb(void *opaque, const char *password,
4220 void *readline_opaque)
4222 Monitor *mon = opaque;
4223 BlockDriverState *bs = readline_opaque;
4224 int ret = 0;
4225 Error *local_err = NULL;
4227 bdrv_add_key(bs, password, &local_err);
4228 if (local_err) {
4229 error_report_err(local_err);
4230 ret = -EPERM;
4232 if (mon->password_completion_cb)
4233 mon->password_completion_cb(mon->password_opaque, ret);
4235 monitor_read_command(mon, 1);
4238 int monitor_read_bdrv_key_start(Monitor *mon, BlockDriverState *bs,
4239 BlockCompletionFunc *completion_cb,
4240 void *opaque)
4242 int err;
4244 monitor_printf(mon, "%s (%s) is encrypted.\n", bdrv_get_device_name(bs),
4245 bdrv_get_encrypted_filename(bs));
4247 mon->password_completion_cb = completion_cb;
4248 mon->password_opaque = opaque;
4250 err = monitor_read_password(mon, bdrv_password_cb, bs);
4252 if (err && completion_cb)
4253 completion_cb(opaque, err);
4255 return err;
4258 int monitor_read_block_device_key(Monitor *mon, const char *device,
4259 BlockCompletionFunc *completion_cb,
4260 void *opaque)
4262 Error *err = NULL;
4263 BlockBackend *blk;
4265 blk = blk_by_name(device);
4266 if (!blk) {
4267 monitor_printf(mon, "Device not found %s\n", device);
4268 return -1;
4270 if (!blk_bs(blk)) {
4271 monitor_printf(mon, "Device '%s' has no medium\n", device);
4272 return -1;
4275 bdrv_add_key(blk_bs(blk), NULL, &err);
4276 if (err) {
4277 error_free(err);
4278 return monitor_read_bdrv_key_start(mon, blk_bs(blk), completion_cb, opaque);
4281 if (completion_cb) {
4282 completion_cb(opaque, 0);
4284 return 0;
4287 QemuOptsList qemu_mon_opts = {
4288 .name = "mon",
4289 .implied_opt_name = "chardev",
4290 .head = QTAILQ_HEAD_INITIALIZER(qemu_mon_opts.head),
4291 .desc = {
4293 .name = "mode",
4294 .type = QEMU_OPT_STRING,
4296 .name = "chardev",
4297 .type = QEMU_OPT_STRING,
4299 .name = "default",
4300 .type = QEMU_OPT_BOOL,
4302 .name = "pretty",
4303 .type = QEMU_OPT_BOOL,
4305 { /* end of list */ }
4309 #ifndef TARGET_I386
4310 void qmp_rtc_reset_reinjection(Error **errp)
4312 error_setg(errp, QERR_FEATURE_DISABLED, "rtc-reset-reinjection");
4314 #endif
4316 #ifndef TARGET_S390X
4317 void qmp_dump_skeys(const char *filename, Error **errp)
4319 error_setg(errp, QERR_FEATURE_DISABLED, "dump-skeys");
4321 #endif
4323 #ifndef TARGET_ARM
4324 GICCapabilityList *qmp_query_gic_capabilities(Error **errp)
4326 error_setg(errp, QERR_FEATURE_DISABLED, "query-gic-capabilities");
4327 return NULL;
4329 #endif
4331 HotpluggableCPUList *qmp_query_hotpluggable_cpus(Error **errp)
4333 MachineState *ms = MACHINE(qdev_get_machine());
4334 MachineClass *mc = MACHINE_GET_CLASS(ms);
4336 if (!mc->query_hotpluggable_cpus) {
4337 error_setg(errp, QERR_FEATURE_DISABLED, "query-hotpluggable-cpus");
4338 return NULL;
4341 return mc->query_hotpluggable_cpus(ms);